text:
package record

import (
	"fmt"
	"math/rand"
	"time"

	"k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/api/v1"
	metav1 "k8s.io/kubernetes/pkg/apis/meta/v1"
	"k8s.io/kubernetes/pkg/client/restclient"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/util/clock"
	utilruntime "k8s.io/kubernetes/pkg/util/runtime"
	"k8s.io/kubernetes/pkg/watch"

	"net/http"

	"github.com/golang/glog"
)

const maxTriesPerEvent = 12

var defaultSleepDuration = 10 * time.Second

const maxQueuedEvents = 1000

// EventSink knows how to store events (client.Client implements it.)
// EventSink must respect the namespace that will be embedded in 'event'.
// It is assumed that EventSink will return the same sorts of errors as
// pkg/client's REST client.
type EventSink interface {
	Create(event *v1.Event) (*v1.Event, error)
	Update(event *v1.Event) (*v1.Event, error)
	Patch(oldEvent *v1.Event, data []byte) (*v1.Event, error)
}

// EventRecorder knows how to record events on behalf of an EventSource.
type EventRecorder interface {
	// Event constructs an event from the given information and puts it in the queue for sending.
	// 'object' is the object this event is about. Event will make a reference-- or you may also
	// pass a reference to the object directly.
	// 'type' of this event, and can be one of Normal, Warning. New types could be added in future
	// 'reason' is the reason this event is generated. 'reason' should be short and unique; it
	// should be in UpperCamelCase format (starting with a capital letter). "reason" will be used
	// to automate handling of events, so imagine people writing switch statements to handle them.
	// You want to make that easy.
	// 'message' is intended to be human readable.
	//
	// The resulting event will be created in the same namespace as the reference object.
	Event(object runtime.Object, eventtype, reason, message string)

	// Eventf is just like Event, but with Sprintf for the message field.
	Eventf(object runtime.Object, eventtype, reason, messageFmt string, args ...interface{})

	// PastEventf is just like Eventf, but with an option to specify the event's 'timestamp' field.
	PastEventf(object runtime.Object, timestamp metav1.Time, eventtype, reason, messageFmt string, args ...interface{})
}

// EventBroadcaster knows how to receive events and send them to any EventSink, watcher, or log.
type EventBroadcaster interface {
	// StartEventWatcher starts sending events received from this EventBroadcaster to the given
	// event handler function. The return value can be ignored or used to stop recording, if
	// desired.
	StartEventWatcher(eventHandler func(*v1.Event)) watch.Interface

	// StartRecordingToSink starts sending events received from this EventBroadcaster to the given
	// sink. The return value can be ignored or used to stop recording, if desired.
	StartRecordingToSink(sink EventSink) watch.Interface

	// StartLogging starts sending events received from this EventBroadcaster to the given logging
	// function. The return value can be ignored or used to stop recording, if desired.
	StartLogging(logf func(format string, args ...interface{})) watch.Interface

	// NewRecorder returns an EventRecorder that can be used to send events to this EventBroadcaster
	// with the event source set to the given event source.
	NewRecorder(source v1.EventSource) EventRecorder
}

// Creates a new event broadcaster.
func NewBroadcaster() EventBroadcaster {
	return &eventBroadcasterImpl{watch.NewBroadcaster(maxQueuedEvents, watch.DropIfChannelFull), defaultSleepDuration}
}

func NewBroadcasterForTests(sleepDuration time.Duration) EventBroadcaster {
	return &eventBroadcasterImpl{watch.NewBroadcaster(maxQueuedEvents, watch.DropIfChannelFull), sleepDuration}
}

type eventBroadcasterImpl struct {
	*watch.Broadcaster
	sleepDuration time.Duration
}

// StartRecordingToSink starts sending events received from the specified eventBroadcaster to the given sink.
// The return value can be ignored or used to stop recording, if desired.
// TODO: make me an object with parameterizable queue length and retry interval
func (eventBroadcaster *eventBroadcasterImpl) StartRecordingToSink(sink EventSink) watch.Interface {
	// The default math/rand package functions aren't thread safe, so create a
	// new Rand object for each StartRecording call.
	randGen := rand.New(rand.NewSource(time.Now().UnixNano()))
	eventCorrelator := NewEventCorrelator(clock.RealClock{})
	return eventBroadcaster.StartEventWatcher(
		func(event *v1.Event) {
			recordToSink(sink, event, eventCorrelator, randGen, eventBroadcaster.sleepDuration)
		})
}

func recordToSink(sink EventSink, event *v1.Event, eventCorrelator *EventCorrelator, randGen *rand.Rand, sleepDuration time.Duration) {
	// Make a copy before modification, because there could be multiple listeners.
	// Events are safe to copy like this.
	eventCopy := *event
	event = &eventCopy
	result, err := eventCorrelator.EventCorrelate(event)
	if err != nil {
		utilruntime.HandleError(err)
	}
	if result.Skip {
		return
	}
	tries := 0
	for {
		if recordEvent(sink, result.Event, result.Patch, result.Event.Count > 1, eventCorrelator) {
			break
		}
		tries++
		if tries >= maxTriesPerEvent {
			glog.Errorf("Unable to write event '%#v' (retry limit exceeded!)", event)
			break
		}
		// Randomize the first sleep so that various clients won't all be
		// synced up if the master goes down.
		if tries == 1 {
			time.Sleep(time.Duration(float64(sleepDuration) * randGen.Float64()))
		} else {
			time.Sleep(sleepDuration)
		}
	}
}

func isKeyNotFoundError(err error) bool {
	statusErr, _ := err.(*errors.StatusError)

	if statusErr != nil && statusErr.Status().Code == http.StatusNotFound {
		return true
	}

	return false
}

// recordEvent attempts to write event to a sink. It returns true if the event
// was successfully recorded or discarded, false if it should be retried.
// If updateExistingEvent is false, it creates a new event, otherwise it updates
// existing event.
func recordEvent(sink EventSink, event *v1.Event, patch []byte, updateExistingEvent bool, eventCorrelator *EventCorrelator) bool {
	var newEvent *v1.Event
	var err error
	if updateExistingEvent {
		newEvent, err = sink.Patch(event, patch)
	}
	// Update can fail because the event may have been removed and it no longer exists.
	if !updateExistingEvent || (updateExistingEvent && isKeyNotFoundError(err)) {
		// Making sure that ResourceVersion is empty on creation
		event.ResourceVersion = ""
		newEvent, err = sink.Create(event)
	}
	if err == nil {
		// we need to update our event correlator with the server returned state to handle name/resourceversion
		eventCorrelator.UpdateState(newEvent)
		return true
	}

	// If we can't contact the server, then hold everything while we keep trying.
	// Otherwise, something about the event is malformed and we should abandon it.
	switch err.(type) {
	case *restclient.RequestConstructionError:
		// We will construct the request the same next time, so don't keep trying.
		glog.Errorf("Unable to construct event '%#v': '%v' (will not retry!)", event, err)
		return true
	case *errors.StatusError:
		if errors.IsAlreadyExists(err) {
			glog.V(5).Infof("Server rejected event '%#v': '%v' (will not retry!)", event, err)
		} else {
			glog.Errorf("Server rejected event '%#v': '%v' (will not retry!)", event, err)
		}
		return true
	case *errors.UnexpectedObjectError:
		// We don't expect this; it implies the server's response didn't match a
		// known pattern. Go ahead and retry.
	default:
		// This case includes actual http transport errors. Go ahead and retry.
	}
	glog.Errorf("Unable to write event: '%v' (may retry after sleeping)", err)
	return false
}

// StartLogging starts sending events received from this EventBroadcaster to the given logging function.
// The return value can be ignored or used to stop recording, if desired.
func (eventBroadcaster *eventBroadcasterImpl) StartLogging(logf func(format string, args ...interface{})) watch.Interface {
	return eventBroadcaster.StartEventWatcher(
		func(e *v1.Event) {
			logf("Event(%#v): type: '%v' reason: '%v' %v", e.InvolvedObject, e.Type, e.Reason, e.Message)
		})
}

// StartEventWatcher starts sending events received from this EventBroadcaster to the given event handler function.
// The return value can be ignored or used to stop recording, if desired.
func (eventBroadcaster *eventBroadcasterImpl) StartEventWatcher(eventHandler func(*v1.Event)) watch.Interface {
	watcher := eventBroadcaster.Watch()
	go func() {
		defer utilruntime.HandleCrash()
		for {
			watchEvent, open := <-watcher.ResultChan()
			if !open {
				return
			}
			event, ok := watchEvent.Object.(*v1.Event)
			if !ok {
				// This is all local, so there's no reason this should
				// ever happen.
				continue
			}
			eventHandler(event)
		}
	}()
	return watcher
}

// NewRecorder returns an EventRecorder that records events with the given event source.
func (eventBroadcaster *eventBroadcasterImpl) NewRecorder(source v1.EventSource) EventRecorder {
	return &recorderImpl{source, eventBroadcaster.Broadcaster, clock.RealClock{}}
}

type recorderImpl struct {
	source v1.EventSource
	*watch.Broadcaster
	clock clock.Clock
}

func (recorder *recorderImpl) generateEvent(object runtime.Object, timestamp metav1.Time, eventtype, reason, message string) {
	ref, err := v1.GetReference(object)
	if err != nil {
		glog.Errorf("Could not construct reference to: '%#v' due to: '%v'. Will not report event: '%v' '%v' '%v'", object, err, eventtype, reason, message)
		return
	}

	if !validateEventType(eventtype) {
		glog.Errorf("Unsupported event type: '%v'", eventtype)
		return
	}

	event := recorder.makeEvent(ref, eventtype, reason, message)
	event.Source = recorder.source

	go func() {
		// NOTE: events should be a non-blocking operation
		defer utilruntime.HandleCrash()
		recorder.Action(watch.Added, event)
	}()
}

func validateEventType(eventtype string) bool {
	switch eventtype {
	case v1.EventTypeNormal, v1.EventTypeWarning:
		return true
	}
	return false
}

func (recorder *recorderImpl) Event(object runtime.Object, eventtype, reason, message string) {
	recorder.generateEvent(object, metav1.Now(), eventtype, reason, message)
}

func (recorder *recorderImpl) Eventf(object runtime.Object, eventtype, reason, messageFmt string, args ...interface{}) {
	recorder.Event(object, eventtype, reason, fmt.Sprintf(messageFmt, args...))
}

func (recorder *recorderImpl) PastEventf(object runtime.Object, timestamp metav1.Time, eventtype, reason, messageFmt string, args ...interface{}) {
	recorder.generateEvent(object, timestamp, eventtype, reason, fmt.Sprintf(messageFmt, args...))
}

func (recorder *recorderImpl) makeEvent(ref *v1.ObjectReference, eventtype, reason, message string) *v1.Event {
	t := metav1.Time{Time: recorder.clock.Now()}
	namespace := ref.Namespace
	if namespace == "" {
		namespace = v1.NamespaceDefault
	}
	return &v1.Event{
		ObjectMeta: v1.ObjectMeta{
			Name:      fmt.Sprintf("%v.%x", ref.Name, t.UnixNano()),
			Namespace: namespace,
		},
		InvolvedObject: *ref,
		Reason:         reason,
		Message:        message,
		FirstTimestamp: t,
		LastTimestamp:  t,
		Count:          1,
		Type:           eventtype,
	}
}


