<commit_before>require("colors");
const semver = require("semver");
const _package = require("./package.json");
const version = _package.engines ? _package.engines.node : "8.0.0";

if (!semver.satisfies(process.version, version)) {
    console.log(
        `warning node-opcua: Required nodejs version ${version} not satisfied with current nodejs version ${
            process.version
        }.`.cyan
    );
}

//---------------------------------------------------------------------------------------------------------------------
// Common
// ---------------------------------------------------------------------------------------------------------------------
module.exports.NodeId = require("node-opcua-nodeid").NodeId;
module.exports.resolveNodeId = require("node-opcua-nodeid").resolveNodeId;
module.exports.makeNodeId = require("node-opcua-nodeid").makeNodeId;
module.exports.coerceNodeId = require("node-opcua-nodeid").coerceNodeId;
module.exports.sameNodeId = require("node-opcua-nodeid").sameNodeId;
module.exports.NodeIdType = require("node-opcua-nodeid").NodeIdType;

module.exports.ExpandedNodeId = require("node-opcua-nodeid/src/expanded_nodeid").ExpandedNodeId;
module.exports.makeExpandedNodeId = require("node-opcua-nodeid/src/expanded_nodeid").makeExpandedNodeId;
module.exports.coerceExpandedNodeId = require("node-opcua-nodeid/src/expanded_nodeid").coerceExpandedNodeId;

module.exports.StatusCodes = require("node-opcua-status-code").StatusCodes;

module.exports.Enum = require("node-opcua-enum");

module.exports.DataType = require("node-opcua-variant").DataType;
module.exports.Variant = require("node-opcua-variant").Variant;
module.exports.VariantArrayType = require("node-opcua-variant").VariantArrayType;
module.exports.buildVariantArray = require("node-opcua-variant").buildVariantArray;

module.exports.DataValue = require("node-opcua-data-value").DataValue;
module.exports.sameDataValue = require("node-opcua-data-value").sameDataValue;

module.exports.NumericRange = require("node-opcua-numeric-range").NumericRange;

module.exports.AccessLevelFlag = require("node-opcua-data-model").AccessLevelFlag;
module.exports.makeAccessLevel = require("node-opcua-data-model").makeAccessLevel;
module.exports.LocalizedText = require("node-opcua-data-model").LocalizedText;
module.exports.coerceLocalizedText = require("node-opcua-data-model").coerceLocalizedText;
module.exports.QualifiedName = require("node-opcua-data-model").QualifiedName;
module.exports.coerceQualifyName = require("node-opcua-data-model").coerceQualifyName;
module.exports.NodeClass = require("node-opcua-data-model").NodeClass;
module.exports.NodeClassMask = require("node-opcua-data-model").NodeClassMask;
module.exports.AttributeIds = require("node-opcua-data-model").AttributeIds;
module.exports.AttributeNameById = require("node-opcua-data-model").AttributeNameById;
module.exports.BrowseDirection = require("node-opcua-data-model").BrowseDirection;

module.exports.VariableTypeIds = require("node-opcua-constants").VariableTypeIds;
module.exports.VariableIds = require("node-opcua-constants").VariableIds;
module.exports.MethodIds = require("node-opcua-constants").MethodIds;
module.exports.ObjectIds = require("node-opcua-constants").ObjectIds;
module.exports.ObjectTypeIds = require("node-opcua-constants").ObjectTypeIds;
module.exports.ReferenceTypeIds = require("node-opcua-constants").ReferenceTypeIds;
module.exports.DataTypeIds = require("node-opcua-constants").DataTypeIds;

// DA
module.exports.standardUnits = require("node-opcua-data-access").standardUnits;
module.exports.makeEUInformation = require("node-opcua-data-access").makeEUInformation;
module.exports.Range = require("node-opcua-data-access").Range;

//
module.exports.get_fully_qualified_domain_name = require("node-opcua-hostname").get_fully_qualified_domain_name;
module.exports.makeApplicationUrn = require("node-opcua-common").makeApplicationUrn;

// services
module.exports.browse_service = require("node-opcua-service-browse");
module.exports.read_service = require("node-opcua-service-read");
module.exports.write_service = require("node-opcua-service-write");
module.exports.call_service = require("node-opcua-service-call");

module.exports.session_service = require("node-opcua-service-session");
module.exports.AnonymousIdentityToken = module.exports.session_service.AnonymousIdentityToken;
module.exports.UserNameIdentityToken = module.exports.session_service.UserNameIdentityToken;

module.exports.register_node_service = require("node-opcua-service-register-node");

module.exports.get_endpoints_service = require("node-opcua-service-endpoints");
module.exports.EndpointDescription = require("node-opcua-service-endpoints").EndpointDescription;
module.exports.ApplicationType = require("node-opcua-service-endpoints").ApplicationType;
module.exports.UserTokenPolicy = require("node-opcua-service-endpoints").UserTokenPolicy;
module.exports.UserIdentityTokenType = require("node-opcua-service-endpoints").UserIdentityTokenType;

module.exports.subscription_service = require("node-opcua-service-subscription");
module.exports.historizing_service = require("node-opcua-service-history");
module.exports.discovery_service = require("node-opcua-service-discovery");
module.exports.secure_channel_service = require("node-opcua-service-secure-channel");

module.exports.translate_browse_paths_to_node_ids_service = require("node-opcua-service-translate-browse-path");
module.exports.BrowsePath = require("node-opcua-service-translate-browse-path").BrowsePath;
module.exports.makeRelativePath = require("node-opcua-service-translate-browse-path").makeRelativePath;
module.exports.makeBrowsePath = require("node-opcua-service-translate-browse-path").makeBrowsePath;

module.exports.query_service = require("node-opcua-service-query");
module.exports.node_managment_service = require("node-opcua-service-node-management");

module.exports.ServerState = require("node-opcua-common").ServerState;
module.exports.ServiceCounter = require("node-opcua-common").ServiceCounter;

module.exports.SecurityPolicy = require("node-opcua-secure-channel").SecurityPolicy;
module.exports.MessageSecurityMode = require("node-opcua-service-secure-channel").MessageSecurityMode;

module.exports.utils = require("node-opcua-utils");
module.exports.crypto_utils = require("node-opcua-crypto");
module.exports.hexDump = require("node-opcua-debug").hexDump;

//----------------------------------------------------------------------------------------------------------------------
// client services
//----------------------------------------------------------------------------------------------------------------------
module.exports.OPCUAClient = require("node-opcua-client").OPCUAClient;
module.exports.OPCUAClientBase = require("node-opcua-client").OPCUAClientBase;

module.exports.NodeCrawler = require("node-opcua-client-crawler").NodeCrawler;
module.exports.ClientSubscription = require("node-opcua-client").ClientSubscription;
module.exports.ClientSession = require("node-opcua-client").ClientSession;

module.exports.client_utils = require("node-opcua-client/src/client_utils");
module.exports.perform_findServers = require("node-opcua-client").perform_findServers;
module.exports.perform_findServersOnNetwork = require("node-opcua-client").perform_findServersOnNetwork;
module.exports.readHistoryServerCapabilities = require("node-opcua-client").readHistoryServerCapabilities;

module.exports.callConditionRefresh = require("node-opcua-client/src/alarms_and_conditions/client_tools").callConditionRefresh;

module.exports.parseEndpointUrl = require("node-opcua-transport").parseEndpointUrl;

//----------------------------------------------------------------------------------------------------------------------
// Server services
//----------------------------------------------------------------------------------------------------------------------
module.exports.OPCUAServer = require("node-opcua-server").OPCUAServer;
module.exports.RegisterServerMethod = require("node-opcua-server").RegisterServerMethod;

module.exports.ServerEngine = require("node-opcua-server").ServerEngine;
module.exports.MonitoredItem = require("node-opcua-server").MonitoredItem;
module.exports.ServerSession = require("node-opcua-server").ServerSession;
module.exports.Subscription = require("node-opcua-server").Subscription;
module.exports.MonitoredItem = require("node-opcua-server").MonitoredItem;

module.exports.generate_address_space = require("node-opcua-address-space").generate_address_space;
module.exports.AddressSpace = require("node-opcua-address-space").AddressSpace;
module.exports.SessionContext = require("node-opcua-address-space").SessionContext;
// basic opcua NodeClass
module.exports.UAObject = require("node-opcua-address-space").UAObject;
module.exports.UAMethod = require("node-opcua-address-space").UAMethod;
module.exports.UAVariable = require("node-opcua-address-space").UAVariable;
module.exports.UADataType = require("node-opcua-address-space").UADataType;

module.exports.getAddressSpaceFixture = require("node-opcua-address-space/test_helpers/get_address_space_fixture").getAddressSpaceFixture;
module.exports.OPCUADiscoveryServer = require("node-opcua-server-discovery").OPCUADiscoveryServer;

module.exports.basic_types = require("node-opcua-basic-types");

// version
module.exports.version = require("./package.json").version;

module.exports.nodesets = require("node-opcua-nodesets");
module.exports.constructNodesetFilename = module.exports.nodesets.constructNodesetFilename;
module.exports.standard_nodeset_file = module.exports.nodesets.standard_nodeset_file;
module.exports.di_nodeset_filename = module.exports.nodesets.di_nodeset_filename;
module.exports.adi_nodeset_filename = module.exports.nodesets.adi_nodeset_filename;

// an incomplete but sufficient nodeset file used during testing
module.exports.mini_nodeset_filename = require("node-opcua-address-space/test_helpers/get_mini_address_space").mini_nodeset_filename;
module.exports.empty_nodeset_filename = require("node-opcua-address-space/test_helpers/get_mini_address_space").empty_nodeset_filename;

module.exports.is_valid_endpointUrl = require("node-opcua-transport").is_valid_endpointUrl;

// filtering tools
module.exports.checkSelectClause = require("node-opcua-address-space").checkSelectClause;
module.exports.constructEventFilter = require("node-opcua-service-filter").constructEventFilter;

const address_space_for_conformance_testing = require("node-opcua-address-space-for-conformance-testing");
module.exports.build_address_space_for_conformance_testing =
    address_space_for_conformance_testing.build_address_space_for_conformance_testing;

module.exports.install_optional_cpu_and_memory_usage_node = require("node-opcua-vendor-diagnostic").install_optional_cpu_and_memory_usage_node;
module.exports.construct_demo_alarm_in_address_space = require("node-opcua-address-space/test_helpers/alarms_and_conditions_demo").construct_demo_alarm_in_address_space;

