text:
echo "Bootstrapping Application Environmental"
echo "[BOOTSTRAP] Dumping Docker Environment:"
echo "-------------------------------------------------"
env

echo "[BOOTSTRAP] Generating config file"
echo "-------------------------------------------------"
cp /code/config/broker.yml.example /config/config.yml

echo "[BOOTSTRAP] Starting broker.py"
echo "-------------------------------------------------"
python /code/broker.py /config/config.yml

redpajama_set_name: RedPajamaGithub


text:
import pytest
from pytest_notebook.nb_regression import NBRegressionFixture

from histogrammar.resources import notebook

@pytest.fixture(scope="module")
def nb_tester():
    """Test notebooks using pytest-notebook"""
    nb_regression = NBRegressionFixture(
        diff_ignore=(
            "/metadata/language_info",
            "/cells/*/execution_count",
            "/cells/*/outputs/*",
        ),
        exec_timeout=1800,
    )
    return nb_regression

def test_notebook_basic(nb_tester):
    nb_tester.check(notebook("histogrammar_tutorial_basic.ipynb"))

def test_notebook_advanced(nb_tester):
    nb_tester.check(notebook("histogrammar_tutorial_advanced.ipynb"))

def test_notebook_exercises(nb_tester):
    nb_tester.check(notebook("histogrammar_tutorial_exercises.ipynb"))


text:
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.FilterQuery;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;

import backtype.storm.Config;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.utils.Utils;

@SuppressWarnings("serial")
public class TestGeoLocation {

    SpoutOutputCollector _collector;
    LinkedBlockingQueue<Status> queue = null;
    TwitterStream _twitterStream;
    String custKey = "D90JVJkIzMYBSU4K1zCvP2FXE";
    String custSecret = "r1GWAmHsTtwuFzQFOdGj0Ad7jBq2CynlwRyNiIEvbQpfzOOsTG";
    String accessKey = "612666274-cQQ4ICpXco0pSQU3Zl7IprEuF9jhgaSE2gXhQzkc";
    String accessSecret = "wFytlnD0xolGvOrqGGCm80ZiKcnsNsj3XwnbEbtO1ukz4";
    String[] keyWords;
    Logger log = LoggerFactory.getLogger(TestGeoLocation.class);

    public void open(Map conf, TopologyContext context,
                     SpoutOutputCollector collector) {
        queue = new LinkedBlockingQueue<Status>(1000);
        _collector = collector;

        StatusListener listener = new StatusListener() {

            public void onStatus(Status status) {

                if( status.getText().length() != 0 && status.getLang().equals("en")) {
                    queue.offer(status);
                    log.info("Getting Lattitude: "+(status.getGeoLocation().getLatitude()));
                }
            }

            public void onDeletionNotice(StatusDeletionNotice sdn) {
            }

            public void onTrackLimitationNotice(int i) {
            }

            public void onScrubGeo(long l, long l1) {
            }

            public void onException(Exception ex) {
            }

            public void onStallWarning(StallWarning arg0) {
                // TODO Auto-generated method stub

            }

        };

        TwitterStream twitterStream = new TwitterStreamFactory(
                new ConfigurationBuilder().setJSONStoreEnabled(true).build())
                .getInstance();

        twitterStream.addListener(listener);
        twitterStream.setOAuthConsumer(custKey, custSecret);
        AccessToken token = new AccessToken(accessKey, accessSecret);
        twitterStream.setOAuthAccessToken(token);

        if (keyWords.length == 0) {

            twitterStream.sample();
        }

        else {

            FilterQuery query = new FilterQuery().track(keyWords);
            twitterStream.filter(query);
        }

    }

    public void nextTuple() {
        Status ret = queue.poll();
        if (ret == null) {
            Utils.sleep(50);
        } else {
            _collector.emit(new Values(ret));

        }
    }

    public void close() {
        _twitterStream.shutdown();
    }

    public Map<String, Object> getComponentConfiguration() {
        Config ret = new Config();
        ret.setMaxTaskParallelism(1);
        return ret;
    }

    public void ack(Object id) {

    }

    public void fail(Object id) {

    }

    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("tweet"));
    }

}


text:
require 'json'
require 'faraday'

module Flowbot
  module Flowdock
    def self.send_message(text, flow_token)
      return unless text

      body = {
        "content" => text,
        "external_user_name" => "Flowbot"
      }

      conn = Faraday.new(:url => "https://api.flowdock.com")
      conn.post do |req|
        req.url "/v1/messages/chat/#{flow_token}"
        req.headers['Content-Type'] = 'application/json'
        req.body = body.to_json
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using HtmlAgilityPack;

namespace SpecByExample.T4.Wizard
{
    /// <summary>
    /// Wizard Tab that lets you specify how to generate code for a table.
    /// The table you select will be wrapped in an adapter and it will try to create an entity for the rows in it so you can easily use them in tests.
    /// </summary>
    public partial class TableInfo : UserControl, IWizardPage
    {
        public TableInfo()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.Dock = DockStyle.Fill;
        }

        /// <summary>
        /// Document to work on.
        /// </summary>
        private HtmlAgilityPack.HtmlDocument HtmlDocumentCache
        {
            get;
            set;
        }

        /// <summary>
        /// Cache of the controls in page PageUrl.
        /// </summary>
        private List<HtmlControlInfo> ControlInfoCache
        {
            get;
            set;
        }

        /// <summary>
        ///  List of all table nodes (value) and their names (key)
        /// </summary>
        private SortedDictionary<string, HtmlNode> TableCache
        {
            get;
            set;
        }

        /// <summary>
        /// Most recently loaded page.
        /// </summary>
        private string PageUrl
        {
            get;
            set;
        }

        #region Implement IWizardPage

        public WizardConfiguration WizardConfig
        {
            get;
            set;
        }

        public void LoadState(PageAdapterWizardViewModel container)
        {
            bool isTablePage = (container.PageInfo.TypeOfPage == PageTemplatesEnum.TablePage);
            PageUrl = container.PageInfo.Url;
            ToggleTableFields(isTablePage);
        }

        public void SaveState(PageAdapterWizardViewModel container)
        {
            if (chkCreateTableWrapper.Checked)
            {
                container.PageInfo.TypeOfPage = PageTemplatesEnum.TablePage;
                container.PageInfo.TableInfo = ComposeTableInfo();
            }
            else
                container.PageInfo.TypeOfPage = PageTemplatesEnum.GenericPage;
        }

        public bool ValidateInput()
        {
            // Ignore disabled controls
            return ValidateChildren();
        }

        #endregion

        #region Handle Events

