<commit_before>const Metrics = require('metrics-sharelatex')
const logger = require('logger-sharelatex')

Metrics.initialize('filestore')
logger.initialize('filestore')

const settings = require('settings-sharelatex')
const express = require('express')
const bodyParser = require('body-parser')

const fileController = require('./app/js/FileController')
const keyBuilder = require('./app/js/KeyBuilder')
const healthCheckController = require('./app/js/HealthCheckController')

const RequestLogger = require('./app/js/RequestLogger')

const app = express()

app.use(RequestLogger.middleware)

if (settings.sentry && settings.sentry.dsn) {
  logger.initializeErrorReporting(settings.sentry.dsn)
}

Metrics.open_sockets.monitor(logger)
Metrics.memory.monitor(logger)
if (Metrics.event_loop) {
  Metrics.event_loop.monitor(logger)
}

app.use(function(req, res, next) {
  Metrics.inc('http-request')
  next()
})

Metrics.injectMetricsRoute(app)

app.head(
  '/project/:project_id/file/:file_id',
  keyBuilder.userFileKeyMiddleware,
  fileController.getFileHead
)
app.get(
  '/project/:project_id/file/:file_id',
  keyBuilder.userFileKeyMiddleware,
  fileController.getFile
)
app.post(
  '/project/:project_id/file/:file_id',
  keyBuilder.userFileKeyMiddleware,
  fileController.insertFile
)
app.put(
  '/project/:project_id/file/:file_id',
  keyBuilder.userFileKeyMiddleware,
  bodyParser.json(),
  fileController.copyFile
)
app.delete(
  '/project/:project_id/file/:file_id',
  keyBuilder.userFileKeyMiddleware,
  fileController.deleteFile
)

app.head(
  '/template/:template_id/v/:version/:format',
  keyBuilder.templateFileKeyMiddleware,
  fileController.getFileHead
)
app.get(
  '/template/:template_id/v/:version/:format',
  keyBuilder.templateFileKeyMiddleware,
  fileController.getFile
)
app.get(
  '/template/:template_id/v/:version/:format/:sub_type',
  keyBuilder.templateFileKeyMiddleware,
  fileController.getFile
)
app.post(
  '/template/:template_id/v/:version/:format',
  keyBuilder.templateFileKeyMiddleware,
  fileController.insertFile
)

app.head(
  '/project/:project_id/public/:public_file_id',
  keyBuilder.publicFileKeyMiddleware,
  fileController.getFileHead
)
app.get(
  '/project/:project_id/public/:public_file_id',
  keyBuilder.publicFileKeyMiddleware,
  fileController.getFile
)
app.post(
  '/project/:project_id/public/:public_file_id',
  keyBuilder.publicFileKeyMiddleware,
  fileController.insertFile
)
app.put(
  '/project/:project_id/public/:public_file_id',
  keyBuilder.publicFileKeyMiddleware,
  bodyParser.json(),
  fileController.copyFile
)
app.delete(
  '/project/:project_id/public/:public_file_id',
  keyBuilder.publicFileKeyMiddleware,
  fileController.deleteFile
)

app.get(
  '/project/:project_id/size',
  keyBuilder.publicProjectKeyMiddleware,
  fileController.directorySize
)

app.get(
  '/bucket/:bucket/key/*',
  keyBuilder.bucketFileKeyMiddleware,
  fileController.getFile
)

app.get('/heapdump', (req, res, next) =>
  require('heapdump').writeSnapshot(
    '/tmp/' + Date.now() + '.filestore.heapsnapshot',
    (err, filename) => {
      if (err) {
        return next(err)
      }
      res.send(filename)
    }
  )
)

app.get('/status', function(req, res) {
  res.send('filestore sharelatex up')
})

app.get('/health_check', healthCheckController.check)

app.use(RequestLogger.errorHandler)

const port = settings.internal.filestore.port || 3009
const host = '0.0.0.0'

if (!module.parent) {
  // Called directly
  app.listen(port, host, error => {
    if (error) {
      logger.error('Error starting Filestore', error)
      throw error
    }
    logger.info(`Filestore starting up, listening on ${host}:${port}`)
  })
}

module.exports = app
<commit_msg>Write to error log on unhandled rejection/exception<commit_after>const Metrics = require('metrics-sharelatex')
const logger = require('logger-sharelatex')

Metrics.initialize('filestore')
logger.initialize('filestore')

const settings = require('settings-sharelatex')
const express = require('express')
const bodyParser = require('body-parser')

const fileController = require('./app/js/FileController')
const keyBuilder = require('./app/js/KeyBuilder')
const healthCheckController = require('./app/js/HealthCheckController')

const RequestLogger = require('./app/js/RequestLogger')

const app = express()

app.use(RequestLogger.middleware)

if (settings.sentry && settings.sentry.dsn) {
  logger.initializeErrorReporting(settings.sentry.dsn)
}

Metrics.open_sockets.monitor(logger)
Metrics.memory.monitor(logger)
if (Metrics.event_loop) {
  Metrics.event_loop.monitor(logger)
}

app.use(function(req, res, next) {
  Metrics.inc('http-request')
  next()
})

Metrics.injectMetricsRoute(app)

app.head(
  '/project/:project_id/file/:file_id',
  keyBuilder.userFileKeyMiddleware,
  fileController.getFileHead
)
app.get(
  '/project/:project_id/file/:file_id',
  keyBuilder.userFileKeyMiddleware,
  fileController.getFile
)
app.post(
  '/project/:project_id/file/:file_id',
  keyBuilder.userFileKeyMiddleware,
  fileController.insertFile
)
app.put(
  '/project/:project_id/file/:file_id',
  keyBuilder.userFileKeyMiddleware,
  bodyParser.json(),
  fileController.copyFile
)
app.delete(
  '/project/:project_id/file/:file_id',
  keyBuilder.userFileKeyMiddleware,
  fileController.deleteFile
)

app.head(
  '/template/:template_id/v/:version/:format',
  keyBuilder.templateFileKeyMiddleware,
  fileController.getFileHead
)
app.get(
  '/template/:template_id/v/:version/:format',
  keyBuilder.templateFileKeyMiddleware,
  fileController.getFile
)
app.get(
  '/template/:template_id/v/:version/:format/:sub_type',
  keyBuilder.templateFileKeyMiddleware,
  fileController.getFile
)
app.post(
  '/template/:template_id/v/:version/:format',
  keyBuilder.templateFileKeyMiddleware,
  fileController.insertFile
)

app.head(
  '/project/:project_id/public/:public_file_id',
  keyBuilder.publicFileKeyMiddleware,
  fileController.getFileHead
)
app.get(
  '/project/:project_id/public/:public_file_id',
  keyBuilder.publicFileKeyMiddleware,
  fileController.getFile
)
app.post(
  '/project/:project_id/public/:public_file_id',
  keyBuilder.publicFileKeyMiddleware,
  fileController.insertFile
)
app.put(
  '/project/:project_id/public/:public_file_id',
  keyBuilder.publicFileKeyMiddleware,
  bodyParser.json(),
  fileController.copyFile
)
app.delete(
  '/project/:project_id/public/:public_file_id',
  keyBuilder.publicFileKeyMiddleware,
  fileController.deleteFile
)

app.get(
  '/project/:project_id/size',
  keyBuilder.publicProjectKeyMiddleware,
  fileController.directorySize
)

app.get(
  '/bucket/:bucket/key/*',
  keyBuilder.bucketFileKeyMiddleware,
  fileController.getFile
)

app.get('/heapdump', (req, res, next) =>
  require('heapdump').writeSnapshot(
    '/tmp/' + Date.now() + '.filestore.heapsnapshot',
    (err, filename) => {
      if (err) {
        return next(err)
      }
      res.send(filename)
    }
  )
)

app.get('/status', function(req, res) {
  res.send('filestore sharelatex up')
})

app.get('/health_check', healthCheckController.check)

app.use(RequestLogger.errorHandler)

const port = settings.internal.filestore.port || 3009
const host = '0.0.0.0'

if (!module.parent) {
  // Called directly
  app.listen(port, host, error => {
    if (error) {
      logger.error('Error starting Filestore', error)
      throw error
    }
    logger.info(`Filestore starting up, listening on ${host}:${port}`)
  })
}

process
  .on('unhandledRejection', (reason, p) => {
    logger.err(reason, 'Unhandled Rejection at Promise', p)
  })
  .on('uncaughtException', err => {
    logger.err(err, 'Uncaught Exception thrown')
    process.exit(1)
  })

module.exports = app
<|endoftext|>


