<commit_before>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function mark_for_destroy(element) {
    $(element).next('.should_destroy').value = 1;
    $(element).up('.role_membership').hide();
}

function toggle_investigator_forms(id_to_show) {

    id_to_hide = $("active_form").value;
    id_to_hide = "form_investigate_" + id_to_hide;

    $("active_form").value = id_to_show;
    id_to_show = "form_investigate_" + id_to_show;

    $(id_to_hide).hide();
    $(id_to_show).show();

}

function sendConditionRequest(path, element, event_id, question_element_id, spinner_id) {
    if (typeof spinner_id == "undefined")
        spinner_id = 'investigator_answer_' +  question_element_id + '_spinner';
    new Ajax.Request(path + '?question_element_id=' + question_element_id +'&response=' + element.value + '&event_id=' + event_id, {
        asynchronous: true,
        evalScripts:  true,
        onCreate:     function() {
            $(spinner_id).show();
        },
        onComplete:   function() {
            $(spinner_id).hide();
        }
    });
}

function sendCoreConditionRequest(path, element, event_id, core_path, spinner_id) {
    if (typeof spinner_id == "undefined")
        spinner_id = core_path + '_spinner';
    new Ajax.Request(path +'?core_path=' + core_path + '&response=' + element.value + '&event_id=' + event_id, {
        asynchronous: true,
        evalScripts:  true,
        onCreate:     function() {
            $(spinner_id).show();
        },
        onComplete:   function() {
            $(spinner_id).hide();
        }
    });
}

function updateStatusRequest(path, value) {
    separator = (path.indexOf("?") > 0) ? "&" : "?";
    new Ajax.Request(path + separator + 'task[status]=' + value, {
        asynchronous:true,
        evalScripts:true,
        method:'put'
    });
}

function setUpSearchFields() {
    if (document.getElementById("name").value.length > 0) {
        document.getElementById("sw_first_name").disabled = true;
        document.getElementById("sw_last_name").disabled = true;
    }

    if (document.getElementById("sw_first_name").value.length > 0 || document.getElementById("sw_last_name").value.length > 0) {
        document.getElementById("name").disabled = true;
    }
}

function checkNameSearchFields(field) {
    if (field.id == "name") {
        if (field.value.length > 0) {
            document.getElementById("sw_first_name").disabled = true;
            document.getElementById("sw_last_name").disabled = true;
        }
        else {
            document.getElementById("sw_first_name").disabled = false;
            document.getElementById("sw_last_name").disabled = false;
        }
    }
    else if (field.id == "sw_first_name" || field.id == "sw_last_name") {
        first = document.getElementById("sw_first_name");
        last = document.getElementById("sw_last_name");

        if (first.value.length > 0 || last.value.length > 0) {
            document.getElementById("name").disabled = true;
        }
        else {
            document.getElementById("name").disabled = false;
        }
    }
}

function build_url_with_tab_index(url) {
    if (!(window.myTabs === undefined)) {
        url = url + "?tab_index=" + myTabs.get("activeIndex");
    }
    return url;
}

function send_url_with_tab_index(url) {
    url = build_url_with_tab_index(url);
    location.href = url;
}

function add_tab_index_to_action(form) {
    form.action = build_url_with_tab_index(form.action);
}

function post_and_return(form_id) {
    form = document.getElementById(form_id);
    form.action = build_url_with_tab_index(form.action);
    form.action = form.action + "&return=true";
    form.submit();
}

function post_and_exit(form_id) {
    form = document.getElementById(form_id);
    form.action = build_url_with_tab_index(form.action);
    form.submit();
}

function toggle_strike_through(element_id) {
    Element.toggleClassName(element_id, 'struck-through');
}

function safe_disable(target) {
    element = document.getElementById(target);
    if (element) {
        element.disabled=true;
    }
}

function toggle_save_buttons(state) {
    btn1 = document.getElementById('save_and_exit_btn');
    btn2 = document.getElementById('save_and_continue_btn');

    var btns = new Array(btn1, btn2);
    $A(btns).each(function(btn) {
        if (btn) {
            if (state == 'on') {
                btn.disabled=false
            } else {
                btn.disabled=true;
            }
        }
    })
}

function contact_parent_address(id) {
  new Ajax.Request('../../contact_events/copy_address/' + id, {
    asynchronous: true,
    evalScripts:  true,
    onComplete: function(transport, json) {
      for (var key in json)
        if (json[key])
          document.getElementById('contact_event_active_patient__address_' + key).value = json[key];
    }
  });
}

function global_shortcuts_init() {
  shortcut.add("Ctrl+Shift+N", function() {
    window.location = "/cmrs/new";
  });

  shortcut.add("Ctrl+Shift+M", function() {
    window.location = "/forms";
  });

  shortcut.add("Ctrl+Shift+.",function() {
    window.location = "/search/people";
  });

  shortcut.add("Ctrl+Shift+Question",function(){
    window.location = "/search/cmrs";
  });

  shortcut.add("Ctrl+Shift+,",function(){
    window.location = "/cmrs";
  });
}

function cmr_shortcuts_init() {
  shortcut.add("Ctrl+Shift+X", function(e) {
    myTabs.set('activeIndex', (
        myTabs.get('activeIndex') == myTabs.get('tabs').length-1 ?
        0 : myTabs.get('activeIndex') + 1
      ));

    //Grab the first thing to focus in the tab
    YAHOO.util.Dom.getElementsBy(function(el) {
        return (el.tagName == 'SELECT' || el.tagName == 'INPUT' || el.tagName == 'A');
      }, '', myTabs.get('activeTab').get('contentEl'))[0].focus();
  },
  {
    'type':'keypress',
    'propagate':false,
    'target':document
  });

  shortcut.add("Ctrl+Shift+Z", function(e) {
    e.stopPropagation();
    e.preventDefault();
    myTabs.set('activeIndex', (
        myTabs.get('activeIndex') == 0 ?
        myTabs.get('tabs').length-1 : myTabs.get('activeIndex')-1
      ));

    YAHOO.util.Dom.getElementsBy(function(el) {
        return (el.tagName == 'SELECT' || el.tagName == 'INPUT' || el.tagName == 'A');
      }, '', myTabs.get('activeTab').get('contentEl'))[0].focus();
  },
  {
    'type':'keypress',
    'propagate':false,
    'target':document
  });

  shortcut.add("Ctrl+Shift+S", function() {
    document.getElementById('save_and_exit_btn').focus();
  });
}
<commit_msg>tri1339 -- fixed shortcuts for ie7<commit_after>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function mark_for_destroy(element) {
    $(element).next('.should_destroy').value = 1;
    $(element).up('.role_membership').hide();
}

function toggle_investigator_forms(id_to_show) {

    id_to_hide = $("active_form").value;
    id_to_hide = "form_investigate_" + id_to_hide;

    $("active_form").value = id_to_show;
    id_to_show = "form_investigate_" + id_to_show;

    $(id_to_hide).hide();
    $(id_to_show).show();

}

function sendConditionRequest(path, element, event_id, question_element_id, spinner_id) {
    if (typeof spinner_id == "undefined")
        spinner_id = 'investigator_answer_' +  question_element_id + '_spinner';
    new Ajax.Request(path + '?question_element_id=' + question_element_id +'&response=' + element.value + '&event_id=' + event_id, {
        asynchronous: true,
        evalScripts:  true,
        onCreate:     function() {
            $(spinner_id).show();
        },
        onComplete:   function() {
            $(spinner_id).hide();
        }
    });
}

function sendCoreConditionRequest(path, element, event_id, core_path, spinner_id) {
    if (typeof spinner_id == "undefined")
        spinner_id = core_path + '_spinner';
    new Ajax.Request(path +'?core_path=' + core_path + '&response=' + element.value + '&event_id=' + event_id, {
        asynchronous: true,
        evalScripts:  true,
        onCreate:     function() {
            $(spinner_id).show();
        },
        onComplete:   function() {
            $(spinner_id).hide();
        }
    });
}

function updateStatusRequest(path, value) {
    separator = (path.indexOf("?") > 0) ? "&" : "?";
    new Ajax.Request(path + separator + 'task[status]=' + value, {
        asynchronous:true,
        evalScripts:true,
        method:'put'
    });
}

function setUpSearchFields() {
    if (document.getElementById("name").value.length > 0) {
        document.getElementById("sw_first_name").disabled = true;
        document.getElementById("sw_last_name").disabled = true;
    }

    if (document.getElementById("sw_first_name").value.length > 0 || document.getElementById("sw_last_name").value.length > 0) {
        document.getElementById("name").disabled = true;
    }
}

function checkNameSearchFields(field) {
    if (field.id == "name") {
        if (field.value.length > 0) {
            document.getElementById("sw_first_name").disabled = true;
            document.getElementById("sw_last_name").disabled = true;
        }
        else {
            document.getElementById("sw_first_name").disabled = false;
            document.getElementById("sw_last_name").disabled = false;
        }
    }
    else if (field.id == "sw_first_name" || field.id == "sw_last_name") {
        first = document.getElementById("sw_first_name");
        last = document.getElementById("sw_last_name");

        if (first.value.length > 0 || last.value.length > 0) {
            document.getElementById("name").disabled = true;
        }
        else {
            document.getElementById("name").disabled = false;
        }
    }
}

function build_url_with_tab_index(url) {
    if (!(window.myTabs === undefined)) {
        url = url + "?tab_index=" + myTabs.get("activeIndex");
    }
    return url;
}

function send_url_with_tab_index(url) {
    url = build_url_with_tab_index(url);
    location.href = url;
}

function add_tab_index_to_action(form) {
    form.action = build_url_with_tab_index(form.action);
}

function post_and_return(form_id) {
    form = document.getElementById(form_id);
    form.action = build_url_with_tab_index(form.action);
    form.action = form.action + "&return=true";
    form.submit();
}

function post_and_exit(form_id) {
    form = document.getElementById(form_id);
    form.action = build_url_with_tab_index(form.action);
    form.submit();
}

function toggle_strike_through(element_id) {
    Element.toggleClassName(element_id, 'struck-through');
}

function safe_disable(target) {
    element = document.getElementById(target);
    if (element) {
        element.disabled=true;
    }
}

function toggle_save_buttons(state) {
    btn1 = document.getElementById('save_and_exit_btn');
    btn2 = document.getElementById('save_and_continue_btn');

    var btns = new Array(btn1, btn2);
    $A(btns).each(function(btn) {
        if (btn) {
            if (state == 'on') {
                btn.disabled=false
            } else {
                btn.disabled=true;
            }
        }
    })
}

function contact_parent_address(id) {
  new Ajax.Request('../../contact_events/copy_address/' + id, {
    asynchronous: true,
    evalScripts:  true,
    onComplete: function(transport, json) {
      for (var key in json)
        if (json[key])
          document.getElementById('contact_event_active_patient__address_' + key).value = json[key];
    }
  });
}

function global_shortcuts_init() {
  shortcut.add("Ctrl+Shift+N", function() {
    window.location = "/cmrs/new";
  });

  shortcut.add("Ctrl+Shift+M", function() {
    window.location = "/forms";
  });

  shortcut.add("Ctrl+Shift+.",function() {
    window.location = "/search/people";
  });

  shortcut.add("Ctrl+Shift+Question",function(){
    window.location = "/search/cmrs";
  });

  shortcut.add("Ctrl+Shift+,",function(){
    window.location = "/cmrs";
  });
}