        /// <summary>
        /// When selecting a table element: load its columns into the grid.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbTables_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Fill the grid with the names of the columns of the HTML page.
            // Use the th elements or if not available, the values from the first row.
            webTableColumnsDatasetBindingSource.DataSource = ComposeGridData(ControlInfoCache);
        }

        private void chkCreateTableWrapper_CheckedChanged(object sender, EventArgs e)
        {
            ToggleTableFields(chkCreateTableWrapper.Checked);
        }

        private void txtEntityName_Validating(object sender, CancelEventArgs e)
        {
            if (txtEntityName.Enabled && txtEntityName.Text.Trim() == String.Empty)
            {
                errorProvider1.SetError(txtEntityName, "Entity name is required");
                e.Cancel = true;
            }
            else
                errorProvider1.SetError(txtEntityName, "");
        }

        private void cmbTables_Validating(object sender, CancelEventArgs e)
        {
            if (cmbTables.Enabled && cmbTables.Text.Trim() == String.Empty)
            {
                errorProvider1.SetError(cmbTables, "Table name is required");
                e.Cancel = true;
            }
            else
                errorProvider1.SetError(cmbTables, "");
        }

        #endregion

        #region Private support methods

        /// <summary>
        /// Initialize the controls on this page
        /// </summary>
        private void InitializeListOfElements(List<HtmlControlInfo> controlInfo)
        {
            // Fill the list with all tables of this page
            var tables = controlInfo.Where(x => x.HtmlControlType == HtmlControlTypeEnum.Table);

            // Replace the list of tables with a new one
            TableCache = new SortedDictionary<string, HtmlNode>();
            foreach (var t in tables)
            {
                var node = HtmlDocumentCache.DocumentNode.SelectSingleNode(t.HtmlXPath);
                TableCache.Add(t.DisplayName, node);
            }
            cmbTables.DataSource = new BindingSource(TableCache,null);
            cmbTables.DisplayMember = "Key";
            cmbTables.ValueMember = "Value";
        }

        /// <summary>
        /// Compose a datatable to databind to the grid.
        /// </summary>
        /// <returns></returns>
        private DataTable ComposeGridData(List<HtmlControlInfo> controlInfo)
        {
            // Get the selected table
            var tableName = cmbTables.Text;
            if (TableCache.ContainsKey(tableName) == false)
                return null;

            DataTable data = new DataTable();
            data.Columns.Add("ColumnPosition",typeof(int));
            data.Columns.Add("ColumnTitle", typeof(string));
            data.Columns.Add("CodeFieldname", typeof(string));
            data.Columns.Add("CodeDatatype", typeof(string));
            data.Columns.Add("IncludeField", typeof(bool));
            var tableNode = TableCache[tableName];

            // Get the headers from the table
            string[] headerTitles = GetHeaderTitles(tableNode);
            int pos = 1;
            foreach (var header in headerTitles)
            {
                data.Rows.Add(new object[] { pos++, header, header, "String", true });
            }
            return data;
        }

        /// <summary>
        /// Get the text from the TH tags or the first row of data
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        private string[] GetHeaderTitles(HtmlNode table)
        {
            // Get the body of the table
            var tbody = table.SelectSingleNode("tbody");
            var rowRoot = tbody ?? table;
            var rows = rowRoot.SelectNodes("tr");

            List<string> columnNames = new List<string>();
            HtmlNode firstRow = null;
            if (rows.Count > 0)
            {
                // Get the first row
                firstRow = rows.First();
                if (firstRow != null)
                {
                    // Assumption: if we find one th in this row, we assume all column headers will be
                    // constructed from TH elements. Otherwise, we assume each TD contains a columnname.
                    var headerCells = firstRow.SelectNodes("th");
                    if (headerCells != null)
                    {
                        foreach (var th in headerCells)
                            columnNames.Add(th.InnerText);
                    }
                    else
                    {
                        headerCells = firstRow.SelectNodes("td");
                        if (headerCells != null)
                        {
                            foreach (var th in headerCells)
                                columnNames.Add(th.InnerText);
                        }

                    }
                }
            }
            return columnNames.ToArray();
        }

        /// <summary>
        /// Collect the data we need to pass back.
        /// </summary>
        /// <returns>Information to use for code generation: which elements must be generated for this table?</returns>
        private SeleniumTableInfo ComposeTableInfo()
        {
            // Create a container for the settings of this table.
            var tableInfo = new SeleniumTableInfo();
            tableInfo.EntityName = txtEntityName.Text;
            tableInfo.TableName = cmbTables.Text;

            // Use the table to fill the entity
            DataTable table = webTableColumnsDatasetBindingSource.DataSource as DataTable;
            if (table != null)
            {
                foreach (DataRow row in table.Rows)
                {
                    // Skip excluded columns
                    bool isIncluded = (bool)row["IncludeField"];
                    if (isIncluded)
                    {
                        int position = (int)row["ColumnPosition"];
                        string title = (string)row["ColumnTitle"];
                        string fieldname = (string)row["CodeFieldname"];
                        string datatype = (string)row["CodeDatatype"];
                        tableInfo.Columns.Add(new TableColumnDef(position, title, fieldname, datatype));
                    }
                }
            }
            return tableInfo;
        }

        private delegate void CursorUpdateDelegate(Cursor cursor);
        private delegate void ControlUpdateDelegate(List<HtmlControlInfo> controlInfo);

        private void SetCursor(Cursor cursor)
        {
            Cursor = cursor;
        }

        private void LoadTableInfoWithTask(string url)
        {
            var loadPageInfoTask = new Task(() =>
            {
                try
                {
                    Invoke(new CursorUpdateDelegate(SetCursor), Cursors.WaitCursor);
                    if (PageUrl != url || HtmlDocumentCache == null || ControlInfoCache == null)
                    {
                        // Get the HTML and parse its objects
                        var loader = new HtmlLoader(WizardConfig.RegisteredControlTypes);
                        HtmlDocumentCache = loader.LoadDocumentFromUrl(url);
                        ControlInfoCache = loader.GetHtmlControls(HtmlDocumentCache, HtmlLoader.DefaultOptions);
                        PageUrl = url;
                    }

                    Invoke(new ControlUpdateDelegate(InitializeListOfElements), ControlInfoCache);
                }
                finally
                {
                    Invoke(new CursorUpdateDelegate(SetCursor), Cursors.Default);
                }
            });
            loadPageInfoTask.Start();
        }

        /// <summary>
        /// Plain variant without a task.
        /// </summary>
        /// <param name="url"></param>
        private void LoadTableInfo(string url)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                if (PageUrl != url || HtmlDocumentCache == null || ControlInfoCache == null)
                {
                    // Get the HTML and parse its objects
                    var loader = new HtmlLoader(WizardConfig.RegisteredControlTypes);
                    HtmlDocumentCache = loader.LoadDocumentFromUrl(url);
                    ControlInfoCache = loader.GetHtmlControls(HtmlDocumentCache, HtmlLoader.DefaultOptions);
                    PageUrl = url;
                }

                InitializeListOfElements(ControlInfoCache);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// Enable/Disable fields for the table info
        /// </summary>
        private void ToggleTableFields(bool enable)
        {
            pnlTableInfo.Enabled = enable;
            errorProvider1.Clear();

            // Load cache with info of this page
            if (enable)
            {
                LoadTableInfo(PageUrl);
//                LoadTableInfoWithTask(PageUrl);
            }
            else
            {
                // Reset the fields
                cmbTables.DataSource = null;
                txtEntityName.Clear();
                webTableColumnsDatasetBindingSource.DataSource = null;
            }
        }

        #endregion
    }
}


text:
package vgtest.testview.view;

import vgtest.testview.TestFlags;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.widget.Button;
import android.widget.FrameLayout;

//! 测试双视图布局的测试视图类
public class TestDoubleViews extends FrameLayout {

    public TestDoubleViews(Context context) {
        super(context);

        final int flags = ((Activity) context).getIntent().getExtras().getInt("flags");
        final LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);

        if ((flags & TestFlags.MAIN_CACHEDVIEW) != 0) {
            useGraphViewCached(context, params, flags);
        } else if ((flags & TestFlags.MAIN_STDVIEW) == 0) {
            useStdViewCached(context, params, flags);
        } else if ((flags & TestFlags.MAIN_SFVIEW) == 0) {
            useSfViewCached(context, params, flags);
        }

        final Button midview = new Button(context);
        midview.setText("This is a button in the FrameLayout.");
        midview.setBackgroundColor(Color.GRAY);
        addView(midview, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    }

    // 主视图使用GraphViewCached
    private void useGraphViewCached(Context context, LayoutParams params, int flags) {
        final GraphViewCached view = new GraphViewCached(context);
        addView(view, params);

        // 动态视图使用普通View
        if ((flags & TestFlags.DYN_STDVIEW) != 0) {
            final DynDrawStdView dynview = new DynDrawStdView(context);
            view.setDynDrawView(dynview);
            addView(dynview, params);
        } else if ((flags & TestFlags.DYN_SFVIEW) != 0) {
            // 动态视图使用SurfaceView
            final DynDrawSfView dynview = new DynDrawSfView(context);
            view.setDynDrawView(dynview);
            addView(dynview, params);
        }
    }

    // 主视图使用普通View
    private void useStdViewCached(Context context, LayoutParams params, int flags) {
        final GraphView view = new GraphView(context);
        addView(view, params);

        if ((flags & TestFlags.DYN_STDVIEW) != 0) {
            final DynDrawStdView dynview = new DynDrawStdView(context);
            view.setDynDrawView(dynview);
            addView(dynview, params);
        } else if ((flags & TestFlags.DYN_SFVIEW) != 0) {
            final DynDrawSfView dynview = new DynDrawSfView(context);
            view.setDynDrawView(dynview);
            addView(dynview, params);
        }
    }

    // 主视图使用SurfaceView
    private void useSfViewCached(Context context, LayoutParams params, int flags) {
        final GraphSfView view = new GraphSfView(context);

        if ((flags & TestFlags.MODEL_SURFACE) == 0) {
            view.setBackgroundColor(Color.TRANSPARENT);
        }
        addView(view, params);

        if ((flags & TestFlags.DYN_STDVIEW) != 0) {
            final DynDrawStdView dynview = new DynDrawStdView(context);
            view.setDynDrawView(dynview);
            addView(dynview, params);
        } else if ((flags & TestFlags.DYN_SFVIEW) != 0) {
            final DynDrawSfView dynview = new DynDrawSfView(context);
            view.setDynDrawView(dynview);
            addView(dynview, params);
        }
    }
}


text:
package com.github.dockerjava.core;

import org.apache.commons.lang.SerializationUtils;
import org.testng.annotations.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

/**
 * @author Kanstantsin Shautsou
 */
public class RemoteApiVersionTest {
    @Test
    public void testSerial() {
        SerializationUtils.serialize(RemoteApiVersion.unknown());
        final RemoteApiVersion remoteApiVersion = RemoteApiVersion.create(1, 20);

        final byte[] serialized = SerializationUtils.serialize(remoteApiVersion);
        RemoteApiVersion deserialized = (RemoteApiVersion) SerializationUtils.deserialize(serialized);

        assertThat("Deserialized object mush match source object", deserialized, equalTo(remoteApiVersion));
    }
}


text:
import os
import pickle
from unittest import SkipTest

import numpy as np
from holoviews import Store, Histogram, Image, Curve, DynamicMap, opts
from holoviews.core.options import (
    OptionError, Cycle, Options, OptionTree, StoreOptions, options_policy
)
from holoviews.element.comparison import ComparisonTestCase
from holoviews import plotting              # noqa Register backends

Options.skip_invalid = False

try:
    # Needed a backend to register backend and options
    from holoviews.plotting import mpl # noqa
except:
    pass

try:
    # Needed to register backend  and options
    from holoviews.plotting import bokeh # noqa
except:
    pass

