<commit_before>import React from 'react';
import {shouldComponentUpdate} from 'react/lib/ReactComponentWithPureRenderMixin';

const PageClick = React.createClass({
  propTypes: {
    children: React.PropTypes.node.isRequired,
    onClick: React.PropTypes.func.isRequired,
    outsideOnly: React.PropTypes.bool
  },

  getDefaultProps() {
    return {
      outsideOnly: true
    };
  },

  componentWillMount() {
    this.insideClick = false;
  },

  componentDidMount() {
    global.window.addEventListener('mousedown', this.onDocumentClick, false);
  },

  shouldComponentUpdate,

  componentWillUnmount() {
    global.window.removeEventListener('mousedown', this.onDocumentClick, false);
  },

  onDocumentClick(...args) {
    if (this.insideClick) {
      return;
    }
    this.props.onClick(...args);
  },

  onMouseDown() {
    this.insideClick = true;
  },

  onMouseUp() {
    this.insideClick = false;
  },

  render() {
    const props = this.props.outsideOnly ? {
      onMouseDown: this.onMouseDown,
      onMouseUp: this.onMouseUp
    } : {};

    return React.cloneElement(React.Children.only(this.props.children), props);
  }
});

export default PageClick;
<commit_msg>Fix PageClick for touch-screens<commit_after>import React from 'react';
import {shouldComponentUpdate} from 'react/lib/ReactComponentWithPureRenderMixin';

const PageClick = React.createClass({
  propTypes: {
    children: React.PropTypes.node.isRequired,
    onClick: React.PropTypes.func.isRequired,
    onMouseDown: React.PropTypes.func,
    onTouchStart: React.PropTypes.func,
    onMouseUp: React.PropTypes.func,
    onTouchEnd: React.PropTypes.func,
    outsideOnly: React.PropTypes.bool
  },

  getDefaultProps() {
    return {
      outsideOnly: true
    };
  },

  componentWillMount() {
    this.insideClick = false;
  },

  componentDidMount() {
    global.window.addEventListener('mousedown', this.onDocumentClick, false);
    global.window.addEventListener('touchstart', this.onDocumentClick, false);
  },

  shouldComponentUpdate,

  componentWillUnmount() {
    global.window.removeEventListener('mousedown', this.onDocumentClick, false);
    global.window.removeEventListener('touchstart', this.onDocumentClick, false);
  },

  onDocumentClick(...args) {
    if (this.insideClick) {
      return;
    }
    this.props.onClick(...args);
  },

  onMouseDown(...args) {
    this.insideClick = true;
    if (this.props.onMouseDown) {
      this.props.onMouseDown(...args);
    }
  },

  onMouseUp(...args) {
    this.insideClick = false;
    if (this.props.onMouseUp) {
      this.props.onMouseUp(...args);
    }
  },

  onTouchStart(...args) {
    this.insideClick = true;
    if (this.props.onTouchStart) {
      this.props.onTouchStart(...args);
    }
  },

  onTouchEnd(...args) {
    this.insideClick = false;
    if (this.props.onTouchEnd) {
      this.props.onTouchEnd(...args);
    }
  },

  render() {
    const props = this.props.outsideOnly ? {
      onMouseDown: this.onMouseDown,
      onMouseUp: this.onMouseUp,
      onTouchStart: this.onTouchStart,
      onTouchEnd: this.onTouchEnd
    } : {};

    return React.cloneElement(React.Children.only(this.props.children), props);
  }
});

export default PageClick;
<|endoftext|>


<commit_before>'use strict';
<commit_msg>successfuly getting the users location<commit_after>'use strict';
//This functions gets the current user's location
function getLocation(){
if(navigator.geolocation){
   navigator.geolocation.getCurrentPosition(showData);
}
}
function showData(position){
  var currentLocation = [position.coords.latitude, position.coords.longitude].join();
  console.log(currentLocation);
}
<|endoftext|>


<commit_before>'use strict';

var request = require('request');

/**
 * Upload `contact` (containing contact data) onto Cluestr.
 *
 *
 * @param {Object} contact Contact to upload, plus cluestrClient
 * @param {Object} cluestrClient Client for upload
 * @param {Object} datas Datas about the current account
 * @param {Object} contact Contact to upload, plus cluestrClient
 * @param {Function} cb Callback to call once contacts has been uploaded.
 */
module.exports = function(contact, cluestrClient, datas, cb) {
  console.log("Uploading ", contact.url);
  var identifier = contact.url;

  if(contact.deleted) {
    return cluestrClient.deleteDocument(identifier, cb);
  }

  // Download image (if any)
  var numericId = contact.id.substr(contact.id.lastIndexOf('/') + 1);
  var params = {
    encoding: null,
    url: 'https://www.google.com/m8/feeds/photos/media/default/' + numericId,
    headers: {
      'Authorization': 'OAuth ' + contact.accessToken,
      'GData-Version': '3.0'
    },
  };

  request.get(params, function (err, resp, body) {
    if(err) {
      return cb(err);
    }

    var datas = {};
    if(resp.statusCode === 200) {
      datas.image = 'data:image/*;base64,' + body.toString('base64');
    }

    // Build contact "the right way"
    contact = {
      identifier: identifier,
      metadatas: contact,
      datas: datas,
      semantic_document_type: 'contact',
      actions: {
        'show': contact.url
      },
      user_access: [cluestrClient.accessToken]
    };

    delete contact.metadatas.url;
    delete contact.metadatas.id;
    delete contact.metadatas.accessToken;

    cluestrClient.sendDocument(contact, cb);
  });
};
<commit_msg>Removed semantic / binary document_type<commit_after>'use strict';

var request = require('request');

/**
 * Upload `contact` (containing contact data) onto Cluestr.
 *
 *
 * @param {Object} contact Contact to upload, plus cluestrClient
 * @param {Object} cluestrClient Client for upload
 * @param {Object} datas Datas about the current account
 * @param {Object} contact Contact to upload, plus cluestrClient
 * @param {Function} cb Callback to call once contacts has been uploaded.
 */
module.exports = function(contact, cluestrClient, datas, cb) {
  console.log("Uploading ", contact.url);
  var identifier = contact.url;

  if(contact.deleted) {
    return cluestrClient.deleteDocument(identifier, cb);
  }

  // Download image (if any)
  var numericId = contact.id.substr(contact.id.lastIndexOf('/') + 1);
  var params = {
    encoding: null,
    url: 'https://www.google.com/m8/feeds/photos/media/default/' + numericId,
    headers: {
      'Authorization': 'OAuth ' + contact.accessToken,
      'GData-Version': '3.0'
    },
  };

  request.get(params, function (err, resp, body) {
    if(err) {
      return cb(err);
    }

    var datas = {};
    if(resp.statusCode === 200) {
      datas.image = 'data:image/*;base64,' + body.toString('base64');
    }

    // Build contact "the right way"
    contact = {
      identifier: identifier,
      metadatas: contact,
      datas: datas,
      document_type: 'contact',
      actions: {
        'show': contact.url
      },
      user_access: [cluestrClient.accessToken]
    };

    delete contact.metadatas.url;
    delete contact.metadatas.id;
    delete contact.metadatas.accessToken;

    cluestrClient.sendDocument(contact, cb);
  });
};
<|endoftext|>


<commit_before>(function($){
 $.fn.airtimeShowSchedule = function(options) {

    var defaults = {
        updatePeriod: 20, //seconds
        sourceDomain: "http://localhost/", //where to get show status from
    };
    var options = $.extend(defaults, options);
    options.sourceDomain = addEndingBackslash(options.sourceDomain);

    return this.each(function() {
        var obj = $(this);
        var sd;

        getServerData();

        function updateWidget(){
            var currentShow = sd.getCurrentShow();
            var nextShows = sd.getNextShows();

            var currentShowName = "";
            var nextShowName = ""

            if (currentShow.length > 0){
                currentShowName = currentShow[0].getName();
            }

            if (nextShows.length > 0){
                nextShowName = nextShows[0].getName();
            }

            tableString = "";
            tableString += "
On air today
";
            tableString += "
"+
                "
";

            var shows=currentShow.concat(nextShows);

            obj.empty();
            for (var i=0; i<shows.length; i++){
                tableString +=
                "
" +
                ""+shows[i].getRange()+"	" +
                ""+shows[i].getName()+" Listen	" +
                "
";
            }

            tableString += "

";

            obj.append(tableString);
        }

        function processData(data){
            sd = new ScheduleData(data);
            updateWidget();
        }

        function getServerData(){
            $.ajax({ url: options.sourceDomain + "api/live-info/", dataType:"jsonp", success:function(data){
                        processData(data);
                  }, error:function(jqXHR, textStatus, errorThrown){}});
            setTimeout(getServerData, options.updatePeriod*1000);
        }
    });
 };
})(jQuery);

