text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Forums extends CI_Controller {

	public function show()
	{
		$user_likes = $this->Forum->get_user_likes();
		$user = $this->Forum->get_user_info();
		$posts = $this->Forum->get_all_posts();
		$this->load->view('/discuss', array("user"=>$user, "posts"=>$posts, "user_likes"=>$user_likes));
	}
	public function post_create()
	{
		if($this->Forum->create($this->input->post())){
			redirect('/discuss');
		} else {
			redirect('/discuss');
		}
	}
	public function comment_create($id)
	{
		if($this->Forum->comm_create($this->input->post(), $id)){
			redirect('/discuss');
		} else {
			redirect('/discuss');
		}
	}
	public function like($id)
	{
		$this->Forum->like($id);
		return redirect('/discuss');
	}
	public function show_comms($id)
	{
		$the_post = $this->Forum->get_post_by_id($id);
		$all_likes = $this->Forum->get_post_likers($id);
		$comms = $this->Forum->show_comms($id);
		$this->load->view('/comments', array("the_post"=>$the_post, "all_likes"=>$all_likes, "comms"=>$comms));
	}

}
?>


text:
__author__ = "mfreer"
__date__ = "2012-07-06 17:42"
__version__ = "1.6"
__all__ = ["EgadsData", "EgadsAlgorithm"]

import logging
import weakref
import datetime
import re
import numpy
import quantities as pq  # @UnresolvedImport
import metadata
from collections import defaultdict

