text:
require 'test_helper'

class BootstrapFormTest < ActionView::TestCase
  include BootstrapForm::Helper

  def setup
    setup_test_fixture
  end

  test "default-style forms" do
    expected = %{<form accept-charset="UTF-8" action="/users" class="new_user" id="new_user" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />
</form>}
    assert_equivalent_xml expected, bootstrap_form_for(@user) { |f| nil }
  end

  test "inline-style forms" do
    expected = %{<form accept-charset="UTF-8" action="/users" class="form-inline" id="new_user" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />
</form>}
    assert_equivalent_xml expected, bootstrap_form_for(@user, layout: :inline) { |f| nil }
  end

  test "horizontal-style forms" do
    expected = %{<form accept-charset="UTF-8" action="/users" class="form-horizontal" id="new_user" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />

Email
<input class="form-control" id="user_email" name="user[email]" type="email" value="steve@example.com" />

</form>}
    assert_equivalent_xml expected, bootstrap_form_for(@user, layout: :horizontal) { |f| f.email_field :email }
  end

  test "existing styles aren't clobbered when specifying a form style" do
    expected = %{<form accept-charset="UTF-8" action="/users" class="my-style form-horizontal" id="new_user" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />

Email
<input class="form-control" id="user_email" name="user[email]" type="email" value="steve@example.com" />

</form>}
    assert_equivalent_xml expected, bootstrap_form_for(@user, layout: :horizontal, html: { class: "my-style" }) { |f| f.email_field :email }
  end

  test "given role attribute should not be covered by default role attribute" do
    expected = %{<form accept-charset="UTF-8" action="/users" class="new_user" id="new_user" method="post" role="not-a-form">
<input name="utf8" type="hidden" value="✓" />
</form>}
    assert_equivalent_xml expected, bootstrap_form_for(@user, html: { role: 'not-a-form'}) {|f| nil}
  end

  test "bootstrap_form_tag acts like a form tag" do
    expected = %{<form accept-charset="UTF-8" action="/users" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />

Your Email<input class="form-control" id="email" name="email" type="text" />
</form>}
    assert_equivalent_xml expected, bootstrap_form_tag(url: '/users') { |f| f.text_field :email, label: "Your Email" }
  end

  test "bootstrap_form_tag does not clobber custom options" do
    expected = %{<form accept-charset="UTF-8" action="/users" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />

Email<input class="form-control" id="ID" name="NAME" type="text" />
</form>}
    assert_equivalent_xml expected, bootstrap_form_tag(url: '/users') { |f| f.text_field :email, name: 'NAME', id: "ID" }
  end

  test "bootstrap_form_tag allows an empty name for checkboxes" do
    expected = %{<form accept-charset="UTF-8" action="/users" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />

<input name="[misc]" type="hidden" value="0" /><input id="_misc" name="[misc]" type="checkbox" value="1" /> Misc
</form>}
    assert_equivalent_xml expected, bootstrap_form_tag(url: '/users') { |f| f.check_box :misc }
  end

  test "errors display correctly and inline_errors are turned off by default when label_errors is true" do
    @user.email = nil
    @user.valid?

    expected = %{<form accept-charset=\"UTF-8\" action=\"/users\" class=\"new_user\" id=\"new_user\" method=\"post\" role=\"form\">
<input name=\"utf8\" type=\"hidden\" value=\"✓\" />

Email can't be blank, is too short (minimum is 5 characters)<input class=\"form-control\" id=\"user_email\" name=\"user[email]\" type=\"text\" />
</form>}
    assert_equivalent_xml expected, bootstrap_form_for(@user, label_errors: true) { |f| f.text_field :email }
  end

  test "errors display correctly and inline_errors can also be on when label_errors is true" do
    @user.email = nil
    @user.valid?

    expected = %{<form accept-charset=\"UTF-8\" action=\"/users\" class=\"new_user\" id=\"new_user\" method=\"post\" role=\"form\">
<input name=\"utf8\" type=\"hidden\" value=\"✓\" />

Email can't be blank, is too short (minimum is 5 characters)<input class=\"form-control\" id=\"user_email\" name=\"user[email]\" type=\"text\" />can't be blank, is too short (minimum is 5 characters)
</form>}
    assert_equivalent_xml expected, bootstrap_form_for(@user, label_errors: true, inline_errors: true) { |f| f.text_field :email }
  end

  test "label error messages use humanized attribute names" do
    I18n.backend.store_translations(:en, {activerecord: {attributes: {user: {email: 'Your e-mail address'}}}})

    @user.email = nil
    @user.valid?

    expected = %{<form accept-charset=\"UTF-8\" action=\"/users\" class=\"new_user\" id=\"new_user\" method=\"post\" role=\"form\">
<input name=\"utf8\" type=\"hidden\" value=\"✓\" />

Your e-mail address can't be blank, is too short (minimum is 5 characters)<input class=\"form-control\" id=\"user_email\" name=\"user[email]\" type=\"text\" />can't be blank, is too short (minimum is 5 characters)
</form>}
    assert_equivalent_xml expected, bootstrap_form_for(@user, label_errors: true, inline_errors: true) { |f| f.text_field :email }

    I18n.backend.store_translations(:en, {activerecord: {attributes: {user: {email: nil}}}})
  end

  test "alert message is wrapped correctly" do
    @user.email = nil
    @user.valid?
    expected = %{

Please fix the following errors:

Email can't be blank

Email is too short (minimum is 5 characters)

Terms must be accepted

}
    assert_equivalent_xml expected, @builder.alert_message('Please fix the following errors:')
  end

  test "changing the class name for the alert message" do
    @user.email = nil
    @user.valid?
    expected = %{

Please fix the following errors:

Email can't be blank

Email is too short (minimum is 5 characters)

Terms must be accepted

}
    assert_equivalent_xml expected, @builder.alert_message('Please fix the following errors:', class: 'my-css-class')
  end

  test "alert_message contains the error summary when inline_errors are turned off" do
    @user.email = nil
    @user.valid?

    output = bootstrap_form_for(@user, inline_errors: false) do |f|
      f.alert_message('Please fix the following errors:')
    end

    expected = %{<form accept-charset="UTF-8" action="/users" class="new_user" id="new_user" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />

Please fix the following errors:

Email can't be blank

Email is too short (minimum is 5 characters)

Terms must be accepted

</form>}
    assert_equivalent_xml expected, output
  end

  test "alert_message allows the error_summary to be turned off" do
    @user.email = nil
    @user.valid?

    output = bootstrap_form_for(@user, inline_errors: false) do |f|
      f.alert_message('Please fix the following errors:', error_summary: false)
    end

    expected = %{<form accept-charset="UTF-8" action="/users" class="new_user" id="new_user" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />

Please fix the following errors:

</form>}
    assert_equivalent_xml expected, output
  end

  test "alert_message allows the error_summary to be turned on with inline_errors also turned on" do
    @user.email = nil
    @user.valid?

    output = bootstrap_form_for(@user, inline_errors: true) do |f|
      f.alert_message('Please fix the following errors:', error_summary: true)
    end

    expected = %{<form accept-charset="UTF-8" action="/users" class="new_user" id="new_user" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />

Please fix the following errors:

Email can't be blank

Email is too short (minimum is 5 characters)

Terms must be accepted

</form>}
    assert_equivalent_xml expected, output
  end

  test "error_summary returns an unordered list of errors" do
    @user.email = nil
    @user.valid?

    expected = %{

Email can't be blank

Email is too short (minimum is 5 characters)

Terms must be accepted

}
    assert_equivalent_xml expected, @builder.error_summary
  end

  test 'errors_on renders the errors for a specific attribute when invalid' do
    @user.email = nil
    @user.valid?

    expected = %{
Email can't be blank, Email is too short (minimum is 5 characters)
}
    assert_equivalent_xml expected, @builder.errors_on(:email)
  end

  test "custom label width for horizontal forms" do
    expected = %{<form accept-charset="UTF-8" action="/users" class="form-horizontal" id="new_user" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />

Email
<input class="form-control" id="user_email" name="user[email]" type="email" value="steve@example.com" />

</form>}
    assert_equivalent_xml expected, bootstrap_form_for(@user, layout: :horizontal) { |f| f.email_field :email, label_col: 'col-sm-1' }
  end

  test "offset for form group without label respects label width for horizontal forms" do
    expected = %{<form accept-charset="UTF-8" action="/users" class="form-horizontal" id="new_user" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />

<input class="btn btn-default" name="commit" type="submit" value="Create User" />

</form>}
    assert_equivalent_xml expected, bootstrap_form_for(@user, layout: :horizontal, label_col: 'col-md-2', control_col: 'col-md-10') { |f| f.form_group { f.submit } }
  end

  test "custom input width for horizontal forms" do
    expected = %{<form accept-charset="UTF-8" action="/users" class="form-horizontal" id="new_user" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />

Email
<input class="form-control" id="user_email" name="user[email]" type="email" value="steve@example.com" />

</form>}
    assert_equivalent_xml expected, bootstrap_form_for(@user, layout: :horizontal) { |f| f.email_field :email, control_col: 'col-sm-5' }
  end

  test "the field contains the error and is not wrapped in div.field_with_errors when bootstrap_form_for is used" do
    @user.email = nil
    @user.valid?

    output = bootstrap_form_for(@user) do |f|
      f.text_field(:email, help: 'This is required')
    end

    expected = %{<form accept-charset="UTF-8" action="/users" class="new_user" id="new_user" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />

Email<input class="form-control" id="user_email" name="user[email]" type="text" />can't be blank, is too short (minimum is 5 characters)
</form>}
    assert_equivalent_xml expected, output
  end

  test "the field is wrapped with div.field_with_errors when form_for is used" do
    @user.email = nil
    @user.valid?

    output = form_for(@user, builder: BootstrapForm::FormBuilder) do |f|
      f.text_field(:email, help: 'This is required')
    end

    expected = %{<form accept-charset="UTF-8" action="/users" class="new_user" id="new_user" method="post">
<input name="utf8" type="hidden" value="✓" />

Email

<input class="form-control" id="user_email" name="user[email]" type="text" />
can't be blank, is too short (minimum is 5 characters)
</form>}
    assert_equivalent_xml expected, output
  end

  test "help is preserved when inline_errors: false is passed to bootstrap_form_for" do
    @user.email = nil
    @user.valid?

    output = bootstrap_form_for(@user, inline_errors: false) do |f|
      f.text_field(:email, help: 'This is required')
    end

    expected = %{<form accept-charset="UTF-8" action="/users" class="new_user" id="new_user" method="post" role="form">
<input name="utf8" type="hidden" value="✓" />

Email<input class="form-control" id="user_email" name="user[email]" type="text" />This is required
</form>}
    assert_equivalent_xml expected, output
  end

  test "allows the form object to be nil" do
    builder = BootstrapForm::FormBuilder.new :other_model, nil, self, {}
    expected = %{
Email<input class="form-control" id="other_model_email" name="other_model[email]" type="text" />
}
    assert_equivalent_xml expected, builder.text_field(:email)
  end

  test 'errors_on hide attribute name in message' do
    @user.email = nil
    @user.valid?

    expected = %{
can't be blank, is too short (minimum is 5 characters)
}

    assert_equivalent_xml expected, @builder.errors_on(:email, hide_attribute_name: true)
  end
end


text:
require 'spec_helper'