(function($){
 $.fn.airtimeLiveInfo = function(options) {

    var defaults = {
        updatePeriod: 5, //seconds
        sourceDomain: "http://localhost/", //where to get show status from
        audioStreamSource: "http://localhost:8000/airtime.mp3" //where to get audio stream from
    };
    var options = $.extend(defaults, options);
    options.sourceDomain = addEndingBackslash(options.sourceDomain);

    return this.each(function() {
        var obj = $(this);
        var sd;
        getServerData();

        function updateWidget(){
            var currentShow = sd.getCurrentShow();
            var nextShows = sd.getNextShows();

            var showStatus = "Offline";
            var currentShowName = "";
            var timeElapsed = "";
            var timeRemaining = "";

            var nextShowName = "";
            var nextShowRange = "";

            if (currentShow.length > 0){
                showStatus = "On Air Now";
                currentShowName = currentShow[0].getName();

                timeElapsed = sd.getShowTimeElapsed(currentShow[0]);
                timeRemaining = sd.getShowTimeRemaining(currentShow[0]);
            }

            if (nextShows.length > 0){
                nextShowName = nextShows[0].getName();
                nextShowRange = nextShows[0].getRange();
            }

            obj.empty();
            obj.append("Listen WADR Live");
            obj.append("
"+showStatus+" >>
");
            obj.append("
" +
                "
Current: "+currentShowName+
                ""+timeElapsed+"" +
                ""+timeRemaining+""+
                "
" +
                "
Next: "+nextShowName+""+nextShowRange+"
" +
                "
");

            //refresh the UI to update the elapsed/remaining time
            setTimeout(updateWidget, 1000);
        }

        function processData(data){
            sd = new ScheduleData(data);
            updateWidget();
        }

        function getServerData(){
            $.ajax({ url: options.sourceDomain + "api/live-info/", dataType:"jsonp", success:function(data){
                        processData(data);
                  }, error:function(jqXHR, textStatus, errorThrown){}});
            setTimeout(getServerData, options.updatePeriod*1000);
        }
    });
 };
})(jQuery);

(function($){
 $.fn.airtimeWeekSchedule = function(options) {

    var defaults = {
        sourceDomain: "http://localhost/", //where to get show status from
        updatePeriod: 600,
        dowText: {monday:"Monday", tuesday:"Tuesday", wednesday:"Wednesday", thursday:"Thursday", friday:"Friday", saturday:"Saturday", sunday:"Sunday"},
        miscText: {time:"Time", programName:"Program Name", details:"Details", readMore:"Read More"}
    };
    var options = $.extend(defaults, options);
    options.sourceDomain = addEndingBackslash(options.sourceDomain);

    return this.each(function() {
        var obj = $(this);
        obj.empty();

        obj.attr("class", "ui-tabs");

        var dow = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];

        var html = '
';
        for (var i=0; i<dow.length; i++){
            html += '
'+options.dowText[dow[i]]+'
';
        }
        html += '
';

        for (var i=0; i<dow.length; i++){
            html += '

'
        }
        obj.append(html);
        getServerData();

        function updateWidget(data){
            for (var i=0; i<dow.length; i++){
                var html =
                  '
'+
                    '<colgroup>'+
                      '<col width="150" />'+
                      '<col width="350" />'+
                      '<col width="240" />'+
                    '</colgroup>'+
                    '
'+
                      '
'+
                        ''+options.miscText.time+'	'+
                        ''+options.miscText.programName+'	'+
                        ''+options.miscText.details+'	'+
                      '
'+
                    '
'+
                    '
'+
                      '
'+
                        '	'+
                      '
'+
                    '
'+
                    '
';
                var daySchedule = data[dow[i]];
                for (var j=0; j<daySchedule.length; j++){
                    var url = daySchedule[j].url;
                    html +=
                      '
'+
                        ''+getTime(daySchedule[j].show_starts)+ " - " + getTime(daySchedule[j].show_ends)+'	'+
                        ''+
                          '
'+daySchedule[j].show_name+'
'+
                        '	'+
                        ''+
                          '
'+
                            '
'+(url.length > 0 ? ''+options.miscText.readMore+'':'')+'
'+
                          '
'+
                        '	'+
                      '
';
                }
                html +=
                    '
'+
                  '
';

                $("#"+dow[i]).empty();
                $("#"+dow[i]).append(html);
            }
        }

        function processData(data){
            updateWidget(data);
        }

        function getServerData(){
            $.ajax({ url: options.sourceDomain + "api/week-info/", dataType:"jsonp", success:function(data){
                        processData(data);
                  }, error:function(jqXHR, textStatus, errorThrown){}});
            setTimeout(getServerData, options.updatePeriod*1000);
        }
    });
 };
})(jQuery);

function addEndingBackslash(str){
    if (str.charAt(str.length-1) != '/')
        return str+'/';
    else return str;
}

/* ScheduleData class BEGIN */
function ScheduleData(data){
    this.data = data;
    this.estimatedSchedulePosixTime;

    this.currentShow = new Array();
    for (var i=0; i< data.currentShow.length; i++){
        this.currentShow[i] = new Show(data.currentShow[i]);
    }

    this.nextShows = new Array();
    for (var i=0; i< data.nextShow.length; i++){
        this.nextShows[i] = new Show(data.nextShow[i]);
    }

    this.schedulePosixTime = convertDateToPosixTime(data.schedulerTime);
    this.schedulePosixTime += parseInt(data.timezoneOffset)*1000;
    var date = new Date();
    this.localRemoteTimeOffset = date.getTime() - this.schedulePosixTime;
}

ScheduleData.prototype.secondsTimer = function(){
    var date = new Date();
    this.estimatedSchedulePosixTime = date.getTime() - this.localRemoteTimeOffset;
}

ScheduleData.prototype.getCurrentShow = function(){
    return this.currentShow;
}

ScheduleData.prototype.getNextShows = function() {
    return this.nextShows;
}

ScheduleData.prototype.getShowTimeElapsed = function(show) {
    this.secondsTimer();

    var showStart = convertDateToPosixTime(show.getStartTimestamp());
    return convertToHHMMSS(this.estimatedSchedulePosixTime - showStart);
};

ScheduleData.prototype.getShowTimeRemaining = function(show) {
    this.secondsTimer();

    var showEnd = convertDateToPosixTime(show.getEndTimestamp());
    return convertToHHMMSS(showEnd - this.estimatedSchedulePosixTime);
};
/* ScheduleData class END */

/* Show class BEGIN */
function Show(showData){
    this.showData = showData;
}

Show.prototype.getName = function(){
    return this.showData.name;
}
Show.prototype.getRange = function(){
    return getTime(this.showData.start_timestamp) + " - " + getTime(this.showData.end_timestamp);
}
Show.prototype.getStartTimestamp = function(){
    return this.showData.start_timestamp;
}
Show.prototype.getEndTimestamp = function(){
    return this.showData.end_timestamp;
}
/* Show class END */

function getTime(timestamp) {
    var time = timestamp.split(" ")[1].split(":");
    return time[0] + ":" + time[1];
};

/* Takes an input parameter of milliseconds and converts these into
 * the format HH:MM:SS */
function convertToHHMMSS(timeInMS){
	var time = parseInt(timeInMS);

	var hours = parseInt(time / 3600000);
	time -= 3600000*hours;

	var minutes = parseInt(time / 60000);
	time -= 60000*minutes;

	var seconds = parseInt(time / 1000);

	hours = hours.toString();
	minutes = minutes.toString();
	seconds = seconds.toString();

	if (hours.length == 1)
		hours = "0" + hours;
	if (minutes.length == 1)
		minutes = "0" + minutes;
	if (seconds.length == 1)
		seconds = "0" + seconds;
	if (hours == "00")
		return minutes + ":" + seconds;
	else
		return hours + ":" + minutes + ":" + seconds;
}

/* Takes in a string of format similar to 2011-02-07 02:59:57,
 * and converts this to epoch/posix time. */
function convertDateToPosixTime(s){
    var datetime = s.split(" ");

    var date = datetime[0].split("-");
    var time = datetime[1].split(":");

	var year = date[0];
	var month = date[1];
	var day = date[2];
	var hour = time[0];
	var minute = time[1];
    var sec = 0;
    var msec = 0;

    if (time[2].indexOf(".") != -1){
        var temp = time[2].split(".");
        sec = temp[0];
        msec = temp[1];
    } else
        sec = time[2];

	return Date.UTC(year, month, day, hour, minute, sec, msec);
}
<commit_msg>CC-1990:Widget to display schedule and "Now Playing" on any website -added internationalization support for all WADR widgets<commit_after>(function($){
 $.fn.airtimeShowSchedule = function(options) {

    var defaults = {
        updatePeriod: 20, //seconds
        sourceDomain: "http://localhost/", //where to get show status from
        text: {onAirToday:"On air today"}
    };
    var options = $.extend(defaults, options);
    options.sourceDomain = addEndingBackslash(options.sourceDomain);

    return this.each(function() {
        var obj = $(this);
        var sd;

        getServerData();

        function updateWidget(){
            var currentShow = sd.getCurrentShow();
            var nextShows = sd.getNextShows();

            var currentShowName = "";
            var nextShowName = ""

            if (currentShow.length > 0){
                currentShowName = currentShow[0].getName();
            }

            if (nextShows.length > 0){
                nextShowName = nextShows[0].getName();
            }

            tableString = "";
            tableString += "
"+options.text.onAirToday+"
";
            tableString += "
"+
                "
";

            var shows=currentShow.concat(nextShows);

            obj.empty();
            for (var i=0; i<shows.length; i++){
                tableString +=
                "
" +
                ""+shows[i].getRange()+"	" +
                ""+shows[i].getName()+"	" +
                "
";
            }

            tableString += "

";

            obj.append(tableString);
        }

        function processData(data){
            sd = new ScheduleData(data);
            updateWidget();
        }

        function airtimeScheduleJsonpError(jqXHR, textStatus, errorThrown){
        }

        function getServerData(){
            $.ajax({ url: options.sourceDomain + "api/live-info/", dataType:"jsonp", success:function(data){
                        processData(data);
                  }, error:airtimeScheduleJsonpError});
            setTimeout(getServerData, options.updatePeriod*1000);
        }
    });
 };
})(jQuery);

(function($){
 $.fn.airtimeLiveInfo = function(options) {

    var defaults = {
        updatePeriod: 5, //seconds
        sourceDomain: "http://localhost/", //where to get show status from
        audioStreamSource: "http://localhost:8000/airtime.mp3", //where to get audio stream from
        text: {listenLive:"Listen WADR Live", onAirNow:"On Air Now", offline:"Offline", current:"Current", next:"Next"}
    };
    var options = $.extend(defaults, options);
    options.sourceDomain = addEndingBackslash(options.sourceDomain);

    return this.each(function() {
        var obj = $(this);
        var sd;
        getServerData();

        function updateWidget(){
            var currentShow = sd.getCurrentShow();
            var nextShows = sd.getNextShows();

            var showStatus = options.text.offline;
            var currentShowName = "";
            var timeElapsed = "";
            var timeRemaining = "";

            var nextShowName = "";
            var nextShowRange = "";

            if (currentShow.length > 0){
                showStatus = options.text.onAirNow;
                currentShowName = currentShow[0].getName();

                timeElapsed = sd.getShowTimeElapsed(currentShow[0]);
                timeRemaining = sd.getShowTimeRemaining(currentShow[0]);
            }

            if (nextShows.length > 0){
                nextShowName = nextShows[0].getName();
                nextShowRange = nextShows[0].getRange();
            }

            obj.empty();
            obj.append(""+options.text.listenLive+"");
            obj.append("
"+showStatus+" >>
");
            obj.append("
" +
                "
"+options.text.current+": "+currentShowName+
                ""+timeElapsed+"" +
                ""+timeRemaining+""+
                "
" +
                "
"+options.text.next+": "+nextShowName+""+nextShowRange+"
" +
                "
");

            //refresh the UI to update the elapsed/remaining time
            setTimeout(updateWidget, 1000);
        }

        function processData(data){
            sd = new ScheduleData(data);
            updateWidget();
        }

        function airtimeScheduleJsonpError(jqXHR, textStatus, errorThrown){
        }

        function getServerData(){
            $.ajax({ url: options.sourceDomain + "api/live-info/", dataType:"jsonp", success:function(data){
                        processData(data);
                  }, error:airtimeScheduleJsonpError});
            setTimeout(getServerData, options.updatePeriod*1000);
        }
    });
 };
})(jQuery);

(function($){
 $.fn.airtimeWeekSchedule = function(options) {

    var defaults = {
        sourceDomain: "http://localhost/", //where to get show status from
        updatePeriod: 600,
        dowText: {monday:"Monday", tuesday:"Tuesday", wednesday:"Wednesday", thursday:"Thursday", friday:"Friday", saturday:"Saturday", sunday:"Sunday"},
        miscText: {time:"Time", programName:"Program Name", details:"Details", readMore:"Read More"}
    };
    var options = $.extend(defaults, options);
    options.sourceDomain = addEndingBackslash(options.sourceDomain);

    return this.each(function() {
        var obj = $(this);
        obj.empty();

        obj.attr("class", "ui-tabs");

        var dow = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];

        var html = '
';
        for (var i=0; i<dow.length; i++){
            html += '
'+options.dowText[dow[i]]+'
';
        }
        html += '
';

        for (var i=0; i<dow.length; i++){
            html += '

'
        }
        obj.append(html);
        getServerData();

        function updateWidget(data){
            for (var i=0; i<dow.length; i++){
                var html =
                  '
'+
                    '<colgroup>'+
                      '<col width="150" />'+
                      '<col width="350" />'+
                      '<col width="240" />'+
                    '</colgroup>'+
                    '
'+
                      '
'+
                        ''+options.miscText.time+'	'+
                        ''+options.miscText.programName+'	'+
                        ''+options.miscText.details+'	'+
                      '
'+
                    '
'+
                    '
'+
                      '
'+
                        '	'+
                      '
'+
                    '
'+
                    '
';
                var daySchedule = data[dow[i]];
                for (var j=0; j<daySchedule.length; j++){
                    var url = daySchedule[j].url;
                    html +=
                      '
'+
                        ''+getTime(daySchedule[j].show_starts)+ " - " + getTime(daySchedule[j].show_ends)+'	'+
                        ''+
                          '
'+daySchedule[j].show_name+'
'+
                        '	'+
                        ''+
                          '
'+
                            '
'+(url.length > 0 ? ''+options.miscText.readMore+'':'')+'
'+
                          '
'+
                        '	'+
                      '
';
                }
                html +=
                    '
'+
                  '
';

                $("#"+dow[i]).empty();
                $("#"+dow[i]).append(html);
            }
        }

        function processData(data){
            updateWidget(data);
        }

        function airtimeScheduleJsonpError(jqXHR, textStatus, errorThrown){
        }

        function getServerData(){
            $.ajax({ url: options.sourceDomain + "api/week-info/", dataType:"jsonp", success:function(data){
                        processData(data);
                  }, error:airtimeScheduleJsonpError});
            setTimeout(getServerData, options.updatePeriod*1000);
        }
    });
 };
})(jQuery);

function addEndingBackslash(str){
    if (str.charAt(str.length-1) != '/')
        return str+'/';
    else return str;
}

/* ScheduleData class BEGIN */
function ScheduleData(data){
    this.data = data;
    this.estimatedSchedulePosixTime;

    this.currentShow = new Array();
    for (var i=0; i< data.currentShow.length; i++){
        this.currentShow[i] = new Show(data.currentShow[i]);
    }

    this.nextShows = new Array();
    for (var i=0; i< data.nextShow.length; i++){
        this.nextShows[i] = new Show(data.nextShow[i]);
    }

    this.schedulePosixTime = convertDateToPosixTime(data.schedulerTime);
    this.schedulePosixTime += parseInt(data.timezoneOffset)*1000;
    var date = new Date();
    this.localRemoteTimeOffset = date.getTime() - this.schedulePosixTime;
}

ScheduleData.prototype.secondsTimer = function(){
    var date = new Date();
    this.estimatedSchedulePosixTime = date.getTime() - this.localRemoteTimeOffset;
}

ScheduleData.prototype.getCurrentShow = function(){
    return this.currentShow;
}

ScheduleData.prototype.getNextShows = function() {
    return this.nextShows;
}

ScheduleData.prototype.getShowTimeElapsed = function(show) {
    this.secondsTimer();

    var showStart = convertDateToPosixTime(show.getStartTimestamp());
    return convertToHHMMSS(this.estimatedSchedulePosixTime - showStart);
};

ScheduleData.prototype.getShowTimeRemaining = function(show) {
    this.secondsTimer();

    var showEnd = convertDateToPosixTime(show.getEndTimestamp());
    return convertToHHMMSS(showEnd - this.estimatedSchedulePosixTime);
};
/* ScheduleData class END */

/* Show class BEGIN */
function Show(showData){
    this.showData = showData;
}

Show.prototype.getName = function(){
    return this.showData.name;
}
Show.prototype.getRange = function(){
    return getTime(this.showData.start_timestamp) + " - " + getTime(this.showData.end_timestamp);
}
Show.prototype.getStartTimestamp = function(){
    return this.showData.start_timestamp;
}
Show.prototype.getEndTimestamp = function(){
    return this.showData.end_timestamp;
}
/* Show class END */

function getTime(timestamp) {
    var time = timestamp.split(" ")[1].split(":");
    return time[0] + ":" + time[1];
};

/* Takes an input parameter of milliseconds and converts these into
 * the format HH:MM:SS */
function convertToHHMMSS(timeInMS){
	var time = parseInt(timeInMS);

	var hours = parseInt(time / 3600000);
	time -= 3600000*hours;

	var minutes = parseInt(time / 60000);
	time -= 60000*minutes;

	var seconds = parseInt(time / 1000);

	hours = hours.toString();
	minutes = minutes.toString();
	seconds = seconds.toString();

	if (hours.length == 1)
		hours = "0" + hours;
	if (minutes.length == 1)
		minutes = "0" + minutes;
	if (seconds.length == 1)
		seconds = "0" + seconds;
	if (hours == "00")
		return minutes + ":" + seconds;
	else
		return hours + ":" + minutes + ":" + seconds;
}

/* Takes in a string of format similar to 2011-02-07 02:59:57,
 * and converts this to epoch/posix time. */
function convertDateToPosixTime(s){
    var datetime = s.split(" ");

    var date = datetime[0].split("-");
    var time = datetime[1].split(":");

	var year = date[0];
	var month = date[1];
	var day = date[2];
	var hour = time[0];
	var minute = time[1];
    var sec = 0;
    var msec = 0;

    if (time[2].indexOf(".") != -1){
        var temp = time[2].split(".");
        sec = temp[0];
        msec = temp[1];
    } else
        sec = time[2];

	return Date.UTC(year, month, day, hour, minute, sec, msec);
}
<|endoftext|>


<commit_before>/* @flow */

import { isDef, isUndef, extend, toNumber } from 'shared/util'

function updateDOMProps (oldVnode: VNodeWithData, vnode: VNodeWithData) {
  if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) {
    return
  }
  let key, cur
  const elm: any = vnode.elm
  const oldProps = oldVnode.data.domProps || {}
  let props = vnode.data.domProps || {}
  // clone observed objects, as the user probably wants to mutate it
  if (isDef(props.__ob__)) {
    props = vnode.data.domProps = extend({}, props)
  }

  for (key in oldProps) {
    if (isUndef(props[key])) {
      elm[key] = ''
    }
  }
  for (key in props) {
    cur = props[key]
    // ignore children if the node has textContent or innerHTML,
    // as these will throw away existing DOM nodes and cause removal errors
    // on subsequent patches (#3360)
    if (key === 'textContent' || key === 'innerHTML') {
      if (vnode.children) vnode.children.length = 0
      if (cur === oldProps[key]) continue
      // #6601 work around Chrome version <= 55 bug where single textNode
      // replaced by innerHTML/textContent retains its parentNode property
      if (elm.childNodes.length === 1) {
        elm.removeChild(elm.childNodes[0])
      }
    }

    // #4521: if a click event triggers update before the change event is
    // dispatched on a checkbox/radio input, the input's checked state will
    // be reset and fail to trigger another update.
    // The root cause here is that browsers may fire microtasks in between click/change.
    // In Chrome / Firefox, click event fires before change, thus having this problem.
    // In Safari / Edge, the order is opposite.
    // Note: in Edge, if you click too fast, only the click event would fire twice.
    if (key === 'checked' && !isNotInFocusAndDirty(elm, cur)) {
      continue
    }

    if (key === 'value') {
      // store value as _value as well since
      // non-string values will be stringified
      elm._value = cur
      // avoid resetting cursor position when value is the same
      const strCur = isUndef(cur) ? '' : String(cur)
      if (shouldUpdateValue(elm, strCur)) {
        elm.value = strCur
      }
    } else {
      elm[key] = cur
    }
  }
}

// check platforms/web/util/attrs.js acceptValue
type acceptValueElm = HTMLInputElement | HTMLSelectElement | HTMLOptionElement;

function shouldUpdateValue (elm: acceptValueElm, checkVal: string): boolean {
  return (!elm.composing && (
    elm.tagName === 'OPTION' ||
    isNotInFocusAndDirty(elm, checkVal) ||
    isDirtyWithModifiers(elm, checkVal)
  ))
}

function isNotInFocusAndDirty (elm: acceptValueElm, checkVal: string): boolean {
  // return true when textbox (.number and .trim) loses focus and its value is
  // not equal to the updated value
  let notInFocus = true
  // #6157
  // work around IE bug when accessing document.activeElement in an iframe
  try { notInFocus = document.activeElement !== elm } catch (e) {}
  return notInFocus && elm.value !== checkVal
}

function isDirtyWithModifiers (elm: any, newVal: string): boolean {
  const value = elm.value
  const modifiers = elm._vModifiers // injected by v-model runtime
  if (isDef(modifiers)) {
    if (modifiers.number) {
      return toNumber(value) !== toNumber(newVal)
    }
    if (modifiers.trim) {
      return value.trim() !== newVal.trim()
    }
  }
  return value !== newVal
}

export default {
  create: updateDOMProps,
  update: updateDOMProps
}
<commit_msg>feat: support v-html for SVG elements (#8652)<commit_after>/* @flow */

import { isDef, isUndef, extend, toNumber } from 'shared/util'
import { isSVG } from 'web/util/index'

let svgContainer

function updateDOMProps (oldVnode: VNodeWithData, vnode: VNodeWithData) {
  if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) {
    return
  }
  let key, cur
  const elm: any = vnode.elm
  const oldProps = oldVnode.data.domProps || {}
  let props = vnode.data.domProps || {}
  // clone observed objects, as the user probably wants to mutate it
  if (isDef(props.__ob__)) {
    props = vnode.data.domProps = extend({}, props)
  }

  for (key in oldProps) {
    if (isUndef(props[key])) {
      elm[key] = ''
    }
  }
  for (key in props) {
    cur = props[key]
    // ignore children if the node has textContent or innerHTML,
    // as these will throw away existing DOM nodes and cause removal errors
    // on subsequent patches (#3360)
    if (key === 'textContent' || key === 'innerHTML') {
      if (vnode.children) vnode.children.length = 0
      if (cur === oldProps[key]) continue
      // #6601 work around Chrome version <= 55 bug where single textNode
      // replaced by innerHTML/textContent retains its parentNode property
      if (elm.childNodes.length === 1) {
        elm.removeChild(elm.childNodes[0])
      }
    }

    // #4521: if a click event triggers update before the change event is
    // dispatched on a checkbox/radio input, the input's checked state will
    // be reset and fail to trigger another update.
    // The root cause here is that browsers may fire microtasks in between click/change.
    // In Chrome / Firefox, click event fires before change, thus having this problem.
    // In Safari / Edge, the order is opposite.
    // Note: in Edge, if you click too fast, only the click event would fire twice.
    if (key === 'checked' && !isNotInFocusAndDirty(elm, cur)) {
      continue
    }

    if (key === 'value') {
      // store value as _value as well since
      // non-string values will be stringified
      elm._value = cur
      // avoid resetting cursor position when value is the same
      const strCur = isUndef(cur) ? '' : String(cur)
      if (shouldUpdateValue(elm, strCur)) {
        elm.value = strCur
      }
    } else if (key === 'innerHTML' && isSVG(elm.tagName) && isUndef(elm.innerHTML)) {
      // IE doesn't support innerHTML for SVG elements
      svgContainer = svgContainer || document.createElement('div')
      svgContainer.innerHTML = `<svg>${cur}</svg>`
      const svg = svgContainer.firstChild
      while (elm.firstChild) {
        elm.removeChild(elm.firstChild)
      }
      while (svg.firstChild) {
        elm.appendChild(svg.firstChild)
      }
    } else {
      elm[key] = cur
    }
  }
}

// check platforms/web/util/attrs.js acceptValue
type acceptValueElm = HTMLInputElement | HTMLSelectElement | HTMLOptionElement;

function shouldUpdateValue (elm: acceptValueElm, checkVal: string): boolean {
  return (!elm.composing && (
    elm.tagName === 'OPTION' ||
    isNotInFocusAndDirty(elm, checkVal) ||
    isDirtyWithModifiers(elm, checkVal)
  ))
}

function isNotInFocusAndDirty (elm: acceptValueElm, checkVal: string): boolean {
  // return true when textbox (.number and .trim) loses focus and its value is
  // not equal to the updated value
  let notInFocus = true
  // #6157
  // work around IE bug when accessing document.activeElement in an iframe
  try { notInFocus = document.activeElement !== elm } catch (e) {}
  return notInFocus && elm.value !== checkVal
}

function isDirtyWithModifiers (elm: any, newVal: string): boolean {
  const value = elm.value
  const modifiers = elm._vModifiers // injected by v-model runtime
  if (isDef(modifiers)) {
    if (modifiers.number) {
      return toNumber(value) !== toNumber(newVal)
    }
    if (modifiers.trim) {
      return value.trim() !== newVal.trim()
    }
  }
  return value !== newVal
}

export default {
  create: updateDOMProps,
  update: updateDOMProps
}
<|endoftext|>


<commit_before>angular
  .module('app')
  .directive('projectQuickView', function() {
    return {
      restrict: 'E',
      replace: false,
      templateUrl: 'app/templates/partials/projectQuickView.html',
      link: function(scope, element, attrs) {
        scope.completed = attrs.completed;
        scope.isContentFromOldSite = function(item) {
          return item.end_date == "2012-10-20T04:00:00.000Z";
        };

        scope.completedStamp = function(item) {
          return scope.completed && !scope.isContentFromOldSite(item);
        };

      }
    };
  });
<commit_msg>Add hasDate method<commit_after>angular
  .module('app')
  .directive('projectQuickView', function() {
    return {
      restrict: 'E',
      replace: false,
      templateUrl: 'app/templates/partials/projectQuickView.html',
      link: function(scope, element, attrs) {
        scope.completed = attrs.completed;

        scope.hasDate = function() {
          return scope.item.end_date !== null;
        };

        scope.isContentFromOldSite = function(item) {
          return scope.item.end_date == "2012-10-20T04:00:00.000Z";
        };

        scope.completedStamp = function(item) {
          return scope.completed && !scope.isContentFromOldSite(item);
        };

      }
    };
  });
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { Grid, Row, Col, Well, Label } from 'react-bootstrap/lib';
import {connect} from 'react-redux';
import config from '../../config';
import Helmet from 'react-helmet';
import superagent from 'superagent';

import { getBlogEntries } from '../../redux/actions/getBlogEntriesActions';

@connect((store) => {
  return {
    getBlogEntriesState: store.getBlogEntries.articleList,
  };
})

export default class Home extends Component {

  componentDidMount() {
    superagent
    .post('/community')
    .send({ loadStatus: 2 })
    .set('Accept', 'application/json')
    .end((error, res) => {
      if (res.body.status === 1) {
        this.props.dispatch(getBlogEntries(res.body.blogArticles));
      }
    });
  }

  static propTypes = {
    userLoggedIn: PropTypes.string
  }

  function loadArticle(id) {
    console.log(id);
  }

  /*loadArticle = (id) => {
    console.log(id);
    //superagent request with /community/article-id-abc123545
    // you get back here markupdata and all other data from specific article in -> res.

    /* handle this in server.js - in saveto Mongo action:
    function convertToSlug(Text)
    {
        return Text
            .toLowerCase()
            .replace(/[^\w ]+/g,'')
            .replace(/ +/g,'-')
            ;
    }
    save it to aditional field like: urlFriendlyTitel
    also new field: articleId

    then within res. you get urlFriendlyTitel -> add it here to dispatch.push:

    this.props.dispatch.push -> /community/transformed-blog-titel from server.js

    */
  //}

  render() {
    const styles = require('./Home.scss');
    const stylesMyProfile = require('../MyProfile/MyProfile.scss');
    const { getBlogEntriesState } = this.props;
    // require the logo image both from client and server
    const logoImage = require('./logo.png');

    let blogContentDef = '';
    getBlogEntriesState.articles.forEach(function(entry){
      blogContentDef += '
' +
                        '

' +
                        '
'+ entry.userNickname + '
' +
                        '
'+ entry.titel + '
' +
                        '
'+ entry.category + '
' +
                        '
'+ entry.technologies + '
' +
                        '
'+ entry.timeFormatted + '

';
      });

    return (

        <Helmet title="Home"/>

{config.app.title}

{config.app.description}

{config.app.subdescription}

React Activity Feed

    );
  }
}
<commit_msg>asdasd555<commit_after>import React, { Component, PropTypes } from 'react';
import { Grid, Row, Col, Well, Label } from 'react-bootstrap/lib';
import {connect} from 'react-redux';
import config from '../../config';
import Helmet from 'react-helmet';
import superagent from 'superagent';

import { getBlogEntries } from '../../redux/actions/getBlogEntriesActions';

@connect((store) => {
  return {
    getBlogEntriesState: store.getBlogEntries.articleList,
  };
})

export default class Home extends Component {

  componentDidMount() {
    superagent
    .post('/community')
    .send({ loadStatus: 2 })
    .set('Accept', 'application/json')
    .end((error, res) => {
      if (res.body.status === 1) {
        this.props.dispatch(getBlogEntries(res.body.blogArticles));
      }
    });
  }

  static propTypes = {
    userLoggedIn: PropTypes.string
  }

  loadArticle(id) {
    console.log(id);
  }

  /*loadArticle = (id) => {
    console.log(id);
    //superagent request with /community/article-id-abc123545
    // you get back here markupdata and all other data from specific article in -> res.

    /* handle this in server.js - in saveto Mongo action:
    function convertToSlug(Text)
    {
        return Text
            .toLowerCase()
            .replace(/[^\w ]+/g,'')
            .replace(/ +/g,'-')
            ;
    }
    save it to aditional field like: urlFriendlyTitel
    also new field: articleId

    then within res. you get urlFriendlyTitel -> add it here to dispatch.push:

    this.props.dispatch.push -> /community/transformed-blog-titel from server.js

    */
  //}

  render() {
    const styles = require('./Home.scss');
    const stylesMyProfile = require('../MyProfile/MyProfile.scss');
    const { getBlogEntriesState } = this.props;
    // require the logo image both from client and server
    const logoImage = require('./logo.png');

    let blogContentDef = '';
    getBlogEntriesState.articles.forEach(function(entry){
      blogContentDef += '
' +
                        '

' +
                        '
'+ entry.userNickname + '
' +
                        '
'+ entry.titel + '
' +
                        '
'+ entry.category + '
' +
                        '
'+ entry.technologies + '
' +
                        '
'+ entry.timeFormatted + '

';
      });

    return (

        <Helmet title="Home"/>

{config.app.title}

{config.app.description}

{config.app.subdescription}

React Activity Feed

    );
  }
}
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Project = mongoose.model('Project');
var logger = require('../utils/logger.js');

var Utils = require('../utils/util.js');

/**
* @api {get} /api/projects get all projects.
* @apiVersion 0.0.1
* @apiName GetProjects
* @apiGroup Projects
* @apiPermission none
*
* @apiDescription Get all projects.
*
* @apiSuccess {Object[]} pl Array of projects.
* @apiSuccess {Object} pl.p An Object that correspond to a project.
* @apiSuccess {String} pl.p._id Project's id.
* @apiSuccess {String} pl.p.name Project name.
* @apiSuccess {String} pl.p.url Github url to the project.
* @apiSuccess {String} pl.p.iconPath Path of a png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.description Html string that represents the project description.
* @apiSuccess {Boolean} pl.p.visibile Boolean used to hide/show a project.
* @apiSuccess {Object} pl.p.projectHomeView Object that contains information used to show a project with carousel and thumbs.
* @apiSuccess {String} pl.p.projectHomeView._id ProjectHomeView's id
* @apiSuccess {String} pl.p.projectHomeView.carouselImagePath Path of the bigger png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.projectHomeView.carouselText CarouselImage description.
* @apiSuccess {String} pl.p.projectHomeView.thumbImagePath Path of the smaller png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.projectHomeView.thumbText ThumbImage description.
* @apiSuccess {String} pl.p.projectHomeView.bigThumbImagePath Path of the mid-size png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.projectHomeView.bigThumbText BigThumbImage description.
* @apiSuccess {Date} pl.p.lastUpdate Date of the last update.
* @apiSuccess {String[]} pl.p.filePaths Deprecated
* @apiSuccess {Object[]} pl.p.gallery Array of gallery objects, with image, thumb and description.
* @apiSuccess {String} pl.p.gallery.thumb Path of the thumb png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.gallery.img Path of the image png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.gallery.description Image description.
* @apiSuccess {String[]} pl.p.futureExtensions Array of Html strings that represents the project's future extensions.
* @apiSuccess {String[]} pl.p.features Array of Html strings that represents the project's features.
* @apiSuccess {String[]} pl.p.releases Array of Html strings that represents the project's releases.
* @apiSuccess {String[]} pl.p.changelog Array of Html strings that represents the project changelog, version by version.
* @apiSuccess {String[]} pl.p.tags Array of Html strings that represents the project's tags.
* @apiSuccess {Object[]} pl.p.authors Alrray of author objects, with personal informations.
* @apiSuccess {String} pl.p.authors.name Author's name.
* @apiSuccess {String} pl.p.authors.surname Author's surname.
* @apiSuccess {String} pl.p.authors.url Author's website/github profile.
* @apiSuccess {Boolean} pl.p.authors.urlAvailable Boolean to used to show/hide author's url.
*
* @apiError ProjectsNotFound 404 Text message 'Project list not found'.
*
* @apiErrorExample {json} Error-Response:
*   HTTP/1.1 404 NOT FOUND
*   {
*     "message": "Project list not found"
*   }
*/
module.exports.projectsList = function(req, res) {
  console.log('projectsList');
  Project.find({}, (err, results) => {
    if (!results || err) {
      console.log('projectsList error:', err);
      Utils.sendJSONres(res, 404, "Project list not found");
      return;
    }
    if (results.length === 0) {
      console.log('projectsList is empty');
      res.status(204).end(); // no content (attention, don't use res.json() in this case)
    } else {
      Utils.sendJSONres(res, 200, results);
      return;
    }
  });
};

/**
* @api {get} /api/projecthome get all home projects.
* @apiVersion 0.0.1
* @apiName GetHomeProjects
* @apiGroup Projects
* @apiPermission none
*
* @apiDescription Get all home projects.
*
* @apiSuccess {Object[]} pl Array of projects.
* @apiSuccess {Object} pl.p An Object that correspond to a project.
* @apiSuccess {String} pl.p._id Project's id.
* @apiSuccess {String} pl.p.name Project name.
* @apiSuccess {String} pl.p.url Github url to the project.
* @apiSuccess {String} pl.p.iconPath Path of a png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.description Html string that represents the project description.
* @apiSuccess {Boolean} pl.p.visibile Boolean used to hide/show a project.
* @apiSuccess {Object} pl.p.projectHomeView Object that contains information used to show a project with carousel and thumbs.
* @apiSuccess {String} pl.p.projectHomeView._id ProjectHomeView's id
* @apiSuccess {String} pl.p.projectHomeView.carouselImagePath Path of the bigger png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.projectHomeView.carouselText CarouselImage description.
* @apiSuccess {String} pl.p.projectHomeView.thumbImagePath Path of the smaller png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.projectHomeView.thumbText ThumbImage description.
* @apiSuccess {String} pl.p.projectHomeView.bigThumbImagePath Path of the mid-size png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.projectHomeView.bigThumbText BigThumbImage description.
* @apiSuccess {Date} pl.p.lastUpdate Date of the last update.
* @apiSuccess {String[]} pl.p.filePaths Deprecated
* @apiSuccess {Object[]} pl.p.gallery Array of gallery objects, with image, thumb and description.
* @apiSuccess {String} pl.p.gallery.thumb Path of the thumb png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.gallery.img Path of the image png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.gallery.description Image description.
* @apiSuccess {String[]} pl.p.futureExtensions Array of Html strings that represents the project's future extensions.
* @apiSuccess {String[]} pl.p.features Array of Html strings that represents the project's features.
* @apiSuccess {String[]} pl.p.releases Array of Html strings that represents the project's releases.
* @apiSuccess {String[]} pl.p.changelog Array of Html strings that represents the project changelog, version by version.
* @apiSuccess {String[]} pl.p.tags Array of Html strings that represents the project's tags.
* @apiSuccess {Object[]} pl.p.authors Alrray of author objects, with personal informations.
* @apiSuccess {String} pl.p.authors.name Author's name.
* @apiSuccess {String} pl.p.authors.surname Author's surname.
* @apiSuccess {String} pl.p.authors.url Author's website/github profile.
* @apiSuccess {Boolean} pl.p.authors.urlAvailable Boolean to used to show/hide author's url.
*
* @apiError ProjectsNotFound 404 Text message 'Project list not found'.
*
* @apiErrorExample {json} Error-Response:
*   HTTP/1.1 404 NOT FOUND
*   {
*     "message": "Project list homepage not found"
*   }
*/
module.exports.projectsListHomepage = function(req, res) {
  console.log('projectsListHomepage');
  Project
    .find({"projectHomeView.carouselImagePath": { $exists: true } })
    .lean().exec((err, results) => {
      if (!results || err) {
        console.log('projectsListHomepage error:', err);
        Utils.sendJSONres(res, 404, "Project list homepage not found");
        return;
      }
      if (results.length === 0) {
        console.log('projectsListHomepage is empty');
        res.status(204).end(); // no content (attention, don't use res.json() in this case)
      } else {
        Utils.sendJSONres(res, 200, results);
        return;
      }
    });
};

/**
* @api {get} /api/projects/:projectid get a project with the requested projectid.
* @apiVersion 0.0.1
* @apiName GetProjectById
* @apiGroup Projects
* @apiPermission none
*
* @apiDescription Get a project by its projectid.
*
* @apiSuccess {Object} p An Object that correspond to a project.
* @apiSuccess {String} p._id Project's id.
* @apiSuccess {String} p.name Project name.
* @apiSuccess {String} p.url Github url to the project.
* @apiSuccess {String} p.iconPath Path of a png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} p.description Html string that represents the project description.
* @apiSuccess {Boolean} p.visibile Boolean used to hide/show a project.
* @apiSuccess {Object} p.projectHomeView Object that contains information used to show a project with carousel and thumbs.
* @apiSuccess {String} p.projectHomeView._id ProjectHomeView's id
* @apiSuccess {String} p.projectHomeView.carouselImagePath Path of the bigger png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} p.projectHomeView.carouselText CarouselImage description.
* @apiSuccess {String} p.projectHomeView.thumbImagePath Path of the smaller png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} p.projectHomeView.thumbText ThumbImage description.
* @apiSuccess {String} p.projectHomeView.bigThumbImagePath Path of the mid-size png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} p.projectHomeView.bigThumbText BigThumbImage description.
* @apiSuccess {Date} p.lastUpdate Date of the last update.
* @apiSuccess {String[]} p.filePaths Deprecated
* @apiSuccess {Object[]} p.gallery Array of gallery objects, with image, thumb and description.
* @apiSuccess {String} p.gallery.thumb Path of the thumb png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} p.gallery.img Path of the image png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} p.gallery.description Image description.
* @apiSuccess {String[]} p.futureExtensions Array of Html strings that represents the project's future extensions.
* @apiSuccess {String[]} p.features Array of Html strings that represents the project's features.
* @apiSuccess {String[]} p.releases Array of Html strings that represents the project's releases.
* @apiSuccess {String[]} p.changelog Array of Html strings that represents the project changelog, version by version.
* @apiSuccess {String[]} p.tags Array of Html strings that represents the project's tags.
* @apiSuccess {Object[]} p.authors Alrray of author objects, with personal informations.
* @apiSuccess {String} p.authors.name Author's name.
* @apiSuccess {String} p.authors.surname Author's surname.
* @apiSuccess {String} p.authors.url Author's website/github profile.
* @apiSuccess {Boolean} p.authors.urlAvailable Boolean to used to show/hide author's url.
*
* @apiError NoProjectId 400 Text message 'No projectid in request'.
* @apiError ProjectNotFound 404 Text message 'Project not found'.
*
* @apiErrorExample {json} Error-Response:
*   HTTP/1.1 404 NOT FOUND
*   {
*     "message": "Project not found"
*   }
* @apiErrorExample {json} Error-Response:
*   HTTP/1.1 400 BAD REQUEST
*   {
*     "message": "No projectid in request"
*   }
*/
module.exports.projectsReadOne = function(req, res) {
  console.log('Finding a Project', req.params);
  if (!req.params.projectid) {
    Utils.sendJSONres(res, 400, "No projectid in request");
    return;
  }

  Project
  .findById(req.params.projectid)
  .exec((err, project) => {
    if (!project || err) {
      Utils.sendJSONres(res, 404, "Project not found");
    } else {
      console.log(project);
      Utils.sendJSONres(res, 200, project);
    }
  });
};
<commit_msg>refactoring doc #50<commit_after>var mongoose = require('mongoose');
var Project = mongoose.model('Project');
var logger = require('../utils/logger.js');

var Utils = require('../utils/util.js');

/**
* @api {get} /api/projects get all projects.
* @apiVersion 0.0.1
* @apiName GetProjects
* @apiGroup Projects
* @apiPermission none
*
* @apiDescription Get all projects.
*
* @apiSuccess {Object[]} pl Array of projects.
* @apiSuccess {Object} pl.p An Object that represents a project.
* @apiSuccess {String} pl.p._id Project's id.
* @apiSuccess {String} pl.p.name Project name.
* @apiSuccess {String} pl.p.url Github url to the project.
* @apiSuccess {String} pl.p.iconPath Path of a png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.description Html string that represents the project description.
* @apiSuccess {Boolean} pl.p.visibile Boolean used to hide/show a project.
* @apiSuccess {Object} pl.p.projectHomeView Object that contains information used to show a project with carousel and thumbs.
* @apiSuccess {String} pl.p.projectHomeView._id ProjectHomeView's id
* @apiSuccess {String} pl.p.projectHomeView.carouselImagePath Path of the bigger png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.projectHomeView.carouselText CarouselImage description.
* @apiSuccess {String} pl.p.projectHomeView.thumbImagePath Path of the smaller png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.projectHomeView.thumbText ThumbImage description.
* @apiSuccess {String} pl.p.projectHomeView.bigThumbImagePath Path of the mid-size png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.projectHomeView.bigThumbText BigThumbImage description.
* @apiSuccess {Date} pl.p.lastUpdate Date of the last update.
* @apiSuccess {String[]} pl.p.filePaths Deprecated
* @apiSuccess {Object[]} pl.p.gallery Array of gallery objects, with image, thumb and description.
* @apiSuccess {String} pl.p.gallery.thumb Path of the thumb png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.gallery.img Path of the image png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.gallery.description Image description.
* @apiSuccess {String[]} pl.p.futureExtensions Array of Html strings that represents the project's future extensions.
* @apiSuccess {String[]} pl.p.features Array of Html strings that represents the project's features.
* @apiSuccess {String[]} pl.p.releases Array of Html strings that represents the project's releases.
* @apiSuccess {String[]} pl.p.changelog Array of Html strings that represents the project changelog, version by version.
* @apiSuccess {String[]} pl.p.tags Array of Html strings that represents the project's tags.
* @apiSuccess {Object[]} pl.p.authors Alrray of author objects, with personal informations.
* @apiSuccess {String} pl.p.authors.name Author's name.
* @apiSuccess {String} pl.p.authors.surname Author's surname.
* @apiSuccess {String} pl.p.authors.url Author's website/github profile.
* @apiSuccess {Boolean} pl.p.authors.urlAvailable Boolean to used to show/hide author's url.
*
* @apiError ProjectsNotFound 404 Text message 'Project list not found'.
*
* @apiErrorExample {json} Error-Response:
*   HTTP/1.1 404 NOT FOUND
*   {
*     "message": "Project list not found"
*   }
*/
module.exports.projectsList = function(req, res) {
  console.log('projectsList');
  Project.find({}, (err, results) => {
    if (!results || err) {
      console.log('projectsList error:', err);
      Utils.sendJSONres(res, 404, "Project list not found");
      return;
    }
    if (results.length === 0) {
      console.log('projectsList is empty');
      res.status(204).end(); // no content (attention, don't use res.json() in this case)
    } else {
      Utils.sendJSONres(res, 200, results);
      return;
    }
  });
};

/**
* @api {get} /api/projecthome get all home projects.
* @apiVersion 0.0.1
* @apiName GetHomeProjects
* @apiGroup Projects
* @apiPermission none
*
* @apiDescription Get all home projects.
*
* @apiSuccess {Object[]} pl Array of projects.
* @apiSuccess {Object} pl.p An Object that represents a project.
* @apiSuccess {String} pl.p._id Project's id.
* @apiSuccess {String} pl.p.name Project name.
* @apiSuccess {String} pl.p.url Github url to the project.
* @apiSuccess {String} pl.p.iconPath Path of a png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.description Html string that represents the project description.
* @apiSuccess {Boolean} pl.p.visibile Boolean used to hide/show a project.
* @apiSuccess {Object} pl.p.projectHomeView Object that contains information used to show a project with carousel and thumbs.
* @apiSuccess {String} pl.p.projectHomeView._id ProjectHomeView's id
* @apiSuccess {String} pl.p.projectHomeView.carouselImagePath Path of the bigger png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.projectHomeView.carouselText CarouselImage description.
* @apiSuccess {String} pl.p.projectHomeView.thumbImagePath Path of the smaller png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.projectHomeView.thumbText ThumbImage description.
* @apiSuccess {String} pl.p.projectHomeView.bigThumbImagePath Path of the mid-size png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.projectHomeView.bigThumbText BigThumbImage description.
* @apiSuccess {Date} pl.p.lastUpdate Date of the last update.
* @apiSuccess {String[]} pl.p.filePaths Deprecated
* @apiSuccess {Object[]} pl.p.gallery Array of gallery objects, with image, thumb and description.
* @apiSuccess {String} pl.p.gallery.thumb Path of the thumb png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.gallery.img Path of the image png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} pl.p.gallery.description Image description.
* @apiSuccess {String[]} pl.p.futureExtensions Array of Html strings that represents the project's future extensions.
* @apiSuccess {String[]} pl.p.features Array of Html strings that represents the project's features.
* @apiSuccess {String[]} pl.p.releases Array of Html strings that represents the project's releases.
* @apiSuccess {String[]} pl.p.changelog Array of Html strings that represents the project changelog, version by version.
* @apiSuccess {String[]} pl.p.tags Array of Html strings that represents the project's tags.
* @apiSuccess {Object[]} pl.p.authors Alrray of author objects, with personal informations.
* @apiSuccess {String} pl.p.authors.name Author's name.
* @apiSuccess {String} pl.p.authors.surname Author's surname.
* @apiSuccess {String} pl.p.authors.url Author's website/github profile.
* @apiSuccess {Boolean} pl.p.authors.urlAvailable Boolean to used to show/hide author's url.
*
* @apiError ProjectsNotFound 404 Text message 'Project list not found'.
*
* @apiErrorExample {json} Error-Response:
*   HTTP/1.1 404 NOT FOUND
*   {
*     "message": "Project list homepage not found"
*   }
*/
module.exports.projectsListHomepage = function(req, res) {
  console.log('projectsListHomepage');
  Project
    .find({"projectHomeView.carouselImagePath": { $exists: true } })
    .lean().exec((err, results) => {
      if (!results || err) {
        console.log('projectsListHomepage error:', err);
        Utils.sendJSONres(res, 404, "Project list homepage not found");
        return;
      }
      if (results.length === 0) {
        console.log('projectsListHomepage is empty');
        res.status(204).end(); // no content (attention, don't use res.json() in this case)
      } else {
        Utils.sendJSONres(res, 200, results);
        return;
      }
    });
};

/**
* @api {get} /api/projects/:projectid get a project with the requested projectid.
* @apiVersion 0.0.1
* @apiName GetProjectById
* @apiGroup Projects
* @apiPermission none
*
* @apiDescription Get a project by its projectid.
*
* @apiSuccess {Object} p An Object that represents a project.
* @apiSuccess {String} p._id Project's id.
* @apiSuccess {String} p.name Project name.
* @apiSuccess {String} p.url Github url to the project.
* @apiSuccess {String} p.iconPath Path of a png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} p.description Html string that represents the project description.
* @apiSuccess {Boolean} p.visibile Boolean used to hide/show a project.
* @apiSuccess {Object} p.projectHomeView Object that contains information used to show a project with carousel and thumbs.
* @apiSuccess {String} p.projectHomeView._id ProjectHomeView's id
* @apiSuccess {String} p.projectHomeView.carouselImagePath Path of the bigger png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} p.projectHomeView.carouselText CarouselImage description.
* @apiSuccess {String} p.projectHomeView.thumbImagePath Path of the smaller png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} p.projectHomeView.thumbText ThumbImage description.
* @apiSuccess {String} p.projectHomeView.bigThumbImagePath Path of the mid-size png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} p.projectHomeView.bigThumbText BigThumbImage description.
* @apiSuccess {Date} p.lastUpdate Date of the last update.
* @apiSuccess {String[]} p.filePaths Deprecated
* @apiSuccess {Object[]} p.gallery Array of gallery objects, with image, thumb and description.
* @apiSuccess {String} p.gallery.thumb Path of the thumb png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} p.gallery.img Path of the image png file. It's a file path inside 'assets' folder.
* @apiSuccess {String} p.gallery.description Image description.
* @apiSuccess {String[]} p.futureExtensions Array of Html strings that represents the project's future extensions.
* @apiSuccess {String[]} p.features Array of Html strings that represents the project's features.
* @apiSuccess {String[]} p.releases Array of Html strings that represents the project's releases.
* @apiSuccess {String[]} p.changelog Array of Html strings that represents the project changelog, version by version.
* @apiSuccess {String[]} p.tags Array of Html strings that represents the project's tags.
* @apiSuccess {Object[]} p.authors Alrray of author objects, with personal informations.
* @apiSuccess {String} p.authors.name Author's name.
* @apiSuccess {String} p.authors.surname Author's surname.
* @apiSuccess {String} p.authors.url Author's website/github profile.
* @apiSuccess {Boolean} p.authors.urlAvailable Boolean to used to show/hide author's url.
*
* @apiError NoProjectId 400 Text message 'No projectid in request'.
* @apiError ProjectNotFound 404 Text message 'Project not found'.
*
* @apiErrorExample {json} Error-Response:
*   HTTP/1.1 404 NOT FOUND
*   {
*     "message": "Project not found"
*   }
* @apiErrorExample {json} Error-Response:
*   HTTP/1.1 400 BAD REQUEST
*   {
*     "message": "No projectid in request"
*   }
*/
module.exports.projectsReadOne = function(req, res) {
  console.log('Finding a Project', req.params);
  if (!req.params.projectid) {
    Utils.sendJSONres(res, 400, "No projectid in request");
    return;
  }

  Project
  .findById(req.params.projectid)
  .exec((err, project) => {
    if (!project || err) {
      Utils.sendJSONres(res, 404, "Project not found");
    } else {
      console.log(project);
      Utils.sendJSONres(res, 200, project);
    }
  });
};
<|endoftext|>


<commit_before>"use strict";

// Thanks to:
// http://fightingforalostcause.net/misc/2006/compare-email-regex.php
// http://thedailywtf.com/Articles/Validating_Email_Addresses.aspx
// http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/201378#201378
function validate(email)
{
	var tester = /^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z0-9](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$/;

	var valid = tester.test(email);
	if(!valid)
		return false;

	// Further checking of some things regex can't handle
	var parts = email.split("@");
	if(parts[0].length>64)
		return false;

	if(email.length>254)
		return false;

	var domainParts = parts[1].split(".");
	if(domainParts.some(function(part) { return part.length>63; }))
		return false;

	return true;
}

exports.validate = validate;
<commit_msg>Extracting regex from function<commit_after>"use strict";

var tester = /^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z0-9](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$/;
// Thanks to:
// http://fightingforalostcause.net/misc/2006/compare-email-regex.php
// http://thedailywtf.com/Articles/Validating_Email_Addresses.aspx
// http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/201378#201378
function validate(email)
{
	var valid = tester.test(email);
	if(!valid)
		return false;

	// Further checking of some things regex can't handle
	var parts = email.split("@");
	if(parts[0].length>64)
		return false;

	if(email.length>254)
		return false;

	var domainParts = parts[1].split(".");
	if(domainParts.some(function(part) { return part.length>63; }))
		return false;

	return true;
}

exports.validate = validate;
<|endoftext|>


<commit_before>var md5 = require("crypto-js/md5");

module.exports = {
    parseServerChallenge: function(header, challenge) {
        var splitting = header.split(', ');
        challenge = challenge || {};

        if(!splitting.length) {
            return challenge;
        }

        for(var i=0; i<splitting.length; i++) {
            var values = /([a-zA-Z]+)=\"?([a-zA-Z0-9.@\/\s]+)\"?/.exec(splitting[i]);
            challenge[values[1]] = values[2];
        }

        return challenge;
    },

    generateRequestHeader: function(_nc, challenge, username, password, method, uri) {

        var nc = ("00000000"+_nc).slice(-8);

        /* Calculate cnonce */
        /* Math.randon().toString(36) -> "0.9g7hgvo99dj".slice(2) -> "9g7hgvo99dj" */
        var cnonce = ("00000000"+Math.random().toString(36).slice(2)).slice(-8);

        /* Calculate response MD5 */
        var ha1 = md5([username, challenge.realm, password].join(":"));
        var ha2 = md5([method, uri].join(":"));
        var response = md5([ha1, challenge.nonce, nc, cnonce, challenge.qop, ha2].join(":"));

        return "Digest " +
            "username=\""  + username            + "\", " +
            "realm=\""     + challenge.realm     + "\", " +
            "nonce=\""     + challenge.nonce     + "\", " +
            "uri=\""       + uri                 + "\", " +
            "algorithm=\"" + challenge.algorithm + "\", " +
            "response=\""  + response            + "\", " +
            "opaque=\""    + challenge.opaque    + "\", " +
            "qop=\""       + challenge.qop       + "\", " +
            "nc=\""        + nc                  + "\", " +
            "cnonce=\""    + cnonce              + "\"";
    }
};
<commit_msg>Remove empty authorization header fields.<commit_after>var md5 = require("crypto-js/md5");

var buildField = function(name, value) {
    return value ? name+"=\""+value+"\", " : "";
};

module.exports = {
    parseServerChallenge: function(header, challenge) {
        var splitting = header.split(', ');
        challenge = challenge || {};

        if(!splitting.length) {
            return challenge;
        }

        for(var i=0; i<splitting.length; i++) {
            var values = /([a-zA-Z]+)=\"?([a-zA-Z0-9.@\/\s]+)\"?/.exec(splitting[i]);
            challenge[values[1]] = values[2];
        }

        return challenge;
    },

    generateRequestHeader: function(_nc, challenge, username, password, method, uri) {

        var nc = ("00000000"+_nc).slice(-8);

        /* Calculate cnonce */
        /* Math.randon().toString(36) -> "0.9g7hgvo99dj".slice(2) -> "9g7hgvo99dj" */
        var cnonce = ("00000000"+Math.random().toString(36).slice(2)).slice(-8);

        /* Calculate response MD5 */
        var ha1 = md5([username, challenge.realm, password].join(":"));
        var ha2 = md5([method, uri].join(":"));
        var response = md5([ha1, challenge.nonce, nc, cnonce, challenge.qop, ha2].join(":"));

        return ("Digest " +
            buildField( "username" , username            ) +
            buildField( "realm"    , challenge.realm     ) +
            buildField( "nonce"    , challenge.nonce     ) +
            buildField( "uri"      , uri                 ) +
            buildField( "algorithm", challenge.algorithm ) +
            buildField( "response" , response            ) +
            buildField( "opaque"   , challenge.opaque    ) +
            buildField( "qop"      , challenge.qop       ) +
            buildField( "nc"       , nc                  ) +
            buildField( "cnonce"   , cnonce              )).slice(0, -2);
    }
};
<|endoftext|>


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

    var Capestatus;

    Capestatus = function Capestatus(cockpit) {
        console.log("Loading Capestatus plugin in the browser.");

        // Instance variables
        this.cockpit = cockpit;
	this.lastPing = null;

        // Add required UI elements
        $("#footercontent").append(
	  '

Connection

 \

Temperature

 \

Depth:

 \

time

 \

 \

 \

 \
           ');

	$("#servoTilt").append(''); //attr style

	//$("#lights").append('

'); //attr class
    $('#navtoolbar').append('

');
        // Register the various event handlers
        this.listen();
	var capes = this;
        setInterval(function(){capes.updateConnectionStatus();}, 1000);

	setInterval(function () {
	    $("#localtime").text((new Date()).toLocaleTimeString(), 1000);
	});
    };

    //This pattern will hook events in the cockpit and pull them all back
    //so that the reference to this instance is available for further processing
    Capestatus.prototype.listen = function listen() {
        var capes = this;
	this.cockpit.socket.on('status', function(data) {
            capes.UpdateStatusIndicators(data);
        });
    };

    Capestatus.prototype.batteryLevel = function batteryLevel(voltage){
        if(voltage < 9)
            return "level1";
        if(voltage < 10)
            return "level2";
        if(voltage < 10.5)
            return "level3";
        if(voltage < 11.5)
            return "level4";
        return "level5";
    };

    Capestatus.prototype.UpdateStatusIndicators = function UpdateStatusIndicators(data){
	var self = this;
	if ('time' in data) {
	    $("#formattedRunTime").text(msToTime(data.time));
	};
	if ('vout' in data) {
	    $("#currentVoltage").text(data.vout.toFixed(1) + 'v');
	    $("#batteryIndicator").attr('class',self.batteryLevel(data.vout));
	};
	if ('iout' in data) $("#currentCurrent").text(data.iout.toFixed(3) + 'A');
	if ('servo' in data) {
	    var angle = (90/500)*data.servo+90//*-45;
	    $("#servoTiltImage").attr("style", "-webkit-transform: rotate("+angle+"deg); -moz-transform: rotate("+angle+"deg);transform: rotate("+angle+"deg)");
	};
	if ('cpuUsage' in data) $("#currentCpuUsage").text((data.cpuUsage*100).toFixed(0) + '%');
	if ('LIGP' in data) $("#brightnessIndicator").attr('class','level'+Math.ceil(data.LIGP*10));

	this.lastPing = new Date();
    };

    Capestatus.prototype.updateConnectionStatus = function(){
        var now = new Date();
        var delay = now - this.lastPing;
        if(delay>3000)
            $("#connectionHealth").attr("class","false");
        else
            $("#connectionHealth").attr("class","true");
    };

    window.Cockpit.plugins.push(Capestatus);

}(window, jQuery));
<commit_msg>defaulted light indicator to zero<commit_after>(function (window, $, undefined) {
    'use strict';

    var Capestatus;

    Capestatus = function Capestatus(cockpit) {
        console.log("Loading Capestatus plugin in the browser.");

        // Instance variables
        this.cockpit = cockpit;
	this.lastPing = null;

        // Add required UI elements
        $("#footercontent").append(
	  '

Connection

 \

Temperature

 \

Depth:

 \

time

 \

 \

 \

 \
           ');

	$("#servoTilt").append(''); //attr style

	//$("#lights").append('

'); //attr class
    $('#navtoolbar').append('

');
        // Register the various event handlers
        this.listen();
	var capes = this;
        setInterval(function(){capes.updateConnectionStatus();}, 1000);

	setInterval(function () {
	    $("#localtime").text((new Date()).toLocaleTimeString(), 1000);
	});
    };

    //This pattern will hook events in the cockpit and pull them all back
    //so that the reference to this instance is available for further processing
    Capestatus.prototype.listen = function listen() {
        var capes = this;
	this.cockpit.socket.on('status', function(data) {
            capes.UpdateStatusIndicators(data);
        });
    };

    Capestatus.prototype.batteryLevel = function batteryLevel(voltage){
        if(voltage < 9)
            return "level1";
        if(voltage < 10)
            return "level2";
        if(voltage < 10.5)
            return "level3";
        if(voltage < 11.5)
            return "level4";
        return "level5";
    };

    Capestatus.prototype.UpdateStatusIndicators = function UpdateStatusIndicators(data){
	var self = this;
	if ('time' in data) {
	    $("#formattedRunTime").text(msToTime(data.time));
	};
	if ('vout' in data) {
	    $("#currentVoltage").text(data.vout.toFixed(1) + 'v');
	    $("#batteryIndicator").attr('class',self.batteryLevel(data.vout));
	};
	if ('iout' in data) $("#currentCurrent").text(data.iout.toFixed(3) + 'A');
	if ('servo' in data) {
	    var angle = (90/500)*data.servo+90//*-45;
	    $("#servoTiltImage").attr("style", "-webkit-transform: rotate("+angle+"deg); -moz-transform: rotate("+angle+"deg);transform: rotate("+angle+"deg)");
	};
	if ('cpuUsage' in data) $("#currentCpuUsage").text((data.cpuUsage*100).toFixed(0) + '%');
	if ('LIGP' in data) $("#brightnessIndicator").attr('class','level'+Math.ceil(data.LIGP*10));

	this.lastPing = new Date();
    };

    Capestatus.prototype.updateConnectionStatus = function(){
        var now = new Date();
        var delay = now - this.lastPing;
        if(delay>3000)
            $("#connectionHealth").attr("class","false");
        else
            $("#connectionHealth").attr("class","true");
    };

    window.Cockpit.plugins.push(Capestatus);

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


<commit_before>statusTimerID = null;
timeTimerID = null;
revtime = false;
g_info = null;
TIME_DELAY = 200;
LIST_FIELDS = ['title', 'artist', 'tracknr', 'album'];
PLIST_HEIGHT = "300px";
slider_visible = "plist";
slider_open = true;

function update_list() {
    $.getJSON("cli/list", function(list) {
        $('#listable').children().remove();
        for (i in list) {
            row = document.createElement("tr");
            for (j in LIST_FIELDS) {
                field = document.createElement("td");
                field.appendChild(document.createTextNode(list[i][LIST_FIELDS[j]]));
                row.appendChild(field);
            }
            $('#listable').append(row);
        }
    });
}

function seek(e) {
    var pos = e.pageX - $("#timebar").offset().left;
    pos = pos / document.getElementById("timebar").offsetWidth;
    $.get("cli/seek?time=" + Math.round(pos*g_info.duration))
    update_status();
}

function asctime(t) {
    var tt = Math.round(t/1000);
    var s = tt % 60;
    var m = (tt-s)/60;
    s = Math.abs(s);
    return m+":"+(s>=10 ? "" : "0")+s;
}

function toggle_slider(content) {
    if (content == 'plist' && slider_visible != 'plist') update_list();
    if (content != slider_visible) {
        $("#"+slider_visible).fadeOut("slow");
        slider_visible = content;
        $("#"+content).fadeIn("slow");
    } else {
        $("#slider").animate({"top": (slider_open?"-=":"+=")+PLIST_HEIGHT}, "slow");
        slider_open = !slider_open;
    }
}

function fliptime() {
    revtime = !revtime;
}

function update_status() {
    $.getJSON("cli/status",
        function(info) {
            g_info = info;
            $("#banner").text(info.title + ' - ' + info.artist);
            $("#bitrate").html(info.channels + " channels   " + Math.round(info.bitrate/1000) + "kbps");
        }
    );
}

function update_time() {
    if (g_info) {
        g_info.playtime = Math.max(Math.min(g_info.playtime+TIME_DELAY, g_info.duration), 0);
        $("#innertimebar").width((g_info.playtime/g_info.duration*100) + "%");
        $("#time").html((revtime ? asctime(g_info.playtime-g_info.duration): asctime(g_info.playtime)) + " / " + asctime(g_info.duration) )
    }
}

function run_status() {
    update_status();
    statusTimerID = self.setTimeout("run_status()", 5000);
}

function pls_clear() {
    $.post('cli/clear');
    update_list();
}

function run_time() {
    update_time();
    timeTimerID = self.setTimeout("run_time()", TIME_DELAY);
}

function initialize_timers() {
    run_status();
    run_time();
}

function filter_mlib(add) {
    $.getJSON("cli/mlib?q="+this.querytxt.value+"&f="+LIST_FIELDS.join('+')+(!add?'':'&add=True'),
        function(result) {
            $('#filtered_mlib').children().remove();
            for (i in result) {
                row = document.createElement("tr");
                for (j in LIST_FIELDS) {
                    field = document.createElement("td");
                    field.appendChild(document.createTextNode(result[i][LIST_FIELDS[j]]));
                    row.appendChild(field);
                }
                $('#filtered_mlib').append(row);
            }
        }
    );
    return false;
}

$(document).ready(function() {
        initialize_timers();
        $("#timebar").click(seek);
        update_list();
        $("#main").draggable();
        $("#mlibForm").submit(filter_mlib);
        $("#mlib").toggle();
});

<commit_msg>We don't need the player to be draggable<commit_after>statusTimerID = null;
timeTimerID = null;
revtime = false;
g_info = null;
TIME_DELAY = 200;
LIST_FIELDS = ['title', 'artist', 'tracknr', 'album'];
PLIST_HEIGHT = "300px";
slider_visible = "plist";
slider_open = true;

function update_list() {
    $.getJSON("cli/list", function(list) {
        $('#listable').children().remove();
        for (i in list) {
            row = document.createElement("tr");
            for (j in LIST_FIELDS) {
                field = document.createElement("td");
                field.appendChild(document.createTextNode(list[i][LIST_FIELDS[j]]));
                row.appendChild(field);
            }
            $('#listable').append(row);
        }
    });
}

function seek(e) {
    var pos = e.pageX - $("#timebar").offset().left;
    pos = pos / document.getElementById("timebar").offsetWidth;
    $.get("cli/seek?time=" + Math.round(pos*g_info.duration))
    update_status();
}

function asctime(t) {
    var tt = Math.round(t/1000);
    var s = tt % 60;
    var m = (tt-s)/60;
    s = Math.abs(s);
    return m+":"+(s>=10 ? "" : "0")+s;
}

function toggle_slider(content) {
    if (content == 'plist' && slider_visible != 'plist') update_list();
    if (content != slider_visible) {
        $("#"+slider_visible).fadeOut("slow");
        slider_visible = content;
        $("#"+content).fadeIn("slow");
    } else {
        $("#slider").animate({"top": (slider_open?"-=":"+=")+PLIST_HEIGHT}, "slow");
        slider_open = !slider_open;
    }
}

function fliptime() {
    revtime = !revtime;
}

function update_status() {
    $.getJSON("cli/status",
        function(info) {
            g_info = info;
            $("#banner").text(info.title + ' - ' + info.artist);
            $("#bitrate").html(info.channels + " channels   " + Math.round(info.bitrate/1000) + "kbps");
        }
    );
}

function update_time() {
    if (g_info) {
        g_info.playtime = Math.max(Math.min(g_info.playtime+TIME_DELAY, g_info.duration), 0);
        $("#innertimebar").width((g_info.playtime/g_info.duration*100) + "%");
        $("#time").html((revtime ? asctime(g_info.playtime-g_info.duration): asctime(g_info.playtime)) + " / " + asctime(g_info.duration) )
    }
}

function run_status() {
    update_status();
    statusTimerID = self.setTimeout("run_status()", 5000);
}

function pls_clear() {
    $.post('cli/clear');
    update_list();
}

function run_time() {
    update_time();
    timeTimerID = self.setTimeout("run_time()", TIME_DELAY);
}

function initialize_timers() {
    run_status();
    run_time();
}

function filter_mlib(add) {
    $.getJSON("cli/mlib?q="+this.querytxt.value+"&f="+LIST_FIELDS.join('+')+(!add?'':'&add=True'),
        function(result) {
            $('#filtered_mlib').children().remove();
            for (i in result) {
                row = document.createElement("tr");
                for (j in LIST_FIELDS) {
                    field = document.createElement("td");
                    field.appendChild(document.createTextNode(result[i][LIST_FIELDS[j]]));
                    row.appendChild(field);
                }
                $('#filtered_mlib').append(row);
            }
        }
    );
    return false;
}

$(document).ready(function() {
        initialize_timers();
        $("#timebar").click(seek);
        update_list();
        // $("#main").draggable();
        $("#mlibForm").submit(filter_mlib);
        $("#mlib").toggle();
});

<|endoftext|>


<commit_before>import {
  isFn
} from 'uni-shared'

import {
  invokeApi,
  wrapperReturnValue
} from './interceptor'

const SYNC_API_RE =
  /^\$|Window$|WindowStyle$|sendHostEvent|sendNativeEvent|restoreGlobal|requireGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64|getLocale|setLocale|invokePushCallback|getWindowInfo|getDeviceInfo|getAppBaseInfo/

const CONTEXT_API_RE = /^create|Manager$/

// Context例外情况
const CONTEXT_API_RE_EXC = ['createBLEConnection']

const TASK_APIS = ['request', 'downloadFile', 'uploadFile', 'connectSocket']

// 同步例外情况
const ASYNC_API = ['createBLEConnection']

const CALLBACK_API_RE = /^on|^off/

export function isContextApi (name) {
  return CONTEXT_API_RE.test(name) && CONTEXT_API_RE_EXC.indexOf(name) === -1
}
export function isSyncApi (name) {
  return SYNC_API_RE.test(name) && ASYNC_API.indexOf(name) === -1
}

export function isCallbackApi (name) {
  return CALLBACK_API_RE.test(name) && name !== 'onPush'
}

export function isTaskApi (name) {
  return TASK_APIS.indexOf(name) !== -1
}

function handlePromise (promise) {
  return promise.then(data => {
    return [null, data]
  })
    .catch(err => [err])
}

export function shouldPromise (name) {
  if (
    isContextApi(name) ||
    isSyncApi(name) ||
    isCallbackApi(name)
  ) {
    return false
  }
  return true
}

/* eslint-disable no-extend-native */
if (!Promise.prototype.finally) {
  Promise.prototype.finally = function (callback) {
    const promise = this.constructor
    return this.then(
      value => promise.resolve(callback()).then(() => value),
      reason => promise.resolve(callback()).then(() => {
        throw reason
      })
    )
  }
}

export function promisify (name, api) {
  if (!shouldPromise(name)) {
    return api
  }
  return function promiseApi (options = {}, ...params) {
    if (isFn(options.success) || isFn(options.fail) || isFn(options.complete)) {
      return wrapperReturnValue(name, invokeApi(name, api, options, ...params))
    }
    return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
      invokeApi(name, api, Object.assign({}, options, {
        success: resolve,
        fail: reject
      }), ...params)
    })))
  }
}
<commit_msg>fix(mp-weixin): getSystemSetting，getAppAuthorizeSetting sync<commit_after>import {
  isFn
} from 'uni-shared'

import {
  invokeApi,
  wrapperReturnValue
} from './interceptor'

const SYNC_API_RE =
  /^\$|Window$|WindowStyle$|sendHostEvent|sendNativeEvent|restoreGlobal|requireGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64|getLocale|setLocale|invokePushCallback|getWindowInfo|getDeviceInfo|getAppBaseInfo|getSystemSetting|getAppAuthorizeSetting/

const CONTEXT_API_RE = /^create|Manager$/

// Context例外情况
const CONTEXT_API_RE_EXC = ['createBLEConnection']

const TASK_APIS = ['request', 'downloadFile', 'uploadFile', 'connectSocket']

// 同步例外情况
const ASYNC_API = ['createBLEConnection']

const CALLBACK_API_RE = /^on|^off/

export function isContextApi (name) {
  return CONTEXT_API_RE.test(name) && CONTEXT_API_RE_EXC.indexOf(name) === -1
}
export function isSyncApi (name) {
  return SYNC_API_RE.test(name) && ASYNC_API.indexOf(name) === -1
}

export function isCallbackApi (name) {
  return CALLBACK_API_RE.test(name) && name !== 'onPush'
}

export function isTaskApi (name) {
  return TASK_APIS.indexOf(name) !== -1
}

function handlePromise (promise) {
  return promise.then(data => {
    return [null, data]
  })
    .catch(err => [err])
}

export function shouldPromise (name) {
  if (
    isContextApi(name) ||
    isSyncApi(name) ||
    isCallbackApi(name)
  ) {
    return false
  }
  return true
}

/* eslint-disable no-extend-native */
if (!Promise.prototype.finally) {
  Promise.prototype.finally = function (callback) {
    const promise = this.constructor
    return this.then(
      value => promise.resolve(callback()).then(() => value),
      reason => promise.resolve(callback()).then(() => {
        throw reason
      })
    )
  }
}

export function promisify (name, api) {
  if (!shouldPromise(name)) {
    return api
  }
  return function promiseApi (options = {}, ...params) {
    if (isFn(options.success) || isFn(options.fail) || isFn(options.complete)) {
      return wrapperReturnValue(name, invokeApi(name, api, options, ...params))
    }
    return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
      invokeApi(name, api, Object.assign({}, options, {
        success: resolve,
        fail: reject
      }), ...params)
    })))
  }
}
<|endoftext|>