class EgadsData(pq.Quantity):
    """
    This class is designed using the EUFAR Standards & Protocols data and metadata
    recommendations. Its purpose is to store related data and metadata and allow them to be
    passed between functions and algorithms in a consistent manner.
    """

    __refs__ = defaultdict(list)

    def __new__(cls, value, units='', variable_metadata={}, dtype=None, **attrs):
        logging.debug('egads - egads_core.py - EgadsData - __new__')
        if isinstance(units, metadata.VariableMetadata):
            if not variable_metadata:
                variable_metadata = units
            units = units.get('units', '')
        if variable_metadata and (not units):
            units = variable_metadata.get('units', '')
            if not units:
                units = variable_metadata.get('Units', '')

        # quantities can't handle the CF time unit 'time since epoch'
        # to allow a proper operation of EGADS, a new attribute has been added,
        # transparent to the user, if the epoch is needed.
        true_units = None
        if ' since ' in units or 'after' in units:
            true_units = units
        units = _validate_units(units)
        if isinstance(value, pq.Quantity):
            ret = pq.Quantity.__new__(cls, value, value.units, dtype=dtype)
        else:
            try:
                ret = pq.Quantity.__new__(cls, value, units, dtype=dtype)
            except (LookupError, SyntaxError):
                ret = pq.Quantity.__new__(cls, value, units="", dtype=dtype)
        if isinstance(variable_metadata, metadata.VariableMetadata):
            ret.metadata = variable_metadata
        else:
            ret.metadata = metadata.VariableMetadata(variable_metadata)
        if true_units:
            ret.metadata['units'] = true_units
        else:
            ret.metadata['units'] = units
        return ret

    def __init__(self, value, units='', variable_metadata=None, dtype='float64', **attrs):
        """
        Constructor Variables

        :param value:
            Scalar or array of values to initialize EgadsData object.
        :param string units:
            Optional - String representation of units to be used for current EgadsData instance, e.g.
            'm/s', 'kg', 'g/cm^3', etc.
        :param VariableMetadata variable_metadata:
            Optional - VariableMetadata dictionary object containing relevant metadata
            for the current EgadsData instance.
        :param **attrs:
            Optional - Keyword/value pairs of additional metadata which will be added into
            the existing variable_metadata object.
        """

        try:
            logging.debug('egads - egads_core.py - EgadsData __init__ - value [' + str(value[0]) + ' ... ' +
                          str(value[-1]) + '], units ' + str(units) + ', variale_metadata ' +
                          str(variable_metadata) + ', dtype' + str(dtype))
        except (IndexError, TypeError):
            logging.exception('egads - egads_core.py - EgadsData - __init__ - value [' + str(value) + '], units ' +
                           str(units) + ', variale_metadata ' + str(variable_metadata) + ', dtype' +
                           str(dtype))
        for key, val in attrs.iteritems():
            self.metadata[key] = val
        self.__refs__[self.__class__].append(weakref.ref(self))

    @property
    def value(self):
        return self.view(type=numpy.ndarray)

    @value.setter
    def value(self, value, indx=None):
        print value, indx

    @property
    def units(self):
        try:
            return super(EgadsData, self).units.dimensionality.string
        except KeyError:
            return ''

    @units.setter
    def units(self, units):
        pq.Quantity.units.fset(self, units)

    def __getitem__(self, other):
        metadata = None
        try:
            metadata = self.metadata.copy()
        except AttributeError:
            pass
        out = super(EgadsData, self).__getitem__(other).view(EgadsData)
        if metadata:
            out.metadata = metadata
        return out

    def __getslice__(self, i, j):
        return self.__getitem__(slice(i, j))

    def __repr__(self):
        try:
            return repr(['EgadsData', self.value, self.dimensionality.string])
        except AttributeError:
            return repr(None)

    def __add__(self, other):
        return super(EgadsData, self).__add__(other).view(EgadsData)

    def __radd__(self, other):
        return super(EgadsData, self).__radd__(other).view(EgadsData)

    def __iadd__(self, other):
        return super(EgadsData, self).__iadd__(other).view(EgadsData)

    def __sub__(self, other):
        return super(EgadsData, self).__sub__(other).view(EgadsData)

    def __rsub__(self, other):
        return super(EgadsData, self).__rsub__(other).view(EgadsData)

    def __isub__(self, other):
        return super(EgadsData, self).__isub__(other).view(EgadsData)

    def __mod__(self, other):
        return super(EgadsData, self).__mod__(other).view(EgadsData)

    def __imod__(self, other):
        return super(EgadsData, self).__imod__(other).view(EgadsData)

    def __imul__(self, other):
        return super(EgadsData, self).__imul__(other).view(EgadsData)

    def __rmul__(self, other):
        return super(EgadsData, self).__rmul__(other).view(EgadsData)

    def copy(self):
        """
        Generate and return a copy of the current EgadsData instance.
        """

        logging.debug('egads - egads_core.py - EgadsData - copy - metadata %s', self.metadata)
        var_copy = EgadsData(super(EgadsData, self).copy())
        var_copy.__dict__ = self.__dict__.copy()
        var_copy.metadata = self.metadata.copy()
        return var_copy

    def rescale(self, units):
        """
        Return a copy of the variable rescaled to the provided units.

        :param string units:
            String representation of desired units.
        """

        logging.debug('egads - egads_core.py - EgadsData - rescale - units %s to %s', self.units, units)
        units = _validate_units(units)
        metadata = None
        try:
            metadata = self.metadata.copy()
        except AttributeError:
            pass
        out = super(EgadsData, self).rescale(units).view(EgadsData)
        if metadata:
            out.metadata = metadata
        try:
            long_units = max(getattr(pq, out.units)._aliases, key=len)
            if ' since ' in out.metadata['units']:
                true_units = str(long_units) + out.metadata['units'][out.metadata['units'].index(' since '):]
                out.metadata['units'] = true_units
            else:
                out.metadata['units'] = long_units
        except (AttributeError, KeyError, ValueError):
            pass
        return out

    def print_description(self):
        """
        Generate and return a description of current EgadsData instance.
        """

        logging.debug('egads - egads_core.py - EgadsData - print_description - ' +  self._get_description())
        outstr = self._get_description()
        print outstr

    def get_units(self):
        """
        Return units used in current EgadsData instance.
        """

        logging.debug('egads - egads_core.py - EgadsData - get_units - ' +  self.units)
        return self.units

    def print_shape(self):
        """
        Prints shape of current EgadsData instance
        """

        logging.debug('egads - egads_core.py - EgadsData - print_shape - ' +  str(self._get_shape()))
        print self._get_shape()

    def _get_description(self):
        """
        Generate description of current EgadsData instance.
        """

        shape = str(self.value.shape)
        units = str(self.units)
        try:
            long_name = self.metadata['long_name']
        except KeyError:
            long_name = 'no_long_name'
        try:
            standard_name = self.metadata['standard_name']
        except KeyError:
            standard_name = 'no_standard_name'

        outstr = ('Current variable is %s with units of %s. \n' % (shape, units) +
                  'Its descriptive name is: %s and its CF name is: %s\n' % (long_name, standard_name))
        return outstr

    def _get_shape(self):
        """
        Get shape of current EgadsData instance.
        """

        return self.value.shape

    @classmethod
    def _get_instances(cls):
        """
        Generator which returns currently defined instances of EgadsData.
        """

        for inst_ref in cls.__refs__[cls]:
            inst = inst_ref()
            if inst is not None:
                yield inst

    logging.info('egads - egads_core.py - EgadsData has been loaded')

