text:
package com.snowplowanalytics.snowplow.event;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.snowplowanalytics.snowplow.internal.constants.Parameters;
import com.snowplowanalytics.snowplow.internal.constants.TrackerConstants;
import com.snowplowanalytics.snowplow.internal.utils.Preconditions;

import java.util.HashMap;
import java.util.Map;

/** An ecommerce item event. */
public class EcommerceTransactionItem extends AbstractPrimitive {

    /** Stock Keeping Unit of the item. */
    @NonNull
    public final String sku;
    /** Price of the item. */
    @NonNull
    public final Double price;
    /** Quantity of the item. */
    @NonNull
    public final Integer quantity;
    /** Name of the item. */
    @Nullable
    public String name;
    /** Category of the item. */
    @Nullable
    public String category;
    /** Currency used for the price of the item. */
    @Nullable
    public String currency;
    /** OrderID of the order that contains this item. */
    @Nullable
    public String orderId;

    /**
     Creates an ecommerce item event.
     @param sku Stock Keeping Unit of the item.
     @param price Price of the item.
     @param quantity Quantity of the item.
     */
    public EcommerceTransactionItem(@NonNull String sku, double price, int quantity) {
        Preconditions.checkNotNull(sku);
        Preconditions.checkArgument(!sku.isEmpty(), "sku cannot be empty");
        this.sku = sku;
        this.price = price;
        this.quantity = quantity;
    }

    // Builder methods

    /** Name of the item. */
    @NonNull
    public EcommerceTransactionItem name(@Nullable String name) {
        this.name = name;
        return this;
    }

    /** Category of the item. */
    @NonNull
    public EcommerceTransactionItem category(@Nullable String category) {
        this.category = category;
        return this;
    }

    /** Currency used for the price of the item. */
    @NonNull
    public EcommerceTransactionItem currency(@Nullable String currency) {
        this.currency = currency;
        return this;
    }

    /** OrderID of the order that contains this item. */
    @NonNull
    public EcommerceTransactionItem orderId(@Nullable String orderId) {
        this.orderId = orderId;
        return this;
    }

    // Public methods

    @Override
    public @NonNull Map<String, Object> getDataPayload() {
        HashMap<String, Object> payload = new HashMap<>();
        if (orderId != null) payload.put(Parameters.TI_ITEM_ID, orderId);
        payload.put(Parameters.TI_ITEM_SKU, sku);
        payload.put(Parameters.TI_ITEM_PRICE, Double.toString(price));
        payload.put(Parameters.TI_ITEM_QUANTITY, Integer.toString(quantity));
        if (name != null) payload.put(Parameters.TI_ITEM_NAME, name);
        if (category != null) payload.put(Parameters.TI_ITEM_CATEGORY, category);
        if (currency != null) payload.put(Parameters.TI_ITEM_CURRENCY, currency);
        return payload;
    }

    @Override
    public @NonNull String getName() {
        return TrackerConstants.EVENT_ECOMM_ITEM;
    }
}


text:
package com.squeezer.designpatterns.singleton;

public class Singleton {

    private static Singleton mInstance;
    private String mMessage;

    private Singleton() {

    }

    public static Singleton getInstance() {

        if (mInstance == null) {
            mInstance = new Singleton();
        }
        return mInstance;
    }

    public String getMessage() {
        return mMessage;
    }

    public void setMessage(String message) {
        mMessage = message;
    }

}

redpajama_set_name: RedPajamaGithub


text:
ActiveRecord::Schema.define(version: 20151227104346) do

  create_table "books", force: :cascade do |t|
    t.string "title", null: false
  end

  create_table "books_patterns", force: :cascade do |t|
    t.integer "page_number", default: 0, null: false
    t.integer "patterns_id"
    t.integer "books_id"
  end

  add_index "books_patterns", ["books_id"], name: "index_books_patterns_on_books_id"
  add_index "books_patterns", ["patterns_id"], name: "index_books_patterns_on_patterns_id"

  create_table "categories", force: :cascade do |t|
    t.string  "name"
    t.integer "parent_id"
    t.integer "lft",                        null: false
    t.integer "rgt",                        null: false
    t.integer "depth",          default: 0, null: false
    t.integer "children_count", default: 0, null: false
  end

  add_index "categories", ["lft"], name: "index_categories_on_lft"
  add_index "categories", ["parent_id"], name: "index_categories_on_parent_id"
  add_index "categories", ["rgt"], name: "index_categories_on_rgt"

  create_table "patterns", force: :cascade do |t|
    t.string "name",     null: false
    t.float  "mingauge", null: false
    t.float  "maxgauge", null: false
  end

end


text:
	%include templates/parts/head.html

	%include templates/parts/navBar.html

						Midterm Info

						February 17, 2017

Logistics

							The CS106X Midterm is Thursday February 23rd from 7pm to 9pm.

                                                The exam will be in 370-370:

The exam is open book, open notes, closed computer.

							Midterm

							Thur, Feb. 23rd

							7-9pm

							370-370

							Midterm Review Session

							Mon, Feb. 20th

							7:30pm-8:30pm

							Room TBA

Topics

The midterm covers the material presented in class through the lecture on Wednesday,
Feb. 15th. Specifically you will be responsible for:

Functions and Pass by Reference

Big O

Use of Collections (Maps, Sets, Stacks, Queues, Vectors and Grids)

Recursion (Definition and Fractals)

Recursive Exploration and Backtracking

Structs and Classes

Linked Lists

The bulk of the midterm will be build on the concepts you covered in the assignments you have completed up to this point in the course (Fauxtoshop, WordLadder/Ngrams/Cipher, Recursion, Backtracking).

					We put together handouts on the topics which we will expect you to know:

Functions

Collections

Recursion

Exploration

Big O

Strategies

					Exams are exciting, and a good chance to learn. Sometimes they can feel competitive. Remember though that in the long term you aren't competing against the other people in the classroom. In fact they will probably be your team mates in the post Stanford world. The only race is with yourself. We don't curve the exam. If everyone does a great job of demonstrating that they understand the material, everyone will get a better grade.

Here is a printable handout with a complete list of all CS106X library functions you may find useful on the exam and a handout on exam strategies:

									Reference Sheet

									Exam Strategies

Practice Midterms

									Practice #1

									Practice Soln #1

									Practice #2

									Practice Soln #2

									Practice #3

									Practice Soln #3

		%include templates/parts/footer.html


text:
using System;
using System.Reflection;
using Apaf.NFSdb.Core.Column;

namespace Apaf.NFSdb.Core.Configuration
{
    public interface IClassColumnSerializerMetadata : IColumnSerializerMetadata
    {
        MethodInfo GetSetMethod();
        MethodInfo GetGetMethod();
        Type DataType { get; }
        string FieldName { get; }
        bool IsRefType();
    }
}


text:
<?php

// Protect from unauthorized access
defined('F0F_INCLUDED') or die;

/**
 * Form Field class for F0F
 * Renders the row ordering interface checkbox in browse views
 *
 * @package  FrameworkOnFramework
 * @since    2.0
 */
class F0FFormFieldOrdering extends JFormField implements F0FFormField
{
	protected $static;

	protected $repeatable;

	/** @var   F0FTable  The item being rendered in a repeatable form field */
	public $item;

	/** @var int A monotonically increasing number, denoting the row number in a repeatable view */
	public $rowid;

	/**
	 * Method to get certain otherwise inaccessible properties from the form field object.
	 *
	 * @param   string  $name  The property name for which to the the value.
	 *
	 * @return  mixed  The property value or null.
	 *
	 * @since   2.0
	 */
	public function __get($name)
	{
		switch ($name)
		{
			case 'static':
				if (empty($this->static))
				{
					$this->static = $this->getStatic();
				}

				return $this->static;
				break;

			case 'repeatable':
				if (empty($this->repeatable))
				{
					$this->repeatable = $this->getRepeatable();
				}

				return $this->repeatable;
				break;

			default:
				return parent::__get($name);
		}
	}

	/**
	 * Method to get the field input markup for this field type.
	 *
	 * @since 2.0
	 *
	 * @return  string  The field input markup.
	 */
	protected function getInput()
	{
		$html = array();
		$attr = '';

		// Initialize some field attributes.
		$attr .= !empty($this->class) ? ' class="' . $this->class . '"' : '';
		$attr .= $this->disabled ? ' disabled' : '';
		$attr .= !empty($this->size) ? ' size="' . $this->size . '"' : '';

		// Initialize JavaScript field attributes.
		$attr .= !empty($this->onchange) ? ' onchange="' . $this->onchange . '"' : '';

		$this->item = $this->form->getModel()->getItem();

		$keyfield = $this->item->getKeyName();
		$itemId   = $this->item->$keyfield;

		$query = $this->getQuery();

		// Create a read-only list (no name) with a hidden input to store the value.
		if ($this->readonly)
		{
			$html[] = JHtml::_('list.ordering', '', $query, trim($attr), $this->value, $itemId ? 0 : 1);
			$html[] = '<input type="hidden" name="' . $this->name . '" value="' . $this->value . '"/>';
		}
		else
		{
			// Create a regular list.
			$html[] = JHtml::_('list.ordering', $this->name, $query, trim($attr), $this->value, $itemId ? 0 : 1);
		}

		return implode($html);
	}

	/**
	 * Get the rendering of this field type for static display, e.g. in a single
	 * item view (typically a "read" task).
	 *
	 * @since 2.0
	 *
	 * @return  string  The field HTML
	 */
	public function getStatic()
	{
		throw new Exception(__CLASS__ . ' cannot be used in single item display forms');
	}

	/**
	 * Get the rendering of this field type for a repeatable (grid) display,
	 * e.g. in a view listing many item (typically a "browse" task)
	 *
	 * @since 2.0
	 *
	 * @return  string  The field HTML
	 */
	public function getRepeatable()
	{
		if (!($this->item instanceof F0FTable))
		{
			throw new Exception(__CLASS__ . ' needs a F0FTable to act upon');
		}

		$class = isset($this->element['class']) ? $this->element['class'] : 'input-mini';
		$icon  = isset($this->element['icon']) ? $this->element['icon'] : 'icon-menu';

		$html = '';

		$view = $this->form->getView();

		$ordering = $view->getLists()->order == 'ordering';

		if (!$view->hasAjaxOrderingSupport())
		{
			// Ye olde Joomla! 2.5 method
			$disabled = $ordering ? '' : 'disabled="disabled"';
			$html .= '';
			$html .= $view->pagination->orderUpIcon($this->rowid, true, 'orderup', 'Move Up', $ordering);
			$html .= '';
			$html .= $view->pagination->orderDownIcon($this->rowid, $view->pagination->total, true, 'orderdown', 'Move Down', $ordering);
			$html .= '';
			$html .= '<input type="text" name="order[]" size="5" value="' . $this->value . '" ' . $disabled;
			$html .= 'class="text-area-order" style="text-align: center" />';
		}
		else
		{
			// The modern drag'n'drop method
			if ($view->getPerms()->editstate)
			{
				$disableClassName = '';
				$disabledLabel = '';

				$hasAjaxOrderingSupport = $view->hasAjaxOrderingSupport();

				if (!$hasAjaxOrderingSupport['saveOrder'])
				{
					$disabledLabel = JText::_('JORDERINGDISABLED');
					$disableClassName = 'inactive tip-top';
				}

				$orderClass = $ordering ? 'order-enabled' : 'order-disabled';

				$html .= '
';
				$html .= '';
				$html .= '';
				$html .= '';

				if ($ordering)
				{
					$html .= '<input type="text" name="order[]" size="5" class="' . $class . ' text-area-order" value="' . $this->value . '" />';
				}

				$html .= '
';
			}
			else
			{
				$html .= '';
				$html .= '';
				$html .= '';
			}
		}

		return $html;
	}