<commit_before>'use strict';

var sass = require('node-sass');
var isArray = require('lodash').isArray;
var isPlainObject = require('lodash').isPlainObject;
var isString = require('lodash').isString;
var isNumber = require('lodash').isNumber;
var isBoolean = require('lodash').isBoolean;
var rgbHex = require('rgb-hex');
var shortHexColor = require('shorten-css-hex');
var parseColor = require('parse-color');
var types = sass.types;

function isColor ( value ) {
	return typeof parseColor(value).rgba !== 'undefined';
}

function getValueFromSass ( value ) {
	var resolvedValue = null;
	var rgbValue = [];
	var alphaValue;
	if ( value instanceof types.List ) {
		resolvedValue = listToArray(value);
	} else if ( value instanceof types.Map ) {
		resolvedValue = mapToObject(value);
	} else if ( value instanceof types.Color ) {
		rgbValue = [value.getR(), value.getG(), value.getB()];
		alphaValue = value.getA();
		if ( alphaValue === 1 ) {
			resolvedValue = shortHexColor(`#${rgbHex.apply(null, rgbValue)}`);
		} else {
			resolvedValue = `rgba(${rgbValue.join(',')},${alphaValue})`;
		}
	} else if ( !(value instanceof types.Null) ) {
		resolvedValue = value.getValue();
	}
	return resolvedValue;
}

