<commit_before>/**
 * JavaScript file for the "run" page in the browser.
 *
 * @since 0.1.0
 * @package TestSwarm
 */
(function ( $, SWARM, undefined ) {
	var currRunId, currRunUrl, testTimeout, pauseTimer, cmds, errorOut;

	function msg( txt ) {
		$( "#msg" ).html( txt );
	}

	function log( txt ) {
		$( "#history" ).prepend( "
" +
			new Date().toString().replace( /^\w+ /, "" ).replace( /:[^:]+$/, "" ) +
			": " + txt + "
" );
		msg( txt );
	}

	/**
	 * Softly validate the SWARM object
	 */
	if ( !SWARM.client_id || !SWARM.client ) {
		$( function() {
			msg( "Error: No client id configured! Aborting." );
		});
		return;
	}

	errorOut = 0;
	cmds = {
		reload: function () {
			window.location.reload();
		}
	};

	function retrySend( query, retry, ok ) {
		$.ajax({
			type: "POST",
			url: SWARM.web.contextpath,
			timeout: 10000,
			cache: false,
			data: query,
			dataType: "json",
			success: function () {
				errorOut = 0;
				ok.apply( this, arguments );
			},
			error: function () {
				if ( errorOut > 4 ) {
					cmds.reload();
				} else {
					errorOut += 1;
					msg( "Error connecting to server, retrying..." );
					setTimeout( retry, 15000 );
				}
			}
		});
	}

	function getTests() {
		if ( currRunId === undefined ) {
			log( "Connected to the swarm." );
		}

		currRunId = 0;
		currRunUrl = false;

		msg( "Querying for more tests to run..." );
		retrySend( "action=getrun&client_id=" + SWARM.client_id, getTests, runTests );
	}

	function cancelTest() {
		if ( testTimeout ) {
			clearTimeout( testTimeout );
			testTimeout = 0;
		}

		$( "iframe" ).remove();
	}

	function testTimedout() {
		cancelTest();
		retrySend( "action=saverun&fail=-1&total=-1&results=Test%20Timed%20Out.&run_id="
			+ currRunId + "&client_id=" + SWARM.client_id,
			testTimedout, function ( data ) {
				if ( data === "ok" ) {
					SWARM.runDone();
				} else {
					getTests();
				}
			} );
	}

	/**
	 * @param data Object Data returned by action=getrun
	 */
	function runTests( data ) {
		var norun_msg, timeLeft, runInfo, params, iframe;

		if ( !$.isPlainObject( data ) ) {
			// Handle session timeout, where server sends back "Username required."
			// Handle TestSwarm reset, where server sends back "Client doesn't exist."
			if ( /^Username required|^Client doesn/.test( data ) ) {
				cmds.reload();
				return;
			}
		}

		// Handle configuration update
		if ( data.swarmUpdate ) {

			// Refresh control
			if ( SWARM.client.refresh_control < data.swarmUpdate.client.refresh_control ) {
				cmds.reload();
				return;
			}

			$.extend( SWARM, data.swarmUpdate );
		}

		// Handle run
		runInfo = data.runInfo;
		if ( runInfo ) {
			currRunId = runInfo.id;
			currRunUrl = runInfo.url;

			log( "Running " + ( runInfo.desc || "" ) + " tests..." );

			params = "run_id=" + currRunId + "&client_id=" + SWARM.client_id;
			iframe = document.createElement( "iframe" );
			iframe.width = 1000;
			iframe.height = 600;
			iframe.className = "test";
			iframe.src = currRunUrl + (currRunUrl.indexOf( "?" ) > -1 ? "&" : "?") +
				"_=" + new Date().getTime() + "&swarmURL=" +
				encodeURIComponent(window.location.protocol + "//" + window.location.host + window.location.pathname + "?" + params + "&action=" );
			$( "#iframes" ).append( iframe );

			// Timeout after a period of time
			testTimeout = setTimeout( testTimedout, SWARM.client.timeout_rate * 1000 );

		} else {

			clearTimeout( pauseTimer );

			norun_msg = data.timeoutMsg || "No new tests to run.";

			msg(norun_msg);

			// If we just completed a run, do a cooldown_rate timeout before we fetch the next
			// run (if there is one). If we just completed a cooldown a no runs where available,
			// go for a (usually longer, depending on configuration) update_rate timeout instead.
			timeLeft = currRunUrl ? SWARM.client.cooldown_rate : SWARM.client.update_rate;

			pauseTimer = setTimeout(function leftTimer() {
				msg(norun_msg + " Getting more in " + timeLeft + " seconds." );
				if ( timeLeft >= 1 ) {
					timeLeft -= 1;
					pauseTimer = setTimeout( leftTimer, 1000 );
				} else {
					timeLeft -= 1;
					getTests();
				}
			}, 1000);

		}
	}

	// Needs to be a publicly exposed function,
	// so that when inject.js does a <form> submission,
	// it can call this from within the frame
	// as window.parent.SWARM.runDone();
	SWARM.runDone = function () {
		cancelTest();
		runTests({ timeoutMsg: "Cooling down." });
	}

	function handleMessage(e) {
		e = e || window.event;
		retrySend( e.data, function () {
			handleMessage(e);
		}, SWARM.runDone );
	}

	/**
	 * Bind
	 */
	if ( window.addEventListener ) {
		window.addEventListener( "message", handleMessage, false );
	} else if ( window.attachEvent ) {
		window.attachEvent( "onmessage", handleMessage );
	}

	$( document).ready( getTests );

}( jQuery, SWARM ) );
<commit_msg>adding missing semi-colon in run.js from 5f16c1feb3375fd70143c42f43f3247240ef160a<commit_after>/**
 * JavaScript file for the "run" page in the browser.
 *
 * @since 0.1.0
 * @package TestSwarm
 */
(function ( $, SWARM, undefined ) {
	var currRunId, currRunUrl, testTimeout, pauseTimer, cmds, errorOut;

	function msg( txt ) {
		$( "#msg" ).html( txt );
	}

	function log( txt ) {
		$( "#history" ).prepend( "
" +
			new Date().toString().replace( /^\w+ /, "" ).replace( /:[^:]+$/, "" ) +
			": " + txt + "
" );
		msg( txt );
	}

	/**
	 * Softly validate the SWARM object
	 */
	if ( !SWARM.client_id || !SWARM.client ) {
		$( function() {
			msg( "Error: No client id configured! Aborting." );
		});
		return;
	}

	errorOut = 0;
	cmds = {
		reload: function () {
			window.location.reload();
		}
	};

	function retrySend( query, retry, ok ) {
		$.ajax({
			type: "POST",
			url: SWARM.web.contextpath,
			timeout: 10000,
			cache: false,
			data: query,
			dataType: "json",
			success: function () {
				errorOut = 0;
				ok.apply( this, arguments );
			},
			error: function () {
				if ( errorOut > 4 ) {
					cmds.reload();
				} else {
					errorOut += 1;
					msg( "Error connecting to server, retrying..." );
					setTimeout( retry, 15000 );
				}
			}
		});
	}

	function getTests() {
		if ( currRunId === undefined ) {
			log( "Connected to the swarm." );
		}

		currRunId = 0;
		currRunUrl = false;

		msg( "Querying for more tests to run..." );
		retrySend( "action=getrun&client_id=" + SWARM.client_id, getTests, runTests );
	}

	function cancelTest() {
		if ( testTimeout ) {
			clearTimeout( testTimeout );
			testTimeout = 0;
		}

		$( "iframe" ).remove();
	}

	function testTimedout() {
		cancelTest();
		retrySend( "action=saverun&fail=-1&total=-1&results=Test%20Timed%20Out.&run_id="
			+ currRunId + "&client_id=" + SWARM.client_id,
			testTimedout, function ( data ) {
				if ( data === "ok" ) {
					SWARM.runDone();
				} else {
					getTests();
				}
			} );
	}

	/**
	 * @param data Object Data returned by action=getrun
	 */
	function runTests( data ) {
		var norun_msg, timeLeft, runInfo, params, iframe;

		if ( !$.isPlainObject( data ) ) {
			// Handle session timeout, where server sends back "Username required."
			// Handle TestSwarm reset, where server sends back "Client doesn't exist."
			if ( /^Username required|^Client doesn/.test( data ) ) {
				cmds.reload();
				return;
			}
		}

		// Handle configuration update
		if ( data.swarmUpdate ) {

			// Refresh control
			if ( SWARM.client.refresh_control < data.swarmUpdate.client.refresh_control ) {
				cmds.reload();
				return;
			}

			$.extend( SWARM, data.swarmUpdate );
		}

		// Handle run
		runInfo = data.runInfo;
		if ( runInfo ) {
			currRunId = runInfo.id;
			currRunUrl = runInfo.url;

			log( "Running " + ( runInfo.desc || "" ) + " tests..." );

			params = "run_id=" + currRunId + "&client_id=" + SWARM.client_id;
			iframe = document.createElement( "iframe" );
			iframe.width = 1000;
			iframe.height = 600;
			iframe.className = "test";
			iframe.src = currRunUrl + (currRunUrl.indexOf( "?" ) > -1 ? "&" : "?") +
				"_=" + new Date().getTime() + "&swarmURL=" +
				encodeURIComponent(window.location.protocol + "//" + window.location.host + window.location.pathname + "?" + params + "&action=" );
			$( "#iframes" ).append( iframe );

			// Timeout after a period of time
			testTimeout = setTimeout( testTimedout, SWARM.client.timeout_rate * 1000 );

		} else {

			clearTimeout( pauseTimer );

			norun_msg = data.timeoutMsg || "No new tests to run.";

			msg(norun_msg);

			// If we just completed a run, do a cooldown_rate timeout before we fetch the next
			// run (if there is one). If we just completed a cooldown a no runs where available,
			// go for a (usually longer, depending on configuration) update_rate timeout instead.
			timeLeft = currRunUrl ? SWARM.client.cooldown_rate : SWARM.client.update_rate;

			pauseTimer = setTimeout(function leftTimer() {
				msg(norun_msg + " Getting more in " + timeLeft + " seconds." );
				if ( timeLeft >= 1 ) {
					timeLeft -= 1;
					pauseTimer = setTimeout( leftTimer, 1000 );
				} else {
					timeLeft -= 1;
					getTests();
				}
			}, 1000);

		}
	}

	// Needs to be a publicly exposed function,
	// so that when inject.js does a <form> submission,
	// it can call this from within the frame
	// as window.parent.SWARM.runDone();
	SWARM.runDone = function () {
		cancelTest();
		runTests({ timeoutMsg: "Cooling down." });
	};

	function handleMessage(e) {
		e = e || window.event;
		retrySend( e.data, function () {
			handleMessage(e);
		}, SWARM.runDone );
	}

	/**
	 * Bind
	 */
	if ( window.addEventListener ) {
		window.addEventListener( "message", handleMessage, false );
	} else if ( window.attachEvent ) {
		window.attachEvent( "onmessage", handleMessage );
	}

	$( document).ready( getTests );

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


<commit_before>var scl_default_page = '#log';

function displayPage(id)
{
	target = id || window.location.hash || scl_default_page;
	window.location.hash = target;

	$('.container').not(target + '-cont').hide();
	$(target + '-cont').show();
}

$(
	function()
	{
		displayPage();
	}
);

<commit_msg>Minor code readability improvements.<commit_after>var scl_default_page = '#log';

function displayPage(id)
{
	target = id || window.location.hash || scl_default_page;
	window.location.hash = target;

	$('.container').hide();
	$(target + '-cont').show();
}

$(document).ready(
	function()
	{
		displayPage();
	}
);

<|endoftext|>


<commit_before>/**
 * This class provides necessary functions for Single sign on feature, which
 * enables your customers to authenticate themselves to your website using their
 * Google credentials.
 */
var bikeStore = bikeStore || {};

(function(sso) {
  /**
   * Checks if buyers pre-authorized the app to use their Wallet information to
   * checkout.
   * @param {Object} authResult Data object represents the OAuth 2.0 token.
   */
  sso.handleLoginResult = function(authResult) {
    if (authResult) {
      if (authResult['error'] == undefined) {
        gapi.auth.setToken(authResult); // Store the returned token.
        gapi.client.load('oauth2', 'v2', function() {
          bikeStore.Cookie.setAccessToken(authResult['access_token'],
            authResult['expires_at']);
          console.log(authResult);
          var request = gapi.client.oauth2.userinfo.get();
          request.execute(sso.handleEmail);
        }); // Trigger request to get the email address.
      } else {
        console.log(authResult['error']);
      }
    }
  };

  /**
   * Set email in cookie and replace header with email id.
   * @param {Object} obj Data which contain user' email id.
   */
  sso.handleEmail = function(obj) {
    bikeStore.Cookie.setEmail(obj['email']);
    $('.nav-filter').attr('class', 'nav-filter');
    $('.nav-username').html('

' +
      obj['email'] + '
' +
      '
' +
      'Logout

');
  };

  /**
   * Log out the customer from the site and reload the page.
   */
  sso.logout = function() {
    // Clear session objects associated with user profile information and reload
    // the page .
    bikeStore.Cookie.setAccessToken('', 1);
    google.wallet.online.setAccessToken('');
    $('#logout').html('');
    $.post('logout', '', function() {
      document.location.href = '/';
    });
  };
})(window.bikeStore.Sso = window.bikeStore.Sso || {});
<commit_msg>Update sso.js<commit_after>/**
 * This class provides necessary functions for Single sign on feature, which
 * enables your customers to authenticate themselves to your website using their
 * Google credentials.
 */
var bikeStore = bikeStore || {};

(function(sso) {
  /**
   * Checks if buyers pre-authorized the app to use their Wallet information to
   * checkout.
   * @param {Object} authResult Data object represents the OAuth 2.0 token.
   */
  sso.handleLoginResult = function(authResult) {
    if (authResult) {
      if (authResult['error'] == undefined) {
        gapi.auth.setToken(authResult); // Store the returned token.
        gapi.client.load('oauth2', 'v2', function() {
          bikeStore.Cookie.setAccessToken(authResult['access_token'],
            authResult['expires_at']);
          console.log(authResult);
          var request = gapi.client.oauth2.userinfo.get();
          request.execute(sso.handleEmail);
        }); // Trigger request to get the email address.
      } else {
        console.log(authResult['error']);
      }
    }
  };

  /**
   * Set email in cookie and replace header with email id.
   * @param {Object} obj Data which contain user' email id.
   */
  sso.handleEmail = function(obj) {
    bikeStore.Cookie.setEmail(obj['email']);
    $('.nav-filter').attr('class', 'nav-filter');
    $('.nav-username').html('

' +
      obj['email'] + '

 Logout

');
  }

  /**
   * Log out the customer from the site and reload the page.
   */
  sso.logout = function() {
    var access_token = bikeStore.Cookie.getAccessToken();
    var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' +
      access_token;
    // Clear session objects associated with user profile information and reload
    // the page .
    bikeStore.Cookie.setAccessToken('', 1);
    google.wallet.online.setAccessToken('');
    // Perform an asynchronous GET request.
    $.ajax({
      type: 'GET',
      url: revokeUrl,
      async: false,
      contentType: "application/json",
      dataType: 'jsonp',
      success: function(nullResponse) {
        $.post('logout', '', function() {
          document.location.href = "/";
        });
      }
    });
  };
})(window.bikeStore.Sso = window.bikeStore.Sso || {});
<|endoftext|>


<commit_before>function getSizeAndPos(winKey) {
  // Convert percentages to pixel values
  const properties = {};
  ['width', 'height', 'left', 'top'].forEach(pKey => {
    const value = localStorage[`ttw_${winKey}_${pKey}`];
    const screenDimension = pKey === 'width' || pKey === 'left'
      ? screen.availWidth
      : screen.availHeight;
    properties[pKey] = Math.round(value * screenDimension);
  });

  return properties;
}

function getOriginId(id) {
  return `ttw_pop_origin_${id}`;
}

function moveTabOut(windowType) {
  chrome.windows.getCurrent({},  curWin => {
    const resizeOriginal = localStorage.ttw_resize_original === 'true';
    const fullscreen = localStorage.ttw_copy_fullscreen === 'true' &&
                       curWin.state === 'fullscreen';

    // resize original window
    if (resizeOriginal && !fullscreen) {
      const vals = getSizeAndPos('original');
      chrome.windows.update(curWin.id, {
        width: vals.width,
        height: vals.height,
        left: vals.left,
        top: vals.top
      });
    }

    // create new window
    chrome.tabs.query({
      currentWindow: true,
      active: true
    }, tabs => {
      const tab = tabs[0];
      const createData = {
        tabId: tab.id,
        type: windowType,
        focused: localStorage.ttw_focus === 'new',
        incognito: tab.incognito
      };

      chrome.runtime.getPlatformInfo(info => {
        if (fullscreen) {
            // On Mac, setting state to fullscreen when the current window is
            // already fullscreen results in a NON fullscreen window (guessing
            // chrome toggles the state after the window is created)
          if(info.os !== chrome.runtime.PlatformOs.MAC) {
            createData.state = fullscreen ? 'fullscreen' : 'normal';
          }
        }
        else {
          const cloning = localStorage.ttw_clone_original === 'true' && !fullscreen;
          if (cloning) {
            // copying all values covers the case of clone-position-same
            ['width', 'height', 'left', 'top'].forEach(k => createData[k] = curWin[k]);

            const pos = localStorage.ttw_clone_position;
            if (pos === 'clone-position-horizontal') {
              const right = curWin.left + curWin.width;
              const hgap = screen.availWidth - right;
              const positionOnRight = curWin.left < hgap;

              createData.width = Math.min(curWin.width, positionOnRight ? hgap : curWin.left);
              createData.left = positionOnRight ? right : curWin.left - Math.min(curWin.width, curWin.left);
            }
            else if (pos === 'clone-position-vertical') {
              const bottom = curWin.top + curWin.height;
              const vgap = screen.availHeight - bottom;
              const positionBelow = curWin.top < vgap;

              createData.top = positionBelow ? bottom : curWin.top - Math.min(curWin.height, curWin.top);
              createData.height = Math.min(curWin.height, positionBelow ? vgap : curWin.top);
            }
          }
          else {
            Object.entries(getSizeAndPos('new')).forEach(p => createData[p[0]] = p[1]);
          }
        }

        // Move it to a new window
        chrome.windows.create(createData, newWindow => {
          // save parent id in case we want to pop_in
          sessionStorage[getOriginId(tab.id)] = curWin.id;

          // focus on original if needed
          if (localStorage.ttw_focus === "original") {
            chrome.windows.update(curWin.id, { focused: true });
          }
        });
      });
    });
  });
}

function tabToWindow(windowType) {
  // Check there are more than 1 tabs in current window
  chrome.tabs.query({
    currentWindow: true
  }, tabs => {
    if (tabs.length <= 1) { return; }
    moveTabOut(windowType);
  });
}

function windowToTab() {
  chrome.tabs.query({
    currentWindow: true,
    active:      true
  }, tabs => {
    const tab = tabs[0];

    const popped_key = getOriginId(tab.id);
    if (!sessionStorage.hasOwnProperty(popped_key)) { return; }

    const origin_window_id = parseInt(sessionStorage[popped_key]);

    // check original window still exists
    chrome.windows.get(origin_window_id, {}, originWindow => {
      if (chrome.runtime.lastError) { return; }

      // move the current tab
      chrome.tabs.move(tab.id, {
        windowId: origin_window_id,
        index:    -1
      }, () => {
        sessionStorage.removeItem(popped_key);
        chrome.tabs.update(tab.id, {
          active: true
        });
      });
    });
  });
}

chrome.commands.onCommand.addListener(command => {
  const lookup = {
    'tab-to-window-normal': () => tabToWindow('normal'),
    'tab-to-window-popup':  () => tabToWindow('popup'),
    'window-to-tab':        windowToTab
  };

  if (lookup.hasOwnProperty(command)) {
    lookup[command]();
  }
});
<commit_msg>make tabtowindow into big func<commit_after>function getSizeAndPos(winKey) {
  // Convert percentages to pixel values
  const properties = {};
  ['width', 'height', 'left', 'top'].forEach(pKey => {
    const value = localStorage[`ttw_${winKey}_${pKey}`];
    const screenDimension = pKey === 'width' || pKey === 'left'
      ? screen.availWidth
      : screen.availHeight;
    properties[pKey] = Math.round(value * screenDimension);
  });

  return properties;
}

function getOriginId(id) {
  return `ttw_pop_origin_${id}`;
}

function tabToWindow(windowType) {
  // Check there are more than 1 tabs in current window
  chrome.tabs.query({
    currentWindow: true
  }, tabs => {
    if (tabs.length <= 1) { return; }
    chrome.windows.getCurrent({},  curWin => {
      const resizeOriginal = localStorage.ttw_resize_original === 'true';
      const fullscreen = localStorage.ttw_copy_fullscreen === 'true' &&
                         curWin.state === 'fullscreen';

      // resize original window
      if (resizeOriginal && !fullscreen) {
        const vals = getSizeAndPos('original');
        chrome.windows.update(curWin.id, {
          width: vals.width,
          height: vals.height,
          left: vals.left,
          top: vals.top
        });
      }

      // create new window
      chrome.tabs.query({
        currentWindow: true,
        active: true
      }, tabs => {
        const tab = tabs[0];
        const createData = {
          tabId: tab.id,
          type: windowType,
          focused: localStorage.ttw_focus === 'new',
          incognito: tab.incognito
        };

        chrome.runtime.getPlatformInfo(info => {
          if (fullscreen) {
              // On Mac, setting state to fullscreen when the current window is
              // already fullscreen results in a NON fullscreen window (guessing
              // chrome toggles the state after the window is created)
            if(info.os !== chrome.runtime.PlatformOs.MAC) {
              createData.state = fullscreen ? 'fullscreen' : 'normal';
            }
          }
          else {
            const cloning = localStorage.ttw_clone_original === 'true' && !fullscreen;
            if (cloning) {
              // copying all values covers the case of clone-position-same
              ['width', 'height', 'left', 'top'].forEach(k => createData[k] = curWin[k]);

              const pos = localStorage.ttw_clone_position;
              if (pos === 'clone-position-horizontal') {
                const right = curWin.left + curWin.width;
                const hgap = screen.availWidth - right;
                const positionOnRight = curWin.left < hgap;

                createData.width = Math.min(curWin.width, positionOnRight ? hgap : curWin.left);
                createData.left = positionOnRight ? right : curWin.left - Math.min(curWin.width, curWin.left);
              }
              else if (pos === 'clone-position-vertical') {
                const bottom = curWin.top + curWin.height;
                const vgap = screen.availHeight - bottom;
                const positionBelow = curWin.top < vgap;

                createData.top = positionBelow ? bottom : curWin.top - Math.min(curWin.height, curWin.top);
                createData.height = Math.min(curWin.height, positionBelow ? vgap : curWin.top);
              }
            }
            else {
              Object.entries(getSizeAndPos('new')).forEach(p => createData[p[0]] = p[1]);
            }
          }

          // Move it to a new window
          chrome.windows.create(createData, newWindow => {
            // save parent id in case we want to pop_in
            sessionStorage[getOriginId(tab.id)] = curWin.id;

            // focus on original if needed
            if (localStorage.ttw_focus === "original") {
              chrome.windows.update(curWin.id, { focused: true });
            }
          });
        });
      });
    });
  });
}

function windowToTab() {
  chrome.tabs.query({
    currentWindow: true,
    active:      true
  }, tabs => {
    const tab = tabs[0];

    const popped_key = getOriginId(tab.id);
    if (!sessionStorage.hasOwnProperty(popped_key)) { return; }

    const origin_window_id = parseInt(sessionStorage[popped_key]);

    // check original window still exists
    chrome.windows.get(origin_window_id, {}, originWindow => {
      if (chrome.runtime.lastError) { return; }

      // move the current tab
      chrome.tabs.move(tab.id, {
        windowId: origin_window_id,
        index:    -1
      }, () => {
        sessionStorage.removeItem(popped_key);
        chrome.tabs.update(tab.id, {
          active: true
        });
      });
    });
  });
}

chrome.commands.onCommand.addListener(command => {
  const lookup = {
    'tab-to-window-normal': () => tabToWindow('normal'),
    'tab-to-window-popup':  () => tabToWindow('popup'),
    'window-to-tab':        windowToTab
  };

  if (lookup.hasOwnProperty(command)) {
    lookup[command]();
  }
});
<|endoftext|>


<commit_before>(function() {
  var $, animationEndSupport, vex;
  $ = jQuery;
  animationEndSupport = false;
  $(function() {
    var s;
    s = (document.body || document.documentElement).style;
    return animationEndSupport = s.animation !== void 0 || s.WebkitAnimation !== void 0 || s.MozAnimation !== void 0 || s.MsAnimation !== void 0 || s.OAnimation !== void 0;
  });
  vex = {
    globalID: 1,
    animationEndEvent: 'animationend webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend',
    baseClassNames: {
      vex: 'vex',
      content: 'vex-content',
      overlay: 'vex-overlay',
      close: 'vex-close',
      closing: 'vex-closing'
    },
    defaultOptions: {
      content: '',
      showCloseButton: true,
      overlayClosesOnClick: true,
      appendLocation: 'body',
      className: '',
      css: {},
      overlayClassName: '',
      overlayCSS: {},
      contentClassName: '',
      contentCSS: {},
      closeClassName: '',
      closeCSS: {}
    },
    open: function(options) {
      options = $.extend({}, vex.defaultOptions, options);
      options.id = vex.globalID;
      vex.globalID += 1;
      options.$vex = $('
').addClass(vex.baseClassNames.vex).addClass(options.className).css(options.css).data({
        vex: options
      });
      options.$vexOverlay = $('
').addClass(vex.baseClassNames.overlay).addClass(options.overlayClassName).css(options.overlayCSS).data({
        vex: options
      });
      if (options.overlayClosesOnClick) {
        options.$vexOverlay.bind('click.vex', function(e) {
          if (e.target !== this) {
            return;
          }
          return vex.close($(this).data().vex.id);
        });
      }
      options.$vex.append(options.$vexOverlay);
      options.$vexContent = $('
').addClass(vex.baseClassNames.content).addClass(options.contentClassName).css(options.contentCSS).append(options.content).data({
        vex: options
      });
      options.$vex.append(options.$vexContent);
      if (options.showCloseButton) {
        options.$closeButton = $('
').addClass(vex.baseClassNames.close).addClass(options.closeClassName).css(options.closeCSS).data({
          vex: options
        }).bind('click.vex', function() {
          return vex.close($(this).data().vex.id);
        });
        options.$vexContent.append(options.$closeButton);
      }
      $(options.appendLocation).append(options.$vex);
      if (options.afterOpen) {
        options.afterOpen(options.$vexContent, options);
      }
      setTimeout((function() {
        return options.$vexContent.trigger('vexOpen', options);
      }), 0);
      return options.$vexContent;
    },
    getAllVexes: function() {
      return $("." + vex.baseClassNames.vex + ":not(\"." + vex.baseClassNames.closing + "\") ." + vex.baseClassNames.content);
    },
    getVexByID: function(id) {
      return vex.getAllVexes().filter(function() {
        return $(this).data().vex.id === id;
      });
    },
    close: function(id) {
      var $lastVexContent;
      if (!id) {
        $lastVexContent = vex.getAllVexes().last();
        if (!$lastVexContent.length) {
          return false;
        }
        id = $lastVexContent.data().vex.id;
      }
      return vex.closeByID(id);
    },
    closeAll: function() {
      var ids;
      ids = vex.getAllVexes().map(function() {
        return $(this).data().vex.id;
      });
      if (!(ids && ids.length)) {
        return false;
      }
      $.each(ids.reverse(), function(index, id) {
        return vex.closeByID(id);
      });
      return true;
    },
    closeByID: function(id) {
      var $vex, $vexContent, beforeClose, close, options;
      $vexContent = vex.getVexByID(id);
      if (!$vexContent.length) {
        return;
      }
      $vex = $vexContent.data().vex.$vex;
      options = $.extend({}, $vexContent.data().vex);
      beforeClose = function() {
        if (options.beforeClose) {
          return options.beforeClose($vexContent, options);
        }
      };
      close = function() {
        $vexContent.trigger('vexClose', options);
        $vex.remove();
        if (options.afterClose) {
          return options.afterClose($vexContent, options);
        }
      };
      if (animationEndSupport) {
        beforeClose();
        $vex.unbind(vex.animationEndEvent).bind(vex.animationEndEvent, function() {
          return close();
        }).addClass(vex.baseClassNames.closing);
      } else {
        beforeClose();
        close();
      }
      return true;
    },
    hideLoading: function() {
      return $('.vex-loading-spinner').remove();
    },
    showLoading: function() {
      vex.hideLoading();
      return $('body').append("

");
    }
  };
  window.vex = vex;
}).call(this);
<commit_msg>Must be an array (fixes bug with `closeAll`)<commit_after>(function() {
  var $, animationEndSupport, vex;
  $ = jQuery;
  animationEndSupport = false;
  $(function() {
    var s;
    s = (document.body || document.documentElement).style;
    animationEndSupport = s.animation !== void 0 || s.WebkitAnimation !== void 0 || s.MozAnimation !== void 0 || s.MsAnimation !== void 0 || s.OAnimation !== void 0;
    return $(window).bind('keyup.vex', function(event) {
      if (event.keyCode === 27) {
        return vex.closeByEscape();
      }
    });
  });
  vex = {
    globalID: 1,
    animationEndEvent: 'animationend webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend',
    baseClassNames: {
      vex: 'vex',
      content: 'vex-content',
      overlay: 'vex-overlay',
      close: 'vex-close',
      closing: 'vex-closing'
    },
    defaultOptions: {
      content: '',
      showCloseButton: true,
      escapeButtonCloses: true,
      overlayClosesOnClick: true,
      appendLocation: 'body',
      className: '',
      css: {},
      overlayClassName: '',
      overlayCSS: {},
      contentClassName: '',
      contentCSS: {},
      closeClassName: '',
      closeCSS: {}
    },
    open: function(options) {
      options = $.extend({}, vex.defaultOptions, options);
      options.id = vex.globalID;
      vex.globalID += 1;
      options.$vex = $('
').addClass(vex.baseClassNames.vex).addClass(options.className).css(options.css).data({
        vex: options
      });
      options.$vexOverlay = $('
').addClass(vex.baseClassNames.overlay).addClass(options.overlayClassName).css(options.overlayCSS).data({
        vex: options
      });
      if (options.overlayClosesOnClick) {
        options.$vexOverlay.bind('click.vex', function(e) {
          if (e.target !== this) {
            return;
          }
          return vex.close($(this).data().vex.id);
        });
      }
      options.$vex.append(options.$vexOverlay);
      options.$vexContent = $('
').addClass(vex.baseClassNames.content).addClass(options.contentClassName).css(options.contentCSS).append(options.content).data({
        vex: options
      });
      options.$vex.append(options.$vexContent);
      if (options.showCloseButton) {
        options.$closeButton = $('
').addClass(vex.baseClassNames.close).addClass(options.closeClassName).css(options.closeCSS).data({
          vex: options
        }).bind('click.vex', function() {
          return vex.close($(this).data().vex.id);
        });
        options.$vexContent.append(options.$closeButton);
      }
      $(options.appendLocation).append(options.$vex);
      if (options.afterOpen) {
        options.afterOpen(options.$vexContent, options);
      }
      setTimeout((function() {
        return options.$vexContent.trigger('vexOpen', options);
      }), 0);
      return options.$vexContent;
    },
    getAllVexes: function() {
      return $("." + vex.baseClassNames.vex + ":not(\"." + vex.baseClassNames.closing + "\") ." + vex.baseClassNames.content);
    },
    getVexByID: function(id) {
      return vex.getAllVexes().filter(function() {
        return $(this).data().vex.id === id;
      });
    },
    close: function(id) {
      var $lastVex;
      if (!id) {
        $lastVex = vex.getAllVexes().last();
        if (!$lastVex.length) {
          return false;
        }
        id = $lastVex.data().vex.id;
      }
      return vex.closeByID(id);
    },
    closeAll: function() {
      var ids;
      ids = vex.getAllVexes().map(function() {
        return $(this).data().vex.id;
      }).toArray();
      if (!(ids != null ? ids.length : void 0)) {
        return false;
      }
      $.each(ids.reverse(), function(index, id) {
        return vex.closeByID(id);
      });
      return true;
    },
    closeByID: function(id) {
      var $vex, $vexContent, beforeClose, close, options;
      $vexContent = vex.getVexByID(id);
      if (!$vexContent.length) {
        return;
      }
      $vex = $vexContent.data().vex.$vex;
      options = $.extend({}, $vexContent.data().vex);
      beforeClose = function() {
        if (options.beforeClose) {
          return options.beforeClose($vexContent, options);
        }
      };
      close = function() {
        $vexContent.trigger('vexClose', options);
        $vex.remove();
        if (options.afterClose) {
          return options.afterClose($vexContent, options);
        }
      };
      if (animationEndSupport) {
        beforeClose();
        $vex.unbind(vex.animationEndEvent).bind(vex.animationEndEvent, function() {
          return close();
        }).addClass(vex.baseClassNames.closing);
      } else {
        beforeClose();
        close();
      }
      return true;
    },
    closeByEscape: function() {
      var $lastVex, id, ids;
      ids = vex.getAllVexes().map(function() {
        return $(this).data().vex.id;
      }).toArray();
      if (!(ids != null ? ids.length : void 0)) {
        return false;
      }
      id = Math.max.apply(Math, ids);
      $lastVex = vex.getVexByID(id);
      if ($lastVex.data().vex.escapeButtonCloses !== true) {
        return false;
      }
      return vex.closeByID(id);
    },
    hideLoading: function() {
      return $('.vex-loading-spinner').remove();
    },
    showLoading: function() {
      vex.hideLoading();
      return $('body').append("

");
    }
  };
  window.vex = vex;
}).call(this);
<|endoftext|>