<commit_before>define(["angular", "qvangular", "qlik"], function(a, b, qlik) {

    "use strict";

    var settings = {
        URL_SPLIT_FRAGMENT: "/sense/app/"
    };

    b.service("linkerService", ["$q",
        function(q) {

            var appCache = {};
            appCache['currentApp'] = qlik.currApp();

            var config = {
                host: window.location.hostname,
                prefix: "/",
                port: window.location.port,
                isSecure: window.location.protocol === "https:",
                openWithoutData: true
            };

            return {

                getAppItems: function(apps) {

                    var appsToFind = [];

                    if (apps.app1 !== undefined && apps.app1.length > 0 && apps.app1Sheet.length > 0)
                        appsToFind.push({
                            app: apps.app1,
                            sheet: apps.app1Sheet
                        });
                    if (apps.app2 !== undefined && apps.app2.length > 0 && apps.app2Sheet.length > 0)
                        appsToFind.push({
                            app: apps.app2,
                            sheet: apps.app2Sheet
                        });
                    if (apps.app3 !== undefined && apps.app3.length > 0 && apps.app3Sheet.length > 0)
                        appsToFind.push({
                            app: apps.app3,
                            sheet: apps.app3Sheet
                        });
                    if (apps.app4 !== undefined && apps.app4.length > 0 && apps.app4Sheet.length > 0)
                        appsToFind.push({
                            app: apps.app4,
                            sheet: apps.app4Sheet
                        });
                    if (apps.app5 !== undefined && apps.app5.length > 0 && apps.app5Sheet.length > 0)
                        appsToFind.push({
                            app: apps.app5,
                            sheet: apps.app5Sheet
                        });

                    return appsToFind;
                },

                getApps: function(apps, ignoreIfCurrentApp) {

                    // build up a list of apps:
                    var appsToReturn = [], initialAppsToFind = this.getAppItems(apps);
                    var appsToFind = [];
                    var deferred = q.defer();
                    var responseCount = 0;

                    console.log(appCache['currentApp']);

                    // if( ignoreIfCurrentApp == true) {
                    //     // remove any items from appsToFind:
                    //     for(var initialLoop = 0; initialLoop < initialAppsToFind.length; initialLoop++)
                    //     {
                    //         console.log(initialAppsToFind[initialLoop]);
                    //     }
                    // } else {
                    //     appsToFind = initialAppsToFind.slice();
                    // }

                    appsToFind = initialAppsToFind.slice();

                    // get the apps list from the API:
                    qlik.getAppList(function(reply) {

                        // and now loop through to see if any are the ones we want:
                        a.forEach(appsToFind, function(currentAppToFind, key) {

                            // does it exist?
                            a.forEach(reply, function(qlikApp, qlikAppKey) {

                                if (currentAppToFind.app === qlikApp.qTitle) {

                                    // assign an image path for the app:
                                    if (typeof qlikApp.qMeta.thumbnail !== 'undefined' && qlikApp.qMeta.thumbnail !== "") {
                                        qlikApp.thumbnail = qlikApp.qMeta.thumbnail;
                                    } else {
                                        qlikApp.thumbnail = '/extensions/AppLinker/img/app.png';
                                    }

                                    // add the sheet:
                                    qlikApp.sheet = currentAppToFind.sheet;

                                    appsToReturn.push(qlikApp);
                                }
                            });
                        });

                        // now get the details for the found apps:
                        ///////////////////////////////////////////////////////////////////////////////////////////

                        a.forEach(appsToReturn, function(qlikApp, qlikAppKey) {

                            // get the apps and cache:
                            //var app = qlik.openApp(qlikApp.qDocId, config);

                            var app = qlik.openApp(qlikApp.qDocId);

                            appCache[qlikApp.qDocId] = app;
                        });

                        // now get details:
                        a.forEach(appsToReturn, function(qlikApp, qlikAppKey){
                            var items = [];

                            appCache[qlikApp.qDocId].getList("FieldList", function(reply) {

                                a.forEach(reply.qFieldList.qItems, function(item, key) {
                                    items.push(item.qName);

                                   // console.log(item.qName);
                                });

                              //  console.log("************************************");

                                qlikApp.selectableItems = items;

                                responseCount++;

                                if (responseCount == appsToReturn.length) {
                                    deferred.resolve(appsToReturn);
                                }
                            });
                        });

                        ///////////////////////////////////////////////////////////////////////////////////////////
                    });

                    return deferred.promise;
                },
                ///////////////////////////////////////////////////////////////////////////////////////////
                openApp: function(currentUrl, appId, sheet) {

                    var urlPrefix = currentUrl.substr(0, currentUrl.indexOf(settings.URL_SPLIT_FRAGMENT)) + settings.URL_SPLIT_FRAGMENT;

                    window.open(urlPrefix + encodeURIComponent(appId) + '/sheet/' + sheet + '/state/analysis');
                },
                ///////////////////////////////////////////////////////////////////////////////////////////
                getSelectedItemKeys: function() {

                    var deferred = q.defer();
                    var app = appCache['currentApp'],
                        //qlik.currApp(),
                        dict = [];

                    app.getList("CurrentSelections", function(reply) {

                        var selections = [];

                        // this gives us the name of the field:
                        a.forEach(reply.qSelectionObject.qSelections, function(value, key) {

                            var qField = value.qField;

                            if( qField.indexOf("=[", 0) == 0) {
                                // remove first two characters and last:
                                // =[Qlik.Partner] => Qlik.Partner
                                qField = qField.substring(2, qField.length - 1);
                            }

                            selections.push(qField);
                        });

                        deferred.resolve(selections);

                    });

                    return deferred.promise;
                },
                ///////////////////////////////////////////////////////////////////////////////////////////
                getSelections: function() {

                    var deferred = q.defer();
                    var app = appCache['currentApp'],
                        //qlik.currApp(),
                        dict = [];

                    app.getList("CurrentSelections", function(reply) {

                        var selections = [];

                        // this gives us the name of the field:
                        a.forEach(reply.qSelectionObject.qSelections, function(value, key) {
                            selections.push(value.qField);

                            //console.log("Selection: ", value.qField);
                        });

                        // are there any selections?:
                        if (selections.length === 0) {
                            // nothing to return since there are no selections:
                            deferred.resolve(undefined);
                        } else {

                            var responseCount = 0;

                            a.forEach(selections, function(currentFieldName, i) {

                                var currentSelectedValues = [];
                                var qFieldDefs = [];
                                qFieldDefs.push(currentFieldName);

                                var query = {
                                    "qDef": {
                                        "qFieldDefs": qFieldDefs
                                    },
                                    "qInitialDataFetch": [{
                                        qTop: 0,
                                        qLeft: 0,
                                        qHeight: 500,
                                        qWidth: 1
                                    }]
                                };

                                app.createList(query, function(reply) {

                                    responseCount++;

                                    $.each(reply.qListObject.qDataPages[0].qMatrix, function(key, value) {

                                        if (value[0].qState === "S") {
                                            currentSelectedValues.push(value[0].qText);
                                        }
                                    });

                                    dict.push({
                                        key: currentFieldName,
                                        values: currentSelectedValues
                                    });

                                    if (responseCount == selections.length) {

                                        // return the dictionary:
                                        deferred.resolve(dict);
                                    }
                                });
                            });
                        }
                    });

                    return deferred.promise;
                },
                ///////////////////////////////////////////////////////////////////////////////////////////
                makeSelections: function(appId, dict) {

                    var deferred = q.defer();

                    config.identity = Math.random().toString(36).substring(2, 10);
                    var appSelections = qlik.openApp(appId, config);

                    console.log("Opening app with config of: ", config);
                    //var appSelections = appCache[appId];

                    if (dict == null)
                        return;

                    var responseCount = 0;
                    var selectionDict = [];

                    // initially, clear all selections in the app:
                    appSelections.clearAll();

                    // we have a dict, so work with it:
                    // array of:
                    // { key : 'Country', values : ['China', 'Russian Federation'] }
                    a.forEach(dict, function(value, key) {

                        // get the field list for the current value.key (which is the selection identifier):
                        var qFieldDefs = [];
                        qFieldDefs.push(value.key);

                        var query = {
                            "qDef": {
                                "qFieldDefs": qFieldDefs
                            },
                            "qInitialDataFetch": [{
                                qTop: 0,
                                qLeft: 0,
                                qHeight: 500,
                                qWidth: 1
                            }]
                        };

                        appSelections.createList(query, function(reply) {

                            responseCount++;

                            var qElemNumbers = [];

                            $.each(reply.qListObject.qDataPages[0].qMatrix, function(listKey, listValue) {

                                $.each(value.values, function(selectionKey, selectionValue) {

                                    if (selectionValue === listValue[0].qText) {
                                        qElemNumbers.push(listValue[0].qElemNumber);
                                    }

                                });
                            });

                            selectionDict.push({
                                key: value.key,
                                values: qElemNumbers
                            });

                            if (responseCount == dict.length) {

                                $.each(selectionDict, function(i, currentFieldDetails) {
                                    appSelections.field(currentFieldDetails.key).select(currentFieldDetails.values, true, true);
                                });

                                // all done:
                                deferred.resolve();

                            }
                        });
                    });

                    return deferred.promise;
                },

                intersect: function(a, b) {
                    var d = {};
                    var results = [];

                    if (typeof a !== "undefined" && typeof b !== "undefined") {

                        for (var i = 0; i < b.length; i++) {
                            d[b[i]] = true;
                        }
                        for (var j = 0; j < a.length; j++) {
                            if (d[a[j]]){

                                //console.log("Intersected: ", a[j]);

                                results.push({
                                    fieldName : a[j],
                                    isTransferable : true
                                });

                            } else {

                                //console.log("Not intersected: ", a[j]);

                                results.push({
                                    fieldName : a[j],
                                    isTransferable : false
                                });

                            }
                        }

                    }

                    return results;
                },

                getTransferableCount: function(items) {

                    var transferableCount = 0;

                    for(var itemLoop = 0; itemLoop < items.length; itemLoop++)
                    {
                        if( items[itemLoop].isTransferable === true){
                            transferableCount += 1;
                        }
                    }

                    return transferableCount;
                }
            }
        }
    ])
});
<commit_msg>Rewriting function to avoid writing 5 if conditions<commit_after>define(["angular", "qvangular", "qlik"], function(a, b, qlik) {

    "use strict";

    var settings = {
        URL_SPLIT_FRAGMENT: "/sense/app/"
    };

    b.service("linkerService", ["$q",
        function(q) {

            var appCache = {};
            appCache['currentApp'] = qlik.currApp();

            var config = {
                host: window.location.hostname,
                prefix: "/",
                port: window.location.port,
                isSecure: window.location.protocol === "https:",
                openWithoutData: true
            };

            return {

                getAppItems: function(apps) {
                    var appsToFind = [];
                    var maxNumberApps = 5;
                    var app, sheet;

                    for(var i=1; i<=maxNumberApps; i++) {
                          app = apps['app' + i];
                          sheet = apps['app' + i + 'Sheet'];

                          if(app !== undefined && app.length > 0 && sheet.length > 0){
                              appsToFind.push({ app: app, sheet: sheet });
                          }
                    }
                    return appsToFind;
                },

                getApps: function(apps, ignoreIfCurrentApp) {

                    // build up a list of apps:
                    var appsToReturn = [], initialAppsToFind = this.getAppItems(apps);
                    var appsToFind = [];
                    var deferred = q.defer();
                    var responseCount = 0;

                    console.log(appCache['currentApp']);

                    // if( ignoreIfCurrentApp == true) {
                    //     // remove any items from appsToFind:
                    //     for(var initialLoop = 0; initialLoop < initialAppsToFind.length; initialLoop++)
                    //     {
                    //         console.log(initialAppsToFind[initialLoop]);
                    //     }
                    // } else {
                    //     appsToFind = initialAppsToFind.slice();
                    // }

                    appsToFind = initialAppsToFind.slice();

                    // get the apps list from the API:
                    qlik.getAppList(function(reply) {

                        // and now loop through to see if any are the ones we want:
                        a.forEach(appsToFind, function(currentAppToFind, key) {

                            // does it exist?
                            a.forEach(reply, function(qlikApp, qlikAppKey) {

                                if (currentAppToFind.app === qlikApp.qTitle) {

                                    // assign an image path for the app:
                                    if (typeof qlikApp.qMeta.thumbnail !== 'undefined' && qlikApp.qMeta.thumbnail !== "") {
                                        qlikApp.thumbnail = qlikApp.qMeta.thumbnail;
                                    } else {
                                        qlikApp.thumbnail = '/extensions/AppLinker/img/app.png';
                                    }

                                    // add the sheet:
                                    qlikApp.sheet = currentAppToFind.sheet;

                                    appsToReturn.push(qlikApp);
                                }
                            });
                        });

                        // now get the details for the found apps:
                        ///////////////////////////////////////////////////////////////////////////////////////////

                        a.forEach(appsToReturn, function(qlikApp, qlikAppKey) {

                            // get the apps and cache:
                            //var app = qlik.openApp(qlikApp.qDocId, config);

                            var app = qlik.openApp(qlikApp.qDocId);

                            appCache[qlikApp.qDocId] = app;
                        });

                        // now get details:
                        a.forEach(appsToReturn, function(qlikApp, qlikAppKey){
                            var items = [];

                            appCache[qlikApp.qDocId].getList("FieldList", function(reply) {

                                a.forEach(reply.qFieldList.qItems, function(item, key) {
                                    items.push(item.qName);

                                   // console.log(item.qName);
                                });

                              //  console.log("************************************");

                                qlikApp.selectableItems = items;

                                responseCount++;

                                if (responseCount == appsToReturn.length) {
                                    deferred.resolve(appsToReturn);
                                }
                            });
                        });

                        ///////////////////////////////////////////////////////////////////////////////////////////
                    });

                    return deferred.promise;
                },
                ///////////////////////////////////////////////////////////////////////////////////////////
                openApp: function(currentUrl, appId, sheet) {

                    var urlPrefix = currentUrl.substr(0, currentUrl.indexOf(settings.URL_SPLIT_FRAGMENT)) + settings.URL_SPLIT_FRAGMENT;

                    window.open(urlPrefix + encodeURIComponent(appId) + '/sheet/' + sheet + '/state/analysis');
                },
                ///////////////////////////////////////////////////////////////////////////////////////////
                getSelectedItemKeys: function() {

                    var deferred = q.defer();
                    var app = appCache['currentApp'],
                        //qlik.currApp(),
                        dict = [];

                    app.getList("CurrentSelections", function(reply) {

                        var selections = [];

                        // this gives us the name of the field:
                        a.forEach(reply.qSelectionObject.qSelections, function(value, key) {

                            var qField = value.qField;

                            if( qField.indexOf("=[", 0) == 0) {
                                // remove first two characters and last:
                                // =[Qlik.Partner] => Qlik.Partner
                                qField = qField.substring(2, qField.length - 1);
                            }

                            selections.push(qField);
                        });

                        deferred.resolve(selections);

                    });

                    return deferred.promise;
                },
                ///////////////////////////////////////////////////////////////////////////////////////////
                getSelections: function() {

                    var deferred = q.defer();
                    var app = appCache['currentApp'],
                        //qlik.currApp(),
                        dict = [];

                    app.getList("CurrentSelections", function(reply) {

                        var selections = [];

                        // this gives us the name of the field:
                        a.forEach(reply.qSelectionObject.qSelections, function(value, key) {
                            selections.push(value.qField);

                            //console.log("Selection: ", value.qField);
                        });

                        // are there any selections?:
                        if (selections.length === 0) {
                            // nothing to return since there are no selections:
                            deferred.resolve(undefined);
                        } else {

                            var responseCount = 0;

                            a.forEach(selections, function(currentFieldName, i) {

                                var currentSelectedValues = [];
                                var qFieldDefs = [];
                                qFieldDefs.push(currentFieldName);

                                var query = {
                                    "qDef": {
                                        "qFieldDefs": qFieldDefs
                                    },
                                    "qInitialDataFetch": [{
                                        qTop: 0,
                                        qLeft: 0,
                                        qHeight: 500,
                                        qWidth: 1
                                    }]
                                };

                                app.createList(query, function(reply) {

                                    responseCount++;

                                    $.each(reply.qListObject.qDataPages[0].qMatrix, function(key, value) {

                                        if (value[0].qState === "S") {
                                            currentSelectedValues.push(value[0].qText);
                                        }
                                    });

                                    dict.push({
                                        key: currentFieldName,
                                        values: currentSelectedValues
                                    });

                                    if (responseCount == selections.length) {

                                        // return the dictionary:
                                        deferred.resolve(dict);
                                    }
                                });
                            });
                        }
                    });

                    return deferred.promise;
                },
                ///////////////////////////////////////////////////////////////////////////////////////////
                makeSelections: function(appId, dict) {

                    var deferred = q.defer();

                    config.identity = Math.random().toString(36).substring(2, 10);
                    var appSelections = qlik.openApp(appId, config);

                    console.log("Opening app with config of: ", config);
                    //var appSelections = appCache[appId];

                    if (dict == null)
                        return;

                    var responseCount = 0;
                    var selectionDict = [];

                    // initially, clear all selections in the app:
                    appSelections.clearAll();

                    // we have a dict, so work with it:
                    // array of:
                    // { key : 'Country', values : ['China', 'Russian Federation'] }
                    a.forEach(dict, function(value, key) {

                        // get the field list for the current value.key (which is the selection identifier):
                        var qFieldDefs = [];
                        qFieldDefs.push(value.key);

                        var query = {
                            "qDef": {
                                "qFieldDefs": qFieldDefs
                            },
                            "qInitialDataFetch": [{
                                qTop: 0,
                                qLeft: 0,
                                qHeight: 500,
                                qWidth: 1
                            }]
                        };

                        appSelections.createList(query, function(reply) {

                            responseCount++;

                            var qElemNumbers = [];

                            $.each(reply.qListObject.qDataPages[0].qMatrix, function(listKey, listValue) {

                                $.each(value.values, function(selectionKey, selectionValue) {

                                    if (selectionValue === listValue[0].qText) {
                                        qElemNumbers.push(listValue[0].qElemNumber);
                                    }

                                });
                            });

                            selectionDict.push({
                                key: value.key,
                                values: qElemNumbers
                            });

                            if (responseCount == dict.length) {

                                $.each(selectionDict, function(i, currentFieldDetails) {
                                    appSelections.field(currentFieldDetails.key).select(currentFieldDetails.values, true, true);
                                });

                                // all done:
                                deferred.resolve();

                            }
                        });
                    });

                    return deferred.promise;
                },

                intersect: function(a, b) {
                    var d = {};
                    var results = [];

                    if (typeof a !== "undefined" && typeof b !== "undefined") {

                        for (var i = 0; i < b.length; i++) {
                            d[b[i]] = true;
                        }
                        for (var j = 0; j < a.length; j++) {
                            if (d[a[j]]){

                                //console.log("Intersected: ", a[j]);

                                results.push({
                                    fieldName : a[j],
                                    isTransferable : true
                                });

                            } else {

                                //console.log("Not intersected: ", a[j]);

                                results.push({
                                    fieldName : a[j],
                                    isTransferable : false
                                });

                            }
                        }

                    }

                    return results;
                },

                getTransferableCount: function(items) {

                    var transferableCount = 0;

                    for(var itemLoop = 0; itemLoop < items.length; itemLoop++)
                    {
                        if( items[itemLoop].isTransferable === true){
                            transferableCount += 1;
                        }
                    }

                    return transferableCount;
                }
            }
        }
    ])
});
<|endoftext|>