function setValueToSass ( value ) {
	var resolvedValue = types.Null.NULL;
	var resolvedColorValue;
	if ( isArray(value) ) {
		resolvedValue = arrayToList(value);
	} else if ( isPlainObject(value) ) {
		resolvedValue = objectToMap(value);
	} else if ( isColor(value) ) {
		resolvedColorValue = parseColor(value).rgba;
		resolvedValue = new types.Color(resolvedColorValue[0], resolvedColorValue[1], resolvedColorValue[2], resolvedColorValue[3]);
	} else if ( isString(value) ) {
		resolvedValue = new types.String(value);
	} else if ( isNumber(value) ) {
		resolvedValue = new types.Number(value);
	} else if ( isBoolean(value) ) {
		resolvedValue = value ? types.Boolean.TRUE : types.Boolean.FALSE;
	}
	return resolvedValue;
}

function arrayToList ( arr ) {
	var length = arr.length;
	var data = new types.List(length);
	for ( let i = 0; i < length; i++ ) {
		data.setValue(i, setValueToSass(arr[i]));
	}
	return data;
}

function objectToMap ( obj ) {
	var length = Object.keys(obj).length;
	var data = new types.Map(length);
	var i = 0;
	for ( let prop in obj ) {
		if ( obj.hasOwnProperty(prop) ) {
			data.setKey(i, setValueToSass(prop));
			data.setValue(i, setValueToSass(obj[prop]));
			i++;
		}
	}
	return data;
}