module.exports.createBoilerType = require("node-opcua-address-space/test_helpers/boiler_system").createBoilerType;
module.exports.makeBoiler = require("node-opcua-address-space/test_helpers/boiler_system").makeBoiler;

module.exports.UAProxyManager = require("node-opcua-client-proxy").UAProxyManager;
<commit_msg>expose Namespace class<commit_after>require("colors");
const semver = require("semver");
const _package = require("./package.json");
const version = _package.engines ? _package.engines.node : "8.0.0";

if (!semver.satisfies(process.version, version)) {
    console.log(
        `warning node-opcua: Required nodejs version ${version} not satisfied with current nodejs version ${
            process.version
        }.`.cyan
    );
}

//---------------------------------------------------------------------------------------------------------------------
// Common
// ---------------------------------------------------------------------------------------------------------------------
module.exports.NodeId = require("node-opcua-nodeid").NodeId;
module.exports.resolveNodeId = require("node-opcua-nodeid").resolveNodeId;
module.exports.makeNodeId = require("node-opcua-nodeid").makeNodeId;
module.exports.coerceNodeId = require("node-opcua-nodeid").coerceNodeId;
module.exports.sameNodeId = require("node-opcua-nodeid").sameNodeId;
module.exports.NodeIdType = require("node-opcua-nodeid").NodeIdType;

module.exports.ExpandedNodeId = require("node-opcua-nodeid/src/expanded_nodeid").ExpandedNodeId;
module.exports.makeExpandedNodeId = require("node-opcua-nodeid/src/expanded_nodeid").makeExpandedNodeId;
module.exports.coerceExpandedNodeId = require("node-opcua-nodeid/src/expanded_nodeid").coerceExpandedNodeId;

module.exports.StatusCodes = require("node-opcua-status-code").StatusCodes;

module.exports.Enum = require("node-opcua-enum");

module.exports.DataType = require("node-opcua-variant").DataType;
module.exports.Variant = require("node-opcua-variant").Variant;
module.exports.VariantArrayType = require("node-opcua-variant").VariantArrayType;
module.exports.buildVariantArray = require("node-opcua-variant").buildVariantArray;

module.exports.DataValue = require("node-opcua-data-value").DataValue;
module.exports.sameDataValue = require("node-opcua-data-value").sameDataValue;

module.exports.NumericRange = require("node-opcua-numeric-range").NumericRange;

module.exports.AccessLevelFlag = require("node-opcua-data-model").AccessLevelFlag;
module.exports.makeAccessLevel = require("node-opcua-data-model").makeAccessLevel;
module.exports.LocalizedText = require("node-opcua-data-model").LocalizedText;
module.exports.coerceLocalizedText = require("node-opcua-data-model").coerceLocalizedText;
module.exports.QualifiedName = require("node-opcua-data-model").QualifiedName;
module.exports.coerceQualifyName = require("node-opcua-data-model").coerceQualifyName;
module.exports.NodeClass = require("node-opcua-data-model").NodeClass;
module.exports.NodeClassMask = require("node-opcua-data-model").NodeClassMask;
module.exports.AttributeIds = require("node-opcua-data-model").AttributeIds;
module.exports.AttributeNameById = require("node-opcua-data-model").AttributeNameById;
module.exports.BrowseDirection = require("node-opcua-data-model").BrowseDirection;

module.exports.VariableTypeIds = require("node-opcua-constants").VariableTypeIds;
module.exports.VariableIds = require("node-opcua-constants").VariableIds;
module.exports.MethodIds = require("node-opcua-constants").MethodIds;
module.exports.ObjectIds = require("node-opcua-constants").ObjectIds;
module.exports.ObjectTypeIds = require("node-opcua-constants").ObjectTypeIds;
module.exports.ReferenceTypeIds = require("node-opcua-constants").ReferenceTypeIds;
module.exports.DataTypeIds = require("node-opcua-constants").DataTypeIds;

// DA
module.exports.standardUnits = require("node-opcua-data-access").standardUnits;
module.exports.makeEUInformation = require("node-opcua-data-access").makeEUInformation;
module.exports.Range = require("node-opcua-data-access").Range;

//
module.exports.get_fully_qualified_domain_name = require("node-opcua-hostname").get_fully_qualified_domain_name;
module.exports.makeApplicationUrn = require("node-opcua-common").makeApplicationUrn;

// services
module.exports.browse_service = require("node-opcua-service-browse");
module.exports.read_service = require("node-opcua-service-read");
module.exports.write_service = require("node-opcua-service-write");
module.exports.call_service = require("node-opcua-service-call");

module.exports.session_service = require("node-opcua-service-session");
module.exports.AnonymousIdentityToken = module.exports.session_service.AnonymousIdentityToken;
module.exports.UserNameIdentityToken = module.exports.session_service.UserNameIdentityToken;

module.exports.register_node_service = require("node-opcua-service-register-node");

module.exports.get_endpoints_service = require("node-opcua-service-endpoints");
module.exports.EndpointDescription = require("node-opcua-service-endpoints").EndpointDescription;
module.exports.ApplicationType = require("node-opcua-service-endpoints").ApplicationType;
module.exports.UserTokenPolicy = require("node-opcua-service-endpoints").UserTokenPolicy;
module.exports.UserIdentityTokenType = require("node-opcua-service-endpoints").UserIdentityTokenType;

module.exports.subscription_service = require("node-opcua-service-subscription");
module.exports.historizing_service = require("node-opcua-service-history");
module.exports.discovery_service = require("node-opcua-service-discovery");
module.exports.secure_channel_service = require("node-opcua-service-secure-channel");

module.exports.translate_browse_paths_to_node_ids_service = require("node-opcua-service-translate-browse-path");
module.exports.BrowsePath = require("node-opcua-service-translate-browse-path").BrowsePath;
module.exports.makeRelativePath = require("node-opcua-service-translate-browse-path").makeRelativePath;
module.exports.makeBrowsePath = require("node-opcua-service-translate-browse-path").makeBrowsePath;

module.exports.query_service = require("node-opcua-service-query");
module.exports.node_managment_service = require("node-opcua-service-node-management");

module.exports.ServerState = require("node-opcua-common").ServerState;
module.exports.ServiceCounter = require("node-opcua-common").ServiceCounter;

module.exports.SecurityPolicy = require("node-opcua-secure-channel").SecurityPolicy;
module.exports.MessageSecurityMode = require("node-opcua-service-secure-channel").MessageSecurityMode;

module.exports.utils = require("node-opcua-utils");
module.exports.crypto_utils = require("node-opcua-crypto");
module.exports.hexDump = require("node-opcua-debug").hexDump;

//----------------------------------------------------------------------------------------------------------------------
// client services
//----------------------------------------------------------------------------------------------------------------------
module.exports.OPCUAClient = require("node-opcua-client").OPCUAClient;
module.exports.OPCUAClientBase = require("node-opcua-client").OPCUAClientBase;

module.exports.NodeCrawler = require("node-opcua-client-crawler").NodeCrawler;
module.exports.ClientSubscription = require("node-opcua-client").ClientSubscription;
module.exports.ClientSession = require("node-opcua-client").ClientSession;

module.exports.client_utils = require("node-opcua-client/src/client_utils");
module.exports.perform_findServers = require("node-opcua-client").perform_findServers;
module.exports.perform_findServersOnNetwork = require("node-opcua-client").perform_findServersOnNetwork;
module.exports.readHistoryServerCapabilities = require("node-opcua-client").readHistoryServerCapabilities;

module.exports.callConditionRefresh = require("node-opcua-client/src/alarms_and_conditions/client_tools").callConditionRefresh;

module.exports.parseEndpointUrl = require("node-opcua-transport").parseEndpointUrl;

//----------------------------------------------------------------------------------------------------------------------
// Server services
//----------------------------------------------------------------------------------------------------------------------
module.exports.OPCUAServer = require("node-opcua-server").OPCUAServer;
module.exports.RegisterServerMethod = require("node-opcua-server").RegisterServerMethod;

module.exports.ServerEngine = require("node-opcua-server").ServerEngine;
module.exports.MonitoredItem = require("node-opcua-server").MonitoredItem;
module.exports.ServerSession = require("node-opcua-server").ServerSession;
module.exports.Subscription = require("node-opcua-server").Subscription;
module.exports.MonitoredItem = require("node-opcua-server").MonitoredItem;

module.exports.generate_address_space = require("node-opcua-address-space").generate_address_space;
module.exports.AddressSpace = require("node-opcua-address-space").AddressSpace;
module.exports.Namespace = require("node-opcua-address-space").Namespace;

module.exports.SessionContext = require("node-opcua-address-space").SessionContext;
// basic opcua NodeClass
module.exports.UAObject = require("node-opcua-address-space").UAObject;
module.exports.UAMethod = require("node-opcua-address-space").UAMethod;
module.exports.UAVariable = require("node-opcua-address-space").UAVariable;
module.exports.UADataType = require("node-opcua-address-space").UADataType;

module.exports.getAddressSpaceFixture = require("node-opcua-address-space/test_helpers/get_address_space_fixture").getAddressSpaceFixture;
module.exports.OPCUADiscoveryServer = require("node-opcua-server-discovery").OPCUADiscoveryServer;

module.exports.basic_types = require("node-opcua-basic-types");

// version
module.exports.version = require("./package.json").version;

module.exports.nodesets = require("node-opcua-nodesets");
module.exports.constructNodesetFilename = module.exports.nodesets.constructNodesetFilename;
module.exports.standard_nodeset_file = module.exports.nodesets.standard_nodeset_file;
module.exports.di_nodeset_filename = module.exports.nodesets.di_nodeset_filename;
module.exports.adi_nodeset_filename = module.exports.nodesets.adi_nodeset_filename;

// an incomplete but sufficient nodeset file used during testing
module.exports.mini_nodeset_filename = require("node-opcua-address-space/test_helpers/get_mini_address_space").mini_nodeset_filename;
module.exports.empty_nodeset_filename = require("node-opcua-address-space/test_helpers/get_mini_address_space").empty_nodeset_filename;

module.exports.is_valid_endpointUrl = require("node-opcua-transport").is_valid_endpointUrl;

// filtering tools
module.exports.checkSelectClause = require("node-opcua-address-space").checkSelectClause;
module.exports.constructEventFilter = require("node-opcua-service-filter").constructEventFilter;