text:
/*jshint strict:false*/
/*global CasperError, console, phantom, require*/

var casper = require("casper").create();
var utils = require("utils");
var url = "http://www.insidetime.co.uk/info-visitorsinfo.asp?nameofprison=";
var times = [];
var prisons = [];

var arrayFromObject = function (obj) {
  var list = [];
  for (var i in obj) {
    list.push(i);
  }
  return list;
};

var prison_details1 = {
"HMP BEDFORD": {"address":"St. Loyes Street,MK40 1HG","email":"SocialVisits.Bedford@hmps.gsi.gov.uk","phone":"01234 373196"},
"HMP PRESTON": {"address":"2 Ribbleton Lane,PR1 5AB ","email":"","phone":"01772 444666"},
"HMP MAIDSTONE": {"address":"36 County Road,ME14 1UZ ","email":"Socialvisits.maidstone@hmps.gsi.gov.uk","phone":"016220775619"},
"HMP-YOI WARREN HILL": {"address":"Hollesley,IP12 3JW ","email":"SocialVisits.WarrenHill@hmps.gsi.gov.uk","phone":"020 8588 4002"},
"HMYOI WETHERBY": {"address":"York Road,LS22 5ED ","email":"SocialVisits.Wetherby@hmps.gsi.gov.uk","phone":"01937 544207"},
"HMP ERLESTOKE": {"address":"DEVIZES,SN10 5TU","email":"eecmbookavisit@hmps.gsi.gov.uk","phone":"01380 814264"},
"HMP-YOI CHELMSFORD": {"address":"200 Springfield Road,CM2 6LQ ","email":"SocialVisits.Chelmsford@hmps.gsi.gov.uk","phone":"01245 552265"},
"HMP STOCKEN": {"address":"Stocken Hall Road,LE15 7RD", "email":"SocialVisits.Stocken@hmps.gsi.gov.uk", "phone":"01780 795156"},
"HMP DARTMOOR": {"address":"Princetown,PL20 6RR", "email":"", "phone":"01822 322022"},
"HMP-YOI LOW NEWTON": { "address": "Brasside,DH1 5YA", "email": "SocialVisits.LowNewton@hmps.gsi.gov.uk", "phone":"0191 376 4147"},
"HMYOI AYLESBURY": {"address":"Bierton Road,HP20 1EH","email":"visitsbookingaylesbury@hmps.gsi.gov.uk","phone":"01296 444099"},
"HMP ISLE OF WIGHT - ALBANY": {"address":"55 Parkhurst Road,PO30 5RS","email":"","phone":"01983 556573"},
"HMP BLANTYRE HOUSE": {"address":"Goudhurst,TN17 2NH","email":"SocialVisits.BlantyreHouse@hmps.gsi.gov.uk","phone":""},
"HMP BRIXTON": {"address":"Jebb Avenue,SW2 5XF","email":"socialvisitsbrixton@hmps.gsi.gov.uk","phone":"0208 678 1433"},
"HMP BULLINGDON": {"address":"Bicester,OX25 1PZ ","email":"socialvisits.bullingdon@hmps.gsi.gov.uk","phone":"01869 353176"},
"HMP DOWNVIEW": {"address":"Sutton Lane,SM2 5PD","email":"socialvisits.downview@hmps.gsi.gov.uk","phone":"0208 196 6359"},
"HMP-YOI EAST SUTTON PARK": {"address":"Sutton Valence,ME17 3DF ","email":"Socialvisits.Eastsuttonpark@hmps.gsi.gov.uk","phone":""},
"HMP SHEPPEY CLUSTER - ELMLEY": {"address":"Church Road,ME12 4DZ ","email":"SocialVisits.Elmley@hmps.gsi.gov.uk","phone":"0300 060 6605"},
"HMP EVERTHORPE": {"address":"1a Beck Road,HU15 1RB","email":"SocialVisits.Everthorpe@hmps.gsi.gov.uk","phone":"01430 426505"},
"HMYOI FELTHAM": {"address":"Bedfont Road,TW13 4ND ","email":"socialvisits.feltham@hmps.gsi.gov.uk","phone":"0208 844 5400"},
"HMYOI GLEN PARVA": {"address":"Tigers Road,LE8 4TN ","email":"socialvisits.glenparva@hmps.gsi.gov.uk","phone":"0116 228 4366"},
"HMP GRENDON": {"address":"Grendon Underwood,HP18 0TL","email":"socialvisits.Grendon@hmps.gsi.gov.uk","phone":""},
"HMP GUYS MARSH": {"address":"SHAFTESBURY,SP7 0AH ","email":"SocialVisitsGuysMarsh@hmps.gsi.gov.uk","phone":"01747 856586"},
"HMP-YOI HATFIELD (MOORLAND OPEN)": {"address":"Thorne Road,DN7 6El","email":"SocialVisits.Hatfield@hmps.gsi.gov.uk","phone":"01405 746611"},
"HMP HAVERIGG": {"address":"MILLOM,LA18 4NA ","email":"socialvisits.haverigg@hmps.gsi.gov.uk","phone":"01229713016"},
"HMP HIGH DOWN": {"address":"Sutton Lane,SM2 5PJ ","email":"socialvisits.highdown@hmps.gsi.gov.uk","phone":"0300 060 6503"},
"HMP HIGHPOINT NORTH": {"address":"Stradishall,CB8 9YG ","email":"SocialVisits.Highpoint @hmps.gsi.gov.uk","phone":"0207 147 6570"},
"HMP HIGHPOINT SOUTH": {"address":"Stradishall,CB8 9YG ","email":"SocialVisits.Highpoint @hmps.gsi.gov.uk","phone":"0207 147 6570"},
"HMP-YOI NORWICH": {"address":"Knox Road,NR1 4LU ","email":"socialvisits.norwich@hmps.gsi.gov.uk","phone":"01603 708795"},
"HMP SHEPPEY CLUSTER - STANDFORD HILL": {"address":"Church Road,ME12 4AA ","email":"SocialVisits.StandfordHill@hmps.gsi.gov.uk","phone":"0300 060 6603"},
"HMP LIVERPOOL": {"address":"68 Hornby Road,L9 3DF","email":"socialvisits.liverpool@hmps.gsi.gov.uk","phone":"0151 530 4050"},
"HMP STYAL": {"address":"WILMSLOW,SK9 4HR ","email":"socialvisits.styal@hmps.gsi.gov.uk","phone":"01625553195"},
"HMP-YOI HOLLOWAY": {"address":"Parkhurst Road,N7 0NU ","email":"socialvisits.holloway@hmps.gsi.gov.uk","phone":""},
"HMP HOLME HOUSE": {"address":"Holme House Road,S18 2QU","email":"SocialVisits@hmpholme house.gsi.gov.uk","phone":"03000 606602"},
"HMP HULL": {"address":"Hedon Road,HU9 5LS ","email":"SocialVisits.Hull@hmps.gsi.gov.uk","phone":"01482 282016"},
"HMP HUNTERCOMBE": {"address":"Huntercombe Place,RG9 5SB ","email":"socialvisits.huntercombe@hmps.gsi.gov.uk","phone":"01302 524980"},
"HMP ISLE OF WIGHT - PARKHURST": {"address":"Clissold Road ,PO30 5RS ","email":"visitshmpiow@hmps.gsi.gov.uk","phone":"01983 634218"},
"HMP LEEDS": {"address":"Gloucester Terrace,LS12 2TJ ","email":"SocialVisits.Leeds@hmps.gsi.gov.uk","phone":"0113 203 2995"},
"HMP SEND": {"address":"Ripley Road,GU23 7LJ ","email":"SocialVisits.Send@hmps.gsi.gov.uk","phone":"01483 471033"},
"HMP SHEPPEY CLUSTER - SWALESIDE": {"address":"Brabazon Road,ME12 4AX","email":"SocialVisits.Swaleside@hmps.gsi.gov.uk","phone":"0300 060 6604"},
"HMYOI HINDLEY": {"address":"Gibson Street,WN2 5TH ","email":"socialvisits.hindley@hmps.gsi.gov.uk","phone":"01440 743134"},
"HMP HOLLESLEY BAY": {"address":"WOODBRIDGE,IP12 3JW ","email":"SocialVisits.HollesleyBay@hmps.gsi.gov.uk","phone":""},
"HMP KENNET": {"address":"Parkbourn,L31 1HX ","email":"socialvisits.kennet@hmps.gsi.gov.uk","phone":"0151 213 3179"},
"HMP KIRKHAM": {"address":"Freckleton Road, Kirkham,PR4 2RN","email":"socialvisits.kirkham@hmps.gsi.gov.uk","phone":""},
"HMYOI LANCASTER FARMS": {"address":"Stone Row Head,LA1 3QZ","email":"socialvisits.lancasterfarms@hmps.gsi.gov.uk","phone":"01524 563636"},
"HMP LINCOLN": {"address":"Greetwell Road,LN2 4BD ","email":"socialvisits.Lincoln@hmps.gsi.gov.uk","phone":"01522 663172"},
"HMP LINDHOLME": {"address":"Bawtry Road,DN7 6EE ","email":"SocialVisits.Lindholme@hmps.gsi.gov.uk","phone":"01302 524980"},
"HMP-YOI LITTLEHEY": {"address":"Perry,PE28 0SR","email":"socialvisits.littlehey@hmps.gsi.gov.uk","phone":"01480 335650"},
"HMP-YOI NEW HALL": {"address":"Dial Wood,WF4 4XX","email":"SocialVisits.NewHall@hmps.gsi.gov.uk","phone":"01924 803219"},
"HMP NORTH SEA CAMP": {"address":"Freiston,PE22 0QX","email":"SocialVisits.NorthSeaCamp@hmps.gsi.gov.uk","phone":"01205 769 368"},
"HMP NOTTINGHAM": {"address":"Perry Road,NG5 3AG ","email":"SocialVisits.Nottingham@hmps.gsi.gov.uk","phone":"0115 962 8980"},
"HMYOI PORTLAND": {"address":"104 The Grove,DT5 1DL","email":"SocialVisits.Portland@hmps.gsi.gov.uk","phone":"01305 715775"},
"HMP RANBY": {"address":"RETFORD,DN22 8EU","email":"visitsbookingranby@hmps.gsi.gov.uk","phone":"01777 862107"},
"HMP SWANSEA": {"address":"200 Oystermouth Road,SA1 3SR","email":"socvisswansea@hmps.gsi.gov.uk","phone":"01792 48 5322"},
"HMP WANDSWORTH": {"address":"PO Box 757,SW18 3HS","email":"socialvisits.wandsworth@hmps.gsi.gov.uk","phone":"01924 612274"},
"HMP WINCHESTER": {"address":"Romsey Road,SO22 5DF","email":"Socialvisits.winchester@hmps.gsi.gov.uk","phone":"0845 223 5514"},
"HMP WORMWOOD SCRUBS": {"address":"Du Cane Road,W12 0AE","email":"socialvisits.WormwoodScrubs@hmps.gsi.gov.uk","phone":"020 8588 3564"},
"HMP WYMOTT": {"address":"Ulnes Walton Lane,PR26 8LW","email":"socialvisits.wymott@hmps.gsi.gov.uk","phone":"01772 442234"},
"HMP USK": {"address":"47 Maryport Street,NP15 1XP","email":"Social Visits, Usk","phone":"01291 671730"},
"HMP SPRING HILL": {"address":"Grendon Underwood,HP18 0TL ","email":"","phone":""},
"HMP SUDBURY": {"address":"Ashbourne,DE6 5HW ","email":"","phone":""},
"HMP LEICESTER": {"address":"116 Welford Road,LE2 7AJ","email":"No Active Social Visits FMB","phone":"0116 228 3128"},
"HMP WOLDS": {"address":"Everthorpe,HU15 2JZ ","email":"?","phone":"01430 428584"},
"HMP PRESCOED": {"address":"Coed-y-Paen,NP4 0TB","email":"Not required","phone":""}
};