class TestOptions(ComparisonTestCase):

    def setUp(self):
        self.original_option_groups = Options._option_groups
        Options._option_groups = ['test']
        super(TestOptions, self).setUp()

    def tearDown(self):
        Options._option_groups = self.original_option_groups
        super(TestOptions, self).tearDown()

    def test_options_init(self):
        Options('test')

    def test_options_valid_keywords1(self):
        opts = Options('test', allowed_keywords=['kw1'], kw1='value')
        self.assertEquals(opts.kwargs, {'kw1':'value'})

    def test_options_valid_keywords2(self):
        opts = Options('test', allowed_keywords=['kw1', 'kw2'], kw1='value')
        self.assertEquals(opts.kwargs, {'kw1':'value'})

    def test_options_valid_keywords3(self):
        opts = Options('test', allowed_keywords=['kw1', 'kw2'], kw1='value1', kw2='value2')
        self.assertEquals(opts.kwargs, {'kw1':'value1', 'kw2':'value2'})

    def test_options_any_keywords3(self):
        opts = Options('test', kw1='value1', kw2='value3')
        self.assertEquals(opts.kwargs, {'kw1':'value1', 'kw2':'value3'})

    def test_options_invalid_keywords1(self):
        try:
            Options('test', allowed_keywords=['kw1'], kw='value')
        except OptionError as e:
            self.assertEqual(str(e), "Invalid option 'kw', valid options are: ['kw1']")

    def test_options_invalid_keywords2(self):
        try:
            Options('test', allowed_keywords=['kw2'], kw2='value', kw3='value')
        except OptionError as e:
            self.assertEqual(str(e), "Invalid option 'kw3', valid options are: ['kw2']")

    def test_options_invalid_keywords_skip1(self):
        with options_policy(skip_invalid=True, warn_on_skip=False):
            opts = Options('test', allowed_keywords=['kw1'], kw='value')
        self.assertEqual(opts.kwargs, {})

    def test_options_invalid_keywords_skip2(self):
        with options_policy(skip_invalid=True, warn_on_skip=False):
            opts = Options('test', allowed_keywords=['kw1'], kw1='value', kw2='val')
        self.assertEqual(opts.kwargs, {'kw1':'value'})

    def test_options_record_invalid(self):
        StoreOptions.start_recording_skipped()
        with options_policy(skip_invalid=True, warn_on_skip=False):
            Options('test', allowed_keywords=['kw1'], kw1='value', kw2='val')
        errors = StoreOptions.stop_recording_skipped()
        self.assertEqual(len(errors),1)
        self.assertEqual(errors[0].invalid_keyword,'kw2')

    def test_options_get_options(self):
        opts = Options('test', allowed_keywords=['kw2', 'kw3'],
                       kw2='value', kw3='value').options
        self.assertEqual(opts, dict(kw2='value', kw3='value'))

    def test_options_get_options_cyclic1(self):
        opts = Options('test', allowed_keywords=['kw2', 'kw3'],
                       kw2='value', kw3='value')
        for i in range(16):
            self.assertEqual(opts[i], dict(kw2='value', kw3='value'))

    def test_options_keys(self):
        opts = Options('test', allowed_keywords=['kw3', 'kw2'],
                       kw2='value', kw3='value')
        self.assertEqual(opts.keys(), ['kw2', 'kw3'])

    def test_options_inherit(self):
        original_kws = dict(kw2='value', kw3='value')
        opts = Options('test', **original_kws)
        new_kws = dict(kw4='val4', kw5='val5')
        new_opts = opts(**new_kws)

        self.assertEqual(new_opts.options, dict(original_kws, **new_kws))

    def test_options_inherit_invalid_keywords(self):
        original_kws = dict(kw2='value', kw3='value')
        opts = Options('test', allowed_keywords=['kw3', 'kw2'], **original_kws)
        new_kws = dict(kw4='val4', kw5='val5')
        try:
            opts(**new_kws)
        except OptionError as e:
            self.assertEqual(str(e), "Invalid option 'kw4', valid options are: ['kw2', 'kw3']")

class TestCycle(ComparisonTestCase):

    def setUp(self):
        self.original_option_groups = Options._option_groups
        Options._option_groups = ['test']
        super(TestCycle, self).setUp()

    def tearDown(self):
        Options._option_groups = self.original_option_groups
        super(TestCycle, self).tearDown()

    def test_cycle_init(self):
        Cycle(values=['a', 'b', 'c'])
        Cycle(values=[1, 2, 3])

    def test_cycle_expansion(self):
        cycle1 = Cycle(values=['a', 'b', 'c'])
        cycle2 = Cycle(values=[1, 2, 3])

        opts = Options('test', one=cycle1, two=cycle2)
        self.assertEqual(opts[0], {'one': 'a', 'two': 1})
        self.assertEqual(opts[1], {'one': 'b', 'two': 2})
        self.assertEqual(opts[2], {'one': 'c', 'two': 3})
        self.assertEqual(opts[3], {'one': 'a', 'two': 1})
        self.assertEqual(opts[4], {'one': 'b', 'two': 2})
        self.assertEqual(opts[5], {'one': 'c', 'two': 3})

    def test_cycle_expansion_unequal(self):
        cycle1 = Cycle(values=['a', 'b', 'c', 'd'])
        cycle2 = Cycle(values=[1, 2, 3])

        opts = Options('test', one=cycle1, two=cycle2)
        self.assertEqual(opts[0], {'one': 'a', 'two': 1})
        self.assertEqual(opts[1], {'one': 'b', 'two': 2})
        self.assertEqual(opts[2], {'one': 'c', 'two': 3})
        self.assertEqual(opts[3], {'one': 'd', 'two': 1})
        self.assertEqual(opts[4], {'one': 'a', 'two': 2})
        self.assertEqual(opts[5], {'one': 'b', 'two': 3})

    def test_cycle_slice(self):
        cycle1 = Cycle(values=['a', 'b', 'c'])[2]
        cycle2 = Cycle(values=[1, 2, 3])

        opts = Options('test', one=cycle1, two=cycle2)
        self.assertEqual(opts[0], {'one': 'a', 'two': 1})
        self.assertEqual(opts[1], {'one': 'b', 'two': 2})
        self.assertEqual(opts[2], {'one': 'a', 'two': 3})
        self.assertEqual(opts[3], {'one': 'b', 'two': 1})

    def test_cyclic_property_true(self):
        cycle1 = Cycle(values=['a', 'b', 'c'])
        opts = Options('test', one=cycle1, two='two')
        self.assertEqual(opts.cyclic, True)

    def test_cyclic_property_false(self):
        opts = Options('test', one='one', two='two')
        self.assertEqual(opts.cyclic, False)

    def test_options_property_disabled(self):
        cycle1 = Cycle(values=['a', 'b', 'c'])
        opts = Options('test', one=cycle1)
        try:
            opts.options
        except Exception as e:
            self.assertEqual(str(e), "The options property may only be used with non-cyclic Options.")

class TestOptionTree(ComparisonTestCase):

    def setUp(self):
        if 'matplotlib' not in Store.renderers:
            raise SkipTest('Matplotlib backend not available.')
        super(TestOptionTree, self).setUp()
        self.original_option_groups = Options._option_groups[:]
        Options._option_groups = ['group1', 'group2']

    def tearDown(self):
        Options._option_groups = self.original_option_groups
        super(TestOptionTree, self).tearDown()

    def test_optiontree_init_1(self):
        OptionTree(groups=['group1', 'group2'])

    def test_optiontree_init_2(self):
        OptionTree(groups=['group1', 'group2'])

    def test_optiontree_setter_getter(self):
        options = OptionTree(groups=['group1', 'group2'])
        opts = Options('group1', kw1='value')
        options.MyType = opts
        self.assertEqual(options.MyType['group1'], opts)
        self.assertEqual(options.MyType['group1'].options, {'kw1':'value'})

    def test_optiontree_dict_setter_getter(self):
        options = OptionTree(groups=['group1', 'group2'])

        opts1 = Options(kw1='value1')
        opts2 = Options(kw2='value2')
        options.MyType = {'group1':opts1, 'group2':opts2}

        self.assertEqual(options.MyType['group1'], opts1)
        self.assertEqual(options.MyType['group1'].options, {'kw1':'value1'})

        self.assertEqual(options.MyType['group2'], opts2)
        self.assertEqual(options.MyType['group2'].options, {'kw2':'value2'})

    def test_optiontree_inheritance(self):
        if 'matplotlib' not in Store.renderers:
            raise SkipTest("General to specific option test requires matplotlib")

        options = OptionTree(groups=['group1', 'group2'])

        opts1 = Options(kw1='value1')
        opts2 = Options(kw2='value2')
        options.MyType = {'group1':opts1, 'group2':opts2}

        opts3 = Options(kw3='value3')
        opts4 = Options(kw4='value4')
        options.MyType.Child = {'group1':opts3, 'group2':opts4}

        self.assertEqual(options.MyType.Child.options('group1').kwargs,
                         {'kw1':'value1', 'kw3':'value3'})

        self.assertEqual(options.MyType.Child.options('group2').kwargs,
                         {'kw2':'value2', 'kw4':'value4'})

    def test_optiontree_inheritance_flipped(self):
        """
        Tests for ordering problems manifested in issue #93
        """
        if 'matplotlib' not in Store.renderers:
            raise SkipTest("General to specific option test requires matplotlib")

        options = OptionTree(groups=['group1', 'group2'])

        opts3 = Options(kw3='value3')
        opts4 = Options(kw4='value4')
        options.MyType.Child = {'group1':opts3, 'group2':opts4}

        opts1 = Options(kw1='value1')
        opts2 = Options(kw2='value2')
        options.MyType = {'group1':opts1, 'group2':opts2}

        self.assertEqual(options.MyType.Child.options('group1').kwargs,
                         {'kw1':'value1', 'kw3':'value3'})

        self.assertEqual(options.MyType.Child.options('group2').kwargs,
                         {'kw2':'value2', 'kw4':'value4'})

