<commit_before>// ==UserScript==
// @name        GitHub Code Show Whitespace
// @version     1.2.7
// @description A userscript that shows whitespace (space, tabs and carriage returns) in code blocks
// @license     MIT
// @author      Rob Garrison
// @namespace   https://github.com/Mottie
// @include     https://github.com/*
// @include     https://gist.github.com/*
// @run-at      document-idle
// @grant       GM_registerMenuCommand
// @grant       GM.registerMenuCommand
// @grant       GM.addStyle
// @grant       GM_addStyle
// @grant       GM.getValue
// @grant       GM_getValue
// @grant       GM.setValue
// @grant       GM_setValue
// @require     https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js?updated=20180103
// @require     https://greasyfork.org/scripts/28721-mutations/code/mutations.js?version=666427
// @icon        https://github.githubassets.com/pinned-octocat.svg
// @updateURL   https://raw.githubusercontent.com/Mottie/Github-userscripts/master/github-code-show-whitespace.user.js
// @downloadURL https://raw.githubusercontent.com/Mottie/Github-userscripts/master/github-code-show-whitespace.user.js
// ==/UserScript==
(async () => {
	"use strict";

	let showWhiteSpace = await GM.getValue("show-whitespace", "false");

	// include em-space & en-space?
	const whitespace = {
			// Applies \xb7 (·) to every space
			"%20"  : " ",
			// Applies \xb7 (·) to every non-breaking space (alternative: \u2423 (␣))
			"%A0"  : " ",
			// Applies \xbb (») to every tab
			"%09"  : "\x09",
			// non-matching key; applied manually
			// Applies \u231d (⌝) to the end of every line
			// (alternatives: \u21b5 (↵) or \u2938 (⤸))
			"CRLF" : "\n"
		},
		span = document.createElement("span"),
		// ignore +/- in diff code blocks
		regexWS = /(\x20| |\x09)/g,
		regexCR = /\r*\n$/,
		regexExceptions = /(\.md)$/i,

		toggleButton = document.createElement("div");
	toggleButton.className = "ghcw-toggle btn btn-sm tooltipped tooltipped-s";
	toggleButton.setAttribute("aria-label", "Toggle Whitespace");
	toggleButton.innerHTML = "";

	GM.addStyle(`
		.ghcw-active .ghcw-whitespace,
		.gist-content-wrapper .file-actions .btn-group {
			position: relative;
			display: inline;
		}
		.ghcw-active .ghcw-whitespace:before {
			position: absolute;
			opacity: .5;
			user-select: none;
			font-weight: bold;
			color: #777 !important;
			top: -.25em;
			left: 0;
		}
		.ghcw-toggle .pl-tab {
			pointer-events: none;
		}
		.ghcw-active .pl-space:before {
			content: "\\b7";
		}
		.ghcw-active .pl-nbsp:before {
			content: "\\b7";
		}
		.ghcw-active .pl-tab:before,
		.ghcw-toggle .pl-tab:before {
			content: "\\bb";
		}
		.ghcw-active .pl-crlf:before {
			content: "\\231d";
			top: .1em;
		}
		/* weird tweak for diff markdown files - see #27 */
		.ghcw-adjust .ghcw-active .ghcw-whitespace:before {
			left: .6em;
		}
		/* hide extra leading space added to diffs - see #27 */
		.diff-table tr.blob-expanded td > span:first-child .pl-space:first-child {
			visibility: hidden;
		}
		.blob-code-inner > br {
			display: none !important;
		}
	`);

	function addToggle() {
		$$(".file-actions").forEach(el => {
			if (!$(".ghcw-toggle", el)) {
				el.insertBefore(toggleButton.cloneNode(true), el.childNodes[0]);
			}
			if (showWhiteSpace === "true") {
				// Let the page render a bit before going nuts
				setTimeout(show(el, true), 200);
			}
		});
	}

	function getNodes(line) {
		const nodeIterator = document.createNodeIterator(
			line,
			NodeFilter.SHOW_TEXT,
			() => NodeFilter.FILTER_ACCEPT
		);
		let currentNode,
			nodes = [];
		while ((currentNode = nodeIterator.nextNode())) {
			nodes.push(currentNode);
		}
		return nodes;
	}

	function escapeHTML(html) {
		return html.replace(/[<>"'&]/g, m => ({
			"<": "<",
			">": ">",
			"&": "&",
			"'": "'",
			"\"": """
		}[m]));
	}

	function replaceWhitespace(html) {
		return escapeHTML(html).replace(regexWS, s => {
			let idx = 0,
				ln = s.length,
				result = "";
			for (idx = 0; idx < ln; idx++) {
				result += whitespace[encodeURI(s[idx])] || s[idx] || "";
			}
			return result;
		});
	}

	function replaceTextNode(nodes) {
		let node, indx, el,
			ln = nodes.length;
		for (indx = 0; indx < ln; indx++) {
			node = nodes[indx];
			if (
				node &&
				node.nodeType === 3 &&
				node.textContent &&
				node.textContent.search(regexWS) > -1
			) {
				el = span.cloneNode();
				el.innerHTML = replaceWhitespace(node.textContent.replace(regexCR, ""));
				node.parentNode.insertBefore(el, node);
				node.parentNode.removeChild(node);
			}
		}
	}

	function* modifyLine(lines) {
		while (lines.length) {
			const line = lines.shift();
			// first node is a syntax string and may have leading whitespace
			replaceTextNode(getNodes(line));
			// remove end CRLF if it exists; then add a line ending
			const html = line.innerHTML;
			const update = html.replace(regexCR, "") + whitespace.CRLF;
			if (update !== html) {
				line.innerHTML = update;
			}
		}
		yield lines;
	}

	function addWhitespace(block) {
		if (block && !block.classList.contains("ghcw-processed")) {
			block.classList.add("ghcw-processed");
			let status;

			// class name of each code row
			const lines = $$(".blob-code-inner:not(.blob-code-hunk)", block);
			const iter = modifyLine(lines);

			// loop with delay to allow user interaction
			const loop = () => {
				for (let i = 0; i < 40; i++) {
					status = iter.next();
				}
				if (!status.done) {
					requestAnimationFrame(loop);
				}
			};
			loop();
		}
	}

	function detectDiff(wrap) {
		const header = $(".file-header", wrap);
		if ($(".diff-table", wrap) && header) {
			const file = header.getAttribute("data-path");
			if (
				// File Exceptions that need tweaking (e.g. ".md")
				regexExceptions.test(file) ||
				// files with no extension (e.g. LICENSE)
				file.indexOf(".") === -1
			) {
				// This class is added to adjust the position of the whitespace
				// markers for specific files; See issue #27
				wrap.classList.add("ghcw-adjust");
			}
		}
	}

	function showAll() {
		$$(".file .highlight").forEach(target => {
			show(target, true);
		});
	}

	function show(target, state) {
		const wrap = target.closest(".file");
		const block = $(".highlight", wrap);
		if (block) {
			wrap.querySelector(".ghcw-toggle").classList.toggle("selected", state);
			block.classList.toggle("ghcw-active", state);
			detectDiff(wrap);
			addWhitespace(block);
		}
	}

	function $(selector, el) {
		return (el || document).querySelector(selector);
	}

	function $$(selector, el) {
		return [...(el || document).querySelectorAll(selector)];
	}

	// bind whitespace toggle button
	document.addEventListener("click", event => {
		const target = event.target;
		if (
			target.nodeName === "DIV" &&
			target.classList.contains("ghcw-toggle")
		) {
			show(target);
		}
	});

	GM.registerMenuCommand("Set GitHub Code White Space", async () => {
		let val = prompt("Always show on page load (true/false)?", showWhiteSpace);
		if (val !== null) {
			val = (val || "").toLowerCase();
			await GM.setValue("show-whitespace", val);
			showWhiteSpace = val;
			showAll();
		}
	});

	document.addEventListener("ghmo:container", addToggle);
	document.addEventListener("ghmo:diff", addToggle);
	// toggle added to diff & file view
	addToggle();

})();
<commit_msg>Code-show-whitespace: Fix alignment in new diff layout<commit_after>// ==UserScript==
// @name        GitHub Code Show Whitespace
// @version     1.2.8
// @description A userscript that shows whitespace (space, tabs and carriage returns) in code blocks
// @license     MIT
// @author      Rob Garrison
// @namespace   https://github.com/Mottie
// @include     https://github.com/*
// @include     https://gist.github.com/*
// @run-at      document-idle
// @grant       GM_registerMenuCommand
// @grant       GM.registerMenuCommand
// @grant       GM.addStyle
// @grant       GM_addStyle
// @grant       GM.getValue
// @grant       GM_getValue
// @grant       GM.setValue
// @grant       GM_setValue
// @require     https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js?updated=20180103
// @require     https://greasyfork.org/scripts/28721-mutations/code/mutations.js?version=666427
// @icon        https://github.githubassets.com/pinned-octocat.svg
// @updateURL   https://raw.githubusercontent.com/Mottie/Github-userscripts/master/github-code-show-whitespace.user.js
// @downloadURL https://raw.githubusercontent.com/Mottie/Github-userscripts/master/github-code-show-whitespace.user.js
// ==/UserScript==
(async () => {
	"use strict";

	let showWhiteSpace = await GM.getValue("show-whitespace", "false");

	// include em-space & en-space?
	const whitespace = {
			// Applies \xb7 (·) to every space
			"%20"  : " ",
			// Applies \xb7 (·) to every non-breaking space (alternative: \u2423 (␣))
			"%A0"  : " ",
			// Applies \xbb (») to every tab
			"%09"  : "\x09",
			// non-matching key; applied manually
			// Applies \u231d (⌝) to the end of every line
			// (alternatives: \u21b5 (↵) or \u2938 (⤸))
			"CRLF" : "\n"
		},
		span = document.createElement("span"),
		// ignore +/- in diff code blocks
		regexWS = /(\x20| |\x09)/g,
		regexCR = /\r*\n$/,
		regexExceptions = /(\.md)$/i,

		toggleButton = document.createElement("div");
	toggleButton.className = "ghcw-toggle btn btn-sm tooltipped tooltipped-s";
	toggleButton.setAttribute("aria-label", "Toggle Whitespace");
	toggleButton.innerHTML = "";

	GM.addStyle(`
		div.file-actions > div,
		.ghcw-active .ghcw-whitespace,
		.gist-content-wrapper .file-actions .btn-group {
			position: relative;
			display: inline;
		}
		.ghcw-active .ghcw-whitespace:before {
			position: absolute;
			opacity: .5;
			user-select: none;
			font-weight: bold;
			color: #777 !important;
			top: -.25em;
			left: 0;
		}
		.ghcw-toggle .pl-tab {
			pointer-events: none;
		}
		.ghcw-active .pl-space:before {
			content: "\\b7";
		}
		.ghcw-active .pl-nbsp:before {
			content: "\\b7";
		}
		.ghcw-active .pl-tab:before,
		.ghcw-toggle .pl-tab:before {
			content: "\\bb";
		}
		.ghcw-active .pl-crlf:before {
			content: "\\231d";
			top: .1em;
		}
		/* weird tweak for diff markdown files - see #27 */
		.ghcw-adjust .ghcw-active .ghcw-whitespace:before {
			left: .6em;
		}
		/* hide extra leading space added to diffs - see #27 */
		.diff-table tr.blob-expanded td > span:first-child .pl-space:first-child {
			visibility: hidden;
		}
		.blob-code-inner > br {
			display: none !important;
		}
	`);

	function addToggle() {
		$$(".file-actions").forEach(el => {
			if (!$(".ghcw-toggle", el)) {
				el.insertBefore(toggleButton.cloneNode(true), el.childNodes[0]);
			}
			if (showWhiteSpace === "true") {
				// Let the page render a bit before going nuts
				setTimeout(show(el, true), 200);
			}
		});
	}

	function getNodes(line) {
		const nodeIterator = document.createNodeIterator(
			line,
			NodeFilter.SHOW_TEXT,
			() => NodeFilter.FILTER_ACCEPT
		);
		let currentNode,
			nodes = [];
		while ((currentNode = nodeIterator.nextNode())) {
			nodes.push(currentNode);
		}
		return nodes;
	}

	function escapeHTML(html) {
		return html.replace(/[<>"'&]/g, m => ({
			"<": "<",
			">": ">",
			"&": "&",
			"'": "'",
			"\"": """
		}[m]));
	}

	function replaceWhitespace(html) {
		return escapeHTML(html).replace(regexWS, s => {
			let idx = 0,
				ln = s.length,
				result = "";
			for (idx = 0; idx < ln; idx++) {
				result += whitespace[encodeURI(s[idx])] || s[idx] || "";
			}
			return result;
		});
	}

	function replaceTextNode(nodes) {
		let node, indx, el,
			ln = nodes.length;
		for (indx = 0; indx < ln; indx++) {
			node = nodes[indx];
			if (
				node &&
				node.nodeType === 3 &&
				node.textContent &&
				node.textContent.search(regexWS) > -1
			) {
				el = span.cloneNode();
				el.innerHTML = replaceWhitespace(node.textContent.replace(regexCR, ""));
				node.parentNode.insertBefore(el, node);
				node.parentNode.removeChild(node);
			}
		}
	}

	function* modifyLine(lines) {
		while (lines.length) {
			const line = lines.shift();
			// first node is a syntax string and may have leading whitespace
			replaceTextNode(getNodes(line));
			// remove end CRLF if it exists; then add a line ending
			const html = line.innerHTML;
			const update = html.replace(regexCR, "") + whitespace.CRLF;
			if (update !== html) {
				line.innerHTML = update;
			}
		}
		yield lines;
	}

	function addWhitespace(block) {
		if (block && !block.classList.contains("ghcw-processed")) {
			block.classList.add("ghcw-processed");
			let status;

			// class name of each code row
			const lines = $$(".blob-code-inner:not(.blob-code-hunk)", block);
			const iter = modifyLine(lines);

			// loop with delay to allow user interaction
			const loop = () => {
				for (let i = 0; i < 40; i++) {
					status = iter.next();
				}
				if (!status.done) {
					requestAnimationFrame(loop);
				}
			};
			loop();
		}
	}

	function detectDiff(wrap) {
		const header = $(".file-header", wrap);
		if ($(".diff-table", wrap) && header) {
			const file = header.getAttribute("data-path");
			if (
				// File Exceptions that need tweaking (e.g. ".md")
				regexExceptions.test(file) ||
				// files with no extension (e.g. LICENSE)
				file.indexOf(".") === -1
			) {
				// This class is added to adjust the position of the whitespace
				// markers for specific files; See issue #27
				wrap.classList.add("ghcw-adjust");
			}
		}
	}

	function showAll() {
		$$(".file .highlight").forEach(target => {
			show(target, true);
		});
	}

	function show(target, state) {
		const wrap = target.closest(".file");
		const block = $(".highlight", wrap);
		if (block) {
			wrap.querySelector(".ghcw-toggle").classList.toggle("selected", state);
			block.classList.toggle("ghcw-active", state);
			detectDiff(wrap);
			addWhitespace(block);
		}
	}

	function $(selector, el) {
		return (el || document).querySelector(selector);
	}

	function $$(selector, el) {
		return [...(el || document).querySelectorAll(selector)];
	}

	// bind whitespace toggle button
	document.addEventListener("click", event => {
		const target = event.target;
		if (
			target.nodeName === "DIV" &&
			target.classList.contains("ghcw-toggle")
		) {
			show(target);
		}
	});

	GM.registerMenuCommand("Set GitHub Code White Space", async () => {
		let val = prompt("Always show on page load (true/false)?", showWhiteSpace);
		if (val !== null) {
			val = (val || "").toLowerCase();
			await GM.setValue("show-whitespace", val);
			showWhiteSpace = val;
			showAll();
		}
	});

	document.addEventListener("ghmo:container", addToggle);
	document.addEventListener("ghmo:diff", addToggle);
	// toggle added to diff & file view
	addToggle();

})();
<|endoftext|>