function listToArray ( list ) {
	var length = list.getLength();
	var data = [];
	var value;
	for ( let i = 0; i < length; i++ ) {
		value = getValueFromSass(list.getValue(i));
		data.push(value);
	}
	return data;
}

function mapToObject ( map ) {
	var length = map.getLength();
	var data = {};
	var key, value;
	for ( let i = 0; i < length; i++ ) {
		key = map.getKey(i).getValue();
		value = getValueFromSass(map.getValue(i));
		data[key] = value;
	}
	return data;
}

/**
 * @param  {sass.types.*} value
 * @param  {Boolean|sass.types.Boolean} quotes
 *
 * @return {sass.types.String}
 */
function encode ( value, quotes ) {
	var shouldQuote = quotes.getValue();
	var resolvedValue = JSON.stringify(getValueFromSass(value));
	if ( shouldQuote ) {
		resolvedValue = `'${resolvedValue}'`;
	}
	return new types.String(resolvedValue);
}

/**
 * @param  {sass.types.String|sass.types.Number|sass.types.Boolean|sass.types.Null} value
 *
 * @return {sass.types.*}
 */
function decode ( value ) {
	var resolvedValue = {};
	try {
		resolvedValue = JSON.parse(value.getValue());
	} catch ( e ) {
		resolvedValue = null;
	}
	return setValueToSass(resolvedValue);
}