class TestStoreInheritanceDynamic(ComparisonTestCase):
    """
    Tests to prevent regression after fix in PR #646
    """

    def setUp(self):
        if 'matplotlib' not in Store.renderers:
            raise SkipTest('Matplotlib backend not available.')
        self.store_copy = OptionTree(sorted(Store.options().items()),
                                     groups=Options._option_groups)
        self.backend = 'matplotlib'
        Store.current_backend = self.backend
        super(TestStoreInheritanceDynamic, self).setUp()

    def tearDown(self):
        Store.options(val=self.store_copy)
        Store._custom_options = {k:{} for k in Store._custom_options.keys()}
        super(TestStoreInheritanceDynamic, self).tearDown()

    def initialize_option_tree(self):
        Store.options(val=OptionTree(groups=['plot', 'style']))
        options = Store.options()
        options.Image = Options('style', cmap='hot', interpolation='nearest')
        return options

    def test_merge_keywords(self):
        options = self.initialize_option_tree()
        options.Image = Options('style', clims=(0, 0.5))

        expected = {'clims': (0, 0.5), 'cmap': 'hot', 'interpolation': 'nearest'}
        direct_kws = options.Image.groups['style'].kwargs
        inherited_kws = options.Image.options('style').kwargs
        self.assertEqual(direct_kws, expected)
        self.assertEqual(inherited_kws, expected)

    def test_merge_keywords_disabled(self):
        options = self.initialize_option_tree()
        options.Image = Options('style', clims=(0, 0.5), merge_keywords=False)

        expected = {'clims': (0, 0.5)}
        direct_kws = options.Image.groups['style'].kwargs
        inherited_kws = options.Image.options('style').kwargs
        self.assertEqual(direct_kws, expected)
        self.assertEqual(inherited_kws, expected)

    def test_specification_general_to_specific_group(self):
        """
        Test order of specification starting with general and moving
        to specific
        """
        if 'matplotlib' not in Store.renderers:
            raise SkipTest("General to specific option test requires matplotlib")

        options = self.initialize_option_tree()

        obj = Image(np.random.rand(10,10), group='SomeGroup')

        options.Image = Options('style', cmap='viridis')
        options.Image.SomeGroup = Options('style', alpha=0.2)

        expected = {'alpha': 0.2, 'cmap': 'viridis', 'interpolation': 'nearest'}
        lookup = Store.lookup_options('matplotlib', obj, 'style')

        self.assertEqual(lookup.kwargs, expected)
        # Check the tree is structured as expected
        node1 = options.Image.groups['style']
        node2 = options.Image.SomeGroup.groups['style']

        self.assertEqual(node1.kwargs, {'cmap': 'viridis', 'interpolation': 'nearest'})
        self.assertEqual(node2.kwargs, {'alpha': 0.2})

    def test_specification_general_to_specific_group_and_label(self):
        """
        Test order of specification starting with general and moving
        to specific
        """
        if 'matplotlib' not in Store.renderers:
            raise SkipTest("General to specific option test requires matplotlib")

        options = self.initialize_option_tree()

        obj = Image(np.random.rand(10,10), group='SomeGroup', label='SomeLabel')

        options.Image = Options('style', cmap='viridis')
        options.Image.SomeGroup.SomeLabel = Options('style', alpha=0.2)

        expected = {'alpha': 0.2, 'cmap': 'viridis', 'interpolation': 'nearest'}
        lookup = Store.lookup_options('matplotlib', obj, 'style')

        self.assertEqual(lookup.kwargs, expected)
        # Check the tree is structured as expected
        node1 = options.Image.groups['style']
        node2 = options.Image.SomeGroup.SomeLabel.groups['style']

        self.assertEqual(node1.kwargs, {'cmap': 'viridis', 'interpolation': 'nearest'})
        self.assertEqual(node2.kwargs, {'alpha': 0.2})

    def test_specification_specific_to_general_group(self):
        """
        Test order of specification starting with a specific option and
        then specifying a general one
        """
        if 'matplotlib' not in Store.renderers:
            raise SkipTest("General to specific option test requires matplotlib")

        options = self.initialize_option_tree()
        options.Image.SomeGroup = Options('style', alpha=0.2)

        obj = Image(np.random.rand(10,10), group='SomeGroup')
        options.Image = Options('style', cmap='viridis')

        expected = {'alpha': 0.2, 'cmap': 'viridis', 'interpolation': 'nearest'}
        lookup = Store.lookup_options('matplotlib', obj, 'style')

        self.assertEqual(lookup.kwargs, expected)
        # Check the tree is structured as expected
        node1 = options.Image.groups['style']
        node2 = options.Image.SomeGroup.groups['style']

        self.assertEqual(node1.kwargs, {'cmap': 'viridis', 'interpolation': 'nearest'})
        self.assertEqual(node2.kwargs, {'alpha': 0.2})

    def test_specification_specific_to_general_group_and_label(self):
        """
        Test order of specification starting with general and moving
        to specific
        """
        if 'matplotlib' not in Store.renderers:
            raise SkipTest("General to specific option test requires matplotlib")

        options = self.initialize_option_tree()
        options.Image.SomeGroup.SomeLabel = Options('style', alpha=0.2)
        obj = Image(np.random.rand(10,10), group='SomeGroup', label='SomeLabel')

        options.Image = Options('style', cmap='viridis')
        expected = {'alpha': 0.2, 'cmap': 'viridis', 'interpolation': 'nearest'}
        lookup = Store.lookup_options('matplotlib', obj, 'style')

        self.assertEqual(lookup.kwargs, expected)
        # Check the tree is structured as expected
        node1 = options.Image.groups['style']
        node2 = options.Image.SomeGroup.SomeLabel.groups['style']

        self.assertEqual(node1.kwargs, {'cmap': 'viridis', 'interpolation': 'nearest'})
        self.assertEqual(node2.kwargs, {'alpha': 0.2})

    def test_custom_opts_to_default_inheritance(self):
        """
        Checks customs inheritance backs off to default tree correctly
        using .opts.
        """
        options = self.initialize_option_tree()
        options.Image.A.B = Options('style', alpha=0.2)

        obj = Image(np.random.rand(10, 10), group='A', label='B')
        expected_obj =  {'alpha': 0.2, 'cmap': 'hot', 'interpolation': 'nearest'}
        obj_lookup = Store.lookup_options('matplotlib', obj, 'style')
        self.assertEqual(obj_lookup.kwargs, expected_obj)

        # Customize this particular object
        custom_obj = obj.opts(style=dict(clims=(0, 0.5)))
        expected_custom_obj =  dict(clims=(0,0.5), **expected_obj)
        custom_obj_lookup = Store.lookup_options('matplotlib', custom_obj, 'style')
        self.assertEqual(custom_obj_lookup.kwargs, expected_custom_obj)

    def test_custom_magic_to_default_inheritance(self):
        """
        Checks customs inheritance backs off to default tree correctly
        simulating the %%opts cell magic.
        """
        if 'matplotlib' not in Store.renderers:
            raise SkipTest("Custom magic inheritance test requires matplotlib")
        options = self.initialize_option_tree()
        options.Image.A.B = Options('style', alpha=0.2)

        obj = Image(np.random.rand(10, 10), group='A', label='B')

        # Before customizing...
        expected_obj =  {'alpha': 0.2, 'cmap': 'hot', 'interpolation': 'nearest'}
        obj_lookup = Store.lookup_options('matplotlib', obj, 'style')
        self.assertEqual(obj_lookup.kwargs, expected_obj)

        custom_tree = {0: OptionTree(groups=Options._option_groups,
                                     style={'Image' : dict(clims=(0, 0.5))})}
        Store._custom_options['matplotlib'] = custom_tree
        obj.id = 0 # Manually set the id to point to the tree above

        # Customize this particular object
        expected_custom_obj =  dict(clims=(0,0.5), **expected_obj)
        custom_obj_lookup = Store.lookup_options('matplotlib', obj, 'style')
        self.assertEqual(custom_obj_lookup.kwargs, expected_custom_obj)

class TestStoreInheritance(ComparisonTestCase):
    """
    Tests to prevent regression after fix in 71c1f3a that resolves
    issue #43
    """

    def setUp(self):
        if 'matplotlib' not in Store.renderers:
            raise SkipTest('Matplotlib backend not available.')
        self.store_copy = OptionTree(sorted(Store.options().items()),
                                     groups=Options._option_groups)
        self.backend = 'matplotlib'
        Store.current_backend = self.backend
        Store.options(val=OptionTree(groups=['plot', 'style']))

        options = Store.options()

        self.default_plot = dict(plot1='plot1', plot2='plot2')
        options.Histogram = Options('plot', **self.default_plot)

        self.default_style = dict(style1='style1', style2='style2')
        options.Histogram = Options('style', **self.default_style)

        data = [np.random.normal() for i in range(10000)]
        frequencies, edges = np.histogram(data, 20)
        self.hist = Histogram(frequencies, edges)
        super(TestStoreInheritance, self).setUp()

    def lookup_options(self, obj, group):
        return Store.lookup_options(self.backend, obj, group)

    def tearDown(self):
        Store.options(val=self.store_copy)
        Store._custom_options = {k:{} for k in Store._custom_options.keys()}
        super(TestStoreInheritance, self).tearDown()

    def test_original_style_options(self):
        self.assertEqual(self.lookup_options(self.hist, 'style').options,
                         self.default_style)

    def test_original_plot_options(self):
        self.assertEqual(self.lookup_options(self.hist, 'plot').options,
                         self.default_plot)

    def test_plot_inheritance_addition(self):
        "Adding an element"
        hist2 = self.hist.opts(plot={'plot3':'plot3'})
        self.assertEqual(self.lookup_options(hist2, 'plot').options,
                         dict(plot1='plot1', plot2='plot2', plot3='plot3'))
        # Check style works as expected
        self.assertEqual(self.lookup_options(hist2, 'style').options, self.default_style)

    def test_plot_inheritance_override(self):
        "Overriding an element"
        hist2 = self.hist.opts(plot={'plot1':'plot_child'})
        self.assertEqual(self.lookup_options(hist2, 'plot').options,
                         dict(plot1='plot_child', plot2='plot2'))
        # Check style works as expected
        self.assertEqual(self.lookup_options(hist2, 'style').options, self.default_style)

    def test_style_inheritance_addition(self):
        "Adding an element"
        hist2 = self.hist.opts(style={'style3':'style3'})
        self.assertEqual(self.lookup_options(hist2, 'style').options,
                         dict(style1='style1', style2='style2', style3='style3'))
        # Check plot options works as expected
        self.assertEqual(self.lookup_options(hist2, 'plot').options, self.default_plot)

    def test_style_inheritance_override(self):
        "Overriding an element"
        hist2 = self.hist.opts(style={'style1':'style_child'})
        self.assertEqual(self.lookup_options(hist2, 'style').options,
                         dict(style1='style_child', style2='style2'))
        # Check plot options works as expected
        self.assertEqual(self.lookup_options(hist2, 'plot').options, self.default_plot)

    def test_style_transfer(self):
        if 'matplotlib' not in Store.renderers:
            raise SkipTest("test_style_transfer requires matplotlib")

        hist = self.hist.opts(style={'style1':'style_child'})
        hist2 = self.hist.opts()
        opts = Store.lookup_options('matplotlib', hist2, 'style').kwargs
        self.assertEqual(opts, {'style1': 'style1', 'style2': 'style2'})
        Store.transfer_options(hist, hist2, 'matplotlib')
        opts = Store.lookup_options('matplotlib', hist2, 'style').kwargs
        self.assertEqual(opts, {'style1': 'style_child', 'style2': 'style2'})