describe 'mysql_client_test::default on centos-5.11' do
  cached(:centos_511_client_56) do
    ChefSpec::SoloRunner.new(
      platform: 'centos',
      version: '5.11',
      step_into: 'mysql_client'
    ) do |node|
      node.set['mysql']['version'] = '5.6'
    end.converge('mysql_client_test::default')
  end

  # Resource in mysql_client_test::default
  context 'compiling the test recipe' do
    it 'creates mysql_client[default]' do
      expect(centos_511_client_56).to create_mysql_client('default')
    end
  end

  # mysql_service resource internal implementation
  context 'stepping into mysql_client[default] resource' do
    it 'installs package[default :create mysql-community-client]' do
      expect(centos_511_client_56).to install_package('default :create mysql-community-client')
        .with(package_name: 'mysql-community-client')
    end

    it 'installs package[default :create mysql-community-devel]' do
      expect(centos_511_client_56).to install_package('default :create mysql-community-devel')
        .with(package_name: 'mysql-community-devel')
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
if ENV['CI']
  require 'coveralls'
  Coveralls.wear!
end

# Configure Rails Environment
ENV["RAILS_ENV"] = "test"

require File.expand_path("../../test/dummy/config/environment.rb", __FILE__)
ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)]
ActiveRecord::Migrator.migrations_paths << File.expand_path('../../db/migrate', __FILE__)
require "rails/test_help"

# Filter out Minitest backtrace while allowing backtrace from other libraries
# to be shown.
Minitest.backtrace_filter = Minitest::BacktraceFilter.new

# Load fixtures from the engine
if ActiveSupport::TestCase.respond_to?(:fixture_path=)
  ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__)
  ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
  ActiveSupport::TestCase.file_fixture_path = ActiveSupport::TestCase.fixture_path + "/files"
  ActiveSupport::TestCase.fixtures :all
end


text:
package org.mini2Dx.ui.element;

import org.mini2Dx.core.serialization.annotation.ConstructorArg;
import org.mini2Dx.core.serialization.annotation.Field;
import org.mini2Dx.ui.layout.LayoutRuleset;
import org.mini2Dx.ui.render.AbsoluteContainerRenderNode;
import org.mini2Dx.ui.render.ParentRenderNode;

/**
 * A {@link Container} that can be positioned manually
 */
public class AbsoluteContainer extends Container {
	@Field(optional=true)
	private float x;
	@Field(optional=true)
	private float y;

	/**
	 * Constructor. Generates a unique ID for this {@link AbsoluteContainer}
	 */
	public AbsoluteContainer() {
		this(null);
	}

	/**
	 * Constructor
	 *
	 * @param id
	 *            The unique ID of the {@link AbsoluteContainer}
	 */
	public AbsoluteContainer(@ConstructorArg(clazz = String.class, name = "id") String id) {
		super(id);
	}

	@Override
	public void attach(ParentRenderNode<?, ?> parentRenderNode) {
		if (renderNode != null) {
			return;
		}
		renderNode = new AbsoluteContainerRenderNode(parentRenderNode, this);
		for (int i = 0; i < children.size(); i++) {
			children.get(i).attach(renderNode);
		}
		parentRenderNode.addChild(renderNode);
	}

	/**
	 * Returns the x coordinate of this {@link AbsoluteContainer}
	 * @return 0 by default
	 */
	public float getX() {
		return x;
	}

	/**
	 * Sets the x coordinate of this {@link AbsoluteContainer}
	 * @param x The x coordinate in pixels
	 */
	public void setX(float x) {
		if (this.x == x) {
			return;
		}
		this.x = x;

		if (renderNode == null) {
			return;
		}
		renderNode.setDirty(true);
	}

	/**
	 * Returns the y coordinate of this {@link AbsoluteContainer}
	 * @return 0 by default
	 */
	public float getY() {
		return y;
	}

	/**
	 * Sets the y coordinate of this {@link AbsoluteContainer}
	 * @param y The y coordinate in pixels
	 */
	public void setY(float y) {
		if (this.y == y) {
			return;
		}
		this.y = y;

		if (renderNode == null) {
			return;
		}
		renderNode.setDirty(true);
	}

	/**
	 * Sets the x and y coordinate of this {@link AbsoluteContainer}
	 * @param x The x coordinate in pixels
	 * @param y The y coordinate in pixels
	 */
	public void set(float x, float y) {
		if (this.x == x && this.y == y) {
			return;
		}
		this.x = x;
		this.y = y;

		if (renderNode == null) {
			return;
		}
		renderNode.setDirty(true);
	}

	/**
	 * Returns the width of the {@link AbsoluteContainer} as determined by its
	 * {@link LayoutRuleset}
	 *
	 * @return
	 */
	public float getWidth() {
		if (renderNode == null) {
			return 0f;
		}
		return renderNode.getOuterWidth();
	}

	/**
	 * Returns the height of the {@link AbsoluteContainer} as determined by its
	 * child {@link UiElement}s
	 *
	 * @return 0 is no elements have been added
	 */
	public float getHeight() {
		if (renderNode == null) {
			return 0f;
		}
		return renderNode.getOuterHeight();
	}
}


text:
module EbuStl
    module BodyNames
        CS = { BodyOption::CS::NOT_PART_OF_CUMULATIVE_SET          => :single,
               BodyOption::CS::FIRST_PART_OF_CUMULATIVE_SET        => :first,
               BodyOption::CS::INTERMEDIATE_PART_OF_CUMULATIVE_SET => :middle,
               BodyOption::CS::LAST_PART_OF_CUMULATIVE_SET         => :last }

        JC = { BodyOption::JC::UNCHANGED       => :default,
               BodyOption::JC::LEFT_JUSTIFIED  => :left,
               BodyOption::JC::CENTERED        => :centered,
               BodyOption::JC::RIGHT_JUSTIFIED => :right }

        CF = { BodyOption::CF::SUBTITLE_DATA        => :subtitle,
              BodyOption::CF::NOT_FOR_TRANSMISSION  => :comment }
    end
end


text: Receives uart input and echos back what was received, repeating infinitely.


text:
<?php

error_reporting(E_ALL & ~E_STRICT);

require_once "vendor/autoload.php";

require_once "support/TestController.php";


text:
namespace Utilities
{
	#define INCREASE_COUNTER(counterName, increaseBy) \
		Utilities::Counting::increaseCounter(counterName, increaseBy);

	#define INIT_COUNTING \
		std::unordered_map<std::string, Utilities::AverageCount> Utilities::Counting::m_averageCounts;

	struct AverageCount
	{
		Real sum;
		unsigned int numberOfCalls;
	};

	class Counting
	{
	public:
		static std::unordered_map<std::string, AverageCount> m_averageCounts;

		static void reset()
		{
			m_averageCounts.clear();
		}

		FORCE_INLINE static void increaseCounter(const std::string& name, const Real increaseBy)
		{
			std::unordered_map<std::string, AverageCount>::iterator iter;
			iter = Counting::m_averageCounts.find(name);
			if (iter != Counting::m_averageCounts.end())
			{
				iter->second.sum += increaseBy;
				iter->second.numberOfCalls++;
			}
			else
			{
				AverageCount ac;
				ac.sum = increaseBy;
				ac.numberOfCalls = 1;
				Counting::m_averageCounts[name] = ac;
			}
		}

		FORCE_INLINE static void printAverageCounts()
		{
			std::unordered_map <std::string, AverageCount>::iterator iter;
			for (iter = Counting::m_averageCounts.begin(); iter != Counting::m_averageCounts.end(); iter++)
			{
				AverageCount &ac = iter->second;
				const double avgCount = ac.sum / ac.numberOfCalls;
				LOG_INFO << "Average number: " << iter->first.c_str() << ": " << avgCount;
			}
			LOG_INFO << "---------------------------------------------------------------------------\n";
		}

		FORCE_INLINE static void printCounterSums()
		{
			std::unordered_map <std::string, AverageCount>::iterator iter;
			for (iter = Counting::m_averageCounts.begin(); iter != Counting::m_averageCounts.end(); iter++)
			{
				AverageCount &ac = iter->second;
				LOG_INFO << "Total number: " << iter->first.c_str() << ": " << ac.sum;
			}
			LOG_INFO << "---------------------------------------------------------------------------\n";
		}
	};
}

#endif // __Counting_H__


text:
namespace YAF.UrlRewriter.Actions
{
    using System;
    using System.Web;

    /// <summary>
    /// Action that sets a cookie.
    /// </summary>
    public class SetCookieAction : IRewriteAction
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="cookieName">The cookie name.</param>
        /// <param name="cookieValue">The cookie value.</param>
        public SetCookieAction(string cookieName, string cookieValue)
        {
            this.Name = cookieName ?? throw new ArgumentNullException(nameof(cookieName));
            this.Value = cookieValue ?? throw new ArgumentNullException(nameof(cookieValue));
        }

        /// <summary>
        /// The name of the variable.
        /// </summary>
        public string Name { get; }

        /// <summary>
        /// The value of the variable.
        /// </summary>
        public string Value { get; }

        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="context">The rewrite context.</param>
        public RewriteProcessing Execute(IRewriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var cookie = new HttpCookie(this.Name, this.Value);
            context.ResponseCookies.Add(cookie);

            return RewriteProcessing.ContinueProcessing;
        }
    }
}


text:
#ifndef sitkImageViewer_h
#define sitkImageViewer_h

#include "sitkImage.h"
#include "sitkIO.h"
#include "sitkProcessObject.h"

namespace itk
{
namespace simple
{

/** \class ImageViewer
  * \brief Display an image in an external viewer (Fiji by default)
  *
  * The ImageViewer class displays an image with an external image display
  * application.  By default the class will search for a Fiji ( https://fiji.sc )
  * executable.  The image is written out to a temporary file and then passed
  * to the application.
  *
  * When SimpleITK is first invoked the following environment variables are
  * queried to set up the external viewer:
  *
  * SITK_SHOW_EXTENSION:  file format extension of the temporary image file.
  * The default is '.mha', the [MetaIO](https://itk.org/Wiki/ITK/MetaIO)
  * file format.
  *
  * SITK_SHOW_COMMAND:  The user can specify an application other than Fiji
  * to view images.
  *
  * These environment variables are only checked at SimpleITK's launch.
  */
class SITKIO_EXPORT ImageViewer
{

public:
  ImageViewer();

  /** Return the user readable name of the class */
  virtual std::string GetName() const { return std::string("ImageViewer"); }

  /** \brief Set/Get the search path used to find the viewing application
   * @{
   */
  static void SetGlobalDefaultSearchPath( const std::vector<std::string> & path );
  static const std::vector<std::string> & GetGlobalDefaultSearchPath();
  /**@}*/

  /** \brief Set/Get name list used to find the viewing application
   * @{
   */
  static void SetGlobalDefaultExecutableNames( const std::vector<std::string> & names );
  static const std::vector<std::string> & GetGlobalDefaultExecutableNames();
  /**@}*/

  /** \brief Set/Get the default file extension
   *
   * The file extension determines the image file type used when
   * writing out the temporary image file.
   * @{
   */
  static void SetGlobalDefaultFileExtension( const std::string & ext );
  static const std::string & GetGlobalDefaultFileExtension();
  /**@}*/

  /** \brief Set/Get the default application used in the command string.
   * @{
   */
  static void SetGlobalDefaultApplication( const std::string & app );
  static const std::string & GetGlobalDefaultApplication();
  /**@}*/

  /** \brief Set the full path to the viewing application used in the command string.
   *
   * The SetApplication method expects a full path name.
   *
   * Using this method overrides the default application search.
   *
   * By default, when this method is called, the command string is
   * set to "%a %f" which simply means *the application path*
   * followed by *the temporary image file*.
   */
  void SetApplication( const std::string & app, const std::string & command = "%a %f" );

  /** \brief Get the full path to the viewing application used in the command string.  */
  const std::string & GetApplication() const;