var prison_details = {
"HMP WHATTON": {"address":"New Lane,NG13 9FQ ","email":"SocialVisits.Whatton@hmps.gsi.gov.uk","phone":"01949 803564"}
};

var prisons = arrayFromObject(prison_details);

// For testing with specific prisons
// prisons = ["HMP BEDFORD", "HMP BLANTYRE HOUSE"];

casper.start("http://www.google.com", function () {

  prisons.forEach(function (prison) {

    casper.thenOpen(url + prison.replace(/ /g, '_'), function () {

      var time_slots = this.evaluate(function () {

        var nodes, slots = {};

        // filter-out text nodes
        var onlyElements = function (nodes) {
          var elements = [];
          [].forEach.call(nodes, function (node) {
            if (node.nodeType == 1) {
              return elements.push(node);
            }
          });
          return elements;
        };

        var normaliseTimes = function (s) {
          s = s.replace(/and/g,'&');
          s = s.replace(/to/g,'-');
          s = s.replace(/\u2013|\u2014/g, "-");
          return s;
        };

        var ignoreWords = function (s) {
          s = s.replace(/\(mains\)/gi,'');
          s = s.replace(/\(vps\)/gi,'');
          s = s.replace(/\(yoi\)/gi,'');
          s = s.replace(/\(enhancedonly\)/gi,'');
          return s;
        };

        var formatString = function (s) {
          s = s.replace(/[ :;\.]/g,'');
          return s;
        };

        var timeArrayFromString = function (t) {
          var startTimes = t.split(','),
              times = [];

          for (var i = 0; i < startTimes.length; i++) {
            times.push([startTimes[i], addHours(startTimes[i], 1)].join('-'));
          }

          return times;
        };

        var addHours = function(start, hours) {
          var time = new Date();

          // set initial time
          time.setHours(start.substr(0, 2));
          time.setMinutes(start.substr(2));

          time.setHours(time.getHours()+hours);

          return [pad(time.getHours()),pad(time.getMinutes())].join('');
        };

        var pad = function (num) {
          return ("00"+num).slice(-2);
        };

        var commaSeparatedTimes = function (times) {
          return times.join('').indexOf('-') > -1;
        };

        var commaSeparatedStartTimes = function (times) {
          return times.join('').indexOf(',') > -1;
        };

        var fixKnownIssues = function (times, prison) {
          switch (prison) {
            case 'HMP_HOLME_HOUSE':
              times = times.join(',').replace('190000','1900').split(',');
              break;
            case 'HMP_LEEDS':
              times = times.join(',').replace('10130','1030').split(',');
              break;
          }

          return times;
        };

        var prisonName = function () {
          return document.location.href.split('=')[1].replace(/(HMP|HMYOI|HMP-YOI)_/, '');
        };

        var extractTimes = function (s) {
          var times;

          s = formatString(s);

          s = ignoreWords(s);

          s = normaliseTimes(s);

          times = s.split("&");

          if (commaSeparatedTimes(times)) {
            times = times.join(',').split(',');
          }

          if (commaSeparatedStartTimes(times)) {
            times = timeArrayFromString(times.join(','));
          }

          times = fixKnownIssues(times, prisonName());

          return times;
        };

        // get tbody
        nodes = onlyElements( document.querySelector('a[name=vtimes]').nextSibling.nextSibling.childNodes );

        // get table rows
        nodes = onlyElements( nodes[0].childNodes );

        // strip-off heading row
        nodes = [].slice.call(nodes, 1);

        [].forEach.call(nodes, function (row) {
          if (row.childNodes.length > 3) {
            slots[row.childNodes[1].textContent.substr(0,3).toLowerCase()] = extractTimes( row.childNodes[3].textContent );
          }
        });

        return slots;

      });
      // end evaluate

      times.push([prison, time_slots]);
    });
  });
});

casper.run(function() {

  var prison_data = {};

  var formatForPVB = function (s) {
    var words;
    s = s.replace(/(HMP|HMYOI|HMP-YOI) /, '');
    words = s.split(' ');
    return words.map(function (word) {
      return word[0] + word.substr(1).toLowerCase();
    }).join(' ');
  };

  // Create object of full prison details
  times.forEach(function (times) {
    var name = formatForPVB(times[0]),
        details = prison_details[times[0].replace(/_/g,'')];

    prison_data[name] = {}; // start with a blank object
    prison_data[name].enabled = false; // disable by default
    prison_data[name].phone = details.phone;
    prison_data[name].email = details.email.toLowerCase(); // for production
    // prison_data[name].email = 'pvb.'+ name.replace(/ /g, '').toLowerCase() +'@maildrop.dsd.io'; // for staging
    prison_data[name].address = details.address.split(','); // make address an array
    prison_data[name].unbookable = ('2014-12-25').split(','); // add standard unbookable dates
    prison_data[name].slots = times[1];
  });

  utils.dump(prison_data);
  var fs = require('fs');
  fs.write('prison_data.json', JSON.stringify(prison_data), 'w');
  this.exit();
});

redpajama_set_name: RedPajamaGithub


text:
var inherits = require('util').inherits;

var Service, Characteristic;

/**
 *
 * Supporting different types:
 *  * Switch
 *  * Dimmer
 *  * Dimmer-%
 *  * RGB
 *  * StairwayLS
 *
 * @param config
 * @param platform
 * @param hap
 * @constructor
 */
function LoxoneLightbulb(config, platform, hap) {
    this.log = platform.log;
    this.platform = platform;
    this.loxone = platform.loxone;

    Service = hap.Service;
    Characteristic = hap.Characteristic;

    this.name = config.name;
    this.input = config.input;
    this.output = config.output;
    this.type = config.type || 'Switch';

    this._service = new Service.Lightbulb(this.name);
    this._service.getCharacteristic(Characteristic.On)
        .on('get', this._getValue.bind(this));

    this._service.getCharacteristic(Characteristic.On)
        .on('set', this._setValue.bind(this));

    if (this.type == 'Dimmer' || this.type == 'Dimmer-%') {
        this._service.getCharacteristic(Characteristic.Brightness)
            .on('get', this._getBrightnessValue.bind(this));

        this._service.getCharacteristic(Characteristic.Brightness)
            .on('set', this._setBrightnessValue.bind(this));

    }
}

LoxoneLightbulb.prototype._getValue = function(callback) {
    var accessory = this;
    this.loxone.getValue(this.output, function(value) {
        if (value == undefined) {
            accessory.log.error(accessory.name + " is undefined when getting value");
            callback(new Error("Could not get value for " + this.output));
            return;
        }

        var on = value != '0';
        if (accessory.type == 'Dimmer') {
            on = value != '0.0';
        } else if (accessory.type == 'Dimmer-%' || accessory.type == 'RGB') {
            on = value != '0%';
        }

        accessory.log(accessory.name + " is " + value, on);
        callback(null, on);
    });
};

LoxoneLightbulb.prototype._setValue = function(on, callback) {
    var loxone = this.loxone;
    var input = this.input;
    var accessory = this;

    var command = on ? "On": "Off";
    if (accessory.type == 'StairwayLS' && on) {
        command = "pulse";
    }

    loxone.set(input, command, function(value) {
        if (value == undefined) {
            accessory.log.error(accessory.name + " is undefined when setting value");
            callback(new Error("Could not set value for " + input + " to " + command));
            return;
        }
        accessory.log("Set value of " + accessory.name + " to " + command);
        callback();
    });
};

LoxoneLightbulb.prototype._getBrightnessValue = function(callback) {
    var accessory = this;
    this.loxone.getValue(this.output, function(value) {
        if (value == undefined) {
            accessory.log.error("Brightness " + accessory.name + " is undefined when getting value");
            callback(new Error("Could not get value for " + this.output));
            return;
        }

        var brightness = value;
        if (accessory.type == 'Dimmer') {
            brightness = value * 10;
        }

        accessory.log("Brightness " + accessory.name + " is " + brightness);
        callback(null, brightness * 1);
    });
};

LoxoneLightbulb.prototype._setBrightnessValue = function(value, callback) {
    var loxone = this.loxone;
    var input = this.input;
    var accessory = this;

    loxone.set(input, value, function(setValue) {
        if (setValue == undefined) {
            accessory.log.error("Brightness " + accessory.name + " is undefined when setting value");
            callback(new Error("Could not set value for " + input + " to " + value));
            return;
        }
        accessory.log("Set brightness of " + accessory.name + " to ", value);
        callback();
    });
};

LoxoneLightbulb.prototype.getServices = function() {
    return [this._service, this.platform.getInformationService(this)];
};

module.exports = LoxoneLightbulb;


text:
package com.xantoria.flippy.condition

object NumberConditions {
  abstract class NCondition extends Condition {
    def appliesTo(d: Double): Boolean
    def appliesTo(i: Int): Boolean

    override def appliesTo(a: Any): Boolean = a match {
      case i: Int => appliesTo(i)
      case d: Double => appliesTo(d)
      case _ => false
    }
  }

  /**
   * Is the value within the numerical range provided?
   */
  class Range(val low: Option[Double], val high: Option[Double]) extends NCondition {
    override def appliesTo(d: Double): Boolean = {
      (low map { d > _ } getOrElse true) && (high map { d < _ } getOrElse true)
    }
    override def appliesTo(i: Int): Boolean = appliesTo(i.toDouble)
  }

  /**
   * Is the value an integer which is a multiple of n?
   */
  class Multiple(val n: Int) extends NCondition {
    def appliesTo(d: Double): Boolean = false
    def appliesTo(i: Int): Boolean = n != 0 && i % n == 0
  }
}


text:
/* -------------------------------------- Includes ----------------------------------- */

#include "psa_defs.h"
#include "cmsis_os2.h"
#include "mbed_atomic.h"
#include "spm_internal.h"
#include "spm_panic.h"
#include "handles_manager.h"

#include <string.h>
#include <stdbool.h>
#include <stdlib.h>

/* ------------------------------------ Definitions ---------------------------------- */

#define PSA_HANDLE_MGR_HANDLE_INDEX_POS         16
#define PSA_HANDLE_MGR_HANDLE_INDEX_MSK         0xFFFF

/* ------------------------------------- Functions ----------------------------------- */