const address_space_for_conformance_testing = require("node-opcua-address-space-for-conformance-testing");
module.exports.build_address_space_for_conformance_testing =
    address_space_for_conformance_testing.build_address_space_for_conformance_testing;

module.exports.install_optional_cpu_and_memory_usage_node = require("node-opcua-vendor-diagnostic").install_optional_cpu_and_memory_usage_node;
module.exports.construct_demo_alarm_in_address_space = require("node-opcua-address-space/test_helpers/alarms_and_conditions_demo").construct_demo_alarm_in_address_space;

module.exports.createBoilerType = require("node-opcua-address-space/test_helpers/boiler_system").createBoilerType;
module.exports.makeBoiler = require("node-opcua-address-space/test_helpers/boiler_system").makeBoiler;

module.exports.UAProxyManager = require("node-opcua-client-proxy").UAProxyManager;
<|endoftext|>


<commit_before>var data = {'args':null,'targets':null,"bucket_id":"","key_id":"","secret_key":""};
var ready = false;

var params = ["bucket_id","key_id","secret_key"];

function file_read(form){
    var reader = new FileReader();
    var set_onload = function(f){
	reader.onload = function(e) {
	    console.log('done with',f);
	    data[f] = e.target.result;
	    document.getElementById(f+'_status').innerHTML='Ready!';
	};
	console.log('set onload',f);
    };
    set_onload(form);
    document.getElementById(form+'_status').innerHTML='Loading...';
    reader.readAsDataURL(document.getElementById(form).files[0]);
}

function serialise(data){
    ans = "";
    payload = "";
    for(var x in data){
	ans += x + ":" + data[x].length + ";";
	payload += data[x]
    }
    ans = ans.slice(0,-1)+"\n"+payload;
    return ans;
}

function submit_form(){
    if(data['args'] == null){
	alert('Please select an arguments file.');
	return;
    }
    for(var i = 0; i < params.length; i++){
	data[params[i]] = document.getElementById(params[i]).value;
    }
    if(data['targets'] != null){
	for(var i = 0; i < params.length; i++){
	    if(data[params[i]].length == 0){
		alert("Please enter "+params[i]);
		return;
	    }
	}
    }
    console.log(data);
    var XHR = new XMLHttpRequest();
    XHR.addEventListener("load", function(event) {
	console.log("DID IT",event.target.responseText);
	ret = JSON.parse(event.target.responseText);
	if(ret.success){
	    document.getElementById('exp_status').innerHTML = "Success!
Experiment dashboard
Experiment query page";
	}
	else{
	    document.getElementById('exp_status').innerHTML = "There was an error:

"+ret.message+"
";
	    document.getElementById('initExp').disabled = false;
	}
    });
    XHR.addEventListener("error", function(event) {
	document.getElementById('exp_status').innerHTML = "There was an unknown network error:";
	document.getElementById('initExp').disabled = false;
    });
    XHR.open("POST", target);
    XHR.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    document.getElementById('initExp').disabled = true;
    document.getElementById('exp_status').innerHTML = "Attempting to Launch...";
    XHR.send(serialise(data));
    return false;
}
<commit_msg>file upload<commit_after>var data = {'args':null,'targets':null,"bucket_id":"","key_id":"","secret_key":""};
var ready = false;

var params = ["bucket_id","key_id","secret_key"];

function file_read(form){
    var reader = new FileReader();
    var set_onload = function(f){
	reader.onload = function(e) {
	    console.log('done with',f);
	    data[f] = e.target.result;
	    document.getElementById(f+'_status').innerHTML='Ready!';
	};
	console.log('set onload',f);
    };
    set_onload(form);
    document.getElementById(form+'_status').innerHTML='Loading...';
    reader.readAsDataURL(document.getElementById(form).files[0]);
}

function serialise(data){
    ans = "";
    payload = "";
    for(var x in data){
	ans += x + ":" + data[x].length + ";";
	payload += data[x]
    }
    ans = ans.slice(0,-1)+"\n"+payload;
    return ans;
}

function submit_form(){
    if(data['args'] == null){
	alert('Please select an arguments file.');
	return;
    }
    for(var i = 0; i < params.length; i++){
	data[params[i]] = document.getElementById(params[i]).value;
    }
    if(data['targets'] != null){
	for(var i = 0; i < params.length; i++){
	    if(data[params[i]].length == 0){
		alert("Please enter "+params[i]);
		return;
	    }
	}
    }
    console.log(data);
    var XHR = new XMLHttpRequest();
    XHR.addEventListener("load", function(event) {
	console.log("DID IT",event.target.responseText);
	ret = JSON.parse(event.target.responseText);
	if(ret.success){
	    document.getElementById('exp_status').innerHTML = "Success!
Experiment dashboard
Experiment query page";
	}
	else{
	    document.getElementById('exp_status').innerHTML = "There was an error:

"+ret.message+"
";
	    document.getElementById('initExp').disabled = false;
	}
    });
    XHR.addEventListener("error", function(event) {
	document.getElementById('exp_status').innerHTML = "There was an unknown network error:";
	document.getElementById('initExp').disabled = false;
    });
    XHR.open("POST", target);
    XHR.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    document.getElementById('initExp').disabled = true;
    document.getElementById('exp_status').innerHTML = "Attempting to Launch...";
    XHR.send(serialise(data));
    return false;
}
<|endoftext|>