module.exports.encode = encode;
module.exports.decode = decode;

module.exports = {
	'json-encode($value, $quotes: true)': encode,
	'json-decode($value)': decode
};
<commit_msg>Rename internal methods to expresive names<commit_after>'use strict';

var sass = require('node-sass');
var isArray = require('lodash').isArray;
var isPlainObject = require('lodash').isPlainObject;
var isString = require('lodash').isString;
var isNumber = require('lodash').isNumber;
var isBoolean = require('lodash').isBoolean;
var rgbHex = require('rgb-hex');
var shortHexColor = require('shorten-css-hex');
var parseColor = require('parse-color');
var types = sass.types;

function isColor ( value ) {
	return typeof parseColor(value).rgba !== 'undefined';
}

function getJsonValueFromSassValue ( value ) {
	var resolvedValue = null;
	var rgbValue = [];
	var alphaValue;
	if ( value instanceof types.List ) {
		resolvedValue = listToArray(value);
	} else if ( value instanceof types.Map ) {
		resolvedValue = mapToObject(value);
	} else if ( value instanceof types.Color ) {
		rgbValue = [value.getR(), value.getG(), value.getB()];
		alphaValue = value.getA();
		if ( alphaValue === 1 ) {
			resolvedValue = shortHexColor(`#${rgbHex.apply(null, rgbValue)}`);
		} else {
			resolvedValue = `rgba(${rgbValue.join(',')},${alphaValue})`;
		}
	} else if ( !(value instanceof types.Null) ) {
		resolvedValue = value.getValue();
	}
	return resolvedValue;
}

