text:
package uk.gov.gds.ier.transaction.overseas.previousName

import uk.gov.gds.ier.transaction.overseas.OverseasControllers
import com.google.inject.{Inject, Singleton}
import uk.gov.gds.ier.config.Config
import uk.gov.gds.ier.security.EncryptionService
import uk.gov.gds.ier.serialiser.JsonSerialiser
import uk.gov.gds.ier.step.{OverseaStep, Routes}
import uk.gov.gds.ier.transaction.overseas.InprogressOverseas
import uk.gov.gds.ier.assets.RemoteAssets

@Singleton
class PreviousNameStep @Inject ()(
    val serialiser: JsonSerialiser,
    val config: Config,
    val encryptionService : EncryptionService,
    val remoteAssets: RemoteAssets,
    val overseas: OverseasControllers
) extends OverseaStep
  with PreviousNameForms
  with PreviousNameMustache {

  val validation = previousNameForm

  val routing = Routes(
    get = routes.PreviousNameStep.get,
    post = routes.PreviousNameStep.post,
    editGet = routes.PreviousNameStep.editGet,
    editPost = routes.PreviousNameStep.editPost
  )

  def nextStep(currentState: InprogressOverseas) = {
    overseas.NinoStep
  }
}


text:
package com.linkedin.pinot.core.util.trace;