<commit_before>function plotSunburst(container, data, config) {

	var defaults = {
    breadcrumb: {w: 75, h: 30, s: 3, t: 10},
		color: d3.scaleOrdinal(d3.schemeCategory20c),
    legend_entry: {w: 75, h: 30, s: 3, r: 3},
		margin: {top: 20, right: 20, bottom: 20, left: 20},
    size_accessor: function (d) {return d.size;}
	};
	config = $.extend({}, defaults, config);

  // redraw whole histogram instead of updating it
  container.select("svg").remove();

  // setup svg image with padding and margins
  var width = container.node().getBoundingClientRect().width;
  var height = container.node().getBoundingClientRect().height;
  var innerWidth = width - config.margin.left - config.margin.right;
  var innerHeight = height - config.margin.top - config.margin.bottom;
  var radius = Math.min(innerWidth, innerHeight) / 2;

  var svg = container.append("svg")
  .attr("width", width)
  .attr("height", height);

  var canvas = svg.append("g")
  .attr("transform", "translate(" + config.margin.left + "," + config.margin.top + ")")
  .append("g")
  .attr("transform", "translate(" + innerWidth / 2 + "," + innerHeight / 2 + ")");

  container.on("mouseleave", mouseleave);

  // generate partition of data
  var partition = d3.partition()
  .size([2 * Math.PI, radius * radius]);

  // generate hierarchy
  var root = d3.hierarchy(data)
    .sum(config.size_accessor)
    .sort(function(a, b) { return b.value - a.value; });

  // get nodes with visible contribution
  var nodes = partition(root).descendants()
    .filter(function(d) {
      return (d.x1 - d.x0 > 0.005); // 0.005 radians = 0.29 degrees
    });

  // set domain for color scale to unique names in tree
  var uniqueNames = (function(graph) {
    var output = [];
    graph.forEach(function(node) {
      if (output.indexOf(node.data.name) === -1) {
        output.push(node.data.name);
      }
    });
    return output;
  })(nodes);

  config.color.domain(uniqueNames);

  // define generic template for circle segment
  var arc = d3.arc()
  .startAngle(function(d) { return d.x0; })
  .endAngle(function(d) { return d.x1; })
  .innerRadius(function(d) { return Math.sqrt(d.y0); })
  .outerRadius(function(d) { return Math.sqrt(d.y1); });

  // draw sunburst plot
  var path = canvas.selectAll("path")
  .data(nodes)
  .enter().append("path")
    .attr("display", function(d) { return d.depth ? null : "none"; }) // hide inner ring
    .attr("d", arc)
    .style("stroke", "#fff")
    .style("fill", function(d) {return config.color(d.data.name); })
    .on("mouseover", mouseover);

  // get total size of the tree = value of root node from partition.
  totalSize = path.datum().value;

  // add legend
  var legend = canvas.append("g")
    .attr("transform", "translate(" + (-innerWidth/2) + "," + (-innerHeight/2 + config.breadcrumb.h) + ")");
      //.attr("height", d3.keys(colors).length * (li.h + li.s));

  // draw legend entries
  var entries = legend.selectAll("g")
    .data(uniqueNames.slice(1,uniqueNames.length))
    .enter()
      .append("g")
        .attr("transform", function(d, i) {return "translate(0," + i * (config.legend_entry.h + config.legend_entry.s) + ")";});

  entries.append("rect")
    .attr("rx", config.legend_entry.r)
    .attr("ry", config.legend_entry.r)
    .attr("width", config.legend_entry.w)
    .attr("height", config.legend_entry.h)
    .style("fill", function(d) { return config.color(d); });

  entries.append("text")
    .attr("x", config.legend_entry.w / 2)
    .attr("y", config.legend_entry.h / 2)
    .attr("dy", "0.35em")
    .attr("text-anchor", "middle")
    .text(function(d) { return d; });

  // initialize breadcrump trail
  var trail = svg.append("svg")
    .attr("width", innerWidth)
    .attr("height", 50)
    .attr("id", "trail");

  trail.append("text")
    .attr("id", "endlabel");

  canvas.append("text")
    .attr("id","percentage")
    .attr("text-anchor", "middle");

  // fade all but the current sequence, and show it in the breadcrumb trail
  function mouseover(d) {
    var percentage = (100 * d.value / totalSize).toPrecision(3);
    var percentageString = percentage + "%";
    if (percentage < 0.1) {
      percentageString = "< 0.1%";
    }

    d3.select("#percentage")
    .text(percentageString)
    .style("visibility","");

    var sequenceArray = d.ancestors().reverse();
    sequenceArray.shift(); // remove root node from the array
    updateBreadcrumbs(sequenceArray, percentageString);

    // fade all the segments
    d3.selectAll("path").style("opacity", 0.3);

    // then highlight only those that are an ancestor of the current segment.
    canvas.selectAll("path")
    .filter(function(node) {return (sequenceArray.indexOf(node) >= 0);})
    .style("opacity", 1);
  }

  // restore everything to full opacity when moving off the visualization.
  function mouseleave(d) {
    // hide the breadcrumb trail
    d3.select("#trail").style("visibility", "hidden");

    // deactivate all segments during transition.
    d3.selectAll("path").on("mouseover", null);

    // transition each segment to full opacity and then reactivate it.
    d3.selectAll("path")
    .transition()
    .duration(500)
    .style("opacity", 1)
    .on("end", function() {d3.select(this).on("mouseover", mouseover);});

    d3.select("#percentage").style("visibility","hidden");
  }

  // update the breadcrumb trail to show the current sequence and percentage.
  function updateBreadcrumbs(nodeArray, percentageString) {
    // data join; key function combines name and depth (= position in sequence).
    var trail = d3.select("#trail")
    .selectAll("g")
    .data(nodeArray, function(d) { return d.data.name + d.depth; });

    // remove exiting nodes.
    trail.exit().remove();

    // ddd breadcrumb and label for entering nodes.
    var entering = trail.enter().append("g");
    entering.append("polygon")
    .attr("points", breadcrumbPoints)
    .style("fill", function(d) { return config.color(d.data.name); });

    entering.append("text")
    .attr("x", (config.breadcrumb.w + config.breadcrumb.t) / 2)
    .attr("y", config.breadcrumb.h / 2)
    .attr("dy", "0.35em")
    .attr("text-anchor", "middle")
    .text(function(d) { return d.data.name; });

    // merge enter and update selections; set position for all nodes.
    entering.merge(trail).attr("transform", function(d, i) {return "translate(" + i * (config.breadcrumb.w + config.breadcrumb.s) + ", 0)";});

  // now move and update the percentage at the end.
  d3.select("#trail").select("#endlabel")
  .attr("x", (nodeArray.length + 0.5) * (config.breadcrumb.w + config.breadcrumb.s))
  .attr("y", config.breadcrumb.h / 2)
  .attr("dy", "0.35em")
  .attr("text-anchor", "middle")
  .text(percentageString);

  // Make the breadcrumb trail visible, if it's hidden.
  d3.select("#trail")
  .style("visibility", "");
  }

  // generate a string that describes the points of a breadcrumb polygon.
  function breadcrumbPoints(d, i) {
    var points = [];
    points.push("0,0");
    points.push(config.breadcrumb.w + ",0");
    points.push(config.breadcrumb.w + config.breadcrumb.t + "," + (config.breadcrumb.h / 2));
    points.push(config.breadcrumb.w + "," + config.breadcrumb.h);
    points.push("0," + config.breadcrumb.h);

    // leftmost breadcrumb -> don't include 6th vertex.
    if (i > 0) {
      points.push(config.breadcrumb.t + "," + (config.breadcrumb.h / 2));
    }

    return points.join(" ");
  }
}
<commit_msg>add documentation and fix indentation<commit_after>/**
* Helper function for visualising a sunburst plot as SVG using d3js
*
* @param {Object}   container - D3 selection to HTML object acting as container of the svg
* @param {Float[]}  data      - array with tree information
* @param {Object}   [config]  - configuration object (optional)
* @param {Int}      [config.breadcrumb]   - definition of polygon for breadcrumb (optional)
* @param {Object}   [config.color]        - D3 scale object for color coding (optional)
* @param {Callback} [config.cutoff]       - minimum relative contribution for a contribution to be shown (optional)
* @param {d3.scale} [config.legend_entry] - definition of polygon for legend entry (optional)
* @param {String}   [config.margin]       - specification of top/bottom/right/left margins (optional)
*
* This function requires the d3.js library and jQuery to be loaded.
*
* This function takes a data object describing a tree structure. The data object
* must have the following layout:
*
* var data = {
*  name: "root",
*  children: [{
*    name: "A",
*    children: [...],
*    size: 3
*   },{
*    name: "B",
*    children: [...],
*    size: 5
*   }
*   ...
*  ],
*  size: 0
* };
*
* The size for each node should describe the size of this specific node NOT
* including the contributions from child nodes. The function then plots the data
* as a sunburst diagram in a SVG inside the given HTML object/container. If the
* container contains a SVG element, it is overwritten and replaced by the
* sunburst SVG. The config object allows to customize the appearance and
* behaviour of the plot.
* The margin object must have bottom/top/left/right attributes specifying the
* individual margins. The color object should be a pre-configured d3 ordinal
* scale object. The domain is overwritten by the function to match the list of
* unique node names.
*
* The SVG elements can be styled using CSS. To this end, the following class
* tags are assigned:
* - The paths representing the sunburst nodes are classed as 'sunburst-node'.
* - Group objects representing the legend entries are classed as 'legend-entry'.
* - The text at the tip of the breadcrumb trail has the id 'endlabel'.
* - The text in the middle of the plot showing the relative percentage has the
*   id 'percentage'.
*/
function plotSunburst(container, data, config) {

  // define some default settings
  var defaults = {
    breadcrumb: {w: 75, h: 30, s: 3, t: 10},
    color: d3.scaleOrdinal(d3.schemeCategory20c),
    cutoff: 0.005,
    legend_entry: {w: 75, h: 30, s: 3, r: 3},
    margin: {top: 20, right: 20, bottom: 20, left: 20}
  };

  // augment user-defined input with default settings
  config = $.extend({}, defaults, config);

  // redraw whole histogram instead of updating it
  container.select("svg").remove();

  // restore back to standard layout
  container.on("mouseleave", mouseleave);

  // setup svg image with padding and margins
  var width = container.node().getBoundingClientRect().width;
  var height = container.node().getBoundingClientRect().height;
  var innerWidth = width - config.margin.left - config.margin.right;
  var innerHeight = height - config.margin.top - config.margin.bottom;
  var radius = Math.min(innerWidth, innerHeight) / 2;

  var svg = container.append("svg")
  .attr("width", width)
  .attr("height", height);

  var canvas = svg.append("g")
  .attr("transform", "translate(" + config.margin.left + "," + config.margin.top + ")")
  .append("g")
  .attr("transform", "translate(" + innerWidth / 2 + "," + innerHeight / 2 + ")");

  // setup partitioning of data
  var partition = d3.partition()
  .size([2 * Math.PI, radius * radius]);

  // generate hierarchy
  var root = d3.hierarchy(data)
  .sum(function (d) {return d.size;})
  .sort(function(a, b) { return b.value - a.value; });

  // get only nodes with visible contribution
  var nodes = partition(root).descendants()
    .filter(function(d) {
      return (d.x1 - d.x0 > config.cutoff);
    });

  // set domain for color scale to unique names in tree
  var uniqueNames = (function(graph) {
    var output = [];
    graph.forEach(function(node) {
      if (output.indexOf(node.data.name) === -1) {
        output.push(node.data.name);
      }
    });
    return output;
  })(nodes);

  config.color.domain(uniqueNames);

  // define generic template for circle segment
  var arc = d3.arc()
  .startAngle(function(d) { return d.x0; })
  .endAngle(function(d) { return d.x1; })
  .innerRadius(function(d) { return Math.sqrt(d.y0); })
  .outerRadius(function(d) { return Math.sqrt(d.y1); });

  // draw sunburst plot
  var path = canvas.selectAll("path")
  .data(nodes)
  .enter().append("path")
  .attr("display", function(d) { return d.depth ? null : "none"; }) // hide inner ring
  .attr("d", arc)
  .classed("sunburst-node", true)
  .style("stroke", "#fff")
  .style("fill", function(d) {return config.color(d.data.name); })
  .on("mouseover", mouseover);

  // get total size of the tree = value of root node from partition.
  totalSize = path.datum().value;

  // add legend
  var legend = canvas.append("g")
  .attr("transform", "translate(" + (-innerWidth/2) + "," + (-innerHeight/2 + config.breadcrumb.h) + ")");

  // draw legend entries
  var entries = legend.selectAll("g")
  .data(uniqueNames.slice(1,uniqueNames.length))
  .enter()
  .append("g")
  .attr("transform", function(d, i) {return "translate(0," + i * (config.legend_entry.h + config.legend_entry.s) + ")";})
  .classed("legend-entry", true);

  entries.append("rect")
  .attr("rx", config.legend_entry.r)
  .attr("ry", config.legend_entry.r)
  .attr("width", config.legend_entry.w)
  .attr("height", config.legend_entry.h)
  .style("fill", function(d) { return config.color(d); });

  entries.append("text")
  .attr("x", config.legend_entry.w / 2)
  .attr("y", config.legend_entry.h / 2)
  .attr("dy", "0.35em")
  .attr("text-anchor", "middle")
  .text(function(d) { return d; });

  // initialize breadcrump trail
  var trail = svg.append("svg")
  .attr("width", innerWidth)
  .attr("height", 50)
  .attr("id", "trail");

  trail
  .append("text")
  .attr("id", "endlabel");

  canvas
  .append("text")
  .attr("id","percentage")
  .attr("text-anchor", "middle");

  // fade all but the current sequence, and show it in the breadcrumb trail
  function mouseover(d) {
    var percentage = (100 * d.value / totalSize).toPrecision(3);
    var percentageString = percentage + "%";
    if (percentage < 0.1) {
      percentageString = "< 0.1%";
    }

    d3.select("#percentage")
    .text(percentageString)
    .style("visibility","");

    var sequenceArray = d.ancestors().reverse();
    sequenceArray.shift(); // remove root node from the array
    updateBreadcrumbs(sequenceArray, percentageString);

    // fade all the segments
    d3.selectAll("path").style("opacity", 0.3);

    // then highlight only those that are an ancestor of the current segment.
    canvas.selectAll("path")
    .filter(function(node) {return (sequenceArray.indexOf(node) >= 0);})
    .style("opacity", 1);
  }

  // restore everything to full opacity when moving off the visualization.
  function mouseleave(d) {
    // hide the breadcrumb trail
    d3.select("#trail").style("visibility", "hidden");

    // deactivate all segments during transition.
    d3.selectAll("path").on("mouseover", null);

    // transition each segment to full opacity and then reactivate it.
    d3.selectAll("path")
    .transition()
    .duration(500)
    .style("opacity", 1)
    .on("end", function() {d3.select(this).on("mouseover", mouseover);});

    d3.select("#percentage").style("visibility","hidden");
  }

  // update the breadcrumb trail to show the current sequence and percentage.
  function updateBreadcrumbs(nodeArray, percentageString) {
    // data join; key function combines name and depth (= position in sequence).
    var trail = d3.select("#trail")
    .selectAll("g")
    .data(nodeArray, function(d) { return d.data.name + d.depth; });

    // remove exiting nodes.
    trail.exit().remove();

    // ddd breadcrumb and label for entering nodes.
    var entering = trail.enter().append("g");
    entering.append("polygon")
    .attr("points", breadcrumbPoints)
    .style("fill", function(d) { return config.color(d.data.name); });

    entering.append("text")
    .attr("x", (config.breadcrumb.w + config.breadcrumb.t) / 2)
    .attr("y", config.breadcrumb.h / 2)
    .attr("dy", "0.35em")
    .attr("text-anchor", "middle")
    .text(function(d) { return d.data.name; });

    // merge enter and update selections; set position for all nodes.
    entering.merge(trail).attr("transform", function(d, i) {return "translate(" + i * (config.breadcrumb.w + config.breadcrumb.s) + ", 0)";});

    // now move and update the percentage at the end.
    d3.select("#trail").select("#endlabel")
    .attr("x", (nodeArray.length + 0.5) * (config.breadcrumb.w + config.breadcrumb.s))
    .attr("y", config.breadcrumb.h / 2)
    .attr("dy", "0.35em")
    .attr("text-anchor", "middle")
    .text(percentageString);

    // Make the breadcrumb trail visible, if it's hidden.
    d3.select("#trail").style("visibility", "");
  }

  // generate a string that describes the points of a breadcrumb polygon.
  function breadcrumbPoints(d, i) {
    var points = [];
    points.push("0,0");
    points.push(config.breadcrumb.w + ",0");
    points.push(config.breadcrumb.w + config.breadcrumb.t + "," + (config.breadcrumb.h / 2));
    points.push(config.breadcrumb.w + "," + config.breadcrumb.h);
    points.push("0," + config.breadcrumb.h);

    // leftmost breadcrumb -> don't include 6th vertex.
    if (i > 0) {
      points.push(config.breadcrumb.t + "," + (config.breadcrumb.h / 2));
    }

    return points.join(" ");
  }
}
<|endoftext|>