psa_handle_t psa_hndl_mgr_handle_create(psa_handle_manager_t *handle_mgr, void *handle_mem, int32_t friend_pid)
{
    // Make sanity checks on arguments
    SPM_ASSERT(handle_mgr != NULL);
    SPM_ASSERT(handle_mem != NULL);

    // Get active partition id - Needed for requester identification
    spm_partition_t *curr_part_ptr = get_active_partition();
    int32_t          current_pid   = ((curr_part_ptr != NULL) ? curr_part_ptr->partition_id : PSA_NSPE_IDENTIFIER);

    // Generate a new handle identifier
    uint32_t tmp_handle;
    do {
        tmp_handle = core_util_atomic_incr_u16(&(handle_mgr->handle_generator), 1);
    } while (tmp_handle == PSA_HANDLE_MGR_INVALID_HANDLE);
    psa_handle_t new_handle = PSA_NULL_HANDLE;

    // Look for a vacant space in handles pool for the generated handle
    for (uint32_t pool_ix = 0; pool_ix < handle_mgr->pool_size; pool_ix++) {

        psa_handle_t expected = PSA_NULL_HANDLE;

        // Write the handles pool index in the upper 16 bits of the handle
        psa_handle_t desired_handle = ((pool_ix << PSA_HANDLE_MGR_HANDLE_INDEX_POS) | tmp_handle);

        // Store the generated handle in the handles pool
        if (core_util_atomic_cas_s32(&(handle_mgr->handles_pool[pool_ix].handle),
                                     &expected,
                                     desired_handle
                                    )) {

            // Handle is successfully stored in handles pool
            new_handle = desired_handle;

            // Store the handle memory in the handles pool, "coupled" with the stored handle
            handle_mgr->handles_pool[pool_ix].handle_mem    = handle_mem;
            handle_mgr->handles_pool[pool_ix].handle_owner  = current_pid;
            handle_mgr->handles_pool[pool_ix].handle_friend = friend_pid;

            break;
        }

        // Occupied index in handles pool - continue looping
    }

    // Handle creation should only occur after a successful memory allocation
    // and is not expected to fail.
    SPM_ASSERT(new_handle != PSA_NULL_HANDLE);

    return new_handle;
}

void psa_hndl_mgr_handle_destroy(psa_handle_manager_t *handle_mgr, psa_handle_t handle)
{
    // Make sanity checks on arguments
    SPM_ASSERT(handle_mgr != NULL);
    SPM_ASSERT(handle != PSA_NULL_HANDLE);

    // Get the handle's index in the handles pool
    uint32_t pool_ix = ((handle >> PSA_HANDLE_MGR_HANDLE_INDEX_POS) & PSA_HANDLE_MGR_HANDLE_INDEX_MSK);
    if (pool_ix >= handle_mgr->pool_size) {
        SPM_PANIC("[ERROR] Handle's index [%lu] is bigger than handles pool size [%hu]! \n", pool_ix, handle_mgr->pool_size);
    }

    if (handle_mgr->handles_pool[pool_ix].handle != handle) {
        SPM_PANIC("[ERROR] Handle %ld is not found in expected index! \n", handle);
    }

    // Get active partition id - Needed for requester identification
    spm_partition_t *curr_part_ptr = get_active_partition();
    int32_t          current_pid   = ((curr_part_ptr != NULL) ? curr_part_ptr->partition_id : PSA_NSPE_IDENTIFIER);

    if ((handle_mgr->handles_pool[pool_ix].handle_owner != current_pid) &&
            (handle_mgr->handles_pool[pool_ix].handle_friend != current_pid)
       ) {
        SPM_PANIC("[ERROR] Request for destroy by non-owner or friend!\n");
    }

    handle_mgr->handles_pool[pool_ix].handle_owner  = PSA_HANDLE_MGR_INVALID_FRIEND_OWNER;
    handle_mgr->handles_pool[pool_ix].handle_friend = PSA_HANDLE_MGR_INVALID_FRIEND_OWNER;
    core_util_atomic_store_s32(&(handle_mgr->handles_pool[pool_ix].handle), PSA_NULL_HANDLE);
}

void *psa_hndl_mgr_handle_get_mem(psa_handle_manager_t *handle_mgr, psa_handle_t handle)
{
    SPM_ASSERT(handle_mgr != NULL);

    if (handle == PSA_NULL_HANDLE) {
        SPM_PANIC("[ERROR] Trying to get memory for an invalid handle! \n");
    }

    // Get the handle's index in the handles pool
    uint32_t pool_ix = ((handle >> PSA_HANDLE_MGR_HANDLE_INDEX_POS) & PSA_HANDLE_MGR_HANDLE_INDEX_MSK);
    if (pool_ix >= handle_mgr->pool_size) {
        SPM_PANIC("[ERROR] Handle's index [%lu] is bigger than handles pool size [%hu]! \n", pool_ix, handle_mgr->pool_size);
    }

    if (handle_mgr->handles_pool[pool_ix].handle != handle) {
        SPM_PANIC("[ERROR] Handle %ld is not found in expected index! \n", handle);
    }

    // Get active partition id - Needed for requester identification
    spm_partition_t *curr_part_ptr = get_active_partition();
    int32_t          current_pid   = ((curr_part_ptr != NULL) ? curr_part_ptr->partition_id : PSA_NSPE_IDENTIFIER);

    if ((current_pid != handle_mgr->handles_pool[pool_ix].handle_owner) &&
            (current_pid != handle_mgr->handles_pool[pool_ix].handle_friend)
       ) {
        SPM_PANIC("[ERROR] Request for handle memory is not allowed for this partition! \n");
    }

    // If a valid handle is "coupled" with a NULL handle memory then
    // it is an internal module error or memory was overwritten --> Assert
    SPM_ASSERT(handle_mgr->handles_pool[pool_ix].handle_mem != NULL);

    return handle_mgr->handles_pool[pool_ix].handle_mem;
}


text:
if (window.testRunner)
    testRunner.overridePreference("WebKitWebAudioEnabled", "1");

function writeString(s, a, offset) {
    for (var i = 0; i < s.length; ++i) {
        a[offset + i] = s.charCodeAt(i);
    }
}

function writeInt16(n, a, offset) {
    n = Math.floor(n);

    var b1 = n & 255;
    var b2 = (n >> 8) & 255;

    a[offset + 0] = b1;
    a[offset + 1] = b2;
}

function writeInt32(n, a, offset) {
    n = Math.floor(n);
    var b1 = n & 255;
    var b2 = (n >> 8) & 255;
    var b3 = (n >> 16) & 255;
    var b4 = (n >> 24) & 255;

    a[offset + 0] = b1;
    a[offset + 1] = b2;
    a[offset + 2] = b3;
    a[offset + 3] = b4;
}

function writeAudioBuffer(audioBuffer, a, offset) {
    var n = audioBuffer.length;
    var channels = audioBuffer.numberOfChannels;

    for (var i = 0; i < n; ++i) {
        for (var k = 0; k < channels; ++k) {
            var buffer = audioBuffer.getChannelData(k);
            var sample = buffer[i] * 32768.0;

            // Clip samples to the limitations of 16-bit.
            // If we don't do this then we'll get nasty wrap-around distortion.
            if (sample < -32768)
                sample = -32768;
            if (sample > 32767)
                sample = 32767;

            writeInt16(sample, a, offset);
            offset += 2;
        }
    }
}

function createWaveFileData(audioBuffer) {
    var frameLength = audioBuffer.length;
    var numberOfChannels = audioBuffer.numberOfChannels;
    var sampleRate = audioBuffer.sampleRate;
    var bitsPerSample = 16;
    var byteRate = sampleRate * numberOfChannels * bitsPerSample/8;
    var blockAlign = numberOfChannels * bitsPerSample/8;
    var wavDataByteLength = frameLength * numberOfChannels * 2; // 16-bit audio
    var headerByteLength = 44;
    var totalLength = headerByteLength + wavDataByteLength;

    var waveFileData = new Uint8Array(totalLength);

    var subChunk1Size = 16; // for linear PCM
    var subChunk2Size = wavDataByteLength;
    var chunkSize = 4 + (8 + subChunk1Size) + (8 + subChunk2Size);

    writeString("RIFF", waveFileData, 0);
    writeInt32(chunkSize, waveFileData, 4);
    writeString("WAVE", waveFileData, 8);
    writeString("fmt ", waveFileData, 12);

    writeInt32(subChunk1Size, waveFileData, 16);      // SubChunk1Size (4)
    writeInt16(1, waveFileData, 20);                  // AudioFormat (2)
    writeInt16(numberOfChannels, waveFileData, 22);   // NumChannels (2)
    writeInt32(sampleRate, waveFileData, 24);         // SampleRate (4)
    writeInt32(byteRate, waveFileData, 28);           // ByteRate (4)
    writeInt16(blockAlign, waveFileData, 32);         // BlockAlign (2)
    writeInt32(bitsPerSample, waveFileData, 34);      // BitsPerSample (4)

    writeString("data", waveFileData, 36);
    writeInt32(subChunk2Size, waveFileData, 40);      // SubChunk2Size (4)

    // Write actual audio data starting at offset 44.
    writeAudioBuffer(audioBuffer, waveFileData, 44);

    return waveFileData;
}

function createAudioData(audioBuffer) {
    return createWaveFileData(audioBuffer);
}

function finishAudioTest(event) {
    var audioData = createAudioData(event.renderedBuffer);
    testRunner.setAudioData(audioData);
    testRunner.notifyDone();
}

// Create an impulse in a buffer of length sampleFrameLength
function createImpulseBuffer(context, sampleFrameLength) {
    var audioBuffer = context.createBuffer(1, sampleFrameLength, context.sampleRate);
    var n = audioBuffer.length;
    var dataL = audioBuffer.getChannelData(0);

    for (var k = 0; k < n; ++k) {
        dataL[k] = 0;
    }
    dataL[0] = 1;

    return audioBuffer;
}

// Create a buffer of the given length with a linear ramp having values 0 <= x < 1.
function createLinearRampBuffer(context, sampleFrameLength) {
    var audioBuffer = context.createBuffer(1, sampleFrameLength, context.sampleRate);
    var n = audioBuffer.length;
    var dataL = audioBuffer.getChannelData(0);

    for (var i = 0; i < n; ++i)
        dataL[i] = i / n;

    return audioBuffer;
}

// Create a buffer of the given length having a constant value.
function createConstantBuffer(context, sampleFrameLength, constantValue) {
    var audioBuffer = context.createBuffer(1, sampleFrameLength, context.sampleRate);
    var n = audioBuffer.length;
    var dataL = audioBuffer.getChannelData(0);

    for (var i = 0; i < n; ++i)
        dataL[i] = constantValue;

    return audioBuffer;
}

// Create a stereo impulse in a buffer of length sampleFrameLength
function createStereoImpulseBuffer(context, sampleFrameLength) {
    var audioBuffer = context.createBuffer(2, sampleFrameLength, context.sampleRate);
    var n = audioBuffer.length;
    var dataL = audioBuffer.getChannelData(0);
    var dataR = audioBuffer.getChannelData(1);

    for (var k = 0; k < n; ++k) {
        dataL[k] = 0;
        dataR[k] = 0;
    }
    dataL[0] = 1;
    dataR[0] = 1;

    return audioBuffer;
}