class TestOptionsMethod(ComparisonTestCase):

    def setUp(self):
        if 'matplotlib' not in Store.renderers:
            raise SkipTest('Matplotlib backend not available.')
        self.store_copy = OptionTree(sorted(Store.options().items()),
                                     groups=Options._option_groups)
        self.backend = 'matplotlib'
        Store.set_current_backend(self.backend)
        super(TestOptionsMethod, self).setUp()

    def lookup_options(self, obj, group):
        return Store.lookup_options(self.backend, obj, group)

    def tearDown(self):
        Store.options(val=self.store_copy)
        Store._custom_options = {k:{} for k in Store._custom_options.keys()}
        super(TestOptionsMethod, self).tearDown()

    def test_plot_options_keywords(self):
        im = Image(np.random.rand(10,10))
        styled_im = im.options(interpolation='nearest', cmap='jet')
        self.assertEqual(self.lookup_options(im, 'plot').options, {})
        self.assertEqual(self.lookup_options(styled_im, 'style').options,
                         dict(cmap='jet', interpolation='nearest'))

    def test_plot_options_one_object(self):
        im = Image(np.random.rand(10,10))
        imopts = opts.Image(interpolation='nearest', cmap='jet')
        styled_im = im.options(imopts)
        self.assertEqual(self.lookup_options(im, 'plot').options, {})
        self.assertEqual(self.lookup_options(styled_im, 'style').options,
                         dict(cmap='jet', interpolation='nearest'))

    def test_plot_options_two_object(self):
        im = Image(np.random.rand(10,10))
        imopts1 = opts.Image(interpolation='nearest')
        imopts2 = opts.Image(cmap='hsv')
        styled_im = im.options(imopts1,imopts2)
        self.assertEqual(self.lookup_options(im, 'plot').options, {})
        self.assertEqual(self.lookup_options(styled_im, 'style').options,
                         dict(cmap='hsv', interpolation='nearest'))

    def test_plot_options_object_list(self):
        im = Image(np.random.rand(10,10))
        imopts1 = opts.Image(interpolation='nearest')
        imopts2 = opts.Image(cmap='summer')
        styled_im = im.options([imopts1,imopts2])
        self.assertEqual(self.lookup_options(im, 'plot').options, {})
        self.assertEqual(self.lookup_options(styled_im, 'style').options,
                         dict(cmap='summer', interpolation='nearest'))

class TestOptsMethod(ComparisonTestCase):

    def setUp(self):
        if 'matplotlib' not in Store.renderers:
            raise SkipTest('Matplotlib backend not available.')
        self.store_copy = OptionTree(sorted(Store.options().items()),
                                     groups=Options._option_groups)
        self.backend = 'matplotlib'
        Store.set_current_backend(self.backend)
        super(TestOptsMethod, self).setUp()

    def lookup_options(self, obj, group):
        return Store.lookup_options(self.backend, obj, group)

    def tearDown(self):
        Store.options(val=self.store_copy)
        Store._custom_options = {k:{} for k in Store._custom_options.keys()}
        super(TestOptsMethod, self).tearDown()

    def test_old_opts_clone_disabled(self):
        im = Image(np.random.rand(10,10))
        styled_im = im.opts(style=dict(interpolation='nearest', cmap='jet'), clone=False)

        self.assertEqual(self.lookup_options(im, 'plot').options, {})
        self.assertEqual(self.lookup_options(styled_im, 'plot').options, {})

        assert styled_im is im
        self.assertEqual(self.lookup_options(im, 'style').options,
                         {'cmap': 'jet', 'interpolation': 'nearest'})

    def test_old_opts_clone_enabled(self):
        im = Image(np.random.rand(10,10))
        styled_im = im.opts(style=dict(interpolation='nearest', cmap='jet'), clone=True)

        self.assertEqual(self.lookup_options(im, 'plot').options, {})
        self.assertEqual(self.lookup_options(styled_im, 'plot').options, {})

        assert styled_im is not im
        im_lookup = self.lookup_options(im, 'style').options
        self.assertEqual(im_lookup['cmap'] == 'jet', False)
        styled_im_lookup =  self.lookup_options(styled_im, 'style').options
        self.assertEqual(styled_im_lookup['cmap'] == 'jet', True)

    def test_simple_clone_disabled(self):
        im = Image(np.random.rand(10,10))
        styled_im = im.opts(interpolation='nearest', cmap='jet', clone=False)

        self.assertEqual(self.lookup_options(im, 'plot').options, {})
        self.assertEqual(self.lookup_options(styled_im, 'plot').options, {})

        assert styled_im is im
        self.assertEqual(self.lookup_options(im, 'style').options,
                         {'cmap': 'jet', 'interpolation': 'nearest'})

    def test_simple_opts_clone_enabled(self):
        im = Image(np.random.rand(10,10))
        styled_im = im.opts(interpolation='nearest', cmap='jet', clone=True)

        self.assertEqual(self.lookup_options(im, 'plot').options, {})
        self.assertEqual(self.lookup_options(styled_im, 'plot').options, {})

        assert styled_im is not im
        im_lookup = self.lookup_options(im, 'style').options
        self.assertEqual(im_lookup['cmap'] == 'jet', False)
        styled_im_lookup =  self.lookup_options(styled_im, 'style').options
        self.assertEqual(styled_im_lookup['cmap'] == 'jet', True)

    def test_opts_method_with_utility(self):
        im = Image(np.random.rand(10,10))
        imopts = opts.Image(cmap='Blues')
        styled_im = im.opts(imopts)

        assert styled_im is im
        self.assertEqual(self.lookup_options(im, 'style').options,
                         {'cmap': 'Blues', 'interpolation': 'nearest'})

    def test_opts_method_dynamicmap_grouped(self):
        dmap = DynamicMap(lambda X: Curve([1, 2, X]),
                          kdims=['X']).redim.range(X=(0, 3))
        retval = dmap.opts({'plot': dict(width=700)})
        assert retval is not dmap
        self.assertEqual(self.lookup_options(retval[0], 'plot').options,
                         {'width':700})

    def test_opts_clear(self):
        im = Image(np.random.rand(10,10))
        styled_im = im.opts(style=dict(cmap='jet', interpolation='nearest',
                                       option1='A', option2='B'), clone=False)
        self.assertEqual(self.lookup_options(im, 'style').options,
                         {'cmap': 'jet', 'interpolation': 'nearest',
                          'option1':'A', 'option2':'B'})
        assert styled_im is im
        cleared = im.opts.clear()
        assert cleared is im
        cleared_options = self.lookup_options(cleared, 'style').options
        self.assertEqual(not any(k in ['option1', 'option2']
                                 for k in cleared_options.keys()), True)

    def test_opts_clear_clone(self):
        im = Image(np.random.rand(10,10))
        styled_im = im.opts(style=dict(cmap='jet', interpolation='nearest',
                                       option1='A', option2='B'), clone=False)
        self.assertEqual(self.lookup_options(im, 'style').options,
                         {'cmap': 'jet', 'interpolation': 'nearest',
                          'option1':'A', 'option2':'B'})
        assert styled_im is im
        cleared = im.opts.clear(clone=True)
        assert cleared is not im
        self.assertEqual(self.lookup_options(im, 'style').options,
                         {'cmap': 'jet', 'interpolation': 'nearest',
                          'option1':'A', 'option2':'B'})
        cleared_options = self.lookup_options(cleared, 'style').options
        self.assertEqual(not any(k in ['option1', 'option2']
                                 for k in cleared_options.keys()), True)

