<commit_before>(function ($, audiojs) {
    'use strict';

    $.fn.addPlayer = function (preload) {
        if ($(this).length !== 1) {
            throw new Error('Cannot instantiate player on ' +
                            'multiple/null selector');
        }
        if (!$(this).data('js-player')) {
            $(this).data('js-player', new Player($(this), preload));
        }
        return $(this).data('js-player');
    };

    var Track = function (src, title, dur, poster_src, pod_id, last_pos, played) {
        return {
            src: src,
            title: title,
            duration: dur,
            poster: poster_src,
            podcast: Number(pod_id),
            last_pos: (last_pos) ? last_pos : 0,
            played: (played) ? played : false
        };
    };

    var TrackElement = function (track) {
        var el = $('

' +
                   '
' +
                   '  ' +
                   '

' + track.title +
                   '

');
        return el;
    };

    var PlayMode = {
        continue: 0x01,
        repeat: 0x02
    };

    var Player = function (parentElement, preload) {
        if (!preload) preload = {};
        var P = {
            _dom: $('

'),
            _mode: (preload.mode) ? preload.mode : 0,
            header: new Header(),
            audio: new AudioPlayer(),
            playlist: new PlayList(preload.playlist),

            init: function (volume) {
                this.audio.init(this, volume);
                this._dom.find('.player-list ol').click(function (e) {
                    var li = ($(e.target).is('li')) ? $(e.target) :
                            $(e.target).closest('li'),
                        index = li.index(),
                        div = ($(e.target).is('div'))? $(e.target) :
                            $(e.target).closest('div');
                    if (div.hasClass('pl-btn-del')) {
                        P.delete(index);
                    }
                    else {
                        P.load(index);
                        P.play();
                    }
                });
            },
            error: function (e) {
                console.log(e);
                this.header.loadError(this.playlist.getTrack());
                this._showState('error');
            },
            load: function (index) {
                var track = this.playlist.load(index);
                this._showState('load');
                this.audio.load(track);
                this.header.load(track);
            },
            unload: function () {
                this.header.load();
                this._showState();
            },
            add: function (src, title, dur, poster_src, pod_id) {
                var i = this.playlist.add(
                    src, title, dur, poster_src, pod_id);
                if (i === 0) this.load(i);
            },
            delete: function (index) {
                var c = this.playlist._cur;
                if (c === index) {
                    this.stop();
                    if (this.playlist.count() > 1) this.nextTrack(true);
                    else this.unload();
                }
                this.playlist.delete(index);
            },
            addAndPlay: function (src, title, dur, poster_src, pod_id) {
                var i = this.playlist.insert(
                    src, title, dur, poster_src, pod_id);
                this.load(i);
                this.play();
                this._dom[0].scrollIntoView();
            },
            stop: function () {
                this.pause();
                this.reset();
            },
            play: function () {
                if (this.playlist.getTrack()) {
                    this.audio.play();
                    this._showState('play');
                }
            },
            pause: function () {
                if (this.playlist.getTrack()) {
                    this.audio.pause();
                    this._showState('pause');
                }
            },
            trackFinished: function () {
                this.playlist.finished();
                if (this.isMode(PlayMode.continue)) {
                    var t = this.playlist.next();
                    if (t !== -1 || this.isMode(PlayMode.repeat)) {
                        this.nextTrack();
                    }
                }
                else if (this.isMode(PlayMode.repeat)) {
                    this.reset();
                    this.play();
                }
            },
            reset: function () {
                this.audio.reset();
            },
            nextTrack: function (noplay) {
                var t = this.playlist.next();
                if (t === -1) t = 0;
                this.load(t);
                if (!noplay) this.play();
            },
            prevTrack: function () {
                var t = this.playlist.prev();
                if (t === -1) t = this.playlist.count() - 1;
                this.load(t);
                this.play();
            },
            skipAhead: function (sec) {
                this.audio.skipAhead(sec);
            },
            skipBack: function (sec) {
                this.audio.skipBack(sec);
            },
            addMode: function (mode) {
                mode = (Number(mode) == mode) ? mode : Modes[mode];
                this._mode = this._mode | mode;
            },
            remMode: function (mode) {
                mode = (Number(mode) == mode) ? mode : Modes[mode];
                this._mode = this._mode & ~mode;
            },
            isMode: function () {
                var i;
                if (arguments.length < 1) return false;
                for (i = 0; i < arguments.length; i++) {
                    if (!(this._mode & arguments[i])) return false;
                }
                return true;
            },
            setVolume: function (vol) {
                this.audio.setVolume(vol);
            },
            _showState: function (type) {
                var all = 'p-play p-pause p-load p-error',
                    pp = this._dom.find('.play-pause'),
                    Types = {
                    play: 'p-play',
                    pause: 'p-pause',
                    load: 'p-load',
                    error: 'p-error'
                };
                if (!type) pp.removeClass(all);
                else if (!Types[type]) throw new Error('Cannot display state: ' + type);
                else if (!pp.hasClass(Types[type])) {
                    pp.removeClass(all);
                    pp.addClass(Types[type]);
                }
            }
        };
        P.header._dom.append(P.audio._dom);
        P._dom.append(P.header._dom);
        P._dom.append(P.playlist._dom);
        parentElement.append(P._dom);
        P.init(preload.volume);
        return P;
    };

    var Header = function () {
        var H = {
            _dom: $('
' +
                    '

' +
                    '
'),
            _marquee_speed: 200, // miliseconds per character

            load: function (track) {
                if (!track) this._unload();
                else {
                    this._insertTitle(track.title);
                }
            },

            loadError: function (track) {

            },

            _unload: function () {
                this._insertTitle("No track selected.");
            },

            _insertTitle: function (msg) {
                this._dom.find('.titlebar').html(msg).marquee({
                    duration: msg.length * this._maruqee_speed,
                    gap: 170,
                    delayBeforeStart: 0,
                    direction: 'left',
                    duplicated: true
                });
            }
        };
        return H;
    };

    var AudioPlayer = function () {
        var AP = {
            _dom: $('
<audio preload></audio>
'),
            _audio: false,

            init: function (player, volume) {
                if (!volume) volume = 0.75;
                if ($(this._dom.getUnique()).length < 1) {
                    throw new Error('Cannot initialize AudioPlayer that is ' +
                                    'not attached to the current DOM.');
                }
                this._audio = audiojs.newInstance(this._dom.find('audio')[0], {
                    trackEnded: function () {
                        player.trackFinished();
                    }
                });
                this._audio.onError = function (e) {
                    player.error(e);
                };
                this._dom.find('.play-pause').click(function () {
                    console.log('playpause: \n\t');
                    console.log($(this));
                    if ($(this).hasClass('p-play')) {
                        player.pause();
                    }
                    else if ($(this).hasClass('p-pause')) {
                        player.play();
                    }
                });
                this._dom.find('.skip.ahead').click(function () {
                    player.skipAhead(30);
                });
                this._dom.find('.skip.back').click(function () {
                    player.skipBack(15);
                });
                this._dom.find('.volume').click(function () {
                    var time = $(this).closest('.audiojs').find('.time');
                    if (time.find('span').css('display') != 'none') {
                        $(this).newTip(true, 'Close');
                        time.find('span').css('display', 'none');
                        time.find('.slider').css('display', 'block');
                        $(this).css('color', '#ccc');
                    }
                    else {
                        $(this).newTip(true, 'Adjust Volume');
                        time.find('span').css('display', 'block');
                        time.find('.slider').css('display', 'none');
                        $(this).css('color', '#777');
                    }
                });
                this._dom.find('.slider').slider({
                    range: "min",
                    min: 0,
                    max: 40,
                    value: volume * 40,
                    slide: function (event, ui) {
                        player.setVolume(ui.value/40);
                    }
                });
                player.setVolume(this._dom.find('.slider').slider('value')/40);
                this._dom.find('[title]').newTip();
            },

            load: function (src) {
                if (!src) this._unload();
                else {
                    if (typeof(src) === 'object') src = src.src;
                    this._audio.load(src);
                }
            },

            _unload: function () {
            },

            play: function () {
                this._audio.play();
            },

            pause: function () {
                this._audio.pause();
            },

            playPause: function () {
                this._audio.playPause();
            },

            skipTo: function (position) {
                var percent, a = this._dom.find('audio')[0];
                position = (position < 0) ? 0 :
                        (position > a.duration) ? a.duration : position;
                percent = Math.floor(position / a.duration * 100) / 100;
                this._audio.skipTo(percent);
            },

            skipAhead: function (seconds) {
                var a = this._dom.find('audio')[0];
                this.skipTo(a.currentTime + seconds);
            },

            skipBack: function (seconds) {
                this.skipAhead(seconds * -1);
            },

            reset: function () {
                this.skipTo(0);
            },

            isPlaying: function () {
                return this._audio.playing;
            },

            getPosition: function () {
                return Math.floor(this._dom.find('audio')[0].currentTime);
            },

            setVolume: function (vol) {
                var el = this._dom.find('.volume');
                if (vol === this._dom.find('audio')[0].volume) return;
                this._audio.setVolume(vol);
                el.find('.glyphicon').css('display', 'none');
                if (vol === 0) {
                    el.find('.glyphicon-volume-off').css('display', 'block');
                }
                else if (vol === 1) {
                    el.find('.glyphicon-volume-up').css('display', 'block');
                }
                else {
                    el.find('.glyphicon-volume-down').css('display', 'block');
                }
            },

        };
        return AP;
    };

    var PlayList = function (list) {
        var PL = {
            _dom: $('

'),
            _list: [],
            _cur: 0,

            add: function (src, title, dur, poster_src, pod_id) {
                var track, played, index, el;
                if (typeof(src) === 'object') {
                    track = src;
                    autoload = title;
                }
                else {
                    track = new Track(src, title, dur, poster_src, pod_id);
                }
                if (this.hasTrack(track)) {
                    throw new Error('Track already in playlist.');
                }
                el = new TrackElement(track);
                this._list.push(track);
                this._appendElement(el);
                index = this.count() - 1;
                if (track.played) this._markPlayed(index);
                return index;
            },

            insert: function (src, title, dur, poster_src, pod_id) {
                var track, played, el;
                if (typeof(src) === 'object') {
                    track = src;
                    autoload = title;
                }
                else {
                    track = new Track(src, title, dur, poster_src, pod_id);
                }
                if (this.hasTrack(track)) {
                    throw new Error('Track already in playlist.');
                }
                el = new TrackElement(track);
                this._list.unshift(track);
                this._insertElement(el);
                if (track.played) this._markPlayed(0);
                if (this.count() !== 1) this._cur++;
                return 0;
            },

            delete: function (index) {
                var rem, element;
                if (this._list[index]) {
                    element = $(this._dom.find('li')[index]);
                    this._list.splice(index, 1);
                    this._removeElement(element);
                }
                if (index <= this._cur) this._cur--;
            },

            load: function (index) {
                var item, element;
                if (index < 0) index = this.count() - 1;
                if (index >= this.count()) index = 0;
                if (!this.getTrack(index)) {
                    return false;
                }
                this._cur = index;
                item = this.getTrack();
                element = $(this._dom.find('li')[index]);
                item.played = false;
                $(element).parent().find('.loaded').removeClass('loaded');
                $(element).removeClass('played');
                $(element).addClass('loaded');
                return item;
            },

            getTrack: function (index) {
                index = (Number(index) === index) ? index : this._cur;
                if (this.count() === 0 || !this._list[index]) {
                    return false;
                }
                return this._list[index];
            },

            hasTrack: function (track_or_src) {
                var src = track_or_src, filter;
                if (typeof(src) !== 'string') {
                    src = src.src;
                }
                filter = this._list.filter(function (track) {
                    return track.src === src;
                })[0];
                return (typeof(filter) !== 'undefined');
            },

            next: function () {
                if (!this._cur || this._cur === this.count() - 1) return -1;
                return this._cur + 1;
            },

            prev: function () {
                if (this._cur === 0) return -1;
                return this._cur - 1;
            },

            finished: function (index) {
                if (!index) index = this._cur;
                if (this._list[index]) {
                    this._list[index].played = true;
                    this._markPlayed(index);
                }
            },

            _markPlayed: function (index) {
                if (this._list[index]) {
                    $(this._list[index].selector).addClass('played');
                }
            },

            count: function () { return this._list.length; },

            _insertElement: function (el) {
                $(this._dom).find('ol').prepend(el);
                el.animate({opacity: 1}, 500);
            },

            _appendElement: function (el) {
                $(this._dom).find('ol').append(el);
                el.animate({opacity: 1}, 500);
            },

            _removeElement: function (el) {
                el.animate({height: '0px', opacity: 0}, 250, function () {
                    el.remove();
                });
            }
        };
        while (list && list.length > 0) {
            PL.insert(list.pop(), false);
        }
        return PL;
    };

}(jQuery, audiojs));<commit_msg>[Fix] Typo<commit_after>(function ($, audiojs) {
    'use strict';

    $.fn.addPlayer = function (preload) {
        if ($(this).length !== 1) {
            throw new Error('Cannot instantiate player on ' +
                            'multiple/null selector');
        }
        if (!$(this).data('js-player')) {
            $(this).data('js-player', new Player($(this), preload));
        }
        return $(this).data('js-player');
    };

    var Track = function (src, title, dur, poster_src, pod_id, last_pos, played) {
        return {
            src: src,
            title: title,
            duration: dur,
            poster: poster_src,
            podcast: Number(pod_id),
            last_pos: (last_pos) ? last_pos : 0,
            played: (played) ? played : false
        };
    };

    var TrackElement = function (track) {
        var el = $('

' +
                   '
' +
                   '  ' +
                   '

' + track.title +
                   '

');
        return el;
    };

    var PlayMode = {
        continue: 0x01,
        repeat: 0x02
    };

    var Player = function (parentElement, preload) {
        if (!preload) preload = {};
        var P = {
            _dom: $('

'),
            _mode: (preload.mode) ? preload.mode : 0,
            header: new Header(),
            audio: new AudioPlayer(),
            playlist: new PlayList(preload.playlist),

            init: function (volume) {
                this.audio.init(this, volume);
                this._dom.find('.player-list ol').click(function (e) {
                    var li = ($(e.target).is('li')) ? $(e.target) :
                            $(e.target).closest('li'),
                        index = li.index(),
                        div = ($(e.target).is('div'))? $(e.target) :
                            $(e.target).closest('div');
                    if (div.hasClass('pl-btn-del')) {
                        P.delete(index);
                    }
                    else {
                        P.load(index);
                        P.play();
                    }
                });
            },
            error: function (e) {
                console.log(e);
                this.header.loadError(this.playlist.getTrack());
                this._showState('error');
            },
            load: function (index) {
                var track = this.playlist.load(index);
                this._showState('load');
                this.audio.load(track);
                this.header.load(track);
            },
            unload: function () {
                this.header.load();
                this._showState();
            },
            add: function (src, title, dur, poster_src, pod_id) {
                var i = this.playlist.add(
                    src, title, dur, poster_src, pod_id);
                if (i === 0) this.load(i);
            },
            delete: function (index) {
                var c = this.playlist._cur;
                if (c === index) {
                    this.stop();
                    if (this.playlist.count() > 1) this.nextTrack(true);
                    else this.unload();
                }
                this.playlist.delete(index);
            },
            addAndPlay: function (src, title, dur, poster_src, pod_id) {
                var i = this.playlist.insert(
                    src, title, dur, poster_src, pod_id);
                this.load(i);
                this.play();
                this._dom[0].scrollIntoView();
            },
            stop: function () {
                this.pause();
                this.reset();
            },
            play: function () {
                if (this.playlist.getTrack()) {
                    this.audio.play();
                    this._showState('play');
                }
            },
            pause: function () {
                if (this.playlist.getTrack()) {
                    this.audio.pause();
                    this._showState('pause');
                }
            },
            trackFinished: function () {
                this.playlist.finished();
                if (this.isMode(PlayMode.continue)) {
                    var t = this.playlist.next();
                    if (t !== -1 || this.isMode(PlayMode.repeat)) {
                        this.nextTrack();
                    }
                }
                else if (this.isMode(PlayMode.repeat)) {
                    this.reset();
                    this.play();
                }
            },
            reset: function () {
                this.audio.reset();
            },
            nextTrack: function (noplay) {
                var t = this.playlist.next();
                if (t === -1) t = 0;
                this.load(t);
                if (!noplay) this.play();
            },
            prevTrack: function () {
                var t = this.playlist.prev();
                if (t === -1) t = this.playlist.count() - 1;
                this.load(t);
                this.play();
            },
            skipAhead: function (sec) {
                this.audio.skipAhead(sec);
            },
            skipBack: function (sec) {
                this.audio.skipBack(sec);
            },
            addMode: function (mode) {
                mode = (Number(mode) == mode) ? mode : Modes[mode];
                this._mode = this._mode | mode;
            },
            remMode: function (mode) {
                mode = (Number(mode) == mode) ? mode : Modes[mode];
                this._mode = this._mode & ~mode;
            },
            isMode: function () {
                var i;
                if (arguments.length < 1) return false;
                for (i = 0; i < arguments.length; i++) {
                    if (!(this._mode & arguments[i])) return false;
                }
                return true;
            },
            setVolume: function (vol) {
                this.audio.setVolume(vol);
            },
            _showState: function (type) {
                var all = 'p-play p-pause p-load p-error',
                    pp = this._dom.find('.play-pause'),
                    Types = {
                    play: 'p-play',
                    pause: 'p-pause',
                    load: 'p-load',
                    error: 'p-error'
                };
                if (!type) pp.removeClass(all);
                else if (!Types[type]) throw new Error('Cannot display state: ' + type);
                else if (!pp.hasClass(Types[type])) {
                    pp.removeClass(all);
                    pp.addClass(Types[type]);
                }
            }
        };
        P.header._dom.append(P.audio._dom);
        P._dom.append(P.header._dom);
        P._dom.append(P.playlist._dom);
        parentElement.append(P._dom);
        P.init(preload.volume);
        return P;
    };

    var Header = function () {
        var H = {
            _dom: $('
' +
                    '

' +
                    '
'),
            _marquee_speed: 200, // miliseconds per character

            load: function (track) {
                if (!track) this._unload();
                else {
                    this._insertTitle(track.title);
                }
            },

            loadError: function (track) {

            },

            _unload: function () {
                this._insertTitle("No track selected.");
            },

            _insertTitle: function (msg) {
                this._dom.find('.titlebar').html(msg).marquee({
                    duration: msg.length * this._marquee_speed,
                    gap: 170,
                    delayBeforeStart: 0,
                    direction: 'left',
                    duplicated: true
                });
            }
        };
        return H;
    };

    var AudioPlayer = function () {
        var AP = {
            _dom: $('
<audio preload></audio>
'),
            _audio: false,

            init: function (player, volume) {
                if (!volume) volume = 0.75;
                if ($(this._dom.getUnique()).length < 1) {
                    throw new Error('Cannot initialize AudioPlayer that is ' +
                                    'not attached to the current DOM.');
                }
                this._audio = audiojs.newInstance(this._dom.find('audio')[0], {
                    trackEnded: function () {
                        player.trackFinished();
                    }
                });
                this._audio.onError = function (e) {
                    player.error(e);
                };
                this._dom.find('.play-pause').click(function () {
                    console.log('playpause: \n\t');
                    console.log($(this));
                    if ($(this).hasClass('p-play')) {
                        player.pause();
                    }
                    else if ($(this).hasClass('p-pause')) {
                        player.play();
                    }
                });
                this._dom.find('.skip.ahead').click(function () {
                    player.skipAhead(30);
                });
                this._dom.find('.skip.back').click(function () {
                    player.skipBack(15);
                });
                this._dom.find('.volume').click(function () {
                    var time = $(this).closest('.audiojs').find('.time');
                    if (time.find('span').css('display') != 'none') {
                        $(this).newTip(true, 'Close');
                        time.find('span').css('display', 'none');
                        time.find('.slider').css('display', 'block');
                        $(this).css('color', '#ccc');
                    }
                    else {
                        $(this).newTip(true, 'Adjust Volume');
                        time.find('span').css('display', 'block');
                        time.find('.slider').css('display', 'none');
                        $(this).css('color', '#777');
                    }
                });
                this._dom.find('.slider').slider({
                    range: "min",
                    min: 0,
                    max: 40,
                    value: volume * 40,
                    slide: function (event, ui) {
                        player.setVolume(ui.value/40);
                    }
                });
                player.setVolume(this._dom.find('.slider').slider('value')/40);
                this._dom.find('[title]').newTip();
            },

            load: function (src) {
                if (!src) this._unload();
                else {
                    if (typeof(src) === 'object') src = src.src;
                    this._audio.load(src);
                }
            },

            _unload: function () {
            },

            play: function () {
                this._audio.play();
            },

            pause: function () {
                this._audio.pause();
            },

            playPause: function () {
                this._audio.playPause();
            },

            skipTo: function (position) {
                var percent, a = this._dom.find('audio')[0];
                position = (position < 0) ? 0 :
                        (position > a.duration) ? a.duration : position;
                percent = Math.floor(position / a.duration * 100) / 100;
                this._audio.skipTo(percent);
            },

            skipAhead: function (seconds) {
                var a = this._dom.find('audio')[0];
                this.skipTo(a.currentTime + seconds);
            },

            skipBack: function (seconds) {
                this.skipAhead(seconds * -1);
            },

            reset: function () {
                this.skipTo(0);
            },

            isPlaying: function () {
                return this._audio.playing;
            },

            getPosition: function () {
                return Math.floor(this._dom.find('audio')[0].currentTime);
            },

            setVolume: function (vol) {
                var el = this._dom.find('.volume');
                if (vol === this._dom.find('audio')[0].volume) return;
                this._audio.setVolume(vol);
                el.find('.glyphicon').css('display', 'none');
                if (vol === 0) {
                    el.find('.glyphicon-volume-off').css('display', 'block');
                }
                else if (vol === 1) {
                    el.find('.glyphicon-volume-up').css('display', 'block');
                }
                else {
                    el.find('.glyphicon-volume-down').css('display', 'block');
                }
            },

        };
        return AP;
    };

    var PlayList = function (list) {
        var PL = {
            _dom: $('

'),
            _list: [],
            _cur: 0,

            add: function (src, title, dur, poster_src, pod_id) {
                var track, played, index, el;
                if (typeof(src) === 'object') {
                    track = src;
                    autoload = title;
                }
                else {
                    track = new Track(src, title, dur, poster_src, pod_id);
                }
                if (this.hasTrack(track)) {
                    throw new Error('Track already in playlist.');
                }
                el = new TrackElement(track);
                this._list.push(track);
                this._appendElement(el);
                index = this.count() - 1;
                if (track.played) this._markPlayed(index);
                return index;
            },

            insert: function (src, title, dur, poster_src, pod_id) {
                var track, played, el;
                if (typeof(src) === 'object') {
                    track = src;
                    autoload = title;
                }
                else {
                    track = new Track(src, title, dur, poster_src, pod_id);
                }
                if (this.hasTrack(track)) {
                    throw new Error('Track already in playlist.');
                }
                el = new TrackElement(track);
                this._list.unshift(track);
                this._insertElement(el);
                if (track.played) this._markPlayed(0);
                if (this.count() !== 1) this._cur++;
                return 0;
            },

            delete: function (index) {
                var rem, element;
                if (this._list[index]) {
                    element = $(this._dom.find('li')[index]);
                    this._list.splice(index, 1);
                    this._removeElement(element);
                }
                if (index <= this._cur) this._cur--;
            },

            load: function (index) {
                var item, element;
                if (index < 0) index = this.count() - 1;
                if (index >= this.count()) index = 0;
                if (!this.getTrack(index)) {
                    return false;
                }
                this._cur = index;
                item = this.getTrack();
                element = $(this._dom.find('li')[index]);
                item.played = false;
                $(element).parent().find('.loaded').removeClass('loaded');
                $(element).removeClass('played');
                $(element).addClass('loaded');
                return item;
            },

            getTrack: function (index) {
                index = (Number(index) === index) ? index : this._cur;
                if (this.count() === 0 || !this._list[index]) {
                    return false;
                }
                return this._list[index];
            },

            hasTrack: function (track_or_src) {
                var src = track_or_src, filter;
                if (typeof(src) !== 'string') {
                    src = src.src;
                }
                filter = this._list.filter(function (track) {
                    return track.src === src;
                })[0];
                return (typeof(filter) !== 'undefined');
            },

            next: function () {
                if (!this._cur || this._cur === this.count() - 1) return -1;
                return this._cur + 1;
            },

            prev: function () {
                if (this._cur === 0) return -1;
                return this._cur - 1;
            },

            finished: function (index) {
                if (!index) index = this._cur;
                if (this._list[index]) {
                    this._list[index].played = true;
                    this._markPlayed(index);
                }
            },

            _markPlayed: function (index) {
                if (this._list[index]) {
                    $(this._list[index].selector).addClass('played');
                }
            },

            count: function () { return this._list.length; },

            _insertElement: function (el) {
                $(this._dom).find('ol').prepend(el);
                el.animate({opacity: 1}, 500);
            },

            _appendElement: function (el) {
                $(this._dom).find('ol').append(el);
                el.animate({opacity: 1}, 500);
            },

            _removeElement: function (el) {
                el.animate({height: '0px', opacity: 0}, 250, function () {
                    el.remove();
                });
            }
        };
        while (list && list.length > 0) {
            PL.insert(list.pop(), false);
        }
        return PL;
    };

}(jQuery, audiojs));<|endoftext|>


<commit_before>var mockfs = require('mock-fs');
var fs = require('fs');
var MountFs = require('mountfs');
var rewriteMockFsOptions = require('./lib/rewriteMockFsOptions');

module.exports = {
    name: 'unexpected-fs',
    installInto: function (expect) {
        expect.addAssertion('with fs mocked out', function (expect, subject, value) {
            this.errorMode = 'bubble';
            var extraArgs = Array.prototype.slice.call(arguments, 3);

            var mockFileSystems = Object.keys(value).map(function (key) {
                var mockFsConfig = rewriteMockFsOptions(value[key]);
                return {
                    mountPath: /\/$/.test(key) ? key : key + '/',
                    fileSystem: mockfs.fs(mockFsConfig)
                };
            });

            var unmountAllMocks = function () {
                mockFileSystems.forEach(function (mockFs) {
                    fs.unmount(mockFs.mountPath);
                });
                fs.unpatch();
            };

            return expect.promise(function () {
                MountFs.patchInPlace();

                mockFileSystems.forEach(function (mockFileSystem) {
                    fs.mount(mockFileSystem.mountPath, mockFileSystem.fileSystem);
                });

                return expect.apply(expect, [subject].concat(extraArgs));
            }).then(function () {
                unmountAllMocks();
            }).caught(function (err) {
                unmountAllMocks();
                throw err;
            });
        });
    }
};
<commit_msg>Use finally to clean up (hello @sunesimonsen).<commit_after>var mockfs = require('mock-fs');
var fs = require('fs');
var MountFs = require('mountfs');
var rewriteMockFsOptions = require('./lib/rewriteMockFsOptions');

module.exports = {
    name: 'unexpected-fs',
    installInto: function (expect) {
        expect.addAssertion('with fs mocked out', function (expect, subject, value) {
            this.errorMode = 'bubble';
            var extraArgs = Array.prototype.slice.call(arguments, 3);

            var mockFileSystems = Object.keys(value).map(function (key) {
                var mockFsConfig = rewriteMockFsOptions(value[key]);
                return {
                    mountPath: /\/$/.test(key) ? key : key + '/',
                    fileSystem: mockfs.fs(mockFsConfig)
                };
            });

            return expect.promise(function () {
                MountFs.patchInPlace();

                mockFileSystems.forEach(function (mockFileSystem) {
                    fs.mount(mockFileSystem.mountPath, mockFileSystem.fileSystem);
                });

                return expect.apply(expect, [subject].concat(extraArgs));
            }).finally(function () {
                mockFileSystems.forEach(function (mockFs) {
                    fs.unmount(mockFs.mountPath);
                });
                fs.unpatch();
            });
        });
    }
};
<|endoftext|>


<commit_before>var clock = document.getElementById('clock');
var c = clock.getContext('2d');
c.lineCap = 'butt';
c.shadowColor = '#28d1fa';

function degToRad(degree) {
    var factor = Math.PI / 180;
    return degree * factor;
}

function renderTime() {
    if(window.innerWidth < 500) {
        c.canvas.width = window.innerWidth - 10;
        c.canvas.height = c.canvas.width;
    } else if(window.innerHeight < 500) {
        c.canvas.height = window.innerHeight - 10;
        c.canvas.width = c.canvas.height;
    } else {
        c.canvas.height = 500;
        c.canvas.width = 500;
    }

    var size = c.canvas.height;
    var halfSize = size / 2;
    var lineWidth = halfSize * 0.124;
    var shadowBlur = halfSize * 25;
    var timeFontSize = halfSize * 0.06;
    var dateFontSize = halfSize * 0.12;
    var timeFont = 'bold ' + timeFontSize + 'px' + ' helvetica';
    var dateFont = 'bold ' + dateFontSize + 'px' + ' helvetica';

    var now = new Date();
    var today = now.toDateString();
    var time = now.toLocaleTimeString();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    var milliseconds = now.getMilliseconds();
    var newSeconds = seconds + milliseconds/1000;
    var newMinutes = minutes + seconds/60 + milliseconds/60000;
    var newHours = hours + minutes/60 + seconds/3600 + milliseconds/3600000;

    var gradient = c.createRadialGradient(halfSize, halfSize, 1, halfSize, halfSize, size * 0.6);
    gradient.addColorStop(0, '#09303a');
    gradient.addColorStop(1, 'black');

    //background
    c.shadowBlur = 0;
    c.fillStyle = gradient;
    c.strokeStyle = 'black';
    c.lineWidth = '1';
    c.beginPath();
    c.arc(halfSize, halfSize, halfSize * 0.996, 0, degToRad(360));
    c.stroke();
    c.fill();

    //hours
    c.shadowBlur = shadowBlur;
    c.strokeStyle = '#28d1fa';
    c.lineWidth = lineWidth;
    c.beginPath();
    c.arc(halfSize, halfSize, 0.8 * halfSize, degToRad(270), degToRad((newHours * 30) - 90));
    c.stroke();

    //minutes
    c.beginPath();
    c.arc(halfSize, halfSize, 0.68 * halfSize, degToRad(270), degToRad((newMinutes * 6) - 90));
    c.stroke();

    //seconds
    c.beginPath();
    c.arc(halfSize, halfSize, 0.56 * halfSize, degToRad(270), degToRad((newSeconds * 6) - 90));
    c.stroke();

    milliseconds
     c.beginPath();
     c.arc(halfSize, halfSize, 0.44 * halfSize, degToRad(270), degToRad((milliseconds * 0.36) - 90));
     c.stroke();

    //date & time
    c.font = timeFont;
    c.fillStyle = '#28d1fa';
    c.fillText(today, halfSize * 0.76, halfSize * 1.16);
    c.font = dateFont;
    c.fillText(time, halfSize * 0.556, halfSize);

}

setInterval(renderTime, 10);
<commit_msg>do not show milliseconds<commit_after>var clock = document.getElementById('clock');
var c = clock.getContext('2d');
c.lineCap = 'butt';
c.shadowColor = '#28d1fa';

function degToRad(degree) {
    var factor = Math.PI / 180;
    return degree * factor;
}

function renderTime() {
    if(window.innerWidth < 500) {
        c.canvas.width = window.innerWidth - 10;
        c.canvas.height = c.canvas.width;
    } else if(window.innerHeight < 500) {
        c.canvas.height = window.innerHeight - 10;
        c.canvas.width = c.canvas.height;
    } else {
        c.canvas.height = 500;
        c.canvas.width = 500;
    }

    var size = c.canvas.height;
    var halfSize = size / 2;
    var lineWidth = halfSize * 0.124;
    var shadowBlur = halfSize * 25;
    var timeFontSize = halfSize * 0.06;
    var dateFontSize = halfSize * 0.12;
    var timeFont = 'bold ' + timeFontSize + 'px' + ' helvetica';
    var dateFont = 'bold ' + dateFontSize + 'px' + ' helvetica';

    var now = new Date();
    var today = now.toDateString();
    var time = now.toLocaleTimeString();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    var milliseconds = now.getMilliseconds();
    var newSeconds = seconds + milliseconds/1000;
    var newMinutes = minutes + seconds/60 + milliseconds/60000;
    var newHours = hours + minutes/60 + seconds/3600 + milliseconds/3600000;

    var gradient = c.createRadialGradient(halfSize, halfSize, 1, halfSize, halfSize, size * 0.6);
    gradient.addColorStop(0, '#09303a');
    gradient.addColorStop(1, 'black');

    //background
    c.shadowBlur = 0;
    c.fillStyle = gradient;
    c.strokeStyle = 'black';
    c.lineWidth = '1';
    c.beginPath();
    c.arc(halfSize, halfSize, halfSize * 0.996, 0, degToRad(360));
    c.stroke();
    c.fill();

    //hours
    c.shadowBlur = shadowBlur;
    c.strokeStyle = '#28d1fa';
    c.lineWidth = lineWidth;
    c.beginPath();
    c.arc(halfSize, halfSize, 0.8 * halfSize, degToRad(270), degToRad((newHours * 30) - 90));
    c.stroke();

    //minutes
    c.beginPath();
    c.arc(halfSize, halfSize, 0.68 * halfSize, degToRad(270), degToRad((newMinutes * 6) - 90));
    c.stroke();

    //seconds
    c.beginPath();
    c.arc(halfSize, halfSize, 0.56 * halfSize, degToRad(270), degToRad((newSeconds * 6) - 90));
    c.stroke();

    //milliseconds
    // c.beginPath();
    // c.arc(halfSize, halfSize, 0.44 * halfSize, degToRad(270), degToRad((milliseconds * 0.36) - 90));
    // c.stroke();

    //date & time
    c.font = timeFont;
    c.fillStyle = '#28d1fa';
    c.fillText(today, halfSize * 0.76, halfSize * 1.16);
    c.font = dateFont;
    c.fillText(time, halfSize * 0.556, halfSize);

}

setInterval(renderTime, 10);
<|endoftext|>


<commit_before>// XXX: To uniform the style of an object literals, we enable `quote-props`
/*eslint quote-props: [2, "always"] no-magic-numbers: 0 */

'use strict';

module.exports = {

    'plugins': [
        'react'
    ],

    'settings': {
        'react': {
            'version': '15.0', // used for 'no-deprecated' rule.
        }
    },

    // ESLint-plugin-React
    // https://github.com/yannickcr/eslint-plugin-react
    'rules': {
        'react/display-name': 0, // Auto covered by jsx transformer.
        'react/forbid-component-props': 1,
        'react/no-danger': 0, // ban `dangerouslySetInnerHTML`. But we still use it :(
        'react/no-danger-with-children': 2,
        'react/no-did-mount-set-state': [1, 'disallow-in-func'],
        'react/no-did-update-set-state': [1, 'disallow-in-func'],
        'react/no-direct-mutation-state': 1, // FIXME: this should be error.
        'react/no-find-dom-node': 2, // Disallow to use `ReactDOM.findDOMNode()`.
        'react/no-multi-comp': 0, // Enable to define a multiple component to a single file.
        'react/no-set-state': 1, // Recommend to use props instead of `setState()`.
        'react/no-unknown-property': 2,
        'react/no-unused-prop-types': [0, { // XXX: Disable to avoid mis-detection
            'customValidators': [],
            'skipShapeProps': false,
        }],
        'react/no-deprecated': 2, // Detect deprected styles
        'react/no-is-mounted': 2,
        'react/no-render-return-value': 2,
        'react/no-string-refs': 2,
        'react/prefer-es6-class': 1, // Prefer ES6 class inheritance style.
        'react/prefer-stateless-function': [1, {
            'ignorePureComponents': false, // we'll reconsider this option when we begin to use `PureComponent`.
        }],
        'react/prop-types': 1,
        'react/react-in-jsx-scope': 1,
        'react/require-optimization': [0, {
            'allowDecorators': []
        }],
        'react/self-closing-comp': [2, {
            'component': true,
            'html': false,
        }],
        'react/require-render-return': 2,

        // We define customized rules because we thought default settings mixes with
        // component's arguments and lifecycle methods.
        'react/sort-comp': [1, {
            'order': [
                'constructor',
                'metadata',
                'rendering',
                'lifecycle',
                'everything-else'
            ],
            'groups': {
                'metadata': [
                    'displayName',
                    'propTypes',
                    'contextTypes',
                    'childContextTypes',
                    'mixins',
                    'getDefaultProps',
                    'getInitialState',
                    'getChildContext'
                ],
                'rendering': [
                    'type-annotations',
                    'render',
                    '/^render.+$/'
                ]
            }
        }],
        'react/sort-prop-types': [0, { // we cannot force alphabetical order to our old codebase.
            'callbacksLast': true,
            'requiredFirst': true,
        }],
        'react/style-prop-object': 2,

        // JSX-specific rules
        'react/jsx-boolean-value': [2, 'always'], // Enforce to specify html's boolean type attribute.
        'react/jsx-closing-bracket-location': 0, // It doesn’t matter.
        'react/jsx-curly-spacing': 1,
        'react/jsx-first-prop-new-line': [1, 'never'],
        'react/jsx-filename-extension': [2, {
            'extensions': ['.jsx']
        }],
        'react/jsx-equals-spacing': [1, 'never'],
        'react/jsx-handler-names': [2, {
            'eventHandlerPrefix': 'on', // There is no event handler which is diffrent from this rules (`onBarFoo`).
            'eventHandlerPropPrefix': 'on',
        }],
        'react/jsx-indent-props': 0, // we cannot force alphabetical order to our old codebase, and this is not any serious problem.
        'react/jsx-indent': [1, 4], // Sort with core's `indent` rule.
        'react/jsx-key': 1,
        'react/jsx-max-props-per-line': 0, // we don't think this is serious problem.
        'react/jsx-no-bind': [2, { // Sort to bind with this in constructor.
            'ignoreRefs': true, // we may use `refs`.
            'allowArrowFunctions': false,
            'allowBind': false,
        }],
        'react/jsx-no-comment-textnodes': 2,
        'react/jsx-no-duplicate-props': 2,
        'react/jsx-no-literals': 1,
        'react/jsx-no-target-blank': 1, // see https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-target-blank.md
        'react/jsx-no-undef': 2,
        'react/jsx-pascal-case': [2, {
            'allowAllCaps': false,
            'ignore': [],
        }],
        'react/jsx-sort-props': 0, // we cannot force alphabetical order to our old codebase, and this is meaningless.
        'react/jsx-space-before-closing': 0, // We don't this is a serious problem.
        'react/jsx-uses-react': 1,
        'react/jsx-uses-vars': 1,
        'react/jsx-wrap-multilines': 2,
    }
};
<commit_msg>Enable react/no-danger<commit_after>// XXX: To uniform the style of an object literals, we enable `quote-props`
/*eslint quote-props: [2, "always"] no-magic-numbers: 0 */

'use strict';

module.exports = {

    'plugins': [
        'react'
    ],

    'settings': {
        'react': {
            'version': '15.0', // used for 'no-deprecated' rule.
        }
    },

    // ESLint-plugin-React
    // https://github.com/yannickcr/eslint-plugin-react
    'rules': {
        'react/display-name': 0, // Auto covered by jsx transformer.
        'react/forbid-component-props': 1,
        'react/no-danger': 2,
        'react/no-danger-with-children': 2,
        'react/no-did-mount-set-state': [1, 'disallow-in-func'],
        'react/no-did-update-set-state': [1, 'disallow-in-func'],
        'react/no-direct-mutation-state': 1, // FIXME: this should be error.
        'react/no-find-dom-node': 2, // Disallow to use `ReactDOM.findDOMNode()`.
        'react/no-multi-comp': 0, // Enable to define a multiple component to a single file.
        'react/no-set-state': 1, // Recommend to use props instead of `setState()`.
        'react/no-unknown-property': 2,
        'react/no-unused-prop-types': [0, { // XXX: Disable to avoid mis-detection
            'customValidators': [],
            'skipShapeProps': false,
        }],
        'react/no-deprecated': 2, // Detect deprected styles
        'react/no-is-mounted': 2,
        'react/no-render-return-value': 2,
        'react/no-string-refs': 2,
        'react/prefer-es6-class': 1, // Prefer ES6 class inheritance style.
        'react/prefer-stateless-function': [1, {
            'ignorePureComponents': false, // we'll reconsider this option when we begin to use `PureComponent`.
        }],
        'react/prop-types': 1,
        'react/react-in-jsx-scope': 1,
        'react/require-optimization': [0, {
            'allowDecorators': []
        }],
        'react/self-closing-comp': [2, {
            'component': true,
            'html': false,
        }],
        'react/require-render-return': 2,

        // We define customized rules because we thought default settings mixes with
        // component's arguments and lifecycle methods.
        'react/sort-comp': [1, {
            'order': [
                'constructor',
                'metadata',
                'rendering',
                'lifecycle',
                'everything-else'
            ],
            'groups': {
                'metadata': [
                    'displayName',
                    'propTypes',
                    'contextTypes',
                    'childContextTypes',
                    'mixins',
                    'getDefaultProps',
                    'getInitialState',
                    'getChildContext'
                ],
                'rendering': [
                    'type-annotations',
                    'render',
                    '/^render.+$/'
                ]
            }
        }],
        'react/sort-prop-types': [0, { // we cannot force alphabetical order to our old codebase.
            'callbacksLast': true,
            'requiredFirst': true,
        }],
        'react/style-prop-object': 2,

        // JSX-specific rules
        'react/jsx-boolean-value': [2, 'always'], // Enforce to specify html's boolean type attribute.
        'react/jsx-closing-bracket-location': 0, // It doesn’t matter.
        'react/jsx-curly-spacing': 1,
        'react/jsx-first-prop-new-line': [1, 'never'],
        'react/jsx-filename-extension': [2, {
            'extensions': ['.jsx']
        }],
        'react/jsx-equals-spacing': [1, 'never'],
        'react/jsx-handler-names': [2, {
            'eventHandlerPrefix': 'on', // There is no event handler which is diffrent from this rules (`onBarFoo`).
            'eventHandlerPropPrefix': 'on',
        }],
        'react/jsx-indent-props': 0, // we cannot force alphabetical order to our old codebase, and this is not any serious problem.
        'react/jsx-indent': [1, 4], // Sort with core's `indent` rule.
        'react/jsx-key': 1,
        'react/jsx-max-props-per-line': 0, // we don't think this is serious problem.
        'react/jsx-no-bind': [2, { // Sort to bind with this in constructor.
            'ignoreRefs': true, // we may use `refs`.
            'allowArrowFunctions': false,
            'allowBind': false,
        }],
        'react/jsx-no-comment-textnodes': 2,
        'react/jsx-no-duplicate-props': 2,
        'react/jsx-no-literals': 1,
        'react/jsx-no-target-blank': 1, // see https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-target-blank.md
        'react/jsx-no-undef': 2,
        'react/jsx-pascal-case': [2, {
            'allowAllCaps': false,
            'ignore': [],
        }],
        'react/jsx-sort-props': 0, // we cannot force alphabetical order to our old codebase, and this is meaningless.
        'react/jsx-space-before-closing': 0, // We don't this is a serious problem.
        'react/jsx-uses-react': 1,
        'react/jsx-uses-vars': 1,
        'react/jsx-wrap-multilines': 2,
    }
};
<|endoftext|>


<commit_before>(function(){
'use strict'

angular.module('readingList', []);

  var genres = [ 'fable', 'fantasy', 'fiction', 'folklore', 'horror', 'humor', 'legend', 'metafiction', 'mystery', 'mythology', 'non-fiction', 'poetry' ];

  var books = [
    {
      title: 'A Game of Thrones: A Song of Ice and Fire',
      author: 'George R.R. Martin',
      isbn: '0553593714',
      review: 'The most inventive and entertaining fantasy saga of our time—warrants one hell of an introduction. I loved this book!',
      rating: 4,
      genres: { 'non-fiction': true, fantasy: true }
    },{
      title: 'HTML for Babies',
      author: 'John C Vanden-Heuvel Sr',
      isbn: '0615487661',
      review: "It's never too early to be standards compliant! I taught my little one mark-up in under one hour!",
      rating: 5,
      genres: { fiction: true }
    },{
      title: 'A is for Array',
      author: 'Brandon J Hansen',
      isbn: '1489522212',
      review: 'A is for Array is the ABC book for future programmers. Filled with fun illustrations and simple real-world examples, my children loved seeing my world intertwined with theirs!',
      rating: 4,
      genres: { fiction: true }
    },{
      title: 'The Dragon Reborn',
      author: 'Robert Jordan',
      isbn: '0812513711',
      review: 'The Wheel weaves as the Wheel wills, and we are only the thread of the Pattern. Moiraine',
      rating: 4,
      genres: { 'non-fiction': true, fantasy: true }
    }
  ];

})();<commit_msg>Assign data to ReadingListController in app.js<commit_after>(function(){
'use strict'

var a = angular.module('readingList', []);

a.controller('ReadingListController', function(){
    this.books = books;
    this.genres = genres;
});

  var genres = [ 'fable', 'fantasy', 'fiction', 'folklore', 'horror', 'humor', 'legend', 'metafiction', 'mystery', 'mythology', 'non-fiction', 'poetry' ];

  var books = [
    {
      title: 'A Game of Thrones: A Song of Ice and Fire',
      author: 'George R.R. Martin',
      isbn: '0553593714',
      review: 'The most inventive and entertaining fantasy saga of our time—warrants one hell of an introduction. I loved this book!',
      rating: 4,
      genres: { 'non-fiction': true, fantasy: true }
    },{
      title: 'HTML for Babies',
      author: 'John C Vanden-Heuvel Sr',
      isbn: '0615487661',
      review: "It's never too early to be standards compliant! I taught my little one mark-up in under one hour!",
      rating: 5,
      genres: { fiction: true }
    },{
      title: 'A is for Array',
      author: 'Brandon J Hansen',
      isbn: '1489522212',
      review: 'A is for Array is the ABC book for future programmers. Filled with fun illustrations and simple real-world examples, my children loved seeing my world intertwined with theirs!',
      rating: 4,
      genres: { fiction: true }
    },{
      title: 'The Dragon Reborn',
      author: 'Robert Jordan',
      isbn: '0812513711',
      review: 'The Wheel weaves as the Wheel wills, and we are only the thread of the Pattern. Moiraine',
      rating: 4,
      genres: { 'non-fiction': true, fantasy: true }
    }
  ];

})();<|endoftext|>


<commit_before>const test         = require('tape')
    , fs           = require('fs')
    , path         = require('path')
    , mkfiletree   = require('mkfiletree')
    , readfiletree = require('readfiletree')
    , leveldown    = require('../')
    , makeTest     = require('./make')

test('test argument-less destroy() throws', function (t) {
  t.throws(
      leveldown.destroy
    , { name: 'Error', message: 'destroy() requires `location` and `callback` arguments' }
    , 'no-arg destroy() throws'
  )
  t.end()
})

test('test callback-less, 1-arg, destroy() throws', function (t) {
  t.throws(
      leveldown.destroy.bind(null, 'foo')
    , { name: 'Error', message: 'destroy() requires `location` and `callback` arguments' }
    , 'callback-less, 1-arg destroy() throws'
  )
  t.end()
})

test('test destroy non-existant directory', function (t) {
  leveldown.destroy('/1/2/3/4', function () {
    t.equal(arguments.length, 1, 'error object returned on callback')
    t.equal(/.*IO error.*\/1\/2\/3\/4\/LOCK.*/.test(arguments[0]), true)
    t.end()
  })
})

test('test destroy non leveldb directory', function (t) {
  var tree = {
      'foo': 'FOO'
    , 'bar': { 'one': 'ONE', 'two': 'TWO', 'three': 'THREE' }
  }
  mkfiletree.makeTemp('destroy-test', tree, function (err, dir) {
    t.notOk(err, 'no error')
    leveldown.destroy(dir, function () {
      t.ok(arguments, 'no arguments')
      readfiletree(dir, function (err, actual) {
        t.notOk(err, 'no error')
        t.deepEqual(actual, tree, 'directory remains untouched')
        mkfiletree.cleanUp(function (err) {
          t.notOk(err, 'no error')
          t.end()
        })
      })
    })
  })
})

makeTest('test destroy() cleans and removes leveldb-only dir', function (db, t, done, location) {
  db.close(function (err) {
    t.notOk(err, 'no error')
    leveldown.destroy(location, function () {
      t.notOk(fs.existsSync(), 'directory completely removed')
      done(false)
    })
  })
})

makeTest('test destroy() cleans and removes only leveldb parts of a dir', function (db, t, done, location) {
  fs.writeFileSync(path.join(location, 'foo'), 'FOO')
  db.close(function (err) {
    t.notOk(err, 'no error')
    leveldown.destroy(location, function () {
      readfiletree(location, function (err, tree) {
        t.deepEqual(tree, { 'foo': 'FOO' }, 'non-leveldb files left intact')
        done(false)
      })
    })
  })
})
<commit_msg>add missing location to fs.existsSync()<commit_after>const test         = require('tape')
    , fs           = require('fs')
    , path         = require('path')
    , mkfiletree   = require('mkfiletree')
    , readfiletree = require('readfiletree')
    , leveldown    = require('../')
    , makeTest     = require('./make')

test('test argument-less destroy() throws', function (t) {
  t.throws(
      leveldown.destroy
    , { name: 'Error', message: 'destroy() requires `location` and `callback` arguments' }
    , 'no-arg destroy() throws'
  )
  t.end()
})

test('test callback-less, 1-arg, destroy() throws', function (t) {
  t.throws(
      leveldown.destroy.bind(null, 'foo')
    , { name: 'Error', message: 'destroy() requires `location` and `callback` arguments' }
    , 'callback-less, 1-arg destroy() throws'
  )
  t.end()
})

test('test destroy non-existant directory', function (t) {
  leveldown.destroy('/1/2/3/4', function () {
    t.equal(arguments.length, 1, 'error object returned on callback')
    t.equal(/.*IO error.*\/1\/2\/3\/4\/LOCK.*/.test(arguments[0]), true)
    t.end()
  })
})

test('test destroy non leveldb directory', function (t) {
  var tree = {
      'foo': 'FOO'
    , 'bar': { 'one': 'ONE', 'two': 'TWO', 'three': 'THREE' }
  }
  mkfiletree.makeTemp('destroy-test', tree, function (err, dir) {
    t.notOk(err, 'no error')
    leveldown.destroy(dir, function () {
      t.ok(arguments, 'no arguments')
      readfiletree(dir, function (err, actual) {
        t.notOk(err, 'no error')
        t.deepEqual(actual, tree, 'directory remains untouched')
        mkfiletree.cleanUp(function (err) {
          t.notOk(err, 'no error')
          t.end()
        })
      })
    })
  })
})

makeTest('test destroy() cleans and removes leveldb-only dir', function (db, t, done, location) {
  db.close(function (err) {
    t.notOk(err, 'no error')
    leveldown.destroy(location, function () {
      t.notOk(fs.existsSync(location), 'directory completely removed')
      done(false)
    })
  })
})

makeTest('test destroy() cleans and removes only leveldb parts of a dir', function (db, t, done, location) {
  fs.writeFileSync(path.join(location, 'foo'), 'FOO')
  db.close(function (err) {
    t.notOk(err, 'no error')
    leveldown.destroy(location, function () {
      readfiletree(location, function (err, tree) {
        t.deepEqual(tree, { 'foo': 'FOO' }, 'non-leveldb files left intact')
        done(false)
      })
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

angular.module('anyfetchFrontApp.timeService', [])
.factory( 'TimeService', function() {

  var datas = {
    times: []
  };

  datas.set = function(times) {
    datas.times = [];
    angular.forEach(Object.keys(times), function(value){
      var date = new Date(parseInt(value));
      var time = {
        timestamp: value,
        count: times[value],
        label: 'From ' + date.getMonth() + ' to ' + (date.getMonth() + 3) + ' ' + date.getFullYear()
      };

      datas.times.push(time);
    });

    return datas.times;
  };

  datas.get = function() {
    return datas.times;
  };

  // Return of the service
  return datas;

});<commit_msg>Month name<commit_after>'use strict';

angular.module('anyfetchFrontApp.timeService', [])
.factory( 'TimeService', function() {

  var datas = {
    times: []
  };

  var months = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'June', 'July', 'Aug.', 'Sep.', 'Oct.', 'Nov.', 'Dec.'];

  datas.set = function(times) {
    datas.times = [];
    angular.forEach(Object.keys(times), function(value){
      var date = new Date(parseInt(value));
      var time = {
        timestamp: value,
        count: times[value],
        label: 'From ' + months[date.getMonth()] + ' to ' + months[(date.getMonth() + 2)] + ' ' + date.getFullYear()
      };

      datas.times.push(time);
    });

    return datas.times;
  };

  datas.get = function() {
    return datas.times;
  };

  // Return of the service
  return datas;

});<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';

import { MODES, SORTS } from 'react/components/Home/config';

import WithCurrentRoute from 'react/hocs/WithCurrentRoute';

import Grid from 'react/components/UI/Grid';
import HeaderMetadataContainer from 'react/components/UI/HeaderMetadataContainer';
import HomeBreadcrumb from 'react/components/HomeMetadata/components/HomeBreadcrumb';
import HomeMetadataView from 'react/components/HomeMetadata/components/HomeMetadataView';
import HomeMetadataSort from 'react/components/HomeMetadata/components/HomeMetadataSort';

class HomeMetadata extends Component {
  static propTypes = {
    mode: PropTypes.oneOf(MODES),
    sort: PropTypes.oneOf(SORTS),
    currentRoute: PropTypes.shape({
      href: PropTypes.string.isRequired,
    }).isRequired,
  }

  static defaultProps = {
    mode: null,
    sort: null,
  }

  render() {
    const { mode, sort, currentRoute: { href } } = this.props;

    return (
      <HeaderMetadataContainer
        breadcrumb={<HomeBreadcrumb />}
      >
        {/^\/explore/.test(href) &&
          <Grid>
            <HomeMetadataView mode={mode} sort={sort} />
            <HomeMetadataSort mode={mode} sort={sort} />
          </Grid>
        }
      </HeaderMetadataContainer>
    );
  }
}

export default WithCurrentRoute(HomeMetadata);
<commit_msg>Tries out router<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Route } from 'react-router-dom';

import { MODES, SORTS } from 'react/components/Home/config';

import WithStaticRouter from 'react/hocs/WithStaticRouter';

import Grid from 'react/components/UI/Grid';
import HeaderMetadataContainer from 'react/components/UI/HeaderMetadataContainer';
import HomeBreadcrumb from 'react/components/HomeMetadata/components/HomeBreadcrumb';
import HomeMetadataView from 'react/components/HomeMetadata/components/HomeMetadataView';
import HomeMetadataSort from 'react/components/HomeMetadata/components/HomeMetadataSort';

class HomeMetadata extends Component {
  static propTypes = {
    mode: PropTypes.oneOf(MODES),
    sort: PropTypes.oneOf(SORTS),
  }

  static defaultProps = {
    mode: null,
    sort: null,
  }

  render() {
    const { mode, sort } = this.props;

    return (
      <HeaderMetadataContainer
        breadcrumb={<HomeBreadcrumb />}
      >
        <Route
          path="/explore"
          render={() => (
            <Grid>
              <HomeMetadataView mode={mode} sort={sort} />
              <HomeMetadataSort mode={mode} sort={sort} />
            </Grid>
          )}
        />
      </HeaderMetadataContainer>
    );
  }
}

export default WithStaticRouter(HomeMetadata);
<|endoftext|>