// Convert time (in seconds) to sample frames.
function timeToSampleFrame(time, sampleRate) {
    return Math.floor(0.5 + time * sampleRate);
}

// Compute the number of sample frames consumed by noteGrainOn with
// the specified |grainOffset|, |duration|, and |sampleRate|.
function grainLengthInSampleFrames(grainOffset, duration, sampleRate) {
    var startFrame = timeToSampleFrame(grainOffset, sampleRate);
    var endFrame = timeToSampleFrame(grainOffset + duration, sampleRate);

    return endFrame - startFrame;
}

// True if the number is not an infinity or NaN
function isValidNumber(x) {
    return !isNaN(x) && (x != Infinity) && (x != -Infinity);
}

function shouldThrowTypeError(func, text) {
    var ok = false;
    try {
        func();
    } catch (e) {
        if (e instanceof TypeError) {
            ok = true;
        }
    }
    if (ok) {
        testPassed(text + " threw TypeError.");
    } else {
        testFailed(text + " should throw TypeError.");
    }
}


text:
(function () {
  'use strict';

  angular.module('app.layout', ['app.core', 'ui.bootstrap.collapse']);
})();


text:
package com.amazonaws.services.elasticache.model;

import java.io.Serializable;

import com.amazonaws.AmazonWebServiceRequest;

/**
 * Container for the parameters to the {@link com.amazonaws.services.elasticache.AmazonElastiCache#deleteSnapshot(DeleteSnapshotRequest) DeleteSnapshot operation}.
 *

 * The DeleteSnapshot action deletes an existing snapshot. When
 * you receive a successful response from this action, ElastiCache
 * immediately begins deleting the snapshot; you cannot cancel or revert
 * this action.
 *

 *
 * @see com.amazonaws.services.elasticache.AmazonElastiCache#deleteSnapshot(DeleteSnapshotRequest)
 */
public class DeleteSnapshotRequest extends AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     * The name of the snapshot to be deleted.
     */
    private String snapshotName;

    /**
     * The name of the snapshot to be deleted.
     *
     * @return The name of the snapshot to be deleted.
     */
    public String getSnapshotName() {
        return snapshotName;
    }

    /**
     * The name of the snapshot to be deleted.
     *
     * @param snapshotName The name of the snapshot to be deleted.
     */
    public void setSnapshotName(String snapshotName) {
        this.snapshotName = snapshotName;
    }

    /**
     * The name of the snapshot to be deleted.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param snapshotName The name of the snapshot to be deleted.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public DeleteSnapshotRequest withSnapshotName(String snapshotName) {
        this.snapshotName = snapshotName;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getSnapshotName() != null) sb.append("SnapshotName: " + getSnapshotName() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getSnapshotName() == null) ? 0 : getSnapshotName().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof DeleteSnapshotRequest == false) return false;
        DeleteSnapshotRequest other = (DeleteSnapshotRequest)obj;

        if (other.getSnapshotName() == null ^ this.getSnapshotName() == null) return false;
        if (other.getSnapshotName() != null && other.getSnapshotName().equals(this.getSnapshotName()) == false) return false;
        return true;
    }

    @Override
    public DeleteSnapshotRequest clone() {

            return (DeleteSnapshotRequest) super.clone();
    }

}


text:
'''
Extends main URL dispatcher in GeoConverter.urls
'''

from django.conf.urls import patterns, url
from OGRgeoConverter.jobs import jobidentification

urlpatterns = patterns('',
                       url(r'^$',
                           'OGRgeoConverter.views.show_main_page'),
                       url(r'^forms/files/(\w+)/start',
                           'OGRgeoConverter.views.start_conversion_job'),
                       url(r'^forms/files/(\w+)/upload',
                           'OGRgeoConverter.views.process_upload'),
                       url(r'^forms/files/(\w+)/remove/(\d+)',
                           'OGRgeoConverter.views.remove_file'),
                       url(r'^forms/files/(\w+)/finish',
                           'OGRgeoConverter.views.finish_conversion_job'),
                       url(r'^forms/webservices/(\w+)/convert',
                           'OGRgeoConverter.views.convert_webservice'),
                       url(r'^download/' + jobidentification.get_job_id_regex(),
                           'OGRgeoConverter.views.download_output_file'),
                       url(r'^remove/queue-' + jobidentification.get_job_id_regex(),
                           'OGRgeoConverter.views.remove_download_item'),
                       url(r'^remove/(\w+)',
                           'OGRgeoConverter.views.remove_download_item'))


text:
package main.domain.account;

import main.domain.Email;
import main.domain.Entity;

public class User extends Entity {
	public static final User EMPTY = new User();
	private CPF cpf;
    private Email email;
    private EncryptedPassword password;
    private Username username;

    public User() {
        this("", CPF.EMPTY, Email.EMPTY, EncryptedPassword.EMPTY, Username.EMPTY);
    }

    private User(String id,CPF cpf, Email email, EncryptedPassword password, Username username) {
        super(id);
        this.cpf = cpf;
        this.email = email;
        this.password = password;
        this.username = username;
    }

    public User copy() {
        return new User(id, cpf, email, password, username);
    }

    public CPF getCPF(){
    	return cpf;
    }

    public Email getEmail() {
        return email;
    }

    public EncryptedPassword getPassword() {
        return password;
    }

    public Username getUsername() {
		return username;
	}

    public void setCPF(CPF cpf){
    	this.cpf = cpf;
    }

	public void setEmail(Email email) {
        this.email = email;
    }

    public void setPassword(EncryptedPassword password) {
        this.password = password;
    }

	public void setUsername(Username username) {
		this.username = username;
	}
}


text:
package com.amazonaws.services.redshift.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *

 * Describes the status of a parameter group.
 *

 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ClusterParameterStatus implements Serializable, Cloneable {

    /**
     *

     * The name of the parameter.
     *

     */
    private String parameterName;
    /**
     *

     * The status of the parameter that indicates whether the parameter is in sync with the database, waiting for a
     * cluster reboot, or encountered an error when being applied.
     *

     *

     * The following are possible statuses and descriptions.
     *

     *

     *

     *

     * in-sync: The parameter value is in sync with the database.
     *

     *

     *

     *

     * pending-reboot: The parameter value will be applied after the cluster reboots.
     *

     *

     *

     *

     * applying: The parameter value is being applied to the database.
     *

     *

     *

     *

     * invalid-parameter: Cannot apply the parameter value because it has an invalid value or syntax.
     *

     *

     *

     *

     * apply-deferred: The parameter contains static property changes. The changes are deferred until the
     * cluster reboots.
     *

     *

     *

     *

     * apply-error: Cannot connect to the cluster. The parameter change will be applied after the cluster
     * reboots.
     *

     *

     *

     *

     * unknown-error: Cannot apply the parameter change right now. The change will be applied after the
     * cluster reboots.
     *

     *

     *

     */
    private String parameterApplyStatus;
    /**
     *

     * The error that prevented the parameter from being applied to the database.
     *

     */
    private String parameterApplyErrorDescription;

    /**
     *

     * The name of the parameter.
     *

     *
     * @param parameterName
     *        The name of the parameter.
     */

    public void setParameterName(String parameterName) {
        this.parameterName = parameterName;
    }

    /**
     *

     * The name of the parameter.
     *

     *
     * @return The name of the parameter.
     */

    public String getParameterName() {
        return this.parameterName;
    }

    /**
     *

     * The name of the parameter.
     *

     *
     * @param parameterName
     *        The name of the parameter.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ClusterParameterStatus withParameterName(String parameterName) {
        setParameterName(parameterName);
        return this;
    }

    /**
     *

     * The status of the parameter that indicates whether the parameter is in sync with the database, waiting for a
     * cluster reboot, or encountered an error when being applied.
     *

     *

     * The following are possible statuses and descriptions.
     *

     *

     *

     *

     * in-sync: The parameter value is in sync with the database.
     *

     *

     *

     *

     * pending-reboot: The parameter value will be applied after the cluster reboots.
     *

     *

     *

     *

     * applying: The parameter value is being applied to the database.
     *

     *

     *

     *

     * invalid-parameter: Cannot apply the parameter value because it has an invalid value or syntax.
     *

     *

     *

     *

     * apply-deferred: The parameter contains static property changes. The changes are deferred until the
     * cluster reboots.
     *

     *

     *

     *

     * apply-error: Cannot connect to the cluster. The parameter change will be applied after the cluster
     * reboots.
     *

     *

     *

     *

     * unknown-error: Cannot apply the parameter change right now. The change will be applied after the
     * cluster reboots.
     *

     *

     *

     *
     * @param parameterApplyStatus
     *        The status of the parameter that indicates whether the parameter is in sync with the database, waiting for
     *        a cluster reboot, or encountered an error when being applied.

     *

     *        The following are possible statuses and descriptions.
     *

     *

     *

     *

     *        in-sync: The parameter value is in sync with the database.
     *

     *

     *

     *

     *        pending-reboot: The parameter value will be applied after the cluster reboots.
     *

     *

     *

     *

     *        applying: The parameter value is being applied to the database.
     *

     *

     *

     *

     *        invalid-parameter: Cannot apply the parameter value because it has an invalid value or
     *        syntax.
     *

     *

     *

     *

     *        apply-deferred: The parameter contains static property changes. The changes are deferred
     *        until the cluster reboots.
     *

     *

     *

     *

     *        apply-error: Cannot connect to the cluster. The parameter change will be applied after the
     *        cluster reboots.
     *

     *

     *

     *

     *        unknown-error: Cannot apply the parameter change right now. The change will be applied after
     *        the cluster reboots.
     *

     *

     */

    public void setParameterApplyStatus(String parameterApplyStatus) {
        this.parameterApplyStatus = parameterApplyStatus;
    }

    /**
     *

     * The status of the parameter that indicates whether the parameter is in sync with the database, waiting for a
     * cluster reboot, or encountered an error when being applied.
     *

     *

     * The following are possible statuses and descriptions.
     *

     *

     *

     *

     * in-sync: The parameter value is in sync with the database.
     *

     *

     *

     *

     * pending-reboot: The parameter value will be applied after the cluster reboots.
     *

     *

     *

     *

     * applying: The parameter value is being applied to the database.
     *

     *

     *

     *

     * invalid-parameter: Cannot apply the parameter value because it has an invalid value or syntax.
     *

     *

     *

     *

     * apply-deferred: The parameter contains static property changes. The changes are deferred until the
     * cluster reboots.
     *

     *

     *

     *

     * apply-error: Cannot connect to the cluster. The parameter change will be applied after the cluster
     * reboots.
     *

     *

     *

     *

     * unknown-error: Cannot apply the parameter change right now. The change will be applied after the
     * cluster reboots.
     *

     *

     *

     *
     * @return The status of the parameter that indicates whether the parameter is in sync with the database, waiting
     *         for a cluster reboot, or encountered an error when being applied.

     *

     *         The following are possible statuses and descriptions.
     *

     *

     *

     *

     *         in-sync: The parameter value is in sync with the database.
     *

     *

     *

     *

     *         pending-reboot: The parameter value will be applied after the cluster reboots.
     *

     *

     *

     *

     *         applying: The parameter value is being applied to the database.
     *

     *

     *

     *

     *         invalid-parameter: Cannot apply the parameter value because it has an invalid value or
     *         syntax.
     *

     *

     *

     *

     *         apply-deferred: The parameter contains static property changes. The changes are deferred
     *         until the cluster reboots.
     *

     *

     *

     *

     *         apply-error: Cannot connect to the cluster. The parameter change will be applied after the
     *         cluster reboots.
     *

     *

     *

     *

     *         unknown-error: Cannot apply the parameter change right now. The change will be applied after
     *         the cluster reboots.
     *

     *

     */

    public String getParameterApplyStatus() {
        return this.parameterApplyStatus;
    }

    /**
     *

     * The status of the parameter that indicates whether the parameter is in sync with the database, waiting for a
     * cluster reboot, or encountered an error when being applied.
     *

     *

     * The following are possible statuses and descriptions.
     *

     *

     *

     *

     * in-sync: The parameter value is in sync with the database.
     *

     *

     *

     *

     * pending-reboot: The parameter value will be applied after the cluster reboots.
     *

     *

     *

     *

     * applying: The parameter value is being applied to the database.
     *

     *

     *

     *

     * invalid-parameter: Cannot apply the parameter value because it has an invalid value or syntax.
     *

     *

     *

     *

     * apply-deferred: The parameter contains static property changes. The changes are deferred until the
     * cluster reboots.
     *

     *

     *

     *

     * apply-error: Cannot connect to the cluster. The parameter change will be applied after the cluster
     * reboots.
     *

     *

     *

     *

     * unknown-error: Cannot apply the parameter change right now. The change will be applied after the
     * cluster reboots.
     *

     *

     *

     *
     * @param parameterApplyStatus
     *        The status of the parameter that indicates whether the parameter is in sync with the database, waiting for
     *        a cluster reboot, or encountered an error when being applied.

     *

     *        The following are possible statuses and descriptions.
     *

     *

     *

     *

     *        in-sync: The parameter value is in sync with the database.
     *

     *

     *

     *

     *        pending-reboot: The parameter value will be applied after the cluster reboots.
     *

     *

     *

     *

     *        applying: The parameter value is being applied to the database.
     *

     *

     *

     *

     *        invalid-parameter: Cannot apply the parameter value because it has an invalid value or
     *        syntax.
     *

     *

     *

     *

     *        apply-deferred: The parameter contains static property changes. The changes are deferred
     *        until the cluster reboots.
     *

     *

     *

     *

     *        apply-error: Cannot connect to the cluster. The parameter change will be applied after the
     *        cluster reboots.
     *

     *

     *

     *

     *        unknown-error: Cannot apply the parameter change right now. The change will be applied after
     *        the cluster reboots.
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ClusterParameterStatus withParameterApplyStatus(String parameterApplyStatus) {
        setParameterApplyStatus(parameterApplyStatus);
        return this;
    }

    /**
     *

     * The error that prevented the parameter from being applied to the database.
     *

     *
     * @param parameterApplyErrorDescription
     *        The error that prevented the parameter from being applied to the database.
     */

    public void setParameterApplyErrorDescription(String parameterApplyErrorDescription) {
        this.parameterApplyErrorDescription = parameterApplyErrorDescription;
    }

    /**
     *

     * The error that prevented the parameter from being applied to the database.
     *

     *
     * @return The error that prevented the parameter from being applied to the database.
     */

    public String getParameterApplyErrorDescription() {
        return this.parameterApplyErrorDescription;
    }

    /**
     *

     * The error that prevented the parameter from being applied to the database.
     *

     *
     * @param parameterApplyErrorDescription
     *        The error that prevented the parameter from being applied to the database.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ClusterParameterStatus withParameterApplyErrorDescription(String parameterApplyErrorDescription) {
        setParameterApplyErrorDescription(parameterApplyErrorDescription);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getParameterName() != null)
            sb.append("ParameterName: ").append(getParameterName()).append(",");
        if (getParameterApplyStatus() != null)
            sb.append("ParameterApplyStatus: ").append(getParameterApplyStatus()).append(",");
        if (getParameterApplyErrorDescription() != null)
            sb.append("ParameterApplyErrorDescription: ").append(getParameterApplyErrorDescription());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ClusterParameterStatus == false)
            return false;
        ClusterParameterStatus other = (ClusterParameterStatus) obj;
        if (other.getParameterName() == null ^ this.getParameterName() == null)
            return false;
        if (other.getParameterName() != null && other.getParameterName().equals(this.getParameterName()) == false)
            return false;
        if (other.getParameterApplyStatus() == null ^ this.getParameterApplyStatus() == null)
            return false;
        if (other.getParameterApplyStatus() != null && other.getParameterApplyStatus().equals(this.getParameterApplyStatus()) == false)
            return false;
        if (other.getParameterApplyErrorDescription() == null ^ this.getParameterApplyErrorDescription() == null)
            return false;
        if (other.getParameterApplyErrorDescription() != null
                && other.getParameterApplyErrorDescription().equals(this.getParameterApplyErrorDescription()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getParameterName() == null) ? 0 : getParameterName().hashCode());
        hashCode = prime * hashCode + ((getParameterApplyStatus() == null) ? 0 : getParameterApplyStatus().hashCode());
        hashCode = prime * hashCode + ((getParameterApplyErrorDescription() == null) ? 0 : getParameterApplyErrorDescription().hashCode());
        return hashCode;
    }

    @Override
    public ClusterParameterStatus clone() {
        try {
            return (ClusterParameterStatus) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
package org.nd4j.codegen.cli;

import com.beust.jcommander.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.codegen.Namespace;
import org.nd4j.codegen.api.LossReduce;
import org.nd4j.linalg.api.buffer.DataType;
import picocli.CommandLine;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Planned CLI for generating classes
 */