class TestOptionTreeFind(ComparisonTestCase):

    def setUp(self):
        self.original_option_groups = Options._option_groups[:]
        Options._option_groups = ['group']
        options = OptionTree(groups=['group'])
        self.opts1 = Options('group', kw1='value1')
        self.opts2 = Options('group', kw2='value2')
        self.opts3 = Options('group', kw3='value3')
        self.opts4 = Options('group', kw4='value4')
        self.opts5 = Options('group', kw5='value5')
        self.opts6 = Options('group', kw6='value6')

        options.MyType = self.opts1
        options.XType = self.opts2
        options.MyType.Foo = self.opts3
        options.MyType.Bar = self.opts4
        options.XType.Foo = self.opts5
        options.XType.Bar = self.opts6

        self.options = options
        self.original_options = Store.options()
        Store.options(val = OptionTree(groups=['group']))

    def tearDown(self):
        Options._option_groups = self.original_option_groups
        Store.options(val=self.original_options)
        Store._custom_options = {k:{} for k in Store._custom_options.keys()}

    def test_optiontree_find1(self):
        self.assertEqual(self.options.find('MyType').options('group').options,
                         dict(kw1='value1'))

    def test_optiontree_find2(self):
        self.assertEqual(self.options.find('XType').options('group').options,
                         dict(kw2='value2'))

    def test_optiontree_find3(self):
        self.assertEqual(self.options.find('MyType.Foo').options('group').options,
                         dict(kw1='value1', kw3='value3'))

    def test_optiontree_find4(self):
        self.assertEqual(self.options.find('MyType.Bar').options('group').options,
                         dict(kw1='value1', kw4='value4'))

    def test_optiontree_find5(self):
        self.assertEqual(self.options.find('XType.Foo').options('group').options,
                         dict(kw2='value2', kw5='value5'))

    def test_optiontree_find6(self):
        self.assertEqual(self.options.find('XType.Bar').options('group').options,
                         dict(kw2='value2', kw6='value6'))

    def test_optiontree_find_mismatch1(self):
        self.assertEqual(self.options.find('MyType.Baz').options('group').options,
                         dict(kw1='value1'))

    def test_optiontree_find_mismatch2(self):
        self.assertEqual(self.options.find('XType.Baz').options('group').options,
                         dict(kw2='value2'))

    def test_optiontree_find_mismatch3(self):
        self.assertEqual(self.options.find('Baz').options('group').options, dict())

    def test_optiontree_find_mismatch4(self):
        self.assertEqual(self.options.find('Baz.Baz').options('group').options, dict())

class TestCrossBackendOptions(ComparisonTestCase):
    """
    Test the style system can style a single object across backends.
    """

    def setUp(self):
        if 'matplotlib' not in Store.renderers:
            raise SkipTest("Cross background tests assumes matplotlib is available")
        if 'bokeh' not in Store.renderers:
            raise SkipTest("Cross background tests assumes bokeh is available.")

        # Some tests require that plotly isn't loaded
        self.plotly_options = Store._options.pop('plotly', None)
        self.store_mpl = OptionTree(sorted(Store.options(backend='matplotlib').items()),
                                    groups=Options._option_groups)
        self.store_bokeh = OptionTree(sorted(Store.options(backend='bokeh').items()),
                                    groups=Options._option_groups)
        self.clear_options()
        super(TestCrossBackendOptions, self).setUp()

    def clear_options(self):
        # Clear global options..
        Store.options(val=OptionTree(groups=['plot', 'style']), backend='matplotlib')
        Store.options(val=OptionTree(groups=['plot', 'style']), backend='bokeh')
        # ... and custom options
        Store.custom_options({}, backend='matplotlib')
        Store.custom_options({}, backend='bokeh')

    def tearDown(self):
        Store.options(val=self.store_mpl, backend='matplotlib')
        Store.options(val=self.store_bokeh, backend='bokeh')
        Store.current_backend = 'matplotlib'
        Store._custom_options = {k:{} for k in Store._custom_options.keys()}

        if self.plotly_options is not None:
            Store._options['plotly'] = self.plotly_options

        super(TestCrossBackendOptions, self).tearDown()

    def test_mpl_bokeh_mpl(self):
        img = Image(np.random.rand(10,10))
        # Use blue in matplotlib
        Store.current_backend = 'matplotlib'
        StoreOptions.set_options(img, style={'Image':{'cmap':'Blues'}})
        mpl_opts = Store.lookup_options('matplotlib', img, 'style').options
        self.assertEqual(mpl_opts, {'cmap':'Blues'})
        # Use purple in bokeh
        Store.current_backend = 'bokeh'
        StoreOptions.set_options(img, style={'Image':{'cmap':'Purple'}})
        bokeh_opts = Store.lookup_options('bokeh', img, 'style').options
        self.assertEqual(bokeh_opts, {'cmap':'Purple'})
        # Check it is still blue in matplotlib...
        Store.current_backend = 'matplotlib'
        mpl_opts = Store.lookup_options('matplotlib', img, 'style').options
        self.assertEqual(mpl_opts, {'cmap':'Blues'})
        # And purple in bokeh..
        Store.current_backend = 'bokeh'
        bokeh_opts = Store.lookup_options('bokeh', img, 'style').options
        self.assertEqual(bokeh_opts, {'cmap':'Purple'})
        return img

    def test_mpl_bokeh_offset_mpl(self):
        img = Image(np.random.rand(10,10))
        # Use blue in matplotlib
        Store.current_backend = 'matplotlib'
        StoreOptions.set_options(img, style={'Image':{'cmap':'Blues'}})
        mpl_opts = Store.lookup_options('matplotlib', img, 'style').options
        self.assertEqual(mpl_opts, {'cmap':'Blues'})
        # Switch to bokeh and style a random object...
        Store.current_backend = 'bokeh'
        img2 = Image(np.random.rand(10,10))
        StoreOptions.set_options(img2, style={'Image':{'cmap':'Reds'}})
        img2_opts = Store.lookup_options('bokeh', img2, 'style').options
        self.assertEqual(img2_opts, {'cmap':'Reds'})
        # Use purple in bokeh on the object...
        StoreOptions.set_options(img, style={'Image':{'cmap':'Purple'}})
        bokeh_opts = Store.lookup_options('bokeh', img, 'style').options
        self.assertEqual(bokeh_opts, {'cmap':'Purple'})
        # Check it is still blue in matplotlib...
        Store.current_backend = 'matplotlib'
        mpl_opts = Store.lookup_options('matplotlib', img, 'style').options
        self.assertEqual(mpl_opts, {'cmap':'Blues'})
        # And purple in bokeh..
        Store.current_backend = 'bokeh'
        bokeh_opts = Store.lookup_options('bokeh', img, 'style').options
        self.assertEqual(bokeh_opts, {'cmap':'Purple'})
        return img

    def test_builder_backend_switch(self):
        Store.options(val=self.store_mpl, backend='matplotlib')
        Store.options(val=self.store_bokeh, backend='bokeh')
        Store.set_current_backend('bokeh')
        self.assertEqual(opts.Curve.__doc__.startswith('Curve('), True)
        docline = opts.Curve.__doc__.splitlines()[0]
        dockeys = eval(docline.replace('Curve', 'dict'))
        self.assertEqual('color' in dockeys, True)
        self.assertEqual('line_width' in dockeys, True)
        Store.set_current_backend('matplotlib')
        self.assertEqual(opts.Curve.__doc__.startswith('Curve('), True)
        docline = opts.Curve.__doc__.splitlines()[0]
        dockeys = eval(docline.replace('Curve', 'dict'))
        self.assertEqual('color' in dockeys, True)
        self.assertEqual('linewidth' in dockeys, True)

    def test_builder_cross_backend_validation(self):
        Store.options(val=self.store_mpl, backend='matplotlib')
        Store.options(val=self.store_bokeh, backend='bokeh')
        Store.set_current_backend('bokeh')
        opts.Curve(line_dash='dotted') # Bokeh keyword
        opts.Curve(linewidth=10)       # MPL keyword
        err = ("In opts.Curve\(...\),  keywords supplied are mixed across backends. "
               "Keyword\(s\) 'linewidth' are invalid for bokeh, "
               "'line_dash' are invalid for matplotlib")
        with self.assertRaisesRegexp(ValueError, err):
            opts.Curve(linewidth=10, line_dash='dotted') # Bokeh and MPL

        # Non-existent keyword across backends (bokeh active)
        err = ("In opts.Curve\(...\), unexpected option 'foobar' for Curve type "
               "across all extensions. Similar options for current "
               "extension \('bokeh'\) are: \['toolbar'\].")
        with self.assertRaisesRegexp(ValueError, err):
            opts.Curve(foobar=3)

        # Non-existent keyword across backends (matplotlib active)
        Store.set_current_backend('matplotlib')

        err = ("In opts.Curve\(...\), unexpected option 'foobar' for Curve "
               "type across all extensions. No similar options found.")
        with self.assertRaisesRegexp(ValueError, err):
            opts.Curve(foobar=3)

