text:
=======
Credits
=======

Development Lead
----------------

* Steven Murray <steven.murray@curtin.edu.au>

Contributors
------------

* Danail Obreschkow <danail.obreschkow@gmail.com>

redpajama_set_name: RedPajamaGithub


text:
"""
A component which allows you to send data to StatsD.

For more details about this component, please refer to the documentation at
https://home-assistant.io/components/statsd/
"""
import logging

import voluptuous as vol

from homeassistant.const import (
    CONF_HOST, CONF_PORT, CONF_PREFIX, EVENT_STATE_CHANGED)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers import state as state_helper

REQUIREMENTS = ['statsd==3.2.1']

_LOGGER = logging.getLogger(__name__)

CONF_ATTR = 'log_attributes'
CONF_RATE = 'rate'
CONF_VALUE_MAP = 'value_mapping'

DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 8125
DEFAULT_PREFIX = 'hass'
DEFAULT_RATE = 1
DOMAIN = 'statsd'

CONFIG_SCHEMA = vol.Schema({
    DOMAIN: vol.Schema({
        vol.Required(CONF_HOST, default=DEFAULT_HOST): cv.string,
        vol.Optional(CONF_ATTR, default=False): cv.boolean,
        vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
        vol.Optional(CONF_PREFIX, default=DEFAULT_PREFIX): cv.string,
        vol.Optional(CONF_RATE, default=DEFAULT_RATE):
            vol.All(vol.Coerce(int), vol.Range(min=1)),
        vol.Optional(CONF_VALUE_MAP): dict,
    }),
}, extra=vol.ALLOW_EXTRA)

def setup(hass, config):
    """Set up the StatsD component."""
    import statsd

    conf = config[DOMAIN]
    host = conf.get(CONF_HOST)
    port = conf.get(CONF_PORT)
    sample_rate = conf.get(CONF_RATE)
    prefix = conf.get(CONF_PREFIX)
    value_mapping = conf.get(CONF_VALUE_MAP)
    show_attribute_flag = conf.get(CONF_ATTR)

    statsd_client = statsd.StatsClient(host=host, port=port, prefix=prefix)

    def statsd_event_listener(event):
        """Listen for new messages on the bus and sends them to StatsD."""
        state = event.data.get('new_state')

        if state is None:
            return

        try:
            if value_mapping and state.state in value_mapping:
                _state = float(value_mapping[state.state])
            else:
                _state = state_helper.state_as_number(state)
        except ValueError:
            # Set the state to none and continue for any numeric attributes.
            _state = None

        states = dict(state.attributes)

        _LOGGER.debug('Sending %s', state.entity_id)

        if show_attribute_flag is True:
            if isinstance(_state, (float, int)):
                statsd_client.gauge(
                    "%s.state" % state.entity_id,
                    _state,
                    sample_rate
                )

            # Send attribute values
            for key, value in states.items():
                if isinstance(value, (float, int)):
                    stat = "%s.%s" % (state.entity_id, key.replace(' ', '_'))
                    statsd_client.gauge(stat, value, sample_rate)

        else:
            if isinstance(_state, (float, int)):
                statsd_client.gauge(state.entity_id, _state, sample_rate)

        # Increment the count
        statsd_client.incr(state.entity_id, rate=sample_rate)

    hass.bus.listen(EVENT_STATE_CHANGED, statsd_event_listener)

    return True


text:
echo Welcome to the new account generation, please type path to the your geth data directory. For example './node0'
read ETH_HOME

mkdir -p $ETH_HOME
./geth --datadir $ETH_HOME account new
echo List of yours accounts:
./geth --datadir $ETH_HOME account list


text:
from st2tests.base import BaseActionTestCase

from local import SaltLocal
import requests_mock
from requests_mock.contrib import fixture
import testtools

__all__ = [
    'SaltLocalActionTestCase'
]

no_args = {
    'module': 'this.something',
    'target': '*',
    'expr_form': 'glob',
    'args': []
}

one_arg = {
    'module': 'this.something',
    'target': '*',
    'expr_form': 'glob',
    'args': ['os'],
}

multiple_args = {
    'module': 'this.something',
    'target': '*',
    'expr_form': 'glob',
    'args': ['this', 'that', 'home'],
}

CONFIG_DATA = {
    'api_url': 'https://example.com',
    'username': 'this',
    'password': 'that'
}
requests_mock.Mocker.TEST_PREFIX = 'test'

class SaltLocalActionTestCase(testtools.TestCase, BaseActionTestCase):
    action_cls = SaltLocal

    def setUp(self):
        super(SaltLocalActionTestCase, self).setUp()
        self.m = self.useFixture(fixture.Fixture())
        self.action = self.get_action_instance(config=CONFIG_DATA)
        self.m.register_uri('POST',
                            "{}/run".format(CONFIG_DATA['api_url']),
                            json={})

    def test_generic_action_no_args(self):
        self.action.run(**no_args)
        self.assertNotIn('arg', self.action.data)

    def test_generic_action_one_arg(self):
        self.action.run(**one_arg)
        self.assertIn('arg', self.action.data)
        self.assertIsInstance(self.action.data['arg'], list)

    def test_generic_action_multiple_args(self):
        self.action.run(**multiple_args)
        self.assertIn('arg', self.action.data)
        self.assertIsInstance(self.action.data['arg'], list)


text:
Preconditions
==========

### Overview
Design Custom Precondition Policies that can be applied to Feeds
Precondition Policies are written as simple Java POJO along with custom Annotations that allow the system to transform policies to/from the User Interface.
The Annotations are the same as those used for the **"field-policy"** module Standardization and Validation policies

Below is the mapping of the User Interface Object and its respective to Domain Model

### Requirements
1. Policy Constructor rules

    The PreconditionPolicy objects must follow *one* of the following rules

      1. Have a no arg constructor
      2. or Have a constructor with parameters each annotated with **@PolicyPropertyRef** (See examples below)

2. Policies must implement the Precondition interface and must be annotated with **@PreconditionPolicy**

### Quick Start

   1. Create a class that implements `com.thinkbiganalytics.policy.precondition.Precondition`
   2. Add the `@PreconditionPolicy` annotation to the class
   3. Annotate any field inputs with `@PolicyProperty` and any Constructor arguments with `@PolicyPropertyRef`

### Annotations
#### @PolicyProperty - Field Annotation
**Purpose:** Annotate any Parameter that is needed to be captured the User Interface in order to create the Precondition

| Attribute              | Required  | Default Value | Description      |
| -----------------      | --------- | -------------    |------------|
| name                   | Y         |                  | Unique Name for the User Inerface and Domain to match.
 **NOTE** This will also become the User Interface Display Name, (**displayName attribute**) if one is not specified |
| displayName            | N         | name value above | The display name on the UI |
| value                  | N         |                  | default value on the UI |
| placeholder            | N         |                  | Html Placeholder attribute |
| type                   | N         |  string          | Render Types. Available Options (number, string, select, regex, date, chips,feedChips, currentFeed) |
| selectableValues       | N         |                  | If type is **select** this is the Array of Strings that will be in the list
 Optionally use the property below for a label/value render |
| labelValues            | N         |                  | If type is **select** this is the Array of Label/Values that will be in the list |
| required               | N         | false            | Indicate if input is required by user in the UI |

#### @PolicyPropertyRef - Parameter Annotation
**Purpose:** Annotate any Constructor Parameter that references a given
**@PolicyProperty**

| Attribute     | Required |  Description |
| ----------    | -------- | ----------   |
| name          | Y        | This name should match the @PolicyProperty name |

#### @PreconditionPolicy  - Class Annotation
**Purpose:** Annotate the Class to inform the system and the User Interface that this is a PreconditionPolicy

| Attribute     | Required |  Description |
| ----------    | -------- | ----------   |
| name          | Y        | This name of the Precondition.  This will be displayed on the User Interface |
| shortDescription   | N        | Short Description of the Precondition. This will be displayed on the User Interface  |
| description   | N        |  A Longer Description of the Precondition.  |

How To
=======

1. Create a new Java Class that implements the **Precondition** class
2. Add the the **@PreconditionPolicy** annotation to your class
3. Implement the **getPreconditionObligations()** that builds up the correct **Metric** objects defined in the **"sla-api"** module and creates the correct Condition/Obligation.

```java
@PreconditionPolicy(name = PreconditionPolicyConstants.FEED_EXECUTED_SINCE_FEEDS_NAME, description = "Policy will trigger the feed when all of the supplied feeds have successfully finished")
public class FeedExecutedSinceFeeds implements Precondition {

    @PolicyProperty(name = "Since Feed", type = PolicyProperty.PROPERTY_TYPE.currentFeed)
    private String sinceCategoryAndFeedName;

    @PolicyProperty(name = "Dependent Feeds", required = true, type = PolicyProperty.PROPERTY_TYPE.feedChips, placeholder = "Start typing a feed",
                    hint = "Select feed(s) that this feed is dependent upon")
    private String categoryAndFeeds;

    private List<String> categoryAndFeedList;

    public FeedExecutedSinceFeeds(@PolicyPropertyRef(name = "Since Feed") String sinceCategoryAndFeedName, @PolicyPropertyRef(name = "Dependent Feeds") String categoryAndFeeds) {
        this.sinceCategoryAndFeedName = sinceCategoryAndFeedName;
        this.categoryAndFeeds = categoryAndFeeds;
        categoryAndFeedList = Arrays.asList(StringUtils.split(categoryAndFeeds, ","));
    }

    @Override
        public Set<PreconditionGroup> getPreconditionObligations() {
            Set<Metric> metrics = new HashSet<>();
            for (String categoryAndFeed : categoryAndFeedList) {
                FeedExecutedSinceFeed metric = new FeedExecutedSinceFeed(sinceCategoryAndFeedName, categoryAndFeed);
                metrics.add(metric);
            }
            Set<PreconditionGroup> preconditionGroups = new HashSet<>();
            preconditionGroups.add(new DefaultPreconditionGroup(metrics, ObligationGroup.Condition.REQUIRED.name()));
            return preconditionGroups;
        }
```


text:
local protobuf = require "protobuf"
module('BceGuildPrivilegeList_pb', package.seeall)

local BCEGUILDPRIVILEGELIST = protobuf.Descriptor();
local BCEGUILDPRIVILEGELIST_GUILDID_FIELD = protobuf.FieldDescriptor();

BCEGUILDPRIVILEGELIST_GUILDID_FIELD.name = "guildID"
BCEGUILDPRIVILEGELIST_GUILDID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceGuildPrivilegeList.guildID"
BCEGUILDPRIVILEGELIST_GUILDID_FIELD.number = 1
BCEGUILDPRIVILEGELIST_GUILDID_FIELD.index = 0
BCEGUILDPRIVILEGELIST_GUILDID_FIELD.label = 1
BCEGUILDPRIVILEGELIST_GUILDID_FIELD.has_default_value = false
BCEGUILDPRIVILEGELIST_GUILDID_FIELD.default_value = ""
BCEGUILDPRIVILEGELIST_GUILDID_FIELD.type = 9
BCEGUILDPRIVILEGELIST_GUILDID_FIELD.cpp_type = 9

BCEGUILDPRIVILEGELIST.name = "BceGuildPrivilegeList"
BCEGUILDPRIVILEGELIST.full_name = ".com.xinqihd.sns.gameserver.proto.BceGuildPrivilegeList"
BCEGUILDPRIVILEGELIST.nested_types = {}
BCEGUILDPRIVILEGELIST.enum_types = {}
BCEGUILDPRIVILEGELIST.fields = {BCEGUILDPRIVILEGELIST_GUILDID_FIELD}
BCEGUILDPRIVILEGELIST.is_extendable = false
BCEGUILDPRIVILEGELIST.extensions = {}

BceGuildPrivilegeList = protobuf.Message(BCEGUILDPRIVILEGELIST)
_G.BCEGUILDPRIVILEGELIST_PB_BCEGUILDPRIVILEGELIST = BCEGUILDPRIVILEGELIST