function cmr_shortcuts_init() {
  shortcut.add("Ctrl+Shift+X", function() {
    myTabs.set('activeIndex', (
        myTabs.get('activeIndex') == myTabs.get('tabs').length-1 ?
        0 : myTabs.get('activeIndex') + 1
      ));

    //Grab the first thing to focus in the tab
    YAHOO.util.Dom.getElementsBy(function(el) {
        return (el.tagName == 'SELECT' || el.tagName == 'INPUT' || el.tagName == 'A');
      }, '', myTabs.get('activeTab').get('contentEl'))[0].focus();
  });

  shortcut.add("Ctrl+Shift+Z", function() {
    myTabs.set('activeIndex', (
        myTabs.get('activeIndex') == 0 ?
        myTabs.get('tabs').length-1 : myTabs.get('activeIndex')-1
      ));

    YAHOO.util.Dom.getElementsBy(function(el) {
        return (el.tagName == 'SELECT' || el.tagName == 'INPUT' || el.tagName == 'A');
      }, '', myTabs.get('activeTab').get('contentEl'))[0].focus();
  });

  shortcut.add("Ctrl+Shift+S", function() {
    document.getElementById('save_and_exit_btn').focus();
  });
}
<|endoftext|>


<commit_before>var express					= require('express'),
		path						= require('path'),
		RouteController = require('./controllers/routes');
		// AuthController 	= require('./controllers/auth');

module.exports = function(app) {
	var router = express.Router();
	// API routes ===========================================================

	router.get('/', function(req, res) {
		res.json({ message: 'Welcome to the API!' });
	});

	// API route handlers for /media
	router.route('/media')
		.post(RouteController.postMedia)
		.get(RouteController.getMedia);

	// API route handlers for /media/:file
	router.route('/media/:file')
		.get(RouteController.getFile)
		.put(RouteController.putFile)
		.delete(RouteController.deleteFile);

	/* Register API Routes */
	app.use('/api/v1', router);

	// frontend routes ===========================================================

	/* Front End Routes Handled by Angular */
	app.get('*', function(req, res) {
		res.sendFile(path.join(__dirname, '../public/views', 'index.html'));
	});
};<commit_msg>Adding API routes for users, removing commented out code<commit_after>var express					= require('express'),
		path						= require('path'),
		RouteController = require('./controllers/routes');

module.exports = function(app) {
	var router = express.Router();
	// API routes ===========================================================

	router.get('/', function(req, res) {
		res.json({ message: 'Welcome to the API!' });
	});

	// API route handlers for /media
	router.route('/media')
		.post(RouteController.postMedia)
		.get(RouteController.getMedia);

	// API route handlers for /media/:file
	router.route('/media/:file')
		.get(RouteController.getFile)
		.put(RouteController.putFile)
		.delete(RouteController.deleteFile);

	// API route handlers for /users
	router.route('/users')
		.post(RouteController.postUsers)
		.get(RouteController.getUsers);

	// API route handlers for /users/:user
	router.route('/users/:user')
		.get(RouteController.getUser)
		.put(RouteController.putUser)
		.delete(RouteController.deleteUser);

	/* Register API Routes */
	app.use('/api/v1', router);

	// frontend routes ===========================================================

	/* Front End Routes Handled by Angular */
	app.get('*', function(req, res) {
		res.sendFile(path.join(__dirname, '../public/views', 'index.html'));
	});
};<|endoftext|>


<commit_before>import './styles.scss'

import React, { Component } from 'react'
import { connect } from 'kea'

import SubmitButton from 'lib/tags/submit-button'

import sceneLogic from 'scenes/login/logic'
import sceneSaga from 'scenes/login/saga'

const logic = connect({
  actions: [
    sceneLogic, [
      'setEmail',
      'setPassword',
      'performLogin'
    ]
  ],
  props: [
    sceneLogic, [
      'email',
      'password',
      'errors',
      'isSubmitting'
    ]
  ],
  sagas: [
    sceneSaga
  ]
})

class LoginScene extends Component {
  handleFormSubmit = (e) => {
    const { performLogin } = this.props.actions
    e.preventDefault()
    performLogin()
  }

  render () {
    const { email, password, errors, isSubmitting } = this.props
    const { setEmail, setPassword } = this.props.actions

    return (

        <form className='login-box' onSubmit={this.handleFormSubmit}>

            Insights

            email
            <input autoFocus type='text' className='input-text' value={email} onChange={(e) => setEmail(e.target.value)} />

          {errors.email ? (

{errors.email}

          ) : null}

            password
            <input type='password' className='input-text' value={password} onChange={(e) => setPassword(e.target.value)} />

          {errors.password ? (

{errors.password}

          ) : null}

            <SubmitButton type='submit' isSubmitting={isSubmitting}>Login</SubmitButton>

            Login with Google

        </form>

    )
  }
}

export default logic(LoginScene)
<commit_msg>disable link to google for now<commit_after>import './styles.scss'

import React, { Component } from 'react'
import { connect } from 'kea'

import SubmitButton from 'lib/tags/submit-button'

import sceneLogic from 'scenes/login/logic'
import sceneSaga from 'scenes/login/saga'

const logic = connect({
  actions: [
    sceneLogic, [
      'setEmail',
      'setPassword',
      'performLogin'
    ]
  ],
  props: [
    sceneLogic, [
      'email',
      'password',
      'errors',
      'isSubmitting'
    ]
  ],
  sagas: [
    sceneSaga
  ]
})

class LoginScene extends Component {
  handleFormSubmit = (e) => {
    const { performLogin } = this.props.actions
    e.preventDefault()
    performLogin()
  }

  render () {
    const { email, password, errors, isSubmitting } = this.props
    const { setEmail, setPassword } = this.props.actions

    return (

        <form className='login-box' onSubmit={this.handleFormSubmit}>

            Insights

            email
            <input autoFocus type='text' className='input-text' value={email} onChange={(e) => setEmail(e.target.value)} />

          {errors.email ? (

{errors.email}

          ) : null}

            password
            <input type='password' className='input-text' value={password} onChange={(e) => setPassword(e.target.value)} />

          {errors.password ? (

{errors.password}

          ) : null}

            <SubmitButton type='submit' isSubmitting={isSubmitting}>Login</SubmitButton>

          {false &&

            Login with Google

}
        </form>

    )
  }
}

export default logic(LoginScene)
<|endoftext|>


<commit_before>module.exports = {
  collated: true,
  context: {
    id: 'id',
    label: 'Radio Label',
    name: 'radio'
  }
};
<commit_msg>#21479 - radio button - added variable class<commit_after>module.exports = {
  collated: true,
  context: {
    id: 'id',
    label: 'Radio Label',
    name: 'radio',
    class: ''
  }
};
<|endoftext|>


<commit_before>import debugModule from "debug";
const debug = debugModule("test:data:more-decoding"); //eslint-disable-line no-unused-vars

import { assert } from "chai";

import Ganache from "ganache-core";

import { prepareContracts } from "../helpers";
import Debugger from "lib/debugger";

import solidity from "lib/solidity/selectors";

import BN from "bn.js";

const __CONTAINERS = `
pragma solidity ^0.5.0;

contract ContainersTest {

  //provides a nice ending point
  event Done();

  //declare needed structs
  struct Pair {
    uint x;
    uint y;
  }

  struct HasMap {
    uint x;
    mapping(string => string) map;
    uint y;
  }

  //declare storage variables to be tested
  Pair[] storageStructArray;
  uint128[4][] storageArrayArray;

  mapping(string => Pair) structMapping;
  mapping(string => uint128[4]) arrayMapping;

  mapping(string => int128) signedMapping;

  //this one is not tested directly
  uint[2] pointedAt;

  function run() public {

    //declare local variables to be tested
    uint[2] memory memoryStaticArray;
    HasMap memory memoryStructWithMap;
    uint[2] storage localStorage = pointedAt;

    //set up variables with values
    storageStructArray.length = 1;
    storageStructArray[0].x = 107;
    storageStructArray[0].y = 214;

    storageArrayArray.length = 1;
    storageArrayArray[0][0] = 2;
    storageArrayArray[0][1] = 3;
    storageArrayArray[0][2] = 7;
    storageArrayArray[0][3] = 57;

    structMapping["hello"].x = 107;
    structMapping["hello"].y = 214;

    arrayMapping["hello"][0] = 2;
    arrayMapping["hello"][1] = 3;
    arrayMapping["hello"][2] = 7;
    arrayMapping["hello"][3] = 57;

    signedMapping["hello"] = -1;

    memoryStaticArray[0] = 107;
    memoryStaticArray[1] = 214;

    memoryStructWithMap.x = 107;
    memoryStructWithMap.y = 214;

    //for this one, let's mix how we access it
    localStorage[0] = 107;
    pointedAt[1] = 214;

    //everything's set up, time to decode!
    emit Done(); //break here (71)
  }
}
`;

let sources = {
  "ContainerTest.sol": __CONTAINERS
};

describe("Further Decoding", function() {
  var provider;

  var abstractions;
  var artifacts;
  var files;

  before("Create Provider", async function() {
    provider = Ganache.provider({ seed: "debugger", gasLimit: 7000000 });
  });

  before("Prepare contracts and artifacts", async function() {
    this.timeout(30000);

    let prepared = await prepareContracts(provider, sources);
    abstractions = prepared.abstractions;
    artifacts = prepared.artifacts;
    files = prepared.files;
  });

  it("Decodes various reference types correctly", async function() {
    this.timeout(4000);

    let instance = await abstractions.ContainersTest.deployed();
    let receipt = await instance.run();
    let txHash = receipt.tx;

    let bugger = await Debugger.forTx(txHash, {
      provider,
      files,
      contracts: artifacts
    });

    let session = bugger.connect();

    let sourceId = session.view(solidity.current.source).id;
    session.addBreakpoint({ sourceId, line: 71 });

    session.continueUntilBreakpoint();

    const variables = await session.variables();

    const expectedResult = {
      memoryStaticArray: [new BN(107), new BN(214)],
      memoryStructWithMap: { x: new BN(107), y: new BN(214) },
      localStorage: [new BN(107), new BN(214)],
      storageStructArray: [{ x: new BN(107), y: new BN(214) }],
      storageArrayArray: [[new BN(2), new BN(3), new BN(7), new BN(57)]],
      structMapping: new Map([["hello", { x: new BN(107), y: new BN(214) }]]),
      arrayMapping: new Map([
        ["hello", [new BN(2), new BN(3), new BN(7), new BN(57)]]
      ]),
      signedMapping: new Map([["hello", -new BN(1)]]),
      pointedAt: [new BN(107), new BN(214)]
    };

    assert.hasAllKeys(variables, expectedResult);

    for (let name in expectedResult) {
      if (expectedResult[name] instanceof Map) {
        //each map has "hello" as its only key
        assert.deepEqual(
          variables[name]["hello"],
          expectedResult[name]["hello"]
        );
      } else {
        assert.deepEqual(variables[name], expectedResult[name]);
      }
    }
  });
});
<commit_msg>Turn up the timeout.  Sigh.<commit_after>import debugModule from "debug";
const debug = debugModule("test:data:more-decoding"); //eslint-disable-line no-unused-vars

import { assert } from "chai";

import Ganache from "ganache-core";

import { prepareContracts } from "../helpers";
import Debugger from "lib/debugger";

import solidity from "lib/solidity/selectors";

import BN from "bn.js";