class TestCrossBackendOptionSpecification(ComparisonTestCase):
    """
    Test the style system can style a single object across backends.
    """

    def setUp(self):
        if 'matplotlib' not in Store.renderers:
            raise SkipTest("Cross background tests assumes matplotlib is available")
        if 'bokeh' not in Store.renderers:
            raise SkipTest("Cross background tests assumes bokeh is available.")

        # Some tests require that plotly isn't loaded
        self.plotly_options = Store._options.pop('plotly', None)
        self.store_mpl = OptionTree(sorted(Store.options(backend='matplotlib').items()),
                                    groups=Options._option_groups)
        self.store_bokeh = OptionTree(sorted(Store.options(backend='bokeh').items()),
                                    groups=Options._option_groups)
        super(TestCrossBackendOptionSpecification, self).setUp()

    def tearDown(self):
        Store.options(val=self.store_mpl, backend='matplotlib')
        Store.options(val=self.store_bokeh, backend='bokeh')
        Store.current_backend = 'matplotlib'
        Store._custom_options = {k:{} for k in Store._custom_options.keys()}

        if self.plotly_options is not None:
            Store._options['plotly'] = self.plotly_options

        super(TestCrossBackendOptionSpecification, self).tearDown()

    def assert_output_options_group_empty(self, obj):
        mpl_output_lookup = Store.lookup_options('matplotlib', obj, 'output').options
        self.assertEqual(mpl_output_lookup, {})
        bokeh_output_lookup = Store.lookup_options('bokeh', obj, 'output').options
        self.assertEqual(bokeh_output_lookup, {})

    def test_mpl_bokeh_mpl_via_option_objects_opts_method(self):
        img = Image(np.random.rand(10,10))
        mpl_opts = Options('Image', cmap='Blues', backend='matplotlib')
        bokeh_opts = Options('Image', cmap='Purple', backend='bokeh')
        self.assertEqual(mpl_opts.kwargs['backend'], 'matplotlib')
        self.assertEqual(bokeh_opts.kwargs['backend'], 'bokeh')
        img.opts(mpl_opts, bokeh_opts)
        mpl_lookup = Store.lookup_options('matplotlib', img, 'style').options
        self.assertEqual(mpl_lookup['cmap'], 'Blues')
        bokeh_lookup = Store.lookup_options('bokeh', img, 'style').options
        self.assertEqual(bokeh_lookup['cmap'], 'Purple')
        self.assert_output_options_group_empty(img)

    def test_mpl_bokeh_mpl_via_builders_opts_method(self):
        img = Image(np.random.rand(10,10))
        mpl_opts = opts.Image(cmap='Blues', backend='matplotlib')
        bokeh_opts = opts.Image(cmap='Purple', backend='bokeh')
        self.assertEqual(mpl_opts.kwargs['backend'], 'matplotlib')
        self.assertEqual(bokeh_opts.kwargs['backend'], 'bokeh')
        img.opts(mpl_opts, bokeh_opts)
        mpl_lookup = Store.lookup_options('matplotlib', img, 'style').options
        self.assertEqual(mpl_lookup['cmap'], 'Blues')
        bokeh_lookup = Store.lookup_options('bokeh', img, 'style').options
        self.assertEqual(bokeh_lookup['cmap'], 'Purple')
        self.assert_output_options_group_empty(img)

    def test_mpl_bokeh_mpl_via_dict_backend_keyword(self):
        curve = Curve([1,2,3])
        styled_mpl = curve.opts({'Curve': dict(color='red')}, backend='matplotlib')
        styled = styled_mpl.opts({'Curve': dict(color='green')}, backend='bokeh')
        mpl_lookup = Store.lookup_options('matplotlib', styled, 'style')
        self.assertEqual(mpl_lookup.kwargs['color'], 'red')
        bokeh_lookup = Store.lookup_options('bokeh', styled, 'style')
        self.assertEqual(bokeh_lookup.kwargs['color'], 'green')

    def test_mpl_bokeh_mpl_via_builders_opts_method_implicit_backend(self):
        img = Image(np.random.rand(10,10))
        Store.set_current_backend('matplotlib')
        mpl_opts = opts.Image(cmap='Blues')
        bokeh_opts = opts.Image(cmap='Purple', backend='bokeh')
        self.assertEqual('backend' not in mpl_opts.kwargs, True)
        self.assertEqual(bokeh_opts.kwargs['backend'], 'bokeh')
        img.opts(mpl_opts, bokeh_opts)
        mpl_lookup = Store.lookup_options('matplotlib', img, 'style').options
        self.assertEqual(mpl_lookup['cmap'], 'Blues')
        bokeh_lookup = Store.lookup_options('bokeh', img, 'style').options
        self.assertEqual(bokeh_lookup['cmap'], 'Purple')
        self.assert_output_options_group_empty(img)

    def test_mpl_bokeh_mpl_via_builders_opts_method_literal_implicit_backend(self):
        img = Image(np.random.rand(10,10))
        curve = Curve([1,2,3])
        overlay = img * curve
        Store.set_current_backend('matplotlib')

        literal = {'Curve':
                   {'style':dict(color='orange')},
                   'Image':
                   {'style':dict(cmap='jet'), 'output':dict(backend='bokeh')}
                   }
        styled = overlay.opts(literal)
        mpl_curve_lookup = Store.lookup_options('matplotlib', styled.Curve.I, 'style')
        self.assertEqual(mpl_curve_lookup.kwargs['color'], 'orange')

        mpl_img_lookup = Store.lookup_options('matplotlib', styled.Image.I, 'style')
        self.assertNotEqual(mpl_img_lookup.kwargs['cmap'], 'jet')

        bokeh_curve_lookup = Store.lookup_options('bokeh', styled.Curve.I, 'style')
        self.assertNotEqual(bokeh_curve_lookup.kwargs['color'], 'orange')

        bokeh_img_lookup = Store.lookup_options('bokeh', styled.Image.I, 'style')
        self.assertEqual(bokeh_img_lookup.kwargs['cmap'], 'jet')

    def test_mpl_bokeh_mpl_via_builders_opts_method_literal_explicit_backend(self):
        img = Image(np.random.rand(10,10))
        curve = Curve([1,2,3])
        overlay = img * curve
        Store.set_current_backend('matplotlib')

        literal = {'Curve':
                   {'style':dict(color='orange'), 'output':dict(backend='matplotlib')},
                   'Image':
                   {'style':dict(cmap='jet'), 'output':dict(backend='bokeh')}
                   }
        styled = overlay.opts(literal)
        mpl_curve_lookup = Store.lookup_options('matplotlib', styled.Curve.I, 'style')
        self.assertEqual(mpl_curve_lookup.kwargs['color'], 'orange')

        mpl_img_lookup = Store.lookup_options('matplotlib', styled.Image.I, 'style')
        self.assertNotEqual(mpl_img_lookup.kwargs['cmap'], 'jet')

        bokeh_curve_lookup = Store.lookup_options('bokeh', styled.Curve.I, 'style')
        self.assertNotEqual(bokeh_curve_lookup.kwargs['color'], 'orange')

        bokeh_img_lookup = Store.lookup_options('bokeh', styled.Image.I, 'style')
        self.assertEqual(bokeh_img_lookup.kwargs['cmap'], 'jet')

    def test_mpl_bokeh_mpl_via_builders_opts_method_flat_literal_explicit_backend(self):
        img = Image(np.random.rand(10,10))
        curve = Curve([1,2,3])
        overlay = img * curve
        Store.set_current_backend('matplotlib')

        literal = {'Curve': dict(color='orange', backend='matplotlib'),
                   'Image': dict(cmap='jet', backend='bokeh')
                   }
        styled = overlay.opts(literal)
        mpl_curve_lookup = Store.lookup_options('matplotlib', styled.Curve.I, 'style')
        self.assertEqual(mpl_curve_lookup.kwargs['color'], 'orange')

        mpl_img_lookup = Store.lookup_options('matplotlib', styled.Image.I, 'style')
        self.assertNotEqual(mpl_img_lookup.kwargs['cmap'], 'jet')

        bokeh_curve_lookup = Store.lookup_options('bokeh', styled.Curve.I, 'style')
        self.assertNotEqual(bokeh_curve_lookup.kwargs['color'], 'orange')

        bokeh_img_lookup = Store.lookup_options('bokeh', styled.Image.I, 'style')
        self.assertEqual(bokeh_img_lookup.kwargs['cmap'], 'jet')

    def test_mpl_bokeh_output_options_group_expandable(self):
        original_allowed_kws = Options._output_allowed_kws[:]
        Options._output_allowed_kws = ['backend', 'file_format_example']
        # Re-register
        Store.register({Curve: plotting.mpl.CurvePlot}, 'matplotlib')
        Store.register({Curve: plotting.bokeh.CurvePlot}, 'bokeh')

        curve_bk = Options('Curve', backend='bokeh', color='blue')
        curve_mpl = Options('Curve', backend='matplotlib', color='red',
                            file_format_example='SVG')
        c = Curve([1,2,3])
        styled = c.opts(curve_bk, curve_mpl)
        self.assertEqual(Store.lookup_options('matplotlib', styled, 'output').kwargs,
                         {'backend':'matplotlib', 'file_format_example':'SVG'})

        self.assertEqual(Store.lookup_options('bokeh', styled, 'output').kwargs,
                         {})
        Options._output_allowed_kws = original_allowed_kws

class TestCrossBackendOptionPickling(TestCrossBackendOptions):

    cleanup = ['test_raw_pickle.pkl', 'test_pickle_mpl_bokeh.pkl']

    def tearDown(self):
        super(TestCrossBackendOptionPickling, self).tearDown()
        for f in self.cleanup:
            try:
                os.remove(f)
            except:
                pass

    def test_raw_pickle(self):
        """
        Test usual pickle saving and loading (no style information preserved)
        """
        fname= 'test_raw_pickle.pkl'
        raw = super(TestCrossBackendOptionPickling, self).test_mpl_bokeh_mpl()
        pickle.dump(raw, open(fname,'wb'))
        self.clear_options()
        img = pickle.load(open(fname,'rb'))
        # Data should match
        self.assertEqual(raw, img)
        # But the styles will be lost without using Store.load/Store.dump
        pickle.current_backend = 'matplotlib'
        mpl_opts = Store.lookup_options('matplotlib', img, 'style').options
        self.assertEqual(mpl_opts, {})
        # ... across all backends
        Store.current_backend = 'bokeh'
        bokeh_opts = Store.lookup_options('bokeh', img, 'style').options
        self.assertEqual(bokeh_opts, {})

    def test_pickle_mpl_bokeh(self):
        """
        Test pickle saving and loading with Store (style information preserved)
        """
        fname = 'test_pickle_mpl_bokeh.pkl'
        raw = super(TestCrossBackendOptionPickling, self).test_mpl_bokeh_mpl()
        Store.dump(raw, open(fname,'wb'))
        self.clear_options()
        img = Store.load(open(fname,'rb'))
        # Data should match
        self.assertEqual(raw, img)
        # Check it is still blue in matplotlib...
        Store.current_backend = 'matplotlib'
        mpl_opts = Store.lookup_options('matplotlib', img, 'style').options
        self.assertEqual(mpl_opts, {'cmap':'Blues'})
        # And purple in bokeh..
        Store.current_backend = 'bokeh'
        bokeh_opts = Store.lookup_options('bokeh', img, 'style').options
        self.assertEqual(bokeh_opts, {'cmap':'Purple'})