<commit_before>function add(data, index, operation, addedProccesstegs) {

  var addedProccesstegs = addedProccesstegs;

  if ( !(data === undefined) ) {

    var underrubrikName = $(data).find('#underrubrik-name').val();
    var underrubrikText = $(data).find('#underrubrik-text').val();
    var processteg = $(data).find('.select-processteg').val();

    if (!(processteg in addedProccesstegs)) {
      $.ajax({
        type: 'POST',
        url: '/api/processtegs',
        data: {
          title: processteg,
          operation: operation,
          template : true
        }
      })
        .done(function (msg) {
          console.log(msg);
          addedProccesstegs[processteg] = [true, msg._id];
          $.ajax({
            type: 'POST',
            url: '/api/processinnehalls',
            data: {
              order: 0,
              title: underrubrikName,
              text: underrubrikText,
              process: msg._id
            }
          })
            .done(function (msg) {
              console.log(msg);
              $(function () {
                add($('#underrubriker').children()[index + 1], index + 1, operation, addedProccesstegs);
              });
            })
            .fail(function (err, status) {
              console.log('Någonting gick fel!');
              console.log(err);
              console.log(status);
            });
        })
        .fail(function (err, status) {
          console.log('Någonting gick fel!');
          console.log(err);
          console.log(status);
        });
    }
    else{
      $.ajax({
        type: 'POST',
        url: '/api/processinnehalls',
        data: {
          order: 0,
          title: underrubrikName,
          text: underrubrikText,
          process: addedProccesstegs[processteg][1]
        }
      })
        .done(function (msg) {
          console.log(msg);
          $(function () {
            add($('#underrubriker').children()[index + 1], index + 1, operation, addedProccesstegs);
          });
        })
        .fail(function (err, status) {
          console.log('Någonting gick fel!');
          console.log(err);
          console.log(status);
        });
    }
  }
  else{
    console.log("handbok skapad");
    alert("handbok skapad");
  }
}

var createNewOperation = function() {
  var tags = $('#tags_1').val();
  var specialty = $(".specialitet-select").val();
  var operationName = $('#operation-name').val();

  console.log(specialty);
  if (specialty == 'Specialitet') {
    console.log('Fix Error here');
    alert("välj specialitet!")
  }
  else
  {
    $.ajax({
      type: 'POST',
      url: '/api/operations',
      data: {
        title: operationName,
        tags: tags,
        specialty: specialty,
        template: true
      }
    })
      .done(function (msg) {
        console.log(msg);
        //adding articles here
        $('.article').each(function (index) {
          var name = $(this).text();
          var kartotek = $(this).attr("data-kartotekID");
          var operation = msg._id;
          var amount = $('#articles').find('#top'+kartotek).text();
          $.ajax({
            type: 'POST',
            url: '/api/artikels',
            data: {
              name: name,
              kartotek: kartotek,
              operation: operation,
              amount : amount
            }
          })
            .done(function (msg) {
              console.log(msg); //Contains the created Article-model
            })
            .fail(function (err, status) {
              console.log('Någonting gick fel!');
              console.log(err);
              console.log(status);
            });
        });
        //adding underrubrik/processteg(recursive)
        $(function() {
          var index = 0;
          add($('#underrubriker').children()[index], index, msg._id, {});
        });
      })
      .fail(function (err, status) {
        console.log('Någonting gick fel!');
        console.log(err);
        console.log(status);
      });
  };
};

var removeArticle = function(element) {
  var parent = $(element).parent();
  $(parent).remove();
};

var addArticle = function(articleTemplate, results) {
  var name = $(this).data('name');
  var kartotekID = $(this).data('kartotekid');
  var found = false;

  $('.article').each(function(index) {
    if($(this).attr("data-kartotekID") == kartotekID) {
      found = true;
      }
  });

  if (!found) {
    var newArticle = $(articleTemplate({ name: name, id: kartotekID })).appendTo('#articles');
    newArticle.find('.col-right').click(function() {
      removeArticle(this);
    });
    $("#plus"+kartotekID).click(function() {
      $("#top"+kartotekID).html(parseInt($("#top"+kartotekID).html()) + 1);
    });
    $("#minus"+kartotekID).click(function() {
      if (parseInt($("#top"+kartotekID).html()) != 1) {
        $("#top"+kartotekID).html(parseInt($("#top"+kartotekID).html() - 1));
      }
    });
  }
  else {
    $("#top"+kartotekID).html(parseInt($("#top"+kartotekID).html()) + 1);
  }
};

var findArticles = function(resultsTemplate, articleTemplate) {
  var articleName = $('#article-search').val();
  var url = '/api/search/Kartotekartikel?text=' + articleName;
  $.get(url).done(function(results) {
    $('#kartotekResults').html(resultsTemplate({ results: results }));

    if (results.length != 0) {
      $('#article-search').addClass('has-results');
    }
    else {
      $('#article-search').removeClass('has-results');
    }

    $('.add-column').click(function() {
      addArticle.call(this, articleTemplate, results);
      $('#article-search').val('').removeClass('has-results');
      $('.kartotekResults')
    });
  });
};

var addSynonym = function() {
  var name = $('#synonym-input').val();
  $('#synonyms').append(synonymTemplate({ name: name }));
};

var initializeSpecialitetSelect = function() {
  $(".specialitet-select").select2({

    ajax: {
      type: 'GET',
      url: '/api/search/Specialitet/',
      dataType: 'json',
      delay: 250,
      data: function (params) {
        return {

          text: params.term, // search term
          all: 1
        };
      },
      processResults: function (data) {
        console.log(data);

        return {
          results: $.map(data, function (item) {
            return {
              text: item.name, id: item._id
            }
          })
        };
      },
      cache: true
    },
    escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
    minimumInputLength: 0

  });
};

var addUnderrubrik = function(underrubrikTemplate){
  var name = $('#underrubrik-name').val();
  var text = $('#underrubrik-text').val();

  //hardcoded for now (iteration1)
  var processteg = ["Anestesi",
                    "Operation",
                    "Patientpositionering"];

  $(underrubrikTemplate({ name: name, text: text, processteg: processteg })).appendTo('#underrubriker');

  //Set select2 for new underrubrik
  $(".select-processteg").select2({
  });

  //Reset inputfields for underrubrik
  $('#underrubrik-name').val('');
  $('#underrubrik-text').val('');
};

// TODO keyCode == 13
$(function() {
  var compiledSynonym = $('#synonym-template').html();
  var synonymTemplate = Handlebars.compile(compiledSynonym);

  var compiledResults = $('#kartotekResults-template').html();
  var kartotekResultsTemplate = Handlebars.compile(compiledResults);

  var compiledArticle = $('#article-template').html();
  var articleTemplate = Handlebars.compile(compiledArticle);

  var compiledUnderrubrik = $('#underrubrik-template').html();
  var underrubrikTemplate = Handlebars.compile(compiledUnderrubrik);

  $('#newOperationButton').click(createNewOperation);
  $('#article-search').keyup(findArticles.bind(undefined, kartotekResultsTemplate, articleTemplate));
  $('#add-synonym-btn').click(addSynonym.bind(undefined, synonymTemplate));
  $('#tags_1').tagsInput({
    width: 'auto',
    defaultText: 'Lägg till synonym',
    removeWithBackspace: false,
    height: '40px'
  });

  $('#newUnderrubrikButton').click(addUnderrubrik.bind(undefined, underrubrikTemplate));

  initializeSpecialitetSelect();

  $(".select-processteg").select2({
  });

  //Helper to get selected processteg when creating underrubrik client-side
  Handlebars.registerHelper('if_selected', function(a, opts) {
    if (a == $('.select-processteg').val()) {
      return opts.fn(this);
    }
    else {
      return opts.inverse(this);
    }
  });
});