import com.google.common.annotations.VisibleForTesting;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.annotation.Nullable;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * The main entry point for servers to record the trace information.
 *

 * To enable tracing, the request handler thread should register the requestId by calling
 * {@link #register(long requestId)}.
 *

 * To trace the {@link Runnable} or {@link java.util.concurrent.Callable} jobs the request handler creates and will be
 * executed in other threads, use {@link TraceRunnable} or {@link TraceCallable} instead.
 *

 * At the end of tracing a request, the request handler thread should call {@link #unregister()} to un-register the
 * request from tracing to prevent resource leak.
 */
public final class TraceContext {
  private TraceContext() {
  }

  /**
   * Trace represents the logs for a single thread.
   */
  static class Trace {
    static class LogEntry {
      final String _key;
      final Object _value;

      LogEntry(String key, Object value) {
        _key = key;
        _value = value;
      }

      JSONObject toJson() {
        return new JSONObject(Collections.singletonMap(_key, _value));
      }
    }

    final String _traceId;
    final List<LogEntry> _logs = new ArrayList<>();
    int _numChildren = 0;

    Trace(@Nullable Trace parent) {
      if (parent == null) {
        _traceId = "0";
      } else {
        _traceId = parent.getChildTraceId();
      }
    }

    void log(String key, Object value) {
      _logs.add(new LogEntry(key, value));
    }

    String getChildTraceId() {
      return _traceId + "_" + _numChildren++;
    }

    JSONObject toJson() {
      JSONArray jsonLogs = new JSONArray();
      for (LogEntry log : _logs) {
        jsonLogs.put(log.toJson());
      }
      return new JSONObject(Collections.singletonMap(_traceId, jsonLogs));
    }
  }

  /**
   * TraceEntry is a wrapper on the trace and the request Id it belongs to.
   */
  static class TraceEntry {
    final long _requestId;
    final Trace _trace;

    TraceEntry(long requestId, Trace trace) {
      _requestId = requestId;
      _trace = trace;
    }
  }

  private static final ThreadLocal<TraceEntry> TRACE_ENTRY_THREAD_LOCAL = new ThreadLocal<TraceEntry>() {
    @Override
    protected TraceEntry initialValue() {
      return null;
    }
  };

  /**
   * Map from request Id to traces associated with the request.
   *
Requests may arrive simultaneously, so we need a concurrent map to manage these requests.
   *
Each request may use multiple threads, so the queue should be thread-safe as well.
   */
  @VisibleForTesting
  static final Map<Long, Queue<Trace>> REQUEST_TO_TRACES_MAP = new ConcurrentHashMap<>();

  /**
   * Register a request to the trace.
   *
Should be called before logging any trace information.
   */
  public static void register(long requestId) {
    REQUEST_TO_TRACES_MAP.put(requestId, new ConcurrentLinkedQueue<Trace>());
    registerThreadToRequest(new TraceEntry(requestId, null));
  }

  /**
   * Register a thread to the request.
   */
  static void registerThreadToRequest(TraceEntry parentTraceEntry) {
    Trace trace = new Trace(parentTraceEntry._trace);
    TRACE_ENTRY_THREAD_LOCAL.set(new TraceEntry(parentTraceEntry._requestId, trace));
    REQUEST_TO_TRACES_MAP.get(parentTraceEntry._requestId).add(trace);
  }

  /**
   * Un-register a request from the trace.
   *
Should be called after all trace information being saved.
   */
  public static void unregister() {
    TraceEntry traceEntry = TRACE_ENTRY_THREAD_LOCAL.get();
    REQUEST_TO_TRACES_MAP.remove(traceEntry._requestId);
    unregisterThreadFromRequest();
  }

  /**
   * Un-register a thread from the request.
   */
  static void unregisterThreadFromRequest() {
    TRACE_ENTRY_THREAD_LOCAL.remove();
  }

  /**
   * Return whether the trace is enabled.
   */
  public static boolean traceEnabled() {
    return TRACE_ENTRY_THREAD_LOCAL.get() != null;
  }

  /**
   * Log the time spent in a specific operator.
   *
Should be called after calling {@link #traceEnabled()} and ensure trace is enabled.
   */
  public static void logTime(String operatorName, long timeMs) {
    TRACE_ENTRY_THREAD_LOCAL.get()._trace.log(operatorName + " Time", timeMs);
  }

  /**
   * Log a key-value pair trace information.
   *
Should be called after calling {@link #traceEnabled()} and ensure trace is enabled.
   */
  public static void logInfo(String key, Object value) {
    TRACE_ENTRY_THREAD_LOCAL.get()._trace.log(key, value);
  }

  /**
   * Get the trace information added so far.
   */
  public static String getTraceInfo() {
    JSONArray jsonTraces = new JSONArray();
    for (Trace trace : REQUEST_TO_TRACES_MAP.get(TRACE_ENTRY_THREAD_LOCAL.get()._requestId)) {
      jsonTraces.put(trace.toJson());
    }
    return jsonTraces.toString();
  }

  /**
   * Get the {@link TraceEntry} for the current thread.
   */
  @Nullable
  static TraceEntry getTraceEntry() {
    return TRACE_ENTRY_THREAD_LOCAL.get();
  }
}

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: Inspired Valley Group Show
date: 2016-05-24
author: Sean Mcdaniel
tags: weekly links, java
status: published
summary: Aliquam euismod, enim ac fermentum tempor, tellus lacus accumsan urna.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 04/03/2019
  endDate: 04/05/2019
  ctyhocn: MBGINHX
  groupCode: IVGS
published: true
---
Duis tincidunt libero in eros varius placerat. Nulla tristique vel massa ut elementum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Etiam varius in mauris gravida porttitor. Nunc fringilla euismod ligula, et euismod magna porta sed. Nunc tellus metus, interdum ac dictum eget, laoreet ut risus. In hac habitasse platea dictumst. Vestibulum metus arcu, semper ac facilisis eu, ultrices sit amet risus.
Aenean pretium massa convallis, imperdiet ante in, posuere dolor. Integer eleifend aliquam vulputate. Maecenas pellentesque convallis felis, at tempus erat pulvinar sed. Aliquam aliquet dignissim enim, in scelerisque lacus. Nulla dictum lacus semper imperdiet pharetra. Duis quis ante porta, bibendum erat eu, tincidunt dui. Suspendisse tristique eros eget metus dictum varius. Nunc velit lectus, placerat sit amet augue quis, fermentum congue odio. Quisque sapien massa, sagittis vel porttitor quis, rutrum in quam. Aenean id mi id lorem iaculis porta eu et libero. Nam vitae cursus dolor, a tincidunt velit.

1 In tincidunt risus sed ex imperdiet, at dignissim ipsum egestas
1 Nunc sollicitudin lectus sed tempus faucibus
1 Sed non orci nec mauris eleifend efficitur eget id libero
1 Aenean consectetur ex quis neque finibus, sit amet dictum nulla eleifend
1 Etiam sit amet nulla lacinia, egestas nunc vitae, sagittis nisi.

Proin sed scelerisque eros, congue aliquam enim. Vivamus nec lorem id magna pharetra facilisis sed in mauris. Sed mollis ipsum facilisis ornare suscipit. Integer nulla tellus, pharetra laoreet varius vitae, rhoncus in nunc. Quisque maximus malesuada euismod. Nunc ultrices nec ligula eget feugiat. Maecenas malesuada eros libero, a interdum dolor rhoncus nec. Maecenas faucibus dictum justo sed cursus. Fusce a libero sit amet ipsum aliquet vestibulum vel ac libero. Pellentesque non diam a nulla bibendum cursus.


text:
<?php

namespace App\Services\Clara;

use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Configuration;
use Illuminate\Support\Facades\Artisan;

class Install
{
    public static function storeBdd($aInputs)
    {
        self::setEnvFile($aInputs);
        self::changeDatabase($aInputs);

        //Run database migration for Sentinel
        Artisan::call('migrate', ['--database' => 'mysql-tmp']);
    }

    private static function setConnectionParams($aInputs)
    {
        return [
            'dbname' 	=> $aInputs['database'],
            'user' 	=> $aInputs['username'],
            'password' 	=> $aInputs['db_password'],
            'host' 	=> $aInputs['host'],
            'port' 	=> $aInputs['port'],
            'driver' 	=> 'pdo_mysql',
        ];
    }

    public static function setEnvFile($aInputs)
    {
        $aConnectionParams  = self::setConnectionParams($aInputs);

        // Test database connection
        $oConnection = DriverManager::getConnection($aConnectionParams, new Configuration());
        $oConnection->connect();

        // Change .env file
        $sEnvFile = \Storage::disk('base')->get('.env');

        $sEnvFile = str_replace('DB_HOST=127.0.0.1'	, 'DB_HOST='.$aInputs['host'], $sEnvFile);
        $sEnvFile = str_replace('DB_PORT=3306'		, 'DB_PORT='.$aInputs['port'], $sEnvFile);
        $sEnvFile = str_replace('DB_DATABASE=homestead'	, 'DB_DATABASE='.$aInputs['database'], $sEnvFile);
        $sEnvFile = str_replace('DB_USERNAME=homestead'	, 'DB_USERNAME='.$aInputs['username'], $sEnvFile);
        $sEnvFile = str_replace('DB_PASSWORD=secret'	, 'DB_PASSWORD='.$aInputs['db_password'], $sEnvFile);

        \Storage::disk('base')->put('.env', $sEnvFile);
    }

    private static function changeDatabase($aInputs)
    {
        // Change database config
        $oConfig                = config('database.connections');
	$oConfig['mysql-tmp']   = [
            'driver'    => 'mysql',
            'host'      => $aInputs['host'],
            'port'      => $aInputs['port'],
            'database'  => $aInputs['database'],
            'username'  => $aInputs['username'],
            'password'  => $aInputs['db_password'],
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
            'engine'    => null,
        ];

        config(['database.connections' => $oConfig]);
    }
}


text: Write a C program to print 8220 Geeks for Geeks 8221 without using a semicolon


text:
namespace ash {

// Test API for AccessibilityController in ash. It is intended for
// integration browser tests that need to verify AccessibilityController
// in ash works as expected.
class ASH_EXPORT AccessibilityControllerTestApi {
 public:
  AccessibilityControllerTestApi() = default;
  virtual ~AccessibilityControllerTestApi() = default;

  static std::unique_ptr<AccessibilityControllerTestApi> Create();

  virtual void SetLargeCursorEnabled(bool enabled) = 0;
  virtual bool IsLargeCursorEnabled() const = 0;
};

}  // namespace ash

#endif  // ASH_PUBLIC_CPP_TEST_ACCESSIBILITY_CONTROLLER_TEST_API_H_


text:
using LanguageExt;
using LanguageExt.TypeClasses;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;

namespace LanguageExt.ClassInstances
{
    ///
    /// Hash of any type in the NumType type-class
    ///
    public struct HashableNumType<NUMTYPE, NUM, A> : Hashable<NumType<NUMTYPE, NUM, A>>
        where NUM     : struct, Num
        where NUMTYPE : NumType<NUMTYPE, NUM, A>
    {
        ///
        /// Get hash code of the value
        ///
        /// <param name="x">Value to get the hash code of</param>
        /// <returns>The hash code of x</returns>
        [Pure]
        public int GetHashCode(NumType<NUMTYPE, NUM, A> x) =>
            x.IsNull() ? 0 : x.GetHashCode();

        ///
        /// Get hash code of the value
        ///
        /// <param name="x">Value to get the hash code of</param>
        /// <returns>The hash code of x</returns>
        [Pure]
        public Task<int> GetHashCodeAsync(NumType<NUMTYPE, NUM, A> x) =>
            GetHashCode(x).AsTask();
    }

    ///
    /// Hash of any type in the NumType type-class
    ///
    public struct HashableNumType<NUMTYPE, NUM, A, PRED> : Hashable<NumType<NUMTYPE, NUM, A, PRED>>
        where PRED    : struct, Pred
        where NUM     : struct, Num
        where NUMTYPE : NumType<NUMTYPE, NUM, A, PRED>
    {
        ///
        /// Get hash code of the value
        ///
        /// <param name="x">Value to get the hash code of</param>
        /// <returns>The hash code of x</returns>
        [Pure]
        public int GetHashCode(NumType<NUMTYPE, NUM, A, PRED> x) =>
            x.IsNull() ? 0 : x.GetHashCode();

        ///
        /// Get hash code of the value
        ///
        /// <param name="x">Value to get the hash code of</param>
        /// <returns>The hash code of x</returns>
        [Pure]
        public Task<int> GetHashCodeAsync(NumType<NUMTYPE, NUM, A, PRED> x) =>
            GetHashCode(x).AsTask();
    }
}


text:
/**
 * Created by manthanhd on 17/10/2016.
 */
function DefaultSkillResolutionStrategyFn() {
    const util = require('util');
    const extend = util._extend;
    const skillsMap = {};
    const undefinedSkills = [];

    this.addSkill = function(skill, options) {
        var minConfidence = 0;
        if(options instanceof Number) {
            minConfidence = options;
        } else if (options && options.minConfidence !== undefined) {
            minConfidence = options.minConfidence;
        }

        var skillClone = extend({}, skill);
        var botSkillObject = {skill: skillClone, minConfidence: minConfidence};

        if (skillClone.topic === undefined || skillClone.topic === 'undefined') {
            skillClone.topic = undefined;
            undefinedSkills.push(botSkillObject);
        }

        if(skillClone.topic instanceof Array) {
            skillClone.topic.forEach(function(topic) {
                if(skillsMap[topic] === undefined) skillsMap[topic] = [];
                skillsMap[topic].push(skillClone);
            });
        } else {
            if (skillsMap[skillClone.topic] === undefined) {
                skillsMap[skillClone.topic] = [];
            }

            skillsMap[skillClone.topic].push(botSkillObject);
        }
    };

    this.getSkills = function() {
        var topics = Object.keys(skillsMap);
        var skills = [];

        topics.forEach(function (topic) {
            skills.push(skillsMap[topic]);
        });

        return skills;
    };

    var _resolveSkillFromTopicWithConfidence = function ResolveSkillFromTopicWithConfidenceFn(topic) {
        if (topic.name === undefined) {
            if (undefinedSkills && undefinedSkills.length > 0) {
                return undefinedSkills[0];
            }

            return;
        }

        var botSkills = skillsMap[topic.name];
        var minConfidenceSkill = undefinedSkills[0];
        var minDistance = 999;
        if (botSkills !== undefined && botSkills.length > 0) {
            for (var i = 0; i < botSkills.length; i++) {
                var botSkill = botSkills[i];
                var distance = topic.confidence - botSkill.minConfidence;
                if (distance < 0) continue;
                if (distance < minDistance) {
                    minDistance = distance;
                    minConfidenceSkill = botSkill;
                }
                if (distance === 0) break;
            }
        }

        return minConfidenceSkill;
    };

    this.resolve = function(err, resolutionContext, callback) {
        var topics = resolutionContext.topics;
        var sentence = resolutionContext.sentence;
        var mostConfidentTopic = topics[0];
        var resolvedBotSkill = _resolveSkillFromTopicWithConfidence(mostConfidentTopic);
        var skill = resolvedBotSkill ? resolvedBotSkill.skill : undefined;

        if (skill === undefined) {
            return callback(new Error("could not resolve any skills"));
        }

        var clonedSkill = extend({}, skill);
        clonedSkill.sentence = sentence;
        clonedSkill.topic = mostConfidentTopic;

        return callback(undefined, clonedSkill);
    };

    return this;
}

function DefaultTopicResolutionStrategyFn() {
    const classifications = [];

    this.collect = function(classification, classificationContext, callback) {
        classifications.push(classification);
        return callback();
    };

    this.resolve = function(callback) {
        var topics = [];

        classifications.forEach(function(classification) {
            topics.push({name: classification.label, confidence: classification.value});
        });

        return callback(undefined, topics);
    };

    return this;
}

function Bot(config) {
    config = config || {};
    const async = require('async');
    const util = require('util');
    const extend = util._extend;
    const LogisticRegressionClassifier = require('talkify-natural-classifier').LogisticRegressionClassifier;
    var classifiers = config.classifier || config.classifiers;
    if (!classifiers) classifiers = [new LogisticRegressionClassifier()];
    if (!(classifiers instanceof Array)) classifiers = [classifiers];

    /**
     * Defines how a skill should be resolved from a given set of topics
     * @type {*}
     */
    const skillResolutionStrategy = config.skillResolutionStrategy || DefaultSkillResolutionStrategyFn();

    const topicResolutionStrategy = config.topicResolutionStrategy || DefaultTopicResolutionStrategyFn;

    const BotTypes = require('./BotTypes');
    const Skill = BotTypes.Skill;
    const SingleLineMessage = BotTypes.SingleLineMessage;
    const Correspondence = BotTypes.Correspondence;
    const Context = BotTypes.Context;

    const BuiltInContextStore = require('./ContextStore');
    const contextStore = config.contextStore || new BuiltInContextStore();

    var botObject = this;

    this.train = function TrainBotFn(topic, text, callback) {
        var classifier = botObject.getClassifier();
        if (!topic || (typeof topic !== 'string' && !(topic instanceof String))) throw new TypeError('topic must be a String and cannot be undefined');

        if (!text || (!(text instanceof Array) && typeof text !== 'string' && !(text instanceof String))) throw new TypeError('text must be a String and cannot be undefined');

        classifier.trainDocument({topic: topic, text: text}, function (err) {
            if (err) return callback(err);

            return classifier.initialize(callback);
        });

        return botObject;
    };

    this.trainAll = function TrainAllBotFn(documents, finished) {
        finished = (finished) ? finished : function (err) {
                throw err;
            };
        var classifier = botObject.getClassifier();
        if (!documents || !(documents instanceof Array)) return finished(new TypeError('expected documents to exist and be of type Array'));
        classifier.trainDocument(documents, function (err) {
            if (err) return callback(err);

            return classifier.initialize(finished);
        });
        return botObject;
    };

    this.addSkill = function AddSkillFn(skill, options) {
        if (!skill || !(skill instanceof Skill)) throw new TypeError('skill parameter is of invalid type. Must be defined and be of type Skill');

        // Allows us to keep backwards compatibility with people who still use 1 with skill as confidence option
        var evaluatedOptions = options instanceof Object ? options : {minConfidence: options};

        skillResolutionStrategy.addSkill(skill, evaluatedOptions);

        return botObject;
    };

    this.getSkills = function GetSkillsFn() {
        return skillResolutionStrategy.getSkills();
    };

    var _resolveContext = function _ResolveContext(id, callback) {
        var retrieved = function (err, contextRecord) {
            if (err) return callback(err);

            if (contextRecord === undefined) return callback(err, new Context(id));

            return callback(err, contextRecord.context);
        };

        return contextStore.get(id, retrieved);
    };

    var _classifyToTopics = function ClassifyToTopicFn(sentence, done) {
        return async.map(classifiers, function (classifier, classificationDone) {
            return process.nextTick(function() {
                var classified = function (err, classifications) {
                    var topicResolver = new topicResolutionStrategy();
                    async.each(classifications, function(classification, callback) {
                        var context = {};
                        topicResolver.collect(classification, context, callback);
                    }, function(err) {
                        topicResolver.resolve(classificationDone);
                    });
                };

                return classifier.getClassifications(sentence, classified);
            });
        }, function (err, classificationArrays) {
            if (err) return done(err, classificationArrays);
            var classifications = [];
            classificationArrays.forEach(function(classificationArray) {
                classificationArray.forEach(function(classification) {
                    classifications.push(classification);
                });
            });
            var indeterminates = [];
            return async.filter(classifications, function (classification, mapped) {
                if (classification.name === undefined) {
                    indeterminates.push(classification);
                    return mapped(undefined, false);
                }

                return mapped(undefined, true);
            }, function (err, allMapped) {
                return async.sortBy(allMapped, function (classification, sorted) {
                    return sorted(undefined, classification.confidence * -1);
                }, function (err, sortedClassifications) {
                    var allClassifications = sortedClassifications.concat(indeterminates);
                    return done(err, allClassifications);
                });
            });
        });
    };

    var _getSkillByName = function (name, skillList) {
        var skills = skillList || botObject.getSkills();
        for (var i = 0; i < skills.length; i++) {
            var skill = skills[i];
            if (skill instanceof Array) {
                var returnSkill = _getSkillByName(name, skill);
                if (returnSkill) return returnSkill;
                continue;
            }

            if (skill.name === name) return skill;
            if (skill.skill.name === name) return skill.skill;
        }
    };

    var _resolveSkills = function _ResolveSkillsFn(sentences, doneCallback) {
        return async.mapSeries(sentences, function (sentence, callback) {
            var classified = function (err, topics) {
                return process.nextTick(function() {
                    return skillResolutionStrategy.resolve(err, {
                        sentence: sentence,
                        topics: topics
                    }, callback);
                });
            };

            return _classifyToTopics(sentence, classified);
        }, function (err, resolvedSkills) {
            return doneCallback(err, resolvedSkills);
        });
    };

    var _applySkills = function _ApplySkillsFn(context, request, response, skills, skillsApplied) {
        return async.mapSeries(skills, function (skill, callback) {
            return process.nextTick(function() {
                var next = function () {
                    var responseMessage = response.message;
                    if (responseMessage) {
                        delete response.message;
                    }

                    if (context.lock) {
                        response.isFinal = true;
                    }

                    if (response.isFinal === true) {
                        return callback('break', responseMessage);
                    }

                    return callback(undefined, responseMessage);
                };

                response.lockConversationForNext = function LockConversationForNextFn() {
                    context.lock = skill.name;
                    return response;
                };

                response.final = function FinalFn() {
                    response.isFinal = true;
                    return response;
                };

                response.send = function SendFn(message) {
                    response.message = message;
                    return next();
                };

                request.sentence.current = skill.sentence;
                request.sentence.index = skills.indexOf(skill);

                request.skill.current = skill;
                request.skill.index = request.sentence.index;

                skill.apply(context.data, request, response, next);
            });
        }, function (err, messages) {
            if (err === 'break') err = undefined;

            return skillsApplied(err, messages);
        });
    };

    this.resolve = function ResolveFn(id, content, callback) {
        var sentences = content.replace(/([.?!])\s*(?=[A-Z])/g, "$1|").split("|");
        var request = new Correspondence(id, new SingleLineMessage(content));
        request.sentence = {all: sentences};
        var response = new Correspondence(id);
        var context;
        var messages;

        var contextMemorized = function (err, memorizedContext) {
            if (err) return callback(err, messages);

            return callback(err, messages);
        };

        var skillsApplied = function (err, responseMessages) {
            messages = responseMessages;
            return contextStore.put(id, context, contextMemorized);
        };

        var skillsResolved = function (err, skills) {
            if (err) return callback(err);

            request.skill = {all: skills};
            return _applySkills(context, request, response, skills, skillsApplied);
        };

        var contextResolved = function (err, resolvedContext) {
            context = resolvedContext;

            if (context.lock) {
                var skill = _getSkillByName(context.lock);
                skill = extend({}, skill);
                delete context.lock;
                request.skill = {all: [skill]};
                return _applySkills(context, request, response, [skill], skillsApplied);
            }

            return _resolveSkills(sentences, skillsResolved);
        };

        _resolveContext(id, contextResolved);
        return botObject;
    };

    this.getContextStore = function GetContextStoreFn() {
        return contextStore;
    };

    this.getClassifiers = function GetClassifiersFn() {
        return classifiers;
    };

    this.getClassifier = function GetClassifierFn() {
        return classifiers[classifiers.length - 1];
    };

    return this;
}

module.exports = Bot;


text:
/** @module "iterable-query/fn" */

import { assert, ToPossiblyAsyncIterable } from "../internal";
import { AsyncQueryable } from "../types";
import { T } from "./common";

/**
 * Gets the first element, optionally filtering elements using the supplied callback.
 *
 * @param source A [[Queryable]] object.
 * @param predicate An optional callback used to match each element.
 * @category Scalar
 */
export async function firstAsync<T, U extends T>(source: AsyncQueryable<T>, predicate: (element: T) => element is U): Promise<U | undefined>;
/**
 * Gets the first element, optionally filtering elements using the supplied callback.
 *
 * @param source A [[Queryable]] object.
 * @param predicate An optional callback used to match each element.
 * @category Scalar
 */
export async function firstAsync<T>(source: AsyncQueryable<T>, predicate?: (element: T) => boolean | PromiseLike<boolean>): Promise<T | undefined>;
export async function firstAsync<T>(source: AsyncQueryable<T>, predicate: (element: T) => boolean | PromiseLike<boolean> = T): Promise<T | undefined> {
    assert.mustBeAsyncQueryable<T>(source, "source");
    assert.mustBeFunction(predicate, "predicate");
    for await (const element of ToPossiblyAsyncIterable(source)) {
        const result = predicate(element);
        if (typeof result === "boolean" ? result : await result) {
            return element;
        }
    }
    return undefined;
}


text:
<form action="http://www.codingforums.com/search.php?do=process" method="post" name="vbform" id="searchform">

Search Single Content Type

Search Multiple Content Types

Search In

			Search Types:

					<input type="checkbox" name="type[]" value="" id="searchtype_all" /> All Types

Search For

			Keyword(s):

					<input id="keyword" type="text" class="textbox" name="query" tabindex="1" value="" />

					<select name="titleonly" tabindex="1">
						<option value="0" selected="selected">Search Entire Posts</option>
						<option value="1" >Search Titles Only</option>
					</select>

			User Name:

						<input type="text" class="textbox popupctrl" name="searchuser" id="userfield_txt" tabindex="1" value="" />

						<input type="checkbox" name="exactname" value="1" id="cb_exactname" tabindex="1" checked="checked" /> Exact name

			Tag:

				<input type="text" class="textbox primary popupctrl" name="tag" id="tag_add_input" tabindex="1" value="" />

			<input type="submit" class="button" name="dosearch" value="Search Now" tabindex="1" accesskey="s"/>
			<input type="reset" class="button" value="Reset" tabindex="1" accesskey="r" />

Additional Options

		Find Posts

					<select name="searchdate" tabindex="1">
						<option value="0" selected="selected">Any Date</option>
						<option value="lastvisit" >Your Last Visit</option>
						<option value="1" >Yesterday</option>
						<option value="7" >A Week Ago</option>
						<option value="14" >2 Weeks Ago</option>
						<option value="30" >A Month Ago</option>
						<option value="90" >3 Months Ago</option>
						<option value="180" >6 Months Ago</option>
						<option value="365" >A Year Ago</option>
					</select>

					<select name="beforeafter" tabindex="1">
						<option value="after" >and Newer</option>
						<option value="before" >and Older</option>
					</select>

			Sort Results by

					<select name="sortby" tabindex="1">
						<option value="title" >Title</option>
						<option value="dateline" selected="selected" >Date</option>
						<option value="user" >User Name</option>
					<option value="relevance" selected="selected">Relevance</option>
					</select>

					<select name="order" tabindex="1">
						<option value="descending" selected="selected">in Descending Order</option>
						<option value="ascending" >in Ascending Order</option>
					</select>

<input type=hidden value='1' id='humanverify' name='humanverify' />

<input type='hidden' id='FunCaptcha-Token' name='fc-token' value='511567f41461414d0.52617907|r=us-east-1|guitextcolor=%2377A029|metabgclr=%23FFFFFF|metaiconclr=%2377A029|meta=1|meta=3|pk=58C48790-A2B5-62E1-8E20-71D5943E838D|surl=https://funcaptcha.co'>
Please enable JavaScript to continue.

			<input type="submit" class="button" name="dosearch" value="Search Now" tabindex="1" accesskey="s"/>
			<input type="reset" class="button" value="Reset" tabindex="1" accesskey="r" />

<input type="hidden" name="s" value="" />
<input type="hidden" name="securitytoken" value="guest" />
<input type="hidden" name="do" value="process" />
<input type="hidden" name="searchthreadid" value="" />

</form>


text:
#import <DevToolsCore/XCObjectBucket.h>

@interface XCBreakpointsBucket : XCObjectBucket
{
}

+ (BOOL)importing;
+ (void)setImporting:(BOOL)arg1;
- (void)_breakpointWasAdded:(id)arg1;
- (void)_breakpointWillBeRemoved:(id)arg1;
- (id)container;
- (void)dealloc;
- (void)listenToSource:(id)arg1 removeOnly:(BOOL)arg2;
- (void)purify;
- (void)validateAgainstProject:(id)arg1;

@end


text:
<?php

	/*
	|--------------------------------------------------------------------------
	| Routes File
	|--------------------------------------------------------------------------
	|
	| Here is where you will register all of the routes in an application.
	| It's a breeze. Simply tell Laravel the URIs it should respond to
	| and give it the controller to call when that URI is requested.
	|
	*/
	/*
	|--------------------------------------------------------------------------
	| Application Routes
	|--------------------------------------------------------------------------
	|
	| This route group applies the "web" middleware group to every route
	| it contains. The "web" middleware group is defined in your HTTP
	| kernel and includes session state, CSRF protection, and more.
	|
	*/
	Route::group(['middleware' => ['web']], function () {
		//Login Routes
		Route::get('/login', ['as' => 'login.create', 'uses' => 'LoginController@create']);
		Route::post('/login', ['as' => 'login.save', 'uses' => 'LoginController@store']);

		//Register Routes
		Route::get('/register', ['as' => 'register.create', 'uses' => 'RegisterController@create']);
		Route::post('/register', ['as' => 'register.save', 'uses' => 'RegisterController@store']);

		//Middleware. Only authenticated users
		Route::group(['middleware' => ['auth']], function () {

			//Logout
			Route::get('/logout', ['as' => 'login.out', 'uses' => 'LoginController@destroy']);

			//Teachers only
			Route::group(['middleware' => ['teacher']], function () {
				Route::get('/teacher', ['as' => 'teacher.index', 'uses' => 'TeacherDashboardController@index']);
			});

			//Students only
			Route::group(['middleware' => ['student']], function () {
				Route::get('/student', ['as' => 'student.index', 'uses' => 'TeacherDashboardController@index']);
			});

		});

		Route::group(['middleware' => ['auth', 'teacher']], function () {
			Route::get('/', ['as' => 'index', 'uses' => 'DashboardController@index']);

			Route::get('/list_assignments', ['as' => 'list_assignments', 'uses' => 'DashboardController@listAssignments']);
			Route::get('/list_teachers', ['as' => 'list_teachers', 'uses' => 'DashboardController@listTeachers']);

			Route::get('/step_1', ['as' => 'create_step_1', 'uses' => 'AssignmentController@createStepOne']);
			Route::post('/step_1', ['as' => 'save_step_1', 'uses' => 'AssignmentController@saveStepOne']);
			Route::get('/step_2', ['as' => 'create_step_2', 'uses' => 'AssignmentController@createStepTwo']);
			Route::post('/step_2', ['as' => 'save_step_2', 'uses' => 'AssignmentController@saveStepTwo']);
			Route::get('/step_3/{id}', ['as' => 'create_step_3', 'uses' => 'DashboardController@createStep3']);

			Route::post('/delete_assignment', ['as' => 'delete_assignment', 'uses' => 'DashboardController@deleteAssignment']);

		});

		Route::group(['middleware' => ['auth', 'student']], function () {
			Route::get('/student', ['as' => 'student.index', 'uses' => 'StudentController@index']);
			Route::post('/get_user_groups', ['as' => 'get_user_groups', 'uses' => 'StudentController@getUserGroups']);
			Route::post('/change_group', ['as' => 'change_group', 'uses' => 'StudentController@changeGroup']);
			Route::post('/execute_group', ['as' => 'execute_group', 'uses' => 'StudentController@executeChange']);

		});

	});


text:
require "spec_helper"

describe Chef::Formatters::ErrorDescription do
  let(:title) { "test title" }

  let(:out) { Chef::Formatters::IndentableOutputStream.new(StringIO.new, STDERR) }

  let(:section_heading) { "test heading" }
  let(:section_text) { "test text" }

  subject { Chef::Formatters::ErrorDescription.new(title) }

  describe "#sections" do
    context "when no sections have been added" do
      it "should return an empty array" do
        expect(subject.sections).to eq []
      end
    end

    context "when a section has been added" do
      before do
        subject.section(section_heading, section_text)
      end

      it "should return an array with the added section as a hash" do
        expect(subject.sections).to eq [ { section_heading => section_text } ]
      end
    end
  end

  describe "#display" do
    before do
      stub_const("Chef::VERSION", "1.2.3")
      stub_const("RUBY_DESCRIPTION", "ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]")
      allow(subject).to receive(:caller) { Kernel.caller + ["/test/bin/chef-client:1:in `<main>'"] }
      allow(File).to receive(:realpath).and_call_original
      allow(File).to receive(:realpath).with("/test/bin/chef-client").and_return("/test/bin/chef-client")
    end

    around do |ex|
      old_program_name = $PROGRAM_NAME
      begin
        $PROGRAM_NAME = "chef-client"
        ex.run
      ensure
        $PROGRAM_NAME = old_program_name
      end
    end

    context "when no sections have been added" do
      it "should output only the title and the Platform section" do
        subject.display(out)
        expect(out.out.string).to eq <<~END
          ================================================================================
          test title
          ================================================================================

          System Info:
          ------------
          chef_version=1.2.3
          ruby=ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
          program_name=chef-client
          executable=/test/bin/chef-client

        END
      end
    end

    context "when a section has been added" do
      before do
        subject.section(section_heading, section_text)
      end

      it "should output the expected sections" do
        subject.display(out)
        expect(out.out.string).to eq <<~END
          ================================================================================
          test title
          ================================================================================

          test heading
          ------------
          test text

          System Info:
          ------------
          chef_version=1.2.3
          ruby=ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
          program_name=chef-client
          executable=/test/bin/chef-client

        END
      end

    end

    context "when node object is available" do
      it "should output the expected sections" do
        # This can't be in a before block because the spec-wide helper calls a
        # reset on global values.
        Chef.set_node({ "platform" => "openvms", "platform_version" => "8.4-2L1" })
        subject.display(out)
        expect(out.out.string).to eq <<~END
          ================================================================================
          test title
          ================================================================================

          System Info:
          ------------
          chef_version=1.2.3
          platform=openvms
          platform_version=8.4-2L1
          ruby=ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
          program_name=chef-client
          executable=/test/bin/chef-client

        END
      end

    end
  end
end


text:
.app {
}
.tsinfolink {
    position:absolute;
    right:0px;
    width: 14px;
    height: 14px;
    border-radius: 7px;
    text-align: center;
    color: white;
    background: #C0C0C0;
    border-style: solid;
    border-width: 1px;
    margin-top: 25px;
    margin-right: 5px;
    cursor: pointer;
}
.highcharts-tooltip {
    font-family:NotoSansBold;
    color:white;
}
.tooltip-point {
    text-align: right;
    color: white;
}
.tooltip-label {
    font-family:NotoSans;
    white-space:nowrap;
    font-size:13px;
    color:white;
}
.etlDate {
    color: grey;
    font-family:NotoSans;
    font-style: italic;
}


text:
package gnu.kawa.functions;
import gnu.text.*;
import gnu.lists.*;
import java.text.Format;
import java.text.FieldPosition;
import java.text.ParseException;
import java.io.Writer;
import gnu.math.*;
import gnu.mapping.OutPort;

/** A representation of a parsed Common Lisp-style format. */

public class LispFormat extends CompoundFormat
{
  public static final String paramFromList = "<from list>";
  public static final String paramFromCount = "<from count>";
  public static final String paramUnspecified = "<unspecified>";

  public LispFormat(char[] format, int offset, int length)
    throws ParseException
  {
    super(null, 0);
    // The index in spec of the most recent ~{, ~(, ~{ or ~[.
    int start_nesting = -1;
    int choices_seen = 0;  // Number of "~;" seen.

    StringBuffer litbuf = new StringBuffer(100);
    java.util.Stack stack = new java.util.Stack();

    int limit = offset + length;
    int i = offset;
    for (;;)
      {
	if ((i >= limit || format[i] == '~') && litbuf.length() > 0)
	  {
	    stack.push(new LiteralFormat(litbuf));
	    litbuf.setLength(0);
	  }
	if (i >= limit)
	  break;
	char ch = format[i++];
	if (ch != '~')
	  {
	    litbuf.append(ch);
	    continue;
	  }
	int speci = stack.size();
	ch = format[i++];
	for (;;)
	  {
	    if (ch == '#')
	      {
		stack.push(paramFromCount);
		ch = format[i++];
	      }
	    else if (ch == 'v' || ch == 'V')
	      {
		stack.push(paramFromList);
		ch = format[i++];
	      }
	    else if (ch == '-' || Character.digit(ch, 10) >= 0)
	      {
		boolean neg = (ch == '-');
		if (neg)
		  ch = format[i++];
		int val = 0;
		int start = i;
		for (;;)
		  {
		    int dig = Character.digit(ch, 10);
		    if (dig < 0)
		      break;
		    val = 10 * val + dig;
		    ch = format[i++];
		  }
		stack.push(i - start < 8 ? IntNum.make(neg ? - val : val)
			   : IntNum.valueOf(format, start, i-start, 10, neg));
	      }
	    else if (ch == '\'')
	      {
		stack.push(Char.make(format[i++]));
		ch = format[i++];
	      }
	    else if (ch == ',')
	      {
		stack.push(paramUnspecified);
	      }
	    else
	      break;
	    if (ch != ',')
	      break;
	    ch = format[i++];
	  }
	boolean seenColon = false;
	boolean seenAt = false;
	for (;;)
	  {
	    if (ch == ':')
	      seenColon = true;
	    else if (ch == '@')
	      seenAt = true;
	    else
	      break;
	    ch = format[i++];
	  }
	ch = Character.toUpperCase(ch);
	int numParams = stack.size() - speci;
	Format fmt;
	int minWidth, padChar, charVal, param1, param2, param3, count;
	switch (ch)
	  {
	  case 'R':  case 'D':  case 'O':  case 'B':  case 'X':
	    int argstart = speci;
	    int base;
	    if (ch == 'R')  base = getParam(stack, argstart++);
	    else if (ch == 'D')  base = 10;
	    else if (ch == 'O')  base = 8;
	    else if (ch == 'X')  base = 16;
	    else base = 2;
	    minWidth = getParam(stack, argstart);
	    padChar = getParam(stack, argstart+1);
	    int commaChar = getParam(stack, argstart+2);
	    int commaInterval = getParam(stack, argstart+3);
            int flags = 0;
            if (seenColon)
              flags |= IntegerFormat.SHOW_GROUPS;
            if (seenAt)
              flags |= IntegerFormat.SHOW_PLUS;
	    fmt = IntegerFormat.getInstance(base, minWidth, padChar,
                                            commaChar, commaInterval, flags);
	    break;
	  case 'P':
	    fmt = LispPluralFormat.getInstance(seenColon, seenAt);
	    break;
	  case 'E':
	  case 'F':
	  case 'G':
	  case '$':
	    LispRealFormat dfmt = new LispRealFormat();
	    dfmt.op = ch;
	    dfmt.arg1 = getParam(stack, speci);
	    dfmt.arg2 = getParam(stack, speci+1);
	    dfmt.arg3 = getParam(stack, speci+2);
	    dfmt.arg4 = getParam(stack, speci+3);
	    if (ch != '$')
	      {
		dfmt.arg5 = getParam(stack, speci+4);
		if (ch == 'E' || ch == 'G')
		  {
		    dfmt.arg6 = getParam(stack, speci+5);
		    dfmt.arg7 = getParam(stack, speci+6);
		  }
	      }
	    dfmt.showPlus = seenAt;
	    dfmt.internalPad = seenColon;
	    if (dfmt.argsUsed == 0)
	      fmt = dfmt.resolve(null, 0);
	    else
	      fmt = dfmt;
	    break;
	  case 'A':  case 'S':  case 'W':
	  case 'Y':  // SRFI-48 "yuppify" (pretty-print)
	    // We don't distinguish between ~S and ~W.  FIXME.
	    fmt = ObjectFormat.getInstance(ch != 'A');
	    if (numParams > 0)
	      {
		minWidth = getParam(stack, speci);
		int colInc = getParam(stack, speci+1);
		int minPad = getParam(stack, speci+2);
		padChar = getParam(stack, speci+3);
		fmt = new LispObjectFormat((ReportFormat) fmt,
					   minWidth, colInc, minPad,
					   padChar, seenAt ? 0 : 100);
	      }
	    break;
	  case 'C':
	    charVal = numParams > 0 ? getParam(stack, speci)
	      : PARAM_FROM_LIST;
	    fmt = LispCharacterFormat.getInstance(charVal, 1,
						  seenAt, seenColon);
	    break;
	  case '*':
	    fmt = new LispRepositionFormat(getParam(stack, speci),
					   seenColon, seenAt);
	    break;
	  case '(':
	    ch = seenColon ? (seenAt ? 'U' : 'C') : (seenAt ? 'T': 'L');
	    CaseConvertFormat cfmt = new CaseConvertFormat(null, ch);
	    stack.setSize(speci);
	    stack.push(cfmt);
	    stack.push(IntNum.make(start_nesting));
	    start_nesting = speci;
	    continue;
	  case ')':
	    if (start_nesting < 0
		|| ! (stack.elementAt(start_nesting)
		      instanceof CaseConvertFormat))
	      throw new ParseException("saw ~) without matching ~(", i);
	    cfmt = (CaseConvertFormat) stack.elementAt(start_nesting);
	    cfmt.setBaseFormat(popFormats(stack, start_nesting + 2, speci));
	    start_nesting = ((IntNum) stack.pop()).intValue();
	    continue;
	  case '?':
	    LispIterationFormat lfmt = new LispIterationFormat();
	    lfmt.seenAt = seenAt;
	    lfmt.maxIterations = 1;
	    lfmt.atLeastOnce = true;
	    fmt = lfmt;
	    break;
	  case '{':
	    lfmt = new LispIterationFormat();
	    lfmt.seenAt = seenAt;
	    lfmt.seenColon = seenColon;
	    lfmt.maxIterations = getParam(stack, speci);
	    stack.setSize(speci);
	    stack.push(lfmt);
	    stack.push(IntNum.make(start_nesting));
	    start_nesting = speci;
	    continue;
	  case '}':
	    if (start_nesting < 0
		|| ! (stack.elementAt(start_nesting)
		      instanceof LispIterationFormat))
	      throw new ParseException("saw ~} without matching ~{", i);
	    lfmt = (LispIterationFormat) stack.elementAt(start_nesting);
	    lfmt.atLeastOnce = seenColon;
	    if (speci > start_nesting + 2)
	      lfmt.body = popFormats(stack, start_nesting + 2, speci);
	    start_nesting = ((IntNum) stack.pop()).intValue();
	    continue;
	  case '<':
	    LispPrettyFormat pfmt = new LispPrettyFormat();
	    pfmt.seenAt = seenAt;
	    if (seenColon)
	      {
		pfmt.prefix = "(";
		pfmt.suffix = ")";
	      }
	    else
	      {
		pfmt.prefix = "";
		pfmt.suffix = "";
	      }
	    stack.setSize(speci);
	    stack.push(pfmt);
	    stack.push(IntNum.make(start_nesting));
	    stack.push(IntNum.make(choices_seen));
	    start_nesting = speci;
	    choices_seen = 0;
	    continue;
	  case '>':
	    if (start_nesting < 0
		|| ! (stack.elementAt(start_nesting)
		      instanceof LispPrettyFormat))
	      throw new ParseException("saw ~> without matching ~<", i);
	    fmt = popFormats(stack, start_nesting + 3 + choices_seen, speci);
	    stack.push(fmt);
	    pfmt = (LispPrettyFormat) stack.elementAt(start_nesting);
	    pfmt.segments = getFormats(stack, start_nesting + 3, stack.size());
	    stack.setSize(start_nesting + 3);
	    start_nesting = ((IntNum) stack.pop()).intValue();
	    start_nesting = ((IntNum) stack.pop()).intValue();
	    if (seenColon)
	      { // Logical Block for pretty-printing
		int nsegments = pfmt.segments.length;
		if (nsegments > 3)
		  throw new ParseException("too many segments in Logical Block format", i);
		if (nsegments >= 2)
		  {
		    if (! (pfmt.segments[0] instanceof LiteralFormat))
		      throw new ParseException("prefix segment is not literal", i);
		    pfmt.prefix = ((LiteralFormat) pfmt.segments[0]).content();
		    pfmt.body = pfmt.segments[1];
		  }
		else
		  pfmt.body = pfmt.segments[0];
		if (nsegments >=3)
		  {
		    if (! (pfmt.segments[2] instanceof LiteralFormat))
		      throw new ParseException("suffix segment is not literal", i);
		    pfmt.suffix = ((LiteralFormat) pfmt.segments[2]).content();
		  }
	      }
	    else // Justification
	      throw new ParseException("not implemented: justfication i.e. ~<...~>", i);
	    continue;
	  case '[':
	    LispChoiceFormat afmt = new LispChoiceFormat();
	    afmt.param = getParam(stack, speci);
	    if (afmt.param == PARAM_UNSPECIFIED)
	      afmt.param = PARAM_FROM_LIST;
	    if (seenColon)
	      afmt.testBoolean = true;
	    if (seenAt)
	      afmt.skipIfFalse = true;
	    stack.setSize(speci);
	    stack.push(afmt);
	    stack.push(IntNum.make(start_nesting));
	    stack.push(IntNum.make(choices_seen));
	    start_nesting = speci;
	    choices_seen = 0;
	    continue;
	  case ';':
	    if (start_nesting >= 0)
	      {
		if (stack.elementAt(start_nesting)
		    instanceof LispChoiceFormat)
		  {
		    afmt = (LispChoiceFormat) stack.elementAt(start_nesting);
		    if (seenColon)
		      afmt.lastIsDefault = true;
		    fmt = popFormats(stack,
				     start_nesting + 3 + choices_seen, speci);
		    stack.push(fmt);
		    choices_seen++;
		    continue;
		  }
		else if (stack.elementAt(start_nesting)
		    instanceof LispPrettyFormat)
		  {
		    pfmt = (LispPrettyFormat) stack.elementAt(start_nesting);
		    if (seenAt)
		      pfmt.perLine = true;
		    fmt = popFormats(stack,
				     start_nesting + 3 + choices_seen, speci);
		    stack.push(fmt);
		    choices_seen++;
		    continue;
		  }
		// else if saw ~< ...
	      }
	    throw new ParseException("saw ~; without matching ~[ or ~<", i);
	  case ']':
	    if (start_nesting < 0
		|| ! (stack.elementAt(start_nesting)
                      instanceof LispChoiceFormat))
              throw new ParseException("saw ~] without matching ~[", i);
	    fmt = popFormats(stack, start_nesting + 3 + choices_seen, speci);
	    stack.push(fmt);
	    afmt = (LispChoiceFormat) stack.elementAt(start_nesting);
	    afmt.choices = getFormats(stack, start_nesting + 3, stack.size());
	    stack.setSize(start_nesting + 3);
	    choices_seen = ((IntNum) stack.pop()).intValue();
	    start_nesting = ((IntNum) stack.pop()).intValue();
	    continue;
	  case '^':
	    param1 = getParam(stack, speci);
	    param2 = getParam(stack, speci+1);
	    param3 = getParam(stack, speci+2);
	    fmt = new LispEscapeFormat(param1, param2, param3);
	    break;
	  case '\n':
	    if (seenAt)
	      litbuf.append(ch);
	    if (! seenColon)
	      {
		while (i < limit)
		  {
		    ch = format[i++];
		    if (! Character.isWhitespace(ch))
		      {
			i--;
			break;
		      }
		  }
	      }
	    continue;
	  case '!':
	    fmt = FlushFormat.getInstance();
	    break;
	  case 'T':
	    param1 = getParam(stack, speci);
	    param2 = getParam(stack, speci+1);
	    param3 = getParam(stack, speci+2);
	    fmt = new LispTabulateFormat(param1, param2, param3, seenAt);
	    break;
	  case '&':
	    param1 = getParam(stack, speci);
	    fmt = new LispFreshlineFormat(param1);
	    break;
	  case 'I': // Indent
	    param1 = getParam(stack, speci);
	    if (param1 == PARAM_UNSPECIFIED)
	      param1 = 0;
	    fmt = LispIndentFormat.getInstance(param1, seenColon);
	    break;
	  case '_': // conditional newline
	    param1 = getParam(stack, speci);
	    if (param1 == PARAM_UNSPECIFIED)
	      param1 = 1;
	    charVal = seenColon && seenAt ? '\n' : ' ';
	    int kind;
	    if (seenAt && seenColon) kind = PrettyWriter.NEWLINE_MANDATORY;
	    else if (seenAt) kind = PrettyWriter.NEWLINE_MISER;
	    else if (seenColon) kind = PrettyWriter.NEWLINE_FILL;
	    else kind = PrettyWriter.NEWLINE_LINEAR;
	    fmt = LispNewlineFormat.getInstance(param1, kind);
	    break;
	  case '~':
	    if (numParams == 0)
	      {
		litbuf.append(ch);
		continue;
	      }
	    /* ... otherwise fall through ... */
	  case '|':
	    count = getParam(stack, speci);
	    if (count == PARAM_UNSPECIFIED)
	      count = 1;
	    // EXTENSION:  Allow repeating other characters than '~'.
	    charVal = getParam(stack, speci+1);
	    if (charVal == PARAM_UNSPECIFIED)
	      charVal = ch == '|' ? '\f' : '~';
	    fmt = LispCharacterFormat.getInstance(charVal, count,
						  false, false);
	    break;
	  case '%':
	    count = getParam(stack, speci);
	    if (count == PARAM_UNSPECIFIED)
	      count = 1;
	    fmt = LispNewlineFormat.getInstance(count,
						PrettyWriter.NEWLINE_LITERAL);
	    break;
          default:
	    throw new ParseException("unrecognized format specifier ~"+ch, i);
          }
	stack.setSize(speci);
	stack.push(fmt);
      }
    if (i > limit)
      throw new IndexOutOfBoundsException();
    if (start_nesting >= 0)
      {
	throw new ParseException("missing ~] or ~}", i);
      }
    this.length = stack.size();
    this.formats = new Format[this.length];
    stack.copyInto(this.formats);
  }

  static Format[] getFormats(java.util.Vector vector, int start, int end)
  {
    Format[] f = new Format[end - start];
    for (int i = start;  i < end;  i++)
      f[i - start] = (Format) vector.elementAt(i);
    return f;
  }

  static Format popFormats(java.util.Vector vector, int start, int end)
  {
    Format f;
    if (end == start + 1)
      f = (Format) vector.elementAt(start);
    else
      f = new CompoundFormat(getFormats(vector, start, end));
    vector.setSize(start);
    return f;
  }

  public LispFormat (String str)
    throws ParseException
  {
    this(str.toCharArray());
  }

  /*
  private void clearSpecs (int speci, int max)
  {
    int num = specs_length - speci - 1;
    for (int i = num;  i < max;  i++)
      addSpec(PARAM_UNSPECIFIED);
    specs_length = speci + 1;
  }
  */

  /*
  private void addSpec(Format fmt)
  {
    if (formats == null)
      formats = new Format[4];
    else
      {
	if (this.length == formats.length)
	  {
	    Format[] newformats = new Format[2 * this.length];
	    System.arraycopy(formats, 0, newformats, 0, this.length);
	    formats = newformats;
	  }
      }
    formats[this.length] = fmt;
    addSpec(this.length);
    this.length++;
  }
  */

  /*
  private void addSpec(int val)
  {
    //System.err.println("addSpec("+val+") at:"+specs_length);
    int old_size = specs.length;
    if (specs_length >= old_size)
      {
	int[] new_specs = new int[2 * old_size];
	System.arraycopy(specs, 0, new_specs, 0, old_size);
	specs = new_specs;
      }
    specs[specs_length++] = val;
  }
  */

  public LispFormat(char[] format)
    throws ParseException
  {
    this(format, 0, format.length);
  }

  public static int getParam(java.util.Vector vec, int index)
  {
    if (index >= vec.size())
      return PARAM_UNSPECIFIED;
    Object arg = vec.elementAt(index);
    if (arg == paramFromList)
      return PARAM_FROM_LIST;
    if (arg == paramFromCount)
      return PARAM_FROM_COUNT;
    if (arg == paramUnspecified)
      return PARAM_UNSPECIFIED;
    return getParam(arg, PARAM_UNSPECIFIED);
  }

  /** Convert sequence (or Object[]) to Object[].
   * Return null if not a valid Sequence. */
  public static Object[] asArray (Object arg)
  {
    if (arg instanceof Object[])
      return (Object[]) arg;
    if (!(arg instanceof Sequence))
      return null;
    int count = ((Sequence) arg).size();
    Object[] arr = new Object[count];
    int i = 0;
    while (arg instanceof Pair)
      {
	Pair pair = (Pair) arg;
	arr[i++] = pair.getCar();
	arg = pair.getCdr();
      }
    if (i < count)
      {
	if (! (arg instanceof Sequence))
	  return null;
	int npairs = i;
	Sequence seq = (Sequence) arg;
	for (; i < count; i++)
	  arr[i] = seq.get(npairs + i);
      }
    return arr;
  }
}

/** Add plural suffixes ("s" or "y/ies") of English words.
 * Used to implement the Common Lisp ~P ('Plural') format operator. */

class LispPluralFormat extends ReportFormat
{
  boolean backup;
  boolean y;

  public static LispPluralFormat getInstance (boolean backup, boolean y)
  {
    LispPluralFormat fmt = new LispPluralFormat();
    fmt.backup = backup;
    fmt.y = y;
    return fmt;
  }

  public int format(Object[] args, int start,
		    Writer dst, FieldPosition fpos)
    throws java.io.IOException
  {
    if (backup)
      start--;
    Object arg = args[start++];
    boolean plural = arg != IntNum.one();
    if (y)
      print(dst, plural ? "ies" : "y");
    else if (plural)
      dst.write('s');
    return start;
  }
}

/** Handle formatting of characters.
 * Used to implement the Common List ~C (Character) and ~~ (Tilde)
 * format operators. */

class LispCharacterFormat extends ReportFormat
{
  boolean seenAt;
  boolean seenColon;
  int count;
  int charVal;

  public static LispCharacterFormat
  getInstance(int charVal, int count, boolean seenAt, boolean seenColon)
  {
    LispCharacterFormat fmt = new LispCharacterFormat();
    fmt.count = count;
    fmt.charVal = charVal;
    fmt.seenAt = seenAt;
    fmt.seenColon = seenColon;
    return fmt;
  }

  public int format(Object[] args, int start,
		    Writer dst, FieldPosition fpos)
    throws java.io.IOException
  {
    int count = getParam(this.count, 1, args, start);
    if (this.count == LispFormat.PARAM_FROM_LIST)  start++;
    int charVal = getParam(this.charVal, '?', args, start);
    if (this.charVal == LispFormat.PARAM_FROM_LIST)  start++;
    while (--count >= 0)
      printChar (charVal, seenAt, seenColon, dst);
    return start;
  }

  public static void printChar(int ch, boolean seenAt, boolean seenColon,
			       Writer dst)
    throws java.io.IOException
  {
    if (seenAt)
      {
	print(dst, Char.toScmReadableString(ch));
      }
    else if (seenColon)
      {
	if (ch < ' ')
	  {
	    dst.write('^');
	    dst.write(ch + 0x40);
	  }
	else if (ch >= 0x7f)
	  {
	    print(dst, "#\\x");
	    print(dst, Integer.toString(ch, 16));
	  }
	else
	  dst.write(ch);
      }
    else
      {
	// if (ch > 0xFFFF) print surrogate chars; else
	dst.write(ch);
      }
  }
}

/** Handle formatting of newline ~% and ~_ format operator. */

class LispNewlineFormat extends ReportFormat
{
  static final String line_separator
    = System.getProperty("line.separator", "\n");

  /** One of NEWLINE_LITERAL, NEWLINE_LINEAR, NEWLINE_FILL, NEWLINE_MISER
   * or NEWLINE_MANDATORY.  These are defined in gnu.text.PrettyWriter. */
  int kind;

  int count;

  public static LispNewlineFormat
  getInstance(int count, int kind)
  {
    LispNewlineFormat fmt = new LispNewlineFormat();
    fmt.count = count;
    fmt.kind = kind;
    return fmt;
  }

  public int format(Object[] args, int start,
		    Writer dst, FieldPosition fpos)
    throws java.io.IOException
  {
    int count = getParam(this.count, 1, args, start);
    if (this.count == LispFormat.PARAM_FROM_LIST)  start++;
    while (--count >= 0)
      printNewline (kind, dst);
    return start;
  }

  public static void printNewline(int kind, Writer dst)
    throws java.io.IOException
  {
    if (dst instanceof OutPort && kind != PrettyWriter.NEWLINE_LITERAL)
      ((OutPort) dst).writeBreak(kind);
    else if (dst instanceof java.io.PrintWriter)
      // May make a difference if autoflush.  // FIXME flush if OutPort?
      ((java.io.PrintWriter) dst).println();
    else
      dst.write(line_separator);
  }
}

/** Handle formatting of ~I (indent) format operator. */

class LispIndentFormat extends ReportFormat
{
  boolean current;

  int columns;

  public static LispIndentFormat
  getInstance(int columns, boolean current)
  {
    LispIndentFormat fmt = new LispIndentFormat();
    fmt.columns = columns;
    fmt.current = current;
    return fmt;
  }

  public int format(Object[] args, int start,
		    Writer dst, FieldPosition fpos)
    throws java.io.IOException
  {
    int columns = getParam(this.columns, 0, args, start);
    if (this.columns == LispFormat.PARAM_FROM_LIST)  start++;
    if (dst instanceof OutPort)
      ((OutPort) dst).setIndentation(columns, current);
    return start;
  }
}

/** Perform general padding.
 * Used to implement the Common Lisp ~A (Ascii) and ~ (S-expression),
 * format operators, unless they have no parameters. */

class LispObjectFormat extends ReportFormat
{
  int minWidth;
  int colInc;
  int minPad;
  int padChar;
  int where;
  ReportFormat base;

  public LispObjectFormat(ReportFormat base,
			  int minWidth, int colInc, int minPad, int padChar,
			  int where)
  {
    this.base = base;
    this.minWidth = minWidth;
    this.colInc = colInc;
    this.minPad = minPad;
    this.padChar = padChar;
    this.where = where;
  }

  public int format(Object[] args, int start,
		    Writer dst, FieldPosition fpos)
    throws java.io.IOException
  {
    int minWidth = getParam(this.minWidth, 0, args, start);
    if (this.minWidth == LispFormat.PARAM_FROM_LIST)  start++;
    int colInc = getParam(this.colInc, 1, args, start);
    if (this.colInc == LispFormat.PARAM_FROM_LIST)  start++;
    int minPad = getParam(this.minPad, 0, args, start);
    if (this.minPad == LispFormat.PARAM_FROM_LIST)  start++;
    char padChar = getParam(this.padChar, ' ', args, start);
    if (this.padChar == LispFormat.PARAM_FROM_LIST)  start++;
    return gnu.text.PadFormat.format(base, args, start, dst,
				     padChar, minWidth, colInc, minPad,
				     where, fpos);
  }
}

class LispEscapeFormat extends ReportFormat
{
  int param1;
  int param2;
  int param3;
  boolean escapeAll;

  public final static LispEscapeFormat alwaysTerminate
  = new LispEscapeFormat(0, LispFormat.PARAM_UNSPECIFIED);

  public LispEscapeFormat(int param1, int param2)
  {
    this.param1 = param1;
    this.param2 = param2;
    this.param3 = LispFormat.PARAM_UNSPECIFIED;
  }

  public LispEscapeFormat(int param1, int param2, int param3)
  {
    this.param1 = param1;
    this.param2 = param2;
    this.param3 = param3;
  }

  static Numeric getParam(int param, Object[] args, int start)
  {
    if (param == LispFormat.PARAM_FROM_COUNT)
      return IntNum.make(args.length - start);
    if (param == LispFormat.PARAM_FROM_LIST)
      {
	Object arg = args[start];
	if (arg instanceof Numeric)
	  return (Numeric) arg;
	if (arg instanceof Number)
	  {
	    if (arg instanceof Float || arg instanceof Double)
	      return new DFloNum(((Number) arg).doubleValue());
	    return IntNum.make(((Number) arg).longValue());
	  }
	if (arg instanceof Char)
	  return new IntNum(((Char) arg).intValue());
	if (arg instanceof Character)
	  return new IntNum((int) ((Character) arg).charValue());
	return new DFloNum(Double.NaN);
      }
    return IntNum.make(param);
  }

  /** WRONG: Tests if we should exit the the surrounding format.
   * Returns 2*ARGS_USED+(DO_TERMINATE?1:0), where ARGS_USED is the
   * number of arguments consumed by the specification, and
   * DO_TERMINATE is true if we actually should exit.
   */
  public int format(Object[] args, int start, Writer dst, FieldPosition fpos)
    throws java.io.IOException
  {
    int orig_start = start;
    boolean do_terminate;
    if (param1 == LispFormat.PARAM_UNSPECIFIED)
      do_terminate = start == args.length;
    else if (param2 == LispFormat.PARAM_UNSPECIFIED && param1 == 0)
      do_terminate = true;  // Efficiency hack
    else
      {
	Numeric arg1 = getParam(param1, args, start);
	if (param1 == LispFormat.PARAM_FROM_LIST)  start++;
	if (param2 == LispFormat.PARAM_UNSPECIFIED)
	  {
	    do_terminate = arg1.isZero();
	  }
	else
	  {
	    Numeric arg2 = getParam(param2, args, start);
	    if (param2 == LispFormat.PARAM_FROM_LIST)  start++;
	    if (param3 == LispFormat.PARAM_UNSPECIFIED)
	      {
		do_terminate = arg1.equals(arg2);
	      }
	    else
	      {
		Numeric arg3 = getParam(param3, args, start);
		if (param3 == LispFormat.PARAM_FROM_LIST)  start++;
		do_terminate = arg2.geq(arg1) && arg3.geq(arg2);
	      }
	  }
      }
    return result(! do_terminate ? 0 : escapeAll ? ESCAPE_ALL : ESCAPE_NORMAL,
		  start);
  }

  public final static int ESCAPE_NORMAL = 0xF1;
  public final static int ESCAPE_ALL = 0xF2;
}

/** Handle <code>~<...~></code> - pretty-printing logical block.
 * (Justification is not implemented.) */

class LispPrettyFormat extends ReportFormat
{
  Format[] segments;
  Format body;
  String prefix;
  String suffix;
  boolean perLine;
  boolean seenAt;

  public int format(Object[] args, int start,
                    Writer dst, FieldPosition fpos)
    throws java.io.IOException
  {
    String pre = prefix;
    String suf = suffix;
    OutPort out = dst instanceof OutPort ? (OutPort) dst : null;
    try
      {
	if (seenAt)
	  {
	    if (out != null)
	      out.startLogicalBlock(pre, perLine, suffix);
	    start = ReportFormat.format(body, args, start, dst, fpos);
	  }
	else
	  {
	    Object curArg = args[start];
	    Object[] curArr = LispFormat.asArray(curArg);
	    if (curArr == null)
	      pre = suf = "";
	    if (out != null)
	      out.startLogicalBlock(pre, perLine, suffix);
	    if (curArr == null)
	      ObjectFormat.format(curArg, dst, -1, true);
	    else
	      ReportFormat.format(body, curArr, 0, dst, fpos);
	    start++;
	  }
      }
    finally
      {
	if (out != null)
	  out.endLogicalBlock(suf);
      }
    return start;
  }

  public String toString ()
  {
    StringBuffer sbuf = new StringBuffer();
    sbuf.append("LispPrettyFormat[");
    sbuf.append("prefix: \""); sbuf.append(prefix);
    sbuf.append("\", suffix: \"");  sbuf.append(suffix);
    sbuf.append("\", body: ");
    sbuf.append(body);
    sbuf.append("]");
    return sbuf.toString();
  }
}

class LispIterationFormat extends ReportFormat
{
  int maxIterations;
  boolean seenAt;
  boolean seenColon;
  boolean atLeastOnce;

  Format body;

  public static int format(Format body, int maxIterations,
			   Object[] args, int start,
			   Writer dst, boolean seenColon, boolean atLeastOnce)
    throws java.io.IOException
  {
    for (int i = 0; ; i++)
      {
	if (i == maxIterations && maxIterations != -1)
	  break;
	if (start == args.length && (i > 0 || ! atLeastOnce))
	  break;
	if (seenColon)
	  {
	    Object curArg = args[start];
	    Object[] curArr = LispFormat.asArray(curArg);
	    if (curArr == null)
	      { // ?
	      }
	    int result = ReportFormat.format(body, curArr, 0, dst, null);
	    start++;
	    if (ReportFormat.resultCode(result) == LispEscapeFormat.ESCAPE_ALL)
	      break;
	  }
	else
	  {
	    start = ReportFormat.format(body, args, start, dst, null);
	    if (start < 0)
	      {
		start = ReportFormat.nextArg(start);
		break;
	      }
	  }
      }
    return start;
  }

  public int format(Object[] args, int start,
                    Writer dst, FieldPosition fpos)
    throws java.io.IOException
  {
    int maxIterations = getParam(this.maxIterations, -1,
					    args, start);
    if (this.maxIterations == LispFormat.PARAM_FROM_LIST)  start++;

    Format body = this.body;
    if (body == null)
      {
	// from args
	Object arg = args[start++];
	if (arg instanceof java.text.Format)
	  body = (java.text.Format) arg;
	else
	  {
	    try
	      {
		body = new LispFormat(arg.toString());
	      }
	    catch (Exception ex)
	      {
		print(dst, "<invalid argument for \"~{~}\" format>");
		return args.length; // FIXME
	      }
	  }
      }
    if (seenAt)
      {
	return format(body, maxIterations, args, start,
		      dst, seenColon, atLeastOnce);
      }
    else
      {
	Object arg = args[start];
	Object[] curArgs = LispFormat.asArray(arg);
	if (curArgs == null)
	  dst.write("{"+arg+"}".toString());
	else
	  format(body, maxIterations, curArgs, 0,
		 dst, seenColon, atLeastOnce);
	return start + 1;
      }
  }

  public String toString ()
  {
    StringBuffer sbuf = new StringBuffer();
    sbuf.append("LispIterationFormat[");
    sbuf.append(body);
    sbuf.append("]");
    return sbuf.toString();
  }
}

class LispChoiceFormat extends ReportFormat
{
  int param;
  boolean lastIsDefault;
  boolean testBoolean;  // choice[0] is selected if arg is false.
  boolean skipIfFalse;
  Format[] choices;

  public int format(Object[] args, int start, Writer dst, FieldPosition fpos)
    throws java.io.IOException
  {
    Format fmt;
    if (testBoolean)  // Handles ~:[false~;true~]
      {
	fmt = choices[args[start] == Boolean.FALSE ? 0 : 1];
	start++;
      }
    else if (! skipIfFalse)
      {
	int index = getParam(this.param, LispFormat.PARAM_FROM_LIST,
					args, start);
	if (param == LispFormat.PARAM_FROM_LIST)  start++;
	if (index < 0 || index >= choices.length)
	  {
	    if (lastIsDefault)
	      index = choices.length - 1;
	    else
	      return start;
	  }
	fmt = choices[index];
      }
    else
      {
	if (args[start] == Boolean.FALSE)
	  return start + 1;
	fmt = choices[0];
      }
    return ReportFormat.format(fmt, args, start, dst, fpos);
  }
}

class LispRepositionFormat extends ReportFormat
{
  boolean backwards;
  boolean absolute;
  int count;

  public LispRepositionFormat(int count, boolean backwards, boolean absolute)
  {
    this.count = count;
    this.backwards = backwards;
    this.absolute = absolute;
  }

  public int format(Object[] args, int start, Writer dst, FieldPosition fpos)
    throws java.io.IOException
  {
    int count = getParam(this.count, absolute ? 0 : 1,
				    args, start);
    if (!absolute)
      {
	if (backwards)
	  count = -count;
	count += start;
      }
    return count < 0 ? 0 : count > args.length ? args.length : count;
  }
}

class LispFreshlineFormat  extends ReportFormat
{
  int count;

  public LispFreshlineFormat (int count)
  {
    this.count = count;
  }

  public int format(Object[] args, int start, Writer dst, FieldPosition fpos)
    throws java.io.IOException
  {
    int count = getParam(this.count, 1, args, start);
    if (this.count == LispFormat.PARAM_FROM_LIST)  start++;
    if (count > 0)
      {
	if (dst instanceof OutPort)
	  {
	    ((OutPort) dst).freshLine();
	    count--;
	  }
	while (--count >= 0)
	  dst.write('\n');
      }
    return start;
  }
}

class LispTabulateFormat extends ReportFormat
{
  boolean relative;
  int colnum;
  int colinc;
  int padChar;

  public LispTabulateFormat(int colnum, int colinc,
			    int padChar, boolean relative)
  {
    this.colnum = colnum;
    this.colinc = colinc;
    this.relative = relative;
    this.padChar = padChar;
  }

  public int format(Object[] args, int start, Writer dst, FieldPosition fpos)
    throws java.io.IOException
  {
    int colnum = getParam(this.colnum, 1, args, start);
    if (this.colnum == LispFormat.PARAM_FROM_LIST)  start++;
    int colinc = getParam(this.colinc, 1, args, start);
    if (this.colinc == LispFormat.PARAM_FROM_LIST)  start++;
    // Extension from SLIB:
    char padChar = getParam(this.padChar, ' ', args, start);
    if (this.padChar == LispFormat.PARAM_FROM_LIST)  start++;
    int column = -1;
    if (dst instanceof OutPort)
      column = ((OutPort) dst).getColumnNumber();
    int spaces;
    if (column >= 0)
      {
	if (! relative)
	  {
	    if (column < colnum)
	      spaces = colnum - column;
	    else if (colinc <= 0)
	      spaces = 0;
	    else
	      spaces = colinc - (column - colnum) % colinc;
	  }
	else
	  {
	    spaces = colnum + colinc - (column + colnum) % colinc;
	  }
      }
    else
      {
	spaces = relative ? colnum : 2;
      }
    while (--spaces >= 0)
      dst.write(padChar);
    return start;
  }
}

/* Support for ~F, ~$, ~E, ~G. */

class LispRealFormat extends ReportFormat
{
  char op;
  int arg1;
  int arg2;
  int arg3;
  int arg4;
  int arg5;
  int arg6;
  int arg7;
  boolean showPlus;
  boolean internalPad;
  /** Twice the number of args consumed; odd if any arg is PARAM_FROM_COUNT. */
  int argsUsed;

  LispRealFormat()
  {
    argsUsed = (arg1 == LispFormat.PARAM_FROM_COUNT
		|| arg2 == LispFormat.PARAM_FROM_COUNT
		|| arg3 == LispFormat.PARAM_FROM_COUNT
		|| arg4 == LispFormat.PARAM_FROM_COUNT
		|| arg5 == LispFormat.PARAM_FROM_COUNT
		|| arg6 == LispFormat.PARAM_FROM_COUNT
		|| arg7 == LispFormat.PARAM_FROM_COUNT) ? 1 : 0;
    if (arg1 == LispFormat.PARAM_FROM_LIST) argsUsed += 2;
    if (arg2 == LispFormat.PARAM_FROM_LIST) argsUsed += 2;
    if (arg3 == LispFormat.PARAM_FROM_LIST) argsUsed += 2;
    if (arg4 == LispFormat.PARAM_FROM_LIST) argsUsed += 2;
    if (arg5 == LispFormat.PARAM_FROM_LIST) argsUsed += 2;
    if (arg6 == LispFormat.PARAM_FROM_LIST) argsUsed += 2;
    if (arg7 == LispFormat.PARAM_FROM_LIST) argsUsed += 2;
  }

  public Format resolve (Object[] args, int start)
  {
    if (op == '$')
      {
	FixedRealFormat mfmt = new FixedRealFormat();
	int decimals = getParam(this.arg1, 2, args, start);
	if (this.arg1 == LispFormat.PARAM_FROM_LIST)  start++;
	int digits = getParam(this.arg2, 1, args, start);
	if (this.arg2 == LispFormat.PARAM_FROM_LIST)  start++;
	int width = getParam(this.arg3, 0, args, start);
	if (this.arg3 == LispFormat.PARAM_FROM_LIST)  start++;
	char padChar = getParam(this.arg4, ' ', args, start);
	if (this.arg4 == LispFormat.PARAM_FROM_LIST)  start++;

	mfmt.setMaximumFractionDigits(decimals);
	mfmt.setMinimumIntegerDigits(digits);
	mfmt.width = width;
	mfmt.padChar = padChar;
	mfmt.internalPad = internalPad;
	mfmt.showPlus = showPlus;
	return mfmt;
      }
    else if (op == 'F')
      {
	FixedRealFormat mfmt = new FixedRealFormat();
	int width = getParam(this.arg1, 0, args, start);
	if (this.arg1 == LispFormat.PARAM_FROM_LIST)  start++;
	int decimals = getParam(this.arg2, -1, args, start);
	if (this.arg2 == LispFormat.PARAM_FROM_LIST)  start++;
	int scale = getParam(this.arg3, 0, args, start);
	if (this.arg3 == LispFormat.PARAM_FROM_LIST)  start++;
	mfmt.overflowChar = getParam(this.arg4, '\0', args, start);
	if (this.arg4 == LispFormat.PARAM_FROM_LIST)  start++;
	char padChar = getParam(this.arg5, ' ', args, start);
	if (this.arg5 == LispFormat.PARAM_FROM_LIST)  start++;
	mfmt.setMaximumFractionDigits(decimals);
	mfmt.setMinimumIntegerDigits(0);
	mfmt.width = width;
	mfmt.scale = scale;
	mfmt.padChar = padChar;
	mfmt.internalPad = internalPad;
	mfmt.showPlus = showPlus;
	return mfmt;
      }
    else // if (op == 'E' || op == 'G')
      {
	ExponentialFormat efmt = new ExponentialFormat();
        efmt.exponentShowSign = true;
	efmt.width = getParam(this.arg1, 0, args, start);
	if (this.arg1 == LispFormat.PARAM_FROM_LIST)  start++;
	efmt.fracDigits = getParam(this.arg2, -1, args, start);
	if (this.arg2 == LispFormat.PARAM_FROM_LIST)  start++;
	efmt.expDigits = getParam(this.arg3, 0, args, start);
	if (this.arg3 == LispFormat.PARAM_FROM_LIST)  start++;
	efmt.intDigits = getParam(this.arg4, 1, args, start);
	if (this.arg4 == LispFormat.PARAM_FROM_LIST)  start++;
	efmt.overflowChar = getParam(this.arg5, '\0', args, start);
	if (this.arg5 == LispFormat.PARAM_FROM_LIST)  start++;
	efmt.padChar = getParam(this.arg6, ' ', args, start);
	if (this.arg6 == LispFormat.PARAM_FROM_LIST)  start++;
	efmt.exponentChar = getParam(this.arg7, 'E', args, start);
	if (this.arg7 == LispFormat.PARAM_FROM_LIST)  start++;
	efmt.general = op == 'G';
	efmt.showPlus = showPlus;
	return efmt;
      }
  }

  public int format(Object[] args, int start, Writer dst, FieldPosition fpos)
    throws java.io.IOException
  {
    StringBuffer sbuf = new StringBuffer(100);
    Format fmt = resolve(args, start);
    start += argsUsed >> 1;
    RealNum value = (RealNum) args[start++];
    fmt.format(value, sbuf, fpos);
    dst.write(sbuf.toString());
    return start;
  }
}


text:
package ethanjones.cubes.launcher;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map.Entry;

public class VersionWindow extends JFrame {
  static VersionWindow INSTANCE;
  private static Comparator<String> stringComparator = Collections.reverseOrder(String.CASE_INSENSITIVE_ORDER);

  private ImageIcon image;
  private JLabel imageLabel;
  private JLabel loadingLabel;

  private Box box;
  private JComboBox<String> version;
  private JButton play;

  private RunStatus runStatus;
  private JLabel runLabel;
  private JProgressBar runProgress;

  VersionWindow() {
    INSTANCE = this;

    setLayout(new BorderLayout());
    setSize(240, 140);

    image = new ImageIcon(resolveResource("logo.png"));
    imageLabel = new JLabel(image);
    add(imageLabel, BorderLayout.CENTER);

    loadingLabel = new JLabel("Loading", SwingConstants.CENTER);
    add(loadingLabel, BorderLayout.PAGE_END);

    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent we) {
        dispose();
      }
    });

    setVisible(true);
    setLocationRelativeTo(null);

    setIconImages(Arrays.asList(
            new ImageIcon(resolveResource("icon-128x.png")).getImage(),
            new ImageIcon(resolveResource("icon-64x.png")).getImage(),
            new ImageIcon(resolveResource("icon-32x.png")).getImage(),
            new ImageIcon(resolveResource("icon-16x.png")).getImage()));
  }

  private URL resolveResource(String path) {
    try {
      URL resource = getClass().getResource("/" + path);
      if (resource != null) return resource;
      File file = new File(path);
      if (file.exists()) return file.toURI().toURL();
      throw new IllegalStateException("Failed to find resource \"" + path + "\"");
    } catch (MalformedURLException e) {
      throw new IllegalStateException("Failed to find resource \"" + path + "\"", e);
    }
  }

  void setVersions() {
    if (box != null) {
      remove(box);
      box = null;
    }
    if (loadingLabel != null) {
      remove(loadingLabel);
      loadingLabel = null;
    }

    ArrayList<String> releases = new ArrayList<String>();
    ArrayList<String> snapshots = new ArrayList<String>();
    for (Entry<String, Version> entry : CubesLauncher.versions.entrySet()) {
      if (entry.getValue().release) {
        releases.add(entry.getKey());
      } else {
        snapshots.add(entry.getKey());
      }
    }
    Collections.sort(releases, stringComparator);
    Collections.sort(snapshots, stringComparator);
    ArrayList<String> versions = new ArrayList<String>();
    versions.addAll(releases);
    versions.addAll(snapshots);

    System.out.println("\nVersions:");
    for (String version : versions) {
      System.out.println(CubesLauncher.versions.get(version).toString());
    }
    System.out.println();

    String[] array = versions.toArray(new String[versions.size()]);

    box = Box.createHorizontalBox();

    version = new JComboBox<String>(array);
    box.add(version);
    box.add(Box.createHorizontalGlue());
    play = new JButton("Play");
    play.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        final String s = (String) version.getSelectedItem();
        final RunStatus runStatus = new RunStatus();
        VersionWindow.this.runStatus = runStatus;
        new Thread("Cubes-Run") {
          @Override
          public void run() {
            CubesLauncher.run(CubesLauncher.versions.get(s), runStatus);
          }
        }.start();
      }
    });
    box.add(play);
    add(box, BorderLayout.PAGE_END);
    revalidate();
  }

  void updateRunProgress() {
    if (runStatus != null) {
      if (box != null) {
        remove(box);
        box = null;
      }
      if (loadingLabel != null) {
        remove(loadingLabel);
        loadingLabel = null;
      }

      if (runStatus.stage == RunStatus.Stage.verifying) {
        if (runProgress != null) {
          remove(runProgress);
          runProgress = null;
        }

        if (runLabel == null) {
          runLabel = new JLabel("Verifying", SwingConstants.CENTER);
          add(runLabel, BorderLayout.PAGE_END);
        }
      } else if (runStatus.stage == RunStatus.Stage.downloading) {
        if (runLabel != null) {
          remove(runLabel);
          runLabel = null;
        }

        if (runProgress == null) {
          runProgress = new JProgressBar(0, 100);
          runProgress.setStringPainted(true);
          add(runProgress, BorderLayout.PAGE_END);
        }
        int percent = (int) (runStatus.progress * 100);
        runProgress.setValue(percent);
        runProgress.setString("Downloading " + percent +"%");
      }
    }
  }
}