text:
package org.apache.camel.component.mllp;

import java.util.concurrent.TimeUnit;

import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.LoggingLevel;
import org.apache.camel.Message;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.test.AvailablePortFinder;
import org.apache.camel.test.junit.rule.mllp.MllpClientResource;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;

public class MllpTcpServerConsumerMessageHeadersTest extends CamelTestSupport {

    @RegisterExtension
    public MllpClientResource mllpClient = new MllpClientResource();

    @EndpointInject("mock://result")
    MockEndpoint result;

    @EndpointInject("mock://on-completion-result")
    MockEndpoint onCompletionResult;

    @Override
    public boolean isUseRouteBuilder() {
        return false;
    }

    @Override
    protected void doPreSetup() throws Exception {
        mllpClient.setMllpHost("localhost");
        mllpClient.setMllpPort(AvailablePortFinder.getNextAvailable());

        super.doPreSetup();
    }

    @Override
    protected CamelContext createCamelContext() throws Exception {
        DefaultCamelContext context = (DefaultCamelContext) super.createCamelContext();

        context.setUseMDCLogging(true);
        context.setName(this.getClass().getSimpleName());

        return context;
    }

    @Test
    public void testHl7HeadersEnabled() throws Exception {
        String testMessage = "MSH|^~\\&|ADT|EPIC|JCAPS|CC|20160902123950|RISTECH|ADT^A08|00001|D|2.3|||||||" + '\r' + '\n';

        addTestRoute(true);

        result.expectedMessageCount(1);

        result.expectedHeaderReceived(MllpConstants.MLLP_SENDING_APPLICATION, "ADT");
        result.expectedHeaderReceived(MllpConstants.MLLP_SENDING_FACILITY, "EPIC");
        result.expectedHeaderReceived(MllpConstants.MLLP_RECEIVING_APPLICATION, "JCAPS");
        result.expectedHeaderReceived(MllpConstants.MLLP_TIMESTAMP, "20160902123950");
        result.expectedHeaderReceived(MllpConstants.MLLP_SECURITY, "RISTECH");
        result.expectedHeaderReceived(MllpConstants.MLLP_MESSAGE_TYPE, "ADT^A08");
        result.expectedHeaderReceived(MllpConstants.MLLP_EVENT_TYPE, "ADT");
        result.expectedHeaderReceived(MllpConstants.MLLP_TRIGGER_EVENT, "A08");
        result.expectedHeaderReceived(MllpConstants.MLLP_MESSAGE_CONTROL, "00001");
        result.expectedHeaderReceived(MllpConstants.MLLP_PROCESSING_ID, "D");
        result.expectedHeaderReceived(MllpConstants.MLLP_VERSION_ID, "2.3");

        mllpClient.connect();

        mllpClient.sendMessageAndWaitForAcknowledgement(testMessage, 10000);

        assertMockEndpointsSatisfied(10, TimeUnit.SECONDS);

        Message message = result.getExchanges().get(0).getIn();

        assertNotNull(message.getHeader(MllpConstants.MLLP_LOCAL_ADDRESS),
                "Should have header" + MllpConstants.MLLP_LOCAL_ADDRESS);
        assertNotNull(message.getHeader(MllpConstants.MLLP_REMOTE_ADDRESS),
                "Should have header" + MllpConstants.MLLP_REMOTE_ADDRESS);
    }

    @Test
    public void testHl7HeadersDisabled() throws Exception {
        String testMessage = "MSH|^~\\&|ADT|EPIC|JCAPS|CC|20160902123950|RISTECH|ADT^A08|00001|D|2.3|||||||" + '\r' + '\n';

        addTestRoute(false);

        result.expectedMessageCount(1);

        mllpClient.connect();

        mllpClient.sendMessageAndWaitForAcknowledgement(testMessage, 10000);

        assertMockEndpointsSatisfied(10, TimeUnit.SECONDS);

        Message message = result.getExchanges().get(0).getIn();

        assertNotNull(message.getHeader(MllpConstants.MLLP_LOCAL_ADDRESS),
                "Should have header" + MllpConstants.MLLP_LOCAL_ADDRESS);
        assertNotNull(message.getHeader(MllpConstants.MLLP_REMOTE_ADDRESS),
                "Should have header" + MllpConstants.MLLP_REMOTE_ADDRESS);

        assertNull(message.getHeader(MllpConstants.MLLP_SENDING_APPLICATION),
                "Should NOT have header" + MllpConstants.MLLP_SENDING_APPLICATION);
        assertNull(message.getHeader(MllpConstants.MLLP_SENDING_FACILITY),
                "Should NOT have header" + MllpConstants.MLLP_SENDING_FACILITY);
        assertNull(message.getHeader(MllpConstants.MLLP_RECEIVING_APPLICATION),
                "Should NOT have header" + MllpConstants.MLLP_RECEIVING_APPLICATION);
        assertNull(message.getHeader(MllpConstants.MLLP_TIMESTAMP), "Should NOT have header" + MllpConstants.MLLP_TIMESTAMP);
        assertNull(message.getHeader(MllpConstants.MLLP_SECURITY), "Should NOT have header" + MllpConstants.MLLP_SECURITY);
        assertNull(message.getHeader(MllpConstants.MLLP_MESSAGE_TYPE),
                "Should NOT have header" + MllpConstants.MLLP_MESSAGE_TYPE);
        assertNull(message.getHeader(MllpConstants.MLLP_EVENT_TYPE), "Should NOT have header" + MllpConstants.MLLP_EVENT_TYPE);
        assertNull(message.getHeader(MllpConstants.MLLP_MESSAGE_CONTROL),
                "Should NOT have header" + MllpConstants.MLLP_MESSAGE_CONTROL);
        assertNull(message.getHeader(MllpConstants.MLLP_PROCESSING_ID),
                "Should NOT have header" + MllpConstants.MLLP_PROCESSING_ID);
        assertNull(message.getHeader(MllpConstants.MLLP_VERSION_ID), "Should NOT have header" + MllpConstants.MLLP_VERSION_ID);
    }

    void addTestRoute(final boolean hl7Headers) throws Exception {
        RouteBuilder builder = new RouteBuilder() {
            int connectTimeout = 500;
            int responseTimeout = 5000;

            @Override
            public void configure() {
                String routeId = "mllp-test-receiver-route";

                onCompletion()
                        .to("mock://on-completion-result")
                        .toF("log:%s?level=INFO&showAll=true", routeId)
                        .log(LoggingLevel.INFO, routeId, "Test route complete");

                fromF("mllp://%s:%d?autoAck=true&connectTimeout=%d&receiveTimeout=%d&hl7Headers=%b",
                        mllpClient.getMllpHost(), mllpClient.getMllpPort(), connectTimeout, responseTimeout, hl7Headers)
                                .routeId(routeId)
                                .log(LoggingLevel.INFO, routeId, "Test route received message")
                                .to(result);

            }
        };
        context.addRoutes(builder);
        context.start();
    }

}


text:
var mongoose = require("mongoose"),
	Game = require("../model/game.js"),
	Lan = require("../model/lan.js"),
	authorize = require("../utils/authorization.js").authorize,
	authenticate = require("../utils/authentication.js").authenticate,
	sanitizeBodyForDB = require("../utils/common.js").sanitizeBodyForDB,
	checkObjectIDParam = require("../utils/common.js").checkObjectIDParam,
	handleError = require("../utils/common.js").handleError;

module.exports = function(app, prefix){
	app.get(prefix,
	function(req, res){
		Game.find({})
		.sort("name")
		.then(function(games){
			res.send(games || []);
		}).catch(handleError(res));
	});

	app.get(prefix + "/:game",
		checkObjectIDParam("game"),
	function(req, res){
		Game.findById(req.params.game)
		.then(function(game){
			if(!game) throw 404;
			res.send(game);
		}).catch(handleError(res));
	});

	app.post(prefix,
		authenticate,
		authorize({hasRoles: ["admin"]}),
		sanitizeBodyForDB,
	function(req, res){
		var uniqueStores = [];
		if(req.body.stores && Array.isArray(req.body.stores)){
			for(var i = 0; i < req.body.stores.length; i += 1){
				if(!mongoose.Types.ObjectId.isValid(req.body.stores[i].store)){
					return res.status(400).end();
				}else if(uniqueStores.indexOf(req.body.stores[i].store) !== -1){
					return res.status(400).end();
				}else{
					uniqueStores.push({
						store: req.body.stores[i].store,
						appid: req.body.stores[i].appid
					});
				}
			}
		}

		var game = new Game(req.body);
		game.stores = uniqueStores;
		game.save()
		.then(function(){
			res.status(201)
			.location(prefix + "/" + game._id)
			.send({_id: game._id});
		}).catch(function(err){
			throw 400;
		}).catch(handleError(res));
	});

	app.put(prefix + "/:game",
		authenticate,
		authorize({hasRoles: ["admin"]}),
		sanitizeBodyForDB,
		checkObjectIDParam("game"),
	function(req, res){
		var uniqueStores = [];
		if(req.body.stores && Array.isArray(req.body.stores)){
			for(var i = 0; i < req.body.stores.length; i += 1){
				if(!mongoose.Types.ObjectId.isValid(req.body.stores[i].store)){
					return res.status(400).end();
				}else if(uniqueStores.indexOf(req.body.stores[i].store) !== -1){
					return res.status(400).end();
				}else{
					uniqueStores.push({
						store: req.body.stores[i].store,
						appid: req.body.stores[i].appid
					});
				}
			}
		}

		// Apply the update
		req.body.stores = uniqueStores;
		Game.findByIdAndUpdate(req.params.game, req.body)
		.then(function(game){
			if(!game) throw 404;
			res.status(200).end();
		}).catch(handleError(res));
	});

	app.delete(prefix + "/:game",
		authenticate,
		authorize({hasRoles: ["admin"]}),
		checkObjectIDParam("game"),
	function(req, res){
		Lan.find({"games.game": req.params.game})
		.then(function(lans){
			if(lans){
				for(var i = 0; i < lans.length; i += 1){
					for(var j = 0; j < lans[i].games.length; j += 1){
						if(lans[i].games[j].game.toString() == req.params.game){
							lans[i].games.splice(j, 1);
						}
					}
					lans[i].save();
				}
			}
		});
		Game.findByIdAndRemove(req.params.game)
		.then(function(game){
			if(!game) throw 404;
			res.status(204).end();
		}).catch(handleError(res));
	});
};


text:
layout: post
title: Pick a random number from a BST
date: 2016-01-09 10:40:16.000000000 -05:00
tags:
- OA
categories:
- Brain Teaser
author: Jason
---
**Randomly pick a number from binary searach tree**

``` java
public class Solution {
    public static int pickRandom(TreeNode root) {
        if (root == null) return -1;

        List<Integer> nums = getList(root);
        return nums.get(rand.nextInt(nums.size()));
    }

    public static List<Integer> getList(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) return result;

        List<Integer> left = getList(root.left);
        List<Integer> right = getList(root.right);
        result.addAll(left);
        result.add(root.val);
        result.addAll(right);
        return result;
    }
}
```

``` python
class Solution(object):
    def pickRandom(self, root):
        if not root:
            return

        stack, ret = [], []
        while stack or root:
            if root:
                stack.append(root)
                root = root.left
            else:
                root = stack.pop()
                ret.append(root)
                root = root.right
        return ret[random.randInt(0, len(ret) - 1)]
```