  /** \brief Set the command string used to launch the viewing application
   *
   * This command string may include the following %tokens:
   *
   * \li \c '%a' for the image viewing application (Fiji by default)
   * \li \c '%f' for SimpleITK's temporary image file
   *
   *  For example, the default command string on Linux systems is:
   *
   *  \code
   *  %a -o %f
   *  \endcode
   *
   *  After token substitution it may become:
   *
   *  \code
   *  /opt/Fiji.app/ImageJ-linux64 -o /tmp/Temp-65535-0.mha
   *  \endcode
   *
   *  For another example, the default command string on Mac OS X is:
   *
   *  \code
   *  open -a %a -n --args -eval \'open(\"%f\"); rename(\"%t\"); \'
   *  \endcode
   *
   *  After token substitution the string may become:
   *
   *  \code
   *  open -a /Applications/Fiji.app -n --args -eval 'open("/tmp/TempFile-29696-0.mha"); rename("/tmp/TempFile-29696-0.mha");'
   *  \endcode
   *
   *  The string after \c '-eval' is an ImageJ macro the opens the file and sets the title of the window.
   *
   *  If the \c '%f' token is not found in the command string, the temporary file name is automatically
   *  appended to the command argument list.
   *
   *  Note: Using the ImageViewer::SetCommand method overrides the default command and/or the
   *  SITK_SHOW_COMMAND environment variable.
   */
  void SetCommand( const std::string & command );

  /* \brief Get the command string used to launch the viewing application */
  const std::string & GetCommand() const;

  /** \brief Set/Get file extension of the temporary image file (default='.nii')
   *
   * If the viewing application is Fiji, the default image format is [MetaIO](https://itk.org/Wiki/ITK/MetaIO), '.mha'.
   *
   * If the viewing application is ImageJ, the default image format is [NifTi](https://nifti.nimh.nih.gov/nifti-1/), '.nii'.  This is because by default ImageJ does not come with the MetaIO plugin.
   * @{
   */
  void SetFileExtension( const std::string & ext );
  const std::string & GetFileExtension() const;
  /**@}*/

  /** \brief Set/Get Debug flag.
   *
   * Turning on/off the Debug flag produces output showing the command string used to
   * launch the viewing application.
   * @{
   */
  static void SetGlobalDefaultDebug( const bool dbg );
  static bool GetGlobalDefaultDebug();

  static void SetGlobalDefaultDebugOn();
  static void SetGlobalDefaultDebugOff();
  /**@}*/

  /** \brief Set/Get Process delay, the wait time after launching the viewing application.
   *
   * On Windows the delay is in seconds, default=1sec.
   * On Mac/Linux the delay is in milli-seconds, default=500ms.
   * @{
   */
  static void SetProcessDelay( const unsigned int delay);
  static unsigned int GetProcessDelay();
  /**@}*/

  /** \brief Set/Get Title string on the ImageJ window.
   * @{
   */
  void SetTitle( const std::string & t );
  const std::string & GetTitle() const;
  /**@}*/

  /** \brief Launch the viewing application to display the given image.
   */
  void Execute ( const Image &image );

  /** \brief Print ourself out to a string.
   */
  std::string ToString() const;

private:

  // hidden, no accessors
  static int  m_GlobalViewerImageCount;
  static bool m_GlobalAreDefaultsInitialized;

  // global only
  static std::vector<std::string> m_GlobalDefaultSearchPath;
  static std::vector<std::string> m_GlobalDefaultExecutableNames;
  static unsigned int             m_GlobalProcessDelay;

  static std::string m_GlobalDefaultViewCommand;
  static std::string m_GlobalDefaultFileExtension;
  static std::string m_GlobalDefaultApplication;

  static bool m_GlobalDefaultDebug;

  std::string m_ViewCommand;
  std::string m_CustomCommand;

  std::string m_Application;

  std::string m_FileExtension;

  std::string m_Title;

  static void initializeDefaults();

  static std::string FindViewingApplication();
};

}
}
#endif


text:
<!DOCTYPE html>

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

	<link rel="stylesheet" type="text/css" media="screen" href="./build/build.css" />


text:
package gui.observers;

import gui.component.ComputedWidget;
import gui.render.Evaluator;
import gui.render.State;
import ast.statement.ComputedQuestion;
import ast.value.Value;

public class ComputedQuestionObserver extends WidgetObserver{

	private ComputedQuestion statement;
	private ComputedWidget widget;
	private State state;

	public ComputedQuestionObserver(ComputedQuestion statement, ComputedWidget widget, State state) {
		this.statement = statement;
		this.widget = widget;
		this.state = state;
	}

	@Override
	public void evaluate() {
		Value val = statement.getExpr().accept(new Evaluator(state.getEnvValues()));
		state.addValue(statement.getId(), val);
		widget.setValue(val);
		widget.getComponent().setVisible(true);
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/egg_info_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="top|center_horizontal"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:orientation="vertical" >

    <com.aviary.android.feather.widget.ToggleButtonCustomFont
        android:id="@+id/tool_image"
        style="@style/FeatherTool.Info"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:clickable="true"
        android:focusable="true"
        android:gravity="center"
        android:scaleType="fitXY"
        android:singleLine="true"
        android:textOn="@string/infoscreen_bottom_button"
        android:textOff="@string/infoscreen_bottom_button"
        />

</LinearLayout>


text:
TEST(Metric, UnknownMetric) {
  EXPECT_ANY_THROW(xgboost::Metric::Create("unknown_name"));
  EXPECT_NO_THROW(xgboost::Metric::Create("rmse"));
  EXPECT_ANY_THROW(xgboost::Metric::Create("unknown_name@1"));
  EXPECT_NO_THROW(xgboost::Metric::Create("error@0.5"));
}


text:
package com.tsy.socialsample;

import com.tsy.sdk.social.sina.WBShareCallbackActivity;

/**
 * Created by tsy on 2017/2/14.
 */

public class WBShareActivity extends WBShareCallbackActivity {
}


text:
package org.apache.lens.cube.parse;

import static org.apache.lens.cube.metadata.DateFactory.*;
import static org.apache.lens.cube.parse.CubeTestSetup.*;
import static org.apache.lens.cube.parse.TestCubeRewriter.compareQueries;

import org.apache.lens.server.api.error.LensException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.ql.parse.ParseException;

import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import lombok.Getter;

public class TestAggregateResolver extends TestQueryRewrite {

  @Getter
  private Configuration conf;
  private final String cubeName = CubeTestSetup.TEST_CUBE_NAME;

  @BeforeTest
  public void setupDriver() throws Exception {
    conf = new Configuration();
    conf.set(CubeQueryConfUtil.DRIVER_SUPPORTED_STORAGES, "C2");
    conf.setBoolean(CubeQueryConfUtil.DISABLE_AUTO_JOINS, true);
    conf.setBoolean(CubeQueryConfUtil.ENABLE_SELECT_TO_GROUPBY, true);
    conf.setBoolean(CubeQueryConfUtil.ENABLE_GROUP_BY_TO_SELECT, true);
  }

  private CubeQueryContext rewrittenQuery;

  @Test
  public void testAggregateResolver() throws Exception {
    conf.setBoolean(CubeQueryConfUtil.DISABLE_AGGREGATE_RESOLVER, false);

    // pass
    String q1 = "SELECT cityid, testCube.msr2 from testCube where " + TWO_DAYS_RANGE;

    // pass
    String q2 = "SELECT cityid, testCube.msr2 * testCube.msr3 from testCube where " + TWO_DAYS_RANGE;

    // pass
    String q3 = "SELECT cityid, sum(testCube.msr2) from testCube where " + TWO_DAYS_RANGE;

    // pass
    String q4 = "SELECT cityid, sum(testCube.msr2) from testCube where " + TWO_DAYS_RANGE
      + " having testCube.msr2 > 100";

    // pass
    String q5 =
      "SELECT cityid, testCube.msr2 from testCube where " + TWO_DAYS_RANGE
        + " having testCube.msr2 + testCube.msr3 > 100";

    // pass
    String q6 =
      "SELECT cityid, testCube.msr2 from testCube where " + TWO_DAYS_RANGE
        + " having testCube.msr2 > 100 AND testCube.msr2 < 1000";

    // pass
    String q7 =
      "SELECT cityid, sum(testCube.msr2) from testCube where " + TWO_DAYS_RANGE
        + " having (testCube.msr2 > 100) OR (testcube.msr2 < 100 AND max(testcube.msr3) > 1000)";

    // pass
    String q8 = "SELECT cityid, sum(testCube.msr2) * max(testCube.msr3) from testCube where " + TWO_DAYS_RANGE;

    // pass
    String q9 =
      "SELECT cityid c1, max(msr3) m3 from testCube where c1 > 100 and " + TWO_DAYS_RANGE + " having (msr2 < 100"
        + " AND m3 > 1000)";

    String q10 = "SELECT cityid, round(testCube.msr2) from testCube where " + TWO_DAYS_RANGE;

    //dimension selected with having
    String q11 = "SELECT cityid from testCube where " + TWO_DAYS_RANGE + " having (testCube.msr2 > 100)";

    String expectedq1 =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `msr2` from ", null,
        "group by testcube.cityid", getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    String expectedq2 =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) * max(testCube.msr3) "
          + "as `testCube.msr2 * testCube.msr3` from ", null,
        "group by testcube.cityid", getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    String expectedq3 =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` "
          + "from ", null, "group by testcube.cityid",
          getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    String expectedq4 =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` "
          + "from ", null, "group by testcube.cityid having" + " sum(testCube.msr2) > 100",
        getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    String expectedq5 =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `msr2` from ", null,
        "group by testcube.cityid having" + " sum(testCube.msr2) + max(testCube.msr3) > 100",
        getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    String expectedq6 =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2)  as `msr2`from ", null,
        "group by testcube.cityid having" + " sum(testCube.msr2) > 100 and sum(testCube.msr2) < 1000",
        getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    String expectedq7 =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` "
          + "from ", null, "group by testcube.cityid having"
          + " sum(testCube.msr2) > 100 OR (sum(testCube.msr2) < 100 AND"
          + " max(testcube.msr3) > 1000)", getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    String expectedq8 =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) * max(testCube.msr3) "
          + "as `sum(testCube.msr2) * max(testCube.msr3)` from ", null,
        "group by testcube.cityid", getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    String expectedq9 =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `c1`, max(testCube.msr3) as `m3` from ", "c1 > 100",
        "group by testcube.cityid" + " having sum(testCube.msr2) < 100 AND (m3 > 1000)",
        getWhereForDailyAndHourly2days(cubeName, "c2_testfact"));
    String expectedq10 =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, round(sum(testCube.msr2))  "
          + "as `round(testCube.msr2)` from ", null,
        "group by testcube.cityid", getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    String expectedq11 =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`from ", null,
        "group by testcube.cityid" + "having sum(testCube.msr2) > 100",
              getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    String[] tests = {
      q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11,
    };
    String[] expected = {
      expectedq1, expectedq2, expectedq3, expectedq4, expectedq5,
      expectedq6, expectedq7, expectedq8, expectedq9, expectedq10,
      expectedq11,
    };

    for (int i = 0; i < tests.length; i++) {
      String hql = rewrite(tests[i], conf);
      System.out.println("hql[" + i + "]:" + hql);
      compareQueries(hql, expected[i]);
    }
    aggregateFactSelectionTests(conf);
    rawFactSelectionTests(getConfWithStorages("C1,C2"));
  }