	/**
	 * Builds the query for the ordering list.
	 *
	 * @since 2.3.2
	 *
	 * @return F0FDatabaseQuery  The query for the ordering form field
	 */
	protected function getQuery()
	{
		$ordering = $this->name;
		$title    = $this->element['ordertitle'] ? (string) $this->element['ordertitle'] : $this->item->getColumnAlias('title');

		$db = F0FPlatform::getInstance()->getDbo();
		$query = $db->getQuery(true);
		$query->select(array($db->quoteName($ordering, 'value'), $db->quoteName($title, 'text')))
				->from($db->quoteName($this->item->getTableName()))
				->order($ordering);

		return $query;
	}
}


text:
/**
 * utils.h
 *
 * $Header: /vetta/cvsroot/novamente/src/utils/utils.h,v 1.1.1.1.2.4 2004/05/31 14:30:59 murilo Exp $
 *
 * Copyright(c) 2001 Thiago Maia, Andre Senna
 * All rights reserved.
 */

#ifndef UTILS_H
#define UTILS_H

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <ext/hash_map>

using namespace __gnu_cxx;
using namespace std;

// defines print levels
#define SILENT          0
#define SHY             1
#define NORMAL          2
#define LOCAL_DEBUG     3
#define VERBOSE         4
#define DEBUG           5

/**
 * Returns a copy of the given string surrounded by ANSI bold tags. This copy
 * is allocated in the stack, so it must be duplicated if not used
 * immediately.
 *
 * @return Copy of the given string surrounded by ANSI bold tags.
 */
char* bold(const char*);

/**
 * Returns the string representation of an integer surrounded by ANSI bold
 * tags. This copy is allocated in the stack, so it must be duplicated if not
 * used immediately.
 *
 * @return The string representation of an integer surrounded by ANSI bold
 * tags.
 */
char* bold(int i);

/**
 * Prints the ANSI sequence to change the icon and window title in the window
 * manager.
 *
 * @param New title.
 */
void setIconAndWindowTitle(const char*);

/**
 * Keeps the current debug level in the system to control the cprintf function.
 */
extern int currentDebugLevel;

/**
 * Core printf function that prints messages according to the current debug
 * level. Format is identical to the standard printf format.
 *
 * @param Desired debug level.
 * @param Format according to the standard printf format.
 */
int cprintf(int, const char *format, ...);

struct eqstr {
    bool operator()(char *s1, char *s2) const {
        return strcmp(s1, s2) == 0;
    }
};

struct eqconststr {
    bool operator()(const char *s1, const char *s2) const {
        return strcmp(s1, s2) == 0;
    }
};

struct eqint {
    bool operator()(int s1, int s2) const {
        return s1 == s2;
    }
};

struct eqlong {
    bool operator()(long s1, long s2) const {
        return s1 == s2;
    }
};

struct eq2int {
    bool operator()(const char *s1, const char *s2) const {
        int size = 2 * sizeof(int);
        for (int i = 0; i < size; i++) {
            if (s1[i] != s2[i]) return false;
        }
        return true;
    }
};

template <class _Key> struct hash2int { };

inline size_t __hash2int(const char* __s) {
    unsigned long __h = 0;
    size_t size = 2 * sizeof(int);
    for (size_t i = 0; i < size; i++, __s++) {
        __h = 5*__h + *__s;
    }
    return size_t(__h);
}

template <> struct hash2int<char *> {
    size_t operator()(const char* __s) const { return __hash2int(__s); }
};

enum padAlignment { CENTER, LEFT, RIGHT };
char* padstr(char*, unsigned int, padAlignment);

class FileList {

    private:

        int size;
        char **fileList;

    public:

        FileList(char *);
        FileList();
        ~FileList();

        static FileList *getAllFilesRecursively(char *);

        int getSize();
        char *getFile(int);
};

/**
 * This method reads a line from a string and returns
 * the rest of the string.
 *
 * @param The char* from where the line should be read from.
 * @param A char* that will point to the start of the line.
 * @return The rest of the string.
 * Note: The string from where the line should be read from is
 * modified by nextLine.
 */
char *nextLine(char *, char *&);

/**
 * Counts the number of bits in 1 in the given unsigned long argument.
 */
int bitcount(unsigned long n);

#endif


text:
package torture

import scala.collection.mutable.ArrayBuffer
import Rand._

class SeqVPop(vregs: HWRegPool, pregs: HWRegPool, def_preg: Reg, sregs: HWRegPool) extends VFInstSeq //TODO: better configuration
{
  override val seqname = "vpop"

  def seq_src3(pop: Int) = () => {
    val src1 = reg_read_any(pregs)
    val src2 = reg_read_any(pregs)
    val src3 = reg_read_any(pregs)
    val dest = reg_write(pregs, src1, src2, src3)
    vinsts += VPOP(dest, src1, src2, src3, HexImm(pop))
  }

  val candidates = new ArrayBuffer[() => vinsts.type]

  candidates += seq_src3(rand_word & 0xFF)

  rand_pick(candidates)()
}


text:
'use strict';

var async = require('async');
var validator = require('validator');

var db = require('./database');
var batch = require('./batch');
var user = require('./user');
var utils = require('./utils');

var events = module.exports;

events.log = function (data, callback) {
	callback = callback || function () {};

	async.waterfall([
		function (next) {
			db.incrObjectField('global', 'nextEid', next);
		},
		function (eid, next) {
			data.timestamp = Date.now();
			data.eid = eid;

			async.parallel([
				function (next) {
					db.sortedSetAdd('events:time', data.timestamp, eid, next);
				},
				function (next) {
					db.setObject('event:' + eid, data, next);
				},
			], next);
		},
	], function (err) {
		callback(err);
	});
};

events.getEvents = function (start, stop, callback) {
	async.waterfall([
		function (next) {
			db.getSortedSetRevRange('events:time', start, stop, next);
		},
		function (eids, next) {
			var keys = eids.map(function (eid) {
				return 'event:' + eid;
			});
			db.getObjects(keys, next);
		},
		function (eventsData, next) {
			eventsData = eventsData.filter(Boolean);
			addUserData(eventsData, 'uid', 'user', next);
		},
		function (eventsData, next) {
			addUserData(eventsData, 'targetUid', 'targetUser', next);
		},
		function (eventsData, next) {
			eventsData.forEach(function (event) {
				Object.keys(event).forEach(function (key) {
					if (typeof event[key] === 'string') {
						event[key] = validator.escape(String(event[key] || ''));
					}
				});
				var e = utils.merge(event);
				e.eid = undefined;
				e.uid = undefined;
				e.type = undefined;
				e.ip = undefined;
				e.user = undefined;
				event.jsonString = JSON.stringify(e, null, 4);
				event.timestampISO = new Date(parseInt(event.timestamp, 10)).toUTCString();
			});
			next(null, eventsData);
		},
	], callback);
};

function addUserData(eventsData, field, objectName, callback) {
	var uids = eventsData.map(function (event) {
		return event && event[field];
	}).filter(function (uid, index, array) {
		return uid && array.indexOf(uid) === index;
	});

	if (!uids.length) {
		return callback(null, eventsData);
	}

	async.waterfall([
		function (next) {
			async.parallel({
				isAdmin: function (next) {
					user.isAdministrator(uids, next);
				},
				userData: function (next) {
					user.getUsersFields(uids, ['username', 'userslug', 'picture'], next);
				},
			}, next);
		},
		function (results, next) {
			var userData = results.userData;

			var map = {};
			userData.forEach(function (user, index) {
				user.isAdmin = results.isAdmin[index];
				map[user.uid] = user;
			});

			eventsData.forEach(function (event) {
				if (map[event[field]]) {
					event[objectName] = map[event[field]];
				}
			});
			next(null, eventsData);
		},
	], callback);
}

events.deleteEvents = function (eids, callback) {
	callback = callback || function () {};
	async.parallel([
		function (next) {
			var keys = eids.map(function (eid) {
				return 'event:' + eid;
			});
			db.deleteAll(keys, next);
		},
		function (next) {
			db.sortedSetRemove('events:time', eids, next);
		},
	], callback);
};

events.deleteAll = function (callback) {
	callback = callback || function () {};

	batch.processSortedSet('events:time', function (eids, next) {
		events.deleteEvents(eids, next);
	}, { alwaysStartAt: 0 }, callback);
};

events.output = function () {
	process.stdout.write('\nDisplaying last ten administrative events...\n'.bold);
	events.getEvents(0, 9, function (err, events) {
		if (err) {
			process.stdout.write('    Error '.red + String(err.message).reset);
			process.exit(1);
		}

		events.forEach(function (event) {
			process.stdout.write('  * ' + String(event.timestampISO).green + ' ' + String(event.type).yellow + (event.text ? ' ' + event.text : '') + ' (uid: '.reset + (event.uid ? event.uid : 0) + ')\n');
		});

		process.exit(0);
	});
};


text:
require "English"

module Aw
  # The Fork class.
  #
  # @api private
  class Fork
    # Initialize the class.
    #
    # @param read  [IO] The read endpoint.
    # @param write [IO] The write endpoint.
    def initialize(read, write)
      # Currently, not available on all platforms.
      raise ::NotImplementedError, "fork()" unless ::Process.respond_to?(:fork)

      @read   = read
      @write  = write
    end

    # @!attribute [r] read
    #
    # @return [IO] The read endpoint.
    attr_reader :read

    # @!attribute [r] write
    #
    # @return [IO] The write endpoint.
    attr_reader :write

    # Runs the block inside a sub-process, and returns the computed value.
    #
    # @example Computes `6 * 7` in a sub-process and returns `42` to the current process.
    #   call { 6 * 7 } # => 42
    #
    # @return [#object_id] The computed value.
    def call(&block)
      pid = fork_and_return_pid(&block)
      write.close
      result = read.read
      ::Process.wait(pid)

      # rubocop:disable Security/MarshalLoad
      ::Marshal.load(result).tap { |r| raise r if r.is_a?(::Exception) }
      # rubocop:enable Security/MarshalLoad
    end

    private

    # Creates a sub-process to execute a block inside, and returns the
    # sub-process ID.
    #
    # @return [Integer] The ID of the created sub-process.
    def fork_and_return_pid
      fork do
        # :nocov:

        read.close

        # rubocop:disable Lint/RescueException
        begin
          result = yield
        rescue ::Exception
          result = $ERROR_INFO
        end
        # rubocop:enable Lint/RescueException

        ::Marshal.dump(result, write)
        exit!(true)

        # :nocov:
      end
    end
  end
end


text:
package service

import (
	"strings"
	"testing"
)

func TestAuth(t *testing.T) {

	var _service CategoryService
	b := _service.LoadCategory("category")
	if b != true {
		t.Errorf("LoadCategory error")
	}

	_json := _service.GetSubCategories(10100)
	if !strings.Contains(_json, "10101") {
		t.Errorf("GetSubCategories error")
	}

	v := _service.GetSubCategoriesBean(10200)
	if len(v) != 10 {
		t.Errorf("GetSubCategories error")
	}

}


text:
package com.intellij.openapi.externalSystem.model.task.event;

import java.util.List;

/**
 * @author Vladislav.Soroka
 * @since 12/2/2015
 */
public class FailureResultImpl extends DefaultOperationResult implements FailureResult {

  private final List<? extends Failure> myFailures;

  public FailureResultImpl(long startTime, long endTime, List<? extends Failure> failures) {
    super(startTime, endTime);
    myFailures = failures;
  }

  @Override
  public List<? extends Failure> getFailures() {
    return myFailures;
  }
}


text:
require 'rubygems'
require 'bundler'
begin
  Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
  $stderr.puts e.message
  $stderr.puts "Run `bundle install` to install missing gems"
  exit e.status_code