text:
//---------------------------------------------------------------------
// <copyright file="ITestModuleLoader.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.Execution
{
    using System.Collections.Generic;
    using System.Reflection;

    /// <summary>
    /// Handles the loading of test module information from assemblies.
    /// </summary>
    public interface ITestModuleLoader
    {
        /// <summary>
        /// Determines whether this loader can load the specified assemblies.
        /// </summary>
        /// <param name="assemblies">The assemblies to consider.</param>
        /// <returns>
        /// <c>true</c> if this loader can load the specified assemblies; otherwise, <c>false</c>.
        /// </returns>
        bool CanLoad(IEnumerable<Assembly> assemblies);

        /// <summary>
        /// Loads test module information from the specified assemblies.
        /// </summary>
        /// <param name="assemblies">The assemblies to consider.</param>
        /// <param name="explorationSeed">The exploration seed to use when loading test items with a <see cref="TestMatrixAttribute"/>.</param>
        /// <param name="explorationKind">The exploraiton kind to use when loading test items with a <see cref="TestMatrixAttribute"/>.</param>
        /// <returns>A <see cref="TestModuleData"/> instance representing the
        /// module information found in the specified assemblies.</returns>
        TestModuleData Load(IEnumerable<Assembly> assemblies, int explorationSeed, TestMatrixExplorationKind? explorationKind);
    }
}


text:
module Astrails
  module Safe
    class Archive < Source

      def command
        "tar -cf - #{config[:options]} #{tar_exclude_files} #{tar_files}"
      end

      def extension; '.tar'; end

      protected

      def tar_exclude_files
        [*config[:exclude]].compact.map{|x| "--exclude=#{x}"}.join(" ")
      end

      def tar_files
        raise RuntimeError, "missing files for tar" unless config[:files]
        [*config[:files]].map{|s| s.strip}.join(" ")
      end

    end
  end
end


text:
using System;
using XamlX.Transform;

namespace Avalonia.Build.Tasks
{
    public class DeterministicIdGenerator : IXamlIdentifierGenerator
    {
        private int _nextId = 1;

        public string GenerateIdentifierPart() => (_nextId++).ToString();
    }
}


text: require "greener/runner"


text:
package io.github.bonigarcia.wdm;

/**
 * Types for driver managers.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 2.1.0
 */
public enum DriverManagerType {

    CHROME, FIREFOX, OPERA, EDGE, PHANTOMJS, IEXPLORER, SELENIUM_SERVER_STANDALONE;

    @Override
    public String toString() {
        switch (this) {
        case CHROME:
            return "Google Chrome";
        case FIREFOX:
            return "Mozilla Firefox";
        case OPERA:
            return "Opera";
        case EDGE:
            return "Microsoft Edge";
        case PHANTOMJS:
            return "PhantomJS";
        case IEXPLORER:
            return "Internet Explorer";
        case SELENIUM_SERVER_STANDALONE:
            return "Selenium Server Standalone";
        default:
            throw new WebDriverManagerException(
                    "Invalid driver manager type: " + this.name());
        }
    }

}


text:
FROM ubuntu
MAINTAINER jnory <jnory@alpacadb.com>

RUN apt-get update
RUN apt-get upgrade -y
RUN apt-get install -y build-essential
RUN apt-get install -y git
RUN apt-get install -y wget
RUN apt-get install -y libjpeg-dev libblas-dev libatlas-dev libatlas-base-dev liblapack-dev gfortran
RUN apt-get install -y libprotobuf-dev libleveldb-dev libsnappy-dev libopencv-dev libboost-all-dev
RUN apt-get install -y libhdf5-serial-dev bc libgflags-dev libgoogle-glog-dev liblmdb-dev protobuf-compiler

# python libs
RUN apt-get install -y python-numpy python-scipy
RUN apt-get install -y python-pip
RUN apt-get install -y python-dev
RUN pip install fabric
RUN pip install six

# download cuda
RUN mkdir -p /opt/archives
RUN cd /opt/archives && wget http://developer.download.nvidia.com/compute/cuda/7_0/Prod/local_installers/cuda_7.0.28_linux.run

# clone caffe
RUN git clone https://github.com/BVLC/caffe.git /opt/caffe/src
RUN cd /opt/caffe/src && git checkout -b labellio 8df472af7f0d475ce866055d0665086e093aaf0e

ADD fabfile.py /opt/
RUN cd /opt && fab local_deploy
RUN rm /opt/fabfile.py
RUN rm /opt/fabfile.pyc


text:
require 'test_helper'

class RememberableTest < ActiveSupport::TestCase
  def resource_class
    User
  end

  def create_resource
    create_user
  end

  test 'remember_me should not generate a new token if using salt' do
    user = create_user
    user.expects(:valid?).never
    user.remember_me!
    assert user.remember_created_at
  end

  test 'remember_me should not generate a new token if valid token exists' do
    user = create_user
    user.singleton_class.send(:attr_accessor, :remember_token)
    User.to_adapter.expects(:find_first).returns(nil)

    user.remember_me!
    existing_token = user.remember_token

    user.remember_me!
    assert_equal existing_token, user.remember_token
  end

  test 'forget_me should not clear remember token if using salt' do
    user = create_user
    user.remember_me!
    user.expects(:valid?).never
    user.forget_me!
  end

  test 'can generate remember token' do
    user = create_user
    user.singleton_class.send(:attr_accessor, :remember_token)
    User.to_adapter.expects(:find_first).returns(nil)
    user.remember_me!
    assert user.remember_token
  end

  test 'serialize into cookie' do
    user = create_user
    user.remember_me!
    id, token, date = User.serialize_into_cookie(user)
    assert_equal id, user.to_key
    assert_equal token, user.authenticatable_salt
    assert date.is_a?(String)
  end

  test 'serialize from cookie' do
    user = create_user
    user.remember_me!
    assert_equal user, User.serialize_from_cookie(user.to_key, user.authenticatable_salt, Time.now.utc)
  end

  test 'serialize from cookie should accept a String with the datetime seconds and microseconds' do
    user = create_user
    user.remember_me!
    assert_equal user, User.serialize_from_cookie(user.to_key, user.authenticatable_salt, Time.now.utc.to_f.to_json)
  end

  test 'serialize from cookie should return nil with invalid datetime' do
    user = create_user
    user.remember_me!
    assert_nil User.serialize_from_cookie(user.to_key, user.authenticatable_salt, "2013")
  end

  test 'serialize from cookie should return nil if no resource is found' do
    assert_nil resource_class.serialize_from_cookie([0], "123", Time.now.utc)
  end

  test 'serialize from cookie should return nil if no timestamp' do
    user = create_user
    user.remember_me!
    assert_nil User.serialize_from_cookie(user.to_key, user.authenticatable_salt)
  end

  test 'serialize from cookie should return nil if timestamp is earlier than token creation' do
    user = create_user
    user.remember_me!
    assert_nil User.serialize_from_cookie(user.to_key, user.authenticatable_salt, 1.day.ago)
  end

  test 'serialize from cookie should return nil if timestamp is older than remember_for' do
    user = create_user
    user.remember_created_at = 1.month.ago
    user.remember_me!
    assert_nil User.serialize_from_cookie(user.to_key, user.authenticatable_salt, 3.weeks.ago)
  end

  test 'serialize from cookie me return nil if is a valid resource with invalid token' do
    user = create_user
    user.remember_me!
    assert_nil User.serialize_from_cookie(user.to_key, "123", Time.now.utc)
  end

  test 'raises a RuntimeError if authenticatable_salt is nil or empty' do
    user = User.new
    def user.authenticable_salt; nil; end
    assert_raise RuntimeError do
      user.rememberable_value
    end

    user = User.new
    def user.authenticable_salt; ""; end
    assert_raise RuntimeError do
      user.rememberable_value
    end
  end

  test 'should respond to remember_me attribute' do
    assert resource_class.new.respond_to?(:remember_me)
    assert resource_class.new.respond_to?(:remember_me=)
  end

  test 'forget_me should clear remember_created_at if expire_all_remember_me_on_sign_out is true' do
    swap Devise, expire_all_remember_me_on_sign_out: true do
      resource = create_resource
      resource.remember_me!
      assert_not_nil resource.remember_created_at

      resource.forget_me!
      assert_nil resource.remember_created_at
    end
  end

  test 'forget_me should not clear remember_created_at if expire_all_remember_me_on_sign_out is false' do
    swap Devise, expire_all_remember_me_on_sign_out: false do
      resource = create_resource
      resource.remember_me!

      assert_not_nil resource.remember_created_at

      resource.forget_me!
      assert_not_nil resource.remember_created_at
    end
  end

  test 'forget_me should not try to update resource if it has been destroyed' do
    resource = create_resource
    resource.expects(:remember_created_at).never
    resource.expects(:save).never

    resource.destroy
    resource.forget_me!
  end

  test 'remember expires at uses remember for configuration' do
    swap Devise, remember_for: 3.days do
      resource = create_resource
      resource.remember_me!
      assert_equal 3.days.from_now.to_date, resource.remember_expires_at.to_date

      Devise.remember_for = 5.days
      assert_equal 5.days.from_now.to_date, resource.remember_expires_at.to_date
    end
  end

  test 'should have the required_fields array' do
    assert_same_content Devise::Models::Rememberable.required_fields(User), [
      :remember_created_at
    ]
  end
end


text:
package com.example.android.apis.animation;

// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import android.animation.AnimatorInflater;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Color;
import com.example.android.apis.R;

import java.util.ArrayList;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

/**
 * This application demonstrates loading Animator objects from XML resources.
 */
public class AnimationLoading extends Activity {

    private static final int DURATION = 1500;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.animation_loading);
        LinearLayout container = (LinearLayout) findViewById(R.id.container);
        final MyAnimationView animView = new MyAnimationView(this);
        container.addView(animView);

        Button starter = (Button) findViewById(R.id.startButton);
        starter.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                animView.startAnimation();
            }
        });
    }

    public class MyAnimationView extends View implements ValueAnimator.AnimatorUpdateListener {

        private static final float BALL_SIZE = 100f;

        public final ArrayList<ShapeHolder> balls = new ArrayList<ShapeHolder>();
        Animator animation = null;

        public MyAnimationView(Context context) {
            super(context);
            addBall(50, 50);
            addBall(200, 50);
            addBall(350, 50);
            addBall(500, 50, Color.GREEN);
        }

        private void createAnimation() {
            Context appContext = AnimationLoading.this;

            if (animation == null) {
                ObjectAnimator anim = (ObjectAnimator) AnimatorInflater.
                        loadAnimator(appContext, R.anim.object_animator);
                anim.addUpdateListener(this);
                anim.setTarget(balls.get(0));

                ValueAnimator fader = (ValueAnimator) AnimatorInflater.
                        loadAnimator(appContext, R.anim.animator);
                fader.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    public void onAnimationUpdate(ValueAnimator animation) {
                        balls.get(1).setAlpha((Float) animation.getAnimatedValue());
                    }
                });

                AnimatorSet seq =
                        (AnimatorSet) AnimatorInflater.loadAnimator(appContext,
                        R.anim.animator_set);
                seq.setTarget(balls.get(2));

                ObjectAnimator colorizer = (ObjectAnimator) AnimatorInflater.
                        loadAnimator(appContext, R.anim.color_animator);
                colorizer.setTarget(balls.get(3));

                animation = new AnimatorSet();
                ((AnimatorSet) animation).playTogether(anim, fader, seq, colorizer);
            }
        }

        public void startAnimation() {
            createAnimation();
            animation.start();
        }

        private ShapeHolder createBall(float x, float y) {
            OvalShape circle = new OvalShape();
            circle.resize(BALL_SIZE, BALL_SIZE);
            ShapeDrawable drawable = new ShapeDrawable(circle);
            ShapeHolder shapeHolder = new ShapeHolder(drawable);
            shapeHolder.setX(x);
            shapeHolder.setY(y);
            return shapeHolder;
        }

        private void addBall(float x, float y, int color) {
            ShapeHolder shapeHolder = createBall(x, y);
            shapeHolder.setColor(color);
            balls.add(shapeHolder);
        }

        private void addBall(float x, float y) {
            ShapeHolder shapeHolder = createBall(x, y);
            int red = (int)(100 + Math.random() * 155);
            int green = (int)(100 + Math.random() * 155);
            int blue = (int)(100 + Math.random() * 155);
            int color = 0xff000000 | red << 16 | green << 8 | blue;
            Paint paint = shapeHolder.getShape().getPaint();
            int darkColor = 0xff000000 | red/4 << 16 | green/4 << 8 | blue/4;
            RadialGradient gradient = new RadialGradient(37.5f, 12.5f,
                    50f, color, darkColor, Shader.TileMode.CLAMP);
            paint.setShader(gradient);
            balls.add(shapeHolder);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            for (ShapeHolder ball : balls) {
                canvas.translate(ball.getX(), ball.getY());
                ball.getShape().draw(canvas);
                canvas.translate(-ball.getX(), -ball.getY());
            }
        }

        public void onAnimationUpdate(ValueAnimator animation) {

            invalidate();
            ShapeHolder ball = balls.get(0);
            ball.setY((Float)animation.getAnimatedValue());
        }
    }
}