<commit_before>/* global d3, INSTRUCTIONTYPE, Instuctions, InitVis, TaskChart, metrics */
/* exported InitVis*/

let catagoryColourScale20 = d3.scale.category20();
let catagoryColourScale10 = d3.scale.category10();

/** Colour by d.type.value*/
function colourScalefunc(d) {
  if (Object.keys(INSTRUCTIONTYPE).length > 10) {
    return catagoryColourScale20(d.type.value);
  }
  return catagoryColourScale10(d.type.value);
}

/** Colour by d.cu*/
function colourCUfunc(d) {
  return catagoryColourScale10(d.cu);
}

let showWfCu = false;
let tc;
let cuVisSvg = null;
let memVisSvg = null;

function InitVis() {
  if (tc) {
    tc.Clear();
  }
  if (cuVisSvg) {
    ClearCuvis();
  }
  tc = new TaskChart(d3.select("#visContainerDiv"), Instuctions, metrics.wfCount);
  tc.setFillfunc(showWfCu ? colourCUfunc : colourScalefunc);
  tc.Redraw();
}

var acitivityMode = true;

function ClearCuvis() {
  if (cuVisSvg) {
    cuVisSvg.remove();
  }
}

function ClearMemvis() {
  if (tc) {
    tc.Clear();
  }
  if (cuVisSvg) {
    ClearCuvis();
  }
  if (memVisSvg) {
    memVisSvg.remove();
  }
  $("#visContainerDiv").toggleClass("visContainer", true);
  $("#visContainerDiv").toggleClass("visContainer1", false);
  $("#visContainerDiv2").remove();
  if (tc) {
    tc.Redraw();
  }
}
function handleMemCheck(cb) {
  if (cb.checked) {
    ShowMemVis();
  } else {
    ClearMemvis();
  }
}
function ShowMemVis() {
  //make the current vis smaller
  if (tc) {
    tc.Clear();
  }
  if (cuVisSvg) {
    ClearCuvis();
  }

  $("#visContainerDiv").toggleClass("visContainer", false);
  $("#visContainerDiv").toggleClass("visContainer1", true);
  $("#outercontainer").append('

');
  tc.Redraw();

  let Ymax = Math.max(metrics.maxMemoryStoreOps, metrics.maxMemoryLoadOps);
  let Ymin = 0;
  let Xmax = metrics.cu[0].instActivity.length;
  let Xmin = 0;
  let padding = [0, 2, 20, 10];
  let container = d3.select("#visContainerDiv2");
  let width = parseInt(container.style("width"), 10);
  let height = parseInt(container.style("height"), 10);
  let xScale = d3.scale.linear().domain([Xmin, Xmax]).range([0, width - (padding[2] + padding[3])]).clamp(true);
  let yScale = d3.scale.linear().domain([Ymin, Ymax]).range([0, height / 2 - (padding[0] + padding[1])]);

  memVisSvg = container.append('svg').attr('width', width).attr('height', height);

  let data = metrics.memory;
  let area = d3.svg.area()
    .x(function(d, index) {
      return xScale(index);
    })
    .y1(yScale(Ymax))
    .y0(function(d) {
      return yScale(Ymax) - yScale(d);
    });

  let loads = memVisSvg.append("g");
  loads.attr("height", height / 2)
    .attr("transform", "translate(" + padding[2] + ",0)").append("path")
    .datum(metrics.memoryLoad)
    .attr("d", area)
    .attr("fill", "#1f77b4");

  loads.append("text")
    .attr("transform", "translate(0,20)")
    .attr("font-weight", "bold")
    .attr("text-anchor", "left")
    .text("Load Ops");

  let stores = memVisSvg.append("g");
  stores.attr("height", height / 2)
    .attr("transform", "translate(" + padding[2] + "," + height / 2 + ")").append("path")
    .datum(metrics.memoryStore)
    .attr("d", area)
    .attr("fill", "#d62728");
  stores.append("text")
    .attr("transform", "translate(0,20)")
    .attr("font-weight", "bold")
    .attr("text-anchor", "left")
    .text("Store Ops");
}

function ShowCuvis() {
  tc.Clear();
  ClearCuvis();
  let Ymax = metrics.globalMaxInstActivity;
  let Ymin = 0;
  let Xmax = metrics.cu[0].instActivity.length;
  let Xmin = 0;
  let padding = [0, 30, 20, 10];
  let container = d3.select("#visContainerDiv");
  let width = parseInt(container.style("width"), 10);
  let height = parseInt(container.style("height"), 10);
  let numberOfLanes = metrics.cuCount;
  let xScale = d3.scale.linear().domain([Xmin, Xmax]).range([0, width - (padding[2] + padding[3])]).clamp(true);
  let yScale = d3.scale.ordinal().domain(d3.range(numberOfLanes)).rangeRoundBands([0, height - (padding[0] + padding[1])]);
  let yScaleLocal = d3.scale.ordinal().domain(d3.range(Ymax + 1)).rangeRoundBands([0, yScale.rangeBand()]);
  let xAxis = d3.svg.axis().scale(xScale).orient("bottom").tickSubdivide(true).tickSize(8).tickPadding(8);
  let yAxis = d3.svg.axis().scale(yScale).orient("left").tickSize(0);

  cuVisSvg = container.append('svg').attr('width', width).attr('height', height);
  cuVisSvg.append("g").attr("class", "x axis")
    .attr("transform", "translate(" + padding[2] + ", " + (height - padding[1]) + ")")
    .transition().call(xAxis);
  cuVisSvg.append("g").attr("class", "y axis")
    .attr("transform", "translate(" + padding[2] + ", 0)")
    .transition().call(yAxis);

  for (let i = 0; i < numberOfLanes; i++) {
    let qqr = i;
    let data = metrics.cu[qqr];
    let area = d3.svg.area()
      .x(function(d, index) {
        return xScale(index);
      })
      .y0(yScale(qqr) + yScale.rangeBand())

      .y1(function(d, index) {
        let a = (yScale(qqr) + yScale.rangeBand());
        let b = yScaleLocal((acitivityMode ? d : d.reduce(function(a, b) {
          return a + b;
        })));
        return (a - b);
      });
    let col = catagoryColourScale10(qqr);
    cuVisSvg.append("g")
      .attr("transform", "translate(" + padding[2] + ",0)").append("path")
      //.datum(acitivityMode ? data.instActivity : data.wfActivity)
      .datum(data.instActivity)
      //.attr("class", "area")
      .attr("d", area)
      .attr("fill", col);
  }
}
<commit_msg>Axis labels for CU view.<commit_after>/* global d3, INSTRUCTIONTYPE, Instuctions, InitVis, TaskChart, metrics */
/* exported InitVis*/

let catagoryColourScale20 = d3.scale.category20();
let catagoryColourScale10 = d3.scale.category10();

/** Colour by d.type.value*/
function colourScalefunc(d) {
  if (Object.keys(INSTRUCTIONTYPE).length > 10) {
    return catagoryColourScale20(d.type.value);
  }
  return catagoryColourScale10(d.type.value);
}

/** Colour by d.cu*/
function colourCUfunc(d) {
  return catagoryColourScale10(d.cu);
}

let showWfCu = false;
let tc;
let cuVisSvg = null;
let memVisSvg = null;

function InitVis() {
  if (tc) {
    tc.Clear();
  }
  if (cuVisSvg) {
    ClearCuvis();
  }
  tc = new TaskChart(d3.select("#visContainerDiv"), Instuctions, metrics.wfCount);
  tc.setFillfunc(showWfCu ? colourCUfunc : colourScalefunc);
  tc.Redraw();
}

var acitivityMode = true;

function ClearCuvis() {
  if (cuVisSvg) {
    cuVisSvg.remove();
  }
}

function ClearMemvis() {
  if (tc) {
    tc.Clear();
  }
  if (cuVisSvg) {
    ClearCuvis();
  }
  if (memVisSvg) {
    memVisSvg.remove();
  }
  $("#visContainerDiv").toggleClass("visContainer", true);
  $("#visContainerDiv").toggleClass("visContainer1", false);
  $("#visContainerDiv2").remove();
  if (tc) {
    tc.Redraw();
  }
}
function handleMemCheck(cb) {
  if (cb.checked) {
    ShowMemVis();
  } else {
    ClearMemvis();
  }
}
function ShowMemVis() {
  //make the current vis smaller
  if (tc) {
    tc.Clear();
  }
  if (cuVisSvg) {
    ClearCuvis();
  }

  $("#visContainerDiv").toggleClass("visContainer", false);
  $("#visContainerDiv").toggleClass("visContainer1", true);
  $("#outercontainer").append('

');
  tc.Redraw();

  let Ymax = Math.max(metrics.maxMemoryStoreOps, metrics.maxMemoryLoadOps);
  let Ymin = 0;
  let Xmax = metrics.cu[0].instActivity.length;
  let Xmin = 0;
  let padding = [0, 2, 20, 10];
  let container = d3.select("#visContainerDiv2");
  let width = parseInt(container.style("width"), 10);
  let height = parseInt(container.style("height"), 10);
  let xScale = d3.scale.linear().domain([Xmin, Xmax]).range([0, width - (padding[2] + padding[3])]).clamp(true);
  let yScale = d3.scale.linear().domain([Ymin, Ymax]).range([0, height / 2 - (padding[0] + padding[1])]);

  memVisSvg = container.append('svg').attr('width', width).attr('height', height);

  let data = metrics.memory;
  let area = d3.svg.area()
    .x(function(d, index) {
      return xScale(index);
    })
    .y1(yScale(Ymax))
    .y0(function(d) {
      return yScale(Ymax) - yScale(d);
    });

  let loads = memVisSvg.append("g");
  loads.attr("height", height / 2)
    .attr("transform", "translate(" + padding[2] + ",0)").append("path")
    .datum(metrics.memoryLoad)
    .attr("d", area)
    .attr("fill", "#1f77b4");

  loads.append("text")
    .attr("transform", "translate(0,20)")
    .attr("font-weight", "bold")
    .attr("text-anchor", "left")
    .text("Load Ops");

  let stores = memVisSvg.append("g");
  stores.attr("height", height / 2)
    .attr("transform", "translate(" + padding[2] + "," + height / 2 + ")").append("path")
    .datum(metrics.memoryStore)
    .attr("d", area)
    .attr("fill", "#d62728");
  stores.append("text")
    .attr("transform", "translate(0,20)")
    .attr("font-weight", "bold")
    .attr("text-anchor", "left")
    .text("Store Ops");
}

function ShowCuvis() {
  tc.Clear();
  ClearCuvis();
  let Ymax = metrics.globalMaxInstActivity;
  let Ymin = 0;
  let Xmax = metrics.cu[0].instActivity.length;
  let Xmin = 0;
  let padding = [0, 48, 30, 5];
  let container = d3.select("#visContainerDiv");
  let width = parseInt(container.style("width"), 10);
  let height = parseInt(container.style("height"), 10);
  let numberOfLanes = metrics.cuCount;
  let xScale = d3.scale.linear().domain([Xmin, Xmax]).range([0, width - (padding[2] + padding[3])]).clamp(true);
  let yScale = d3.scale.ordinal().domain(d3.range(numberOfLanes)).rangeRoundBands([0, height - (padding[0] + padding[1])]);
  let yScaleLocal = d3.scale.ordinal().domain(d3.range(Ymax + 1)).rangeRoundBands([0, yScale.rangeBand()]);
  let xAxis = d3.svg.axis().scale(xScale).orient("bottom").tickSubdivide(true).tickSize(8).tickPadding(8);
  let yAxis = d3.svg.axis().scale(yScale).orient("left").tickSize(0);

  cuVisSvg = container.append('svg').attr('width', width).attr('height', height);

  let xax = cuVisSvg.append("g");
  xax.attr("class", "x axis")
    .attr("transform", "translate(" + padding[2] + ", " + (height - padding[1]) + ")")
    .transition().call(xAxis);

  xax.append("text")
    .attr("transform", "translate(" + xScale.range()[1] / 2 + ",40)")
    .attr("font-weight", "bold")
    .attr("text-anchor", "middle")
    .text("(simulated) GPU Ticks");

  let yax = cuVisSvg.append("g");
  yax.attr("class", "y axis")
    .attr("transform", "translate(" + padding[2] + ", 0)")
    .transition().call(yAxis);
  yax.append("text")
    .attr("transform", "translate(-18," + yScale.rangeExtent()[1] / 2 + ") rotate(-90)")
    .attr("font-weight", "bold")
    .attr("text-anchor", "middle")
    .text("Compute Unit ID");

  for (let i = 0; i < numberOfLanes; i++) {
    let qqr = i;
    let data = metrics.cu[qqr];
    let area = d3.svg.area()
      .x(function(d, index) {
        return xScale(index);
      })
      .y0(yScale(qqr) + yScale.rangeBand())

      .y1(function(d, index) {
        let a = (yScale(qqr) + yScale.rangeBand());
        let b = yScaleLocal((acitivityMode ? d : d.reduce(function(a, b) {
          return a + b;
        })));
        return (a - b);
      });
    let col = catagoryColourScale10(qqr);
    cuVisSvg.append("g")
      .attr("transform", "translate(" + padding[2] + ",0)").append("path")
      //.datum(acitivityMode ? data.instActivity : data.wfActivity)
      .datum(data.instActivity)
      //.attr("class", "area")
      .attr("d", area)
      .attr("fill", col);
  }
}
<|endoftext|>


<commit_before>
<commit_msg>Delete jshint.js<commit_after><|endoftext|>


<commit_before>var fs = require('fs')
  , util = require('./lib/util.js')

// ByteArray is a janky implementation of array that allows me to pretend I
// have a typed array. It can turn four bytes into an unsigned 32 bit integer
// (big-endian). Once a stable version of node comes out with typed arrays,
// replace this with that.
var ByteArray = function(bytes){
  if (!(this instanceof ByteArray)) return new ByteArray(bytes);
  if (bytes) { this.pushBytes(bytes); }
}
ByteArray.prototype = new Array;
ByteArray.prototype.is = function(otherArray){
  for (var i = otherArray.length; i > 0; --i)
    if (otherArray[i] !== this[i]) return false;
  return true;
}
ByteArray.prototype.to32Int = function() {
  var x = 3, sum = 0, i = 0;
  for (; i <= x; i++)
    sum += Math.pow(256, (x-i)) * this[i];
  return sum;
}
ByteArray.prototype.pushBytes = function(bytes) {
  Array.prototype.push.apply(this, Array.prototype.slice.call(Buffer(bytes)));
  return this;
}

const PNG_MAGIC_NUMBER = ByteArray([137, 80, 78, 71, 13, 10, 26, 10]);

// An interface for reading chunks from a PNG. `source` can be a buffer, file
// descriptor or a string containing the path to a file.
var Reader = function(source) {
  if (!(this instanceof Reader)) return new Reader(source);
  this.source = source;
  this.data = null;
  this.cursor = 0;
  this.chunks = null;
}
Reader.prototype.getContents = function() {
  var source = this.source
    , len = null
    , buf = null
  if (Buffer.isBuffer(source))
    return this.data = source;
  else if ('number' === typeof source) {
    len = fs.fstatSync(source).size
    buf = Buffer(len);
    fs.readSync(source, buf, 0, len);
    return this.data = buf;
  }
  else if ('string' === typeof source) {
    return this.data = fs.readFileSync(source);
  }
  throw "unrecognized source. must be filename, file descriptor or buffer";
}
Reader.prototype.rewind = function(len){
  if (!len) this.cursor = 0;
  else { this.cursor -= len }
  if (this.cursor < 0) this.cursor = 0;;
}
Reader.prototype.eat = function(len) {
  var buf = this.peek(len);
  this.cursor += len;
  return buf;
}
Reader.prototype.peek = function(len) {
  if (!this.data) this.getContents();
  return this.data.slice(this.cursor, (this.cursor + len));
}

// Ensures that the buffer being read is a PNG by comparing it to the known
// PNG magic number, then read all of the chunks in the file to an array
// `this.chunks`.
Reader.prototype.readChunks = function() {
  var magic_nom_nom
    , chunk;
  this.chunks = [];
  this.rewind();
  magic_nom_nom = this.eat(8)
  if (!PNG_MAGIC_NUMBER.is(magic_nom_nom)) throw "this is not a PNG";
  while (chunk = this.readNextChunk()) this.chunks.push(chunk)
  return this.chunks;
}
// Generally this should not be called by itself, `this.readChunks` should be
// used. If `this.cursor` is not at a chunk boundary, this should probably cause
// an error. Otherwise there's a chance that this can silently return garbage data.
Reader.prototype.readNextChunk = function() {
  if (this.cursor === this.data.length) return null;
  var start = this.cursor
    , len = ByteArray(this.eat(4)).to32Int()
    , type = this.eat(4).toString()
    , data = this.eat(len)
    , crc = this.eat(4)
    , end = this.cursor
  return {start: start, len: len, type: type, data: data, crc: crc, end: end}
}
// Get an array of chunks that match the type. Possible types are listed here:
// http://www.w3.org/TR/PNG/#11Chunks. Order is determined by where the chunks
// appear in the file, and the return type will always be an array (even if
// the specification only allows one one instance of that type)
Reader.prototype.findByType = function(type) {
  if (!this.chunks) this.readChunks()
  return this.chunks.filter(function(chunk){
    return (chunk.type === type);
  });
}

// Writer is an interface for inserting chunks into a PNG. Other than
// generating a valid, CRCd chunk, there is no validation to speak of. Using this
// to add types with invalid data can break your PNG.
//
// Using pushBytes in this way causes five new buffers to be created. This can
// definitely be done more efficiently.
function Writer(source) {
  if (!(this instanceof Writer)) return new Writer(source);
  Reader.call(this, source)
}
Writer.prototype = new Reader;
Writer.prototype.chunk = function(type, data) {
  var body = ByteArray()
    , chunk = ByteArray()
  body
    .pushBytes(type)
    .pushBytes(data);
  chunk
    .pushBytes(util.intToBytes(data.length))
    .pushBytes(body)
    .pushBytes(util.intToBytes(util.crc32(body)));

  return Buffer(chunk);
}

// The specification for tEXt chunks requires a keyword and data, separated by
// a null character, for the body of the chunk.
Writer.prototype.tEXt = function(keyword, data) {
  return this.chunk('tEXt', [keyword, data].join("\u0000"));
}

// Expose objects as well as shortcut methods for reading and writing tEXt chunks.
exports.Reader = Reader;
exports.Writer = Writer;
exports.read = function(src, key){
  var textChunks = Reader(src).findByType('tEXt');
  return textChunks;
};
exports.write = function(src, key, data) {
  var writer = Writer(src)
    , ihdr_end = writer.findByType('IHDR').pop().end
    , chunk = writer.tEXt(key, data)
    , len = writer.data.length + chunk.length
    , buf = Buffer(len)
  writer.data.copy(buf, 0, 0, ihdr_end);
  chunk.copy(buf, ihdr_end)
  writer.data.copy(buf, (ihdr_end + chunk.length), ihdr_end)
  return buf;
}
<commit_msg>Moving metapng.js to index.js, updating package.json<commit_after><|endoftext|>


<commit_before>#!/usr/local/bin/node
/*
curl -i https://api.github.com/orgs/intel-hadoop/members
curl -i https://api.github.com/repos/intel-hadoop/gearpump/commits?since=2014-10-16&until=2014-10-31
curl -i https://api.github.com/repos/intel-hadoop/gearpump/stats/contributors
curl -i https://api.github.com/repos/intel-hadoop/gearpump/stats/participation
*/
function gitapi(uri, cb) {
  var request = require('request');
  var options = {
    url: 'https://api.github.com'+uri,
    auth: {
      'user': 'kkasravi',
      'pass': 'kdkkdk1'
    },
    headers: {
        'User-Agent': 'request'
    }
  };
  function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
      var info = JSON.parse(body);
      cb(info);
    } else {
      console.log('statusCode='+response.statusCode+' error='+error);
    }
  }
  request(options, callback);
}