text:
using System.Collections.Generic;

namespace Magento.RestApi.Models
{
    /// <summary>
    ///
    /// </summary>
    public class Filter
    {
        /// <summary>
        ///
        /// </summary>
        public Filter()
        {
            Page = 1;
            PageSize = 10;
            SortDirection = SortDirection.asc;
            FilterExpressions = new List<FilterExpression>();
        }

        /// <summary>
        ///
        /// </summary>
        public int PageSize { get; set; }
        /// <summary>
        ///
        /// </summary>
        public int Page { get; set; }
        /// <summary>
        ///
        /// </summary>
        public SortDirection SortDirection { get; set; }
        /// <summary>
        ///
        /// </summary>
        public string SortField { get; set; }
        /// <summary>
        ///
        /// </summary>
        public List<FilterExpression> FilterExpressions { get; set; }
    }

    /// <summary>
    ///
    /// </summary>
    public enum SortDirection
    {
        /// <summary>
        ///
        /// </summary>
        asc,
        /// <summary>
        ///
        /// </summary>
        desc
    }
}


text:
<?php

namespace EnjoyYourBusiness\PictureResizeBundle\Operation;

use EnjoyYourBusiness\PictureResizeBundle\Image\Image;

/**
 * Class OperationCrop
 *
 * @package   EnjoyYourBusiness\pictureresizebundle\Operation
 *
 * @author    Emmanuel Derrien <emmanuel.derrien@enjoyyourbusiness.fr>
 * @author    Anthony Maudry <anthony.maudry@enjoyyourbusiness.fr>
 * @author    Loic Broc <loic.broc@enjoyyourbusiness.fr>
 * @author    Rémy Mantéi <remy.mantei@enjoyyourbusiness.fr>
 * @author    Lucien Bruneau <lucien.bruneau@enjoyyourbusiness.fr>
 * @author    Matthieu Prieur <matthieu.prieur@enjoyyourbusiness.fr>
 * @copyright 2014 Enjoy Your Business - RCS Bourges B 800 159 295 ©
 */
class OperationResizeCrop extends OperationResize
{
    const NAME_FORMAT = 'crop-%d-%d';

    /**
     * Applies the operation to an image
     *
     * @param Image $image
     *
     * @return resource
     */
    public function apply(Image $image)
    {
        $ratioOrigin = $image->getWidth() / $image->getHeight();
        $tmpWidth = $this->width;
        $tmpHeight = $this->height;
        $destinationX = 0;
        $destinationY = 0;
        if ($tmpWidth / $tmpHeight > $ratioOrigin) {
            $tmpHeight = $tmpWidth / $ratioOrigin;
            $destinationY = ($this->height - $tmpHeight) / 2;
        } else {
            $tmpWidth = $tmpHeight * $ratioOrigin;
            $destinationX = ($this->width - $tmpWidth) / 2;
        }

        $tmpResource = imagecreatetruecolor($tmpWidth, $tmpHeight);
        imagecopyresampled($tmpResource, $image->getResource(), 0, 0, 0, 0, $tmpWidth, $tmpHeight, $image->getWidth(), $image->getHeight());

        $newResource = imagecreatetruecolor($this->width, $this->height);
        imagecopy($newResource, $tmpResource, $destinationX, $destinationY, 0, 0, $tmpWidth, $tmpHeight);

        return $newResource;
    }

    /**
     * The name of the operation. Should take in conseideration the different versions of the operation ie :
     * a resize should provide a name with the new size : 'resize-{width}-{height}'
     *
     * @return string
     */
    public function getName(): string
    {
        return sprintf(self::NAME_FORMAT, $this->width, $this->height);
    }
}


text:
extern alias TestAlias1;
extern alias TestAlias2;
using System;
using System.Linq;
using NUnit.Framework;
using TestMonkeys.EntityTest.Engine.PropertyRuleSet;

namespace EntityTest.Test.PropertySetValidatorTests
{

    public class AliasNamespaceTests
    {
        [Ignore("Figure out how to test the internal class, or move it back as public")]
        [Test]
        public void PropertySet_AliasTest()
        {
            //RuleStorage rules=RuleStorage.Instance;
            //Type type1= typeof(TestAlias1::AliasTestPack.Class1);
            //var type1Rules=rules.GetValidationRules(type1);
            //Assert.That(type1Rules.ValidationStrategyBuilders.Any(x=>x.Key.Name=="TestPack1NotNull"), Is.True, "type1 rule notNull");
            //Type type2 = typeof(TestAlias2::AliasTestPack.Class1);
            //var type2Rules = rules.GetValidationRules(type2);
            //Assert.That(type2Rules.ValidationStrategyBuilders.Any(x => x.Key.Name =="TestPack1NotNull"), Is.False, "type1 rule notNull present");
            //Assert.That(type2Rules.ValidationStrategyBuilders.Any(x => x.Key.Name == "TestPack2NotNull"), Is.True, "type1 rule notNull present");

        }

    }
}


text:
package io.cattle.platform.agent.server.resource.impl;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AgentResources {

    private static final Logger log = LoggerFactory.getLogger(AgentResources.class);

    Map<String, Map<String, Object>> hosts = new TreeMap<>();
    Map<String, Map<String, Object>> storagePools = new TreeMap<>();
    Map<String, Map<String, Object>> ipAddresses = new TreeMap<>();
    String hash = null;

    public String getHash() {
        if (hash != null) {
            return hash;
        }

        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Failed to find SHA1 digest", e);
        }

        hashMap(md, hosts);
        hashMap(md, storagePools);
        hashMap(md, ipAddresses);

        return Hex.encodeHexString(md.digest());
    }

    public boolean hasContent() {
        return hosts.size() > 0;
    }

    protected void hashMap(MessageDigest md, Map<String, Map<String, Object>> data) {
        for (Map<String, Object> value : data.values()) {
            for (Map.Entry<String, Object> entry : value.entrySet()) {
                try {
                    md.update(entry.getKey().getBytes("UTF-8"));
                    Object obj = entry.getValue();
                    if (obj != null) {
                        md.update(obj.toString().getBytes("UTF-8"));
                    }
                } catch (UnsupportedEncodingException e) {
                    log.error("Failed to hash [{}]", entry, e);
                }
            }
        }
    }

    public void setHost(String uuid, Map<String, Object> data) {
        hosts.put(uuid, new TreeMap<>(data));
    }

    public Map<String, Map<String, Object>> getHosts() {
        return hosts;
    }

    public Map<String, Map<String, Object>> getStoragePools() {
        return storagePools;
    }

    public void setStoragePool(String uuid, Map<String, Object> data) {
        storagePools.put(uuid, new TreeMap<>(data));
    }

    public Map<String, Map<String, Object>> getIpAddresses() {
        return ipAddresses;
    }

    public void setIpAddress(String uuid, Map<String, Object> data) {
        ipAddresses.put(uuid, new TreeMap<>(data));
    }
}


text:
<ion-header>
  <ion-toolbar color="primary">
    <ion-title>Settings</ion-title>
  </ion-toolbar>
</ion-header>
<ion-content>
  <% if (props.auth) { -%>

      <ion-icon class="profile-icon" name="person-circle"></ion-icon>

{{username}}

  <% } -%>
  <ion-list>
    <ion-list-header>
      <ion-label translate>Account</ion-label>
    </ion-list-header>
    <ion-item button>
      <ion-icon name="person-circle" slot="start"></ion-icon>
      <ion-label translate>Profile</ion-label>
    </ion-item>
    <% if (props.auth) { -%>
    <ion-item button (click)="logout()">
      <ion-icon name="log-out" slot="start"></ion-icon>
      <ion-label translate>Logout</ion-label>
    </ion-item>
    <% } -%>
    <ng-container *ngIf="isWeb">
      <ion-list-header>
        <ion-label translate>Preferences</ion-label>
      </ion-list-header>
      <app-language-selector type="item"></app-language-selector>
    </ng-container>
  </ion-list>
</ion-content>


text:
import { Pipe, Type } from '@angular/core';
import { ReflectorReader } from './private_import_core';
/**
 * Resolve a `Type` for {@link Pipe}.
 *
 * This interface can be overridden by the application developer to create custom behavior.
 *
 * See {@link Compiler}
 */
export declare class PipeResolver {
    private _reflector;
    constructor(_reflector?: ReflectorReader);
    /**
     * Return {@link Pipe} for a given `Type`.
     */
    resolve(type: Type<any>, throwIfNotFound?: boolean): Pipe;
}


text:
namespace Command.Business
{
    /// <summary>
    ///
    /// </summary>
    public interface ICommandMessagePayload
    {
    }
}


text:
package org.datagr4m.drawing.viewer.mouse.edges;

import java.util.Comparator;

import org.datagr4m.drawing.model.items.hierarchical.IHierarchicalNodeModel;
import org.datagr4m.viewer.mouse.IClickableItem;

public class ClickPriorityComparator implements Comparator<IClickableItem> {
    @Override
    public int compare(IClickableItem arg0, IClickableItem arg1) {
        // return 0;
        boolean isModel0 = isModel(arg0);
        boolean isModel1 = isModel(arg1); // not model=slot, edge, etc
        if (isModel0 && isModel1)
            return modelCompare((IHierarchicalNodeModel) arg0, (IHierarchicalNodeModel) arg1);
        else if (isModel0 && !isModel1)
            return 1;
        else if (!isModel0 && isModel1)
            return -1;
        return 0;
    }

    protected int modelCompare(IHierarchicalNodeModel arg0, IHierarchicalNodeModel arg1) {
        return (arg1.getDepth() - arg0.getDepth());
    }

    protected boolean isModel(IClickableItem item) {
        return (item instanceof IHierarchicalNodeModel);
    }
}