<commit_msg>Fixed search on kartotekartikel in create.js<commit_after>function add(data, index, operation, addedProccesstegs) {

  var addedProccesstegs = addedProccesstegs;

  if ( !(data === undefined) ) {

    var underrubrikName = $(data).find('#underrubrik-name').val();
    var underrubrikText = $(data).find('#underrubrik-text').val();
    var processteg = $(data).find('.select-processteg').val();

    if (!(processteg in addedProccesstegs)) {
      $.ajax({
        type: 'POST',
        url: '/api/processtegs',
        data: {
          title: processteg,
          operation: operation,
          template : true
        }
      })
        .done(function (msg) {
          console.log(msg);
          addedProccesstegs[processteg] = [true, msg._id];
          $.ajax({
            type: 'POST',
            url: '/api/processinnehalls',
            data: {
              order: 0,
              title: underrubrikName,
              text: underrubrikText,
              process: msg._id
            }
          })
            .done(function (msg) {
              console.log(msg);
              $(function () {
                add($('#underrubriker').children()[index + 1], index + 1, operation, addedProccesstegs);
              });
            })
            .fail(function (err, status) {
              console.log('Någonting gick fel!');
              console.log(err);
              console.log(status);
            });
        })
        .fail(function (err, status) {
          console.log('Någonting gick fel!');
          console.log(err);
          console.log(status);
        });
    }
    else{
      $.ajax({
        type: 'POST',
        url: '/api/processinnehalls',
        data: {
          order: 0,
          title: underrubrikName,
          text: underrubrikText,
          process: addedProccesstegs[processteg][1]
        }
      })
        .done(function (msg) {
          console.log(msg);
          $(function () {
            add($('#underrubriker').children()[index + 1], index + 1, operation, addedProccesstegs);
          });
        })
        .fail(function (err, status) {
          console.log('Någonting gick fel!');
          console.log(err);
          console.log(status);
        });
    }
  }
  else{
    console.log("handbok skapad");
    alert("handbok skapad");
  }
}

var createNewOperation = function() {
  var tags = $('#tags_1').val();
  var specialty = $(".specialitet-select").val();
  var operationName = $('#operation-name').val();

  console.log(specialty);
  if (specialty == 'Specialitet') {
    console.log('Fix Error here');
    alert("välj specialitet!")
  }
  else
  {
    $.ajax({
      type: 'POST',
      url: '/api/operations',
      data: {
        title: operationName,
        tags: tags,
        specialty: specialty,
        template: true
      }
    })
      .done(function (msg) {
        console.log(msg);
        //adding articles here
        $('.article').each(function (index) {
          var name = $(this).text();
          var kartotek = $(this).attr("data-kartotekID");
          var operation = msg._id;
          var amount = $('#articles').find('#top'+kartotek).text();
          $.ajax({
            type: 'POST',
            url: '/api/artikels',
            data: {
              name: name,
              kartotek: kartotek,
              operation: operation,
              amount : amount
            }
          })
            .done(function (msg) {
              console.log(msg); //Contains the created Article-model
            })
            .fail(function (err, status) {
              console.log('Någonting gick fel!');
              console.log(err);
              console.log(status);
            });
        });
        //adding underrubrik/processteg(recursive)
        $(function() {
          var index = 0;
          add($('#underrubriker').children()[index], index, msg._id, {});
        });
      })
      .fail(function (err, status) {
        console.log('Någonting gick fel!');
        console.log(err);
        console.log(status);
      });
  }
};

var removeArticle = function(element) {
  var parent = $(element).parent();
  $(parent).remove();
};

var addArticle = function(articleTemplate, results) {
  var name = $(this).data('name');
  var kartotekID = $(this).data('kartotekid');
  var found = false;

  $('.article').each(function(index) {
    if($(this).attr("data-kartotekID") == kartotekID) {
      found = true;
      }
  });

  if (!found) {
    var newArticle = $(articleTemplate({ name: name, id: kartotekID })).appendTo('#articles');
    newArticle.find('.col-right').click(function() {
      removeArticle(this);
    });
    $("#plus"+kartotekID).click(function() {
      $("#top"+kartotekID).html(parseInt($("#top"+kartotekID).html()) + 1);
    });
    $("#minus"+kartotekID).click(function() {
      if (parseInt($("#top"+kartotekID).html()) != 1) {
        $("#top"+kartotekID).html(parseInt($("#top"+kartotekID).html() - 1));
      }
    });
  }
  else {
    $("#top"+kartotekID).html(parseInt($("#top"+kartotekID).html()) + 1);
  }
};

var findArticles = function(resultsTemplate, articleTemplate) {
  var articleName = $('#article-search').val();
  var url = '/api/search/Kartotekartikel?text=' + articleName;
  $.get(url).done(function(results) {
    $('#kartotekResults').html(resultsTemplate({ results: results }));

    if (results.length != 0) {
      $('#article-search').addClass('has-results');
    }
    else {
      $('#article-search').removeClass('has-results');
    }

    $('.add-column').click(function() {
      addArticle.call(this, articleTemplate, results);
      $('#article-search').val('').removeClass('has-results');
      $('.kartotekResults')
    });
  });
};

var addSynonym = function() {
  var name = $('#synonym-input').val();
  $('#synonyms').append(synonymTemplate({ name: name }));
};

var initializeSpecialitetSelect = function() {
  $(".specialitet-select").select2({

    ajax: {
      type: 'GET',
      url: '/api/search/Specialitet/',
      dataType: 'json',
      delay: 250,
      data: function (params) {
        return {

          text: params.term, // search term
          all: 1
        };
      },
      processResults: function (data) {
        console.log(data);

        return {
          results: $.map(data, function (item) {
            return {
              text: item.name, id: item._id
            }
          })
        };
      },
      cache: true
    },
    escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
    minimumInputLength: 0

  });
};

var addUnderrubrik = function(underrubrikTemplate){
  var name = $('#underrubrik-name').val();
  var text = $('#underrubrik-text').val();

  //hardcoded for now (iteration1)
  var processteg = ["Anestesi",
                    "Operation",
                    "Patientpositionering"];

  $(underrubrikTemplate({ name: name, text: text, processteg: processteg })).appendTo('#underrubriker');

  //Set select2 for new underrubrik
  $(".select-processteg").select2({
  });

  //Reset inputfields for underrubrik
  $('#underrubrik-name').val('');
  $('#underrubrik-text').val('');
};

// TODO keyCode == 13
$(function() {
  var compiledSynonym = $('#synonym-template').html();
  var synonymTemplate = Handlebars.compile(compiledSynonym);

  var compiledResults = $('#kartotekResults-template').html();
  var kartotekResultsTemplate = Handlebars.compile(compiledResults);

  var compiledArticle = $('#article-template').html();
  var articleTemplate = Handlebars.compile(compiledArticle);

  var compiledUnderrubrik = $('#underrubrik-template').html();
  var underrubrikTemplate = Handlebars.compile(compiledUnderrubrik);

  $('#newOperationButton').click(createNewOperation);
  $('#article-search').keyup(findArticles.bind(undefined, kartotekResultsTemplate, articleTemplate));
  $('#add-synonym-btn').click(addSynonym.bind(undefined, synonymTemplate));
  $('#tags_1').tagsInput({
    width: 'auto',
    defaultText: 'Lägg till synonym',
    removeWithBackspace: false,
    height: '40px'
  });

  $('#newUnderrubrikButton').click(addUnderrubrik.bind(undefined, underrubrikTemplate));

  initializeSpecialitetSelect();

  $(".select-processteg").select2({
  });

  //Helper to get selected processteg when creating underrubrik client-side
  Handlebars.registerHelper('if_selected', function(a, opts) {
    if (a == $('.select-processteg').val()) {
      return opts.fn(this);
    }
    else {
      return opts.inverse(this);
    }
  });
});

<|endoftext|>


<commit_before>/*
 * debugger.io: An interactive web scripting sandbox
 *
 * cdn.js: client-side CDN cache and filter
 */