const __CONTAINERS = `
pragma solidity ^0.5.0;

contract ContainersTest {

  //provides a nice ending point
  event Done();

  //declare needed structs
  struct Pair {
    uint x;
    uint y;
  }

  struct HasMap {
    uint x;
    mapping(string => string) map;
    uint y;
  }

  //declare storage variables to be tested
  Pair[] storageStructArray;
  uint128[4][] storageArrayArray;

  mapping(string => Pair) structMapping;
  mapping(string => uint128[4]) arrayMapping;

  mapping(string => int128) signedMapping;

  //this one is not tested directly
  uint[2] pointedAt;

  function run() public {

    //declare local variables to be tested
    uint[2] memory memoryStaticArray;
    HasMap memory memoryStructWithMap;
    uint[2] storage localStorage = pointedAt;

    //set up variables with values
    storageStructArray.length = 1;
    storageStructArray[0].x = 107;
    storageStructArray[0].y = 214;

    storageArrayArray.length = 1;
    storageArrayArray[0][0] = 2;
    storageArrayArray[0][1] = 3;
    storageArrayArray[0][2] = 7;
    storageArrayArray[0][3] = 57;

    structMapping["hello"].x = 107;
    structMapping["hello"].y = 214;

    arrayMapping["hello"][0] = 2;
    arrayMapping["hello"][1] = 3;
    arrayMapping["hello"][2] = 7;
    arrayMapping["hello"][3] = 57;

    signedMapping["hello"] = -1;

    memoryStaticArray[0] = 107;
    memoryStaticArray[1] = 214;

    memoryStructWithMap.x = 107;
    memoryStructWithMap.y = 214;

    //for this one, let's mix how we access it
    localStorage[0] = 107;
    pointedAt[1] = 214;

    //everything's set up, time to decode!
    emit Done(); //break here (71)
  }
}
`;

let sources = {
  "ContainerTest.sol": __CONTAINERS
};

describe("Further Decoding", function() {
  var provider;

  var abstractions;
  var artifacts;
  var files;

  before("Create Provider", async function() {
    provider = Ganache.provider({ seed: "debugger", gasLimit: 7000000 });
  });

  before("Prepare contracts and artifacts", async function() {
    this.timeout(30000);

    let prepared = await prepareContracts(provider, sources);
    abstractions = prepared.abstractions;
    artifacts = prepared.artifacts;
    files = prepared.files;
  });

  it("Decodes various reference types correctly", async function() {
    this.timeout(8000);

    let instance = await abstractions.ContainersTest.deployed();
    let receipt = await instance.run();
    let txHash = receipt.tx;

    let bugger = await Debugger.forTx(txHash, {
      provider,
      files,
      contracts: artifacts
    });

    let session = bugger.connect();

    let sourceId = session.view(solidity.current.source).id;
    session.addBreakpoint({ sourceId, line: 71 });

    session.continueUntilBreakpoint();

    const variables = await session.variables();

    const expectedResult = {
      memoryStaticArray: [new BN(107), new BN(214)],
      memoryStructWithMap: { x: new BN(107), y: new BN(214) },
      localStorage: [new BN(107), new BN(214)],
      storageStructArray: [{ x: new BN(107), y: new BN(214) }],
      storageArrayArray: [[new BN(2), new BN(3), new BN(7), new BN(57)]],
      structMapping: new Map([["hello", { x: new BN(107), y: new BN(214) }]]),
      arrayMapping: new Map([
        ["hello", [new BN(2), new BN(3), new BN(7), new BN(57)]]
      ]),
      signedMapping: new Map([["hello", -new BN(1)]]),
      pointedAt: [new BN(107), new BN(214)]
    };

    assert.hasAllKeys(variables, expectedResult);

    for (let name in expectedResult) {
      if (expectedResult[name] instanceof Map) {
        //each map has "hello" as its only key
        assert.deepEqual(
          variables[name]["hello"],
          expectedResult[name]["hello"]
        );
      } else {
        assert.deepEqual(variables[name], expectedResult[name]);
      }
    }
  });
});
<|endoftext|>


<commit_before>/*global QUnit*/

sap.ui.define([
	"sap/ui/thirdparty/jquery",
	"sap/ui/fl/registry/Settings",
	"sap/ui/fl/Cache",
	"sap/ui/fl/Utils",
	"sap/ui/fl/LrepConnector",
	"sap/ui/thirdparty/sinon-4"
], function(
	jQuery,
	Settings,
	Cache,
	Utils,
	LrepConnector,
	sinon
) {
	"use strict";

	var bPresetFlexChangeMode;
	var bFlexibilityAdaptationButtonAllowed;
	var sandbox = sinon.sandbox.create();

	QUnit.module("sapbyDefault.ui.fl.registry.Settings", {
		beforeEach: function() {
			bPresetFlexChangeMode = Settings._bFlexChangeMode;
			bFlexibilityAdaptationButtonAllowed = Settings._bFlexibilityAdaptationButtonAllowed;

			var oSettings = {
				isKeyUser: false,
				isAtoAvailable: false,
				isAtoEnabled: false,
				features: {
					addField: ["CUSTOMER", "VENDOR"],
					changeTypeOnlyForUser: ["USER"],
					completelyDisabledChangeType: []
				}
			};
			this.cut = new Settings(oSettings);
		},
		afterEach: function() {
			Settings._bFlexChangeMode = bPresetFlexChangeMode;
			Settings._bFlexibilityAdaptationButtonAllowed = bFlexibilityAdaptationButtonAllowed;

			Settings._instance = undefined;

			// detach all events
			jQuery.each(Settings._oEventProvider.mEventRegistry, function (sEventKey, aEvents) {
				jQuery.each(aEvents, function (index, oRegisteredEvent) {
					Settings.detachEvent(sEventKey, oRegisteredEvent.fFunction);
				});
			});

			sandbox.restore();
		}
	}, function() {
		QUnit.test("init", function(assert) {
			assert.ok(this.cut._oSettings);
		});

		QUnit.test("isKeyUser", function(assert) {
			assert.equal(this.cut._oSettings.isKeyUser, false);
			var bIsKeyUser = this.cut.isKeyUser();
			assert.equal(bIsKeyUser, false);
		});

		QUnit.test("isModelS", function(assert) {
			assert.equal(this.cut._oSettings.isAtoAvailable, false);
			var bIsModelS = this.cut.isModelS();
			assert.equal(bIsModelS, false);
		});

		QUnit.test("isAtoEnabled", function(assert) {
			assert.equal(this.cut._oSettings.isAtoEnabled, false);
			var bIsAtoEnabled = this.cut.isAtoEnabled();
			assert.equal(bIsAtoEnabled, false);
		});

		QUnit.test("variants sharing is enabled by default", function(assert) {
			assert.equal(this.cut._oSettings.isVariantSharingEnabled, true);
			var bIsVariantSharingEnabled = this.cut.isVariantSharingEnabled();
			assert.equal(bIsVariantSharingEnabled, true);
		});

		QUnit.test("variants sharing is set to false", function(assert) {
			var oSettings = {
				isVariantSharingEnabled: false
			};
			this.cut = new Settings(oSettings);
			assert.equal(this.cut._oSettings.isVariantSharingEnabled, false);
			var bIsVariantSharingEnabled = this.cut.isVariantSharingEnabled();
			assert.equal(bIsVariantSharingEnabled, false);
		});

		QUnit.test("get instance from flex settings request when flex data promise is not available", function(assert) {
			var done = assert.async();

			var oSetting = {
				isKeyUser: true,
				isAtoAvailable: true
			};

			var oStubCreateConnector = sandbox.stub(sap.ui.fl.LrepConnector, "createConnector").returns({
				loadSettings : function() {
					return Promise.resolve(oSetting);
				}
			});
			var oStubGetFlexDataPromise = sandbox.stub(Cache, "getFlexDataPromise").returns(undefined);
			Settings.getInstance().then(function(oSettings) {
				assert.equal(oStubGetFlexDataPromise.callCount, 1);
				assert.equal(oStubCreateConnector.callCount, 1);
				assert.equal(oSettings.isKeyUser(), true);
				assert.equal(oSettings.isModelS(), true);
				Settings.getInstance().then(function(oSettings2) {
					assert.equal(oStubCreateConnector.callCount, 1);
					assert.equal(oSettings, oSettings2);
					oStubCreateConnector.restore();
					oStubGetFlexDataPromise.restore();
					done();
				});
			});
		});

		QUnit.test("get instance from flex settings request when flex data promise is rejected", function(assert) {
			var done = assert.async();

			var oSetting = {
				isKeyUser: true,
				isAtoAvailable: true
			};
			var oStubCreateConnector = sandbox.stub(sap.ui.fl.LrepConnector, "createConnector").returns({
				loadSettings : function() {
					return Promise.resolve(oSetting);
				}
			});
			var oStubGetFlexDataPromise = sandbox.stub(Cache, "getFlexDataPromise").rejects();
			Settings.getInstance().then(function(oSettings) {
				assert.equal(oStubGetFlexDataPromise.callCount, 1);
				assert.equal(oStubCreateConnector.callCount, 1);
				assert.equal(oSettings.isKeyUser(), true);
				assert.equal(oSettings.isModelS(), true);
				Settings.getInstance().then(function(oSettings2) {
					assert.equal(oStubCreateConnector.callCount, 1);
					assert.equal(oSettings, oSettings2);
					oStubCreateConnector.restore();
					oStubGetFlexDataPromise.restore();
					done();
				});
			});
		});

		QUnit.test("get instance from cache when flex data promise is resolved", function(assert) {
			var done = assert.async();

			var oFileContent = {
				changes: {
					settings: {
						isKeyUser: true,
						isAtoAvailable: true
					}
				}
			};
			var oStubGetFlexDataPromise = sandbox.stub(Cache, "getFlexDataPromise").resolves(oFileContent);
			Settings.getInstance().then(function(oSettings) {
				assert.equal(oStubGetFlexDataPromise.callCount, 1);
				assert.equal(oSettings.isKeyUser(), true);
				assert.equal(oSettings.isModelS(), true);
				Settings.getInstance().then(function(oSettings2) {
					assert.equal(oSettings, oSettings2);
					oStubGetFlexDataPromise.restore();
					done();
				});
			});
		});

		QUnit.test("getInstanceOrUndef", function(assert) {
			var done = assert.async();

			var oSetting = {
				isKeyUser: true,
				isAtoAvailable: true
			};
			var oStubCreateConnector = sandbox.stub(sap.ui.fl.LrepConnector, "createConnector").returns({
				loadSettings : function() {
					return Promise.resolve(oSetting);
				}
			});
			var oSettings0 = Settings.getInstanceOrUndef();
			assert.ok(!oSettings0);
			Settings.getInstance().then(function(oSettings1) {
				assert.ok(oSettings1);
				assert.equal(oStubCreateConnector.callCount, 1);
				var oSettings2 = Settings.getInstanceOrUndef();
				assert.equal(oSettings1, oSettings2);
				assert.equal(oStubCreateConnector.callCount, 1);
				oStubCreateConnector.restore();
				done();
			});
		});

		QUnit.test("_isFlexChangeModeFromUrl", function(assert) {
			var bFlexChangeMode = Settings._isFlexChangeModeFromUrl();
			assert.equal(bFlexChangeMode, undefined);

			var UriParameters = sap.ui.require("sap/base/util/UriParameters");
			assert.ok(UriParameters, "UriParameters must be loaded");

			var oStub = sandbox.stub(UriParameters.prototype, "get");
			oStub.withArgs("sap-ui-fl-changeMode").returns("true");

			bFlexChangeMode = Settings._isFlexChangeModeFromUrl();
			assert.equal(bFlexChangeMode, true);
			oStub.withArgs("sap-ui-fl-changeMode").returns("false");
			bFlexChangeMode = Settings._isFlexChangeModeFromUrl();
			assert.equal(bFlexChangeMode, false);

			oStub.restore();
		});

		QUnit.test("isFlexChangeMode", function(assert) {
			var bFlexChangeMode = Settings.isFlexChangeMode();
			assert.equal(bFlexChangeMode, true); //default is true

			Settings.leaveFlexChangeMode();
			bFlexChangeMode = Settings.isFlexChangeMode();
			assert.equal(bFlexChangeMode, false);

			Settings.activateFlexChangeMode();
			bFlexChangeMode = Settings.isFlexChangeMode();
			assert.equal(bFlexChangeMode, true);

			var UriParameters = sap.ui.require("sap/base/util/UriParameters");
			assert.ok(UriParameters, "UriParameters must be loaded");

			var oStub = sandbox.stub(UriParameters.prototype, "get");
			oStub.withArgs("sap-ui-fl-changeMode").returns("false");

			bFlexChangeMode = Settings.isFlexChangeMode();
			assert.equal(bFlexChangeMode, false);

			oStub.restore();
		});

		QUnit.test("leave flexChangeMode eventing", function(assert) {
			var done = assert.async();

			var bFlexChangeMode = Settings.isFlexChangeMode();
			assert.equal(bFlexChangeMode, true); //default is true

			var fOnChangeModeUpdated = function(oEvent) {
				Settings.detachEvent(sap.ui.fl.registry.Settings.events.changeModeUpdated, fOnChangeModeUpdated.bind(this));
				assert.equal(oEvent.getParameter("bFlexChangeMode"), false);
				assert.equal(sap.ui.fl.registry.Settings.isFlexChangeMode(), false);
				done();
			};
			Settings.attachEvent(sap.ui.fl.registry.Settings.events.changeModeUpdated, fOnChangeModeUpdated.bind(this));
			sap.ui.fl.registry.Settings.leaveFlexChangeMode();
		});

		QUnit.test("activate flexChangeMode eventing", function(assert) {
			var done = assert.async();

			var bFlexChangeMode = Settings.isFlexChangeMode();
			assert.equal(bFlexChangeMode, true); //default is true

			var fOnChangeModeUpdated = function(oEvent) {
				Settings.detachEvent(sap.ui.fl.registry.Settings.events.changeModeUpdated, fOnChangeModeUpdated.bind(this));
				assert.equal(oEvent.getParameter("bFlexChangeMode"), true);
				assert.equal(Settings.isFlexChangeMode(), true);
				done();
			};
			Settings.leaveFlexChangeMode();
			Settings.attachEvent(sap.ui.fl.registry.Settings.events.changeModeUpdated, fOnChangeModeUpdated.bind(this));
			Settings.activateFlexChangeMode();
		});

		QUnit.test("returns by default adaptation button disllowed", function (assert) {
			var bFlexibilityAdaptationButtonAllowed = sap.ui.fl.registry.Settings.isFlexibilityAdaptationButtonAllowed();

			assert.equal(bFlexibilityAdaptationButtonAllowed, false);
		});

		QUnit.test("changes adaptation button allowed", function (assert) {
			var bRetrievedAdaptationButtonAllowed;
			var bFlexibilityAdaptationButtonAllowed = true;
			var bFlexibilityAdaptationButtonDisallowed = false;

			Settings.setFlexibilityAdaptationButtonAllowed(bFlexibilityAdaptationButtonDisallowed);
			bRetrievedAdaptationButtonAllowed = Settings.isFlexibilityAdaptationButtonAllowed();
			assert.equal(bRetrievedAdaptationButtonAllowed, bFlexibilityAdaptationButtonDisallowed);

			Settings.setFlexibilityAdaptationButtonAllowed(bFlexibilityAdaptationButtonAllowed);
			bRetrievedAdaptationButtonAllowed = Settings.isFlexibilityAdaptationButtonAllowed();
			assert.equal(bRetrievedAdaptationButtonAllowed, bFlexibilityAdaptationButtonAllowed);
		});

		QUnit.test("fires adaptation mode event on an adaptation button activation and the button is active", function(assert) {
			var done = assert.async();

			var fOnChangeModeUpdated = function(oEvent) {
				Settings.detachEvent(sap.ui.fl.registry.Settings.events.flexibilityAdaptationButtonAllowedChanged, fOnChangeModeUpdated.bind(this));
				assert.equal(oEvent.getParameter("bFlexibilityAdaptationButtonAllowed"), true, "the event was fired with the flag that the adaptation button was allowed");
				assert.equal(sap.ui.fl.registry.Settings.isFlexibilityAdaptationButtonAllowed(), true, "the adaptation button is allowed");
				done();
			};
			Settings.attachEvent(sap.ui.fl.registry.Settings.events.flexibilityAdaptationButtonAllowedChanged, fOnChangeModeUpdated.bind(this));
			Settings.setFlexibilityAdaptationButtonAllowed(true);
		});

		QUnit.test("fires adaptation mode event on an adaptation button deactivation and the button is deactive", function(assert) {
			var done = assert.async();

			var fOnChangeModeUpdated = function(oEvent) {
				Settings.detachEvent(sap.ui.fl.registry.Settings.events.flexibilityAdaptationButtonAllowedChanged, fOnChangeModeUpdated.bind(this));
				assert.equal(oEvent.getParameter("bFlexibilityAdaptationButtonAllowed"), false, "the event was fired with the flag that the adaptation button was disallowed");
				assert.equal(sap.ui.fl.registry.Settings.isFlexibilityAdaptationButtonAllowed(), false, "the adaptation button is disallowed");
				done();
			};
			sap.ui.fl.registry.Settings.setFlexibilityAdaptationButtonAllowed(true);
			Settings.attachEvent(sap.ui.fl.registry.Settings.events.flexibilityAdaptationButtonAllowedChanged, fOnChangeModeUpdated.bind(this));
			sap.ui.fl.registry.Settings.setFlexibilityAdaptationButtonAllowed(false);
		});
	});

	QUnit.module("Given that Settings file is loaded", {
		afterEach: function() {
			sandbox.restore();
		}
	}, function() {
		QUnit.test("and the system is a trial system", function(assert) {
			assert.notOk(Settings.getInstanceOrUndef(), "initially the instance is undefined");

			// call initialize function again to initialize with trial
			sandbox.stub(Utils, "isTrialSystem").returns(true);
			Settings._initInstance();

			var oSettings = Settings.getInstanceOrUndef();
			assert.ok(oSettings, "the settings instance is available");
			assert.equal(oSettings.isKeyUser(), true);
			assert.equal(oSettings.isAtoAvailable(), false);
			assert.equal(oSettings.isAtoEnabled(), false);
			assert.equal(oSettings.isProductiveSystem(), false);
			assert.equal(oSettings.isVariantSharingEnabled(), false);
		});
	});

	QUnit.module("Given that Settings loading failed", {
		afterEach: function() {
			sandbox.restore();
		}
	}, function() {
		QUnit.test("a default response is resolving the request", function(assert) {
			var oLrepConnector = new LrepConnector();
			sandbox.stub(oLrepConnector, "loadSettings").resolves();
			sandbox.stub(LrepConnector, "createConnector").returns(oLrepConnector);

			return Settings.getInstance().then(function (oSettings) {
				assert.ok(oSettings, "the settings instance is available");
				assert.equal(oSettings.isKeyUser(), false);
				assert.equal(oSettings.isAtoAvailable(), false);
				assert.equal(oSettings.isAtoEnabled(), false);
				assert.equal(oSettings.isProductiveSystem(), true);
				assert.equal(oSettings.isVariantSharingEnabled(), false);
			});
		});
	});

	QUnit.done(function () {
		jQuery("#qunit-fixture").hide();
	});
});
<commit_msg>[FIX][INTERNAL] sap.ui.fl.registry.Settings.qunit does not fail<commit_after>/*global QUnit*/