function setJsonValueToSassValue ( value ) {
	var resolvedValue = types.Null.NULL;
	var resolvedColorValue;
	if ( isArray(value) ) {
		resolvedValue = arrayToList(value);
	} else if ( isPlainObject(value) ) {
		resolvedValue = objectToMap(value);
	} else if ( isColor(value) ) {
		resolvedColorValue = parseColor(value).rgba;
		resolvedValue = new types.Color(resolvedColorValue[0], resolvedColorValue[1], resolvedColorValue[2], resolvedColorValue[3]);
	} else if ( isString(value) ) {
		resolvedValue = new types.String(value);
	} else if ( isNumber(value) ) {
		resolvedValue = new types.Number(value);
	} else if ( isBoolean(value) ) {
		resolvedValue = value ? types.Boolean.TRUE : types.Boolean.FALSE;
	}
	return resolvedValue;
}

function arrayToList ( arr ) {
	var length = arr.length;
	var data = new types.List(length);
	for ( let i = 0; i < length; i++ ) {
		data.setValue(i, setJsonValueToSassValue(arr[i]));
	}
	return data;
}

function objectToMap ( obj ) {
	var length = Object.keys(obj).length;
	var data = new types.Map(length);
	var i = 0;
	for ( let prop in obj ) {
		if ( obj.hasOwnProperty(prop) ) {
			data.setKey(i, setJsonValueToSassValue(prop));
			data.setValue(i, setJsonValueToSassValue(obj[prop]));
			i++;
		}
	}
	return data;
}