<commit_before>// @flow

import type { SiteGroup } from './types';

import Lokka from 'lokka';
import Transport from 'lokka-transport-http';

const amazeeioapihost = process.env.AMAZEEIO_API_HOST || "http://api:3000"

const graphqlapi = new Lokka({
  transport: new Transport(`${amazeeioapihost}/graphql`)
});

export class SiteGroupNotFound extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'SiteGroupNotFound';
  }
}

export class NoActiveSystemsDefined extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'NoActiveSystemsDefined';
  }
}

export async function siteGroupByGitUrl (gitUrl: string): SiteGroup {

  const result = await graphqlapi.query(`
    {
      siteGroup:siteGroupByGitUrl(giturl: "${gitUrl}"){
        siteGroupName
        slack
        openshift
      }
    }
  `)

  if (result.siteGroup != null) {
    return result.siteGroup
  } else {
    throw new SiteGroupNotFound(`Cannot find site information for git repo ${gitUrl}`)
  }
}

export async function getSiteGroupsByGitUrl (gitUrl: string): SiteGroup[] {

  const result = await graphqlapi.query(`
    {
      allSiteGroups(giturl: "${gitUrl}") {
        edges {
          node {
            siteGroupName
            slack
            openshift
          }
        }
      }
    }
  `)

  if (result.allSiteGroups.edges.length != 0) {
    // graphql returns multiple sitegroups in an array all with the key 'node`, we remove this here and make it a direct array with sitegroups
    return result.allSiteGroups.edges.map((edge) => edge.node)
  } else {
    throw new SiteGroupNotFound(`Cannot find site information for git repo ${gitUrl}`)
  }
}