@Slf4j
public class PicoCliCodeGen {
    private static final String relativePath = "nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/";
    private static final String allProjects = "all";

    @Parameter(names = "-dir", description = "Root directory of deeplearning4j mono repo")
    private String repoRootDir;

    @Parameter(names = "-docsdir", description = "Root directory for generated docs")
    private String docsdir;

    @Parameter(names = "-namespaces", description = "List of namespaces to generate, or 'ALL' to generate all namespaces", required = true)
    private List<String> namespaces;

    private void generateNamespaces() {

        List<Namespace> usedNamespaces = new ArrayList<>();

        for (String s : namespaces) {
            if ("all".equalsIgnoreCase(s)) {
                Collections.addAll(usedNamespaces, Namespace.values());
                break;
            }

            CommandLine.Model.CommandSpec commandSpec = CommandLine.Model.CommandSpec.create();

            int cnt = 0;
            for (int i = 0; i < usedNamespaces.size(); ++i) {
                Namespace ns = usedNamespaces.get(i);
                CommandLine.Model.CommandSpec subCommand = CommandLine.Model.CommandSpec.create();
                commandSpec.addSubcommand(ns.name(), subCommand);
                ns.getNamespace().getOps().forEach(op -> {
                    CommandLine.Model.CommandSpec commandSpec1 = CommandLine.Model.CommandSpec.create();
                    subCommand.addSubcommand(op.name(), commandSpec1);
                    op.inputs().forEach(input -> {
                        //TODO: Add SDVariable converter for picocli and figure out where to put that converter
                        commandSpec1.addOption(CommandLine.Model.OptionSpec.builder("--" + input.getName())
                                .type(SDVariable.class)
                                .required(true)
                                .description(input.getDescription())
                                .build());
                    });

                    op.getArgs().forEach(arg -> {
                        CommandLine.Model.OptionSpec.Builder builder = CommandLine.Model.OptionSpec.builder("--" + arg.getName())
                                .description(arg.getDescription());

                        switch (arg.getType()) {
                            case INT:
                                builder.type(Integer.class);
                                break;
                            case BOOL:
                                builder.type(Boolean.class);
                                break;
                            case ENUM:
                                break;
                            case LONG:
                                builder.type(Long.class);
                                break;
                            case STRING:
                                builder.type(String.class);
                                break;
                            case NDARRAY:
                                break;
                            case NUMERIC:
                                break;
                            case CONDITION:
                                break;
                            case DATA_TYPE:
                                builder.type(DataType.class);
                                break;
                            case LOSS_REDUCE:
                                builder.type(LossReduce.class);
                                break;
                            case FLOATING_POINT:
                                break;
                        }

                        builder.required(arg.getDefaultValue() == null);

                        if (arg.getDefaultValue() != null) {
                            builder.defaultValue(arg.getDefaultValue().toString());
                        }

                        commandSpec1.addOption(builder.build());
                    });

                });
                log.info("Starting generation of namespace: {}", ns);

                ++cnt;
            }

            log.info("Complete - generated {} namespaces", cnt);
        }
    }

    public static void main(String[] args) throws Exception {
        new CLI().runMain(args);
    }

    public void runMain(String[] args) throws Exception {
        JCommander.newBuilder()
                .addObject(this)
                .build()
                .parse(args);

        // Either root directory for source code generation or docs directory must be present. If root directory is
        // absenbt - then it's "generate docs only" mode.
        if (StringUtils.isEmpty(repoRootDir) && StringUtils.isEmpty(docsdir)) {
            throw new IllegalStateException("Provide one or both of arguments : -dir, -docsdir");
        }

        File outputDir = null;
        if (StringUtils.isNotEmpty(repoRootDir)) {
            //First: Check root directory.
            File dir = new File(repoRootDir);
            if (!dir.exists() || !dir.isDirectory()) {
                throw new IllegalStateException("Provided root directory does not exist (or not a directory): " + dir.getAbsolutePath());
            }

            outputDir = new File(dir, relativePath);
            if (!outputDir.exists() || !dir.isDirectory()) {
                throw new IllegalStateException("Expected output directory does not exist: " + outputDir.getAbsolutePath());
            }
        }

        if(namespaces == null || namespaces.isEmpty() ) {
            throw new IllegalStateException("No namespaces were provided");
        }

        generateNamespaces();

    }
}


text:
ENV["RAILS_ENV"] ||= 'test'

begin
  require File.expand_path("../dummy/config/environment", __FILE__)
rescue LoadError
  $stderr.puts "Could not load dummy application. Please ensure you have run `bundle exec rake test_app`"
  exit 1
end

require 'rspec/rails'
require 'ffaker'
require 'spree_sample'

RSpec.configure do |config|
  config.color = true
  config.infer_spec_type_from_file_location!
  config.expect_with :rspec do |c|
    c.syntax = :expect
  end
  config.mock_with :rspec do |c|
    c.syntax = :expect
  end

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, comment the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = true

  config.include FactoryGirl::Syntax::Methods
  config.fail_fast = ENV['FAIL_FAST'] || false

  config.example_status_persistence_file_path = "./spec/examples.txt"

  config.order = :random

  Kernel.srand config.seed
end


text:
package griffon.converter;

import griffon.annotations.core.Nullable;

import java.util.Objects;

/**
 * @author Andres Almiray
 * @since 3.0.0
 */
public interface Converter<T> {
    /**
     * Converts the input argument to the given type {@code T}.
     *
     * @param value the value to be converted. May be {@code null}.
     *
     * @return the converted value. May be {@code null}.
     *
     * @throws ConversionException if the given value could not be converted to the target type.
     */
    @Nullable
    T fromObject(@Nullable Object value) throws ConversionException;