sap.ui.define([
	"sap/ui/thirdparty/jquery",
	"sap/ui/fl/registry/Settings",
	"sap/ui/fl/Cache",
	"sap/ui/fl/Utils",
	"sap/ui/fl/LrepConnector",
	"sap/ui/thirdparty/sinon-4"
], function(
	jQuery,
	Settings,
	Cache,
	Utils,
	LrepConnector,
	sinon
) {
	"use strict";

	var bPresetFlexChangeMode;
	var bFlexibilityAdaptationButtonAllowed;
	var sandbox = sinon.sandbox.create();

	QUnit.module("sapbyDefault.ui.fl.registry.Settings", {
		beforeEach: function() {
			bPresetFlexChangeMode = Settings._bFlexChangeMode;
			bFlexibilityAdaptationButtonAllowed = Settings._bFlexibilityAdaptationButtonAllowed;

			var oSettings = {
				isKeyUser: false,
				isAtoAvailable: false,
				isAtoEnabled: false,
				features: {
					addField: ["CUSTOMER", "VENDOR"],
					changeTypeOnlyForUser: ["USER"],
					completelyDisabledChangeType: []
				}
			};
			this.cut = new Settings(oSettings);
		},
		afterEach: function() {
			Settings._bFlexChangeMode = bPresetFlexChangeMode;
			Settings._bFlexibilityAdaptationButtonAllowed = bFlexibilityAdaptationButtonAllowed;

			Settings._instance = undefined;

			// detach all events
			jQuery.each(Settings._oEventProvider.mEventRegistry, function (sEventKey, aEvents) {
				jQuery.each(aEvents, function (index, oRegisteredEvent) {
					Settings.detachEvent(sEventKey, oRegisteredEvent.fFunction);
				});
			});

			sandbox.restore();
		}
	}, function() {
		QUnit.test("init", function(assert) {
			assert.ok(this.cut._oSettings);
		});

		QUnit.test("isKeyUser", function(assert) {
			assert.equal(this.cut._oSettings.isKeyUser, false);
			var bIsKeyUser = this.cut.isKeyUser();
			assert.equal(bIsKeyUser, false);
		});

		QUnit.test("isModelS", function(assert) {
			assert.equal(this.cut._oSettings.isAtoAvailable, false);
			var bIsModelS = this.cut.isModelS();
			assert.equal(bIsModelS, false);
		});

		QUnit.test("isAtoEnabled", function(assert) {
			assert.equal(this.cut._oSettings.isAtoEnabled, false);
			var bIsAtoEnabled = this.cut.isAtoEnabled();
			assert.equal(bIsAtoEnabled, false);
		});

		QUnit.test("variants sharing is enabled by default", function(assert) {
			assert.equal(this.cut._oSettings.isVariantSharingEnabled, true);
			var bIsVariantSharingEnabled = this.cut.isVariantSharingEnabled();
			assert.equal(bIsVariantSharingEnabled, true);
		});

		QUnit.test("variants sharing is set to false", function(assert) {
			var oSettings = {
				isVariantSharingEnabled: false
			};
			this.cut = new Settings(oSettings);
			assert.equal(this.cut._oSettings.isVariantSharingEnabled, false);
			var bIsVariantSharingEnabled = this.cut.isVariantSharingEnabled();
			assert.equal(bIsVariantSharingEnabled, false);
		});

		QUnit.test("get instance from flex settings request when flex data promise is not available", function(assert) {
			var done = assert.async();

			var oSetting = {
				isKeyUser: true,
				isAtoAvailable: true
			};

			var oStubCreateConnector = sandbox.stub(sap.ui.fl.LrepConnector, "createConnector").returns({
				loadSettings : function() {
					return Promise.resolve(oSetting);
				}
			});
			var oStubGetFlexDataPromise = sandbox.stub(Cache, "getFlexDataPromise").returns(undefined);
			Settings.getInstance().then(function(oSettings) {
				assert.equal(oStubGetFlexDataPromise.callCount, 1);
				assert.equal(oStubCreateConnector.callCount, 1);
				assert.equal(oSettings.isKeyUser(), true);
				assert.equal(oSettings.isModelS(), true);
				Settings.getInstance().then(function(oSettings2) {
					assert.equal(oStubCreateConnector.callCount, 1);
					assert.equal(oSettings, oSettings2);
					oStubCreateConnector.restore();
					oStubGetFlexDataPromise.restore();
					done();
				});
			});
		});

		QUnit.test("get instance from flex settings request when flex data promise is rejected", function(assert) {
			var done = assert.async();

			var oSetting = {
				isKeyUser: true,
				isAtoAvailable: true
			};
			var oStubCreateConnector = sandbox.stub(sap.ui.fl.LrepConnector, "createConnector").returns({
				loadSettings : function() {
					return Promise.resolve(oSetting);
				}
			});
			var oStubGetFlexDataPromise = sandbox.stub(Cache, "getFlexDataPromise").rejects();
			Settings.getInstance().then(function(oSettings) {
				assert.equal(oStubGetFlexDataPromise.callCount, 1);
				assert.equal(oStubCreateConnector.callCount, 1);
				assert.equal(oSettings.isKeyUser(), true);
				assert.equal(oSettings.isModelS(), true);
				Settings.getInstance().then(function(oSettings2) {
					assert.equal(oStubCreateConnector.callCount, 1);
					assert.equal(oSettings, oSettings2);
					oStubCreateConnector.restore();
					oStubGetFlexDataPromise.restore();
					done();
				});
			});
		});

		QUnit.test("get instance from cache when flex data promise is resolved", function(assert) {
			var done = assert.async();

			var oFileContent = {
				changes: {
					settings: {
						isKeyUser: true,
						isAtoAvailable: true
					}
				}
			};
			var oStubGetFlexDataPromise = sandbox.stub(Cache, "getFlexDataPromise").resolves(oFileContent);
			Settings.getInstance().then(function(oSettings) {
				assert.equal(oStubGetFlexDataPromise.callCount, 1);
				assert.equal(oSettings.isKeyUser(), true);
				assert.equal(oSettings.isModelS(), true);
				Settings.getInstance().then(function(oSettings2) {
					assert.equal(oSettings, oSettings2);
					oStubGetFlexDataPromise.restore();
					done();
				});
			});
		});

		QUnit.test("getInstanceOrUndef", function(assert) {
			var done = assert.async();

			var oSetting = {
				isKeyUser: true,
				isAtoAvailable: true
			};
			var oStubCreateConnector = sandbox.stub(sap.ui.fl.LrepConnector, "createConnector").returns({
				loadSettings : function() {
					return Promise.resolve(oSetting);
				}
			});
			var oSettings0 = Settings.getInstanceOrUndef();
			assert.ok(!oSettings0);
			Settings.getInstance().then(function(oSettings1) {
				assert.ok(oSettings1);
				assert.equal(oStubCreateConnector.callCount, 1);
				var oSettings2 = Settings.getInstanceOrUndef();
				assert.equal(oSettings1, oSettings2);
				assert.equal(oStubCreateConnector.callCount, 1);
				oStubCreateConnector.restore();
				done();
			});
		});

		QUnit.test("_isFlexChangeModeFromUrl", function(assert) {
			var bFlexChangeMode = Settings._isFlexChangeModeFromUrl();
			assert.equal(bFlexChangeMode, undefined);

			var UriParameters = sap.ui.require("sap/base/util/UriParameters");
			assert.ok(UriParameters, "UriParameters must be loaded");

			var oStub = sandbox.stub(UriParameters.prototype, "get");
			oStub.withArgs("sap-ui-fl-changeMode").returns("true");

			bFlexChangeMode = Settings._isFlexChangeModeFromUrl();
			assert.equal(bFlexChangeMode, true);
			oStub.withArgs("sap-ui-fl-changeMode").returns("false");
			bFlexChangeMode = Settings._isFlexChangeModeFromUrl();
			assert.equal(bFlexChangeMode, false);

			oStub.restore();
		});

		QUnit.test("isFlexChangeMode", function(assert) {
			var bFlexChangeMode = Settings.isFlexChangeMode();
			assert.equal(bFlexChangeMode, true); //default is true

			Settings.leaveFlexChangeMode();
			bFlexChangeMode = Settings.isFlexChangeMode();
			assert.equal(bFlexChangeMode, false);

			Settings.activateFlexChangeMode();
			bFlexChangeMode = Settings.isFlexChangeMode();
			assert.equal(bFlexChangeMode, true);

			var UriParameters = sap.ui.require("sap/base/util/UriParameters");
			assert.ok(UriParameters, "UriParameters must be loaded");

			var oStub = sandbox.stub(UriParameters.prototype, "get");
			oStub.withArgs("sap-ui-fl-changeMode").returns("false");

			bFlexChangeMode = Settings.isFlexChangeMode();
			assert.equal(bFlexChangeMode, false);

			oStub.restore();
		});

		QUnit.test("leave flexChangeMode eventing", function(assert) {
			var done = assert.async();

			var bFlexChangeMode = Settings.isFlexChangeMode();
			assert.equal(bFlexChangeMode, true); //default is true

			var fOnChangeModeUpdated = function(oEvent) {
				Settings.detachEvent(sap.ui.fl.registry.Settings.events.changeModeUpdated, fOnChangeModeUpdated.bind(this));
				assert.equal(oEvent.getParameter("bFlexChangeMode"), false);
				assert.equal(sap.ui.fl.registry.Settings.isFlexChangeMode(), false);
				done();
			};
			Settings.attachEvent(sap.ui.fl.registry.Settings.events.changeModeUpdated, fOnChangeModeUpdated.bind(this));
			sap.ui.fl.registry.Settings.leaveFlexChangeMode();
		});

		QUnit.test("activate flexChangeMode eventing", function(assert) {
			var done = assert.async();

			var bFlexChangeMode = Settings.isFlexChangeMode();
			assert.equal(bFlexChangeMode, true); //default is true

			var fOnChangeModeUpdated = function(oEvent) {
				Settings.detachEvent(sap.ui.fl.registry.Settings.events.changeModeUpdated, fOnChangeModeUpdated.bind(this));
				assert.equal(oEvent.getParameter("bFlexChangeMode"), true);
				assert.equal(Settings.isFlexChangeMode(), true);
				done();
			};
			Settings.leaveFlexChangeMode();
			Settings.attachEvent(sap.ui.fl.registry.Settings.events.changeModeUpdated, fOnChangeModeUpdated.bind(this));
			Settings.activateFlexChangeMode();
		});

		QUnit.test("returns by default adaptation button disllowed", function (assert) {
			var bFlexibilityAdaptationButtonAllowed = sap.ui.fl.registry.Settings.isFlexibilityAdaptationButtonAllowed();

			assert.equal(bFlexibilityAdaptationButtonAllowed, false);
		});

		QUnit.test("changes adaptation button allowed", function (assert) {
			var bRetrievedAdaptationButtonAllowed;
			var bFlexibilityAdaptationButtonAllowed = true;
			var bFlexibilityAdaptationButtonDisallowed = false;

			Settings.setFlexibilityAdaptationButtonAllowed(bFlexibilityAdaptationButtonDisallowed);
			bRetrievedAdaptationButtonAllowed = Settings.isFlexibilityAdaptationButtonAllowed();
			assert.equal(bRetrievedAdaptationButtonAllowed, bFlexibilityAdaptationButtonDisallowed);

			Settings.setFlexibilityAdaptationButtonAllowed(bFlexibilityAdaptationButtonAllowed);
			bRetrievedAdaptationButtonAllowed = Settings.isFlexibilityAdaptationButtonAllowed();
			assert.equal(bRetrievedAdaptationButtonAllowed, bFlexibilityAdaptationButtonAllowed);
		});

		QUnit.test("fires adaptation mode event on an adaptation button activation and the button is active", function(assert) {
			var done = assert.async();

			var fOnChangeModeUpdated = function(oEvent) {
				Settings.detachEvent(sap.ui.fl.registry.Settings.events.flexibilityAdaptationButtonAllowedChanged, fOnChangeModeUpdated.bind(this));
				assert.equal(oEvent.getParameter("bFlexibilityAdaptationButtonAllowed"), true, "the event was fired with the flag that the adaptation button was allowed");
				assert.equal(sap.ui.fl.registry.Settings.isFlexibilityAdaptationButtonAllowed(), true, "the adaptation button is allowed");
				done();
			};
			Settings.attachEvent(sap.ui.fl.registry.Settings.events.flexibilityAdaptationButtonAllowedChanged, fOnChangeModeUpdated.bind(this));
			Settings.setFlexibilityAdaptationButtonAllowed(true);
		});

		QUnit.test("fires adaptation mode event on an adaptation button deactivation and the button is deactive", function(assert) {
			var done = assert.async();

			var fOnChangeModeUpdated = function(oEvent) {
				Settings.detachEvent(sap.ui.fl.registry.Settings.events.flexibilityAdaptationButtonAllowedChanged, fOnChangeModeUpdated.bind(this));
				assert.equal(oEvent.getParameter("bFlexibilityAdaptationButtonAllowed"), false, "the event was fired with the flag that the adaptation button was disallowed");
				assert.equal(sap.ui.fl.registry.Settings.isFlexibilityAdaptationButtonAllowed(), false, "the adaptation button is disallowed");
				done();
			};
			sap.ui.fl.registry.Settings.setFlexibilityAdaptationButtonAllowed(true);
			Settings.attachEvent(sap.ui.fl.registry.Settings.events.flexibilityAdaptationButtonAllowedChanged, fOnChangeModeUpdated.bind(this));
			sap.ui.fl.registry.Settings.setFlexibilityAdaptationButtonAllowed(false);
		});
	});

	QUnit.module("Given that Settings file is loaded", {
		afterEach: function() {
			delete Settings._instance;
			sandbox.restore();
		}
	}, function() {
		QUnit.test("and the system is a trial system", function(assert) {
			assert.notOk(Settings.getInstanceOrUndef(), "initially the instance is undefined");

			// call initialize function again to initialize with trial
			sandbox.stub(Utils, "isTrialSystem").returns(true);
			Settings._initInstance();

			var oSettings = Settings.getInstanceOrUndef();
			assert.ok(oSettings, "the settings instance is available");
			assert.equal(oSettings.isKeyUser(), true);
			assert.equal(oSettings.isAtoAvailable(), false);
			assert.equal(oSettings.isAtoEnabled(), false);
			assert.equal(oSettings.isProductiveSystem(), false);
			assert.equal(oSettings.isVariantSharingEnabled(), false);
		});
	});

	QUnit.module("Given that Settings loading failed", {
		afterEach: function() {
			delete Settings._instance;
			sandbox.restore();
		}
	}, function() {
		QUnit.test("a default response is resolving the request", function(assert) {
			var oLrepConnector = new LrepConnector();
			sandbox.stub(oLrepConnector, "loadSettings").resolves();
			sandbox.stub(LrepConnector, "createConnector").returns(oLrepConnector);

			return Settings.getInstance().then(function (oSettings) {
				assert.ok(oSettings, "the settings instance is available");
				assert.equal(oSettings.isKeyUser(), false);
				assert.equal(oSettings.isAtoAvailable(), false);
				assert.equal(oSettings.isAtoEnabled(), false);
				assert.equal(oSettings.isProductiveSystem(), true);
				assert.equal(oSettings.isVariantSharingEnabled(), false);
			});
		});
	});

	QUnit.done(function () {
		jQuery("#qunit-fixture").hide();
	});
});
<|endoftext|>