export async function getSlackinfoForSiteGroup (siteGroup: string): SiteGroup {

  const result = await graphqlapi.query(`
    {
      siteGroup:siteGroupByName(name: "${siteGroup}"){
        slack
      }
    }
  `)

  if (result.siteGroup.slack) {
    return result.siteGroup
  } else {
    throw new SiteGroupNotFound(`Cannot find site information for siteGroup ${siteGroup}`)
  }
}

export async function getActiveSystemsForSiteGroup (siteGroup: string, task: string): String {

  const result = await graphqlapi.query(`
    {
      siteGroup:siteGroupByName(name: "${siteGroup}"){
        activeSystems
      }
    }
  `)

  if (result.siteGroup != null) {
    if (result.siteGroup.hasOwnProperty('activeSystems')) {
      return result.siteGroup.activeSystems
    } else {
      throw new NoActiveSystemsDefined(`Cannot find active systems for siteGroup ${siteGroup}`)
    }
  } else {
    throw new SiteGroupNotFound(`Cannot find SiteGroup: ${siteGroup}`)
  }
}
<commit_msg>adapting to new api<commit_after>// @flow

import type { SiteGroup } from './types';

import Lokka from 'lokka';
import Transport from 'lokka-transport-http';

const amazeeioapihost = process.env.AMAZEEIO_API_HOST || "http://api-new:3000"

const graphqlapi = new Lokka({
  transport: new Transport(`${amazeeioapihost}/graphql`)
});

export class SiteGroupNotFound extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'SiteGroupNotFound';
  }
}

export class NoActiveSystemsDefined extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'NoActiveSystemsDefined';
  }
}

export async function siteGroupByGitUrl (gitUrl: string): SiteGroup {

  const result = await graphqlapi.query(`
    {
      siteGroup:siteGroupByGitUrl(gitUrl: "${gitUrl}"){
        siteGroupName
        slack {
          webhook
          channel
        }
        openshift
      }
    }
  `)

  if (!result || !result.siteGroup) {
    throw new SiteGroupNotFound(`Cannot find site information for git repo ${gitUrl}`)
  }

  return result.siteGroup;
}

export async function getSiteGroupsByGitUrl(gitUrl: string): SiteGroup[] {

  const result = await graphqlapi.query(`
    {
      allSiteGroups(gitUrl: "${gitUrl}") {
        siteGroupName
        slack {
          webhook
          channel
        }
        openshift
      }
    }
  `);

  if (!result || !result.allSiteGroups || !result.allSiteGroups.length) {
    throw new SiteGroupNotFound(`Cannot find site information for git repo ${gitUrl}`)
  }

  return result.allSiteGroups;
}

export async function getSlackinfoForSiteGroup (siteGroup: string): SiteGroup {

  const result = await graphqlapi.query(`
    {
      siteGroup:siteGroupByName(name: "${siteGroup}"){
        slack {
          webhook
          channel
        }
      }
    }
  `)

  if (!result || !result.siteGroup || !result.siteGroup.slack) {
    throw new SiteGroupNotFound(`Cannot find site information for siteGroup ${siteGroup}`)
  }

  return result.siteGroup;
}

export async function getActiveSystemsForSiteGroup (siteGroup: string, task: string): String {

  const result = await graphqlapi.query(`
    {
      siteGroup:siteGroupByName(name: "${siteGroup}"){
        activeSystems
      }
    }
  `);

  if (!result || !result.siteGroup) {
    throw new SiteGroupNotFound(`Cannot find site information for siteGroup ${siteGroup}`);
  }

  if (!result.siteGroup.activeSystems){
    throw new NoActiveSystemsDefined(`Cannot find active systems for siteGroup ${siteGroup}`)
  }

  return result.siteGroup.activeSystems;
}
<|endoftext|>


<commit_before>'use strict'

/* global EXIF:false */

;(function (ownerDocument) {
  class ImageExif extends HTMLElement {
    constructor () {
      super()

      this._debug = false
      this.debug('constructing')

      this.root = this.attachShadow({mode: 'open'})

      const template = ownerDocument.querySelector('template')
      this.root.appendChild(document.importNode(template.content, true))
    }

    connectedCallback () {
      this.debug('connected img-exif')

      // this.render()
    }

    render () {
      if (this.src && !this.isConnected) return
      this.debug('rendering img-exif')

      const $target = this.root.querySelector('canvas, img')
      if ($target) this.root.removeChild($target)

      this.$canvas = document.createElement('canvas')
      this.$img = document.createElement('img')

      const self = this
      const $img = this.$img
      const $canvas = this.$canvas

      const ctx = $canvas.getContext('2d')

      // parse image for orientation
      EXIF.getData({ src: this.src }, function (buffer) {
        self.debug('got EXIF data', self.src)

        // get orientation
        const orientation = EXIF.getTag(this, 'Orientation')
        self.debug(`orientation code: ${orientation}`)

        // set image src to blob
        $img.src = URL.createObjectURL(new Blob([buffer]))

        const transformRequired = orientation && orientation !== 1
        const $target = transformRequired ? $canvas : $img

        $img.onload = () => {
          self.debug('blob image loaded')

          // if orientation adjustment is needed
          if (transformRequired) {
            // if image dimensions have changed
            if ([5, 6, 7, 8].includes(orientation)) {
              $canvas.width = $img.height
              $canvas.height = $img.width
            } else {
              $canvas.width = $img.width
              $canvas.height = $img.height
            }

            // possible orientation effects
            const orientations = {
              // 1: () => ctx.transform(1, 0, 0, 1, 0, 0),
              2: () => ctx.transform(-1, 0, 0, 1, $img.width, 0),
              3: () => ctx.transform(-1, 0, 0, -1, $img.width, $img.height),
              4: () => ctx.transform(1, 0, 0, -1, 0, $img.height),
              5: () => ctx.transform(0, 1, 1, 0, 0, 0),
              6: () => ctx.transform(0, 1, -1, 0, $img.height, 0),
              7: () => ctx.transform(0, -1, -1, 0, $img.height, $img.width),
              8: () => ctx.transform(0, -1, 1, 0, 0, $img.width)
            }

            // apply orientation to canvas
            orientations[orientation]()

            // draw image to canvas
            ctx.drawImage($img, 0, 0)
          }

          // insert canvas or img
          self.root.appendChild($target)
        }
      })
    }

    get src () {
      return this.getAttribute('src')
    }

    set src (val) {
      return this.setAttribute('src', val)
    }

    get alt () {
      return this.hasAttribute('alt') ? this.getAttribute('alt') : null
    }

    set alt (val) {
      return this.setAttribute('alt', val)
    }

    disconnectedCallback () {
      this.debug('disconnection img-exif')
    }

    adoptedCallback () {
      this.debug('adopted img-exif')
    }

    static get observedAttributes () {
      return ['src', 'alt']
    }

    attributeChangedCallback (attrName, oldVal, newVal) {
      this.debug(`attribute changed on img-exif: ${attrName}, ${oldVal} => ${newVal}`)

      const changes = {
        src: () => { if (oldVal !== newVal) this.render() },
        alt: () => { if (oldVal !== newVal) this.render() }
      }

      if (attrName in changes) changes[attrName]()
    }

    debug (msg) {
      if (this._debug) console.info(msg)
    }
  }

  window.customElements.define('img-exif', ImageExif)
})(document.currentScript.ownerDocument)
<commit_msg>add blob url getter<commit_after>'use strict'

/* global EXIF:false */