function teamsCallback(name, teamcallback, teams) {
  teams.some(function(team) {
    if(team.name === name) {
      teamcallback(team);
      return true;
    }
    return false;
  })
}
function getTeam(team, teamcallback) {
  gitapi('/orgs/intel-hadoop/teams',teamsCallback.bind(undefined,team,teamcallback));
}
function statsCallback(team, repo, members, stats) {
  console.log(team+'\n  '+repo)
  var totals = {commits:0,additions:0,deletions:0};
  stats.forEach(function(stat) {
    var member = stat.author.login
    if(members[member]) {
      console.log('    '+member);
      members[member].weeks = stat.weeks.slice(-2)
      members[member].weeks.forEach(function(week) {
        var date = new Date()
        date.setTime(parseInt(week.w+'000'));
        var commit = parseInt(week.c);
        var additions = parseInt(week.a);
        var deletions = parseInt(week.d);
        totals.commits += commit;
        totals.additions += additions;
        totals.deletions += deletions;
        console.log('      '+date.toDateString()+' commits:'+week.c+' additions:'+week.a+' deletions:'+week.d);
      });
    }
  });
  console.log('  commits:'+totals.commits+' additions:'+totals.additions+' deletions:'+totals.deletions+'\n');
}
function getStats(repo, statscallback) {
  gitapi(repo,statscallback);
}
function membersCallback(team, repo, membersArray) {
  var members = {}
  membersArray.forEach(function(member) {
    members[member.login] = {}
  });
  getStats(repo+'/stats/contributors',statsCallback.bind(undefined, team, repo, members));
}
function getMembers(teamid,memberscallback) {
  var uri = '/teams/'+teamid+'/members';
  gitapi(uri,memberscallback);
}
function getCommits(range,commitsCallback) {
  var uri = '/teams/'+teamid+'/members';
  gitapi(uri,memberscallback);
}
function teamCallback(memberscallback, team) {
  getMembers(team.id,memberscallback);
}
getTeam('oryx',teamCallback.bind(undefined,membersCallback.bind(undefined,'oryx','/repos/OryxProject/oryx')))
getTeam('gearpump',teamCallback.bind(undefined,membersCallback.bind(undefined,'gearpump','/repos/intel-hadoop/gearpump')))
getTeam('spark',teamCallback.bind(undefined,membersCallback.bind(undefined,'spark','/repos/apache/spark')))
<commit_msg>adding pullrequests, refactoring callbacks and adding Metrics class.<commit_after>#!/usr/local/bin/node
/*
curl -i https://api.github.com/orgs/intel-hadoop/members
curl -i 'https://api.github.com/repos/intel-hadoop/gearpump/commits?since=2014-10-16&until=2014-10-31'
curl -i 'https://api.github.com/repos/intel-hadoop/gearpump/pulls?state=closed&direction=asc'
curl -i https://api.github.com/repos/intel-hadoop/gearpump/stats/contributors
curl -i https://api.github.com/repos/intel-hadoop/gearpump/stats/participation
*/
function gitapi(uri, cb) {
  var request = require('request');
  var options = {
    url: 'https://api.github.com'+uri,
    auth: {
      'user': 'kkasravi',
      'pass': 'kdkkdk1'
    },
    headers: {
        'User-Agent': 'request'
    }
  };
  function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
      var info = JSON.parse(body);
      cb(info);
    } else {
      console.log('statusCode='+response.statusCode+' error='+error);
    }
  }
  request(options, callback);
}