end
require 'test/unit'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'param_protection'
require 'test_request_with_params'
require 'sanitizer'

class Test::Unit::TestCase
end


text:
<?php

namespace ByJG\RestServer\Exception;

class Error405Exception extends ClientShowException
{
    public function handleHeader()
    {
        $this->sendHeader(405, 'Method not allowed');
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Steam.Models.TF2
{
    public class SchemaKillEaterScoreTypeModel
    {
        public uint Type { get; set; }

        public string TypeName { get; set; }

        public string LevelData { get; set; }
    }
}


text:
package org.hisp.dhis.dxf2.metadata.objectbundle.hooks;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import org.hisp.dhis.common.DeliveryChannel;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundle;
import org.hisp.dhis.program.notification.ProgramNotificationRecipient;
import org.hisp.dhis.program.notification.ProgramNotificationTemplate;

import java.util.Set;

/**
 * @author Halvdan Hoem Grelland
 */
public class ProgramNotificationTemplateObjectBundleHook
    extends AbstractObjectBundleHook
{
    private ImmutableMap<ProgramNotificationRecipient, Function<ProgramNotificationTemplate, ValueType>>
        RECIPIENT_TO_VALUETYPE_RESOLVER = new ImmutableMap.Builder<ProgramNotificationRecipient, Function<ProgramNotificationTemplate, ValueType>>()
        .put( ProgramNotificationRecipient.PROGRAM_ATTRIBUTE, template -> template.getRecipientProgramAttribute().getValueType() )
        .put( ProgramNotificationRecipient.DATA_ELEMENT, template -> template.getRecipientDataElement().getValueType() )
        .build();

    private static  final  ImmutableMap<ValueType,Set<DeliveryChannel>>
        CHANNEL_MAPPER = new ImmutableMap.Builder<ValueType, Set<DeliveryChannel>>()
        .put( ValueType.PHONE_NUMBER, Sets.newHashSet( DeliveryChannel.SMS ) )
        .put( ValueType.EMAIL, Sets.newHashSet( DeliveryChannel.EMAIL ) )
        .build();

    @Override
    public <T extends IdentifiableObject> void preCreate( T object, ObjectBundle bundle )
    {
        if ( !ProgramNotificationTemplate.class.isInstance( object ) ) return;
        ProgramNotificationTemplate template = (ProgramNotificationTemplate) object;

        preProcess( template );
    }

    @Override
    public <T extends IdentifiableObject> void preUpdate( T object, T persistedObject, ObjectBundle bundle )
    {
        if ( !ProgramNotificationTemplate.class.isInstance( object ) ) return;
        ProgramNotificationTemplate template = (ProgramNotificationTemplate) object;

        preProcess( template );
    }

    @Override
    public <T extends IdentifiableObject> void postCreate( T persistedObject, ObjectBundle bundle )
    {
        if ( !ProgramNotificationTemplate.class.isInstance( persistedObject ) ) return;
        ProgramNotificationTemplate template = (ProgramNotificationTemplate) persistedObject;

        postProcess( template );
    }

    @Override
    public <T extends IdentifiableObject> void postUpdate( T persistedObject, ObjectBundle bundle )
    {
        if ( !ProgramNotificationTemplate.class.isInstance( persistedObject ) ) return;
        ProgramNotificationTemplate template = (ProgramNotificationTemplate) persistedObject;

        postProcess( template );
    }

    /**
     * Removes any non-valid combinations of properties on the template object.
     */
    private void preProcess( ProgramNotificationTemplate template )
    {
        if ( template.getNotificationTrigger().isImmediate() )
        {
            template.setRelativeScheduledDays( null );
        }

        if ( ProgramNotificationRecipient.USER_GROUP != template.getNotificationRecipient() )
        {
            template.setRecipientUserGroup( null );
        }

        if ( ProgramNotificationRecipient.PROGRAM_ATTRIBUTE != template.getNotificationRecipient() )
        {
            template.setRecipientProgramAttribute( null );
        }

        if ( ProgramNotificationRecipient.DATA_ELEMENT != template.getNotificationRecipient() )
        {
            template.setRecipientDataElement( null );
        }

        if ( ! ( template.getNotificationRecipient().isExternalRecipient() ) )
        {
            template.setDeliveryChannels( Sets.newHashSet() );
        }
    }

    private void postProcess( ProgramNotificationTemplate template )
    {
        if ( ProgramNotificationRecipient.PROGRAM_ATTRIBUTE == template.getNotificationRecipient() )
        {
            resolveTemplateRecipients( template, ProgramNotificationRecipient.PROGRAM_ATTRIBUTE );
        }

        if ( ProgramNotificationRecipient.DATA_ELEMENT == template.getNotificationRecipient() )
        {
            resolveTemplateRecipients( template, ProgramNotificationRecipient.DATA_ELEMENT );
        }
    }

    private void resolveTemplateRecipients( ProgramNotificationTemplate pnt, ProgramNotificationRecipient pnr )
    {
        Function<ProgramNotificationTemplate,ValueType> resolver = RECIPIENT_TO_VALUETYPE_RESOLVER.get( pnr );

        ValueType valueType = null;

        if ( resolver != null && ( pnt.getRecipientProgramAttribute() != null || pnt.getRecipientDataElement() != null ) )
        {
            valueType = resolver.apply( pnt );
        }

        pnt.setDeliveryChannels( CHANNEL_MAPPER.getOrDefault( valueType, Sets.newHashSet() ) );
    }
}


text:
class EncryptionKeyGenerator < Rails::Generator::Base
  def manifest
    record do |m|
      m.encryption_key
    end
  end
end


text:
Mithril = m = new function app(window, undefined) {
	var type = {}.toString
	var parser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[.+?\])/g, attrParser = /\[(.+?)(?:=("|'|)(.*?)\2)?\]/
	var voidElements = /AREA|BASE|BR|COL|COMMAND|EMBED|HR|IMG|INPUT|KEYGEN|LINK|META|PARAM|SOURCE|TRACK|WBR/

	function m() {
		var args = arguments
		var hasAttrs = args[1] != null && type.call(args[1]) == "[object Object]" && !("tag" in args[1]) && !("subtree" in args[1])
		var attrs = hasAttrs ? args[1] : {}
		var classAttrName = "class" in attrs ? "class" : "className"
		var cell = {tag: "div", attrs: {}}
		var match, classes = []
		while (match = parser.exec(args[0])) {
			if (match[1] == "") cell.tag = match[2]
			else if (match[1] == "#") cell.attrs.id = match[2]
			else if (match[1] == ".") classes.push(match[2])
			else if (match[3][0] == "[") {
				var pair = attrParser.exec(match[3])
				cell.attrs[pair[1]] = pair[3] || (pair[2] ? "" :true)
			}
		}
		if (classes.length > 0) cell.attrs[classAttrName] = classes.join(" ")

		cell.children = hasAttrs ? args[2] : args[1]

		for (var attrName in attrs) {
			if (attrName == classAttrName) cell.attrs[attrName] = (cell.attrs[attrName] || "") + " " + attrs[attrName]
			else cell.attrs[attrName] = attrs[attrName]
		}
		return cell
	}
	function build(parentElement, parentTag, parentCache, parentIndex, data, cached, shouldReattach, index, editable, namespace, configs) {
		//`build` is a recursive function that manages creation/diffing/removal of DOM elements based on comparison between `data` and `cached`
		//the diff algorithm can be summarized as this:
		//1 - compare `data` and `cached`
		//2 - if they are different, copy `data` to `cached` and update the DOM based on what the difference is
		//3 - recursively apply this algorithm for every array and for the children of every virtual element

		//the `cached` data structure is essentially the same as the previous redraw's `data` data structure, with a few additions:
		//- `cached` always has a property called `nodes`, which is a list of DOM elements that correspond to the data represented by the respective virtual element
		//- in order to support attaching `nodes` as a property of `cached`, `cached` is *always* a non-primitive object, i.e. if the data was a string, then cached is a String instance. If data was `null` or `undefined`, cached is `new String("")`
		//- `cached also has a `configContext` property, which is the state storage object exposed by config(element, isInitialized, context)
		//- when `cached` is an Object, it represents a virtual element; when it's an Array, it represents a list of elements; when it's a String, Number or Boolean, it represents a text node

		//`parentElement` is a DOM element used for W3C DOM API calls
		//`parentTag` is only used for handling a corner case for textarea values
		//`parentCache` is used to remove nodes in some multi-node cases
		//`parentIndex` and `index` are used to figure out the offset of nodes. They're artifacts from before arrays started being flattened and are likely refactorable
		//`data` and `cached` are, respectively, the new and old nodes being diffed
		//`shouldReattach` is a flag indicating whether a parent node was recreated (if so, and if this node is reused, then this node must reattach itself to the new parent)
		//`editable` is a flag that indicates whether an ancestor is contenteditable
		//`namespace` indicates the closest HTML namespace as it cascades down from an ancestor
		//`configs` is a list of config functions to run after the topmost `build` call finishes running

		//there's logic that relies on the assumption that null and undefined data are equivalent to empty strings
		//- this prevents lifecycle surprises from procedural helpers that mix implicit and explicit return statements
		//- it simplifies diffing code
		if (data == null) data = ""
		if (data.subtree === "retain") return cached

		var cachedType = type.call(cached), dataType = type.call(data)
		if (cached == null || cachedType != dataType) {
			if (cached != null) {
				if (parentCache && parentCache.nodes) {
					var offset = index - parentIndex
					var end = offset + (dataType == "[object Array]" ? data : cached.nodes).length
					clear(parentCache.nodes.slice(offset, end), parentCache.slice(offset, end))
				}
				else if (cached.nodes) clear(cached.nodes, cached)
			}
			cached = new data.constructor
			cached.nodes = []
		}

		if (dataType == "[object Array]") {
			data = flatten(data)
			var nodes = [], intact = cached.length === data.length, subArrayCount = 0

			//keys algorithm: sort elements without recreating them if keys are present
			//1) create a map of all existing keys, and mark all for deletion
			//2) add new keys to map and mark them for addition
			//3) if key exists in new list, change action from deletion to a move
			//4) for each key, handle its corresponding action as marked in previous steps
			//5) copy unkeyed items into their respective gaps
			var DELETION = 1, INSERTION = 2 , MOVE = 3
			var existing = {}, unkeyed = [], shouldMaintainIdentities = false
			for (var i = 0; i < cached.length; i++) {
				if (cached[i] && cached[i].attrs && cached[i].attrs.key != null) {
					shouldMaintainIdentities = true
					existing[cached[i].attrs.key] = {action: DELETION, index: i}
				}
			}
			if (shouldMaintainIdentities) {
				for (var i = 0; i < data.length; i++) {
					if (data[i] && data[i].attrs) {
						if (data[i].attrs.key != null) {
							var key = data[i].attrs.key
							if (!existing[key]) existing[key] = {action: INSERTION, index: i}
							else existing[key] = {action: MOVE, index: i, from: existing[key].index, element: parentElement.childNodes[existing[key].index]}
						}
						else unkeyed.push({index: i, element: parentElement.childNodes[i]})
					}
				}
				var actions = Object.keys(existing).map(function(key) {return existing[key]})
				var changes = actions.sort(function(a, b) {return a.action - b.action || a.index - b.index})
				var newCached = cached.slice()

				for (var i = 0, change; change = changes[i]; i++) {
					if (change.action == DELETION) {
						clear(cached[change.index].nodes, cached[change.index])
						newCached.splice(change.index, 1)
					}
					if (change.action == INSERTION) {
						var dummy = window.document.createElement("div")
						dummy.key = data[change.index].attrs.key
						parentElement.insertBefore(dummy, parentElement.childNodes[change.index])
						newCached.splice(change.index, 0, {attrs: {key: data[change.index].attrs.key}, nodes: [dummy]})
					}

					if (change.action == MOVE) {
						if (parentElement.childNodes[change.index] !== change.element && change.element !== null) {
							parentElement.insertBefore(change.element, parentElement.childNodes[change.index])
						}
						newCached[change.index] = cached[change.from]
					}
				}
				for (var i = 0; i < unkeyed.length; i++) {
					var change = unkeyed[i]
					parentElement.insertBefore(change.element, parentElement.childNodes[change.index])
					newCached[change.index] = cached[change.index]
				}
				cached = newCached
				cached.nodes = []
				for (var i = 0, child; child = parentElement.childNodes[i]; i++) cached.nodes.push(child)
			}
			//end key algorithm

			for (var i = 0, cacheCount = 0; i < data.length; i++) {
				//diff each item in the array
				var item = build(parentElement, parentTag, cached, index, data[i], cached[cacheCount], shouldReattach, index + subArrayCount || subArrayCount, editable, namespace, configs)
				if (item === undefined) continue
				if (!item.nodes.intact) intact = false
				var isArray = type.call(item) == "[object Array]"
				subArrayCount += isArray ? item.length : 1
				cached[cacheCount++] = item
			}
			if (!intact) {
				//diff the array itself

				//update the list of DOM nodes by collecting the nodes from each item
				for (var i = 0; i < data.length; i++) {
					if (cached[i] != null) nodes = nodes.concat(cached[i].nodes)
				}
				//remove items from the end of the array if the new array is shorter than the old one
				//if errors ever happen here, the issue is most likely a bug in the construction of the `cached` data structure somewhere earlier in the program
				for (var i = 0, node; node = cached.nodes[i]; i++) {
					if (node.parentNode != null && nodes.indexOf(node) < 0) clear([node], [cached[i]])
				}
				//add items to the end if the new array is longer than the old one
				for (var i = cached.nodes.length, node; node = nodes[i]; i++) {
					if (node.parentNode == null) parentElement.appendChild(node)
				}
				if (data.length < cached.length) cached.length = data.length
				cached.nodes = nodes
			}
		}
		else if (data != null && dataType == "[object Object]") {
			//if an element is different enough from the one in cache, recreate it
			if (data.tag != cached.tag || Object.keys(data.attrs).join() != Object.keys(cached.attrs).join() || data.attrs.id != cached.attrs.id) {
				clear(cached.nodes)
				if (cached.configContext && typeof cached.configContext.onunload == "function") cached.configContext.onunload()
			}
			if (typeof data.tag != "string") return

			var node, isNew = cached.nodes.length === 0
			if (data.attrs.xmlns) namespace = data.attrs.xmlns
			else if (data.tag === "svg") namespace = "http://www.w3.org/2000/svg"
			else if (data.tag === "math") namespace = "http://www.w3.org/1998/Math/MathML"
			if (isNew) {
				node = namespace === undefined ? window.document.createElement(data.tag) : window.document.createElementNS(namespace, data.tag)
				cached = {
					tag: data.tag,
					//process children before attrs so that select.value works correctly
					children: build(node, data.tag, undefined, undefined, data.children, cached.children, true, 0, data.attrs.contenteditable ? node : editable, namespace, configs),
					attrs: setAttributes(node, data.tag, data.attrs, {}, namespace),
					nodes: [node]
				}
				parentElement.insertBefore(node, parentElement.childNodes[index] || null)
			}
			else {
				node = cached.nodes[0]
				setAttributes(node, data.tag, data.attrs, cached.attrs, namespace)
				cached.children = build(node, data.tag, undefined, undefined, data.children, cached.children, false, 0, data.attrs.contenteditable ? node : editable, namespace, configs)
				cached.nodes.intact = true
				if (shouldReattach === true && node != null) parentElement.insertBefore(node, parentElement.childNodes[index] || null)
			}
			//schedule configs to be called. They are called after `build` finishes running
			if (typeof data.attrs["config"] === "function") {
				configs.push(data.attrs["config"].bind(window, node, !isNew, cached.configContext = cached.configContext || {}, cached))
			}
		}
		else if (typeof dataType != "function") {
			//handle text nodes
			var nodes
			if (cached.nodes.length === 0) {
				if (data.$trusted) {
					nodes = injectHTML(parentElement, index, data)
				}
				else {
					nodes = [window.document.createTextNode(data)]
					if (!parentElement.nodeName.match(voidElements)) parentElement.insertBefore(nodes[0], parentElement.childNodes[index] || null)
				}
				cached = "string number boolean".indexOf(typeof data) > -1 ? new data.constructor(data) : data
				cached.nodes = nodes
			}
			else if (cached.valueOf() !== data.valueOf() || shouldReattach === true) {
				nodes = cached.nodes
				if (!editable || editable !== window.document.activeElement) {
					if (data.$trusted) {
						clear(nodes, cached)
						nodes = injectHTML(parentElement, index, data)
					}
					else {
						//corner case: replacing the nodeValue of a text node that is a child of a textarea/contenteditable doesn't work
						//we need to update the value property of the parent textarea or the innerHTML of the contenteditable element instead
						if (parentTag === "textarea") parentElement.value = data
						else if (editable) editable.innerHTML = data
						else {
							if (nodes[0].nodeType == 1 || nodes.length > 1) { //was a trusted string
								clear(cached.nodes, cached)
								nodes = [window.document.createTextNode(data)]
							}
							parentElement.insertBefore(nodes[0], parentElement.childNodes[index] || null)
							nodes[0].nodeValue = data
						}
					}
				}
				cached = new data.constructor(data)
				cached.nodes = nodes
			}
			else cached.nodes.intact = true
		}

		return cached
	}
	function setAttributes(node, tag, dataAttrs, cachedAttrs, namespace) {
		var groups = {}
		for (var attrName in dataAttrs) {
			var dataAttr = dataAttrs[attrName]
			var cachedAttr = cachedAttrs[attrName]
			if (!(attrName in cachedAttrs) || (cachedAttr !== dataAttr) || node === window.document.activeElement) {
				cachedAttrs[attrName] = dataAttr
				if (attrName === "config") continue
				else if (typeof dataAttr == "function" && attrName.indexOf("on") == 0) {
					node[attrName] = autoredraw(dataAttr, node)
				}
				else if (attrName === "style" && typeof dataAttr == "object") {
					for (var rule in dataAttr) {
						if (cachedAttr == null || cachedAttr[rule] !== dataAttr[rule]) node.style[rule] = dataAttr[rule]
					}
					for (var rule in cachedAttr) {
						if (!(rule in dataAttr)) node.style[rule] = ""
					}
				}
				else if (namespace != null) {
					if (attrName === "href") node.setAttributeNS("http://www.w3.org/1999/xlink", "href", dataAttr)
					else if (attrName === "className") node.setAttribute("class", dataAttr)
					else node.setAttribute(attrName, dataAttr)
				}
				else if (attrName === "value" && tag === "input") {
					if (node.value !== dataAttr) node.value = dataAttr
				}
				else if (attrName in node && !(attrName == "list" || attrName == "style")) {
					node[attrName] = dataAttr
				}
				else node.setAttribute(attrName, dataAttr)
			}
		}
		return cachedAttrs
	}
	function clear(nodes, cached) {
		for (var i = nodes.length - 1; i > -1; i--) {
			if (nodes[i] && nodes[i].parentNode) {
				nodes[i].parentNode.removeChild(nodes[i])
				cached = [].concat(cached)
				if (cached[i]) unload(cached[i])
			}
		}
		if (nodes.length != 0) nodes.length = 0
	}
	function unload(cached) {
		if (cached.configContext && typeof cached.configContext.onunload == "function") cached.configContext.onunload()
		if (cached.children) {
			if (type.call(cached.children) == "[object Array]") for (var i = 0; i < cached.children.length; i++) unload(cached.children[i])
			else if (cached.children.tag) unload(cached.children)
		}
	}
	function injectHTML(parentElement, index, data) {
		var nextSibling = parentElement.childNodes[index]
		if (nextSibling) {
			var isElement = nextSibling.nodeType != 1
			var placeholder = window.document.createElement("span")
			if (isElement) {
				parentElement.insertBefore(placeholder, nextSibling)
				placeholder.insertAdjacentHTML("beforebegin", data)
				parentElement.removeChild(placeholder)
			}
			else nextSibling.insertAdjacentHTML("beforebegin", data)
		}
		else parentElement.insertAdjacentHTML("beforeend", data)
		var nodes = []
		while (parentElement.childNodes[index] !== nextSibling) {
			nodes.push(parentElement.childNodes[index])
			index++
		}
		return nodes
	}
	function flatten(data) {
		var flattened = []
		for (var i = 0; i < data.length; i++) {
			var item = data[i]
			if (type.call(item) == "[object Array]") flattened.push.apply(flattened, flatten(item))
			else flattened.push(item)
		}
		return flattened
	}
	function autoredraw(callback, object, group) {
		return function(e) {
			e = e || event
			m.redraw.strategy("diff")
			m.startComputation()
			try {return callback.call(object, e)}
			finally {
				if (!lastRedrawId) lastRedrawId = -1;
				m.endComputation()
			}
		}
	}

	var html
	var documentNode = {
		insertAdjacentHTML: function(_, data) {
			window.document.write(data)
			window.document.close()
		},
		appendChild: function(node) {
			if (html === undefined) html = window.document.createElement("html")
			if (node.nodeName == "HTML") html = node
			else html.appendChild(node)
			if (window.document.documentElement && window.document.documentElement !== html) {
				window.document.replaceChild(html, window.document.documentElement)
			}
			else window.document.appendChild(html)
		},
		insertBefore: function(node) {
			this.appendChild(node)
		},
		childNodes: []
	}
	var nodeCache = [], cellCache = {}
	m.render = function(root, cell, forceRecreation) {
		var configs = []
		if (!root) throw new Error("Please ensure the DOM element exists before rendering a template into it.")
		var id = getCellCacheKey(root)
		var node = root == window.document || root == window.document.documentElement ? documentNode : root
		if (cellCache[id] === undefined) clear(node.childNodes)
		if (forceRecreation === true) reset(root)
		cellCache[id] = build(node, null, undefined, undefined, cell, cellCache[id], false, 0, null, undefined, configs)
		for (var i = 0; i < configs.length; i++) configs[i]()
	}
	function getCellCacheKey(element) {
		var index = nodeCache.indexOf(element)
		return index < 0 ? nodeCache.push(element) - 1 : index
	}

	m.trust = function(value) {
		value = new String(value)
		value.$trusted = true
		return value
	}

	function _prop(store) {
		var prop = function() {
			if (arguments.length) store = arguments[0]
			return store
		}

		prop.toJSON = function() {
			return store
		}

		return prop
	}

	m.prop = function (store) {
		if ((typeof store === 'object' || typeof store === 'function') &&
				typeof store.then === 'function') {
			var prop = _prop()
			newPromisedProp(prop, store).then(prop)

			return prop
		}

		return _prop(store)
	}

	var roots = [], modules = [], controllers = [], lastRedrawId = 0, computePostRedrawHook = null, prevented = false
	m.module = function(root, module) {
		var index = roots.indexOf(root)
		if (index < 0) index = roots.length
		var isPrevented = false
		if (controllers[index] && typeof controllers[index].onunload == "function") {
			var event = {
				preventDefault: function() {isPrevented = true}
			}
			controllers[index].onunload(event)
		}
		if (!isPrevented) {
			m.redraw.strategy("all")
			m.startComputation()
			roots[index] = root
			modules[index] = module
			controllers[index] = new module.controller
			m.endComputation()
		}
	}
	m.redraw = function(force) {
		var cancel = window.cancelAnimationFrame || window.clearTimeout
		var defer = window.requestAnimationFrame || window.setTimeout
		if (lastRedrawId && force !== true) {
			cancel(lastRedrawId)
			lastRedrawId = defer(redraw, 0)
		}
		else {
			redraw()
			lastRedrawId = defer(function() {lastRedrawId = null}, 0)
		}
	}
	m.redraw.strategy = m.prop()
	function redraw() {
		var mode = m.redraw.strategy()
		for (var i = 0; i < roots.length; i++) {
			if (controllers[i] && mode != "none") m.render(roots[i], modules[i].view(controllers[i]), mode == "all")
		}
		if (computePostRedrawHook) {
			computePostRedrawHook()
			computePostRedrawHook = null
		}
		lastRedrawId = null
		m.redraw.strategy("diff")
	}

	var pendingRequests = 0
	m.startComputation = function() {pendingRequests++}
	m.endComputation = function() {
		pendingRequests = Math.max(pendingRequests - 1, 0)
		if (pendingRequests == 0) m.redraw()
	}

	m.withAttr = function(prop, withAttrCallback) {
		return function(e) {
			e = e || event
			var currentTarget = e.currentTarget || this
			withAttrCallback(prop in currentTarget ? currentTarget[prop] : currentTarget.getAttribute(prop))
		}
	}

	//routing
	var modes = {pathname: "", hash: "#", search: "?"}
	var redirect = function() {}, routeParams = {}, currentRoute
	m.route = function() {
		if (arguments.length === 0) return currentRoute
		else if (arguments.length === 3 && typeof arguments[1] == "string") {
			var root = arguments[0], defaultRoute = arguments[1], router = arguments[2]
			redirect = function(source) {
				var path = currentRoute = normalizeRoute(source)
				if (!routeByValue(root, router, path)) {
					m.route(defaultRoute, true)
				}
			}
			var listener = m.route.mode == "hash" ? "onhashchange" : "onpopstate"
			window[listener] = function() {
				if (currentRoute != normalizeRoute(window.location[m.route.mode])) {
					redirect(window.location[m.route.mode])
				}
			}
			computePostRedrawHook = setScroll
			window[listener]()
		}
		else if (arguments[0].addEventListener) {
			var element = arguments[0]
			var isInitialized = arguments[1]
			if (element.href.indexOf(modes[m.route.mode]) < 0) {
				element.href = window.location.pathname + modes[m.route.mode] + element.pathname
			}
			if (!isInitialized) {
				element.removeEventListener("click", routeUnobtrusive)
				element.addEventListener("click", routeUnobtrusive)
			}
		}
		else if (typeof arguments[0] == "string") {
			currentRoute = arguments[0]
			var querystring = typeof arguments[1] == "object" ? buildQueryString(arguments[1]) : null
			if (querystring) currentRoute += (currentRoute.indexOf("?") === -1 ? "?" : "&") + querystring

			var shouldReplaceHistoryEntry = (arguments.length == 3 ? arguments[2] : arguments[1]) === true

			if (window.history.pushState) {
				computePostRedrawHook = function() {
					window.history[shouldReplaceHistoryEntry ? "replaceState" : "pushState"](null, window.document.title, modes[m.route.mode] + currentRoute)
					setScroll()
				}
				redirect(modes[m.route.mode] + currentRoute)
			}
			else window.location[m.route.mode] = currentRoute
		}
	}
	m.route.param = function(key) {return routeParams[key]}
	m.route.mode = "search"
	function normalizeRoute(route) {return route.slice(modes[m.route.mode].length)}
	function routeByValue(root, router, path) {
		routeParams = {}

		var queryStart = path.indexOf("?")
		if (queryStart !== -1) {
			routeParams = parseQueryString(path.substr(queryStart + 1, path.length))
			path = path.substr(0, queryStart)
		}

		for (var route in router) {
			if (route == path) {
				m.module(root, router[route])
				return true
			}

			var matcher = new RegExp("^" + route.replace(/:[^\/]+?\.{3}/g, "(.*?)").replace(/:[^\/]+/g, "([^\\/]+)") + "\/?$")

			if (matcher.test(path)) {
				path.replace(matcher, function() {
					var keys = route.match(/:[^\/]+/g) || []
					var values = [].slice.call(arguments, 1, -2)
					for (var i = 0; i < keys.length; i++) routeParams[keys[i].replace(/:|\./g, "")] = decodeURIComponent(values[i])
					m.module(root, router[route])
				})
				return true
			}
		}
	}
	function routeUnobtrusive(e) {
		e = e || event
		if (e.ctrlKey || e.metaKey || e.which == 2) return
		e.preventDefault()
		m.route(e.currentTarget[m.route.mode].slice(modes[m.route.mode].length))
	}
	function setScroll() {
		if (m.route.mode != "hash" && window.location.hash) window.location.hash = window.location.hash
		else window.scrollTo(0, 0)
	}
	function buildQueryString(object, prefix) {
		var str = []
		for(var prop in object) {
			var key = prefix ? prefix + "[" + prop + "]" : prop, value = object[prop]
			str.push(typeof value == "object" ? buildQueryString(value, key) : encodeURIComponent(key) + "=" + encodeURIComponent(value))
		}
		return str.join("&")
	}
	function parseQueryString(str) {
		var pairs = str.split("&"), params = {}
		for (var i = 0; i < pairs.length; i++) {
			var pair = pairs[i].split("=")
			params[decodeSpace(pair[0])] = pair[1] ? decodeSpace(pair[1]) : (pair.length === 1 ? true : "")
		}
		return params
	}
	function decodeSpace(string) {
		return decodeURIComponent(string.replace(/\+/g, " "))
	}
	function reset(root) {
		var cacheKey = getCellCacheKey(root)
		clear(root.childNodes, cellCache[cacheKey])
		cellCache[cacheKey] = undefined
	}

	function newPromisedProp(prop, promise) {
		prop.then = function () {
			var newProp = m.prop()
			return newPromisedProp(newProp,
				promise.then.apply(promise, arguments).then(newProp))
		}
		prop.promise = prop
		prop.resolve = function (val) {
			prop(val)
			promise = promise.resolve.apply(promise, arguments)
			return prop
		}
		prop.reject = function () {
			promise = promise.reject.apply(promise, arguments)
			return prop
		}

		return prop
	}
	m.deferred = function () {
		return newPromisedProp(m.prop(), new Deferred())
	}
	// Promiz.mithril.js | Zolmeister | MIT
	function Deferred(fn, er) {
		// states
		// 0: pending
		// 1: resolving
		// 2: rejecting
		// 3: resolved
		// 4: rejected
		var self = this,
			state = 0,
			val = 0,
			next = [];

		self['promise'] = self

		self['resolve'] = function (v) {
			if (!state) {
				val = v
				state = 1

				fire()
			}
			return this
		}

		self['reject'] = function (v) {
			if (!state) {
				val = v
				state = 2

				fire()
			}
			return this
		}

		self['then'] = function (fn, er) {
			var d = new Deferred(fn, er)
			if (state == 3) {
				d.resolve(val)
			}
			else if (state == 4) {
				d.reject(val)
			}
			else {
				next.push(d)
			}
			return d
		}

		var finish = function (type) {
			state = type || 4
			next.map(function (p) {
				state == 3 && p.resolve(val) || p.reject(val)
			})
		}

		// ref : reference to 'then' function
		// cb, ec, cn : successCallback, failureCallback, notThennableCallback
		function thennable (ref, cb, ec, cn) {
			if ((typeof val == 'object' || typeof val == 'function') && typeof ref == 'function') {
				try {

					// cnt protects against abuse calls from spec checker
					var cnt = 0
					ref.call(val, function (v) {
						if (cnt++) return
						val = v
						cb()
					}, function (v) {
						if (cnt++) return
						val = v
						ec()
					})
				} catch (e) {
					val = e
					ec()
				}
			} else {
				cn()
			}
		};

		function fire() {

			// check if it's a thenable
			var ref;
			try {
				ref = val && val.then
			} catch (e) {
				val = e
				state = 2
				return fire()
			}
			thennable(ref, function () {
				state = 1
				fire()
			}, function () {
				state = 2
				fire()
			}, function () {
				try {
					if (state == 1 && typeof fn == 'function') {
						val = fn(val)
					}

					else if (state == 2 && typeof er == 'function') {
						val = er(val)
						state = 1
					}
				} catch (e) {
					val = e
					return finish()
				}

				if (val == self) {
					val = TypeError()
					finish()
				} else thennable(ref, function () {
						finish(3)
					}, finish, function () {
						finish(state == 1 && 3)
					})

			})
		}
	}

	m.sync = function(args) {
		var method = "resolve"
		function synchronizer(pos, resolved) {
			return function(value) {
				results[pos] = value
				if (!resolved) method = "reject"
				if (--outstanding == 0) {
					deferred.promise(results)
					deferred[method](results)
				}
				return value
			}
		}

		var deferred = m.deferred()
		var outstanding = args.length
		var results = new Array(outstanding)
		if (args.length > 0) {
			for (var i = 0; i < args.length; i++) {
				args[i].then(synchronizer(i, true), synchronizer(i, false))
			}
		}
		else deferred.resolve()

		return deferred.promise
	}
	function identity(value) {return value}

	function ajax(options) {
		var xhr = new window.XMLHttpRequest
		xhr.open(options.method, options.url, true, options.user, options.password)
		xhr.onreadystatechange = function() {
			if (xhr.readyState === 4) {
				if (xhr.status >= 200 && xhr.status < 300) options.onload({type: "load", target: xhr})
				else options.onerror({type: "error", target: xhr})
			}
		}
		if (options.serialize == JSON.stringify && options.method != "GET") {
			xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
		}
		if (typeof options.config == "function") {
			var maybeXhr = options.config(xhr, options)
			if (maybeXhr != null) xhr = maybeXhr
		}
		xhr.send(options.method == "GET" ? "" : options.data)
		return xhr
	}
	function bindData(xhrOptions, data, serialize) {
		if (data && Object.keys(data).length > 0) {
			if (xhrOptions.method == "GET") {
				xhrOptions.url = xhrOptions.url + (xhrOptions.url.indexOf("?") < 0 ? "?" : "&") + buildQueryString(data)
			}
			else xhrOptions.data = serialize(data)
		}
		return xhrOptions
	}
	function parameterizeUrl(url, data) {
		var tokens = url.match(/:[a-z]\w+/gi)
		if (tokens && data) {
			for (var i = 0; i < tokens.length; i++) {
				var key = tokens[i].slice(1)
				url = url.replace(tokens[i], data[key])
				delete data[key]
			}
		}
		return url
	}

	m.request = function(xhrOptions) {
		if (xhrOptions.background !== true) m.startComputation()
		var deferred = m.deferred()
		var serialize = xhrOptions.serialize = xhrOptions.serialize || JSON.stringify
		var deserialize = xhrOptions.deserialize = xhrOptions.deserialize || JSON.parse
		var extract = xhrOptions.extract || function(xhr) {
			return xhr.responseText.length === 0 && deserialize === JSON.parse ? null : xhr.responseText
		}
		xhrOptions.url = parameterizeUrl(xhrOptions.url, xhrOptions.data)
		xhrOptions = bindData(xhrOptions, xhrOptions.data, serialize)
		xhrOptions.onload = xhrOptions.onerror = function(e) {
			try {
				e = e || event
				var unwrap = (e.type == "load" ? xhrOptions.unwrapSuccess : xhrOptions.unwrapError) || identity
				var response = unwrap(deserialize(extract(e.target, xhrOptions)))
				if (e.type == "load") {
					if (type.call(response) == "[object Array]" && xhrOptions.type) {
						for (var i = 0; i < response.length; i++) response[i] = new xhrOptions.type(response[i])
					}
					else if (xhrOptions.type) response = new xhrOptions.type(response)
				}
				deferred[e.type == "load" ? "resolve" : "reject"](response)
			}
			catch (e) {
				if (e instanceof SyntaxError) throw new SyntaxError("Could not parse HTTP response. See http://lhorie.github.io/mithril/mithril.request.html#using-variable-data-formats")
				else if (type.call(e) == "[object Error]" && e.constructor !== Error) throw e
				else deferred.reject(e)
			}
			if (xhrOptions.background !== true) m.endComputation()
		}
		ajax(xhrOptions)
		return deferred.promise
	}

	//testing API
	m.deps = function(mock) {return window = mock}
	//for internal testing only, do not use `m.deps.factory`
	m.deps.factory = app

	return m
}(typeof window != "undefined" ? window : {})

if (typeof module != "undefined" && module !== null) module.exports = m
if (typeof define == "function" && define.amd) define(function() {return m})

;;;
;//	Mithril sugar tags.
//	Copyright (C) 2014 jsguy (Mikkel Bergmann)
//	MIT licensed
(function(context){
	context.m = context.m || {};
	context.m.sugarTags = {};
	var arg = function(l1, l2){
			var i;
			for (i in l2) {if(l2.hasOwnProperty(i)) {
				l1.push(l2[i]);
			}}
			return l1;
		},
		tagList = ["A","ABBR","ACRONYM","ADDRESS","AREA","ARTICLE","ASIDE","AUDIO","B","BDI","BDO","BIG","BLOCKQUOTE","BODY","BR","BUTTON","CANVAS","CAPTION","CITE","CODE","COL","COLGROUP","COMMAND","DATALIST","DD","DEL","DETAILS","DFN","DIV","DL","DT","EM","EMBED","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAME","FRAMESET","H1","H2","H3","H4","H5","H6","HEAD","HEADER","HGROUP","HR","HTML","I","IFRAME","IMG","INPUT","INS","KBD","KEYGEN","LABEL","LEGEND","LI","LINK","MAP","MARK","META","METER","NAV","NOSCRIPT","OBJECT","OL","OPTGROUP","OPTION","OUTPUT","P","PARAM","PRE","PROGRESS","Q","RP","RT","RUBY","SAMP","SCRIPT","SECTION","SELECT","SMALL","SOURCE","SPAN","SPLIT","STRONG","STYLE","SUB","SUMMARY","SUP","TABLE","TBODY","TD","TEXTAREA","TFOOT","TH","THEAD","TIME","TITLE","TR","TRACK","TT","UL","VAR","VIDEO","WBR"],
		lowerTagCache,
		i,
		//	Set "localSugarTags" on mithril to avoid global scope
		scope = context.m.localSugarTags? context.m.sugarTags: context;

	//	Create sugar'd functions in the required scope
	for (i in tagList) {if(tagList.hasOwnProperty(i)) {
		(function(tag){
			var lowerTag = tag.toLowerCase();
			scope[tag] = function(){
				return (context.m.e? context.m.e: context.m).apply(this, arg([lowerTag], arguments));
			};
		}(tagList[i]));
	}}

	//	Lowercased sugar tags
	context.m.sugarTags.lower = function(){
		if(!lowerTagCache) {
			lowerTagCache = {};
			//	Create lowercase sugar'd function cache
			for (i in tagList) {if(tagList.hasOwnProperty(i)) {
				(function(tag){
					var lowerTag = tag.toLowerCase();
					lowerTagCache[lowerTag] = function(){
						return (context.m.e? context.m.e: m).apply(this, arg([lowerTag], arguments));
					};
				}(tagList[i]));
			}}
		}
		return lowerTagCache;
	};

}(window));;//	Mithril bindings.
//	Copyright (C) 2014 jsguy (Mikkel Bergmann)
//	MIT licensed
(function(context){
	context.m = context.m || {};

	//	Pub/Sub based extended properties
	context.m.p = function(value) {
		var self = this,
			subs = [],
			prevValue,
			delay = false,
			//  Send notifications to subscribers
			notify = function (value, prevValue) {
				var i;
				for (i = 0; i < subs.length; i += 1) {
					subs[i].func.apply(subs[i].context, [value, prevValue]);
				}
			},
			prop = function() {
				if (arguments.length) {
					value = arguments[0];
					if (prevValue !== value) {
						var tmpPrev = prevValue;
						prevValue = value;
						notify(value, tmpPrev);
					}
				}
				return value;
			};

		//	Allow push on arrays
		prop.push = function(val) {
			if(value.push && typeof value.length !== "undefined") {
				value.push(val);
			}
			prop(value);
		}

		//	Allow subscription for when the value changes
		//	func gets two parameters: value and prevValue
		prop.subscribe = function (func, context) {
			subs.push({ func: func, context: context || self });
			return prop;
		};

		//	Allow property to not automatically render
		prop.delay = function(value) {
			delay = !!value;
			return prop;
		};

		//	Automatically update rendering when a value changes
		//	As mithril waits for a request animation frame, this should be ok.
		//	You can use .delay(true) to be able to manually handle updates
		prop.subscribe(function(val){
			if(!delay) {
				m.startComputation();
				m.endComputation();
			}
			return prop;
		});

		return prop;
	};

	context.m.e = function(element, attrs, children) {
		for (var attrName in attrs) {
			if (m.bindings[attrName]) {
				m.bindings[attrName].apply(attrs, [attrs[attrName]]);
			}
		}
		return m(element, attrs, children);
	};

	//	Add bindings method
	context.m.addBinding = function(name, func){
		context.m.bindings = context.m.bindings || {};
		context.m.bindings[name] = func;
	};

	//	Get the underlying value of a property
	context.m.unwrap = function(prop) {
		return (typeof prop == "function")? prop(): prop;
	};

	//	Bi-directional binding of value
	context.m.addBinding("value", function(prop) {
		if (typeof prop == "function") {
			this.value = prop();
			this.onchange = m.withAttr("value", prop);
		} else {
			this.value = prop;
		}
	});

	//	Bi-directional binding of checked property
	context.m.addBinding("checked", function(prop) {
		if (typeof prop == "function") {
			this.checked = prop();
			this.onchange = m.withAttr("checked", prop);
		} else {
			this.checked = prop;
		}
	});

	//	Add bindings for various events
	var events = ["Input", "Keyup", "Keypress"];
	for(var i = 0; i < events.length; i += 1) {
		var eve = events[i];
		(function(name, eve){
			//	Bi-directional binding of value
			context.m.addBinding(name, function(prop) {
				if (typeof prop == "function") {
					this.value = prop();
					this[eve] = m.withAttr("value", prop);
				} else {
					this.value = prop;
				}
			});
		}("value" + eve, "on" + eve.toLowerCase()));
	}

	//	Hide node
	context.m.addBinding("hide", function(prop){
		this.style = {
			display: context.m.unwrap(prop)? "none" : ""
		};
	});

	//	Toggle boolean value on click
	context.m.addBinding('toggle', function(prop){
		this.onclick = function(){
			var value = prop();
			prop(!value);
		}
	});

}(window));;//	Mithril templates.
//	Copyright (C) 2014 jsguy (Mikkel Bergmann)
//	MIT licensed
(function(context){
	context.m = context.m || {};

	context.m.templates = {};

	//	Returns a template from either a function or string
	//	Note: use 'data' as the variable for the data
	context.m.template = function(tmpl, data){
		try{
			var isFunc = (typeof tmpl == 'function'), t, f, result;
			if(isFunc) {
				result = tmpl(data);
			} else {
				t = document.getElementById(tmpl);
				t = t? t.innerHTML: tmpl;

				//	Use sugar tags if they are available
				f = (m.sugarTags?
					new Function("data", 'with(m.sugarTags) {return(' + t + ')};'):
					new Function("data", 'return(' + t + ')'));
				result = f(data);
			}

			return result;
		} catch(e){
			var msg = e.message;
			console.log(msg);
			return "Mithril template error: " + msg + ".";
		}
	};

	//	Returns an ajax loadable template
	context.m.template.load = function(url){
		return m.request({
			method: "GET",
			url: url,
			deserialize: function(value) {
				return value;
			}
		});
	};

	//	Defines a template for later use
	context.m.template.define = function(name, tmpl){
		context.m.templates[name] = tmpl;
	};

	//	Compiles a defined template
	context.m.template.compile = function(name, data){
		return context.m.template(context.m.templates[name], data);
	};

}(window));


text:
function [p, Info] = camd (A, Control, C)				    %#ok
%CAMD p = camd (A), the approximate minimum degree ordering of A
%    P = CAMD (S) returns the approximate minimum degree permutation vector for
%    the sparse matrix C = S+S'.  The Cholesky factorization of C (P,P), or
%    S (P,P), tends to be sparser than that of C or S.  CAMD tends to be faster
%    than SYMMMD and SYMAMD, and tends to return better orderings than SYMMMD.
%    S must be square. If S is full, camd(S) is equivalent to camd(sparse(S)).
%
%    Usage:  P = camd (S) ;                   % finds the ordering
%            [P, Info] = camd (S,Control,C) ; % optional parameters & statistics
%            Control = camd ;                 % returns default parameters
%            camd ;                           % prints default parameters.
%
%       Control (1); If S is n-by-n, then rows/columns with more than
%           max (16, (Control (1))* sqrt(n)) entries in S+S' are considered
%           "dense", and ignored during ordering.  They are placed last in the
%           output permutation.  The default is 10.0 if Control is not present.
%       Control (2): If nonzero, then aggressive absorption is performed.
%           This is the default if Control is not present.
%       Control (3): If nonzero, print statistics about the ordering.
%
%       Info (1): status (0: ok, -1: out of memory, -2: matrix invalid)
%       Info (2): n = size (A,1)
%       Info (3): nnz (A)
%       Info (4): the symmetry of the matrix S (0.0 means purely unsymmetric,
%           1.0 means purely symmetric).  Computed as:
%           B = tril (S, -1) + triu (S, 1) ; symmetry = nnz (B & B') / nnz (B);
%       Info (5): nnz (diag (S))
%       Info (6): nnz in S+S', excluding the diagonal (= nnz (B+B'))
%       Info (7): number "dense" rows/columns in S+S'
%       Info (8): the amount of memory used by CAMD, in bytes
%       Info (9): the number of memory compactions performed by CAMD
%
%    The following statistics are slight upper bounds because of the
%    approximate degree in CAMD.  The bounds are looser if "dense" rows/columns
%    are ignored during ordering (Info (7) > 0).  The statistics are for a
%    subsequent factorization of the matrix C (P,P).  The LU factorization
%    statistics assume no pivoting.
%
%       Info (10): the number of nonzeros in L, excluding the diagonal
%       Info (11): the number of divide operations for LL', LDL', or LU
%       Info (12): the number of multiply-subtract pairs for LL' or LDL'
%       Info (13): the number of multiply-subtract pairs for LU
%       Info (14): the max # of nonzeros in any column of L (incl. diagonal)
%       Info (15:20): unused, reserved for future use
%
%    An assembly tree post-ordering is performed, which is typically the same
%    as an elimination tree post-ordering.  It is not always identical because
%    of the approximate degree update used, and because "dense" rows/columns
%    do not take part in the post-order.  It well-suited for a subsequent
%    "chol", however.  If you require a precise elimination tree post-ordering,
%    then do the following:
%
%    Example:
%       P = camd (S) ;
%       C = spones (S) + spones (S') ;  % skip this if S already symmetric
%       [ignore, Q] = etree (C (P,P)) ;
%       P = P (Q) ;
%
%    CAMD has the ability to order the matrix with constraints.  Each
%    node i in the graph (row/column i in the matrix) has a constraint,
%    C(i), which is in the range 1 to n.  All nodes with C(i) = 1 are
%    ordered first, followed by all nodes with constraint 2, and so on.
%    That is, C(P) is monotonically non-decreasing.  If C is not provided,
%    no constraints are used (the ordering will be similar to AMD's ordering,
%    except that the postordering is different).
%
%    See also AMD, COLMMD, COLAMD, COLPERM, SYMAMD, SYMMMD, SYMRCM.

% Copyright 1994-2007, Tim Davis, Patrick R. Amestoy, Iain S. Duff, and Y. Chen.
%
%    Acknowledgements: This work was supported by the National Science
%       Foundation, under grants ASC-9111263, DMS-9223088, and CCR-0203270,
%       and by Sandia National Laboratories.
%

help camd
error ('camd mexFunction not found!  Type "camd_make" in MATLAB to compile camd');


text:
#include "aitree.h"

/*
 * The constructor passes the start node, goal node and the number of
 * operators to the constructor of class Search.
 */
DepthTree::DepthTree(int op, Node *start, Node *goal)
    :Search(op, start, goal)
{
    maxdepth = 0;
}

/*
 * setdepth() is called by the application to limit the depth of
 * of the search.
 */
void DepthTree::setdepth(unsigned depth)
{
    maxdepth = depth;
}

unsigned DepthTree::getdepth() const
{
    return(maxdepth);
}

/*
 * add() adds a node to the search graph. add() does not check whether the
 * node is already in the graph. It does check however if the depth bound
 * has been reached (if a depth bound for the search has been set). If so,
 * the node is not added to the graph. A depth-first search is established
 * by adding the node to the head of OPEN.
 */
int DepthTree::add(Node *succ)
{
    if (maxdepth)
    {
        unsigned depth;
        DepthNode *par,
	          *dsucc = (DepthNode *)succ;

	/*
	 * Compute current depth of the tree and compare this to
	 * the depth bound.
	 */
        par = (DepthNode *)dsucc->getparent();
	depth = par->getdepth() + 1;

        if (depth >= maxdepth)
	    return(0);

	dsucc->setdepth(depth);
    }

    open.addtohead(succ);
    return(1);
}


text:
const baseConfig = require('./base.conf');

module.exports = function (config) {
  baseConfig({
    set(base) {
      base.browsers = [];
      base.customLaunchers = null;
      base.forceJSONP = true;
      base.logLevel = config.LOG_DEBUG;
      base.transports = ['polling'];
      config.set(base);
    },
  });
};


text:
module.exports = function(context) {
    return function(e) {
        var sel = d3.select(e.popup._contentNode);

        sel.selectAll('.cancel')
            .on('click', clickClose);

        sel.selectAll('.save')
            .on('click', saveFeature);

        sel.selectAll('.add')
            .on('click', addRow);

        sel.selectAll('.delete-invert')
            .on('click', removeFeature);

        function clickClose() {
            context.map.closePopup(e.popup);
        }

        function removeFeature() {
            if (e.popup._source && context.mapLayer.hasLayer(e.popup._source)) {
                context.mapLayer.removeLayer(e.popup._source);
                context.data.set({map: context.mapLayer.toGeoJSON()}, 'popup');
            }
        }

        function saveFeature() {
            var obj = {};
            var table = sel.select('table.marker-properties');
            table.selectAll('tr').each(collectRow);
            function collectRow() {
                if (d3.select(this).selectAll('input')[0][0].value) {
                    obj[d3.select(this).selectAll('input')[0][0].value] =
                        d3.select(this).selectAll('input')[0][1].value;
                }
            }
            e.popup._source.feature.properties = obj;
            context.data.set({map: context.mapLayer.toGeoJSON()}, 'popup');
            context.map.closePopup(e.popup);
        }

        function addRow() {
            var tr = sel.select('table.marker-properties tbody')
                .append('tr');

            tr.append('th')
                .append('input')
                .attr('type', 'text');

            tr.append('td')
                .append('input')
                .attr('type', 'text');
        }
    };
};


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>RFID Serial C++ Library for Linux: Graph Legend</title>

<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />

<link href="search/search.css" rel="stylesheet" type="text/css"/>

RFID Serial C++ Library for Linux

This library offers a bunch of methods and opbject to communicate via serial device with a CAEN SpA. RFID reader via easy2read protocol.

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Graph Legend

This page explains how to interpret the graphs that are generated by doxygen.

Consider the following example:

/*! Invisible class because of truncation */
class Invisible { };

/*! Truncated class, inheritance relation is hidden */
class Truncated : public Invisible { };

/* Class not documented with doxygen comments */
class Undocumented { };

/*! Class that is inherited using public inheritance */
class PublicBase : public Truncated { };

/*! A template class */
template<class T> class Templ { };

/*! Class that is inherited using protected inheritance */
class ProtectedBase { };

/*! Class that is inherited using private inheritance */
class PrivateBase { };

/*! Class that is used by the Inherited class */
class Used { };

/*! Super class that inherits a number of other classes */
class Inherited : public PublicBase,
                  protected ProtectedBase,
                  private PrivateBase,
                  public Undocumented,
                  public Templ<int>
{
  private:
    Used *m_usedClass;
};

 This will result in the following graph:

The boxes in the above graph have the following meaning:

A filled gray box represents the struct or class for which the graph is generated.

A box with a black border denotes a documented struct or class.

A box with a grey border denotes an undocumented struct or class.

A box with a red border denotes a documented struct or class forwhich not all inheritance/containment relations are shown. A graph is truncated if it does not fit within the specified boundaries.

The arrows have the following meaning:

A dark blue arrow is used to visualize a public inheritance relation between two classes.

A dark green arrow is used for protected inheritance.

A dark red arrow is used for private inheritance.

A purple dashed arrow is used if a class is contained or used by another class. The arrow is labeled with the variable(s) through which the pointed class or struct is accessible.

A yellow dashed arrow denotes a relation between a template instance and the template class it was instantiated from. The arrow is labeled with the template parameters of the instance.

 All Classes Files Functions Variables Typedefs Defines

<address class="footer">
Generated on Wed Sep 4 2013 07:46:45 for RFID Serial C++ Library for Linux by

 1.7.6.1
</address>


text:
import requests
import os

DOCUMENTATION = '''
---
module: foreman_provisioner
version_added: "0.1"
short_description: Provision servers via Foreman
description:
   - Provision servers via Foreman
options:
   username:
     description:
         - login username to authenticate to Foreman
     required: true
     default: admin
   password:
     description:
         - Password of login user
     required: true
   auth_url:
     description:
         - The Foreman api url
     required: true
   host_id:
     description:
         - Name or ID of the host as listed in foreman
     required: true
   rebuild:
     description:
         - Should we rebuilt the requested host
     default: true
     required: false
   mgmt_strategy:
     description:
         - Whether to use Foreman or system ipmi command.
     default: 'foreman'
     required: false
   mgmt_action:
     description:
         - Which command to send with the power-management selected by
         mgmt_strategy. For example: reset, reboot, cycle
     default: 'cycle'
     required: false
   ipmi_username:
     description:
         - Host IPMI username
     default: 'ADMIN'
     required: false
   ipmi_password:
     description:
         - Host IPMI password
     default: 'ADMIN'
     required: false
   wait_for_host:
     description:
         - Number of seconds we should wait for the host given the 'rebuild' state was set.
     default: 10
     required: false
'''

MIN_SUPPORTED_VERSION = 2
MGMT_SUPPORTED_STRATEGIES = ['foreman', 'ipmi']

class ForemanManager(object):
    """
    This class represents a simple interface for foreman* to easily rebuild /
    get / reserve hosts from foreman.
    *Foreman: http://theforeman.org/
    """
    def __init__(self, url, username, password, extra_headers=None, version=2):
        """
        :param url: the url of the foreman we wish to authenticate with
        :param username: the username we will use to login
        :param password: the password we will use to login
        :param extra_headers: if we require extra headers to be added to the
        http request
        :param version: the version of foreman API we wish to use (default: 2)
        :type version: int
        """
        if version < MIN_SUPPORTED_VERSION:
            raise Exception("API version: {0} "
                            "is not supported at the moment".format(version))

        self.session = requests.Session()
        self.session.auth = (username, password)

        headers = {'Accept': 'application/json',
                   'Content-type': 'application/json'}

        if extra_headers:
            headers.update(extra_headers)

        self.session.headers.update(headers)

        self.url = url.rstrip('/')
        self.default_uri = '/api/v2/hosts/'

    def reserve_host(self, host_id):
        """
        This method 'tags' a host as reserved in foreman
        :param host_id: the name of ID of the host we wish to reserve
        :returns: the host information on success, else empty body
        :rtype: list of dictionaries -- [{"host": {}}]
        """
        #TODO(tkammer): add the option to provide the query itself after "?"
        request_url = '{0}/api/hosts_reserve' \
                      '?query=name ~ {1}'.format(self.url, host_id)
        response = self.session.get(request_url, verify=False)
        body = response.json()
        return body

    def release_host(self, host_id):
        """
        This method removed the 'tag' made by 'reserve_host" in foreman
        :param host_id: the name or ID of the host we wish to release
        :returns: the host name
        :rtype: list of strings
        """
        request_url = '{0}/api/hosts_release' \
                      '?query=name ~ {1}'.format(self.url, host_id)
        response = self.session.get(request_url, verify=False)
        body = response.json()
        Exception(body)
        return body

    def get_host(self, host_id):
        """
        This method returns the host details as listed in the foreman
        :param host_id: the name or ID of the host we wish to get
        :returns: host information
        :rtype: dict
        """
        request_url = '{0}/{1}/{2}'.format(self.url, self.default_uri, host_id)
        response = self.session.get(request_url, verify=False)
        body = response.json()
        return body

    def update_host(self, host_id, update_info):
        """
        This method updates a host details in foreman
        :param host_id: the name or ID of the host we wish to update
        :param update_info: params we wish to update on foreman
        :type update_info: dict
        :returns: host information
        :rtype: dict
        """
        request_url = '{0}/{1}/{2}'.format(self.url, self.default_uri, host_id)
        response = self.session.put(request_url, data=update_info, verify=False)
        body = response.json()
        return body.get('host')

    def set_build_on_host(self, host_id, flag):
        """
        sets the 'build' flag of a host to a given :param flag:
        :param host_id: the id or name of the host as it is listed in foreman
        :param flag: a boolean value (true/false) to set the build flag with
        """
        host = self.update_host(host_id, json.dumps({'build': flag}))
        self.get_host(host_id)
        if self.get_host(host_id).get('build') != flag:
            raise Exception("Failed setting build on host {0}".format(host_id))

    def bmc(self, host_id, command):
        """
        execute a command through the BMC plugin (on/off/restart/shutdown/etc)
        :param host_id: the id or name of the host as it is listed in foreman
        :param command: the command to send through the BMC plugin, supported
        commands: 'status', 'on', 'off', 'cycle', 'reset', 'soft'
        """
        request_url = '{0}/{1}/{2}/power'.format(self.url, self.default_uri, host_id)
        command = json.dumps({'power_action': command})
        response = self.session.put(request_url, data=command, verify=False)
        #TODO(tkammer): add verification that the BMC command was issued

    def ipmi(self, host_id, command, username, password):
        """
        execute a command through the ipmitool
        :param host_id: the ipmi id of the host
        :param command: the command to send through the ipmitool
        :param username: host IPMI username
        :param password: host IPMI password
        commands: 'status', 'on', 'off', 'cycle', 'reset', 'soft' # TBD
        """
        command = "ipmitool -I lanplus -H {host_id} -U {username} -P " \
                  "{password} chassis power {cmd}".format(
            host_id=host_id, username=username, password=password, cmd=command)
        return_code = subprocess.call(command, shell=True)

        if return_code:
            raise Exception("Call to {0}, returned with {1}".format(command, return_code))

    def _validate_bmc(self, host_id):
        """
        This method validate that there is at least one BMC on the given host
        :param host_id: the id or name of the host as it is listed in foreman
        """
        request_url = '{0}/{1}/{2}/interfaces'.format(
            self.url, self.default_uri, host_id)
        response = self.session.get(request_url, verify=False)
        body = response.json()
        missing_bmc = True
        for interface in body['results']:
            if "BMC" in interface['type'].upper():
                missing_bmc = False
                break
        return missing_bmc

    def provision(self, host_id, mgmt_strategy, mgmt_action,
                  ipmi_username, ipmi_password, wait_for_host=10):
        """
        This method rebuilds a machine, doing so by running get_host and bmc.
        :param host_id: the name or ID of the host we wish to rebuild
        :param mgmt_strategy: the way we wish to reboot the machine
        (i.e: foreman, ipmi, etc)
        :param mgmt_action: the action we wish to use with the strategy
        (e.g: cycle, reset, etc)
        :param wait_for_host: number of seconds the function waits after host
        finished rebuilding before checking connectivity
        :param ipmi_username: remote server username (IPMI)
        :param ipmi_password: remote server password (IPMI)
        :raises: KeyError if BMC hasn't been found on the given host
                 Exception in case of machine could not be reached after
                 rebuild
        """
        wait_for_host = int(wait_for_host)
        if self._validate_bmc(host_id):
            raise KeyError("BMC not found on {}".format(host_id))
        building_host = self.get_host(host_id)
        self.set_build_on_host(host_id, True)
        if mgmt_strategy == 'foreman':
            self.bmc(host_id, mgmt_action)
        elif mgmt_strategy == 'ipmi':
            host = "{0}.{1}".format(building_host.get('interfaces')[0].get('name'), building_host.get('domain_name'))
            self.ipmi(host, mgmt_action, ipmi_username, ipmi_password)
        else:
            raise Exception("{0} is not a supported "
                            "management strategy".format(mgmt_strategy))
        if wait_for_host:
            while self.get_host(host_id).get('build'):
                time.sleep(wait_for_host)

            command = "ping -q -c 30 -w 300 {0}".format(building_host.get('name'))
            return_code = subprocess.call(command, shell=True)

            if return_code:
                raise Exception("Could not reach {0}, rc={1}, cmd={2}".format(host_id, return_code, command))

def main():
    module = AnsibleModule(
        argument_spec=dict(
            username=dict(default='admin'),
            password=dict(required=True),
            auth_url=dict(required=True),
            host_id=dict(required=True),
            rebuild=dict(default=True, type='bool', choices=BOOLEANS),
            mgmt_strategy=dict(default='foreman',
                               choices=MGMT_SUPPORTED_STRATEGIES),
            mgmt_action=dict(default='cycle', choices=['on', 'off', 'cycle',
                                                       'reset', 'soft']),
            wait_for_host=dict(default=10),
            ipmi_username=dict(default='ADMIN'),
            ipmi_password=dict(default='ADMIN')))

    foreman_client = ForemanManager(url=module.params['auth_url'],
                                    username=module.params['username'],
                                    password=module.params['password'])

    status_changed = False

    if module.boolean(module.params['rebuild']):
        try:
            foreman_client.provision(module.params['host_id'],
                                     module.params['mgmt_strategy'],
                                     module.params['mgmt_action'],
                                     module.params['ipmi_username'],
                                     module.params['ipmi_password'],
                                     module.params['wait_for_host'])
        except KeyError as e:
            module.fail_json(msg=e.message)
        else:
            status_changed = True

    #TODO(tkammer): implement RESERVE and RELEASE
    host = foreman_client.get_host(module.params['host_id'])
    interface = foreman_client.get_host('{0}/interfaces'.format(module.params['host_id']))
    if host.has_key('error'):
        module.fail_json(msg=host['error'])

    module.exit_json(changed=status_changed, host=host, interface=interface)

from ansible.module_utils.basic import *
main()


text:
<!DOCTYPE html>

		<title>Adventure Time!</title>
		<link = rel="stylesheet" type="text/css" href="stylesheets/blog.css"></link>

Adventure Time!

 When you think of the times in your life where you've been the happiest, the proudest, or the most satisfied, which values come to mind?

Adventure

Coolness under fire

Creativity

Personal development

Competence

Pick one value and write a couple of sentences about why one of the values you chose is important to you.

Creativity is important to me because it is a form of expression.  In any type of work you do you have to express yourself and creativity allows to do that in your own way, which makes your work unique.

In general, I try to live up to these values:

Disagree 1 ---- 2 ---- 3 ---- 4 ---- 5 Agree

Adventure - 5

Coolness under fire - 5

Creativity - 5

Personal development - 5

Competence - 5

What was the last topic that someone asked for your advice on?

The only instance I can remember clearly is when my friend asked  me for romantic advice.  I gave him my two cents and the issues he was having and helped him as best as I could.  I think it was more about communicating your issue rather than the answer itself in that situation.  Sometimes you know what you need to do you just need to affirmation to do it.

How do you feel when you think about your values? Do you think it can help you mediate stereotype threat if you recognize you feel it?

Yes I think it can help me mediate the stereotype threat.  Part of having values is knowing who you are as a person and what you stand for.  I think if you have a good sense of that you will be able to handle any situation that could be stressful to you.

Can you think of any other exercises you can use to help you when you are feeling down (for whatever reason) at DBC?

Just take a 15 minute break and listen to your favorite music or watch some funny videos like vines.  I think having this break can help relieve stress in an efficient and timely manner.

Written By

				Andres Saavedra


text:
function testCore() {
    const button: HTMLElement = new HTMLButtonElement();

    const config: qq.BasicOptions = {
        autoUpload: true,
        button,
        debug: true,
        disableCancelForFormUploads: true,
        formatFileName: (rawFileName: string) => {
            return "hi";
        },
        maxConnections: 10,
        multiple: true
    };

    const uploader = new qq.FineUploaderBasic(config);
}


text:
using System;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using STEP;

namespace IFC
{
	/// <summary>
	/// <see href="http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifcperson.htm"/>
	/// </summary>
	public  partial class IfcPerson : BaseIfc
	{
		public IfcIdentifier Identification{get;set;} // optional
		public IfcLabel FamilyName{get;set;} // optional
		public IfcLabel GivenName{get;set;} // optional
		public List<IfcLabel> MiddleNames{get;set;} // optional
		public List<IfcLabel> PrefixTitles{get;set;} // optional
		public List<IfcLabel> SuffixTitles{get;set;} // optional
		public List<IfcActorRole> Roles{get;set;} // optional
		public List<IfcAddress> Addresses{get;set;} // optional
		public List<IfcPersonAndOrganization> EngagedIn{get;set;} // inverse

		/// <summary>
		/// Construct a IfcPerson with all required attributes.
		/// </summary>
		public IfcPerson():base()
		{
			MiddleNames = new List<IfcLabel>();
			PrefixTitles = new List<IfcLabel>();
			SuffixTitles = new List<IfcLabel>();
			Roles = new List<IfcActorRole>();
			Addresses = new List<IfcAddress>();
			EngagedIn = new List<IfcPersonAndOrganization>();

		}
		/// <summary>
		/// Construct a IfcPerson with required and optional attributes.
		/// </summary>
		[JsonConstructor]
		public IfcPerson(IfcIdentifier identification,IfcLabel familyName,IfcLabel givenName,List<IfcLabel> middleNames,List<IfcLabel> prefixTitles,List<IfcLabel> suffixTitles,List<IfcActorRole> roles,List<IfcAddress> addresses):base()
		{
			EngagedIn = new List<IfcPersonAndOrganization>();

			Identification = identification;
			FamilyName = familyName;
			GivenName = givenName;
			MiddleNames = middleNames;
			PrefixTitles = prefixTitles;
			SuffixTitles = suffixTitles;
			Roles = roles;
			Addresses = addresses;

		}
		public static  IfcPerson FromJSON(string json){ return JsonConvert.DeserializeObject<IfcPerson>(json); }

        public override string GetStepParameters()
        {
            var parameters = new List<string>();
			parameters.Add(Identification != null ? Identification.ToStepValue() : "$");
			parameters.Add(FamilyName != null ? FamilyName.ToStepValue() : "$");
			parameters.Add(GivenName != null ? GivenName.ToStepValue() : "$");
			parameters.Add(MiddleNames != null ? MiddleNames.ToStepValue() : "$");
			parameters.Add(PrefixTitles != null ? PrefixTitles.ToStepValue() : "$");
			parameters.Add(SuffixTitles != null ? SuffixTitles.ToStepValue() : "$");
			parameters.Add(Roles != null ? Roles.ToStepValue() : "$");
			parameters.Add(Addresses != null ? Addresses.ToStepValue() : "$");

            return string.Join(", ", parameters.ToArray());
        }
	}
}


text:
/*
 * ModelRegistration.h
 *
 *  Created on: Apr 18, 2014
 *      Author: edgar
 */

#ifndef MODELREGISTRATION_H_
#define MODELREGISTRATION_H_

#include <iostream>
#include <opencv2/core/core.hpp>

class ModelRegistration
{
public:

  ModelRegistration();
  virtual ~ModelRegistration();

  void setNumMax(int n) { max_registrations_ = n; }

  std::vector<cv::Point2f> get_points2d() const { return list_points2d_; }
  std::vector<cv::Point3f> get_points3d() const { return list_points3d_; }
  int getNumMax() const { return max_registrations_; }
  int getNumRegist() const { return n_registrations_; }

  bool is_registrable() const { return (n_registrations_ < max_registrations_); }
  void registerPoint(const cv::Point2f &point2d, const cv::Point3f &point3d);
  void reset();

private:
/** The current number of registered points */
int n_registrations_;
/** The total number of points to register */
int max_registrations_;
/** The list of 2D points to register the model */
std::vector<cv::Point2f> list_points2d_;
/** The list of 3D points to register the model */
std::vector<cv::Point3f> list_points3d_;
};

#endif /* MODELREGISTRATION_H_ */


text:
require 'ebay/types/selling_manager_search'
require 'ebay/types/pagination'
require 'ebay/types/time_range'

module Ebay # :nodoc:
  module Requests # :nodoc:
    # == Attributes
    #  object_node :search, 'Search', :class => SellingManagerSearch, :optional => true
    #  numeric_node :store_category_id, 'StoreCategoryID', :optional => true
    #  value_array_node :filters, 'Filter', :default_value => []
    #  boolean_node :archived, 'Archived', 'true', 'false', :optional => true
    #  text_node :sort, 'Sort', :optional => true
    #  text_node :sort_order, 'SortOrder', :optional => true
    #  object_node :pagination, 'Pagination', :class => Pagination, :optional => true
    #  object_node :sale_date_range, 'SaleDateRange', :class => TimeRange, :optional => true
    class GetSellingManagerSoldListings < Abstract
      include XML::Mapping
      include Initializer
      root_element_name 'GetSellingManagerSoldListingsRequest'
      object_node :search, 'Search', :class => SellingManagerSearch, :optional => true
      numeric_node :store_category_id, 'StoreCategoryID', :optional => true
      value_array_node :filters, 'Filter', :default_value => []
      boolean_node :archived, 'Archived', 'true', 'false', :optional => true
      text_node :sort, 'Sort', :optional => true
      text_node :sort_order, 'SortOrder', :optional => true
      object_node :pagination, 'Pagination', :class => Pagination, :optional => true
      object_node :sale_date_range, 'SaleDateRange', :class => TimeRange, :optional => true
    end
  end
end