;(function (ownerDocument) {
  class ImageExif extends HTMLElement {
    constructor () {
      super()

      this._debug = false
      this.debug('constructing')

      this.root = this.attachShadow({mode: 'open'})

      const template = ownerDocument.querySelector('template')
      this.root.appendChild(document.importNode(template.content, true))
    }

    connectedCallback () {
      this.debug('connected img-exif')

      // this.render()
    }

    render () {
      if (this.src && !this.isConnected) return
      this.debug('rendering img-exif')

      const $target = this.root.querySelector('canvas, img')
      if ($target) this.root.removeChild($target)

      this.$canvas = document.createElement('canvas')
      this.$img = document.createElement('img')

      const self = this
      const $img = this.$img
      const $canvas = this.$canvas

      const ctx = $canvas.getContext('2d')

      // parse image for orientation
      EXIF.getData({ src: this.src }, function (buffer) {
        self.debug('got EXIF data', self.src)

        // get orientation
        const orientation = EXIF.getTag(this, 'Orientation')
        self.debug(`orientation code: ${orientation}`)

        // set image src to blob
        $img.src = URL.createObjectURL(new Blob([buffer]))

        const transformRequired = orientation && orientation !== 1
        const $target = transformRequired ? $canvas : $img

        $img.onload = () => {
          self.debug('blob image loaded')

          // if orientation adjustment is needed
          if (transformRequired) {
            // if image dimensions have changed
            if ([5, 6, 7, 8].includes(orientation)) {
              $canvas.width = $img.height
              $canvas.height = $img.width
            } else {
              $canvas.width = $img.width
              $canvas.height = $img.height
            }

            // possible orientation effects
            const orientations = {
              // 1: () => ctx.transform(1, 0, 0, 1, 0, 0),
              2: () => ctx.transform(-1, 0, 0, 1, $img.width, 0),
              3: () => ctx.transform(-1, 0, 0, -1, $img.width, $img.height),
              4: () => ctx.transform(1, 0, 0, -1, 0, $img.height),
              5: () => ctx.transform(0, 1, 1, 0, 0, 0),
              6: () => ctx.transform(0, 1, -1, 0, $img.height, 0),
              7: () => ctx.transform(0, -1, -1, 0, $img.height, $img.width),
              8: () => ctx.transform(0, -1, 1, 0, 0, $img.width)
            }

            // apply orientation to canvas
            orientations[orientation]()

            // draw image to canvas
            ctx.drawImage($img, 0, 0)
          }

          // insert canvas or img
          self.root.appendChild($target)
        }
      })
    }

    get blobUrl () {
      return new Promise((resolve, reject) => {
        this.$canvas.toBlob(function (blob) {
          resolve(URL.createObjectURL(blob))
        })
      })
    }

    get src () {
      return this.getAttribute('src')
    }

    set src (val) {
      return this.setAttribute('src', val)
    }

    get alt () {
      return this.hasAttribute('alt') ? this.getAttribute('alt') : null
    }

    set alt (val) {
      return this.setAttribute('alt', val)
    }

    disconnectedCallback () {
      this.debug('disconnection img-exif')
    }

    adoptedCallback () {
      this.debug('adopted img-exif')
    }

    static get observedAttributes () {
      return ['src', 'alt']
    }

    attributeChangedCallback (attrName, oldVal, newVal) {
      this.debug(`attribute changed on img-exif: ${attrName}, ${oldVal} => ${newVal}`)

      const changes = {
        src: () => { if (oldVal !== newVal) this.render() },
        alt: () => { if (oldVal !== newVal) this.render() }
      }

      if (attrName in changes) changes[attrName]()
    }

    debug (msg) {
      if (this._debug) console.info(msg)
    }
  }

  window.customElements.define('img-exif', ImageExif)
})(document.currentScript.ownerDocument)
<|endoftext|>


<commit_before>/*!
 * tablequeryjs
 * https://github.com/asimihsan/tablequeryjs
 *
 * Copyright 2013 Asim Ihsan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*

References:
-   http://stackoverflow.com/a/5947280/223301

*/

/*
Examples:

'first name' ilike Mark
'first name' like r
'first name' like Mark or number = 3
number = 3
number == 3
not number == 3
not 'first name' ilike mark
not ('first name' ilike mark or number = 2)

*/

var tablequery = tablequery || {};
tablequery._.extend(tablequery, (function() {

    var table; // = $("table");
    var table_parent;
    var table_tbody_rows;
    var table_search_text; // = $("#table_search_text");

    var parser_exception_message;
    var table_headings = {};
    var table_column_types = {};
    var table_search_text_keyup_timer;

    tablequery._get_rows_to_display = function(trees) {
        console.log("get_rows_to_display.");
        console.log(trees);
        var return_value;
        var node_type = trees[0];
        var left = trees[1];
        if (trees.length == 3) {
            var right = trees[2];
        }
        if (!($.isArray(left))) {
            console.log("Child nodes.");
            switch(node_type) {
                case "EQ":
                case "NEQ":
                    var expr = new RegExp("^" + right + "$");
                    break;
                case "ILIKE":
                case "NILIKE":
                    var expr = new RegExp(right, "i");
                    break;
                case "LIKE":
                case "NLIKE":
                    var expr = new RegExp(right);
                    break;
                case "ILIKE_ANY":
                    var expr = new RegExp(left, "i");
                    break;
            } // switch(node_type)
            if (left in table_headings) {
                var column_indices = [table_headings[left]];
            } else if (node_type === "ILIKE_ANY") {
                var column_indices = tablequery._.values(table_headings);
            } else {
                var column_indices = [];
            }
            var test_for_true = node_type.substring(0,1) != "N";
            if (!(tablequery._.isUndefined(right))) {
                var date_range = tablequery.get_date_range(node_type, right);
                var time_range = tablequery.get_time_range(node_type, right);
            }
            return_value = table_tbody_rows.filter(function(index, row) {
                return tablequery._.any(
                    tablequery._.map($(row).children(), function(column, index) {
                        if (!(tablequery._.contains(column_indices, index))) {
                            return;
                        }
                        var text = $.trim(column.textContent);
                        switch(table_column_types[index]) {
                            case "date":
                                return {"type": "date",
                                        "value": tablequery._get_datetime(text)};
                            case "time":
                                return {"type": "time",
                                        "value": tablequery._get_time(text)};
                            case "number":
                                if (_isNumber(text)) {
                                    return {"type": "number",
                                            "value": parseInt(text, 10)};
                                }
                            case "text":
                                return {"type": "text",
                                        "value": text};
                        }
                    }),
                    function(data) {
                        if (tablequery._.isUndefined(data)) {
                            return false;
                        }
                        switch(data.type) {
                            case "time":
                                if (tablequery._.isUndefined(time_range))
                                    return false;
                                result = time_range.contains(data.value);
                                break;
                            case "date":
                                if (tablequery._.isUndefined(date_range))
                                    return false;
                                result = date_range.contains(data.value);
                                break;
                            case "number":
                            case "text":
                                result = expr.test(data.value);
                                break;
                        }
                        if (test_for_true) {
                            return result;
                        } else {
                            return !result;
                        }
                    }
                );
            });
        } else {
            console.log("Interior nodes.");
            var left_trees = tablequery._get_rows_to_display(left);
            if (trees.length == 3) {
                var right_trees = tablequery._get_rows_to_display(right);
            }
            switch(node_type) {
                case "AND":
                    console.log("AND");
                    return_value = tablequery._.intersection(left_trees, right_trees);
                    break;
                case "OR":
                    return_value = left_trees.add(right_trees);
                    break;
                case "NOT":
                    console.log("NOT");
                    var left_tree_indices = {}
                    tablequery._.each(left_trees, function(obj) { left_tree_indices[$(obj).index()] = true; });
                    return_value = tablequery._.filter(table_tbody_rows, function(row) {
                        return !($(row).index() in left_tree_indices);
                    });
            } // switch(node_type)
        } // if (!($.isArray(left)))
        if (!return_value) {
            console.log("no return value, return all rows.");
            return_value = table_tbody_rows;
        }
        console.log("returning")
        console.log(return_value);
        return return_value;
    }
    tablequery._get_rows_to_display = tablequery._.memoize(tablequery._get_rows_to_display);

    tablequery._parse_search_text = function(search_text) {
        var is_parse_successful = true;
        var parsed_query;
        try {
            parsed_query = parser.parse(search_text);
        } catch(e) {
            parser_exception_message = e.message;
            is_parse_successful = false;
        }
        return {"rc": is_parse_successful, "parsed_query": parsed_query};
    }

    tablequery._update_table_search_text_warning = function(is_parse_successful, clear) {
        if ((table_search_text.val().length == 0) || clear) {
            table_search_text.css("border", "");
        } else if (is_parse_successful) {
            table_search_text.css("border", "2px solid green");
        } else {
            table_search_text.css("border", "2px solid red");
        }
    }

    tablequery._update_table_lookups = function() {
        table_headings = {};
        table.find("th").each(function(i, el) {
            table_headings[$.trim(el.textContent.toLowerCase())] = i;
        });
        table_column_types = {};
        table.find("tr").eq(1).children().each(function(i, el) {
            var text = $.trim(el.textContent);
            if (_isNumber(text)) {
                table_column_types[i] = "number";
            } else if (tablequery._get_datetime(text).isValid()) {
                table_column_types[i] = "date";
            } else if (tablequery._get_time(text).isValid()) {
                table_column_types[i] = "time";
            } else {
                table_column_types[i] = "text";
            }
        });
    }

    tablequery.set_table = function(selector) {
        table = $(selector);
        table_parent = table.parent();
        table_tbody_rows = table.find("tbody tr");
        tablequery._update_table_lookups();
    }

    tablequery.hide_selector = function(selector) {
        selector.css("display", "none");
    }

    tablequery.show_selector = function(selector) {
        selector.css("display", "");
    }

    var previous_query_failed;
    tablequery.set_table_search_text = function(selector) {
        table_search_text = $(selector);

        tablequery._table_search_text_on_keyup = function(e, text_value) {
            var rv = tablequery._parse_search_text(text_value);
            tablequery._update_table_search_text_warning(rv.rc, false);
            if (rv.rc) {
                tablequery._update_table_lookups();
                previous_query_failed = false;
                var rows_to_display = tablequery._get_rows_to_display(rv.parsed_query);
                table.detach();
                tablequery.hide_selector(table_tbody_rows);
                tablequery._.each(rows_to_display, function(row) { tablequery.show_selector($(row)); });
                table_parent.append(table);
            } else {
                if (!previous_query_failed) {
                    tablequery.show_selector(table_tbody_rows);
                }
                previous_query_failed = true;
            }
            tablequery.trigger('search');
        }
        tablequery._table_search_text_on_keyup_debounced = tablequery._.debounce(tablequery._table_search_text_on_keyup, 500);
        table_search_text.keyup(function(e) {
            if ((e.keyCode || e.which || e.charCode || 0) === 13) {
                tablequery._table_search_text_on_keyup(e, table_search_text.val());
            } else {
                tablequery._table_search_text_on_keyup_debounced(e, table_search_text.val());
            }
        });

        // Suppress form submit.
        table_search_text.keypress(function(e) {
            return (e.keyCode || e.which || e.charCode || 0) !== 13;
        });

        table_search_text.click(function() {
            tablequery._table_search_text_on_keyup_debounced(undefined,
                                                             table_search_text.val());
        });
        table_search_text.blur(function() {
            tablequery._table_search_text_on_keyup_debounced(undefined,
                                                             table_search_text.val());
        });
        // --------------------------------------------------------------------
    }

    tablequery._now = function() {
        return moment();
    }

    tablequery._get_time = function(string) {
        if (!(/^(\d{1,2}|\d{1,2}:\d{2}|\d{1,2}:\d{2}:\d{2})$/.test(string))) {
            return moment("-");
        }
        return_value = moment(string, [
            'ss',
            'mm:ss',
            'HH:mm:ss',
        ]);
        if (!(tablequery._.contains(tablequery._.functions(return_value), 'isValid'))) {
            return moment("-");
        }
        return return_value;
    }
    tablequery._get_time = tablequery._.memoize(tablequery._get_time);

    tablequery._get_datetime = function(string) {
        return_value = moment(string, [
            "YYYY-MM-DD",
            "YYYY-MM-DD HH",
            "YYYY-MM-DD HH:mm",
            "YYYY-MM-DD HH:mm:ss",
            "YYYY-MM-DD HH:mm:ssZ",
            "YYYY-MM-DDTHH:mm:ss",
            "YYYY-MM-DDTHH:mm:ssZ",
        ]);
        if (!(tablequery._.contains(tablequery._.functions(return_value), 'isValid'))) {
            return moment("-");
        }
        return return_value;
    }
    tablequery._get_datetime = tablequery._.memoize(tablequery._get_datetime);

    tablequery.get_time_range = function(node_type, query) {
        var time = tablequery._get_time(query);
        if (!(time.isValid()))
            return;
        switch(time._f) {
            case "ss":
                var precision = "second";
                break;
            case "mm:ss":
                var precision = "minute";
                break;
            case "HH:mm:ss":
                var precision = "hour";
                break;
        }
        switch(node_type) {
            case "EQ":
            case "NEQ":
                var time_range = moment().range(moment(time).startOf(precision),
                                                moment(time).endOf(precision));
                break;
            case "LTE":
            case "LT":
                var time_range = moment().range(moment(0),
                                                moment(time));
                break;
            case "GTE":
            case "GT":
                var time_range = moment().range(moment(time),
                                                moment("9999"));
                break;
        }
        return time_range;
    }

    tablequery.get_date_range = function(node_type, query) {
        var now = tablequery._now();
        var duration, datetime, datetimeStart, datetimeEnd;
        if (query === "today") {
            duration = moment.duration(0, 'days');
        } else if (query === "yesterday") {
            duration = moment.duration(1, 'days');
        } else {
            datetime = tablequery._get_datetime(query);
            if (!(datetime.isValid()))
                return;
        }
        switch(node_type) {
            case "EQ":
            case "NEQ":
                if (!(tablequery._.isUndefined(duration))) {
                    var date_range = moment().range(moment(now - duration).startOf('day'),
                                                    moment(now - duration).endOf('day'));
                } else {
                    var date_range = moment().range(moment(datetime).startOf('day'),
                                                    moment(datetime).endOf('day'));
                }
                break;
            case "LTE":
            case "LT":
                if (!(tablequery._.isUndefined(duration))) {
                    var date_range = moment().range(moment(0),
                                                    moment(now - duration).endOf('day'));
                } else {
                    var date_range = moment().range(moment(0),
                                                    moment(datetime));
                }
                break;
            case "GTE":
            case "GT":
                if (!(tablequery._.isUndefined(duration))) {
                    var date_range = moment().range(moment(now - duration).startOf('day'),
                                                    moment("9999"));
                } else {
                    var date_range = moment().range(moment(datetime),
                                                    moment("9999"));
                }
                break;
        }
        return date_range;
    }

    _isNumber = function(string) {
        return /^[0-9]+$/.test(string);
    }
    _isNumber = tablequery._.memoize(_isNumber);
})());
<commit_msg>tablequeryjs-core - comment out debug logs, fix closure-compiler errors<commit_after>/*!
 * tablequeryjs
 * https://github.com/asimihsan/tablequeryjs
 *
 * Copyright 2013 Asim Ihsan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*

References:
-   http://stackoverflow.com/a/5947280/223301

*/