class EgadsAlgorithm(object):
    """
    EGADS algorithm base class. All egads algorithms should inherit this class.

    The EgadsAlgorithm class provides base methods for algorithms in EGADS and
    initializes algorithm attributes.
    """

    def __init__(self, return_Egads=True):
        """
        Initializes EgadsAlgorithm instance with None values for all standard
        attributes.

        Constructor Variables

        :param bool return_Egads: Optional -
            Flag used to configure which object type will be returned by the current
            EgadsAlgorithm. If ``true`` an :class: EgadsData instance with relevant
            metadata will be returned by the algorithm, otherwise an array or
            scalar will be returned.
        """

        logging.debug('egads - egads_core.py - EgadsAlgorithm - __init__ - return_egads ' +  str(return_Egads))
        self.name = self.__class__.__name__
        self.return_Egads = return_Egads
        self.metadata = None
        self.output_metadata = None
        self._output_fields = ['name', 'units', 'long_name', 'standard_name', 'fill_value',
                               'valid_range', 'sampled_rate', 'category', 'calibration_coeff',
                               'dependencies']
        self.output_properties = {}
        for key in self._output_fields:
            self.output_properties[key] = None

    def run(self, *args):
        """
        Basic run method. This method should be called from EgadsAlgorithm children,
        passing along the correct inputs to the _call_algorithm method.

        :param *args:
            Parameters to pass into algorithm in the order specified in algorithm metadata.
        """

        logging.debug('egads - egads_core.py - EgadsAlgorithm - run - name ' + self.name + ', args ' + str(args))
        if not isinstance(self.output_metadata, list):
            output_metadata = self.output_metadata
            self.output_metadata = []
            self.output_metadata.append(output_metadata)
        for metadata in self.output_metadata:
            for key, value in metadata.iteritems():
                try:
                    match = re.compile('input[0-9]+').search(value)
                    while match:
                        input_seq = metadata.get(key)[match.start():match.end()]
                        input_index = int(input_seq.strip('input'))

                        if isinstance(args[input_index], EgadsData):
                            metadata[key] = metadata[key].replace(input_seq, args[input_index].metadata.get(key, ''))
                        else:
                            metadata[key] = metadata[key].replace(input_seq, '')
                        match = re.compile('input[0-9]+').search(metadata[key])
                except TypeError:
                    match = None
                try:
                    if key == 'Category':
                        if value == ['']:
                            out_category = []
                            for arg in args:
                                if isinstance(arg, EgadsData):
                                    out_category.append(arg.metadata[key])
                            metadata[key] = out_category
                except KeyError:
                    pass
        output = self._call_algorithm(*args)
        if len(self.metadata['Outputs']) > 1:
            result = []
            for i, value in enumerate(output):
                self.output_metadata[i].set_parent(self.metadata)
                result.append(self._return_result(value, self.output_metadata[i]))
            result = tuple(result)
        else:
            self.output_metadata[0].set_parent(self.metadata)
            result = self._return_result(output, self.output_metadata[0])
        return result

    def _none_units_check(self, *args):
        try:
            for i, _ in enumerate(self.output_metadata):
                if self.output_metadata[i]['units'] is None:
                    self.output_metadata[i]['units'] = args[i].get('units', '')
        except TypeError:
            if self.output_metadata['units'] is None:
                self.output_metadata[i]['units'] = args.get('units', '')

    def _return_result(self, value, metadata):
        if self.return_Egads is True:
            result = EgadsData(value, metadata)
        else:
            result = value
        return result

    def _call_algorithm(self, *args):
        """
        Does check on arguments to pass to algorithm.

        If arguments are EgadsData instances, a check is done for expected units.
        Then the numeric value is passed to the algorithm. If argument is not
        EgadsData instance, units are assumed to be correct, and numeric value
        is passed to algorithm.
        """

        logging.debug('egads - egads_core.py - EgadsAlgorithm - _call_algorithm')
        out_arg = []
        for i, arg in enumerate(args):
            if isinstance(arg, EgadsData):
                required_units = self.metadata['InputUnits'][i]
                if required_units is not None:
                    arg_corr = arg
                    required_units = _validate_units(required_units)
                    to_dims = pq.quantity.validate_dimensionality(required_units)
                    to_temps = []
                    for to_unit in to_dims.iterkeys():
                        if isinstance(to_unit, pq.UnitTemperature):
                            to_temps.append(to_unit)
                    from_temps = []
                    for from_unit in arg._dimensionality.iterkeys():
                        if isinstance(from_unit, pq.UnitTemperature):
                            from_temps.append(from_unit)
                    for from_temp, to_temp in zip(from_temps, to_temps):
                        if from_temp._dimensionality != to_temp._dimensionality:
                            if 'degC' in str(from_temp) and 'K' in str(to_temp):
                                arg_corr = arg_corr + EgadsData(value=273.15, units=from_temp)
                            elif 'K' in str(from_temp) and 'degC' in str(to_temp):
                                arg_corr = arg_corr - EgadsData(value=273.15, units=from_temp)
                            else:
                                pass
                    arg_corr = arg_corr.rescale(required_units)
                    out_arg.append(arg_corr.value)
                else:
                    out_arg.append(arg.value)
            else:
                out_arg.append(numpy.array(arg))
        result = self._algorithm(*out_arg)
        self.time_stamp()
        self.processor()
        return result

    def _algorithm(self):
        """
        Skeleton algorithm method. Must be defined in EgadsAlgorithm children.
        """

        raise AssertionError('Algorithm not implemented')

    def get_info(self):
        """
        Print docstring of algorithm to standard output.
        """

        logging.debug('egads - egads_core.py - EgadsAlgorithm - get_info')
        print self.__doc__

    def time_stamp(self):
        """
        Calculate and set date processed for all output variables.
        """

        logging.debug('egads - egads_core.py - EgadsAlgorithm - time_stamp.')
        for output in self.output_metadata:
                output['DateProcessed'] = self.now()

    def now(self):
        """
        Calculate and return current date/time in ISO 8601 format.
        """

        logging.debug('egads - egads_core.py - EgadsAlgorithm - now - time_stamp ' + datetime.datetime.isoformat(datetime.datetime.today()))
        return datetime.datetime.isoformat(datetime.datetime.today())

    def processor(self):
        """
        Indicate the algorithm used to produce the output variable
        """
        logging.debug('egads - egads_core.py - EgadsAlgorithm - processor')
        for output in self.output_metadata:
                output['Processor'] = self.metadata['Processor']

    def _populate_data_object(self, value, metadata):
        """
        Method for automatically populating new EgadsData instance
        with calculated value and algorithm/variable metadata.
        """

        result = EgadsData(value, metadata)
        for key, val in self.output_properties.iteritems():
            result.__setattr__(key, val)
        return result

    logging.info('egads - egads_core.py - EgadsAlgorithm has been loaded')

