<commit_before>
$(function () {

    $('.ui.dropdown:not(.native):not(.special)[multiple]').dropdown({
        fullTextSearch: true,
        duration: 100
    });

    $('.ui.dropdown:not(.native):not(.special):not([multiple]):not(.clearable)').dropdown({
        fullTextSearch: true,
        duration: 100
    });

    $('.ui.dropdown:not(.native):not(.special):not([multiple]).clearable').dropdown({
        clearable: true,
        fullTextSearch: true,
        duration: 100
    });

    $('body').on('click', '.message .close', function() {

        $(this)
          .closest('.message')
          .transition('fade')
        ;
    });

    $('.ui.accordion')
      .accordion()
    ;

    $('.popover').popup({ 'on': Modernizr.touch ? 'click' : 'hover' });

    // Initialize main menu features.

    $('.main_navigation_wrapper').visibility({
        type: 'fixed'
    });

    $('.main_navigation_wrapper:not(:first-of-type) [id]').removeAttr('id');

    $('.main_navigation_wrapper:first-of-type').headroom({
        offset : 50,
        tolerance : 5
    });

    function show_mobile_menu() {

        //
        $('html, body').animate({
            scrollTop: 0
        }, 100);
        //

        var menu = $('#main_navigation .ui.vertical.menu');

        $('#main_navigation .extra').hide();

        menu.transition({
            animation: 'slide down',
            onComplete : function() {

                menu.css('display', 'block');
                $('#main_navigation .menu.toggle i').addClass('close').removeClass('content');
            }
        });
    }

    function hide_mobile_menu() {

        //
        $('html, body').animate({
            scrollTop: 0
        }, 100);
        //

        var menu = $('#main_navigation .ui.vertical.menu');

        menu.transition({
            animation: 'slide down',
            onComplete : function() {

                menu.css('display', 'none');
                $('#main_navigation .menu.toggle i').addClass('content').removeClass('close');
            }
        });
    }

    function toggle_mobile_menu() {

        var menu = $('#main_navigation .ui.vertical.menu');

        if (menu.hasClass('hidden')) {
            show_mobile_menu();
        } else {
            hide_mobile_menu();
        }
    }

    $('#main_navigation .menu.toggle').on('click', function(e) {

        e.preventDefault();
        toggle_mobile_menu();
    });

});

/*
 * See http://appglobe.com/scroll-to-top-animation/
 */

(function($) {

    addScrollTopAnimation();

    function addScrollTopAnimation() {

        var $scrolltop_link = $('.ui.button.scroll.top');

        $scrolltop_link.on( 'click' ,  function ( ev ) {

            ev.preventDefault();

            $( 'html, body' ).animate( {

                scrollTop: 0

            }, 700 );

        })

        // Hides the link initially
        .data('hidden', 1).hide();

        var scroll_event_fired = false;

        $(window).on('scroll', function() {

            scroll_event_fired = true;

        });

        /*
        Checks every 300 ms if a scroll event has been fired.
        */
        setInterval( function() {

            if( scroll_event_fired ) {

                // Main menu shadow.
                if ($(this).scrollTop() > 2) {
                    $('#main_navigation .main_navigation_wrapper').addClass('with-shadow');
                } else {
                    $('#main_navigation .main_navigation_wrapper').removeClass('with-shadow');
                }

                /*
                Stop code below from being executed until the next scroll event.
                */
                scroll_event_fired = false;

                var is_hidden =  $scrolltop_link.data('hidden');

                /*
                Display the scroll top link when the page is scrolled
                down the height of half a viewport from top,  Hide it otherwise.
                */
                if ( $( this ).scrollTop()  >  $( this ).height() / 2 ) {

                    if( is_hidden ) {

                        $scrolltop_link.fadeIn(600).data('hidden', 0);

                    }
                }

                else {

                    if( !is_hidden ) {

                        $scrolltop_link.fadeOut(600).data('hidden', 1);

                    }
                }

            }

        }, 300);

    }

})(jQuery);

// https://github.com/danbeam/ellipsis/

function ellipsize() {
    $('.ellipsis').ellipsis();
    $('.ellipsis-1').ellipsis({'lines': 1});
    $('.ellipsis-2').ellipsis({'lines': 2});
    $('.ellipsis-3').ellipsis({'lines': 3});
    $('.ellipsis-4').ellipsis({'lines': 4});
    $('.ellipsis-5').ellipsis({'lines': 5});
    $('.ellipsis-6').ellipsis({'lines': 6});
    $('.ellipsis-7').ellipsis({'lines': 7});
    $('.ellipsis-8').ellipsis({'lines': 8});
    $('.ellipsis-9').ellipsis({'lines': 9});
    $('.ellipsis-10').ellipsis({'lines': 10});
}

$(ellipsize);  // when document is ready
$(window).on('resize', ellipsize);  // on resize
<commit_msg>Removing uncompatible with Fomantic UI piece of code. Signed-off-by:Ivan Tcholakov <ivantcholakov@gmail.com><commit_after>
$(function () {

    $('.ui.dropdown:not(.native):not(.special)[multiple]').dropdown({
        fullTextSearch: true,
        duration: 100
    });

    $('.ui.dropdown:not(.native):not(.special):not([multiple]):not(.clearable)').dropdown({
        fullTextSearch: true,
        duration: 100
    });

    $('.ui.dropdown:not(.native):not(.special):not([multiple]).clearable').dropdown({
        clearable: true,
        fullTextSearch: true,
        duration: 100
    });

    $('body').on('click', '.message .close', function() {

        $(this)
          .closest('.message')
          .transition('fade')
        ;
    });

    $('.ui.accordion')
      .accordion()
    ;

    $('.popover').popup({ 'on': Modernizr.touch ? 'click' : 'hover' });

    // Initialize main menu features.

    $('.main_navigation_wrapper').visibility({
        type: 'fixed'
    });

    $('.main_navigation_wrapper:not(:first-of-type) [id]').removeAttr('id');

    $('.main_navigation_wrapper:first-of-type').headroom({
        offset : 50,
        tolerance : 5
    });

    function show_mobile_menu() {

        //
        $('html, body').animate({
            scrollTop: 0
        }, 100);
        //

        var menu = $('#main_navigation .ui.vertical.menu');

        $('#main_navigation .extra').hide();

        menu.transition({
            animation: 'slide down',
            onComplete : function() {

                menu.css('display', 'block');
                $('#main_navigation .menu.toggle i').addClass('close').removeClass('content');
            }
        });
    }

    function hide_mobile_menu() {

        //
        $('html, body').animate({
            scrollTop: 0
        }, 100);
        //

        var menu = $('#main_navigation .ui.vertical.menu');

        menu.transition({
            animation: 'slide down',
            onComplete : function() {

                menu.css('display', 'none');
                $('#main_navigation .menu.toggle i').addClass('content').removeClass('close');
            }
        });
    }

    function toggle_mobile_menu() {

        var menu = $('#main_navigation .ui.vertical.menu');

        if (menu.hasClass('hidden')) {
            show_mobile_menu();
        } else {
            hide_mobile_menu();
        }
    }

    $('#main_navigation .menu.toggle').on('click', function(e) {

        e.preventDefault();
        toggle_mobile_menu();
    });

});

/*
 * See http://appglobe.com/scroll-to-top-animation/
 */

(function($) {

    addScrollTopAnimation();

    function addScrollTopAnimation() {

        var $scrolltop_link = $('.ui.button.scroll.top');

        $scrolltop_link.on( 'click' ,  function ( ev ) {

            ev.preventDefault();

            $( 'html, body' ).animate( {

                scrollTop: 0

            }, 700 );

        })

        // Hides the link initially
        .data('hidden', 1).hide();

        var scroll_event_fired = false;

        $(window).on('scroll', function() {

            scroll_event_fired = true;

        });

        /*
        Checks every 300 ms if a scroll event has been fired.
        */
        setInterval( function() {

            if( scroll_event_fired ) {

                // Main menu shadow.
                if ($(this).scrollTop() > 2) {
                    $('#main_navigation .main_navigation_wrapper').addClass('with-shadow');
                } else {
                    $('#main_navigation .main_navigation_wrapper').removeClass('with-shadow');
                }

                /*
                Stop code below from being executed until the next scroll event.
                */
                scroll_event_fired = false;

                var is_hidden =  $scrolltop_link.data('hidden');

                /*
                Display the scroll top link when the page is scrolled
                down the height of half a viewport from top,  Hide it otherwise.
                */
                if ( $( this ).scrollTop()  >  $( this ).height() / 2 ) {

                    if( is_hidden ) {

                        $scrolltop_link.fadeIn(600).data('hidden', 0);

                    }
                }

                else {

                    if( !is_hidden ) {

                        $scrolltop_link.fadeOut(600).data('hidden', 1);

                    }
                }

            }

        }, 300);

    }

})(jQuery);
<|endoftext|>