<commit_before>
import * as Promise from 'bluebird'

import { removePageFromMarkSearch } from './removePageFromMarkSearch'
import { checkIfPageIsSaved } from './checkIfPageIsSaved'
import { updateIcon } from './updateIcon'
import { sendMessageToNotifyContentScript } from './sendMessageToNotifyContentScript'
import { errorLogger } from './errorLogger'
import { marksearchServerAddress, marksearchApiToken } from './serverAddressAndToken'
import { insertContentScript } from './utils'

function browserActionEventHandler(tab){
  /*****
  * Put showNotification_ContentScript script in straight away so we can notify user of success/failure.
  * Need to check first if it is already running on the page as it has a message listener & multiple
  * showNotification_ContentScript scripts will mean multiple listeners and multiple notifications.
  *
  * Using bluebird here so that can use .bind for 'action',  'tab' et.al. so they don't get overwritten if another
  * browserActionEventHandler runs before this finishes. (need to use non-arrow functions where using this.
  * so the this context isnt messed up)
  */

  /* eslint-disable no-invalid-this */
  Promise.resolve()
    .bind({action: 'saving or removing', tab, noToken: false})
    .then(() => sendMessageToNotifyContentScript({notifyScriptRunningCheck: true}))
    .then( response => {
      if(!response || !response.scriptAlreadyInserted){
        insertContentScript('showNotification_ContentScript.build.js')
      }
    })
    .then(function() {
      /*****
      * If they havent yet saved the MarkSearch token to the extension settings page, then throw.
      * We need to wait untill the showNotification_ContentScript is inserted before we check the tokens are saved
      * as we will need that content script to inform the user that they haven't saved the them.
      * We send the error info with sendMessageToNotifyContentScript in the catch at the end of the promise
      * chain below.
      */
      if(!marksearchServerAddress || !marksearchApiToken){
        this.noToken = true
        throw new Error('Token not saved in extension settings')
      }
      return checkIfPageIsSaved(this.tab.id)
    })
    .then(function(pageIsSavedInMarkSearch){
      /*****
      * If they have clicked on the button and the page is already saved, remove it.
      */
      if(pageIsSavedInMarkSearch){
        /*****
        * removePageFromMarkSearch resolves true if it successfully removed the page
        */
        return removePageFromMarkSearch(this.tab.url)
      }
      /*****
      * If it's not saved, run the content script to save it.
      * Note: dont' have to worry about multiple sendPageData_ContentScript's being on the page as
      * it doesn't have any message/event listeners and just sends a single message straight away.
      */
      this.action = 'savePage'
      insertContentScript('sendPageData_ContentScript.build.js')
      /*****
      * return false to indicate we didn't remove a page
      */
      return false
    })
    .then(function(successfullyRemovedPage){
      if(successfullyRemovedPage){
        this.action = 'removedPage'
        const pageIsSavedInMarkSearch = false
        updateIcon(pageIsSavedInMarkSearch, this.tab.id)
        return sendMessageToNotifyContentScript(
          {
            action: this.action,
            actionSucceeded: true
          }
        )
      }
    })
    .catch(function(error){
      /*****
      * If we get here then checkIfPageIsSaved or removePageFromMarkSearch didn't work, or there was no
      * token saved in the settings. We should notify the user.
      */
      errorLogger(error)
      const errorMessage = `There was an error ${ this.action } this page from MarkSearch.
                            ${ (error && error.message) ? error.message : '' }`
      sendMessageToNotifyContentScript(
        {
          action: this.action,
          actionSucceeded: false,
          errorMessage,
          noTokens: this.noToken
        }
      )
    })
    /* eslint-enable no-invalid-this */
}

export { browserActionEventHandler }
<commit_msg>Comment<commit_after>
import * as Promise from 'bluebird'

import { removePageFromMarkSearch } from './removePageFromMarkSearch'
import { checkIfPageIsSaved } from './checkIfPageIsSaved'
import { updateIcon } from './updateIcon'
import { sendMessageToNotifyContentScript } from './sendMessageToNotifyContentScript'
import { errorLogger } from './errorLogger'
import { marksearchServerAddress, marksearchApiToken } from './serverAddressAndToken'
import { insertContentScript } from './utils'

function browserActionEventHandler(tab){
  /*****
  * Put showNotification_ContentScript script in straight away so we can notify user of success/failure.
  * Need to check first if it is already running on the page as it has a message listener & multiple
  * showNotification_ContentScript scripts will mean multiple listeners and multiple notifications.
  *
  * Using bluebird here so that can use .bind for 'action',  'tab' et.al. so they don't get overwritten if another
  * browserActionEventHandler runs before this finishes. (need to use non-arrow functions where using this.
  * so the this context isnt messed up)
  */

  /* eslint-disable no-invalid-this */
  Promise.resolve()
    .bind({action: 'saving or removing', tab, noToken: false})
    .then(() => sendMessageToNotifyContentScript({notifyScriptRunningCheck: true}))
    .then( response => {
      if(!response || !response.scriptAlreadyInserted){
        insertContentScript('showNotification_ContentScript.build.js')
      }
    })
    .then(function() {
      /*****
      * If they havent yet saved the MarkSearch token to the extension settings page, then throw.
      * We need to wait untill the showNotification_ContentScript is inserted before we check the tokens are saved
      * as we will need that content script to inform the user that they haven't saved the them.
      * We send the error info with sendMessageToNotifyContentScript in the catch at the end of the promise
      * chain below.
      */
      if(!marksearchServerAddress || !marksearchApiToken){
        this.noToken = true
        throw new Error('Token not saved in extension settings')
      }
      return checkIfPageIsSaved(this.tab.id)
    })
    .then(function(pageIsSavedInMarkSearch){
      /*****
      * If they have clicked on the button and the page is already saved, remove it.
      */
      if(pageIsSavedInMarkSearch){
        /*****
        * removePageFromMarkSearch resolves true if it successfully removed the page
        */
        return removePageFromMarkSearch(this.tab.url)
      }
      /*****
      * If it's not saved, run the content script to save it.
      * Note: dont' have to worry about multiple sendPageData_ContentScript's being on the page as
      * it doesn't have any message/event listeners and just sends a single message straight away.
      */
      this.action = 'savePage'
      insertContentScript('sendPageData_ContentScript.build.js')
      /*****
      * return false to indicate we didn't remove a page
      */
      return false
    })
    .then(function(successfullyRemovedPage){
      if(successfullyRemovedPage){
        this.action = 'removedPage'
        const pageIsSavedInMarkSearch = false
        updateIcon(pageIsSavedInMarkSearch, this.tab.id)
        return sendMessageToNotifyContentScript(
          {
            action: this.action,
            actionSucceeded: true
          }
        )
      }
    })
    .catch(function(error){
      /*****
      * If we get here then checkIfPageIsSaved or removePageFromMarkSearch didn't work, or there was no
      * token saved in the settings. Log error and notify the user.
      */
      errorLogger(error)
      const errorMessage = `There was an error ${ this.action } this page from MarkSearch.
                            ${ (error && error.message) ? error.message : '' }`
      sendMessageToNotifyContentScript(
        {
          action: this.action,
          actionSucceeded: false,
          errorMessage,
          noTokens: this.noToken
        }
      )
    })
    /* eslint-enable no-invalid-this */
}

export { browserActionEventHandler }
<|endoftext|>


<commit_before>import TokenStack from './token_stack';

export function setTokensForIndex(index, token, tokens) {
  let key = `${index}`;
  if (tokens[key] instanceof Array === false) tokens[key] = [];
  return tokens[key].push(token);
}

export function getTokensForIndex(index, tokens) {
  if (!tokens[`${index}`]) return [];
  return tokens[`${index}`].reverse();
}

function updateStack(stack, token) {
  // todo: add check to handle dangling end token
  switch (token.type) {
    case 'BLOCK_END':
      stack.pop();
      break;
    case 'RANGE_END':
      stack.pop();
      break;
    case 'BLOCK_START':
      stack.push(token);
      break;
    case 'RANGE_START':
      stack.push(token);
      break;
    default:
      break;
  }
}

function handleBufferedTokens(tokens, stack, fixedTokens) {
  if (tokens.length > 0) {
    tokens.forEach((token) => {
      fixedTokens.push(token);
      updateStack(stack, token);
    });
  }
}

function isBlock(token) {
  return token.type === 'BLOCK_START' || token.type === 'BLOCK_END';
}

function isRange(token) {
  return token.type === 'RANGE_START' || token.type === 'RANGE_END';
}

function isEndToken(token) {
  return token.type === 'RANGE_END' || token.type === 'BLOCK_END';
}

function isStartToken(token) {
  return token.type === 'RANGE_START' || token.type === 'BLOCK_START';
}