/*
Examples:

'first name' ilike Mark
'first name' like r
'first name' like Mark or number = 3
number = 3
number == 3
not number == 3
not 'first name' ilike mark
not ('first name' ilike mark or number = 2)

*/

var tablequery = tablequery || {};
tablequery._.extend(tablequery, (function() {

    var table; // = $("table");
    var table_parent;
    var table_tbody_rows;
    var table_search_text; // = $("#table_search_text");

    var parser_exception_message;
    var table_headings = {};
    var table_column_types = {};
    var table_search_text_keyup_timer;

    tablequery._get_rows_to_display = function(trees) {
        //console.log("get_rows_to_display.");
        //console.log(trees);
        var return_value;
        var node_type = trees[0];
        var left = trees[1];
        if (trees.length == 3) {
            var right = trees[2];
        }
        if (!($.isArray(left))) {
            //console.log("Child nodes.");
            switch(node_type) {
                case "EQ":
                case "NEQ":
                    var expr = new RegExp("^" + right + "$");
                    break;
                case "ILIKE":
                case "NILIKE":
                    var expr = new RegExp(right, "i");
                    break;
                case "LIKE":
                case "NLIKE":
                    var expr = new RegExp(right);
                    break;
                case "ILIKE_ANY":
                    var expr = new RegExp(left, "i");
                    break;
            } // switch(node_type)
            if (left in table_headings) {
                var column_indices = [table_headings[left]];
            } else if (node_type === "ILIKE_ANY") {
                var column_indices = tablequery._.values(table_headings);
            } else {
                var column_indices = [];
            }
            var test_for_true = node_type.substring(0,1) != "N";
            if (!(tablequery._.isUndefined(right))) {
                var date_range = tablequery.get_date_range(node_type, right);
                var time_range = tablequery.get_time_range(node_type, right);
            }
            return_value = table_tbody_rows.filter(function(index, row) {
                return tablequery._.any(
                    tablequery._.map($(row).children(), function(column, index) {
                        if (!(tablequery._.contains(column_indices, index))) {
                            return;
                        }
                        var text = $.trim(column.textContent);
                        switch(table_column_types[index]) {
                            case "date":
                                return {"type": "date",
                                        "value": tablequery._get_datetime(text)};
                            case "time":
                                return {"type": "time",
                                        "value": tablequery._get_time(text)};
                            case "number":
                                if (_isNumber(text)) {
                                    return {"type": "number",
                                            "value": parseInt(text, 10)};
                                }
                            case "text":
                                return {"type": "text",
                                        "value": text};
                        }
                    }),
                    function(data) {
                        if (tablequery._.isUndefined(data)) {
                            return false;
                        }
                        switch(data.type) {
                            case "time":
                                if (tablequery._.isUndefined(time_range))
                                    return false;
                                result = time_range.contains(data.value);
                                break;
                            case "date":
                                if (tablequery._.isUndefined(date_range))
                                    return false;
                                result = date_range.contains(data.value);
                                break;
                            case "number":
                            case "text":
                                result = expr.test(data.value);
                                break;
                        }
                        if (test_for_true) {
                            return result;
                        } else {
                            return !result;
                        }
                    }
                );
            });
        } else {
            //console.log("Interior nodes.");
            var left_trees = tablequery._get_rows_to_display(left);
            if (trees.length == 3) {
                var right_trees = tablequery._get_rows_to_display(right);
            }
            switch(node_type) {
                case "AND":
                    //console.log("AND");
                    return_value = tablequery._.intersection(left_trees, right_trees);
                    break;
                case "OR":
                    return_value = left_trees.add(right_trees);
                    break;
                case "NOT":
                    //console.log("NOT");
                    var left_tree_indices = {}
                    tablequery._.each(left_trees, function(obj) { left_tree_indices[$(obj).index()] = true; });
                    return_value = tablequery._.filter(table_tbody_rows, function(row) {
                        return !($(row).index() in left_tree_indices);
                    });
            } // switch(node_type)
        } // if (!($.isArray(left)))
        if (!return_value) {
            //console.log("no return value, return all rows.");
            return_value = table_tbody_rows;
        }
        //console.log("returning")
        //console.log(return_value);
        return return_value;
    }
    tablequery._get_rows_to_display = tablequery._.memoize(tablequery._get_rows_to_display);

    tablequery._parse_search_text = function(search_text) {
        var is_parse_successful = true;
        var parsed_query;
        try {
            parsed_query = parser.parse(search_text);
        } catch(e) {
            parser_exception_message = e.message;
            is_parse_successful = false;
        }
        return {"rc": is_parse_successful, "parsed_query": parsed_query};
    }

    tablequery._update_table_search_text_warning = function(is_parse_successful, clear) {
        if ((table_search_text.val().length == 0) || clear) {
            table_search_text.css("border", "");
        } else if (is_parse_successful) {
            table_search_text.css("border", "2px solid green");
        } else {
            table_search_text.css("border", "2px solid red");
        }
    }

    tablequery._update_table_lookups = function() {
        table_headings = {};
        table.find("th").each(function(i, el) {
            table_headings[$.trim(el.textContent.toLowerCase())] = i;
        });
        table_column_types = {};
        table.find("tr").eq(1).children().each(function(i, el) {
            var text = $.trim(el.textContent);
            if (_isNumber(text)) {
                table_column_types[i] = "number";
            } else if (tablequery._get_datetime(text).isValid()) {
                table_column_types[i] = "date";
            } else if (tablequery._get_time(text).isValid()) {
                table_column_types[i] = "time";
            } else {
                table_column_types[i] = "text";
            }
        });
    }

    tablequery.set_table = function(selector) {
        table = $(selector);
        table_parent = table.parent();
        table_tbody_rows = table.find("tbody tr");
        tablequery._update_table_lookups();
    }

    tablequery.hide_selector = function(selector) {
        selector.css("display", "none");
    }

    tablequery.show_selector = function(selector) {
        selector.css("display", "");
    }

    var previous_query_failed;
    tablequery.set_table_search_text = function(selector) {
        table_search_text = $(selector);

        tablequery._table_search_text_on_keyup = function(e, text_value) {
            var rv = tablequery._parse_search_text(text_value);
            tablequery._update_table_search_text_warning(rv.rc, false);
            if (rv.rc) {
                tablequery._update_table_lookups();
                previous_query_failed = false;
                var rows_to_display = tablequery._get_rows_to_display(rv.parsed_query);
                table.detach();
                tablequery.hide_selector(table_tbody_rows);
                tablequery._.each(rows_to_display, function(row) { tablequery.show_selector($(row)); });
                table_parent.append(table);
            } else {
                if (!previous_query_failed) {
                    tablequery.show_selector(table_tbody_rows);
                }
                previous_query_failed = true;
            }
            tablequery.trigger('search');
        }
        tablequery._table_search_text_on_keyup_debounced = tablequery._.debounce(tablequery._table_search_text_on_keyup, 500);
        table_search_text.keyup(function(e) {
            if ((e.keyCode || e.which || e.charCode || 0) === 13) {
                tablequery._table_search_text_on_keyup(e, table_search_text.val());
            } else {
                tablequery._table_search_text_on_keyup_debounced(e, table_search_text.val());
            }
        });

        // Suppress form submit.
        table_search_text.keypress(function(e) {
            return (e.keyCode || e.which || e.charCode || 0) !== 13;
        });

        table_search_text.click(function() {
            tablequery._table_search_text_on_keyup_debounced(undefined,
                                                             table_search_text.val());
        });
        table_search_text.blur(function() {
            tablequery._table_search_text_on_keyup_debounced(undefined,
                                                             table_search_text.val());
        });
        // --------------------------------------------------------------------
    }

    tablequery._now = function() {
        return moment();
    }

    tablequery._get_time = function(string) {
        if (!(/^(\d{1,2}|\d{1,2}:\d{2}|\d{1,2}:\d{2}:\d{2})$/.test(string))) {
            return moment("-");
        }
        return_value = moment(string, [
            'ss',
            'mm:ss',
            'HH:mm:ss'
        ]);
        if (!(tablequery._.contains(tablequery._.functions(return_value), 'isValid'))) {
            return moment("-");
        }
        return return_value;
    }
    tablequery._get_time = tablequery._.memoize(tablequery._get_time);

    tablequery._get_datetime = function(string) {
        return_value = moment(string, [
            "YYYY-MM-DD",
            "YYYY-MM-DD HH",
            "YYYY-MM-DD HH:mm",
            "YYYY-MM-DD HH:mm:ss",
            "YYYY-MM-DD HH:mm:ssZ",
            "YYYY-MM-DDTHH:mm:ss",
            "YYYY-MM-DDTHH:mm:ssZ"
        ]);
        if (!(tablequery._.contains(tablequery._.functions(return_value), 'isValid'))) {
            return moment("-");
        }
        return return_value;
    }
    tablequery._get_datetime = tablequery._.memoize(tablequery._get_datetime);

    tablequery.get_time_range = function(node_type, query) {
        var time = tablequery._get_time(query);
        if (!(time.isValid()))
            return;
        switch(time._f) {
            case "ss":
                var precision = "second";
                break;
            case "mm:ss":
                var precision = "minute";
                break;
            case "HH:mm:ss":
                var precision = "hour";
                break;
        }
        switch(node_type) {
            case "EQ":
            case "NEQ":
                var time_range = moment().range(moment(time).startOf(precision),
                                                moment(time).endOf(precision));
                break;
            case "LTE":
            case "LT":
                var time_range = moment().range(moment(0),
                                                moment(time));
                break;
            case "GTE":
            case "GT":
                var time_range = moment().range(moment(time),
                                                moment("9999"));
                break;
        }
        return time_range;
    }

    tablequery.get_date_range = function(node_type, query) {
        var now = tablequery._now();
        var duration, datetime, datetimeStart, datetimeEnd;
        if (query === "today") {
            duration = moment.duration(0, 'days');
        } else if (query === "yesterday") {
            duration = moment.duration(1, 'days');
        } else {
            datetime = tablequery._get_datetime(query);
            if (!(datetime.isValid()))
                return;
        }
        switch(node_type) {
            case "EQ":
            case "NEQ":
                if (!(tablequery._.isUndefined(duration))) {
                    var date_range = moment().range(moment(now - duration).startOf('day'),
                                                    moment(now - duration).endOf('day'));
                } else {
                    var date_range = moment().range(moment(datetime).startOf('day'),
                                                    moment(datetime).endOf('day'));
                }
                break;
            case "LTE":
            case "LT":
                if (!(tablequery._.isUndefined(duration))) {
                    var date_range = moment().range(moment(0),
                                                    moment(now - duration).endOf('day'));
                } else {
                    var date_range = moment().range(moment(0),
                                                    moment(datetime));
                }
                break;
            case "GTE":
            case "GT":
                if (!(tablequery._.isUndefined(duration))) {
                    var date_range = moment().range(moment(now - duration).startOf('day'),
                                                    moment("9999"));
                } else {
                    var date_range = moment().range(moment(datetime),
                                                    moment("9999"));
                }
                break;
        }
        return date_range;
    }

    _isNumber = function(string) {
        return /^[0-9]+$/.test(string);
    }
    _isNumber = tablequery._.memoize(_isNumber);
})());
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var lifeLineOptions = {};
lifeLineOptions.class = "lifeline";
// Lifeline rectangle options
lifeLineOptions.rect = {};
lifeLineOptions.rect.width = 100;
lifeLineOptions.rect.height = 30;
lifeLineOptions.rect.roundX = 20;
lifeLineOptions.rect.roundY = 20;
lifeLineOptions.rect.class = "lifeline-rect";

