language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function processLifeCycle(lifecycle, lcMap, directionMap) {
var raw = lcMap[lifecycle];
var dirMap = {};
var ptr = raw.configuration[0].lifecycle[0].scxml[0].state;
var state;
for (var index in ptr) {
state = ptr[index];
var transitions = state.transition;
dirMap[state.id] = {};
for (var transitionIndex in transitions) {
var transition = transitions[transitionIndex];
dirMap[state.id][transition.target] = transition.event;
}
}
directionMap[lifecycle] = dirMap;
} | function processLifeCycle(lifecycle, lcMap, directionMap) {
var raw = lcMap[lifecycle];
var dirMap = {};
var ptr = raw.configuration[0].lifecycle[0].scxml[0].state;
var state;
for (var index in ptr) {
state = ptr[index];
var transitions = state.transition;
dirMap[state.id] = {};
for (var transitionIndex in transitions) {
var transition = transitions[transitionIndex];
dirMap[state.id][transition.target] = transition.event;
}
}
directionMap[lifecycle] = dirMap;
} |
JavaScript | function loadLifeCycle(lifecycleName, map) {
var file = new File('/extensions/lifecycles/' + lifecycleName + '.xml');
file.open('r');
var data = file.readAll();
file.close();
//Convert to an xml
data = '<?xml version="1.0" encoding="ISO-8859-1"?>' + data;
var xml = new XML(data);
//Convert to a json
data = data.replace('<?xml version="1.0" encoding="ISO-8859-1"?>', '');
var lcJSON = utility.xml.convertE4XtoJSON(xml);
map[lifecycleName] = lcJSON;
} | function loadLifeCycle(lifecycleName, map) {
var file = new File('/extensions/lifecycles/' + lifecycleName + '.xml');
file.open('r');
var data = file.readAll();
file.close();
//Convert to an xml
data = '<?xml version="1.0" encoding="ISO-8859-1"?>' + data;
var xml = new XML(data);
//Convert to a json
data = data.replace('<?xml version="1.0" encoding="ISO-8859-1"?>', '');
var lcJSON = utility.xml.convertE4XtoJSON(xml);
map[lifecycleName] = lcJSON;
} |
JavaScript | function checkIfStatesConnect(a, b, dirMap) {
if (!dirMap.hasOwnProperty(a)) {
return false;
}
if (!dirMap[a].hasOwnProperty(b)) {
return false;
}
return dirMap[a][b];
} | function checkIfStatesConnect(a, b, dirMap) {
if (!dirMap.hasOwnProperty(a)) {
return false;
}
if (!dirMap[a].hasOwnProperty(b)) {
return false;
}
return dirMap[a][b];
} |
JavaScript | function isPresent(state, stack) {
var array = stack.toArray();
if (array.indexOf(state) == -1) {
return false;
}
return true;
} | function isPresent(state, stack) {
var array = stack.toArray();
if (array.indexOf(state) == -1) {
return false;
}
return true;
} |
JavaScript | function chooseAction(fromState, toState, dirMap) {
if (!dirMap.hasOwnProperty(fromState)) {
return null;
}
if (!dirMap[fromState].hasOwnProperty(toState)) {
return null;
}
return dirMap[fromState][toState];
} | function chooseAction(fromState, toState, dirMap) {
if (!dirMap.hasOwnProperty(fromState)) {
return null;
}
if (!dirMap[fromState].hasOwnProperty(toState)) {
return null;
}
return dirMap[fromState][toState];
} |
JavaScript | function applyUiConfigSettings(uiConfig, deployedAssets) {
var assetsBlock = uiConfig.assets || {};
var ignored = assetsBlock.ignore || [];
//Update the ignored list
var newDeployedList = [];
var currentAsset;
//Check if there are any ignored assets
for (var index in deployedAssets) {
currentAsset = deployedAssets[index];
if (ignored.indexOf(currentAsset) == -1) {
log.debug('ignoring asset '+currentAsset+' as it is ignored in the ui config file: '+UI_CONFIG_FILE);
newDeployedList.push(currentAsset);
}
}
//Update the deployed assets if an ignore block was specified
if (newDeployedList.length > 0) {
deployedAssets = newDeployedList;
}
return deployedAssets;
} | function applyUiConfigSettings(uiConfig, deployedAssets) {
var assetsBlock = uiConfig.assets || {};
var ignored = assetsBlock.ignore || [];
//Update the ignored list
var newDeployedList = [];
var currentAsset;
//Check if there are any ignored assets
for (var index in deployedAssets) {
currentAsset = deployedAssets[index];
if (ignored.indexOf(currentAsset) == -1) {
log.debug('ignoring asset '+currentAsset+' as it is ignored in the ui config file: '+UI_CONFIG_FILE);
newDeployedList.push(currentAsset);
}
}
//Update the deployed assets if an ignore block was specified
if (newDeployedList.length > 0) {
deployedAssets = newDeployedList;
}
return deployedAssets;
} |
JavaScript | function loadConfigFile(path) {
var config = {};
var checkUIFile = new File(path);
if (checkUIFile.isExists()) {
config = require(path);
}
else{
log.debug('a ui config file is not present at '+path);
}
return config;
} | function loadConfigFile(path) {
var config = {};
var checkUIFile = new File(path);
if (checkUIFile.isExists()) {
config = require(path);
}
else{
log.debug('a ui config file is not present at '+path);
}
return config;
} |
JavaScript | function disableActions(actions) {
//Eagerly disable all of the buttons
var buttons = ['btn-asset-promote', 'btn-asset-demote'];
for (var buttonIndex in buttons) {
var button = buttons[buttonIndex];
$('#' + button).prop('disabled', true);
}
//Enable only relevant buttons.
for (var actionIndex in actions) {
var action = actions[actionIndex];
if (action == 'Promote') {
$('#btn-asset-promote').prop('disabled', false);
} else if (action == 'Demote') {
$('#btn-asset-demote').prop('disabled', false);
}
}
} | function disableActions(actions) {
//Eagerly disable all of the buttons
var buttons = ['btn-asset-promote', 'btn-asset-demote'];
for (var buttonIndex in buttons) {
var button = buttons[buttonIndex];
$('#' + button).prop('disabled', true);
}
//Enable only relevant buttons.
for (var actionIndex in actions) {
var action = actions[actionIndex];
if (action == 'Promote') {
$('#btn-asset-promote').prop('disabled', false);
} else if (action == 'Demote') {
$('#btn-asset-demote').prop('disabled', false);
}
}
} |
JavaScript | function buildLCGraph() {
//alert(id);
$.ajax({
url: '/publisher/api/lifecycle/' + asset + '/' + id + '?t=' + new Date().getTime(),
type: 'GET',
success: function (response) {
var element = $('#canvas');
if (element) {
if($('svg',element).length > 0 ){$('svg',element).remove()}
var paper = new Raphael('canvas', 600, 500);
//element.html(response);
/* if(!graph.Renderer.config.canvas.canvasElement){
graph.Renderer.config.canvas.canvasElement=element;
graph.Renderer.initRaphael();
graph.Renderer.render(graph.NMap);
} */
var statInfo = JSON.parse(response);
sugyama.init(statInfo.lifecycle, paper);
var START_X = 10;
var START_Y = 50;
var VERTEX_RADIUS = 15;
var LAYER_SEP = 85;
var LAYER_SPACE = 200;
//alert(statInfo.state);
//var curState = $('#state').text();
sugyama.draw(START_X, START_Y, VERTEX_RADIUS, LAYER_SPACE, LAYER_SEP, statInfo.state);
actions = statInfo.lifecycle.configuration[0].lifecycle[0].scxml[0].state;
keys = sugyama.getKeys();
//graph.Renderer.setSelected(statInfo.state);
disableActions(statInfo.actions);
buildButtons(statInfo.actions);
highlightTransition(statInfo.state);
}
//$('#canvas').html(response);
},
error: function (response) {
$('#canvas').html('Error obtaining life-cycle state of asset.');
}
});
} | function buildLCGraph() {
//alert(id);
$.ajax({
url: '/publisher/api/lifecycle/' + asset + '/' + id + '?t=' + new Date().getTime(),
type: 'GET',
success: function (response) {
var element = $('#canvas');
if (element) {
if($('svg',element).length > 0 ){$('svg',element).remove()}
var paper = new Raphael('canvas', 600, 500);
//element.html(response);
/* if(!graph.Renderer.config.canvas.canvasElement){
graph.Renderer.config.canvas.canvasElement=element;
graph.Renderer.initRaphael();
graph.Renderer.render(graph.NMap);
} */
var statInfo = JSON.parse(response);
sugyama.init(statInfo.lifecycle, paper);
var START_X = 10;
var START_Y = 50;
var VERTEX_RADIUS = 15;
var LAYER_SEP = 85;
var LAYER_SPACE = 200;
//alert(statInfo.state);
//var curState = $('#state').text();
sugyama.draw(START_X, START_Y, VERTEX_RADIUS, LAYER_SPACE, LAYER_SEP, statInfo.state);
actions = statInfo.lifecycle.configuration[0].lifecycle[0].scxml[0].state;
keys = sugyama.getKeys();
//graph.Renderer.setSelected(statInfo.state);
disableActions(statInfo.actions);
buildButtons(statInfo.actions);
highlightTransition(statInfo.state);
}
//$('#canvas').html(response);
},
error: function (response) {
$('#canvas').html('Error obtaining life-cycle state of asset.');
}
});
} |
JavaScript | function buttonClickLogic(action, comment) {
$.ajax({
url: '/publisher/apis/assets/' + id + '/state?type=' + asset + '&nextState=' + action + '&comment=' + comment,
type: 'POST',
data: JSON.stringify({
'comment': comment, 'nextState': action
}),
contentType: 'application/json',
success: function (response) {
var actionName = action.toLowerCase();
actionName += 'd';
showAlert('Asset was moved to state: ' + actionName + ' successfully.', 'success');
buildCheckList(asset, id);
buildLCGraph();
buildHistory(asset, id);
$.ajax({
url: '/publisher/apis/assets/' + id + '/state?type=' + asset,
type: 'GET',
success: function (response) {
//Convert the response to a JSON object
var statInfo = response;
$('#state').html(statInfo.data.id);
$('#view-lifecyclestate').html(statInfo.data.id);
//disableActions(statInfo.actions);
if (statInfo.data.isDeletable) {
$.ajax({
url: '/publisher/apis/assets/' + id + '?type=' + asset,
type: 'DELETE'
});
}
},
error: function (response) {
$('#state').html('Error obtaining life-cycle state of asset.');
}
});
},
error: function (response) {
if (response.status === 400) {
showAlert('You need to insert a comment for this change.', 'danger');
} else {
showAlert(action + ' operation failed', 'danger');
}
}
});
} | function buttonClickLogic(action, comment) {
$.ajax({
url: '/publisher/apis/assets/' + id + '/state?type=' + asset + '&nextState=' + action + '&comment=' + comment,
type: 'POST',
data: JSON.stringify({
'comment': comment, 'nextState': action
}),
contentType: 'application/json',
success: function (response) {
var actionName = action.toLowerCase();
actionName += 'd';
showAlert('Asset was moved to state: ' + actionName + ' successfully.', 'success');
buildCheckList(asset, id);
buildLCGraph();
buildHistory(asset, id);
$.ajax({
url: '/publisher/apis/assets/' + id + '/state?type=' + asset,
type: 'GET',
success: function (response) {
//Convert the response to a JSON object
var statInfo = response;
$('#state').html(statInfo.data.id);
$('#view-lifecyclestate').html(statInfo.data.id);
//disableActions(statInfo.actions);
if (statInfo.data.isDeletable) {
$.ajax({
url: '/publisher/apis/assets/' + id + '?type=' + asset,
type: 'DELETE'
});
}
},
error: function (response) {
$('#state').html('Error obtaining life-cycle state of asset.');
}
});
},
error: function (response) {
if (response.status === 400) {
showAlert('You need to insert a comment for this change.', 'danger');
} else {
showAlert(action + ' operation failed', 'danger');
}
}
});
} |
JavaScript | function buildButtons(actions) {
//Obtain the button container
var BUTTON_CONTAINER = '#form-actions';
//Clear the button container of previous buttons
$(BUTTON_CONTAINER).html('');
for (var index in actions) {
var action = actions[index];
//Populate buttons based on the action
var element = document.createElement('input');
element.type = 'button';
element.value = action;
element.className = 'btn btn-primary pull-right';
element.id = 'btn' + action;
$(BUTTON_CONTAINER).append(element);
/*
$('#btn' + action).on('click', function(e) {
var clicked = e.target.value;
e.preventDefault();
buttonClickLogic(clicked);
});*/
}
$('circle').hover(function () {
$(this).attr('r', 18);
}, function () {
$(this).attr('r', 15);
});
window.changeState = function (className) {
var thisState = className;
if (isClickable(thisState)) {
$.ajax({
url: '/publisher/apis/assets/' + id + '/state?type=' + asset,
type: 'GET',
success: function (response) {
var deleteStates = response.data.deletableStates;
if (deleteStates) {
if (deleteStates[0] == thisState) {
$('#deleteModal').data('state', thisState).modal('show');
} else {
$('#commentModal').data('state', thisState).modal('show');
}
}
}
});
} else {
showAlert('Invalid operation', 'danger');
}
}
} | function buildButtons(actions) {
//Obtain the button container
var BUTTON_CONTAINER = '#form-actions';
//Clear the button container of previous buttons
$(BUTTON_CONTAINER).html('');
for (var index in actions) {
var action = actions[index];
//Populate buttons based on the action
var element = document.createElement('input');
element.type = 'button';
element.value = action;
element.className = 'btn btn-primary pull-right';
element.id = 'btn' + action;
$(BUTTON_CONTAINER).append(element);
/*
$('#btn' + action).on('click', function(e) {
var clicked = e.target.value;
e.preventDefault();
buttonClickLogic(clicked);
});*/
}
$('circle').hover(function () {
$(this).attr('r', 18);
}, function () {
$(this).attr('r', 15);
});
window.changeState = function (className) {
var thisState = className;
if (isClickable(thisState)) {
$.ajax({
url: '/publisher/apis/assets/' + id + '/state?type=' + asset,
type: 'GET',
success: function (response) {
var deleteStates = response.data.deletableStates;
if (deleteStates) {
if (deleteStates[0] == thisState) {
$('#deleteModal').data('state', thisState).modal('show');
} else {
$('#commentModal').data('state', thisState).modal('show');
}
}
}
});
} else {
showAlert('Invalid operation', 'danger');
}
}
} |
JavaScript | function buildCheckList(asset, id) {
//Check if the id exists before making a call
if ((asset == '') || (id == '')) {
//console.log('omitting');
return;
}
//Clear the checklist rendering area
$('#checklist').html('');
//Make a call to the lifecycle check list
$.ajax({
url: '/publisher/api/lifecycle/checklist/' + asset + '/' + id,
type: 'GET',
success: function (response) {
var out = '<ul>';
var obj = JSON.parse(response);
for (var index in obj.checkListItems) {
var current = obj.checkListItems[index];
out += '<li><input type="checkbox" onclick="onCheckListItemClick(this,' + index + ')" ';
if (current.checked) {
out += 'checked';
}
out += '>' + current.name + '</label></li>';
}
out += '</ul>';
//Render the check list
$('#checklist').html(out);
}
});
} | function buildCheckList(asset, id) {
//Check if the id exists before making a call
if ((asset == '') || (id == '')) {
//console.log('omitting');
return;
}
//Clear the checklist rendering area
$('#checklist').html('');
//Make a call to the lifecycle check list
$.ajax({
url: '/publisher/api/lifecycle/checklist/' + asset + '/' + id,
type: 'GET',
success: function (response) {
var out = '<ul>';
var obj = JSON.parse(response);
for (var index in obj.checkListItems) {
var current = obj.checkListItems[index];
out += '<li><input type="checkbox" onclick="onCheckListItemClick(this,' + index + ')" ';
if (current.checked) {
out += 'checked';
}
out += '>' + current.name + '</label></li>';
}
out += '</ul>';
//Render the check list
$('#checklist').html(out);
}
});
} |
JavaScript | function buildHistory(asset, id) {
var version = '1.0.0';
//Make a call to the api to obtain the history
var path = '/publisher/api/lifecycle/information/history/' + asset + '/' + id + '/' + version;
$.ajax({
url: path,
type: 'GET',
success: function (response) {
//console.log(response);
var obj = JSON.parse(response);
var out = createHistoryEntry(obj.item);
$('#lc-history').html(out);
},
error: function (response) {
// console.log('lc history not retrieved');
}
});
} | function buildHistory(asset, id) {
var version = '1.0.0';
//Make a call to the api to obtain the history
var path = '/publisher/api/lifecycle/information/history/' + asset + '/' + id + '/' + version;
$.ajax({
url: path,
type: 'GET',
success: function (response) {
//console.log(response);
var obj = JSON.parse(response);
var out = createHistoryEntry(obj.item);
$('#lc-history').html(out);
},
error: function (response) {
// console.log('lc history not retrieved');
}
});
} |
JavaScript | function onCheckListItemClickHandler(checkbox, index) {
if (checkbox.checked) {
callCheckListItem(checkbox, index);
} else {
callUncheckListItem(checkbox, index);
}
} | function onCheckListItemClickHandler(checkbox, index) {
if (checkbox.checked) {
callCheckListItem(checkbox, index);
} else {
callUncheckListItem(checkbox, index);
}
} |
JavaScript | function callCheckListItem(checkbox, checkListItemIndex) {
$.ajax({
url: '/publisher/api/lifecycle/checklistitem/' + checkListItemIndex + '/' + asset + '/' + id,
type: 'POST',
success: function (response) {
alert('Item checked successfully');
},
error: function (response) {
checkbox.checked = false;
//Revert the checkbox to the previous state
alert('Could not check item');
}
});
} | function callCheckListItem(checkbox, checkListItemIndex) {
$.ajax({
url: '/publisher/api/lifecycle/checklistitem/' + checkListItemIndex + '/' + asset + '/' + id,
type: 'POST',
success: function (response) {
alert('Item checked successfully');
},
error: function (response) {
checkbox.checked = false;
//Revert the checkbox to the previous state
alert('Could not check item');
}
});
} |
JavaScript | function callUncheckListItem(checkbox, checkListItemIndex) {
$.ajax({
url: '/publisher/api/lifecycle/checklistitem/' + checkListItemIndex + '/' + asset + '/' + id,
type: 'DELETE',
success: function (response) {
alert('Item unchecked successfully');
},
error: function (response) {
checkbox.checked = true;
//Revert the checkbox to previous state
alert('Could not uncheck item');
}
});
} | function callUncheckListItem(checkbox, checkListItemIndex) {
$.ajax({
url: '/publisher/api/lifecycle/checklistitem/' + checkListItemIndex + '/' + asset + '/' + id,
type: 'DELETE',
success: function (response) {
alert('Item unchecked successfully');
},
error: function (response) {
checkbox.checked = true;
//Revert the checkbox to previous state
alert('Could not uncheck item');
}
});
} |
JavaScript | function processErrorReport(report) {
var msg = '';
for (var index in report) {
for (var item in report[index]) {
msg += report[index][item] + "<br>";
}
}
return msg;
} | function processErrorReport(report) {
var msg = '';
for (var index in report) {
for (var item in report[index]) {
msg += report[index][item] + "<br>";
}
}
return msg;
} |
JavaScript | function fillForm(field, formData) {
var fieldType = field.type;
if (fieldType == 'file') {
//console.log('added ' + field.id + ' file.');
formData[field.id] = field.files[0];
} else {
formData[field.id] = field.value;
}
return formData;
} | function fillForm(field, formData) {
var fieldType = field.type;
if (fieldType == 'file') {
//console.log('added ' + field.id + ' file.');
formData[field.id] = field.files[0];
} else {
formData[field.id] = field.value;
}
return formData;
} |
JavaScript | function obtainTags() {
var tagArray = [];
try {
var tags = $(TAG_CONTAINER).tokenInput('get');
for (var index in tags) {
tagArray.push(tags[index].name);
}
return tagArray;
} catch(e) {
return tagArray;
}
} | function obtainTags() {
var tagArray = [];
try {
var tags = $(TAG_CONTAINER).tokenInput('get');
for (var index in tags) {
tagArray.push(tags[index].name);
}
return tagArray;
} catch(e) {
return tagArray;
}
} |
JavaScript | function Artifact(name, options) {
var configs = options || {};
if (!typeof name === 'string') {
throw 'An artifact cannot be created without a name';
}
this.name = name;
this.path = configs.path || '';
this.fileExtension = configs.extension;
} | function Artifact(name, options) {
var configs = options || {};
if (!typeof name === 'string') {
throw 'An artifact cannot be created without a name';
}
this.name = name;
this.path = configs.path || '';
this.fileExtension = configs.extension;
} |
JavaScript | function RoutePattern(options){
this.paramCount=0;
this.pattern='';
this.context='';
this.func=null;
utility.config(options,this);
} | function RoutePattern(options){
this.paramCount=0;
this.pattern='';
this.context='';
this.func=null;
utility.config(options,this);
} |
JavaScript | function handle(context) {
var object=context.object||{};
var config=context.config;
var fields=config.storeFields;
var url;
var uuid;
var field;
//Go through all of the targeted fields
for(var index in fields){
utility.isPresent(object.attributes,fields[index],function(){
//Current field been examined
field=fields[index];
//Extract the uuid/filename from a url and write them back to the asset.
extractUUID(field,object);
});
}
return true;
} | function handle(context) {
var object=context.object||{};
var config=context.config;
var fields=config.storeFields;
var url;
var uuid;
var field;
//Go through all of the targeted fields
for(var index in fields){
utility.isPresent(object.attributes,fields[index],function(){
//Current field been examined
field=fields[index];
//Extract the uuid/filename from a url and write them back to the asset.
extractUUID(field,object);
});
}
return true;
} |
JavaScript | function extractUUID(field,asset){
var value;
var comps;
var uuid;
var fileName;
//Obtain the value
value=asset.attributes[field];
//Break up the value based on /
comps=value.split('/');
//Do nothing if the number of components is 2 or less
if(comps.length<=FIELD_ELEMENT_LIMIT){
log.debug('only uuid/file present');
return;
}
//Get the last two values in the component array
uuid=comps[comps.length-UUID_OFFSET];
fileName=comps[comps.length-FILE_OFFSET];
//Check if the uuid is valid
if(!utility.isValidUuid(uuid)){
log.debug('the uuid: '+uuid+' is not valid for field '+field);
asset.attributes[field]=value;
return;
//throw 'Invalid UUID in storage field.'+field;
}
asset.attributes[field]=uuid+'/'+fileName;
} | function extractUUID(field,asset){
var value;
var comps;
var uuid;
var fileName;
//Obtain the value
value=asset.attributes[field];
//Break up the value based on /
comps=value.split('/');
//Do nothing if the number of components is 2 or less
if(comps.length<=FIELD_ELEMENT_LIMIT){
log.debug('only uuid/file present');
return;
}
//Get the last two values in the component array
uuid=comps[comps.length-UUID_OFFSET];
fileName=comps[comps.length-FILE_OFFSET];
//Check if the uuid is valid
if(!utility.isValidUuid(uuid)){
log.debug('the uuid: '+uuid+' is not valid for field '+field);
asset.attributes[field]=value;
return;
//throw 'Invalid UUID in storage field.'+field;
}
asset.attributes[field]=uuid+'/'+fileName;
} |
JavaScript | function createNewVersion(newVersion, assetId, assetType) {
var path = '/publisher/api/version/' + assetType + '/' + assetId + '/' + newVersion;
$.ajax({
url : path,
type : 'POST',
success : function(response) {
$('#modal-redirect').modal('show');
setTimeout(function() {
var newVersionDetails = JSON.parse(response);
window.location = newVersionDetails.url;
}, 2000);
},
error : function() {
displayVersionMessage({
msgCss : CSS_ERR,
message : 'A new version of this ' + assetType + ' was not created.'
})
}
})
} | function createNewVersion(newVersion, assetId, assetType) {
var path = '/publisher/api/version/' + assetType + '/' + assetId + '/' + newVersion;
$.ajax({
url : path,
type : 'POST',
success : function(response) {
$('#modal-redirect').modal('show');
setTimeout(function() {
var newVersionDetails = JSON.parse(response);
window.location = newVersionDetails.url;
}, 2000);
},
error : function() {
displayVersionMessage({
msgCss : CSS_ERR,
message : 'A new version of this ' + assetType + ' was not created.'
})
}
})
} |
JavaScript | function handleLoggedInUser(o, session) {
var storeMasterManager = session.get(TENANT_STORE_MANAGERS);
var server = require('store').server;
var tenantId = (o instanceof Request) ? server.tenant(o, session).tenantId : o;
if (storeMasterManager) {
return storeMasterManager;
}
storeMasterManager = new StoreMasterManager(tenantId, session);
session.put(TENANT_STORE_MANAGERS, storeMasterManager);
return storeMasterManager;
} | function handleLoggedInUser(o, session) {
var storeMasterManager = session.get(TENANT_STORE_MANAGERS);
var server = require('store').server;
var tenantId = (o instanceof Request) ? server.tenant(o, session).tenantId : o;
if (storeMasterManager) {
return storeMasterManager;
}
storeMasterManager = new StoreMasterManager(tenantId, session);
session.put(TENANT_STORE_MANAGERS, storeMasterManager);
return storeMasterManager;
} |
JavaScript | function handleAnonUser(tenantId) {
var appManagerName = APP_MANAGERS + '.' + tenantId
var anonMasterManager = application.get(appManagerName);
//Check if it is cached
if (anonMasterManager) {
return anonMasterManager;
}
var anonMasterManager = new AnonStoreMasterManager(tenantId);
application.put(appManagerName, anonMasterManager);
return anonMasterManager;
} | function handleAnonUser(tenantId) {
var appManagerName = APP_MANAGERS + '.' + tenantId
var anonMasterManager = application.get(appManagerName);
//Check if it is cached
if (anonMasterManager) {
return anonMasterManager;
}
var anonMasterManager = new AnonStoreMasterManager(tenantId);
application.put(appManagerName, anonMasterManager);
return anonMasterManager;
} |
JavaScript | function StoreMasterManager(tenantId, session) {
var user = require('store').user;
var registry = user.userRegistry(session);
var managers = buildManagers(registry, tenantId);
this.modelManager = managers.modelManager;
this.rxtManager = managers.rxtManager;
this.storageSecurityProvider = managers.storageSecurityProvider;
this.tenantId = tenantId;
} | function StoreMasterManager(tenantId, session) {
var user = require('store').user;
var registry = user.userRegistry(session);
var managers = buildManagers(registry, tenantId);
this.modelManager = managers.modelManager;
this.rxtManager = managers.rxtManager;
this.storageSecurityProvider = managers.storageSecurityProvider;
this.tenantId = tenantId;
} |
JavaScript | function AnonStoreMasterManager(tenantID) {
var store = require('store');
var registry = store.server.systemRegistry(tenantID);
var managers = buildManagers(registry, tenantID);
this.modelManager = managers.modelManager;
this.rxtManager = managers.rxtManager;
this.storageSecurityProvider = managers.storageSecurityProvider;
this.tenantId = tenantID;
} | function AnonStoreMasterManager(tenantID) {
var store = require('store');
var registry = store.server.systemRegistry(tenantID);
var managers = buildManagers(registry, tenantID);
this.modelManager = managers.modelManager;
this.rxtManager = managers.rxtManager;
this.storageSecurityProvider = managers.storageSecurityProvider;
this.tenantId = tenantID;
} |
JavaScript | function translate(schema, modelManager, results) {
var result;
var field;
var models = [];
var model;
for (var index in results) {
result = results[index];
model = modelManager.get(schema.name);
for (var prop in result) {
for (var key in schema.fields) {
field = schema.fields[key];
if (field.name.toUpperCase() == prop.toUpperCase()) {
model[field.name] = result[prop];
}
}
}
models.push(model);
}
return models;
} | function translate(schema, modelManager, results) {
var result;
var field;
var models = [];
var model;
for (var index in results) {
result = results[index];
model = modelManager.get(schema.name);
for (var prop in result) {
for (var key in schema.fields) {
field = schema.fields[key];
if (field.name.toUpperCase() == prop.toUpperCase()) {
model[field.name] = result[prop];
}
}
}
models.push(model);
}
return models;
} |
JavaScript | function Bundle(options) {
this.path = '';
this.name = '';
this.extension = '';
this.type = '';
this.isDirectory = false;
this.instance = null;
utility.config(options, this);
//A resource can have many resources inside it
this.children = [];
} | function Bundle(options) {
this.path = '';
this.name = '';
this.extension = '';
this.type = '';
this.isDirectory = false;
this.instance = null;
utility.config(options, this);
//A resource can have many resources inside it
this.children = [];
} |
JavaScript | function BundleContainer(options) {
this.bundle = null;
this.queryBundles = [];
utility.config(options, this);
} | function BundleContainer(options) {
this.bundle = null;
this.queryBundles = [];
utility.config(options, this);
} |
JavaScript | function BundleManager(options) {
this.rootBundle = null;
this.path = '';
utility.config(options, this);
if (this.path != '') {
this.rootBundle = recursiveBuild(new File(this.path));
}
} | function BundleManager(options) {
this.rootBundle = null;
this.path = '';
utility.config(options, this);
if (this.path != '') {
this.rootBundle = recursiveBuild(new File(this.path));
}
} |
JavaScript | function recursiveFind(root, predicate, found) {
//Check if the root is a leaf
if (root.children.length == 0) {
//Check if the current root is a match
if (utility.isEqual(predicate, root)) {
log.debug('Found a match as leaf: ' + root.name);
return root;
}
return null;
}
else {
//Check if the directory will be a match
if (utility.isEqual(predicate, root)) {
log.debug('Found a match as a root: ' + root.name);
return root;
}
var foundResource;
var currentResource;
//Go through each resource in the sub resources
for (var index in root.children) {
currentResource = root.children[index];
foundResource = recursiveFind(currentResource, predicate, found);
//Check if a resource was found.
if (foundResource) {
log.debug('adding bundle: ' + foundResource.name);
found.push(foundResource);
}
}
//return found;
}
} | function recursiveFind(root, predicate, found) {
//Check if the root is a leaf
if (root.children.length == 0) {
//Check if the current root is a match
if (utility.isEqual(predicate, root)) {
log.debug('Found a match as leaf: ' + root.name);
return root;
}
return null;
}
else {
//Check if the directory will be a match
if (utility.isEqual(predicate, root)) {
log.debug('Found a match as a root: ' + root.name);
return root;
}
var foundResource;
var currentResource;
//Go through each resource in the sub resources
for (var index in root.children) {
currentResource = root.children[index];
foundResource = recursiveFind(currentResource, predicate, found);
//Check if a resource was found.
if (foundResource) {
log.debug('adding bundle: ' + foundResource.name);
found.push(foundResource);
}
}
//return found;
}
} |
JavaScript | function recursiveBuild(file) {
//Check if it is a directory in order to identify whether it is a child
if (!file.isDirectory()) {
var resource = new Bundle({
name: file.getName(),
extension: utility.fileio.getExtension(file),
instance: file
});
log.debug(file.getName() + ' not a directory ');
return resource;
}
else {
log.debug(file.getName() + ' will be a root bundle.');
//Create a resource of root type
var dir = new Bundle({
isDirectory: true,
name: file.getName(),
instance: file
});
//Obtain the sub resources within the given directory
var resources = file.listFiles();
log.debug('resources found: ' + resources.length);
//Go through each file
for (var index in resources) {
var current = recursiveBuild(resources[index], dir);
log.debug('adding: ' + current.name + ' as a child resource of ' + dir.name);
dir.add(current);
}
return dir;
}
} | function recursiveBuild(file) {
//Check if it is a directory in order to identify whether it is a child
if (!file.isDirectory()) {
var resource = new Bundle({
name: file.getName(),
extension: utility.fileio.getExtension(file),
instance: file
});
log.debug(file.getName() + ' not a directory ');
return resource;
}
else {
log.debug(file.getName() + ' will be a root bundle.');
//Create a resource of root type
var dir = new Bundle({
isDirectory: true,
name: file.getName(),
instance: file
});
//Obtain the sub resources within the given directory
var resources = file.listFiles();
log.debug('resources found: ' + resources.length);
//Go through each file
for (var index in resources) {
var current = recursiveBuild(resources[index], dir);
log.debug('adding: ' + current.name + ' as a child resource of ' + dir.name);
dir.add(current);
}
return dir;
}
} |
JavaScript | function findConfig(masterConfig, assetType) {
var assetData = masterConfig.assetData || [];
var asset;
//Locate the asset type
for (var index in assetData) {
asset = assetData[index];
if (asset.type == assetType) {
return asset;
}
}
return null;
} | function findConfig(masterConfig, assetType) {
var assetData = masterConfig.assetData || [];
var asset;
//Locate the asset type
for (var index in assetData) {
asset = assetData[index];
if (asset.type == assetType) {
return asset;
}
}
return null;
} |
JavaScript | function findAssetType(pluralAssetName) {
var lastCharacter = pluralAssetName.charAt(pluralAssetName.length - 1);
if (lastCharacter == 's') {
return pluralAssetName.substring(0, pluralAssetName.length - 1);
}
return pluralAssetName;
} | function findAssetType(pluralAssetName) {
var lastCharacter = pluralAssetName.charAt(pluralAssetName.length - 1);
if (lastCharacter == 's') {
return pluralAssetName.substring(0, pluralAssetName.length - 1);
}
return pluralAssetName;
} |
JavaScript | function isIgnored(config, target) {
var ignored = config.ignore || [];
if (ignored.indexOf(target) != -1) {
return true;
}
return false;
} | function isIgnored(config, target) {
var ignored = config.ignore || [];
if (ignored.indexOf(target) != -1) {
return true;
}
return false;
} |
JavaScript | function ScriptObject(scriptInstance) {
this.functionObject = {};
if (scriptInstance) {
this.init(scriptInstance);
}
} | function ScriptObject(scriptInstance) {
this.functionObject = {};
if (scriptInstance) {
this.init(scriptInstance);
}
} |
JavaScript | function clone(object) {
var cloned = {};
//Go through each property
for (var index in object) {
cloned[index] = object[index];
}
return cloned;
} | function clone(object) {
var cloned = {};
//Go through each property
for (var index in object) {
cloned[index] = object[index];
}
return cloned;
} |
JavaScript | function cached(){
//var instance=application.get(APP_SECURITY_MANAGER);
//Checks if an instance exists
//if(!instance){
instance=new SecurityManager();
//}
return instance;
} | function cached(){
//var instance=application.get(APP_SECURITY_MANAGER);
//Checks if an instance exists
//if(!instance){
instance=new SecurityManager();
//}
return instance;
} |
JavaScript | function checkEquality(a, b, key) {
if (a[key] instanceof Array) {
return (a[key].indexOf(b[key]) != -1) ? true : false;
}
else {
return a[key] == b[key];
}
} | function checkEquality(a, b, key) {
if (a[key] instanceof Array) {
return (a[key].indexOf(b[key]) != -1) ? true : false;
}
else {
return a[key] == b[key];
}
} |
JavaScript | function checkEqualityCaseSensitive(a, b, key) {
if (a[key] instanceof Array) {
return (a[key].indexOf(b[key]) != -1) ? true : false;
}
else {
return a[key].toLowerCase() == b[key].toLowerCase();
}
} | function checkEqualityCaseSensitive(a, b, key) {
if (a[key] instanceof Array) {
return (a[key].indexOf(b[key]) != -1) ? true : false;
}
else {
return a[key].toLowerCase() == b[key].toLowerCase();
}
} |
JavaScript | function assert(target, predicateObj) {
//The function counts the number of properties in an object
function countProps(obj) {
var count = 0;
for (var index in obj) {
count++;
}
return count;
}
//The function recursively matches properties between the two
//objects
function recursiveInspect(target, obj, isEqual) {
//Check if the object is empty
if (countProps(obj) == 0) {
//log.debug('empty object');
return true;
}
else {
//Go through each property
for (var key in obj) {
//Check if the target's property is a predicate
if (target.hasOwnProperty(key)) {
//Check if it is an object
if (countProps(target[key]) > 0) {
isEqual = recursiveInspect(target[key], obj[key]);
}
else {
//isEqual=(obj[key]==target[key]);
isEqual = checkEquality(obj, target, key);
}
}
else {
//If the target does not have the property then it cannot be equal
return false;
}
//Check if the object is not equal
if (!isEqual) {
return false;
}
}
return true;
}
}
return recursiveInspect(target, predicateObj, true);
} | function assert(target, predicateObj) {
//The function counts the number of properties in an object
function countProps(obj) {
var count = 0;
for (var index in obj) {
count++;
}
return count;
}
//The function recursively matches properties between the two
//objects
function recursiveInspect(target, obj, isEqual) {
//Check if the object is empty
if (countProps(obj) == 0) {
//log.debug('empty object');
return true;
}
else {
//Go through each property
for (var key in obj) {
//Check if the target's property is a predicate
if (target.hasOwnProperty(key)) {
//Check if it is an object
if (countProps(target[key]) > 0) {
isEqual = recursiveInspect(target[key], obj[key]);
}
else {
//isEqual=(obj[key]==target[key]);
isEqual = checkEquality(obj, target, key);
}
}
else {
//If the target does not have the property then it cannot be equal
return false;
}
//Check if the object is not equal
if (!isEqual) {
return false;
}
}
return true;
}
}
return recursiveInspect(target, predicateObj, true);
} |
JavaScript | function countProps(obj) {
var count = 0;
for (var index in obj) {
count++;
}
return count;
} | function countProps(obj) {
var count = 0;
for (var index in obj) {
count++;
}
return count;
} |
JavaScript | function assertCaseSensitive(target, predicateObj) {
//The function counts the number of properties in an object
function countProps(obj) {
var count = 0;
for (var index in obj) {
count++;
}
return count;
}
//The function recursively matches properties between the two
//objects
function recursiveInspect(target, obj, isEqual) {
//Check if the object is empty
if (countProps(obj) == 0) {
//log.debug('empty object');
return true;
}
else {
//Go through each property
for (var key in obj) {
//Check if the target's property is a predicate
if (target.hasOwnProperty(key)) {
//Check if it is an object
if (countProps(target[key]) > 0) {
isEqual = recursiveInspect(target[key], obj[key]);
}
else {
//isEqual=(obj[key]==target[key]);
isEqual = checkEqualityCaseSensitive(obj, target, key);
}
}
else {
//If the target does not have the property then it cannot be equal
return false;
}
//Check if the object is not equal
if (!isEqual) {
return false;
}
}
return true;
}
}
return recursiveInspect(target, predicateObj, true);
} | function assertCaseSensitive(target, predicateObj) {
//The function counts the number of properties in an object
function countProps(obj) {
var count = 0;
for (var index in obj) {
count++;
}
return count;
}
//The function recursively matches properties between the two
//objects
function recursiveInspect(target, obj, isEqual) {
//Check if the object is empty
if (countProps(obj) == 0) {
//log.debug('empty object');
return true;
}
else {
//Go through each property
for (var key in obj) {
//Check if the target's property is a predicate
if (target.hasOwnProperty(key)) {
//Check if it is an object
if (countProps(target[key]) > 0) {
isEqual = recursiveInspect(target[key], obj[key]);
}
else {
//isEqual=(obj[key]==target[key]);
isEqual = checkEqualityCaseSensitive(obj, target, key);
}
}
else {
//If the target does not have the property then it cannot be equal
return false;
}
//Check if the object is not equal
if (!isEqual) {
return false;
}
}
return true;
}
}
return recursiveInspect(target, predicateObj, true);
} |
JavaScript | function sortLevel(level, map) {
var nodes;
var node;
//Check if the map has the indicated level
if (!map.hasOwnProperty(level)) {
return;
}
//Get the nodes in the indicated level
nodes = map[level];
//Go through each node
for (var index = 0; index < nodes.length; index++) {
node = nodes[index];
//Go through the rest of the node starting from the index
for (var indexCompare = 0; indexCompare < nodes.length ; indexCompare++) {
//Sort the levels in descending order
if (node.distance > nodes[indexCompare].distance) {
swap(index,indexCompare,nodes);
}
}
}
} | function sortLevel(level, map) {
var nodes;
var node;
//Check if the map has the indicated level
if (!map.hasOwnProperty(level)) {
return;
}
//Get the nodes in the indicated level
nodes = map[level];
//Go through each node
for (var index = 0; index < nodes.length; index++) {
node = nodes[index];
//Go through the rest of the node starting from the index
for (var indexCompare = 0; indexCompare < nodes.length ; indexCompare++) {
//Sort the levels in descending order
if (node.distance > nodes[indexCompare].distance) {
swap(index,indexCompare,nodes);
}
}
}
} |
JavaScript | function swap(a, b, array) {
var temp = array[a];
array[a] = array[b];
array[b] = temp;
} | function swap(a, b, array) {
var temp = array[a];
array[a] = array[b];
array[b] = temp;
} |
JavaScript | function isNodePresent(label, nodes) {
var node;
for (var index in nodes) {
node = nodes[index];
if (node.label == label) {
return true;
}
}
return false;
} | function isNodePresent(label, nodes) {
var node;
for (var index in nodes) {
node = nodes[index];
if (node.label == label) {
return true;
}
}
return false;
} |
JavaScript | function isConnected(a, b, matrix) {
if(!matrix.hasOwnProperty(a.label)){
return false;
}
if (matrix[a.label].hasOwnProperty(b.label)) {
if (matrix[a.label][b.label] == 1) {
return true;
}
}
return false;
} | function isConnected(a, b, matrix) {
if(!matrix.hasOwnProperty(a.label)){
return false;
}
if (matrix[a.label].hasOwnProperty(b.label)) {
if (matrix[a.label][b.label] == 1) {
return true;
}
}
return false;
} |
JavaScript | function drawArrowHead(a,b,paper,matrix){
var angle;
var arrow;
//Check if there is an arrow from a-> b
if(checkDoubleArrow(a,b,matrix)){
angle = Math.atan2(b.y - a.y, b.x - a.x);
angle = angle * (180 / Math.PI);
drawArrow({x: (b.x+ a.x)/2, y: (b.y+ a.y)/2, angle: angle}, paper);
}
//Check if there is an arrow from b -> a
if(checkDoubleArrow(b,a,matrix)){
angle = Math.atan2(a.y - b.y, a.x - b.x);
angle = angle * (180 / Math.PI);
drawArrow({x: (a.x+ b.x)/2, y: (a.y+ b.y)/2, angle: angle}, paper);
}
} | function drawArrowHead(a,b,paper,matrix){
var angle;
var arrow;
//Check if there is an arrow from a-> b
if(checkDoubleArrow(a,b,matrix)){
angle = Math.atan2(b.y - a.y, b.x - a.x);
angle = angle * (180 / Math.PI);
drawArrow({x: (b.x+ a.x)/2, y: (b.y+ a.y)/2, angle: angle}, paper);
}
//Check if there is an arrow from b -> a
if(checkDoubleArrow(b,a,matrix)){
angle = Math.atan2(a.y - b.y, a.x - b.x);
angle = angle * (180 / Math.PI);
drawArrow({x: (a.x+ b.x)/2, y: (a.y+ b.y)/2, angle: angle}, paper);
}
} |
JavaScript | function checkDoubleArrow(a,b,matrix){
if(!matrix.hasOwnProperty(a.label)){
return false;
}
if(matrix[a.label].hasOwnProperty(b.label)) {
return true;
}
return false;
} | function checkDoubleArrow(a,b,matrix){
if(!matrix.hasOwnProperty(a.label)){
return false;
}
if(matrix[a.label].hasOwnProperty(b.label)) {
return true;
}
return false;
} |
JavaScript | function drawArrow(options, paper) {
var x = options.x;
var y = options.y;
var width = options.width || 4;
var height = options.height || 8;
var angle = options.angle || null;
var attributes = options.attributes || {fill: '#647E9A', stroke:'#647E9A'};
var rotateX = x;
var rotateY = y;
var path = [];
path.push('M');
path.push(x);
path.push(y);
path.push('L');
path.push(x - height);
path.push(y - width);
path.push('L');
path.push(x - height);
path.push(y + width);
path.push('L');
path.push(x);
path.push(y);
var pathString = path.join(',');
var pathInstance = paper.path(pathString);
//Attempt to apply all the attributes
for (var index in attributes) {
pathInstance.attr(index, attributes[index]);
}
//Rotate the arrow by the provided angle
if (angle) {
pathInstance.rotate(angle, rotateX, rotateY);
}
} | function drawArrow(options, paper) {
var x = options.x;
var y = options.y;
var width = options.width || 4;
var height = options.height || 8;
var angle = options.angle || null;
var attributes = options.attributes || {fill: '#647E9A', stroke:'#647E9A'};
var rotateX = x;
var rotateY = y;
var path = [];
path.push('M');
path.push(x);
path.push(y);
path.push('L');
path.push(x - height);
path.push(y - width);
path.push('L');
path.push(x - height);
path.push(y + width);
path.push('L');
path.push(x);
path.push(y);
var pathString = path.join(',');
var pathInstance = paper.path(pathString);
//Attempt to apply all the attributes
for (var index in attributes) {
pathInstance.attr(index, attributes[index]);
}
//Rotate the arrow by the provided angle
if (angle) {
pathInstance.rotate(angle, rotateX, rotateY);
}
} |
JavaScript | function layout(matrix, levels) {
var sink = findHighestSinks(matrix);
var connected = keys;
for (var key in connected) {
//Calculate the path distance for each connection
var path = calculatePath(matrix, sink, connected[key]);
if (path < 0) {
path = calculatePath(matrix, connected[key], sink);
}
levels.add(connected[key], path + 1);
}
return levels;
} | function layout(matrix, levels) {
var sink = findHighestSinks(matrix);
var connected = keys;
for (var key in connected) {
//Calculate the path distance for each connection
var path = calculatePath(matrix, sink, connected[key]);
if (path < 0) {
path = calculatePath(matrix, connected[key], sink);
}
levels.add(connected[key], path + 1);
}
return levels;
} |
JavaScript | function retrieve(context){
$.ajax({
url: context.url,
type: 'GET',
success: function (response) {
var respObj=JSON.parse(response);
if(respObj.cachedAssets.length){
var recentTmplComp = Handlebars.compile(recentTmpl);
$('.asset-being-added').html(recentTmplComp(respObj)).slideDown();
}
if(respObj.cachedAssetsBefore!=respObj.cachedAssetsAfter){
window.location='/publisher/assets/'+context.type+'/';
}
},
error: function (e) {
showMessage('Unable to retrieve new assets');
}
});
} | function retrieve(context){
$.ajax({
url: context.url,
type: 'GET',
success: function (response) {
var respObj=JSON.parse(response);
if(respObj.cachedAssets.length){
var recentTmplComp = Handlebars.compile(recentTmpl);
$('.asset-being-added').html(recentTmplComp(respObj)).slideDown();
}
if(respObj.cachedAssetsBefore!=respObj.cachedAssetsAfter){
window.location='/publisher/assets/'+context.type+'/';
}
},
error: function (e) {
showMessage('Unable to retrieve new assets');
}
});
} |
JavaScript | function obtainMetaInformation() {
//Obtain the current url
var url = window.location.pathname;
//The type of asset
var type = $('#meta-asset-type').val();
//The id
//Break the url into components
var comps = url.split('/');
//Given a url of the form /pub/api/asset/{asset-type}/{asset-id}
//length=5
//then: length-2 = {asset-type} length-1 = {asset-id}
//var id=comps[comps.length-1];
var type = comps[comps.length - 2];
var url = CACHE_URL + type;
return {
type: type,
url: url
}
} | function obtainMetaInformation() {
//Obtain the current url
var url = window.location.pathname;
//The type of asset
var type = $('#meta-asset-type').val();
//The id
//Break the url into components
var comps = url.split('/');
//Given a url of the form /pub/api/asset/{asset-type}/{asset-id}
//length=5
//then: length-2 = {asset-type} length-1 = {asset-id}
//var id=comps[comps.length-1];
var type = comps[comps.length - 2];
var url = CACHE_URL + type;
return {
type: type,
url: url
}
} |
JavaScript | function minMaxAvgGraph(xscale) {
this.minArray = new Array();
this.maxArray = new Array();
this.avgArray = new Array();
for (var i = 0; i < xscale; i++) {
this.minArray[i] = [i, 0.0];
}
for (var j = 0; j < xscale; j++) {
this.maxArray[j] = [j, 0.0];
}
for (var k = 0; k < xscale; k++) {
this.avgArray[k] = [k, 0.0];
}
this.xscale = xscale;
} | function minMaxAvgGraph(xscale) {
this.minArray = new Array();
this.maxArray = new Array();
this.avgArray = new Array();
for (var i = 0; i < xscale; i++) {
this.minArray[i] = [i, 0.0];
}
for (var j = 0; j < xscale; j++) {
this.maxArray[j] = [j, 0.0];
}
for (var k = 0; k < xscale; k++) {
this.avgArray[k] = [k, 0.0];
}
this.xscale = xscale;
} |
JavaScript | function parseFileName(url){
var fileName=determineOS(url);
//log.info('file name:'+fileName);
return fileName;
} | function parseFileName(url){
var fileName=determineOS(url);
//log.info('file name:'+fileName);
return fileName;
} |
JavaScript | function determineOS(path){
var components=path.split('\\');
if(components.length>1){
return obtainFromWindowsPath(components);
}
return obtainFromOtherOSPath(path);
} | function determineOS(path){
var components=path.split('\\');
if(components.length>1){
return obtainFromWindowsPath(components);
}
return obtainFromOtherOSPath(path);
} |
JavaScript | function obtainFromWindowsPath(path){
//log.info('windows path:'+fileName);
var fileName=path[path.length-1];
return fileName;
} | function obtainFromWindowsPath(path){
//log.info('windows path:'+fileName);
var fileName=path[path.length-1];
return fileName;
} |
JavaScript | function obtainFromOtherOSPath(path){
var comps=path.split('/');
//log.info('other os: '+comps);
if(comps.length<=1){
return comps[FIRST_ELEMENT];
}
return comps[comps.length-1];
} | function obtainFromOtherOSPath(path){
var comps=path.split('/');
//log.info('other os: '+comps);
if(comps.length<=1){
return comps[FIRST_ELEMENT];
}
return comps[comps.length-1];
} |
JavaScript | function processResponse(resp, code, content) {
resp.status = code;
resp.contentType = 'application/json';
resp.content = content;
return resp;
} | function processResponse(resp, code, content) {
resp.status = code;
resp.contentType = 'application/json';
resp.content = content;
return resp;
} |
JavaScript | function addFile(fileObj) {
var tenantId = fileObj.tenantId || carbon.server.superTenant.tenantId;
var registry = es.server.systemRegistry(tenantId);
var resource = {};
resource.content = fileObj.file.getStream();
var extension = ref.getExtension(fileObj.file);
resource.mediaType = ref.getMimeType(extension);
log.info("Extension of the inserting file is " + extension);
log.info("Media type of the inserting file is " + resource.mediaType);
resource.uuid = uuid.generate();
resource.name = fileObj.file.getName();
resource.properties = {};
resource.properties.extension = extension;
var pathSuffix = fileObj.type + "/" + fileObj.assetId + "/" + fileObj.fieldName;
var path = pathPrefix + pathSuffix;
registry.put(path, resource);
return fileObj.fieldName;
} | function addFile(fileObj) {
var tenantId = fileObj.tenantId || carbon.server.superTenant.tenantId;
var registry = es.server.systemRegistry(tenantId);
var resource = {};
resource.content = fileObj.file.getStream();
var extension = ref.getExtension(fileObj.file);
resource.mediaType = ref.getMimeType(extension);
log.info("Extension of the inserting file is " + extension);
log.info("Media type of the inserting file is " + resource.mediaType);
resource.uuid = uuid.generate();
resource.name = fileObj.file.getName();
resource.properties = {};
resource.properties.extension = extension;
var pathSuffix = fileObj.type + "/" + fileObj.assetId + "/" + fileObj.fieldName;
var path = pathPrefix + pathSuffix;
registry.put(path, resource);
return fileObj.fieldName;
} |
JavaScript | function isPermitted(session) {
//Obtain the session and check if there is a user
var user = require('store').server.current(session);
if (user) {
return true;
}
return false;
} | function isPermitted(session) {
//Obtain the session and check if there is a user
var user = require('store').server.current(session);
if (user) {
return true;
}
return false;
} |
JavaScript | function onSecurityCheckFail() {
var app = require('rxt').app;
var context = app.getContext();
log.debug('security check failed redirecting...');
response.sendRedirect(context + '/login');
} | function onSecurityCheckFail() {
var app = require('rxt').app;
var context = app.getContext();
log.debug('security check failed redirecting...');
response.sendRedirect(context + '/login');
} |
JavaScript | function selectAll(schema, predicate) {
var query = 'SELECT * FROM {1}; ';
return query;
} | function selectAll(schema, predicate) {
var query = 'SELECT * FROM {1}; ';
return query;
} |
JavaScript | function checkIfTableExists(schema) {
var tableName = schema.table.toUpperCase();
var query = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='" + tableName + "' AND TABLE_SCHEMA='PUBLIC'; ";
//log.debug('checking if table exists '+query);
return query;
} | function checkIfTableExists(schema) {
var tableName = schema.table.toUpperCase();
var query = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='" + tableName + "' AND TABLE_SCHEMA='PUBLIC'; ";
//log.debug('checking if table exists '+query);
return query;
} |
JavaScript | function isHandled(object){
//We check for the exsistence of an attributes property
if(object.hasOwnProperty('attributes')){
return true;
}
log.debug('the object: '+stringify(object)+' is not handled.');
} | function isHandled(object){
//We check for the exsistence of an attributes property
if(object.hasOwnProperty('attributes')){
return true;
}
log.debug('the object: '+stringify(object)+' is not handled.');
} |
JavaScript | function handle(context){
var object=context.object||{};
var config=context.config;
var fields=config.storeFields;
var field;
var uuid;
var path;
for(var index in fields){
//Current field been examined
field=fields[index];
//log.debug(field);
utility.isPresent(object.attributes,field,function(){
//Get the value of the current field
path=object.attributes[field];
//Attempt to store
uuid=addToStorage(path,context);
//Update value
if(uuid){
object.attributes[field]=uuid;
}
});
}
//log.debug(object);
return true;
} | function handle(context){
var object=context.object||{};
var config=context.config;
var fields=config.storeFields;
var field;
var uuid;
var path;
for(var index in fields){
//Current field been examined
field=fields[index];
//log.debug(field);
utility.isPresent(object.attributes,field,function(){
//Get the value of the current field
path=object.attributes[field];
//Attempt to store
uuid=addToStorage(path,context);
//Update value
if(uuid){
object.attributes[field]=uuid;
}
});
}
//log.debug(object);
return true;
} |
JavaScript | function addToStorage(path,context){
var file=new File(path);
var uuid=null;
//log.debug('examining path: '+path);
//Only add it storage if it is a valid path and get the uuid
if(file.isExists()){
log.debug('loaded resource '+path+' into storage.');
uuid=useStorageManager(path,file,context);
}
return uuid
} | function addToStorage(path,context){
var file=new File(path);
var uuid=null;
//log.debug('examining path: '+path);
//Only add it storage if it is a valid path and get the uuid
if(file.isExists()){
log.debug('loaded resource '+path+' into storage.');
uuid=useStorageManager(path,file,context);
}
return uuid
} |
JavaScript | function onAssetInitialization(context) {
log.debug('reading configuration data from ' + context.bundle.getName() + ' [json].');
//obtain the configuration file
var configFile = context.bundle.get({extension: 'json'}).result();
//If the configuration file does not exist then stop.
if (!configFile) {
log.debug('unable to load configuration file for ' + context.bundle.getName());
context['stopProcessing'] = true;
return;
}
//Read the contents
var configContents = configFile.getContents();
var jsonConfig = parse(configContents);
//Clone the object but ignore tags and rate
var artifact = utility.cloneObject(jsonConfig, ['tags', 'rate']);
artifact.attributes.images_thumbnail = context.assetPath + artifact.attributes.images_thumbnail;
artifact.attributes.images_banner = context.assetPath + artifact.attributes.images_banner;
//artifact.attributes.overview_url=context.assetPath+artifact.attributes.overview_url;
//artifact.attributes.images_thumbnail = context.httpContext + artifact.attributes.images_thumbnail;
//artifact.attributes.images_banner = context.httpContext + artifact.attributes.images_banner;
//Create the deployment object
context['artifact'] = artifact;
//Set the tags
context['tags'] = jsonConfig.tags.split(',');
//Set the ratings
context['rate'] = jsonConfig.rate;
context['path'] = '/_system/governance/' + context.assetType + '/' + artifact.attributes.overview_provider +
'/' + artifact.attributes.overview_name + '/' + artifact.attributes.overview_version;
log.debug('tags located: ' + context.tags);
log.debug('rate located: ' + context.rate);
} | function onAssetInitialization(context) {
log.debug('reading configuration data from ' + context.bundle.getName() + ' [json].');
//obtain the configuration file
var configFile = context.bundle.get({extension: 'json'}).result();
//If the configuration file does not exist then stop.
if (!configFile) {
log.debug('unable to load configuration file for ' + context.bundle.getName());
context['stopProcessing'] = true;
return;
}
//Read the contents
var configContents = configFile.getContents();
var jsonConfig = parse(configContents);
//Clone the object but ignore tags and rate
var artifact = utility.cloneObject(jsonConfig, ['tags', 'rate']);
artifact.attributes.images_thumbnail = context.assetPath + artifact.attributes.images_thumbnail;
artifact.attributes.images_banner = context.assetPath + artifact.attributes.images_banner;
//artifact.attributes.overview_url=context.assetPath+artifact.attributes.overview_url;
//artifact.attributes.images_thumbnail = context.httpContext + artifact.attributes.images_thumbnail;
//artifact.attributes.images_banner = context.httpContext + artifact.attributes.images_banner;
//Create the deployment object
context['artifact'] = artifact;
//Set the tags
context['tags'] = jsonConfig.tags.split(',');
//Set the ratings
context['rate'] = jsonConfig.rate;
context['path'] = '/_system/governance/' + context.assetType + '/' + artifact.attributes.overview_provider +
'/' + artifact.attributes.overview_name + '/' + artifact.attributes.overview_version;
log.debug('tags located: ' + context.tags);
log.debug('rate located: ' + context.rate);
} |
JavaScript | function onCreateArtifactManager(context) {
//require configuration
var config = require('/config/publisher.json');
var username = config.user.username;
//Create a registry instance
var registry = new carbon.registry.Registry(server.instance(), {
username: username,
tenantId: SUPER_TENANT_ID
});
//Load the governance artifacts
GovernanceUtils.loadGovernanceArtifacts(registry.registry);
try {
//Create a new artifact manager
var artifactManager = new carbon.registry.ArtifactManager(registry, context.assetType);
} catch (e) {
log.debug('unable to create artifactManager of type: ' + context.assetType);
return;
}
var userManager = server.userManager(SUPER_TENANT_ID);
context['artifactManager'] = artifactManager;
context['registry'] = registry;
context['userManager'] = userManager;
log.debug('created artifact manager for ' + context.assetType);
} | function onCreateArtifactManager(context) {
//require configuration
var config = require('/config/publisher.json');
var username = config.user.username;
//Create a registry instance
var registry = new carbon.registry.Registry(server.instance(), {
username: username,
tenantId: SUPER_TENANT_ID
});
//Load the governance artifacts
GovernanceUtils.loadGovernanceArtifacts(registry.registry);
try {
//Create a new artifact manager
var artifactManager = new carbon.registry.ArtifactManager(registry, context.assetType);
} catch (e) {
log.debug('unable to create artifactManager of type: ' + context.assetType);
return;
}
var userManager = server.userManager(SUPER_TENANT_ID);
context['artifactManager'] = artifactManager;
context['registry'] = registry;
context['userManager'] = userManager;
log.debug('created artifact manager for ' + context.assetType);
} |
JavaScript | function onSetAssetPermissions(context) {
var userManager = context.userManager;
//log.debug('anon role: '+carbon.user.anonRole);
log.debug('giving anon role GET rights to ' + context.path);
userManager.authorizeRole(carbon.user.anonRole, context.path, carbon.registry.actions.GET);
} | function onSetAssetPermissions(context) {
var userManager = context.userManager;
//log.debug('anon role: '+carbon.user.anonRole);
log.debug('giving anon role GET rights to ' + context.path);
userManager.authorizeRole(carbon.user.anonRole, context.path, carbon.registry.actions.GET);
} |
JavaScript | function checkAssetInRegistry(context) {
var artifactManager = context.artifactManager;
var artifact = context.artifact;
//Assume that the asset does not exist
context['isExisting'] = false;
//Check if the asset exists
var locatedAssets = artifactManager.find(function (asset) {
var attributes = asset.attributes;
//Check if the search index is present
if (attributes.hasOwnProperty(SEARCH_INDEX)) {
//Check if the search index values are the same
if (attributes[SEARCH_INDEX] == artifact.attributes[SEARCH_INDEX]) {
return true;
}
}
return false;
}, null);
//Check if any assets were located
if (locatedAssets.length > 0) {
log.debug('asset is present');
context['isExisting'] = true;
context['currentAsset'] = locatedAssets[0];
}
} | function checkAssetInRegistry(context) {
var artifactManager = context.artifactManager;
var artifact = context.artifact;
//Assume that the asset does not exist
context['isExisting'] = false;
//Check if the asset exists
var locatedAssets = artifactManager.find(function (asset) {
var attributes = asset.attributes;
//Check if the search index is present
if (attributes.hasOwnProperty(SEARCH_INDEX)) {
//Check if the search index values are the same
if (attributes[SEARCH_INDEX] == artifact.attributes[SEARCH_INDEX]) {
return true;
}
}
return false;
}, null);
//Check if any assets were located
if (locatedAssets.length > 0) {
log.debug('asset is present');
context['isExisting'] = true;
context['currentAsset'] = locatedAssets[0];
}
} |
JavaScript | function onAddAsset(context) {
var artifactManager = context.artifactManager;
var artifact = context.artifact;
var name = artifact.attributes.overview_name;
var social = carbon.server.osgiService('org.wso2.carbon.social.core.service.SocialActivityService');
//Add the asset
log.debug('about to add the asset : ' + artifact.name);
var assetId = artifactManager.add(artifact);
if(artifact.id == undefined || artifact.id == null || artifact.id == '') {
artifact.id = assetId;
}
//Store any resources in the Storage Manager
context.dataInjector.inject(artifact, context.dataInjectorModes.STORAGE);
artifact.attributes.images_banner = 'images_banner';
artifact.attributes.images_thumbnail = 'images_thumbnail';
artifactManager.update(artifact);
var assets = artifactManager.find(function (adapter) {
return (adapter.attributes.overview_name == name) ? true : false;
}, null);
context['currentAsset'] = assets[0] || null;
//log.debug('added asset: ' + stringify(context.currentAsset));
try{
social.warmUpRatingCache(context.currentAsset.type + ':' + context.currentAsset.id);
}catch(e){
log.warn("Unable to publish the asset: " + context.currentAsset.type + ":" + context.currentAsset.id + " to social cache. This may affect on sort by popularity function.");
}
//addToSocialCache(context.currentAsset);
//log.debug('finished');
} | function onAddAsset(context) {
var artifactManager = context.artifactManager;
var artifact = context.artifact;
var name = artifact.attributes.overview_name;
var social = carbon.server.osgiService('org.wso2.carbon.social.core.service.SocialActivityService');
//Add the asset
log.debug('about to add the asset : ' + artifact.name);
var assetId = artifactManager.add(artifact);
if(artifact.id == undefined || artifact.id == null || artifact.id == '') {
artifact.id = assetId;
}
//Store any resources in the Storage Manager
context.dataInjector.inject(artifact, context.dataInjectorModes.STORAGE);
artifact.attributes.images_banner = 'images_banner';
artifact.attributes.images_thumbnail = 'images_thumbnail';
artifactManager.update(artifact);
var assets = artifactManager.find(function (adapter) {
return (adapter.attributes.overview_name == name) ? true : false;
}, null);
context['currentAsset'] = assets[0] || null;
//log.debug('added asset: ' + stringify(context.currentAsset));
try{
social.warmUpRatingCache(context.currentAsset.type + ':' + context.currentAsset.id);
}catch(e){
log.warn("Unable to publish the asset: " + context.currentAsset.type + ":" + context.currentAsset.id + " to social cache. This may affect on sort by popularity function.");
}
//addToSocialCache(context.currentAsset);
//log.debug('finished');
} |
JavaScript | function onUpdateAsset(context) {
var artifactManager = context.artifactManager;
var currentAsset = context.currentAsset;
var artifact = context.artifact;
//Set the id
artifact.id = currentAsset.id;
//Disable createdtime update of a default asset
artifact.attributes.overview_createdtime = currentAsset.attributes.overview_createdtime;
//Store any resources in the Storage Manager
context.dataInjector.inject(artifact, context.dataInjectorModes.STORAGE);
artifactManager.update(artifact);
//log.debug('finished updating the artifact : '+currentAsset.name);
} | function onUpdateAsset(context) {
var artifactManager = context.artifactManager;
var currentAsset = context.currentAsset;
var artifact = context.artifact;
//Set the id
artifact.id = currentAsset.id;
//Disable createdtime update of a default asset
artifact.attributes.overview_createdtime = currentAsset.attributes.overview_createdtime;
//Store any resources in the Storage Manager
context.dataInjector.inject(artifact, context.dataInjectorModes.STORAGE);
artifactManager.update(artifact);
//log.debug('finished updating the artifact : '+currentAsset.name);
} |
JavaScript | function onAttachLifecycle(context) {
var artifactManager = context.artifactManager;
var currentAsset = context.currentAsset;
var currentLifeCycleName = currentAsset.lifecycle || null;
var currentLifeCycleState = currentAsset.lifecycleState || null;
var attempts = 0;
log.debug('attaching lifecycle to: '+currentAsset.attributes.overview_name);
log.debug('current lifecycle: ' + currentLifeCycleName + ' , current state: ' + currentLifeCycleState);
//Check if a lifecycle has been attached
if (!currentLifeCycleName) {
log.debug('before calling current asset ' + DEFAULT_LIFECYCLE);
log.debug(currentAsset);
//Attach the lifecycle
artifactManager.attachLifecycle(DEFAULT_LIFECYCLE, currentAsset);
//Update the current asset
currentAsset = artifactManager.get(currentAsset.id);
}
else {
//We skip moving to the Published state.
log.debug('skipping promotion operations as a lifecycle has been attached');
return;
}
//Try to reach the desired life-cycle state before the attempt limit
while ((currentLifeCycleState != DESIRED_LIFECYCLE_STATE) && (attempts < PROMOTE_COUNT)) {
artifactManager.promoteLifecycleState(INVOKED_OPERATION, currentAsset);
//Update the current life-cycle state.
currentLifeCycleState = artifactManager.getLifecycleState(currentAsset);
//Increase the attempts by one
attempts++;
log.debug('current lifecycle state: ' + currentLifeCycleState);
}
log.debug('final state of : '+currentAsset.attributes.overview_name+' '+currentLifeCycleState);
} | function onAttachLifecycle(context) {
var artifactManager = context.artifactManager;
var currentAsset = context.currentAsset;
var currentLifeCycleName = currentAsset.lifecycle || null;
var currentLifeCycleState = currentAsset.lifecycleState || null;
var attempts = 0;
log.debug('attaching lifecycle to: '+currentAsset.attributes.overview_name);
log.debug('current lifecycle: ' + currentLifeCycleName + ' , current state: ' + currentLifeCycleState);
//Check if a lifecycle has been attached
if (!currentLifeCycleName) {
log.debug('before calling current asset ' + DEFAULT_LIFECYCLE);
log.debug(currentAsset);
//Attach the lifecycle
artifactManager.attachLifecycle(DEFAULT_LIFECYCLE, currentAsset);
//Update the current asset
currentAsset = artifactManager.get(currentAsset.id);
}
else {
//We skip moving to the Published state.
log.debug('skipping promotion operations as a lifecycle has been attached');
return;
}
//Try to reach the desired life-cycle state before the attempt limit
while ((currentLifeCycleState != DESIRED_LIFECYCLE_STATE) && (attempts < PROMOTE_COUNT)) {
artifactManager.promoteLifecycleState(INVOKED_OPERATION, currentAsset);
//Update the current life-cycle state.
currentLifeCycleState = artifactManager.getLifecycleState(currentAsset);
//Increase the attempts by one
attempts++;
log.debug('current lifecycle state: ' + currentLifeCycleState);
}
log.debug('final state of : '+currentAsset.attributes.overview_name+' '+currentLifeCycleState);
} |
JavaScript | function onSetTags(context) {
var tags = context.tags;
log.debug('adding tags [' + context.tags + '] to path ' + context.path);
//Go through all tags
for (tag in tags) {
//Check if the tag is present
if (tags.hasOwnProperty(tag)) {
context.registry.tag(context.path, tags[tag]);
}
}
log.debug('finished adding tags');
} | function onSetTags(context) {
var tags = context.tags;
log.debug('adding tags [' + context.tags + '] to path ' + context.path);
//Go through all tags
for (tag in tags) {
//Check if the tag is present
if (tags.hasOwnProperty(tag)) {
context.registry.tag(context.path, tags[tag]);
}
}
log.debug('finished adding tags');
} |
JavaScript | function onSetRatings(context) {
var rate = context.rate;
log.debug('adding rating : ' + context.rate + ' to path ' + context.path);
if (!rate) {
context.registry.rate(context.path, rate);
}
} | function onSetRatings(context) {
var rate = context.rate;
log.debug('adding rating : ' + context.rate + ' to path ' + context.path);
if (!rate) {
context.registry.rate(context.path, rate);
}
} |
JavaScript | function onAttachLifecycle(context) {
var artifactManager = context.artifactManager;
var currentAsset = context.currentAsset;
var currentLifeCycleName = currentAsset.lifecycle || null;
var currentLifeCycleState = currentAsset.lifecycleState || null;
var attempts = 0;
log.debug('attaching lifecycle to: ' + currentAsset.attributes.overview_name);
log.debug('current lifecycle: ' + currentLifeCycleName + ' , current state: ' + currentLifeCycleState);
//Check if a lifecycle has been attached
if (!currentLifeCycleName) {
log.debug('before calling current asset ' + DEFAULT_LIFECYCLE);
log.debug(currentAsset);
//Attach the lifecycle
artifactManager.attachLifecycle(DEFAULT_LIFECYCLE, currentAsset);
//Update the current asset
currentAsset = artifactManager.get(currentAsset.id);
}
else {
//We skip moving to the Published state.
log.debug('skipping promotion operations as a lifecycle has been attached');
return;
}
log.debug('attempting to execute the robot path: '+stringify(pathToDesiredState));
executeRobotPath(pathToDesiredState,artifactManager,currentAsset);
log.debug('finished executing robot path');
//Try to reach the desired life-cycle state before the attempt limit
/*while ((currentLifeCycleState != DESIRED_LIFECYCLE_STATE) && (attempts < PROMOTE_COUNT)) {
artifactManager.promoteLifecycleState(INVOKED_OPERATION, currentAsset);
//Update the current life-cycle state.
currentLifeCycleState = artifactManager.getLifecycleState(currentAsset);
//Increase the attempts by one
attempts++;
log.debug('current lifecycle state: ' + currentLifeCycleState);
}
log.debug('final state of : ' + currentAsset.attributes.overview_name + ' ' + currentLifeCycleState); */
} | function onAttachLifecycle(context) {
var artifactManager = context.artifactManager;
var currentAsset = context.currentAsset;
var currentLifeCycleName = currentAsset.lifecycle || null;
var currentLifeCycleState = currentAsset.lifecycleState || null;
var attempts = 0;
log.debug('attaching lifecycle to: ' + currentAsset.attributes.overview_name);
log.debug('current lifecycle: ' + currentLifeCycleName + ' , current state: ' + currentLifeCycleState);
//Check if a lifecycle has been attached
if (!currentLifeCycleName) {
log.debug('before calling current asset ' + DEFAULT_LIFECYCLE);
log.debug(currentAsset);
//Attach the lifecycle
artifactManager.attachLifecycle(DEFAULT_LIFECYCLE, currentAsset);
//Update the current asset
currentAsset = artifactManager.get(currentAsset.id);
}
else {
//We skip moving to the Published state.
log.debug('skipping promotion operations as a lifecycle has been attached');
return;
}
log.debug('attempting to execute the robot path: '+stringify(pathToDesiredState));
executeRobotPath(pathToDesiredState,artifactManager,currentAsset);
log.debug('finished executing robot path');
//Try to reach the desired life-cycle state before the attempt limit
/*while ((currentLifeCycleState != DESIRED_LIFECYCLE_STATE) && (attempts < PROMOTE_COUNT)) {
artifactManager.promoteLifecycleState(INVOKED_OPERATION, currentAsset);
//Update the current life-cycle state.
currentLifeCycleState = artifactManager.getLifecycleState(currentAsset);
//Increase the attempts by one
attempts++;
log.debug('current lifecycle state: ' + currentLifeCycleState);
}
log.debug('final state of : ' + currentAsset.attributes.overview_name + ' ' + currentLifeCycleState); */
} |
JavaScript | function create(schema) {
var query = dbScriptManager.find(H2_DRIVER, schema.table);
return query;
} | function create(schema) {
var query = dbScriptManager.find(H2_DRIVER, schema.table);
return query;
} |
JavaScript | function dependencyStream(indexes, options) {
var md = mdeps({
filter: function (id) {
return !!options.external || moduleFilters.internalOnly(id);
},
transform: options.transform,
postFilter: moduleFilters.externals(indexes, options)
});
indexes.forEach(function (index) {
md.write(path.resolve(index));
});
md.end();
return md;
} | function dependencyStream(indexes, options) {
var md = mdeps({
filter: function (id) {
return !!options.external || moduleFilters.internalOnly(id);
},
transform: options.transform,
postFilter: moduleFilters.externals(indexes, options)
});
indexes.forEach(function (index) {
md.write(path.resolve(index));
});
md.end();
return md;
} |
JavaScript | function detectNumberSeparators() {
var n = 1000.50;
var l = n.toLocaleString();
var s = n.toString();
var o = {
decimal: l.substring(5,6),
thousands: l.substring(1,2)
};
if (l.substring(5,6) == s.substring(5,6)) {
o.decimal = ".";
}
if (l.substring(1,2) == s.substring(1,2)) {
o.thousands = ",";
}
return o;
} | function detectNumberSeparators() {
var n = 1000.50;
var l = n.toLocaleString();
var s = n.toString();
var o = {
decimal: l.substring(5,6),
thousands: l.substring(1,2)
};
if (l.substring(5,6) == s.substring(5,6)) {
o.decimal = ".";
}
if (l.substring(1,2) == s.substring(1,2)) {
o.thousands = ",";
}
return o;
} |
JavaScript | function inferHierarchy(comments) {
var nameIndex = {}, i;
// We're going to iterate comments in reverse to generate the memberships so
// to avoid reversing the sort order we reverse the array for the name index.
comments.reverse();
// First, create a fast lookup index of Namespace names
// that might be used in memberof tags, and let all objects
// have members
for (i = 0; i < comments.length; i++) {
nameIndex[comments[i].name] = comments[i];
comments[i].members = { instance: [], static: [] };
}
for (i = comments.length - 1; i >= 0; i--) {
if (comments[i].memberof) {
if (nameIndex[comments[i].memberof]) {
if (comments[i].scope) {
nameIndex[comments[i].memberof].members[comments[i].scope].push(comments[i]);
// remove non-root nodes from the lowest level: these are reachable
// as members of other docs.
comments.splice(i, 1);
} else {
console.error('found memberof but no @scope, @static, or @instance tag');
}
} else {
console.error('memberof reference to %s not found', comments[i].memberof);
}
}
}
// Now the members are in the right order but the root comments are reversed
// so we reverse once more.
comments.reverse();
/**
* Add paths to each comment, making it possible to generate permalinks
* that differentiate between instance functions with the same name but
* different `@memberof` values.
*
* @param {Object} comment the jsdoc comment
* @param {Array<String>} prefix an array of strings representing names
* @returns {undefined} changes its input by reference.
*/
function addPath(comment, prefix) {
comment.path = prefix.concat([comment.name]);
comment.members.instance.forEach(function (member) {
addPath(member, comment.path);
});
comment.members.static.forEach(function (member) {
addPath(member, comment.path);
});
}
for (i = 0; i < comments.length; i++) addPath(comments[i], []);
return comments;
} | function inferHierarchy(comments) {
var nameIndex = {}, i;
// We're going to iterate comments in reverse to generate the memberships so
// to avoid reversing the sort order we reverse the array for the name index.
comments.reverse();
// First, create a fast lookup index of Namespace names
// that might be used in memberof tags, and let all objects
// have members
for (i = 0; i < comments.length; i++) {
nameIndex[comments[i].name] = comments[i];
comments[i].members = { instance: [], static: [] };
}
for (i = comments.length - 1; i >= 0; i--) {
if (comments[i].memberof) {
if (nameIndex[comments[i].memberof]) {
if (comments[i].scope) {
nameIndex[comments[i].memberof].members[comments[i].scope].push(comments[i]);
// remove non-root nodes from the lowest level: these are reachable
// as members of other docs.
comments.splice(i, 1);
} else {
console.error('found memberof but no @scope, @static, or @instance tag');
}
} else {
console.error('memberof reference to %s not found', comments[i].memberof);
}
}
}
// Now the members are in the right order but the root comments are reversed
// so we reverse once more.
comments.reverse();
/**
* Add paths to each comment, making it possible to generate permalinks
* that differentiate between instance functions with the same name but
* different `@memberof` values.
*
* @param {Object} comment the jsdoc comment
* @param {Array<String>} prefix an array of strings representing names
* @returns {undefined} changes its input by reference.
*/
function addPath(comment, prefix) {
comment.path = prefix.concat([comment.name]);
comment.members.instance.forEach(function (member) {
addPath(member, comment.path);
});
comment.members.static.forEach(function (member) {
addPath(member, comment.path);
});
}
for (i = 0; i < comments.length; i++) addPath(comments[i], []);
return comments;
} |
JavaScript | function addPath(comment, prefix) {
comment.path = prefix.concat([comment.name]);
comment.members.instance.forEach(function (member) {
addPath(member, comment.path);
});
comment.members.static.forEach(function (member) {
addPath(member, comment.path);
});
} | function addPath(comment, prefix) {
comment.path = prefix.concat([comment.name]);
comment.members.instance.forEach(function (member) {
addPath(member, comment.path);
});
comment.members.static.forEach(function (member) {
addPath(member, comment.path);
});
} |
JavaScript | function autolink(text) {
if (paths.indexOf(slug(text)) !== -1) {
return '<a href="#' + slug(text) + '">' + text + '</a>';
} else if (getGlobalExternalLink(text)) {
return '<a href="' + getGlobalExternalLink(text) + '">' + text + '</a>';
}
return text;
} | function autolink(text) {
if (paths.indexOf(slug(text)) !== -1) {
return '<a href="#' + slug(text) + '">' + text + '</a>';
} else if (getGlobalExternalLink(text)) {
return '<a href="' + getGlobalExternalLink(text) + '">' + text + '</a>';
}
return text;
} |
JavaScript | function createClient(cache, opt = {}) {
return new ApolloClient(Object.assign({
// FIXME
link: createHttpLink({ uri: "http://localhost:8081/graphql" }),
cache
}, config.apolloClientOptions, opt));
} | function createClient(cache, opt = {}) {
return new ApolloClient(Object.assign({
// FIXME
link: createHttpLink({ uri: "http://localhost:8081/graphql" }),
cache
}, config.apolloClientOptions, opt));
} |
JavaScript | async function viewAllEmployees() {
// waits for findAllEmployees action to run before looking at next line of code
let allEmployees = await db.findAllEmployees();
console.table(allEmployees);
loadMainPrompts();
} | async function viewAllEmployees() {
// waits for findAllEmployees action to run before looking at next line of code
let allEmployees = await db.findAllEmployees();
console.table(allEmployees);
loadMainPrompts();
} |
JavaScript | function captureScreenFn() {
AR.logger.info("captureScreen called ...");
if (World.initialized) {
document.location = "architectsdk://button?action=captureScreen";
}
} | function captureScreenFn() {
AR.logger.info("captureScreen called ...");
if (World.initialized) {
document.location = "architectsdk://button?action=captureScreen";
}
} |
JavaScript | function encryptFile(blob, fileName, contentType, ID, callback, token) {
var fileExt = getFileExtension(fileName);
// Get session settings
var encrypt = $('#encrypt').is(':checked');
// Start the file reader
var reader = new FileReader();
// When the file has been loaded, encrypt it
reader.onload = (function (callback) {
return function (e) {
// Just send straight to server if they don't want to encrypt it
if (!encrypt) {
callback(e.target.result, null, null, contentType, fileExt, ID, encrypt, token);
}
else {
// Set variables for tracking
var lastTime = (new Date()).getTime();
var lastData = 0;
// Create random key and iv (divide size by 8 for character length)
var keyStr = randomString((keySize / 8), '#aA');
var ivStr = randomString((blockSize / 8), '#aA');
var worker = new Worker(GenerateBlobURL(encScriptSrc));
worker.addEventListener('message', function (e) {
switch (e.data.cmd) {
case 'progress':
var curTime = (new Date()).getTime();
var elapsedTime = (curTime - lastTime) / 1000;
if (elapsedTime >= 0.1) {
var speed = ((e.data.processed - lastData) / elapsedTime);
lastTime = curTime;
lastData = e.data.processed;
var percentComplete = Math.round(e.data.processed * 100 / e.data.total);
setProgress(ID, percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Encrypting [' + getReadableFileSizeString(e.data.processed) + ' / ' + getReadableFileSizeString(e.data.total) + ' @ ' + getReadableBandwidthString(speed * 8) + ']');
}
break;
case 'finish':
if (callback != null) {
// Finish
callback(e.data.buffer, keyStr, ivStr, contentType, fileExt, ID, encrypt, token);
}
break;
}
});
worker.onerror = function (err) {
uploadFailed(ID, token, err);
}
token.callback = function () { // SPECIFY CANCELLATION
worker.terminate(); // terminate the worker process
uploadCanceled(ID, token, null);
};
// Generate the script to include as a blob
var scriptBlob = GenerateBlobURL(aesScriptSrc);
// Execute worker with data
var objData =
{
cmd: 'encrypt',
script: scriptBlob,
key: keyStr,
iv: ivStr,
chunkSize: chunkSize,
file: e.target.result
};
worker.postMessage(objData, [objData.file]);
}
};
})(callback);
reader.onerror = function (err) {
uploadFailed(ID, token, err);
}
reader.onprogress = function(data) {
if (data.lengthComputable) {
var progress = parseInt(((data.loaded / data.total) * 100), 10);
setProgress(ID, progress, 'progress-bar-success progress-bar-striped active', progress + '%', 'Loading');
}
};
reader.onabort = function() {
uploadCanceled(ID, token, null);
};
token.callback = function () { // SPECIFY CANCELLATION
reader.abort(); // abort request
};
// Start async read
reader.readAsArrayBuffer(blob);
} | function encryptFile(blob, fileName, contentType, ID, callback, token) {
var fileExt = getFileExtension(fileName);
// Get session settings
var encrypt = $('#encrypt').is(':checked');
// Start the file reader
var reader = new FileReader();
// When the file has been loaded, encrypt it
reader.onload = (function (callback) {
return function (e) {
// Just send straight to server if they don't want to encrypt it
if (!encrypt) {
callback(e.target.result, null, null, contentType, fileExt, ID, encrypt, token);
}
else {
// Set variables for tracking
var lastTime = (new Date()).getTime();
var lastData = 0;
// Create random key and iv (divide size by 8 for character length)
var keyStr = randomString((keySize / 8), '#aA');
var ivStr = randomString((blockSize / 8), '#aA');
var worker = new Worker(GenerateBlobURL(encScriptSrc));
worker.addEventListener('message', function (e) {
switch (e.data.cmd) {
case 'progress':
var curTime = (new Date()).getTime();
var elapsedTime = (curTime - lastTime) / 1000;
if (elapsedTime >= 0.1) {
var speed = ((e.data.processed - lastData) / elapsedTime);
lastTime = curTime;
lastData = e.data.processed;
var percentComplete = Math.round(e.data.processed * 100 / e.data.total);
setProgress(ID, percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Encrypting [' + getReadableFileSizeString(e.data.processed) + ' / ' + getReadableFileSizeString(e.data.total) + ' @ ' + getReadableBandwidthString(speed * 8) + ']');
}
break;
case 'finish':
if (callback != null) {
// Finish
callback(e.data.buffer, keyStr, ivStr, contentType, fileExt, ID, encrypt, token);
}
break;
}
});
worker.onerror = function (err) {
uploadFailed(ID, token, err);
}
token.callback = function () { // SPECIFY CANCELLATION
worker.terminate(); // terminate the worker process
uploadCanceled(ID, token, null);
};
// Generate the script to include as a blob
var scriptBlob = GenerateBlobURL(aesScriptSrc);
// Execute worker with data
var objData =
{
cmd: 'encrypt',
script: scriptBlob,
key: keyStr,
iv: ivStr,
chunkSize: chunkSize,
file: e.target.result
};
worker.postMessage(objData, [objData.file]);
}
};
})(callback);
reader.onerror = function (err) {
uploadFailed(ID, token, err);
}
reader.onprogress = function(data) {
if (data.lengthComputable) {
var progress = parseInt(((data.loaded / data.total) * 100), 10);
setProgress(ID, progress, 'progress-bar-success progress-bar-striped active', progress + '%', 'Loading');
}
};
reader.onabort = function() {
uploadCanceled(ID, token, null);
};
token.callback = function () { // SPECIFY CANCELLATION
reader.abort(); // abort request
};
// Start async read
reader.readAsArrayBuffer(blob);
} |
JavaScript | function outputAges(age, homeplanet) {
if(setUnits=='Seconds'){
var earthYears = age / 31557600;
} else if(setUnits=='Days'){
var earthYears = age / 365.25;
} else {
var earthYears = planets[homeplanet] * age;
}
var tableData = '';
Object.keys(planets).forEach(function (key) {
tableData += '<p class="' + key.toLowerCase() + '"><span>' + (earthYears / planets[key]).toPrecision(5) + '</span><span class="planet"> ' + key + '</span> years' + '</a>';
});
console.log(tableData);
document.getElementById('results').innerHTML = tableData;
} | function outputAges(age, homeplanet) {
if(setUnits=='Seconds'){
var earthYears = age / 31557600;
} else if(setUnits=='Days'){
var earthYears = age / 365.25;
} else {
var earthYears = planets[homeplanet] * age;
}
var tableData = '';
Object.keys(planets).forEach(function (key) {
tableData += '<p class="' + key.toLowerCase() + '"><span>' + (earthYears / planets[key]).toPrecision(5) + '</span><span class="planet"> ' + key + '</span> years' + '</a>';
});
console.log(tableData);
document.getElementById('results').innerHTML = tableData;
} |
JavaScript | function updateDisplay(info) {
display.innerHTML = info;
} | function updateDisplay(info) {
display.innerHTML = info;
} |
JavaScript | function enableDisabled(){
var planetButtons = document.getElementsByClassName('planet');
for(var i = 0; i < planetButtons.length; i++){
planetButtons[i].classList.remove('disabled');
}
} | function enableDisabled(){
var planetButtons = document.getElementsByClassName('planet');
for(var i = 0; i < planetButtons.length; i++){
planetButtons[i].classList.remove('disabled');
}
} |
JavaScript | function clearScreens() {
numericString = '';
display.innerHTML = '';
units.innerHTML = '';
document.getElementById('results').innerHTML = 'Results will appear here...';
document.getElementById('planet').className = "";
enablePlaceholder();
enableDisabled();
} | function clearScreens() {
numericString = '';
display.innerHTML = '';
units.innerHTML = '';
document.getElementById('results').innerHTML = 'Results will appear here...';
document.getElementById('planet').className = "";
enablePlaceholder();
enableDisabled();
} |
JavaScript | function hackEventWithinDoPostBack() {
var originalEventDescriptor = Object.getOwnPropertyDescriptor(Window.prototype, "event");
var hackEventVariable = false;
var eventPropertyHolder;
Object.defineProperty(window, "event", {
configurable: true,
get: function get() {
var result = originalEventDescriptor ? originalEventDescriptor.get.apply(this, arguments) : eventPropertyHolder;
if (result || !hackEventVariable)
return result;
return {};
},
set: function set(value) {
if (originalEventDescriptor)
originalEventDescriptor.set.apply(this, arguments);
else
eventPropertyHolder = value;
}
});
var originalDoPostBack = window.__doPostBack;
window.__doPostBack = function hackedDoPostBack() {
hackEventVariable = true;
originalDoPostBack.apply(this, arguments);
hackEventVariable = false;
};
} | function hackEventWithinDoPostBack() {
var originalEventDescriptor = Object.getOwnPropertyDescriptor(Window.prototype, "event");
var hackEventVariable = false;
var eventPropertyHolder;
Object.defineProperty(window, "event", {
configurable: true,
get: function get() {
var result = originalEventDescriptor ? originalEventDescriptor.get.apply(this, arguments) : eventPropertyHolder;
if (result || !hackEventVariable)
return result;
return {};
},
set: function set(value) {
if (originalEventDescriptor)
originalEventDescriptor.set.apply(this, arguments);
else
eventPropertyHolder = value;
}
});
var originalDoPostBack = window.__doPostBack;
window.__doPostBack = function hackedDoPostBack() {
hackEventVariable = true;
originalDoPostBack.apply(this, arguments);
hackEventVariable = false;
};
} |
JavaScript | function docReady() {
var host = window.location.host;
var shellSocket = new WebSocket("ws://" + host + "/hello/socket");
shellSocket.onmessage = function (event) {
console.log(event);
document.getElementById("reply_result").innerHTML = event.data;
};
} | function docReady() {
var host = window.location.host;
var shellSocket = new WebSocket("ws://" + host + "/hello/socket");
shellSocket.onmessage = function (event) {
console.log(event);
document.getElementById("reply_result").innerHTML = event.data;
};
} |
JavaScript | function docReady() {
var ansi_up = new AnsiUp;
var host = window.location.host;
var shellSocket = new WebSocket("ws://" + host + "/shell/socket");
shellSocket.onmessage = function (event) {
var html = ansi_up.ansi_to_html(event.data);
document.getElementById("console_output").innerHTML = html;
};
shellSocket.onopen = function (event) {
shellSocket.send("lb");
};
document.getElementById("command_button").onclick = function() {
input = document.getElementById("command_input").value;
document.getElementById("command_input").value = "";
shellSocket.send(input);
};
var input = document.getElementById("command_input");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.key === "Enter") {
document.getElementById("command_button").click();
}
});
} | function docReady() {
var ansi_up = new AnsiUp;
var host = window.location.host;
var shellSocket = new WebSocket("ws://" + host + "/shell/socket");
shellSocket.onmessage = function (event) {
var html = ansi_up.ansi_to_html(event.data);
document.getElementById("console_output").innerHTML = html;
};
shellSocket.onopen = function (event) {
shellSocket.send("lb");
};
document.getElementById("command_button").onclick = function() {
input = document.getElementById("command_input").value;
document.getElementById("command_input").value = "";
shellSocket.send(input);
};
var input = document.getElementById("command_input");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.key === "Enter") {
document.getElementById("command_button").click();
}
});
} |
JavaScript | function render_canvas(canvas_id) {
var node = document.getElementById('canvas-'+canvas_id);
if (node.title) {
var hash = CryptoJS.SHA1(node.title);
var code = (hash.words[0] << 24) | (hash.words[1] << 16) |
(hash.words[2] << 8) | hash.words[3];
if (node.style.display == 'none') node.style.display = "inline";
var size = node.width || 48;
render_identicon(node, code, size);
}
} | function render_canvas(canvas_id) {
var node = document.getElementById('canvas-'+canvas_id);
if (node.title) {
var hash = CryptoJS.SHA1(node.title);
var code = (hash.words[0] << 24) | (hash.words[1] << 16) |
(hash.words[2] << 8) | hash.words[3];
if (node.style.display == 'none') node.style.display = "inline";
var size = node.width || 48;
render_identicon(node, code, size);
}
} |
JavaScript | refreshTransactions() {
if (!(this.lastSnappedTo < BlueApp.getWallets().length) && this.lastSnappedTo !== undefined) {
// last card, nop
console.log('last card, nop');
return;
}
this.setState(
{
isFlatListRefreshControlHidden: false,
},
() => {
InteractionManager.runAfterInteractions(async () => {
let noErr = true;
try {
await BlueElectrum.ping();
await BlueElectrum.waitTillConnected();
let balanceStart = +new Date();
await BlueApp.fetchWalletBalances(this.lastSnappedTo || 0);
let balanceEnd = +new Date();
console.log('fetch balance took', (balanceEnd - balanceStart) / 1000, 'sec');
let start = +new Date();
await BlueApp.fetchWalletTransactions(this.lastSnappedTo || 0);
let end = +new Date();
console.log('fetch tx took', (end - start) / 1000, 'sec');
} catch (err) {
noErr = false;
console.warn(err);
}
if (noErr) await BlueApp.saveToDisk(); // caching
this.redrawScreen();
});
},
);
} | refreshTransactions() {
if (!(this.lastSnappedTo < BlueApp.getWallets().length) && this.lastSnappedTo !== undefined) {
// last card, nop
console.log('last card, nop');
return;
}
this.setState(
{
isFlatListRefreshControlHidden: false,
},
() => {
InteractionManager.runAfterInteractions(async () => {
let noErr = true;
try {
await BlueElectrum.ping();
await BlueElectrum.waitTillConnected();
let balanceStart = +new Date();
await BlueApp.fetchWalletBalances(this.lastSnappedTo || 0);
let balanceEnd = +new Date();
console.log('fetch balance took', (balanceEnd - balanceStart) / 1000, 'sec');
let start = +new Date();
await BlueApp.fetchWalletTransactions(this.lastSnappedTo || 0);
let end = +new Date();
console.log('fetch tx took', (end - start) / 1000, 'sec');
} catch (err) {
noErr = false;
console.warn(err);
}
if (noErr) await BlueApp.saveToDisk(); // caching
this.redrawScreen();
});
},
);
} |
JavaScript | async lazyRefreshWallet(index) {
/** @type {Array.<AbstractWallet>} wallets */
let wallets = BlueApp.getWallets();
if (!wallets[index]) {
return;
}
let oldBalance = wallets[index].getBalance();
let noErr = true;
let didRefresh = false;
try {
if (wallets && wallets[index] && wallets[index].type !== PlaceholderWallet.type && wallets[index].timeToRefreshBalance()) {
console.log('snapped to, and now its time to refresh wallet #', index);
await wallets[index].fetchBalance();
if (oldBalance !== wallets[index].getBalance() || wallets[index].getUnconfirmedBalance() !== 0) {
console.log('balance changed, thus txs too');
// balance changed, thus txs too
await wallets[index].fetchTransactions();
this.redrawScreen();
didRefresh = true;
} else if (wallets[index].timeToRefreshTransaction()) {
console.log(wallets[index].getLabel(), 'thinks its time to refresh TXs');
await wallets[index].fetchTransactions();
if (wallets[index].fetchPendingTransactions) {
await wallets[index].fetchPendingTransactions();
}
if (wallets[index].fetchUserInvoices) {
await wallets[index].fetchUserInvoices();
await wallets[index].fetchBalance(); // chances are, paid ln invoice was processed during `fetchUserInvoices()` call and altered user's balance, so its worth fetching balance again
}
this.redrawScreen();
didRefresh = true;
} else {
console.log('balance not changed');
}
}
} catch (Err) {
noErr = false;
console.warn(Err);
}
if (noErr && didRefresh) {
await BlueApp.saveToDisk(); // caching
}
} | async lazyRefreshWallet(index) {
/** @type {Array.<AbstractWallet>} wallets */
let wallets = BlueApp.getWallets();
if (!wallets[index]) {
return;
}
let oldBalance = wallets[index].getBalance();
let noErr = true;
let didRefresh = false;
try {
if (wallets && wallets[index] && wallets[index].type !== PlaceholderWallet.type && wallets[index].timeToRefreshBalance()) {
console.log('snapped to, and now its time to refresh wallet #', index);
await wallets[index].fetchBalance();
if (oldBalance !== wallets[index].getBalance() || wallets[index].getUnconfirmedBalance() !== 0) {
console.log('balance changed, thus txs too');
// balance changed, thus txs too
await wallets[index].fetchTransactions();
this.redrawScreen();
didRefresh = true;
} else if (wallets[index].timeToRefreshTransaction()) {
console.log(wallets[index].getLabel(), 'thinks its time to refresh TXs');
await wallets[index].fetchTransactions();
if (wallets[index].fetchPendingTransactions) {
await wallets[index].fetchPendingTransactions();
}
if (wallets[index].fetchUserInvoices) {
await wallets[index].fetchUserInvoices();
await wallets[index].fetchBalance(); // chances are, paid ln invoice was processed during `fetchUserInvoices()` call and altered user's balance, so its worth fetching balance again
}
this.redrawScreen();
didRefresh = true;
} else {
console.log('balance not changed');
}
}
} catch (Err) {
noErr = false;
console.warn(Err);
}
if (noErr && didRefresh) {
await BlueApp.saveToDisk(); // caching
}
} |
JavaScript | function isPostCode(toCheck) {
// Permitted letters depend upon their position in the postcode.
var alpha1 = "[abcdefghijklmnoprstuwyz]"; // Character 1
var alpha2 = "[abcdefghklmnopqrstuvwxy]"; // Character 2
var alpha3 = "[abcdefghjkpmnrstuvwxy]"; // Character 3
var alpha4 = "[abehmnprvwxy]"; // Character 4
var alpha5 = "[abdefghjlnpqrstuwxyz]"; // Character 5
var BFPOa5 = "[abdefghjlnpqrst]"; // BFPO alpha5
var BFPOa6 = "[abdefghjlnpqrstuwzyz]"; // BFPO alpha6
// Array holds the regular expressions for the valid postcodes
var pcexp = new Array();
// BFPO postcodes
pcexp.push(new RegExp("^(bf1)(\\s*)([0-6]{1}" + BFPOa5 + "{1}" + BFPOa6 + "{1})$", "i"));
// Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
pcexp.push(new RegExp("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
// Expression for postcodes: ANA NAA
pcexp.push(new RegExp("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
// Expression for postcodes: AANA NAA
pcexp.push(new RegExp("^(" + alpha1 + "{1}" + alpha2 + "{1}" + "?[0-9]{1}" + alpha4 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
// Exception for the special postcode GIR 0AA
pcexp.push(/^(GIR)(\s*)(0AA)$/i);
// Standard BFPO numbers
pcexp.push(/^(bfpo)(\s*)([0-9]{1,4})$/i);
// c/o BFPO numbers
pcexp.push(/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
// Overseas Territories
pcexp.push(/^([A-Z]{4})(\s*)(1ZZ)$/i);
// Anguilla
pcexp.push(/^(ai-2640)$/i);
// Load up the string to check
var postCode = toCheck;
// Assume we're not going to find a valid postcode
var valid = false;
// Check the string against the types of post codes
for (var i = 0; i < pcexp.length; i++) {
if (pcexp[i].test(postCode)) {
// The post code is valid - split the post code into component parts
pcexp[i].exec(postCode);
// Copy it back into the original string, converting it to uppercase and inserting a space
// between the inward and outward codes
postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
// If it is a BFPO c/o type postcode, tidy up the "c/o" part
postCode = postCode.replace(/C\/O\s*/, "c/o ");
// If it is the Anguilla overseas territory postcode, we need to treat it specially
if (toCheck.toUpperCase() == 'AI-2640') {
postCode = 'AI-2640'
};
// Load new postcode back into the form element
valid = true;
// Remember that we have found that the code is valid and break from loop
break;
}
}
// Return with either the reformatted valid postcode or the original invalid postcode
if (valid) {
return postCode;
} else
return false;
} | function isPostCode(toCheck) {
// Permitted letters depend upon their position in the postcode.
var alpha1 = "[abcdefghijklmnoprstuwyz]"; // Character 1
var alpha2 = "[abcdefghklmnopqrstuvwxy]"; // Character 2
var alpha3 = "[abcdefghjkpmnrstuvwxy]"; // Character 3
var alpha4 = "[abehmnprvwxy]"; // Character 4
var alpha5 = "[abdefghjlnpqrstuwxyz]"; // Character 5
var BFPOa5 = "[abdefghjlnpqrst]"; // BFPO alpha5
var BFPOa6 = "[abdefghjlnpqrstuwzyz]"; // BFPO alpha6
// Array holds the regular expressions for the valid postcodes
var pcexp = new Array();
// BFPO postcodes
pcexp.push(new RegExp("^(bf1)(\\s*)([0-6]{1}" + BFPOa5 + "{1}" + BFPOa6 + "{1})$", "i"));
// Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
pcexp.push(new RegExp("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
// Expression for postcodes: ANA NAA
pcexp.push(new RegExp("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
// Expression for postcodes: AANA NAA
pcexp.push(new RegExp("^(" + alpha1 + "{1}" + alpha2 + "{1}" + "?[0-9]{1}" + alpha4 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
// Exception for the special postcode GIR 0AA
pcexp.push(/^(GIR)(\s*)(0AA)$/i);
// Standard BFPO numbers
pcexp.push(/^(bfpo)(\s*)([0-9]{1,4})$/i);
// c/o BFPO numbers
pcexp.push(/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
// Overseas Territories
pcexp.push(/^([A-Z]{4})(\s*)(1ZZ)$/i);
// Anguilla
pcexp.push(/^(ai-2640)$/i);
// Load up the string to check
var postCode = toCheck;
// Assume we're not going to find a valid postcode
var valid = false;
// Check the string against the types of post codes
for (var i = 0; i < pcexp.length; i++) {
if (pcexp[i].test(postCode)) {
// The post code is valid - split the post code into component parts
pcexp[i].exec(postCode);
// Copy it back into the original string, converting it to uppercase and inserting a space
// between the inward and outward codes
postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
// If it is a BFPO c/o type postcode, tidy up the "c/o" part
postCode = postCode.replace(/C\/O\s*/, "c/o ");
// If it is the Anguilla overseas territory postcode, we need to treat it specially
if (toCheck.toUpperCase() == 'AI-2640') {
postCode = 'AI-2640'
};
// Load new postcode back into the form element
valid = true;
// Remember that we have found that the code is valid and break from loop
break;
}
}
// Return with either the reformatted valid postcode or the original invalid postcode
if (valid) {
return postCode;
} else
return false;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.