function isMatching(t1, t2) {
  if (t1.name !== t2.name) return false;

  if (
    (isStartToken(t1) && isEndToken(t2)) ||
    (isStartToken(t2) && isEndToken(t1))
  ) {
    return true;
  }

  return false;
}

function createVirtualToken(token) {
  return Object.assign({}, token, { _virtual: true });
}

function createMatch(token) {
  let type;
  if (isBlock(token) && isStartToken(token)) type = 'BLOCK_END';
  if (isBlock(token) && isEndToken(token)) type = 'BLOCK_START';
  if (isRange(token) && isStartToken(token)) type = 'RANGE_END';
  if (isRange(token) && isEndToken(token)) type = 'RANGE_START';
  return Object.assign({}, createVirtualToken(token), { type });
}

// Returns true if the given token end the most recent token in the stack
function closesPreviousToken(token, stack) {
  let lastStackToken = stack.at(stack.length - 1);
  if (lastStackToken.name === token.name && isStartToken(lastStackToken) && isEndToken(token)) {
    return true;
  }
  return false;
}

function closeOpenTokens(fixedTokens, stack) {
  // push ending tokens until we find a start
  let stackAllIndex = stack.length - 1;
  while (stack.length > 0) {
    let newMatchingToken = createMatch(stack.at(stackAllIndex));
    fixedTokens.push(newMatchingToken);
    updateStack(stack, newMatchingToken);
    stackAllIndex -= 1;
  }
}

const hasVisibleChars = /\S/;
export function isVisibleToken(token) {
  if (!token.chars) return false;
  return !!hasVisibleChars.exec(token.chars);
}

export function normalize(tokens) {
  let tokensForIndex = {}; // buffer for tokens waiting to be inserted
  let stack = new TokenStack();
  let newMatchingToken;
  let fixedTokens = [];
  let stackAllIndex;
  tokens.forEach((token, index) => {
    let bufferedTokens = getTokensForIndex(index, tokensForIndex);
    handleBufferedTokens(bufferedTokens, stack, fixedTokens);

    // no tokens allowed between table cells
    // if (
    //   !isTableCell(token) &&
    //   !isTableRow(token) &&
    //   !isInTableCell(stack) &&
    //   isInTableRow(stack)) {
    //   return;
    // }

    if (!isEndToken(token)) {
      fixedTokens.push(token);
      updateStack(stack, token);
      return;
    }

    // At this point we know we are dealing with a block or range ending token

    // The happy path. This ending token matches the opening token
    if (closesPreviousToken(token, stack)) {
      fixedTokens.push(token);
      updateStack(stack, token);
      return;
    }

    // if there can be no matching start token dont add to fixed tokens.
    if (!stack.contains(token.name)) {
      return;
    }

    // if closing a table cell close any open tokens
    if (token.name === 'TABLE_CELL') {
      // push ending tokens until we find a TABLE_CELL start
      stackAllIndex = stack.length - 1;
      while (!isMatching(token, stack.at(stackAllIndex))) {
        newMatchingToken = createMatch(stack.at(stackAllIndex));
        fixedTokens.push(newMatchingToken);
        updateStack(stack, newMatchingToken);
        stackAllIndex -= 1;
      }
      fixedTokens.push(token);
      updateStack(stack, token);
      return;
    }

    // push ending tokens until we find a start
    stackAllIndex = stack.length - 1;
    while (!isMatching(token, stack.at(stackAllIndex))) {
      if (stack.at(stackAllIndex).name === 'TABLE_CELL' && isStartToken(stack.at(stackAllIndex))) {
        return;
      }
      newMatchingToken = createMatch(stack.at(stackAllIndex));
      setTokensForIndex(index + 1, createVirtualToken(stack.at(stackAllIndex)), tokensForIndex);
      fixedTokens.push(newMatchingToken);
      updateStack(stack, newMatchingToken);
      // buffer starting tokens to be pushed for the next index
      stackAllIndex -= 1;
    }
    fixedTokens.push(token);
    updateStack(stack, token);
  });

  // if there are any open tokens still left on the tack close them
  closeOpenTokens(fixedTokens, stack);
  return fixedTokens;
}
<commit_msg>export functions and fix import path<commit_after>import TokenStack from './token_stack';
import { insertTableTokens } from './table_utils';

export function setTokensForIndex(index, token, tokens) {
  let key = `${index}`;
  if (tokens[key] instanceof Array === false) tokens[key] = [];
  return tokens[key].push(token);
}

export function getTokensForIndex(index, tokens) {
  if (!tokens[`${index}`]) return [];
  return tokens[`${index}`].reverse();
}

export function updateStack(stack, token) {
  // todo: add check to handle dangling end token
  switch (token.type) {
    case 'BLOCK_END':
      stack.pop();
      break;
    case 'RANGE_END':
      stack.pop();
      break;
    case 'BLOCK_START':
      stack.push(token);
      break;
    case 'RANGE_START':
      stack.push(token);
      break;
    default:
      break;
  }
}

function handleBufferedTokens(tokens, stack, fixedTokens) {
  if (tokens.length > 0) {
    tokens.forEach((token) => {
      fixedTokens.push(token);
      updateStack(stack, token);
    });
  }
}

export function isBlock(token) {
  return token.type === 'BLOCK_START' || token.type === 'BLOCK_END';
}

export function isRange(token) {
  return token.type === 'RANGE_START' || token.type === 'RANGE_END';
}

export function isEndToken(token) {
  return token.type === 'RANGE_END' || token.type === 'BLOCK_END';
}

export function isStartToken(token) {
  return token.type === 'RANGE_START' || token.type === 'BLOCK_START';
}

export function isMatching(t1, t2) {
  if (t1.name !== t2.name) return false;

  if (
    (isStartToken(t1) && isEndToken(t2)) ||
    (isStartToken(t2) && isEndToken(t1))
  ) {
    return true;
  }

  return false;
}

export function createVirtualToken(token) {
  return Object.assign({}, token, { _virtual: true });
}

export function createMatch(token) {
  let type;
  if (isBlock(token) && isStartToken(token)) type = 'BLOCK_END';
  if (isBlock(token) && isEndToken(token)) type = 'BLOCK_START';
  if (isRange(token) && isStartToken(token)) type = 'RANGE_END';
  if (isRange(token) && isEndToken(token)) type = 'RANGE_START';
  return Object.assign({}, createVirtualToken(token), { type });
}

// Returns true if the given token end the most recent token in the stack
export function closesPreviousToken(token, stack) {
  let lastStackToken = stack.at(stack.length - 1);
  if (lastStackToken.name === token.name && isStartToken(lastStackToken) && isEndToken(token)) {
    return true;
  }
  return false;
}

export function closeOpenTokens(fixedTokens, stack) {
  // push ending tokens until we find a start
  let stackAllIndex = stack.length - 1;
  while (stack.length > 0) {
    let newMatchingToken = createMatch(stack.at(stackAllIndex));
    fixedTokens.push(newMatchingToken);
    updateStack(stack, newMatchingToken);
    stackAllIndex -= 1;
  }
}

const hasVisibleChars = /\S/;
export function isVisibleToken(token) {
  if (!token.chars) return false;
  return !!hasVisibleChars.exec(token.chars);
}

// todo: add middleware to handle tables
export function normalize(tokens) {
  let tokensForIndex = {}; // buffer for tokens waiting to be inserted
  let stack = new TokenStack();
  let newMatchingToken;
  let fixedTokens = [];
  let stackAllIndex;
  tokens.forEach((token, index) => {
    let bufferedTokens = getTokensForIndex(index, tokensForIndex);
    handleBufferedTokens(bufferedTokens, stack, fixedTokens);

    // no tokens allowed between table cells
    // if (
    //   !isTableCell(token) &&
    //   !isTableRow(token) &&
    //   !isInTableCell(stack) &&
    //   isInTableRow(stack)) {
    //   return;
    // }

    if (!isEndToken(token)) {
      fixedTokens.push(token);
      updateStack(stack, token);
      return;
    }

    // At this point we know we are dealing with a block or range ending token

    // The happy path. This ending token matches the opening token
    if (closesPreviousToken(token, stack)) {
      fixedTokens.push(token);
      updateStack(stack, token);
      return;
    }

    // if there can be no matching start token dont add to fixed tokens.
    if (!stack.contains(token.name)) {
      return;
    }

    // if closing a table cell close any open tokens
    if (token.name === 'TABLE_CELL') {
      // push ending tokens until we find a TABLE_CELL start
      stackAllIndex = stack.length - 1;
      while (!isMatching(token, stack.at(stackAllIndex))) {
        newMatchingToken = createMatch(stack.at(stackAllIndex));
        fixedTokens.push(newMatchingToken);
        updateStack(stack, newMatchingToken);
        stackAllIndex -= 1;
      }
      fixedTokens.push(token);
      updateStack(stack, token);
      return;
    }

    // push ending tokens until we find a start
    stackAllIndex = stack.length - 1;
    while (!isMatching(token, stack.at(stackAllIndex))) {
      // drop ending tokens if they are not properly nested in a table cell.
      if (stack.at(stackAllIndex).name === 'TABLE_CELL' && isStartToken(stack.at(stackAllIndex))) {
        return;
      }
      newMatchingToken = createMatch(stack.at(stackAllIndex));
      setTokensForIndex(index + 1, createVirtualToken(stack.at(stackAllIndex)), tokensForIndex);
      fixedTokens.push(newMatchingToken);
      updateStack(stack, newMatchingToken);
      // buffer starting tokens to be pushed for the next index
      stackAllIndex -= 1;
    }
    fixedTokens.push(token);
    updateStack(stack, token);
  });

  // if there are any open tokens still left on the tack close them
  closeOpenTokens(fixedTokens, stack);
  return insertTableTokens(fixedTokens);
}
<|endoftext|>


<commit_before>module.exports = {
  getViewPortInfo: function getViewPort () {
    var e = document.documentElement
    var g = document.getElementsByTagName('body')[0]
    var x = window.innerWidth || e.clientWidth || g.clientWidth
    var y = window.innerHeight || e.clientHeight || g.clientHeight

    return {
      width: x,
      height: y
    }
  },

  mergeObject: function (o1, o2) {
    var a
    var o3 = {}

    for (a in o1) {
      o3[a] = o1[a]
    }

    for (a in o2) {
      o3[a] = o2[a]
    }

    return o3
  },

  isUndefined: function (obj) {
    return (typeof obj) === 'undefined'
  },

  getCurrentScript: function () {
    // Source http://www.2ality.com/2014/05/current-script.html
    return document.currentScript || (function () {
        var scripts = document.getElementsByTagName('script')
        return scripts[scripts.length - 1]
      })()
  },

  generateUuid: function () {
    function _p8 (s) {
      var p = (Math.random().toString(16) + '000000000').substr(2, 8)
      return s ? '-' + p.substr(0, 4) + '-' + p.substr(4, 4) : p
    }
    return _p8() + _p8(true) + _p8(true) + _p8()
  }

}
<commit_msg>Add method to detect if CORS is supported<commit_after>module.exports = {
  getViewPortInfo: function getViewPort () {
    var e = document.documentElement
    var g = document.getElementsByTagName('body')[0]
    var x = window.innerWidth || e.clientWidth || g.clientWidth
    var y = window.innerHeight || e.clientHeight || g.clientHeight

    return {
      width: x,
      height: y
    }
  },

  mergeObject: function (o1, o2) {
    var a
    var o3 = {}

    for (a in o1) {
      o3[a] = o1[a]
    }

    for (a in o2) {
      o3[a] = o2[a]
    }

    return o3
  },

  isUndefined: function (obj) {
    return (typeof obj) === 'undefined'
  },

  isCORSSupported: function () {
    var xhr = new window.XMLHttpRequest()
    return 'withCredentials' in xhr
  },

  getCurrentScript: function () {
    // Source http://www.2ality.com/2014/05/current-script.html
    return document.currentScript || (function () {
        var scripts = document.getElementsByTagName('script')
        return scripts[scripts.length - 1]
      })()
  },

  generateUuid: function () {
    function _p8 (s) {
      var p = (Math.random().toString(16) + '000000000').substr(2, 8)
      return s ? '-' + p.substr(0, 4) + '-' + p.substr(4, 4) : p
    }
    return _p8() + _p8(true) + _p8(true) + _p8()
  }

}
<|endoftext|>