def _validate_units(units):
    """
    Function to pre-validate units to be passed into Quantities for comprehension.

    Corrects string units which are written without carets or multiplication symbols:
    'kg m-3' becomes 'kg*m^-3'

    In quantities 0.10.1+, the '%' symbol is not correctly recognized. Thus corrects
    the '%' symbol to 'percent'.

    In few atmospheric measurement dataset, '0.01' can be used to represent '%'. Thus
    corrects the '0.01' symbol to 'percent'.

    In few atmospheric measurement dataset, dimensionless data based on event have their
    units equal to '1'. Thus corrects the '1' to 'dimensionless'.

    In quantities, the time unit 'time since ...' is not correctly recognized. Thus
    corrects the 'time since ...' to 'time'.
    """

    logging.debug('egads - egads_core.py - _validate_units - units ' + str(units))

    # few patches have been introduced for compatibility"
    if "degree_" in units or "decimal degree" in units:
        units = "degree"
    if units == "-":
        units = ""
    if " since " in units:
        units = units[:units.index(" since ")]
    if " after " in units:
        units = units[:units.index(" after ")]
    if " / " in units:
        units = units[:units.index(" / ")] + "/" + units[units.index(" / ")+3:]
    if isinstance(units, str) or isinstance(units, unicode):
        regex = re.compile('(?<=[A-Za-z])[0-9-]')
        match = regex.search(units)
        while match is not None:
            units = units[:match.start()] + "^" + units[match.start():]
            match = regex.search(units)
        regex_space = re.compile('[ ]+')
        units = regex_space.sub('*', units)
        if '%' in units:
            units = units.replace('%', 'percent')
        if units == '1':
            units = 'dimensionless'
        if units == '0.01':
            units = 'percent'
    return units

redpajama_set_name: RedPajamaGithub


text:
title: Responsive-Designs Erstellen
date: 2013-02-25 21:11
lang: de
---

Da ich mich immer mehr Leute fragen, wie das mit dem Responsive denn geht, dachte ich mir, die grundlegenden Informationen hierzu mal in einem kleinen Artikel zusammenzufassen, welcher gerade seine Gestalt annimmt.

Zunächst mal ist es wichtig, die Programmiersprache "CSS" einigermaßen gut zu beherrschen, denn darauf baut sich die ganze Optimierung des Designs auf. Jedes Design, das responsive ist, arbeitet mit sogenannten Media-Queries, welche seit der dritten CSS-Version auf fast allen Browsern verfügbar sind.

Das ganze Verfahren lässt sich wohl am besten durch verschiedene Beispiele erklären. Die folgenden Snippets können ganz einfach und ohne Probleme im CSS-Code der eigenen Webseite eingebettet werden.

Der folgende Code aktiviert die Attributierungen, die er enthält, wenn der Bildschirm des aufrufenden Benutzers kleiner als 1220 Pixel ist:

{% highlight css %}
@media only screen and (max-width: 1220px) {
	#testelement {
		display: block;
		position: relative;
	}
}
{% endhighlight %}

Es lassen sich alle Arten von Attributierungen im Code anbringen, da sind absolut keine Grenzen gesetzt. Jedenfalls werden diese aktiviert, wenn die eingestellten Anforderungen der Media-Queries mit dem Bildschirm übereinstimmen.

Das gleiche funktioniert auch umgekehrt. Das bedeuted, es können minimale Maße als Anforderungen für den Bildschirm gesetzt werden:

{% highlight css %}
@media only screen and (min-width: 660px) {
	#testelement {
		overflow: hidden;
		border: medium double #000;
	}
}
{% endhighlight %}

So können alle Code-Elemente einer Webseite angesprochen werden, bis jedes Element an die Maße des Bildschirms angepasst ist. Und schon sind sie fertig!


text:
var fs = require('fs');
var resolve = require('path').resolve;
var whiskers = require('./whiskers');