define([
  'config', 'utils', 'jquery', 'underscore',
  'backbone', 'bus', 'dom', 'keys', 'templates'
],
function(config, utils, $, _, Backbone, bus, dom, keys, templates) {
  'use strict';

  var cdn = utils.module('cdn');

  var cdnjs = '%s://cdnjs.cloudflare.com/ajax/libs/%s/%s/%s';
  var cache = null;

  /**
   * Check if client-side CDN package cache exists
   *
   * @return {Boolean} true if cache exists, false otherwise
   */
  cdn.cache_exists = function() {
    return _.isArray(cache) && cache.length > 0;
  };

  /**
   * Return a cached version of CDN packages
   *
   * @param {Boolean} update - if true, force the cache to update first
   * @return {Promise} promise to return the CDN packages {Array}
   */
  cdn.get_cache = function(update) {
    var d = $.Deferred();

    if (!update && cdn.cache_exists()) {
      d.resolve(cache);
    } else {
      cdn.update_cache().done(function(packages) {
        d.resolve(utils.ensure_array(packages));
      }).fail(function(err) {
        d.resolve(utils.ensure_array(cache));
      });
    }

    return d.promise();
  };

  /**
   * Update the CDN package cache now
   *
   * @return {Promise}
   */
  cdn.update_cache = function() {
    var d = $.Deferred();

    $.get(utils.uri('cdn')).done(function(packages) {
      cache = packages;
      d.resolve(packages);
    }).fail(function(err) {
      d.reject(err);
    });

    return d.promise();
  };

  /**
   * Init the CDN filter input
   */
  cdn.init_filter = function() {
    var filterModel = new cdn.FilterInput();
    var filterView = new cdn.FilterInputView({ model: filterModel });
  };

  /**
   * Current filter value
   */
  cdn.FilterInput = Backbone.Model.extend({
    'defaults': { value: '' }
  });

  /**
   * Input element for filtering CDN packages
   *
   * @param {cdn.FilterInput} - filter model
   */
  cdn.FilterInputView = Backbone.View.extend({
    template: 'cdn-filter',
    el: '#markup .panel-controls',

    initialize: function(options) {
      bus.on('cdn:result:select mirror:focus', this.clear, this);
      this.model.on('change:value', this.update, this);

      this.render();
    },

    events: {
      'input #cdn': 'keypress',
      'keydown #cdn': 'keypress'
    },

    keypress: function(e) {
      if (e.which === keys.key_code_for('up')) {
        bus.trigger('cdn:results:prev-active');
      } else if (e.which === keys.key_code_for('down')) {
        bus.trigger('cdn:results:next-active');
      } else if (e.which === keys.key_code_for('enter')) {
        bus.trigger('cdn:results:select-active');
      }

      this.model.set({ value: $(e.target).val() });
    },

    clear: function() {
      this.model.set({ value: '' });
      this.$cdn.val('');
    },

    update: function() {
      var that = this;
      var filter = _.trim(this.model.get('value')).toLowerCase();

      cdn.get_cache().done(function(packages) {
        // filter for the packages that match the input
        var filtered = _.filter(packages, function(pkg) {
          return !!pkg.name && !!pkg.filename && !!pkg.version &&
            _.str.include(pkg.name.toLowerCase(), filter);
        });

        // sort filtered packages by comparing them with the filter string
        var sorted = _.sortBy(filtered, function(pkg) {
          return _.levenshtein(filter, pkg.name.toLowerCase());
        });

        // limit the number of displayed results for performance
        var limited = _.first(sorted, config.cdn_results);

        that.resultsView.set_filter(filter);
        that.resultsCollection.reset(limited);
      });
    },

    render: function() {
      var that = this;

      templates.get(this.template, this).done(function(template_fn) {
        var html = template_fn();
        this.$el.html(html);
        this.$cdn = this.$el.find('#cdn');

        // focus the input on key command
        keys.register_handler({ ctrl: true, key: '/' }, function(e) {
          that.$cdn.select();
        });

        cdn.get_cache().done(function(packages) {
          that.$cdn.prop('disabled', false);

          that.resultsCollection = new cdn.FilterResults([]);
          that.resultsView = new cdn.FilterResultsView({
            collection: that.resultsCollection
          });
        });
      });
    }
  });

  /**
   * An available CDN package
   */
  cdn.FilterResult = Backbone.Model.extend({
    defaults: {
      name: '',
      filename: '',
      version: '',
      active: false
    }
  });

  /**
   * List element representing an available CDN package
   *
   * @param {cdn.FilterResult} - model of an available package
   */
  cdn.FilterResultView = Backbone.View.extend({
    template: 'cdn-result',
    tagName: 'li',

    initialize: function(options) {
      this.render();
    },

    events: {
      'click': 'select_lib'
    },

    get_uri: function(secure) {
      var pkg = this.model.toJSON();
      var protocol = !!secure ? 'https' : 'http';
      return _.sprintf(cdnjs, protocol, pkg.name, pkg.version, pkg.filename);
    },

    select_lib: function() {
      bus.trigger('cdn:result:select', this.get_uri());
    },

    render: function() {
      templates.get(this.template, this).done(function(template_fn) {
        var html = template_fn({ pkg: this.model.toJSON() });
        this.$el.html(html);
      });
    }
  });

  /**
   * Collection of cdn.FilterResult(s)
   */
  cdn.FilterResults = Backbone.Collection.extend({
    model: cdn.FilterResult
  });

  /**
   * List of CDN packages to add to project
   * filtered and sorted by cdn.FilterInput
   *
   * @param {cdn.FilterResults} - collection of available packages
   * @param {jQuery} $el - element to template into
   * @param {String} filter - filter used
   */
  cdn.FilterResultsView = Backbone.View.extend({
    el: '#cdn-results',

    initialize: function(options) {
      this.collection.on('reset', this.render, this);

      bus.off_ns('cdn:results');
      bus.on('cdn:results:prev-active', this.prev_active, this);
      bus.on('cdn:results:next-active', this.next_active, this);
      bus.on('cdn:results:select-active', this.select_active, this);

      bus.on('cdn:result:select mirror:focus', this.hide, this);

      this.$content = this.$el.children('.content');
      this.filter = '';
      this.render();
    },

    set_filter: function(filter) {
      this.filter = filter;
    },

    show: function() {
      this.$el.css({ 'display': 'block' });

      // adjust margins when overflowing
      var overflow = dom.is_overflowing_with_scrollbar(this.$ol);
      this.$ol.toggleClass('overflow', overflow);

      var maxHeight = Math.min(this.$ol.outerHeight() + 4, config.cdn_height);
      this.$el.css({ 'max-height': _.sprintf('%spx', maxHeight) });

      this.first_active();
      dom.transition_with_scrollbar(this.$el, { 'opacity': 1 });
    },

    hide: function(callback, stopFn) {
      var that = this;

      this.$el.transition({ 'opacity': 0 }, 'fast', function() {
        if (_.isFunction(stopFn) && stopFn() === true) { return; }

        this.css({ 'display': 'none' });
        _.isFunction(callback) && callback.call(that);
      });
    },

    // set the first result as the active result
    first_active: function() {
      var $children = this.$ol.children();
      $children.filter('.active').removeClass('.active');
      $children.first().addClass('active');

      this.scroll_active();
    },

    // set the previous result as the active result
    prev_active: function() {
      var $children = this.$ol.children();
      var $active = $children.filter('.active');
      var $prev = $active.first().prev();

      if ($prev.length) {
        $active.removeClass('active');
        $prev.addClass('active');
      }

      this.scroll_active();
    },

    // set the next result as the active result
    next_active: function() {
      var $children = this.$ol.children();
      var $active = $children.filter('.active');
      var $next = $active.first().next();

      if ($next.length) {
        $active.removeClass('active');
        $next.addClass('active');
      } else if (!$active.length) {
        $children.first().addClass('active');
      }

      this.scroll_active();
    },

    // keep the active result visible
    scroll_active: function() {
      var $active = this.$ol.children().filter('.active').first();
      if ($active.length && this.$ol.hasClass('overflow')) {
        var paddingTop = parseInt(this.$ol.css('padding-top'), 10);
        var paddingBottom = parseInt(this.$ol.css('padding-bottom'), 10);

        var contentHeight = this.$content.outerHeight();
        var contentTop = this.$content.scrollTop();
        var contentBottom = contentTop + contentHeight;

        var activeHeight = $active.outerHeight();
        var activeTop = contentTop + $active.position().top;
        var activeBottom = activeTop + activeHeight;

        var scrollTop;

        // too far down
        if (activeBottom > contentBottom) {
          scrollTop = activeBottom - contentHeight + paddingBottom;
          dom.scrollbar_scroll_top(this.$ol, scrollTop);
        }
        // too far up
        else if (activeTop < contentTop) {
          scrollTop = activeTop - paddingTop;
          dom.scrollbar_scroll_top(this.$ol, scrollTop);
        }
      }
    },

    // insert the active result
    select_active: function() {
      var activeResultView = _.find(this._rvs, function(rv) {
        return rv.$el.hasClass('active');
      });

      if (activeResultView instanceof cdn.FilterResultView) {
        activeResultView.select_lib();
      }
    },

    render: function() {
      var that = this;

      // close the results list if there is no filter
      if (!this.filter) {
        this.hide(function() { that.$content.empty(); },
        // abort if a filter exists by the time the transition completes
        function() { return !!that.filter; });

        return;
      }

      // show "no results" as appropriate
      // var $nomatch = this.$el.children('.nomatch');
      // $nomatch.toggleClass('hide', !!this.collection.models.length);

      this._rvs = [];
      this.$ol = $('<ol>');

      // populate filtered/sorted packages
      _.each(this.collection.models, function(result) {
        var rv = new cdn.FilterResultView({ model: result });
        this._rvs.push(rv);
        this.$ol.append(rv.el);
      }, this);

      this.$content.html(this.$ol);
      this.show();
    }
  });

  return cdn;
});
<commit_msg>preventDefault on CDN filter keypress actions<commit_after>/*
 * debugger.io: An interactive web scripting sandbox
 *
 * cdn.js: client-side CDN cache and filter
 */