<commit_before>angular.module('ex1').controller('HomeCtrl',function($scope,$interval,equationResolverService){
    $scope.resolve=function(){   // action function - click on resolve button in app

        $scope.outputResolve=equationResolverService.resolve($scope.aValue, $scope.bValue);  // return resolve of equatation

        // lighting resolve - just visual effects
        $scope.colorOfResolve='#6FD49A' ;
        $interval(function(){ $scope.colorOfResolve='white';} ,3000);
    } ;
});<commit_msg>repair repo bugs<commit_after><|endoftext|>


<commit_before>'use strict';

angular.module('copayApp.controllers').controller('tabHomeController',
  function($rootScope, $timeout, $scope, $state, $stateParams, $ionicModal, $ionicScrollDelegate, gettextCatalog, lodash, popupService, ongoingProcess, profileService, walletService, configService, $log, platformInfo, storageService, txpModalService, $window, bitpayCardService) {
    var wallet;
    var listeners = [];
    var notifications = [];
    $scope.externalServices = {};
    $scope.bitpayCardEnabled = true; // TODO
    $scope.openTxpModal = txpModalService.open;
    $scope.version = $window.version;
    $scope.name = $window.appConfig.nameCase;
    $scope.homeTip = $stateParams.fromOnboarding;

    if(!$scope.homeTip){
       storageService.getHomeTipAccepted(function(error, value){
         $scope.homeTip = (value == 'false') ? false : true;
       });
     }

    $scope.openNotificationModal = function(n) {
      wallet = profileService.getWallet(n.walletId);

      if (n.txid) {
        openTxModal(n);
      } else {
        var txp = lodash.find($scope.txps, {
          id: n.txpId
        });
        if (txp) {
          txpModalService.open(txp);
        } else {
          ongoingProcess.set('loadingTxInfo', true);
          walletService.getTxp(wallet, n.txpId, function(err, txp) {
            var _txp = txp;
            ongoingProcess.set('loadingTxInfo', false);
            if (err) {
              $log.warn('No txp found');
              return popupService.showAlert(null, gettextCatalog.getString('Transaction not found'));
            }
            txpModalService.open(_txp);
          });
        }
      }
    };

    var openTxModal = function(n) {
      wallet = profileService.getWallet(n.walletId);

      ongoingProcess.set('loadingTxInfo', true);
      walletService.getTx(wallet, n.txid, function(err, tx) {
        ongoingProcess.set('loadingTxInfo', false);

        if (err) {
          $log.error(err);
          return popupService.showAlert(gettextCatalog.getString('Error'), err);
        }

        if (!tx) {
          $log.warn('No tx found');
          return popupService.showAlert(null, gettextCatalog.getString('Transaction not found'));
        }

        $scope.wallet = wallet;
        $scope.btx = lodash.cloneDeep(tx);
        $ionicModal.fromTemplateUrl('views/modals/tx-details.html', {
          scope: $scope
        }).then(function(modal) {
          $scope.txDetailsModal = modal;
          $scope.txDetailsModal.show();
        });

        walletService.getTxNote(wallet, n.txid, function(err, note) {
          if (err) $log.debug(gettextCatalog.getString('Could not fetch transaction note'));
          $scope.btx.note = note;
        });
      });
    };

    $scope.openWallet = function(wallet) {
      if (!wallet.isComplete()) {
        return $state.go('tabs.copayers', {
          walletId: wallet.credentials.walletId
        });
      }

      $state.go('tabs.wallet', {
        walletId: wallet.credentials.walletId
      });
    };

    var updateTxps = function() {
      profileService.getTxps({
        limit: 3
      }, function(err, txps, n) {
        if (err) $log.error(err);
        $scope.txps = txps;
        $scope.txpsN = n;
        $timeout(function() {
          $ionicScrollDelegate.resize();
        }, 100);
      })
    };

    var updateAllWallets = function() {
      $scope.wallets = profileService.getWallets();
      if (lodash.isEmpty($scope.wallets)) return;

      var i = $scope.wallets.length;
      var j = 0;
      var timeSpan = 60 * 60 * 24 * 7;

      lodash.each($scope.wallets, function(wallet) {
        walletService.getStatus(wallet, {}, function(err, status) {
          if (err) {
            $log.error(err);
          } else {
            wallet.status = status;
          }
          if (++j == i) {
            updateTxps();
          }
        });
      });

      if (!$scope.recentTransactionsEnabled) return;
      $scope.fetchingNotifications = true;
      profileService.getNotifications({
        limit: 3
      }, function(err, n) {
        if (err) {
          $log.error(err);
          return;
        }
        $scope.fetchingNotifications = false;
        $scope.notifications = n;

        $timeout(function() {
          $ionicScrollDelegate.resize();
          $scope.$apply();
        }, 100);

      })
    };

    var updateWallet = function(wallet) {
      $log.debug('Updating wallet:' + wallet.name)
      walletService.getStatus(wallet, {}, function(err, status) {
        if (err) {
          $log.error(err);
          return;
        }
        wallet.status = status;
        updateTxps();

        if (!$scope.recentTransactionsEnabled) return;

        $scope.fetchingNotifications = true;
        profileService.getNotifications({
          limit: 3
        }, function(err, notifications) {
          $scope.fetchingNotifications = false;
          if (err) {
            $log.error(err);
            return;
          }
          $scope.notifications = notifications;
        });
      });
    };

    $scope.hideHomeTip = function() {
      storageService.setHomeTipAccepted(false, function(error, value){
        $scope.homeTip = false;
        $state.transitionTo($state.current, null, {
          reload: true,
          inherit: false,
          notify: false
        });
      });
    };

    var nextStep = function() {
      lodash.each(['AmazonGiftCards', 'BitpayCard', 'BuyAndSell'], function(service) {
        storageService.getNextStep(service, function(err, value) {
          $scope.externalServices[service] = value ? true : false;
          $timeout(function() {
            $ionicScrollDelegate.resize();
          }, 10);
        });
      });
    };

    $scope.shouldHideNextSteps = function() {
      $scope.hideNextSteps = !$scope.hideNextSteps;
      $timeout(function() {
        $ionicScrollDelegate.resize();
        $scope.$apply();
      }, 100);
    };

    var bitpayCardCache = function() {
      bitpayCardService.getCacheData(function(err, data) {
        if (err ||  lodash.isEmpty(data)) return;
        $scope.bitpayCard = data;
      });
    };

    $scope.$on("$ionicView.enter", function(event, data) {
      $scope.bitpayCard = null;
      nextStep();
      updateAllWallets();

      listeners = [
        $rootScope.$on('bwsEvent', function(e, walletId, type, n) {
          var wallet = profileService.getWallet(walletId);
          updateWallet(wallet);
        }),
        $rootScope.$on('Local/TxAction', function(e, walletId) {
          $log.debug('Got action for wallet ' + walletId);
          var wallet = profileService.getWallet(walletId);
          updateWallet(wallet);
        })
      ];

      configService.whenAvailable(function() {
        var config = configService.getSync();
        var isWindowsPhoneApp = platformInfo.isWP && platformInfo.isCordova;

        $scope.glideraEnabled = config.glidera.enabled && !isWindowsPhoneApp;
        $scope.coinbaseEnabled = config.coinbase.enabled && !isWindowsPhoneApp;
        $scope.amazonEnabled = config.amazon.enabled;
        $scope.bitpayCardEnabled = config.bitpayCard.enabled;

        var buyAndSellEnabled = !$scope.externalServices.BuyAndSell && ($scope.glideraEnabled || $scope.coinbaseEnabled);
        var amazonEnabled = !$scope.externalServices.AmazonGiftCards && $scope.amazonEnabled;
        var bitpayCardEnabled = !$scope.externalServices.BitpayCard && $scope.bitpayCardEnabled;

        $scope.nextStepEnabled = buyAndSellEnabled || amazonEnabled || bitpayCardEnabled;
        $scope.recentTransactionsEnabled = config.recentTransactions.enabled;

        if ($scope.bitpayCardEnabled) bitpayCardCache();
      });
    });

    $scope.$on("$ionicView.leave", function(event, data) {
      lodash.each(listeners, function(x) {
        x();
      });
    });

  });
<commit_msg>removed unneeded state transition<commit_after>'use strict';

angular.module('copayApp.controllers').controller('tabHomeController',
  function($rootScope, $timeout, $scope, $state, $stateParams, $ionicModal, $ionicScrollDelegate, gettextCatalog, lodash, popupService, ongoingProcess, profileService, walletService, configService, $log, platformInfo, storageService, txpModalService, $window, bitpayCardService) {
    var wallet;
    var listeners = [];
    var notifications = [];
    $scope.externalServices = {};
    $scope.bitpayCardEnabled = true; // TODO
    $scope.openTxpModal = txpModalService.open;
    $scope.version = $window.version;
    $scope.name = $window.appConfig.nameCase;
    $scope.homeTip = $stateParams.fromOnboarding;

    if(!$scope.homeTip){
       storageService.getHomeTipAccepted(function(error, value){
         $scope.homeTip = (value == 'false') ? false : true;
       });
     }

    $scope.openNotificationModal = function(n) {
      wallet = profileService.getWallet(n.walletId);

      if (n.txid) {
        openTxModal(n);
      } else {
        var txp = lodash.find($scope.txps, {
          id: n.txpId
        });
        if (txp) {
          txpModalService.open(txp);
        } else {
          ongoingProcess.set('loadingTxInfo', true);
          walletService.getTxp(wallet, n.txpId, function(err, txp) {
            var _txp = txp;
            ongoingProcess.set('loadingTxInfo', false);
            if (err) {
              $log.warn('No txp found');
              return popupService.showAlert(null, gettextCatalog.getString('Transaction not found'));
            }
            txpModalService.open(_txp);
          });
        }
      }
    };

    var openTxModal = function(n) {
      wallet = profileService.getWallet(n.walletId);

      ongoingProcess.set('loadingTxInfo', true);
      walletService.getTx(wallet, n.txid, function(err, tx) {
        ongoingProcess.set('loadingTxInfo', false);

        if (err) {
          $log.error(err);
          return popupService.showAlert(gettextCatalog.getString('Error'), err);
        }

        if (!tx) {
          $log.warn('No tx found');
          return popupService.showAlert(null, gettextCatalog.getString('Transaction not found'));
        }

        $scope.wallet = wallet;
        $scope.btx = lodash.cloneDeep(tx);
        $ionicModal.fromTemplateUrl('views/modals/tx-details.html', {
          scope: $scope
        }).then(function(modal) {
          $scope.txDetailsModal = modal;
          $scope.txDetailsModal.show();
        });

        walletService.getTxNote(wallet, n.txid, function(err, note) {
          if (err) $log.debug(gettextCatalog.getString('Could not fetch transaction note'));
          $scope.btx.note = note;
        });
      });
    };

    $scope.openWallet = function(wallet) {
      if (!wallet.isComplete()) {
        return $state.go('tabs.copayers', {
          walletId: wallet.credentials.walletId
        });
      }

      $state.go('tabs.wallet', {
        walletId: wallet.credentials.walletId
      });
    };

    var updateTxps = function() {
      profileService.getTxps({
        limit: 3
      }, function(err, txps, n) {
        if (err) $log.error(err);
        $scope.txps = txps;
        $scope.txpsN = n;
        $timeout(function() {
          $ionicScrollDelegate.resize();
        }, 100);
      })
    };

    var updateAllWallets = function() {
      $scope.wallets = profileService.getWallets();
      if (lodash.isEmpty($scope.wallets)) return;

      var i = $scope.wallets.length;
      var j = 0;
      var timeSpan = 60 * 60 * 24 * 7;

      lodash.each($scope.wallets, function(wallet) {
        walletService.getStatus(wallet, {}, function(err, status) {
          if (err) {
            $log.error(err);
          } else {
            wallet.status = status;
          }
          if (++j == i) {
            updateTxps();
          }
        });
      });

      if (!$scope.recentTransactionsEnabled) return;
      $scope.fetchingNotifications = true;
      profileService.getNotifications({
        limit: 3
      }, function(err, n) {
        if (err) {
          $log.error(err);
          return;
        }
        $scope.fetchingNotifications = false;
        $scope.notifications = n;

        $timeout(function() {
          $ionicScrollDelegate.resize();
          $scope.$apply();
        }, 100);

      })
    };

    var updateWallet = function(wallet) {
      $log.debug('Updating wallet:' + wallet.name)
      walletService.getStatus(wallet, {}, function(err, status) {
        if (err) {
          $log.error(err);
          return;
        }
        wallet.status = status;
        updateTxps();

        if (!$scope.recentTransactionsEnabled) return;

        $scope.fetchingNotifications = true;
        profileService.getNotifications({
          limit: 3
        }, function(err, notifications) {
          $scope.fetchingNotifications = false;
          if (err) {
            $log.error(err);
            return;
          }
          $scope.notifications = notifications;
        });
      });
    };

    $scope.hideHomeTip = function() {
      storageService.setHomeTipAccepted(false, function(error, value){
        $scope.homeTip = false;
      });
    };

    var nextStep = function() {
      lodash.each(['AmazonGiftCards', 'BitpayCard', 'BuyAndSell'], function(service) {
        storageService.getNextStep(service, function(err, value) {
          $scope.externalServices[service] = value ? true : false;
          $timeout(function() {
            $ionicScrollDelegate.resize();
          }, 10);
        });
      });
    };

    $scope.shouldHideNextSteps = function() {
      $scope.hideNextSteps = !$scope.hideNextSteps;
      $timeout(function() {
        $ionicScrollDelegate.resize();
        $scope.$apply();
      }, 100);
    };

    var bitpayCardCache = function() {
      bitpayCardService.getCacheData(function(err, data) {
        if (err ||  lodash.isEmpty(data)) return;
        $scope.bitpayCard = data;
      });
    };

    $scope.$on("$ionicView.enter", function(event, data) {
      $scope.bitpayCard = null;
      nextStep();
      updateAllWallets();

      listeners = [
        $rootScope.$on('bwsEvent', function(e, walletId, type, n) {
          var wallet = profileService.getWallet(walletId);
          updateWallet(wallet);
        }),
        $rootScope.$on('Local/TxAction', function(e, walletId) {
          $log.debug('Got action for wallet ' + walletId);
          var wallet = profileService.getWallet(walletId);
          updateWallet(wallet);
        })
      ];

      configService.whenAvailable(function() {
        var config = configService.getSync();
        var isWindowsPhoneApp = platformInfo.isWP && platformInfo.isCordova;

        $scope.glideraEnabled = config.glidera.enabled && !isWindowsPhoneApp;
        $scope.coinbaseEnabled = config.coinbase.enabled && !isWindowsPhoneApp;
        $scope.amazonEnabled = config.amazon.enabled;
        $scope.bitpayCardEnabled = config.bitpayCard.enabled;

        var buyAndSellEnabled = !$scope.externalServices.BuyAndSell && ($scope.glideraEnabled || $scope.coinbaseEnabled);
        var amazonEnabled = !$scope.externalServices.AmazonGiftCards && $scope.amazonEnabled;
        var bitpayCardEnabled = !$scope.externalServices.BitpayCard && $scope.bitpayCardEnabled;

        $scope.nextStepEnabled = buyAndSellEnabled || amazonEnabled || bitpayCardEnabled;
        $scope.recentTransactionsEnabled = config.recentTransactions.enabled;

        if ($scope.bitpayCardEnabled) bitpayCardCache();
      });
    });

    $scope.$on("$ionicView.leave", function(event, data) {
      lodash.each(listeners, function(x) {
        x();
      });
    });

  });