    /**
     * Converts the input argument to the a {@code String}.
     *
     * @param value the value to be converted. May be {@code null}.
     *
     * @return the {@code String} representation of the given value. May be {@code null}.
     *
     * @throws ConversionException if the given value could not be converted to a String.
     */
    @Nullable
    default String toString(@Nullable T value) throws ConversionException {
        return Objects.toString(value, null);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<artifactId>fiddlewith-httpclient</artifactId>

	<parent>
		<groupId>foop.fiddlewith</groupId>
		<artifactId>fiddlewith</artifactId>
		<version>0.1.0-SNAPSHOT</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>fiddlewith-xml</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>com.github.tomakehurst</groupId>
			<artifactId>wiremock</artifactId>
			<version>1.38</version>

			<!-- Include this if you have dependency conflicts for Guava, Jetty, Jackson
				or Apache HTTP Client -->
			<classifier>standalone</classifier>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.yammer.dropwizard</groupId>
			<artifactId>dropwizard-client</artifactId>
			<version>${version.dropwizard}</version>
		</dependency>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>fiddlewith-api</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>fiddlewith-xml</artifactId>
			<version>${project.version}</version>
		</dependency>
	</dependencies>

</project>


text:
package org.python.util.install.driver;

import java.io.File;
import java.io.IOException;

import org.python.util.install.FileHelper;
import org.python.util.install.Installation;
import org.python.util.install.InstallationListener;
import org.python.util.install.InstallerCommandLine;
import org.python.util.install.JavaHomeHandler;
import org.python.util.install.JavaVersionTester;
import org.python.util.install.Installation.JavaVersionInfo;

public abstract class Autotest implements InstallationListener {

    private static final String _DIR_SUFFIX = "_dir";

    private static int _count = 0; // unique test number
    private static File _rootDirectory = null;
    private static JavaVersionInfo _systemDefaultJavaVersion;

    private String _name;
    private File _targetDir;
    private JavaHomeHandler _javaHomeHandler;
    private boolean _verbose;
    private String[] _commandLineArgs;
    private Verifier _verifier;

    /**
     * constructor
     *
     * @throws IOException
     * @throws DriverException
     */
    protected Autotest(InstallerCommandLine commandLine) throws IOException, DriverException {
        _count++;
        buildName();
        if (_rootDirectory == null) {
            createRootDirectory();
        }
        createTargetDirectory();
        setCommandLineArgs(new String[0]); // a priori value
        _verbose = commandLine.hasVerboseOption();
        _javaHomeHandler = commandLine.getJavaHomeHandler();
    }

    /**
     * @return the root directory for all test installations
     */
    protected static File getRootDir() {
        return _rootDirectory;
    }

    /**
     * @return the target directory of this test
     */
    protected File getTargetDir() {
        return _targetDir;
    }

    /**
     * @return the name of this test
     */
    protected String getName() {
        return _name;
    }

    /**
     * @return the array of command line arguments
     */
    protected String[] getCommandLineArgs() {
        return _commandLineArgs;
    }

    /**
     * set the array of command line arguments
     *
     * @param commandLineArgs
     */
    protected void setCommandLineArgs(String[] commandLineArgs) {
        _commandLineArgs = commandLineArgs;
    }

    /**
     * @return the java home handler, can be asked for deviation using isDeviation().
     */
    protected JavaHomeHandler getJavaHomeHandler() {
        return _javaHomeHandler;
    }

    /**
     * @return true if this test should be verbose
     */
    protected boolean isVerbose() {
        return _verbose;
    }

    /**
     * @return the name suffix for this test
     */
    protected abstract String getNameSuffix();

    /**
     * @throws DriverException if the target directory does not exist or is empty (installation failed)
     */
    protected void assertTargetDirNotEmpty() throws DriverException {
        File targetDir = getTargetDir();
        if (targetDir != null) {
            if (targetDir.exists() && targetDir.isDirectory()) {
                if (targetDir.listFiles().length > 0) {
                    return;
                }
            }
        }
        throw new DriverException("installation failed for " + targetDir.getAbsolutePath());
    }

    /**
     * Convenience method to add the additional arguments, if specified behind the -A option
     *

     * This adds (if present):
     *

     *
 target directory (should always be present)
     *
 verbose
     *
 jre
     *

     */
    protected void addAdditionalArguments() {
        if (getTargetDir() != null) {
            addArgument("-d");
            addArgument(getTargetDir().getAbsolutePath());
        }
        if (isVerbose()) {
            addArgument("-v");
        }
        JavaHomeHandler javaHomeHandler = getJavaHomeHandler();
        if (javaHomeHandler.isDeviation() && javaHomeHandler.isValidHome()) {
            addArgument("-j");
            addArgument(javaHomeHandler.getHome().getAbsolutePath());
        }
    }

    /**
     * Add an additional String argument to the command line arguments
     *
     * @param newArgument
     */
    protected void addArgument(String newArgument) {
        setCommandLineArgs(addArgument(newArgument, getCommandLineArgs()));
    }

    /**
     * set the verifier
     */
    protected void setVerifier(Verifier verifier) {
        _verifier = verifier;
        _verifier.setTargetDir(getTargetDir());
    }

    protected Verifier getVerifier() {
        return _verifier;
    }

    //
    // private stuff
    //

    /**
     * build a test name containing some special characters (which will be used to create the target
     * directory), and store it into _name.
     */
    private void buildName() {
        StringBuilder b = new StringBuilder(24);
        if (_count <= 99) {
            b.append('0');
        }
        if (_count <= 9) {
            b.append('0');
        }
        b.append(_count);
        // explicitly use a blank, to nail down some platform specific problems
        b.append(' ');
        // add an exclamation mark if possible (see issue #1208)
        if(canHandleExclamationMarks()) {
            b.append('!');
        }
        b.append(getNameSuffix());
        b.append('_');
        _name = b.toString();
    }

    /**
     * Add the new argument to the args array
     *
     * @param newArgument
     * @param args
     *
     * @return the new String array, with size increased by 1
     */
    private String[] addArgument(String newArgument, String[] args) {
        String[] newArgs = new String[args.length + 1];
        for (int i = 0; i < args.length; i++) {
            newArgs[i] = args[i];
        }
        newArgs[args.length] = newArgument;
        return newArgs;
    }

    /**
     * create the root directory for all automatic installations
     *

     * assumed to be a subdirectory of java.io.tmpdir
     *
     * @throws IOException
     * @throws DriverException
     */
    private void createRootDirectory() throws IOException, DriverException {
        File tmpFile = File.createTempFile("jython.autoinstall.root_", _DIR_SUFFIX);
        if (FileHelper.createTempDirectory(tmpFile)) {
            _rootDirectory = tmpFile;
        } else {
            throw new DriverException("unable to create root temporary directory");
        }
    }

    /**
     * create a target directory for a test installation
     *
     * @throws IOException
     * @throws DriverException
     */
    private void createTargetDirectory() throws IOException, DriverException {
        File tmpFile = File.createTempFile(getName(), _DIR_SUFFIX, _rootDirectory);
        if (FileHelper.createTempDirectory(tmpFile)) {
            _targetDir = tmpFile;
        } else {
            throw new DriverException("unable to create temporary target directory");
        }
    }

    /**
     * Determine if the target directory may contain an exclamation mark (see also issue #1208).
     *

     * Autotests can handle exclamation marks, if both the running and the system default java
     * specification versions are 1.6 or higher. Class.getResource() was fixed for JDK 1.6, but only if the directory name does not end with '!'...
     *

     * Currently there is no way on windows, because the enabledelayedexpansion in jython.bat cannot
     * handle exclamation marks in variable names.
     *
     * @return true if we can handle exclamation marks, false otherwise
     */
    private boolean canHandleExclamationMarks() {
        boolean exclamation = false;
        if (!Installation.isWindows()) {
            // get the running java specification version
            String specificationVersion = System.getProperty(JavaVersionTester.JAVA_SPECIFICATION_VERSION,
                                                             "");
            if (Installation.getJavaSpecificationVersion(specificationVersion) > 15) {
                // get the system default java version
                if (_systemDefaultJavaVersion == null) {
                    _systemDefaultJavaVersion = Installation.getDefaultJavaVersion();
                }
                if (_systemDefaultJavaVersion.getErrorCode() == Installation.NORMAL_RETURN) {
                    specificationVersion = _systemDefaultJavaVersion.getSpecificationVersion();
                    if (Installation.getJavaSpecificationVersion(specificationVersion) > 15) {
                        exclamation = true;
                    }
                }
            }
        }
        return exclamation;
    }

}


text:
package isokey

//Signer defines a service that signs keys
type Signer interface {
	Sign(key *Key) (digest string, err error)
}


text:
package com.joey.bak.base.view;

/**
 * Created by joe on 16/5/18.
 */
public interface BaseView {
    void showToastMsg(String msg);
}


text:
typedef enum
{
    COLSE_CONNECT     = 40,
    MEM_POOL_COVER    = 60,
    NET_CONNECT_ERROR = 80,
    DSTASK_QUIT       = 81,
	DESTROY = 82,
}emNOTIFY;

class DistributionManager:public INotify
{
public:
    DistributionManager(INotify  *notify_obj, int queue_num_ =3,int _perSize = 1024*1024*1):
	  notify_object_(notify_obj), memory_pool_(this,queue_num_,_perSize)
    {
		m_lPacketSeq = 0;
       task_need_extradata_ = false;
    }
    ~DistributionManager(){Stop();}
private:
    static int task_id_;

public:
    static int get_task_id(){return task_id_;}

public:
    MemoryPool memory_pool_;
    map<int,DistributionTask*> task_record_;
    Poco::FastMutex   mutex_;
    bool task_need_extradata_;
	INotify  *notify_object_;
	long key_;
	DWORD       m_lPacketSeq;

public:
	bool AddClient(StreamSocket &socket_);

	void set(long key) { key_ = key; }

	string Notify(int type, char* frame, int length_);

	//»ñÈ¡°üÐòºÅ
	long GetPacketSeq()
	{
		m_lPacketSeq++;
		if ( m_lPacketSeq > 0xffff )
		{
			m_lPacketSeq = 0;
		}
		return m_lPacketSeq;
	}

private:
    void Stop();
};


text:
// SPDX-License-Identifier: MIT

/*
** This Sentence Not Recommended For New Designs
** XDR is recommended.
*/

#include "nmea0183.h"
#pragma hdrstop

void MHU::Empty( void ) noexcept
{
   RelativeHumidityPercent = 0.0;
   AbsoluteHumidityPercent = 0.0;
   DewPointDegreesCelcius  = 0.0;
}

bool MHU::Parse( SENTENCE const& sentence ) noexcept
{
   /*
   ** MHU - Humidity
   **
   **        1   2   3   4 5
   **        |   |   |   | |
   ** $--MHU,x.x,x.x,x.x,C*hh<CR><LF>
   **
   ** Field Number:
   **  1) Relative Humidity Percent
   **  2) Absolute humidity percent
   **  3) Dew Point
   **  4) C = Degrees Celsius
   **  5) Checksum
   */

   /*
   ** First we check the checksum...
   */

   if ( sentence.IsChecksumBad( 5 ) == NMEA0183_BOOLEAN::True )
   {
       SetErrorMessage(STRING_VIEW("Invalid Checksum"));
       return( false );
   }

   RelativeHumidityPercent = sentence.Double( 1 );
   AbsoluteHumidityPercent = sentence.Double( 2 );
   DewPointDegreesCelcius  = sentence.Double( 3 );

   return( false );
}

bool MHU::Write( SENTENCE& sentence ) const noexcept
{
   /*
   ** Let the parent do its thing
   */

   RESPONSE::Write( sentence );

   sentence += RelativeHumidityPercent;
   sentence += AbsoluteHumidityPercent;
   sentence += DewPointDegreesCelcius;
   sentence += STRING_VIEW("C");

   sentence.Finish();

   return( true );
}

MHU const& MHU::operator = ( MHU const& source ) noexcept
{
   RelativeHumidityPercent  = source.RelativeHumidityPercent;
   AbsoluteHumidityPercent  = source.AbsoluteHumidityPercent;
   DewPointDegreesCelcius   = source.DewPointDegreesCelcius;

   return( *this );
}


text:
package com.acadiasoft.im.simm.model.param.cq;

import com.acadiasoft.im.simm.model.SensitivityIdentifier;
import com.acadiasoft.im.simm.model.imtree.identifiers.BucketType;
import com.acadiasoft.im.simm.model.param.SimmRiskWeight;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author joe.peterson
 *
 */
public class CreditQualifyingRiskWeight implements SimmRiskWeight {

  private static final Map<BucketType, BigDecimal> WEIGHTS = new HashMap<>();

  static {
    WEIGHTS.put(BucketType.CRQ1, new BigDecimal("75"));
    WEIGHTS.put(BucketType.CRQ2, new BigDecimal("91"));
    WEIGHTS.put(BucketType.CRQ3, new BigDecimal("78"));
    WEIGHTS.put(BucketType.CRQ4, new BigDecimal("55"));
    WEIGHTS.put(BucketType.CRQ5, new BigDecimal("67"));
    WEIGHTS.put(BucketType.CRQ6, new BigDecimal("47"));
    WEIGHTS.put(BucketType.CRQ7, new BigDecimal("187"));
    WEIGHTS.put(BucketType.CRQ8, new BigDecimal("665"));
    WEIGHTS.put(BucketType.CRQ9, new BigDecimal("262"));
    WEIGHTS.put(BucketType.CRQ10, new BigDecimal("251"));
    WEIGHTS.put(BucketType.CRQ11, new BigDecimal("172"));
    WEIGHTS.put(BucketType.CRQ12, new BigDecimal("247"));
    WEIGHTS.put(BucketType.CRQRESIDUAL, new BigDecimal("665"));
  }

  private static final BigDecimal VEGA = new BigDecimal("0.74");

  @Override
  public BigDecimal getDeltaRiskWeight(SensitivityIdentifier s) {
    return WEIGHTS.get(s.getBucketIdentifier().getBucketType());
  }

  @Override
  public BigDecimal getVegaRiskWeight(SensitivityIdentifier s) {
    return VEGA;
  }

}


text:
function EditorDialog::onAdd(%this)
{
	ThemeManager.setProfile(%this, "overlayProfile");

	%this.window = new GuiWindowCtrl()
	{
		class = "EditorDialogWindow";
		HorizSizing = "center";
		VertSizing = "center";
		Position = "0 0";
		Extent = %this.dialogSize;
		Text = %this.dialogText;
		canClose = %this.dialogCanClose;
		canMove = true;
		CanMinimize = false;
		CanMaximize = false;
		titleHeight = 30;
		dialog = %this;
	};
	ThemeManager.setProfile(%this.window, "windowProfile");
	ThemeManager.setProfile(%this.window, "windowContentProfile", "contentProfile");
	ThemeManager.setProfile(%this.window, "windowButtonProfile", "MinButtonProfile");
	ThemeManager.setProfile(%this.window, "windowButtonProfile", "MaxButtonProfile");
	ThemeManager.setProfile(%this.window, "windowButtonProfile", "CloseButtonProfile");
	%this.add(%this.window);

	%this.content = new GuiScrollCtrl()
	{
		HorizSizing = "width";
		VertSizing = "height";
		Position = "0 0";
		Extent = (getWord(%this.dialogSize, 0) - 8) SPC (getWord(%this.dialogSize, 1) - 34);//we assume a 4 pixel border
		hScrollBar = "dynamic";
		vScrollBar = "dynamic";
		constantThumbHeight="0";
		showArrowButtons = 0;
		scrollBarThickness = 16;
	};
	ThemeManager.setProfile(%this.content, "scrollingPanelProfile");
	ThemeManager.setProfile(%this.content, "scrollingPanelThumbProfile", ThumbProfile);
	ThemeManager.setProfile(%this.content, "scrollingPanelTrackProfile", TrackProfile);
	ThemeManager.setProfile(%this.content, "scrollingPanelArrowProfile", ArrowProfile);
	%this.window.add(%this.content);
}

function EditorDialogWindow::onClose(%this)
{
	%this.dialog.call("onClose");
}


text:
@implementation UIImageView (JXHHeader)

- (void)setHeader:(NSString *)url
{
    [self setCircleHeader:url];
}

- (void)setRectHeader:(NSString *)url
{
    [self sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"defaultUserIcon"]];
}

- (void)setCircleHeader:(NSString *)url
{
    JXHWeakSelf;

    UIImage *placeholder = [[UIImage imageNamed:@"defaultUserIcon"] circleImage];
    [self sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:placeholder completed:
     ^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
         // 如果图片下载失败,就不做任何处理,按照默认的做法:会显示占位图片
         if (image == nil) return;

         weakSelf.image = [image circleImage];
     }];
}