text:
import itertools

from oslo_log import log
import passlib.hash

import keystone.conf
from keystone import exception
from keystone.i18n import _

CONF = keystone.conf.CONF
LOG = log.getLogger(__name__)

SUPPORTED_HASHERS = frozenset([passlib.hash.bcrypt,
                               passlib.hash.scrypt,
                               passlib.hash.pbkdf2_sha512,
                               passlib.hash.sha512_crypt])

_HASHER_NAME_MAP = {hasher.name: hasher for hasher in SUPPORTED_HASHERS}

# NOTE(notmorgan): Build the list of prefixes. This comprehension builds
# a dictionary where the keys are the prefix (all hashedpasswords are
# '$<ident>$<metadata>$<hash>') so we can do a fast-lookup on the hasher to
# use. If has hasher has multiple ident options it is encoded in the
# .ident_values attribute whereas hashers that have a single option
# (sha512_crypt) only has the .ident attribute.
_HASHER_IDENT_MAP = {
    prefix: module for module, prefix in itertools.chain(
        *[zip([mod] * len(getattr(mod, 'ident_values', (mod.ident,))),
              getattr(mod, 'ident_values', (mod.ident,)))
          for mod in SUPPORTED_HASHERS])}

def _get_hasher_from_ident(hashed):
    try:
        return _HASHER_IDENT_MAP[hashed[0:hashed.index('$', 1) + 1]]
    except KeyError:
        raise ValueError(
            _('Unsupported password hashing algorithm ident: %s') %
            hashed[0:hashed.index('$', 1) + 1])