<|endoftext|>


<commit_before>export default function (UIkit) {

    UIkit.component('height-viewport', {

        props: {
            mode: String
        },

        defaults: {
            mode: 'viewport'
        },

        init() {
            if (this.mode !== 'expand') {
                this.$el.css('min-height', this.getHeight());
            }
        },

        update: {

            handler() {

                this.borderBox = this.$el.css('box-sizing') === 'border-box';

                if (this.mode === 'expand') {

                    this.$el.css('min-height', '');
                    if (document.documentElement.offsetHeight < window.innerHeight) {
                        this.$el.css('min-height', this.$el.outerHeight() + window.innerHeight - document.documentElement.offsetHeight - (this.borderBox ? 0 : this.$el.outerHeight() - this.$el.height()))
                    }
                    return;

                }

                // IE 10-11 fix (min-height on a flex container won't apply to its flex items)
                this.$el.css('height', '');
                if (this.getHeight() >= this.$el.height()) {
                    this.$el.css('height', this.getHeight());
                }

                this.$el.css('min-height', this.getHeight());

            },

            events: ['load', 'resize', 'orientationchange']

        },

        methods: {

            getHeight() {

                var height = window.innerHeight;

                if (this.mode === 'offset'&& this.$el.offset().top < height) {
                    height -= this.$el.offset().top + (this.borderBox ? 0 : this.$el.outerHeight() - this.$el.height());
                }

                return height;
            }

        }

    });

}
<commit_msg>fixed viewport height<commit_after>export default function (UIkit) {

    UIkit.component('height-viewport', {

        props: {
            mode: String
        },

        defaults: {
            mode: 'viewport'
        },

        init() {
            if (this.mode !== 'expand') {
                this.$el.css('min-height', this.getHeight());
            }
        },

        update: {

            handler() {

                this.borderBox = this.$el.css('box-sizing') === 'border-box';

                if (this.mode === 'expand') {

                    this.$el.css('min-height', '');
                    if (document.documentElement.offsetHeight < window.innerHeight) {
                        this.$el.css('min-height', this.$el.outerHeight() + window.innerHeight - document.documentElement.offsetHeight - (this.borderBox ? 0 : this.$el.outerHeight() - this.$el.height()))
                    }
                    return;

                }

                // IE 10-11 fix (min-height on a flex container won't apply to its flex items)
                this.$el.css({height: '', minHeight: ''});
                if (this.getHeight() >= this.$el.outerHeight()) {
                    this.$el.css('height', this.getHeight());
                }

                this.$el.css('min-height', this.getHeight());

            },

            events: ['load', 'resize', 'orientationchange']

        },

        methods: {

            getHeight() {

                var height = window.innerHeight;

                if (this.mode === 'offset' && this.$el.offset().top < height) {
                    height -= this.$el.offset().top + (this.borderBox ? 0 : this.$el.outerHeight() - this.$el.height());
                }

                return height;
            }

        }

    });

}
<|endoftext|>


<commit_before>var FunctionBlockFinder = function(editorSession) {
  this.editorSession = editorSession;
};

FunctionBlockFinder.prototype.findFromRow = function (startRowBaseZero) {
  var bracketsLevel = 0;
  var line = null;
  var lineCount = this.editorSession.getLength();
  var lineNr;

  for(lineNr = startRowBaseZero; lineNr < lineCount && (!line || bracketsLevel > 0); lineNr++) {
    line = this.editorSession.getLine(lineNr);
    if(line.indexOf("{") > -1) {
      bracketsLevel++;
    }
    if(line.indexOf("}") > -1) {
      bracketsLevel--;
    }
  }
  return { "start" : startRowBaseZero + 1, "end" : lineNr};
};
<commit_msg>remove unneccessary file<commit_after><|endoftext|>


<commit_before>(function () {
  var ns = $.namespace('pskl.tools.transform');

  ns.Flip = function () {
    this.toolId = 'tool-flip';
    this.helpText = 'Flip vertically';
    this.tooltipDescriptors = [
      {key : 'alt', description : 'Flip horizontally'},
      {key : 'ctrl', description : 'Apply to all layers'},
      {key : 'shift', description : 'Apply to all frames'}
    ];
  };

  pskl.utils.inherit(ns.Flip, ns.AbstractTransformTool);

  ns.Flip.prototype.applyToolOnFrame_ = function (frame, altKey) {
    var axis;

    if (altKey) {
      axis = ns.TransformUtils.HORIZONTAL;
    } else {
      axis = ns.TransformUtils.VERTICAL;
    }

    ns.TransformUtils.flip(frame, axis);
  };

})();
<commit_msg>Fix #894: Replaced help text for flip &rotated tool-flip icon (#899)<commit_after>(function () {
  var ns = $.namespace('pskl.tools.transform');

  ns.Flip = function () {
    this.toolId = 'tool-flip';
    this.helpText = 'Flip horizontally';
    this.tooltipDescriptors = [
      {key : 'alt', description : 'Flip vertically'},
      {key : 'ctrl', description : 'Apply to all layers'},
      {key : 'shift', description : 'Apply to all frames'}
    ];
  };

  pskl.utils.inherit(ns.Flip, ns.AbstractTransformTool);

  ns.Flip.prototype.applyToolOnFrame_ = function (frame, altKey) {
    var axis;

    if (altKey) {
      axis = ns.TransformUtils.HORIZONTAL;
    } else {
      axis = ns.TransformUtils.VERTICAL;
    }

    ns.TransformUtils.flip(frame, axis);
  };

})();
<|endoftext|>


<commit_before>"use strict";
var assert = require('assert');

var Game = function() {

  this.roll = function(pins) {
    return -1;
  };

  return this;
};

describe('bowling game', function() {
  it('is able to create a game', function() {
    assert(new Game());
  });

  it('is able to bowl a zero', function() {
    assert(new Game().roll(0));
  });
});<commit_msg>refactor out the game class<commit_after>"use strict";
var assert = require('assert');

var Game = function() {

  this.roll = function(pins) {
    return -1;
  };

  return this;
};

describe('bowling game', function() {
  describe('game', function() {

    var game;

    beforeEach(function() {
      game = new Game();
    });

    it('is able to bowl a zero', function() {
      assert(game.roll(0));
    });
  });
});<|endoftext|>


<commit_before>var sfcgCalendar = require("./calendar.js");
var sfcgWebsite = require("./sf_city_guides.js");
var async = require('async');

var CONCURRENCY_LIMIT = 1;
var deleteOnly = false;

//Handle arguments
process.argv.forEach(function (val, index, array) {
	if (index>=2) {
		if (val="delete") {
			console.log("Delete existing events only");
			deleteOnly = true;
		}
	}
});

//It starts here!
sfcgCalendar.getCalendarAuthentication(function(auth) {
  //Get authentication
  console.log("Calendar Authentication acquired");

  console.log("Deleting existing gCal events");
  deleteAllEvents(auth, function() {
    if (deleteOnly) {
	console.log("Only deleting existing events");
	return;
    }
    console.log("Getting this week's upcoming events");
    sfcgWebsite.getThisWeeksEvents(function(events) {
      createEvents(auth, events, function() {
        console.log("Entire process done! Tada!");
      });
    });
  });

});

function deleteAllEvents(auth, allEventsDeletedCallback) {
  //Get all existing events and delete them
  var q = async.queue(function(task, callback) {
      sfcgCalendar.deleteCalendarEvent(task.auth,task.event,callback);
  },CONCURRENCY_LIMIT);

  q.drain = function() {
    console.log("All events have been deleted");
    allEventsDeletedCallback();
  }

  sfcgCalendar.getAllCalendarEvents(auth,null,[],function(events) {
    if (events.length==0) {
      allEventsDeletedCallback();
      return;
    }
    for (var i=0; i < events.length; i++) {
      var event = events[i];
      q.push({auth:auth, event: event}, function(err) {
        console.log("Finished deleting event");
      })
    }
  });
}

function createEvents(auth, events,allEventsCreatedCallback) {
  var q = async.queue(function(task, callback) {
    sfcgCalendar.createCalendarEvent(task.auth,task.event,callback);
  },CONCURRENCY_LIMIT);

  q.drain = function() {
    console.log("All events have been created");
    allEventsCreatedCallback();
  }

  for (var i=0; i < events.length; i++) {
    var event = events[i];
    q.push({auth: auth, event: event}, function(err) {
      console.log("Finished creating event");
    });
  }
}
<commit_msg>Trying to throttle event creation calls better<commit_after>var sfcgCalendar = require("./calendar.js");
var sfcgWebsite = require("./sf_city_guides.js");
var async = require('async');

var CONCURRENCY_LIMIT = 1;
var deleteOnly = false;

//Handle arguments
process.argv.forEach(function (val, index, array) {
	if (index>=2) {
		if (val="delete") {
			console.log("Delete existing events only");
			deleteOnly = true;
		}
	}
});

//It starts here!
sfcgCalendar.getCalendarAuthentication(function(auth) {
  //Get authentication
  console.log("Calendar Authentication acquired");

  console.log("Deleting existing gCal events");
  deleteAllEvents(auth, function() {
    if (deleteOnly) {
	console.log("Only deleting existing events");
	return;
    }
    console.log("Getting this week's upcoming events");
    sfcgWebsite.getThisWeeksEvents(function(events) {
      createEvents(auth, events, function() {
        console.log("Entire process done! Tada!");
      });
    });
  });

});