module.exports = function(path, options, fn) {
  var templates = [path];
  var partials = [''];  // empty string at index 0
  for (var p in options.partials) {
    if (typeof options.partials[p] !== "function") {
        partials.push(p);
        templates.push(resolve(options.settings.views, options.partials[p]));
      }
  }
  var pending = templates.length;

  function compile(path, fn) {
    var compiled = whiskers.cache[path];
    // cached
    if (options.cache && compiled) return fn(null, compiled);
    // read
    fs.readFile(path, 'utf8', function(err, str){
      if (err) return fn(err);
      compiled = whiskers.compile(str);
      if (options.cache) whiskers.cache[path] = compiled;
      fn(null, compiled);
    });
  }

  templates.forEach(function(template, i){
    compile(template, function(err, compiled){
      if (err) return fn(err);
      // the view is the first template
      if (i == 0) {
        path = compiled;
      } else {
        options.partials[partials[i]] = compiled;
        if (!options[partials[i]]) options[partials[i]] = compiled;
      }
      --pending || fn(null, path(options));
    });
  });
};


text:
class AddDeletedAtToUsers < ActiveRecord::Migration
  def change
    add_column :users, :deleted_at, :datetime
    add_index :users, :deleted_at

    add_column :posts, :deleted_at, :datetime
    add_index :posts, :deleted_at

    add_column :comments, :deleted_at, :datetime
    add_index :comments, :deleted_at
  end
end


text:
#ifndef MAIN_MENU_H
#define MAIN_MENU_H

#include "game_state.h"

extern void initMMState(gs_t *);

#endif


text:
namespace acid {
Entity::Entity(const std::filesystem::path &filename) {
	auto entityPrefab = EntityPrefab::Create(filename);
	*entityPrefab >> *this;
}

void Entity::Update() {
	for (auto it = components.begin(); it != components.end();) {
		if ((*it)->IsRemoved()) {
			it = components.erase(it);
			continue;
		}

		if ((*it)->GetEntity() != this)
			(*it)->SetEntity(this);

		if ((*it)->IsEnabled()) {
			if (!(*it)->started) {
				(*it)->Start();
				(*it)->started = true;
			}

			(*it)->Update();
		}

		++it;
	}
}

Component *Entity::AddComponent(std::unique_ptr<Component> &&component) {
	if (!component) return nullptr;

	component->SetEntity(this);
	return components.emplace_back(std::move(component)).get();
}

void Entity::RemoveComponent(Component *component) {
	components.erase(std::remove_if(components.begin(), components.end(), [component](std::unique_ptr<Component> &c) {
		return c.get() == component;
	}), components.end());
}

void Entity::RemoveComponent(const std::string &name) {
	components.erase(std::remove_if(components.begin(), components.end(), [name](std::unique_ptr<Component> &c) {
		return name == c->GetTypeName();
	}), components.end());
}
}


text:
using System;
using System.Text;
using System.Security.Permissions;
using System.Runtime.Serialization;
using OpenADK.Library;
using OpenADK.Library.Global;
using OpenADK.Library.us.Common;

namespace OpenADK.Library.us.Assessment{

/// <summary>A FeedbackItem</summary>
/// <remarks>
///
/// <para>Author: Generated by adkgen</para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.6</para>
/// </remarks>
[Serializable]
public class FeedbackItem : SifElement
{
	/// <summary>
	/// Creates an instance of a FeedbackItem
	/// </summary>
	public FeedbackItem() : base ( AssessmentDTD.FEEDBACKITEM ){}

	/// <summary>
	/// Constructor used by the .Net Serialization formatter
	/// </summary>
	[SecurityPermission( SecurityAction.Demand, SerializationFormatter=true )]
	protected FeedbackItem( SerializationInfo info, StreamingContext context ) : base( info, context ) {}
	/// <summary>
	/// Gets or sets the value of the <c><FeedbackCode></c> element.
	/// </summary>
	/// <value> The <c>FeedbackCode</c> element of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this element as: "If there is a coding system associated with the feedback concerning the score, then this will identify that code. The format and content of the code is determined by the assessment program."</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public string FeedbackCode
	{
		get
		{
			return (string) GetSifSimpleFieldValue( AssessmentDTD.FEEDBACKITEM_FEEDBACKCODE ) ;
		}
		set
		{
			SetFieldValue( AssessmentDTD.FEEDBACKITEM_FEEDBACKCODE, new SifString( value ), value );
		}
	}

	/// <summary>
	/// Gets or sets the value of the <c><DiagnosticStatement></c> element.
	/// </summary>
	/// <value> The <c>DiagnosticStatement</c> element of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this element as: "Psychometric purpose or design-related comment about the question."</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public string DiagnosticStatement
	{
		get
		{
			return (string) GetSifSimpleFieldValue( AssessmentDTD.FEEDBACKITEM_DIAGNOSTICSTATEMENT ) ;
		}
		set
		{
			SetFieldValue( AssessmentDTD.FEEDBACKITEM_DIAGNOSTICSTATEMENT, new SifString( value ), value );
		}
	}