Metrics = (function() {
  function Metrics(team, org, repo) {
    this.team = team;
    this.org = org;
    this.repo = repo
  }

  Metrics.prototype.addMembers = function (members) {
    this.members = members;
  }
  return Metrics;
})();

function getTeam(team, teamcallback) {
  function teamsCallback(name, teamcallback, teams) {
    teams.some(function(team) {
      if(team.name === name) {
        teamcallback(team);
        return true;
      }
      return false;
    })
  }
  gitapi('/orgs/intel-hadoop/teams',teamsCallback.bind(undefined,team,teamcallback));
}

function pullRequestCallback(data) {
  data.forEach(function(pull) {
    if(metrics.members[pull.user.login]) {
      var created = new Date(pull.created_at)
      var closed = new Date(pull.closed_at)
      console.log(pull.base.repo.name+' '+pull.user.login+' created '+created.toDateString()+' closed '+closed.toDateString())
    }
  });
}

function getPullRequests(repo, pullrequestcallback) {
  function pullRequestsCallback(repo, pullrequestcallback, data) {
    pullrequestcallback(data)
  }
  gitapi(repo+'/pulls?state=closed&direction=asc',pullRequestsCallback.bind(undefined,repo,pullrequestcallback));
}

function membersCallback(team, repo, membersArray) {
  var members = {}
  membersArray.forEach(function(member) {
    members[member.login] = {}
  });
  function statsCallback(team, repo, members, stats) {
    console.log(team+'\n  '+repo)
    var totals = {commits:0,additions:0,deletions:0};
    stats.forEach(function(stat) {
      var member = stat.author.login
      if(members[member]) {
        console.log('    '+member);
        members[member].weeks = stat.weeks.slice(-2)
        members[member].weeks.forEach(function(week) {
          var date = new Date()
          date.setTime(parseInt(week.w+'000'));
          var commit = parseInt(week.c);
          var additions = parseInt(week.a);
          var deletions = parseInt(week.d);
          totals.commits += commit;
          totals.additions += additions;
          totals.deletions += deletions;
          console.log('      '+date.toDateString()+' commits:'+week.c+' additions:'+week.a+' deletions:'+week.d);
        });
      }
    });
    metrics.addMembers(members);
    console.log('  commits:'+totals.commits+' additions:'+totals.additions+' deletions:'+totals.deletions+'\n');
    getPullRequests(repo,pullRequestCallback)
  }
  function getStats(repo, statscallback) {
    gitapi(repo,statscallback);
  }
  getStats(repo+'/stats/contributors',statsCallback.bind(undefined, team, repo, members));
}