function deleteAllEvents(auth, allEventsDeletedCallback) {
  //Get all existing events and delete them
  var q = async.queue(function(task, callback) {
      sfcgCalendar.deleteCalendarEvent(task.auth,task.event,callback);
  },CONCURRENCY_LIMIT);

  q.drain = function() {
    console.log("All events have been deleted");
    allEventsDeletedCallback();
  }

  sfcgCalendar.getAllCalendarEvents(auth,null,[],function(events) {
    if (events.length==0) {
      allEventsDeletedCallback();
      return;
    }
    for (var i=0; i < events.length; i++) {
      var event = events[i];
      q.push({auth:auth, event: event}, function(err) {
        console.log("Finished deleting event");
      })
    }
  });
}

function createEvents(auth, events,allEventsCreatedCallback) {
  var q = async.queue(function(task, callback) {
		setTimeout(sfcgCalendar.createCalendarEvent(task.auth,task.event,callback),1000); //1s delay
    // sfcgCalendar.createCalendarEvent(task.auth,task.event,callback);
  },CONCURRENCY_LIMIT);

  q.drain = function() {
    console.log("All events have been created");
    allEventsCreatedCallback();
  }

  for (var i=0; i < events.length; i++) {
    var event = events[i];
    q.push({auth: auth, event: event}, function(err) {
      console.log("Finished creating event");
    });
  }
}
<|endoftext|>


<commit_before>// Ember controller for create vm form
var VmsNewController = Ember.ObjectController.extend({
  computeSorting: ['name'],
  //disable advanced form
  advancedForm: false,

  //project combobox
  projectsFilter: Ember.computed.filterBy('projects', 'name'),
  projectsSort: Ember.computed.sort('projectsFilter', 'computeSorting'),

  //system combobox
  selectedSystem: null,
  osSort: null,

  //users combobox
  emailSorting: ['email'],
  usersSort: Ember.computed.sort('users', 'emailSorting'),

  //init to null parameters
  selectedProject: null,
  selectedUser: null,
  selectedBranch: null,
  selectedCommit: null,
  selectedOs: null,
  usersList: null,
  vmsizesList: null,
  selectedSizing: null,

  //validation variables
  errorProject: false,
  errorUser: false,
  errorBranch: false,
  errorCommit: false,
  errorOs: false,
  errorVmsize: false,

  //validation function
  checkProject: function() {
    var project = this.get('selectedProject') ;
    var errorProject = false ;

    if (!project) {
      errorProject = true ;
    }

    this.set('errorProject', errorProject) ;
  }.observes('selectedProject'),

  checkUser: function() {
    var user = this.get('selectedUser') ;
    var errorUser = false ;

    if (user == null) {
      errorUser = true ;
    }

    this.set('errorUser', errorUser) ;
  }.observes('selectedUser'),

  checkBranch: function() {
    var branch = this.get('selectedBranch');
    var errorBranch = true;
    var selectedCommit = null;

    if (branch) {
      errorBranch = false;
      selectedCommit = branch.get('commits').toArray()[0];
    }

    this.set('errorBranch', errorBranch);
    // set default commit
    this.set('selectedCommit', selectedCommit);
  }.observes('selectedBranch'),

  checkCommit: function() {
    var commit = this.get('selectedCommit') ;
    var errorCommit = false ;

    if (!commit) {
      errorCommit = true ;
    }

    this.set('errorCommit', errorCommit) ;
  }.observes('selectedCommit'),

  checkOs: function() {
    var os = this.get('selectedOs') ;
    var errorOs = false ;

    if (!os) {
      errorOs = true ;
    }

    this.set('errorOs', errorOs) ;
  }.observes('selectedOs'),

  checkVmsize: function() {
    var vmsize = this.get('selectedSizing') ;
    var errorVmsize = false ;

    if (!vmsize) {
      errorVmsize = true ;
    }

    this.set('errorVmsize', errorVmsize) ;
  }.observes('selectedSizing'),

  //check form before submit
  formIsValid: function() {
    this.checkProject() ;
    this.checkUser() ;
    this.checkBranch() ;
    this.checkCommit() ;
    this.checkOs() ;
    this.checkVmsize() ;

    if (!this.get('errorProject') &&
        !this.get('errorUser') &&
        !this.get('errorBranch') &&
        !this.get('errorCommit') &&
        !this.get('errorOs') &&
        !this.get('errorVmsize')) return true ;
    return false ;
  },

  //clear form
  clearForm: function() {
    this.set('selectedProject', null) ;
    this.set('selectedUser', null) ;
    this.set('selectedBranch', null) ;
    this.set('selectedCommit', null) ;
    this.set('selectedOs', null) ;
    this.set('selectedSizing', null) ;
    this.set('advancedForm', false) ;
  },

  // Return true if user is a Dev or more
  isDev: function() {
    var access_level = App.AuthManager.get('apiKey.accessLevel') ;

    if (access_level >= 30) return true ;
    return false ;
  }.property('App.AuthManager.apiKey'),

  // project change event
  projectChange: function() {
    var store = this.store;
    var self = this;
    var cp = 0;

    //if selectedproject was flushed, flush usersList
    if (!this.get('selectedProject')) {
      this.set('usersList', []) ;
      this.set('osSort', []) ;
      this.set('vmsizesList', []) ;
      return ;
    }

    //first, change users combobox
    var users = this.get('selectedProject').get('users').toArray();
    var access_level = App.AuthManager.get('apiKey.accessLevel');
    var systemtype = null;

    if (access_level < 40) {
      this.get('selectedProject').get('users').toArray().forEach(function (user){
        if (user && user.id != App.AuthManager.get('apiKey.user')) {
              users.removeObject(user);
        }
      });
    }

    this.set('usersList', users);

    //vmsize combobox
    var vmsizesid = this.get('selectedProject').get('vmsizes').mapBy('id');
    var vmsizes = [];
    vmsizesid.forEach(function(vmsizeid){
      vmsizes[cp++] = self.get('vmsizes').filterBy('id', vmsizeid).toArray()[0];
    });

    vmsizes = this.get('selectedProject').get('vmsizes');
    this.set('vmsizesList', vmsizes);

    //and the system combobox
    var systemimages = null;
    systemtype = this.get('selectedProject').get('systemimagetype');
    systemimages = this.get('systemimages').filterBy('systemimagetype.id', systemtype.get('id')).toArray();
    this.set('osSort', systemimages);

    //init default values
    this.set('selectedUser', users[0]);
    this.set('selectedOs', systemimages[0]);
    this.set('selectedSizing', vmsizes.toArray()[0]);

    //init default branch and commit
    store.find('branche', this.get('selectedProject').get('id') + '-master').then(function (branch) {
      self.set('selectedBranch', branch);
    });
  }.observes('selectedProject'),

  actions: {
    // Submit form
    createItem: function() {
      var router = this.get('target');

      var data = {};
      var store = this.store;

      // get the values from the form
      var selectedProject = this.get('selectedProject');
      var selectedCommit = this.get('selectedCommit');
      var selectedUser = this.get('selectedUser');
      var selectedOs = this.get('selectedOs');
      var selectedVmsize = this.get('selectedSizing');

      // check if form is valid
      if (!this.formIsValid()) {
        return ;
      }

      // format value for the post request
      data['commit'] = selectedCommit;
      data['project'] = selectedProject;
      data['user'] = selectedUser;
      data['systemimage'] = selectedOs;
      data['vmsize'] = selectedVmsize;

      // create a vm object for the rest post request
      vm = store.createRecord('vm', data);

      selectedUser.get('vms').pushObject(vm);
      selectedProject.get('vms').pushObject(vm);
      selectedOs.get('vms').pushObject(vm);
      selectedCommit.get('vms').pushObject(vm);

      //loader because 10s to complete create vm
      $('#waitingModal').modal();
      vm.save().then(function() {
        router.transitionTo('vms.list');
        $('#waitingModal').modal('hide');
      }) ;

    },

     // Toggle or untoggle all items
    toggleAdvanced: function() {
      if (this.get('advancedForm')) this.set('advancedForm', false);
      else this.set('advancedForm', true);
    },
  }
});

module.exports = VmsNewController;<commit_msg>ensure that current user is always default value in vm form<commit_after>// Ember controller for create vm form
var VmsNewController = Ember.ObjectController.extend({
  computeSorting: ['name'],
  //disable advanced form
  advancedForm: false,

  //project combobox
  projectsFilter: Ember.computed.filterBy('projects', 'name'),
  projectsSort: Ember.computed.sort('projectsFilter', 'computeSorting'),

  //system combobox
  selectedSystem: null,
  osSort: null,

  //users combobox
  emailSorting: ['email'],
  usersSort: Ember.computed.sort('users', 'emailSorting'),

  //init to null parameters
  selectedProject: null,
  selectedUser: null,
  selectedBranch: null,
  selectedCommit: null,
  selectedOs: null,
  usersList: null,
  vmsizesList: null,
  selectedSizing: null,

  //validation variables
  errorProject: false,
  errorUser: false,
  errorBranch: false,
  errorCommit: false,
  errorOs: false,
  errorVmsize: false,

  //validation function
  checkProject: function() {
    var project = this.get('selectedProject') ;
    var errorProject = false ;

    if (!project) {
      errorProject = true ;
    }

    this.set('errorProject', errorProject) ;
  }.observes('selectedProject'),

  checkUser: function() {
    var user = this.get('selectedUser') ;
    var errorUser = false ;

    if (user == null) {
      errorUser = true ;
    }

    this.set('errorUser', errorUser) ;
  }.observes('selectedUser'),

  checkBranch: function() {
    var branch = this.get('selectedBranch');
    var errorBranch = true;
    var selectedCommit = null;

    if (branch) {
      errorBranch = false;
      selectedCommit = branch.get('commits').toArray()[0];
    }

    this.set('errorBranch', errorBranch);
    // set default commit
    this.set('selectedCommit', selectedCommit);
  }.observes('selectedBranch'),

  checkCommit: function() {
    var commit = this.get('selectedCommit') ;
    var errorCommit = false ;

    if (!commit) {
      errorCommit = true ;
    }

    this.set('errorCommit', errorCommit) ;
  }.observes('selectedCommit'),

  checkOs: function() {
    var os = this.get('selectedOs') ;
    var errorOs = false ;

    if (!os) {
      errorOs = true ;
    }

    this.set('errorOs', errorOs) ;
  }.observes('selectedOs'),

  checkVmsize: function() {
    var vmsize = this.get('selectedSizing') ;
    var errorVmsize = false ;

    if (!vmsize) {
      errorVmsize = true ;
    }

    this.set('errorVmsize', errorVmsize) ;
  }.observes('selectedSizing'),

  //check form before submit
  formIsValid: function() {
    this.checkProject() ;
    this.checkUser() ;
    this.checkBranch() ;
    this.checkCommit() ;
    this.checkOs() ;
    this.checkVmsize() ;

    if (!this.get('errorProject') &&
        !this.get('errorUser') &&
        !this.get('errorBranch') &&
        !this.get('errorCommit') &&
        !this.get('errorOs') &&
        !this.get('errorVmsize')) return true ;
    return false ;
  },

  //clear form
  clearForm: function() {
    this.set('selectedProject', null) ;
    this.set('selectedUser', null) ;
    this.set('selectedBranch', null) ;
    this.set('selectedCommit', null) ;
    this.set('selectedOs', null) ;
    this.set('selectedSizing', null) ;
    this.set('advancedForm', false) ;
  },

  // Return true if user is a Dev or more
  isDev: function() {
    var access_level = App.AuthManager.get('apiKey.accessLevel') ;

    if (access_level >= 30) return true ;
    return false ;
  }.property('App.AuthManager.apiKey'),

  // project change event
  projectChange: function() {
    var store = this.store;
    var self = this;
    var cp = 0;

    //if selectedproject was flushed, flush usersList
    if (!this.get('selectedProject')) {
      this.set('usersList', []) ;
      this.set('osSort', []) ;
      this.set('vmsizesList', []) ;
      return ;
    }

    //first, change users combobox
    var users = this.get('selectedProject').get('users').toArray();
    var access_level = App.AuthManager.get('apiKey.accessLevel');
    var user_id = App.AuthManager.get('apiKey.user');
    var user_index = 0;
    var systemtype = null;

    if (access_level < 40) {
      this.get('selectedProject').get('users').toArray().forEach(function (user){
        if (user && user.id != user_id) {
              users.removeObject(user);
        }
      });
    }

    // set default index in users array
    for (var i = 0; i < users.length; i++) {
      if (users[i].id == user_id) {
        user_index = i;
        break;
      }
    }

    this.set('usersList', users);

    //vmsize combobox
    var vmsizesid = this.get('selectedProject').get('vmsizes').mapBy('id');
    var vmsizes = [];
    vmsizesid.forEach(function(vmsizeid){
      vmsizes[cp++] = self.get('vmsizes').filterBy('id', vmsizeid).toArray()[0];
    });

    vmsizes = this.get('selectedProject').get('vmsizes');
    this.set('vmsizesList', vmsizes);

    //and the system combobox
    var systemimages = null;
    systemtype = this.get('selectedProject').get('systemimagetype');
    systemimages = this.get('systemimages').filterBy('systemimagetype.id', systemtype.get('id')).toArray();
    this.set('osSort', systemimages);

    //init default values
    this.set('selectedUser', users[user_index]);
    this.set('selectedOs', systemimages[0]);
    this.set('selectedSizing', vmsizes.toArray()[0]);

    //init default branch and commit
    store.find('branche', this.get('selectedProject').get('id') + '-master').then(function (branch) {
      self.set('selectedBranch', branch);
    });
  }.observes('selectedProject'),

  actions: {
    // Submit form
    createItem: function() {
      var router = this.get('target');

      var data = {};
      var store = this.store;

      // get the values from the form
      var selectedProject = this.get('selectedProject');
      var selectedCommit = this.get('selectedCommit');
      var selectedUser = this.get('selectedUser');
      var selectedOs = this.get('selectedOs');
      var selectedVmsize = this.get('selectedSizing');

      // check if form is valid
      if (!this.formIsValid()) {
        return ;
      }

      // format value for the post request
      data['commit'] = selectedCommit;
      data['project'] = selectedProject;
      data['user'] = selectedUser;
      data['systemimage'] = selectedOs;
      data['vmsize'] = selectedVmsize;

      // create a vm object for the rest post request
      vm = store.createRecord('vm', data);

      selectedUser.get('vms').pushObject(vm);
      selectedProject.get('vms').pushObject(vm);
      selectedOs.get('vms').pushObject(vm);
      selectedCommit.get('vms').pushObject(vm);

      //loader because 10s to complete create vm
      $('#waitingModal').modal();
      vm.save().then(function() {
        router.transitionTo('vms.list');
        $('#waitingModal').modal('hide');
      }) ;

    },

     // Toggle or untoggle all items
    toggleAdvanced: function() {
      if (this.get('advancedForm')) this.set('advancedForm', false);
      else this.set('advancedForm', true);
    },
  }
});