<commit_before>
$(function() {

  var socket        = ('http://okdoki-disk-drive-shopper.herokuapp.com:80/');
  var page          = 'http://localhost:80/';
  var msg_count     = 0;
  var msg_css_class = 'msg';
  var errors_403    = 0;
  var err_count     = 0;
  var msg_limit     = 250;
  var err_limit     = 25;
  var is_local      = ['127.0.0.1', 'localhost'].indexOf(window.location.hostname) > -1 ;
  var ignore_text   = ';-)~ Type here.';

  if(is_local) {
    var msg_limit   = 3;
    var err_limit   = 3;
  };

  var last_time = (new Date()).getTime();
  var dom_target = $('#messages');

  function log(msg) {
    if(console && console.log) {
      console.log( msg );
      return true;
    };

    return false;
  };

  function ajax_success (msg, stat) {
    var data = msg.msg;

    if(msg.success) {

      errors_403 = 0;
      err_count  = 0;
      publish_msg( data );

    } else {

      if(data == 'Error: Forbidden') {
        if(msg._csrf) {
          $('#csrf_token').val(msg._csrf);
          log('Updating token.');
        } else {
          if (++errors_403 > err_limit) {
            publish_msg( "Unknown error. Trying 'Refresh'-ing this page." );
            log(msg.msg);
            errors_403 = 0;
          };
        };
      } else {
        log( "Error: " + data );
      };

    };

    last_time = (new Date()).getTime();
    setTimeout(call_ajax, (1.5 * 1000));

  }; // === func ajax_success

  function ajax_error (xhr, textStatus, errorThrown) {
    if (++err_count > err_limit) {
      publish_msg( "Unknown error. Trying 'Refresh'-ing this page." );
      err_count = 0;
    };

    if(textStatus == 'error' && !errorThrown) {
      log( "Retrying in 5 seconds. Website appears to be down for a moment.");
    } else {
      log( "Retrying in 5 seconds. Error msg: " + textStatus + " Error: " + errorThrown);
    };

    setTimeout(call_ajax, (5 * 1000));
  };

  function append_publish_msg() {
    dom_target.html( dom_target.html() + "
" + _.escape(msg) + '
' );
  };

  function remove_old_msg(raw_num) {
    if(!raw_num)
      var num = 1;
    else
      var num = raw_num;

    if(msg_count > msg_limit) {
      if(msg_count == (msg_limit + 1)) {
        dom_target.children('div').remove('div:last-child');
        append_msg("1 old message deleted", "append");
      } else {
        dom_target.children('div').remove('div:last-child');
        dom_target.children('div').remove('div:last-child');
        append_msg( (msg_count - msg_limit ) + " old messages deleted", "append");
      };
    };
  }; // === remove_old_msg

  function create_msg_ele(msg) {
    var new_ele = "
" + _.escape(msg) + '
';
    return new_ele;
  };

  function append_msg(msg) {
    dom_target.html( dom_target.html() + create_msg_ele(msg) );
  };

  function prepend_msg(msg) {
    dom_target.html( create_msg_ele(msg) + dom_target.html() );
  };

  function publish_msg(msg, append) {
    ++msg_count;
    remove_old_msg();
    prepend_msg(msg);
  };

  function call_ajax() {
    $.ajax({
      type     : 'POST',
      url      : window.location.origin + "/ask",
      cache    : false,
      data     : {'request_type':'latest msgs', '_csrf': $('#csrf_token').val()},
      dataType : 'json',
      success  : ajax_success,
      error    : ajax_error
    });
  };

  function run_command(txt) {
    alert(txt);
    return true;
  };

  var create_msg = $('#create_msg');
  var textarea   = create_msg.children('textarea');

  textarea.click(function() {
    if(textarea.val() == ignore_text) {
      textarea.val('');
    };
    textarea.removeClass('blur_ed');
  });

  textarea.blur(function () {
    textarea.addClass('blur_ed');
    if( $.trim(textarea.val()) == '' )
      textarea.val(ignore_text);
  });

  create_msg.children('button.submit').click(function() {
    run_command(textarea.val());
  });

  call_ajax();

});
<commit_msg>Fixed: same error msg no longer is repeatedly published.<commit_after>
$(function() {

  var socket        = ('http://okdoki-disk-drive-shopper.herokuapp.com:80/');
  var page          = 'http://localhost:80/';
  var msg_count     = 0;
  var msg_css_class = 'msg';
  var errors_403    = 0;
  var err_count     = 0;
  var err_showing   = true;
  var msg_limit     = 250;
  var err_limit     = 25;
  var is_local      = ['127.0.0.1', 'localhost'].indexOf(window.location.hostname) > -1 ;
  var ignore_text   = ';-)~ Type here.';

  if(is_local) {
    var msg_limit   = 3;
    var err_limit   = 3;
  };

  var last_time = (new Date()).getTime();
  var dom_target = $('#messages');

  function log(msg) {
    if(console && console.log) {
      console.log( msg );
      return true;
    };

    return false;
  };

  function ajax_success (msg, stat) {
    var data = msg.msg;

    if(msg.success) {

      errors_403 = 0;
      err_count  = 0;
      publish_msg( data );

    } else {

      if(data == 'Error: Forbidden') {
        if(msg._csrf) {
          $('#csrf_token').val(msg._csrf);
          log('Updating token.');
        } else {
          if (++errors_403 > err_limit) {
            publish_msg( "Unknown error. Trying 'Refresh'-ing this page.", true );
            log(msg.msg);
            errors_403 = 0;
          };
        };
      } else {
        log( "Error: " + data );
      };

    };

    last_time = (new Date()).getTime();
    setTimeout(call_ajax, (1.5 * 1000));

  }; // === func ajax_success

  function ajax_error (xhr, textStatus, errorThrown) {
    if (++err_count > err_limit) {
      publish_msg( "Unknown error. Trying 'Refresh'-ing this page.", true);
      err_count = 0;
    };

    if(textStatus == 'error' && !errorThrown) {
      log( "Retrying in 5 seconds. Website appears to be down for a moment.");
    } else {
      log( "Retrying in 5 seconds. Error msg: " + textStatus + " Error: " + errorThrown);
    };

    setTimeout(call_ajax, (5 * 1000));
  };

  function append_publish_msg() {
    dom_target.html( dom_target.html() + "
" + _.escape(msg) + '
' );
  };

  function remove_old_msg(raw_num) {
    if(!raw_num)
      var num = 1;
    else
      var num = raw_num;

    if(msg_count > msg_limit) {
      if(msg_count == (msg_limit + 1)) {
        dom_target.children('div').remove('div:last-child');
        append_msg("1 old message deleted", "append");
      } else {
        dom_target.children('div').remove('div:last-child');
        dom_target.children('div').remove('div:last-child');
        append_msg( (msg_count - msg_limit ) + " old messages deleted", "append");
      };
    };
  }; // === remove_old_msg

  function create_msg_ele(msg) {
    var new_ele = "
" + _.escape(msg) + '
';
    return new_ele;
  };

  function append_msg(msg) {
    dom_target.html( dom_target.html() + create_msg_ele(msg) );
  };

  function prepend_msg(msg) {
    dom_target.html( create_msg_ele(msg) + dom_target.html() );
  };

  function publish_msg(msg, err_msg) {
    if(err_msg) {
      if(err_showing == msg)
        return false;
      err_showing = msg;
    } else {
      err_showing = false;
    };

    ++msg_count;
    remove_old_msg();
    prepend_msg(msg);
  };

  function call_ajax() {
    $.ajax({
      type     : 'POST',
      url      : window.location.origin + "/ask",
      cache    : false,
      data     : {'request_type':'latest msgs', '_csrf': $('#csrf_token').val()},
      dataType : 'json',
      success  : ajax_success,
      error    : ajax_error
    });
  };

  function run_command(txt) {
    alert(txt);
    return true;
  };

  var create_msg = $('#create_msg');
  var textarea   = create_msg.children('textarea');

  textarea.click(function() {
    if(textarea.val() == ignore_text) {
      textarea.val('');
    };
    textarea.removeClass('blur_ed');
  });

  textarea.blur(function () {
    textarea.addClass('blur_ed');
    if( $.trim(textarea.val()) == '' )
      textarea.val(ignore_text);
  });

  create_msg.children('button.submit').click(function() {
    run_command(textarea.val());
  });

  call_ajax();

});
<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import Snippets from './Snippets'

class Form extends React.Component {

  constructor(props) {
    super(props);
  }

  componentWillMount(){

  }

  componentDidMount(){

  }

  mouseEnter = (e) => {
    console.log("e.target: ", e.target)
    e.target.style.height = "325px"
    e.target.style.width = "325px"
  }

  mouseLeave = (e) => {
    console.log("e.target: ", e.target)
    e.target.style.height = "300px"
    e.target.style.width = "300px"
  }

  render() {

    var box = {
      width: "300px",
      height: "300px",
      background: "gray",
      display: "inline-flex",
      margin: "10px",
      textAlign: "center"
     }

    var wrapper = {

      height: "500px"

    }

    var p = {
      marginLeft: "auto",
      marginRight: "auto",
      height: "20px",
      width: "100px"
    }

    var btn = {
      display: "inline-block",
      verticalAlign: "top",
      height: "300px",
      width: "300px"
    }

    var row = {
      height: "50px"
    }

    return (

React init state syntax

Basic div container

            <button id="btnSearch" className="btn btn-primary btn-md center-block" style={btn} onClick={this.props.boxIsClicked} value={0}>Hello World</button>
            <button id="btnClear" className="btn btn-danger btn-md center-block" style={btn} onClick={this.props.boxIsClicked} value={1}>Hello World </button>

    );
  }

}

export default Form;<commit_msg>display none original gray boxes<commit_after>'use strict';

import React from 'react';
import Snippets from './Snippets'

class Form extends React.Component {

  constructor(props) {
    super(props);
  }

  componentWillMount(){

  }

  componentDidMount(){

  }

  mouseEnter = (e) => {
    console.log("e.target: ", e.target)
    e.target.style.height = "325px"
    e.target.style.width = "325px"
  }

  mouseLeave = (e) => {
    console.log("e.target: ", e.target)
    e.target.style.height = "300px"
    e.target.style.width = "300px"
  }

  render() {

    var box = {
      width: "300px",
      height: "300px",
      background: "gray",
      display: "inline-flex",
      margin: "10px",
      textAlign: "center",
      display: "none"
     }

    var wrapper = {

      height: "500px"

    }

    var p = {
      marginLeft: "auto",
      marginRight: "auto",
      height: "20px",
      width: "100px"
    }

    var btn = {
      display: "inline-block",
      verticalAlign: "top",
      height: "300px",
      width: "300px",
      marginLeft: "10px",
      marginRight: "10px"
    }

    var row = {
      height: "50px"
    }

    return (

React init state syntax

Basic div container

            <button id="btnSearch" className="btn btn-primary btn-md center-block" style={btn} onClick={this.props.boxIsClicked} value={0}>Hello World</button>
            <button id="btnClear" className="btn btn-danger btn-md center-block" style={btn} onClick={this.props.boxIsClicked} value={1}>Hello World </button>

    );
  }

}

export default Form;<|endoftext|>


<commit_before>define([
  'jquery',
  'underscore',
  'backbone',
  'collections/topic',
], function($, _, Backbone, TopicCollection) {
  return {

    parseYoutubeUrl: function (url) {
      // FIXME: 80+
      var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
      var match = url.match (regExp);
      if (match && match[7].length == 11){
        return match[7];
      } else {
        return false;
      }
    },

    hidePopover: function () {
      if (this.currentPopover) {
        $(this.currentPopover).popover ('hide');
        this.currentPopover = 0;
      }
    },

    popover: function (ev) {

      var that = this;
      var link = $(ev.currentTarget).attr ('href');

      if (this.isLoading) {
        return false;
      }

      if (this.currentPopover == ev.currentTarget) {
        if ($(ev.currentTarget).attr ('data-content-url')) {
          location.href = $(ev.currentTarget).attr ('href');
          return true;
        } else {
          return false;
        }
      }

      this.hidePopover ();
      this.hideDropdown ();

      // TODO: expand this
      var position = function (context, source) {
        var position = $(source).position ();
        var main_position = $(that.el).width ();

        if ($(window).width () < 767) {
          return "auto";
        }

        if (position.top < 100)
          return "bottom";

        if (position.left < 300)
          return "auto left";

        return "auto top";
      };

      // external link

      // FIXME: this is shitty code I've ever written
      //        code repeats, hard to read etc.
      //        need to refactor ASAP

      if (link.match (/^http(s)*:\/\//)) {

        // do nothing if we already show content
        if ($(ev.currentTarget).attr ('data-loaded')) {
          return false;
        }

        if ((youtube_id = this.parseYoutubeUrl (link)) != false) {
          $(ev.currentTarget).after ('

');
          $(ev.currentTarget).attr ('data-loaded', 'true');
          return false;
        }

        // check if its image
        // FIXME: 80+
        if (link.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?/i)) {

          $(ev.currentTarget).after ('

');
          $(ev.currentTarget).attr ('data-loaded', 'true');

          return false;

        }

        // get content from readability if external url is not an image
        $.ajax ('https://readability.com/api/content/v1/parser?url=' +
                escape (link) + '&token=' +
                // token supposed to be secret but who cares
                'd83f7c87d05f46dcff11e87cbe4b278268f30132'
               ).done (function (data) {

                  $(ev.currentTarget).after ('

' +
                                             data.content +
                                             '

');
                  $(ev.currentTarget).attr ('data-loaded', 'true');

               });

        return false;
      }

      if ($(ev.currentTarget).attr ('data-content')) {
        that.currentPopover = ev.currentTarget;
        $(ev.currentTarget).popover ('show');
        return false;
      }

      this.isLoading = true;

      var topicCollection = new TopicCollection ();
      topicCollection.external_url = link;
      topicCollection.order = 0;
      topicCollection.fetch ({
        success: function (entries) {
          $(ev.currentTarget).attr ('data-content',
                   $('
' + entries.at (0).get ('content') + '
').text ());
          $(ev.currentTarget).popover ({ placement: position,
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          $(ev.currentTarget).attr ('data-content-url', 'true');
          $(ev.currentTarget).attr ('href', "#t/0/" + topicCollection.external_url);

          that.isLoading = false;

          that.currentPopover = ev.currentTarget;
        },

        error: function () {
          $(ev.currentTarget).attr ('data-content',
            '404 böyle bir başlık/entry yok')
          $(ev.currentTarget).popover ({ placement: position,
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          that.isLoading = false;

          that.currentPopover = ev.currentTarget;
        }
      });

      return false;

    },

    trigger: function (ev) {

      if (this.currentPopover) {
        this.hidePopover ();
      }

      return false;
    },

    reset: function () {
      this.currentPopover = false;
      this.currentDropdown = false;
    }

  };
});
<commit_msg>remove more dropdown methods<commit_after>define([
  'jquery',
  'underscore',
  'backbone',
  'collections/topic',
], function($, _, Backbone, TopicCollection) {
  return {

    parseYoutubeUrl: function (url) {
      // FIXME: 80+
      var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
      var match = url.match (regExp);
      if (match && match[7].length == 11){
        return match[7];
      } else {
        return false;
      }
    },

    hidePopover: function () {
      if (this.currentPopover) {
        $(this.currentPopover).popover ('hide');
        this.currentPopover = 0;
      }
    },

    popover: function (ev) {

      var that = this;
      var link = $(ev.currentTarget).attr ('href');

      if (this.isLoading) {
        return false;
      }

      if (this.currentPopover == ev.currentTarget) {
        if ($(ev.currentTarget).attr ('data-content-url')) {
          location.href = $(ev.currentTarget).attr ('href');
          return true;
        } else {
          return false;
        }
      }

      this.hidePopover ();

      // TODO: expand this
      var position = function (context, source) {
        var position = $(source).position ();
        var main_position = $(that.el).width ();

        if ($(window).width () < 767) {
          return "auto";
        }

        if (position.top < 100)
          return "bottom";

        if (position.left < 300)
          return "auto left";

        return "auto top";
      };

      // external link

      // FIXME: this is shitty code I've ever written
      //        code repeats, hard to read etc.
      //        need to refactor ASAP

      if (link.match (/^http(s)*:\/\//)) {

        // do nothing if we already show content
        if ($(ev.currentTarget).attr ('data-loaded')) {
          return false;
        }

        if ((youtube_id = this.parseYoutubeUrl (link)) != false) {
          $(ev.currentTarget).after ('

');
          $(ev.currentTarget).attr ('data-loaded', 'true');
          return false;
        }

        // check if its image
        // FIXME: 80+
        if (link.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?/i)) {

          $(ev.currentTarget).after ('

');
          $(ev.currentTarget).attr ('data-loaded', 'true');

          return false;

        }

        // get content from readability if external url is not an image
        $.ajax ('https://readability.com/api/content/v1/parser?url=' +
                escape (link) + '&token=' +
                // token supposed to be secret but who cares
                'd83f7c87d05f46dcff11e87cbe4b278268f30132'
               ).done (function (data) {

                  $(ev.currentTarget).after ('

' +
                                             data.content +
                                             '

');
                  $(ev.currentTarget).attr ('data-loaded', 'true');

               });

        return false;
      }

      if ($(ev.currentTarget).attr ('data-content')) {
        that.currentPopover = ev.currentTarget;
        $(ev.currentTarget).popover ('show');
        return false;
      }

      this.isLoading = true;

      var topicCollection = new TopicCollection ();
      topicCollection.external_url = link;
      topicCollection.order = 0;
      topicCollection.fetch ({
        success: function (entries) {
          $(ev.currentTarget).attr ('data-content',
                   $('
' + entries.at (0).get ('content') + '
').text ());
          $(ev.currentTarget).popover ({ placement: position,
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          $(ev.currentTarget).attr ('data-content-url', 'true');
          $(ev.currentTarget).attr ('href', "#t/0/" + topicCollection.external_url);

          that.isLoading = false;

          that.currentPopover = ev.currentTarget;
        },

        error: function () {
          $(ev.currentTarget).attr ('data-content',
            '404 böyle bir başlık/entry yok')
          $(ev.currentTarget).popover ({ placement: position,
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          that.isLoading = false;

          that.currentPopover = ev.currentTarget;
        }
      });

      return false;

    },

    trigger: function (ev) {

      if (this.currentPopover) {
        this.hidePopover ();
      }

      return false;
    },

    reset: function () {
      this.currentPopover = false;
    }

  };
});
<|endoftext|>


<commit_before>function MainCtrl( $scope )
{
	var socket = io.connect()
	  , element = document.getElementById( 'command' )
	  , selection = document.getElementById( 'fileSelection' )
	  , button = document.getElementById( 'upload' )
	  , emitter = new EventStream()
	  , cl = new CommandLine( element, emitter )
	  , getTime = getTimeHHMMSS
	  , serverIP = ''
	  , cwd = ''
	  , dirtyLS = false;

	selection.onchange = function() {
		selection.form.submit();
	};

	button.onclick = function() {
		selection.form.action = cwd;
		selection.click();
	};

	socket.on( 'disconnect', function() {
		$scope.output += '<' + getTime() + '> connection lost\n';
		$scope.address = '';
		$scope.$apply();
	} );

	socket.on( 'macros', function(data) {
		cl.macros = data;
	});

	$scope.socket = socket;
	$scope.output = '';
	$scope.command = '';
	$scope.address = '';

	cl.on( 'Ctrl+c', function() {
		socket.emit( 'kill' );
	} );

	emitter.on( 'cd', function() {
		var ind = element.value.lastIndexOf( ' ' )
		  , end = element.value.substr( ind + 1 );

		socket.emit( 'ls', cwd, end );
		dirtyLS = true;
	});

	cl.on( 'Space', function() {
		if (dirtyLS) {
			socket.emit( 'ls', cwd, '' );
			dirtyLS = false;
		}
	});

	tick();

	emitter.on( 'eval', function( command ) {
		$scope.evaluate(command);
	});

	$scope.evaluate = function( command ) {
		dirtyLS = false;
		socket.once( 'cwd', setCWD );
		cwd = getCWD();
		socket.emit( 'evaluate', cwd, command.trim() );
	};

	socket.on( 'enter', function( command ) {
		$scope.output += $scope.address + ' <' + getTime() + '> $' + ' ' + command + '\n';
		$scope.$apply();
	} );

	socket.on( 'ip', function( IP ) {
		serverIP = IP;
		onRefresh();
	} );

	socket.on( 'feedback', function (data) {
		$scope.output += data;
		$scope.$apply();
		allign();
	} );

	socket.once( 'cwd', setCWD );

	socket.on( 'ls', function( data ) {
		cl.registerAutoComplete( data );
	} );

	socket.on( 'exit', function( code, signal ) {

		socket.removeListener( 'cwd', setCWD );

		if (code) {
			$scope.output += 'code: ' + code + '\n';
		}
		if (signal) {
			$scope.output += 'signal: ' + signal + '\n';
		}
		$scope.output += '<' + getTime() + '>\n\n';
		$scope.$apply();
		allign();
	} );

	window.addEventListener( 'load', onRefresh );
	window.addEventListener( 'hashchange', onRefresh );

	function tick() {
		emitter.tick();
		setTimeout( tick, 100 );
	}

	function onRefresh() {
		cwd = getCWD();
		$scope.address = serverIP + ' ' + cwd;
		$scope.$apply();
		allign();
	}

	function allign() {
		var com = document.getElementById( 'command' );
		com.scrollIntoView();
	}

	function setCWD( d ) {
		cwd = d;
		location.hash = d;
	}

	function getCWD() {
		return location.hash.slice(1);
	}

}<commit_msg>fix out complete after init<commit_after>function MainCtrl( $scope )
{
	var socket = io.connect()
	  , element = document.getElementById( 'command' )
	  , selection = document.getElementById( 'fileSelection' )
	  , button = document.getElementById( 'upload' )
	  , emitter = new EventStream()
	  , cl = new CommandLine( element, emitter )
	  , getTime = getTimeHHMMSS
	  , serverIP = ''
	  , cwd = ''
	  , dirtyLS = true;

	selection.onchange = function() {
		selection.form.submit();
	};

	button.onclick = function() {
		selection.form.action = cwd;
		selection.click();
	};

	socket.on( 'disconnect', function() {
		$scope.output += '<' + getTime() + '> connection lost\n';
		$scope.address = '';
		$scope.$apply();
	} );

	socket.on( 'macros', function(data) {
		cl.macros = data;
	});

	$scope.socket = socket;
	$scope.output = '';
	$scope.command = '';
	$scope.address = '';

	cl.on( 'Ctrl+c', function() {
		socket.emit( 'kill' );
	} );

	emitter.on( 'cd', function() {
		var ind = element.value.lastIndexOf( ' ' )
		  , end = element.value.substr( ind + 1 );

		socket.emit( 'ls', cwd, end );
		dirtyLS = true;
	});

	cl.on( 'Space', function() {
		if (dirtyLS) {
			socket.emit( 'ls', cwd, '' );
			dirtyLS = false;
		}
	});

	tick();

	emitter.on( 'eval', function( command ) {
		$scope.evaluate(command);
	});

	$scope.evaluate = function( command ) {
		dirtyLS = false;
		socket.once( 'cwd', setCWD );
		cwd = getCWD();
		socket.emit( 'evaluate', cwd, command.trim() );
	};

	socket.on( 'enter', function( command ) {
		$scope.output += $scope.address + ' <' + getTime() + '> $' + ' ' + command + '\n';
		$scope.$apply();
	} );

	socket.on( 'ip', function( IP ) {
		serverIP = IP;
		onRefresh();
	} );

	socket.on( 'feedback', function (data) {
		$scope.output += data;
		$scope.$apply();
		allign();
	} );

	socket.once( 'cwd', setCWD );

	socket.on( 'ls', function( data ) {
		cl.registerAutoComplete( data );
	} );

	socket.on( 'exit', function( code, signal ) {

		socket.removeListener( 'cwd', setCWD );

		if (code) {
			$scope.output += 'code: ' + code + '\n';
		}
		if (signal) {
			$scope.output += 'signal: ' + signal + '\n';
		}
		$scope.output += '<' + getTime() + '>\n\n';
		$scope.$apply();
		allign();
	} );

	window.addEventListener( 'load', onRefresh );
	window.addEventListener( 'hashchange', onRefresh );

	function tick() {
		emitter.tick();
		setTimeout( tick, 100 );
	}

	function onRefresh() {
		cwd = getCWD();
		$scope.address = serverIP + ' ' + cwd;
		$scope.$apply();
		allign();
	}

	function allign() {
		var com = document.getElementById( 'command' );
		com.scrollIntoView();
	}

	function setCWD( d ) {
		cwd = d;
		location.hash = d;
	}

	function getCWD() {
		return location.hash.slice(1);
	}

}<|endoftext|>


<commit_before>var windspeedData = module.exports = [
    {
        id: 0,
        icon: '/images/icons/windspeed/windspeed0.png',
        valueLabel: '0 - 1',
        captionLabel: 'Knots'
    },
    {
        id: 1,
        icon: '/images/icons/windspeed/windspeed2.png',
        valueLabel: '2 - 3',
        captionLabel: 'Knots'
    },
    {
        id: 2,
        icon: '/images/icons/windspeed/windspeed4.png',
        valueLabel: '4 - 6',
        captionLabel: 'Knots'
    },
    {
        id: 3,
        icon: '/images/icons/windspeed/windspeed7.png',
        valueLabel: '7 - 10',
        captionLabel: 'Knots'
    },
    {
        id: 4,
        icon: '/images/icons/windspeed/windspeed11.png',
        valueLabel: '11 - 16',
        captionLabel: 'Knots'
    },
    {
        id: 5,
        icon: '/images/icons/windspeed/windspeed17.png',
        valueLabel: '17 - 21',
        captionLabel: 'Knots'
    },
        {
        id: 6,
        icon: '/images/icons/windspeed/windspeed22.png',
        valueLabel: '22 - 27',
        captionLabel: 'Knots'
    },
    {
        id: 7,
        icon: '/images/icons/windspeed/windspeed28.png',
        valueLabel: '28+',
        captionLabel: 'Knots'
    }
];
<commit_msg>Correct wind speed to conform with Beaufort scale<commit_after>var windspeedData = module.exports = [
    {
        id: 0,
        icon: '/images/icons/windspeed/windspeed0.png',
        valueLabel: '< 1',
        captionLabel: 'Knots'
    },
    {
        id: 1,
        icon: '/images/icons/windspeed/windspeed2.png',
        valueLabel: '1 - 3',
        captionLabel: 'Knots'
    },
    {
        id: 2,
        icon: '/images/icons/windspeed/windspeed4.png',
        valueLabel: '4 - 6',
        captionLabel: 'Knots'
    },
    {
        id: 3,
        icon: '/images/icons/windspeed/windspeed7.png',
        valueLabel: '7 - 10',
        captionLabel: 'Knots'
    },
    {
        id: 4,
        icon: '/images/icons/windspeed/windspeed11.png',
        valueLabel: '11 - 16',
        captionLabel: 'Knots'
    },
    {
        id: 5,
        icon: '/images/icons/windspeed/windspeed17.png',
        valueLabel: '17 - 21',
        captionLabel: 'Knots'
    },
        {
        id: 6,
        icon: '/images/icons/windspeed/windspeed22.png',
        valueLabel: '22 - 27',
        captionLabel: 'Knots'
    },
    {
        id: 7,
        icon: '/images/icons/windspeed/windspeed28.png',
        valueLabel: '28+',
        captionLabel: 'Knots'
    }
];
<|endoftext|>


<commit_before>import truncate from './truncate'

function isObject(x) {
  return x != null && typeof x === 'object'
}

/**
 * Sanitize specific object properties (by truncating them).
 *
 * NOTE: This method takes a rudimentary approach to modifying the object properties that could have unintended
 * side-effects, such as removing prototype data.
 *
 * @param  {Object} data sanitize (truncate) object properties.
 * @param  {Array} properties list of object properties to sanitize.
 * @return {Object} cloned object with sanitized properties.
 */
const sanitize = (data, properties = []) => {
  let sanitizedData
  if (isObject(data)) {
    sanitizedData = { ...data }
    properties.forEach(key => {
      sanitizedData[key] = truncate(data[key])
    })
  }
  return sanitizedData || data
}

export default sanitize
<commit_msg>refactor: only sanitise data props if set<commit_after>import truncate from './truncate'

function isObject(x) {
  return x != null && typeof x === 'object'
}

/**
 * Sanitize specific object properties (by truncating them).
 *
 * NOTE: This method takes a rudimentary approach to modifying the object properties that could have unintended
 * side-effects, such as removing prototype data.
 *
 * @param  {Object} data sanitize (truncate) object properties.
 * @param  {Array} properties list of object properties to sanitize.
 * @return {Object} cloned object with sanitized properties.
 */
const sanitize = (data, properties = []) => {
  let sanitizedData
  if (isObject(data)) {
    sanitizedData = { ...data }
    properties.forEach(key => {
      if (data[key]) {
        sanitizedData[key] = truncate(data[key])
      }
    })
  }
  return sanitizedData || data
}

export default sanitize
<|endoftext|>


<commit_before>var od = 1000*60*60*24;

Array.max = function( array ){
    return Math.max.apply( Math, array );
};

Array.min = function( array ){
    return Math.min.apply( Math, array );
};

var dateToStr = function (d) {
  var y = d.getFullYear().toString(),
    m = '0' + (d.getMonth() +1).toString(),
    s = '0' + d.getDate().toString();
    return y + '-' + m.substring(m.length - 2) + '-' + s.substring(s.length - 2);
};

function plotSeries(series, config) {
  var
    // series boundaries
    bounds = series.pop(),

    // padding for the graphics
    padding = 20,

    // bar graph width (will be added to sWidth to determine svg width)
    bWidth = 150,

    // scatterplot dimensions and scale
    sWidth = 650,
    sHeight = 400,

    sXMin = bounds['seriesMin']['x'],
    sXMax = bounds['seriesMax']['x'],

    sYMin = bounds['seriesMin']['yLeft'],
    sYMax = bounds['seriesMax']['yLeft'],

    sRMin = bounds['seriesMin']['yRight'],
    sRMax = bounds['seriesMax']['yRight'],

    sXScale = d3.scale.linear().domain([sXMin, sXMax]).range([0, sWidth]),
    sYScale = d3.scale.linear().domain([sYMin, sYMax]).range([sHeight, 0]),
    sRScale = d3.scale.linear().domain([sRMin, sRMax]).range([sRMin, sRMax]),

    sXLabels = config['xLabels']['value'].split(','),
    sXLScale = d3.scale.ordinal().domain(sXLabels).rangePoints([0, sWidth]),

    sColors = d3.scale.category10(),

    // extracting the date for display
    dateParts = config.asOfDate.value.split('-').map(Number),
    selectedDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]),

    sTitle = d3.select("body")
      .append("h3")
      .text(selectedDate.toDateString())
      .attr("align", "center"),

    svg = d3.select("body")
      .append("svg:svg")
      // may append the width of the bar graph too
      .attr("width", sWidth + bWidth + padding * 4)
      .attr("height", sHeight + padding * 2)
      .append("svg:g")
      .attr("transform", "translate(" + padding + "," + padding + ")"),

    vRules = svg.selectAll("g.vrule")
      .data(sXLabels)
      .enter().append("svg:g")
      .attr("class", "rule"),

    hRules = svg.selectAll("g.hrule")
      .data(sYScale.ticks(20))
      .enter().append("svg:g")
      .attr("class", "rule");

  vRules.append("svg:line")
    .attr("x1", sXLScale)
    .attr("x2", sXLScale)
    .attr("y1", 0)
    .attr("y2", sHeight - 1);

  vRules.append("svg:text")
    .attr("x", sXLScale)
    .attr("y", sHeight + 3)
    .attr("dy", "1.71em")
    .attr("text-anchor", "start")
    .text(function(d,i) { return d; });

  hRules.append("svg:line")
    .attr("y1", sYScale)
    .attr("y2", sYScale)
    .attr("x1", 0)
    .attr("x2", sWidth + 1);

  hRules.append("svg:text")
    .attr("y", sYScale)
    .attr("x", -3)
    .attr("dy", ".35em")
    .attr("stroke", "grey")
    .attr("text-anchor", "end")
    .text(sYScale.tickFormat(10));

  series = series.sort(function(p,n) {
    var r = 0;
    if (p.seriesKey < n.seriesKey)
      r = -1;
    if (p.seriesKey > n.seriesKey)
      r = 1;
    return r;
  });

  function toggleVisible(di) {
    var selectedCircles = svg.selectAll(".circle" + di),
      selectedRects = svg.selectAll(".rect" + di),
      newRectFill = "";

    selectedCircles.attr("opacity", function(d,i) {
      var newOpacity;
      d.v = (d.v == true ? false : true);
      if (d.v) {
        newOpacity = .4;
        newRectFill = sColors(d.i);
      } else {
        newOpacity = 0;
        newRectFill = "none";
      }
      return newOpacity;
    });

    selectedRects.attr("fill", newRectFill);
  }

  // throwing this in a function so we can call it for each day
  function plotDay() {
    sTitle.text(selectedDate.toDateString());

    // clean up what follows
    var a = series.map(function() {return 0;});

    var t = [];

    series.map(function(e,i){
      e.data.map(function(o){
        if (o.yLeft_1 > 0  && o.yRight_1 > 0 && o.xTime.split(' ')[0] == dateToStr(selectedDate)) {
          a[i] = a[i] + o.yRight_2;
          o.i = i;
          o.a = a[i];
          o.v = true;
          t.push(o);
        }
      });
    });

    var data = t.sort(function(p,n) {
      var r = 0;
      if (p.x < n.x)
         r = -1;
      if (p.x > n.x)
        r = 1;
      return r;
    });

    // plot the initial set of circles
    var circle = svg.selectAll("circle")
      .data(data)
      .enter().append("svg:circle")
      .attr("class", function(d,i) { return "circle" + d.i; })
      .attr("fill", function(d,i) {return sColors(d.i);})
      .attr("opacity", .30)
      .attr("cx", function(d,i) {return sXScale(d.x);})
      .attr("cy", function(d,i) {return sYScale(d.yLeft_1);})
      .attr("r", function(d,i) {return sRScale(4 + (d.yRight_1 * 2));});

    // bolt on a bar graph
    var
      bXMax = Array.max(a),
      bXScale = d3.scale.linear().domain([0, bXMax]).range([0, bWidth]),
      bYScale = d3.scale.ordinal().domain(d3.range(series.length)).rangeBands([sHeight/8, sHeight - sHeight/8], .8);

    var barLabels = svg.selectAll("g.barLabels")
      .data(series)
      .enter().append("svg:text")
      .attr("class", "barText")
      .attr("transform", function(d, i) { return "translate(" + (sWidth + 3) + "," + (bYScale(i) - 5) + ")"; })
      .text(function(d,i) { return series[i]["seriesName"].replace(/"/g,''); })
      .on("click", function(d,i) { toggleVisible(i); });

    var bars = svg.selectAll("g.bar")
      .data(a)
      .enter().append("svg:g")
      .attr("transform", function(d, i) { return "translate(" + (sWidth + 3) + "," + bYScale(i) + ")"; });

    bars.append("svg:rect")
      .attr("class", function(d,i) {return "rect" + i;})
      .attr("stroke", function(d,i) {return sColors(i);})
      .attr("fill", function(d,i) { return sColors(i); })
      .attr("width",  function(d,i) { return bXScale(d); })
      .attr("height", bYScale.rangeBand());

    bars.append("svg:text")
      .attr("class", "barText")
      .attr("x", bXScale)
      .attr("y", bYScale.rangeBand() / 2)
      .attr("dx", -6)
      .attr("dy", ".35em")
      .attr("fill", "white")
      .attr("text-anchor", "end")
      .text(bXScale.tickFormat(10));

  }

  function clearPlot() {
    svg.selectAll("circle").remove();
    svg.selectAll("g.barLabels").remove();
    svg.selectAll("g.bar").remove();
    svg.selectAll(".barText").remove();
    svg.selectAll("rect").remove();
  }

  plotDay();

  d3.select(window).on("keydown", function() {
    //alert(d3.event.keyCode);
    switch (d3.event.keyCode) {
      case 37: selectedDate = new Date(selectedDate.getTime() - od) ; break;
      case 39: selectedDate = new Date(selectedDate.getTime() + od) ; break;
    }
    clearPlot();
    plotDay();
  });

}
<commit_msg>scatterplot keyboard navigation and visibility behaving nicely<commit_after>var od = 1000*60*60*24;

Array.max = function( array ){
    return Math.max.apply( Math, array );
};

Array.min = function( array ){
    return Math.min.apply( Math, array );
};

var dateToStr = function (d) {
  var y = d.getFullYear().toString(),
    m = '0' + (d.getMonth() +1).toString(),
    s = '0' + d.getDate().toString();
    return y + '-' + m.substring(m.length - 2) + '-' + s.substring(s.length - 2);
};

function plotSeries(series, config) {
  var
    // series boundaries
    bounds = series.pop(),

    // padding for the graphics
    padding = 20,

    // bar graph width (will be added to sWidth to determine svg width)
    bWidth = 150,

    // scatterplot dimensions and scale
    sWidth = 650,
    sHeight = 400,

    sXMin = bounds['seriesMin']['x'],
    sXMax = bounds['seriesMax']['x'],

    sYMin = bounds['seriesMin']['yLeft'],
    sYMax = bounds['seriesMax']['yLeft'],

    sRMin = bounds['seriesMin']['yRight'],
    sRMax = bounds['seriesMax']['yRight'],

    sXScale = d3.scale.linear().domain([sXMin, sXMax]).range([0, sWidth]),
    sYScale = d3.scale.linear().domain([sYMin, sYMax]).range([sHeight, 0]),
    sRScale = d3.scale.linear().domain([sRMin, sRMax]).range([sRMin, sRMax]),

    sXLabels = config['xLabels']['value'].split(','),
    sXLScale = d3.scale.ordinal().domain(sXLabels).rangePoints([0, sWidth]),

    sColors = d3.scale.category10(),

    // extracting the date for display
    dateParts = config.asOfDate.value.split('-').map(Number),
    selectedDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]),

    sTitle = d3.select("body")
      .append("h3")
      .text(selectedDate.toDateString())
      .attr("align", "center"),

    svg = d3.select("body")
      .append("svg:svg")
      // may append the width of the bar graph too
      .attr("width", sWidth + bWidth + padding * 4)
      .attr("height", sHeight + padding * 2)
      .append("svg:g")
      .attr("transform", "translate(" + padding + "," + padding + ")"),

    vRules = svg.selectAll("g.vrule")
      .data(sXLabels)
      .enter().append("svg:g")
      .attr("class", "rule"),

    hRules = svg.selectAll("g.hrule")
      .data(sYScale.ticks(20))
      .enter().append("svg:g")
      .attr("class", "rule");

  vRules.append("svg:line")
    .attr("x1", sXLScale)
    .attr("x2", sXLScale)
    .attr("y1", 0)
    .attr("y2", sHeight - 1);

  vRules.append("svg:text")
    .attr("x", sXLScale)
    .attr("y", sHeight + 3)
    .attr("dy", "1.71em")
    .attr("text-anchor", "start")
    .text(function(d,i) { return d; });

  hRules.append("svg:line")
    .attr("y1", sYScale)
    .attr("y2", sYScale)
    .attr("x1", 0)
    .attr("x2", sWidth + 1);

  hRules.append("svg:text")
    .attr("y", sYScale)
    .attr("x", -3)
    .attr("dy", ".35em")
    .attr("stroke", "grey")
    .attr("text-anchor", "end")
    .text(sYScale.tickFormat(10));

  series = series.sort(function(p,n) {
    var r = 0;
    if (p.seriesKey < n.seriesKey)
      r = -1;
    if (p.seriesKey > n.seriesKey)
      r = 1;
    return r;
  });

  var invisibleCircles = [];

  function toggleVisible(di) {
    var selectedCircles = svg.selectAll(".circle" + di),
      selectedRects = svg.selectAll(".rect" + di),
      newRectFill = "",
      makeVisible = invisibleCircles.indexOf(di);

    if (makeVisible != -1) {
      invisibleCircles.splice(makeVisible,1);
    } else {
      invisibleCircles.push(di);
    }

    selectedCircles.attr("opacity", function(d,i) {
      var newOpacity;

      d.v = (d.v == true ? false : true);
      if (d.v) {
        newOpacity = .3;
        newRectFill = sColors(d.i);
      } else {
        newOpacity = 0;
        newRectFill = "none";
      }
      return newOpacity;
    });

    selectedRects.attr("fill", newRectFill);
  }

  // throwing this in a function so we can call it for each day
  function plotDay() {
    sTitle.text(selectedDate.toDateString());

    // clean up what follows
    var a = series.map(function() {return 0;});

    var t = [];

    series.map(function(e,i){
      e.data.map(function(o){
        if (o.yLeft_1 > 0  && o.yRight_1 > 0 && o.xTime.split(' ')[0] == dateToStr(selectedDate)) {
          a[i] = a[i] + o.yRight_2;
          o.i = i;
          o.a = a[i];
          o.v = (invisibleCircles.indexOf(i) == -1) ? true : false;
          t.push(o);
        }
      });
    });

    var data = t.sort(function(p,n) {
      var r = 0;
      if (p.x < n.x)
         r = -1;
      if (p.x > n.x)
        r = 1;
      return r;
    });

    // plot the initial set of circles
    var circle = svg.selectAll("circle")
      .data(data)
      .enter().append("svg:circle")
      .attr("class", function(d,i) { return "circle" + d.i; })
      .attr("fill", function(d,i) {return sColors(d.i);})
      .attr("opacity", function(d,i) {
        var o = .3;
        if (invisibleCircles.indexOf(d.i) != -1) {
          o = 0;
        }
        return o;
      })
      .attr("cx", function(d,i) {return sXScale(d.x);})
      .attr("cy", function(d,i) {return sYScale(d.yLeft_1);})
      .attr("r", function(d,i) {return sRScale(4 + (d.yRight_1 * 2));});

    // bolt on a bar graph
    var
      bXMax = Array.max(a),
      bXScale = d3.scale.linear().domain([0, bXMax]).range([0, bWidth]),
      bYScale = d3.scale.ordinal().domain(d3.range(series.length)).rangeBands([sHeight/8, sHeight - sHeight/8], .8);

    var barLabels = svg.selectAll("g.barLabels")
      .data(series)
      .enter().append("svg:text")
      .attr("class", "barText")
      .attr("transform", function(d, i) { return "translate(" + (sWidth + 3) + "," + (bYScale(i) - 5) + ")"; })
      .text(function(d,i) { return series[i]["seriesName"].replace(/"/g,''); })
      .on("click", function(d,i) { toggleVisible(i); });

    var bars = svg.selectAll("g.bar")
      .data(a)
      .enter().append("svg:g")
      .attr("transform", function(d, i) { return "translate(" + (sWidth + 3) + "," + bYScale(i) + ")"; });

    bars.append("svg:rect")
      .attr("class", function(d,i) {return "rect" + i;})
      .attr("stroke", function(d,i) {return sColors(i);})
      .attr("fill", function(d,i) {
        var f = sColors(i);
        if (invisibleCircles.indexOf(i) != -1) {
          f = "none";
        }
        return f;
      })
      .attr("width",  function(d,i) { return bXScale(d); })
      .attr("height", bYScale.rangeBand());

    bars.append("svg:text")
      .attr("class", "barText")
      .attr("x", bXScale)
      .attr("y", bYScale.rangeBand() / 2)
      .attr("dx", -6)
      .attr("dy", ".35em")
      .attr("fill", "white")
      .attr("text-anchor", "end")
      .text(bXScale.tickFormat(10));

  }

  function clearPlot() {
    svg.selectAll("circle").remove();
    svg.selectAll("g.barLabels").remove();
    svg.selectAll("g.bar").remove();
    svg.selectAll(".barText").remove();
    svg.selectAll("rect").remove();
  }

  plotDay();

  d3.select(window).on("keydown", function() {
    //alert(d3.event.keyCode);
    switch (d3.event.keyCode) {
      // left
      case 37: selectedDate = new Date(selectedDate.getTime() - od) ; break;
      // right
      case 39: selectedDate = new Date(selectedDate.getTime() + od) ; break;
      // up
      case 38: selectedDate = new Date(selectedDate.getTime() - (7*od)) ; break;
      // down
      case 40: selectedDate = new Date(selectedDate.getTime() + (7*od)) ; break;
    }
    clearPlot();
    plotDay();
  });

}
<|endoftext|>


<commit_before>/**
 * @author Titus Wormer
 * @copyright 2015 Titus Wormer
 * @license MIT
 * @module no-shell-dollars
 * @fileoverview
 *   Warn when shell code is prefixed by `$` (dollar sign) characters.
 *
 *   Ignores indented code blocks and fenced code blocks without language flag.
 *
 * @example {"name": "ok.md"}
 *
 *   ```sh
 *   echo a
 *   echo a > file
 *   ```
 *
 *   ```zsh
 *   $ echo a
 *   a
 *   $ echo a > file
 *   ```
 *
 *   Some empty code:
 *
 *   ```command
 *   ```
 *
 *   It’s fine to use dollars in non-shell code.
 *
 *   ```js
 *   $('div').remove();
 *   ```
 *
 * @example {"name": "not-ok.md", "label": "input"}
 *
 *   ```bash
 *   $ echo a
 *   $ echo a > file
 *   ```
 *
 * @example {"name": "not-ok.md", "label": "output"}
 *
 *   1:1-4:4: Do not use dollar signs before shell commands
 */

'use strict'

var rule = require('unified-lint-rule')
var visit = require('unist-util-visit')
var generated = require('unist-util-generated')

module.exports = rule('remark-lint:no-shell-dollars', noShellDollars)

var reason = 'Do not use dollar signs before shell commands'

// List of shell script file extensions (also used as code flags for syntax
// highlighting on GitHub):
// See: <https://github.com/github/linguist/blob/001ca52/lib/linguist/languages.yml#L4702>
var flags = [
  'sh',
  'bash',
  'bats',
  'cgi',
  'command',
  'fcgi',
  'ksh',
  'tmux',
  'tool',
  'zsh'
]

function noShellDollars(tree, file) {
  visit(tree, 'code', visitor)

  function visitor(node) {
    var lines
    var line
    var length
    var index

    // Check both known shell code and unknown code.
    if (!generated(node) && node.lang && flags.indexOf(node.lang) !== -1) {
      lines = node.value.split('\n')
      length = lines.length
      index = -1

      if (length <= 1) {
        return
      }

      while (++index < length) {
        line = lines[index]

        if (line.trim() && !line.match(/^\s*\$\s*/)) {
          return
        }
      }

      file.message(reason, node)
    }
  }
}
<commit_msg>Update flags url<commit_after>/**
 * @author Titus Wormer
 * @copyright 2015 Titus Wormer
 * @license MIT
 * @module no-shell-dollars
 * @fileoverview
 *   Warn when shell code is prefixed by `$` (dollar sign) characters.
 *
 *   Ignores indented code blocks and fenced code blocks without language flag.
 *
 * @example {"name": "ok.md"}
 *
 *   ```sh
 *   echo a
 *   echo a > file
 *   ```
 *
 *   ```zsh
 *   $ echo a
 *   a
 *   $ echo a > file
 *   ```
 *
 *   Some empty code:
 *
 *   ```command
 *   ```
 *
 *   It’s fine to use dollars in non-shell code.
 *
 *   ```js
 *   $('div').remove();
 *   ```
 *
 * @example {"name": "not-ok.md", "label": "input"}
 *
 *   ```bash
 *   $ echo a
 *   $ echo a > file
 *   ```
 *
 * @example {"name": "not-ok.md", "label": "output"}
 *
 *   1:1-4:4: Do not use dollar signs before shell commands
 */

'use strict'

var rule = require('unified-lint-rule')
var visit = require('unist-util-visit')
var generated = require('unist-util-generated')

module.exports = rule('remark-lint:no-shell-dollars', noShellDollars)

var reason = 'Do not use dollar signs before shell commands'

// List of shell script file extensions (also used as code flags for syntax
// highlighting on GitHub):
// See: <https://github.com/github/linguist/blob/40992ba/lib/linguist/languages.yml#L4984>
var flags = [
  'sh',
  'bash',
  'bats',
  'cgi',
  'command',
  'fcgi',
  'ksh',
  'tmux',
  'tool',
  'zsh'
]

function noShellDollars(tree, file) {
  visit(tree, 'code', visitor)

  function visitor(node) {
    var lines
    var line
    var length
    var index

    // Check both known shell code and unknown code.
    if (!generated(node) && node.lang && flags.indexOf(node.lang) !== -1) {
      lines = node.value.split('\n')
      length = lines.length
      index = -1

      if (length <= 1) {
        return
      }

      while (++index < length) {
        line = lines[index]

        if (line.trim() && !line.match(/^\s*\$\s*/)) {
          return
        }
      }

      file.message(reason, node)
    }
  }
}
<|endoftext|>


<commit_before>/*********************************************************************************** *
 * MIT License
 *
 * Copyright (c) 2017 Raphael "rGunti" Guntersweiler
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * ********************************************************************************* */

$(document).ready(function() {
    var songs = [];
    var renderedItems = 0;
    var PAGE_SIZE = 10;

    function generateSongInfoText(song) {
        return '' + (song.Title || song.file) + '' + (song.Artist ? ' by ' + song.Artist + '' : '')
    }

    function renderSongs(startIndex) {
        renderedItems = startIndex;
        for (var i = startIndex; i < startIndex + PAGE_SIZE && i < songs.length; i++) {
            var song = songs[i];

            // Song can be null (for some reason)
            if (!song) {
                songs.splice(i, 1);
                continue;
            }

            var item = $('#queueItemTemplate').clone();
            item.attr('id', '');

            $('.result-title', item).text(song.Title || song.file);
            if (song.Artist) {
                $('.result-artist', item).text(song.Artist);
            } else {
                $('.result-artist', item).hide();
            }
            $('.result-length', item).text(formatTimeWithMinutes(song.Time));
            $('.result-pos', item).text(Number(song.Pos) + 1);

            var button = $('.result-actions', item);
            button.click(onSongClick);
            button.data('song', song);

            item.appendTo('#queueRenderTarget').hide();

            renderedItems++;
        }
        fadeInHiddenElement();
        $('.queuePositionIndicator').text((startIndex + 1) + '-' + renderedItems + '/' + songs.length);
    }

    function fadeInHiddenElement() {
        //console.log('Fade In');
        var item = $('#queueRenderTarget .collection-item:hidden:first');
        if (item.length > 0) {
            item.fadeIn(100, fadeInHiddenElement);
        }
    }

    function fadeOutVisibleElements(callback) {
        //console.log('Fade Out');
        var item = $('#queueRenderTarget .collection-item:visible:last');
        if (item.length > 0) {
            item.fadeOut(50, function() {
                item.remove();
                fadeOutVisibleElements(callback);
            });
        } else {
            if (callback) callback();
        }
    }

    function onSongClick(e) {
        var target = $(e.currentTarget);
        var song = target.data('song');

        $('#selectActionModal .result-pos').text(Number(song.Pos) + 1);
        $('#selectActionModal .result-title').text(song.Title || song.file);
        $('#selectActionModal .result-artist').text(song.Artist || '');
        $('#selectActionModal').data('song', song).modal('open');
    }

    $('.queueLoadMoreButton').click(function(e) {
        var target = renderedItems;
        reloadQueueData(function(d,o) {
            //console.log(d.length, o.length, renderedItems);
            if (d.length === o.length && target === o.length) {
                Materialize.toast("You've reached the end of the queue.", 2500);
                return;
            }
            if (d.length <= target) {
                target = d.length - 1;
                var mod = target % PAGE_SIZE;
                if (mod > 0) {
                    target -= mod;
                } else {
                    target -= PAGE_SIZE;
                }
            }
            fadeOutVisibleElements(function() {
                renderSongs(target);
            });
        });
    });

    $('.queueReloadButton').click(function(e) {
        var target = renderedItems - (renderedItems % PAGE_SIZE);
        if (target === renderedItems) target -= PAGE_SIZE;
        reloadQueueData(function(d) {
            //console.log(renderedItems, target, d.length);

            if (d.length < target) {
                target = d.length - 1;
                var mod = target % PAGE_SIZE;
                if (mod > 0) {
                    target -= mod;
                } else {
                    target -= PAGE_SIZE;
                }
            }

            fadeOutVisibleElements(function() {
                renderSongs(Math.max(0, target));
            });
        });
    });

    $('.queueLoadLessButton').click(function(e) {
        var target = renderedItems - PAGE_SIZE;
        var mod = target % PAGE_SIZE;
        if (mod > 0) {
            target -= mod;
        } else {
            target -= PAGE_SIZE;
        }
        //console.log(renderedItems, mod, target);

        reloadQueueData(function(d, o) {
            //console.log(d.length);

            if (d.length < target) {
                target = d.length - 1;
                mod = target % PAGE_SIZE;
                if (mod > 0) {
                    target -= mod;
                } else {
                    target -= PAGE_SIZE;
                }
            }

            fadeOutVisibleElements(function() {
                renderSongs(Math.max(0, target));
            });
        });
    });

    $('#selectActionModal a.collection-item').click(function(e) {
        var song = $('#selectActionModal').data('song');
        var action = $(e.currentTarget).data('action');
        //console.log(song, action);

        if (!action) { return; }

        switch (action) {
            case 'play':
                sendSimpleAjaxRequest('/mpd/queue/' + song.Pos + '/play', 'post', null, function(r) {
                    Materialize.toast(
                        '
Now playing
' + generateSongInfoText(song) + '
', 2500);
                });
                break;
            case 'remove':
                sendSimpleAjaxRequest('/mpd/queue/' + song.Pos + '/remove', 'post', null, function(r) {
                    Materialize.toast('
' + generateSongInfoText(song) +
                        '
 has been removed from the queue.
', 2500);
                    $('.queueReloadButton').first().click();
                });
                break;
            default:
                $.toaster({
                    title: 'Unknown Action',
                    message: action,
                    priority: 'danger'
                });
                break;
        }
        $('#selectActionModal').modal('close');
    });

    $('#clearQueueLink').click(function(e) {
        $('#clearQueueModal').modal('open');
    });

    $('#clearQueueModal .confirm-yes').click(function(e) {
        sendSimpleAjaxRequest(
            '/mpd/queue/clear',
            'post',
            null,
            function() {
                $('#clearQueueModal').modal('close');
                LoadingIndicator.hide();
                Materialize.toast('Queue cleared!', 2500);
                $('.queueReloadButton').first().click();
            },
            function() {
                LoadingIndicator.hide();
            }
        );
    });

    $('#createPlaylistFromQueueLink').click(function(e) {
        e.preventDefault();
        $('#createPlaylistModal').modal('open');
    });

    $('#createPlaylistModal button.modal-button-cancel').click(function() {
        $('#createPlaylistModal').modal('close');
    });

    $('#createPlaylistModal form').submit(function(e) {
        e.preventDefault();
        LoadingIndicator.show();

        var playlistName = $('#createPlaylistPlaylistName').val();
        sendSimpleAjaxRequest(
            '/mpd/queue/toPlaylist',
            'post',
            { name: playlistName },
            function() {
                $('#createPlaylistPlaylistName').val('');
                $('#createPlaylistModal').modal('close');
                LoadingIndicator.hide();
                Materialize.toast('Playlist "' + playlistName + '" created', 2500);
            },
            function() {
                LoadingIndicator.hide();
            }
        );
    });

    function reloadQueueData(renderCallback) {
        $.ajax({
            url: '/mpd/queue',
            method: 'get',
            beforeSend: function() {
                LoadingIndicator.show();
                $('.queueNavigationButtons').attr('disabled', true);
            }
        }).done(function(data, textStatus, jqXHR) {
            if (data.ok) {
                if (data.data && data.data.length >= 1 && data.data[0] !== null) {
                    var oldSongs = songs;
                    songs = data.data;
                    renderCallback(songs, oldSongs);
                } else {
                    Materialize.toast('No Songs found! Add a few songs to the queue to start the party.', 2500);
                }
            } else {
                Materialize.toast('Error! ' + data.message);
            }
        }).fail(function(jqXHR, textStatus, errorThrown) {
            Materialize.toast('Error! Something went horribly wrong here D:
Some more detail for you:
' + textStatus);
        }).always(function(data_or_jqXHR, textStatus, jqXHR_or_errorThrown) {
            LoadingIndicator.hide();
            $('.queueNavigationButtons').attr('disabled', false);
        });
    }

    reloadQueueData(function(data) {
        renderSongs(0);
    });
});
<commit_msg>Fixed a bug on the queue script which prevented JS from clearing the Queue view<commit_after>/*********************************************************************************** *
 * MIT License
 *
 * Copyright (c) 2017 Raphael "rGunti" Guntersweiler
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * ********************************************************************************* */

$(document).ready(function() {
    var songs = [];
    var renderedItems = 0;
    var PAGE_SIZE = 10;

    function generateSongInfoText(song) {
        return '' + (song.Title || song.file) + '' + (song.Artist ? ' by ' + song.Artist + '' : '')
    }

    function renderSongs(startIndex) {
        renderedItems = startIndex;
        for (var i = startIndex; i < startIndex + PAGE_SIZE && i < songs.length; i++) {
            var song = songs[i];

            // Song can be null (for some reason)
            if (!song) {
                songs.splice(i, 1);
                continue;
            }

            var item = $('#queueItemTemplate').clone();
            item.attr('id', '');

            $('.result-title', item).text(song.Title || song.file);
            if (song.Artist) {
                $('.result-artist', item).text(song.Artist);
            } else {
                $('.result-artist', item).hide();
            }
            $('.result-length', item).text(formatTimeWithMinutes(song.Time));
            $('.result-pos', item).text(Number(song.Pos) + 1);

            var button = $('.result-actions', item);
            button.click(onSongClick);
            button.data('song', song);

            item.appendTo('#queueRenderTarget').hide();

            renderedItems++;
        }
        fadeInHiddenElement();
        $('.queuePositionIndicator').text((startIndex + 1) + '-' + renderedItems + '/' + songs.length);
    }

    function fadeInHiddenElement() {
        //console.log('Fade In');
        var item = $('#queueRenderTarget .collection-item:hidden:first');
        if (item.length > 0) {
            item.fadeIn(100, fadeInHiddenElement);
        }
    }

    function fadeOutVisibleElements(callback) {
        //console.log('Fade Out');
        var item = $('#queueRenderTarget .collection-item:visible:last');
        if (item.length > 0) {
            item.fadeOut(50, function() {
                item.remove();
                fadeOutVisibleElements(callback);
            });
        } else {
            if (callback) callback();
        }
    }

    function onSongClick(e) {
        var target = $(e.currentTarget);
        var song = target.data('song');

        $('#selectActionModal .result-pos').text(Number(song.Pos) + 1);
        $('#selectActionModal .result-title').text(song.Title || song.file);
        $('#selectActionModal .result-artist').text(song.Artist || '');
        $('#selectActionModal').data('song', song).modal('open');
    }

    $('.queueLoadMoreButton').click(function(e) {
        var target = renderedItems;
        reloadQueueData(function(d,o) {
            //console.log(d.length, o.length, renderedItems);
            if (d.length === o.length && target === o.length) {
                Materialize.toast("You've reached the end of the queue.", 2500);
                return;
            }
            if (d.length <= target) {
                target = d.length - 1;
                var mod = target % PAGE_SIZE;
                if (mod > 0) {
                    target -= mod;
                } else {
                    target -= PAGE_SIZE;
                }
            }
            fadeOutVisibleElements(function() {
                renderSongs(target);
            });
        });
    });

    $('.queueReloadButton').click(function(e) {
        var target = renderedItems - (renderedItems % PAGE_SIZE);
        if (target === renderedItems) target -= PAGE_SIZE;
        reloadQueueData(function(d) {
            //console.log(renderedItems, target, d.length);

            if (d.length < target) {
                target = d.length - 1;
                var mod = target % PAGE_SIZE;
                if (mod > 0) {
                    target -= mod;
                } else {
                    target -= PAGE_SIZE;
                }
            }

            fadeOutVisibleElements(function() {
                renderSongs(Math.max(0, target));
            });
        });
    });

    $('.queueLoadLessButton').click(function(e) {
        var target = renderedItems - PAGE_SIZE;
        var mod = target % PAGE_SIZE;
        if (mod > 0) {
            target -= mod;
        } else {
            target -= PAGE_SIZE;
        }
        //console.log(renderedItems, mod, target);

        reloadQueueData(function(d, o) {
            //console.log(d.length);

            if (d.length < target) {
                target = d.length - 1;
                mod = target % PAGE_SIZE;
                if (mod > 0) {
                    target -= mod;
                } else {
                    target -= PAGE_SIZE;
                }
            }

            fadeOutVisibleElements(function() {
                renderSongs(Math.max(0, target));
            });
        });
    });

    $('#selectActionModal a.collection-item').click(function(e) {
        var song = $('#selectActionModal').data('song');
        var action = $(e.currentTarget).data('action');
        //console.log(song, action);

        if (!action) { return; }

        switch (action) {
            case 'play':
                sendSimpleAjaxRequest('/mpd/queue/' + song.Pos + '/play', 'post', null, function(r) {
                    Materialize.toast(
                        '
Now playing
' + generateSongInfoText(song) + '
', 2500);
                });
                break;
            case 'remove':
                sendSimpleAjaxRequest('/mpd/queue/' + song.Pos + '/remove', 'post', null, function(r) {
                    Materialize.toast('
' + generateSongInfoText(song) +
                        '
 has been removed from the queue.
', 2500);
                    $('.queueReloadButton').first().click();
                });
                break;
            default:
                $.toaster({
                    title: 'Unknown Action',
                    message: action,
                    priority: 'danger'
                });
                break;
        }
        $('#selectActionModal').modal('close');
    });

    $('#clearQueueLink').click(function(e) {
        $('#clearQueueModal').modal('open');
    });

    $('#clearQueueModal .confirm-yes').click(function(e) {
        sendSimpleAjaxRequest(
            '/mpd/queue/clear',
            'post',
            null,
            function() {
                $('#clearQueueModal').modal('close');
                Materialize.toast('Queue cleared!', 2500);

                fadeOutVisibleElements();
                $('.queuePositionIndicator').text('1-0/0');
            },
            function() {
                LoadingIndicator.hide();
            }
        );
    });

    $('#createPlaylistFromQueueLink').click(function(e) {
        e.preventDefault();
        $('#createPlaylistModal').modal('open');
    });

    $('#createPlaylistModal button.modal-button-cancel').click(function() {
        $('#createPlaylistModal').modal('close');
    });

    $('#createPlaylistModal form').submit(function(e) {
        e.preventDefault();
        LoadingIndicator.show();

        var playlistName = $('#createPlaylistPlaylistName').val();
        sendSimpleAjaxRequest(
            '/mpd/queue/toPlaylist',
            'post',
            { name: playlistName },
            function() {
                $('#createPlaylistPlaylistName').val('');
                $('#createPlaylistModal').modal('close');
                LoadingIndicator.hide();
                Materialize.toast('Playlist "' + playlistName + '" created', 2500);
            },
            function() {
                LoadingIndicator.hide();
            }
        );
    });

    function reloadQueueData(renderCallback) {
        $.ajax({
            url: '/mpd/queue',
            method: 'get',
            beforeSend: function() {
                LoadingIndicator.show();
                $('.queueNavigationButtons').attr('disabled', true);
            }
        }).done(function(data, textStatus, jqXHR) {
            if (data.ok) {
                if (data.data && data.data.length >= 1 && data.data[0] !== null) {
                    var oldSongs = songs;
                    songs = data.data;
                    renderCallback(songs, oldSongs);
                } else {
                    Materialize.toast('No Songs found! Add a few songs to the queue to start the party.', 2500);
                }
            } else {
                Materialize.toast('Error! ' + data.message);
            }
        }).fail(function(jqXHR, textStatus, errorThrown) {
            Materialize.toast('Error! Something went horribly wrong here D:
Some more detail for you:
' + textStatus);
        }).always(function(data_or_jqXHR, textStatus, jqXHR_or_errorThrown) {
            LoadingIndicator.hide();
            $('.queueNavigationButtons').attr('disabled', false);
        });
    }

    reloadQueueData(function(data) {
        renderSongs(0);
    });
});
<|endoftext|>


<commit_before>var path = "/";

function file_explorer(elem) {
  if (typeof elem == "undefined")
    elem = "body";
  this.elem = jQuery(elem);
  this.files = this.elem.find(".files");
  this.cd = this.elem.find(".current_path");
  this.href = "";
  var that = this;
  jQuery(this.elem).on("click", ".current_path a,.files .directory a", function (e) {
    e.preventDefault();
    that.changeDirectory($(this).attr("href"))
    return false;
  })
  // open file when clicked
  jQuery(this.elem).on("click", ".files .file a", function (e) {
    e.preventDefault();

    Silk.openFile($(this).attr("href"), $(this).parent().attr("data-mime"));
    // alert("You're going to have to setup a default view for mimetype: " + $(this).parent().attr("data-mime"));
    return false;
  })
  // Create folder
  jQuery("#newFolder").click(function (e) {
    var name = prompt("Name of Folder");
    methods.listen("fe/create/folder", {path: that.href, name: name}, function (err, result) {
      if(err){
      alert(err);
      return;
    }
    })
  })
  this.listener = methods.listen("fe/list/path", function (err, list) {
    if (err) return alert(JSON.stringify(err));
    that.processList(that.href, list);
  });

  this.changeDirectory("/");
}

file_explorer.prototype.changeDirectory = function (href) {
  // get files in / directory
  console.log("sending href: " + href);
  this.href = href;
  this.listener.send(href)
}

file_explorer.prototype.processCD = function (href) {
  aref = href.split("/");
  if (/\/$/.test(href)) {
    aref.pop();
  }
  this.cd.empty();
  var netref = "";
  for (var i = 0; i < aref.length; i++) {
    var name = aref[i];
    if (name == "") {
      name = "root";
    } else
      netref += "/" + name
    this.cd.append("/" + name + "");
  }
}
file_explorer.prototype.processList = function (href, list) {
  var files = [];
  this.processCD(href);
  this.files.empty();

  // add folders and separate files
  for (var i = 0; i < list.length; i++) {
    var item = list[i];
    if (item.isDir) {
      var el = jQuery("
" + item.name + "
");
      this.files.append(el);
      el.addClass("directory");

    } else {
      files.push(item);
    }
  }

  // add files
  for (var i = 0; i < files.length; i++) {
    var item = list[i];
    var el = jQuery("
" + item.name + "
");
    this.files.append(el);
    el.addClass("file");
    el.attr("data-mime", item.mime);

  }

}

jQuery(function ($) {
  new file_explorer();
})<commit_msg>Use new api when opening a file<commit_after>var path = "/";

function file_explorer(elem) {
  if(typeof elem == "undefined")
    elem = "body";
  this.elem = jQuery(elem);
  this.files = this.elem.find(".files");
  this.cd = this.elem.find(".current_path");
  this.href = "";
  var that = this;
  jQuery(this.elem).on("click", ".current_path a,.files .directory a", function (e) {
    e.preventDefault();
    that.changeDirectory($(this).attr("href"))
    return false;
  })
  // open file when clicked
  jQuery(this.elem).on("click", ".files .file a", function (e) {
    e.preventDefault();
    Manager.get('open', {path: $(this).attr("href"), mime: $(this).parent().attr("data-mime")});
    // alert("You're going to have to setup a default view for mimetype: " + $(this).parent().attr("data-mime"));
    return false;
  })
  // Create folder
  jQuery("#newFolder").click(function (e) {
    var name = prompt("Name of Folder");
    methods.listen("fe/create/folder", {path: that.href, name: name}, function (err, result) {
      if(err) {
        alert(err);
        return;
      }
    })
  })
  this.listener = methods.listen("fe/list/path", function (err, list) {
    if(err) return alert(JSON.stringify(err));
    that.processList(that.href, list);
  });

  this.changeDirectory("/");
}

file_explorer.prototype.changeDirectory = function (href) {
  // get files in / directory
  console.log("sending href: " + href);
  this.href = href;
  this.listener.send(href)
}

file_explorer.prototype.processCD = function (href) {
  aref = href.split("/");
  if(/\/$/.test(href)) {
    aref.pop();
  }
  this.cd.empty();
  var netref = "";
  for (var i = 0; i < aref.length; i++) {
    var name = aref[i];
    if(name == "") {
      name = "root";
    } else
      netref += "/" + name
    this.cd.append("/" + name + "");
  }
}
file_explorer.prototype.processList = function (href, list) {
  var files = [];
  this.processCD(href);
  this.files.empty();

  // add folders and separate files
  for (var i = 0; i < list.length; i++) {
    var item = list[i];
    if(item.isDir) {
      var el = jQuery("
" + item.name + "
");
      this.files.append(el);
      el.addClass("directory");

    } else {
      files.push(item);
    }
  }

  // add files
  for (var i = 0; i < files.length; i++) {
    var item = list[i];
    var el = jQuery("
" + item.name + "
");
    this.files.append(el);
    el.addClass("file");
    el.attr("data-mime", item.mime);

  }

}

jQuery(function ($) {
  new file_explorer();
})
<|endoftext|>