function getMembers(teamid,memberscallback) {
  var uri = '/teams/'+teamid+'/members';
  gitapi(uri,memberscallback);
}
function getCommits(range,commitsCallback) {
  var uri = '/teams/'+teamid+'/members';
  gitapi(uri,memberscallback);
}
function teamCallback(memberscallback, team) {
  getMembers(team.id,memberscallback);
}
var metrics = new Metrics('intel-hadoop', 'gearpump', 'gearpump')
//getTeam('oryx',teamCallback.bind(undefined,membersCallback.bind(undefined, 'oryx', '/repos/OryxProject/oryx')))
getTeam('gearpump',teamCallback.bind(undefined,membersCallback.bind(undefined, 'gearpump','/repos/intel-hadoop/gearpump')))
//getTeam('spark',teamCallback.bind(undefined,membersCallback.bind(undefined, 'spark','/repos/apache/spark')))
<|endoftext|>


<commit_before>// Increases in probability of a sentence/the readme
// ending with each additional word
var DELTA_WORD_SENTENCE = 0.0026;
var DELTA_SENTENCE_README = 0.0016;

function normalize(arr){
    var sum = arr.reduce((a, b) => a + b, 0);
    return arr.map(val => val/sum);
}

// Probabilities
// Format is [noun, verb, adj, adv, interj, city, dem, art]
// PROBABILITIES.x is the array xProb
var PROB_KEYS = ["noun", "verb", "adj", "adv", "interj", "city", "dem", "art"];
var nounProb = [0, 3, 2, 1, 4, 1, 0, 0];
var verbProb = [0, 0, 0, 5, 3, 2, 3, 1];
var adjProb = [7, 3, 2, 1, 4, 3, 2, 6];
var advProb = [3,3,3,3,3,3,3,3];
var interjProb = [3,3,3,3,3,3,3,3];
var cityProb = [3,3,3,3,3,3,3,3];
var demProb = [3,3,3,3,3,3,3,3];
var artProb = [3,3,3,3,3,3,3,3];