module.exports = VmsNewController;<|endoftext|>


<commit_before>import { acceptance, logIn } from "helpers/qunit-helpers";
import { resetPluginApi } from 'discourse/lib/plugin-api';

acceptance('Cakeday', {
  settings: {
    cakeday_enabled: true,
    cakeday_emoji: 'cake',
    cakeday_birthday_enabled: true,
    cakeday_birthday_emoji: 'birthday'
  },

  beforeEach() {
    const response = object => {
      return [
        200,
        { "Content-Type": "application/json" },
        object
      ];
    };

    server.get('/t/11.json', () => { // eslint-disable-line no-undef
      return response({"post_stream":{"posts":[{"id":14,"name":null,"username":"tgx","avatar_template":"/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png","created_at":"2016-11-21T06:55:17.892Z","cooked":"
This is a topic written for an acceptance test
","post_number":1,"post_type":1,"updated_at":"2016-11-21T06:55:17.892Z","reply_count":0,"reply_to_post_number":null,"quote_count":0,"avg_time":null,"incoming_link_count":0,"reads":1,"score":0,"yours":true,"topic_id":11,"topic_slug":"some-really-interesting-topic","display_username":null,"primary_group_name":null,"primary_group_flair_url":null,"primary_group_flair_bg_color":null,"primary_group_flair_color":null,"version":1,"can_edit":true,"can_delete":false,"can_recover":true,"can_wiki":true,"read":true,"user_title":null,"actions_summary":[{"id":3,"can_act":true},{"id":4,"can_act":true},{"id":5,"hidden":true,"can_act":true},{"id":7,"can_act":true},{"id":8,"can_act":true}],"moderator":false,"admin":true,"staff":true,"user_id":1,"hidden":false,"hidden_reason_id":null,"trust_level":4,"deleted_at":null,"user_deleted":false,"edit_reason":null,"can_view_edit_history":true,"wiki":false,"user_created_at":moment().subtract(1, 'year'),"user_date_of_birth":moment().format('YYYY-MM-DD')}],"stream":[14]},"timeline_lookup":[[1,0]],"id":11,"title":"Some really interesting topic","fancy_title":"Some really interesting topic","posts_count":1,"created_at":"2016-11-21T06:55:17.771Z","views":1,"reply_count":0,"participant_count":1,"like_count":0,"last_posted_at":"2016-11-21T06:55:17.892Z","visible":true,"closed":false,"archived":false,"has_summary":false,"archetype":"regular","slug":"some-really-interesting-topic","category_id":1,"word_count":9,"deleted_at":null,"user_id":1,"draft":null,"draft_key":"topic_11","draft_sequence":1,"posted":true,"unpinned":null,"pinned_globally":false,"pinned":false,"pinned_at":null,"pinned_until":null,"details":{"auto_close_at":null,"auto_close_hours":null,"auto_close_based_on_last_post":false,"created_by":{"id":1,"username":"tgx","avatar_template":"/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png"},"last_poster":{"id":1,"username":"tgx","avatar_template":"/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png"},"participants":[{"id":1,"username":"tgx","avatar_template":"/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png","post_count":1}],"suggested_topics":[{"id":8,"title":"Welcome to Discourse","fancy_title":"Welcome to Discourse","slug":"welcome-to-discourse","posts_count":1,"reply_count":0,"highest_post_number":1,"image_url":null,"created_at":"2016-11-21T06:53:31.836Z","last_posted_at":"2016-11-21T06:53:31.877Z","bumped":true,"bumped_at":"2016-11-21T06:53:31.877Z","unseen":false,"pinned":true,"unpinned":null,"excerpt":"The first paragraph of this pinned topic will be visible as a welcome message to all new visitors on your homepage. It's important! \n\nEdit this into a brief description of your community: \n\n\nWho is it for?\nWhat can they …","visible":true,"closed":false,"archived":false,"bookmarked":null,"liked":null,"archetype":"regular","like_count":0,"views":0,"category_id":1,"posters":[{"extras":"latest single","description":"Original Poster, Most Recent Poster","user":{"id":-1,"username":"system","avatar_template":"/letter_avatar_proxy/v2/letter/s/bcef8e/{size}.png"}}]}],"notification_level":3,"notifications_reason_id":1,"can_move_posts":true,"can_edit":true,"can_delete":true,"can_recover":true,"can_remove_allowed_users":true,"can_invite_to":true,"can_create_post":true,"can_reply_as_new_topic":true,"can_flag_topic":true},"highest_post_number":1,"last_read_post_number":1,"last_read_post_id":14,"deleted_by":null,"has_deleted":false,"actions_summary":[{"id":4,"count":0,"hidden":false,"can_act":true},{"id":7,"count":0,"hidden":false,"can_act":true},{"id":8,"count":0,"hidden":false,"can_act":true}],"chunk_size":20,"bookmarked":false});
    });

    server.get('/u/tgx.json', () => { // eslint-disable-line no-undef
      return response({
        "user": {
          "date_of_birth":moment().format('YYYY-MM-DD'),
          "created_at":moment().subtract(1, 'year')
        }
      });
    });
  }
});

test("User is not logged in", assert => {
  visit("/");
  click('#toggle-hamburger-menu');

  andThen(() => {
    assert.equal(find('.cakeday-link').length, 0, 'Cakeday is not shown to anonymous users');
  });
});

test('Anniversary emoji', assert => {
  logIn();
  Discourse.reset();

  visit("/t/some-really-interesting-topic/11");

  andThen(() => {
    const $posterIcons = find('.poster-icon');

    assert.equal($posterIcons[0].title, I18n.t('user.anniversary.title'));
    assert.equal($posterIcons[1].title, I18n.t('user.date_of_birth.title'));
    assert.equal(find('img.emoji', $posterIcons[0]).length, 1);
    assert.equal(find('img.emoji', $posterIcons[1]).length, 1);
  });

  click('.trigger-user-card');

  andThen(() => {
    const $emojiImages = find('.emoji-images div');

    assert.equal($emojiImages[1].title, I18n.t('user.anniversary.title'));
    assert.equal($emojiImages[0].title, I18n.t('user.date_of_birth.title'));
    assert.equal(1, $emojiImages[0].children.length);
    assert.equal(1, $emojiImages[1].children.length);
  });
});
<commit_msg>Fix lint.<commit_after>import { acceptance, logIn } from "helpers/qunit-helpers";

acceptance('Cakeday', {
  settings: {
    cakeday_enabled: true,
    cakeday_emoji: 'cake',
    cakeday_birthday_enabled: true,
    cakeday_birthday_emoji: 'birthday'
  },

  beforeEach() {
    const response = object => {
      return [
        200,
        { "Content-Type": "application/json" },
        object
      ];
    };

    server.get('/t/11.json', () => { // eslint-disable-line no-undef
      return response({"post_stream":{"posts":[{"id":14,"name":null,"username":"tgx","avatar_template":"/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png","created_at":"2016-11-21T06:55:17.892Z","cooked":"
This is a topic written for an acceptance test
","post_number":1,"post_type":1,"updated_at":"2016-11-21T06:55:17.892Z","reply_count":0,"reply_to_post_number":null,"quote_count":0,"avg_time":null,"incoming_link_count":0,"reads":1,"score":0,"yours":true,"topic_id":11,"topic_slug":"some-really-interesting-topic","display_username":null,"primary_group_name":null,"primary_group_flair_url":null,"primary_group_flair_bg_color":null,"primary_group_flair_color":null,"version":1,"can_edit":true,"can_delete":false,"can_recover":true,"can_wiki":true,"read":true,"user_title":null,"actions_summary":[{"id":3,"can_act":true},{"id":4,"can_act":true},{"id":5,"hidden":true,"can_act":true},{"id":7,"can_act":true},{"id":8,"can_act":true}],"moderator":false,"admin":true,"staff":true,"user_id":1,"hidden":false,"hidden_reason_id":null,"trust_level":4,"deleted_at":null,"user_deleted":false,"edit_reason":null,"can_view_edit_history":true,"wiki":false,"user_created_at":moment().subtract(1, 'year'),"user_date_of_birth":moment().format('YYYY-MM-DD')}],"stream":[14]},"timeline_lookup":[[1,0]],"id":11,"title":"Some really interesting topic","fancy_title":"Some really interesting topic","posts_count":1,"created_at":"2016-11-21T06:55:17.771Z","views":1,"reply_count":0,"participant_count":1,"like_count":0,"last_posted_at":"2016-11-21T06:55:17.892Z","visible":true,"closed":false,"archived":false,"has_summary":false,"archetype":"regular","slug":"some-really-interesting-topic","category_id":1,"word_count":9,"deleted_at":null,"user_id":1,"draft":null,"draft_key":"topic_11","draft_sequence":1,"posted":true,"unpinned":null,"pinned_globally":false,"pinned":false,"pinned_at":null,"pinned_until":null,"details":{"auto_close_at":null,"auto_close_hours":null,"auto_close_based_on_last_post":false,"created_by":{"id":1,"username":"tgx","avatar_template":"/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png"},"last_poster":{"id":1,"username":"tgx","avatar_template":"/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png"},"participants":[{"id":1,"username":"tgx","avatar_template":"/letter_avatar_proxy/v2/letter/t/ecae2f/{size}.png","post_count":1}],"suggested_topics":[{"id":8,"title":"Welcome to Discourse","fancy_title":"Welcome to Discourse","slug":"welcome-to-discourse","posts_count":1,"reply_count":0,"highest_post_number":1,"image_url":null,"created_at":"2016-11-21T06:53:31.836Z","last_posted_at":"2016-11-21T06:53:31.877Z","bumped":true,"bumped_at":"2016-11-21T06:53:31.877Z","unseen":false,"pinned":true,"unpinned":null,"excerpt":"The first paragraph of this pinned topic will be visible as a welcome message to all new visitors on your homepage. It's important! \n\nEdit this into a brief description of your community: \n\n\nWho is it for?\nWhat can they …","visible":true,"closed":false,"archived":false,"bookmarked":null,"liked":null,"archetype":"regular","like_count":0,"views":0,"category_id":1,"posters":[{"extras":"latest single","description":"Original Poster, Most Recent Poster","user":{"id":-1,"username":"system","avatar_template":"/letter_avatar_proxy/v2/letter/s/bcef8e/{size}.png"}}]}],"notification_level":3,"notifications_reason_id":1,"can_move_posts":true,"can_edit":true,"can_delete":true,"can_recover":true,"can_remove_allowed_users":true,"can_invite_to":true,"can_create_post":true,"can_reply_as_new_topic":true,"can_flag_topic":true},"highest_post_number":1,"last_read_post_number":1,"last_read_post_id":14,"deleted_by":null,"has_deleted":false,"actions_summary":[{"id":4,"count":0,"hidden":false,"can_act":true},{"id":7,"count":0,"hidden":false,"can_act":true},{"id":8,"count":0,"hidden":false,"can_act":true}],"chunk_size":20,"bookmarked":false});
    });

    server.get('/u/tgx.json', () => { // eslint-disable-line no-undef
      return response({
        "user": {
          "date_of_birth":moment().format('YYYY-MM-DD'),
          "created_at":moment().subtract(1, 'year')
        }
      });
    });
  }
});

test("User is not logged in", assert => {
  visit("/");
  click('#toggle-hamburger-menu');

  andThen(() => {
    assert.equal(find('.cakeday-link').length, 0, 'Cakeday is not shown to anonymous users');
  });
});

test('Anniversary emoji', assert => {
  logIn();
  Discourse.reset();

  visit("/t/some-really-interesting-topic/11");

  andThen(() => {
    const $posterIcons = find('.poster-icon');

    assert.equal($posterIcons[0].title, I18n.t('user.anniversary.title'));
    assert.equal($posterIcons[1].title, I18n.t('user.date_of_birth.title'));
    assert.equal(find('img.emoji', $posterIcons[0]).length, 1);
    assert.equal(find('img.emoji', $posterIcons[1]).length, 1);
  });

  click('.trigger-user-card');

  andThen(() => {
    const $emojiImages = find('.emoji-images div');

    assert.equal($emojiImages[1].title, I18n.t('user.anniversary.title'));
    assert.equal($emojiImages[0].title, I18n.t('user.date_of_birth.title'));
    assert.equal(1, $emojiImages[0].children.length);
    assert.equal(1, $emojiImages[1].children.length);
  });
});
<|endoftext|>


<commit_before>/*globals require, describe, it, before, after, WebGMEGlobal, WebGME*/

/**
 * @author pmeijer / https://github.com/pmeijer
 */

require('../../_globals.js');

var requirejs = require('requirejs'),
    should = require('chai').should(),
    ExecutorClient = requirejs('executor/ExecutorClient'),
    executorClient,
    server,
    serverBaseUrl;
// TODO: How to specify the nedb paths for jobList and workerList?
describe('ExecutorClient', function () {
    'use strict';

    before(function (done) {
        // we have to set the config here
        var config = WebGMEGlobal.getConfig(),
            param = {};
        config.port = 9001;
        config.authentication = false;
        config.enableExecutor = true;

        param.serverPort = config.port;

        serverBaseUrl = 'http://127.0.0.1:' + config.port;

        server = WebGME.standaloneServer(config);
        server.start(function () {
            executorClient = new ExecutorClient(param);
            done();
        });
    });

    after(function (done) {
        server.stop(done);
    });

    it('getWorkersInfo should return empty object', function (done) {
        executorClient.getWorkersInfo(function (err, res) {
            if (err) {
                done(err);
                return;
            }
            should.equal(typeof res, 'object');
            should.equal(Object.keys(res).length, 0);
            done();
        });
    });

    it('createJob followed by getInfo should return CREATED jobInfo', function (done) {
        var jobInfo = {
            hash: '77704f10a36aa4214f5b0095ba8099e729a10f46'
        };
        executorClient.createJob(jobInfo, function (err, res) {
            var createTime;
            if (err) {
                done(err);
                return;
            }
            should.equal(typeof res, 'object');
            createTime = res.createTime;
            should.equal(res.status, 'CREATED');
            should.equal(typeof createTime, 'string');
            executorClient.getInfo(jobInfo.hash, function (err, res) {
                if (err) {
                    done(err);
                    return;
                }
                should.equal(typeof res, 'object');
                should.equal(res.createTime, createTime);
                should.equal(res.status, 'CREATED');
                done();
            });
        });
    });

    it('getInfo for non-existing hash should return 404', function (done) {
        executorClient.getInfo('87704f10a36aa4214f5b0095ba8099e729a10f46', function (err, res) {
            should.equal(err,404);
            done();
        });
    });

    it('getAllInfo should return 500', function (done) {
        executorClient.getAllInfo(function(err) {
            should.equal(err, 500);
            done();
        });
    });

    it('getInfoByStatus SUCCESS should succeed', function (done) {
        executorClient.getInfoByStatus('SUCCESS', function(err, res) {
            should.equal(err, null);
            done();
        });
    });
});<commit_msg>#178 remove test for unimplemented call.<commit_after>/*globals require, describe, it, before, after, WebGMEGlobal, WebGME*/

/**
 * @author pmeijer / https://github.com/pmeijer
 */

require('../../_globals.js');

var requirejs = require('requirejs'),
    should = require('chai').should(),
    ExecutorClient = requirejs('executor/ExecutorClient'),
    executorClient,
    server,
    serverBaseUrl;
// TODO: How to specify the nedb paths for jobList and workerList?
describe('ExecutorClient', function () {
    'use strict';

    before(function (done) {
        // we have to set the config here
        var config = WebGMEGlobal.getConfig(),
            param = {};
        config.port = 9001;
        config.authentication = false;
        config.enableExecutor = true;

        param.serverPort = config.port;

        serverBaseUrl = 'http://127.0.0.1:' + config.port;

        server = WebGME.standaloneServer(config);
        server.start(function () {
            executorClient = new ExecutorClient(param);
            done();
        });
    });

    after(function (done) {
        server.stop(done);
    });

    it('getWorkersInfo should return empty object', function (done) {
        executorClient.getWorkersInfo(function (err, res) {
            if (err) {
                done(err);
                return;
            }
            should.equal(typeof res, 'object');
            should.equal(Object.keys(res).length, 0);
            done();
        });
    });

    it('createJob followed by getInfo should return CREATED jobInfo', function (done) {
        var jobInfo = {
            hash: '77704f10a36aa4214f5b0095ba8099e729a10f46'
        };
        executorClient.createJob(jobInfo, function (err, res) {
            var createTime;
            if (err) {
                done(err);
                return;
            }
            should.equal(typeof res, 'object');
            createTime = res.createTime;
            should.equal(res.status, 'CREATED');
            should.equal(typeof createTime, 'string');
            executorClient.getInfo(jobInfo.hash, function (err, res) {
                if (err) {
                    done(err);
                    return;
                }
                should.equal(typeof res, 'object');
                should.equal(res.createTime, createTime);
                should.equal(res.status, 'CREATED');
                done();
            });
        });
    });

    it('getInfo for non-existing hash should return 404', function (done) {
        executorClient.getInfo('87704f10a36aa4214f5b0095ba8099e729a10f46', function (err, res) {
            should.equal(err,404);
            done();
        });
    });

    it('getAllInfo should return 500', function (done) {
        executorClient.getAllInfo(function(err) {
            should.equal(err, 500);
            done();
        });
    });

    //it('getInfoByStatus SUCCESS should succeed', function (done) {
    //    executorClient.getInfoByStatus('SUCCESS', function(err, res) {
    //        should.equal(err, null);
    //        done();
    //    });
    //});
});<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';

const InventoryDonorItem = props => {
  return (

            {props.title}

            Lorem ipsum dolor sit amet, consectetur adipiscing elit.
            Phasellus nec iaculis mauris.

            2 hours remaining

          Contact donor
          Claim

  );
};

InventoryDonorItem.propTypes = {
  title: PropTypes.string
};

export default InventoryDonorItem;
<commit_msg>replaced lorem ipsum with description from server<commit_after>import React, { PropTypes } from 'react';

const InventoryDonorItem = props => {
  return (

            {props.title}

            {props.description}

            2 hours remaining

          Contact donor
          Claim

  );
};

InventoryDonorItem.propTypes = {
  title: PropTypes.string,
  description: PropTypes.string
};

export default InventoryDonorItem;
<|endoftext|>


<commit_before>/**
 * Created by yangm11 on 11/10/2017.
 */
'use strict';

function randomString() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

  for( var i=0; i < 5; i++ )
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

let m = new Map();
let o = {};
let a = [];

function run(n) {
  let start = Date.now();
  for (let i = 0; i < n; i++) {
    m.set(randomString(), randomString());
  }
  console.log('Map set, ' + (Date.now() - start) + ' ms');

  start = Date.now();
  for (let i = 0; i < n; i++) {
    o[randomString()] = randomString();
  }
  console.log('Object set, ' + (Date.now() - start) + ' ms');

  start = Date.now();
  for (let i = 0; i < n; i++) {
    a.push([randomString(), randomString()]);
  }
  console.log('Array set, ' + (Date.now() - start) + ' ms');

  let s = randomString();

  start = Date.now();
  for (let key of m) {
    if (m.get(key) === s) {
      console.log('Found in map');
    }
  }
  console.log('Iterate the map in ' + (Date.now() - start) + ' ms');

  start = Date.now();
  let props = Object.keys(o);
  for (let i = 0; i < props.length; i++) {
    if (o[props[i]] === s) {
      console.log('Found in object');
    }
  }
  console.log('Iterate the object in ' + (Date.now() - start) + ' ms');

  start = Date.now();
  for (let i = 0; i < a.length; i++) {
    if (a[i][1] === s) {
      console.log('Found in array');
    }
  }
  console.log('Iterate the array in ' + (Date.now() - start) + ' ms');
}

if (typeof module !== 'undefined' && module.parent) {

} else {
  // test code go here
  run(3000000);
}<commit_msg>testing<commit_after>/**
 * Created by yangm11 on 11/10/2017.
 */
'use strict';

function randomString() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  for( var i=0; i < 5; i++ )
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

let m = new Map();
let o = {};
let a = [];

function run(n) {
  let start = Date.now();
  for (let i = 0; i < n; i++) {
    let s = randomString();
    if (m.has(s)) {
      m.get(s).push(randomString());
    } else {
      m.set(s, [randomString()]);
    }
  }
  console.log('Map set, ' + (Date.now() - start) + ' ms');

  start = Date.now();
  for (let i = 0; i < n; i++) {
    let s = randomString();
    if (o[s]) {
      o[s].push(randomString());
    } else {
      o[s] = [randomString()];
    }
  }
  console.log('Object set, ' + (Date.now() - start) + ' ms');

  start = Date.now();
  for (let i = 0; i < n; i++) {
    let s = randomString();
    if (i === 0) {
      a.push([s, randomString()]);
    } else {
      for (let j = 0; j < a.length; j++) {
        if (a[j][0] === s) {
          a[j].push(randomString());
          break;
        }
        if (j === a.length - 1) {
          a.push([s, randomString()]);
        }
      }
    }

  }
  console.log('Array set, ' + (Date.now() - start) + ' ms');

  let s = randomString();

  start = Date.now();
  for (let [k, v] of m.keys()) {
    if (v.includes(s)) {
      console.log('Found in map');
    }
  }
  console.log('Iterate the map in ' + (Date.now() - start) + ' ms');

  start = Date.now();
  let props = Object.keys(o);
  for (let i = 0; i < props.length; i++) {
    if (o[props[i]].includes(s)) {
      console.log('Found in object');
    }
  }
  console.log('Iterate the object in ' + (Date.now() - start) + ' ms');

  start = Date.now();
  for (let i = 0; i < a.length; i++) {
    if (a[i].includes(s)) {
      console.log('Found in array');
    }
  }
  console.log('Iterate the array in ' + (Date.now() - start) + ' ms');
  console.log(a.slice(0, 10));
  console.log(a.length);
}

if (typeof module !== 'undefined' && module.parent) {

} else {
  // test code go here
  run(3000000);
}<|endoftext|>