// Lifeline middle-rect options
lifeLineOptions.middleRect = {};
lifeLineOptions.middleRect.width = 100;
lifeLineOptions.middleRect.height = 500;
lifeLineOptions.middleRect.roundX = 1;
lifeLineOptions.middleRect.roundY = 1;
lifeLineOptions.middleRect.class = "lifeline-middleRect";

// Lifeline options
lifeLineOptions.line = {};
lifeLineOptions.line.height = 500;
lifeLineOptions.line.class = "lifeline-line";
// Lifeline text options
lifeLineOptions.text = {};
lifeLineOptions.text.class = "lifeline-title";

var createPoint = function (x, y) {
    return new GeoCore.Models.Point({'x': x, 'y': y});
};

var createLifeLine = function (title, center) {
    return new SequenceD.Models.LifeLine({title: title, centerPoint: center});
};

var createFixedSizedMediator = function (title, center) {
    return new SequenceD.Models.FixedSizedMediator({title: title, centerPoint: center});
};

var createMessage = function (start, end) {
    return new SequenceD.Models.Message({source: start, destination: end});
};

// Create tool palette elements
var lifeline = new Tools.Models.Tool({
    id: "tool1",
    title: "Lifeline",
    icon: "images/icon1.png"
});

// Create tool group
var group = new Tools.Models.ToolGroup();
group.add(lifeline);
for (var manipulator in Processors.manipulators) {
    var tool = new Tools.Models.Tool(Processors.manipulators[manipulator]);
    group.add(tool);
}
for (var flowController in Processors.flowControllers) {
    var tool = new Tools.Models.Tool(Processors.flowControllers[flowController]);
    group.add(tool);
}
var toolGroupWrapper = new Tools.Models.ToolGroupWrapper({
    toolGroupName: "Diagram Elements",
    toolGroupID: "diagram-elements",
    toolGroup: group
});

// Create tool palette
var toolPalette = new Tools.Models.ToolPalatte();
toolPalette.add(toolGroupWrapper);
var paletteView = new Tools.Views.ToolPalatteView({collection: toolPalette});
paletteView.render();

// Create the model for the diagram
var diagram = new Diagrams.Models.Diagram({});

// Create the diagram view
var diagramOptions = {selector: '.editor'};
var diagramView = new Diagrams.Views.DiagramView({model: diagram, options: diagramOptions});
diagramView.render();

lifeLineOptions.diagram = diagram;

// var lifeline1 = createLifeLine("LifeLine1",createPoint(250, 50));
// diagram.addElement(lifeline1, lifeLineOptions);
// var lifeline2 = createLifeLine("LifeLine2",createPoint(500, 50));
// diagram.addElement(lifeline2, lifeLineOptions);
// var lifeline3 = createLifeLine("LifeLine3",createPoint(750, 50));
// diagram.addElement(lifeline3, lifeLineOptions);

// var lf1Activation1 = new SequenceD.Models.Activation({owner:lifeline1});
// var lf2Activation1 = new SequenceD.Models.Activation({owner:lifeline2});
// var lf3Activation1 = new SequenceD.Models.Activation({owner:lifeline3});

// var messageOptions = {'class':'message'};
// var msg1 = new SequenceD.Models.Message({source: lf1Activation1, destination: lf3Activation1});
// diagram.addElement(msg1, messageOptions);
// var msg2 = new SequenceD.Models.Message({source: lf2Activation1, destination: lf3Activation1});
// diagram.addElement(msg2, messageOptions);
// var msg3 = new SequenceD.Models.Message({source: lf3Activation1, destination: lf1Activation1});
// diagram.addElement(msg3, messageOptions);
// var msg4 = new SequenceD.Models.Message({source: lf3Activation1, destination: lf2Activation1});
// diagram.addElement(msg4, messageOptions);
// var msg5 = new SequenceD.Models.Message({source: lf3Activation1, destination: lf1Activation1});
// diagram.addElement(msg5, messageOptions);
selected = "";
selectedModel = "";
var udcontrol = new Dialogs.Controls.UpdateDeleteControler({visible: false});
var udcontrolView = new Dialogs.Views.UpdateDeletedControlerView({model: udcontrol});
udcontrolView.render();