var PROBABILITIES = {
    noun: normalize(nounProb),
    verb: normalize(verbProb),
    adj: normalize(adjProb),
    adv: normalize(advProb),
    interj: normalize(interjProb),
    city: normalize(cityProb),
    dem: normalize(demProb),
    art: normalize(artProb)
}

// function getNextWord(prev) returns a new word based on prev
// prev is a string from PROB_KEYS
function getNextPart(prev){
    var prevIdx = PROB_KEYS.indexOf(prev);
    var rand = Math.random();
    var curr = PROBABILITIES[prev];
     for (let i = 0; i < curr.length; i++){
        if (rand < curr[i]){
            return PROB_KEYS[i];
        }
    }
}

function getWord(partOfSpeech){
    var dict = DICTIONARY[partOfSpeech];
    var randIdx = Math.floor(Math.random() * dict.length);
    return dict[randIdx];
}

function generateTitle(){
    var noun = getWord("noun");
    var noun2 = getWord("noun");
    return noun[0].toUpperCase() + noun.substr(1, 3) + noun2[0].toUpperCase() + noun2.substr(1,noun2.length);
}

function generateReadme(){
    // Counts up how many words are in a
    // sentence and how many in a word.
    // Sentence counter resets at end of each sentence.
    var docWordCounter = 0;
    var sentenceWordCounter = 0;
    var currDocEndProb = 0;
    var currSentenceEndProb = 0;

    var randDocKey = Math.random();
    var randSentenceKey = Math.random();

    var README = "";
    var prevPartOfSpeech = PROB_KEYS[0];

    // Loop to generate readme
    while (randDocKey > currDocEndProb){

        var currSentence = getWord(prevPartOfSpeech);
        prevPartOfSpeech = getNextPart(prevPartOfSpeech);
        currSentenceEndProb = currSentenceEndProb + DELTA_WORD_SENTENCE;

        randSentenceKey = Math.random();
        // Loop to generate sentence
        while (randSentenceKey > currSentenceEndProb){
            currSentence = currSentence + ' ' + getWord(prevPartOfSpeech);
            prevPartOfSpeech = getNextPart(prevPartOfSpeech);
            currSentenceEndProb = currSentenceEndProb + DELTA_WORD_SENTENCE;
            randSentenceKey = Math.random();
        }
        currSentence = currSentence + '. ';
        currSentence = currSentence[0].toUpperCase() + currSentence.substr(1, currSentence.length);
        README = README + currSentence;
        currDocEndProb = currDocEndProb + DELTA_SENTENCE_README;
        randDocKey = Math.random();

    }

    return README;

}
<commit_msg>formatting + basecase<commit_after>// Increases in probability of a sentence/the readme
// ending with each additional word
var DELTA_WORD_SENTENCE = 0.0026;
var DELTA_SENTENCE_README = 0.0016;

