text:
var audioModel = (function () {

    /* determines the minimum time between responses. */
    /* triggered responses (of the same or higher priority) that occur during the timeout will be queued. */
    var audio_response_que = [];
    var global_audio_response_timeout = 3 * 1000 /* in ms*/;
    var global_timeout_active = false;

    var audio_response_priority_level = 0;
    var starting_priority_level = 3;
    var priority_level_cooldown = 30 * 1000 /* in ms*/;
    var priority_level_timeout;

    var defeated = false;

    var maybePlayQueuedResponse = function (clear_cooldown) {
        if (clear_cooldown && !audio_response_que.length)
            global_timeout_active = false;
        else
            global_timeout_active = true;

        if (!audio_response_que.length)
            return;

        var entry = audio_response_que.shift();

        if (audio_response_priority_level <= entry.priority || entry.priority === -1)
            api.audio.playSoundAtLocation(entry.cue, 0, 0, 0);

        setTimeout(function () { maybePlayQueuedResponse(true) }, global_audio_response_timeout);
    };
    var enqueueAudioResponse = function (cue, priority) {
        audio_response_que.push({ cue: cue, priority: priority });

        if (audio_response_que.length === 1 && !global_timeout_active)
            maybePlayQueuedResponse();
    };

    var setAudioResponsePriorityLevel = function (level) {
        if (level < 0)
            return;

        if (level > audio_response_priority_level)
            audio_response_que.length = 0;

        audio_response_priority_level = level;
        clearTimeout(priority_level_timeout);

        if (level > 0)
            priority_level_timeout = setTimeout(function () {
                setAudioResponsePriorityLevel(level - 1);
            }, priority_level_cooldown);
    };
    setAudioResponsePriorityLevel(starting_priority_level);

    function AudioResponseModel(options) {
        var self = this;

        var simple_audio = typeof options.audio === 'string';
        var lastTriggerTime = _.now();
        var sequence = -1;
        var has_played = false;
        var priority = options.ignore_priority ? -1 : (options.priority || 0);
        var always_play = options.always_play;

        var resolve = function (cue, skip) {
            var simple_cue = typeof cue === 'string';
            var target = simple_cue ? cue : cue[Math.min(sequence, cue.length - 1)];

            if (skip)
                api.audio.playSoundAtLocation(target, 0, 0, 0);
            else
                enqueueAudioResponse(target, priority);
        }

        var play = function () {
            ++sequence;

            if (options.play_once && has_played)
                return;

            if (priority && !options.ignore_priority && priority >= audio_response_priority_level)
                setAudioResponsePriorityLevel(priority);

            has_played = true;

            if (simple_audio)
                resolve(options.audio);
            else
                _.forEach(options.audio, function (element, index) { /* expects an array of arrays where the first value is a delay and the second value is an audio cue */
                    _.delay(function () {
                        resolve(element[1], !!index); /* only enqueue the first value... that way we can ignore the global audio cooldown */
                    }, element[0]);
                });
        };

        self.trigger = function () {
            if (!always_play)
                if (!options.ignore_priority && priority < audio_response_priority_level)
                    return;

            var now = _.now();
            var delta = now - lastTriggerTime;

            if (!options.reset || delta > options.reset) {
                sequence = -1;
            }

            if (!options.interval || delta > options.interval) {
                lastTriggerTime = now;
                play();
            }

        };
    };

    function MusicCueGroupModel(list, priority, minimum_duration) {
        var self = this;

        var cues = list;
        var last_index = -1;

        var sample_fn = (cues.length > 1)
                ? function () { return _.sample(_.pull(_.range(cues.length), last_index)) }
                : function () { return 0 };

        var start_time = 0;

        self.priority = priority;
        self.minimum_duration = minimum_duration || 0;

        self.start = function () {

            var next = sample_fn();
            last_index = next;
            start_time = _.now();

            engine.call('audio.setMusic', cues[next]);
        };

        self.minimumRemainingDuration = function () {
            minimum_duration - _.now() - start_time;
        };

        self.allowExit = function () {
            if (!minimum_duration)
                return true;

            return (_.now() - start_time) > minimum_duration;
        };
    }

    function MusicCueModel () {
        var self = this;

        var groups = {
            'spectator': new MusicCueGroupModel(['/Music/Music_Launch_Commander_spectating'], 1),
            'launch': new MusicCueGroupModel(['/Music/Music_Launch_Commander'], 1),
            'base': new MusicCueGroupModel(['/Music/Music_Base'], 2, 40 * 1000 /* ms */),
            'battle': new MusicCueGroupModel(['/Music/Music_battle'], 2, 85 * 1000 /* ms */),
            'smash': new MusicCueGroupModel(['/Music/Music_Planets_smash_long'], 2, 85 * 1000 /* ms */),
            'victory': new MusicCueGroupModel(['/Music/Music_Gameover_Win'], 3),
            'defeat': new MusicCueGroupModel(['/Music/Music_Commander_Death'], 3),
            'celestial_targeting': new MusicCueGroupModel(['/Music/Music_Halley_Select_planet'], 2),
            'ragnarok_ready': new MusicCueGroupModel(['/Music/Music_Ragnarock_complete'], 4, 80 * 1000 /* ms */),
            'rewind': new MusicCueGroupModel(['/Music/Music_Launch_Commander_spectating'], 5)
        };

        var active_group = '';

        var building_timeout_delay = 40 * 1000; /* in ms */
        var building_timeout;

        var current_priority = function () {
            return groups[active_group] ? groups[active_group].priority : 0;
        }

        var makeActiveAndStart = function (target) {
            active_group = target;
            groups[active_group].start();
        }

        self.clearCurrentMusic = function() {
            active_group = '';
            clearTimeout(building_timeout);
        }

        self.stopRagnarokMusic = function() {
            if (active_group !== 'victory' && active_group !== 'defeat') {
                self.clearCurrentMusic();
                self.startCueGroup('base');
            }
        }

        self.startCueGroup = function (target) {
            var buildingTimeoutCancelTargets = ['battle', 'victory', 'defeat', 'ragnarok_ready'];
            if (_.contains(buildingTimeoutCancelTargets, target))
                clearTimeout(building_timeout);

            if (target === 'ragnarok_ready' && active_group !== 'ragnarok_ready') {
                makeActiveAndStart(target);
                return;
            }

            var ragnarokCancelTargets = ['victory', 'defeat'];
            if (active_group === 'ragnarok_ready' && _.contains(ragnarokCancelTargets, target))
                self.clearCurrentMusic();

            if (target === 'battle')
                building_timeout = setTimeout(function () { self.startCueGroup('base') }, building_timeout_delay);

            if (target === active_group
                    || current_priority() > groups[target].priority)
                return;

            if (groups[active_group] && !groups[active_group].allowExit() && current_priority() === groups[target].priority) {
                if (target === 'base')
                    building_timeout = setTimeout(function () { self.startCueGroup('base') }, groups[active_group].minimumRemainingDuration() + 1);
                return;
            }

            makeActiveAndStart(target);
        }
    }

    function AudioModel() {

        var self = this;

        var music = new MusicCueModel();
        self.music = music;

        var responses = {};

        responses[constants.event_type.low_metal] = new AudioResponseModel({
            audio: [
                [0, ['',
                     '/SE/UI/UI_Alert_metal_low',
                     '',
                     '',
                     '',
                     '',
                     '',
                     '',
                     '',
                     '']],
                [2 * 1000 /* in ms */, ['',
                                        '/VO/Computer/economy_low_metal',
                                        '',
                                        '',
                                        '/VO/Computer/economy_low_metal_seq2',
                                        '',
                                        '',
                                        '',
                                        '/VO/Computer/economy_low_metal_seq3',
                                        '']]
            ],
            interval: 60 * 1000 /* in ms */,
            reset: 90 * 1000,
            priority: 1
        });
        responses[constants.event_type.low_energy] = new AudioResponseModel({
            audio: [
                [0, ['',
                     '/SE/UI/UI_Alert_energy_low',
                     '',
                     '',
                     '',
                     '']],
                [2 * 1000 /* in ms */, ['',
                                        '/VO/Computer/economy_low_power',
                                        '',
                                        '',
                                        '/VO/Computer/economy_low_power',
                                        '']]
            ],
            interval: 60 * 1000 /* in ms */,
            reset: 90 * 1000 /* in ms */,
            priority: 1
        });
        responses[constants.event_type.full_metal] = new AudioResponseModel({
            audio: [
                [2 * 1000 /* in ms */, ['',
                                        '',
                                        '/VO/Computer/economy_metal_full',
                                        '',
                                        '',
                                        '/VO/Computer/economy_metal_full',
                                        '']]
            ],
            interval: 60 * 1000 /* in ms */,
            reset: 360 * 1000 /* in ms */,
            priority: 0
        });
        responses[constants.event_type.full_energy] = new AudioResponseModel({
            audio: [
                [2 * 1000 /* in ms */, ['',
                                        '',
                                        '',
                                        '/VO/Computer/economy_power_full',
                                        '',
                                        '',
                                        '/VO/Computer/economy_power_full',
                                        '']]
            ],
            interval: 60 * 1000 /* in ms */,
            reset: 360 * 1000 /* in ms */,
            priority: 0
        });

        responses[constants.event_type.under_attack] = new AudioResponseModel({
            audio: [
                [0, '/SE/UI/UI_under_attack'],
                [2 * 1000 /* in ms */, '/VO/Computer/under_attack']
            ],
            interval: 60 * 1000 /* in ms */,
            reset: 90 * 1000 /* in ms */,
            priority: 3
        });
        responses[constants.event_type.commander_healed] = new AudioResponseModel({
            audio: '/VO/Computer/commander_healed',
            interval: 60 * 1000 /* in ms */,
            reset: 90 * 1000 /* in ms */,
            priority: 3
        });
        responses[constants.event_type.commander_under_attack] = new AudioResponseModel({
            audio: [
                [0, '/SE/UI/UI_commander_under_attack'],
                [2 * 1000 /* in ms */, '/VO/Computer/commander_under_attack']
            ],
            interval: 60 * 1000 /* in ms */,
            reset: 60 * 1000 /* in ms */,
            priority: 3
        });

        responses[constants.event_type.allied_commander_under_attack] = new AudioResponseModel({
            audio: '/VO/Computer/commander_under_attack_allied',
            interval: 60 * 1000 /* in ms */,
            reset: 60 * 1000 /* in ms */,
            priority: 3
        });

        responses[constants.event_type.allied_commander_low_health] = new AudioResponseModel({
            audio: '/VO/Computer/commander_under_attack_lowhealth_allied',
            interval: 60 * 1000 /* in ms */,
            reset: 60 * 1000 /* in ms */,
            priority: 3
        });

        responses[constants.event_type.enemy_commander_under_attack] = new AudioResponseModel({
            audio: '/VO/Computer/attacking_enemy_commander',
            interval: 60 * 1000 /* in ms */,
            reset: 60 * 1000 /* in ms */,
            priority: 3
        });

        responses[constants.event_type.enemy_commander_low_health] = new AudioResponseModel({
            audio: '/VO/Computer/commander_under_attack_lowhealth_enemy',
            interval: 60 * 1000 /* in ms */,
            reset: 60 * 1000 /* in ms */,
            priority: 3
        });

        responses[constants.event_type.commander_low_health] = new AudioResponseModel({
            audio: [
                [0, '/SE/UI/UI_commander_low_health'],
                [2 * 1000 /* in ms */, '/VO/Computer/commander_under_attack_lowhealth']
            ],
            interval: 60 * 1000 /* in ms */,
            reset: 60 * 1000 /* in ms */,
            priority: 4
        });

        responses[constants.event_type.commander_under_attack_very_low_health] = new AudioResponseModel({
            audio: '/VO/Computer/commander_under_attack_extremly_lowhealth',
            interval: 60 * 1000 /* in ms */,
            reset: 60 * 1000 /* in ms */,
            priority: 4
        });

        responses[constants.event_type.commander_destroyed] = new AudioResponseModel({
            audio: '/VO/Computer/commander_destroyed',
            priority: 5
        });

        responses[constants.event_type.asteroid_incoming] = new AudioResponseModel({
            audio: '/VO/Computer/annihiation_orbit_altered',
            priority: 5
        });

        responses[constants.event_type.asteroid_imminent] = new AudioResponseModel({
            audio: '/VO/Computer/annihiation_imminent',
            priority: 5
        });

        responses[constants.event_type.asteroid_impact] = new AudioResponseModel({
            audio: '', /* we just want to set the priority level here, we don't need to play a cue */
            priority: 6
        });

        responses[constants.event_type.new_enemy_contact] = new AudioResponseModel({
            audio: '/VO/Computer/site_unit_enemy',
            ignore_priority: true,
            //priority: 4
        });
        responses[constants.event_type.enemy_commander_sighted] = new AudioResponseModel({
            audio: '/VO/Computer/site_commander_enemy',
            always_play: true,
            priority: 4
        });
        responses[constants.event_type.enemy_commander_destroyed] = new AudioResponseModel({
            audio: '/VO/Computer/commander_destroyed_enemy',
            always_play: true,
            priority: 4
        });

        responses[constants.event_type.projectile] = {
            '/pa/units/land/nuke_launcher/nuke_launcher_ammo.json' : new AudioResponseModel({
                audio: '/VO/Computer/site_nuke_incoming',
                priority: 3
            })
        };

        responses[constants.event_type.death] = {
            '/pa/units/land/nuke_launcher/nuke_launcher.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_nuke',
                priority: 2
            }),
            '/pa/units/land/anti_nuke_launcher/anti_nuke_launcher.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_anti_nuke',
                priority: 3
            }),
            '/pa/units/orbital/delta_v_engine/delta_v_engine.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_hally',
                priority: 4
            }),
            '/pa/units/orbital/deep_space_radar/deep_space_radar.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_orbital_radar',
                priority: 2
            }),
            '/pa/units/land/tactical_missile_launcher/tactical_missile_launcher.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_catapult',
                priority: 1
            }),
            '/pa/units/orbital/deep_space_radar/deep_space_radar.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_orbital_radar',
                priority: 2
            }),
            '/pa/units/orbital/orbital_laser/orbital_laser.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_ssx',
                priority: 2
            }),
            '/pa/units/orbital/radar_satellite_adv/radar_satellite_adv.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_orbital_radar',
                priority: 1
            }),
            '/pa/units/land/artillery_long/artillery_long.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_holkins',
                priority: 1
            }),
            '/pa/units/sea/battleship/battleship.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_battleship',
                priority: 2,
            }),
            '/pa/units/sea/missile_ship/missile_ship.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_stingray',
                priority: 2
            }),
            '/pa/units/orbital/defense_satellite/defense_satellite.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_anchor',
                priority: 2
            }),
            '/pa/units/orbital/ion_defense/ion_defense.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_umbrella',
                priority: 2
            }),
            '/pa/units/land/unit_cannon/unit_cannon.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_unit_cannon',
                priority: 4
             }),
            '/pa/units/land/control_module/control_module.json' : new AudioResponseModel({
                audio: '/VO/Computer/lost_control_module',
                priority: 4
            }),
            '/pa/units/land/artillery_unit_launcher/artillery_unit_launcher.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/lost_lob',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/bot_support_commander/bot_support_commander.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/lost_support_commander',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/tank_nuke/tank_nuke.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/lost_nuke_tank',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/sea/hover_ship/hover_ship.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/lost_hover_boat',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/sea/drone_carrier/carrier/carrier.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/lost_drone_aircraft_carrier',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/orbital_battleship/orbital_battleship.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/lost_orbital_destroyer',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/orbital_railgun/orbital_railgun.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/lost_orbital_laser_longinus',
                priority: 1,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/air/titan_air/titan_air.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/lost_zeus_airship',
                priority: 4,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/titan_bot/titan_bot.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/lost_altlas_seismic',
                priority: 4,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/titan_vehicle/titan_vehicle.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/lost_hover_tank',
                priority: 4,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/titan_orbital/titan_orbital.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/lost_orbital_station',
                priority: 4,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/titan_structure/titan_structure.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/lost_Ragnarok',
                priority: 5,
                interval: 30 * 1000 /* in ms */,
            })
        };

        responses[constants.event_type.allied_death] = {};

        var advanced_factory_response = new AudioResponseModel({
            audio: '/VO/Computer/construction_building_factory_T2_built',
            priority: 1,
            play_once: true,
        });

        responses[constants.event_type.ready] = {
            '/pa/units/land/vehicle_factory_adv/vehicle_factory_adv.json': advanced_factory_response,
            '/pa/units/land/bot_factory_adv/bot_factory_adv.json': advanced_factory_response,
            '/pa/units/air/air_factory_adv/air_factory_adv.json': advanced_factory_response,
            '/pa/units/naval/naval_factory_adv/naval_factory_adv.json': advanced_factory_response,

            '/pa/units/orbital/orbital_launcher/orbital_launcher.json' : new AudioResponseModel({
                audio: '/VO/Computer/construction_building_orbital_factory_built',
                priority: 1,
                interval: 10 * 1000 /* in ms */
            }),
            '/pa/units/land/nuke_launcher/nuke_launcher.json': new AudioResponseModel({
                audio: '/VO/Computer/construction_building_nuke_built',
                priority: 2,
                interval: 10 * 1000 /* in ms */
            }),
            '/pa/units/land/anti_nuke_launcher/anti_nuke_launcher.json': new AudioResponseModel({
                audio: '/VO/Computer/construction_building_anti_nuke_built',
                priority: 1,
                interval: 10 * 1000 /* in ms */
            }),
            '/pa/units/orbital/delta_v_engine/delta_v_engine.json': new AudioResponseModel({
                audio: '/VO/Computer/construction_building_halley_built',
                priority: 2
            }),
            '/pa/units/orbital/deep_space_radar/deep_space_radar.json': new AudioResponseModel({
                audio: '/VO/Computer/construction_building_orbital_radar_built',
                priority: 1,
                interval: 10 * 1000 /* in ms */
            }),
            '/pa/units/land/tactical_missile_launcher/tactical_missile_launcher.json': new AudioResponseModel({
                audio: '/VO/Computer/construction_building_tactical_missile_launcher_built',
                priority: 1,
                interval: 10 * 1000 /* in ms */
            }),
            '/pa/units/orbital/deep_space_radar/deep_space_radar.json': new AudioResponseModel({
                audio: '/VO/Computer/construction_deep_space_radar_built',
                priority: 1,
                interval: 10 * 1000 /* in ms */
            }),
            '/pa/units/orbital/orbital_laser/orbital_laser.json': new AudioResponseModel({
                audio: '/VO/Computer/construction_orbital_laser_ssx_built',
                priority: 1,
                interval: 10 * 1000 /* in ms */
            }),
            '/pa/units/orbital/radar_satellite_adv/radar_satellite_adv.json': new AudioResponseModel({
                audio: '/VO/Computer/construction_radar_satellite_adv_built',
                priority: 1,
                interval: 10 * 1000 /* in ms */
            }),
            '/pa/units/land/artillery_long/artillery_long.json': new AudioResponseModel({
                audio: '/VO/Computer/construction_building_artillery_long_built',
                priority: 1,
                interval: 10 * 1000 /* in ms */
            }),
            '/pa/units/sea/battleship/battleship.json': new AudioResponseModel({
                audio: '/VO/Computer/construction_battleship_built',
                priority: 2,
                interval: 10 * 1000 /* in ms */
            }),
            '/pa/units/sea/missile_ship/missile_ship.json': new AudioResponseModel({
                audio: '/VO/Computer/construction_missile_ship_built',
                priority: 2,
                interval: 10 * 1000 /* in ms */
            }),
            '/pa/units/orbital/defense_satellite/defense_satellite.json': new AudioResponseModel({
                audio: '/VO/Computer/construction_defense_satellite_anchor_built',
                priority: 2,
                interval: 10 * 1000 /* in ms */
            }),
            '/pa/units/land/unit_cannon/unit_cannon.json' : new AudioResponseModel({
                audio: '/VO/Computer/construction_unit_cannon',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
             }),
            '/pa/units/land/control_module/control_module.json': new AudioResponseModel({
                audio: '/VO/Computer/construction_control_module_built',
                priority: 3
            }),
            '/pa/units/land/artillery_unit_launcher/artillery_unit_launcher.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/construction_lob_built',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/bot_support_commander/bot_support_commander.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/construction_support_commander_built',
                priority: 4,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/tank_nuke/tank_nuke.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/construction_nuke_tank_built',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/sea/hover_ship/hover_ship.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/construction_hover_boat_built',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/sea/drone_carrier/carrier/carrier.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/construction_drone_aircraft_carrier_built',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/orbital_battleship/orbital_battleship.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/construction_orbital_destroyer_built',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/orbital_railgun/orbital_railgun.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/construction_orbital_laser_longinus_built',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/air/titan_air/titan_air.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/construction_zeus_airship_built',
                priority: 4,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/sea/titan_sea/titan_sea.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/construction_warpship_built',
                priority: 4,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/titan_bot/titan_bot.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/construction_altlas_seismic_built',
                priority: 4,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/titan_vehicle/titan_vehicle.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/construction_hover_tank_built',
                priority: 4,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/titan_orbital/titan_orbital.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/construction_orbital_station_built',
                priority: 4,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/titan_structure/titan_structure.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/construction_Ragnarok_built',
                priority: 4,
                interval: 30 * 1000 /* in ms */,
            })

        };

        responses[constants.event_type.sight] = {
            '/pa/units/land/nuke_launcher/nuke_launcher.json' : new AudioResponseModel({
                audio: '/VO/Computer/site_nuke_installation',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/anti_nuke_launcher/anti_nuke_launcher.json' : new AudioResponseModel({
                audio: '/VO/Computer/site_anti_nuke',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/delta_v_engine/delta_v_engine.json' : new AudioResponseModel({
                audio: '/VO/Computer/site_hally',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/deep_space_radar/deep_space_radar.json' : new AudioResponseModel({
                audio: '/VO/Computer/site_orbital_radar',
                priority: 1,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/tactical_missile_launcher/tactical_missile_launcher.json' : new AudioResponseModel({
                audio: '/VO/Computer/site_catapult',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/orbital_laser/orbital_laser.json' : new AudioResponseModel({
                audio: '/VO/Computer/site_ssx',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/radar_satellite_adv/radar_satellite_adv.json' : new AudioResponseModel({
                audio: '/VO/Computer/site_orbital_radar',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/artillery_long/artillery_long.json' : new AudioResponseModel({
                audio: '/VO/Computer/site_holkins',
                priority: 1,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/sea/battleship/battleship.json' : new AudioResponseModel({
                audio: '/VO/Computer/site_battleship',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/defense_satellite/defense_satellite.json' : new AudioResponseModel({
                audio: '/VO/Computer/site_anchor',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/ion_defense/ion_defense.json' : new AudioResponseModel({
                audio: '/VO/Computer/site_umbrella',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
             }),
             '/pa/units/land/unit_cannon/unit_cannon.json' : new AudioResponseModel({
                audio: '/VO/Computer/site_unit_cannon',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
             }),
            '/pa/units/land/control_module/control_module.json' : new AudioResponseModel({
                audio: '/VO/Computer/site_control_module',
                priority: 4,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/bot_support_commander/bot_support_commander.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/site_support_commander',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/tank_nuke/tank_nuke.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/site_nuke_tank',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/sea/hover_ship/hover_ship.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/site_hover_boat',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/sea/drone_carrier/carrier/carrier.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/site_drone_aircraft_carrier',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/orbital_battleship/orbital_battleship.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/site_orbital_destroyer',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/orbital_railgun/orbital_railgun.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/site_orbital_laser_longinus',
                priority: 1,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/air/titan_air/titan_air.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/site_zeus_airship',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/sea/titan_sea/titan_sea.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/site_warpship',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/titan_bot/titan_bot.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/site_altlas_seismic',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/titan_vehicle/titan_vehicle.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/site_hover_tank',
                priority: 1,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/titan_orbital/titan_orbital.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/site_orbital_station',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/titan_structure/titan_structure.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/site_Ragnarok',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            })
        };

        responses[constants.event_type.target_destroyed] = {
            '/pa/units/land/nuke_launcher/nuke_launcher.json' : new AudioResponseModel({
                audio: '/VO/Computer/destroyed_nuke',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/anti_nuke_launcher/anti_nuke_launcher.json' : new AudioResponseModel({ /* didn't play */
                audio: '/VO/Computer/destroyed_anti_nuke',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/delta_v_engine/delta_v_engine.json' : new AudioResponseModel({
                audio: '/VO/Computer/destroyed_hally',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/deep_space_radar/deep_space_radar.json' : new AudioResponseModel({
                audio: '/VO/Computer/destroyed_orbital_radar',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/tactical_missile_launcher/tactical_missile_launcher.json' : new AudioResponseModel({
                audio: '/VO/Computer/destroyed_catapult',
                priority: 1,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/orbital_laser/orbital_laser.json' : new AudioResponseModel({
                audio: '/VO/Computer/destroyed_ssx',
                priority: 1,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/radar_satellite_adv/radar_satellite_adv.json' : new AudioResponseModel({
                audio: '/VO/Computer/destroyed_orbital_radar',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/artillery_long/artillery_long.json' : new AudioResponseModel({
                audio: '/VO/Computer/destroyed_holkins',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/sea/battleship/battleship.json' : new AudioResponseModel({
                audio: '/VO/Computer/destroyed_battleship',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/sea/missile_ship/missile_ship.json' : new AudioResponseModel({
                audio: '/VO/Computer/destroyed_stingray',
                priority: 1,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/defense_satellite/defense_satellite.json' : new AudioResponseModel({ /* didn't play */
                audio: '/VO/Computer/destroyed_anchor',
                priority: 1,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/ion_defense/ion_defense.json' : new AudioResponseModel({
                audio: '/VO/Computer/destroyed_umbrella',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/unit_cannon/unit_cannon.json' : new AudioResponseModel({
                audio: '/VO/Computer/destroyed_unit_cannon',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
             }),
            '/pa/units/land/control_module/control_module.json' : new AudioResponseModel({
                audio: '/VO/Computer/destroyed_control_module',
                priority: 4,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/artillery_unit_launcher/artillery_unit_launcher.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/destroyed_lob',
                priority: 1,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/bot_support_commander/bot_support_commander.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/destroyed_support_commander',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/tank_nuke/tank_nuke.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/destroyed_nuke_tank',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/sea/hover_ship/hover_ship.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/destroyed_hover_boat',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/sea/drone_carrier/carrier/carrier.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/destroyed_drone_aircraft_carrier',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/orbital_battleship/orbital_battleship.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/destroyed_orbital_destroyer',
                priority: 2,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/orbital_railgun/orbital_railgun.json': new AudioResponseModel({
                audio: '/VO/Computer/X1/destroyed_orbital_laser_longinus',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/air/titan_air/titan_air.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/destroyed_zeus_airship',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/sea/titan_sea/titan_sea.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/destroyed_warpship',
                priority: 1,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/titan_bot/titan_bot.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/destroyed_altlas_seismic',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/titan_vehicle/titan_vehicle.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/destroyed_hover_tank',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/orbital/titan_orbital/titan_orbital.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/destroyed_orbital_station',
                priority: 3,
                interval: 30 * 1000 /* in ms */,
            }),
            '/pa/units/land/titan_structure/titan_structure.json': new AudioResponseModel({
                audio: '/VO/Computer/Titan/destroyed_Ragnarok',
                priority: 4,
                interval: 30 * 1000 /* in ms */,
            })
        };

        responses[constants.event_type.enemy_commander_destroyed] = new AudioResponseModel({
            audio: '/VO/Computer/commander_destroyed_enemy',
            always_play: true,
            priority: 4
        });

        responses[constants.event_type.allied_commander_destroyed] = new AudioResponseModel({
            audio: '/VO/Computer/commander_destroyed_allied',
            always_play: true,
            priority: 4
        });

        responses[constants.event_type.thrust_control_established] = new AudioResponseModel({
            audio: '/VO/Computer/annihiation_hallys_needed_met',
            always_play: true,
            priority: 4
        });

        responses[constants.event_type.weapon_control_established] = new AudioResponseModel({
            audio: '/VO/Computer/annihilation_m_control_met',
            always_play: true,
            priority: 4
        });

        responses[constants.event_type.asteroid_respawned] = new AudioResponseModel({
            audio: '/VO/Computer/astroid_new_sighted',
            always_play: true,
            priority: 4
        });

        responses[constants.event_type.teleporter_linked] = new AudioResponseModel({
            audio: '/VO/Computer/teleporter_linked',
            always_play: true,
            priority: 2
        });

        responses[constants.event_type.transport_arrival] = new AudioResponseModel({
            audio: '/VO/Computer/transport_orbital_reached_destination',
            always_play: true,
            priority: 2
        });

        responses[constants.event_type.commander_arrival] = new AudioResponseModel({
            audio: '/VO/Computer/transport_orbital_reached_destination_Commander',
            always_play: true,
            priority: 4
        });

        responses[constants.event_type.enemy_commander_departure] = new AudioResponseModel({
            audio: '/VO/Computer/commander_orbital_transport_enemy',
            always_play: true,
            priority: 2
        });

        responses[constants.event_type.unit_energy_shutdown] = new AudioResponseModel({
            audio: '/VO/Computer/economy_power_low_teleports_radars_powered_down',
            priority: 2,
            interval: 30 * 1000 /* in ms */,
        });

        responses[constants.event_type.unit_energy_startup] = new AudioResponseModel({
            audio: '/VO/Computer/economy_power_restored_teleports_radars_powered_up',
            priority: 2,
            interval: 30 * 1000 /* in ms */,
        });

        responses[constants.event_type.ragnarok_loaded] = new AudioResponseModel({
            audio: '/VO/Computer/Titan/Ragnarok_loaded',
            priority: 5,
            always_play: true
        });

        responses[constants.event_type.nuke_ready] = new AudioResponseModel({
            audio: '/VO/Computer/missile_ready_nuke',
            priority: 2,
            always_play: true
        });

        responses[constants.event_type.unitcannon_full] = new AudioResponseModel({
            audio: '/VO/Computer/unitcannon_full',
            priority: 2,
            always_play: true
        });

        responses[constants.event_type.anti_nuke_ready] = new AudioResponseModel({
            audio: '/VO/Computer/missile_ready_antinuke',
            priority: 2,
            always_play: true
        });

        responses[constants.event_type.bounty_recieved] = new AudioResponseModel({
            audio: '/VO/Computer/mode_bounty_recieved',
            priority: 5
        });

        responses[constants.event_type.bounty_claimed_ally] = new AudioResponseModel({
            audio: '/VO/Computer/mode_bounty_claimed_ally',
            priority: 4
        });

        responses[constants.event_type.bounty_claimed_enemy] = new AudioResponseModel({
            audio: '/VO/Computer/mode_bounty_claimed_enemy',
            priority: 4
        });

        responses[constants.event_type.construction_continuous_on] = new AudioResponseModel({
            audio: '/VO/Computer/construction_continuous_on',
            interval: 30 * 1000 /* in ms */,
            priority: 2
        });

        responses[constants.event_type.construction_continuous_off] = new AudioResponseModel({
            audio: '/VO/Computer/construction_continuous_off',
            interval: 30 * 1000 /* in ms */,
            priority: 2
        });

        self.stopRagnarokMusic  = function () {
            music.stopRagnarokMusic();
        }

        self.triggerRagnarokMusic = function () {
            music.startCueGroup('ragnarok_ready');
        }

        self.triggerSpectatorMusic = function () {
            music.startCueGroup('spectator');
        }

        self.triggerLaunchMusic = function () {
            music.startCueGroup('launch');
        }

        self.triggerBuildingMusic = function () {
            music.startCueGroup('base');
        }

        self.triggerBattleMusic = function () {
            music.startCueGroup('battle');
        }

        self.triggerPlanetSmashMusic = function () {
            music.startCueGroup('smash');
        }

        self.triggerVictoryMusic = function () {
            music.startCueGroup('victory');
        }

        self.triggerDefeatMusic = function () {
            music.startCueGroup('defeat');
        }

        self.triggerCelestialTargetingMusic = function () {
            music.startCueGroup('celestial_targeting');
        }

        self.triggerRewindMusic = function () {
            music.startCueGroup('rewind');
        }

        self.setDefeated = function (value) {
            if (defeated && !value)
                setAudioResponsePriorityLevel(starting_priority_level);
            defeated = value;
        }

        self.processEvent = function (event_type, sub_type) {
            if (defeated)
                return;

            var response = responses[event_type];
            var use_sub_type = sub_type !== -1;

            if (response) {
                // Note: This strips off spec tags when looking for a sub-type
                var specNameMatch = /.*\.json/.exec(sub_type);
                if (specNameMatch)
                    sub_type = specNameMatch.pop();
                if (use_sub_type && response[sub_type])
                    response = response[sub_type];

                if (response.trigger)
                    response.trigger();
            }
        };
    }

    return new AudioModel();
})()