text:
package com.dominikgruber.fpinscala.chapter12

sealed trait Validation[+E, +A]

case class Failure[E](head: E, tail: Vector[E] = Vector()) extends Validation[E, Nothing]
case class Success[A](a: A) extends Validation[Nothing, A]

object Validation {

  /**
   * Exercise 06
   * Write an Applicative instance for Validation that accumulates errors in
   * Failure. Note that in the case of Failure there's always at least one error,
   * stored in head. The rest of the errors accumulate in the tail.
   */
  def valApp[E] = new Applicative[({type f[x] = Validation[E,x]})#f] {
    def unit[A](a: => A): Validation[E,A] = Success(a)

    override def map2[A,B,C](fa: Validation[E,A], fb: Validation[E,B])(f: (A, B) => C): Validation[E,C] =
      (fa, fb) match {
        case (Success(a), Success(b)) => Success(f(a, b))
        case (Failure(h1, t1), Failure(h2, t2)) => Failure(h1, t1 ++ Vector(h2) ++ t2)
        case (e@Failure(_, _), _) => e
        case (_, e@Failure(_, _)) => e
      }
  }
}


text:
package com.yixia.zi.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;

import android.os.Environment;

public class FileHelper {

	public static void deleteDir(File f) {
		if (f.exists() && f.isDirectory()) {
			for (File file : f.listFiles()) {
				if (file.isDirectory())
					deleteDir(file);
				file.delete();
			}
			f.delete();
		}
	}

	public static void deleteDirAllMedias(File f) {
		if (f != null && f.exists() && f.isDirectory()) {
			File[] files = f.listFiles();
			if (files != null) {
				for (File file : files) {
					if (file.exists() && !file.isDirectory() && file.canRead() && Media.isVideoOrAudio(file))
						file.delete();
				}
			}
			files = f.listFiles();
			if (files == null || files.length == 0)
				f.delete();
		}
	}

	public static String getCanonical(File f) {
		if (f == null)
			return null;

		try {
			return f.getCanonicalPath();
		} catch (IOException e) {
			return f.getAbsolutePath();
		}
	}

	public static File[] listFilesAccordingPref(File f, final boolean hiddenShown) {
		return f.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String filename) {
				if (filename == null)
					return false;
				File f = new File(dir, filename);
				if (!f.canRead() || !hiddenShown && f.isHidden())
					return false;
				return true;
			}
		});
	}

	public static File[] listSubtrackFilesAccordingPref(File f, final boolean hiddenShown) {
		return f.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String filename) {
				if (filename == null)
					return false;
				File f = new File(dir, filename);
				if (!f.canRead() || !hiddenShown && f.isHidden() || !Media.isSubTrack(f) && !f.isDirectory())
					return false;
				return true;
			}
		});
	}

	public static String[] listAllMedias(File f) {
		File[] medias = f.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String filename) {
				if (filename == null)
					return false;
				File f = new File(dir, filename);
				if (f.exists() && f.canRead() && Media.isVideoOrAudio(f))
					return true;
				else
					return false;
			}
		});

		if (medias == null)
			return null;

		sortFilesByName(medias);

		int len = medias.length;
		String[] mediaNames = new String[len];
		for (int i = 0; i < len; i++)
			mediaNames[i] = FileHelper.getCanonical(medias[i]);

		return mediaNames;
	}

	public static void sortFilesBySize(File[] files) {
		Arrays.sort(files, new Comparator<File>() {
			@Override
			public int compare(File f1, File f2) {
				if (f1.isDirectory() && f2.isDirectory() || f1.isFile() && f2.isFile())
					return Long.valueOf(f2.length()).compareTo(f1.length());
				else if (f1.isDirectory() && f2.isFile())
					return -1;
				else
					return 1;
			}
		});
	}

	public static void sortFilesByName(File[] files) {
		Arrays.sort(files, new Comparator<File>() {
			@Override
			public int compare(File f1, File f2) {
				if (f1.isDirectory() && f2.isDirectory() || f1.isFile() && f2.isFile())
					return f1.getName().trim().compareToIgnoreCase(f2.getName().trim());
				else if (f1.isDirectory() && f2.isFile())
					return -1;
				else
					return 1;
			}
		});
	}

	public static String getUrlFileName(String url) {
		int slashIndex = url.lastIndexOf('/');
		if (slashIndex > -1)
			return url.substring(slashIndex + 1);
		else
			return url;
	}

	public static String getUrlFileNameNoEx(String url) {
		int slashIndex = url.lastIndexOf('/');
		int dotIndex = url.lastIndexOf('.');
		String filenameWithoutExtension;
		if (dotIndex == -1) {
			filenameWithoutExtension = url.substring(slashIndex + 1);
		} else {
			filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex);
		}
		return filenameWithoutExtension;
	}

	public static String getUrlExtension(String url) {
		if (!StringUtils.isBlank(url)) {
			int slashIndex = url.lastIndexOf('/');
			if (slashIndex > -1) {
				String fileName = url.substring(slashIndex + 1);
				int dotIndex = fileName.indexOf('.');
				int paramIndex = fileName.indexOf('?');
				if (dotIndex != -1) {
					if (paramIndex == -1) {
						paramIndex = fileName.indexOf('&');
						if (paramIndex == -1)
							return fileName.substring(dotIndex + 1).toLowerCase();
						else
							return fileName.substring(dotIndex + 1, paramIndex).toLowerCase();
					} else if (paramIndex <= (fileName.length() - 1)) {
						return fileName.substring(dotIndex + 1, paramIndex).toLowerCase();
					}
				}
			}

		}
		return "";
	}

	public static String getFileNameNoEx(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length()))) {
				return filename.substring(0, dot);
			}
		}
		return filename;
	}

	public static boolean sdAvailable() {
		return Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState()) || Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
	}

	public static String getFileNameForTitle(String title) {
		int lastDot = title.lastIndexOf('.');
		return lastDot > 0 ? title.substring(0, lastDot) : title;
	}

	public static File getExternalStoragePublicDirectory(String type) {
		return new File(Environment.getExternalStorageDirectory(), type);
	}

	public static int getFileAvailable(String file) {
		return getFileAvailable(new File(file));
	}

	public static int getFileAvailable(File file) {
		int ds = 0;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			ds = fis.available();
		} catch (Exception e) {
		} finally {
			try {
				if (fis != null)
					fis.close();
			} catch (Exception e) {

			}
		}
		return ds;
	}
}


text:
dir = File.expand_path(File.dirname(__FILE__))
Dir.glob("#{dir}/ruby/**/*.rb") { |f| require f }


text:
from axolotl.state.signedprekeystore import SignedPreKeyStore
from axolotl.state.signedprekeyrecord import SignedPreKeyRecord
from axolotl.invalidkeyidexception import InvalidKeyIdException
class LiteSignedPreKeyStore(SignedPreKeyStore):
    def __init__(self, dbConn):
        """
        :type dbConn: Connection
        """
        self.dbConn = dbConn
        dbConn.execute("CREATE TABLE IF NOT EXISTS signed_prekeys (_id INTEGER PRIMARY KEY AUTOINCREMENT,"
                       "prekey_id INTEGER UNIQUE, timestamp INTEGER, record BLOB);")

    def loadSignedPreKey(self, signedPreKeyId):
        q = "SELECT record FROM signed_prekeys WHERE prekey_id = ?"

        cursor = self.dbConn.cursor()
        cursor.execute(q, (signedPreKeyId,))

        result = cursor.fetchone()
        if not result:
            raise InvalidKeyIdException("No such signedprekeyrecord! %s " % signedPreKeyId)

        return SignedPreKeyRecord(serialized=result[0])

    def loadSignedPreKeys(self):
        q = "SELECT record FROM signed_prekeys"

        cursor = self.dbConn.cursor()
        cursor.execute(q,)
        result = cursor.fetchall()
        results = []
        for row in result:
            results.append(SignedPreKeyRecord(serialized=row[0]))

        return results

    def storeSignedPreKey(self, signedPreKeyId, signedPreKeyRecord):
        #q = "DELETE FROM signed_prekeys WHERE prekey_id = ?"
        #self.dbConn.cursor().execute(q, (signedPreKeyId,))
        #self.dbConn.commit()

        q = "INSERT INTO signed_prekeys (prekey_id, record) VALUES(?,?)"
        cursor = self.dbConn.cursor()
        cursor.execute(q, (signedPreKeyId, signedPreKeyRecord.serialize()))
        self.dbConn.commit()

    def containsSignedPreKey(self, signedPreKeyId):
        q = "SELECT record FROM signed_prekeys WHERE prekey_id = ?"
        cursor = self.dbConn.cursor()
        cursor.execute(q, (signedPreKeyId,))
        return cursor.fetchone() is not None

    def removeSignedPreKey(self, signedPreKeyId):
        q = "DELETE FROM signed_prekeys WHERE prekey_id = ?"
        cursor = self.dbConn.cursor()
        cursor.execute(q, (signedPreKeyId,))
        self.dbConn.commit()


text:
using Plato.Messaging.Interfaces;

namespace Plato.Messaging.RMQ.Interfaces
{
    public interface IRMQPublisherBytes : IMessageSender<byte[]>, IRMQPublisher
    {
    }
}


text:
@interface MYUniversalHelper : NSObject

+ (void)showAlertWithTitle:(NSString *)title
                   message:(NSString *)message;

+ (void)showAlertWithTitle:(NSString *)title
                   message:(NSString *)message
         cancelButtonTitle:(NSString *)cancelButtonTitle
             cancelHandler:(CancelHandler)cancelHandler;

+ (void)showAlertWithTitle:(NSString *)title
                   message:(NSString *)message
         cancelButtonTitle:(NSString *)cancelButtonTitle
             cancelHandler:(CancelHandler)cancelHandler
     completionButtonTitle:(NSString *)completionButtonTitle
         completionHandler:(CompletionHandler)completionHandler;

@end


text:
// RobotBuilder Version: 0.0.2
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in th future.
package org.usfirst.frc330.Beachbot2013Java.commands;
import edu.wpi.first.wpilibj.command.AutoSpreadsheetCommand;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc330.Beachbot2013Java.Robot;
/*
 * $Log: PickupFrisbeesOnBatteryCompensated.java,v $
 * Revision 1.1  2013-03-24 18:08:13  jross
 * Create new command for adjusting pickup speed based on linear scaling of battery voltage
 *
 * Revision 1.8  2013-03-15 02:58:07  echan
 * robotbuilder update
 *
 * Revision 1.7  2013-03-15 02:51:09  echan
 * added cvs log comments
 *
 */
/**
 *
 */
public class  PickupFrisbeesOnBatteryCompensated extends Command implements AutoSpreadsheetCommand {
    public PickupFrisbeesOnBatteryCompensated() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);

        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
        requires(Robot.frisbeePickup);
    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
    }
    // Called just before this Command runs the first time
    protected void initialize() {
        Robot.frisbeePickup.setFrisbeeTransferOutput();
    }
    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        Robot.frisbeePickup.setFrisbeePickupMotorPickupBatteryCompensated();
    }
    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }
    // Called once after isFinished returns true
    protected void end() {
        Robot.frisbeePickup.setFrisbeePickupMotorStop();
    }
    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
        end();
    }
    public void setParam1(double param1) {
    }
    public void setParam2(double param2) {
    }
    public void setParam3(double param3) {
    }
    public void setStopAtEnd(boolean stopAtEnd) {
    }
    public Command copy() {
        return new PickupFrisbeesOnBatteryCompensated();
    }
}


text:
package org.carlspring.strongbox.event;

import java.nio.file.Path;

/**
 * @author carlspring
 */
public class RepositoryBasedEvent<T extends Path> extends Event
{

    private T path;

    public RepositoryBasedEvent(T path,
                                int type)
    {
        super(type);
        this.path = path;
    }

    public T getPath()
    {
        return path;
    }

    public void setPath(T path)
    {
        this.path = path;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestCase.DataAccess.Entities.Contracts;

namespace TestCase.DataAccess.Entities.Locking
{
    /// <summary>
    /// Lock event type entity.
    /// </summary>
    /// <seealso cref="TestCase.DataAccess.Entities.Contracts.IEntity" />
    public class LockEventTypeEntity : IEntity
    {
        /// <summary>
        /// Gets or sets the identifier.
        /// </summary>
        public Guid Id { get; set; }

        /// <summary>
        /// Gets or sets the date created.
        /// </summary>
        public DateTime DateCreated { get; set; }

        /// <summary>
        /// Gets or sets the date updated.
        /// </summary>
        public DateTime DateUpdated { get; set; }

        /// <summary>
        /// Gets or sets the abrv.
        /// </summary>
        public string Abrv { get; set; }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name { get; set; }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>MerkleTree.TreeRangeIterator</title>
<meta name="date" content="2015-05-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.utils

Class MerkleTree.TreeRangeIterator

java.lang.Object

com.google.common.collect.UnmodifiableIterator<T>

com.google.common.collect.AbstractIterator<MerkleTree.TreeRange>

org.apache.cassandra.utils.MerkleTree.TreeRangeIterator

All Implemented Interfaces:

com.google.common.collect.PeekingIterator<MerkleTree.TreeRange>, java.lang.Iterable<MerkleTree.TreeRange>, java.util.Iterator<MerkleTree.TreeRange>

Enclosing class:

MerkleTree

public static class MerkleTree.TreeRangeIterator
extends com.google.common.collect.AbstractIterator<MerkleTree.TreeRange>
implements java.lang.Iterable<MerkleTree.TreeRange>, com.google.common.collect.PeekingIterator<MerkleTree.TreeRange>

Returns the leaf (range) of a given tree in increasing order.
 If the full range covered by the tree don't wrap, then it will return the
 ranges in increasing order.
 If the full range wrap, the first *and* last range returned by the
 iterator will be the wrapping range. It is the only case where the same
 leaf will be returned twice.

Method Summary

Methods

Modifier and Type
Method and Description

MerkleTree.TreeRange
computeNext()

Find the next TreeRange.

java.util.Iterator<MerkleTree.TreeRange>
iterator()

Methods inherited from class com.google.common.collect.AbstractIterator

endOfData, hasNext, next, peek

Methods inherited from class com.google.common.collect.UnmodifiableIterator

remove

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface com.google.common.collect.PeekingIterator

next, peek, remove

Methods inherited from interface java.util.Iterator

hasNext

Method Detail

computeNext

public MerkleTree.TreeRange computeNext()

Find the next TreeRange.

Specified by:

computeNext in class com.google.common.collect.AbstractIterator<MerkleTree.TreeRange>

Returns:

The next TreeRange.

iterator

public java.util.Iterator<MerkleTree.TreeRange> iterator()

Specified by:

iterator in interface java.lang.Iterable<MerkleTree.TreeRange>

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package org.dmonix.zookeeper;

import static javascalautils.TryCompanion.Success;
import static javascalautils.OptionCompanion.Option;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javascalautils.Option;
import javascalautils.Try;
import javascalautils.Unit;

/**
 * Mock implementation of {@link PropertiesStorageFactory} and {@link PropertiesStorage}.
 * @author Peter Nerg
 */
public final class MockPropertiesStorageFactory implements PropertiesStorageFactory, PropertiesStorage {

	private final Map<String, PropertySet> properties = new HashMap<>();

	public static PropertiesStorageFactory apply(String connectString) {
		return new MockPropertiesStorageFactory();
	}

	/* (non-Javadoc)
	 * @see org.dmonix.zookeeper.PropertiesStorageFactory#withRootPath(java.lang.String)
	 */
	@Override
	public PropertiesStorageFactory withRootPath(String rootPath) {
		return this;
	}

	/* (non-Javadoc)
	 * @see org.dmonix.zookeeper.PropertiesStorageFactory#create()
	 */
	@Override
	public Try<PropertiesStorage> create() {
		return Success(this);
	}

	/* (non-Javadoc)
	 * @see java.io.Closeable#close()
	 */
	@Override
	public void close() {
	}

	/* (non-Javadoc)
	 * @see org.dmonix.zookeeper.PropertiesStorage#get(java.lang.String)
	 */
	@Override
	public Try<Option<PropertySet>> get(String name) {
		return Success(Option(properties.get(name)));
	}

	/* (non-Javadoc)
	 * @see org.dmonix.zookeeper.PropertiesStorage#store(org.dmonix.zookeeper.PropertySet)
	 */
	@Override
	public Try<Unit> store(PropertySet propertySet) {
		properties.put(propertySet.name(), propertySet);
		return Success(Unit.Instance);
	}

	/* (non-Javadoc)
	 * @see org.dmonix.zookeeper.PropertiesStorage#delete(java.lang.String)
	 */
	@Override
	public Try<Unit> delete(String name) {
		properties.remove(name);
		return Success(Unit.Instance);
	}

	/* (non-Javadoc)
	 * @see org.dmonix.zookeeper.PropertiesStorage#propertySets()
	 */
	@Override
	public Try<List<String>> propertySets() {
		return Success(new ArrayList<>(properties.keySet()));
	}
}


text:
package com.silicornio.googlyeyes.dband;

public class GEModelFactory {

	/**
	 * Read the model.conf file
	 * @param path String where the file is located
	 * @return ModelConf generated
	 */
	public static GEModelConf readModelObjects(String path){

//		//get the file into a string
//		String sFile = FileReader.fileToString(path);
//		if(sFile==null){
//			JEL.e("Path of the model file is wrong");
//			return null;
//		}
//
//		//read the ModelConf
//		Gson gson = new Gson();
		return null;//gson.fromJson(sFile, ModelConf.class);
	}
	/**
	 * Find the attribute with the ID of the object given
	 * @param sModel String with the name of the model
	 * @param models ModelObject[] array of models where to search
	 * @return ModelObjectAttribute if was found or null
	 */
	public static GEModelObjectAttribute findAttributeId(String sModel, GEModelObject[] models){

		//get the model reference
		GEModelObject moRef = GEModelFactory.findObject(sModel, models);
		if(moRef!=null) {

			//get the attribute with the identifier
			return GEModelFactory.findAttributeId(moRef);
		}

		return null;
	}

	/**
	 * Find the attribute inside of a model
	 * @param nameAttribute String name of the attribute
	 * @param model ModelObject where to search
	 * @return ModelObjectAttribute found or null if it doesn't exists in the model
	 */
	public static GEModelObjectAttribute findAttribute(String nameAttribute, GEModelObject model){

		for(GEModelObjectAttribute ma : model.attributes){
			if(ma.name.equalsIgnoreCase(nameAttribute)){
				return ma;
			}
		}

		//not found
		return null;
	}

	/**
	 * Find the attribute inside of a model that is ID
	 * @param model ModelObject where to search
	 * @return ModelObjectAttribute found or null if it doesn't exists in the model
	 */
	public static GEModelObjectAttribute findAttributeId(GEModelObject model){

		for(GEModelObjectAttribute ma : model.attributes){
			if(ma.id){
				return ma;
			}
		}

		//not found
		return null;
	}

	/**
	 * Find the attribute inside of a model that is ObjectJson
	 * @param model ModelObject where to search
	 * @return ModelObjectAttribute found or null if it doesn't exists in the model
	 */
	public static GEModelObjectAttribute findAttributeObjectJson(GEModelObject model){

		for(GEModelObjectAttribute ma : model.attributes){
			if(ma.objectJson){
				return ma;
			}
		}

		//not found
		return null;
	}

	/**
	 * Find the object inside of a list of models
	 * @param nameObject String name of the attribute
	 * @param models ModelObject[] where to search
	 * @return ModelObject found or null if it doesn't exists in models
	 */
	public static GEModelObject findObject(String nameObject, GEModelObject[] models){

		//find the object
		for(GEModelObject m : models){
			if(m.name.equalsIgnoreCase(nameObject)){
				return m;
			}
		}

		//not found
		return null;
	}

}


text:
<chapter id="cxx-interface">
	<title>The C++ Interface</title>
	<sect1 id="cxx-quick-sample">
		<title>A quick sample</title>
		<blockquote>
			<title>dumptpt.cxx</title>
			<programlisting>
#include <libtpt/tpt.h>
#include <iostream>
#include <stdexcept>

// Dump the parsed template output straight to std::cout
void dumptemplate(const char* filename)
{
	try {
		// Instantiate a parser
		TPT::Parser p(filename);

		// Add an include path (only ./ searched by default)
		p.addincludepath("./include");

		// Parse the template directly to standard output
		if (p.run(std::cout))
		{
			// handle reporting of template errors
		}
	} catch(const std::exception& e) {
		std::cout << "EXCETPION: " << e.what() << std::endl;
	}
}
</programlisting>
		</blockquote>
	</sect1>
</chapter>


text:
package com.level11data.databricks.client.entities.jobs;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;

@Consumes(MediaType.APPLICATION_JSON)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CronScheduleDTO {
    @JsonProperty("quartz_cron_expression")
    public String QuartzCronExpression;

    @JsonProperty("timezone_id")
    public String TimezoneId;

    @Override
    public String toString() {
        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
        try {
            return ow.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            return "Could Not Marshal Object to JSON";
        }
    }
}


text:
import React from 'react'
import PropTypes from 'prop-types'
import { mount } from 'enzyme'
import HoC from '../HoC'
import Square from '../holders/Square'

const P = HoC('p', props => !props.children)

describe('Holdable HoC component', () => {
  it('Create correctly', () => {
    expect(P).toHaveProperty('displayName', 'Hold(p)')
    expect(P.propTypes.holder).not.toBeNull()
    expect(P.propTypes.holderProps).not.toBeNull()
    expect(P.propTypes.props).not.toBeNull()
    expect(P.propTypes.innerRef).not.toBeNull()
    expect(P.defaultProps.holder).not.toBeUndefined()
    expect(P.defaultProps.holderProps).not.toBeUndefined()
    expect(P.defaultProps.props).not.toBeUndefined()
    expect(P.defaultProps.innerRef).not.toBeUndefined()
  })

  it('Do not hold', () => {
    const wrapper = mount(<Container presentation={P}>foo</Container>)
    expect(wrapper).toMatchSnapshot()
  })

  it('Hold', () => {
    const wrapper = mount(<Container presentation={P} />)
    expect(wrapper).toMatchSnapshot()

    wrapper.setState({ children: 'I am child, then cancel hold.' })
    expect(wrapper).toMatchSnapshot()

    wrapper.setState({
      props: {
        name: 'bar',
        holder: Square,
        holderProps: {
          color: 'green',
          width: 40,
          height: 30,
        },
      },
      children: '',
    })
    expect(wrapper).toMatchSnapshot()
  })
})

class Container extends React.Component {
  constructor(...args) {
    super(...args)
    this.state = {
      props: {
        name: 'foo',
        holder: undefined,
        holderProps: null,
      },
      children: this.props.children,
    }
  }

  render() {
    const { presentation } = this.props
    const { props, children } = this.state
    return (
      <div>
        { React.createElement(presentation, props, children) }
      </div>
    )
  }
}

Container.propTypes = {
  presentation: PropTypes.func.isRequired,
  children: PropTypes.string,
}

Container.defaultProps = {
  children: '',
}


text:
var App = require('app');
var date = require('utils/date/date');

App.WizardStep9HostLogPopupBodyView = Em.View.extend({

  classNames: ['col-sm-12'],

  templateName: require('templates/wizard/step9/step9HostTasksLogPopup'),

  /**
   * Does host lost heartbeat
   * @type {bool}
   */
  isHeartbeatLost: Em.computed.equal('parentView.host.status', 'heartbeat_lost'),

  /**
   * Does host doesn't have scheduled tasks for install
   * @type {bool}
   */
  isNoTasksScheduled: Em.computed.alias('parentView.host.isNoTasksForInstall'),

  /**
   * Is log-box hidden
   * @type {bool}
   */
  isLogWrapHidden: true,

  /**
   * Is log-textarea visible
   * @type {bool}
   */
  showTextArea: false,

  /**
   * No tasks shown
   * @type {bool}
   */
  isEmptyList: true,

  /**
   * Is task logs loaded
   * @type {Boolean}
   */
  isTaskLoaded: true,

  /**
   * Checks if no visible tasks are in popup
   * @method visibleTasks
   */
  visibleTasks: function () {
    this.set("isEmptyList", true);
    if (this.get('category.value')) {
      var filter = this.get('category.value');
      var tasks = this.get('tasks');
      tasks.setEach("isVisible", false);

      if (filter == "all") {
        tasks.setEach("isVisible", true);
      }
      else if (filter == "pending") {
        tasks.filterProperty("status", "pending").setEach("isVisible", true);
        tasks.filterProperty("status", "queued").setEach("isVisible", true);
      }
      else if (filter == "in_progress") {
        tasks.filterProperty("status", "in_progress").setEach("isVisible", true);
      }
      else if (filter == "failed") {
        tasks.filterProperty("status", "failed").setEach("isVisible", true);
      }
      else if (filter == "completed") {
        tasks.filterProperty("status", "completed").setEach("isVisible", true);
      }
      else if (filter == "aborted") {
        tasks.filterProperty("status", "aborted").setEach("isVisible", true);
      }
      else if (filter == "timedout") {
        tasks.filterProperty("status", "timedout").setEach("isVisible", true);
      }

      if (tasks.filterProperty("isVisible", true).length > 0) {
        this.set("isEmptyList", false);
      }
    }
  }.observes('category', 'tasks'),

  /**
   * List categories (implements possible values for task status)
   * @type {Em.Object[]}
   */
  categories: [
    Em.Object.create({value: 'all', label: Em.I18n.t('installer.step9.hostLog.popup.categories.all') }),
    Em.Object.create({value: 'pending', label: Em.I18n.t('installer.step9.hostLog.popup.categories.pending')}),
    Em.Object.create({value: 'in_progress', label: Em.I18n.t('installer.step9.hostLog.popup.categories.in_progress')}),
    Em.Object.create({value: 'failed', label: Em.I18n.t('installer.step9.hostLog.popup.categories.failed') }),
    Em.Object.create({value: 'completed', label: Em.I18n.t('installer.step9.hostLog.popup.categories.completed') }),
    Em.Object.create({value: 'aborted', label: Em.I18n.t('installer.step9.hostLog.popup.categories.aborted') }),
    Em.Object.create({value: 'timedout', label: Em.I18n.t('installer.step9.hostLog.popup.categories.timedout') })
  ],

  /**
   * Current category
   * @type {Em.Object}
   */
  category: null,

  /**
   * List of tasks
   * @type {Em.Object[]}
   */
  tasks: function () {
    var tasksArr = [];
    var host = this.get('parentView.host');
    var tasks = this.getStartedTasks(host);
    tasks = tasks.sortProperty('Tasks.id');
    if (tasks.length) {
      tasks.forEach(function (_task) {
        var taskInfo = Em.Object.create({});
        taskInfo.set('id', _task.Tasks.id);
        taskInfo.set('requestId', _task.Tasks.request_id);
        taskInfo.set('command', _task.Tasks.command.toLowerCase() === 'service_check' ? '' : _task.Tasks.command.toLowerCase());
        taskInfo.set('commandDetail', App.format.commandDetail(_task.Tasks.command_detail, _task.Tasks.request_inputs, _task.Tasks.ops_display_name));
        taskInfo.set('status', App.format.taskStatus(_task.Tasks.status));
        taskInfo.set('role', App.format.role(_task.Tasks.role, false));
        taskInfo.set('stderr', _task.Tasks.stderr);
        taskInfo.set('stdout', _task.Tasks.stdout);
        taskInfo.set('outputLog', _task.Tasks.output_log);
        taskInfo.set('errorLog', _task.Tasks.error_log);
        taskInfo.set('startTime',  date.startTime(_task.Tasks.start_time));
        taskInfo.set('duration', date.durationSummary(_task.Tasks.start_time, _task.Tasks.end_time));
        taskInfo.set('isVisible', true);
        taskInfo.set('icon', '');
        taskInfo.set('hostName', _task.Tasks.host_name);
        if (taskInfo.get('status') == 'pending' || taskInfo.get('status') == 'queued') {
          taskInfo.set('icon', 'glyphicon glyphicon-cog');
        } else if (taskInfo.get('status') == 'in_progress') {
          taskInfo.set('icon', 'icon-cogs');
        } else if (taskInfo.get('status') == 'completed') {
          taskInfo.set('icon', 'glyphicon glyphicon-ok');
        } else if (taskInfo.get('status') == 'failed') {
          taskInfo.set('icon', 'glyphicon glyphicon-exclamation-sign');
        } else if (taskInfo.get('status') == 'aborted') {
          taskInfo.set('icon', 'glyphicon glyphicon-minus');
        } else if (taskInfo.get('status') == 'timedout') {
          taskInfo.set('icon', 'glyphicon glyphicon-time');
        }
        tasksArr.push(taskInfo);
      }, this);
    }
    this.set('isTaskLoaded', true);
    return tasksArr;
  }.property('parentView.c.logTasksChangesCounter'),

  /**
   * Navigate to task list from task view
   * @method backToTaskList
   */
  backToTaskList: function () {
    this.destroyClipBoard();
    this.set("isLogWrapHidden", true);
  },

  /**
   * Get list of host's started tasks
   * @param {object} host
   * @returns {object[]}
   * @method getStartedTasks
   */
  getStartedTasks: function (host) {
    return host.logTasks.filter(function (task) {
      return task.Tasks.status;
    });
  },

  /**
   * Open new window with task's log
   * @method openTaskLogInDialog
   */
  openTaskLogInDialog: function () {
    var newWindow = window.open();
    var newDocument = newWindow.document;
    newDocument.write('<pre>' + this.get('formattedLogsForOpenedTask') + '<pre>');
    newDocument.close();
  },

  /**
   * Currently open task
   * @type {Em.Object}
   */
  openedTask: function () {
    return this.get('tasks').findProperty('id', this.get('parentView.c.currentOpenTaskId'))
  }.property('parentView.c.currentOpenTaskId', 'tasks.[]'),

  /**
   * @type {string}
   */
  formattedLogsForOpenedTask: function () {
    var stderr = this.get('openedTask.stderr');
    var stdout = this.get('openedTask.stdout');
    return 'stderr: \n' + stderr + '\n stdout:\n' + stdout;
  }.property('openedTask.stderr', 'openedTask.stdout'),

  /**
   * Click-handler for toggle task's log view (textarea to box and back)
   * @param {object} event
   * @method toggleTaskLog
   */
  toggleTaskLog: function (event) {
    if (this.get('isLogWrapHidden')) {
      var taskInfo = event.context;
      this.set("isLogWrapHidden", false);
      this.set('parentView.c.currentOpenTaskId', taskInfo.id);
      this.set('parentView.c.currentOpenTaskRequestId', taskInfo.requestId);
      this.set('isTaskLoaded', false);
      this.get('parentView.c').loadCurrentTaskLog();
      $(".modal").scrollTop(0);
      $(".modal-body").scrollTop(0);
    }
    else {
      this.set("isLogWrapHidden", true);
      this.set('parentView.c.currentOpenTaskId', 0);
      this.set('parentView.c.currentOpenTaskRequestId', 0);
    }
  },

  /**
   * Create (if doesn't exist) or destroy (if exists) clipboard textarea
   * @method textTrigger
   */
  textTrigger: function () {
    if (this.get('showClipBoard')) {
      this.destroyClipBoard();
    }
    else {
      this.createClipBoard();
    }
  },

  /**
   * @type {boolean}
   */
  showClipBoard: false,

  /**
   * Create clipboard with task's log
   * @method createClipBoard
   */
  createClipBoard: function () {
    this.set('showClipBoard', true);
    $('.task-detail-log-maintext').css('display', 'none');
  },

  /**
   * Destroy clipboard with task's log
   * @method destroyClipBoard
   */
  destroyClipBoard: function () {
    this.set('showClipBoard', false);
    $('.task-detail-log-maintext').css('display', 'block');
  }
});


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.terin.asu_flashcardapp">

    <!-- Allows access to other API levels for backwards compatibility
    <uses-sdk android:minSdkVersion="15"
        android:targetSdkVersion="21"
        android:maxSdkVersion="25" />
    -->

    <!-- To auto-complete the email text field in the login form with the user's emails -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppMaterialTheme">
        <activity
            android:name=".LoginActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".AddCourse"></activity>
        <activity android:name=".AddDeck"></activity>
        <activity android:name=".AddCard"></activity>
        <activity android:name=".Options"></activity>
        <activity android:name=".CourseList"></activity>
        <activity android:name=".UserStats"></activity>
        <activity android:name=".CreateItems"></activity>
        <activity android:name=".CreateOptions"></activity>
        <activity android:name=".DeckList"></activity>
        <activity android:name=".StudyWindow"></activity>
    </application>

</manifest>


text:
package fr.hmil.roshttp.response

import java.nio.ByteBuffer

import fr.hmil.roshttp.BackendConfig
import fr.hmil.roshttp.exceptions.ResponseException
import fr.hmil.roshttp.util.{HeaderMap, Utils}
import monix.execution.Scheduler
import monix.reactive.Observable

import scala.collection.mutable
import scala.concurrent.{Future, Promise}
import scala.util.{Failure, Success}

/**
 * An HTTP response obtained via an [[fr.hmil.roshttp.HttpRequest]]
 */
class SimpleHttpResponse(
    val statusCode: Int,
    val headers: HeaderMap[String],
    val body: String)
  extends HttpResponse

object SimpleHttpResponse extends HttpResponseFactory[SimpleHttpResponse] {
  override def apply(
      header: HttpResponseHeader,
      bodyStream: Observable[ByteBuffer],
      config: BackendConfig)
      (implicit scheduler: Scheduler): Future[SimpleHttpResponse] = {

    val charset = Utils.charsetFromContentType(header.headers.getOrElse("content-type", null))
    val buffers = mutable.Queue[ByteBuffer]()
    val promise = Promise[SimpleHttpResponse]()

    val streamCollector = bodyStream.
      foreach(elem => buffers.enqueue(elem)).
      map({_ =>
        val body = recomposeBody(buffers, config.maxChunkSize, charset)
        new SimpleHttpResponse(header.statusCode, header.headers, body)
      })

    streamCollector.onComplete({
      case res:Success[SimpleHttpResponse] =>
        promise.trySuccess(res.value)
      case e:Failure[_] =>
        promise.tryFailure(new ResponseException(e.exception, header))
    })

    promise.future
  }

  private def recomposeBody(seq: mutable.Queue[ByteBuffer], maxChunkSize: Int, charset: String): String = {
    // Allocate maximum expected body length
    val buffer = ByteBuffer.allocate(seq.length * maxChunkSize)
    val totalBytes = seq.foldLeft(0)({ (count, chunk) =>
      buffer.put(chunk)
      count + chunk.limit()
    })
    buffer.limit(totalBytes)
    Utils.getStringFromBuffer(buffer, charset)
  }
}


text:
<!DOCTYPE html>

      <title>Destinatii</title>

        <link rel="stylesheet" href="style1.css" >
        <link rel="stylesheet" href="style2.css" >
         <link rel="stylesheet" href="fa/css/font-awesome.css">

Acasa

Destinatii

Cazare

Destinatii

Cinque Terre, Italia

Promenade des Anglais, Nisa, Franţa

Praga, Republica Cehă

Shanghai, China

Jakarta, Indonesia

Abu Simbel, Egipt

Durban

Parcul National Kruger

Washington, SUA

Montreal

Miami

Salta, Argentina

Santiago de Chile, Chile

Rio de Janeiro, Brazilia

Seul, Coreea de Sud


text:
var text, start, el, demo, i;

i = 0;
start = 'http://mywebsite.com/page.html';
text = '#edit';

// initialize
el = document.getElementById('edit-text');
demo = document.getElementById('flip-demo');
el.innerHTML = start;

function startOver(){
    demo.removeAttribute('hero-card-flipped');
    demo.removeAttribute('active', '');
    el.innerHTML = start;
    i=0;

    setTimeout(type, 500);
}

// flip
function flip(){
    var el;

    demo = document.getElementById('flip-demo');

    // toggle attribute
    if(demo.hasAttribute('hero-card-flipped')){
      demo.removeAttribute('hero-card-flipped');

    }
    else{
      demo.setAttribute('hero-card-flipped', '');

      setTimeout(startOver, 10000);
    }
}

function type(){

    if(el.innerHTML.length < (start.length + text.length)){

      // add text
      el.innerHTML = el.innerHTML + text.charAt(i);
      i++;

      setTimeout(type, 80);
    }
    else{

      setTimeout(function(){
        demo.setAttribute('active', '');
      }, 300);

      setTimeout(flip, 800);
    }

}

setTimeout(type, 500);


text:
int main()
{
	int range = 100;
	int number = 10;
	auto t1 = chrono::steady_clock::now();
	LinkedList l = LinkedList(number, range);
	l.visitNode();
	system("pause");

	Binarytree b(range, number);
	//cout <<
	b.visitLeft();
	b.visitRight();
	TreeNode* node = b.topNode();
	cout << "node count: " << b.count(node) << endl;
	cout << "tree height: " << b.height(node) << endl;
	//TreeNode* max_node = b.maxNode(node);
	//cout << "max node: " << max_node->data << endl;
	//cout << "visit node: " << b.visitTree(node) << endl;
	b.visitTree(node);
	//auto t2 = chrono::steady_clock::now();
	//cout << point::run_time(t1, t2) << endl;
	system("pause");
	return 0;
}


text:
package main

import (
	"bufio"
	"io"
	"os"
	"os/exec"
	"regexp"

	fmt "github.com/jhunt/go-ansi"

	"github.com/shieldproject/shield/plugin"
)

var (
	DefaultPort = "5432"
)

func main() {
	p := PostgresPlugin{
		Name:    "PostgreSQL Backup Plugin",
		Author:  "SHIELD Core Team",
		Version: "0.0.1",
		Features: plugin.PluginFeatures{
			Target: "yes",
			Store:  "no",
		},
		Example: `
{
  "pg_user"     : "username",   # REQUIRED

  "pg_password" : "password",
  "pg_host"     : "10.0.0.1",
  "pg_port"     : "5432",             # Port that PostgreSQL is listening on
  "pg_database" : "db1",              # Limit backup/restore operation to this database
  "pg_bindir"   : "/path/to/pg/bin"   # Where to find the psql command
  "pg_options"  : "",                 # optional
}
`,
		Defaults: `
{
  "pg_port"   : "5432",
  "pg_bindir" : "/var/vcap/packages/postgres-9.4/bin"
}
`,
		Fields: []plugin.Field{
			plugin.Field{
				Mode:  "target",
				Name:  "pg_host",
				Type:  "string",
				Title: "PostgreSQL Host",
				Help:  "The hostname or IP address of your PostgreSQL server.",
			},
			plugin.Field{
				Mode:    "target",
				Name:    "pg_port",
				Type:    "port",
				Title:   "PostgreSQL Port",
				Help:    "The TCP port that PostgreSQL is bound to, listening for incoming connections.",
				Default: "5432",
			},
			plugin.Field{
				Mode:     "target",
				Name:     "pg_user",
				Type:     "string",
				Title:    "PostgreSQL Username",
				Help:     "Username to authenticate to PostgreSQL as.",
				Required: true,
			},
			plugin.Field{
				Mode:  "target",
				Name:  "pg_password",
				Type:  "password",
				Title: "PostgreSQL Password",
				Help:  "Password to authenticate to PostgreSQL as.",
			},
			plugin.Field{
				Mode:  "target",
				Name:  "pg_database",
				Type:  "string",
				Title: "Database to Backup",
				Help:  "Limit scope of the backup to include only this database.  By default, all databases will be backed up.",
			},
			plugin.Field{
				Mode:  "target",
				Name:  "pg_read_replica_host",
				Type:  "string",
				Title: "Postgres Read Replica (Host)",
				Help:  "An optional Postgres replica (possibly readonly) to use for backups, instead of the canonical host.  Restore operations will still be conducted against the real database host.",
			},
			plugin.Field{
				Mode:  "target",
				Name:  "pg_read_replica_port",
				Type:  "string",
				Title: "Postgres Read Replica (Port)",
				Help:  "An optional Postgres replica (possibly readonly) to use for backups, instead of the canonical host.  Restore operations will still be conducted against the real database host.",
			},
			plugin.Field{
				Mode:    "target",
				Name:    "pg_options",
				Type:    "string",
				Title:   "Additional `pg_dump` options",
				Help:    "You can tune `pg_dump` (which performs the backup) by specifying additional options and command-line arguments.  If you don't know why you might need this, leave it blank.",
				Example: "--data-only",
			},
			plugin.Field{
				Mode:    "target",
				Name:    "pg_bindir",
				Type:    "abspath",
				Title:   "Path to PostgreSQL bin/ directory",
				Help:    "The absolute path to the bin/ directory that contains the `psql` command.",
				Default: "/var/vcap/packages/postgres-9.4/bin",
			},
		},
	}

	plugin.Run(p)
}

type PostgresPlugin plugin.PluginInfo

type PostgresConnectionInfo struct {
	Host        string
	Port        string
	User        string
	Password    string
	Bin         string
	ReplicaHost string
	ReplicaPort string
	Database    string
	Options     string
}

func (p PostgresPlugin) Meta() plugin.PluginInfo {
	return plugin.PluginInfo(p)
}

func (p PostgresPlugin) Validate(endpoint plugin.ShieldEndpoint) error {
	var (
		s    string
		err  error
		fail bool
	)

	s, err = endpoint.StringValueDefault("pg_host", "")
	if err != nil {
		fmt.Printf("@R{\u2717 pg_host      %s}\n", err)
		fail = true
	} else if s == "" {
		fmt.Printf("@G{\u2713 pg_host}      using @C{localhost}\n")
	} else {
		fmt.Printf("@G{\u2713 pg_host}      @C{%s}\n", s)
	}

	s, err = endpoint.StringValueDefault("pg_port", "")
	if err != nil {
		fmt.Printf("@R{\u2717 pg_port      %s}\n", err)
		fail = true
	} else if s == "" {
		fmt.Printf("@G{\u2713 pg_port}      using default port @C{%s}\n", DefaultPort)
	} else {
		fmt.Printf("@G{\u2713 pg_port}      @C{%s}\n", s)
	}

	s, err = endpoint.StringValue("pg_user")
	if err != nil {
		fmt.Printf("@R{\u2717 pg_user      %s}\n", err)
		fail = true
	} else {
		fmt.Printf("@G{\u2713 pg_user}      @C{%s}\n", plugin.Redact(s))
	}

	s, err = endpoint.StringValueDefault("pg_password", "")
	if err != nil {
		fmt.Printf("@R{\u2717 pg_password  %s}\n", err)
		fail = true
	} else if s == "" {
		fmt.Printf("@G{\u2713 pg_password}  none (no credentials will be sent)\n")
	} else {
		fmt.Printf("@G{\u2713 pg_password}  @C{%s}\n", plugin.Redact(s))
	}

	s, err = endpoint.StringValueDefault("pg_database", "")
	if err != nil {
		fmt.Printf("@R{\u2717 pg_database  %s}\n", err)
	} else if s == "" {
		fmt.Printf("@G{\u2713 pg_database}  none (all databases will be backed up)\n")
	} else {
		fmt.Printf("@G{\u2713 pg_database}  @C{%s}\n", s)
	}

	s, err = endpoint.StringValueDefault("pg_read_replica_host", "")
	if err != nil {
		fmt.Printf("@R{\u2717 pg_read_replica_host  %s}\n", err)
		fail = true
	} else if s == "" {
		fmt.Printf("@G{\u2713 pg_read_replica_host}  no read replica given\n")
	} else {
		fmt.Printf("@G{\u2713 pg_read_replica_host}  @C{%s}\n", plugin.Redact(s))
	}

	s, err = endpoint.StringValueDefault("pg_read_replica_port", "")
	if err != nil {
		fmt.Printf("@R{\u2717 pg_read_replica_port  %s}\n", err)
		fail = true
	} else if s == "" {
		fmt.Printf("@G{\u2713 pg_read_replica_port}  no read replica given\n")
	} else {
		fmt.Printf("@G{\u2713 pg_read_replica_port}  @C{%s}\n", plugin.Redact(s))
	}

	s, err = endpoint.StringValueDefault("pg_options", "")
	if err != nil {
		fmt.Printf("@R{\u2717 pg_options  %s}\n", err)
		fail = true
	} else if s == "" {
		fmt.Printf("@G{\u2713 pg_options}  no options given\n")
	} else {
		fmt.Printf("@G{\u2713 pg_options}  @C{%s}\n", s)
	}

	if fail {
		return fmt.Errorf("postgres: invalid configuration")
	}
	return nil
}

func (p PostgresPlugin) Backup(endpoint plugin.ShieldEndpoint) error {
	pg, err := pgConnectionInfo(endpoint)
	if err != nil {
		return err
	}

	if pg.ReplicaHost != "" && pg.ReplicaPort != "" {
		plugin.DEBUG("Using readonly replica -> `%s`", plugin.Redact(fmt.Sprintf("%s:%s", pg.Host, pg.Port)))
		pg.Host = pg.ReplicaHost
		pg.Port = pg.ReplicaPort
	}

	setupEnvironmentVariables(pg)

	cmd := ""
	if pg.Database != "" {
		// Run dump all on the specified db
		cmd = fmt.Sprintf("%s/pg_dump %s -C -c --no-password %s", pg.Bin, pg.Database, pg.Options)
	} else {
		// Else run dump on all
		cmd = fmt.Sprintf("%s/pg_dumpall -c --no-password %s", pg.Bin, pg.Options)
	}
	plugin.DEBUG("Executing: `%s`", cmd)
	return plugin.Exec(cmd, plugin.STDOUT)
}

func (p PostgresPlugin) Restore(endpoint plugin.ShieldEndpoint) error {
	pg, err := pgConnectionInfo(endpoint)
	if err != nil {
		return err
	}

	setupEnvironmentVariables(pg)

	cmd := exec.Command(fmt.Sprintf("%s/psql", pg.Bin), "-d", "postgres")
	plugin.DEBUG("Exec: %s/psql -d postgres", pg.Bin)
	plugin.DEBUG("Redirecting stdout and stderr to stderr")
	cmd.Stdout = os.Stderr
	cmd.Stderr = os.Stderr
	stdin, err := cmd.StdinPipe()
	if err != nil {
		return err
	}
	scanErr := make(chan error)
	go func(out io.WriteCloser, in io.Reader, errChan chan<- error) {
		plugin.DEBUG("Starting to read SQL statements from stdin...")
		r := bufio.NewReader(in)
		reg := regexp.MustCompile("^DROP DATABASE (.*);$")
		i := 0
		for {
			thisLine := []byte{}
			isPrefix := true
			var err error
			for isPrefix {
				var tmpLine []byte
				tmpLine, isPrefix, err = r.ReadLine()
				if err != nil {
					if err == io.EOF {
						goto eof
					}
					errChan <- err
					return
				}
				thisLine = append(thisLine, tmpLine...)
			}
			m := reg.FindStringSubmatch(string(thisLine))
			if len(m) > 0 {
				plugin.DEBUG("Found dropped database '%s' on line %d", m[1], i)
				out.Write([]byte(fmt.Sprintf("UPDATE pg_database SET datallowconn = 'false' WHERE datname = '%s';\n", m[1])))
				out.Write([]byte(fmt.Sprintf("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '%s';\n", m[1])))
			}
			_, err = out.Write([]byte(string(thisLine) + "\n"))
			if err != nil {
				plugin.DEBUG("Error when writing to output: %s", err)
				errChan <- err
				return
			}
			i++
		}
	eof:
		plugin.DEBUG("Completed restore with %d lines of SQL", i)
		out.Close()
		errChan <- nil
	}(stdin, os.Stdin, scanErr)
	err = cmd.Run()
	if err != nil {
		return err
	}
	return <-scanErr
}

func (p PostgresPlugin) Store(endpoint plugin.ShieldEndpoint) (string, int64, error) {
	return "", 0, plugin.UNIMPLEMENTED
}

func (p PostgresPlugin) Retrieve(endpoint plugin.ShieldEndpoint, file string) error {
	return plugin.UNIMPLEMENTED
}

func (p PostgresPlugin) Purge(endpoint plugin.ShieldEndpoint, file string) error {
	return plugin.UNIMPLEMENTED
}

func setupEnvironmentVariables(pg *PostgresConnectionInfo) {
	plugin.DEBUG("Setting up env:\n   PGUSER=%s, PGPASSWORD=%s, PGHOST=%s, PGPORT=%s", pg.User, pg.Password, pg.Host, pg.Port)

	os.Setenv("PGUSER", pg.User)
	os.Setenv("PGPASSWORD", pg.Password)
	os.Setenv("PGHOST", pg.Host)
	os.Setenv("PGPORT", pg.Port)
}

func pgConnectionInfo(endpoint plugin.ShieldEndpoint) (*PostgresConnectionInfo, error) {
	user, err := endpoint.StringValue("pg_user")
	if err != nil {
		return nil, err
	}
	plugin.DEBUG("PGUSER: '%s'", user)

	password, err := endpoint.StringValueDefault("pg_password", "")
	if err != nil {
		return nil, err
	}
	plugin.DEBUG("PGPASSWORD: '%s'", password)

	host, err := endpoint.StringValueDefault("pg_host", "")
	if err != nil {
		return nil, err
	}
	plugin.DEBUG("PGHOST: '%s'", host)

	port, err := endpoint.StringValueDefault("pg_port", DefaultPort)
	if err != nil {
		return nil, err
	}
	plugin.DEBUG("PGPORT: '%s'", port)

	replicahost, err := endpoint.StringValueDefault("pg_read_replica_host", "")
	if err != nil {
		return nil, err
	}
	plugin.DEBUG("PG_READ_REPLICA_HOST: '%s'", replicahost)

	replicaport, err := endpoint.StringValueDefault("pg_read_replica_port", "")
	if err != nil {
		return nil, err
	}
	plugin.DEBUG("PG_READ_REPLICA_PORT: '%s'", replicaport)

	options, err := endpoint.StringValueDefault("pg_options", "")
	if err != nil {
		return nil, err
	}
	plugin.DEBUG("PG_OPTIONS: '%s'", options)

	database, err := endpoint.StringValueDefault("pg_database", "")
	if err != nil {
		return nil, err
	}
	plugin.DEBUG("PGDATABASE: '%s'", database)

	bin, err := endpoint.StringValueDefault("pg_bindir", "/var/vcap/packages/postgres-9.4/bin")
	if err != nil {
		return nil, err
	}
	plugin.DEBUG("PGBINDIR: '%s'", bin)

	return &PostgresConnectionInfo{
		Host:        host,
		Port:        port,
		User:        user,
		Password:    password,
		ReplicaHost: replicahost,
		ReplicaPort: replicaport,
		Bin:         bin,
		Database:    database,
		Options:     options,
	}, nil
}


text:
Mathematical formulation
------------------------

This section details the mathematical formulation of the different components. For each component, a link to the actual implementing function in the Calliope code is given.

Decision variables
------------------

.. automodule:: calliope.backend.pyomo.variables
    :members:

Objective functions
-------------------

.. automodule:: calliope.backend.pyomo.objective
    :members:

.. _api_constraints:

Constraints
===========

Energy Balance
--------------

.. automodule:: calliope.backend.pyomo.constraints.energy_balance
    :members:

.. _constraint_capacity:

Capacity
--------

.. automodule:: calliope.backend.pyomo.constraints.capacity
    :members:

Dispatch
--------

.. automodule:: calliope.backend.pyomo.constraints.dispatch
    :members:

Costs
-----

.. automodule:: calliope.backend.pyomo.constraints.costs
    :members:

Export
------

.. automodule:: calliope.backend.pyomo.constraints.export
    :members:

MILP
----

.. automodule:: calliope.backend.pyomo.constraints.milp
    :members:

Conversion
----------

.. automodule:: calliope.backend.pyomo.constraints.conversion
    :members:

Conversion_plus
---------------

.. automodule:: calliope.backend.pyomo.constraints.conversion_plus
    :members:

Network
-------

.. automodule:: calliope.backend.pyomo.constraints.network
    :members:

Policy
------

.. automodule:: calliope.backend.pyomo.constraints.policy
    :members:


text:
<?php

namespace App\Http\Controllers;

use App\Topping;
use Illuminate\Http\Request;

class ToppingsController extends Controller
{

	public function __construct()
	{
		$this->middleware('admin')->except([
			'index', 'show'
		]);
	}

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.createTopping');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
	{
		$this->validate($request, [
			'name' => 'required|unique:toppings',
			'price' => 'required|numeric'
		]);

		Topping::create($request->all());

		return redirect('/manage/toppings');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Topping  $topping
     * @return \Illuminate\Http\Response
     */
    public function show(Topping $topping)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Topping  $topping
     * @return \Illuminate\Http\Response
     */
    public function edit(Topping $topping)
    {
		return view('admin.editTopping')->withTopping($topping);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Topping  $topping
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Topping $topping)
    {
		$this->validate($request, [
			'name' => 'required',
			'price' => 'required|min:0|numeric'
		]);

		$topping->name = $request->name;
		$topping->price = $request->price;
		$topping->save();

		return redirect('/manage/toppings');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Topping  $topping
     * @return \Illuminate\Http\Response
     */
    public function destroy(Topping $topping)
    {
		$topping->delete();

		return redirect('/manage/toppings');
    }
}


text:
<?php
/**
 * Description of FileManager
 *
 * @author Christian Hiroz
 */

namespace Elton\CoreBundle\Manager;

use Doctrine\ORM\EntityManager;

class JumbotronManager extends CoreManager{
    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function getRepository()
    {
        return $this->em->getRepository('EltonCoreBundle:Jumbotron');
    }
}


text:
behave is behaviour-driven development, Python style.

@see
* http://pythonhosted.org/behave/
* http://jenisys.github.io/behave.example/
* http://tott-meetup.readthedocs.org/en/latest/sessions/behave.html


text:
package com.bitunified.ledconfig.domain.product.PCB.types;

import com.bitunified.ledconfig.domain.Dimension;
import com.bitunified.ledconfig.domain.Property;
import com.bitunified.ledconfig.domain.product.PCB.LedStrip;

public class PowerLedStrip extends LedStrip {

    public PowerLedStrip() {
        super();
    }

    public PowerLedStrip(Dimension dimension) {
        super(dimension);
        addProperty(COLOR);

    }
}


text:
#ifndef LINALG_CONSTS_H
#define LINALG_CONSTS_H

#define FORTRANIZE(name) name ## _

#endif


text:
package org.gradle.api.internal.artifacts.result;

import org.gradle.api.artifacts.component.ComponentSelector;
import org.gradle.api.artifacts.result.ResolvedComponentResult;
import org.gradle.api.artifacts.result.ResolvedDependencyResult;
import org.gradle.api.artifacts.result.ResolvedVariantResult;

public class DefaultResolvedDependencyResult extends AbstractDependencyResult implements ResolvedDependencyResult {
    private final ResolvedComponentResult selectedComponent;
    private final ResolvedVariantResult selectedVariant;

    public DefaultResolvedDependencyResult(ComponentSelector requested,
                                           boolean constraint,
                                           ResolvedComponentResult selectedComponent,
                                           ResolvedVariantResult selectedVariant,
                                           ResolvedComponentResult from) {
        super(requested, from, constraint);
        this.selectedComponent = selectedComponent;
        this.selectedVariant = selectedVariant;
    }

    @Override
    public ResolvedComponentResult getSelected() {
        return selectedComponent;
    }

    public ResolvedVariantResult getResolvedVariant() {
        return selectedVariant;
    }

    @Override
    public String toString() {
        if (getRequested().matchesStrictly(getSelected().getId())) {
            return getRequested().toString();
        } else {
            return getRequested() + " -> " + getSelected().getId();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using GlyssenCharacters;
using GlyssenCharactersTests.Properties;
using NUnit.Framework;
using SIL.Xml;

namespace GlyssenCharactersTests
{
	class RelatedCharactersTests
	{

		[OneTimeSetUp]
		public void OneTimeSetUp()
		{
			// Use a test version of the file so the tests won't break every time we fix a problem in the production control file.
			RelatedCharactersData.Source = Resources.TestRelatedCharacters;
		}

		[Test]
		public void Serialize()
		{
			HashSet<RelatedCharacters> set = new HashSet<RelatedCharacters>
			{
				new RelatedCharacters
				{
					CharacterIds = new List<string> { "David", "David (old)" },
					RelationshipType = CharacterRelationshipType.SameCharacterWithMultipleAges
				}
			};
			var serializedString = XmlSerializationHelper.SerializeToString(set);
			Assert.That(serializedString.IndexOf("<RelatedCharacters RelationshipType=\"SameCharacterWithMultipleAges\">",
				StringComparison.Ordinal), Is.GreaterThanOrEqualTo(0));
			Assert.That(serializedString.IndexOf("<CharacterId>David</CharacterId>",
				StringComparison.Ordinal), Is.GreaterThanOrEqualTo(0));
			Assert.That(serializedString.IndexOf("<CharacterId>David (old)</CharacterId>",
				StringComparison.Ordinal), Is.GreaterThanOrEqualTo(0));
		}

		[Test]
		public void GetAll()
		{
			var allRelatedCharactersSet = RelatedCharactersData.Singleton.GetAll();
			Assert.Greater(allRelatedCharactersSet.Count, 0);

			var davidRelatedCharacters = allRelatedCharactersSet.First(rc => rc.CharacterIds.Contains("David"));
			Assert.True(davidRelatedCharacters.CharacterIds.Contains("David (old)"));
			Assert.AreEqual(CharacterRelationshipType.SameCharacterWithMultipleAges, davidRelatedCharacters.RelationshipType);
		}

		[Test]
		public void GetCharacterIdsForType()
		{
			var characterIds = RelatedCharactersData.Singleton.GetCharacterIdsForType(CharacterRelationshipType.SameCharacterWithMultipleAges);
			Assert.AreEqual(14, characterIds.Count);
			Assert.True(characterIds.Contains("David"));
			Assert.True(characterIds.Contains("David (old)"));
		}

		[Test]
		public void GetCharacterIdToRelatedCharactersDictionary()
		{
			var dictionary = RelatedCharactersData.Singleton.GetCharacterIdToRelatedCharactersDictionary();
			Assert.AreEqual(14, dictionary.Count);
			Assert.True(dictionary["David (old)"].Single().CharacterIds.Contains("David"));
		}
	}
}