  @Test
  public void testDimOnlyDistinctQuery() throws ParseException, LensException {

    conf.setBoolean(CubeQueryConfUtil.DISABLE_AGGREGATE_RESOLVER, false);

    //Add distinct
    String query1 = "SELECT testcube.cityid,testcube.zipcode,testcube.stateid from testCube where " + TWO_DAYS_RANGE;
    String hQL1 = rewrite(query1, conf);
    String expectedQL1 =
      getExpectedQuery(cubeName, "SELECT distinct testcube.cityid as `cityid`, testcube.zipcode as `zipcode`, "
          + "testcube.stateid as `stateid`" + " from ", null,
        null, getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    compareQueries(hQL1, expectedQL1);

    //Don't add distinct
    String query2 = "SELECT count (distinct testcube.cityid) from testcube where " + TWO_DAYS_RANGE;
    String hQL2 = rewrite(query2, conf);
    String expectedQL2 =
      getExpectedQuery(cubeName, "SELECT count (distinct testcube.cityid) as `count(distinct testcube.cityid)`"
          + " from ", null, null,
        getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    compareQueries(hQL2, expectedQL2);

    //Don't add distinct
    String query3 = "SELECT  testcube.cityid, count(distinct testcube.stateid) from testcube where " + TWO_DAYS_RANGE;
    String hQL3 = rewrite(query3, conf);
    String expectedQL3 =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, count(distinct testcube.stateid) "
          + "as `count(distinct testcube.stateid)` " + " from ", null,
        "group by testcube.cityid", getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    compareQueries(hQL3, expectedQL3);

    //Don't add distinct
    String query4 = "SELECT  count(testcube.stateid) from testcube where " + TWO_DAYS_RANGE;
    String hQL4 = rewrite(query4, conf);
    String expectedQL4 =
      getExpectedQuery(cubeName, "SELECT count(testcube.stateid) as `count(testcube.stateid)`" + " from ", null,
        null, getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    compareQueries(hQL4, expectedQL4);

    //Don't add distinct, by setting the flag false
    conf.setBoolean(CubeQueryConfUtil.ENABLE_ATTRFIELDS_ADD_DISTINCT, false);
    String query5 = "SELECT  testcube.stateid from testcube where " + TWO_DAYS_RANGE;
    String hQL5 = rewrite(query5, conf);
    String expectedQL5 =
      getExpectedQuery(cubeName, "SELECT testcube.stateid as `stateid`" + " from ", null,
        null, getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    compareQueries(hQL5, expectedQL5);

  }

  @Test
  public void testAggregateResolverOff() throws ParseException, LensException {
    Configuration conf2 = getConfWithStorages("C1,C2");
    conf2.setBoolean(CubeQueryConfUtil.DISABLE_AGGREGATE_RESOLVER, true);

    // Test if raw fact is selected for query with no aggregate function on a
    // measure, with aggregate resolver disabled
    String query = "SELECT cityid, testCube.msr2 FROM testCube WHERE " + TWO_DAYS_RANGE;
    CubeQueryContext cubeql = rewriteCtx(query, conf2);
    String hQL = cubeql.toHQL();
    Assert.assertEquals(1, cubeql.getCandidates().size());
    Candidate candidate = cubeql.getCandidates().iterator().next();
    Assert.assertTrue(candidate instanceof StorageCandidate);
    Assert.assertEquals("c1_testFact2_raw".toLowerCase(),
        ((StorageCandidate) candidate).getStorageTable().toLowerCase());
    String expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, testCube.msr2 as `msr2` from ", null, null,
        getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);
    conf2.set(CubeQueryConfUtil.DRIVER_SUPPORTED_STORAGES, "C2");
    aggregateFactSelectionTests(conf2);
    conf2.set(CubeQueryConfUtil.DRIVER_SUPPORTED_STORAGES, "C1,C2");
    rawFactSelectionTests(conf2);
  }

  private void aggregateFactSelectionTests(Configuration conf) throws ParseException, LensException {
    String query = "SELECT count(distinct cityid) from testcube where " + TWO_DAYS_RANGE;
    CubeQueryContext cubeql = rewriteCtx(query, conf);
    String hQL = cubeql.toHQL();
    String expectedQL =
      getExpectedQuery(cubeName, "SELECT count(distinct testcube.cityid) as `count( distinct cityid)` from ",
          null, null, getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    compareQueries(hQL, expectedQL);

    query = "SELECT distinct cityid from testcube where " + TWO_DAYS_RANGE;
    hQL = rewrite(query, conf);
    expectedQL =
      getExpectedQuery(cubeName, "SELECT distinct testcube.cityid  as `cityid` from ", null, null,
        getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    compareQueries(hQL, expectedQL);

    // with aggregate resolver on/off, msr with its default aggregate around it
    // should pick up aggregated fact
    query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE;
    cubeql = rewriteCtx(query, conf);
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` "
          + "from ", null, "group by testcube.cityid", getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    compareQueries(hQL, expectedQL);

    query = "SELECT cityid, sum(testCube.msr2) m2 FROM testCube WHERE " + TWO_DAYS_RANGE + " order by m2";
    cubeql = rewriteCtx(query, conf);
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `m2` from ", null,
        "group by testcube.cityid order by m2 asc", getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    compareQueries(hQL, expectedQL);

    query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE + " having max(msr3) > 100";
    cubeql = rewriteCtx(query, conf);
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` "
          + "from ", null, "group by testcube.cityid having max(testcube.msr3) > 100",
        getWhereForDailyAndHourly2days(cubeName, "C2_testfact"));
    compareQueries(hQL, expectedQL);
  }

  private void rawFactSelectionTests(Configuration conf) throws ParseException, LensException {
    // Check a query with non default aggregate function
    String query = "SELECT cityid, avg(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE;
    CubeQueryContext cubeql = rewriteCtx(query, conf);
    String hQL = cubeql.toHQL();
    Assert.assertEquals(1, cubeql.getCandidates().size());
    Candidate candidate = cubeql.getCandidates().iterator().next();
    Assert.assertTrue(candidate instanceof StorageCandidate);
    Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate)
        .getStorageTable().toLowerCase());
    String expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, avg(testCube.msr2) as `avg(testCube.msr2)` "
          + "from ", null, "group by testcube.cityid", getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);

    // query with measure in a where clause
    query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE testCube.msr1 < 100 and " + TWO_DAYS_RANGE;
    cubeql = rewriteCtx(query, conf);
    Assert.assertEquals(1, cubeql.getCandidates().size());
    candidate = cubeql.getCandidates().iterator().next();
    Assert.assertTrue(candidate instanceof StorageCandidate);
    Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate)
        .getStorageTable().toLowerCase());
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` "
          + "from ", "testcube.msr1 < 100", "group by testcube.cityid", getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);

    query = "SELECT cityid, testCube.msr2 FROM testCube WHERE testCube.msr2 < 100 and " + TWO_DAYS_RANGE;
    cubeql = rewriteCtx(query, conf);
    Assert.assertEquals(1, cubeql.getCandidates().size());
    candidate = cubeql.getCandidates().iterator().next();
    Assert.assertTrue(candidate instanceof StorageCandidate);
    Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate)
        .getStorageTable().toLowerCase());
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, testCube.msr2 as `msr2` from ",
          "testcube.msr2 < 100", null, getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);

    query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE + " group by testCube.msr1";
    cubeql = rewriteCtx(query, conf);
    Assert.assertEquals(1, cubeql.getCandidates().size());
    candidate = cubeql.getCandidates().iterator().next();
    Assert.assertTrue(candidate instanceof StorageCandidate);
    Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate)
        .getStorageTable().toLowerCase());
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2)  as `sum(testCube.msr2)` "
          + "from ", null, " group by testCube.msr1", getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);

    query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE + " group by testCube.msr3";
    cubeql = rewriteCtx(query, conf);
    Assert.assertEquals(1, cubeql.getCandidates().size());
    candidate = cubeql.getCandidates().iterator().next();
    Assert.assertTrue(candidate instanceof StorageCandidate);
    Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate)
        .getStorageTable().toLowerCase());
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` "
          + "from ", null, " group by testCube.msr3", getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);

    query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE + " order by testCube.msr1";
    cubeql = rewriteCtx(query, conf);
    Assert.assertEquals(1, cubeql.getCandidates().size());
    candidate = cubeql.getCandidates().iterator().next();
    Assert.assertTrue(candidate instanceof StorageCandidate);
    Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate)
        .getStorageTable().toLowerCase());
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2)  as `sum(testCube.msr2)` "
          + "from ", null, " group by testcube.cityid order by testcube.msr1 asc",
          getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);

    query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE + " order by testCube.msr3";
    cubeql = rewriteCtx(query, conf);
    Assert.assertEquals(1, cubeql.getCandidates().size());
    candidate = cubeql.getCandidates().iterator().next();
    Assert.assertTrue(candidate instanceof StorageCandidate);
    Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate)
        .getStorageTable().toLowerCase());
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` "
          + "from ", null, " group by testcube.cityid order by testcube.msr3 asc",
          getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);

    query = "SELECT distinct cityid, round(testCube.msr2) from testCube where " + TWO_DAYS_RANGE;
    cubeql = rewriteCtx(query, conf);
    Assert.assertEquals(1, cubeql.getCandidates().size());
    candidate = cubeql.getCandidates().iterator().next();
    Assert.assertTrue(candidate instanceof StorageCandidate);
    Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate)
        .getStorageTable().toLowerCase());
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT distinct testcube.cityid as `cityid`, round(testCube.msr2)  "
          + "as `round(testCube.msr2)` from ", null, null, getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);

    query = "SELECT cityid, count(distinct(testCube.msr2)) from testCube where " + TWO_DAYS_RANGE;
    cubeql = rewriteCtx(query, conf);
    Assert.assertEquals(1, cubeql.getCandidates().size());
    candidate = cubeql.getCandidates().iterator().next();
    Assert.assertTrue(candidate instanceof StorageCandidate);
    Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate)
        .getStorageTable().toLowerCase());
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, count(distinct testCube.msr2) "
          + "as `count(distinct(testCube.msr2))` from ", null, "group by testcube.cityid",
          getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);

    // query with no default aggregate measure
    query = "SELECT cityid, round(testCube.msr1) from testCube where " + TWO_DAYS_RANGE;
    cubeql = rewriteCtx(query, conf);
    Assert.assertEquals(1, cubeql.getCandidates().size());
    candidate = cubeql.getCandidates().iterator().next();
    Assert.assertTrue(candidate instanceof StorageCandidate);
    Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate)
        .getStorageTable().toLowerCase());
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, round(testCube.msr1) as `round(testCube.msr1)` "
          + "from ", null, null, getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);

    query = "SELECT distinct cityid, round(testCube.msr1) from testCube where " + TWO_DAYS_RANGE;
    cubeql = rewriteCtx(query, conf);
    Assert.assertEquals(1, cubeql.getCandidates().size());
    candidate = cubeql.getCandidates().iterator().next();
    Assert.assertTrue(candidate instanceof StorageCandidate);
    Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate)
        .getStorageTable().toLowerCase());
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT distinct testcube.cityid as `cityid`, round(testCube.msr1) "
          + "as `round(testCube.msr1)` from ", null, null, getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);

    query = "SELECT cityid, count(distinct(testCube.msr1)) from testCube where " + TWO_DAYS_RANGE;
    cubeql = rewriteCtx(query, conf);
    Assert.assertEquals(1, cubeql.getCandidates().size());
    candidate = cubeql.getCandidates().iterator().next();
    Assert.assertTrue(candidate instanceof StorageCandidate);
    Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate)
        .getStorageTable().toLowerCase());
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, count(distinct testCube.msr1) "
          + "as ` count(distinct testCube.msr1)` from ", null, "group by testcube.cityid",
          getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);

    query = "SELECT cityid, sum(testCube.msr1) from testCube where " + TWO_DAYS_RANGE;
    cubeql = rewriteCtx(query, conf);
    Assert.assertEquals(1, cubeql.getCandidates().size());
    candidate = cubeql.getCandidates().iterator().next();
    Assert.assertTrue(candidate instanceof StorageCandidate);
    Assert.assertEquals("c1_testFact2_raw".toLowerCase(), ((StorageCandidate) candidate)
        .getStorageTable().toLowerCase());
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr1) as `sum(testCube.msr1)` "
          + "from ", null, "group by testcube.cityid",
          getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);
    query = "SELECT cityid, sum(testCube.msr2) FROM testCube WHERE " + TWO_DAYS_RANGE + " having max(msr1) > 100";
    cubeql = rewriteCtx(query, conf);
    hQL = cubeql.toHQL();
    expectedQL =
      getExpectedQuery(cubeName, "SELECT testcube.cityid as `cityid`, sum(testCube.msr2) as `sum(testCube.msr2)` "
          + "from ", null, "group by testcube.cityid having max(testcube.msr1) > 100",
          getWhereForHourly2days("c1_testfact2_raw"));
    compareQueries(hQL, expectedQL);
  }
}


text:
package com.siondream.core.assets;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetErrorListener;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.AssetLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.JsonReader;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.JsonValue.JsonIterator;
import com.badlogic.gdx.utils.Logger;
import com.badlogic.gdx.utils.ObjectMap;
import com.esotericsoftware.spine.AnimationStateData;
import com.esotericsoftware.spine.SkeletonData;
import com.siondream.core.Env;
import com.siondream.core.animation.SpriteAnimationData;
import com.siondream.core.animation.SpriteAnimationLoader;
import com.siondream.core.physics.PhysicsData;
import com.siondream.core.physics.PhysicsLoader;
import com.siondream.core.spine.AnimationStateDataLoader;
import com.siondream.core.spine.SkeletonDataLoader;

public class Assets implements Disposable, AssetErrorListener {

	private static final String TAG = "Assets";
	private Logger logger;
	private AssetManager manager;
	private ObjectMap<String, Array<Asset>> groups;

	public Assets(String assetFile) {
		logger = new Logger(TAG, Env.debugLevel);

		logger.info("initialising");

		manager = new AssetManager();
//		manager.setErrorListener(this);
		manager.setLoader(TiledMap.class, new TmxMapLoader(new InternalFileHandleResolver()));
		manager.setLoader(PhysicsData.class, new PhysicsLoader(new InternalFileHandleResolver()));
		manager.setLoader(SpriteAnimationData.class, new SpriteAnimationLoader(new InternalFileHandleResolver()));
		manager.setLoader(SkeletonData.class, new SkeletonDataLoader(new InternalFileHandleResolver()));
		manager.setLoader(AnimationStateData.class, new AnimationStateDataLoader(new InternalFileHandleResolver()));

		loadGroups(assetFile);
	}

	public AssetLoader<?, ?> getLoader(Class<?> type) {
		return manager.getLoader(type);
	}

	public void loadGroup(String groupName) {
		logger.info("loading group " + groupName);

		Array<Asset> assets = groups.get(groupName, null);

		if (assets != null) {
			for (Asset asset : assets) {
				manager.load(asset.path, asset.type, asset.parameters);
			}
		}
		else {
			logger.error("error loading group " + groupName + ", not found");
		}
	}

	public void unloadGroup(String groupName) {
		logger.info("unloading group " + groupName);

		Array<Asset> assets = groups.get(groupName, null);

		if (assets != null) {
			for (Asset asset : assets) {
				if (manager.isLoaded(asset.path, asset.type)) {
					manager.unload(asset.path);
				}
			}
		}
		else {
			logger.error("error unloading group " + groupName + ", not found");
		}
	}

	public synchronized <T> T get(String fileName) {
		return manager.get(fileName);
	}

	public synchronized <T> T get(String fileName, Class<T> type) {
		return manager.get(fileName, type);
	}

	public <T> boolean isLoaded(String fileName, Class<T> type) {
		return manager.isLoaded(fileName, type);
	}

	public boolean update() {
		return manager.update();
	}

	public void finishLoading() {
		manager.finishLoading();
	}

	public float getProgress() {
		return manager.getProgress();
	}

	@Override
	public void dispose() {
		logger.info("shutting down");
		manager.dispose();
	}

	@Override
	public void error(AssetDescriptor asset, Throwable throwable) {
		logger.error("error loading " + asset.fileName + " message: " + throwable.getMessage());
	}

	private void loadGroups(String assetFile) {
		groups = new ObjectMap<String, Array<Asset>>();

		logger.info("loading file " + assetFile);

//		try {
			Json json = new Json();
			JsonReader reader = new JsonReader();
			JsonValue root = reader.parse(Gdx.files.internal(assetFile));

			JsonIterator groupIt = root.iterator();

			while (groupIt.hasNext()) {
				JsonValue groupValue = groupIt.next();

				if (groups.containsKey(groupValue.name)) {
					logger.error("group " + groupValue.name + " already exists, skipping");
					continue;
				}

				logger.info("registering group " + groupValue.name);

				Array<Asset> assets = new Array<Asset>();

				JsonIterator assetIt = groupValue.iterator();

				while (assetIt.hasNext()) {
					JsonValue assetValue = assetIt.next();

					Asset asset = json.fromJson(Asset.class, assetValue.toString());
					assets.add(asset);
				}

				groups.put(groupValue.name, assets);
			}
//		}
//		catch (Exception e) {
//			logger.error("error loading file " + assetFile + " " + e.getMessage());
//		}
	}
}


text:
tone: 4
eothinon: 7
title: Sunday of the Samaritan Woman & After-feast of Mid-Pentecost
saints:
    - Holy Martyr Theodosia of Tyre
    - Righteous Martyr Theodosia of Constantinople
    - Hieromartyr Olvian, bishop of Aneos, and his disciples
    - New-martyr John of Smyrna
    - New-martyr Andrew Argenti of Chios
    - John of Ustug, fool-for-Christ

# Orthros
apolytikion:
    - Resurrectional Apolytikion - Tone 4
    - Glory/Resurrectional Apolytikion - Tone 4
    - Both Now/Apolytikion for Mid-Pentecost - Tone 8

kathismata: null
evlogetaria: null
prokeimenon: null
canon: Paschal Canon
little_ektenia_3: 2
normal_exaposteilarion: false
exaposteilaria:
    - Exaposteilarion of Pascha - Tone 2
    - Exaposteilarion of the Samaritan Woman - Tone 2
    - Exaposteilarion of Mid-Pentecost - Tone 2
praises: null
doxastikon: Doxastikon of the Samaritan Woman (Tone 6) **AND** Doxastikon of Pascha (Tone 5)
great_doxology: 5
troparion: null

# Divine Liturgy
antiphon_12: Paschal Verses
antiphon_3: for Pascha
entrance: Entrance Hymn of Pascha
post_entrance:
    - Resurrectional Apolytikion - Tone 4
    - Apolytikion of Mid-Pentecost - Tone 8
ascension: true
kontakion: Kontakion of Pascha - Tone 8
trisagion: false
megalynarion: Sunday of the Samaritan Woman - Tone 1
koinonikon: Pascha
post_communion: Instead of "We have seen the true light" sing "Christ is Risen" **ONCE**
post_communion_markdown: false

---


text:
using System;
using System.Collections.Generic;
using Castle.MicroKernel;
using Castle.MicroKernel.Registration;
using Rhino.Licensing.AdminTool.Extensions;
using Rhino.Licensing.AdminTool.Services;
using Rhino.Licensing.AdminTool.ViewModels;
using System.Linq;

namespace Rhino.Licensing.AdminTool.Startup
{
    public class ViewModelRegistration : IRegistration
    {
        public virtual void Register(IKernel kernel)
        {
            kernel.Register(AllTypes.FromAssemblyContaining<ViewModelRegistration>()
                                    .Where(t => ViewModelNamespaces.Contains(t.Namespace) &&
                                                !SkipAutoRegistration.Contains(t))
                                    .WithService.FirstInterfaceOnClass()
                                    .Configure(c => c.LifeStyle.Transient));

            kernel.Register(Component.For<IShellViewModel>()
                                     .ImplementedBy<ShellViewModel>()
                                     .Forward<IStatusService>()
                                     .LifeStyle.Singleton);
        }

        private static IEnumerable<string> ViewModelNamespaces
        {
            get
            {
                yield return "Rhino.Licensing.AdminTool.ViewModels";
                yield return "Rhino.Licensing.AdminTool.Dialogs";
            }
        }

        private static IEnumerable<Type> SkipAutoRegistration
        {
            get
            {
                yield return typeof (ShellViewModel);
            }
        }
    }
}


text:
#include "sysdep.h"
#include "bfd.h"
#include "libbfd.h"
#include "objalloc.h"
#include "libiberty.h"

/*
SECTION
	Hash Tables

@cindex Hash tables
	BFD provides a simple set of hash table functions.  Routines
	are provided to initialize a hash table, to free a hash table,
	to look up a string in a hash table and optionally create an
	entry for it, and to traverse a hash table.  There is
	currently no routine to delete an string from a hash table.

	The basic hash table does not permit any data to be stored
	with a string.  However, a hash table is designed to present a
	base class from which other types of hash tables may be
	derived.  These derived types may store additional information
	with the string.  Hash tables were implemented in this way,
	rather than simply providing a data pointer in a hash table
	entry, because they were designed for use by the linker back
	ends.  The linker may create thousands of hash table entries,
	and the overhead of allocating private data and storing and
	following pointers becomes noticeable.

	The basic hash table code is in <<hash.c>>.

@menu
@* Creating and Freeing a Hash Table::
@* Looking Up or Entering a String::
@* Traversing a Hash Table::
@* Deriving a New Hash Table Type::
@end menu

INODE
Creating and Freeing a Hash Table, Looking Up or Entering a String, Hash Tables, Hash Tables
SUBSECTION
	Creating and freeing a hash table

@findex bfd_hash_table_init
@findex bfd_hash_table_init_n
	To create a hash table, create an instance of a <<struct
	bfd_hash_table>> (defined in <<bfd.h>>) and call
	<<bfd_hash_table_init>> (if you know approximately how many
	entries you will need, the function <<bfd_hash_table_init_n>>,
	which takes a @var{size} argument, may be used).
	<<bfd_hash_table_init>> returns <<FALSE>> if some sort of
	error occurs.

@findex bfd_hash_newfunc
	The function <<bfd_hash_table_init>> take as an argument a
	function to use to create new entries.  For a basic hash
	table, use the function <<bfd_hash_newfunc>>.  @xref{Deriving
	a New Hash Table Type}, for why you would want to use a
	different value for this argument.

@findex bfd_hash_allocate
	<<bfd_hash_table_init>> will create an objalloc which will be
	used to allocate new entries.  You may allocate memory on this
	objalloc using <<bfd_hash_allocate>>.

@findex bfd_hash_table_free
	Use <<bfd_hash_table_free>> to free up all the memory that has
	been allocated for a hash table.  This will not free up the
	<<struct bfd_hash_table>> itself, which you must provide.

@findex bfd_hash_set_default_size
	Use <<bfd_hash_set_default_size>> to set the default size of
	hash table to use.

INODE
Looking Up or Entering a String, Traversing a Hash Table, Creating and Freeing a Hash Table, Hash Tables
SUBSECTION
	Looking up or entering a string

@findex bfd_hash_lookup
	The function <<bfd_hash_lookup>> is used both to look up a
	string in the hash table and to create a new entry.

	If the @var{create} argument is <<FALSE>>, <<bfd_hash_lookup>>
	will look up a string.  If the string is found, it will
	returns a pointer to a <<struct bfd_hash_entry>>.  If the
	string is not found in the table <<bfd_hash_lookup>> will
	return <<NULL>>.  You should not modify any of the fields in
	the returns <<struct bfd_hash_entry>>.

	If the @var{create} argument is <<TRUE>>, the string will be
	entered into the hash table if it is not already there.
	Either way a pointer to a <<struct bfd_hash_entry>> will be
	returned, either to the existing structure or to a newly
	created one.  In this case, a <<NULL>> return means that an
	error occurred.

	If the @var{create} argument is <<TRUE>>, and a new entry is
	created, the @var{copy} argument is used to decide whether to
	copy the string onto the hash table objalloc or not.  If
	@var{copy} is passed as <<FALSE>>, you must be careful not to
	deallocate or modify the string as long as the hash table
	exists.

INODE
Traversing a Hash Table, Deriving a New Hash Table Type, Looking Up or Entering a String, Hash Tables
SUBSECTION
	Traversing a hash table

@findex bfd_hash_traverse
	The function <<bfd_hash_traverse>> may be used to traverse a
	hash table, calling a function on each element.  The traversal
	is done in a random order.

	<<bfd_hash_traverse>> takes as arguments a function and a
	generic <<void *>> pointer.  The function is called with a
	hash table entry (a <<struct bfd_hash_entry *>>) and the
	generic pointer passed to <<bfd_hash_traverse>>.  The function
	must return a <<boolean>> value, which indicates whether to
	continue traversing the hash table.  If the function returns
	<<FALSE>>, <<bfd_hash_traverse>> will stop the traversal and
	return immediately.

INODE
Deriving a New Hash Table Type, , Traversing a Hash Table, Hash Tables
SUBSECTION
	Deriving a new hash table type

	Many uses of hash tables want to store additional information
	which each entry in the hash table.  Some also find it
	convenient to store additional information with the hash table
	itself.  This may be done using a derived hash table.

	Since C is not an object oriented language, creating a derived
	hash table requires sticking together some boilerplate
	routines with a few differences specific to the type of hash
	table you want to create.

	An example of a derived hash table is the linker hash table.
	The structures for this are defined in <<bfdlink.h>>.  The
	functions are in <<linker.c>>.

	You may also derive a hash table from an already derived hash
	table.  For example, the a.out linker backend code uses a hash
	table derived from the linker hash table.

@menu
@* Define the Derived Structures::
@* Write the Derived Creation Routine::
@* Write Other Derived Routines::
@end menu

INODE
Define the Derived Structures, Write the Derived Creation Routine, Deriving a New Hash Table Type, Deriving a New Hash Table Type
SUBSUBSECTION
	Define the derived structures

	You must define a structure for an entry in the hash table,
	and a structure for the hash table itself.

	The first field in the structure for an entry in the hash
	table must be of the type used for an entry in the hash table
	you are deriving from.  If you are deriving from a basic hash
	table this is <<struct bfd_hash_entry>>, which is defined in
	<<bfd.h>>.  The first field in the structure for the hash
	table itself must be of the type of the hash table you are
	deriving from itself.  If you are deriving from a basic hash
	table, this is <<struct bfd_hash_table>>.

	For example, the linker hash table defines <<struct
	bfd_link_hash_entry>> (in <<bfdlink.h>>).  The first field,
	<<root>>, is of type <<struct bfd_hash_entry>>.  Similarly,
	the first field in <<struct bfd_link_hash_table>>, <<table>>,
	is of type <<struct bfd_hash_table>>.

INODE
Write the Derived Creation Routine, Write Other Derived Routines, Define the Derived Structures, Deriving a New Hash Table Type
SUBSUBSECTION
	Write the derived creation routine

	You must write a routine which will create and initialize an
	entry in the hash table.  This routine is passed as the
	function argument to <<bfd_hash_table_init>>.

	In order to permit other hash tables to be derived from the
	hash table you are creating, this routine must be written in a
	standard way.

	The first argument to the creation routine is a pointer to a
	hash table entry.  This may be <<NULL>>, in which case the
	routine should allocate the right amount of space.  Otherwise
	the space has already been allocated by a hash table type
	derived from this one.

	After allocating space, the creation routine must call the
	creation routine of the hash table type it is derived from,
	passing in a pointer to the space it just allocated.  This
	will initialize any fields used by the base hash table.

	Finally the creation routine must initialize any local fields
	for the new hash table type.

	Here is a boilerplate example of a creation routine.
	@var{function_name} is the name of the routine.
	@var{entry_type} is the type of an entry in the hash table you
	are creating.  @var{base_newfunc} is the name of the creation
	routine of the hash table type your hash table is derived
	from.

EXAMPLE

.struct bfd_hash_entry *
.@var{function_name} (struct bfd_hash_entry *entry,
.                     struct bfd_hash_table *table,
.                     const char *string)
.{
.  struct @var{entry_type} *ret = (@var{entry_type} *) entry;
.
. {* Allocate the structure if it has not already been allocated by a
.    derived class.  *}
.  if (ret == NULL)
.    {
.      ret = bfd_hash_allocate (table, sizeof (* ret));
.      if (ret == NULL)
.        return NULL;
.    }
.
. {* Call the allocation method of the base class.  *}
.  ret = ((@var{entry_type} *)
.	 @var{base_newfunc} ((struct bfd_hash_entry *) ret, table, string));
.
. {* Initialize the local fields here.  *}
.
.  return (struct bfd_hash_entry *) ret;
.}

DESCRIPTION
	The creation routine for the linker hash table, which is in
	<<linker.c>>, looks just like this example.
	@var{function_name} is <<_bfd_link_hash_newfunc>>.
	@var{entry_type} is <<struct bfd_link_hash_entry>>.
	@var{base_newfunc} is <<bfd_hash_newfunc>>, the creation
	routine for a basic hash table.

	<<_bfd_link_hash_newfunc>> also initializes the local fields
	in a linker hash table entry: <<type>>, <<written>> and
	<<next>>.

INODE
Write Other Derived Routines, , Write the Derived Creation Routine, Deriving a New Hash Table Type
SUBSUBSECTION
	Write other derived routines

	You will want to write other routines for your new hash table,
	as well.

	You will want an initialization routine which calls the
	initialization routine of the hash table you are deriving from
	and initializes any other local fields.  For the linker hash
	table, this is <<_bfd_link_hash_table_init>> in <<linker.c>>.

	You will want a lookup routine which calls the lookup routine
	of the hash table you are deriving from and casts the result.
	The linker hash table uses <<bfd_link_hash_lookup>> in
	<<linker.c>> (this actually takes an additional argument which
	it uses to decide how to return the looked up value).

	You may want a traversal routine.  This should just call the
	traversal routine of the hash table you are deriving from with
	appropriate casts.  The linker hash table uses
	<<bfd_link_hash_traverse>> in <<linker.c>>.

	These routines may simply be defined as macros.  For example,
	the a.out backend linker hash table, which is derived from the
	linker hash table, uses macros for the lookup and traversal
	routines.  These are <<aout_link_hash_lookup>> and
	<<aout_link_hash_traverse>> in aoutx.h.
*/

/* The default number of entries to use when creating a hash table.  */
#define DEFAULT_SIZE 4051

/* The following function returns a nearest prime number which is
   greater than N, and near a power of two.  Copied from libiberty.
   Returns zero for ridiculously large N to signify an error.  */

static unsigned long
higher_prime_number (unsigned long n)
{
  /* These are primes that are near, but slightly smaller than, a
     power of two.  */
  static const unsigned long primes[] =
    {
      (unsigned long) 31,
      (unsigned long) 61,
      (unsigned long) 127,
      (unsigned long) 251,
      (unsigned long) 509,
      (unsigned long) 1021,
      (unsigned long) 2039,
      (unsigned long) 4093,
      (unsigned long) 8191,
      (unsigned long) 16381,
      (unsigned long) 32749,
      (unsigned long) 65521,
      (unsigned long) 131071,
      (unsigned long) 262139,
      (unsigned long) 524287,
      (unsigned long) 1048573,
      (unsigned long) 2097143,
      (unsigned long) 4194301,
      (unsigned long) 8388593,
      (unsigned long) 16777213,
      (unsigned long) 33554393,
      (unsigned long) 67108859,
      (unsigned long) 134217689,
      (unsigned long) 268435399,
      (unsigned long) 536870909,
      (unsigned long) 1073741789,
      (unsigned long) 2147483647,
					/* 4294967291L */
      ((unsigned long) 2147483647) + ((unsigned long) 2147483644),
  };

  const unsigned long *low = &primes[0];
  const unsigned long *high = &primes[sizeof (primes) / sizeof (primes[0])];

  while (low != high)
    {
      const unsigned long *mid = low + (high - low) / 2;
      if (n >= *mid)
	low = mid + 1;
      else
	high = mid;
    }

  if (n >= *low)
    return 0;

  return *low;
}

static unsigned long bfd_default_hash_table_size = DEFAULT_SIZE;

/* Create a new hash table, given a number of entries.  */

bfd_boolean
bfd_hash_table_init_n (struct bfd_hash_table *table,
		       struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
							  struct bfd_hash_table *,
							  const char *),
		       unsigned int entsize,
		       unsigned int size)
{
  unsigned long alloc;

  alloc = size;
  alloc *= sizeof (struct bfd_hash_entry *);
  if (alloc / sizeof (struct bfd_hash_entry *) != size)
    {
      bfd_set_error (bfd_error_no_memory);
      return FALSE;
    }

  table->memory = (void *) objalloc_create ();
  if (table->memory == NULL)
    {
      bfd_set_error (bfd_error_no_memory);
      return FALSE;
    }
  table->table = (struct bfd_hash_entry **)
      objalloc_alloc ((struct objalloc *) table->memory, alloc);
  if (table->table == NULL)
    {
      bfd_hash_table_free (table);
      bfd_set_error (bfd_error_no_memory);
      return FALSE;
    }
  memset ((void *) table->table, 0, alloc);
  table->size = size;
  table->entsize = entsize;
  table->count = 0;
  table->frozen = 0;
  table->newfunc = newfunc;
  return TRUE;
}

/* Create a new hash table with the default number of entries.  */

bfd_boolean
bfd_hash_table_init (struct bfd_hash_table *table,
		     struct bfd_hash_entry *(*newfunc) (struct bfd_hash_entry *,
							struct bfd_hash_table *,
							const char *),
		     unsigned int entsize)
{
  return bfd_hash_table_init_n (table, newfunc, entsize,
				bfd_default_hash_table_size);
}

/* Free a hash table.  */

void
bfd_hash_table_free (struct bfd_hash_table *table)
{
  objalloc_free ((struct objalloc *) table->memory);
  table->memory = NULL;
}

static inline unsigned long
bfd_hash_hash (const char *string, unsigned int *lenp)
{
  const unsigned char *s;
  unsigned long hash;
  unsigned int len;
  unsigned int c;

  hash = 0;
  len = 0;
  s = (const unsigned char *) string;
  while ((c = *s++) != '\0')
    {
      hash += c + (c << 17);
      hash ^= hash >> 2;
    }
  len = (s - (const unsigned char *) string) - 1;
  hash += len + (len << 17);
  hash ^= hash >> 2;
  if (lenp != NULL)
    *lenp = len;
  return hash;
}

/* Look up a string in a hash table.  */

struct bfd_hash_entry *
bfd_hash_lookup (struct bfd_hash_table *table,
		 const char *string,
		 bfd_boolean create,
		 bfd_boolean copy)
{
  unsigned long hash;
  struct bfd_hash_entry *hashp;
  unsigned int len;
  unsigned int _index;

  hash = bfd_hash_hash (string, &len);
  _index = hash % table->size;
  for (hashp = table->table[_index];
       hashp != NULL;
       hashp = hashp->next)
    {
      if (hashp->hash == hash
	  && strcmp (hashp->string, string) == 0)
	return hashp;
    }

  if (! create)
    return NULL;

  if (copy)
    {
      char *new_string;

      new_string = (char *) objalloc_alloc ((struct objalloc *) table->memory,
                                            len + 1);
      if (!new_string)
	{
	  bfd_set_error (bfd_error_no_memory);
	  return NULL;
	}
      memcpy (new_string, string, len + 1);
      string = new_string;
    }

  return bfd_hash_insert (table, string, hash);
}

/* Insert an entry in a hash table.  */

struct bfd_hash_entry *
bfd_hash_insert (struct bfd_hash_table *table,
		 const char *string,
		 unsigned long hash)
{
  struct bfd_hash_entry *hashp;
  unsigned int _index;

  hashp = (*table->newfunc) (NULL, table, string);
  if (hashp == NULL)
    return NULL;
  hashp->string = string;
  hashp->hash = hash;
  _index = hash % table->size;
  hashp->next = table->table[_index];
  table->table[_index] = hashp;
  table->count++;

  if (!table->frozen && table->count > table->size * 3 / 4)
    {
      unsigned long newsize = higher_prime_number (table->size);
      struct bfd_hash_entry **newtable;
      unsigned int hi;
      unsigned long alloc = newsize * sizeof (struct bfd_hash_entry *);

      /* If we can't find a higher prime, or we can't possibly alloc
	 that much memory, don't try to grow the table.  */
      if (newsize == 0 || alloc / sizeof (struct bfd_hash_entry *) != newsize)
	{
	  table->frozen = 1;
	  return hashp;
	}

      newtable = ((struct bfd_hash_entry **)
		  objalloc_alloc ((struct objalloc *) table->memory, alloc));
      if (newtable == NULL)
	{
	  table->frozen = 1;
	  return hashp;
	}
      memset (newtable, 0, alloc);

      for (hi = 0; hi < table->size; hi ++)
	while (table->table[hi])
	  {
	    struct bfd_hash_entry *chain = table->table[hi];
	    struct bfd_hash_entry *chain_end = chain;

	    while (chain_end->next && chain_end->next->hash == chain->hash)
	      chain_end = chain_end->next;

	    table->table[hi] = chain_end->next;
	    _index = chain->hash % newsize;
	    chain_end->next = newtable[_index];
	    newtable[_index] = chain;
	  }
      table->table = newtable;
      table->size = newsize;
    }

  return hashp;
}

/* Rename an entry in a hash table.  */

void
bfd_hash_rename (struct bfd_hash_table *table,
		 const char *string,
		 struct bfd_hash_entry *ent)
{
  unsigned int _index;
  struct bfd_hash_entry **pph;

  _index = ent->hash % table->size;
  for (pph = &table->table[_index]; *pph != NULL; pph = &(*pph)->next)
    if (*pph == ent)
      break;
  if (*pph == NULL)
    abort ();

  *pph = ent->next;
  ent->string = string;
  ent->hash = bfd_hash_hash (string, NULL);
  _index = ent->hash % table->size;
  ent->next = table->table[_index];
  table->table[_index] = ent;
}

/* Replace an entry in a hash table.  */

void
bfd_hash_replace (struct bfd_hash_table *table,
		  struct bfd_hash_entry *old,
		  struct bfd_hash_entry *nw)
{
  unsigned int _index;
  struct bfd_hash_entry **pph;

  _index = old->hash % table->size;
  for (pph = &table->table[_index];
       (*pph) != NULL;
       pph = &(*pph)->next)
    {
      if (*pph == old)
	{
	  *pph = nw;
	  return;
	}
    }

  abort ();
}

/* Allocate space in a hash table.  */

void *
bfd_hash_allocate (struct bfd_hash_table *table,
		   unsigned int size)
{
  void * ret;

  ret = objalloc_alloc ((struct objalloc *) table->memory, size);
  if (ret == NULL && size != 0)
    bfd_set_error (bfd_error_no_memory);
  return ret;
}

/* Base method for creating a new hash table entry.  */

struct bfd_hash_entry *
bfd_hash_newfunc (struct bfd_hash_entry *entry,
		  struct bfd_hash_table *table,
		  const char *string ATTRIBUTE_UNUSED)
{
  if (entry == NULL)
    entry = (struct bfd_hash_entry *) bfd_hash_allocate (table,
                                                         sizeof (* entry));
  return entry;
}

/* Traverse a hash table.  */

void
bfd_hash_traverse (struct bfd_hash_table *table,
		   bfd_boolean (*func) (struct bfd_hash_entry *, void *),
		   void * info)
{
  unsigned int i;

  table->frozen = 1;
  for (i = 0; i < table->size; i++)
    {
      struct bfd_hash_entry *p;

      for (p = table->table[i]; p != NULL; p = p->next)
	if (! (*func) (p, info))
	  goto out;
    }
 out:
  table->frozen = 0;
}

unsigned long
bfd_hash_set_default_size (unsigned long hash_size)
{
  /* Extend this prime list if you want more granularity of hash table size.  */
  static const unsigned long hash_size_primes[] =
    {
      31, 61, 127, 251, 509, 1021, 2039, 4091, 8191, 16381, 32749, 65537
    };
  unsigned int _index;

  /* Work out best prime number near the hash_size.  */
  for (_index = 0; _index < ARRAY_SIZE (hash_size_primes) - 1; ++_index)
    if (hash_size <= hash_size_primes[_index])
      break;

  bfd_default_hash_table_size = hash_size_primes[_index];
  return bfd_default_hash_table_size;
}

/* A few different object file formats (a.out, COFF, ELF) use a string
   table.  These functions support adding strings to a string table,
   returning the byte offset, and writing out the table.

   Possible improvements:
   + look for strings matching trailing substrings of other strings
   + better data structures?  balanced trees?
   + look at reducing memory use elsewhere -- maybe if we didn't have
     to construct the entire symbol table at once, we could get by
     with smaller amounts of VM?  (What effect does that have on the
     string table reductions?)  */

/* An entry in the strtab hash table.  */

struct strtab_hash_entry
{
  struct bfd_hash_entry root;
  /* Index in string table.  */
  bfd_size_type index;
  /* Next string in strtab.  */
  struct strtab_hash_entry *next;
};

/* The strtab hash table.  */

struct bfd_strtab_hash
{
  struct bfd_hash_table table;
  /* Size of strtab--also next available index.  */
  bfd_size_type size;
  /* First string in strtab.  */
  struct strtab_hash_entry *first;
  /* Last string in strtab.  */
  struct strtab_hash_entry *last;
  /* Whether to precede strings with a two byte length, as in the
     XCOFF .debug section.  */
  bfd_boolean xcoff;
};

/* Routine to create an entry in a strtab.  */

static struct bfd_hash_entry *
strtab_hash_newfunc (struct bfd_hash_entry *entry,
		     struct bfd_hash_table *table,
		     const char *string)
{
  struct strtab_hash_entry *ret = (struct strtab_hash_entry *) entry;

  /* Allocate the structure if it has not already been allocated by a
     subclass.  */
  if (ret == NULL)
    ret = (struct strtab_hash_entry *) bfd_hash_allocate (table,
                                                          sizeof (* ret));
  if (ret == NULL)
    return NULL;

  /* Call the allocation method of the superclass.  */
  ret = (struct strtab_hash_entry *)
	 bfd_hash_newfunc ((struct bfd_hash_entry *) ret, table, string);

  if (ret)
    {
      /* Initialize the local fields.  */
      ret->index = (bfd_size_type) -1;
      ret->next = NULL;
    }

  return (struct bfd_hash_entry *) ret;
}

/* Look up an entry in an strtab.  */

#define strtab_hash_lookup(t, string, create, copy) \
  ((struct strtab_hash_entry *) \
   bfd_hash_lookup (&(t)->table, (string), (create), (copy)))

/* Create a new strtab.  */

struct bfd_strtab_hash *
_bfd_stringtab_init (void)
{
  struct bfd_strtab_hash *table;
  bfd_size_type amt = sizeof (* table);

  table = (struct bfd_strtab_hash *) bfd_malloc (amt);
  if (table == NULL)
    return NULL;

  if (!bfd_hash_table_init (&table->table, strtab_hash_newfunc,
			    sizeof (struct strtab_hash_entry)))
    {
      free (table);
      return NULL;
    }

  table->size = 0;
  table->first = NULL;
  table->last = NULL;
  table->xcoff = FALSE;

  return table;
}

/* Create a new strtab in which the strings are output in the format
   used in the XCOFF .debug section: a two byte length precedes each
   string.  */

struct bfd_strtab_hash *
_bfd_xcoff_stringtab_init (void)
{
  struct bfd_strtab_hash *ret;

  ret = _bfd_stringtab_init ();
  if (ret != NULL)
    ret->xcoff = TRUE;
  return ret;
}

/* Free a strtab.  */

void
_bfd_stringtab_free (struct bfd_strtab_hash *table)
{
  bfd_hash_table_free (&table->table);
  free (table);
}

/* Get the index of a string in a strtab, adding it if it is not
   already present.  If HASH is FALSE, we don't really use the hash
   table, and we don't eliminate duplicate strings.  If COPY is true
   then store a copy of STR if creating a new entry.  */

bfd_size_type
_bfd_stringtab_add (struct bfd_strtab_hash *tab,
		    const char *str,
		    bfd_boolean hash,
		    bfd_boolean copy)
{
  struct strtab_hash_entry *entry;

  if (hash)
    {
      entry = strtab_hash_lookup (tab, str, TRUE, copy);
      if (entry == NULL)
	return (bfd_size_type) -1;
    }
  else
    {
      entry = (struct strtab_hash_entry *) bfd_hash_allocate (&tab->table,
                                                              sizeof (* entry));
      if (entry == NULL)
	return (bfd_size_type) -1;
      if (! copy)
	entry->root.string = str;
      else
	{
	  size_t len = strlen (str) + 1;
	  char *n;

	  n = (char *) bfd_hash_allocate (&tab->table, len);
	  if (n == NULL)
	    return (bfd_size_type) -1;
          memcpy (n, str, len);
	  entry->root.string = n;
	}
      entry->index = (bfd_size_type) -1;
      entry->next = NULL;
    }

  if (entry->index == (bfd_size_type) -1)
    {
      entry->index = tab->size;
      tab->size += strlen (str) + 1;
      if (tab->xcoff)
	{
	  entry->index += 2;
	  tab->size += 2;
	}
      if (tab->first == NULL)
	tab->first = entry;
      else
	tab->last->next = entry;
      tab->last = entry;
    }

  return entry->index;
}

/* Get the number of bytes in a strtab.  */

bfd_size_type
_bfd_stringtab_size (struct bfd_strtab_hash *tab)
{
  return tab->size;
}

/* Write out a strtab.  ABFD must already be at the right location in
   the file.  */

bfd_boolean
_bfd_stringtab_emit (bfd *abfd, struct bfd_strtab_hash *tab)
{
  bfd_boolean xcoff;
  struct strtab_hash_entry *entry;

  xcoff = tab->xcoff;

  for (entry = tab->first; entry != NULL; entry = entry->next)
    {
      const char *str;
      size_t len;

      str = entry->root.string;
      len = strlen (str) + 1;

      if (xcoff)
	{
	  bfd_byte buf[2];

	  /* The output length includes the null byte.  */
	  bfd_put_16 (abfd, (bfd_vma) len, buf);
	  if (bfd_bwrite ((void *) buf, (bfd_size_type) 2, abfd) != 2)
	    return FALSE;
	}

      if (bfd_bwrite ((void *) str, (bfd_size_type) len, abfd) != len)
	return FALSE;
    }

  return TRUE;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  operator*

    HACD::Vec3::operator*(const Vec3 &rhs) const
    HACD::Vec3::operator*(T rhs) const
    HACD::operator*()

  operator*=
  HACD::Vec3

  operator+
  HACD::Vec3

  operator+=

    HACD::Vec3::operator+=(const Vec3 &rhs)
    HACD::Vec3::operator+=(T a)

  operator-

    HACD::Vec3::operator-(const Vec3 &rhs) const
    HACD::Vec3::operator-() const

  operator-=

    HACD::Vec3::operator-=(const Vec3 &rhs)
    HACD::Vec3::operator-=(T a)

  operator/
  HACD::Vec3

  operator/=
  HACD::Vec3

  operator<
  HACD

  operator=

    HACD::CircularList::operator=()
    HACD::ICHull::operator=()
    HACD::Vec3::operator=()

  operator>
  HACD

  operator^
  HACD::Vec3

Searching...

No Matches


text:
//
//  CoreResourcesFromBundleProvider.h
//  OsmAnd
//
//  Created by Alexey Pelykh on 12/8/13.
//  Copyright (c) 2013 OsmAnd. All rights reserved.
//

#ifndef __OsmAnd__CoreResourcesFromBundleProvider__
#define __OsmAnd__CoreResourcesFromBundleProvider__

#include <CoreFoundation/CoreFoundation.h>
#include <objc/objc.h>

#include <OsmAndCore/ICoreResourcesProvider.h>

class CoreResourcesFromBundleProvider : public OsmAnd::ICoreResourcesProvider
{
private:
    static NSString* getResourcePath(const QString& name);
    static NSString* getResourcePath(const QString& name,
                                     const float displayDensityFactor);
protected:
public:
    CoreResourcesFromBundleProvider();
    virtual ~CoreResourcesFromBundleProvider();

    virtual QByteArray getResource(const QString& name,
                                   const float displayDensityFactor,
                                   bool* ok = nullptr) const;
    virtual QByteArray getResource(const QString& name,
                                   bool* ok = nullptr) const;

    virtual bool containsResource(const QString& name,
                                  const float displayDensityFactor) const;
    virtual bool containsResource(const QString& name) const;
};

#endif /* defined(__OsmAnd__CoreResourcesFromBundleProvider__) */


text:
/**
 * Main application routes
 */

'use strict';

var errors = require('./components/errors');
var path = require('path');

module.exports = function(app) {

/* Get version info and git info (via drone env) of API */
router.get('/version', function (req, res) {
   var commit = require('../git.json');
   var package = require('../package.json');

    if (!commit) {
        commit = {git: false};
    }

    commit.version = package.version;

    res.send(commit);
});

  // Insert routes below
  app.use('/api/polls', require('./api/poll'));
  app.use('/api/things', require('./api/thing'));
  app.use('/api/users', require('./api/user'));

  app.use('/auth', require('./auth'));

  // All undefined asset or api routes should return a 404
  app.route('/:url(api|auth|components|app|bower_components|assets)/*')
   .get(errors[404]);

  // All other routes should redirect to the index.html
  app.route('/*')
    .get(function(req, res) {
      res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
    });
};


text:
package set

// An unordered collection of unique elements which supports lookups, insertions, deletions,
// iteration, and common binary set operations.  It is not guaranteed to be thread-safe.
type Set interface {
	// Returns a new empty Set of the same type.
	New() Set

	// Returns a new Set that contains exactly the same elements as this set.
	Copy() Set

	// Returns the cardinality of this set.
	Len() int

	// Returns true if and only if this set contains v (according to Go equality rules).
	Contains(v interface{}) bool
	// Inserts v into this set.
	Add(v interface{})
	// Removes v from this set, if it is present.  Returns true if and only if v was present.
	Remove(v interface{}) bool

	// Executes f(v) for every element v in this set.  If f mutates this set, behavior is undefined.
	Do(f func(interface{}))
	// Executes f(v) once for every element v in the set, aborting if f ever returns false. If f
	// mutates this set, behavior is undefined.
	DoWhile(f func(interface{}) bool)
	// Returns a channel from which each element in the set can be read exactly once.  If this set
	// is mutated before the channel is emptied, the exact data read from the channel is undefined.
	Iter() <-chan interface{}

	// Adds every element in s into this set.
	Union(s Set)
	// Removes every element not in s from this set.
	Intersect(s Set)
	// Removes every element in s from this set.
	Subtract(s Set)
	// Removes all elements from the set.
	Init()
	// Returns true if and only if all elements in this set are elements in s.
	IsSubset(s Set) bool
	// Returns true if and only if all elements in s are elements in this set.
	IsSuperset(s Set) bool
	// Returns true if and only if this set and s contain exactly the same elements.
	IsEqual(s Set) bool
	// Removes all elements v from this set that satisfy f(v) == true.
	RemoveIf(f func(interface{}) bool)
}

// Returns a new set which is the union of s1 and s2.  s1 and s2 are unmodified.
func Union(s1 Set, s2 Set) Set {
	if s1 == nil {
		if s2 == nil {
			return nil
		}

		return s2.Copy()
	}
	s3 := s1.Copy()
	s3.Union(s2)
	return s3
}

// Returns a new set which is the intersect of s1 and s2.  s1 and s2 are
// unmodified.
func Intersect(s1 Set, s2 Set) Set {
	if s1 == nil {
		if s2 == nil {
			return nil
		}

		return s2.New()
	}
	s3 := s1.Copy()
	s3.Intersect(s2)
	return s3
}

// Returns a new set which is the difference between s1 and s2.  s1 and s2 are
// unmodified.
func Subtract(s1 Set, s2 Set) Set {
	if s1 == nil {
		if s2 == nil {
			return nil
		}

		return s2.New()
	}
	s3 := s1.Copy()
	s3.Subtract(s2)
	return s3
}

// Returns a new Set pre-populated with the given items
func NewSet(items ...interface{}) Set {
	res := setImpl{
		data: make(map[interface{}]struct{}),
	}
	for _, item := range items {
		res.Add(item)
	}
	return res
}

// Returns a new Set pre-populated with the given items
func NewKeyedSet(keyf func(interface{}) interface{}, items ...interface{}) Set {
	res := keyedSetImpl{
		data:    make(map[interface{}]interface{}),
		keyfunc: keyf,
	}
	for _, item := range items {
		res.Add(item)
	}
	return res
}

type setImpl struct {
	data map[interface{}]struct{}
}

func (s setImpl) Len() int {
	return len(s.data)
}

func (s setImpl) New() Set {
	return NewSet()
}

func (s setImpl) Copy() Set {
	return copySet(s)
}

func (s setImpl) Init() {
	s.data = make(map[interface{}]struct{})
}

func (s setImpl) Contains(v interface{}) bool {
	_, ok := s.data[v]
	return ok
}

func (s setImpl) Add(v interface{}) {
	s.data[v] = struct{}{}
}

func (s setImpl) Remove(v interface{}) bool {
	_, ok := s.data[v]
	if ok {
		delete(s.data, v)
	}
	return ok
}

func (s setImpl) Do(f func(interface{})) {
	for key := range s.data {
		f(key)
	}
}

func (s setImpl) DoWhile(f func(interface{}) bool) {
	for key := range s.data {
		if !f(key) {
			break
		}
	}
}

func (s setImpl) Iter() <-chan interface{} {
	iter := make(chan interface{})
	go func() {
		for key := range s.data {
			iter <- key
		}
		close(iter)
	}()
	return iter
}

func (s setImpl) Union(s2 Set) {
	union(s, s2)
}

func (s setImpl) Intersect(s2 Set) {
	var toRemove []interface{}
	for key := range s.data {
		if s2 == nil || !s2.Contains(key) {
			toRemove = append(toRemove, key)
		}
	}

	for _, key := range toRemove {
		s.Remove(key)
	}
}

func (s setImpl) Subtract(s2 Set) {
	subtract(s, s2)
}

func (s setImpl) IsSubset(s2 Set) (isSubset bool) {
	return subset(s, s2)
}

func (s setImpl) IsSuperset(s2 Set) bool {
	return superset(s, s2)
}

func (s setImpl) IsEqual(s2 Set) bool {
	return equal(s, s2)
}

func (s setImpl) RemoveIf(f func(interface{}) bool) {
	var toRemove []interface{}
	for item := range s.data {
		if f(item) {
			toRemove = append(toRemove, item)
		}
	}

	for _, item := range toRemove {
		s.Remove(item)
	}
}

// keyedSetImpl implementation below here

type keyedSetImpl struct {
	data    map[interface{}]interface{}
	keyfunc (func(interface{}) interface{})
}

func (s keyedSetImpl) Len() int {
	return len(s.data)
}

func (s keyedSetImpl) New() Set {
	return NewKeyedSet(s.keyfunc)
}

func (s keyedSetImpl) Copy() Set {
	return copySet(s)
}

func (s keyedSetImpl) Init() {
	s.data = make(map[interface{}]interface{})
}

func (s keyedSetImpl) Contains(v interface{}) bool {
	_, ok := s.data[s.keyfunc(v)]
	return ok
}

func (s keyedSetImpl) Add(v interface{}) {
	s.data[s.keyfunc(v)] = v
}

func (s keyedSetImpl) Remove(v interface{}) bool {
	key := s.keyfunc(v)
	_, ok := s.data[key]
	if ok {
		delete(s.data, key)
	}
	return ok

}

func (s keyedSetImpl) Do(f func(interface{})) {
	for _, v := range s.data {
		f(v)
	}
}

func (s keyedSetImpl) DoWhile(f func(interface{}) bool) {
	for _, v := range s.data {
		if !f(v) {
			break
		}
	}
}

func (s keyedSetImpl) Iter() <-chan interface{} {
	iter := make(chan interface{})
	go func() {
		for _, v := range s.data {
			iter <- v
		}
		close(iter)
	}()
	return iter
}

func (s keyedSetImpl) Union(s2 Set) {
	union(s, s2)
}

func (s keyedSetImpl) Intersect(s2 Set) {
	var toRemove []interface{}
	for _, v := range s.data {
		if s2 == nil || !s2.Contains(v) {
			toRemove = append(toRemove, v)
		}
	}

	for _, v := range toRemove {
		s.Remove(v)
	}
}

func (s keyedSetImpl) Subtract(s2 Set) {
	subtract(s, s2)
}

func (s keyedSetImpl) IsSubset(s2 Set) (isSubset bool) {
	return subset(s, s2)
}

func (s keyedSetImpl) IsSuperset(s2 Set) bool {
	return superset(s, s2)
}

func (s keyedSetImpl) IsEqual(s2 Set) bool {
	return equal(s, s2)
}

func (s keyedSetImpl) RemoveIf(f func(interface{}) bool) {
	var toRemove []interface{}
	for _, item := range s.data {
		if f(item) {
			toRemove = append(toRemove, item)
		}
	}

	for _, item := range toRemove {
		s.Remove(item)
	}
}

// Common functions between the two implementations, since go
// does not allow for any inheritance.

func equal(s Set, s2 Set) bool {
	if s.Len() != s2.Len() {
		return false
	}

	return s.IsSubset(s2)
}

func superset(s Set, s2 Set) bool {
	return s2.IsSubset(s)
}

func subset(s Set, s2 Set) (isSubset bool) {
	isSubset = true
	s.DoWhile(func(item interface{}) bool {
		if !s2.Contains(item) {
			isSubset = false
		}
		return isSubset
	})
	return
}

func subtract(s Set, s2 Set) {
	if s2 == nil {
		return
	}
	s2.Do(func(item interface{}) { s.Remove(item) })
}

func union(s Set, s2 Set) {
	if s2 == nil {
		return
	}
	s2.Do(func(item interface{}) { s.Add(item) })
}

func copySet(s Set) Set {
	res := s.New()
	res.Union(s)
	return res
}