// Initialize the editor
var propertyPane = new JSONEditor(document.getElementById("propertyPane"),{
    schema: {
        "title": "Person",
        type: "object",
        properties: {
            name: { "type": "string" }
        }
    },
    no_additional_properties: true,
    disable_properties:true,
    disable_edit_json:true
});

// Set the value
propertyPane.setValue({
    name: "John Smith"
});

// Get the value
var data = propertyPane.getValue();
console.log(data.name); // "John Smith"
<commit_msg>Temporarily commenting property pane initialization<commit_after>/**
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var lifeLineOptions = {};
lifeLineOptions.class = "lifeline";
// Lifeline rectangle options
lifeLineOptions.rect = {};
lifeLineOptions.rect.width = 100;
lifeLineOptions.rect.height = 30;
lifeLineOptions.rect.roundX = 20;
lifeLineOptions.rect.roundY = 20;
lifeLineOptions.rect.class = "lifeline-rect";

// Lifeline middle-rect options
lifeLineOptions.middleRect = {};
lifeLineOptions.middleRect.width = 100;
lifeLineOptions.middleRect.height = 500;
lifeLineOptions.middleRect.roundX = 1;
lifeLineOptions.middleRect.roundY = 1;
lifeLineOptions.middleRect.class = "lifeline-middleRect";

// Lifeline options
lifeLineOptions.line = {};
lifeLineOptions.line.height = 500;
lifeLineOptions.line.class = "lifeline-line";
// Lifeline text options
lifeLineOptions.text = {};
lifeLineOptions.text.class = "lifeline-title";

var createPoint = function (x, y) {
    return new GeoCore.Models.Point({'x': x, 'y': y});
};

var createLifeLine = function (title, center) {
    return new SequenceD.Models.LifeLine({title: title, centerPoint: center});
};

var createFixedSizedMediator = function (title, center) {
    return new SequenceD.Models.FixedSizedMediator({title: title, centerPoint: center});
};

var createMessage = function (start, end) {
    return new SequenceD.Models.Message({source: start, destination: end});
};

// Create tool palette elements
var lifeline = new Tools.Models.Tool({
    id: "tool1",
    title: "Lifeline",
    icon: "images/icon1.png"
});

// Create tool group
var group = new Tools.Models.ToolGroup();
group.add(lifeline);
for (var manipulator in Processors.manipulators) {
    var tool = new Tools.Models.Tool(Processors.manipulators[manipulator]);
    group.add(tool);
}
for (var flowController in Processors.flowControllers) {
    var tool = new Tools.Models.Tool(Processors.flowControllers[flowController]);
    group.add(tool);
}
var toolGroupWrapper = new Tools.Models.ToolGroupWrapper({
    toolGroupName: "Diagram Elements",
    toolGroupID: "diagram-elements",
    toolGroup: group
});

// Create tool palette
var toolPalette = new Tools.Models.ToolPalatte();
toolPalette.add(toolGroupWrapper);
var paletteView = new Tools.Views.ToolPalatteView({collection: toolPalette});
paletteView.render();

// Create the model for the diagram
var diagram = new Diagrams.Models.Diagram({});

// Create the diagram view
var diagramOptions = {selector: '.editor'};
var diagramView = new Diagrams.Views.DiagramView({model: diagram, options: diagramOptions});
diagramView.render();

lifeLineOptions.diagram = diagram;

// var lifeline1 = createLifeLine("LifeLine1",createPoint(250, 50));
// diagram.addElement(lifeline1, lifeLineOptions);
// var lifeline2 = createLifeLine("LifeLine2",createPoint(500, 50));
// diagram.addElement(lifeline2, lifeLineOptions);
// var lifeline3 = createLifeLine("LifeLine3",createPoint(750, 50));
// diagram.addElement(lifeline3, lifeLineOptions);

// var lf1Activation1 = new SequenceD.Models.Activation({owner:lifeline1});
// var lf2Activation1 = new SequenceD.Models.Activation({owner:lifeline2});
// var lf3Activation1 = new SequenceD.Models.Activation({owner:lifeline3});

// var messageOptions = {'class':'message'};
// var msg1 = new SequenceD.Models.Message({source: lf1Activation1, destination: lf3Activation1});
// diagram.addElement(msg1, messageOptions);
// var msg2 = new SequenceD.Models.Message({source: lf2Activation1, destination: lf3Activation1});
// diagram.addElement(msg2, messageOptions);
// var msg3 = new SequenceD.Models.Message({source: lf3Activation1, destination: lf1Activation1});
// diagram.addElement(msg3, messageOptions);
// var msg4 = new SequenceD.Models.Message({source: lf3Activation1, destination: lf2Activation1});
// diagram.addElement(msg4, messageOptions);
// var msg5 = new SequenceD.Models.Message({source: lf3Activation1, destination: lf1Activation1});
// diagram.addElement(msg5, messageOptions);
selected = "";
selectedModel = "";
var udcontrol = new Dialogs.Controls.UpdateDeleteControler({visible: false});
var udcontrolView = new Dialogs.Views.UpdateDeletedControlerView({model: udcontrol});
udcontrolView.render();

// Initialize the editor
// var propertyPane = new JSONEditor(document.getElementById("propertyPane"),{
//     schema: {
//         "title": "Person",
//         type: "object",
//         properties: {
//             name: { "type": "string" }
//         }
//     },
//     no_additional_properties: true,
//     disable_properties:true,
//     disable_edit_json:true
// });

// // Set the value
// propertyPane.setValue({
//     name: "John Smith"
// });

// // Get the value
// var data = propertyPane.getValue();
// console.log(data.name); // "John Smith"
<|endoftext|>


<commit_before>/**
 * @author zz85 / https://github.com/zz85
 * Parametric Surfaces Geometry
 * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
 */

THREE.ParametricGeometry = function ( slices, stacks, func ) {

	THREE.Geometry.call( this );

	var verts = this.vertices;
	var faces = this.faces;
	var uvs = this.faceVertexUvs[ 0 ];

	var face3 = true;

	var i, il, j, p;
	var u, v;

	var stackCount = stacks + 1;
	var sliceCount = slices + 1;

	for ( i = 0; i <= stacks; i ++ ) {

		v = i / stacks;

		for ( j = 0; j <= slices; j ++ ) {

			u = j / slices;

			p = func( u, v );
			verts.push( p );

		}
	}

	var a, b, c, d;
	var uva, uvb, uvc, uvd;

	for ( i = 0; i < stacks; i ++ ) {
		for ( j = 0; j < slices; j ++ ) {

			a = i * sliceCount + j;
			b = i * sliceCount + j + 1;
			c = (i + 1) * sliceCount + j;
			d = (i + 1) * sliceCount + j + 1;

			uva = new THREE.UV( i / slices, j / stacks );
			uvb = new THREE.UV( i / slices, ( j + 1 ) / stacks );
			uvc = new THREE.UV( ( i + 1 ) / slices, j / stacks );
			uvd = new THREE.UV( ( i + 1 ) / slices, ( j + 1 ) / stacks );

			faces.push( new THREE.Face3( a, b, c ) );
			faces.push( new THREE.Face3( b, d, c ) );

			uvs.push( [ uva, uvb, uvc ] );
			uvs.push( [ uvb, uvd, uvc ] );
		}

	}

	console.log(this);

	// magic bullet
	var diff = this.mergeVertices();
	console.log('removed ', diff, ' vertices by merging')

	this.computeCentroids();
	this.computeFaceNormals();
	this.computeVertexNormals();

};

THREE.ParametricGeometry.prototype = new THREE.Geometry();
THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
<commit_msg>test face4s generation in parametricgeometry<commit_after>/**
 * @author zz85 / https://github.com/zz85
 * Parametric Surfaces Geometry
 * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
 */

THREE.ParametricGeometry = function ( slices, stacks, func ) {

	THREE.Geometry.call( this );

	var verts = this.vertices;
	var faces = this.faces;
	var uvs = this.faceVertexUvs[ 0 ];

	var face3 = !true;

	var i, il, j, p;
	var u, v;

	var stackCount = stacks + 1;
	var sliceCount = slices + 1;

	for ( i = 0; i <= stacks; i ++ ) {

		v = i / stacks;

		for ( j = 0; j <= slices; j ++ ) {

			u = j / slices;

			p = func( u, v );
			verts.push( p );

		}
	}

	var a, b, c, d;
	var uva, uvb, uvc, uvd;

	for ( i = 0; i < stacks; i ++ ) {
		for ( j = 0; j < slices; j ++ ) {

			a = i * sliceCount + j;
			b = i * sliceCount + j + 1;
			c = (i + 1) * sliceCount + j;
			d = (i + 1) * sliceCount + j + 1;

			uva = new THREE.UV( i / slices, j / stacks );
			uvb = new THREE.UV( i / slices, ( j + 1 ) / stacks );
			uvc = new THREE.UV( ( i + 1 ) / slices, j / stacks );
			uvd = new THREE.UV( ( i + 1 ) / slices, ( j + 1 ) / stacks );

			if ( face3 ) {

				faces.push( new THREE.Face3( a, b, c ) );
				faces.push( new THREE.Face3( b, d, c ) );

				uvs.push( [ uva, uvb, uvc ] );
				uvs.push( [ uvb, uvd, uvc ] );

			} else {

				faces.push( new THREE.Face4( a, b, d, c ) );
				uvs.push( [ uva, uvb, uvc, uvd ] );

			}

		}

	}

	// console.log(this);

	// magic bullet
	var diff = this.mergeVertices();
	console.log('removed ', diff, ' vertices by merging');

	this.computeCentroids();
	this.computeFaceNormals();
	this.computeVertexNormals();

};

THREE.ParametricGeometry.prototype = new THREE.Geometry();
THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
<|endoftext|>