text:
package arb.soundcipher;

import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.lang.Class;
import java.lang.reflect.Method;
import processing.core.PApplet;
import arb.soundcipher.constants.ProgramChanges;
import arb.soundcipher.constants.PitchClassSets;
import arb.soundcipher.constants.DrumMap;
import arb.soundcipher.constants.MidiMessageTypes;
import java.util.List;
import javax.sound.midi.*;

/**
 * The SCScore class provides music data structure and
 * scheduling services. It is part
 * of the {@link SoundCipher} library for
 * Processing.
 * A score can contain notes, phrases (note sequences), chords
 * (note clusters), or 'callbacks.' A score can be played back once,
 * repeated or looped.
 *
 * Notes in a score play back using the internal JavaSound soundbank,
 * MIDI Events (note messages) are sent to the active MIDI device,
 * while Scheduled Events provide a callback into Processing for any
 * arbitary synchronised purpose (e.g. audio file playback, drawing,
 * sound synthesis parameter control, and OSC or MIDI message sending).
 *
 * When using a SCScore instance always include a stop() method in your
 * Processing program to halt playback when the program exits.
 * Like so, assuming your SCScore instance is called score.

 * void stop() {

 *   score.stop();

 * }

 *
 * @author Andrew R. Brown
 */
public class SCScore extends SCUtilities implements MetaEventListener,
        ProgramChanges, DrumMap, PitchClassSets, MidiMessageTypes {

    /** A JavaSound Sequencer instance. */
    protected Sequencer sequencer;
    /** A JavaSound Sequence instance. */
    private Sequence seq;
    /** The default tempo to the score, 120.0 beats per minute. */
    public double tempo = 120.0; // bpm
    /** The default number of repeats on score playback, 0.
     * -1 indicates infinite repeats (looping). */
    public double repeat = 0; // -1 is infinite repeat
    /** The number of repeats a score has played */
    public double repeatCounter = 0;
    /** The number of MIDI pulses per quater note */
    private int resolution = 240; // ppqn
    /** A flag to indicate if the score is currently playing. */
    public boolean playing = false;
    /** A flag to indicate if the class should print verbose debug or not.*/
    private boolean debug = false;
    /** Specifies the default instrument to 0 [0 - 127]
     * (0 = piano on the JavaSound synthesizer) */
    public double instrument = 0;
    /** Specifies the default MIDI channel to 0 [0-15] */
    public double channel = 0;
    /** Specifies the default pan poisition to be 64, in the centre [0 - 127] */
    public double pan = 64;
    /** Specifies the amount of duration that will sound,
     * e.g., 0.2 = stacatto, 1.0 = legato */
    public double articulation = 0.8;
    /** The link back to Processing. */
    private static PApplet pApplet;
    /** The top number of the score's time signature. */
    public double numerator = 4; // time signature
    /** The lower number of the score's time signature. */
    public double denominator = 4; // time signature

    /**
     * Creates a empty SoundCipher Score (SCScore) object.
     * A SCScore is an enhanced and easy to use wrapper for a JavaSound sequencer.
     */
    public SCScore() {
        if (debug) {
            System.out.println("SoundCipher Score constructor");
        }
        try {
            sequencer = MidiSystem.getSequencer();
            sequencer.open();
            sequencer.addMetaEventListener(this);
            seq = new Sequence(Sequence.PPQ, resolution);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Specify the default channel for notes added to this score.
     * @param newChan The value to set the channel to, from 0-15.
     */
    public void channel(double newChan) {
	if (newChan >= 0 && newChan <= 15) {
	    this.channel = (int)newChan;
	} else System.out.println("SCScore channels should be between 0 and 15.");
    }

    /**
     * Specify the default instrument for notes added to this score.
     * @param newChan The value to set the instrument to, from 0-15.
     */
    public void instrument(double newInst) {
	if (newInst >= 0 && newInst <= 127) {
	    this.instrument = (int)newInst;
	} else System.out.println("SCScore instrument should be between 0 and 127.");
    }

    /**
     * Specify the default pan position for notes added to this score.
     * @param newPos The value to set the pan psotion to, from 0 - 127.
     */
    public void pan(double newPos) {
	if (newPos >= 0 && newPos <= 127) {
	    this.pan = (int)newPos;
	} else System.out.println("SCScore pan position should be between 0 and 127, 64 is in the middle.");
    }

    /**
     * Specify the top number of the time signture for this score.
     * @param value The value for the numerator, whole number greater than 0.
     */
    public void numerator(double value) {
	if (value > 0) {
	    this.numerator = (int)value;
	} else System.out.println("SCScore numerator should be larger than zero.");
    }

    /**
     * Specify the lower number of the time signture for this score.
     * @param value The value for the denamonator, whole number greater than 0.
     */
    public void denominator(double value) {
	if (value > 0) {
	    this.denominator = (int)value;
	} else System.out.println("SCScore denaominator should be larger than zero.");
    }

    /**
     * Specify the speed (tempo) of the score in beats per minute
     *
     * @param newTempo The new tempo value.
     */
    public void tempo(double newTempo) {
        this.tempo = newTempo;
        sequencer.setTempoInBPM((float) tempo);
    }

    /**
     * Start the Score playback.
     */
    public void play() {
        this.play(this.repeat, this.tempo);
    }

    /**
     * Start the Score playback.
     *
     * @param repeat The number of repeats (-1 = infinite)
     */
    public void play(double repeat) {
        this.play(repeat, this.tempo);
    }

    /**
     * Start the Score playback.
     *
     * @param repeat The number of repeats (-1 = infinite)
     * @param tempo The playback speed in beats per minute
     */
    public void play(double repeat, double tempo) {
        if (debug) {
            System.out.println("Playing ... repeat = " + repeat);
        }
        //if (playing) this.stop();
        this.repeat = repeat;
        this.tempo = tempo;
        this.repeatCounter = 0;
        update();
        sequencer.setMicrosecondPosition(0l);
        sequencer.setTempoInBPM((float) tempo);
        sequencer.start();
        playing = true;
    }

    /**
     * Halt the score playback.
     */
    public void stop() {
        if (debug) {
            System.out.println("stop");
        }
        sequencer.stop();
        playing = false;
    }

    /**
     * Refresh the sequence data and start time of the score.
     *
     * An update is required if data is dynamically added to the score while it is playing.
     */
    public void update() {
        if (debug) {
            System.out.println("update");
        }
        try {
            sequencer.setTempoInBPM((float) tempo); // working??
            sequencer.setSequence(seq);
        } catch (javax.sound.midi.InvalidMidiDataException e) {
            e.printStackTrace();
        }
        if (repeat >= 0) {
            sequencer.setLoopCount((int) repeat);
        }
    }

    /**
     * Remove all data from the score.
     */
    public void empty() {
        if (debug) {
            System.out.println("empty");
        }
        if (sequencer != null) {
            //if (seq != null) {
            //    Track[] tracks = seq.getTracks();
            //    for (int j = tracks.length; j > 0; j--) {
            //        seq.deleteTrack(tracks[j - 1]);
            //        tracks[j - 1] = null;
            //    }
            //}
	    try {
		seq = new Sequence(Sequence.PPQ, resolution);
	    } catch (javax.sound.midi.InvalidMidiDataException e) {}
        }
    }

    /**
     * Specify the number of repetitions for the score (-1 = infinite loop)
     *
     * @param repeat The new repeat value.
     */
    public void repeat(double repeat) {
        this.repeat = repeat;
    }

    /**
     * A conditional that indicates if the score is currently playing.
     *
     * @return True or False
     */
    public boolean isPlaying() {
        return playing;
    }

    /**
     * Retreive the Sequencer object used by this SCScore.
     *
     * @return A JavaSound sequencer object
     */
    public Sequencer sequencer() {
        return this.sequencer;
    }

    /**
     * Schedules a single note in the score.
     *
     * This reduced-argument version of the method can be useful for creating scores where
     * all notes are on a same MIDI channel, instrument, articulation and pan settings.
     *
     * @param startBeat Specifies when the note will play, in beats, after the score starts
     * @param pitch The MIDI pitch (frequency) at which the note will play [0-127]
     * @param dynamic The loudness, MIDI velocity, of the note [0-127]
     * @param duration The length that the note will sound, in beats
     */
    public void addNote(double startBeat, double pitch, double dynamic, double duration) {
        addNote(startBeat, this.channel, this.instrument, pitch, dynamic, duration, this.articulation, this.pan);
    }

    /**
     * Schedules a single note in the score.
     *
     * @param startBeat Specifies when the note will play, in beats, after the score starts
     * @param channel The MIDI channel to use for this note [0-15]
     * @param instrument The JavaSound instrument (sound) to use for this note [0-127]
     * @param pitch The MIDI pitch (frequency) at which the note will play [0-127]
     * @param dynamic The loudness, MIDI velocity, of the note [0-127]
     * @param duration The length that the note will sound, in beats
     * @param articulation An articulation multiplier for duration (0.8 by default)
     * @param pan The note's left-right location in the stereo field [0-127]
     */
    public void addNote(double startBeat, double channel, double instrument, double pitch,
            double dynamic, double duration, double articulation, double pan) {
        addPhrase(startBeat, channel, instrument, new double[]{pitch},
                new double[]{dynamic}, new double[]{duration},
                new double[]{articulation}, new double[]{pan});
    }

    /**
     * Schedules a note sequence (phrase) within the score.
     *
     * @param startBeat Specifies when the phrase will start to play,
     * in beats, after the score starts
     * @param channel The MIDI channel to use for this note [0-15]
     * @param instrument The JavaSound instrument (sound) to use for this note [0-127]
     * @param pitches The MIDI pitches (frequencies) at which the note will play [0-127]
     * @param dynamics The loudness, MIDI velocity, of each note [0-127]
     * @param durations The lengths that each note will sound, in beats
     * @param articulations An articulation multiplier for each duration (0.8 by default)
     * @param pans Each note's left-right location in the stereo field [0-127]
     */
    public void addPhrase(double startBeat, double channel, double instrument,
            float[] pitches, float[] dynamics, float[] durations,
            float[] articulations, float[] pans) {
        double[] dPitches = new double[pitches.length];
        double[] dDynamics = new double[pitches.length];
        double[] dDurations = new double[pitches.length];
        double[] dArticulations = new double[pitches.length];
        double[] dPans = new double[pitches.length];
        for (int i = 0; i < pitches.length; i++) {
            dPitches[i] = pitches[i];
            dDynamics[i] = dynamics[i];
            dDurations[i] = durations[i];
            dArticulations[i] = articulations[i];
            dPans[i] = pans[i];
        }
        this.addPhrase(startBeat, channel, instrument, dPitches, dDynamics, dDurations, dArticulations, dPans);
    }

    /**
     * Schedules a note sequence (phrase) within the score.
     *
     * @param startBeat Specifies when the phrase will start to play,
     * in beats, after the score starts
     * @param channel The MIDI channel to use for this note [0-15]
     * @param instrument The JavaSound instrument (sound) to use for this note [0-127]
     * @param pitches The MIDI pitches (frequencies) at which the note will play [0-127]
     * @param dynamics The loudness, MIDI velocity, of each note [0-127]
     * @param durations The lengths that each note will sound, in beats
     * @param articulations An articulation multiplier for each duration (0.8 by default)
     * @param pans Each note's left-right location in the stereo field [0-127]
     */
    public void addPhrase(double startBeat, double channel, double instrument,
            double[] pitches, double[] dynamics, double[] durations,
            double[] articulations, double[] pans) {
        double endBeat = startBeat;
        for (int i = 0; i < durations.length; i++) {
            endBeat += durations[i];
        }
        try {
            buildSequence(startBeat, channel, instrument, pitches, dynamics,
                    durations, articulations, pans, false);
            // add event to round off the sequence
            Track[] tracks = seq.getTracks();
            tracks[0].add(createEvent(ShortMessage.POLY_PRESSURE, (int) channel, 0, 0,
                    (long) (endBeat * resolution)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Schedules a note cluster (chord) within the score.
     *
     * @param startBeat Specifies when the notes will play, in beats, after the score starts
     * @param pitches Arracy of MIDI pitches for each note [0-127]
     * @param dynamic The loudness, MIDI velocity, of the notes [0-127]
     * @param duration The length that the notes will sound, in beats
     */
    public void addChord(double startBeat, float[] pitches, double dynamic, double duration) {
        this.addChord(startBeat, this.channel, this.instrument, pitches, dynamic, duration, this.articulation, this.pan);
    }

    /**
     * Schedules a note cluster (chord) within the score.
     *
     * @param startBeat Specifies when the notes will play, in beats, after the score starts
     * @param channel The MIDI channel to use for this note [0-15]
     * @param instrument The JavaSound instrument (sound) to use for this note [0-127]
     * @param pitches An array of MIDI pitches for each note [0-127]
     * @param dynamic The loudness, MIDI velocity, of the notes [0-127]
     * @param duration The length that the notes will sound, in beats
     * @param articulation An articulation multiplier for duration (0.8 by default)
     * @param pan The note's left-right location in the stereo field [0-127]
     */
    public void addChord(double startBeat, double channel, double instrument,
            float[] pitches, double dynamic, double duration,
            double articulation, double pan) {
	double[] dPitches = new double[pitches.length];
        for (int i = 0; i < pitches.length; i++) {
            dPitches[i] = (double) pitches[i];
        }
        double[] dynamics = new double[pitches.length];
        double[] durations = new double[pitches.length];
        double[] articulations = new double[pitches.length];
        double[] pans = new double[pitches.length];
        for (int i = 0; i < pitches.length; i++) {
            dynamics[i] = dynamic;
            durations[i] = duration;
            articulations[i] = articulation;
            pans[i] = pan;
        }
        try {
            buildSequence(startBeat, channel, instrument, dPitches, dynamics,
                    durations, articulations, pans, true);
            // add event to round off the sequence
            Track[] tracks = seq.getTracks();
            tracks[0].add(createEvent(ShortMessage.POLY_PRESSURE, (int) channel, 0, 0,
                    (long) ((startBeat + duration) * resolution)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Schedules an callback event within the score.
     *
     * @param startBeat Specifies when the callback will be triggered, in beats, after the score starts.
     * @param callbackID The identifier for this event, which is passed as part of the callback.
     */
    public void addCallback(double startBeat, int callbackID) {
	Track[] tracks = seq.getTracks();
        Track track;
	if (tracks.length > 0 && tracks[0] != null) {
	    track = tracks[0];
	} else track = seq.createTrack();
        long startTime = (long) (startBeat * resolution);
        try {
            MetaMessage mm = new MetaMessage();
            mm.setMessage(70, new byte[]{new Integer(callbackID).byteValue()}, 1);
            track.add(new MidiEvent(mm, startTime));
        } catch (javax.sound.midi.InvalidMidiDataException e) {
            e.printStackTrace();
        }
    }

    /**
     * Creates notes and schedules them for playback within a JavaSound Sequence.
     *
     * @param startBeat Specifies when the notes will play, in beats, within the sequence.
     * @param channel The MIDI channel to use for these notes [0-15].
     * @param instrument The JavaSound instrument (sound) to use for these notes [0-127].
     * @param pitches The MIDI pitches (frequencies) at which the notes will play [0-127].
     * @param dynamics The loudness (MIDI velocity) of each note [0-127].
     * @param durations The length that each note will sound, in beats.
     * @param articulations An articulation multiplier for each duration (0.8 by default).
     * @param pans Each note's left-right location in the stereo field [0-127].
     */
    private void buildSequence(double startBeat, double chan, double inst,
            double[] pitches, double[] dynamics, double[] durations,
            double[] articulations, double[] pans, boolean isChord) {
	// select a track to add notes to
	Track[] tracks = seq.getTracks();
	Track track = seq.createTrack();
	for (int i=0; i<tracks.length; i++) {
	    MidiEvent sampleEvent = tracks[i].get(0);
	    MidiMessage sampleMessage = sampleEvent.getMessage();
	    int status = sampleMessage.getStatus();
	    if (status == 192 + chan) track = tracks[i];
	}
        // insert program change
        track.add(createEvent(ShortMessage.PROGRAM_CHANGE, (int) chan, (int) inst, 0, (long) 0.0));
        // add note events to track
        double currBeat = startBeat;
        for (int i = 0; i < pitches.length; i++) {
            if (debug) {
                System.out.println("Pitch " + pitches[i]);
            }
            addMidiEvents(track, chan, currBeat, pitches[i], dynamics[i],
                    durations[i], articulations[i], pans[i]);
            if (isChord) {
                currBeat += 0;
            } else {
                currBeat += durations[i];
            }
        }
        if (debug) {
            System.out.println("===========");
        }
    }

    /**
     * Schedules data for a single note (note on and off messages) to a track in the score.
     *
     * @param track The JavaSound track to which the events should added
     * @param channel The MIDI channel to use for this note [0-15]
     * @param startBeat Specifies when the notes will play, in beats, after the score starts
     * @param pitch The MIDI pitch (frequency) for the note [0-127]
     * @param dynamic The loudness, MIDI velocity, of the notes [0-127]
     * @param duration The length that the notes will sound, in beats
     * @param articulation An articulation multiplier for duration (0.8 by default)
     * @param pan The note's left-right location in the stereo field [0-127]
     */
    private void addMidiEvents(Track track, double chan, double startBeat, double pitch,
            double dynamic, double duration, double articulation,
            double pan) {
        long startTime = (long) (startBeat * resolution);
        long dur = (long) (duration * articulation * resolution);
        int bPitch = Math.max((int) pitch, -1); // -1 is a rest
        bPitch = Math.min(bPitch, 127);
        int bDyn = Math.max((int) dynamic, 0);
        bDyn = Math.min(bDyn, 127);
        if (bPitch >= 0) {
            // pan
            track.add(createEvent(ShortMessage.CONTROL_CHANGE, (int) chan, 10, (int) pan,
                    startTime));
            // note
            track.add(createEvent(ShortMessage.NOTE_ON, (int) chan, bPitch, bDyn,
                    startTime));
            track.add(createEvent(ShortMessage.NOTE_OFF, (int) chan, bPitch, 0,
                    startTime + dur));
        }
    }

    /**
     * Creates a single MIDI message and adds it to the score.
     *
     * @param startBeat Specifies when the message will be sent, in beats, after the score starts
     * @param type The MIDI message status value; the type of message to add (control change, pitch bend etc.)
     * @param channel The MIDI channel to use for this message [0-15]
     * @param val1 The first byte of data (e.g., control change number)
     * @param val2 The second byte of data (e.g., control change value)
     */
    public void addMIDIMessage(double startBeat, int type, double channel, double val1, double val2) {
        Track track = seq.createTrack();
        track.add(createEvent(type, (int) channel, (int) val1, (int) val2, (long) (startBeat * resolution)));
    }

    /**
     * Create an individual MIDI message event.
     *
     * @param type The message type (note on, note off etc.)
     * @param chan The MIDI channel to use for this event [0-15]
     * @param val1 The first data byte value
     * @param val2 The second data byte value
     * @param tick The time for the event to be scheduled in PPQN since the start of the track
     */
    private MidiEvent createEvent(int type, int chan, int val1, int val2, long tick) {
        ShortMessage bMessage = new ShortMessage();
        MidiEvent bEvent = null;
        try {
            bMessage.setMessage(type, chan, val1, val2);
            bEvent = new MidiEvent(bMessage, tick);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return bEvent;
    }

    /**
     * Read a MIDI file into a SoundCipher score
     *
     * @param filePath Path and name of the MIDI file. Absolute file path required.
     */
    public void addMidiFile(String filePath) {
        try {
            File file = new File(filePath);
            try {
                Sequence tempSeq = MidiSystem.getSequence(file);
                if (debug) {
                    System.out.println("seq div type: " + seq.getDivisionType());
                }
                if (debug) {
                    System.out.println("tempSeq res: " + tempSeq.getResolution() +
                            " Div type: " + tempSeq.getDivisionType());
                }
                Track[] tracks = tempSeq.getTracks();
                for (int i = 0; i < tracks.length; i++) {
                    Track t = seq.createTrack();
                    for (int j = 0; j < tracks[i].size(); j++) {
                        t.add(tracks[i].get(j));
                    }
                }
            } catch (javax.sound.midi.InvalidMidiDataException imde) {
                imde.printStackTrace();
            }
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Read a MIDI file input stream into a SoundCipher score
     *
     * @param is The InputStream for the MIDI file.
     */
    public void addMidiStream(InputStream is) {
        try {
            Sequence tempSeq = MidiSystem.getSequence(is);
            if (debug) {
                System.out.println("seq div type: " + seq.getDivisionType());
            }
            if (debug) {
                System.out.println("tempSeq res: " + tempSeq.getResolution() +
                        " Div type: " + tempSeq.getDivisionType());
            }
            Track[] tracks = tempSeq.getTracks();
            for (int i = 0; i < tracks.length; i++) {
                Track t = seq.createTrack();
                for (int j = 0; j < tracks[i].size(); j++) {
                    t.add(tracks[i].get(j));
                }
            }
        } catch (Exception ioe) {
            ioe.printStackTrace();
        }

    }

    /**
     * Save the score as a MIDI file
     *
     * @param filePath Path and name of the MIDI file to be written. Absolute file path required
     */
    public void writeMidiFile(String filePath) {
	Sequence tempSeq = seq;
	Track[] tracks = tempSeq.getTracks();
	Track track = tracks[0];
	// add tempo message
	try {
            MetaMessage mm = new MetaMessage();
	    String hexString =  Integer.toHexString(new Integer((int)(1000000 * 60 / this.tempo)));
	    int hsLength = hexString.length();
	    String hexString3 = hexString.substring(hsLength - 2, hsLength - 0);
	    String hexString2 = hexString.substring(hsLength - 4, hsLength - 2);
	    String hexString1 = "0";
	    if (hsLength > 5) {
		hexString1 = hexString.substring(0, 2);
	    } else if (hsLength > 4) hexString1 = hexString.substring(0, 1);
            mm.setMessage(81, new byte[]{new Integer(Integer.parseInt(hexString1, 16)).byteValue(),
					 new Integer(Integer.parseInt(hexString2, 16)).byteValue(),
					 new Integer(Integer.parseInt(hexString3, 16)).byteValue()}, 3);
            track.add(new MidiEvent(mm, 0));
        } catch (javax.sound.midi.InvalidMidiDataException e) {
            e.printStackTrace();
        }
	// add time signature message
	try {
            MetaMessage mm = new MetaMessage();
	    int dd = 2;
	    if (denominator == 8) dd = 3;
	    if (denominator == 2) dd = 1;
	    int cc = (int)(resolution / denominator * 4); // number of midiclocks per metronome beat
            mm.setMessage(88, new byte[]{new Integer((int)numerator).byteValue(),
					 new Integer(dd).byteValue(),
					 new Integer(cc).byteValue(),
					 new Integer(8).byteValue()}, 4);
            track.add(new MidiEvent(mm, 0));
        } catch (javax.sound.midi.InvalidMidiDataException e) {
            e.printStackTrace();
        }
	// write file
        try {
            File file = new File(filePath);
            MidiSystem.write(tempSeq, 1, file);
            if (debug) {
                System.out.println("MIDI file written");
            }
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Specify the MIDI device to be used for score playback.
     *
     * @param deviceNumber The id of the MIDI output as returned from getMidiDeviceInfo()
     */
    public void setMidiDeviceOutput(int deviceNumber) {
        try {
            System.out.println("=== Opening MIDI output device ====");
            MidiDevice.Info[] midiDeviceInfo = MidiSystem.getMidiDeviceInfo();
            // close other devices
            /*
            for (int i=0; i<midiDeviceInfo.length; i++) {
            if (i != deviceNumber && MidiSystem.getMidiDevice(midiDeviceInfo[i]).isOpen()) {
            MidiSystem.getMidiDevice(midiDeviceInfo[i]).close();
            }
            }
             */
            // open selected device
            if (!MidiSystem.getMidiDevice(midiDeviceInfo[deviceNumber]).isOpen()) {
                MidiSystem.getMidiDevice(midiDeviceInfo[deviceNumber]).open();
            }
            // make connection to external device
            MidiDevice md = MidiSystem.getMidiDevice(midiDeviceInfo[deviceNumber]);
            Receiver rec = md.getReceiver();
            Transmitter seqTrans = sequencer.getTransmitter();
            seqTrans.setReceiver(rec);
            /*
            MidiSystem.getMidiDevice(midiDeviceInfo[deviceNumber]).open();
            MidiSystem.getTransmitter().setReceiver(MidiSystem.getMidiDevice(midiDeviceInfo[deviceNumber]).getReceiver());
            sequencer.getTransmitter().setReceiver(MidiSystem.getMidiDevice(midiDeviceInfo[deviceNumber]).getReceiver()); // working?
             */
            System.out.println("MIDI output is now directed to: " + midiDeviceInfo[deviceNumber].getName());

        } catch (javax.sound.midi.MidiUnavailableException mue) {
            System.out.println("SoundCipher error: in setMidiDeviceOutput() ");
            mue.printStackTrace();
        }
    }

    /**
     * Register a listener with Processing to parse scheduled callbacks generated by
     * the score when played. The program needs to override the method;

     * void handleCallbacks(int eventID);

     * which is called each time a callback is triggered during score playback.
     * EventIDs are used to distinguish between different callback types and are
     * allocated at the programmers discretion.
     *
     * @param pa The Processing Applet object
     */
    public void addCallbackListener(PApplet pa) {
        this.pApplet = pa;
    }

    /**
     * The MetaMessage callback handler.
     * Parses callback from events when the score is played.
     *
     * @param message The MetaMessage object passed from JavaSound during sequence playback
     */
    public void meta(MetaMessage message) {
        if (message.getType() == 47) {  // 47 is end of track
            if (repeat == -1) {
                repeatCounter = repeatCounter + 1;
		update();
                sequencer.setMicrosecondPosition(0l);
                sequencer.setTempoInBPM((float) this.tempo);
                sequencer.start();
            } else {
                playing = false;
            }
        }
        if (message.getType() == 70) {
            if (pApplet != null) {
                Class pClass = pApplet.getClass();
                try {
                    Method[] methods = pClass.getDeclaredMethods();
                    for (int i = 0; i < methods.length; i++) {
                        if (methods[i].getName().equals("handleCallbacks")) {
                            methods[i].invoke(pApplet, new Byte((message.getData())[0]).intValue());
                        }
                    }
                } catch (java.lang.Exception e) {
                    System.out.println("SoundCipher error: the handleCallbacks(int eventId) method may not be declared." + e);
                }
            } else {
                System.out.println("SoundCipher error: event scheduling not initated, call addCallbackListener(PApplet pApplet)");
            }
            if (debug) {
                System.out.println("got meta message " + message.getType() + " data: " +
                        new Byte((message.getData())[0]).intValue());
            }
        }
    }
    /**
     * Exit elegantly when required by closing all active processes.
     */
    /*
    public void close() {
    if (debug) System.out.println("Close SCScore!!");
    this.stop();
    this.empty();
    sequencer.close();
    sequencer = null;
    seq = null;
    }
     */
    /**
     * Respond to a finalize() call if sent from Java by calling {@close}
     */
    /*
    public void finalize() {
    if (debug) System.out.println("finalize SCScore!!");
    this.close();
    }
     */
}


text:
"""This module contains the configuration manager."""
import os
import glob
import itertools
from pkg_resources import iter_entry_points

class ConfigurationManager:

    """Class for managing, loading, etc. one or several configuration files."""

    @staticmethod
    def load_single(path):
        """
        Return a configuration file object returned by the correct loader.

        The correct configuration file loader is guessed based on the file's extension.

        """
        # If the file doesn't exist, don't bother doing anything with it.
        if not os.path.isfile(path):
            raise FileNotFoundError('The file "%s" does not exist!' % path)

        # Grab the extension from the path.
        extension = os.path.splitext(path)[1]

        if extension in ['', '.']:
            raise IOError('A file without an extension can\'t be loaded!')

        extension = extension[:0] + extension[(0+1):]

        # Attempt to find an entry point named after this extension
        entry_points = list(iter_entry_points(group='ballercfg.extension_loaders', name=extension))

        # If our list of entry points is empty, throw an error
        if not entry_points:
            raise IOError('No loader was found for a file with the extension "%s"!' % extension)

        # Fetch configuration loader from entry point
        loader = entry_points[0].load()

        # Return configuration file loader instance
        return loader(path)

    @staticmethod
    def load(paths):
        """Return an instance of `MultiConfigurationFile` containing `paths`."""
        from ballercfg.multi_configuration_file import MultiConfigurationFile

        # If paths is a string turn it into a list so we can easily load one or multiple directories
        if isinstance(paths, str):
            paths = [paths]

        files = [glob.glob(p) for p in paths]
        files = list(itertools.chain.from_iterable(files))

        return MultiConfigurationFile(files)

class AbstractConfigurationFile:

    """
    This class exposes the contents of a configuration file.

    It handles loading of the configuration file and fetching the values of variables.

    """

    def __init__(self, path):
        """
        Construct an instance of this class with a `path` to a file.

        The contents of the specified file are also immediately loaded.

        """
        self.load(path)

    @property
    def path(self):
        """Return the path to the configuration."""
        return self._path

    @path.setter
    def path(self, value):
        """Set the path to the configuration file."""
        self._path = value

    @property
    def data(self):
        """Return a dict containing configuration file data."""
        return self._data

    @data.setter
    def data(self, value):
        """Set a dict containing configuration file data."""
        self._data = value

    def load(self, path):
        """
        Load a configuration file into this instance.

        This method should be used with caution, as no checks are done to ensure
        the file loaded actually exists and is formatted correctly.

        """
        self.path = path
        self.reload()

    def reload(self):
        """
        Reload the contents of the configuration file.

        This is an abstract method, you should implement your own.

        You should probably call the `post_reload` method after your logic here
        so the data you load can be processed properly.

        """
        raise NotImplementedError(
            'All (indirect) derivatives of `AbstractConfigurationFile` must implement a `reload` method.')

    def get(self, key, default=None):
        """
        Fetch the value of `key`.

        If a value with such a key was not set, the value of `default` is returned.

        """
        value = self.data

        try:
            for k in key.split('.'):
                value = value[k]
        except (KeyError, TypeError):
            return default

        return value

redpajama_set_name: RedPajamaGithub


text:
@extends('layouts/default')

@section('main')
	Looks like it works.
@stop


text:
<?php
namespace Mw\Metamorph;

use TYPO3\Flow\Core\Bootstrap;
use TYPO3\Flow\Package\Package as BasePackage;

class Package extends BasePackage {

	/**
	 * Invokes custom PHP code directly after the package manager has been initialized.
	 *
	 * @param \TYPO3\Flow\Core\Bootstrap $bootstrap The current bootstrap
	 * @return void
	 */
	public function boot(Bootstrap $bootstrap) {
		/** @noinspection PhpIncludeInspection */
		require_once FLOW_PATH_PACKAGES . '/Libraries/nikic/php-parser/lib/bootstrap.php';
	}
}


text:
#import "WMGaugeView.h"

/* Scale conversion macro from [0-1] range to view  real size range */
#define FULL_SCALE(x,y)    (x)*self.bounds.size.width, (y)*self.bounds.size.height

@implementation WMGaugeView
{
    /* Drawing rects */
    CGRect fullRect;
    CGRect innerRimRect;
    CGRect innerRimBorderRect;
    CGRect faceRect;
    CGRect rangeLabelsRect;
    CGRect scaleRect;

    /* View center */
    CGPoint center;

    /* Scale variables */
    CGFloat scaleRotation;
    CGFloat divisionValue;
    CGFloat subdivisionValue;
    CGFloat subdivisionAngle;

    /* Background image */
    UIImage *background;

    /* Needle layer */
    CALayer *rootNeedleLayer;

    /* Annimation completion */
    void (^animationCompletion)(BOOL);
}

#pragma mark - Initialization

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self initialize];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self initialize];
}

/**
 *  Set all properties to default values
 *  Set all private variables to default values
 */
- (void)initialize;
{
    _style = nil;
    _showInnerRim = NO;
    _showInnerBackground = YES;
    _innerRimWidth = 0.05;
    _innerRimBorderWidth = 0.005;

    _scalePosition = 0.025;
    _scaleStartAngle = 30.0;
    _scaleEndAngle = 330.0;
    _scaleDivisions = 12.0;
    _scaleSubdivisions = 10.0;
    _showScale = YES;
    _showScaleShadow = YES;
    _showScaleValues = YES;
    _scalesubdivisionsAligment = WMGaugeViewSubdivisionsAlignmentTop;
    _scaleDivisionsLength = 0.045;
    _scaleDivisionsWidth = 0.01;
    _scaleSubdivisionsLength = 0.015;
    _scaleSubdivisionsWidth = 0.01;

    _value = 0.0;
    _minValue = 0.0;
    _maxValue = 240.0;

    background = nil;

    _showRangeLabels = NO;
    _rangeLabelsWidth = 0.05;
    _rangeLabelsFont = [UIFont fontWithName:@"Helvetica" size:0.05];
    _adjustRangeLabelSizeToFitWidth = NO;
    _rangeLabelsFontColor = [UIColor whiteColor];
    _rangeLabelsFontKerning = 1.0;
    _rangeValues = nil;
    _rangeColors = nil;
    _rangeLabels = nil;

    _scaleDivisionColor = RGB(68, 84, 105);
    _scaleSubDivisionColor = RGB(217, 217, 217);

    _scaleFont = nil;

    _unitOfMeasurementVerticalOffset = 0.6;
    _unitOfMeasurementColor = [UIColor whiteColor];
    _unitOfMeasurementFont = [UIFont fontWithName:@"Helvetica" size:0.04];
    _unitOfMeasurement = @"";
    _showUnitOfMeasurement = NO;

    animationCompletion = nil;

    [self initDrawingRects];
    [self initScale];
}

/**
 *  Initialize all drawing rects and center point
 */
- (void)initDrawingRects
{
    center = CGPointMake(0.5, 0.5);
    fullRect = CGRectMake(0.0, 0.0, 1.0, 1.0);

    _innerRimBorderWidth = _showInnerRim ? _innerRimBorderWidth : 0.0;
    _innerRimWidth = _showInnerRim ? _innerRimWidth : 0.0;

    innerRimRect = fullRect;
    innerRimBorderRect = CGRectMake(innerRimRect.origin.x + _innerRimBorderWidth,
                                    innerRimRect.origin.y + _innerRimBorderWidth,
                                    innerRimRect.size.width - 2 * _innerRimBorderWidth,
                                    innerRimRect.size.height - 2 * _innerRimBorderWidth);
    faceRect = CGRectMake(innerRimRect.origin.x + _innerRimWidth,
                          innerRimRect.origin.y + _innerRimWidth,
                          innerRimRect.size.width - 2 * _innerRimWidth,
                          innerRimRect.size.height - 2 * _innerRimWidth);
    rangeLabelsRect = CGRectMake(faceRect.origin.x + (_showRangeLabels ? _rangeLabelsWidth : 0.0),
                                 faceRect.origin.y + (_showRangeLabels ? _rangeLabelsWidth : 0.0),
                                 faceRect.size.width - 2 * (_showRangeLabels ? _rangeLabelsWidth : 0.0),
                                 faceRect.size.height - 2 * (_showRangeLabels ? _rangeLabelsWidth : 0.0));
    scaleRect = CGRectMake(rangeLabelsRect.origin.x + _scalePosition,
                           rangeLabelsRect.origin.y + _scalePosition,
                           rangeLabelsRect.size.width - 2 * _scalePosition,
                           rangeLabelsRect.size.height - 2 * _scalePosition);
}

#pragma mark - Drawing

/**
 * Main drawing entry point
 */
- (void)drawRect:(CGRect)rect
{
    if (background == nil)
    {
        // Create image context
        UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
        CGContextRef context = UIGraphicsGetCurrentContext();

        // Scale context for [0-1] drawings
        CGContextScaleCTM(context, rect.size.width , rect.size.height);

        // Draw gauge background in image context
        [self drawGauge:context];

        // Save background
        background = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

    // Drawing background in view
    [background drawInRect:rect];

    if (rootNeedleLayer == nil)
    {
        // Initialize needle layer
        rootNeedleLayer = [CALayer new];

        // For performance puporse, the needle layer is not scaled to [0-1] range
        rootNeedleLayer.frame = self.bounds;
        [self.layer addSublayer:rootNeedleLayer];

        // Draw needle
        [self drawNeedle];

        // Set needle current value
        [self setValue:_value animated:NO];
    }
}

/**
 *  Gauge background drawing
 */
- (void)drawGauge:(CGContextRef)context
{
    [self drawRim:context];

    if (_showInnerBackground)
        [self drawFace:context];

    if (_showUnitOfMeasurement)
        [self drawText:context];

    if (_showScale)
        [self drawScale:context];

    if (_showRangeLabels)
        [self drawRangeLabels:context];
}

/**
 *  Gauge external rim drawing
 */
- (void)drawRim:(CGContextRef)context
{
    // TODO
}

/**
 *  Gauge inner background drawing
 */
- (void)drawFace:(CGContextRef)context
{
    if ([_style conformsToProtocol:@protocol(WMGaugeViewStyle)]) {
        [_style drawFaceWithContext:context inRect:faceRect];
    }
}

/**
 *  Unit of measurement drawing
 */
- (void)drawText:(CGContextRef)context
{
    CGContextSetShadow(context, CGSizeMake(0.05, 0.05), 2.0);
    UIFont* font = _unitOfMeasurementFont ? _unitOfMeasurementFont : [UIFont fontWithName:@"Helvetica" size:0.04];
    UIColor* color = _unitOfMeasurementColor ? _unitOfMeasurementColor : [UIColor whiteColor];
    NSDictionary* stringAttrs = @{ NSFontAttributeName : font, NSForegroundColorAttributeName : color };
    NSAttributedString* attrStr = [[NSAttributedString alloc] initWithString:_unitOfMeasurement attributes:stringAttrs];
    CGSize fontWidth;
    fontWidth = [_unitOfMeasurement sizeWithAttributes:stringAttrs];

    [attrStr drawAtPoint:CGPointMake(0.5 - fontWidth.width / 2.0, _unitOfMeasurementVerticalOffset)];
}

/**
 * Scale drawing
 */
- (void)drawScale:(CGContextRef)context
{
    CGContextSaveGState(context);
    [self rotateContext:context fromCenter:center withAngle:DEGREES_TO_RADIANS(180 + _scaleStartAngle)];

    int totalTicks = _scaleDivisions * _scaleSubdivisions + 1;
    for (int i = 0; i < totalTicks; i++)
    {
        CGFloat offset = 0.0;
        if (_scalesubdivisionsAligment == WMGaugeViewSubdivisionsAlignmentCenter) offset = (_scaleDivisionsLength - _scaleSubdivisionsLength) / 2.0;
        if (_scalesubdivisionsAligment == WMGaugeViewSubdivisionsAlignmentBottom) offset = _scaleDivisionsLength - _scaleSubdivisionsLength;

        CGFloat y1 = scaleRect.origin.y;
        CGFloat y2 = y1 + _scaleSubdivisionsLength;
        CGFloat y3 = y1 + _scaleDivisionsLength;

        float value = [self valueForTick:i];
        float div = (_maxValue - _minValue) / _scaleDivisions;
        float mod = (int)value % (int)div;

        // Division
        if ((fabsf(mod - 0) < 0.000001) || (fabsf(mod - div) < 0.000001))
        {
            // Initialize Core Graphics settings
            UIColor *color = (_rangeValues && _rangeColors) ? [self rangeColorForValue:value] : _scaleDivisionColor;
            CGContextSetStrokeColorWithColor(context, color.CGColor);
            CGContextSetLineWidth(context, _scaleDivisionsWidth);
            CGContextSetShadow(context, CGSizeMake(0.05, 0.05), _showScaleShadow ? 2.0 : 0.0);

            // Draw tick
            CGContextMoveToPoint(context, 0.5, y1);
            CGContextAddLineToPoint(context, 0.5, y3);
            CGContextStrokePath(context);

            // Draw label
            if(_showScaleValues) {
                NSString *valueString = [NSString stringWithFormat:@"%0.0f",value];
                UIFont* font = _scaleFont ? _scaleFont : [UIFont fontWithName:@"Helvetica-Bold" size:0.05];
                NSDictionary* stringAttrs = @{ NSFontAttributeName : font, NSForegroundColorAttributeName : color };
                NSAttributedString* attrStr = [[NSAttributedString alloc] initWithString:valueString attributes:stringAttrs];
                CGSize fontWidth;
                fontWidth = [valueString sizeWithAttributes:stringAttrs];

                [attrStr drawAtPoint:CGPointMake(0.5 - fontWidth.width / 2.0, y3 + 0.005)];
            }
        }
        // Subdivision
        else
        {
            // Initialize Core Graphics settings
            UIColor *color = (_rangeValues && _rangeColors) ? [self rangeColorForValue:value] : _scaleSubDivisionColor;
            CGContextSetStrokeColorWithColor(context, color.CGColor);
            CGContextSetLineWidth(context, _scaleSubdivisionsWidth);
            CGContextMoveToPoint(context, 0.5, y1);
            if (_showScaleShadow) CGContextSetShadow(context, CGSizeMake(0.05, 0.05), 2.0);

            // Draw tick
            CGContextMoveToPoint(context, 0.5, y1 + offset);
            CGContextAddLineToPoint(context, 0.5, y2 + offset);
            CGContextStrokePath(context);
        }

        // Rotate to next tick
        [self rotateContext:context fromCenter:center withAngle:DEGREES_TO_RADIANS(subdivisionAngle)];
    }
    CGContextRestoreGState(context);
}

/**
 * scale range labels drawing
 */
- (void)drawRangeLabels:(CGContextRef)context
{
    CGContextSaveGState(context);
    [self rotateContext:context fromCenter:center withAngle:DEGREES_TO_RADIANS(90 + _scaleStartAngle)];
    CGContextSetShadow(context, CGSizeMake(0.0, 0.0), 0.0);

    CGFloat maxAngle = _scaleEndAngle - _scaleStartAngle;
    CGFloat lastStartAngle = 0.0f;

    for (int i = 0; i < _rangeValues.count; i ++)
    {
        // Range value
        float value = ((NSNumber*)[_rangeValues objectAtIndex:i]).floatValue;
        float valueAngle = (value - _minValue) / (_maxValue - _minValue) * maxAngle;

        // Range curved shape
        UIBezierPath *path = [UIBezierPath bezierPath];
        [path addArcWithCenter:center radius:rangeLabelsRect.size.width / 2.0 startAngle:DEGREES_TO_RADIANS(lastStartAngle) endAngle:DEGREES_TO_RADIANS(valueAngle) - 0.01 clockwise:YES];

        UIColor *color = _rangeColors[i];
        [color setStroke];
        path.lineWidth = _rangeLabelsWidth;
        [path stroke];

        // Range curved label
        [self drawStringAtContext:context string:(NSString*)_rangeLabels[i] withCenter:center radius:rangeLabelsRect.size.width / 2.0 startAngle:DEGREES_TO_RADIANS(lastStartAngle) endAngle:DEGREES_TO_RADIANS(valueAngle)];

        lastStartAngle = valueAngle;
    }

    CGContextRestoreGState(context);
}

/**
 * Needle drawing
 */
- (void)drawNeedle
{
    if ([_style conformsToProtocol:@protocol(WMGaugeViewStyle)]) {
        [_style drawNeedleOnLayer:rootNeedleLayer inRect:self.bounds];
    }
}

#pragma mark - Tools

/**
 * Core Graphics rotation in context
 */
- (void)rotateContext:(CGContextRef)context fromCenter:(CGPoint)center_ withAngle:(CGFloat)angle
{
    CGContextTranslateCTM(context, center_.x, center_.y);
    CGContextRotateCTM(context, angle);
    CGContextTranslateCTM(context, -center_.x, -center_.y);
}

/**
 * Needle angle computation
 */
- (CGFloat)needleAngleForValue:(double)value
{
    return DEGREES_TO_RADIANS(_scaleStartAngle + (value - _minValue) / (_maxValue - _minValue) * (_scaleEndAngle - _scaleStartAngle)) + M_PI;
}

/**
 * Initialize scale helper values
 */
- (void)initScale
{
    scaleRotation = (int)(_scaleStartAngle + 180) % 360;
    divisionValue = (_maxValue - _minValue) / _scaleDivisions;
    subdivisionValue = divisionValue / _scaleSubdivisions;
    subdivisionAngle = (_scaleEndAngle - _scaleStartAngle) / (_scaleDivisions * _scaleSubdivisions);
}

/**
 * Scale tick value computation
 */
- (float)valueForTick:(int)tick
{
    return tick * (divisionValue / _scaleSubdivisions) + _minValue;
}

/**
 * Scale range label color for value
 */
- (UIColor*)rangeColorForValue:(float)value
{
    NSInteger length = _rangeValues.count;
    for (int i = 0; i < length - 1; i++)
    {
        if (value < [_rangeValues[i] floatValue])
            return _rangeColors[i];
    }
    if (value <= [_rangeValues[length - 1] floatValue])
        return _rangeColors[length - 1];
    return nil;
}

/**
 * Draw curved NSSring in context
 */
- (void)drawStringAtContext:(CGContextRef) context string:(NSString*)text withCenter:(CGPoint)center_ radius:(CGFloat)radius startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle
{
    CGContextSaveGState(context);

    UIFont* font = _rangeLabelsFont ? _rangeLabelsFont : [UIFont fontWithName:@"Helvetica" size:0.05];
    UIColor* color = _rangeLabelsFontColor ? _rangeLabelsFontColor : [UIColor whiteColor];

    //add extra character to ensure there is some padding
    NSString* testText = [text stringByAppendingString:@"$"];
    while(_adjustRangeLabelSizeToFitWidth) {

        CGFloat maxWidth = radius * (endAngle - startAngle);
        CGSize textSize = [testText boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX)
                                      options:NSStringDrawingUsesLineFragmentOrigin
                                   attributes:@{NSFontAttributeName: font}
                                       context:nil].size;

        if(textSize.height < _rangeLabelsWidth) {
            break;
        }

        font = [font fontWithSize:font.pointSize * 0.9];
    }

    NSDictionary* stringAttrs = @{ NSFontAttributeName : font, NSForegroundColorAttributeName : color };
    CGSize textSize = [text sizeWithAttributes:stringAttrs];

    float perimeter = 2 * M_PI * radius;
    float textAngle = textSize.width / perimeter * 2 * M_PI * _rangeLabelsFontKerning;
    float offset = ((endAngle - startAngle) - textAngle) / 2.0;

    float letterPosition = 0;
    NSString *lastLetter = @"";

    [self rotateContext:context fromCenter:center withAngle:startAngle + offset];
    for (int index = 0; index < [text length]; index++)
    {
        NSRange range = {index, 1};
        NSString* letter = [text substringWithRange:range];
        NSAttributedString* attrStr = [[NSAttributedString alloc] initWithString:letter attributes:stringAttrs];
        CGSize charSize = [letter sizeWithAttributes:stringAttrs];
        float totalWidth = [[NSString stringWithFormat:@"%@%@",lastLetter, letter] sizeWithAttributes:stringAttrs].width;
        float currentLetterWidth = [letter sizeWithAttributes:stringAttrs].width;
        float lastLetterWidth = [lastLetter sizeWithAttributes:stringAttrs].width;
        float kerning = (lastLetterWidth) ? 0.0 : ((currentLetterWidth + lastLetterWidth) - totalWidth);

        letterPosition += (charSize.width / 2) - kerning;
        float angle = (letterPosition / perimeter * 2 * M_PI) * _rangeLabelsFontKerning;
        CGPoint letterPoint = CGPointMake((radius - charSize.height / 2.0) * cos(angle) + center_.x, (radius - charSize.height / 2.0) * sin(angle) + center_.y);

        CGContextSaveGState(context);
        CGContextTranslateCTM(context, letterPoint.x, letterPoint.y);
        CGAffineTransform rotationTransform = CGAffineTransformMakeRotation(angle + M_PI_2);
        CGContextConcatCTM(context, rotationTransform);
        CGContextTranslateCTM(context, -letterPoint.x, -letterPoint.y);

        [attrStr drawAtPoint:CGPointMake(letterPoint.x - charSize.width/2 , letterPoint.y - charSize.height)];

        CGContextRestoreGState(context);

        letterPosition += charSize.width / 2;
        lastLetter = letter;
    }
    CGContextRestoreGState(context);
}

/**
 * Invalidate background
 * Background will be regenerated during next draw rect
 */
- (void)invalidateBackground
{
    background = nil;
    [self initDrawingRects];
    [self initScale];
    [self setNeedsDisplay];
}

/**
 * Invalidate Needle
 * Needle will be regenerated during next draw rect
 */
- (void)invalidateNeedle
{
    [rootNeedleLayer removeAllAnimations];
    rootNeedleLayer.sublayers = nil;
    rootNeedleLayer = nil;

    [self setNeedsDisplay];
}

#pragma mark - Value update

/**
 * Update gauge value
 */
- (void)updateValue:(float)value
{
    // Clamp value if out of range
    if (value > _maxValue)
        value = _maxValue;
    else if (value < _minValue)
        value = _minValue;
    else
        value = value;

    // Set value
    _value = value;
}

/**
 * Update gauge value with animation
 */
- (void)setValue:(float)value animated:(BOOL)animated
{
    [self setValue:value animated:animated duration:0.8];
}

/**
 * Update gauge value with animation and fire a completion block
 */
- (void)setValue:(float)value animated:(BOOL)animated completion:(void (^)(BOOL finished))completion
{
    [self setValue:value animated:animated duration:0.8 completion:completion];
}

/**
 * Update gauge value with animation and duration
 */
- (void)setValue:(float)value animated:(BOOL)animated duration:(NSTimeInterval)duration
{
    [self setValue:value animated:animated duration:duration completion:nil];
}

/**
 * Update gauge value with animation, duration and fire a completion block
 */
- (void)setValue:(float)value animated:(BOOL)animated duration:(NSTimeInterval)duration completion:(void (^)(BOOL finished))completion
{
    animationCompletion = completion;

    double lastValue = _value;

    [self updateValue:value];
    double middleValue = lastValue + (((lastValue + (_value - lastValue) / 2.0) >= 0) ? (_value - lastValue) / 2.0 : (lastValue - _value) / 2.0);

    // Needle animation to target value
    // An intermediate "middle" value is used to make sure the needle will follow the right rotation direction

    CAKeyframeAnimation * animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.removedOnCompletion = YES;
    animation.duration = animated ? duration : 0.0;
    animation.delegate = (id<CAAnimationDelegate>)self;
    animation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeRotation([self needleAngleForValue:lastValue]  , 0, 0, 1.0)],
                         [NSValue valueWithCATransform3D:CATransform3DMakeRotation([self needleAngleForValue:middleValue], 0, 0, 1.0)],
                         [NSValue valueWithCATransform3D:CATransform3DMakeRotation([self needleAngleForValue:_value]     , 0, 0, 1.0)]];

    if ([_style conformsToProtocol:@protocol(WMGaugeViewStyle)] == NO || [_style needleLayer:rootNeedleLayer willMoveAnimated:animated duration:duration animation:animation] == NO)
    {
        rootNeedleLayer.transform = [[animation.values lastObject] CATransform3DValue];
        [rootNeedleLayer addAnimation:animation forKey:kCATransition];
    }
}

#pragma mark - CAAnimation delegate

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if (animationCompletion)
        animationCompletion(flag);

    animationCompletion = nil;
}

#pragma mark - Properties

- (void)setValue:(float)value
{
    [self setValue:value animated:YES];
}

- (void)setShowInnerBackground:(bool)showInnerBackground
{
    _showInnerBackground = showInnerBackground;
    [self invalidateBackground];
}

- (void)setShowInnerRim:(bool)showInnerRim
{
    _showInnerRim = showInnerRim;
    [self invalidateBackground];
}

- (void)setInnerRimWidth:(CGFloat)innerRimWidth
{
    _innerRimWidth = innerRimWidth;
    [self invalidateBackground];
}

- (void)setInnerRimBordeWidth:(CGFloat)innerRimBorderWidth
{
    _innerRimBorderWidth = innerRimBorderWidth;
    [self invalidateBackground];
}

- (void)setScalePosition:(CGFloat)scalePosition
{
    _scalePosition = scalePosition;
    [self invalidateBackground];
}

- (void)setScaleStartAngle:(CGFloat)scaleStartAngle
{
    _scaleStartAngle = scaleStartAngle;
    [self invalidateBackground];
}

- (void)setScaleEndAngle:(CGFloat)scaleEndAngle
{
    _scaleEndAngle = scaleEndAngle;
    [self invalidateBackground];
}

- (void)setScaleDivisions:(CGFloat)scaleDivisions
{
    _scaleDivisions = scaleDivisions;
    [self invalidateBackground];
}

- (void)setScaleSubdivisions:(CGFloat)scaleSubdivisions
{
    _scaleSubdivisions = scaleSubdivisions;
    [self invalidateBackground];
}

- (void)setShowScaleShadow:(bool)showScaleShadow
{
    _showScaleShadow = showScaleShadow;
    [self invalidateBackground];
}

- (void)setShowScale:(bool)showScale
{
    _showScale = showScale;
    [self invalidateBackground];
}

-(void)setShowScaleValues:(bool)showScaleValues {
    _showScaleValues = showScaleValues;
    [self invalidateBackground];
}

- (void)setScalesubdivisionsAligment:(WMGaugeViewSubdivisionsAlignment)scalesubdivisionsAligment
{
    _scalesubdivisionsAligment = scalesubdivisionsAligment;
    [self invalidateBackground];
}

- (void)setScaleDivisionsLength:(CGFloat)scaleDivisionsLength
{
    _scaleDivisionsLength = scaleDivisionsLength;
    [self invalidateBackground];
}

- (void)setScaleDivisionsWidth:(CGFloat)scaleDivisionsWidth
{
    _scaleDivisionsWidth = scaleDivisionsWidth;
    [self invalidateBackground];
}

- (void)setScaleSubdivisionsLength:(CGFloat)scaleSubdivisionsLength
{
    _scaleSubdivisionsLength = scaleSubdivisionsLength;
    [self invalidateBackground];
}

- (void)setScaleSubdivisionsWidth:(CGFloat)scaleSubdivisionsWidth
{
    _scaleSubdivisionsWidth = scaleSubdivisionsWidth;
    [self invalidateBackground];
}

- (void)setScaleDivisionColor:(UIColor *)scaleDivisionColor
{
    _scaleDivisionColor = scaleDivisionColor;
    [self invalidateBackground];
}

- (void)setScaleSubDivisionColor:(UIColor *)scaleSubDivisionColor
{
    _scaleSubDivisionColor = scaleSubDivisionColor;
    [self invalidateBackground];
}

- (void)setScaleFont:(UIFont *)scaleFont
{
    _scaleFont = scaleFont;
    [self invalidateBackground];
}

- (void)setRangeLabelsWidth:(CGFloat)rangeLabelsWidth
{
    _rangeLabelsWidth = rangeLabelsWidth;
    [self invalidateBackground];
}

- (void)setMinValue:(float)minValue
{
    _minValue = minValue;
    [self invalidateBackground];
}

- (void)setMaxValue:(float)maxValue
{
    _maxValue = maxValue;
    [self invalidateBackground];
}

- (void)setRangeValues:(NSArray *)rangeValues
{
    _rangeValues = rangeValues;
    [self invalidateBackground];
}

- (void)setRangeColors:(NSArray *)rangeColors
{
    _rangeColors = rangeColors;
    [self invalidateBackground];
}

- (void)setRangeLabels:(NSArray *)rangeLabels
{
    _rangeLabels = rangeLabels;
    [self invalidateBackground];
}

- (void)setUnitOfMeasurement:(NSString *)unitOfMeasurement
{
    _unitOfMeasurement = unitOfMeasurement;
    [self invalidateBackground];
}

- (void)setShowUnitOfMeasurement:(bool)showUnitOfMeasurement
{
    _showUnitOfMeasurement = showUnitOfMeasurement;
    [self invalidateBackground];
}

- (void)setShowRangeLabels:(bool)showRangeLabels
{
    _showRangeLabels = showRangeLabels;
    [self invalidateBackground];
}

- (void)setRangeLabelsFontKerning:(CGFloat)rangeLabelsFontKerning
{
    _rangeLabelsFontKerning = rangeLabelsFontKerning;
    [self invalidateBackground];
}

- (void)setUnitOfMeasurementFont:(UIFont *)unitOfMeasurementFont
{
    _unitOfMeasurementFont = unitOfMeasurementFont;
    [self invalidateBackground];
}

- (void)setRangeLabelsFont:(UIFont *)rangeLabelsFont
{
    _rangeLabelsFont = rangeLabelsFont;
    [self invalidateBackground];
}

- (void)setUnitOfMeasurementVerticalOffset:(CGFloat)unitOfMeasurementVerticalOffset
{
    _unitOfMeasurementVerticalOffset = unitOfMeasurementVerticalOffset;
    [self invalidateBackground];
}

- (void)setUnitOfMeasurementColor:(UIColor *)unitOfMeasurementColor
{
    _unitOfMeasurementColor = unitOfMeasurementColor;
    [self invalidateBackground];
}

- (void)setRangeLabelsFontColor:(UIColor *)rangeLabelsFontColor
{
    _rangeLabelsFontColor = rangeLabelsFontColor;
    [self invalidateBackground];
}

- (void)setStyle:(id<WMGaugeViewStyle>)style {
    _style = style;
    [self invalidateBackground];
    [self invalidateNeedle];
}

@end


text:
using System.Reflection;

namespace LottieUWP.Tests
{
    sealed partial class App
    {
        protected override void OnInitializeRunner()
        {
            AddTestAssembly(GetType().GetTypeInfo().Assembly);
        }
    }
}


text: from .snapshot import make_snapshot


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Distrubute Social Network</title>

  <link href="{{url_for('static',filename='css/bootstrap.min.css')}}" rel="stylesheet">
  <link href="{{url_for('static',filename='css/main.css')}}" rel="stylesheet">

  <link href="{{url_for('static',filename='css/struct.css')}}" rel="stylesheet">
  <link href="{{url_for('static',filename='css/permission.css')}}" rel="stylesheet">
  <link href="{{url_for('static',filename='css/mypost.css')}}" rel="stylesheet">
  <link href="{{url_for('static',filename='css/bootstrap-markdown.min.css')}}" rel="stylesheet">

  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
              Toggle navigation

            </button>
            Brand

Stream

Post

              {%if session.logged_in%}

                Circles

Search Author

View Circles

One more separated link

              {%endif%}

            <form class="navbar-form navbar-left">

                <input type="text" class="form-control" placeholder="Author Name" id="search_input">

              <button type="submit" class="btn btn-default" id="search_button"></button>
            </form>

              {%if not session.logged_in%}

<button id ="modal_bt" class="btn btn-default navbar-btn" data-toggle="modal" data-target="#myModal">Login</button>

              {%else%}

                Message {{ msgCount }}
                {%endif%}

Clear All

                {%if not session.logged_in%}

Guest

                {%else%}
                {{session.logged_in}}
                {%endif%}

{%if session.admin_model%}

Admin
{%endif%}

Change Password

Change Setting

Logout

              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Change your Password

              <form class="form-horizontal" id="change_pwd_form" method="post">

                      Password

                        <input type="password" id="change_pwd" class="form-control" name="register_pwd" placeholder="Password">

                      Retype Password

                        <input type="password" class="form-control" name ="re_pwd" id="re_pwd" placeholder="Password">

              </form>

              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button type="button" class="btn btn-primary" id="submit_new_pwd">Save changes</button>

              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×
              </button>

Welcome

              <form id="login_form"  class ="form-horizontal" action="{{url_for('login')}}" method="post">

                  Author Name:
                  <input type="text" class="form-control" name="username" id="login_username" placeholder="Enter Author Name" autofocus>

                  Password:
                  <input type="password" class="form-control" name="password" id="login_password" placeholder="Password" required>
                  Sign in with GitHub

              </form>
              <form class="form-horizontal" id="register_form" method="post" enctype="multipart/form-data">

Required Information

                      Email

                        <input type="email" class="form-control" id="email" name="email" placeholder="Email">

                      Author Name

                        <input type="text" class="form-control" id="author_name" name="author_name" placeholder="Author Name">

                      Password

                        <input type="password" id="register_pwd" class="form-control" name="register_pwd" placeholder="Password">

                      Retype Password

                        <input type="password" class="form-control" name ="re_pwd" id="re_pwd" placeholder="Password">

                    <button type="button" class="btn btn-default btn-xs" id="switcher">

                    </button>
                    Personal Information (Option)

                      Nick Name

                        <input type="text" class="form-control" name="nick_name" placeholder="Nick Name">

                      Birthday

                        <input type="text" name ="birthday" id="datepicker" class="form-control" placeholder="Birthday">

                      Profile Upload

                        <input type="file" name="profile_image" id="profile">

Size of file is up to 5 MB

                      City

                        <input type="text" name ="city" id="city" class="form-control" placeholder="City" autocomplete="on">

                      Gender

                            <input type="radio" name ="gender" value="male">Male

                            <input type="radio" name ="gender" value="Female">Female

              </form>

              <button type="button" class="btn btn-default" id="re_button">Register</button>
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button type="button" class="btn btn-primary" id ="button_login" >Log in</button>

              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Add Authors

                      #
                      Author Name
                      Nick Name
                      Server Name

1	hello	world

«

»

                    <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>

          {%if session.logged_in%}

        {%endif%}
        {%if session.admin_model%}

        {%endif%}


text:
#ifndef statusview_curses_hh
#define statusview_curses_hh

#include <string>
#include <vector>

#include "view_curses.hh"

/**
 * Container for individual status values.
 */
class status_field {
public:
    /**
     * @param width The maximum width of the field in characters.
     * @param role The color role for this field, defaults to VCR_STATUS.
     */
    status_field(int width = 1, role_t role = role_t::VCR_STATUS)
        : sf_width(width), sf_role(role)
    {
    }

    virtual ~status_field() = default;

    /** @param value The new value for this field. */
    void set_value(std::string value);

    /**
     * Set the new value for this field using a formatted string.
     *
     * @param fmt The format string.
     * @param ... Arguments for the format.
     */
    status_field& set_value(const char* fmt, ...)
    {
        char buffer[256];
        va_list args;

        va_start(args, fmt);
        vsnprintf(buffer, sizeof(buffer), fmt, args);
        this->set_value(std::string(buffer));
        va_end(args);

        return *this;
    }

    void set_stitch_value(role_t left, role_t right);

    void set_left_pad(size_t val) { this->sf_left_pad = val; }

    size_t get_left_pad() const { return this->sf_left_pad; }

    /** @return The string value for this field. */
    attr_line_t& get_value() { return this->sf_value; }

    void right_justify(bool yes) { this->sf_right_justify = yes; }
    bool is_right_justified() const { return this->sf_right_justify; }

    status_field& set_cylon(bool yes)
    {
        this->sf_cylon = yes;
        return *this;
    }

    bool is_cylon() const { return this->sf_cylon; }

    void do_cylon();

    /** @return True if this field's value is an empty string. */
    bool empty() const { return this->sf_value.get_string().empty(); }

    void clear() { this->sf_value.clear(); }

    /** @param role The color role for this field. */
    void set_role(role_t role) { this->sf_role = role; }
    /** @return The color role for this field. */
    role_t get_role() const { return this->sf_role; }

    /** @param width The maximum display width, in characters. */
    void set_width(ssize_t width) { this->sf_width = width; }
    /** @param width The maximum display width, in characters. */
    ssize_t get_width() const { return this->sf_width; }

    /** @param width The maximum display width, in characters. */
    void set_min_width(int width) { this->sf_min_width = width; }
    /** @param width The maximum display width, in characters. */
    size_t get_min_width() const { return this->sf_min_width; }

    void set_share(int share) { this->sf_share = share; }

    int get_share() const { return this->sf_share; }

protected:
    ssize_t sf_width; /*< The maximum display width, in chars. */
    ssize_t sf_min_width{0}; /*< The minimum display width, in chars. */
    bool sf_right_justify{false};
    bool sf_cylon{false};
    ssize_t sf_cylon_pos{0};
    attr_line_t sf_value; /*< The value to display for this field. */
    role_t sf_role; /*< The color role for this field. */
    int sf_share{0};
    size_t sf_left_pad{0};
};

/**
 * Data source for the fields to be displayed in a status view.
 */
class status_data_source {
public:
    virtual ~status_data_source() = default;

    /**
     * @return The number of status_fields in this source.
     */
    virtual size_t statusview_fields() = 0;

    /**
     * Callback used to get a particular field.
     *
     * @param field The index of the field to return.
     * @return A reference to the field at the given index.
     */
    virtual status_field& statusview_value_for_field(int field) = 0;
};

/**
 * A view that displays a collection of fields in a line on the display.
 */
class statusview_curses : public view_curses {
public:
    void set_data_source(status_data_source* src) { this->sc_source = src; }
    status_data_source* get_data_source() { return this->sc_source; }

    void set_top(int top) { this->sc_top = top; }
    int get_top() const { return this->sc_top; }

    void set_window(WINDOW* win) { this->sc_window = win; }
    WINDOW* get_window() { return this->sc_window; }

    void set_enabled(bool value) { this->sc_enabled = value; }
    bool get_enabled() const { return this->sc_enabled; }

    void set_default_role(role_t role) { this->sc_default_role = role; }
    role_t get_default_role() const { return this->sc_default_role; }

    void window_change();

    void do_update() override;

private:
    status_data_source* sc_source{nullptr};
    WINDOW* sc_window{nullptr};
    int sc_top{0};
    bool sc_enabled{true};
    role_t sc_default_role{role_t::VCR_STATUS};
};

#endif


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

namespace Bar
{
	class Program
	{
		static void Main(string[] args)
		{
			int a = 3;
			int b = 5;
			Worker w = new Worker();
			int c = w.Add(a, b);

			Console.WriteLine("\nEnd.");
			Console.ReadKey();
			Console.WriteLine("bye bye...");
			Console.WriteLine("(c) by Günther");
		}
	}
}


text:
package com.hazelcast.simulator.agent.operations;

import com.hazelcast.simulator.protocol.operation.SimulatorOperation;

/**
 * Starts the timeout detection for {@link com.hazelcast.simulator.agent.workerprocess.WorkerProcess} on the Simulator Agent.
 */
public class StartTimeoutDetectionOperation implements SimulatorOperation {
    public StartTimeoutDetectionOperation() {
    }
}


text:
source "$(dirname "${BASH_SOURCE}")/../../hack/lib/init.sh"

# Check inputs
if [[ -z "${KUBECONFIG-}" ]]; then
  os::log::fatal "KUBECONFIG must be set to a root account"
fi
test_report_dir="${ARTIFACT_DIR}"
mkdir -p "${test_report_dir}"

cat <<END > "${test_report_dir}/README.md"
This conformance report is generated by the OpenShift CI infrastructure. The canonical source location for this test script is located at https://github.com/openshift/origin/blob/master/test/extended/conformance-k8s.sh

This file was generated by:

  Commit $( git rev-parse HEAD || "<commit>" )
  Tag    $( git describe || "<tag>" )

To recreate these results

1. Install an [OpenShift cluster](https://docs.openshift.com/container-platform/latest/install_config/install/advanced_install.html)
2. Retrieve a \`.kubeconfig\` file with administrator credentials on that cluster and set the environment variable KUBECONFIG

    export KUBECONFIG=PATH_TO_KUBECONFIG

3. Clone the OpenShift source repository and change to that directory:

    git clone https://github.com/openshift/origin.git
    cd origin

4. Place the \`oc\` binary for that cluster in your PATH
5. Run the conformance test:

    test/extended/conformance-k8s.sh

Nightly conformance tests are run against release branches and reported https://openshift-gce-devel.appspot.com/builds/origin-ci-test/logs/periodic-ci-origin-conformance-k8s/
END

version="${KUBERNETES_VERSION:-release-1.18}"
kubernetes="${KUBERNETES_ROOT:-${OS_ROOT}/../../../k8s.io/kubernetes}"
if [[ -d "${kubernetes}" ]]; then
  git fetch origin --tags
else
  if [[ -n "${KUBERNETES_ROOT-}" ]]; then
    os::log::fatal "Cannot find Kubernetes source directory, set KUBERNETES_ROOT"
  fi
  kubernetes="${OS_ROOT}/_output/components/kubernetes"
  if [[ ! -d "${kubernetes}" ]]; then
    mkdir -p "$( dirname "${kubernetes}" )"
    os::log::info "Cloning Kubernetes source"
    git clone "https://github.com/kubernetes/kubernetes.git" -b "${version}" "${kubernetes}" # --depth=1 unfortunately we need history info as well
  fi
fi

os::log::info "Running Kubernetes conformance suite for ${version}"

# Execute OpenShift prerequisites
# Disable container security
oc adm policy add-scc-to-group privileged system:authenticated system:serviceaccounts
oc adm policy remove-scc-from-group restricted system:authenticated
oc adm policy remove-scc-from-group anyuid system:cluster-admins
# Mark the master nodes as unschedulable so tests ignore them
oc get nodes -o name -l 'node-role.kubernetes.io/master' | xargs -L1 oc adm cordon
unschedulable="$( ( oc get nodes -o name -l 'node-role.kubernetes.io/master'; ) | wc -l )"
# TODO: undo these operations

# Execute Kubernetes prerequisites
pushd "${kubernetes}" > /dev/null
git checkout "${version}"
make WHAT=cmd/kubectl
make WHAT=test/e2e/e2e.test
make WHAT=vendor/github.com/onsi/ginkgo/ginkgo
export PATH="${kubernetes}/_output/local/bin/$( os::build::host_platform ):${PATH}"

kubectl version  > "${test_report_dir}/version.txt"
echo "-----"    >> "${test_report_dir}/version.txt"
oc version      >> "${test_report_dir}/version.txt"

# Run the test, serial tests first, then parallel

rc=0

ginkgo \
  -nodes 1 -noColor '-focus=(\[Conformance\].*\[Serial\]|\[Serial\].*\[Conformance\])' $( which e2e.test ) -- \
  -report-dir "${test_report_dir}" \
  -allowed-not-ready-nodes ${unschedulable} \
  2>&1 | tee -a "${test_report_dir}/e2e.log" || rc=1

rename -v junit_ junit_serial_ ${test_report_dir}/junit*.xml

ginkgo \
  -nodes 4 -noColor '-skip=\[Serial\]' '-focus=\[Conformance\]' $( which e2e.test ) -- \
  -report-dir "${test_report_dir}" \
  -allowed-not-ready-nodes ${unschedulable} \
  2>&1 | tee -a "${test_report_dir}/e2e.log" || rc=1

echo
echo "Run complete, results in ${test_report_dir}"

exit $rc


text:
namespace autofill {
class AddressAccessoryController;
class CreditCardAccessoryController;
}  // namespace autofill

class PasswordAccessoryController;

// Use ManualFillingController::GetOrCreate to obtain instances of this class.
class ManualFillingControllerImpl
    : public ManualFillingController,
      public content::WebContentsUserData<ManualFillingControllerImpl>,
      public base::trace_event::MemoryDumpProvider {
 public:
  ManualFillingControllerImpl(const ManualFillingControllerImpl&) = delete;
  ManualFillingControllerImpl& operator=(const ManualFillingControllerImpl&) =
      delete;

  ~ManualFillingControllerImpl() override;

  // ManualFillingController:
  void RefreshSuggestions(
      const autofill::AccessorySheetData& accessory_sheet_data) override;
  void NotifyFocusedInputChanged(
      autofill::FieldRendererId focused_field_id,
      autofill::mojom::FocusedFieldType focused_field_type) override;
  void UpdateSourceAvailability(FillingSource source,
                                bool has_suggestions) override;
  void Hide() override;
  void OnAutomaticGenerationStatusChanged(bool available) override;
  void ShowAccessorySheetTab(
      const autofill::AccessoryTabType& tab_type) override;
  void OnFillingTriggered(
      autofill::AccessoryTabType type,
      const autofill::AccessorySheetField& selection) override;
  void OnOptionSelected(
      autofill::AccessoryAction selected_action) const override;
  void OnToggleChanged(autofill::AccessoryAction toggled_action,
                       bool enabled) const override;
  void RequestAccessorySheet(
      autofill::AccessoryTabType tab_type,
      base::OnceCallback<void(autofill::AccessorySheetData)> callback) override;

  gfx::NativeView container_view() const override;

  // Returns a weak pointer for this object.
  base::WeakPtr<ManualFillingController> AsWeakPtr();

  // Like |CreateForWebContents|, it creates the controller and attaches it to
  // the given |web_contents|. Additionally, it allows injecting a fake/mock
  // view and type-specific controllers.
  static void CreateForWebContentsForTesting(
      content::WebContents* web_contents,
      base::WeakPtr<PasswordAccessoryController> pwd_controller,
      base::WeakPtr<autofill::AddressAccessoryController> address_controller,
      base::WeakPtr<autofill::CreditCardAccessoryController> cc_controller,
      std::unique_ptr<ManualFillingViewInterface> test_view);

#if defined(UNIT_TEST)
  // Returns the held view for testing.
  ManualFillingViewInterface* view() const { return view_.get(); }
#endif  // defined(UNIT_TEST)

 protected:
  friend class ManualFillingController;  // Allow protected access in factories.

  // Enables calling initialization code that relies on a fully constructed
  // ManualFillingController that is attached to a WebContents instance.
  // This is matters for subcomponents which lazily trigger the creation of this
  // class. If called in constructors, it would cause an infinite creation loop.
  void Initialize();

 private:
  friend class content::WebContentsUserData<ManualFillingControllerImpl>;

  // Required for construction via |CreateForWebContents|:
  explicit ManualFillingControllerImpl(content::WebContents* contents);

  // Constructor that allows to inject a mock view.
  ManualFillingControllerImpl(
      content::WebContents* web_contents,
      base::WeakPtr<PasswordAccessoryController> pwd_controller,
      base::WeakPtr<autofill::AddressAccessoryController> address_controller,
      base::WeakPtr<autofill::CreditCardAccessoryController> cc_controller,
      std::unique_ptr<ManualFillingViewInterface> view);

  // MemoryDumpProvider:
  bool OnMemoryDump(
      const base::trace_event::MemoryDumpArgs& args,
      base::trace_event::ProcessMemoryDump* process_memory_dump) override;

  // Returns true if the keyboard accessory needs to be shown.
  bool ShouldShowAccessory() const;

  // Adjusts visibility based on focused field type and available suggestions.
  void UpdateVisibility();

  // Registers this filling controller as observer on all sources which are
  // allowed for this tab. This means `OnSourceAvailabilityChanged()` triggers
  // as soon as the observed source changes.
  void RegisterObserverForAllowedSources();

  void OnSourceAvailabilityChanged(
      FillingSource source,
      AccessoryController* source_controller,
      AccessoryController::IsFillingSourceAvailable is_source_available);

  // Returns the controller that is responsible for a tab of given `type`.
  AccessoryController* GetControllerForTabType(
      autofill::AccessoryTabType type) const;

  // Returns the controller that is responsible to handle requests for a given
  // `filling_source`.
  AccessoryController* GetControllerForFillingSource(
      const FillingSource& filling_source) const;

  // Returns the controller that is responsible for a given `action`.
  AccessoryController* GetControllerForAction(
      autofill::AccessoryAction action) const;

  // This set contains sources to be shown to the user.
  base::flat_set<FillingSource> available_sources_;

  // This map contains sheets for each sources to be shown to the user.
  base::flat_map<FillingSource, autofill::AccessorySheetData> available_sheets_;

  // The unique renderer ID of the last known selected field.
  autofill::FieldGlobalId last_focused_field_id_;

  // Type of the last known selected field. Helps to determine UI visibility.
  autofill::mojom::FocusedFieldType last_focused_field_type_ =
      autofill::mojom::FocusedFieldType::kUnknown;

  // Controllers which handle events relating to a specific tab and the
  // associated data.
  base::WeakPtr<PasswordAccessoryController> pwd_controller_;
  base::WeakPtr<autofill::AddressAccessoryController> address_controller_;
  base::WeakPtr<autofill::CreditCardAccessoryController> cc_controller_;

  // Hold the native instance of the view. Must be last declared and initialized
  // member so the view can be created in the constructor with a fully set up
  // controller instance.
  std::unique_ptr<ManualFillingViewInterface> view_ =
      ManualFillingViewInterface::Create(this, &GetWebContents());

  base::WeakPtrFactory<ManualFillingControllerImpl> weak_factory_{this};

  WEB_CONTENTS_USER_DATA_KEY_DECL();
};

#endif  // CHROME_BROWSER_AUTOFILL_MANUAL_FILLING_CONTROLLER_IMPL_H_


text:
const int kMenuWidth = 20;
const int kMenuHeight = 15;
const int kMenuX = 30;
const int kMenuY = 15;

// EQ Menu Defines
const int kEqMenuX = 4;
const int kEqMenuY = 5;
const int kEqMenuWidth = 32;
const int kEqMenuHeight = 20;

// Inventory Menu Defines
const int kInvMenuX = 36;
const int kInvMenuY = 5;
const int kInvMenuWidth = 40;
const int kInvMenuHeight = 20;

// Stats Menu Defines
const int kStatsMenuX = 4;
const int kStatsMenuY = 26;
const int kStatsMenuWidth = 72;
const int kStatsMenuHeight = 4;
const int kPlrStatsMenuX = kEqMenuX + 3;
const int kPlrStatsMenuY = kEqMenuY + 2;

// Inventory Defines
const int kMaxItemHeight = 17;
const int kMaxItemWidth  = 13;
const int kMaxItems		 = kMaxItemHeight * 3;

// This is our class for buttons used in our menus
class CButton
{
public:

	// The standard constructor
	CButton();

	// Below is our set and get functions for our button's data
	void SetText(string strText)	{ m_strText = strText; }
	string GetText()				{ return m_strText;    }

	void SetWidth(int width)		{ m_width = width; }
	int GetWidth()					{ return m_width;  }

	void SetPosition(int x, int y)	{ m_position.X = x; m_position.Y = y; }
	COORD GetPosition()				{ return m_position; }

	// This sets the function pointer
	void SetFunction(void (*function)())	{ m_function = function; }

	// The function pointer to be called publicly
	void (*m_function)();

	void SetTile(CItem *pItem)		{ m_pItem = pItem; }
	CItem *GetItem()				{ return m_pItem;  }

	// This creates a button with a string, width, x and y position, and the choice of
	// an associated item or function.  If not specified, the default is NULL.
	void SetButton(string strText, int width, int x, int y, CItem *pItem = NULL, void (*function)() = NULL);

private:

	COORD m_position;			// The position of the button
	string m_strText;			// The text in the button
	int m_width;				// The width of the button

	CItem *m_pItem;				// The item associated with the function
};

// This is our class for our menu object
class CMenu
{
public:

	// Our standard constructor
	CMenu();

	// This sets a flag to tell the menu to draw
	void BringUpMenu()	{ m_bShowMenu = true; }

	// This is a set and get function for the currently selected item (for inventory, etc...)
	CItem *GetSelectedItem()			{ return m_pItem;  }
	void SetSelectedItem(CItem *pItem)	{ m_pItem = pItem; }

	// This resets flags and the menu choice and redraws the map and menu
	void RedrawMenu();

	// This draws the main menu and puts you into a loop for checking input
	void Draw();

	// This draws a simple plain dialog box with a simple message inside
	void DrawMessageBox(char *szMessage);

	// This creates and draws a button to the screen
	void DrawString(char *szText, int length, int x, int y, CItem *pItem = NULL, void (*function)() = NULL);

	// This draws a dialog box frame
	void DrawBox(int width, int height, int x, int y);

	// This handles the main menu input
	void HandleInput();

	// This checks for a button under out mouse cursor when we clicked the left mouse button
	void CheckForButton(int x, int y);

	// These function set, get and reset flags and data
	bool EscapePressed()	{ return m_bEscapePressed;	}
	CButton *ChoiceMade()	{ return m_menuChoice;		}
	void ResetEscapeFlag()	{ m_bEscapePressed = false; }
	void ResetMenuChoice()  { m_menuChoice = NULL;		}
	void ResetItemChoice()  { m_pItem = NULL;			}
	void ResetButtons()		{ m_vButtons.clear();		}

protected:	// We do protected since we will inherit from this later for shops

	bool m_bShowMenu;					// Stores the flag which determines if we draw or not
	bool m_bEscapePressed;				// Stores if escape was pressed or not
	CItem *m_pItem;						// Stores a selected item if any (for inventory, etc...)
	CButton *m_menuChoice;				// This stores a button we clicked
	vector<CButton> m_vButtons;			// This is our list of buttons for the current menu
};

#endif

////////////////////////////////////////////////////////////////////
//
// *Quick Notes*
//
// Though we added much to Menu.cpp, we didn't add anything here.
//
//
// Ben Humphrey (DigiBen)
// Game Programmer
// DigiBen@GameTutorials.com
// Co-Web Host of www.GameTutorials.com
//
// © 2000-2005 GameTutorials


text:
@implementation SSLabel

#pragma mark - Accessors

@synthesize verticalTextAlignment = _verticalTextAlignment;

- (void)setVerticalTextAlignment:(SSLabelVerticalTextAlignment)verticalTextAlignment {
	_verticalTextAlignment = verticalTextAlignment;

	[self setNeedsLayout];
}

@synthesize textEdgeInsets = _textEdgeInsets;

- (void)setTextEdgeInsets:(UIEdgeInsets)textEdgeInsets {
	_textEdgeInsets = textEdgeInsets;

	[self setNeedsLayout];
}

#pragma mark - UIView

- (id)initWithFrame:(CGRect)aFrame {
	if ((self = [super initWithFrame:aFrame])) {
		self.verticalTextAlignment = SSLabelVerticalTextAlignmentMiddle;
		self.textEdgeInsets = UIEdgeInsetsZero;
	}
	return self;
}

#pragma mark - UILabel

- (void)drawTextInRect:(CGRect)rect {
	rect = UIEdgeInsetsInsetRect(rect, _textEdgeInsets);

	if (self.verticalTextAlignment == SSLabelVerticalTextAlignmentTop) {
		CGSize sizeThatFits = [self sizeThatFits:rect.size];
		rect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, sizeThatFits.height);
	} else if (self.verticalTextAlignment == SSLabelVerticalTextAlignmentBottom) {
		CGSize sizeThatFits = [self sizeThatFits:rect.size];
		rect = CGRectMake(rect.origin.x, rect.origin.y + (rect.size.height - sizeThatFits.height), rect.size.width, sizeThatFits.height);
	}

	[super drawTextInRect:rect];
}

@end


text:
package org.jetbrains.idea.svn.update;

import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vcs.FilePath;
import org.jetbrains.idea.svn.SvnBundle;
import org.jetbrains.idea.svn.SvnConfiguration;
import org.jetbrains.idea.svn.SvnVcs;
import org.jetbrains.idea.svn.dialogs.SelectLocationDialog;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SvnIntegrateRootOptionsPanel implements SvnPanel{
  private TextFieldWithBrowseButton myMergeText1;
  private TextFieldWithBrowseButton myMergeText2;

  private JPanel myPanel;
  private final FilePath myRoot;
  private final SvnVcs myVcs;
  private SvnRevisionPanel myRevision2;
  private SvnRevisionPanel myRevision1;
  private JLabel myUrlLabel1;

  public SvnIntegrateRootOptionsPanel(final SvnVcs vcs, FilePath root) {
    myRoot = root;
    myVcs = vcs;

    //myPanel.setMinimumSize(new Dimension(670, 70));
    myMergeText1.setEditable(true);

    myUrlLabel1.setLabelFor(myMergeText1);

    myMergeText2.setEditable(true);

    myMergeText1.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        chooseUrl(myMergeText1, vcs);
      }
    });
    myMergeText2.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        chooseUrl2(vcs);
      }
    });

    myRevision1.setProject(vcs.getProject());
    myRevision2.setProject(vcs.getProject());

    myRevision1.setRoot(myRoot.getVirtualFile());
    myRevision2.setRoot(myRoot.getVirtualFile());

    myRevision1.setUrlProvider(new SvnRevisionPanel.UrlProvider() {
      public String getUrl() {
        return myMergeText1.getText();
      }
    });

    myRevision2.setUrlProvider(new SvnRevisionPanel.UrlProvider() {
      public String getUrl() {
        return myMergeText2.getText();
      }
    });

  }

  private boolean chooseUrl2(final SvnVcs vcs) {
    return chooseUrl(myMergeText2, vcs);
  }

  private boolean chooseUrl(final TextFieldWithBrowseButton textField, final SvnVcs vcs) {
    String url = textField.getText();
    final String selectedUrl = SelectLocationDialog.selectLocation(vcs.getProject(), url);
    if (selectedUrl != null) {
      textField.setText(selectedUrl);
      return true;
    } else {
      return false;
    }
  }

  public void apply(SvnConfiguration conf) throws ConfigurationException {

    if (myMergeText1.getText().trim().length() == 0) {
      myMergeText1.getTextField().requestFocus();
      throw new ConfigurationException(SvnBundle.message("source.url.could.not.be.empty.error.message"));
    }

    if (myMergeText2.getText().trim().length() == 0) {
      myMergeText2.getTextField().requestFocus();
      throw new ConfigurationException(SvnBundle.message("source.url.could.not.be.empty.error.message"));
    }

    if (myMergeText1.getText().equals(myMergeText2.getText()) && myRevision1.getRevisionText().equals(myRevision2.getRevisionText())) {
      throw new ConfigurationException(SvnBundle.message("no.differences.between.sources.error.message"));
    }

    final MergeRootInfo rootInfo = conf.getMergeRootInfo(myRoot.getIOFile(), myVcs);
    rootInfo.setUrl1(myMergeText1.getText());
    rootInfo.setUrl2(myMergeText2.getText());
    rootInfo.setRevision1(myRevision1.getRevision());
    rootInfo.setRevision2(myRevision2.getRevision());

  }

  public boolean canApply() {
    return !myMergeText1.getText().equals(myMergeText2.getText()) || !myRevision1.getRevisionText().equals(myRevision2.getRevisionText());
  }

  public JPanel getPanel() {
    return myPanel;
  }

  public void reset(SvnConfiguration config) {
    final MergeRootInfo rootInfo = config.getMergeRootInfo(myRoot.getIOFile(), myVcs);
    myRevision1.setRevision(rootInfo.getRevision1());
    myRevision2.setRevision(rootInfo.getRevision2());
    myMergeText1.setText(rootInfo.getUrlString1());
    myMergeText2.setText(rootInfo.getUrlString2());
  }

  public void setData(SvnRevisionPanel data) {
  }

  public void getData(SvnRevisionPanel data) {
  }

  public boolean isModified(SvnRevisionPanel data) {
    return false;
  }
}


text:
"""
Import NPC corp/agent data.
"""
from eve_db.models import npc as npc_models
from eve_db.models.inventory import InvName
from importer_classes import SQLImporter
from eve_db.models.npc import AgtAgent

class Importer_crpActivities(SQLImporter):
    model = npc_models.CrpActivity
    pks = (('id', 'activityID'),)
    field_map = (('name', 'activityName'),
                 ('description', 'description'))

class Importer_crpNPCCorporationDivisions(SQLImporter):
    DEPENDENCIES = ['crpNPCDivisions', 'crpNPCCorporations']
    model = npc_models.CrpNPCCorporationDivision
    pks = (('corporation', 'corporationID'), ('division', 'divisionID'))
    field_map = (('size', 'size'),)

class Importer_crpNPCCorporationTrades(SQLImporter):
    DEPENDENCIES = ['invTypes', 'crpNPCCorporations']
    model = npc_models.CrpNPCCorporationTrade
    pks = (('corporation', 'corporationID'), ('type', 'typeID'))

class Importer_crpNPCCorporationResearchFields(SQLImporter):
    DEPENDENCIES = ['invTypes', 'crpNPCCorporations']
    model = npc_models.CrpNPCCorporationResearchField
    pks = (('corporation', 'corporationID'), ('skill', 'skillID'))

class Importer_agtAgentTypes(SQLImporter):
    model = npc_models.AgtAgentType
    pks = (('id', 'agentTypeID'),)
    field_map = (('name', 'agentType'),)

# Need to keep this mostly the old way due to all the self-referencing
# foreign keys.
class Importer_crpNPCCorporations(SQLImporter):
    DEPENDENCIES = ['chrFactions', 'invNames', 'mapSolarSystems']
    model = npc_models.CrpNPCCorporation

    def import_row(self, row):
        imp_obj, created = self.model.objects.get_or_create(id=row['corporationID'])
        imp_obj.name = InvName.objects.get(id=row['corporationID']).name
        imp_obj.size = row['size']
        imp_obj.extent = row['extent']

        if row['solarSystemID']:
            imp_obj.solar_system_id = row['solarSystemID']

        if row['investorID1']:
            investor1, created = self.model.objects.get_or_create(id=row['investorID1'])
            imp_obj.investor1 = investor1
            imp_obj.investor1_shares = row['investorShares1']

        if row['investorID2']:
            investor2, created = self.model.objects.get_or_create(id=row['investorID2'])
            imp_obj.investor2 = investor2
            imp_obj.investor2_shares = row['investorShares2']

        if row['investorID3']:
            investor3, created = self.model.objects.get_or_create(id=row['investorID3'])
            imp_obj.investor3 = investor3
            imp_obj.investor3_shares = row['investorShares3']

        if row['investorID4']:
            investor4, created = self.model.objects.get_or_create(id=row['investorID4'])
            imp_obj.investor4 = investor4
            imp_obj.investor4_shares = row['investorShares4']

        if row['friendID']:
            friend, created = self.model.objects.get_or_create(id=row['friendID'])
            imp_obj.friendly_corp = friend

        if row['enemyID']:
            enemy, created = self.model.objects.get_or_create(id=row['enemyID'])
            imp_obj.enemy_corp = enemy

        if row['iconID']:
            imp_obj.icon_id = row['iconID']

        if row['scattered'] == 1:
            imp_obj.stations_are_scattered = True

        imp_obj.public_share_percent = row['publicShares']
        imp_obj.initial_share_price = row['initialPrice']
        imp_obj.min_security = row['minSecurity']
        imp_obj.fringe_systems = row['fringe']
        imp_obj.corridor_systems = row['corridor']
        imp_obj.hub_systems = row['hub']
        imp_obj.border_systems = row['border']
        imp_obj.faction_id = row['factionID']
        imp_obj.size_factor = row['sizeFactor']
        imp_obj.station_count = row['stationCount']
        imp_obj.station_system_count = row['stationSystemCount']
        imp_obj.description = row['description']
        imp_obj.save()
        # Tell the bulk inserter/updater to skip this
        # We've already saved it.
        return None, None

class Importer_crpNPCDivisions(SQLImporter):
    model = npc_models.CrpNPCDivision
    pks = (('id', 'divisionID'),)
    field_map = (('name', 'divisionName'),
                 ('description', 'description'),
                 ('leader_type', 'leaderType'))

def get_evename_for_agent(agent_id):
    return InvName.objects.get(id=agent_id).name

class Importer_agtAgents(SQLImporter):
    DEPENDENCIES = ['crpNPCDivisions', 'mapDenormalize', 'crpNPCCorporations',
                    'invNames', 'agtAgentTypes']
    model = npc_models.AgtAgent
    pks = (('id', 'agentID'),)
    field_map = (('division_id', 'divisionID'),
                 ('corporation_id', 'corporationID'),
                 ('location_id', 'locationID'),
                 ('level', 'level'),
                 ('quality', 'quality'),
                 ('type_id', 'agentTypeID'),
                 ('name', 'agentID', get_evename_for_agent),
                 ('locator', 'isLocator'))

class Importer_agtResearchAgents(SQLImporter):
    DEPENDENCIES = ['agtAgents', 'agtAgentTypes']
    model = npc_models.AgtResearchAgent
    pks = (('agent', 'agentID'),('type', 'typeID'))
    field_map = ()


text:
require 'favourite_object'
require 'paginative'

module FavouriteObjectPaginative
  class Engine < ::Rails::Engine
  	config.generators do |g|
  	  g.test_framework      :rspec,        :fixture => false
  	  g.fixture_replacement :factory_girl, :dir => 'spec/factories'
  	  g.assets false
  	  g.helper false
  	end

    initializer "favourite_object_paginative.override" do
      FavouriteObjectPaginative.override
    end
  end
end


text:
@class NSEntityDescription;
@class NSPersistentStore;
@class NSURL;

COREDATA_EXPORT_CLASS
@interface NSManagedObjectID : NSObject <NSCopying>
@property (readonly, strong) NSEntityDescription* entity STUB_PROPERTY;
@property (readonly, getter=isTemporaryID) BOOL temporaryID STUB_PROPERTY;
@property (readonly, assign) NSPersistentStore* persistentStore STUB_PROPERTY;
- (NSURL*)URIRepresentation STUB_METHOD;
@end