	/// <summary>
	/// Gets or sets the value of the <c><FeedbackDescription></c> element.
	/// </summary>
	/// <value> The <c>FeedbackDescription</c> element of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this element as: "This is further qualification of a Student Score. If this is a teacher scored item, then this may be comments the teacher is providing back to the student."</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public string FeedbackDescription
	{
		get
		{
			return (string) GetSifSimpleFieldValue( AssessmentDTD.FEEDBACKITEM_FEEDBACKDESCRIPTION ) ;
		}
		set
		{
			SetFieldValue( AssessmentDTD.FEEDBACKITEM_FEEDBACKDESCRIPTION, new SifString( value ), value );
		}
	}

	/// <summary>
	/// Gets or sets the value of the <c><FeedbackSource></c> element.
	/// </summary>
	/// <value> The <c>FeedbackSource</c> element of this object.</value>
	/// <remarks>
	/// <para>The SIF specification defines the meaning of this element as: "This indicates the source for this feedback. May indicate if this is teacher, scorer, or system generated feedback. Values for this attribute would be determined by the assessment program."</para>
	/// <para>Version: 2.6</para>
	/// <para>Since: 2.6</para>
	/// </remarks>
	public string FeedbackSource
	{
		get
		{
			return (string) GetSifSimpleFieldValue( AssessmentDTD.FEEDBACKITEM_FEEDBACKSOURCE ) ;
		}
		set
		{
			SetFieldValue( AssessmentDTD.FEEDBACKITEM_FEEDBACKSOURCE, new SifString( value ), value );
		}
	}

}}


text:
package org.broad.igv.ui.color;

import org.broad.igv.logging.*;
import org.broad.igv.util.ObjectCache;

import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * Miscellaneous utilities for parsing and manipulating colors.
 *
 * @author Jim Robinson
 */
public class ColorUtilities {

    private static Logger log = LogManager.getLogger(ColorUtilities.class);

    public static ObjectCache<Object, Color> colorCache = new ObjectCache<>(1000);
    private static ObjectCache<Color, Color> slightlyDarkerCache = new ObjectCache<>(1000);
    private static Map<Integer, Color> grayscaleColors = new HashMap();

    // HTML 4.1 color table,  + orange and magenta
    static Map<String, String> colorSymbols = new HashMap();
    private static Map<String, ColorPalette> palettes;
    public static Map<Color, float[]> componentsCache = Collections.synchronizedMap(new HashMap<>());

    static {
        colorSymbols.put("white", "FFFFFF");
        colorSymbols.put("silver", "C0C0C0");
        colorSymbols.put("gray", "808080");
        colorSymbols.put("black", "000000");
        colorSymbols.put("red", "FF0000");
        colorSymbols.put("maroon", "800000");
        colorSymbols.put("yellow", "FFFF00");
        colorSymbols.put("olive", "808000");
        colorSymbols.put("lime", "00FF00");
        colorSymbols.put("green", "008000");
        colorSymbols.put("aqua", "00FFFF");
        colorSymbols.put("teal", "008080");
        colorSymbols.put("blue", "0000FF");
        colorSymbols.put("navy", "000080");
        colorSymbols.put("fuchsia", "FF00FF");
        colorSymbols.put("purple", "800080");
        colorSymbols.put("orange", "FFA500");
        colorSymbols.put("magenta", "FF00FF");
    }

    /**
     * @param idx
     * @return
     * @see #randomColor(int, float)
     */
    private static int[] quasiRandomColor(int idx) {
        int BASE_COL = 40;
        int RAND_COL = 255 - BASE_COL;

        idx += 1;    // avoid 0
        int r = Math.abs(BASE_COL + (idx * 33) % RAND_COL);
        int g = Math.abs(BASE_COL + (idx * 55) % RAND_COL);
        int b = Math.abs(BASE_COL + (idx * 77) % RAND_COL);

        return new int[]{r, g, b};
    }

    /**
     * Port of DChip function of the same name.
     * Calls {@link #randomColor(int, float)} with {@code alpha=1.0}
     *
     * @param idx
     * @return
     */
    public static Color randomColor(int idx) {
        return randomColor(idx, 1.0f);
    }

    /**
     * Generate a color based on {@code idx}. Unpredictable but deterministic (like a hash)
     * Good for generating a set of colors for successive values of {@code idx}.
     * Alpha value is set as specified
     *
     * @param idx
     * @param alpha alpha value of color, from 0.0-1.0
     * @return
     */
    public static Color randomColor(int idx, float alpha) {

        int[] rgb = quasiRandomColor(idx);

        int r = rgb[0];
        int g = rgb[1];
        int b = rgb[2];

        // Reject colors too close to white
        if (r > 200 && g > 200 && b > 200) {
            int tmp = r % 3;
            if (tmp == 0) {
                r = 255 - r;
            } else if (tmp == 1) {
                g = 255 - g;
            } else {
                b = 255 - b;
            }
        }
        return new Color(r, g, b, (int) (255 * alpha));
    }

    public static Color randomDesaturatedColor(float alpha) {
        float hue = (float) Math.random();
        float brightenss = (float) (Math.random() * 0.7);
        Color base = Color.getHSBColor(hue, 0, brightenss);
        if (alpha >= 1) return base;
        else return new Color(base.getRed(), base.getGreen(), base.getBlue(), (int) (alpha * 255));

    }