function normalize(arr) {
    var sum = arr.reduce((a, b) => a + b, 0);
    return arr.map(val => val / sum);
}

// Probabilities
// Format is [noun, verb, adj, adv, interj, city, dem, art]
// PROBABILITIES.x is the array xProb
var PROB_KEYS = ["noun", "verb", "adj", "adv", "interj", "city", "dem", "art"];
var nounProb = [0, 3, 2, 1, 4, 1, 0, 0];
var verbProb = [0, 0, 0, 5, 3, 2, 3, 1];
var adjProb = [7, 3, 2, 1, 4, 3, 2, 6];
var advProb = [3, 3, 3, 3, 3, 3, 3, 3];
var interjProb = [3, 3, 3, 3, 3, 3, 3, 3];
var cityProb = [3, 3, 3, 3, 3, 3, 3, 3];
var demProb = [3, 3, 3, 3, 3, 3, 3, 3];
var artProb = [3, 3, 3, 3, 3, 3, 3, 3];

var PROBABILITIES = {
    noun: normalize(nounProb),
    verb: normalize(verbProb),
    adj: normalize(adjProb),
    adv: normalize(advProb),
    interj: normalize(interjProb),
    city: normalize(cityProb),
    dem: normalize(demProb),
    art: normalize(artProb)
}

// function getNextWord(prev) returns a new word based on prev
// prev is a string from PROB_KEYS
function getNextPart(prev) {
    var prevIdx = PROB_KEYS.indexOf(prev);
    var rand = Math.random();
    var curr = PROBABILITIES[prev];
    for (let i = 0; i < curr.length; i++) {
        if (rand < curr[i]) {
            return PROB_KEYS[i];
        }
    }
    return PROB_KEYS[0];
}

function getWord(partOfSpeech) {
    var dict = DICTIONARY[partOfSpeech];
    var randIdx = Math.floor(Math.random() * dict.length);
    return dict[randIdx];
}

function generateTitle() {
    var noun = getWord("noun");
    var noun2 = getWord("noun");
    return noun[0].toUpperCase() + noun.substr(1, 3) + noun2[0].toUpperCase() + noun2.substr(1, noun2.length);
}

function generateReadme() {
    // Counts up how many words are in a
    // sentence and how many in a word.
    // Sentence counter resets at end of each sentence.
    var docWordCounter = 0;
    var sentenceWordCounter = 0;
    var currDocEndProb = 0;
    var currSentenceEndProb = 0;

    var randDocKey = Math.random();
    var randSentenceKey = Math.random();

    var README = "";
    var prevPartOfSpeech = PROB_KEYS[0];

    // Loop to generate readme
    while (randDocKey > currDocEndProb) {
        var currSentence = getWord(prevPartOfSpeech);
        prevPartOfSpeech = getNextPart(prevPartOfSpeech);
        currSentenceEndProb = currSentenceEndProb + DELTA_WORD_SENTENCE;

        randSentenceKey = Math.random();
        // Loop to generate sentence
        while (randSentenceKey > currSentenceEndProb) {
            currSentence = currSentence + ' ' + getWord(prevPartOfSpeech);
            prevPartOfSpeech = getNextPart(prevPartOfSpeech);
            currSentenceEndProb = currSentenceEndProb + DELTA_WORD_SENTENCE;
            randSentenceKey = Math.random();
        }
        currSentence = currSentence + '. ';
        currSentence = currSentence[0].toUpperCase() + currSentence.substr(1, currSentence.length);
        README = README + currSentence;
        currDocEndProb = currDocEndProb + DELTA_SENTENCE_README;
        randDocKey = Math.random();

    }

    return README;

}
<|endoftext|>


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

    angular
        .module('orange')
        .provider('OrangeApi', OrangeApi);

    OrangeApi.$inject = [];

    /* @ngInject */
    function OrangeApi() {
        var baseUrl = null;
        var clientSecret = null;
        var accessToken = null;

        return {
            setBaseUrl: function (url) {
                baseUrl = url;
            },
            setClientSecret: function (secret) {
                clientSecret = secret;
            },
            setAccessToken: function (token) {
                accessToken = token;
            },
            $get: ['Restangular', '$state', '$rootScope', '$ionicLoading', '$injector', 'GlobalService',
                function (Restangular, $state, $rootScope, $ionicLoading, $injector, GlobalService) {

                var OrangeRest = Restangular.withConfig(function (RestangularConfigurer) {

                    RestangularConfigurer.setBaseUrl(baseUrl);
                    RestangularConfigurer.setDefaultHttpFields({cache: false});
                    RestangularConfigurer.setDefaultHeaders({
                        'X-Client-Secret': clientSecret,
                        'Authorization': 'Bearer ' + accessToken
                    });
                    RestangularConfigurer.setDefaultHttpFields({timeout: 30 * 1000});

                    RestangularConfigurer.addRequestInterceptor(function (element) {
                        if (element && element.hasOwnProperty('success')) {
                            delete element['success']
                        }
                        return element;
                    });

                    RestangularConfigurer.addResponseInterceptor(function (data, operation, what, url, response, deferred) {
                        var extractedData = function(obj, key) {
                            var ret;
                            ret = obj[key];
                            delete obj[key];
                            ret.meta = obj;
                            return ret
                        };

                        if (operation == 'getList') {

                            if (data.hasOwnProperty(what)) {
                                return extractedData(data, what)
                            } else if  (data.hasOwnProperty('entries')) {
                                return extractedData(data, 'entries')
                            }

                            return data
                        }

                        return data;
                    });

                    RestangularConfigurer.setErrorInterceptor(function (response, deferred, responseHandler) {
                        if (!_.isUndefined(response.data)) {
                            var _error = (response.data === null) ? [] : response.data.errors[0];
                        }
                        switch (response.status) {
                            case 500:
                                $ionicLoading.hide();
                                GlobalService.showError('Server Error');
                                return false;

                            case 401:
                                if ($state.current.name === 'loading') {
                                    error401();
                                    return false;
                                }
                                if (_error !== $rootScope.ERROR_LIST.WRONG_PASSWORD) {
                                    $ionicLoading.hide();
                                    GlobalService.showError(_.startCase(_error)).then(error401);
                                    return false;
                                }
                                break;

                            case 404:
                                if (_error === $rootScope.ERROR_LIST.INVALID_PATIENT_ID) {
                                    GlobalService.showError('Patient not found').then(function () {
                                        var patientService = $injector.get('PatientService');
                                        patientService.clear();
                                        patientService.changeStateByPatient();
                                    });
                                    return false;
                                }
                                break;

                            default:
                                if (response.status == 502 || !response.status) {
                                    $ionicLoading.hide();
                                    $rootScope.parentResponse = response;
                                    $rootScope.promise = deferred;

                                    if (_.isUndefined($rootScope.currentState))
                                        $rootScope.currentState = $state.current.name;

                                    $state.go('retry');
                                    return false;
                                }
                        }

                        return true;
                    })
                });

                function setAccessToken(token) {
                    var headers = OrangeRest.defaultHeaders;
                    accessToken = token;
                    headers['Authorization'] = 'Bearer ' + accessToken;
                    OrangeRest.setDefaultHeaders(headers);
                }

                function error401() {
                    var authService = $injector.get('Auth');
                    authService.logout();
                    $state.go('onboarding');
                }

                return {
                    setAccessToken: setAccessToken,
                    auth: OrangeRest.all('auth'),
                    user: OrangeRest.all('user'),
                    requested: OrangeRest.all('requested'),
                    requests: OrangeRest.all('requests'),
                    patients: OrangeRest.all('patients'),
                    npi: OrangeRest.all('npi'),
                    rxnorm: {
                        search: OrangeRest.all('rxnorm').all('group'),
                        spelling: OrangeRest.all('rxnorm').all('spelling')
                    },
                    medications: OrangeRest.all('medications'),
                    schedule: OrangeRest.all('schedule'),
                    rest: OrangeRest
                }
            }]
        }

    }
})();
<commit_msg>[bugfix][ORANGE-364] Fixed hangs application on loading screen with no connection<commit_after>(function () {
    'use strict';

    angular
        .module('orange')
        .provider('OrangeApi', OrangeApi);

    OrangeApi.$inject = [];

    /* @ngInject */
    function OrangeApi() {
        var baseUrl = null;
        var clientSecret = null;
        var accessToken = null;

        return {
            setBaseUrl: function (url) {
                baseUrl = url;
            },
            setClientSecret: function (secret) {
                clientSecret = secret;
            },
            setAccessToken: function (token) {
                accessToken = token;
            },
            $get: ['Restangular', '$state', '$rootScope', '$ionicLoading', '$injector', 'GlobalService',
                function (Restangular, $state, $rootScope, $ionicLoading, $injector, GlobalService) {

                var OrangeRest = Restangular.withConfig(function (RestangularConfigurer) {

                    RestangularConfigurer.setBaseUrl(baseUrl);
                    RestangularConfigurer.setDefaultHttpFields({cache: false});
                    RestangularConfigurer.setDefaultHeaders({
                        'X-Client-Secret': clientSecret,
                        'Authorization': 'Bearer ' + accessToken
                    });
                    RestangularConfigurer.setDefaultHttpFields({timeout: 30 * 1000});

                    RestangularConfigurer.addRequestInterceptor(function (element) {
                        if (element && element.hasOwnProperty('success')) {
                            delete element['success']
                        }
                        return element;
                    });

                    RestangularConfigurer.addResponseInterceptor(function (data, operation, what, url, response, deferred) {
                        var extractedData = function(obj, key) {
                            var ret;
                            ret = obj[key];
                            delete obj[key];
                            ret.meta = obj;
                            return ret
                        };

                        if (operation == 'getList') {

                            if (data.hasOwnProperty(what)) {
                                return extractedData(data, what)
                            } else if  (data.hasOwnProperty('entries')) {
                                return extractedData(data, 'entries')
                            }

                            return data
                        }

                        return data;
                    });

                    RestangularConfigurer.setErrorInterceptor(function (response, deferred, responseHandler) {
                        if (!_.isUndefined(response.data)) {
                            var _error = (response.data === null) ? [] : response.data.errors[0];
                        }
                        switch (response.status) {
                            case 500:
                                $ionicLoading.hide();
                                GlobalService.showError('Server Error');
                                return false;

                            case 401:
                                if ($state.current.name === 'loading') {
                                    error401();
                                    return false;
                                }
                                if (_error !== $rootScope.ERROR_LIST.WRONG_PASSWORD) {
                                    $ionicLoading.hide();
                                    GlobalService.showError(_.startCase(_error)).then(error401);
                                    return false;
                                }
                                break;

                            case 404:
                                if (_error === $rootScope.ERROR_LIST.INVALID_PATIENT_ID) {
                                    GlobalService.showError('Patient not found').then(function () {
                                        var patientService = $injector.get('PatientService');
                                        patientService.clear();
                                        patientService.changeStateByPatient();
                                    });
                                    return false;
                                }
                                break;

                            default:
                                if (response.status == 502 || !response.status) {
                                    $ionicLoading.hide();
                                    $rootScope.parentResponse = response;
                                    $rootScope.promise = deferred;

                                    if (_.isUndefined($rootScope.currentState))
                                        $rootScope.currentState = $state.current.name;

                                    if ($state.current.name === 'loading') {
                                        return response;
                                    } else {
                                        $state.go('retry');
                                        return false;
                                    }
                                }
                        }

                        return true;
                    })
                });

                function setAccessToken(token) {
                    var headers = OrangeRest.defaultHeaders;
                    accessToken = token;
                    headers['Authorization'] = 'Bearer ' + accessToken;
                    OrangeRest.setDefaultHeaders(headers);
                }

                function error401() {
                    var authService = $injector.get('Auth');
                    authService.logout();
                    $state.go('onboarding');
                }

                return {
                    setAccessToken: setAccessToken,
                    auth: OrangeRest.all('auth'),
                    user: OrangeRest.all('user'),
                    requested: OrangeRest.all('requested'),
                    requests: OrangeRest.all('requests'),
                    patients: OrangeRest.all('patients'),
                    npi: OrangeRest.all('npi'),
                    rxnorm: {
                        search: OrangeRest.all('rxnorm').all('group'),
                        spelling: OrangeRest.all('rxnorm').all('spelling')
                    },
                    medications: OrangeRest.all('medications'),
                    schedule: OrangeRest.all('schedule'),
                    rest: OrangeRest
                }
            }]
        }

    }
})();
<|endoftext|>