def verify_length_and_trunc_password(password):
    """Verify and truncate the provided password to the max_password_length."""
    max_length = CONF.identity.max_password_length
    try:
        if len(password) > max_length:
            if CONF.strict_password_check:
                raise exception.PasswordVerificationError(size=max_length)
            else:
                msg = "Truncating user password to %d characters."
                LOG.warning(msg, max_length)
                return password[:max_length]
        else:
            return password
    except TypeError:
        raise exception.ValidationError(attribute='string', target='password')

def check_password(password, hashed):
    """Check that a plaintext password matches hashed.

    hashpw returns the salt value concatenated with the actual hash value.
    It extracts the actual salt if this value is then passed as the salt.

    """
    if password is None or hashed is None:
        return False
    password_utf8 = verify_length_and_trunc_password(password).encode('utf-8')
    hasher = _get_hasher_from_ident(hashed)
    return hasher.verify(password_utf8, hashed)

def hash_user_password(user):
    """Hash a user dict's password without modifying the passed-in dict."""
    password = user.get('password')
    if password is None:
        return user

    return dict(user, password=hash_password(password))

def hash_password(password):
    """Hash a password. Harder."""
    params = {}
    password_utf8 = verify_length_and_trunc_password(password).encode('utf-8')
    conf_hasher = CONF.identity.password_hash_algorithm
    hasher = _HASHER_NAME_MAP.get(conf_hasher)

    if hasher is None:
        raise RuntimeError(
            _('Password Hash Algorithm %s not found') %
            CONF.identity.password_hash_algorithm)

    if CONF.identity.password_hash_rounds:
        params['rounds'] = CONF.identity.password_hash_rounds
    if hasher is passlib.hash.scrypt:
        if CONF.identity.scrypt_block_size:
            params['block_size'] = CONF.identity.scrypt_block_size
        if CONF.identity.scrypt_parallelism:
            params['parallelism'] = CONF.identity.scrypt_parallelism
        if CONF.identity.salt_bytesize:
            params['salt_size'] = CONF.identity.salt_bytesize
    if hasher is passlib.hash.pbkdf2_sha512:
        if CONF.identity.salt_bytesize:
            params['salt_size'] = CONF.identity.salt_bytesize

    return hasher.using(**params).hash(password_utf8)