text:
package com.interest.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MDateUtil {
	public final static String DATE_HHmmss = "HH:mm:ss";
	public final static String DATE_yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
	public final static String DATE_yyyyMMddHHmmssSSS = "yyyy-MM-dd HH:mm:ss.SSS";
	public final static String DATE_yyyyMM = "yyyy-MM";
	public final static String DATE_yyyyMMdd = "yyyy-MM-dd";
	public final static String DATE_yyyyMMddHHmm = "yyyy-MM-dd HH:mm";
	public final static String DATE_MMdd = "MM.dd";
	public final static String DATE_YYYYMMDD = "yyyyMMdd";
	public final static String DATE_YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
	/**
	 * 格式化日期
	 *
	 * @param pattern
	 *            详情查看SimpleDateFormat javadoc
	 * @param time
	 * @return
	 */
	public static String format(String pattern, long time) {
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		return format.format(new Date(time));
	}

	/**
	 * 计算date2与date1相差分钟数
	 *
	 * @param date1
	 * @param date2
	 * @return date2 < date1为负值,否则为正值
	 */
	public static int getMinSpace(Date date1, Date date2) {
		int result = (int) ((date2.getTime() - date1.getTime()) / (60 * 1000));
		return result;
	}

	/**
	 * 计算date2与date1相差日数
	 *
	 * @param date1
	 * @param date2
	 * @return date2 < date1为负值,否则为正值
	 */
	public static int getDateSpace(Date date1, Date date2) {
		int result = (int) ((date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000));
		return result;
	}

	/**
	 * 计算date2与date1相差日数(只取天数)
	 *
	 * @param date1
	 * @param date2
	 * @return date2 < date1为负值,否则为正值
	 */
	public static int getDateSpacesExt(Date date1, Date date2) {
		int result = (int) ((date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000));//取整天数

		int yu = (int)(date2.getTime() - date1.getTime()) % (60 * 60 * 1000);//获取剩余小时
		Calendar c = Calendar.getInstance();
		c.setTime(date2);
		if((c.get(Calendar.HOUR)+yu)>=24){
			result += 1;
		}
		return result;
	}

	/**
	 * 计算date2与date1相差月数
	 *
	 * @param date1
	 * @param date2
	 * @return date2 < date1为负值,否则为正值
	 */
	public static int getMonthSpace(Date date1, Date date2) {
		int result = 0;
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(date1);
		c2.setTime(date2);
		result = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
		//再加上年间隔
		int yearSpace = getYearSpace(date1, date2);
		result += yearSpace*12;
		return result;
	}

	/**
	 * 计算date2与date1相差年数
	 *
	 * @param date1
	 * @param date2
	 * @return date2 < date1为负值,否则为正值
	 */
	public static int getYearSpace(Date date1, Date date2) {
		int result = 0;
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(date1);
		c2.setTime(date2);
		result = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
		return result;
	}

	/**
	 * 日期增减天数
	 * @param date
	 * @param day
	 * @return
	 */
	public static Date addDay(Date date, int day) {
		Calendar c1 = Calendar.getInstance();
		c1.setTime(date);
		c1.add(Calendar.DAY_OF_MONTH, day);
		return c1.getTime();
	}

	/**
	 * 日期增减月数
	 * @param date
	 * @param month
	 * @return
	 */
	public static Date addMonth(Date date, int month) {
		Calendar c1 = Calendar.getInstance();
		c1.setTime(date);
		c1.add(Calendar.MONTH, month);
		return c1.getTime();
	}

	/**
	 * 获取当月天数
	 */
	public static int getCurrentMonthLastDay()
	{
	    Calendar a = Calendar.getInstance();
	    a.set(Calendar.DATE, 1);//把日期设置为当月第一天
	    a.roll(Calendar.DATE, -1);//日期回滚一天,也就是最后一天
	    int maxDate = a.get(Calendar.DATE);
	    return maxDate;
	}

	/**
	 * 获取上月天数
	 */
	public static int getLastMonthLastDay()
	{
	    Calendar a = Calendar.getInstance();
	    a.add(Calendar.MONTH, -1);
	    a.set(Calendar.DATE, 1);//把日期设置为当月第一天
	    a.roll(Calendar.DATE, -1);//日期回滚一天,也就是最后一天
	    int maxDate = a.get(Calendar.DATE);
	    return maxDate;
	}

	/**
	 * 得到指定月的天数
	 * */
	public static int getMonthLastDay(int year, int month)
	{
	    Calendar a = Calendar.getInstance();
	    a.set(Calendar.YEAR, year);
	    a.set(Calendar.MONTH, month - 1);
	    a.set(Calendar.DATE, 1);//把日期设置为当月第一天
	    a.roll(Calendar.DATE, -1);//日期回滚一天,也就是最后一天
	    int maxDate = a.get(Calendar.DATE);
	    return maxDate;
	}

	/**
	 * 获取当前时间字串
	 * @return
	 */
	public static String formatDate() {
		return formatDate("yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 获取指定格式当前时间字串
	 * @param pattern
	 * @return
	 */
	public static String formatDate(String pattern) {
		return formatDate(pattern, new Date());
	}

	/**
	 * 获取指定格式时间字串
	 * @param pattern
	 * @param date
	 * @return
	 */
	public static String formatDate(String pattern, Date date) {
		return new SimpleDateFormat(pattern).format(date);
	}

	/**
	 * 解析时间字串
	 * @param pattern
	 * @param text
	 * @return
	 */
	public static Date parseDateStr(String pattern, String text) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
		try {
			return dateFormat.parse(text);
		} catch (ParseException ex) {
		}
		return new Date();
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<package>
  <name>thor_mang_scripts</name>
  <version>0.0.0</version>
  <description>The thor_mang_scripts package</description>

  <!-- One maintainer tag required, multiple allowed, one person per tag -->
  <maintainer email="stumpf@sim.tu-darmstadt.de">Alexander Stumpf</maintainer>

  <!-- One license tag required, multiple allowed, one license per tag -->
  <license>BSD</license>

  <!-- Url tags are optional, but mutiple are allowed, one per tag -->
  <!-- Optional attribute type can be: website, bugtracker, or repository -->
  <!-- Example: -->
  <!-- <url type="website">http://ros.org/wiki/thor_scripts</url> -->

  <!-- Author tags are optional, mutiple are allowed, one per tag -->
  <!-- Authors do not have to be maintianers, but could be -->
  <!-- Example: -->
  <author email="stumpf@sim.tu-darmstadt.de">Alexander Stumpf</author>

  <!-- The *_depend tags are used to specify dependencies -->
  <!-- Dependencies can be catkin packages or system dependencies -->
  <buildtool_depend>catkin</buildtool_depend>

</package>


text:
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QGridLayout, QLabel, QListWidget, QListWidgetItem

from electrum_mona.i18n import _
from electrum_mona.network import Network
from electrum_mona.bip39_recovery import account_discovery
from electrum_mona.logging import get_logger

from .util import WindowModalDialog, MessageBoxMixin, TaskThread, Buttons, CancelButton, OkButton

_logger = get_logger(__name__)

class Bip39RecoveryDialog(WindowModalDialog):

    ROLE_ACCOUNT = Qt.UserRole

    def __init__(self, parent: QWidget, get_account_xpub, on_account_select):
        self.get_account_xpub = get_account_xpub
        self.on_account_select = on_account_select
        WindowModalDialog.__init__(self, parent, _('BIP39 Recovery'))
        self.setMinimumWidth(400)
        vbox = QVBoxLayout(self)
        self.content = QVBoxLayout()
        self.content.addWidget(QLabel(_('Scanning common paths for existing accounts...')))
        vbox.addLayout(self.content)
        self.ok_button = OkButton(self)
        self.ok_button.clicked.connect(self.on_ok_button_click)
        self.ok_button.setEnabled(False)
        vbox.addLayout(Buttons(CancelButton(self), self.ok_button))
        self.finished.connect(self.on_finished)
        self.show()
        self.thread = TaskThread(self)
        self.thread.finished.connect(self.deleteLater) # see #3956
        self.thread.add(self.recovery, self.on_recovery_success, None, self.on_recovery_error)

    def on_finished(self):
        self.thread.stop()

    def on_ok_button_click(self):
        item = self.list.currentItem()
        account = item.data(self.ROLE_ACCOUNT)
        self.on_account_select(account)

    def recovery(self):
        network = Network.get_instance()
        coroutine = account_discovery(network, self.get_account_xpub)
        return network.run_from_another_thread(coroutine)

    def on_recovery_success(self, accounts):
        self.clear_content()
        if len(accounts) == 0:
            self.content.addWidget(QLabel(_('No existing accounts found.')))
            return
        self.content.addWidget(QLabel(_('Choose an account to restore.')))
        self.list = QListWidget()
        for account in accounts:
            item = QListWidgetItem(account['description'])
            item.setData(self.ROLE_ACCOUNT, account)
            self.list.addItem(item)
        self.list.clicked.connect(lambda: self.ok_button.setEnabled(True))
        self.content.addWidget(self.list)

    def on_recovery_error(self, exc_info):
        self.clear_content()
        self.content.addWidget(QLabel(_('Error: Account discovery failed.')))
        _logger.error(f"recovery error", exc_info=exc_info)

    def clear_content(self):
        for i in reversed(range(self.content.count())):
            self.content.itemAt(i).widget().setParent(None)


text:
"use strict";

var sdlServer = require('../index.js');

function importTest(name, path) {
    describe(name, function() {
        require(path);
    });
}

describe('SDL SERVER TESTS', function () {
    before(function(done) {
        this.timeout(16000);
        setTimeout(done, 15000);
    });

    describe('api', function() {
        describe('v1', function() {
            importTest('/applications', './api/v1/applications/applications');
            importTest('/applications/action', './api/v1/applications/action');
            importTest('/applications/auto', './api/v1/applications/auto');
            importTest('/staging/policy', './api/v1/policy/staging');
            importTest('/production/policy', './api/v1/policy/production');
            importTest('/policy/preview', './api/v1/policy/preview');
            importTest('/policy/apps', './api/v1/policy/apps');
            importTest('/permssions/update', './api/v1/permissions/update');
            importTest('/permissions/unmapped', './api/v1/permissions/unmapped');
            importTest('/groups', './api/v1/groups/groups');
            importTest('/groups/names', './api/v1/groups/names');
            importTest('/groups/promote', './api/v1/groups/promote');
            importTest('/messages', './api/v1/messages/messages');
            importTest('/messages/promote', './api/v1/messages/promote');
            importTest('/messages/update', './api/v1/messages/update');
            importTest('/messages/names', './api/v1/messages/names');
            importTest('/module', './api/v1/module/module');
            importTest('/module/promote', './api/v1/module/promote');
        });
    });

    importTest('cache', './cache/cache');
    importTest('basic-auth', './basicAuth/basicAuth');
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Noise++: noisepp/core/NoiseBlend.h Source File</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Classes

Files

noisepp/core/NoiseBlend.h

00001 // Noise++ Library
00002 // Copyright (c) 2008, Urs C. Hanselmann
00003 // All rights reserved.
00004 //
00005 // Redistribution and use in source and binary forms, with or without modification,
00006 // are permitted provided that the following conditions are met:
00007 //
00008 //    * Redistributions of source code must retain the above copyright notice,
00009 //      this list of conditions and the following disclaimer.
00010 //    * Redistributions in binary form must reproduce the above copyright notice,
00011 //      this list of conditions and the following disclaimer in the documentation
00012 //      and/or other materials provided with the distribution.
00013 //
00014 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
00015 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
00016 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
00017 // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
00018 // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
00019 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
00020 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
00021 // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00022 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
00023 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00024 //
00025
00026 #ifndef NOISEPP_BLEND_H
00027 #define NOISEPP_BLEND_H
00028
00029 #include "NoisePipeline.h"
00030 #include "NoiseModule.h"
00031
00032 namespace noisepp
00033 {
00034         class BlendElement1D : public PipelineElement1D
00035         {
00036                 private:
00037                         ElementID mLeft, mRight, mControl;
00038                         const PipelineElement1D *mLeftPtr;
00039                         const PipelineElement1D *mRightPtr;
00040                         const PipelineElement1D *mControlPtr;
00041
00042                 public:
00043                         BlendElement1D (const Pipeline1D *pipe, ElementID left, ElementID right, ElementID control) : mLeft(left), mRight(right), mControl(control)
00044                         {
00045                                 mLeftPtr = pipe->getElement(mLeft);
00046                                 mRightPtr = pipe->getElement(mRight);
00047                                 mControlPtr = pipe->getElement(mControl);
00048                         }
00049                         virtual Real getValue (Real x, Cache *cache) const
00050                         {
00051                                 Real leftValue, rightValue, blendValue;
00052
00053                                 leftValue = getElementValue (mLeftPtr, mLeft, x, cache);
00054                                 rightValue = getElementValue (mRightPtr, mRight, x, cache);
00055                                 blendValue = getElementValue (mControlPtr, mControl, x, cache);
00056
00057                                 return Math::InterpLinear (leftValue, rightValue, (blendValue + Real(1.0)) / Real(2.0));
00058                         }
00059         };
00060
00061         class BlendElement2D : public PipelineElement2D
00062         {
00063                 private:
00064                         ElementID mLeft, mRight, mControl;
00065                         const PipelineElement2D *mLeftPtr;
00066                         const PipelineElement2D *mRightPtr;
00067                         const PipelineElement2D *mControlPtr;
00068
00069                 public:
00070                         BlendElement2D (const Pipeline2D *pipe, ElementID left, ElementID right, ElementID control) : mLeft(left), mRight(right), mControl(control)
00071                         {
00072                                 mLeftPtr = pipe->getElement(mLeft);
00073                                 mRightPtr = pipe->getElement(mRight);
00074                                 mControlPtr = pipe->getElement(mControl);
00075                         }
00076                         virtual Real getValue (Real x, Real y, Cache *cache) const
00077                         {
00078                                 Real leftValue, rightValue, blendValue;
00079
00080                                 leftValue = getElementValue (mLeftPtr, mLeft, x, y, cache);
00081                                 rightValue = getElementValue (mRightPtr, mRight, x, y, cache);
00082                                 blendValue = getElementValue (mControlPtr, mControl, x, y, cache);
00083
00084                                 return Math::InterpLinear (leftValue, rightValue, (blendValue + Real(1.0)) / Real(2.0));
00085                         }
00086         };
00087
00088         class BlendElement3D : public PipelineElement3D
00089         {
00090                 private:
00091                         ElementID mLeft, mRight, mControl;
00092                         const PipelineElement3D *mLeftPtr;
00093                         const PipelineElement3D *mRightPtr;
00094                         const PipelineElement3D *mControlPtr;
00095
00096                 public:
00097                         BlendElement3D (const Pipeline3D *pipe, ElementID left, ElementID right, ElementID control) : mLeft(left), mRight(right), mControl(control)
00098                         {
00099                                 mLeftPtr = pipe->getElement(mLeft);
00100                                 mRightPtr = pipe->getElement(mRight);
00101                                 mControlPtr = pipe->getElement(mControl);
00102                         }
00103                         virtual Real getValue (Real x, Real y, Real z, Cache *cache) const
00104                         {
00105                                 Real leftValue, rightValue, blendValue;
00106
00107                                 leftValue = getElementValue (mLeftPtr, mLeft, x, y, z, cache);
00108                                 rightValue = getElementValue (mRightPtr, mRight, x, y, z, cache);
00109                                 blendValue = getElementValue (mControlPtr, mControl, x, y, z, cache);
00110
00111                                 return Math::InterpLinear (leftValue, rightValue, (blendValue + Real(1.0)) / Real(2.0));
00112                         }
00113         };
00114
00118         class BlendModule : public TripleSourceModule<BlendElement1D, BlendElement2D, BlendElement3D>
00119         {
00120                 public:
00122                         ModuleTypeId getType() const { return MODULE_BLEND; }
00123         };
00124 };
00125
00126 #endif


text:
#pragma once
#include <aws/workmail/WorkMail_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/workmail/model/Resource.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace WorkMail
{
namespace Model
{
  class AWS_WORKMAIL_API ListResourcesResult
  {
  public:
    ListResourcesResult();
    ListResourcesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ListResourcesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
One page of the organization's resource representation.

     */
    inline const Aws::Vector<Resource>& GetResources() const{ return m_resources; }

    /**
     *
One page of the organization's resource representation.

     */
    inline void SetResources(const Aws::Vector<Resource>& value) { m_resources = value; }

    /**
     *
One page of the organization's resource representation.

     */
    inline void SetResources(Aws::Vector<Resource>&& value) { m_resources = std::move(value); }

    /**
     *
One page of the organization's resource representation.

     */
    inline ListResourcesResult& WithResources(const Aws::Vector<Resource>& value) { SetResources(value); return *this;}

    /**
     *
One page of the organization's resource representation.

     */
    inline ListResourcesResult& WithResources(Aws::Vector<Resource>&& value) { SetResources(std::move(value)); return *this;}

    /**
     *
One page of the organization's resource representation.

     */
    inline ListResourcesResult& AddResources(const Resource& value) { m_resources.push_back(value); return *this; }

    /**
     *
One page of the organization's resource representation.

     */
    inline ListResourcesResult& AddResources(Resource&& value) { m_resources.push_back(std::move(value)); return *this; }

    /**
     *
 The token used to paginate through all the organization's resources. While
     * results are still available, it has an associated value. When the last page is
     * reached, the token is empty.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
 The token used to paginate through all the organization's resources. While
     * results are still available, it has an associated value. When the last page is
     * reached, the token is empty.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    /**
     *
 The token used to paginate through all the organization's resources. While
     * results are still available, it has an associated value. When the last page is
     * reached, the token is empty.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    /**
     *
 The token used to paginate through all the organization's resources. While
     * results are still available, it has an associated value. When the last page is
     * reached, the token is empty.

     */
    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    /**
     *
 The token used to paginate through all the organization's resources. While
     * results are still available, it has an associated value. When the last page is
     * reached, the token is empty.

     */
    inline ListResourcesResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
 The token used to paginate through all the organization's resources. While
     * results are still available, it has an associated value. When the last page is
     * reached, the token is empty.

     */
    inline ListResourcesResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
 The token used to paginate through all the organization's resources. While
     * results are still available, it has an associated value. When the last page is
     * reached, the token is empty.

     */
    inline ListResourcesResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::Vector<Resource> m_resources;

    Aws::String m_nextToken;
  };

} // namespace Model
} // namespace WorkMail
} // namespace Aws


text:
var forwardslash= function(position, board){

  while (position[0] < 5 && position[1] > 0){
      position[0]++;
      position[1]--;
    };
    var collection = [position];
    var row = position[0];
    var col = position[1];
    while (row > 0 && col<6){
      row--;
      col++;
      collection.push([row, col]);
    };
    var values = collection.map(function(loc) {return board[loc[0]][loc[1]]});
    return values;
  }

var backslash= function(position, board){

  while (position[0] > 0 && position[1] > 0){
      position[0]--;
      position[1]--;
    };
    var collection = [position];
    var row = position[0];
    var col = position[1];
    while (row < 5 && col <6){
      row++;
      col++;
      collection.push([row, col]);
    };
    var values = collection.map(function(loc) {return board[loc[0]][loc[1]]});
    return values;
  }

function getCol(board, loc) {
  var column = [];
  for (var i = 0; i < board.length; i++) {
    column.push(board[i][loc[1]]);
  }
  return column;
}


text:
package flag_test

import (
	. "code.cloudfoundry.org/cli/command/flag"
	flags "github.com/jessevdk/go-flags"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Megabytes", func() {
	var megabytes Megabytes

	Describe("UnmarshalFlag", func() {
		BeforeEach(func() {
			megabytes = Megabytes{}
		})

		When("the suffix is M", func() {
			It("interprets the number as megabytes", func() {
				err := megabytes.UnmarshalFlag("17M")
				Expect(err).ToNot(HaveOccurred())
				Expect(megabytes.Value).To(BeEquivalentTo(17))
			})
		})

		When("the suffix is MB", func() {
			It("interprets the number as megabytes", func() {
				err := megabytes.UnmarshalFlag("19MB")
				Expect(err).ToNot(HaveOccurred())
				Expect(megabytes.Value).To(BeEquivalentTo(19))
			})
		})

		When("the suffix is G", func() {
			It("interprets the number as gigabytes", func() {
				err := megabytes.UnmarshalFlag("2G")
				Expect(err).ToNot(HaveOccurred())
				Expect(megabytes.Value).To(BeEquivalentTo(2048))
			})
		})

		When("the suffix is GB", func() {
			It("interprets the number as gigabytes", func() {
				err := megabytes.UnmarshalFlag("3GB")
				Expect(err).ToNot(HaveOccurred())
				Expect(megabytes.Value).To(BeEquivalentTo(3072))
			})
		})

		When("the suffix is lowercase", func() {
			It("is case insensitive", func() {
				err := megabytes.UnmarshalFlag("7m")
				Expect(err).ToNot(HaveOccurred())
				Expect(megabytes.Value).To(BeEquivalentTo(7))
			})
		})

		When("the megabytes are invalid", func() {
			It("returns an error", func() {
				err := megabytes.UnmarshalFlag("invalid")
				Expect(err).To(MatchError(&flags.Error{
					Type:    flags.ErrRequired,
					Message: `Byte quantity must be an integer with a unit of measurement like M, MB, G, or GB`,
				}))
			})
		})

		When("a decimal is used", func() {
			It("returns an error", func() {
				err := megabytes.UnmarshalFlag("1.2M")
				Expect(err).To(MatchError(&flags.Error{
					Type:    flags.ErrRequired,
					Message: `Byte quantity must be an integer with a unit of measurement like M, MB, G, or GB`,
				}))
			})
		})

		When("the units are missing", func() {
			It("returns an error", func() {
				err := megabytes.UnmarshalFlag("37")
				Expect(err).To(MatchError(&flags.Error{
					Type:    flags.ErrRequired,
					Message: `Byte quantity must be an integer with a unit of measurement like M, MB, G, or GB`,
				}))
			})
		})

		When("the suffix is B", func() {
			It("returns an error", func() {
				err := megabytes.UnmarshalFlag("10B")
				Expect(err).To(MatchError(&flags.Error{
					Type:    flags.ErrRequired,
					Message: `Byte quantity must be an integer with a unit of measurement like M, MB, G, or GB`,
				}))
			})
		})

		When("value is empty", func() {
			It("sets IsSet to false", func() {
				err := megabytes.UnmarshalFlag("")
				Expect(err).NotTo(HaveOccurred())
				Expect(megabytes.IsSet).To(BeFalse())
			})
		})
	})
})


text:
layout: page
title: Seattle Police Officer 8377 Jonathan S. Goodwin
permalink: /information/agencies/city_of_seattle/seattle_police_department/copbook/8377/
---

**Age as of Feb. 24, 2016:** 32


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net;
using NuGet;
using Ookii.Dialogs.Wpf;

namespace PackageExplorer
{
    internal class WindowsCredentialProvider : ICredentialProvider
    {
        #region ICredentialProvider Members

        public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            return PromptUserForCredentials(uri, forcePrompt: true);
        }

        #endregion

        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
        private static ICredentials PromptUserForCredentials(Uri uri, bool forcePrompt)
        {
            string proxyHost = uri.Host;
            string credentialsTarget = string.Format(CultureInfo.InvariantCulture, "PackageExplorer_{0}", proxyHost);

            ICredentials basicCredentials = null;

            using (var dialog = new CredentialDialog())
            {
                dialog.Target = credentialsTarget;
                dialog.WindowTitle = string.Format(
                    CultureInfo.CurrentCulture, Resources.Resources.ProxyConnectToMessage, proxyHost);

                dialog.MainInstruction = dialog.WindowTitle;
                dialog.ShowUIForSavedCredentials = forcePrompt;
                dialog.ShowSaveCheckBox = true;
                if (dialog.ShowDialog())
                {
                    basicCredentials = dialog.Credentials;
                    if (dialog.IsSaveChecked)
                    {
                        CredentialDialog.StoreCredential(credentialsTarget, dialog.Credentials);
                    }
                }
            }
            return basicCredentials;
        }
    }
}


text:
using ElectronicObserver.Utility.Mathematics;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ElectronicObserver.Resource.Record
{

	/// <summary>
	/// レコードの基底です。
	/// </summary>
	public abstract class RecordBase
	{

		/// <summary>
		/// レコードの要素の基底です。
		/// </summary>
		public abstract class RecordElementBase
		{

			public abstract void LoadLine(string line);
			public abstract string SaveLine();

		}

		/// <summary>
		/// ファイルからレコードを読み込みます。
		/// </summary>
		/// <param name="path">ファイルが存在するフォルダのパス。</param>
		public virtual bool Load(string path)
		{

			path = GetFilePath(path);

			try
			{
				bool hasError = false;

				using (StreamReader sr = new StreamReader(path, Utility.Configuration.Config.Log.FileEncoding))
				{

					ClearRecord();

					bool ignoreError = false;

					string line;
					sr.ReadLine();          //ヘッダを読み飛ばす

					while ((line = sr.ReadLine()) != null)
					{
						try
						{
							LoadLine(line);

						}
						catch (Exception ex)
						{
							if (ignoreError)
								continue;

							hasError = true;
							Utility.ErrorReporter.SendErrorReport(ex, $"レコード {Path.GetFileName(path)} の破損を検出しました。");

							switch (MessageBox.Show($"レコード {Path.GetFileName(path)} で破損データを検出しました。\r\n\r\n[中止]: 読み込みを中止します。データを失う可能性があります。\r\n[再試行]: <推奨>読み込みを続行します。\r\n[無視]: 読み込みを続行します。(以降再確認しません。)",
								"レコード破損検出", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2))
							{
								case DialogResult.Abort:
									throw;

								case DialogResult.Retry:
									// do nothing
									break;

								case DialogResult.Ignore:
									ignoreError = true;
									break;
							}
						}
					}

				}

				if (hasError)
				{
					string backupDestination = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + "_backup_" + DateTimeHelper.GetTimeStamp() + Path.GetExtension(path));
					File.Copy(path, backupDestination);
					Utility.Logger.Add(3, $"修復前のレコードを {backupDestination} に退避しました。復旧に失敗した場合はこのファイルから復元を試みてください。");

					SaveAll(RecordManager.Instance.MasterPath);
				}

				UpdateLastSavedIndex();
				return true;

			}
			catch (FileNotFoundException)
			{
				Utility.Logger.Add(1, "レコード " + path + " は存在しません。");

			}
			catch (Exception ex)
			{
				Utility.ErrorReporter.SendErrorReport(ex, "レコード " + path + " の読み込みに失敗しました。");
			}

			return false;
		}

		/// <summary>
		/// ファイルに全てのレコードを書き込みます。
		/// </summary>
		/// <param name="path">ファイルが存在するフォルダのパス。</param>
		public virtual bool SaveAll(string path)
		{

			path = GetFilePath(path);

			try
			{

				using (StreamWriter sw = new StreamWriter(path, false, Utility.Configuration.Config.Log.FileEncoding))
				{

					sw.WriteLine(RecordHeader);
					sw.Write(SaveLinesAll());

				}

				UpdateLastSavedIndex();
				return true;

			}
			catch (Exception ex)
			{
				Utility.ErrorReporter.SendErrorReport(ex, "レコード " + path + " の書き込みに失敗しました。");
			}

			return false;
		}

		/// <summary>
		/// ファイルに前回からの差分を追記します。
		/// </summary>
		/// <param name="path">ファイルが存在するフォルダのパス。</param>
		public virtual bool SavePartial(string path)
		{

			if (!SupportsPartialSave)
				return false;

			path = GetFilePath(path);
			bool exists = File.Exists(path);

			try
			{

				using (StreamWriter sw = new StreamWriter(path, true, Utility.Configuration.Config.Log.FileEncoding))
				{

					if (!exists)
						sw.WriteLine(RecordHeader);

					sw.Write(SaveLinesPartial());
				}

				UpdateLastSavedIndex();
				return true;

			}
			catch (Exception ex)
			{
				Utility.ErrorReporter.SendErrorReport(ex, "レコード " + path + " の書き込みに失敗しました。");
			}

			return false;
		}

		protected string GetFilePath(string path)
		{
			return path.Trim(@" \\""".ToCharArray()) + "\\" + FileName;
		}

		/// <summary>
		/// ファイルから読み込んだデータを解析し、レコードに追加します。
		/// </summary>
		/// <param name="line">読み込んだ一行分のデータ。</param>
		protected abstract void LoadLine(string line);

		/// <summary>
		/// レコードのデータをファイルに書き込める文字列に変換します。
		/// </summary>
		protected abstract string SaveLinesAll();

		/// <summary>
		/// レコードの差分データをファイルに書き込める文字列に変換します。
		/// </summary>
		protected abstract string SaveLinesPartial();

		public abstract bool SupportsPartialSave { get; }

		/// <summary>
		/// レコードをクリアします。ロード直前に呼ばれます。
		/// </summary>
		protected abstract void ClearRecord();

		protected abstract void UpdateLastSavedIndex();

		public abstract bool NeedToSave { get; }

		public abstract void RegisterEvents();

		/// <summary>
		/// レコードのヘッダを取得します。
		/// </summary>
		public abstract string RecordHeader { get; }

		/// <summary>
		/// 保存するファイル名を取得します。
		/// </summary>
		public abstract string FileName { get; }

	}

}


text:
<!--
  ~ Copyright 2016 Red Hat, Inc. and/or its affiliates
  ~ and other contributors as indicated by the @author tags.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <artifactId>keycloak-user-storage-properties</artifactId>
    <groupId>de.codecentric.keycloak</groupId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>

        <properties>
        <version.compiler.maven.plugin>3.5.1</version.compiler.maven.plugin>
        <version.hibernate.javax.persistence>1.0.0.Final</version.hibernate.javax.persistence>
        <version.jboss-ejb-api>1.0.0.Final</version.jboss-ejb-api>
        <arquillian-graphene.version>2.3.2</arquillian-graphene.version>
        <arquillian-phantom.version>1.2.1.Final</arquillian-phantom.version>
        <version.junit>4.12</version.junit>
        <version.wildfly.maven.plugin>1.2.2.Final</version.wildfly.maven.plugin>
        <keycloak.version>4.6.0.Final</keycloak.version>
        <wildfly.version>11.0.0.Final</wildfly.version>
        <jackson.version>2.9.5</jackson.version>
        <selenium-bom.version>3.11.0</selenium-bom.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.jboss.arquillian</groupId>
                <artifactId>arquillian-bom</artifactId>
                <version>1.4.0.Final</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.wildfly.bom</groupId>
                <artifactId>wildfly-javaee7</artifactId>
                <version>${wildfly.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-core</artifactId>
            <version>${keycloak.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
                <groupId>org.jboss.arquillian.selenium</groupId>
                <artifactId>selenium-bom</artifactId>
                <version>${selenium-bom.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-server-spi</artifactId>
            <version>${keycloak.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-server-spi-private</artifactId>
            <scope>provided</scope>
            <version>${keycloak.version}</version>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-services</artifactId>
            <scope>provided</scope>
            <version>${keycloak.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>${version.hibernate.javax.persistence}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.spec.javax.ejb</groupId>
            <artifactId>jboss-ejb-api_3.2_spec</artifactId>
            <version>${version.jboss-ejb-api}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.graphene</groupId>
            <artifactId>graphene-webdriver</artifactId>
            <version>${arquillian-graphene.version}</version>
            <type>pom</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.extension</groupId>
            <artifactId>arquillian-phantom-driver</artifactId>
            <version>${arquillian-phantom.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.junit</groupId>
            <artifactId>arquillian-junit-container</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${version.junit}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.keycloak</groupId>
            <artifactId>keycloak-test-helper</artifactId>
            <version>${keycloak.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>maven.oracle.com</id>
            <name>oracle-maven-repo</name>
            <url>https://maven.oracle.com</url>
            <layout>default</layout>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
            </releases>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>maven.oracle.com</id>
            <name>oracle-maven-repo</name>
            <url>https://maven.oracle.com</url>
            <layout>default</layout>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
            </releases>
        </pluginRepository>
    </pluginRepositories>

    <build>
        <finalName>authenticator-required-action-example</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${version.compiler.maven.plugin}</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <version>${version.wildfly.maven.plugin}</version>
                <configuration>
                    <skip>false</skip>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-enforcer-plugin</artifactId>
                <executions>
                    <execution>
                        <id>enforce-quickstart-realm-file-exist</id>
                        <phase>validate</phase>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
import sbt._

object Deps {
    val akkaActor = "com.typesafe.akka" %% "akka-actor" % Versions.akka
    val akkaStream = "com.typesafe.akka" %% "akka-stream" % Versions.akka
    val akkaSlf = "com.typesafe.akka" %% "akka-slf4j" % Versions.akka
    val akkaTest = "com.typesafe.akka" %% "akka-testkit" % Versions.akka
    val logback = "ch.qos.logback" % "logback-classic" % Versions.logback
    val scalaTest = "org.scalatest" %% "scalatest" % Versions.scalaTest
    val snmp4j = "org.snmp4j" % "snmp4j" % Versions.snmp4j

    val ficus = "com.iheart" %% "ficus" % Versions.ficus
}


text:
<?php
/**
 * Maze.core
 *
 * @license http://opensource.org/licenses/MIT MIT
 */

/**
 * Core_Form_AddNode
 *
 * @license http://opensource.org/licenses/MIT MIT
 */
class Core_Form_AddNode extends Zend_Form
{
    protected $_elementDecorators = array(
        'ViewHelper',
        'TwitterBootstrapError'
    );

    public function __construct($options = null)
    {
        $this->addPrefixPath('MazeLib_Form_Decorator_', 'MazeLib/Form/Decorator/', 'decorator');
        parent::__construct($options);
    }

    public function init()
    {
        $this->addElement("select", "nodetype", array(
            "label" => "node type",
            "multiOptions" => array(
                "" => "Assign a server type",
                Core_Form_Node::SERVER_VIRTUAL   => "Virtual Server",
                Core_Form_Node::SERVER_CLOUD     => "Cloud Server",
                Core_Form_Node::SERVER_DEDICATED => "Dedicated Server"
            ),
            "class" => "selectpicker show-menu-arrow show-tick",
            "value" => array("")
        ));

        $this->addElement('text', 'name', array(
            'required' => true,
            'label' => 'node name *',
        ));
        $this->addElement('text', 'ipAddress', array(
            'label' => 'ip address *',
            'required' => true,
            'validators' => array(
                new Zend_Validate_Hostname(
                    array(
                        'allow' => Zend_Validate_Hostname::ALLOW_DNS
                                 | Zend_Validate_Hostname::ALLOW_IP,
                        'idn'   => true
                    )
                )
            )
        ));
        $this->addElement('hidden', 'apiKey');

        $this->setElementDecorators($this->_elementDecorators);
    }

}


text:
describe ('Thermostat',function(){
  var thermostat;

  beforeEach(function(){
    thermostat = new Thermostat();
  });

  it ('shows 20 degrees as default', function(){
    expect(thermostat.showTemperature()).toEqual(20);
  });

  it ('increases temperature by 1 degree', function(){
  	expect(thermostat.increaseTemperatureBy1()).toEqual(21);
  });

  it ('decreases temperature by 1 degree', function() {
  	expect(thermostat.decreaseTemperatureBy1()).toEqual(19);
  });

  it ('can be reset to 20 degrees in one click', function() {
  	thermostat.resetTemperature();
  	expect(thermostat.temperature).toEqual(20);
  });

  it ('does not allow temperature below 10 degrees', function(){
    for(var i=0; i <= 10; i++) {
      thermostat.decreaseTemperatureBy1();
    }
    expect(function(){thermostat.decreaseTemperatureBy1();}).toThrow(new Error("Error!"));
  });

  it ('has power saving mode on by default', function(){
    expect(thermostat.powerSavingMode).toEqual("On");
  });

  it ('can have power saving mode switched off', function() {
   thermostat.switchPowerSavingMode();
   expect(thermostat.powerSavingMode).toEqual("Off");
  });

  it ('can have power saving mode switched on', function() {
   thermostat.switchPowerSavingMode();
   thermostat.switchPowerSavingMode();
   expect(thermostat.powerSavingMode).toEqual("On");
  });

  it ('does not allow to increase temperature from 25 degrees when PSM is on', function(){
    for(var i=0; i < 5; i++) {
      thermostat.increaseTemperatureBy1();
    }
    expect(function(){thermostat.increaseTemperatureBy1();}).toThrow(new Error("Error!"));
  });

  it ('does not allow to increase temperature from 32 degrees when PSM is off', function(){
    thermostat.switchPowerSavingMode();
    for(var i=0; i < 12; i++) {
      thermostat.increaseTemperatureBy1();
    }
    expect(function(){thermostat.increaseTemperatureBy1();}).toThrow(new Error("Error!"));
  });

  it ('allows to increase temperature to 30 degrees when PSM is off', function(){
    thermostat.switchPowerSavingMode();
    for(var i=0; i < 9; i++) {
      thermostat.increaseTemperatureBy1();
    }
    expect(thermostat.increaseTemperatureBy1()).toEqual(30);
  });

});


text:
cask 'pref-setter' do
  version :latest
  sha256 :no_check

  url 'http://www.nightproductions.net/downloads/prefsetter.zip'
  appcast 'http://www.nightproductions.net/feeds/prefsetter.xml',
          :sha256 => 'f1b7198f1e689695eb730cf7d68fb39e802f146213c2e41ab5b1c381ffdfc357'
  name 'Pref Setter'
  homepage 'http://www.nightproductions.net/prefsetter.html'
  license :gratis

  app 'Pref Setter/Pref Setter.app'
end


text:
<?php

declare(strict_types = 1);

namespace dpi\ak;

use dpi\ak\AvatarKit\AvatarServices\AvatarServiceInterface;
use dpi\ak\Exception\AvatarFactoryException;

/**
 * Avatar service factory.
 */
class AvatarServiceFactory implements AvatarServiceFactoryInterface {

  /**
   * Avatar service discovery.
   *
   * @var \dpi\ak\AvatarServiceDiscoveryInterface
   */
  protected $discovery;

  /**
   * AvatarServiceFactory constructor.
   *
   * @param \dpi\ak\AvatarServiceDiscoveryInterface $avatarServiceDiscovery
   *   Avatar service discovery.
   */
  public function __construct(AvatarServiceDiscoveryInterface $avatarServiceDiscovery) {
    $this->discovery = $avatarServiceDiscovery;
  }

  /**
   * {@inheritdoc}
   */
  public function createService(string $id, AvatarConfigurationInterface $configuration) : AvatarServiceInterface {
    // @todo if plugin is remote, require a destination for avatars.
    $metadata = $this->discovery->getMetadata($id);

    // Protocol.
    if (!empty($metadata->protocols)) {
      $protocols = $metadata->protocols;

      $protocol = $configuration->getProtocol();
      if (is_string($protocol)) {
        if (!in_array($protocol, $protocols)) {
          throw new AvatarFactoryException('Invalid or undefined protocol.');
        }
      }
    }

    // Dimensions.
    $width = $configuration->getWidth();
    $height = $configuration->getHeight();
    if ($width || $height) {
      if (!empty($metadata->dimensions)) {
        // Dimensions validator.
        $regex = '/^(?<minx>\d*)x(?<miny>\d*)\-(?<maxx>\d*)x(?<maxy>\d*)$/D';
        $dimensions = $metadata->dimensions;
        preg_match_all($regex, $dimensions, $matches, PREG_SET_ORDER);
        $valid_x = !$width || ($width >= $matches[0]['minx'] && $width <= $matches[0]['maxx']);
        $valid_y = !$height || ($height >= $matches[0]['miny'] && $height <= $matches[0]['maxy']);
        if (!($valid_x && $valid_y)) {
          throw new AvatarFactoryException('Requested dimensions failed validation.');
        }
      }
    }

    $class = $this->discovery->getClass($id);
    $instance = $this->newInstance($class, $configuration);

    return $instance;
  }

  /**
   * Create a new instance of a avatar service.
   *
   * @param string $class
   *   The class to instantiate.
   * @param \dpi\ak\AvatarConfigurationInterface $configuration
   *   The configuration of the avatar service.
   *
   * @return \dpi\ak\AvatarKit\AvatarServices\AvatarServiceInterface
   *   Return a new avatar service.
   */
  protected function newInstance(string $class, AvatarConfigurationInterface $configuration) : AvatarServiceInterface {
    return new $class($configuration);
  }

}


text:
ROOT = ../../../../..

DIR = Pegasus/Config/tests/ConfigManager

include $(ROOT)/mak/config.mak

include ../libraries.mak

LOCAL_DEFINES = -DPEGASUS_INTERNALONLY

PROGRAM = TestConfigManager

SOURCES = ConfigManager.cpp

include $(ROOT)/mak/program.mak

LOCAL_FILES_TO_CLEAN = \
	$(TMP_DIR)/cimserver_planned.conf \
	$(TMP_DIR)/cimserver_planned.conf.bak \
	$(TMP_DIR)/cimserver_current.conf \
	$(TMP_DIR)/cimserver_current.conf.bak

tests:
	$(COPY) ../../../../Server/cimserver_planned.conf $(TMP_DIR)/cimserver_planned.conf
	$(COPY) ../../../../Server/cimserver_planned.conf $(TMP_DIR)/cimserver_current.conf
	$(PROGRAM)
	$(RM) $(LOCAL_FILES_TO_CLEAN)

poststarttests: