<commit_before>/**
 * Copyright 2015, 2016 Brendan Murray
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

// See https://www.maximintegrated.com/en/app-notes/index.mvp/id/187 for
// a description of the 1-wire protocol.

// Dependency - file system access
var fs = require('fs');
var _ = require('underscore');

module.exports = function(RED) {
   "use strict";

   // The main node definition - most things happen in here
   function ds18b20Sensor(config) {

      // Create a RED node
      RED.nodes.createNode(this, config);

      // Store local copies of the node configuration (as defined in the .html)
      var node = this;

      // The root path of the sensors
      var W1PATH = "/sys/bus/w1/devices";

      // The directories location
      var W1DIRS = "/sys/devices/";

      // The devices list file
      var W1DEVICES = "/sys/devices/w1_bus_master1/w1_master_slaves";

      // Save the default device ID
      this.topic = config.topic;

      // If we are to return an array
      this.returnArray = false;

      // Load information from the devices list
      this.loadDeviceData = function() {
         var deviceList = [];
         var fsOptions = { "encoding":"utf8", "flag":"r" };
         var dirs = fs.readdirSync(W1DIRS, "utf8");
         for (var iY=0; iY<dirs.length; iY++) {
            if (dirs[iY].startsWith("w1_bus_master")) {
               var devs = fs.readFileSync(W1DIRS + dirs[iY] +
                             "/w1_master_slaves", fsOptions).split("\n");
               for (var iX=0; iX<devs.length; iX++) {
                  if (devs[iX] !== undefined && devs[iX] !== "") {
                     var fData = fs.readFileSync(W1PATH + "/" + devs[iX] +
                                           "/w1_slave", fsOptions).trim();
                     // Extract the numeric part
                     var tBeg = fData.indexOf("t=")+2;
                     if (tBeg >= 0) {
                        var tEnd = tBeg+1;
                        while (tEnd<fData.length &&
                               fData[tEnd]>='0' && fData[tEnd]<='9') {
                           tEnd++;
                        }
                        var temp   = fData.substring(tBeg, tEnd);
                        var tmpDev = devs[iX].substr(13,2) + devs[iX].substr(11,2) +
                                     devs[iX].substr(9,2)  + devs[iX].substr(7,2)  +
                                     devs[iX].substr(5,2)  + devs[iX].substr(3,2);

                        deviceList.push({
                            "family": devs[iX].substr(0,2),
                            "id":     tmpDev.toUpperCase(),
                            "file":   devs[iX],
                            "temp":   temp/1000.0
                        });
                     }
                  }
               }
            }
         }
         return deviceList;
      }

      // Return the deviceList entry, given a device ID
      this.findDevice = function(deviceList, devId) {
         devId = devId.toUpperCase();
         for (var iX=0; iX<deviceList.length; iX++) {
            if (devId === deviceList[iX].file.substr(3).toUpperCase() ||
                devId === deviceList[iX].id) {
               return deviceList[iX];
            }
         }
         // If it's not in the normalised form
         var tmpDev = devId.substr(13,2) + devId.substr(11,2) +
                      devId.substr(9,2)  + devId.substr(7,2)  +
                      devId.substr(5,2)  + devId.substr(3,2);
         for (var iX=0; iX<deviceList.length; iX++) {
            if (devId === deviceList[iX].file.substr(3).toUpperCase() ||
                devId === deviceList[iX].id) {
               return deviceList[iX];
            }
         }

         return null;
      }

      // Read the data & return a message object
      this.read = function(inMsg) {
         // Retrieve the full set of data
         var deviceList = this.loadDeviceData();

         var msgList = [];
         var msg;

         if (this.topic != undefined && this.topic != "") {
            // Split a list into devices (or 1 if only 1)
            var sList = this.topic.split(" ");
            var retArr = [];
            for (var iX=0; iX<sList.length; iX++) {
               // Set up the returned message
               var dev = this.findDevice(deviceList, sList[iX]);
               if (this.returnArray || sList.length > 1) {
                  retArr.push(dev);
               } else {
                  msg = _.clone(inMsg);
                  if (dev === null) {  // Device not found!
                    msg.family  = 0;
                    msg.payload = "";
                  } else {
                    msg.topic = dev.id;
                    msg.family  = dev.family;
                    msg.payload = dev.temp;
                  }
                  msgList.push(msg);
               }
            }
            if (this.returnArray || sList.length > 1) {
              msg = _.clone(inMsg);
              msg.topic   = "";
              msg.payload = retArr;
              msgList.push(msg);
            }
         } else { // No list of devices in the topic
            if (this.returnArray) { // Return as an array?
               msg     = _.clone(inMsg);
               msg.topic   = "";
               msg.payload = deviceList;
               msgList.push(msg);
            } else { // Not an array - a series of messages
               for (var iX=0; iX<deviceList.length; iX++) {
                  msg = _.clone(inMsg);
                  msg.topic   = deviceList[iX].id;
                  msg.family  = deviceList[iX].family;
                  msg.payload = deviceList[iX].temp;
                  msgList.push(msg);
               }
            }
         }
         return msgList;
      };

      // respond to inputs....
      this.on('input', function (msg) {
         this.topic = config.topic;
         if (msg.topic !== undefined && msg.topic !== "") {
            this.topic = msg.topic;
         }
         this.returnArray = msg.array | config.array;

         var arr = this.read(msg);

         if (arr) {
            node.send([ arr ]);
         }
      });

   }

   // Register the node by name.
   RED.nodes.registerType("rpi-ds18b20", ds18b20Sensor);
}

<commit_msg>Return the file and dir<commit_after>/**
 * Copyright 2015, 2016 Brendan Murray
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

// See https://www.maximintegrated.com/en/app-notes/index.mvp/id/187 for
// a description of the 1-wire protocol.

// Dependency - file system access
var fs = require('fs');
var _ = require('underscore');

module.exports = function(RED) {
   "use strict";

   // The main node definition - most things happen in here
   function ds18b20Sensor(config) {

      // Create a RED node
      RED.nodes.createNode(this, config);

      // Store local copies of the node configuration (as defined in the .html)
      var node = this;

      // The root path of the sensors
      var W1PATH = "/sys/bus/w1/devices";

      // The directories location
      var W1DIRS = "/sys/devices/";

      // The devices list file
      var W1DEVICES = "/sys/devices/w1_bus_master1/w1_master_slaves";

      // Save the default device ID
      this.topic = config.topic;

      // If we are to return an array
      this.returnArray = false;

      // Load information from the devices list
      this.loadDeviceData = function() {
         var deviceList = [];
         var fsOptions = { "encoding":"utf8", "flag":"r" };
         var dirs = fs.readdirSync(W1DIRS, "utf8");
         for (var iY=0; iY<dirs.length; iY++) {
            if (dirs[iY].startsWith("w1_bus_master")) {
               var devs = fs.readFileSync(W1DIRS + dirs[iY] +
                             "/w1_master_slaves", fsOptions).split("\n");
               for (var iX=0; iX<devs.length; iX++) {
                  if (devs[iX] !== undefined && devs[iX] !== "") {
                     var fData = fs.readFileSync(W1PATH + "/" + devs[iX] +
                                           "/w1_slave", fsOptions).trim();
                     // Extract the numeric part
                     var tBeg = fData.indexOf("t=")+2;
                     if (tBeg >= 0) {
                        var tEnd = tBeg+1;
                        while (tEnd<fData.length &&
                               fData[tEnd]>='0' && fData[tEnd]<='9') {
                           tEnd++;
                        }
                        var temp   = fData.substring(tBeg, tEnd);
                        var tmpDev = devs[iX].substr(13,2) + devs[iX].substr(11,2) +
                                     devs[iX].substr(9,2)  + devs[iX].substr(7,2)  +
                                     devs[iX].substr(5,2)  + devs[iX].substr(3,2);

                        deviceList.push({
                            "family": devs[iX].substr(0,2),
                            "id":     tmpDev.toUpperCase(),
                            "dir":    dirs[iY],
                            "file":   devs[iX],
                            "temp":   temp/1000.0
                        });
                     }
                  }
               }
            }
         }
         return deviceList;
      }

      // Return the deviceList entry, given a device ID
      this.findDevice = function(deviceList, devId) {
         devId = devId.toUpperCase();
         for (var iX=0; iX<deviceList.length; iX++) {
            if (devId === deviceList[iX].file.substr(3).toUpperCase() ||
                devId === deviceList[iX].id) {
               return deviceList[iX];
            }
         }
         // If it's not in the normalised form
         var tmpDev = devId.substr(13,2) + devId.substr(11,2) +
                      devId.substr(9,2)  + devId.substr(7,2)  +
                      devId.substr(5,2)  + devId.substr(3,2);
         for (var iX=0; iX<deviceList.length; iX++) {
            if (devId === deviceList[iX].file.substr(3).toUpperCase() ||
                devId === deviceList[iX].id) {
               return deviceList[iX];
            }
         }

         return null;
      }

      // Read the data & return a message object
      this.read = function(inMsg) {
         // Retrieve the full set of data
         var deviceList = this.loadDeviceData();

         var msgList = [];
         var msg;

         if (this.topic != undefined && this.topic != "") {
            // Split a list into devices (or 1 if only 1)
            var sList = this.topic.split(" ");
            var retArr = [];
            for (var iX=0; iX<sList.length; iX++) {
               // Set up the returned message
               var dev = this.findDevice(deviceList, sList[iX]);
               if (this.returnArray || sList.length > 1) {
                  retArr.push(dev);
               } else {
                  msg = _.clone(inMsg);
                  if (dev === null) {  // Device not found!
                    msg.family  = 0;
                    msg.payload = "";
                  } else {
                    msg.file    = dev.file;
                    msg.dir     = dev.dir;
                    msg.topic   = dev.id;
                    msg.family  = dev.family;
                    msg.payload = dev.temp;
                  }
                  msgList.push(msg);
               }
            }
            if (this.returnArray || sList.length > 1) {
              msg = _.clone(inMsg);
              msg.topic   = "";
              msg.payload = retArr;
              msgList.push(msg);
            }
         } else { // No list of devices in the topic
            if (this.returnArray) { // Return as an array?
               msg     = _.clone(inMsg);
               msg.topic   = "";
               msg.payload = deviceList;
               msgList.push(msg);
            } else { // Not an array - a series of messages
               for (var iX=0; iX<deviceList.length; iX++) {
                  msg = _.clone(inMsg);
                  msg.file    = deviceList[iX].file;
                  msg.dir     = deviceList[iX].dir;
                  msg.topic   = deviceList[iX].id;
                  msg.family  = deviceList[iX].family;
                  msg.payload = deviceList[iX].temp;
                  msgList.push(msg);
               }
            }
         }
         return msgList;
      };

      // respond to inputs....
      this.on('input', function (msg) {
         this.topic = config.topic;
         if (msg.topic !== undefined && msg.topic !== "") {
            this.topic = msg.topic;
         }
         this.returnArray = msg.array | config.array;

         var arr = this.read(msg);

         if (arr) {
            node.send([ arr ]);
         }
      });

   }

   // Register the node by name.
   RED.nodes.registerType("rpi-ds18b20", ds18b20Sensor);
}

<|endoftext|>


<commit_before>$(function() {
  var handleStart = function(event) {
    var request;
    var zhtext;
    var pinyin;
    var num;
    var anshtml;
    var mp3elmid;
    zhtext = $(event.target).data('zh');
    pinyin = $(event.target).data('pinyin');
    num = $(event.target).data('num');
    if(zhtext) {
      $(event.target).css('border', '2px solid #000');
      anshtml = '';
      if(pinyin) {
	anshtml = anshtml + '<ruby>' + zhtext + '<rt>' + pinyin + '</rt></ruby>';
      } else {
	anshtml = anshtml + zhtext;
      }
      mp3elmid = 'mp3elm_' + num;
      anshtml = anshtml + '
-';
      $(event.target).html(anshtml);
      $(event.target).off('touchstart', handleStart);

      // ----------------------------------------
      // 音声MP3データのダウンロード
      // ----------------------------------------
      var ctx = new AudioContext();
      var elm = document.getElementById(mp3elmid);
      var mp3 = "/mp3/" + zhtext + ".mp3";
      var xhr = new XMLHttpRequest();

      xhr.open('GET', mp3, true);
      xhr.responseType = "arraybuffer";
      xhr.onload = function () {
	if(xhr.status == 200) {
	  $(elm).html('');
	  $(elm).click(function() {
	    window.AudioContext = window.AudioContext || window.webkitAudioContext;
	    var src = ctx.createBufferSource();

	    // オーディオをデコード
	    ctx.decodeAudioData(xhr.response, function (buf) {
              src.buffer = buf;
              src.loop = false;
              src.connect(ctx.destination);
              src.start(0);
	    });
	  });
        }
      };
      xhr.send(null);

      // ----------------------------------------
      // 15秒後に表示を元に戻す
      // ----------------------------------------
      setTimeout(function() {
        $(event.target).html($(event.target).data('jp'));
        $(event.target).css('border', '2px solid #fff');
        $(event.target).on('touchstart', handleStart);
        ctx.close();
      }, 15000);
    }
  };

  var handleEnd = function(event) {
    $(event.target).html($(event.target).data('jp'));
    $(document).off('touchend', handleEnd);
  };

  var q = $.url().param().q;
  var wordsjson = "y7words.json";
  if(q)
    wordsjson = q;

  var time1;
  time1 = new Date();
  $.getJSON("json/" + wordsjson + "?" + time1.getTime(), function(words) {
    var i, cnt, template;
    cnt = 0;
    for(i = 0; i < words.length; i++) {
      if(words[i] && words[i][0] && words[i][0]!=='END') {
        cnt = cnt + 1;
        if(words[i][1]) {
          template = '';
          template = template + '
';
          template = template + '
' + words[i][0];
          template = template + '
';
          template = template + '
';
        } else {
          template = '
' + words[i][0] + '
';
        }
        $("main").append(template);
      }
      $("#navbar1").text(cnt);
    }
    $(".word").on('touchstart', handleStart);
    $(".word").on('click', handleStart);
  });

  //iOS版
  var request;
  var status = 0;

  function downloadMP3(zhtext) {
    request = new XMLHttpRequest();
    request.open("GET", "/mp3/" + zhtext + ".mp3", true);
    request.responseType = "arraybuffer";
    request.onload = completeOnLoad;
    request.send();
  }

  function clickPlay() {
    if (status == 0) {
      status = 1;
      request = new XMLHttpRequest();
      request.open("GET", "/mp3/出口仓库.mp3", true);
      request.responseType = "arraybuffer";
      request.onload = completeOnLoad;
      request.send();
    } else if (status == 2) {
      window.AudioContext = window.AudioContext || window.webkitAudioContext;
      context = new AudioContext();

      source = context.createBufferSource();

      // オーディオをデコード
      context.decodeAudioData(request.response, function (buf) {
        source.buffer = buf;
        source.loop = false;
        source.connect(context.destination);
        source.start(0);
      });
    }
  };

  function completeOnLoad() {
    status = 2;
    var elem = document.getElementById("mp3play1");
    elem.innerText = "再生";
  }

  $("#mp3play1").click(clickPlay);

});
<commit_msg>2019-01-09<commit_after>$(function() {
  var handleStart = function(event) {
    var request;
    var zhtext;
    var pinyin;
    var num;
    var anshtml;
    var mp3elmid;
    zhtext = $(event.target).data('zh');
    pinyin = $(event.target).data('pinyin');
    num = $(event.target).data('num');
    if(zhtext) {
      $(event.target).css('border', '2px solid #000');
      anshtml = '';
      if(pinyin) {
	anshtml = anshtml + '<ruby>' + zhtext + '<rt>' + pinyin + '</rt></ruby>';
      } else {
	anshtml = anshtml + zhtext;
      }
      mp3elmid = 'mp3elm_' + num;
      anshtml = anshtml + '
-';
      $(event.target).html(anshtml);
      $(event.target).off('touchstart', handleStart);

      // ----------------------------------------
      // 音声MP3データのダウンロード
      // ----------------------------------------
      window.AudioContext = window.AudioContext || window.webkitAudioContext;
      var ctx = new AudioContext();
      var elm = document.getElementById(mp3elmid);
      var mp3 = "/mp3/" + zhtext + ".mp3";
      var xhr = new XMLHttpRequest();

      xhr.open('GET', mp3, true);
      xhr.responseType = "arraybuffer";
      xhr.onload = function () {
	if(xhr.status == 200) {
	  $(elm).html('');
	  $(elm).click(function() {
	    var src = ctx.createBufferSource();

	    // オーディオをデコード
	    ctx.decodeAudioData(xhr.response, function (buf) {
              src.buffer = buf;
              src.loop = false;
              src.connect(ctx.destination);
              src.start(0);
	    });
	  });
        }
      };
      xhr.send(null);

      // ----------------------------------------
      // 15秒後に表示を元に戻す
      // ----------------------------------------
      setTimeout(function() {
        $(event.target).html($(event.target).data('jp'));
        $(event.target).css('border', '2px solid #fff');
        $(event.target).on('touchstart', handleStart);
        ctx.close();
      }, 15000);
    }
  };

  var handleEnd = function(event) {
    $(event.target).html($(event.target).data('jp'));
    $(document).off('touchend', handleEnd);
  };

  var q = $.url().param().q;
  var wordsjson = "y7words.json";
  if(q)
    wordsjson = q;

  var time1;
  time1 = new Date();
  $.getJSON("json/" + wordsjson + "?" + time1.getTime(), function(words) {
    var i, cnt, template;
    cnt = 0;
    for(i = 0; i < words.length; i++) {
      if(words[i] && words[i][0] && words[i][0]!=='END') {
        cnt = cnt + 1;
        if(words[i][1]) {
          template = '';
          template = template + '
';
          template = template + '
' + words[i][0];
          template = template + '
';
          template = template + '
';
        } else {
          template = '
' + words[i][0] + '
';
        }
        $("main").append(template);
      }
      $("#navbar1").text(cnt);
    }
    $(".word").on('touchstart', handleStart);
    $(".word").on('click', handleStart);
  });

  //iOS版
  var request;
  var status = 0;

  function downloadMP3(zhtext) {
    request = new XMLHttpRequest();
    request.open("GET", "/mp3/" + zhtext + ".mp3", true);
    request.responseType = "arraybuffer";
    request.onload = completeOnLoad;
    request.send();
  }

  function clickPlay() {
    if (status == 0) {
      status = 1;
      request = new XMLHttpRequest();
      request.open("GET", "/mp3/出口仓库.mp3", true);
      request.responseType = "arraybuffer";
      request.onload = completeOnLoad;
      request.send();
    } else if (status == 2) {
      window.AudioContext = window.AudioContext || window.webkitAudioContext;
      context = new AudioContext();

      source = context.createBufferSource();

      // オーディオをデコード
      context.decodeAudioData(request.response, function (buf) {
        source.buffer = buf;
        source.loop = false;
        source.connect(context.destination);
        source.start(0);
      });
    }
  };

  function completeOnLoad() {
    status = 2;
    var elem = document.getElementById("mp3play1");
    elem.innerText = "再生";
  }

  $("#mp3play1").click(clickPlay);

});
<|endoftext|>


<commit_before>/*
	ejies-jsextensions.js by Emmanuel Jourdan, Ircam - 02 2005
	"shared library" used for the ejies JavaScripts
	Pour l'instant, ça ne sert à rien... mais à l'avenir... j'en ferai sans doute un usage intensif :-)
*/

var ejies = new EjiesUtils();
post("ejies", ejies.VersNum, ejies.VersDate);
post("\n     by Emmanuel Jourdan\, Ircam\n");

function EjiesUtils()
{
	this.VersNum = "2.0b2";		// Version Number
	this.VersDate = "(10/2008)";	// Version release date

	// clip method
	this.clip = function(x, min, max)
	{
		return Math.min(Math.max(x,min),max);
	}

	/*
	 *	error function
	 *	args: this, followed by any number/type of arguments
	 */
	this.error = function(x)
	{
		var errorString = "• error: " + x.jsarguments[0] + ":";

		// If the it's a string with a lenth of 1 -> it's strange...
		// that means we passed a string to the function (and the length property refer to a string)
		if (arguments.length > 2 && typeof(arguments[1]) == "string" && arguments[1].length == 1)
			errorString += " " + arguments[1];
		else {
			for (var i = 1; i < arguments.length; i++)
				errorString += " " + arguments[i];
		}

		post(errorString + "\n");
	}

	return this;
}

/*
 *	Attribute parsing
 */
function ej_attr_args_offset(a)
{
	var i;

	// walk and find first string starting with @
	// ignore first argument which is the script name
	for (i = 1; i < a.length; i++) {
		// String.prototype.isPrototypeOf(a[i]) doesn't work...
		if (a[i] && typeof(a[i]) == "string" && (a[i].toString().charAt(0)=="@"))
			return i;
	}

	return i;
}

// x argument is passed the "this" object
function ej_attr_args_process(x,a)
{
	var i;
	var attrname = null;
	var attrargs = null;
	var tmpString;
	var firstAttribute = ej_attr_args_offset(a);

	// walk and find strings starting with @
	// call functions with attr names followed by any arguments
	for (i = firstAttribute; i < a.length;i ++) {
		// Function.prototype.isPrototypeOf("this." + a[i]) doesn't work here either
		if (a[i] && typeof(a[i]) == "string" && Function.prototype.isPrototypeOf(x[a[i].slice(1)]) && (a[i].toString().charAt(0)=="@")) {

			// if there's a pending, execute with arguments, or give
			// an error if there's no corresponding setter function
			ej_attr_process_pending(x,attrname,attrargs);

			// grab new attrname, stripping '@'
			attrname = a[i].slice(1); // works because a[i] is a string

			// reset arguments
			attrargs = null;
		} else {
			// this is an attribute argument, store in our arguments array
			if (attrargs == null)
				attrargs = new Array();

			if (a[i].toString().charAt(0) != "@") {
				attrargs[attrargs.length] = a[i];
			} else {
				post("js: attribute " + a[i].slice(1) + " is not a valid attribtue argument\n");
				return;
			}

		}
	}

	// process pending to handle last attribute argument
	ej_attr_process_pending(x,attrname,attrargs);

	// quite ugly, delete the attributes from the jsarguments array
	x.jsarguments.length = firstAttribute;
}

function ej_attr_process_pending(x,attrname,attrargs)
{
	if (attrname)
	{
		if (x[attrname] && Function.prototype.isPrototypeOf(x[attrname]))
		{
			// here you might need to do a little more work to determine the
			// way that you need to pass the attribute arguments. might requre
			// some trickiness or a brute force switch statement based on
			// attrargs.length or something, but should give you the basic idea.

			if (attrargs != null)
				x[attrname].apply(x, attrargs); // unroll the arguments
		} else {
			post("js: attribute " + attrname + " is not a valid attribtue argument\n");
		}
	}
}
<commit_msg>new line before posting, just in case<commit_after>/*
	ejies-jsextensions.js by Emmanuel Jourdan, Ircam - 02 2005
	"shared library" used for the ejies JavaScripts
	Pour l'instant, ça ne sert à rien... mais à l'avenir... j'en ferai sans doute un usage intensif :-)
*/

var ejies = new EjiesUtils();
post("\nejies", ejies.VersNum, ejies.VersDate);
post("\n     by Emmanuel Jourdan\, Ircam\n");

function EjiesUtils()
{
	this.VersNum = "2.0b2";		// Version Number
	this.VersDate = "(10/2008)";	// Version release date

	// clip method
	this.clip = function(x, min, max)
	{
		return Math.min(Math.max(x,min),max);
	}

	/*
	 *	error function
	 *	args: this, followed by any number/type of arguments
	 */
	this.error = function(x)
	{
		var errorString = "• error: " + x.jsarguments[0] + ":";

		// If the it's a string with a lenth of 1 -> it's strange...
		// that means we passed a string to the function (and the length property refer to a string)
		if (arguments.length > 2 && typeof(arguments[1]) == "string" && arguments[1].length == 1)
			errorString += " " + arguments[1];
		else {
			for (var i = 1; i < arguments.length; i++)
				errorString += " " + arguments[i];
		}

		post(errorString + "\n");
	}

	return this;
}

/*
 *	Attribute parsing
 */
function ej_attr_args_offset(a)
{
	var i;

	// walk and find first string starting with @
	// ignore first argument which is the script name
	for (i = 1; i < a.length; i++) {
		// String.prototype.isPrototypeOf(a[i]) doesn't work...
		if (a[i] && typeof(a[i]) == "string" && (a[i].toString().charAt(0)=="@"))
			return i;
	}

	return i;
}

// x argument is passed the "this" object
function ej_attr_args_process(x,a)
{
	var i;
	var attrname = null;
	var attrargs = null;
	var tmpString;
	var firstAttribute = ej_attr_args_offset(a);

	// walk and find strings starting with @
	// call functions with attr names followed by any arguments
	for (i = firstAttribute; i < a.length;i ++) {
		// Function.prototype.isPrototypeOf("this." + a[i]) doesn't work here either
		if (a[i] && typeof(a[i]) == "string" && Function.prototype.isPrototypeOf(x[a[i].slice(1)]) && (a[i].toString().charAt(0)=="@")) {

			// if there's a pending, execute with arguments, or give
			// an error if there's no corresponding setter function
			ej_attr_process_pending(x,attrname,attrargs);

			// grab new attrname, stripping '@'
			attrname = a[i].slice(1); // works because a[i] is a string

			// reset arguments
			attrargs = null;
		} else {
			// this is an attribute argument, store in our arguments array
			if (attrargs == null)
				attrargs = new Array();

			if (a[i].toString().charAt(0) != "@") {
				attrargs[attrargs.length] = a[i];
			} else {
				post("js: attribute " + a[i].slice(1) + " is not a valid attribtue argument\n");
				return;
			}

		}
	}

	// process pending to handle last attribute argument
	ej_attr_process_pending(x,attrname,attrargs);

	// quite ugly, delete the attributes from the jsarguments array
	x.jsarguments.length = firstAttribute;
}

function ej_attr_process_pending(x,attrname,attrargs)
{
	if (attrname)
	{
		if (x[attrname] && Function.prototype.isPrototypeOf(x[attrname]))
		{
			// here you might need to do a little more work to determine the
			// way that you need to pass the attribute arguments. might requre
			// some trickiness or a brute force switch statement based on
			// attrargs.length or something, but should give you the basic idea.

			if (attrargs != null)
				x[attrname].apply(x, attrargs); // unroll the arguments
		} else {
			post("js: attribute " + attrname + " is not a valid attribtue argument\n");
		}
	}
}
<|endoftext|>


<commit_before>const eslintrc = {
  extends: [
    'airbnb',
    'prettier',
    'plugin:jest/recommended',
    'plugin:react/recommended',
    'plugin:import/typescript',
    'prettier/react',
  ],
  env: {
    browser: true,
    node: true,
    jasmine: true,
    jest: true,
    es6: true,
  },
  settings: {
    react: {
      version: '16.9',
    },
  },
  parser: '@typescript-eslint/parser',
  plugins: ['markdown', 'react', 'babel', 'jest', '@typescript-eslint'],
  // https://github.com/typescript-eslint/typescript-eslint/issues/46#issuecomment-470486034
  overrides: [
    {
      files: ['*.ts', '*.tsx'],
      rules: {
        '@typescript-eslint/no-unused-vars': [2, { args: 'none' }],
      },
    },
  ],
  rules: {
    camelcase: 0,
    'react/jsx-one-expression-per-line': 0,
    'react/prop-types': 0,
    'react/forbid-prop-types': 0,
    'react/jsx-indent': 0,
    'react/jsx-wrap-multilines': ['error', { declaration: false, assignment: false }],
    'import/no-extraneous-dependencies': [
      'error',
      {
        devDependencies: [
          'site/**',
          'tests/**',
          'scripts/**',
          '**/*.test.js',
          '**/__tests__/*',
          '*.config.js',
          '**/*.md',
        ],
      },
    ],
    'jsx-a11y/no-static-element-interactions': 0,
    'jsx-a11y/anchor-has-content': 0,
    'jsx-a11y/click-events-have-key-events': 0,
    'jsx-a11y/anchor-is-valid': 0,
    'comma-dangle': ['error', 'always-multiline'],
    'react/jsx-filename-extension': 0,
    'react/state-in-constructor': 0,
    'react/jsx-props-no-spreading': 0,
    'prefer-destructuring': 0, // TODO: remove later
    'consistent-return': 0, // TODO: remove later
    'no-return-assign': 0, // TODO: remove later
    'no-param-reassign': 0, // TODO: remove later
    'react/destructuring-assignment': 0, // TODO: remove later
    'react/no-did-update-set-state': 0, // TODO: remove later
    'react/require-default-props': 0,
    'react/default-props-match-prop-types': 0,
    'import/no-cycle': 0,
    'react/no-find-dom-node': 0,
    'no-underscore-dangle': 0,
    'react/sort-comp': 0,
    // label-has-for has been deprecated
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/label-has-for.md
    'jsx-a11y/label-has-for': 0,
    // for (let i = 0; i < len; i++)
    'no-plusplus': 0,
    // https://eslint.org/docs/rules/no-continue
    // labeledLoop is conflicted with `eslint . --fix`
    'no-continue': 0,
    'react/display-name': 0,
    // ban this for Number.isNaN needs polyfill
    'no-restricted-globals': 0,
    'max-classes-per-file': 0,
    'react/static-property-placement': 0,
    'jest/no-test-callback': 0,
    'jest/expect-expect': 0,
  },
  globals: {
    gtag: true,
  },
};

if (process.env.RUN_ENV === 'DEMO') {
  eslintrc.globals = Object.assign(eslintrc.globals, {
    React: true,
    ReactDOM: true,
    mountNode: true,
  });

  Object.assign(eslintrc.rules, {
    indent: 0,
    'no-console': 0,
    'no-plusplus': 0,
    'eol-last': 0,
    'no-script-url': 0,
    'prefer-rest-params': 0,
    'react/no-access-state-in-setstate': 0,
    'react/destructuring-assignment': 0,
    'react/no-multi-comp': 0,
    'jsx-a11y/href-no-hash': 0,
    'import/no-extraneous-dependencies': 0,
    'import/no-unresolved': 0,
    'jsx-a11y/control-has-associated-label': 0,
  });
}

module.exports = eslintrc;
<commit_msg>import/extensions:0<commit_after>const eslintrc = {
  extends: [
    'airbnb',
    'prettier',
    'plugin:jest/recommended',
    'plugin:react/recommended',
    'plugin:import/typescript',
    'prettier/react',
  ],
  env: {
    browser: true,
    node: true,
    jasmine: true,
    jest: true,
    es6: true,
  },
  settings: {
    react: {
      version: '16.9',
    },
  },
  parser: '@typescript-eslint/parser',
  plugins: ['markdown', 'react', 'babel', 'jest', '@typescript-eslint'],
  // https://github.com/typescript-eslint/typescript-eslint/issues/46#issuecomment-470486034
  overrides: [
    {
      files: ['*.ts', '*.tsx'],
      rules: {
        '@typescript-eslint/no-unused-vars': [2, { args: 'none' }],
      },
    },
  ],
  rules: {
    camelcase: 0,
    'react/jsx-one-expression-per-line': 0,
    'react/prop-types': 0,
    'react/forbid-prop-types': 0,
    'react/jsx-indent': 0,
    'react/jsx-wrap-multilines': ['error', { declaration: false, assignment: false }],
    'import/no-extraneous-dependencies': [
      'error',
      {
        devDependencies: [
          'site/**',
          'tests/**',
          'scripts/**',
          '**/*.test.js',
          '**/__tests__/*',
          '*.config.js',
          '**/*.md',
        ],
      },
    ],
    'jsx-a11y/no-static-element-interactions': 0,
    'jsx-a11y/anchor-has-content': 0,
    'jsx-a11y/click-events-have-key-events': 0,
    'jsx-a11y/anchor-is-valid': 0,
    'comma-dangle': ['error', 'always-multiline'],
    'react/jsx-filename-extension': 0,
    'react/state-in-constructor': 0,
    'react/jsx-props-no-spreading': 0,
    'prefer-destructuring': 0, // TODO: remove later
    'consistent-return': 0, // TODO: remove later
    'no-return-assign': 0, // TODO: remove later
    'no-param-reassign': 0, // TODO: remove later
    'react/destructuring-assignment': 0, // TODO: remove later
    'react/no-did-update-set-state': 0, // TODO: remove later
    'react/require-default-props': 0,
    'react/default-props-match-prop-types': 0,
    'import/no-cycle': 0,
    'react/no-find-dom-node': 0,
    'no-underscore-dangle': 0,
    'react/sort-comp': 0,
    // label-has-for has been deprecated
    // https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/label-has-for.md
    'jsx-a11y/label-has-for': 0,
    // for (let i = 0; i < len; i++)
    'no-plusplus': 0,
    // https://eslint.org/docs/rules/no-continue
    // labeledLoop is conflicted with `eslint . --fix`
    'no-continue': 0,
    'react/display-name': 0,
    // ban this for Number.isNaN needs polyfill
    'no-restricted-globals': 0,
    'max-classes-per-file': 0,
    'react/static-property-placement': 0,
    'jest/no-test-callback': 0,
    'jest/expect-expect': 0,
    'import/extensions': 0,
  },
  globals: {
    gtag: true,
  },
};

if (process.env.RUN_ENV === 'DEMO') {
  eslintrc.globals = Object.assign(eslintrc.globals, {
    React: true,
    ReactDOM: true,
    mountNode: true,
  });

  Object.assign(eslintrc.rules, {
    indent: 0,
    'no-console': 0,
    'no-plusplus': 0,
    'eol-last': 0,
    'no-script-url': 0,
    'prefer-rest-params': 0,
    'react/no-access-state-in-setstate': 0,
    'react/destructuring-assignment': 0,
    'react/no-multi-comp': 0,
    'jsx-a11y/href-no-hash': 0,
    'import/no-extraneous-dependencies': 0,
    'import/no-unresolved': 0,
    'jsx-a11y/control-has-associated-label': 0,
  });
}

module.exports = eslintrc;
<|endoftext|>