@end


text:
from __future__ import unicode_literals
import json

from moto.core.responses import BaseResponse
from .models import ssm_backends

class SimpleSystemManagerResponse(BaseResponse):

    @property
    def ssm_backend(self):
        return ssm_backends[self.region]

    @property
    def request_params(self):
        try:
            return json.loads(self.body)
        except ValueError:
            return {}

    def _get_param(self, param, default=None):
        return self.request_params.get(param, default)

    def delete_parameter(self):
        name = self._get_param('Name')
        self.ssm_backend.delete_parameter(name)
        return json.dumps({})

    def delete_parameters(self):
        names = self._get_param('Names')
        result = self.ssm_backend.delete_parameters(names)

        response = {
            'DeletedParameters': [],
            'InvalidParameters': []
        }

        for name in names:
            if name in result:
                response['DeletedParameters'].append(name)
            else:
                response['InvalidParameters'].append(name)
        return json.dumps(response)

    def get_parameters(self):
        names = self._get_param('Names')
        with_decryption = self._get_param('WithDecryption')

        result = self.ssm_backend.get_parameters(names, with_decryption)

        response = {
            'Parameters': [],
            'InvalidParameters': [],
        }

        for parameter in result:
            param_data = parameter.response_object(with_decryption)
            response['Parameters'].append(param_data)

        param_names = [param.name for param in result]
        for name in names:
            if name not in param_names:
                response['InvalidParameters'].append(name)
        return json.dumps(response)

    def describe_parameters(self):
        page_size = 10
        filters = self._get_param('Filters')
        token = self._get_param('NextToken')
        if hasattr(token, 'strip'):
            token = token.strip()
        if not token:
            token = '0'
        token = int(token)

        result = self.ssm_backend.get_all_parameters()
        response = {
            'Parameters': [],
        }

        end = token + page_size
        for parameter in result[token:]:
            param_data = parameter.response_object(False)
            add = False

            if filters:
                for filter in filters:
                    if filter['Key'] == 'Name':
                        k = param_data['Name']
                        for v in filter['Values']:
                            if k.startswith(v):
                                add = True
                                break
                    elif filter['Key'] == 'Type':
                        k = param_data['Type']
                        for v in filter['Values']:
                            if k == v:
                                add = True
                                break
                    elif filter['Key'] == 'KeyId':
                        k = param_data.get('KeyId')
                        if k:
                            for v in filter['Values']:
                                if k == v:
                                    add = True
                                    break
            else:
                add = True

            if add:
                response['Parameters'].append(param_data)

            token = token + 1
            if len(response['Parameters']) == page_size:
                response['NextToken'] = str(end)
                break

        return json.dumps(response)

    def put_parameter(self):
        name = self._get_param('Name')
        description = self._get_param('Description')
        value = self._get_param('Value')
        type_ = self._get_param('Type')
        keyid = self._get_param('KeyId')
        overwrite = self._get_param('Overwrite', False)

        self.ssm_backend.put_parameter(
            name, description, value, type_, keyid, overwrite)
        return json.dumps({})

    def add_tags_to_resource(self):
        resource_id = self._get_param('ResourceId')
        resource_type = self._get_param('ResourceType')
        tags = {t['Key']: t['Value'] for t in self._get_param('Tags')}
        self.ssm_backend.add_tags_to_resource(
            resource_id, resource_type, tags)
        return json.dumps({})

    def remove_tags_from_resource(self):
        resource_id = self._get_param('ResourceId')
        resource_type = self._get_param('ResourceType')
        keys = self._get_param('TagKeys')
        self.ssm_backend.remove_tags_from_resource(
            resource_id, resource_type, keys)
        return json.dumps({})

    def list_tags_for_resource(self):
        resource_id = self._get_param('ResourceId')
        resource_type = self._get_param('ResourceType')
        tags = self.ssm_backend.list_tags_for_resource(
            resource_id, resource_type)
        tag_list = [{'Key': k, 'Value': v} for (k, v) in tags.items()]
        response = {'TagList': tag_list}
        return json.dumps(response)


text:
package hr.element.beepo
package Security

import hr.ngs.patterns._
import com.fasterxml.jackson.annotation._

class Role private(
    @transient private val _locator: Option[IServiceLocator]
  , private var _URI: String
  , private var _Name: String
  ) extends IIdentifiable
    with Serializable {

  @JsonGetter("URI")
  def URI = {

    _URI
  }

  private[Security]def URI_= (value: String) {
    //TODO missing primitive type distinction require(value ne null)

    _URI = value

  }

  override def hashCode = URI.hashCode
  override def equals(o: Any) = o match {
    case c: Role => c.URI == URI
    case _ => false
  }

  override def toString = "Role("+ URI +")"

  @JsonGetter("Name")
  def Name = {

    _Name
  }

  def Name_= (value: String) {
    //TODO missing primitive type distinction require(value ne null)

    _Name = value

  }

  @JsonCreator private def this(
    @JacksonInject("locator") _locator: IServiceLocator
  , @JsonProperty("URI") URI: String
  , @JsonProperty("Name") Name: String
  ) =
    this(_locator = Some(_locator), _URI = URI, _Name = Name)

}

object Role {

  def apply(
    Name: String = ""
  ) = {
    new Role(
      _locator = None
    , _URI = java.util.UUID.randomUUID.toString
    , _Name = Name)
  }

  private[Security] def buildInternal(_locator: IServiceLocator
    , URI: String
    , Name: String) =
    new Role(
      _locator = Some(_locator)
    , _URI = URI
    , _Name = Name)
}