text:
package java.awt;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.peer.ChoicePeer;
import java.io.Serializable;
import java.util.EventListener;
import java.util.Vector;

import javax.accessibility.Accessible;
import javax.accessibility.AccessibleAction;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;

/**
 * This class implements a drop down choice list.
 *
 * @author Aaron M. Renn (arenn@urbanophile.com)
 */
public class Choice extends Component
  implements ItemSelectable, Serializable, Accessible
{
  /**
   * The number used to generate the name returned by getName.
   */
  private static transient long next_choice_number;

  // Serialization constant
  private static final long serialVersionUID = -4075310674757313071L;

  /**
   * @serial A list of items for the choice box, which can be null.
   * This is package-private to avoid an accessor method.
   */
  Vector pItems = new Vector();

  /**
   * @serial The index of the selected item in the choice box.
   */
  private int selectedIndex = -1;

  /**
   * ItemListener chain
   */
  private ItemListener item_listeners;

  /**
   * This class provides accessibility support for the
   * combo box.
   *
   * @author Jerry Quinn  (jlquinn@optonline.net)
   * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
   */
  protected class AccessibleAWTChoice
    extends AccessibleAWTComponent
    implements AccessibleAction
  {

    /**
     * Serialization constant to match JDK 1.5
     */
    private static final long serialVersionUID = 7175603582428509322L;

    /**
     * Default constructor which simply calls the
     * super class for generic component accessibility
     * handling.
     */
    public AccessibleAWTChoice()
    {
      super();
    }

    /**
     * Returns an implementation of the AccessibleAction
     * interface for this accessible object.  In this case, the
     * current instance is simply returned (with a more appropriate
     * type), as it also implements the accessible action as well as
     * the context.
     *
     * @return the accessible action associated with this context.
     * @see javax.accessibility.AccessibleAction
     */
    public AccessibleAction getAccessibleAction()
    {
      return this;
    }

    /**
     * Returns the role of this accessible object.
     *
     * @return the instance of AccessibleRole,
     *         which describes this object.
     * @see javax.accessibility.AccessibleRole
     */
    public AccessibleRole getAccessibleRole()
    {
      return AccessibleRole.COMBO_BOX;
    }

    /**
     * Returns the number of actions associated with this accessible
     * object.  In this case, it is the number of choices available.
     *
     * @return the number of choices available.
     * @see javax.accessibility.AccessibleAction#getAccessibleActionCount()
     */
    public int getAccessibleActionCount()
    {
      return pItems.size();
    }

    /**
     * Returns a description of the action with the supplied id.
     * In this case, it is the text used in displaying the particular
     * choice on-screen.
     *
     * @param i the id of the choice whose description should be
     *          retrieved.
     * @return the String used to describe the choice.
     * @see javax.accessibility.AccessibleAction#getAccessibleActionDescription(int)
     */
    public String getAccessibleActionDescription(int i)
    {
      return (String) pItems.get(i);
    }

    /**
     * Executes the action with the specified id.  In this case,
     * calling this method provides the same behaviour as would
     * choosing a choice from the list in a visual manner.
     *
     * @param i the id of the choice to select.
     * @return true if a valid choice was specified.
     * @see javax.accessibility.AccessibleAction#doAccessibleAction(int)
     */
    public boolean doAccessibleAction(int i)
    {
      if (i < 0 || i >= pItems.size())
	return false;

      Choice.this.select( i );

      return true;
    }
  }

  /**
   * Initializes a new instance of Choice.
   *
   * @exception HeadlessException If GraphicsEnvironment.isHeadless()
   * returns true
   */
  public Choice()
  {
    if (GraphicsEnvironment.isHeadless())
      throw new HeadlessException ();
  }

  /**
   * Returns the number of items in the list.
   *
   * @return The number of items in the list.
   */
  public int getItemCount()
  {
    return countItems ();
  }

  /**
   * Returns the number of items in the list.
   *
   * @return The number of items in the list.
   *
   * @deprecated This method is deprecated in favor of getItemCount.
   */
  public int countItems()
  {
    return pItems.size();
  }

  /**
   * Returns the item at the specified index in the list.
   *
   * @param index The index into the list to return the item from.
   *
   * @exception ArrayIndexOutOfBoundsException If the index is invalid.
   */
  public String getItem(int index)
  {
    return (String)pItems.elementAt(index);
  }

  /**
   * Adds the specified item to this choice box.
   *
   * @param item The item to add.
   *
   * @exception NullPointerException If the item's value is null
   *
   * @since 1.1
   */
  public synchronized void add(String item)
  {
    if (item == null)
      throw new NullPointerException ("item must be non-null");

    pItems.addElement(item);

    if (peer != null)
      ((ChoicePeer) peer).add(item, getItemCount() - 1);

    if (selectedIndex == -1)
      select( 0 );
  }

  /**
   * Adds the specified item to this choice box.
   *
   * This method is oboslete since Java 2 platform 1.1. Please use @see add
   * instead.
   *
   * @param item The item to add.
   *
   * @exception NullPointerException If the item's value is equal to null
   */
  public synchronized void addItem(String item)
  {
    add(item);
  }

  /** Inserts an item into this Choice.  Existing items are shifted
   * upwards.  If the new item is the only item, then it is selected.
   * If the currently selected item is shifted, then the first item is
   * selected.  If the currently selected item is not shifted, then it
   * remains selected.
   *
   * @param item The item to add.
   * @param index The index at which the item should be inserted.
   *
   * @exception IllegalArgumentException If index is less than 0
   */
  public synchronized void insert(String item, int index)
  {
    if (index < 0)
      throw new IllegalArgumentException ("index may not be less then 0");

    if (index > getItemCount ())
      index = getItemCount ();

    pItems.insertElementAt(item, index);

    if (peer != null)
      ((ChoicePeer) peer).add (item, index);

    if (selectedIndex == -1 || selectedIndex >= index)
      select(0);
  }

  /**
   * Removes the specified item from the choice box.
   *
   * @param item The item to remove.
   *
   * @exception IllegalArgumentException If the specified item doesn't exist.
   */
  public synchronized void remove(String item)
  {
    int index = pItems.indexOf(item);
    if (index == -1)
      throw new IllegalArgumentException ("item \""
					  + item + "\" not found in Choice");
    remove(index);
  }

  /**
   * Removes the item at the specified index from the choice box.
   *
   * @param index The index of the item to remove.
   *
   * @exception IndexOutOfBoundsException If the index is not valid.
   */
  public synchronized void remove(int index)
  {
    if ((index < 0) || (index > getItemCount()))
      throw new IllegalArgumentException("Bad index: " + index);

    pItems.removeElementAt(index);

    if (peer != null)
      ((ChoicePeer) peer).remove( index );

    if( getItemCount() == 0 )
      selectedIndex = -1;
    else
      {
       if( selectedIndex > index )
         selectedIndex--;
       else if( selectedIndex == index )
         selectedIndex = 0;

       if( peer != null )
         ((ChoicePeer)peer).select( selectedIndex );
       }
  }

  /**
   * Removes all of the objects from this choice box.
   */
  public synchronized void removeAll()
  {
    if (getItemCount() <= 0)
      return;

    pItems.removeAllElements ();

    if (peer != null)
      {
	ChoicePeer cp = (ChoicePeer) peer;
	cp.removeAll ();
      }

    selectedIndex = -1;
  }

  /**
   * Returns the currently selected item, or null if no item is
   * selected.
   *
   * @return The currently selected item.
   */
  public synchronized String getSelectedItem()
  {
    return (selectedIndex == -1
	    ? null
	    : ((String)pItems.elementAt(selectedIndex)));
  }

  /**
   * Returns an array with one row containing the selected item.
   *
   * @return An array containing the selected item.
   */
  public synchronized Object[] getSelectedObjects()
  {
    if (selectedIndex == -1)
      return null;

    Object[] objs = new Object[1];
    objs[0] = pItems.elementAt(selectedIndex);

    return objs;
  }

  /**
   * Returns the index of the selected item.
   *
   * @return The index of the selected item.
   */
  public int getSelectedIndex()
  {
    return selectedIndex;
  }

  /**
   * Forces the item at the specified index to be selected.
   *
   * @param index The index of the row to make selected.
   *
   * @exception IllegalArgumentException If the specified index is invalid.
   */
  public synchronized void select(int index)
  {
    if ((index < 0) || (index >= getItemCount()))
      throw new IllegalArgumentException("Bad index: " + index);

    if( selectedIndex == index )
      return;

    selectedIndex = index;
    if( peer != null )
      ((ChoicePeer)peer).select( index );
  }

  /**
   * Forces the named item to be selected.
   *
   * @param item The item to be selected.
   *
   * @exception IllegalArgumentException If the specified item does not exist.
   */
  public synchronized void select(String item)
  {
    int index = pItems.indexOf(item);
    if( index >= 0 )
      select( index );
  }

  /**
   * Creates the native peer for this object.
   */
  public void addNotify()
  {
    if (peer == null)
      peer = getToolkit ().createChoice (this);
    super.addNotify ();
  }

  /**
   * Adds the specified listener to the list of registered listeners for
   * this object.
   *
   * @param listener The listener to add.
   */
  public synchronized void addItemListener(ItemListener listener)
  {
    item_listeners = AWTEventMulticaster.add(item_listeners, listener);
  }

  /**
   * Removes the specified listener from the list of registered listeners for
   * this object.
   *
   * @param listener The listener to remove.
   */
  public synchronized void removeItemListener(ItemListener listener)
  {
    item_listeners = AWTEventMulticaster.remove(item_listeners, listener);
  }

  /**
   * Processes this event by invoking processItemEvent() if the
   * event is an instance of ItemEvent, otherwise the event
   * is passed to the superclass.
   *
   * @param event The event to process.
   */
  protected void processEvent(AWTEvent event)
  {
    if (event instanceof ItemEvent)
      processItemEvent((ItemEvent)event);
    else
      super.processEvent(event);
  }

  void dispatchEventImpl(AWTEvent e)
  {
    super.dispatchEventImpl(e);

    if( e.id <= ItemEvent.ITEM_LAST && e.id >= ItemEvent.ITEM_FIRST &&
	( item_listeners != null ||
	  ( eventMask & AWTEvent.ITEM_EVENT_MASK ) != 0 ) )
      processEvent(e);
  }

  /**
   * Processes item event by dispatching to any registered listeners.
   *
   * @param event The event to process.
   */
  protected void processItemEvent(ItemEvent event)
  {
    int index = pItems.indexOf((String) event.getItem());
    if (item_listeners != null)
      item_listeners.itemStateChanged(event);
  }

  /**
   * Returns a debugging string for this object.
   *
   * @return A debugging string for this object.
   */
  protected String paramString()
  {
    return "selectedIndex=" + selectedIndex + "," + super.paramString();
  }

  /**
   * Returns an array of all the objects currently registered as FooListeners
   * upon this Choice. FooListeners are registered using the addFooListener
   * method.
   *
   * @exception ClassCastException If listenerType doesn't specify a class or
   * interface that implements java.util.EventListener.
   *
   * @since 1.3
   */
  public EventListener[] getListeners (Class listenerType)
  {
    if (listenerType == ItemListener.class)
      return AWTEventMulticaster.getListeners (item_listeners, listenerType);

    return super.getListeners (listenerType);
  }

  /**
   * Returns all registered item listeners.
   *
   * @since 1.4
   */
  public ItemListener[] getItemListeners ()
  {
    return (ItemListener[]) getListeners (ItemListener.class);
  }

  /**
   * Gets the AccessibleContext associated with this Choice.
   * The context is created, if necessary.
   *
   * @return the associated context
   */
  public AccessibleContext getAccessibleContext()
  {
    /* Create the context if this is the first request */
    if (accessibleContext == null)
      accessibleContext = new AccessibleAWTChoice();
    return accessibleContext;
  }

  /**
   * Generate a unique name for this Choice.
   *
   * @return A unique name for this Choice.
   */
  String generateName()
  {
    return "choice" + getUniqueLong();
  }

  private static synchronized long getUniqueLong()
  {
    return next_choice_number++;
  }
} // class Choice


text:
FactoryGirl.define do
  factory :itsf_fund_reports_execution, :class => 'ITSF::FundReports::Execution' do
    quantity 1
    description "Order description"
    price "9.99"
    executed_at 1.day.ago
    sequence(:order_identifier) { |i| "Order identifier ##{i}" }
    order_reference "Order reference"
    association :account, :factory => :itsf_fund_reports_account
    association :action, :factory => :itsf_fund_reports_action
    association :currency, :factory => :itsf_fund_reports_currency
    association :exchange, :factory => :itsf_fund_reports_exchange
    association :underlying, :factory => :itsf_fund_reports_underlying

    factory :itsf_fund_reports_execution_sell do
      executed_at 1.day.ago
      association :action, :factory => :itsf_fund_reports_action_sld
    end # factory

    factory :itsf_fund_reports_execution_buy_to_cover do
      executed_at 1.day.ago - 1.hour
      association :action, :factory => :itsf_fund_reports_action_bot
    end # factory

    factory :itsf_fund_reports_execution_buy do
      executed_at 1.day.ago
      association :action, :factory => :itsf_fund_reports_action_bot
    end # factory
  end # factory
end # FactoryGirl.define