function listToArray ( list ) {
	var length = list.getLength();
	var data = [];
	var value;
	for ( let i = 0; i < length; i++ ) {
		value = getJsonValueFromSassValue(list.getValue(i));
		data.push(value);
	}
	return data;
}

function mapToObject ( map ) {
	var length = map.getLength();
	var data = {};
	var key, value;
	for ( let i = 0; i < length; i++ ) {
		key = map.getKey(i).getValue();
		value = getJsonValueFromSassValue(map.getValue(i));
		data[key] = value;
	}
	return data;
}

/**
 * @param  {sass.types.*} value
 * @param  {Boolean|sass.types.Boolean} quotes
 *
 * @return {sass.types.String}
 */
function encode ( value, quotes ) {
	var shouldQuote = quotes.getValue();
	var resolvedValue = JSON.stringify(getJsonValueFromSassValue(value));
	if ( shouldQuote ) {
		resolvedValue = `'${resolvedValue}'`;
	}
	return new types.String(resolvedValue);
}

/**
 * @param  {sass.types.String|sass.types.Number|sass.types.Boolean|sass.types.Null} value
 *
 * @return {sass.types.*}
 */
function decode ( value ) {
	var resolvedValue = {};
	try {
		resolvedValue = JSON.parse(value.getValue());
	} catch ( e ) {
		resolvedValue = null;
	}
	return setJsonValueToSassValue(resolvedValue);
}

module.exports.encode = encode;
module.exports.decode = decode;

module.exports = {
	'json-encode($value, $quotes: true)': encode,
	'json-decode($value)': decode
};
<|endoftext|>