define([
  'config', 'utils', 'jquery', 'underscore',
  'backbone', 'bus', 'dom', 'keys', 'templates'
],
function(config, utils, $, _, Backbone, bus, dom, keys, templates) {
  'use strict';

  var cdn = utils.module('cdn');

  var cdnjs = '%s://cdnjs.cloudflare.com/ajax/libs/%s/%s/%s';
  var cache = null;

  /**
   * Check if client-side CDN package cache exists
   *
   * @return {Boolean} true if cache exists, false otherwise
   */
  cdn.cache_exists = function() {
    return _.isArray(cache) && cache.length > 0;
  };

  /**
   * Return a cached version of CDN packages
   *
   * @param {Boolean} update - if true, force the cache to update first
   * @return {Promise} promise to return the CDN packages {Array}
   */
  cdn.get_cache = function(update) {
    var d = $.Deferred();

    if (!update && cdn.cache_exists()) {
      d.resolve(cache);
    } else {
      cdn.update_cache().done(function(packages) {
        d.resolve(utils.ensure_array(packages));
      }).fail(function(err) {
        d.resolve(utils.ensure_array(cache));
      });
    }

    return d.promise();
  };

  /**
   * Update the CDN package cache now
   *
   * @return {Promise}
   */
  cdn.update_cache = function() {
    var d = $.Deferred();

    $.get(utils.uri('cdn')).done(function(packages) {
      cache = packages;
      d.resolve(packages);
    }).fail(function(err) {
      d.reject(err);
    });

    return d.promise();
  };

  /**
   * Init the CDN filter input
   */
  cdn.init_filter = function() {
    var filterModel = new cdn.FilterInput();
    var filterView = new cdn.FilterInputView({ model: filterModel });
  };

  /**
   * Current filter value
   */
  cdn.FilterInput = Backbone.Model.extend({
    'defaults': { value: '' }
  });

  /**
   * Input element for filtering CDN packages
   *
   * @param {cdn.FilterInput} - filter model
   */
  cdn.FilterInputView = Backbone.View.extend({
    template: 'cdn-filter',
    el: '#markup .panel-controls',

    initialize: function(options) {
      bus.on('cdn:result:select mirror:focus', this.clear, this);
      this.model.on('change:value', this.update, this);

      this.render();
    },

    events: {
      'input #cdn': 'keypress',
      'keydown #cdn': 'keypress'
    },

    keypress: function(e) {
      if (e.which === keys.key_code_for('up')) {
        bus.trigger('cdn:results:prev-active');
        e.preventDefault();
      } else if (e.which === keys.key_code_for('down')) {
        bus.trigger('cdn:results:next-active');
        e.preventDefault();
      } else if (e.which === keys.key_code_for('enter')) {
        bus.trigger('cdn:results:select-active');
        e.preventDefault();
      }

      this.model.set({ value: $(e.target).val() });
    },

    clear: function() {
      this.model.set({ value: '' });
      this.$cdn.val('');
    },

    update: function() {
      var that = this;
      var filter = _.trim(this.model.get('value')).toLowerCase();

      cdn.get_cache().done(function(packages) {
        // filter for the packages that match the input
        var filtered = _.filter(packages, function(pkg) {
          return !!pkg.name && !!pkg.filename && !!pkg.version &&
            _.str.include(pkg.name.toLowerCase(), filter);
        });

        // sort filtered packages by comparing them with the filter string
        var sorted = _.sortBy(filtered, function(pkg) {
          return _.levenshtein(filter, pkg.name.toLowerCase());
        });

        // limit the number of displayed results for performance
        var limited = _.first(sorted, config.cdn_results);

        that.resultsView.set_filter(filter);
        that.resultsCollection.reset(limited);
      });
    },

    render: function() {
      var that = this;

      templates.get(this.template, this).done(function(template_fn) {
        var html = template_fn();
        this.$el.html(html);
        this.$cdn = this.$el.find('#cdn');

        // focus the input on key command
        keys.register_handler({ ctrl: true, key: '/' }, function(e) {
          that.$cdn.select();
        });

        cdn.get_cache().done(function(packages) {
          that.$cdn.prop('disabled', false);

          that.resultsCollection = new cdn.FilterResults([]);
          that.resultsView = new cdn.FilterResultsView({
            collection: that.resultsCollection
          });
        });
      });
    }
  });

  /**
   * An available CDN package
   */
  cdn.FilterResult = Backbone.Model.extend({
    defaults: {
      name: '',
      filename: '',
      version: '',
      active: false
    }
  });

  /**
   * List element representing an available CDN package
   *
   * @param {cdn.FilterResult} - model of an available package
   */
  cdn.FilterResultView = Backbone.View.extend({
    template: 'cdn-result',
    tagName: 'li',

    initialize: function(options) {
      this.render();
    },

    events: {
      'click': 'select_lib'
    },

    get_uri: function(secure) {
      var pkg = this.model.toJSON();
      var protocol = !!secure ? 'https' : 'http';
      return _.sprintf(cdnjs, protocol, pkg.name, pkg.version, pkg.filename);
    },

    select_lib: function() {
      bus.trigger('cdn:result:select', this.get_uri());
    },

    render: function() {
      templates.get(this.template, this).done(function(template_fn) {
        var html = template_fn({ pkg: this.model.toJSON() });
        this.$el.html(html);
      });
    }
  });

  /**
   * Collection of cdn.FilterResult(s)
   */
  cdn.FilterResults = Backbone.Collection.extend({
    model: cdn.FilterResult
  });

  /**
   * List of CDN packages to add to project
   * filtered and sorted by cdn.FilterInput
   *
   * @param {cdn.FilterResults} - collection of available packages
   * @param {jQuery} $el - element to template into
   * @param {String} filter - filter used
   */
  cdn.FilterResultsView = Backbone.View.extend({
    el: '#cdn-results',

    initialize: function(options) {
      this.collection.on('reset', this.render, this);

      bus.off_ns('cdn:results');
      bus.on('cdn:results:prev-active', this.prev_active, this);
      bus.on('cdn:results:next-active', this.next_active, this);
      bus.on('cdn:results:select-active', this.select_active, this);

      bus.on('cdn:result:select mirror:focus', this.hide, this);

      this.$content = this.$el.children('.content');
      this.filter = '';
      this.render();
    },

    set_filter: function(filter) {
      this.filter = filter;
    },

    show: function() {
      this.$el.css({ 'display': 'block' });

      // adjust margins when overflowing
      var overflow = dom.is_overflowing_with_scrollbar(this.$ol);
      this.$ol.toggleClass('overflow', overflow);

      var maxHeight = Math.min(this.$ol.outerHeight() + 4, config.cdn_height);
      this.$el.css({ 'max-height': _.sprintf('%spx', maxHeight) });

      this.first_active();
      dom.transition_with_scrollbar(this.$el, { 'opacity': 1 });
    },

    hide: function(callback, stopFn) {
      var that = this;

      this.$el.transition({ 'opacity': 0 }, 'fast', function() {
        if (_.isFunction(stopFn) && stopFn() === true) { return; }

        this.css({ 'display': 'none' });
        _.isFunction(callback) && callback.call(that);
      });
    },

    // set the first result as the active result
    first_active: function() {
      var $children = this.$ol.children();
      $children.filter('.active').removeClass('.active');
      $children.first().addClass('active');

      this.scroll_active();
    },

    // set the previous result as the active result
    prev_active: function() {
      var $children = this.$ol.children();
      var $active = $children.filter('.active');
      var $prev = $active.first().prev();

      if ($prev.length) {
        $active.removeClass('active');
        $prev.addClass('active');
      }

      this.scroll_active();
    },

    // set the next result as the active result
    next_active: function() {
      var $children = this.$ol.children();
      var $active = $children.filter('.active');
      var $next = $active.first().next();

      if ($next.length) {
        $active.removeClass('active');
        $next.addClass('active');
      } else if (!$active.length) {
        $children.first().addClass('active');
      }

      this.scroll_active();
    },

    // keep the active result visible
    scroll_active: function() {
      var $active = this.$ol.children().filter('.active').first();
      if ($active.length && this.$ol.hasClass('overflow')) {
        var paddingTop = parseInt(this.$ol.css('padding-top'), 10);
        var paddingBottom = parseInt(this.$ol.css('padding-bottom'), 10);

        var contentHeight = this.$content.outerHeight();
        var contentTop = this.$content.scrollTop();
        var contentBottom = contentTop + contentHeight;

        var activeHeight = $active.outerHeight();
        var activeTop = contentTop + $active.position().top;
        var activeBottom = activeTop + activeHeight;

        var scrollTop;

        // too far down
        if (activeBottom > contentBottom) {
          scrollTop = activeBottom - contentHeight + paddingBottom;
          dom.scrollbar_scroll_top(this.$ol, scrollTop);
        }
        // too far up
        else if (activeTop < contentTop) {
          scrollTop = activeTop - paddingTop;
          dom.scrollbar_scroll_top(this.$ol, scrollTop);
        }
      }
    },

    // insert the active result
    select_active: function() {
      var activeResultView = _.find(this._rvs, function(rv) {
        return rv.$el.hasClass('active');
      });

      if (activeResultView instanceof cdn.FilterResultView) {
        activeResultView.select_lib();
      }
    },

    render: function() {
      var that = this;

      // close the results list if there is no filter
      if (!this.filter) {
        this.hide(function() { that.$content.empty(); },
        // abort if a filter exists by the time the transition completes
        function() { return !!that.filter; });

        return;
      }

      // show "no results" as appropriate
      // var $nomatch = this.$el.children('.nomatch');
      // $nomatch.toggleClass('hide', !!this.collection.models.length);

      this._rvs = [];
      this.$ol = $('<ol>');

      // populate filtered/sorted packages
      _.each(this.collection.models, function(result) {
        var rv = new cdn.FilterResultView({ model: result });
        this._rvs.push(rv);
        this.$ol.append(rv.el);
      }, this);

      this.$content.html(this.$ol);
      this.show();
    }
  });

  return cdn;
});
<|endoftext|>


<commit_before>#!/usr/bin/nodejs

'use strict';

global.DOMParser = require('xmldom').DOMParser;
//require('../closure-library/closure/goog/bootstrap/nodejs')
global.Blockly = require('./blockly_wrapped.js');
//require('./blocks_compressed.js');
//require('./javascript_compressed.js');
//require('./msg/js/en.js');

Blockly.Events.Create = function() { this.isNull=function(){return 1}; };

var fname = process.argv[0] == 'blockly' ? process.argv[1] : process.argv[2];
var fs = require('fs');
var xmlText = fs.readFileSync(fname, 'utf8');

try {
    var xml = Blockly.Xml.textToDom(xmlText);
}
catch (e) {
    console.log(e);
    process.exit(2);
}

var workspace = new Blockly.Workspace();
Blockly.Xml.domToWorkspace(xml, workspace);
var code = Blockly.JavaScript.workspaceToCode(workspace);

var prepend = `
var HKOIInput = {
  lines : []
};
var window = {
  'alert': function(x) {
    console.log(x);
  },
  'prompt': function(x) {
    return HKOIInput.lines.shift();
  }
};
var HKOIUpdateVar = function() {};
var HKOIEnterScope = function() {};
var HKOIExitScope = function() {};
(function() {
  var str = "";
  while (true) {
    var buf = new Buffer(1024);
    var fs = require('fs')
    var stdin = fs.openSync('/dev/stdin', 'r');
    var br = fs.readSync(stdin, buf, 0, 1024);
    if (br == 0) break;
    str += buf.toString();
  }
  HKOIInput.lines = str.split('\n');
})();

`;
code = prepend + code;
code = code.replace(/^\s*HKOIUpdateVar.*/gm, '');

fs.writeFileSync('program.exe', code);
fs.chmodSync('program.exe', 493);
<commit_msg>FIx compile.js<commit_after>#!/usr/bin/nodejs

'use strict';

global.DOMParser = require('xmldom').DOMParser;
//require('../closure-library/closure/goog/bootstrap/nodejs')
global.Blockly = require('./blockly_wrapped.js');
//require('./blocks_compressed.js');
//require('./javascript_compressed.js');
//require('./msg/js/en.js');

Blockly.Events.Create = function() { this.isNull=function(){return 1}; };

var fname = process.argv[0] == 'blockly' ? process.argv[1] : process.argv[2];
var fs = require('fs');
var xmlText = fs.readFileSync(fname, 'utf8');

try {
    var xml = Blockly.Xml.textToDom(xmlText);
}
catch (e) {
    console.log(e);
    process.exit(2);
}

var workspace = new Blockly.Workspace();
Blockly.Xml.domToWorkspace(xml, workspace);
var code = Blockly.JavaScript.workspaceToCode(workspace);

var prepend = `
var HKOIInput = {
  lines : []
};
var window = {
  'alert': function(x) {
    console.log(x);
  },
  'prompt': function(x) {
    return HKOIInput.lines.shift();
  }
};
var HKOIUpdateVar = function() {};
var HKOIEnterScope = function() {};
var HKOIExitScope = function() {};

const solution = () => {
`;

var append = `
};

(function() {
  var str = "";
  process.stdin.on('readable', () => {
    const chunk = process.stdin.read();
    str += chunk;
  });
  process.stdin.on('end', () => {
    HKOIInput.lines = str.split('\\n');
    solution();
  });
})();
`;

code = prepend + code + append;
code = code.replace(/^\s*HKOIUpdateVar.*/gm, '');

fs.writeFileSync('program.exe', code);
fs.chmodSync('program.exe', 493);
<|endoftext|>