<commit_before>var types = {
	jQuery: "A jQuery object.",
	Object: "A simple Javascript object. For example, it could be a String or a Number.",
	String: "A string of characters.",
	Number: "A numeric valid.",
	Element: "The Javascript object representation of a DOM Element.",
	Hash: "A Javascript object that contains key/value pairs in the form of properties and values.",
	"Array<Element>": "An Array of DOM Elements.",
	"Array<String>": "An Array of strings.",
	Function: "A reference to a Javascript function."
};

$(document).ready(function(){
	$("span.tooltip").each(function(){
		if ( types[ this.innerHTML ] )
			this.title = types[ this.innerHTML ];
	}).ToolTipDemo('#fff');

	$("a.name").click(function(){
		$("div.more,div.short",this.parentNode.parentNode)
			.find("div.desc",function(){
				$(this).html( $(this).html().replace(/\n\n/g, "

") );
			})
			.toggle('slow');
		return false;
	});

	$("#docs").alphaPager(function(a){
		return $.fn.text.apply( [a.childNodes[1]] ).replace(/^\$\./,"").substr(0,1).toUpperCase();
	});
});
<commit_msg>Fixed an issue with .find(expr,Function) and a Safari bug.<commit_after>var types = {
	jQuery: "A jQuery object.",
	Object: "A simple Javascript object. For example, it could be a String or a Number.",
	String: "A string of characters.",
	Number: "A numeric valid.",
	Element: "The Javascript object representation of a DOM Element.",
	Hash: "A Javascript object that contains key/value pairs in the form of properties and values.",
	"Array<Element>": "An Array of DOM Elements.",
	"Array<String>": "An Array of strings.",
	Function: "A reference to a Javascript function.",
	XMLHttpRequest: "An XMLHttpRequest object (referencing a HTTP request)."
};

$(document).ready(function(){
	$("span.tooltip").each(function(){
		if ( types[ this.innerHTML ] )
			this.title = types[ this.innerHTML ];
	}).ToolTipDemo('#fff');

	$("a.name").click(function(){
		$("div.more,div.short",this.parentNode.parentNode)
			.find("div.desc").each(function(){
				$(this).html( $(this).html().replace(/\n\n/g, "

") );
			}).end()
			.toggle('slow');
		return false;
	});

	$("#docs").alphaPager(function(a){
		return $.fn.text.apply( [a.getElementsByTagName("span")[2]] ).replace(/^\$\./,"").substr(0,1).toUpperCase();
	});
});
<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var CanvasPool = require('../../display/canvas/CanvasPool');

/**
 * Calculates the ascent, descent and fontSize of a given font style.
 *
 * @function Phaser.GameObjects.MeasureText
 * @since 3.0.0
 *
 * @param {Phaser.GameObjects.TextStyle} textStyle - The TextStyle object to measure.
 *
 * @return {Phaser.Types.GameObjects.Text.TextMetrics} An object containing the ascent, descent and fontSize of the TextStyle.
 */
var MeasureText = function (textStyle)
{
    // @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered.
    var canvas = CanvasPool.create(this);

    // @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to.
    var context = canvas.getContext('2d');

    textStyle.syncFont(canvas, context);

    var metrics = context.measureText(textStyle.testString);

    if (metrics.hasOwnProperty('actualBoundingBoxAscent') && metrics.hasOwnProperty('actualBoundingBoxDescent'))
    {
        var ascent = metrics.actualBoundingBoxAscent;
        var descent = metrics.actualBoundingBoxDescent;

        var output = {
            ascent: ascent,
            descent: descent,
            fontSize: (ascent + descent)
        };

        CanvasPool.remove(canvas);

        return output;
    }

    var width = Math.ceil(metrics.width * textStyle.baselineX);
    var baseline = width;
    var height = 2 * baseline;

    baseline = baseline * textStyle.baselineY | 0;

    canvas.width = width;
    canvas.height = height;

    context.fillStyle = '#f00';
    context.fillRect(0, 0, width, height);

    context.font = textStyle._font;

    context.textBaseline = 'alphabetic';
    context.fillStyle = '#000';
    context.fillText(textStyle.testString, 0, baseline);

    var output = {
        ascent: 0,
        descent: 0,
        fontSize: 0
    };

    if (!context.getImageData(0, 0, width, height))
    {
        output.ascent = baseline;
        output.descent = baseline + 6;
        output.fontSize = output.ascent + output.descent;

        CanvasPool.remove(canvas);

        return output;
    }

    var imagedata = context.getImageData(0, 0, width, height).data;
    var pixels = imagedata.length;
    var line = width * 4;
    var i;
    var j;
    var idx = 0;
    var stop = false;

    // ascent. scan from top to bottom until we find a non red pixel
    for (i = 0; i < baseline; i++)
    {
        for (j = 0; j < line; j += 4)
        {
            if (imagedata[idx + j] !== 255)
            {
                stop = true;
                break;
            }
        }

        if (!stop)
        {
            idx += line;
        }
        else
        {
            break;
        }
    }

    output.ascent = baseline - i;

    idx = pixels - line;
    stop = false;

    // descent. scan from bottom to top until we find a non red pixel
    for (i = height; i > baseline; i--)
    {
        for (j = 0; j < line; j += 4)
        {
            if (imagedata[idx + j] !== 255)
            {
                stop = true;
                break;
            }
        }

        if (!stop)
        {
            idx -= line;
        }
        else
        {
            break;
        }
    }

    output.descent = (i - baseline);
    output.fontSize = output.ascent + output.descent;

    CanvasPool.remove(canvas);

    return output;
};

module.exports = MeasureText;
<commit_msg>Fixed a few linting errors<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var CanvasPool = require('../../display/canvas/CanvasPool');

/**
 * Calculates the ascent, descent and fontSize of a given font style.
 *
 * @function Phaser.GameObjects.MeasureText
 * @since 3.0.0
 *
 * @param {Phaser.GameObjects.TextStyle} textStyle - The TextStyle object to measure.
 *
 * @return {Phaser.Types.GameObjects.Text.TextMetrics} An object containing the ascent, descent and fontSize of the TextStyle.
 */
var MeasureText = function (textStyle)
{
    var canvas = CanvasPool.create(this);
    var context = canvas.getContext('2d');

    textStyle.syncFont(canvas, context);

    var metrics = context.measureText(textStyle.testString);

    if (metrics.hasOwnProperty('actualBoundingBoxAscent'))
    {
        var ascent = metrics.actualBoundingBoxAscent;
        var descent = metrics.actualBoundingBoxDescent;

        CanvasPool.remove(canvas);

        return {
            ascent: ascent,
            descent: descent,
            fontSize: ascent + descent
        };
    }

    var width = Math.ceil(metrics.width * textStyle.baselineX);
    var baseline = width;
    var height = 2 * baseline;

    baseline = baseline * textStyle.baselineY | 0;

    canvas.width = width;
    canvas.height = height;

    context.fillStyle = '#f00';
    context.fillRect(0, 0, width, height);

    context.font = textStyle._font;

    context.textBaseline = 'alphabetic';
    context.fillStyle = '#000';
    context.fillText(textStyle.testString, 0, baseline);

    var output = {
        ascent: 0,
        descent: 0,
        fontSize: 0
    };

    if (!context.getImageData(0, 0, width, height))
    {
        output.ascent = baseline;
        output.descent = baseline + 6;
        output.fontSize = output.ascent + output.descent;

        CanvasPool.remove(canvas);

        return output;
    }

    var imagedata = context.getImageData(0, 0, width, height).data;
    var pixels = imagedata.length;
    var line = width * 4;
    var i;
    var j;
    var idx = 0;
    var stop = false;

    // ascent. scan from top to bottom until we find a non red pixel
    for (i = 0; i < baseline; i++)
    {
        for (j = 0; j < line; j += 4)
        {
            if (imagedata[idx + j] !== 255)
            {
                stop = true;
                break;
            }
        }

        if (!stop)
        {
            idx += line;
        }
        else
        {
            break;
        }
    }

    output.ascent = baseline - i;

    idx = pixels - line;
    stop = false;

    // descent. scan from bottom to top until we find a non red pixel
    for (i = height; i > baseline; i--)
    {
        for (j = 0; j < line; j += 4)
        {
            if (imagedata[idx + j] !== 255)
            {
                stop = true;
                break;
            }
        }

        if (!stop)
        {
            idx -= line;
        }
        else
        {
            break;
        }
    }

    output.descent = (i - baseline);
    output.fontSize = output.ascent + output.descent;

    CanvasPool.remove(canvas);

    return output;
};

module.exports = MeasureText;
<|endoftext|>


<commit_before>/**
 * Adapter for connecting a thin (low-power) remote client to the VisSynth server
 *  -Runs besides server.js on the server machine to provide a stateless simple low-level interface
 *  -Uses hardware_ui.js as UI-defining layer, that is shared by all hardware UI's and the HTML-based emulator hardware_ui.html
 *  -Interfaces remote by low level encoder and LCD message packets over UDP
 *  -Connects the VisSynth Server by Websockets like the browser UI would do
 *  -Holds state of loaded chains
 */

var http = require('http');
var WebSocket = require('ws');

var base_host='localhost';
var base_port='8082';

var remote_host='10.42.0.2',remote_port='8083';

var websocket;
onopen=onupdate=onclose=null;
var open_socket=function()
{
  websocket=new WebSocket('ws://'+base_host+':'+base_port);

  console.log('WebSocket open: '+base_host);

  websocket.on('open',function(){
    // opt in for update feed
try{
    this.send(JSON.stringify({'method':'get', path:'/feeds'+session_url+'update',data:''}));
   }
catch(e)
{
console.log(e);
}
    console.log('WebSocket open.');
    if(onopen) onopen();
  });
  websocket.on('message', function(data)
  {
    var packet=JSON.parse(data);
    var path=packet.path, message=packet.data;
    if(path=='/feeds'+session_url+'update')
    {
      if(onupdate) onupdate(message);
    }
  });
  websocket.on('close',function()
  {
    console.log('WebSocket closed remotely.');
    if(this==websocket)
    {
      setTimeout(open_socket,1000);
      if(onclose) onclose();
    }
  });
  websocket.on('error',function(err)
  {
    console.log('WebSocket error: '+err);
  });
}

// provide functions needed by hardware UI

session_url='/';

set_host=function(host)
{
  websocket.close();
  base_host=host;
  open_socket();
}

put=function(url,data)
{
  console.log('PUT: '+url);
  try{
  websocket.send(JSON.stringify({'method':'put','path':url,'data':data}));
   }
catch(e)
{
console.log(e);
}
}

get=function(url,callback,error_callback)
{
  console.log('GET: '+url);
  var req=http.request({
    host:base_host,
    port:base_port,
    path:url
  },function(res){
    if(!callback) return;
    res.setEncoding('utf8');
    var body='';
   res.on('data', function(chunk){
      body+=chunk;
    });
    res.on('end', function(){
      callback(body);
    })
  }).on('error',function(err){
    console.log('GET error: '+url+' '+err);
    // delay callback for 1s as we would otherwise do repeated roundtrips without delay for long polling calls
    error_callback(url);
  });
  req.end();
}

// provide UDP sockets or WebSockets???
const dgram = require('dgram');
const server = dgram.createSocket('udp4');

server.on('error', function(err) {
  console.log("server error: "+err.stack);
  server.close();
});

server.on('message', function(msg, rinfo) {
  console.log("server got: "+msg+" from "+rinfo.address+":"+rinfo.port);

  var data=JSON.parse(''+msg);
  var knob_nr=data['k'];
  var delta=data['d'];

  var knob=knobs[knob_nr];
  if(!knob) return;
  knob.callback(knob.id, delta);
});

server.on('listening', function() {
  var address = server.address();
  console.log("server listening"+address.address+":"+address.port);
});

server.bind(8083);

function pad(text,length)
{
 while(text.length<length) text+=' ';
 return text;
}

var lcd_update=false;
var lcd_text='';
set_display=function(text)
{
  console.log('DISPLAY:');
  console.log(text);
  console.log('');

  lcd_text=text;

 if(!lcd_update)
   lcd_update=setTimeout(function(){
     lcd_update=false;
     var lines=lcd_text.split('\n');
     var message=pad(lines[0],20)+pad(lines[1],20)+pad(lines[2],20)+pad(lines[3],20);
     var buffer=new Buffer('{'+message+'}');
     server.send(buffer,0,buffer.length,remote_port,remote_host,function(err){if(err) console.log("err: "+err)});
   },100);
}

knobs=[];
add_knob=function(id,callback)
{
  console.log('add_knob '+id);

  // for stdin test feed
  knobs.push({id:id,callback:callback});
};

process.stdin.on('readable', function(){
  process.stdin.setEncoding('utf8');
  var chunk = process.stdin.read();
  if (chunk !== null) {
    var parts=chunk.split(' ');
    var i=parseInt(parts[0]);
    var d=parseInt(parts[1]);
    if(!knobs[i]) return;
    var id=knobs[i].id;
    knobs[i].callback(id,d);
  }
});

/*process.stdin.on('end', () => {
  process.stdout.write('end');
});*/

require('./ui_hardware.js');
open_socket();

<commit_msg>hardcode remote config<commit_after>/**
 * Adapter for connecting a thin (low-power) remote client to the VisSynth server
 *  -Runs besides server.js on the server machine to provide a stateless simple low-level interface
 *  -Uses hardware_ui.js as UI-defining layer, that is shared by all hardware UI's and the HTML-based emulator hardware_ui.html
 *  -Interfaces remote by low level encoder and LCD message packets over UDP
 *  -Connects the VisSynth Server by Websockets like the browser UI would do
 *  -Holds state of loaded chains
 */

var http = require('http');
var WebSocket = require('ws');

var base_host='localhost';
var base_port='8082';

var remote_host='168.254.20.10',remote_port='8083';

var websocket;
onopen=onupdate=onclose=null;
var open_socket=function()
{
  websocket=new WebSocket('ws://'+base_host+':'+base_port);

  console.log('WebSocket open: '+base_host);

  websocket.on('open',function(){
    // opt in for update feed
try{
    this.send(JSON.stringify({'method':'get', path:'/feeds'+session_url+'update',data:''}));
   }
catch(e)
{
console.log(e);
}
    console.log('WebSocket open.');
    if(onopen) onopen();
  });
  websocket.on('message', function(data)
  {
    var packet=JSON.parse(data);
    var path=packet.path, message=packet.data;
    if(path=='/feeds'+session_url+'update')
    {
      if(onupdate) onupdate(message);
    }
  });
  websocket.on('close',function()
  {
    console.log('WebSocket closed remotely.');
    if(this==websocket)
    {
      setTimeout(open_socket,1000);
      if(onclose) onclose();
    }
  });
  websocket.on('error',function(err)
  {
    console.log('WebSocket error: '+err);
  });
}

// provide functions needed by hardware UI

session_url='/';

set_host=function(host)
{
  websocket.close();
  base_host=host;
  open_socket();
}

put=function(url,data)
{
  console.log('PUT: '+url);
  try{
  websocket.send(JSON.stringify({'method':'put','path':url,'data':data}));
   }
catch(e)
{
console.log(e);
}
}

get=function(url,callback,error_callback)
{
  console.log('GET: '+url);
  var req=http.request({
    host:base_host,
    port:base_port,
    path:url
  },function(res){
    if(!callback) return;
    res.setEncoding('utf8');
    var body='';
   res.on('data', function(chunk){
      body+=chunk;
    });
    res.on('end', function(){
      callback(body);
    })
  }).on('error',function(err){
    console.log('GET error: '+url+' '+err);
    // delay callback for 1s as we would otherwise do repeated roundtrips without delay for long polling calls
    error_callback(url);
  });
  req.end();
}

// provide UDP sockets or WebSockets???
const dgram = require('dgram');
const server = dgram.createSocket('udp4');

server.on('error', function(err) {
  console.log("server error: "+err.stack);
  server.close();
});

server.on('message', function(msg, rinfo) {
  console.log("server got: "+msg+" from "+rinfo.address+":"+rinfo.port);

  var data=JSON.parse(''+msg);
  var knob_nr=data['k'];
  var delta=data['d'];

  var knob=knobs[knob_nr];
  if(!knob) return;
  knob.callback(knob.id, delta);
});

server.on('listening', function() {
  var address = server.address();
  console.log("server listening"+address.address+":"+address.port);
});

server.bind(8083);

function pad(text,length)
{
 while(text.length<length) text+=' ';
 return text;
}

var lcd_update=false;
var lcd_text='';
set_display=function(text)
{
  console.log('DISPLAY:');
  console.log(text);
  console.log('');

  lcd_text=text;

 if(!lcd_update)
   lcd_update=setTimeout(function(){
     lcd_update=false;
     var lines=lcd_text.split('\n');
     var message=pad(lines[0],20)+pad(lines[1],20)+pad(lines[2],20)+pad(lines[3],20);
     var buffer=new Buffer('{'+message+'}');
     server.send(buffer,0,buffer.length,remote_port,remote_host,function(err){if(err) console.log("err: "+err)});
   },100);
}

knobs=[];
add_knob=function(id,callback)
{
  console.log('add_knob '+id);

  // for stdin test feed
  knobs.push({id:id,callback:callback});
};

process.stdin.on('readable', function(){
  process.stdin.setEncoding('utf8');
  var chunk = process.stdin.read();
  if (chunk !== null) {
    var parts=chunk.split(' ');
    var i=parseInt(parts[0]);
    var d=parseInt(parts[1]);
    if(!knobs[i]) return;
    var id=knobs[i].id;
    knobs[i].callback(id,d);
  }
});

/*process.stdin.on('end', () => {
  process.stdout.write('end');
});*/

require('./ui_hardware.js');
open_socket();

<|endoftext|>


<commit_before>import React from 'react';
import { Col, Box } from '@tlon/indigo-react';
import { GraphContentWide } from "~/views/landscape/components/Graph/GraphContentWide";
import styled from 'styled-components';

const TruncatedBox = styled(Col)`
  display: -webkit-box;
  -webkit-line-clamp: ${p => p.truncate ?? 'unset'};
  -webkit-box-orient: vertical;

`;

export function PostContent(props) {
  const { post, isParent, api, isReply } = props;

  return (
    <TruncatedBox
      display="-webkit-box"
      width="100%"
      pl="2"
      pr="2"
      truncate={isParent ? null : 8}
      textOverflow="ellipsis"
      overflow="hidden"
     >
      <GraphContentWide
        transcluded={0}
        post={post}
        api={api}
        showOurContact
      />
    </TruncatedBox>
  );
}

<commit_msg>PostContent: fix bottom spacing<commit_after>import React from 'react';
import { Col, Box } from '@tlon/indigo-react';
import { GraphContentWide } from "~/views/landscape/components/Graph/GraphContentWide";
import styled from 'styled-components';

const TruncatedBox = styled(Col)`
  display: -webkit-box;
  -webkit-line-clamp: ${p => p.truncate ?? 'unset'};
  -webkit-box-orient: vertical;

`;

export function PostContent(props) {
  const { post, isParent, api, isReply } = props;

  return (
    <TruncatedBox
      display="-webkit-box"
      width="100%"
      px="2"
      pb="2"
      truncate={isParent ? null : 8}
      textOverflow="ellipsis"
      overflow="hidden"
     >
      <GraphContentWide
        transcluded={0}
        post={post}
        api={api}
        showOurContact
      />
    </TruncatedBox>
  );
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var modalPopup = ".modal",
    modalPopupContainer = modalPopup + " .modal-content",
    modalPopupContent = modalPopup + " .modal-content";

var emmAdminBasePath = "/api/device-mgt/v1.0";

//function openCollapsedNav() {
//    $(".wr-hidden-nav-toggle-btn").addClass("active");
//    $("#hiddenNav").slideToggle("slideDown", function () {
//        if ($(this).css("display") == "none") {
//            $(".wr-hidden-nav-toggle-btn").removeClass("active");
//        }
//    });
//}

/*
 * set popup maximum height function.
 */
function setPopupMaxHeight() {
    var maxHeight = "max-height";
    var marginTop = "margin-top";
    var body = "body";
    $(modalPopupContent).css(maxHeight, ($(body).height() - ($(body).height() / 100 * 30)));
    $(modalPopupContainer).css(marginTop, (-($(modalPopupContainer).height() / 2)));
}

/*
 * show popup function.
 */
function showPopup() {
    $(modalPopup).modal('show');
}

/*
 * hide popup function.
 */
function hidePopup() {
    $(modalPopupContent).html("");
    $(modalPopupContent).removeClass("operation-data");
    $(modalPopup).modal('hide');
    $('body').removeClass('modal-open').css('padding-right','0px');
    $('.modal-backdrop').remove();
}

/*
 * QR-code generation function.
 */
function generateQRCode(qrCodeClass) {
    var enrollmentURL = $("#qr-code-modal").data("enrollment-url");
    $(qrCodeClass).qrcode({
        text: enrollmentURL,
        width: 200,
        height: 200
    });
}

function toggleEnrollment() {
    $(".modal-content").html($("#qr-code-modal").html());
    generateQRCode(".modal-content .qr-code");
    modalDialog.show();
}

var updateNotificationCountOnSuccess = function (data, textStatus, jqXHR) {
    var notificationBubble = "#notification-bubble";
    if (jqXHR.status == 200 && data) {
        var responsePayload = JSON.parse(data);
        var newNotificationsCount = responsePayload["count"];
        if (newNotificationsCount > 0) {
            $(notificationBubble).html(newNotificationsCount);
            $(notificationBubble).show();
        } else {
            $(notificationBubble).hide();
        }
    }
};

function updateNotificationCountOnError() {
    var notificationBubble = "#notification-bubble";
    $(notificationBubble).html("Error");
    $(notificationBubble).show();
}

function loadNewNotificationsOnSideViewPanel() {
    if ($("#right-sidebar").attr("is-authorized") == "false") {
        $("#notification-bubble-wrapper").remove();
    } else {
        var serviceURL = emmAdminBasePath + "/notifications?status=NEW";
        invokerUtil.get(serviceURL, updateNotificationCountOnSuccess, updateNotificationCountOnError);
        loadNewNotifications();
    }
}

function loadNewNotifications() {
    var messageSideBar = ".sidebar-messages";
    if ($("#right-sidebar").attr("is-authorized") == "false") {
        $(messageSideBar).html("
You are not authorized to view notifications.
");
    } else {
        var notifications = $("#notifications");
        var currentUser = notifications.data("currentUser");

        $.template("notification-listing", notifications.attr("src"), function (template) {
            var serviceURL = emmAdminBasePath + "/notifications?offset=0&limit=5&status=NEW";
            invokerUtil.get(
                serviceURL,
                // on success
                function (data, textStatus, jqXHR) {
                    if (jqXHR.status == 200 && data) {
                        var viewModel = {};
                        var responsePayload = JSON.parse(data);
                        if (responsePayload["notifications"]) {
                            if (responsePayload.count > 0) {
                                viewModel["notifications"] = responsePayload["notifications"];
                                viewModel["appContext"] = context;
                                $(messageSideBar).html(template(viewModel));
                            } else {
                                $(messageSideBar).html('
No new notifications found...
');
                            }
                        } else {
                            $(messageSideBar).html("
Unexpected error " +
                                "occurred while loading new notifications.
");
                        }
                    }
                },
                // on error
                function (jqXHR) {
                    if (jqXHR.status = 500) {
                        $(messageSideBar).html("
Unexpected error occurred while trying " +
                            "to retrieve any new notifications.
");
                    }
                }
            );
        });
    }
}

/**
 * Toggle function for
 * notification listing sidebar.
 * @return {Null}
 */
$.sidebar_toggle = function (action, target, container) {
    var elem = '[data-toggle=sidebar]',
        button,
        containerOffsetLeft,
        containerOffsetRight,
        targetOffsetLeft,
        targetOffsetRight,
        targetWidth,
        targetSide,
        relationship,
        pushType,
        buttonParent;

    var sidebar_window = {
        update: function (target, container, button) {
            containerOffsetLeft = $(container).data('offset-left') ? $(container).data('offset-left') : 0;
            containerOffsetRight = $(container).data('offset-right') ? $(container).data('offset-right') : 0;
            targetOffsetLeft = $(target).data('offset-left') ? $(target).data('offset-left') : 0;
            targetOffsetRight = $(target).data('offset-right') ? $(target).data('offset-right') : 0;
            targetWidth = $(target).data('width');
            targetSide = $(target).data("side");
            pushType = $(container).parent().is('body') == true ? 'padding' : 'margin';

            if (button !== undefined) {
                relationship = button.attr('rel') ? button.attr('rel') : '';
                buttonParent = $(button).parent();
            }
        },

        show: function () {
            if ($(target).data('sidebar-fixed') == true) {
                $(target).height($(window).height() - $(target).data('fixed-offset'));
            }
            $(target).trigger('show.sidebar');
            if (targetWidth !== undefined) {
                $(target).css('width', targetWidth);
            }
            $(target).addClass('toggled');
            if (button !== undefined) {
                if (relationship !== '') {
                    // Removing active class from all relative buttons
                    $(elem + '[rel=' + relationship + ']:not([data-handle=close])').removeClass("active");
                    $(elem + '[rel=' + relationship + ']:not([data-handle=close])').attr('aria-expanded', 'false');
                }
                // Adding active class to button
                if (button.attr('data-handle') !== 'close') {
                    button.addClass("active");
                    button.attr('aria-expanded', 'true');
                }
                if (buttonParent.is('li')) {
                    if (relationship !== '') {
                        $(elem + '[rel=' + relationship + ']:not([data-handle=close])').parent().removeClass("active");
                        $(elem + '[rel=' + relationship + ']:not([data-handle=close])').parent().attr('aria-expanded', 'false');
                    }
                    buttonParent.addClass("active");
                    buttonParent.attr('aria-expanded', 'true');
                }
            }
            // Sidebar open function
            if (targetSide == 'left') {
                if ((button !== undefined) && (button.attr('data-container-divide'))) {
                    $(container).css(pushType + '-' + targetSide, targetWidth + targetOffsetLeft);
                }
                $(target).css(targetSide, targetOffsetLeft);
            } else if (targetSide == 'right') {
                if ((button !== undefined) && (button.attr('data-container-divide'))) {
                    $(container).css(pushType + '-' + targetSide, targetWidth + targetOffsetRight);
                }
                $(target).css(targetSide, targetOffsetRight);
            }
            $(target).trigger('shown.sidebar');
        },

        hide: function () {
            $(target).trigger('hide.sidebar');
            $(target).removeClass('toggled');
            if (button !== undefined) {
                if (relationship !== '') {
                    // Removing active class from all relative buttons
                    $(elem + '[rel=' + relationship + ']:not([data-handle=close])').removeClass("active");
                    $(elem + '[rel=' + relationship + ']:not([data-handle=close])').attr('aria-expanded', 'false');
                }
                // Removing active class from button
                if (button.attr('data-handle') !== 'close') {
                    button.removeClass("active");
                    button.attr('aria-expanded', 'false');
                }
                if ($(button).parent().is('li')) {
                    if (relationship !== '') {
                        $(elem + '[rel=' + relationship + ']:not([data-handle=close])').parent().removeClass("active");
                        $(elem + '[rel=' + relationship + ']:not([data-handle=close])').parent().attr('aria-expanded', 'false');
                    }
                }
            }
            // Sidebar close function
            if (targetSide == 'left') {
                if ((button !== undefined) && (button.attr('data-container-divide'))) {
                    $(container).css(pushType + '-' + targetSide, targetOffsetLeft);
                }
                $(target).css(targetSide, -Math.abs(targetWidth + targetOffsetLeft));
            } else if (targetSide == 'right') {
                if ((button !== undefined) && (button.attr('data-container-divide'))) {
                    $(container).css(pushType + '-' + targetSide, targetOffsetRight);
                }
                $(target).css(targetSide, -Math.abs(targetWidth + targetOffsetRight));
            }
            $(target).trigger('hidden.sidebar');
        }
    };
    if (action === 'show') {
        sidebar_window.update(target, container);
        sidebar_window.show();
    }
    if (action === 'hide') {
        sidebar_window.update(target, container);
        sidebar_window.hide();
    }
    // binding click function
    var body = 'body';
    $(body).off('click', elem);
    $(body).on('click', elem, function (e) {
        e.preventDefault();
        button = $(this);
        container = button.data('container');
        target = button.data('target');
        sidebar_window.update(target, container, button);
        /**
         * Sidebar function on data container divide
         * @return {Null}
         */
        if (button.attr('aria-expanded') == 'false') {
            sidebar_window.show();
        } else if (button.attr('aria-expanded') == 'true') {
            sidebar_window.hide();
        }
    });
};

$.fn.collapse_nav_sub = function () {
    var navSelector = 'ul.nav';

    if (!$(navSelector).hasClass('collapse-nav-sub')) {
        $(navSelector + ' > li', this).each(function () {
            var position = $(this).offset().left - $(this).parent().scrollLeft();
            $(this).attr('data-absolute-position', (position + 5));
        });

        $(navSelector + ' li', this).each(function () {
            if ($('ul', this).length !== 0) {
                $(this).addClass('has-sub');
            }
        });

        $(navSelector + ' > li', this).each(function () {
            $(this).css({
                'left': $(this).data('absolute-position'),
                'position': 'absolute'
            });
        });

        $(navSelector + ' li.has-sub', this).on('click', function () {
            var elem = $(this);
            if (elem.attr('aria-expanded') !== 'true') {
                elem.siblings().fadeOut(100, function () {
                    elem.animate({'left': '15'}, 200, function () {
                        $(elem).first().children('ul').fadeIn(200);
                    });
                });
                elem.siblings().attr('aria-expanded', 'false');
                elem.attr('aria-expanded', 'true');
            } else {
                $(elem).first().children('ul').fadeOut(100, function () {
                    elem.animate({'left': $(elem).data('absolute-position')}, 200, function () {
                        elem.siblings().fadeIn(100);
                    });
                });
                elem.siblings().attr('aria-expanded', 'false');
                elem.attr('aria-expanded', 'false');
            }
        });

        $(navSelector + ' > li.has-sub ul', this).on('click', function (e) {
            e.stopPropagation();
        });
        $(navSelector).addClass('collapse-nav-sub');
    }
};

$(".download-link").click(function(){
    toggleEnrollment();
});

$(document).ready(function () {
    $.sidebar_toggle();
    if (typeof $.fn.collapse == 'function') {
        $('.navbar-collapse.tiles').on('shown.bs.collapse', function () {
            $(this).collapse_nav_sub();
        });
    }

    loadNewNotificationsOnSideViewPanel();
    $("#right-sidebar").on("click", ".new-notification", function () {
        var notificationId = $(this).data("id");
        var redirectUrl = $(this).data("url");
        var markAsReadNotificationsEpr = emmAdminBasePath + "/notifications/" + notificationId + "/mark-checked";
        var messageSideBar = ".sidebar-messages";

        invokerUtil.put(
            markAsReadNotificationsEpr,
            null,
            // on success
            function (data) {
                data = JSON.parse(data);
                if (data.statusCode == responseCodes["ACCEPTED"]) {
                    location.href = redirectUrl;
                }
            },
            // on error
            function () {
                var content = "

Warning
" +
                    "
Unexpected error occurred while loading notification. Please refresh the page and" +
                    " try again

";
                $(messageSideBar).html(content);
            }
        );
    });
});
<commit_msg>Fix for inconsistant notification message<commit_after>/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var modalPopup = ".modal",
    modalPopupContainer = modalPopup + " .modal-content",
    modalPopupContent = modalPopup + " .modal-content";

var emmAdminBasePath = "/api/device-mgt/v1.0";

//function openCollapsedNav() {
//    $(".wr-hidden-nav-toggle-btn").addClass("active");
//    $("#hiddenNav").slideToggle("slideDown", function () {
//        if ($(this).css("display") == "none") {
//            $(".wr-hidden-nav-toggle-btn").removeClass("active");
//        }
//    });
//}

/*
 * set popup maximum height function.
 */
function setPopupMaxHeight() {
    var maxHeight = "max-height";
    var marginTop = "margin-top";
    var body = "body";
    $(modalPopupContent).css(maxHeight, ($(body).height() - ($(body).height() / 100 * 30)));
    $(modalPopupContainer).css(marginTop, (-($(modalPopupContainer).height() / 2)));
}

/*
 * show popup function.
 */
function showPopup() {
    $(modalPopup).modal('show');
}

/*
 * hide popup function.
 */
function hidePopup() {
    $(modalPopupContent).html("");
    $(modalPopupContent).removeClass("operation-data");
    $(modalPopup).modal('hide');
    $('body').removeClass('modal-open').css('padding-right','0px');
    $('.modal-backdrop').remove();
}

/*
 * QR-code generation function.
 */
function generateQRCode(qrCodeClass) {
    var enrollmentURL = $("#qr-code-modal").data("enrollment-url");
    $(qrCodeClass).qrcode({
        text: enrollmentURL,
        width: 200,
        height: 200
    });
}

function toggleEnrollment() {
    $(".modal-content").html($("#qr-code-modal").html());
    generateQRCode(".modal-content .qr-code");
    modalDialog.show();
}

var updateNotificationCountOnSuccess = function (data, textStatus, jqXHR) {
    var notificationBubble = "#notification-bubble";
    if (jqXHR.status == 200 && data) {
        var responsePayload = JSON.parse(data);
        var newNotificationsCount = responsePayload["count"];
        if (newNotificationsCount > 0) {
            $(notificationBubble).html(newNotificationsCount);
            $(notificationBubble).show();
        } else {
            $(notificationBubble).hide();
        }
    }
};

function updateNotificationCountOnError() {
    var notificationBubble = "#notification-bubble";
    $(notificationBubble).html("Error");
    $(notificationBubble).show();
}

function loadNewNotificationsOnSideViewPanel() {
    if ($("#right-sidebar").attr("is-authorized") == "false") {
        $("#notification-bubble-wrapper").remove();
    } else {
        var serviceURL = emmAdminBasePath + "/notifications?status=NEW";
        invokerUtil.get(serviceURL, updateNotificationCountOnSuccess, updateNotificationCountOnError);
        loadNewNotifications();
    }
}

function loadNewNotifications() {
    var messageSideBar = ".sidebar-messages";
    if ($("#right-sidebar").attr("is-authorized") == "false") {
        $(messageSideBar).html("
You are not authorized to view notifications.
");
    } else {
        var notifications = $("#notifications");
        var currentUser = notifications.data("currentUser");

        $.template("notification-listing", notifications.attr("src"), function (template) {
            var serviceURL = emmAdminBasePath + "/notifications?offset=0&limit=5&status=NEW";
            invokerUtil.get(
                serviceURL,
                // on success
                function (data, textStatus, jqXHR) {
                    if (jqXHR.status == 200 && data) {
                        var viewModel = {};
                        var responsePayload = JSON.parse(data);
                        if (responsePayload["notifications"]) {
                            if (responsePayload.count > 0) {
                                viewModel["notifications"] = responsePayload["notifications"];
                                viewModel["appContext"] = context;
                                $(messageSideBar).html(template(viewModel));
                            } else {
                                $(messageSideBar).html("
No New Notifications
" +
                                    "
" +
                                    "Check this section for error notifications
related to device operations" +
                                    "
");
                            }
                        } else {
                            $(messageSideBar).html("
Unexpected error " +
                                "occurred while loading new notifications.
");
                        }
                    }
                },
                // on error
                function (jqXHR) {
                    if (jqXHR.status = 500) {
                        $(messageSideBar).html("
Unexpected error occurred while trying " +
                            "to retrieve any new notifications.
");
                    }
                }
            );
        });
    }
}

/**
 * Toggle function for
 * notification listing sidebar.
 * @return {Null}
 */
$.sidebar_toggle = function (action, target, container) {
    var elem = '[data-toggle=sidebar]',
        button,
        containerOffsetLeft,
        containerOffsetRight,
        targetOffsetLeft,
        targetOffsetRight,
        targetWidth,
        targetSide,
        relationship,
        pushType,
        buttonParent;

    var sidebar_window = {
        update: function (target, container, button) {
            containerOffsetLeft = $(container).data('offset-left') ? $(container).data('offset-left') : 0;
            containerOffsetRight = $(container).data('offset-right') ? $(container).data('offset-right') : 0;
            targetOffsetLeft = $(target).data('offset-left') ? $(target).data('offset-left') : 0;
            targetOffsetRight = $(target).data('offset-right') ? $(target).data('offset-right') : 0;
            targetWidth = $(target).data('width');
            targetSide = $(target).data("side");
            pushType = $(container).parent().is('body') == true ? 'padding' : 'margin';

            if (button !== undefined) {
                relationship = button.attr('rel') ? button.attr('rel') : '';
                buttonParent = $(button).parent();
            }
        },

        show: function () {
            if ($(target).data('sidebar-fixed') == true) {
                $(target).height($(window).height() - $(target).data('fixed-offset'));
            }
            $(target).trigger('show.sidebar');
            if (targetWidth !== undefined) {
                $(target).css('width', targetWidth);
            }
            $(target).addClass('toggled');
            if (button !== undefined) {
                if (relationship !== '') {
                    // Removing active class from all relative buttons
                    $(elem + '[rel=' + relationship + ']:not([data-handle=close])').removeClass("active");
                    $(elem + '[rel=' + relationship + ']:not([data-handle=close])').attr('aria-expanded', 'false');
                }
                // Adding active class to button
                if (button.attr('data-handle') !== 'close') {
                    button.addClass("active");
                    button.attr('aria-expanded', 'true');
                }
                if (buttonParent.is('li')) {
                    if (relationship !== '') {
                        $(elem + '[rel=' + relationship + ']:not([data-handle=close])').parent().removeClass("active");
                        $(elem + '[rel=' + relationship + ']:not([data-handle=close])').parent().attr('aria-expanded', 'false');
                    }
                    buttonParent.addClass("active");
                    buttonParent.attr('aria-expanded', 'true');
                }
            }
            // Sidebar open function
            if (targetSide == 'left') {
                if ((button !== undefined) && (button.attr('data-container-divide'))) {
                    $(container).css(pushType + '-' + targetSide, targetWidth + targetOffsetLeft);
                }
                $(target).css(targetSide, targetOffsetLeft);
            } else if (targetSide == 'right') {
                if ((button !== undefined) && (button.attr('data-container-divide'))) {
                    $(container).css(pushType + '-' + targetSide, targetWidth + targetOffsetRight);
                }
                $(target).css(targetSide, targetOffsetRight);
            }
            $(target).trigger('shown.sidebar');
        },

        hide: function () {
            $(target).trigger('hide.sidebar');
            $(target).removeClass('toggled');
            if (button !== undefined) {
                if (relationship !== '') {
                    // Removing active class from all relative buttons
                    $(elem + '[rel=' + relationship + ']:not([data-handle=close])').removeClass("active");
                    $(elem + '[rel=' + relationship + ']:not([data-handle=close])').attr('aria-expanded', 'false');
                }
                // Removing active class from button
                if (button.attr('data-handle') !== 'close') {
                    button.removeClass("active");
                    button.attr('aria-expanded', 'false');
                }
                if ($(button).parent().is('li')) {
                    if (relationship !== '') {
                        $(elem + '[rel=' + relationship + ']:not([data-handle=close])').parent().removeClass("active");
                        $(elem + '[rel=' + relationship + ']:not([data-handle=close])').parent().attr('aria-expanded', 'false');
                    }
                }
            }
            // Sidebar close function
            if (targetSide == 'left') {
                if ((button !== undefined) && (button.attr('data-container-divide'))) {
                    $(container).css(pushType + '-' + targetSide, targetOffsetLeft);
                }
                $(target).css(targetSide, -Math.abs(targetWidth + targetOffsetLeft));
            } else if (targetSide == 'right') {
                if ((button !== undefined) && (button.attr('data-container-divide'))) {
                    $(container).css(pushType + '-' + targetSide, targetOffsetRight);
                }
                $(target).css(targetSide, -Math.abs(targetWidth + targetOffsetRight));
            }
            $(target).trigger('hidden.sidebar');
        }
    };
    if (action === 'show') {
        sidebar_window.update(target, container);
        sidebar_window.show();
    }
    if (action === 'hide') {
        sidebar_window.update(target, container);
        sidebar_window.hide();
    }
    // binding click function
    var body = 'body';
    $(body).off('click', elem);
    $(body).on('click', elem, function (e) {
        e.preventDefault();
        button = $(this);
        container = button.data('container');
        target = button.data('target');
        sidebar_window.update(target, container, button);
        /**
         * Sidebar function on data container divide
         * @return {Null}
         */
        if (button.attr('aria-expanded') == 'false') {
            sidebar_window.show();
        } else if (button.attr('aria-expanded') == 'true') {
            sidebar_window.hide();
        }
    });
};

$.fn.collapse_nav_sub = function () {
    var navSelector = 'ul.nav';

    if (!$(navSelector).hasClass('collapse-nav-sub')) {
        $(navSelector + ' > li', this).each(function () {
            var position = $(this).offset().left - $(this).parent().scrollLeft();
            $(this).attr('data-absolute-position', (position + 5));
        });

        $(navSelector + ' li', this).each(function () {
            if ($('ul', this).length !== 0) {
                $(this).addClass('has-sub');
            }
        });

        $(navSelector + ' > li', this).each(function () {
            $(this).css({
                'left': $(this).data('absolute-position'),
                'position': 'absolute'
            });
        });

        $(navSelector + ' li.has-sub', this).on('click', function () {
            var elem = $(this);
            if (elem.attr('aria-expanded') !== 'true') {
                elem.siblings().fadeOut(100, function () {
                    elem.animate({'left': '15'}, 200, function () {
                        $(elem).first().children('ul').fadeIn(200);
                    });
                });
                elem.siblings().attr('aria-expanded', 'false');
                elem.attr('aria-expanded', 'true');
            } else {
                $(elem).first().children('ul').fadeOut(100, function () {
                    elem.animate({'left': $(elem).data('absolute-position')}, 200, function () {
                        elem.siblings().fadeIn(100);
                    });
                });
                elem.siblings().attr('aria-expanded', 'false');
                elem.attr('aria-expanded', 'false');
            }
        });

        $(navSelector + ' > li.has-sub ul', this).on('click', function (e) {
            e.stopPropagation();
        });
        $(navSelector).addClass('collapse-nav-sub');
    }
};

$(".download-link").click(function(){
    toggleEnrollment();
});

$(document).ready(function () {
    $.sidebar_toggle();
    if (typeof $.fn.collapse == 'function') {
        $('.navbar-collapse.tiles').on('shown.bs.collapse', function () {
            $(this).collapse_nav_sub();
        });
    }

    loadNewNotificationsOnSideViewPanel();
    $("#right-sidebar").on("click", ".new-notification", function () {
        var notificationId = $(this).data("id");
        var redirectUrl = $(this).data("url");
        var markAsReadNotificationsEpr = emmAdminBasePath + "/notifications/" + notificationId + "/mark-checked";
        var messageSideBar = ".sidebar-messages";

        invokerUtil.put(
            markAsReadNotificationsEpr,
            null,
            // on success
            function (data) {
                data = JSON.parse(data);
                if (data.statusCode == responseCodes["ACCEPTED"]) {
                    location.href = redirectUrl;
                }
            },
            // on error
            function () {
                var content = "

Warning
" +
                    "
Unexpected error occurred while loading notification. Please refresh the page and" +
                    " try again

";
                $(messageSideBar).html(content);
            }
        );
    });
});
<|endoftext|>


<commit_before>document.getElementById("id_logic_level_version").innerHTML="Logic level version: 2017.11.01.1";

var canvas = document.getElementById("id_canvas");
var context = canvas.getContext("2d");

context.beginPath();
var w = canvas.getAttribute("width");
var h = canvas.getAttribute("height");

context.arc(w/2, h/2,10,0,2* Math.PI);
context.stroke();<commit_msg>culoarea cercului<commit_after>document.getElementById("id_logic_level_version").innerHTML="Logic level version: 2017.11.01.1";

var canvas = document.getElementById("id_canvas");
var context = canvas.getContext("2d");

context.beginPath();
var w = canvas.getAttribute("width");
var h = canvas.getAttribute("height");

context.arc(w/2, h/2,10,0,2* Math.PI);
context.strokeStyle="red";
context.stroke();<|endoftext|>


<commit_before>module.exports = {
  /**
   * Generate a cache key unique to this query
   * @param {superagent} agent
   * @param {object} reg
   * @param {object} cProps
   */
  keygen: function(agent, req, cProps){
    var cleanParams = null;
    var cleanOptions = null;
    var params = this.getQueryParams(req);
    var options = this.getHeaderOptions(req);
    if(cProps.pruneParams || cProps.pruneOptions){
      cleanParams = (cProps.pruneParams) ? this.pruneObj(this.cloneObject(params), cProps.pruneParams) : params;
      cleanOptions = (cProps.pruneOptions) ? this.pruneObj(this.cloneObject(options), cProps.pruneOptions, true) : options;
    }
    return JSON.stringify({
      nameSpace: agent.cache.nameSpace,
      method: req.method,
      uri: req.url,
      params: cleanParams || params || null,
      options: cleanOptions || options || null
    });
  },

  /**
   * Find and extract query params
   * @param {object} reg
   */
  getQueryParams: function(req){
    if(req && req.qs && !this.isEmpty(req.qs)){
      return req.qs;
    }
    else if(req && req.qsRaw){
      return this.arrayToObj(req.qsRaw);
    }
    else if(req && req.req){
      return this.stringToObj(req.req.path);
    }
    else if(req && req._query){
      return this.stringToObj(req._query.join('&'));
    }
    return null;
  },

  /**
   * Find and extract headers
   * @param {object} reg
   */
  getHeaderOptions: function(req){
    //I have to remove the User-Agent header ever since superagent 1.7.0
    if(req && req._header){
      return this.pruneObj(req._header, ['User-Agent', 'user-agent']);
    }
    else if(req && req.req && req.req._headers){
      return this.pruneObj(req.req._headers, ['User-Agent', 'user-agent']);
    }
    else if(req && req.header){
      return this.pruneObj(req.header, ['User-Agent', 'user-agent']);
    }
    return null;
  },

  /**
   * Convert an array to an object
   * @param {array} arr
   */
  arrayToObj: function(arr){
    if(arr && arr.length){
      var obj = {};
      for(var i = 0; i < arr.length; i++){
        var str = arr[i];
        var kvArray = str.split('&');
        for(var j = 0; j < kvArray.length; j++){
          var kvString = kvArray[j].split('=');
          obj[kvString[0]] = kvString[1];
        }
      }
      return obj;
    }
    return null;
  },

  /**
   * Convert a string to an object
   * @param {string} str
   */
  stringToObj: function(str){
    if(str){
      var obj = {};
      if(~str.indexOf('?')){
        var strs = str.split('?');
        str = strs[1];
      }
      var kvArray = str.split('&');
      for(var i = 0; i < kvArray.length; i++){
        var kvString = kvArray[i].split('=');
        obj[kvString[0]] = kvString[1];
      }
      return obj;
    }
    return null;
  },

  /**
   * Remove properties from an object
   * @param {object} obj
   * @param {array} props
   * @param {boolean} isOptions
   */
  pruneObj: function(obj, props, isOptions){
    for(var i = 0; i < props.length; i++){
      var prop = props[i];
      if(isOptions){
        delete obj[prop.toLowerCase()];
      }
      delete obj[prop];
    }
    return obj;
  },

  /**
   * Simplify superagent's http response object
   * @param {object} r
   */
  gutResponse: function(r){
    var newResponse = {};
    newResponse.body = r.body;
    newResponse.text = r.text;
    newResponse.headers = r.headers;
    newResponse.statusCode = r.statusCode;
    newResponse.status = r.status;
    newResponse.ok = r.ok;
    return newResponse;
  },

  /**
   * Determine whether a value is considered empty
   * @param {*} val
   */
  isEmpty: function(val){
    return (val === false || val === null || (typeof val == 'object' && Object.keys(val).length == 0));
  },

  /**
   * Return a clone of an object
   * @param {object} obj
   */
  cloneObject: function(obj){
    var newObj = {};
    for(var attr in obj) {
      if (obj.hasOwnProperty(attr)){
        newObj[attr] = obj[attr];
      }
    }
    return newObj;
  },

  handlePendingRequests: function(curProps, superagent, key, err, response){
    if(curProps.preventDuplicateCalls){
      if(superagent.pendingRequests[key] && (!this.isEmpty(response) || curProps.cacheWhenEmpty)){
        var self = this;
        var pendingRequests = superagent.pendingRequests[key];
        pendingRequests.forEach(function (cb){
          self.callbackExecutor(cb, err, response, key);
        });
      }
      delete superagent.pendingRequests[key];
    }
  },

  /**
   * Reset superagent-cache's default query properties using the defaults object
   * @param {object} d
   */
  resetProps: function(d){
    return {
      doQuery: (typeof d.doQuery === 'boolean') ? d.doQuery : true,
      cacheWhenEmpty: (typeof d.cacheWhenEmpty === 'boolean') ? d.cacheWhenEmpty : true,
      prune: d.prune,
      pruneParams: d.pruneParams,
      pruneOptions: d.pruneOptions,
      responseProp: d.responseProp,
      expiration: d.expiration,
      preventDuplicateCalls: d.preventDuplicateCalls,
      backgroundRefresh: d.backgroundRefresh
    };
  },

  /**
   * Generate a background refresh query identical to the current query
   * @param {superagent} agent
   * @param {object} curProps
   */
  getBackgroundRefreshFunction: function(agent, curProps){
    return function(key, cb){
      key = JSON.parse(key);
      var method = key.method.toLowerCase();
      var request = agent[method](key.uri)
        .doQuery(curProps.doQuery)
        .pruneParams(curProps.pruneParams)
        .pruneOptions(curProps.pruneOptions)
        .prune(curProps.prune)
        .responseProp(curProps.responseProp)
        .expiration(curProps.expiration)
        .cacheWhenEmpty(curProps.cacheWhenEmpty);
      if(key.params){
        request.query(key.params)
      }
      if(key.options){
        request.set(key.options);
      }
      request.end(cb);
    }
  },

  /**
   * Handle the varying number of callback output params
   * @param {function} cb
   * @param {object} err
   * @param {object} response
   * @param {string} key
   */
  callbackExecutor: function(cb, err, response, key){
    if(cb.length === 1){
      cb(response);
    }
    else if(cb.length > 1){
      cb(err, response, key);
    }
    else{
      throw new Error('UnsupportedCallbackException: Your .end() callback must pass at least one argument.');
    }
  }
}
<commit_msg>Adding forceUpdate consumption to the defaults object.<commit_after>module.exports = {
  /**
   * Generate a cache key unique to this query
   * @param {superagent} agent
   * @param {object} reg
   * @param {object} cProps
   */
  keygen: function(agent, req, cProps){
    var cleanParams = null;
    var cleanOptions = null;
    var params = this.getQueryParams(req);
    var options = this.getHeaderOptions(req);
    if(cProps.pruneParams || cProps.pruneOptions){
      cleanParams = (cProps.pruneParams) ? this.pruneObj(this.cloneObject(params), cProps.pruneParams) : params;
      cleanOptions = (cProps.pruneOptions) ? this.pruneObj(this.cloneObject(options), cProps.pruneOptions, true) : options;
    }
    return JSON.stringify({
      nameSpace: agent.cache.nameSpace,
      method: req.method,
      uri: req.url,
      params: cleanParams || params || null,
      options: cleanOptions || options || null
    });
  },

  /**
   * Find and extract query params
   * @param {object} reg
   */
  getQueryParams: function(req){
    if(req && req.qs && !this.isEmpty(req.qs)){
      return req.qs;
    }
    else if(req && req.qsRaw){
      return this.arrayToObj(req.qsRaw);
    }
    else if(req && req.req){
      return this.stringToObj(req.req.path);
    }
    else if(req && req._query){
      return this.stringToObj(req._query.join('&'));
    }
    return null;
  },

  /**
   * Find and extract headers
   * @param {object} reg
   */
  getHeaderOptions: function(req){
    //I have to remove the User-Agent header ever since superagent 1.7.0
    if(req && req._header){
      return this.pruneObj(req._header, ['User-Agent', 'user-agent']);
    }
    else if(req && req.req && req.req._headers){
      return this.pruneObj(req.req._headers, ['User-Agent', 'user-agent']);
    }
    else if(req && req.header){
      return this.pruneObj(req.header, ['User-Agent', 'user-agent']);
    }
    return null;
  },

  /**
   * Convert an array to an object
   * @param {array} arr
   */
  arrayToObj: function(arr){
    if(arr && arr.length){
      var obj = {};
      for(var i = 0; i < arr.length; i++){
        var str = arr[i];
        var kvArray = str.split('&');
        for(var j = 0; j < kvArray.length; j++){
          var kvString = kvArray[j].split('=');
          obj[kvString[0]] = kvString[1];
        }
      }
      return obj;
    }
    return null;
  },

  /**
   * Convert a string to an object
   * @param {string} str
   */
  stringToObj: function(str){
    if(str){
      var obj = {};
      if(~str.indexOf('?')){
        var strs = str.split('?');
        str = strs[1];
      }
      var kvArray = str.split('&');
      for(var i = 0; i < kvArray.length; i++){
        var kvString = kvArray[i].split('=');
        obj[kvString[0]] = kvString[1];
      }
      return obj;
    }
    return null;
  },

  /**
   * Remove properties from an object
   * @param {object} obj
   * @param {array} props
   * @param {boolean} isOptions
   */
  pruneObj: function(obj, props, isOptions){
    for(var i = 0; i < props.length; i++){
      var prop = props[i];
      if(isOptions){
        delete obj[prop.toLowerCase()];
      }
      delete obj[prop];
    }
    return obj;
  },

  /**
   * Simplify superagent's http response object
   * @param {object} r
   */
  gutResponse: function(r){
    var newResponse = {};
    newResponse.body = r.body;
    newResponse.text = r.text;
    newResponse.headers = r.headers;
    newResponse.statusCode = r.statusCode;
    newResponse.status = r.status;
    newResponse.ok = r.ok;
    return newResponse;
  },

  /**
   * Determine whether a value is considered empty
   * @param {*} val
   */
  isEmpty: function(val){
    return (val === false || val === null || (typeof val == 'object' && Object.keys(val).length == 0));
  },

  /**
   * Return a clone of an object
   * @param {object} obj
   */
  cloneObject: function(obj){
    var newObj = {};
    for(var attr in obj) {
      if (obj.hasOwnProperty(attr)){
        newObj[attr] = obj[attr];
      }
    }
    return newObj;
  },

  handlePendingRequests: function(curProps, superagent, key, err, response){
    if(curProps.preventDuplicateCalls){
      if(superagent.pendingRequests[key] && (!this.isEmpty(response) || curProps.cacheWhenEmpty)){
        var self = this;
        var pendingRequests = superagent.pendingRequests[key];
        pendingRequests.forEach(function (cb){
          self.callbackExecutor(cb, err, response, key);
        });
      }
      delete superagent.pendingRequests[key];
    }
  },

  /**
   * Reset superagent-cache's default query properties using the defaults object
   * @param {object} d
   */
  resetProps: function(d){
    return {
      doQuery: (typeof d.doQuery === 'boolean') ? d.doQuery : true,
      cacheWhenEmpty: (typeof d.cacheWhenEmpty === 'boolean') ? d.cacheWhenEmpty : true,
      prune: d.prune,
      pruneParams: d.pruneParams,
      pruneOptions: d.pruneOptions,
      responseProp: d.responseProp,
      expiration: d.expiration,
      forceUpdate: d.forceUpdate,
      preventDuplicateCalls: d.preventDuplicateCalls,
      backgroundRefresh: d.backgroundRefresh
    };
  },

  /**
   * Generate a background refresh query identical to the current query
   * @param {superagent} agent
   * @param {object} curProps
   */
  getBackgroundRefreshFunction: function(agent, curProps){
    return function(key, cb){
      key = JSON.parse(key);
      var method = key.method.toLowerCase();
      var request = agent[method](key.uri)
        .doQuery(curProps.doQuery)
        .pruneParams(curProps.pruneParams)
        .pruneOptions(curProps.pruneOptions)
        .prune(curProps.prune)
        .responseProp(curProps.responseProp)
        .expiration(curProps.expiration)
        .cacheWhenEmpty(curProps.cacheWhenEmpty);
      if(key.params){
        request.query(key.params)
      }
      if(key.options){
        request.set(key.options);
      }
      request.end(cb);
    }
  },

  /**
   * Handle the varying number of callback output params
   * @param {function} cb
   * @param {object} err
   * @param {object} response
   * @param {string} key
   */
  callbackExecutor: function(cb, err, response, key){
    if(cb.length === 1){
      cb(response);
    }
    else if(cb.length > 1){
      cb(err, response, key);
    }
    else{
      throw new Error('UnsupportedCallbackException: Your .end() callback must pass at least one argument.');
    }
  }
}
<|endoftext|>