<commit_before>/**
 * @package comments
 */
(function($) {
	$(document).ready(function () {

		var commentsHolder = $('.comments-holder'),
			commentsList = $('.comments-list', commentsHolder),
			noCommentsYet = $('.no-comments-yet', commentsHolder),
			form = $('#Form_CommentsForm'),
			error = $('#Form_CommentsForm_error', form).hide()

		/**
		 * Validate
		 */
		form.validate({
		invalidHandler : function(form, validator){
				$('html, body').animate({
			scrollTop: $(validator.errorList[0].element).offset().top - 30
			}, 200);
			},

			errorElement: "span",
			errorClass: "error",

			rules: {
				Name : {
					required : true
				},
				Email : {
					required : true,
					email : true
				},
				Comment: {
					required : true
				},
				URL: {
					url : true
				}
			},
			messages: {
				Name : {
					required : 'Plaese enter your name'
				},
				Email : {
					required : 'Plaese enter your email address',
					email : 'Plaese enter a valid email address'
				},
				Comment: {
					required : 'Plaese enter your comment'
				},
				URL: {
					url : 'Please enter a valid URL'
				}
			}
		});

		/**
		 * Clicking one of the metalinks performs the operation via ajax
		 * this inclues the spam and approve links
		 */
		form.submit(function (e) {

			// trigger validation, if there are errors add the error classes to the elements
			if(!form.validate().valid()){
				form.find('span.error').addClass('message required');
				return false;
			}

			// submit the form
			$(this).ajaxSubmit(function(response) {
				noCommentsYet.hide();

				if(!commentsList.length){
					commentsHolder.append("

");
					commentsList = $('.comments-list', commentsHolder);
				}

				var newComment = $('
')
					.addClass('even first')
					.html(response)
					.hide();

				if(response.match('Spam detected!!')) {
					newComment.addClass('spam');
				}

				commentsList.prepend(newComment.fadeIn());

				$(this).resetForm();

			});

			return false;
		});

		/**
		 * Clicking one of the metalinks performs the operation via ajax
		 * this inclues the spam and approve links
		 */
		$(".action-links a", commentsList).live('click', function(e) {
			var link = $(this);
			var comment = link.parents('.comment:first');
			var commentsList = comment.parents('ul:first');

			$.ajax({
				url: $(this).attr('href'),
				cache: false,
				success: function(html){
					if(link.hasClass('ham')) {
						// comment has been marked as not spam
						comment.html(html);
						comment.removeClass('spam').hide().fadeIn();
					}
					else if(link.hasClass('approve')) {
						// comment has been approved
						comment.html(html);
						comment.removeClass('unmoderated').hide().fadeIn();
					}
					else if(link.hasClass('delete')) {
						comment.fadeOut(1000, function() {
							comment.remove();

							if(commentsList.children().length == 0) {
								noCommentsYet.show();
							}
						});
					}
					else if(link.hasClass('spam')) {
						if(html) {
							comment.html(html).addClass('spam').hide().fadeIn();
						} else {
							comment.fadeOut(1000, function() {				// Fade out the comment
								comment.remove();							// remove the comment

								if(comments.children().length == 0) {
									noCommentsYet.show();
								}
							});
						}
					}
				},
				failure: function(html) {
					alert(html)
				}
			});

			e.preventDefault();
		})
	});
})(jQuery);
<commit_msg>AJAX pagination and some light house keeping<commit_after>/**
 * @package comments
 */
(function($) {
	$(document).ready(function () {

		var container = $('.comments-holder-container'),
			commentsHolder = $('.comments-holder'),
			commentsList = $('.comments-list', commentsHolder),
			pagination = $('.comments-pagination'),
			noCommentsYet = $('.no-comments-yet', commentsHolder),
			form = $('form', container);

		/**
		 * Validate
		 */
		form.validate({
		invalidHandler : function(form, validator){
				$('html, body').animate({
			scrollTop: $(validator.errorList[0].element).offset().top - 30
			}, 200);
			},

			errorElement: "span",
			errorClass: "error",

			rules: {
				Name : {
					required : true
				},
				Email : {
					required : true,
					email : true
				},
				Comment: {
					required : true
				},
				URL: {
					url : true
				}
			},
			messages: {
				Name : {
					required : 'Plaese enter your name'
				},
				Email : {
					required : 'Plaese enter your email address',
					email : 'Plaese enter a valid email address'
				},
				Comment: {
					required : 'Plaese enter your comment'
				},
				URL: {
					url : 'Please enter a valid URL'
				}
			}
		});

		/**
		 * Clicking one of the metalinks performs the operation via ajax
		 * this inclues the spam and approve links
		 */
		form.submit(function (e) {

			// trigger validation, if there are errors add the error classes to the elements
			if(!form.validate().valid()){
				form.find('span.error').addClass('message required');
				return false;
			}

			// submit the form
			$(this).ajaxSubmit(function(response) {
				noCommentsYet.hide();

				if(!commentsList.length){
					commentsHolder.append("

");
					commentsList = $('.comments-list', commentsHolder);
				}

				var newComment = $('
')
					.addClass('even first')
					.html(response)
					.hide();

				if(response.match('Spam detected!!')) {
					newComment.addClass('spam');
				}

				commentsList.prepend(newComment.fadeIn());

				$(this).resetForm();

			});

			return false;
		});

		/**
		 * Clicking one of the metalinks performs the operation via ajax
		 * this inclues the spam and approve links
		 */
		$(".action-links a", commentsList).live('click', function(e) {
			var link = $(this);
			var comment = link.parents('.comment:first');

			$.ajax({
				url: $(this).attr('href'),
				cache: false,
				success: function(html){
					if(link.hasClass('ham')) {
						// comment has been marked as not spam
						comment.html(html);
						comment.removeClass('spam').hide().fadeIn();
					}
					else if(link.hasClass('approve')) {
						// comment has been approved
						comment.html(html);
						comment.removeClass('unmoderated').hide().fadeIn();
					}
					else if(link.hasClass('delete')) {
						comment.fadeOut(1000, function() {
							comment.remove();

							if(commentsList.children().length == 0) {
								noCommentsYet.show();
							}
						});
					}
					else if(link.hasClass('spam')) {
						comment.html(html).addClass('spam').hide().fadeIn();
					}
				},
				failure: function(html) {
					alert(html)
				}
			});

			e.preventDefault();
		});

		/**
		 * Ajax pagination
		 */
		pagination.find('a').live('click', function(){
			commentsList.addClass('loading');
			$.ajax({
				url: $(this).attr('href'),
				cache: false,
				success: function(html){
					html = $(html);
					commentsList.hide().html(html.find('.comments-list:first')).fadeIn();
					pagination.hide().html(html.find('.comments-pagination:first')).fadeIn();
					commentsList.removeClass('loading');
				},
				failure: function(html) {
					alert('Error loading comments');
				}
			});
			return false;
		});
	});
})(jQuery);
<|endoftext|>


<commit_before>{
  "id":18,
  "name":"Secure communications",
  "description": "Authenticates third party medical professionals and lets them send information securely.",
  "theme": "Platforms",
  "location": "Leeds",
  "phase":"beta",
  "sro":"Nic Harrison",
  "service_man":"Liz Whitefield",
  "facing":"internal",
  "phase-history":{
    "discovery": [
      {"label":"Completed", "date": "December 2014"}
    ],
    "alpha": [
      {"label":"Completed", "date": "July 2015"}
    ],
    "beta": [
      {"label":"Started", "date": "August 2015"},
      {"label":"Private beta predicted", "date": "April 2016"},
      {"label":"Public beta predicted", "date": "July 2016"}
    ]
  },
  "priority":"High",
  "prototype":"http://ds1500.herokuapp.com/"
}
<commit_msg>Private beta started<commit_after>{
  "id":18,
  "name":"Secure communications",
  "description": "Authenticates third party medical professionals and lets them send information securely.",
  "theme": "Platforms",
  "location": "Leeds",
  "phase":"beta",
  "sro":"Nic Harrison",
  "service_man":"Liz Whitefield",
  "facing":"internal",
  "phase-history":{
    "discovery": [
      {"label":"Completed", "date": "December 2014"}
    ],
    "alpha": [
      {"label":"Completed", "date": "July 2015"}
    ],
    "beta": [
      {"label":"Started", "date": "August 2015"},
      {"label":"Private beta started", "date": "April 2016"},
      {"label":"Public beta predicted", "date": "July 2016"}
    ]
  },
  "priority":"High",
  "prototype":"http://ds1500.herokuapp.com/"
}
<|endoftext|>


<commit_before>HOTGATOR = function() {

    var mapData;
    var dateLimit = new Date('3000-01-01');

    var dayIcon = [
            'img/sunday.png',
            'img/monday.png',
            'img/tuesday.png',
            'img/wednesday.png',
            'img/thursday.png',
            'img/friday.png',
            'img/saturday.png',
    ];

    function calagatorCallback (data) {
        makeMap(data);
    };

    var calagatorData = function() {
        var ajaxCall = $.getScript("http://calagator.org/events.json?callback=HOTGATOR.calagatorCallback");
    };

    calagatorData();

    var update = function(form) {

        console.log(form);
        var newdate = new Date($("select:first").val());
        if (!newdate) {
            return false;
        }

        dateLimit = newdate;
        console.log(dateLimit);
        calagatorData();
        return false;
    };

    var makeMap = function(mapData) {

        // Cleanup
        $(".eventlink").remove();

        var latlng = new google.maps.LatLng(45.5374054,  -122.65028);

        var myOptions = {
            zoom: 11,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.TERRAIN
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        console.log("made map");

        function correctHeight() {
            var window_height = $(window).height();
            var header_height = $("#search-container").offset().top;
            $("#search-container").height(window_height - header_height - 20); //-20 for padding
            $("#map_canvas").height(window_height - header_height);
        }
        correctHeight();

        jQuery.event.add(window, "resize", correctHeight);
        console.log("made window");

        var infowindow = new google.maps.InfoWindow();

        function getDayIcon(date) {
            var d = new Date(date);
            return (dayIcon[d.getDay()]);
        }

        function add_info_window(map, marker, infowindow, event) {
            var ed = event.start_time.split('T');
            var properDate = ed[0].split('-');
            function open_info_window() {
                infowindow.open(map,marker);
                infowindow.setContent('

' + event.title + '
'
                    + '
'
                    + '
' + properDate[1] + '-' + properDate[2] + '-' + properDate[0]
                    + '
'
                    + ed[1]
                    + '
'
                    + ' '
                    + event.venue.title
                    + '
'
                );
            }
            google.maps.event.addListener(marker, 'click', open_info_window);
            $("#event-" + event.id).click(open_info_window);
        }

        var lastDate = '0000-00-00';
        console.log("About to loop through events with " + dateLimit );

        // Loop through all events
        $.each(mapData, function(index,event){

            if (!event.venue)  {
                return true;
            }
            var place = new google.maps.LatLng(event.venue.latitude, event.venue.longitude);

            // Filter dates of events
            // TODO: add update of the search-container
            var eventDate = event.start_time.split('T');
            var comparedate = new Date(eventDate[0]);
            if (comparedate > dateLimit) {
                console.log("skipping event on day" + eventDate[0]);
                return true;
            }
            var day = new Date(eventDate[0]).getDay();
            var marker = new google.maps.Marker({
                  position: place,
                  map: map,
                  title: event.title,
                  icon: dayIcon[day]
            });

            if (eventDate[0] == lastDate)
                $("#search-container").append( '
     ' + event.title + '
');
            else
                $("#search-container").append( '

' + eventDate[0] + '
     ' + event.title + '
');

            lastDate = eventDate[0];
            add_info_window(map, marker, infowindow, event);

        });
    };

    return {
        makeMap: makeMap,
        calagatorCallback: calagatorCallback,
        update: update
    };

}();
<commit_msg>Make our namespace HotGator and make it lexical<commit_after>var HotGator = function() {

    var mapData;
    var dateLimit = new Date('3000-01-01');

    var dayIcon = [
            'img/sunday.png',
            'img/monday.png',
            'img/tuesday.png',
            'img/wednesday.png',
            'img/thursday.png',
            'img/friday.png',
            'img/saturday.png',
    ];

    function calagatorCallback (data) {
        makeMap(data);
    };

    var calagatorData = function() {
        var ajaxCall = $.getScript("http://calagator.org/events.json?callback=HotGator.calagatorCallback");
    };

    calagatorData();

    var update = function(form) {

        console.log(form);
        var newdate = new Date($("select:first").val());
        if (!newdate) {
            return false;
        }

        dateLimit = newdate;
        console.log(dateLimit);
        calagatorData();
        return false;
    };

    var makeMap = function(mapData) {

        // Cleanup
        $(".eventlink").remove();

        var latlng = new google.maps.LatLng(45.5374054,  -122.65028);

        var myOptions = {
            zoom: 11,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.TERRAIN
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        console.log("made map");

        function correctHeight() {
            var window_height = $(window).height();
            var header_height = $("#search-container").offset().top;
            $("#search-container").height(window_height - header_height - 20); //-20 for padding
            $("#map_canvas").height(window_height - header_height);
        }
        correctHeight();

        jQuery.event.add(window, "resize", correctHeight);
        console.log("made window");

        var infowindow = new google.maps.InfoWindow();

        function getDayIcon(date) {
            var d = new Date(date);
            return (dayIcon[d.getDay()]);
        }

        function add_info_window(map, marker, infowindow, event) {
            var ed = event.start_time.split('T');
            var properDate = ed[0].split('-');
            function open_info_window() {
                infowindow.open(map,marker);
                infowindow.setContent('

' + event.title + '
'
                    + '
'
                    + '
' + properDate[1] + '-' + properDate[2] + '-' + properDate[0]
                    + '
'
                    + ed[1]
                    + '
'
                    + ' '
                    + event.venue.title
                    + '
'
                );
            }
            google.maps.event.addListener(marker, 'click', open_info_window);
            $("#event-" + event.id).click(open_info_window);
        }

        var lastDate = '0000-00-00';
        console.log("About to loop through events with " + dateLimit );

        // Loop through all events
        $.each(mapData, function(index,event){

            if (!event.venue)  {
                return true;
            }
            var place = new google.maps.LatLng(event.venue.latitude, event.venue.longitude);

            // Filter dates of events
            // TODO: add update of the search-container
            var eventDate = event.start_time.split('T');
            var comparedate = new Date(eventDate[0]);
            if (comparedate > dateLimit) {
                console.log("skipping event on day" + eventDate[0]);
                return true;
            }
            var day = new Date(eventDate[0]).getDay();
            var marker = new google.maps.Marker({
                  position: place,
                  map: map,
                  title: event.title,
                  icon: dayIcon[day]
            });

            if (eventDate[0] == lastDate)
                $("#search-container").append( '
     ' + event.title + '
');
            else
                $("#search-container").append( '

' + eventDate[0] + '
     ' + event.title + '
');

            lastDate = eventDate[0];
            add_info_window(map, marker, infowindow, event);

        });
    };

    return {
        makeMap: makeMap,
        calagatorCallback: calagatorCallback,
        update: update
    };

}();
<|endoftext|>


<commit_before>import { expect } from 'chai';
import steps from '../support/asygen';

const { then } = module.exports = steps();

then(/^I should see the total amount of my bill$/, function *() {
  const { By } = this.webdriver;

  const element = yield this.driver.findElement(By.css('.bill-total'));
  const value = yield element.getAttribute('textContent');
  expect(value).to.equal('£130.10');
});

then(/^I should see (\d+) subscriptions$/, async function(amount) {
  const { By } = this.webdriver;

  const elements = await this.driver.findElements(By.css('.subscription > div'));
  expect(elements.length).to.equal(parseInt(amount, 0));
});

then(/^I should see (\d+) (purchases|charges)$/, async function(amount, type) {
  const { By } = this.webdriver;

  const elements = await this.driver.findElements(By.css('.' + type + ' tbody tr'));
  expect(elements.length).to.equal(parseInt(amount, 0));
});
<commit_msg>Fixed multiple await issue<commit_after>import { expect } from 'chai';
import steps from '../support/asygen';

const { then } = module.exports = steps();

then(/^I should see the total amount of my bill$/, async function() {
  const { By } = this.webdriver;

  const element = this.driver.findElement(By.css('.bill-total'));
  const value = await element.getAttribute('textContent');
  expect(value).to.equal('£130.10');
});

then(/^I should see (\d+) subscriptions$/, async function(amount) {
  const { By } = this.webdriver;

  const elements = await this.driver.findElements(By.css('.subscription > div'));
  expect(elements.length).to.equal(parseInt(amount, 0));
});

then(/^I should see (\d+) (purchases|charges)$/, async function(amount, type) {
  const { By } = this.webdriver;

  const elements = await this.driver.findElements(By.css('.' + type + ' tbody tr'));
  expect(elements.length).to.equal(parseInt(amount, 0));
});
<|endoftext|>


<commit_before>/**
 * editor_plugin_src.js
 *
 * Copyright 2010, Ephox * Released under TODO
 *
 * License: TODO
 */

(function() {
	tinymce.create('tinymce.plugins.AutolinkPlugin', {
		/**
		 * Initializes the plugin, this will be executed after the plugin has been created.
		 * This call is done before the editor instance has finished it's initialization so use the onInit event
		 * of the editor instance to intercept that event.
		 *
		 * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
		 * @param {string} url Absolute URL to where the plugin is located.
		 */

		init : function(ed, url) {
			// Add a node change handler
			ed.onKeyUp.add(function(ed, e) {
                switch(e.keyCode) {
                    case 32:  // space character
                        var end = start = ed.selection.getRng().endOffset -1;
                        var endContainer = ed.selection.getRng().endContainer;
                        break;

                    default:
                        return;
                }

                do
                {
                    var r = ed.dom.createRng();
                    r.setStart(endContainer, end - 2);
                    r.setEnd(endContainer, end - 1);
                    ed.selection.setRng(r);
                    end -= 1;
                } while (ed.selection.getContent({format : 'text'}) != ' ' &&
                        ed.selection.getContent({format : 'text'}) != '' && (ed.selection.getRng().startOffset -1) >= 0)

                if (ed.selection.getRng().startOffset == 0) {
                    var r = ed.dom.createRng();
                    r.setStart(endContainer, 0)
                        r.setEnd(endContainer, start);
                    ed.selection.setRng(r);
                }
                else {
                    var r = ed.dom.createRng();
                    r.setStart(endContainer, end);
                    r.setEnd(endContainer, start);
                    ed.selection.setRng(r);
                }

                var text = ed.selection.getContent({format : 'text'});
                var matches = text.match(/^(https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)(.+)$/i);
                if (matches) {
                    tinyMCE.execCommand('mceInsertLink',false, matches[1] + matches[2]);

                    // collapse the selection, moving caret to end of selection
                    ed.selection.collapse(false);
                    ed.selection.select(ed.selection.getNode().nextSibling);
                    ed.selection.collapse(true);
                    tinyMCE.execCommand('mceInsertContent',false, ' ');
                } else {
                    // move the caret to its original position
                    ed.selection.collapse(false);
                    var r = ed.dom.createRng();
                    r.setStart(endContainer, start + 1);
                    r.setEnd(endContainer, start + 1);
                    ed.selection.setRng(r);
                }
            });
		},

		/**
		 * Creates control instances based in the incomming name. This method is normally not
		 * needed since the addButton method of the tinymce.Editor class is a more easy way of adding buttons
		 * but you sometimes need to create more complex controls like listboxes, split buttons etc then this
		 * method can be used to create those.
		 *
		 * @param {String} n Name of the control to create.
		 * @param {tinymce.ControlManager} cm Control manager to use inorder to create new control.
		 * @return {tinymce.ui.Control} New control instance or null if no control was created.
		 */
		createControl : function(n, cm) {
			return null;
		},

		/**
		 * Returns information about the plugin as a name/value array.
		 * The current keys are longname, author, authorurl, infourl and version.
		 *
		 * @return {Object} Name/value array containing information about the plugin.
		 */
		getInfo : function() {
			return {
				longname : 'Autolink plugin',
				author : 'Ephox - Yonas Yanfa',
				authorurl : 'http://www.ephox.com',
				infourl : 'http://www.ephox.com',
				version : "1.0"
			};
		}
	});

	// Register plugin
	tinymce.PluginManager.add('autolink', tinymce.plugins.AutolinkPlugin);
})();<commit_msg>Automatically replace www. with http://www.<commit_after>/**
 * editor_plugin_src.js
 *
 * Copyright 2010, Ephox * Released under TODO
 *
 * License: TODO
 */

(function() {
	tinymce.create('tinymce.plugins.AutolinkPlugin', {
		/**
		 * Initializes the plugin, this will be executed after the plugin has been created.
		 * This call is done before the editor instance has finished it's initialization so use the onInit event
		 * of the editor instance to intercept that event.
		 *
		 * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
		 * @param {string} url Absolute URL to where the plugin is located.
		 */

		init : function(ed, url) {
			// Add a node change handler
			ed.onKeyUp.add(function(ed, e) {
                switch(e.keyCode) {
                    case 32:  // space character
                        var end = start = ed.selection.getRng().endOffset -1;
                        var endContainer = ed.selection.getRng().endContainer;
                        break;

                    default:
                        return;
                }

                do
                {
                    var r = ed.dom.createRng();
                    r.setStart(endContainer, end - 2);
                    r.setEnd(endContainer, end - 1);
                    ed.selection.setRng(r);
                    end -= 1;
                } while (ed.selection.getContent({format : 'text'}) != ' ' &&
                        ed.selection.getContent({format : 'text'}) != '' && (ed.selection.getRng().startOffset -1) >= 0)

                if (ed.selection.getRng().startOffset == 0) {
                    var r = ed.dom.createRng();
                    r.setStart(endContainer, 0)
                        r.setEnd(endContainer, start);
                    ed.selection.setRng(r);
                }
                else {
                    var r = ed.dom.createRng();
                    r.setStart(endContainer, end);
                    r.setEnd(endContainer, start);
                    ed.selection.setRng(r);
                }

                var text = ed.selection.getContent({format : 'text'});
                var matches = text.match(/^(https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)(.+)$/i);
                if (matches) {
                    if (matches[1] == 'www.') {
                        matches[1] = 'http://www.';
                    }
                    tinyMCE.execCommand('mceInsertLink',false, matches[1] + matches[2]);

                    // collapse the selection, moving caret to end of selection
                    ed.selection.collapse(false);
                    ed.selection.select(ed.selection.getNode().nextSibling);
                    ed.selection.collapse(true);
                    tinyMCE.execCommand('mceInsertContent',false, ' ');
                } else {
                    // move the caret to its original position
                    ed.selection.collapse(false);
                    var r = ed.dom.createRng();
                    r.setStart(endContainer, start + 1);
                    r.setEnd(endContainer, start + 1);
                    ed.selection.setRng(r);
                }
            });
		},

		/**
		 * Creates control instances based in the incomming name. This method is normally not
		 * needed since the addButton method of the tinymce.Editor class is a more easy way of adding buttons
		 * but you sometimes need to create more complex controls like listboxes, split buttons etc then this
		 * method can be used to create those.
		 *
		 * @param {String} n Name of the control to create.
		 * @param {tinymce.ControlManager} cm Control manager to use inorder to create new control.
		 * @return {tinymce.ui.Control} New control instance or null if no control was created.
		 */
		createControl : function(n, cm) {
			return null;
		},

		/**
		 * Returns information about the plugin as a name/value array.
		 * The current keys are longname, author, authorurl, infourl and version.
		 *
		 * @return {Object} Name/value array containing information about the plugin.
		 */
		getInfo : function() {
			return {
				longname : 'Autolink plugin',
				author : 'Ephox - Yonas Yanfa',
				authorurl : 'http://www.ephox.com',
				infourl : 'http://www.ephox.com',
				version : "1.0"
			};
		}
	});

	// Register plugin
	tinymce.PluginManager.add('autolink', tinymce.plugins.AutolinkPlugin);
})();<|endoftext|>


<commit_before>function WalkontableVerticalScrollbarNative(instance) {
  this.instance = instance;
  this.type = 'vertical';
  this.cellSize = 23;
  this.init();
  this.clone = this.makeClone('top');
}

WalkontableVerticalScrollbarNative.prototype = new WalkontableOverlay();

//resetFixedPosition (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.resetFixedPosition = function () {
  if (!this.instance.wtTable.holder.parentNode) {
    return; //removed from DOM
  }
  var elem = this.clone.wtTable.holder.parentNode;

  var box;
  if (this.scrollHandler === window) {
    box = this.instance.wtTable.hider.getBoundingClientRect();
    var top = Math.ceil(box.top, 10);
    var bottom = Math.ceil(box.bottom, 10);

    if (top < 0 && bottom > 0) {
      elem.style.top = '0';
    }
    else {
      elem.style.top = top + 'px';
    }
  }
  else {
    box = this.instance.wtScrollbars.horizontal.scrollHandler.getBoundingClientRect();
    elem.style.top = Math.ceil(box.top, 10) + 'px';
    elem.style.left = Math.ceil(box.left, 10) + 'px';
  }

  if (this.instance.wtScrollbars.horizontal.scrollHandler === window) {
    elem.style.width = this.instance.wtViewport.getWorkspaceActualWidth() + 'px';
  }
  else {
    elem.style.width = WalkontableDom.prototype.outerWidth(this.instance.wtTable.holder.parentNode) + 'px';
  }

  elem.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px';
};

//react on movement of the other dimension scrollbar (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.react = function () {
  if (!this.instance.wtTable.holder.parentNode) {
    return; //removed from DOM
  }
  if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) {
    var elem = this.clone.wtTable.holder.parentNode;
    elem.firstChild.style.left = -this.instance.wtScrollbars.horizontal.windowScrollPosition + 'px';
  }
};

WalkontableVerticalScrollbarNative.prototype.getScrollPosition = function () {
  if (this.scrollHandler === window) {
    return this.scrollHandler.scrollY;
  }
  else {
    return this.scrollHandler.scrollTop;
  }
};

WalkontableVerticalScrollbarNative.prototype.setScrollPosition = function (pos) {
  this.scrollHandler.scrollTop = pos;
};

WalkontableVerticalScrollbarNative.prototype.onScroll = function (forcePosition) {
  WalkontableOverlay.prototype.onScroll.apply(this, arguments);

  var scrollDelta;
  var newOffset = 0;

  if (1 == 1 || this.windowScrollPosition > this.tableParentOffset) {
    scrollDelta = this.windowScrollPosition - this.tableParentOffset;

    partialOffset = 0;
    if (scrollDelta > 0) {
      var sum = 0;
      var last;
      for (var i = 0; i < this.total; i++) {
        last = this.instance.getSetting('rowHeight', i);
        sum += last;
        if (sum > scrollDelta) {
          break;
        }
      }

      if (this.offset > 0) {
        partialOffset = (sum - scrollDelta);
      }
      newOffset = i;
      newOffset = Math.min(newOffset, this.total);
    }
  }

  this.curOuts = newOffset > this.maxOuts ? this.maxOuts : newOffset;
  newOffset -= this.curOuts;

  this.instance.update('offsetRow', newOffset);
  this.readSettings(); //read new offset
  this.instance.draw();

  this.instance.getSetting('onScrollVertically');
};

WalkontableVerticalScrollbarNative.prototype.getLastCell = function () {
  return this.instance.getSetting('offsetRow') + this.instance.wtTable.tbodyChildrenLength - 1;
};

var partialOffset = 0;

WalkontableVerticalScrollbarNative.prototype.sumCellSizes = function (from, length) {
  var sum = 0;
  while (from < length) {
    sum += this.instance.getSetting('rowHeight', from);
    from++;
  }
  return sum;
};

//applyToDOM (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.applyToDOM = function () {
  var headerSize = this.instance.wtViewport.getColumnHeaderHeight();
  this.fixedContainer.style.height = headerSize + this.sumCellSizes(0, this.total) + 4 + 'px'; //+4 is needed, otherwise vertical scroll appears in Chrome (window scroll mode) - maybe because of fill handle in last row or because of box shadow
  this.fixed.style.top = this.measureBefore + 'px';
  this.fixed.style.bottom = '';
};

WalkontableVerticalScrollbarNative.prototype.scrollTo = function (cell) {
  var newY = this.tableParentOffset + cell * this.cellSize;
  this.$scrollHandler.scrollTop(newY);
  this.onScroll(newY);
};

//readWindowSize (in future merge it with this.prepare?)
WalkontableVerticalScrollbarNative.prototype.readWindowSize = function () {
  if (this.scrollHandler === window) {
    this.windowSize = document.documentElement.clientHeight;
    this.tableParentOffset = this.instance.wtTable.holderOffset.top;
  }
  else {
    //this.windowSize = WalkontableDom.prototype.outerHeight(this.scrollHandler);
    this.windowSize = this.scrollHandler.clientHeight; //returns height without DIV scrollbar
    this.tableParentOffset = 0;
  }
  this.windowScrollPosition = this.getScrollPosition();
};

//readSettings (in future merge it with this.prepare?)
WalkontableVerticalScrollbarNative.prototype.readSettings = function () {
  this.offset = this.instance.getSetting('offsetRow');
  this.total = this.instance.getSetting('totalRows');
};<commit_msg>Added missing fields initialization in scrollNativeVertical<commit_after>function WalkontableVerticalScrollbarNative(instance) {
  this.instance = instance;
  this.type = 'vertical';
  this.cellSize = 23;
  this.curOuts = this.maxOuts;
  this.init();
  this.clone = this.makeClone('top');
}

WalkontableVerticalScrollbarNative.prototype = new WalkontableOverlay();

WalkontableVerticalScrollbarNative.prototype.init = function () {
  WalkontableOverlay.prototype.init.call(this);
  this.readSettings();
};

//resetFixedPosition (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.resetFixedPosition = function () {
  if (!this.instance.wtTable.holder.parentNode) {
    return; //removed from DOM
  }
  var elem = this.clone.wtTable.holder.parentNode;

  var box;
  if (this.scrollHandler === window) {
    box = this.instance.wtTable.hider.getBoundingClientRect();
    var top = Math.ceil(box.top, 10);
    var bottom = Math.ceil(box.bottom, 10);

    if (top < 0 && bottom > 0) {
      elem.style.top = '0';
    }
    else {
      elem.style.top = top + 'px';
    }
  }
  else {
    box = this.instance.wtScrollbars.horizontal.scrollHandler.getBoundingClientRect();
    elem.style.top = Math.ceil(box.top, 10) + 'px';
    elem.style.left = Math.ceil(box.left, 10) + 'px';
  }

  if (this.instance.wtScrollbars.horizontal.scrollHandler === window) {
    elem.style.width = this.instance.wtViewport.getWorkspaceActualWidth() + 'px';
  }
  else {
    elem.style.width = WalkontableDom.prototype.outerWidth(this.instance.wtTable.holder.parentNode) + 'px';
  }

  elem.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px';
};

//react on movement of the other dimension scrollbar (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.react = function () {
  if (!this.instance.wtTable.holder.parentNode) {
    return; //removed from DOM
  }
  if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) {
    var elem = this.clone.wtTable.holder.parentNode;
    elem.firstChild.style.left = -this.instance.wtScrollbars.horizontal.windowScrollPosition + 'px';
  }
};

WalkontableVerticalScrollbarNative.prototype.getScrollPosition = function () {
  if (this.scrollHandler === window) {
    return this.scrollHandler.scrollY;
  }
  else {
    return this.scrollHandler.scrollTop;
  }
};

WalkontableVerticalScrollbarNative.prototype.setScrollPosition = function (pos) {
  this.scrollHandler.scrollTop = pos;
};

WalkontableVerticalScrollbarNative.prototype.onScroll = function (forcePosition) {
  WalkontableOverlay.prototype.onScroll.apply(this, arguments);

  var scrollDelta;
  var newOffset = 0;

  if (1 == 1 || this.windowScrollPosition > this.tableParentOffset) {
    scrollDelta = this.windowScrollPosition - this.tableParentOffset;

    partialOffset = 0;
    if (scrollDelta > 0) {
      var sum = 0;
      var last;
      for (var i = 0; i < this.total; i++) {
        last = this.instance.getSetting('rowHeight', i);
        sum += last;
        if (sum > scrollDelta) {
          break;
        }
      }

      if (this.offset > 0) {
        partialOffset = (sum - scrollDelta);
      }
      newOffset = i;
      newOffset = Math.min(newOffset, this.total);
    }
  }

  this.curOuts = newOffset > this.maxOuts ? this.maxOuts : newOffset;
  newOffset -= this.curOuts;

  this.instance.update('offsetRow', newOffset);
  this.readSettings(); //read new offset
  this.instance.draw();

  this.instance.getSetting('onScrollVertically');
};

WalkontableVerticalScrollbarNative.prototype.getLastCell = function () {
  return this.instance.getSetting('offsetRow') + this.instance.wtTable.tbodyChildrenLength - 1;
};

var partialOffset = 0;

WalkontableVerticalScrollbarNative.prototype.sumCellSizes = function (from, length) {
  var sum = 0;
  while (from < length) {
    sum += this.instance.getSetting('rowHeight', from);
    from++;
  }
  return sum;
};

//applyToDOM (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.applyToDOM = function () {
  var headerSize = this.instance.wtViewport.getColumnHeaderHeight();
  this.fixedContainer.style.height = headerSize + this.sumCellSizes(0, this.total) + 4 + 'px'; //+4 is needed, otherwise vertical scroll appears in Chrome (window scroll mode) - maybe because of fill handle in last row or because of box shadow
  this.fixed.style.top = this.measureBefore + 'px';
  this.fixed.style.bottom = '';
};

WalkontableVerticalScrollbarNative.prototype.scrollTo = function (cell) {
  var newY = this.tableParentOffset + cell * this.cellSize;
  this.$scrollHandler.scrollTop(newY);
  this.onScroll(newY);
};

//readWindowSize (in future merge it with this.prepare?)
WalkontableVerticalScrollbarNative.prototype.readWindowSize = function () {
  if (this.scrollHandler === window) {
    this.windowSize = document.documentElement.clientHeight;
    this.tableParentOffset = this.instance.wtTable.holderOffset.top;
  }
  else {
    //this.windowSize = WalkontableDom.prototype.outerHeight(this.scrollHandler);
    this.windowSize = this.scrollHandler.clientHeight; //returns height without DIV scrollbar
    this.tableParentOffset = 0;
  }
  this.windowScrollPosition = this.getScrollPosition();
};

//readSettings (in future merge it with this.prepare?)
WalkontableVerticalScrollbarNative.prototype.readSettings = function () {
  this.offset = this.instance.getSetting('offsetRow');
  this.total = this.instance.getSetting('totalRows');
};<|endoftext|>