    /**
     * Method description
     *
     * @param inputColor
     * @param hue
     * @param saturation
     * @param brightness
     * @return
     */
    public static Color adjustHSB(Color inputColor, float hue, float saturation, float brightness) {
        float[] hsbvals = new float[3];
        Color.RGBtoHSB(inputColor.getRed(), inputColor.getGreen(), inputColor.getBlue(), hsbvals);
        return Color.getHSBColor(hue * hsbvals[0], saturation * hsbvals[1], brightness * hsbvals[2]);
    }

    public static String colorToString(Color color) {

        StringBuffer buffer = new StringBuffer();
        buffer.append(color.getRed());
        buffer.append(",");
        buffer.append(color.getGreen());
        buffer.append(",");
        buffer.append(color.getBlue());
        return buffer.toString();
    }

    public static Color stringToColor(String string) {
        return stringToColor(string, Color.black);
    }

    public static Color stringToColor(String string, Color defaultColor) {

        if (string == null) return defaultColor;

        try {
            Color c = stringToColorNoDefault(string);
            if (c == null) {
                c = defaultColor;
            }
            colorCache.put(string, c);
            return c;
        } catch (NumberFormatException numberFormatException) {
            log.error("Error in color string. ", numberFormatException);
            return defaultColor;
        }
    }

    public static Color stringToColorNoDefault(String string) throws NumberFormatException {
        // Excel will quote color strings, strip all quotes
        string = string.replace("\"", "").replace("'", "");

        Color c = null;
        if (string.contains(",")) {
            if(string.startsWith("rgb(") && string.endsWith(")")) {
                // javascript style string
                string = string.substring(4, string.length() - 1);
            }
            if (string.contains(".")) {
                String[] rgb = string.split(",");
                int red = (int) (255 * Double.parseDouble(rgb[0]));
                int green = (int) (255 * Double.parseDouble(rgb[1]));
                int blue = (int) (255 * Double.parseDouble(rgb[2]));
                c = new Color(red, green, blue);

            } else {
                String[] rgb = string.split(",");
                int red = Integer.parseInt(rgb[0]);
                int green = Integer.parseInt(rgb[1]);
                int blue = Integer.parseInt(rgb[2]);
                c = new Color(red, green, blue);
            }
        } else if (string.startsWith("#")) {
            c = hexToColor(string.substring(1));
        } else {
            try {
                int intValue = Integer.parseInt(string);
                if (intValue >= 0) {
                    c = new Color(intValue);
                }
            } catch (NumberFormatException e) {
                String hexString = colorSymbols.get(string.toLowerCase());
                if (hexString != null) {
                    c = hexToColor(hexString);
                }
            }
        }
        return c;
    }

    private static Color hexToColor(String string) {
        if (string.length() == 6) {
            int red = Integer.parseInt(string.substring(0, 2), 16);
            int green = Integer.parseInt(string.substring(2, 4), 16);
            int blue = Integer.parseInt(string.substring(4, 6), 16);
            return new Color(red, green, blue);
        } else {
            return null;
        }

    }

    public static float[] getRGBColorComponents(Color color) {
        float[] comps = componentsCache.get(color);
        if (comps == null) {
            comps = color.getRGBColorComponents(null);
            componentsCache.put(color, comps);
        }
        return comps;
    }

    public static Color slightlyDarker(Color color) {
        Color d = slightlyDarkerCache.get(color);
        if(d == null) {
            float [] comps = color.getRGBColorComponents(null);
            float factor = 0.95f;
            d = new Color(factor*comps[0], factor*comps[1], factor*comps[2]);
            slightlyDarkerCache.put(color, d);
        }
        return d;
    }

    /**
     * Return  alphas shaded color.  This method is used, rather than the Color constructor, so that
     * the alpha is not lost in postscript output.
     *
     * @param alpha
     * @return
     */
    public static Color getCompositeColor(Color backgroundColor, Color foregroundColor, float alpha) {

        float[] dest = getRGBColorComponents(backgroundColor);
        float[] source = getRGBColorComponents(foregroundColor);

        int r = (int) ((alpha * source[0] + (1 - alpha) * dest[0]) * 255 + 0.5);
        int g = (int) ((alpha * source[1] + (1 - alpha) * dest[1]) * 255 + 0.5);
        int b = (int) ((alpha * source[2] + (1 - alpha) * dest[2]) * 255 + 0.5);
        int a = 255;
        int value = ((a & 0xFF) << 24) |
                ((r & 0xFF) << 16) |
                ((g & 0xFF) << 8) |
                ((b & 0xFF) << 0);

        Color c = colorCache.get(value);
        if (c == null) {
            c = new Color(value);
            colorCache.put(value, c);
        }
        return c;
    }