<commit_before>function pad(value, length, prefix) {
	value = '' + value;
	if( prefix == undefined ) prefix = '0';
	while( value.length < length ) { value = prefix + value; }
	return value;
}

function ISO_datetimestamp() {
	var date = new Date();
	var y = date.getFullYear();
	var mo = pad( date.getMonth()+1, 2 );
	var d = pad( date.getDate(), 2 );
	var h = pad( date.getHours(), 2);
	var mi = pad( date.getMinutes(), 2);
	var s = pad( date.getSeconds(), 2);
	var zo = -date.getTimezoneOffset();
	var z = ( zo < 0 ? "-" : "+" )
	      + pad( Math.floor( Math.abs(zo) / 60 ), 2 )
	      + pad( Math.floor( Math.abs(zo) % 60 ), 2 );
	return y+"-"+mo+"-"+d+"T"+h+":"+mi+":"+s+z;
}

var vb_host = process.argv[2] || "::1"
var vb_port = process.argv[3] || 8445;

var vb = require('net').createConnection(vb_port, vb_host);
vb.on('error', function() {
	console.log(ISO_datetimestamp() + " Connect to backend ([" + vb_host + "]:" + vb_port + ") failed, exitting...");
	node.exit(1);
});
vb.on('connect', function() {
	console.log(ISO_datetimestamp() + " Connected to backend");
});

var io = require('socket.io').listen(8080, null, "::").set('log level', 0);
io.sockets.on('connection', function (socket) {
	console.log(ISO_datetimestamp() + " New connection from [" + socket.handshake.address.address +"]:"+ socket.handshake.address.port);

	socket.on('disconnect', function () {
		console.log(ISO_datetimestamp() + " Disconnect from [" + socket.handshake.address.address + "]:" + socket.handshake.address.port);
	});
});

var vb_buffer = new Buffer( 2*(4+8+2) ); // We will never need to store more than 2 messages before we can process
var vb_buffer_len = 0;

vb.on('data', function(data) {
	// Add data to buffer
	data.copy(vb_buffer, vb_buffer_len, 0);
	vb_buffer_len += data.length;

next_message:
	while( vb_buffer_len > 6 ) { // Try to parse a message
		if( vb_buffer[0] != 0x0f ) { // Unaligned read
			console.log(ISO_datetimestamp() + " backend: unaligned read, skipping byte");
			vb_buffer.copy(vb_buffer, 0, 1, vb_buffer.length-1);
			vb_buffer_len--;
			continue;
		}

		if( (vb_buffer[1] & 0xfc) != 0xf8
		 || (vb_buffer[3] & 0xb0) != 0x00 ) { // Invalid syntax
			console.log(ISO_datetimestamp() + " backend: invalid message");
			vb_buffer.copy(vb_buffer, 0, 1, vb_buffer.length-1);
			vb_buffer_len--;
			continue;
		}

		var len = vb_buffer[3] & 0x0f;
		if( vb_buffer_len < 6+len ) break; // and wait for more data

		var msg = {};
		msg.addr = vb_buffer[2];
		msg.prio = vb_buffer[1] & 0x03;
		msg.rtr = vb_buffer[3] & 0x40;
		msg.data = new Buffer(len);
		vb_buffer.copy(msg.data, 0, 4, 4+len);

		// Remove message from buffer
		vb_buffer.copy(vb_buffer, 0, 6+len, vb_buffer.length-6-len);
		vb_buffer_len -= 6+len;

		// Parse the message
		if( msg.data[0] == 0xfb ) {
			var rs = {};

			var relay;
			switch(msg.data[1]) {
			case 0x01: relay = 0; break;
			case 0x02: relay = 1; break;
			case 0x04: relay = 2; break;
			case 0x08: relay = 3; break;
			case 0x10: relay = 4; break;
			default: continue next_message;
			}

			rs.id = pad(msg.addr.toString(16), 2) + "." + relay
			switch(msg.data[3]) {
			case 0x00: rs.status="off"; break;
			case 0x01: rs.status="on"; break;
			case 0x03: rs.status="interval"; break;
			default: continue next_message;
			}

			io.sockets.emit('RelayStatus', rs);
		}
	}
});
<commit_msg>Added cache inside NodeJS for last messages<commit_after>function pad(value, length, prefix) {
	value = '' + value;
	if( prefix == undefined ) prefix = '0';
	while( value.length < length ) { value = prefix + value; }
	return value;
}

function ISO_datetimestamp() {
	var date = new Date();
	var y = date.getFullYear();
	var mo = pad( date.getMonth()+1, 2 );
	var d = pad( date.getDate(), 2 );
	var h = pad( date.getHours(), 2);
	var mi = pad( date.getMinutes(), 2);
	var s = pad( date.getSeconds(), 2);
	var zo = -date.getTimezoneOffset();
	var z = ( zo < 0 ? "-" : "+" )
	      + pad( Math.floor( Math.abs(zo) / 60 ), 2 )
	      + pad( Math.floor( Math.abs(zo) % 60 ), 2 );
	return y+"-"+mo+"-"+d+"T"+h+":"+mi+":"+s+z;
}

var vb_host = process.argv[2] || "::1"
var vb_port = process.argv[3] || 8445;

var vb = require('net').createConnection(vb_port, vb_host);
vb.on('error', function() {
	console.log(ISO_datetimestamp() + " Connect to backend ([" + vb_host + "]:" + vb_port + ") failed, exitting...");
	node.exit(1);
});
vb.on('connect', function() {
	console.log(ISO_datetimestamp() + " Connected to backend");
});

VbState = function() {};
VbState.prototype.update = function(id, state) {
	this[id] = state;
	console.log(ISO_datetimestamp() + " VB: " + id + " : " + state);
	io.sockets.emit('message', { "id": id, "state": state } );
};
var vb_state = new VbState();

var io = require('socket.io').listen(8080, null, "::").set('log level', 0);
io.sockets.on('connection', function (socket) {
	console.log(ISO_datetimestamp() + " New connection from [" + socket.handshake.address.address +"]:"+ socket.handshake.address.port);

	socket.on('disconnect', function () {
		console.log(ISO_datetimestamp() + " Disconnect from [" + socket.handshake.address.address + "]:" + socket.handshake.address.port);
	});

	for(var id in vb_state) {
		if( typeof(vb_state[id]) == 'function' ) continue;
		socket.emit('message', {"id": id, "state": vb_state[id]} );
	}
});

var vb_buffer = new Buffer( 2*(4+8+2) ); // We will never need to store more than 2 messages before we can process
var vb_buffer_len = 0;

vb.on('data', function(data) {
	// Add data to buffer
	data.copy(vb_buffer, vb_buffer_len, 0);
	vb_buffer_len += data.length;

next_message:
	while( vb_buffer_len > 6 ) { // Try to parse a message
		if( vb_buffer[0] != 0x0f ) { // Unaligned read
			console.log(ISO_datetimestamp() + " backend: unaligned read, skipping byte");
			vb_buffer.copy(vb_buffer, 0, 1, vb_buffer.length-1);
			vb_buffer_len--;
			continue;
		}

		if( (vb_buffer[1] & 0xfc) != 0xf8
		 || (vb_buffer[3] & 0xb0) != 0x00 ) { // Invalid syntax
			console.log(ISO_datetimestamp() + " backend: invalid message");
			vb_buffer.copy(vb_buffer, 0, 1, vb_buffer.length-1);
			vb_buffer_len--;
			continue;
		}

		var len = vb_buffer[3] & 0x0f;
		if( vb_buffer_len < 6+len ) break; // and wait for more data

		var msg = {};
		msg.addr = vb_buffer[2];
		msg.prio = vb_buffer[1] & 0x03;
		msg.rtr = vb_buffer[3] & 0x40;
		msg.data = new Buffer(len);
		vb_buffer.copy(msg.data, 0, 4, 4+len);

		// Remove message from buffer
		vb_buffer.copy(vb_buffer, 0, 6+len, vb_buffer.length-6-len);
		vb_buffer_len -= 6+len;

		// Parse the message
		if( msg.data[0] == 0xfb ) {
			var relay;
			switch(msg.data[1]) {
			case 0x01: relay = 0; break;
			case 0x02: relay = 1; break;
			case 0x04: relay = 2; break;
			case 0x08: relay = 3; break;
			case 0x10: relay = 4; break;
			default: continue next_message;
			}
			var id = pad(msg.addr.toString(16), 2) + "." + relay

			var state;
			switch(msg.data[3]) {
			case 0x00: state="off"; break;
			case 0x01: state="on"; break;
			case 0x03: state="interval"; break;
			default: continue next_message;
			}

			vb_state.update(id, state);
		} else if( msg.data[0] == 0xec ) {
			var blind;
			switch(msg.data[1]) {
			case 0x03: blind = 0; break;
			case 0x0c: blind = 1; break;
			default: continue next_message;
			}
			var id = pad(msg.addr.toString(16), 2) + "." + blind;

			var state;
			switch(msg.data[3]) {
			case 0x00:
				if( vb_state[id] == 'going up' ) state="up";
				else if( vb_state[id] == 'going down' ) state="down";
				else state="stopped";
				break;
			case 0x01:
			case 0x04: state="going up"; break;
			case 0x02:
			case 0x08: state="going down"; break;
			default: continue next_message;
			}

			vb_state.update(id, state);
		}
	}
});
<|endoftext|>