    /**
     * Return  alphas shaded color for a white background.  This method is used, rather than the Color constructor, so that
     * the alpha is not lost in postscript output.
     *
     * @param source
     * @param alpha
     * @return
     */
    public static Color getCompositeColor(Color source, float alpha) {
        return getCompositeColor(Color.white, source, alpha);
    }

    public static Map<String, ColorPalette> loadPalettes() throws IOException {

        InputStream is = ColorUtilities.class.getResourceAsStream("resources/colorPalettes.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String nextLine;

        palettes = new LinkedHashMap<String, ColorPalette>();
        palleteNames = new ArrayList();

        String currentPalletName = null;
        java.util.List<Color> currentColorList = new ArrayList();
        while ((nextLine = br.readLine()) != null) {
            nextLine = nextLine.trim();
            if (nextLine.length() == 0) continue;
            if (nextLine.startsWith("#")) {
                if (currentPalletName != null) {
                    ColorPalette palette = new ColorPalette(currentPalletName, currentColorList.toArray(new Color[currentColorList.size()]));
                    palettes.put(currentPalletName, palette);
                    palleteNames.add(currentPalletName);
                    currentColorList.clear();
                }
                currentPalletName = nextLine.substring(1);
            } else {
                String[] tokens = nextLine.split(";");
                for (String s : tokens) {
                    // Remove white space
                    s = s.replaceAll(" ", "");
                    Color c = ColorUtilities.stringToColor(s);
                    currentColorList.add(c);
                }
            }

        }

        if (!currentColorList.isEmpty()) {
            ColorPalette palette = new ColorPalette(currentPalletName, currentColorList.toArray(new Color[currentColorList.size()]));
            palettes.put(currentPalletName, palette);
            palleteNames.add(currentPalletName);
        }

        return palettes;
    }

    static int nextPaletteIdx = 0;
    static ArrayList<String> palleteNames = new ArrayList();

    public static ColorPalette getNextPalette() {
        try {
            if (palettes == null) loadPalettes();
            ColorPalette pallete = palettes.get(palleteNames.get(nextPaletteIdx));
            nextPaletteIdx++;
            if (nextPaletteIdx >= palleteNames.size()) {
                nextPaletteIdx = 0;
            }
            return pallete;
        } catch (IOException e) {
            log.error(e);
            return null;
        }

    }

    public static ColorPalette getPalette(String s) {
        try {
            if (palettes == null) loadPalettes();
            return palettes.get(s);
        } catch (IOException e) {
            log.error(e);
            return null;
        }
    }

    public static ColorPalette getDefaultPalette() {
        try {
            if (palettes == null) {
                loadPalettes();
            }
            if (palettes.isEmpty()) {
                return null;
            }
            return palettes.values().iterator().next();
        } catch (IOException e) {
            log.error("Error loading color palletes", e);
            return null;
        }
    }

    public static synchronized Color getGrayscaleColor(int gray) {
        gray = Math.max(0, Math.min(255, gray));
        Color c = grayscaleColors.get(gray);
        if (c == null) {
            c = new Color(gray, gray, gray);
            grayscaleColors.put(gray, c);
        }
        return c;
    }

    /**
     * Return a new Color, same as the old, but with a new alpha value
     *
     * @param oldColor
     * @param newAlpha
     * @return
     */
    public static Color modifyAlpha(Color oldColor, int newAlpha) {
        return new Color(oldColor.getRed(), oldColor.getGreen(), oldColor.getBlue(), newAlpha);
    }

    /**
     * Converts an HSL color value to RGB. Conversion formula
     * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
     *
     * @param h The hue  [0, 360]
     * @param s The saturation  [0, 1]
     * @param l The lightness  [0, 1]
     * @return The RGB representation
     */
    public static int[] hslToRgb(double h, double s, double l) {

        double c = (1 - Math.abs(2 * l - 1)) * s;

        double hprime = h / 60;
        double x = c * (1 - Math.abs(hprime % 2 - 1));
        double r, g, b;

        if (hprime < 1) {
            r = c;
            g = x;
            b = 0;
        } else if (hprime < 2) {
            r = x;
            g = c;
            b = 0;
        } else if (hprime < 3) {
            r = 0;
            g = c;
            b = x;
        } else if (hprime < 4) {
            r = 0;
            g = x;
            b = c;
        } else if (hprime < 5) {
            r = x;
            g = 0;
            b = c;
        } else {
            r = c;
            g = 0;
            b = x;
        }
        double m = l - 0.5 * c;

        return new int[]{
                (int) ((r + m) * 255),
                (int) ((g + m) * 255),
                (int) ((b + m) * 255)
        };
//        int r, g, b;
//
//        if (s == 0) {
//            r = g = b = (int) (255 * l); // achromatic
//        } else {
//            double q = l < 0.5 ? l * (1 + s) : l + s - l * s;
//            double p = 2 * l - q;
//            r = (int) (255 * hue2rgb(p, q, h + 1 / 3));
//            g = (int) (255 * hue2rgb(p, q, h));
//            b = (int) (255 * hue2rgb(p, q, h - 1 / 3));
//        }
//
//        return new int[]{r, g, b};
    }

}