<commit_before>// TODO in EditorGridPanel add clickToEdit option new EditorGridPanel(this).setClicksToEdit(2)
// TODO fieldLabel must have ":" have labelSeparator

var logId = true;
var elemCount = 0;
function getVarName(name){
    name = name ? name : 'item' + (elemCount++);
    // remove spaces and capitalize each word
    var words = name.split(/\s/);
    Ext.each(words, function(w, i){
        words[i] = Ext.util.Format.capitalize(w);
    });
    name = words.join('');

    name = name.replace(/[\(\)/\\:;\<>=\-"]/gi, '');
    //name = Ext.util.Format.capitalize(name);
    return !name ? name : name.charAt(0).toLowerCase() + name.substr(1);
}

function getPanelConfig(item){
    var code = '';
    if(item.title){
        code += '.setTitle("' + item.title + '")';
    } else if(item.fieldLabel){
        code += '.setLabel("' + item.fieldLabel + '")';
    }
    return code;
}

function getItemCode(container, item){
    var name = '',
        code = '\tpublic ',
        xtype = item.getXType(),
        xtypes = item.getXTypes(),
        label = item.fieldLabel + (item.ownerCt.getLayout().labelSeparator || '');

    //console.debug('getItemCode', container, item);
    if(xtype == 'editorgrid' || xtypes.indexOf('/editorgrid/') != -1 || item instanceof Ext.grid.EditorGridPanel){
        name = getVarName(item.title) + 'EditorGridPanel';
        code += 'EditorGridPanel ' + name + ' = new EditorGridPanel(' + container + ')';
        code += getPanelConfig(item);
    } else if(xtype == 'grid' || xtypes.indexOf('/grid/') != -1 || item instanceof Ext.grid.GridPanel){
        name = getVarName(item.title) + 'GridPanel';
        code += 'GridPanel ' + name + ' = new GridPanel(' + container + ')';
        code += getPanelConfig(item);
    } else if(xtype == 'panel' || xtypes.indexOf('/panel/') != -1 || item instanceof Ext.Panel){
        console.debug('panel item:', item.id, item);
        name = getVarName(item.title) + 'Panel';
        code += 'Panel ' + name + ' = new Panel(' + container + ')';
        code += getPanelConfig(item);
    } else if(xtype == 'combo' || xtypes.indexOf('/combo/') != -1){
        name = getVarName(label) + 'ComboBox';
        code += 'ComboBox ' + name + ' = new ComboBox(' + container + ', "' + label +  '")';
    } else if(xtype == 'textarea' || xtypes.indexOf('/textarea/') != -1){
        name = getVarName(label) + 'TextArea';
        code += 'TextArea ' + name + ' = new TextArea(' + container + ', "'  + label +  '")';
    } else if(xtype == 'textfield' || xtypes.indexOf('/textfield/') != -1){
        name = getVarName(label) + 'TextField';
        code += 'TextField ' + name + ' = new TextField(' + container + ', "'  + label +  '")';
    } else if(xtype == 'displayfield' || xtypes.indexOf('/displayfield/') != -1){
        name = getVarName(label) + 'DisplayField';
        code += 'DisplayField ' + name + ' = new DisplayField(' + container + ', "'  + label +  '")';
    } else if(xtype == 'checkbox' || xtypes.indexOf('/checkbox/') != -1){
        name = getVarName(label || item.boxLabel) + 'Checkbox';
        code += 'Checkbox ' + name + ' = new Checkbox(' + container + ', "'  + (label || item.boxLabel) +  '")';
    } else if(xtype == 'button' || xtypes.indexOf('/button/') != -1){
        name = getVarName(item.text) + 'Button';
        code += 'Button ' + name + ' = new Button(' + container + ', "'  + item.text +  '")';
    } else if(!isNecesaryType(xtype, xtypes)){
        code = '';
    } else {
        //code += 'XYZ xyz = new XYZ("' + xtype + '", "' + xtypes + '")';
		code = '';
        console.warn(container, item, xtype, xtypes, item.id);
    }
    if(code != ''){
        code += ';';
        if(logId){
            code += '// ' + item.id;
        }
        code += '\n';
    }
    return {
        code: code,
        name: name
    };
}

function isNecesaryType(xtype, xtypes){
	var necesary = true;
	if(xtype == 'hidden' || xtypes.indexOf('/hidden/') != -1){
        necesary = false;
    } else if(xtype == 'tbfill' || xtypes.indexOf('/tbfill/') != -1){
        necesary = false;
    } else if(xtype == 'tbtext' || xtypes.indexOf('/tbtext/') != -1){
        necesary = false;
    } else if(xtype == 'tbspacer' || xtypes.indexOf('/tbspacer/') != -1){
        necesary = false;
    } else if(xtype == 'tbseparator' || xtypes.indexOf('/tbseparator/') != -1){
        necesary = false;
    } else if(xtype == 'box' || xtypes.indexOf('/box/') != -1){
        necesary = false; // TODO this is temporary
    }
	return necesary;
}

function isTabPanel(item){
    return item.getXType() == 'tabpanel' || item.getXTypes().indexOf('/tabpanel/') != -1;
}

function getEachElementsCode(container, items, isTab){
    var code = '';
    if(items){
        if (Ext.isArray(items)){
            for(var i = 0, len = items.length; i < len; i++){
                code += getItemsCode(container, items[i]);
            }
        } else {
            items.each(function(it){
                var c = container;
                if(isTab){
                    c = getVarName(it.title) + 'TabPanel';
                    code += '\tpublic TabPanel ' + c + ' = new TabPanel(' + container + ', "' + it.title +  '");\n';
                }
                code += getItemsCode(c, it);
            });
        }
    }

    return code;
}

function getItemsCode(container, item){
    //console.debug('getItemsCode', container, item);
    var elements,
        code = '',
        tbar = item.getTopToolbar ? item.getTopToolbar() : false,
        bbar = item.getBottomToolbar ? item.getBottomToolbar(): false,
        fbar = w.getFooterToolbar ? w.getFooterToolbar(): false;

    var isTab = isTabPanel(item);
    if(!isTab){
        elements = getItemCode(container, item);
        code += elements.code;
        container = elements.name || container;
    }
    code += getEachElementsCode(container, item.items, isTab);
    if(tbar){
        code += getEachElementsCode(container, tbar.items, false);
    }
    if(bbar){
        code += getEachElementsCode(container, bbar.items, false);
    }
    if(fbar){
        code += getEachElementsCode(container, fbar.items, false);
    }

    return code;
}

function getActiveWinClassCode(){
    var w = Ext.WindowMgr.getActive(),
        name = getVarName(w.title),
        code,
        container = 'this';
    console.debug('getActiveWinClassCode', name);
    code = 'public class ' + name + 'Window extends Window {\n';
    code += '\tpublic ' + name + 'Window(){\n';
    code += '\t\tsetTitle("' + w.title + '");\n\t}\n';
    w.items.each(function(it){
        code += getItemsCode(container, it);
    });

    var tbar = w.getTopToolbar ? w.getTopToolbar() : false,
        bbar = w.getBottomToolbar ? w.getBottomToolbar(): false,
        fbar = w.getFooterToolbar ? w.getFooterToolbar(): false;

    if(tbar){
        code += getEachElementsCode(container, tbar.items, false);
    }
    if(bbar){
        code += getEachElementsCode(container, bbar.items, false);
    }
    if(fbar){
        code += getEachElementsCode(container, fbar.items, false);
    }

    code += '}\n';
    return code;
}

console.info('\n'+ getActiveWinClassCode());<commit_msg>organize and pack functions in one object and reuse some code.<commit_after>// TODO in EditorGridPanel add clickToEdit option new EditorGridPanel(this).setClicksToEdit(2)
// TODO fieldLabel must have ":" have labelSeparator

var _classGen = {
    logId: true,
    elemCount: 0,

    getVarName: function(name){
        name = name ? name : 'item' + (_classGen.elemCount++);
        // remove spaces and capitalize each word
        var words = name.split(/\s/);
        Ext.each(words, function(w, i){
            words[i] = Ext.util.Format.capitalize(w);
        });
        name = words.join('');

        name = name.replace(/[\(\)/\\:;\<>=\-"]/gi, '');
        //name = Ext.util.Format.capitalize(name);
        return !name ? name : name.charAt(0).toLowerCase() + name.substr(1);
    },

    getPanelConfig: function (item){
        var code = '';
        if(item.title){
            code += '.setTitle("' + item.title + '")';
        } else if(item.fieldLabel){
            code += '.setLabel("' + item.fieldLabel + '")';
        }
        return code;
    },

    getItemCode: function (container, item){
        var name = '',
            code = '\tpublic ',
            xtype = item.getXType(),
            xtypes = item.getXTypes(),
            label = item.fieldLabel + (item.ownerCt.getLayout().labelSeparator || '');

        //console.debug('getItemCode', container, item);
        if(xtype == 'editorgrid' || xtypes.indexOf('/editorgrid/') != -1 || item instanceof Ext.grid.EditorGridPanel){
            name = _classGen.getVarName(item.title) + 'EditorGridPanel';
            code += 'EditorGridPanel ' + name + ' = new EditorGridPanel(' + container + ')';
            code += _classGen.getPanelConfig(item);
        } else if(xtype == 'grid' || xtypes.indexOf('/grid/') != -1 || item instanceof Ext.grid.GridPanel){
            name = _classGen.getVarName(item.title) + 'GridPanel';
            code += 'GridPanel ' + name + ' = new GridPanel(' + container + ')';
            code += _classGen.getPanelConfig(item);
        } else if(xtype == 'panel' || xtypes.indexOf('/panel/') != -1 || item instanceof Ext.Panel){
            console.debug('panel item:', item.id, item);
            name = _classGen.getVarName(item.title) + 'Panel';
            code += 'Panel ' + name + ' = new Panel(' + container + ')';
            code += _classGen.getPanelConfig(item);
        } else if(xtype == 'combo' || xtypes.indexOf('/combo/') != -1){
            name = _classGen.getVarName(label) + 'ComboBox';
            code += 'ComboBox ' + name + ' = new ComboBox(' + container + ', "' + label +  '")';
        } else if(xtype == 'textarea' || xtypes.indexOf('/textarea/') != -1){
            name = _classGen.getVarName(label) + 'TextArea';
            code += 'TextArea ' + name + ' = new TextArea(' + container + ', "'  + label +  '")';
        } else if(xtype == 'textfield' || xtypes.indexOf('/textfield/') != -1){
            name = _classGen.getVarName(label) + 'TextField';
            code += 'TextField ' + name + ' = new TextField(' + container + ', "'  + label +  '")';
        } else if(xtype == 'displayfield' || xtypes.indexOf('/displayfield/') != -1){
            name = _classGen.getVarName(label) + 'DisplayField';
            code += 'DisplayField ' + name + ' = new DisplayField(' + container + ', "'  + label +  '")';
        } else if(xtype == 'checkbox' || xtypes.indexOf('/checkbox/') != -1){
            name = _classGen.getVarName(label || item.boxLabel) + 'Checkbox';
            code += 'Checkbox ' + name + ' = new Checkbox(' + container + ', "'  + (label || item.boxLabel) +  '")';
        } else if(xtype == 'button' || xtypes.indexOf('/button/') != -1){
            name = _classGen.getVarName(item.text) + 'Button';
            code += 'Button ' + name + ' = new Button(' + container + ', "'  + item.text +  '")';
        } else if(!_classGen.isNecesaryType(xtype, xtypes)){
            code = '';
        } else {
            //code += 'XYZ xyz = new XYZ("' + xtype + '", "' + xtypes + '")';
            code = '';
            console.warn(container, item, xtype, xtypes, item.id);
        }
        if(code != ''){
            code += ';';
            if(_classGen.logId){
                code += '// ' + item.id;
            }
            code += '\n';
        }
        return {
            code: code,
            name: name
        };
    },

    isNecesaryType : function (xtype, xtypes){
        var necesary = true;
        if(xtype == 'hidden' || xtypes.indexOf('/hidden/') != -1){
            necesary = false;
        } else if(xtype == 'tbfill' || xtypes.indexOf('/tbfill/') != -1){
            necesary = false;
        } else if(xtype == 'tbtext' || xtypes.indexOf('/tbtext/') != -1){
            necesary = false;
        } else if(xtype == 'tbspacer' || xtypes.indexOf('/tbspacer/') != -1){
            necesary = false;
        } else if(xtype == 'tbseparator' || xtypes.indexOf('/tbseparator/') != -1){
            necesary = false;
        } else if(xtype == 'box' || xtypes.indexOf('/box/') != -1){
            necesary = false; // TODO this is temporary
        }
        return necesary;
    },

    isTabPanel : function (item){
        return item.getXType() == 'tabpanel' || item.getXTypes().indexOf('/tabpanel/') != -1;
    },

    getEachElementsCode : function (container, items, isTab){
        var code = '';
        if(items){
            if (Ext.isArray(items)){
                for(var i = 0, len = items.length; i < len; i++){
                    code += _classGen.getItemsCode(container, items[i]);
                }
            } else {
                items.each(function(it){
                    var c = container;
                    if(isTab){
                        c = _classGen.getVarName(it.title) + 'TabPanel';
                        code += '\tpublic TabPanel ' + c + ' = new TabPanel(' + container + ', "' + it.title +  '");\n';
                    }
                    code += _classGen.getItemsCode(c, it);
                });
            }
        }

        return code;
    },

    getItemsCode: function (container, item){
        //console.debug('getItemsCode', container, item);
        var elements,
            code = '';

        var isTab = _classGen.isTabPanel(item);
        if(!isTab){
            elements = _classGen.getItemCode(container, item);
            code += elements.code;
            container = elements.name || container;
        }

        code += _classGen.getInsideItems(container, item, isTab);

        return code;
    },

    getInsideItems: function(container, item, isTab){
        var code = '',
            tbar = item.getTopToolbar ? item.getTopToolbar() : false,
            bbar = item.getBottomToolbar ? item.getBottomToolbar(): false,
            fbar = item.getFooterToolbar ? item.getFooterToolbar(): false;

        code += _classGen.getEachElementsCode(container, item.items, isTab);
        if(tbar){
            code += _classGen.getEachElementsCode(container, tbar.items, false);
        }
        if(bbar){
            code += _classGen.getEachElementsCode(container, bbar.items, false);
        }
        if(fbar){
            code += _classGen.getEachElementsCode(container, fbar.items, false);
        }
        return code;
    },

    getActiveWinClassCode : function (){
        var w = Ext.WindowMgr.getActive(),
            name = _classGen.getVarName(w.title),
            code,
            container = 'this';
        console.debug('getActiveWinClassCode', name);
        code = 'public class ' + name + 'Window extends Window {\n';
        code += '\tpublic ' + name + 'Window(){\n';
        code += '\t\tsetTitle("' + w.title + '");\n';
        code += '\t}\n';

        code += _classGen.getInsideItems(container, w, false);

        code += '}\n';
        return code;
    }
};

console.info('\n'+ _classGen.getActiveWinClassCode());<|endoftext|>


<commit_before>'use strict'
/* node = {
    characteristics: [],
    type: string,
    parent: node
    children: []
    max-children: Number,
    description: string
 }*/

 // TODO: Characteristics also need a type, so that we don't end up redefining it.

// TODO: Characteristic types:
// Neighbor
// thing (number of)
// Most prominent feature (link to a child?)

// TODO: Make walk more sticky, or make it go down more often.
// TODO: Can specify what type and how many of each child you have.
// TODO: Similarly, can specify what type and how many of each characteristic you have
// TODO: Specify siblings?

import {randRange, randomLetter, choose} from './random'

function dateGenerator() {
  let newDate = randRange(1, 30000) + ' ' + randomLetter().toUpperCase() + randomLetter().toUpperCase();

  if (Math.random() < 0.25) {
    newDate += randomLetter().toUpperCase();
  }

  return newDate;
}

function generateClassificationName(len) {
  len = len || randRange(2, 8);
  let name = '';
  while (name.length < len)
  {
    const add = Math.random().toString(36).slice(2);
    name += add.slice(0, Math.min(add.length, (len - name.length)));
  }
  return name.toUpperCase();
}

class AnsibleAtom {
  constructor() {
    this.parent = null;
    this.children = [];
    this.maxChildren = 0;
    this.maxCharacteristics = 0;
    this.name = '';
    this.description = '';
    this.characteristics = [];
  }

  _generateCharacteristic() {
    return '';
  }

  _generateNewChild() {
    return null;
  }

  discoverNewChild() {
    const child = this._generateNewChild();
    if (!child) {
        return null;
    }

    child.parent = this;
    this.children.push(child);
    return child;
  }

  discoverNewCharacteristic() {
    const characteristic = this._generateCharacteristic();
    this.characteristics.push(characteristic);
    return characteristic;
  }

  isTerminal() {
    return this.maxChildren === 0 && this.maxCharacteristics === 0;
  }
}

class BlackHole extends AnsibleAtom {
  constructor() {
    super();
    this.maxChildren = 0;
    this.maxCharacteristics = 10000;
    this.name = generateClassificationName();
    const years = Math.random() * 1000;
    const size = Math.random() * 1000;
    this.description = `This black hole will last for ${years} years, and is ${size} km large.`;
  }

  _generateCharacteristic() {
    return choose(['A', 'B', 'C', 'D']) + ' ' + choose(['1', '2', '3', '4']);
  }
}

class SolarSystem extends AnsibleAtom {
  constructor() {
    super();
    this.maxChildren = 0;
    this.maxCharacteristics = 10000;
    this.name = generateClassificationName();
    const years = Math.random() * 1000;
    const size = Math.random() * 1000;
    this.description = 'This solar system is \'uge!';
  }

  _generateCharacteristic() {
    return choose(['A', 'B', 'C', 'D']) + ' ' + choose(['1', '2', '3', '4']);
  }
}

// TODO: How should this relate to, eg creators of the monument? Should it be done this way
// or should it be done differently? How do characteristics work?
class Monument extends AnsibleAtom {
  constructor() {
    super();
    this.name = Monument._generateName();
    this.maxCharacteristics = 0;
    this.maxChildren = 0;
    this.description = Monument._generateDescription();
  }

  static _generateName() {
    return choose(['Grafla', 'Dkejifs', 'dsafje', 'Gef a ', 'The Space Needle', 'SDjkle', 'SDFe']);
  }

  static _generateDescription() {
    // TODO: don't do a choose, need to pick 2 from the range.
    var physical = () => {
      return choose(['ancient', 'old', 'crumbling', 'historic', 'royal', 'imperial', 'sunken', 'twisted', 'lucky', 'magnificient', 'glorious', 'shining', 'tall', 'cracked', 'great', 'big', 'huge', 'giant', 'grand', 'gigantic', 'colossal', 'tremendous', 'gargantuan', 'moss-covered', 'haloed', 'gleaming']);
    }

    let description = 'This monument is a ';
    const numPhysical = randRange(1, 2);
    for (var i = 0; i < numPhysical; i++) {
      description += physical();
      if (i < numPhysical-1) {
        description += ', ';
      }
    }

    description += ' ';
    if (Math.random() < 0.9) {
      description += choose(['stone', 'gold', 'copper', 'bronze', 'silver', 'white', 'black', 'green', 'gray', 'obsidian', 'wooden']);
      description += ' ';
    }

    // TODO: Fix, as these are not unique.
    description += choose(['tower', choose('', 'smiling', 'proud', 'wise', 'crying', 'singing', 'laughing') + choose('statue', 'statues', 'colossus'), 'bridge', 'towers', 'spire', 'spires', 'cathedral', 'church', 'masoleum', 'maze', 'castle', 'fort', 'keep']);

    return description;
  }
}

class Galaxy extends AnsibleAtom {
  constructor() {
    super();
    this.maxChildren = 10000;
    this.maxCharacteristics = 10000;
    this.name = Galaxy._generateName();
    this.description = Galaxy._generateDescription();
  }

  _generateCharacteristic() {
    return choose(['Its nearest neighbor is ' + choose([Galaxy._generateName() + ' galaxy', 'a black hole', 'a dark matter reactor', 'the pocket universe ' + Galaxy._generateName()]), 'Its prominent feature is ' + choose(['a black hole', 'a dyson sphere', 'intelligent life', 'a historic event']), 'It has ' + Math.random() * 1000 + choose([' stars', ' planets', ' fast food joints'])]);
  }

  _generateNewChild() {
    const childType = choose([BlackHole, SolarSystem, Monument]);
    return new childType();
  }

  static _generateName() {
    const standardName = function() {
      return choose(['Andromeda', 'Big Daddy', 'Tencent', 'Fubar', 'Johnny', 'Sixty-O', 'Dfjsktisd', 'Lemonade']);
    };

    return choose([generateClassificationName, standardName])();
  }

  static _generateDescription() {
    const type = choose(['huge', 'giant', 'colossal', 'average', 'medium', 'small', 'tiny', 'miniscule']) + ' ' + choose(['grey', 'blue', 'green', 'rainbow', 'puke-colored', 'magenta', 'black as night']) + ' ' + choose(['elliptical', 'spherical', 'spiral', 'S0', 'irregular']);
    return (`It is a ${type} galaxy.`);
  }
}

export class RandomSensor {
    constructor() {
        this.currentNode = null;
    }

    retrieveData() {
        if (!this.currentNode) {
            // Let's start a node!
            this.currentNode = new Galaxy();
            return `Lets talk about ${this.currentNode.name}. ${this.currentNode.description}`;
        }

        const newNode = this.walk();
        if (this.currentNode != newNode) {
            this.currentNode = newNode;
            return `Lets talk about ${newNode.name}. ${newNode.description}`;
        }

        // We now have a current node. Decide if we want to print a characteristic about this node, or make a new child.
        if (Math.random() < 0.25 && this.currentNode.children < this.currentNode.maxChildren) {
            // Make a new child:
            const childNode = this.currentNode.discoverNewChild();
            if (!childNode.isTerminal()) {
              this.currentNode = childNode;
            }
            return `It has a child ${childNode.name}. ${childNode.description}`;
        } else if (Math.random() < 0.2) {
            return `We are talking about ${newNode.name}`;
        } else {
            return this.currentNode.discoverNewCharacteristic();
        }
    }

    walk() {
        let newNode = this.currentNode;
        const numSteps = Math.floor(Math.random()*5) + 1;
        let i = 0;
        for (i = 0; i < numSteps; i++) {
            if (this.currentNode.parent && Math.random() < 0.25) {
                newNode = this.currentNode.parent;
            } else if (this.currentNode.children.length > 0 && Math.random() < 0.25) {
                newNode = choose(this.currentNode.children);
            }
        }

        return newNode;
    }
}

export class StaticSensor {
    retrieveData() {
        return 'Earth is roughly a sphere.'
    }
};
<commit_msg>Atmoshperic generator.<commit_after>'use strict'
/* node = {
    characteristics: [],
    type: string,
    parent: node
    children: []
    max-children: Number,
    description: string
 }*/

 // TODO: Characteristics also need a type, so that we don't end up redefining it.

// TODO: Characteristic types:
// Neighbor
// thing (number of)
// Most prominent feature (link to a child?)

// TODO: Make walk more sticky, or make it go down more often.
// TODO: Can specify what type and how many of each child you have.
// TODO: Similarly, can specify what type and how many of each characteristic you have
// TODO: Specify siblings?

import {randRange, randomLetter, choose} from './random'

function dateGenerator() {
  let newDate = randRange(1, 30000) + ' ' + randomLetter().toUpperCase() + randomLetter().toUpperCase();

  if (Math.random() < 0.25) {
    newDate += randomLetter().toUpperCase();
  }

  return newDate;
}

function addIf(nodule, chance) {
  if (Math.random() <= chance) {
    return nodule;
  }

  return '';
}

function generateAtmosphere() {
  const atmosphereAdjective = function() {
    return choose(['wispy', 'noxious', 'fumey', 'sparse', 'heavy', 'dense', 'light', 'overbearing']);
  }

  const atmopshereElement = function() {
    return choose(['ammonia', 'oxygen', 'nitrogen', 'helium', 'hydrogen', 'dark matter']);
  }

  const description = addIf(choose(['purple', 'grey', 'white', 'blue', 'yellow', 'orange', 'tan', 'pink']) + ', ', 0.5) + atmosphereAdjective() + addIf(', and ' + atmosphereAdjective(), 0.25);
  if (Math.random() < 0.25) {
    return 'There is no atmopshere to speak of';
  }

  return choose(['The atmopshere is one of ' + atmopshereElement() + ' and is ' + description, 'The atmoshpere is full of ' + description + ' clouds, made of ' + atmopshereElement()]);

}

function generateClassificationName(len) {
  len = len || randRange(2, 8);
  let name = '';
  while (name.length < len)
  {
    const add = Math.random().toString(36).slice(2);
    name += add.slice(0, Math.min(add.length, (len - name.length)));
  }
  return name.toUpperCase();
}

class AnsibleAtom {
  constructor() {
    this.parent = null;
    this.children = [];
    this.maxChildren = 0;
    this.maxCharacteristics = 0;
    this.name = '';
    this.description = '';
    this.characteristics = [];
  }

  _generateCharacteristic() {
    return '';
  }

  _generateNewChild() {
    return null;
  }

  discoverNewChild() {
    const child = this._generateNewChild();
    if (!child) {
        return null;
    }

    child.parent = this;
    this.children.push(child);
    return child;
  }

  discoverNewCharacteristic() {
    const characteristic = this._generateCharacteristic();
    this.characteristics.push(characteristic);
    return characteristic;
  }

  isTerminal() {
    return this.maxChildren === 0 && this.maxCharacteristics === 0;
  }
}

class BlackHole extends AnsibleAtom {
  constructor() {
    super();
    this.maxChildren = 0;
    this.maxCharacteristics = 10000;
    this.name = generateClassificationName();
    const years = Math.random() * 1000;
    const size = Math.random() * 1000;
    this.description = `This black hole will last for ${years} years, and is ${size} km large.`;
  }

  _generateCharacteristic() {
    return choose(['A', 'B', 'C', 'D']) + ' ' + choose(['1', '2', '3', '4']);
  }
}

class SolarSystem extends AnsibleAtom {
  constructor() {
    super();
    this.maxChildren = 0;
    this.maxCharacteristics = 10000;
    this.name = generateClassificationName();
    const years = Math.random() * 1000;
    const size = Math.random() * 1000;
    this.description = 'This solar system is \'uge!';
  }

  _generateCharacteristic() {
    return choose(['A', 'B', 'C', 'D']) + ' ' + choose(['1', '2', '3', '4']);
  }
}

// TODO: How should this relate to, eg creators of the monument? Should it be done this way
// or should it be done differently? How do characteristics work?
class Monument extends AnsibleAtom {
  constructor() {
    super();
    this.name = Monument._generateName();
    this.maxCharacteristics = 0;
    this.maxChildren = 0;
    this.description = Monument._generateDescription();
  }

  static _generateName() {
    return choose(['Grafla', 'Dkejifs', 'dsafje', 'Gef a ', 'The Space Needle', 'SDjkle', 'SDFe']);
  }

  static _generateDescription() {
    // TODO: don't do a choose, need to pick 2 from the range.
    var physical = () => {
      return choose(['ancient', 'old', 'crumbling', 'historic', 'royal', 'imperial', 'sunken', 'twisted', 'lucky', 'magnificient', 'glorious', 'shining', 'tall', 'cracked', 'great', 'big', 'huge', 'giant', 'grand', 'gigantic', 'colossal', 'tremendous', 'gargantuan', 'moss-covered', 'haloed', 'gleaming']);
    }

    let description = 'This monument is a ';
    const numPhysical = randRange(1, 2);
    for (var i = 0; i < numPhysical; i++) {
      description += physical();
      if (i < numPhysical-1) {
        description += ', ';
      }
    }

    description += ' ';
    if (Math.random() < 0.9) {
      description += choose(['stone', 'gold', 'copper', 'bronze', 'silver', 'white', 'black', 'green', 'gray', 'obsidian', 'wooden']);
      description += ' ';
    }

    // TODO: Fix, as these are not unique.
    description += choose(['tower', choose('', 'smiling', 'proud', 'wise', 'crying', 'singing', 'laughing') + choose('statue', 'statues', 'colossus'), 'bridge', 'towers', 'spire', 'spires', 'cathedral', 'church', 'masoleum', 'maze', 'castle', 'fort', 'keep']);

    return description;
  }
}

class Galaxy extends AnsibleAtom {
  constructor() {
    super();
    this.maxChildren = 10000;
    this.maxCharacteristics = 10000;
    this.name = Galaxy._generateName();
    this.description = Galaxy._generateDescription();
  }

  _generateCharacteristic() {
    return choose(['Its nearest neighbor is ' + choose([Galaxy._generateName() + ' galaxy', 'a black hole', 'a dark matter reactor', 'the pocket universe ' + Galaxy._generateName()]), 'Its prominent feature is ' + choose(['a black hole', 'a dyson sphere', 'intelligent life', 'a historic event']), 'It has ' + Math.random() * 1000 + choose([' stars', ' planets', ' fast food joints'])]);
  }

  _generateNewChild() {
    const childType = choose([BlackHole, SolarSystem, Monument]);
    return new childType();
  }

  static _generateName() {
    const standardName = function() {
      return choose(['Andromeda', 'Big Daddy', 'Tencent', 'Fubar', 'Johnny', 'Sixty-O', 'Dfjsktisd', 'Lemonade']);
    };

    return choose([generateClassificationName, standardName])();
  }

  static _generateDescription() {
    const type = choose(['huge', 'giant', 'colossal', 'average', 'medium', 'small', 'tiny', 'miniscule']) + ' ' + choose(['grey', 'blue', 'green', 'rainbow', 'puke-colored', 'magenta', 'black as night']) + ' ' + choose(['elliptical', 'spherical', 'spiral', 'S0', 'irregular']);
    return (`It is a ${type} galaxy.`);
  }
}

export class RandomSensor {
    constructor() {
        this.currentNode = null;
    }

    retrieveData() {
      return generateAtmosphere();
        if (!this.currentNode) {
            // Let's start a node!
            this.currentNode = new Galaxy();
            return `Lets talk about ${this.currentNode.name}. ${this.currentNode.description}`;
        }

        const newNode = this.walk();
        if (this.currentNode != newNode) {
            this.currentNode = newNode;
            return `Lets talk about ${newNode.name}. ${newNode.description}`;
        }

        // We now have a current node. Decide if we want to print a characteristic about this node, or make a new child.
        if (Math.random() < 0.25 && this.currentNode.children < this.currentNode.maxChildren) {
            // Make a new child:
            const childNode = this.currentNode.discoverNewChild();
            if (!childNode.isTerminal()) {
              this.currentNode = childNode;
            }
            return `It has a child ${childNode.name}. ${childNode.description}`;
        } else if (Math.random() < 0.2) {
            return `We are talking about ${newNode.name}`;
        } else {
            return this.currentNode.discoverNewCharacteristic();
        }
    }

    walk() {
        let newNode = this.currentNode;
        const numSteps = Math.floor(Math.random()*5) + 1;
        let i = 0;
        for (i = 0; i < numSteps; i++) {
            if (this.currentNode.parent && Math.random() < 0.25) {
                newNode = this.currentNode.parent;
            } else if (this.currentNode.children.length > 0 && Math.random() < 0.25) {
                newNode = choose(this.currentNode.children);
            }
        }

        return newNode;
    }
}

export class StaticSensor {
    retrieveData() {
        return 'Earth is roughly a sphere.'
    }
};
<|endoftext|>


<commit_before><commit_msg>implement new ICOllectionAdapter interface methods<commit_after><|endoftext|>


<commit_before>////////////////////////////////////////
// ADFSUserMappingAPI
//
// Copyright (c) 2017 Jonathan Hardison
////////////////////////////////////////

import http from 'http';
import express from 'express';
import bodyParser from 'body-parser';

import config from './config';
import routes from './routes';

// consts //
let app = express();
app.server = http.createServer(app);

// middleware //
app.use(bodyParser.json({
    limit: config.bodyLimit
}));

// all routes and versions in routes //
app.use('/', routes);

// listen and binding setup //
app.server.listen(config.port);
console.log(`Started API Service on port: ${app.server.address().port}`);

export default app;<commit_msg>adding cross domain<commit_after>////////////////////////////////////////
// ADFSUserMappingAPI
//
// Copyright (c) 2017 Jonathan Hardison
////////////////////////////////////////

import http from 'http';
import express from 'express';
import bodyParser from 'body-parser';

import config from './config';
import routes from './routes';

// consts //
let app = express();
app.server = http.createServer(app);

// middleware //
app.use(bodyParser.json({
    limit: config.bodyLimit
}));

app.use(allowCrossDomain);

// all routes and versions in routes //
app.use('/', routes);

// listen and binding setup //
app.server.listen(config.port);
console.log(`Started API Service on port: ${app.server.address().port}`);

export default app;<|endoftext|>


<commit_before>// https://github.com/kriasoft/react-starter-kit/blob/master/docs/recipes/how-to-implement-routing.md

/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */
import moment from 'moment';
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import expressJwt from 'express-jwt';
import expressGraphQL from 'express-graphql';
import jwt from 'jsonwebtoken';
import PrettyError from 'pretty-error';
import _httpErrorPages from 'http-error-pages';
import ical from 'ical-generator';

import schema from './data/schema';

import { handleCalendarWebhook, handleTwilioWebhook } from './hooks';
// import { logLogin } from './data/database/login';
import { reactMiddleware, reactErrorMiddleware } from './reactMiddleware';
import API from './api/';

import config from './config';

const PEOPLE_PREFIX = 'people/';

const app = express();

//
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the
// user agent is not known.
// -----------------------------------------------------------------------------
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';

//
// Register Node.js middleware
// -----------------------------------------------------------------------------
app.use(express.static(path.resolve(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

const cal = ical({
  domain: config.app.workDomain,
  name: config.app.workCalendar,
});

//
// Authentication
// -----------------------------------------------------------------------------
function checkingUser(req, _payload, done) {
  const secret = config.auth.jwt.secret;
  // req.payload = { foo: 'bar' };
  // console.log(`checking req.url`, req.url);
  // console.log(`payload`, payload);
  // if (payload.data) {
  //   logLogin(payload.data.username, payload);
  // }
  done(null, secret);
}

function populatePayload(req, _res, next) {
  const token = req.cookies.token;
  if (token) {
    const decoded = jwt.verify(token, config.auth.jwt.secret);
    req.payload = decoded;
  }
  return next();
}

/* bot denial */
app.use((req, res, next) => {
  if (req.headers.from === 'googlebot(at)googlebot.com') {
    return res.status(401).json({
      message: 'Unathorized Access',
    });
  }
  return next();
});

/* to populate cross cookies, tech debt */
app.use((req, res, next) => {
  if (req.query.token) {
    // console.log('req.query.token', req.query.token);
    const expiresIn = 60 * 60 * 24 * 180; // 180 days
    res.cookie('token', req.query.token, {
      maxAge: 1000 * expiresIn,
      httpOnly: true,
    });
    /* tech debt */
    res.cookie('jwt', req.query.token, {
      maxAge: 1000 * expiresIn,
      httpOnly: true,
    });
    return next();
  }
  return next();
});

app.use(
  expressJwt({
    secret: checkingUser,
    credentialsRequired: true,
    getToken: function fromHeaderOrQuerystring(req) {
      // console.log(`Object.keys(req)`, Object.keys(req));
      if (req.cookies.token) {
        return req.cookies.token;
      } else if (req.query && req.query.token) {
        return req.query.token;
      }
      return null;
    },
  }).unless({
    path: [
      '/graphql',
      '/events/calendar',
      /\/general*/,
      /\/assets*/,
      /\/page+/,
      /\/p+/,
      /\/api+/,
      /\/webhooks+/,
    ],
  }),
);
// Error handler for express-jwt
app.use(populatePayload);
app.use(reactErrorMiddleware);

//
// Register API middleware
// -----------------------------------------------------------------------------
app.use(
  '/graphql',
  expressGraphQL(async req => ({
    schema,
    graphiql: __DEV__,
    rootValue: { request: req },
    pretty: __DEV__,
  })),
);

app.use('/events/calendar', async (req, res) => {
  await handleCalendarWebhook(req.headers);
  res.sendStatus(200);
});

app.use('/webhooks/twilio', async (req, res) => {
  handleTwilioWebhook(req, res);
});

app.use('/public/appointment/confirm/:eventId', async (req, res) => {
  const { eventId } = req.params;
  await API({ action: 'patchEvent', status: 'confirmed', eventId });
  res.status(200);
  res.send(
    `<!doctype html><html><body style="background-color:#373277"><h1><center><span style="color:white">Your Appointment is confirmed!</span></center></h1></body></html>`,
  );
});

app.use('/general/confirmation/:eventId', async (req, res, next) => {
  const { eventId } = req.params;

  if (eventId === 'images') return;

  const event = await API({ action: 'getEvent', eventId });
  req.data = { event, workAddress: config.app.workAddress };
  await API({
    action: 'patchEvent',
    status: 'confirmed',
    confirmed: moment().format('lll'),
    eventId,
  });

  reactMiddleware(req, res, next);
});

app.use('/general/reservation/:eventId', async (req, res, next) => {
  const { eventId } = req.params;

  if (eventId === 'images') return;
  const event = await API({ action: 'getEvent', eventId });
  req.data = { event, workAddress: config.app.workAddress };

  const now = moment();
  const appointmentEnd = moment(event.end.dateTime);
  // eslint-disable-next-line consistent-return
  if (now.isAfter(appointmentEnd)) {
    res.redirect('/');
  } else {
    reactMiddleware(req, res, next);
  }
});

app.use('/general/calendar/:eventId', async (req, res) => {
  const { eventId } = req.params;

  if (eventId === 'images') return;
  const event = await API({ action: 'getEvent', eventId });
  // req.data = { event, workAddress: config.app.workAddress };

  const customerId = event.extendedProperties.shared.resourceName;

  cal.createEvent({
    start: event.start.dateTime,
    end: event.end.dateTime,
    summary: 'Rare Beauty Appointment',
    description: `
We do Lashes, Facial, Waxing, Threading and More

Appointment(s) are found @ ${config.app.customerURL}/${customerId.substring(
      PEOPLE_PREFIX.length,
      customerId.length,
    )}/appointments
    `,
    location: config.app.workAddress,
    url:
      (event.extendedProperties && event.extendedProperties.shared.shortURL) ||
      config.app.workDomain,
  });

  // eslint-disable-next-line consistent-return
  return cal.serve(res);
  // next(req, res, next);
});

//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
app.use('*', reactMiddleware);

//
// Error handling
// -----------------------------------------------------------------------------
if (__DEV__) {
  const pe = new PrettyError();
  pe.skipNodeFiles();
  pe.skipPackage('express');

  // eslint-disable-next-line no-unused-vars
  app.use(reactErrorMiddleware);
} else {
  _httpErrorPages(app);
}

//
// Launch the server
// -----------------------------------------------------------------------------
if (!module.hot) {
  app.listen(config.port, () => {
    console.info(`The server is running at http://localhost:${config.port}/`);
  });
} else {
  // development mode
  app.hot = module.hot;
  module.hot.accept('./router');
}

export default app;
<commit_msg>server error<commit_after>// https://github.com/kriasoft/react-starter-kit/blob/master/docs/recipes/how-to-implement-routing.md

/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */
import moment from 'moment';
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import expressJwt from 'express-jwt';
import expressGraphQL from 'express-graphql';
import jwt from 'jsonwebtoken';
import PrettyError from 'pretty-error';
import _httpErrorPages from 'http-error-pages';
import ical from 'ical-generator';

import schema from './data/schema';

import { handleCalendarWebhook, handleTwilioWebhook } from './hooks';
// import { logLogin } from './data/database/login';
import { reactMiddleware, reactErrorMiddleware } from './reactMiddleware';
import API from './api/';

import config from './config';

const PEOPLE_PREFIX = 'people/';

const app = express();

//
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the
// user agent is not known.
// -----------------------------------------------------------------------------
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';

//
// Register Node.js middleware
// -----------------------------------------------------------------------------
app.use(express.static(path.resolve(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

const cal = ical({
  domain: config.app.workDomain,
  name: config.app.workCalendar,
});

//
// Authentication
// -----------------------------------------------------------------------------
function checkingUser(req, _payload, done) {
  const secret = config.auth.jwt.secret;
  // req.payload = { foo: 'bar' };
  // console.log(`checking req.url`, req.url);
  // console.log(`payload`, payload);
  // if (payload.data) {
  //   logLogin(payload.data.username, payload);
  // }
  done(null, secret);
}

function populatePayload(req, _res, next) {
  const token = req.cookies.token;
  if (token) {
    const decoded = jwt.verify(token, config.auth.jwt.secret);
    req.payload = decoded;
  }
  return next();
}

/* bot denial */
app.use((req, res, next) => {
  if (req.headers.from === 'googlebot(at)googlebot.com') {
    return res.status(401).json({
      message: 'Unathorized Access',
    });
  }
  return next();
});

/* to populate cross cookies, tech debt */
app.use((req, res, next) => {
  if (req.query.token) {
    // console.log('req.query.token', req.query.token);
    const expiresIn = 60 * 60 * 24 * 180; // 180 days
    res.cookie('token', req.query.token, {
      maxAge: 1000 * expiresIn,
      httpOnly: true,
    });
    /* tech debt */
    res.cookie('jwt', req.query.token, {
      maxAge: 1000 * expiresIn,
      httpOnly: true,
    });
    return next();
  }
  return next();
});

app.use(
  expressJwt({
    secret: checkingUser,
    credentialsRequired: true,
    getToken: function fromHeaderOrQuerystring(req) {
      // console.log(`Object.keys(req)`, Object.keys(req));
      if (req.cookies.token) {
        return req.cookies.token;
      } else if (req.query && req.query.token) {
        return req.query.token;
      }
      return null;
    },
  }).unless({
    path: [
      '/graphql',
      '/events/calendar',
      /\/general*/,
      /\/assets*/,
      /\/page+/,
      /\/p+/,
      /\/api+/,
      /\/webhooks+/,
    ],
  }),
);
// Error handler for express-jwt
app.use(populatePayload);
app.use(reactErrorMiddleware);

//
// Register API middleware
// -----------------------------------------------------------------------------
app.use(
  '/graphql',
  expressGraphQL(async req => ({
    schema,
    graphiql: __DEV__,
    rootValue: { request: req },
    pretty: __DEV__,
  })),
);

app.use('/events/calendar', async (req, res) => {
  try {
    await handleCalendarWebhook(req.headers);
  } catch (e) {
    console.error(`handleCalendarWebhook`, e);
  }
  res.sendStatus(200);
});

app.use('/webhooks/twilio', async (req, res) => {
  handleTwilioWebhook(req, res);
});

app.use('/public/appointment/confirm/:eventId', async (req, res) => {
  const { eventId } = req.params;
  await API({ action: 'patchEvent', status: 'confirmed', eventId });
  res.status(200);
  res.send(
    `<!doctype html><html><body style="background-color:#373277"><h1><center><span style="color:white">Your Appointment is confirmed!</span></center></h1></body></html>`,
  );
});

app.use('/general/confirmation/:eventId', async (req, res, next) => {
  const { eventId } = req.params;

  if (eventId === 'images') return;

  const event = await API({ action: 'getEvent', eventId });
  req.data = { event, workAddress: config.app.workAddress };
  await API({
    action: 'patchEvent',
    status: 'confirmed',
    confirmed: moment().format('lll'),
    eventId,
  });

  reactMiddleware(req, res, next);
});

app.use('/general/reservation/:eventId', async (req, res, next) => {
  const { eventId } = req.params;

  if (eventId === 'images') return;
  const event = await API({ action: 'getEvent', eventId });
  req.data = { event, workAddress: config.app.workAddress };

  const now = moment();
  const appointmentEnd = moment(event.end.dateTime);
  // eslint-disable-next-line consistent-return
  if (now.isAfter(appointmentEnd)) {
    res.redirect('/');
  } else {
    reactMiddleware(req, res, next);
  }
});

app.use('/general/calendar/:eventId', async (req, res) => {
  const { eventId } = req.params;

  if (eventId === 'images') return;
  const event = await API({ action: 'getEvent', eventId });
  // req.data = { event, workAddress: config.app.workAddress };

  const customerId = event.extendedProperties.shared.resourceName;

  cal.createEvent({
    start: event.start.dateTime,
    end: event.end.dateTime,
    summary: 'Rare Beauty Appointment',
    description: `
We do Lashes, Facial, Waxing, Threading and More

Appointment(s) are found @ ${config.app.customerURL}/${customerId.substring(
      PEOPLE_PREFIX.length,
      customerId.length,
    )}/appointments
    `,
    location: config.app.workAddress,
    url:
      (event.extendedProperties && event.extendedProperties.shared.shortURL) ||
      config.app.workDomain,
  });

  // eslint-disable-next-line consistent-return
  return cal.serve(res);
  // next(req, res, next);
});

//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
app.use('*', reactMiddleware);

//
// Error handling
// -----------------------------------------------------------------------------
if (__DEV__) {
  const pe = new PrettyError();
  pe.skipNodeFiles();
  pe.skipPackage('express');

  // eslint-disable-next-line no-unused-vars
  app.use(reactErrorMiddleware);
} else {
  _httpErrorPages(app);
}

//
// Launch the server
// -----------------------------------------------------------------------------
if (!module.hot) {
  app.listen(config.port, () => {
    console.info(`The server is running at http://localhost:${config.port}/`);
  });
} else {
  // development mode
  app.hot = module.hot;
  module.hot.accept('./router');
}

export default app;
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
app.use('/', express.static('www'));

var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Basic node server listening at http://%s:%s', host, port);
});

<commit_msg>whitespace<commit_after>var express = require('express');
var app = express();
app.use('/', express.static('www'));

var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Basic node server listening at http://%s:%s', host, port);
});<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var dotenv = require('dotenv');
var fs = require('fs');
var turf = require('turf');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var HttpStatus = require('http-status-codes');
var lineReader = require('line-reader');
var uuid = require('node-uuid');
var nosql = require('nosql');

var imageTypes = {
    'Landsat': 2,
    'Sentinel': 4
};

var expressLogFile = fs.createWriteStream(__dirname + '/express.log', {
    flags: 'a'
});

var app = express();
app.use(morgan('combined', {
    stream: expressLogFile
}));
var jsonParser = bodyParser.json();
app.use(expressValidator());
app.disable('x-powered-by');
dotenv.load();

var port = process.env.PORT || 3000;
var dbObservations = nosql.load('./db/ew_observations.nosql');
dbObservations.description('Earthwatchers observations.');

var router = express.Router();

//TODO where to put this
function arraySearch(arr, val) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === val) {
            return i;
        }
    }
    return -1;
}

function nocache(req, res, next) {
    res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
    res.header('Expires', '-1');
    res.header('Pragma', 'no-cache');
    next();
}

// get root document
router.get('/', function (req, res) {
    res.json({
        message: 'Earthwatchers serverside'
    });
});

// get the version
router.get('/version', function (req, res) {
    res.json({
        message: 'Version 0.2'
    });
});

// get statistics for a project
router.get('/statistics/:project', nocache, function (req, res) {
    // sampleurl : observations/Borneo
    var projectName = req.params.project;
    console.log('request observations for project: ' + projectName);

    var observations = 0;
    var users = [];
    var hexagons = [];

    dbObservations.each(function (observation) {
        if (observation.project === projectName) {
            //search for unique users
            if (arraySearch(users, observation.user) === -1) {
                users.push(observation.user);
            }

            //search for unique hexagons
            if (arraySearch(hexagons, observation.geohex) === -1) {
                hexagons.push(observation.geohex);
            }
            observations++;
        }
    }, function (err) {
        console.log('observations:' + observations + ', hexagons:' + hexagons.length + ', users: ' + users.length);
        var returnObject = {
            "project": projectName,
            "observations": observations,
            "hexagons": hexagons,
            "users": users
        };
        res.status(HttpStatus.OK).send(returnObject);
    });
});

// get observations for a project and user
router.get('/observations/:project/:username', nocache, function (req, res) {
    // sampleurl : observations/Borneo/bert
    var project = req.params.project;
    var username = req.params.username;
    console.log('Request observations for project: ' + project + ', username: ' + username);

    var observations = 0;
    var hexagons = [];

    dbObservations.each(function (observation) {
        if (observation.project === project && observation.user === username) {
            //search for unique hexagons
            if (arraySearch(hexagons, observation.geohex) === -1) {
                hexagons.push(observation.geohex);
            }
            observations++;
        }
    }, function (err) {
        console.log('observations:' + observations + ', hexagons:' + hexagons.length);
        var returnObject = {
            "project": project,
            "observations": observations,
            "hexagons": hexagons.length,
            "user": username
        };
        res.status(HttpStatus.OK).send(returnObject);
    });
});

// get observations for a project, hexagon and user
router.get('/observations/:project/:geohexcode/:username', nocache, function (req, res) {
    // sampleurl : observations/Borneo/PO2632/bert
    var project = req.params.project;
    var geohexcode = req.params.geohexcode;
    var username = req.params.username;
    console.log('request observations for project: ' + project + ', geohexcode:' + geohexcode + ', username: ' + username);

    dbObservations.all(function (doc) {
        return (doc.project === project && doc.geohex === geohexcode && doc.user === username);
    }, function (error, selected) {
        res.status(HttpStatus.OK).send(selected);
    });
});

// spatial select the stalliteimages that intersect with client envelope
// example request:
// /satelliteimages?bbox=111.68,0.14,111.69,0.15&imagetype=Landsat
router.get('/satelliteimages', function (req, res) {
    var bboxPar = req.query.bbox;
    var imageType = req.query.imagetype;
    if (bboxPar !== null || imageType !== null) {
        var imageTypeNr = imageTypes[imageType];

        var bbox = bboxPar.split(',');
        for (var i = 0, len = bbox.length; i < len; i++) {
            bbox[i] = parseFloat(bbox[i]);
        }
        var poly = turf.bboxPolygon(bbox);

        var satelliteimages = fs.readFileSync(__dirname + '/satelliteimages.geojson', 'utf8');
        var jsonSatelliteImages = JSON.parse(satelliteimages);
        var selectedSatelliteImages = [];
        for (var f in jsonSatelliteImages.features) {
            var intersection = turf.intersect(jsonSatelliteImages.features[f], poly);
            if (intersection != null) {
                if (jsonSatelliteImages.features[f].properties.ImageType === imageTypeNr) {
                    selectedSatelliteImages.push(jsonSatelliteImages.features[f]);
                }
            }
        }
        res.json(turf.featurecollection(selectedSatelliteImages));

    } else {
        res.status(HttpStatus.NOT_FOUND).send('Error: Parameter bbox not specified');
    }
});

// post an observation
router.post('/observations', jsonParser, function (req, res) {
    var id = uuid.v4();
    req.checkBody('user', 'User is required').notEmpty();
    req.checkBody('lat', 'lat is required').notEmpty();
    req.checkBody('lon', 'lon is required').notEmpty();
    req.checkBody('geohex', 'geohex is required').notEmpty();
    req.checkBody('observation', 'observation is required').notEmpty();
    req.checkBody('project', 'project is required').notEmpty();

    var errors = req.validationErrors();

    if (errors === null) {
        // delete previous clear observtions
        if(req.body.observation==="clear"){
            dbObservations.remove(function (doc) {
                    return (doc.observation === req.body.observation);
                }, function (error, count) {
                }
            );
        }
        req.body.date = new Date().toISOString();
        req.body.id = id;

        dbObservations.insert(req.body, function (err, count) {
            console.log(req.body.date + ': added user: ' + req.body.user + ', hexagon: ' + req.body.geohex + ', project: ' + req.body.project + ', observation: ' + req.body.observation);
            res.status(HttpStatus.CREATED).send(req.body);
        });
    } else {
        res.status(HttpStatus.NOT_FOUND).send("request validation error:" + errors);
    }
});

// delete an observation
router.delete('/observations/:id', function (req, res) {
    var id = req.params.id;
    console.log('delete observation id: ' + id);
    dbObservations.remove(function (doc) {
            return (doc.id === id);
        }, function (error, count) {
            res.status(HttpStatus.OK).send(req.body);
        }
    );
});

// change an observation
router.put('/observations', jsonParser, function (req, res) {
    req.checkBody('id', 'Id is required').notEmpty();
    req.checkBody('lat', 'lat is required').notEmpty();
    req.checkBody('lon', 'lon is required').notEmpty();

    var errors = req.validationErrors();

    if (errors === null) {
        var id = req.body.id;
        console.log('update observation: ' + id);

        dbObservations.update(function (doc) {
                if (doc.id === id) {
                    doc.date = new Date().toISOString();
                    doc.lat = req.body.lat;
                    doc.lon = req.body.lon;
                }

                return doc;
            }, function (error, count) {
                res.status(HttpStatus.OK).send(req.body);
            }
        );

    } else {
        res.status(HttpStatus.NOT_FOUND).send("request validation error:" + errors);
    }
});

// get the leaderboard
router.get('/leaderboard', nocache, function (req, res) {
    // sampleurl : leaderboard/
    var projectName = req.params.project;
    console.log('request leaderboard for all projects');

    var observations = [];
    var users = [];
    var hexagons = [];
    var projects = [];

    dbObservations.each(function (observation) {
            //search for unique users
            var userNumber = arraySearch(users, observation.user);

            if (userNumber === -1) {
                users.push(observation.user);
                hexagons.push([observation.geohex]);
                projects.push([observation.project]);
                observation.observation === 'clear' ? observations.push(0) : observations.push(1);
            } else {
                //search for unique hexagons
                if (arraySearch( hexagons[userNumber], observation.geohex) === -1) {
                    hexagons[userNumber].push(observation.geohex);
                }

                //search for unique projects
                if (arraySearch( projects[userNumber], observation.project) === -1) {
                    projects[userNumber].push(observation.project);
                }

                //show real observations (don't show an observed hexagon with no observations as a observation
                if (observation.observation !== 'clear') {
                    observations[userNumber]++;
                }
            }
    }, function (err) {
        var returnObject = [];
        for (var i = 0; i < users.length; i++) {
            var userObject = {
                "username": users[i],
                "hexagons": hexagons[i].length,
                "projects": projects[i].length,
                "observations": observations[i]
            };
            returnObject.push(userObject);
        }
        res.status(HttpStatus.OK).send(returnObject);
    });
});

app.use('/api', router);
app.use(express.static(path.join(__dirname, 'app')));
var server = app.listen(port);
module.exports = server;
console.log('Earthwatchers server started on port ' + port);

<commit_msg>multiuser fix for clean hexagon<commit_after>var express = require('express');
var path = require('path');
var dotenv = require('dotenv');
var fs = require('fs');
var turf = require('turf');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var HttpStatus = require('http-status-codes');
var lineReader = require('line-reader');
var uuid = require('node-uuid');
var nosql = require('nosql');

var imageTypes = {
    'Landsat': 2,
    'Sentinel': 4
};

var expressLogFile = fs.createWriteStream(__dirname + '/express.log', {
    flags: 'a'
});

var app = express();
app.use(morgan('combined', {
    stream: expressLogFile
}));
var jsonParser = bodyParser.json();
app.use(expressValidator());
app.disable('x-powered-by');
dotenv.load();

var port = process.env.PORT || 3000;
var dbObservations = nosql.load('./db/ew_observations.nosql');
dbObservations.description('Earthwatchers observations.');

var router = express.Router();

//TODO where to put this
function arraySearch(arr, val) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === val) {
            return i;
        }
    }
    return -1;
}

function nocache(req, res, next) {
    res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
    res.header('Expires', '-1');
    res.header('Pragma', 'no-cache');
    next();
}

// get root document
router.get('/', function (req, res) {
    res.json({
        message: 'Earthwatchers serverside'
    });
});

// get the version
router.get('/version', function (req, res) {
    res.json({
        message: 'Version 0.2'
    });
});

// get statistics for a project
router.get('/statistics/:project', nocache, function (req, res) {
    // sampleurl : observations/Borneo
    var projectName = req.params.project;
    console.log('request observations for project: ' + projectName);

    var observations = 0;
    var users = [];
    var hexagons = [];

    dbObservations.each(function (observation) {
        if (observation.project === projectName) {
            //search for unique users
            if (arraySearch(users, observation.user) === -1) {
                users.push(observation.user);
            }

            //search for unique hexagons
            if (arraySearch(hexagons, observation.geohex) === -1) {
                hexagons.push(observation.geohex);
            }
            observations++;
        }
    }, function (err) {
        console.log('observations:' + observations + ', hexagons:' + hexagons.length + ', users: ' + users.length);
        var returnObject = {
            "project": projectName,
            "observations": observations,
            "hexagons": hexagons,
            "users": users
        };
        res.status(HttpStatus.OK).send(returnObject);
    });
});

// get observations for a project and user
router.get('/observations/:project/:username', nocache, function (req, res) {
    // sampleurl : observations/Borneo/bert
    var project = req.params.project;
    var username = req.params.username;
    console.log('Request observations for project: ' + project + ', username: ' + username);

    var observations = 0;
    var hexagons = [];

    dbObservations.each(function (observation) {
        if (observation.project === project && observation.user === username) {
            //search for unique hexagons
            if (arraySearch(hexagons, observation.geohex) === -1) {
                hexagons.push(observation.geohex);
            }
            observations++;
        }
    }, function (err) {
        console.log('observations:' + observations + ', hexagons:' + hexagons.length);
        var returnObject = {
            "project": project,
            "observations": observations,
            "hexagons": hexagons.length,
            "user": username
        };
        res.status(HttpStatus.OK).send(returnObject);
    });
});

// get observations for a project, hexagon and user
router.get('/observations/:project/:geohexcode/:username', nocache, function (req, res) {
    // sampleurl : observations/Borneo/PO2632/bert
    var project = req.params.project;
    var geohexcode = req.params.geohexcode;
    var username = req.params.username;
    console.log('request observations for project: ' + project + ', geohexcode:' + geohexcode + ', username: ' + username);

    dbObservations.all(function (doc) {
        return (doc.project === project && doc.geohex === geohexcode && doc.user === username);
    }, function (error, selected) {
        res.status(HttpStatus.OK).send(selected);
    });
});

// spatial select the stalliteimages that intersect with client envelope
// example request:
// /satelliteimages?bbox=111.68,0.14,111.69,0.15&imagetype=Landsat
router.get('/satelliteimages', function (req, res) {
    var bboxPar = req.query.bbox;
    var imageType = req.query.imagetype;
    if (bboxPar !== null || imageType !== null) {
        var imageTypeNr = imageTypes[imageType];

        var bbox = bboxPar.split(',');
        for (var i = 0, len = bbox.length; i < len; i++) {
            bbox[i] = parseFloat(bbox[i]);
        }
        var poly = turf.bboxPolygon(bbox);

        var satelliteimages = fs.readFileSync(__dirname + '/satelliteimages.geojson', 'utf8');
        var jsonSatelliteImages = JSON.parse(satelliteimages);
        var selectedSatelliteImages = [];
        for (var f in jsonSatelliteImages.features) {
            var intersection = turf.intersect(jsonSatelliteImages.features[f], poly);
            if (intersection != null) {
                if (jsonSatelliteImages.features[f].properties.ImageType === imageTypeNr) {
                    selectedSatelliteImages.push(jsonSatelliteImages.features[f]);
                }
            }
        }
        res.json(turf.featurecollection(selectedSatelliteImages));

    } else {
        res.status(HttpStatus.NOT_FOUND).send('Error: Parameter bbox not specified');
    }
});

// post an observation
router.post('/observations', jsonParser, function (req, res) {
    var id = uuid.v4();
    req.checkBody('user', 'User is required').notEmpty();
    req.checkBody('lat', 'lat is required').notEmpty();
    req.checkBody('lon', 'lon is required').notEmpty();
    req.checkBody('geohex', 'geohex is required').notEmpty();
    req.checkBody('observation', 'observation is required').notEmpty();
    req.checkBody('project', 'project is required').notEmpty();

    var errors = req.validationErrors();

    if (errors === null) {
        // delete previous clear observtions
        if(req.body.observation==="clear"){
            dbObservations.remove(function (doc) {
                    return (doc.observation === req.body.observation && doc.project === req.body.project && doc.user===req.body.user);
                }, function (error, count) {
                }
            );
        }
        req.body.date = new Date().toISOString();
        req.body.id = id;

        dbObservations.insert(req.body, function (err, count) {
            console.log(req.body.date + ': added user: ' + req.body.user + ', hexagon: ' + req.body.geohex + ', project: ' + req.body.project + ', observation: ' + req.body.observation);
            res.status(HttpStatus.CREATED).send(req.body);
        });
    } else {
        res.status(HttpStatus.NOT_FOUND).send("request validation error:" + errors);
    }
});

// delete an observation
router.delete('/observations/:id', function (req, res) {
    var id = req.params.id;
    console.log('delete observation id: ' + id);
    dbObservations.remove(function (doc) {
            return (doc.id === id);
        }, function (error, count) {
            res.status(HttpStatus.OK).send(req.body);
        }
    );
});

// change an observation
router.put('/observations', jsonParser, function (req, res) {
    req.checkBody('id', 'Id is required').notEmpty();
    req.checkBody('lat', 'lat is required').notEmpty();
    req.checkBody('lon', 'lon is required').notEmpty();

    var errors = req.validationErrors();

    if (errors === null) {
        var id = req.body.id;
        console.log('update observation: ' + id);

        dbObservations.update(function (doc) {
                if (doc.id === id) {
                    doc.date = new Date().toISOString();
                    doc.lat = req.body.lat;
                    doc.lon = req.body.lon;
                }

                return doc;
            }, function (error, count) {
                res.status(HttpStatus.OK).send(req.body);
            }
        );

    } else {
        res.status(HttpStatus.NOT_FOUND).send("request validation error:" + errors);
    }
});

// get the leaderboard
router.get('/leaderboard', nocache, function (req, res) {
    // sampleurl : leaderboard/
    var projectName = req.params.project;
    console.log('request leaderboard for all projects');

    var observations = [];
    var users = [];
    var hexagons = [];
    var projects = [];

    dbObservations.each(function (observation) {
            //search for unique users
            var userNumber = arraySearch(users, observation.user);

            if (userNumber === -1) {
                users.push(observation.user);
                hexagons.push([observation.geohex]);
                projects.push([observation.project]);
                observation.observation === 'clear' ? observations.push(0) : observations.push(1);
            } else {
                //search for unique hexagons
                if (arraySearch( hexagons[userNumber], observation.geohex) === -1) {
                    hexagons[userNumber].push(observation.geohex);
                }

                //search for unique projects
                if (arraySearch( projects[userNumber], observation.project) === -1) {
                    projects[userNumber].push(observation.project);
                }

                //show real observations (don't show an observed hexagon with no observations as a observation
                if (observation.observation !== 'clear') {
                    observations[userNumber]++;
                }
            }
    }, function (err) {
        var returnObject = [];
        for (var i = 0; i < users.length; i++) {
            var userObject = {
                "username": users[i],
                "hexagons": hexagons[i].length,
                "projects": projects[i].length,
                "observations": observations[i]
            };
            returnObject.push(userObject);
        }
        res.status(HttpStatus.OK).send(returnObject);
    });
});

app.use('/api', router);
app.use(express.static(path.join(__dirname, 'app')));
var server = app.listen(port);
module.exports = server;
console.log('Earthwatchers server started on port ' + port);

<|endoftext|>


<commit_before><commit_msg>This sample git practice<commit_after><|endoftext|>


<commit_before>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import 'babel-polyfill';
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import expressJwt from 'express-jwt';
import expressGraphQL from 'express-graphql';
import jwt from 'jsonwebtoken';
import ReactDOM from 'react-dom/server';
import PrettyError from 'pretty-error';
import passport from './core/passport';
import schema from './data/schema';
import Router from './routes';
import assets from './assets';
import { port, auth, analytics } from './config';

const server = global.server = express();

//
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the
// user agent is not known.
// -----------------------------------------------------------------------------
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';

//
// Register Node.js middleware
// -----------------------------------------------------------------------------
server.use(express.static(path.join(__dirname, 'public')));
server.use(cookieParser());
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json());

var ApiResponse = require('./public/responses');

server.get('/api', function (req, res) {
  var a = "HELLO ... /api/election/vote/v1 ... /api/election/data/v1";
   res.send(a);
});

server.get('/api/election/vote/v1', function(req, res) {
  // get information for block

  // chaincode.invoke.OUR_FUNCTION(function() {
  //    our callback
  // });

  res.send("Vote submitted");
});

// hardcoded response for getting election data
server.get('/api/election/data/v1', function(req, res) {
  var b = {
        election: {
          election_id:"0001",
          election_name:"MyElection",
          parties:[
            {
              party_id:"01",
              party_name:"Blue",
              candidates:[
                {
                  candidate_id:"01",
                  candidate_name:"Arya Stark"
                },
                {
                  candidate_id:"02",
                  candidate_name:"John Snow"
                }
              ]
            },
            {
              party_id:"02",
              party_name:"Red",
              candidates:[
                {
                  candidate_id:"01",
                  candidate_name:"Jamie Lanister"
                },
                {
                  candidate_id:"02",
                  candidate_name:"Cersie Lanister"
                }
              ]
            },
          ]
        }
      };
  res.json(b);
});

//
// Authentication
// -----------------------------------------------------------------------------
server.use(expressJwt({
  secret: auth.jwt.secret,
  credentialsRequired: false,
  /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
  getToken: req => req.cookies.id_token,
  /* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
}));
server.use(passport.initialize());

server.get('/login/facebook',
  passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false })
);
server.get('/login/facebook/return',
  passport.authenticate('facebook', { failureRedirect: '/login', session: false }),
  (req, res) => {
    const expiresIn = 60 * 60 * 24 * 180; // 180 days
    const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn });
    res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true });
    res.redirect('/');
  }
);

//
// Register API middleware
// -----------------------------------------------------------------------------
server.use('/graphql', expressGraphQL(req => ({
  schema,
  graphiql: true,
  rootValue: { request: req },
  pretty: process.env.NODE_ENV !== 'production',
})));

//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
  try {
    let statusCode = 200;
    const template = require('./views/index.jade');
    const data = { title: '', description: '', css: '', body: '', entry: assets.main.js };

    if (process.env.NODE_ENV === 'production') {
      data.trackingId = analytics.google.trackingId;
    }

    const css = [];
    const context = {
      insertCss: styles => css.push(styles._getCss()),
      onSetTitle: value => (data.title = value),
      onSetMeta: (key, value) => (data[key] = value),
      onPageNotFound: () => (statusCode = 404),
    };

    await Router.dispatch({ path: req.path, query: req.query, context }, (state, component) => {
      data.body = ReactDOM.renderToString(component);
      data.css = css.join('');
    });

    res.status(statusCode);
    res.send(template(data));
  } catch (err) {
    next(err);
  }
});

//
// Error handling
// -----------------------------------------------------------------------------
const pe = new PrettyError();
pe.skipNodeFiles();
pe.skipPackage('express');

server.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
  console.log(pe.render(err)); // eslint-disable-line no-console
  const template = require('./views/error.jade');
  const statusCode = err.status || 500;
  res.status(statusCode);
  res.send(template({
    message: err.message,
    stack: process.env.NODE_ENV === 'production' ? '' : err.stack,
  }));
});

//
// Launch the server
// -----------------------------------------------------------------------------
server.listen(port, () => {
  /* eslint-disable no-console */
  console.log(`The server is running at http://localhost:${port}/`);
});
<commit_msg>added dummy api endpoints for election data and vote.<commit_after>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import 'babel-polyfill';
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import expressJwt from 'express-jwt';
import expressGraphQL from 'express-graphql';
import jwt from 'jsonwebtoken';
import ReactDOM from 'react-dom/server';
import PrettyError from 'pretty-error';
import passport from './core/passport';
import schema from './data/schema';
import Router from './routes';
import assets from './assets';
import { port, auth, analytics } from './config';

const server = global.server = express();

//
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the
// user agent is not known.
// -----------------------------------------------------------------------------
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';

//
// Register Node.js middleware
// -----------------------------------------------------------------------------
server.use(express.static(path.join(__dirname, 'public')));
server.use(cookieParser());
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json());

server.get('/api', function (req, res) {
    res.send(getWelcome());
});

server.post('/api/election/vote/v1', function(req, res) {
  // get information for block

  // chaincode.invoke.init_marble(function() {
  //   return {"eman", "red", "20", "bob"}
  // });

  res.sendStatus(200);
});

// hardcoded response for getting election data
server.get('/api/election/data/v1', function(req, res) {
  res.json(getElectionData());
});

//
// Authentication
// -----------------------------------------------------------------------------
server.use(expressJwt({
  secret: auth.jwt.secret,
  credentialsRequired: false,
  /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
  getToken: req => req.cookies.id_token,
  /* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */
}));
server.use(passport.initialize());

server.get('/login/facebook',
  passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false })
);
server.get('/login/facebook/return',
  passport.authenticate('facebook', { failureRedirect: '/login', session: false }),
  (req, res) => {
    const expiresIn = 60 * 60 * 24 * 180; // 180 days
    const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn });
    res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true });
    res.redirect('/');
  }
);

//
// Register API middleware
// -----------------------------------------------------------------------------
server.use('/graphql', expressGraphQL(req => ({
  schema,
  graphiql: true,
  rootValue: { request: req },
  pretty: process.env.NODE_ENV !== 'production',
})));

//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
  try {
    let statusCode = 200;
    const template = require('./views/index.jade');
    const data = { title: '', description: '', css: '', body: '', entry: assets.main.js };

    if (process.env.NODE_ENV === 'production') {
      data.trackingId = analytics.google.trackingId;
    }

    const css = [];
    const context = {
      insertCss: styles => css.push(styles._getCss()),
      onSetTitle: value => (data.title = value),
      onSetMeta: (key, value) => (data[key] = value),
      onPageNotFound: () => (statusCode = 404),
    };

    await Router.dispatch({ path: req.path, query: req.query, context }, (state, component) => {
      data.body = ReactDOM.renderToString(component);
      data.css = css.join('');
    });

    res.status(statusCode);
    res.send(template(data));
  } catch (err) {
    next(err);
  }
});

//
// Error handling
// -----------------------------------------------------------------------------
const pe = new PrettyError();
pe.skipNodeFiles();
pe.skipPackage('express');

server.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
  console.log(pe.render(err)); // eslint-disable-line no-console
  const template = require('./views/error.jade');
  const statusCode = err.status || 500;
  res.status(statusCode);
  res.send(template({
    message: err.message,
    stack: process.env.NODE_ENV === 'production' ? '' : err.stack,
  }));
});

//
// Launch the server
// -----------------------------------------------------------------------------
server.listen(port, () => {
  /* eslint-disable no-console */
  console.log(`The server is running at http://localhost:${port}/`);
});

// ----------- stuff -----------------

function getWelcome() {
  return "HELLO ... /api/election/vote/v1 ... /api/election/data/v1";
}

function getElectionData(){
    return {
        election: {
          election_id:"0001",
          election_name:"MyElection",
          parties:[
            {
              party_id:"01",
              party_name:"Blue",
              candidates:[
                {
                  candidate_id:"01",
                  candidate_name:"Arya Stark"
                },
                {
                  candidate_id:"02",
                  candidate_name:"John Snow"
                }
              ]
            },
            {
              party_id:"02",
              party_name:"Red",
              candidates:[
                {
                  candidate_id:"01",
                  candidate_name:"Jamie Lanister"
                },
                {
                  candidate_id:"02",
                  candidate_name:"Cersie Lanister"
                }
              ]
            },
          ]
        }
      };
}
<|endoftext|>


<commit_before>"use strict";
require("should");

const {
  mud
} = require("../../lib/dynamic/mud");
// spec: F(n) = F(n-1) + F(n-2), F(0) = 0, F(1) = 1

describe("Swamp traveling", () => {

  it("should handle single matrix", () => {
    const matrix = [[3]];
    mud(matrix).should.eql({
      result: 3,
      path: [[0, 0]]
    });
  });

  it("should handle 2 element vector", () => {
    const matrix = [[3, 2]];
    mud(matrix, 0).should.eql({
      result: 5,
      path: [[0, 0], [1, 0]]
    });
  });

  it("should handle vector", () => {
    const matrix = [[3, 2, 1, 4, 5]];
    mud(matrix).should.eql({
      result: 15,
      path: [[0, 0], [1, 0], [2, 0], [3, 0], [4, 0]]
    });
  });

  it("should handle 2x2 matrix", () => {
    const matrix = [
      [1, 1],
      [2, 2]
    ];
    mud(matrix).should.eql({
      result: 2,
      path: [[0, 0], [1, 0]]
    });
  });

  it("should handle diagonal right and down in a 2x2 matrix", () => {
    const matrix = [
      [1, 2],
      [2, 1]
    ];
    mud(matrix).should.eql({
      result: 2,
      path: [[0, 0], [1, 1]]
    });
  });

  it("should handle bigger matrix", () => {
    const matrix = [
      [1, 2, 3, 4],
      [2, 1, 3, 4],
      [3, 4, 2, 4],
      [1, 1, 1, 1]
    ];
    mud(matrix).should.eql({
      result: 4,
      path: [[0, 3], [1, 3], [2, 3], [3, 3]]
    });
  });

  describe("Swamp traveling with starting point", () => {

    it("should handle single matrix", () => {
      const matrix = [[3]];
      mud(matrix, 0).should.eql({
        result: 3,
        path: [[0, 0]]
      });
    });

    it("should handle vector", () => {
      const matrix = [[3, 2, 1, 4, 5]];
      mud(matrix, 0).should.eql({
        result: 15,
        path: [[0, 0], [1, 0], [2, 0], [3, 0], [4, 0]]
      });
    });

    it("should handle 2x2 matrix", () => {
      const matrix = [
        [1, 1],
        [2, 2]
      ];
      mud(matrix, 0).should.eql({
        result: 2,
        path: [[0, 0], [1, 0]]
      });
    });

    it("should handle bigger matrix", () => {
      const matrix = [
        [1, 2, 3, 4],
        [2, 1, 3, 4],
        [3, 4, 2, 4],
        [1, 1, 1, 1]
      ];
      const result = mud(matrix, 1);
      result.should.eql({
        result: 6,
        path: [[0, 1], [1, 1], [2, 2], [3, 3]]
      });
    });
  });
});
<commit_msg>Add test case<commit_after>"use strict";
require("should");

const {
  mud
} = require("../../lib/dynamic/mud");
// spec: F(n) = F(n-1) + F(n-2), F(0) = 0, F(1) = 1

describe("Swamp traveling", () => {

  it("should handle single matrix", () => {
    const matrix = [[3]];
    mud(matrix).should.eql({
      result: 3,
      path: [[0, 0]]
    });
  });

  it("should handle 2 element vector", () => {
    const matrix = [[3, 2]];
    mud(matrix, 0).should.eql({
      result: 5,
      path: [[0, 0], [1, 0]]
    });
  });

  it("should handle vector", () => {
    const matrix = [[3, 2, 1, 4, 5]];
    mud(matrix).should.eql({
      result: 15,
      path: [[0, 0], [1, 0], [2, 0], [3, 0], [4, 0]]
    });
  });

  it("should handle 2x2 matrix", () => {
    const matrix = [
      [1, 1],
      [2, 2]
    ];
    mud(matrix).should.eql({
      result: 2,
      path: [[0, 0], [1, 0]]
    });
  });

  it("should handle diagonal right and down in a 2x2 matrix", () => {
    const matrix = [
      [1, 2],
      [2, 1]
    ];
    mud(matrix).should.eql({
      result: 2,
      path: [[0, 0], [1, 1]]
    });
  });

  it("should handle bigger matrix", () => {
    const matrix = [
      [1, 2, 3, 4],
      [2, 1, 3, 4],
      [3, 4, 2, 4],
      [1, 1, 1, 1]
    ];
    mud(matrix).should.eql({
      result: 4,
      path: [[0, 3], [1, 3], [2, 3], [3, 3]]
    });
  });

  it("should conflicting paths in matrix", () => {
    const matrix = [
      [1, 1, 3, 4],
      [2, 5, 5, 3],
      [1, 3, 1, 4],
      [4, 4, 4, 4]
    ];
    mud(matrix).should.eql({
      result: 8,
      path: [[0, 0], [1, 0], [2, 0], [3, 1]]
    });
  });

  describe("Swamp traveling with starting point", () => {

    it("should handle single matrix", () => {
      const matrix = [[3]];
      mud(matrix, 0).should.eql({
        result: 3,
        path: [[0, 0]]
      });
    });

    it("should handle vector", () => {
      const matrix = [[3, 2, 1, 4, 5]];
      mud(matrix, 0).should.eql({
        result: 15,
        path: [[0, 0], [1, 0], [2, 0], [3, 0], [4, 0]]
      });
    });

    it("should handle 2x2 matrix", () => {
      const matrix = [
        [1, 1],
        [2, 2]
      ];
      mud(matrix, 0).should.eql({
        result: 2,
        path: [[0, 0], [1, 0]]
      });
    });

    it("should handle bigger matrix", () => {
      const matrix = [
        [1, 2, 3, 4],
        [2, 1, 3, 4],
        [3, 4, 2, 4],
        [1, 1, 1, 1]
      ];
      const result = mud(matrix, 1);
      result.should.eql({
        result: 6,
        path: [[0, 1], [1, 1], [2, 2], [3, 3]]
      });
    });
  });
});
<|endoftext|>


<commit_before>/**
    @file       server.js
    @brief      Node.JS Server.

    @author     Oleg Kertanov <okertanov@gmail.com>
    @date       May 2012
    @copyright  Copyright (C) 2012 Oleg Kertanov <okertanov@gmail.com>
    @license    BSD
    @see LICENSE file
*/

(function()
{

// Strict mode by default
"use strict";

// System modules
var os      = require('os'),
    fs      = require('fs'),
    path    = require('path'),
    express = require('express');

// App modules
var ApiController = require('./api-controller.js').ApiController;

// Pathes
var ServerRoot  = __filename,
    ProjectRoot = path.normalize(ServerRoot + '/../'),
    WWWRoot     = path.normalize(ProjectRoot + '/wwwroot/');

// Configuration
var Port = 8882;

// Express application
var app = express.createServer();

app.configure(function () {
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

ApiController.Initialize();
ApiController.Route(app);

// Server
app.listen(Port);

process
    .on('exit', function () {
        ApiController.Terminate();
    })
    .on('uncaughtException', function (e){
        ApiController.Terminate();
        throw e;
    })
    .on('SIGINT', function () {
        ApiController.Terminate();
    });

})()

<commit_msg>migrate to express: continue 17<commit_after>/**
    @file       server.js
    @brief      Node.JS Server.

    @author     Oleg Kertanov <okertanov@gmail.com>
    @date       May 2012
    @copyright  Copyright (C) 2012 Oleg Kertanov <okertanov@gmail.com>
    @license    BSD
    @see LICENSE file
*/

(function()
{

// Strict mode by default
"use strict";

// System modules
var os      = require('os'),
    fs      = require('fs'),
    path    = require('path'),
    express = require('express');

// App modules
var ApiController = require('./api-controller.js').ApiController;

// Pathes
var ServerRoot  = __filename,
    ProjectRoot = path.normalize(ServerRoot + '/../'),
    WWWRoot     = path.normalize(ProjectRoot + '/wwwroot/');

// Configuration
var Port = 8882;

// Express application
var app = express.createServer();

app.configure(function () {
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

ApiController.Initialize();
ApiController.Route(app);

// Server
app.listen(Port);

process
    .on('exit', function () {
        ApiController.Terminate();
    })
    .on('uncaughtException', function (e){
        ApiController.Terminate();
        throw e;
    })
    .on('SIGINT', function () {
        ApiController.Terminate();
        process.exit();
    });

})()

<|endoftext|>


<commit_before><commit_msg>Update KRC.js<commit_after><|endoftext|>


<commit_before>/*
1. Define Angular application (make sure link to Angular library is included)
2. Inject firebase (make sure link to Firebase library is included)
3. Create controller
4. Define routes (put above controller)
5. Use angular's $interval
*/
var app = angular.module("todoApp", ['firebase', 'ui.router'])

.config(function ($stateProvider, $locationProvider) {
    $locationProvider.html5Mode(true);
    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: 'templates/home.html'
         })
        .state('history', {
            url: '/history',
            templateUrl: 'templates/history.html'
         })
        .state('active', {
            url: '/active',
            templateUrl: 'templates/active.html'
         })
        .state('expired', {
            url: '/expired',
            templateUrl: 'templates/expired.html'
         })

    });

app.controller("TodoCtrl", ["$scope", "$firebase", "$interval", function($scope, $firebase, $interval) {
    console.log("I'm the controller!");
    var ref = new Firebase("https://popping-torch-9799.firebaseio.com/");
    // create an AngularFire reference to the data
    var sync = $firebase(ref);
    // download the data into a local object
    $scope.data = sync.$asObject();

    $scope.newTodo = '';

    $scope.todos = [
        {done: false, text: 'first', archived: true},
        {done: false, text: 'second', archived: false}
    ];

    $scope.completedTodos = [];
    function isCompleted() {
        for (i = 0; i< $scope.todos.length; i++){
            if($scope.todo[i].done){
                $scope.completedTodos.push($scope.todos[i]);
            }
        }
    }

    $scope.addTodo = function(todo) {
        console.log("Todo is", todo);
        var totallyNewTodo = {
            done: false,
            text: todo,
            expired: false,
            created: Firebase.ServiceValue.TIMESTAMP
        };
        $scope.todos.push(totallyNewTodo);
        // $scope.newTodo = '';
        console.log("Todos", $scope.todos);
    };

    $scope.callAtInterval = function() {
        console.log("Interval works");
    };

    $interval( function (){ $scope.callAtInterval(); }, 300, [3]);
}]);

       <commit_msg>fixed timestamp typo<commit_after>/*
1. Define Angular application (make sure link to Angular library is included)
2. Inject firebase (make sure link to Firebase library is included)
3. Create controller
4. Define routes (put above controller)
5. Use angular's $interval
*/
var app = angular.module("todoApp", ['firebase', 'ui.router'])

.config(function ($stateProvider, $locationProvider) {
    $locationProvider.html5Mode(true);
    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: 'templates/home.html'
         })
        .state('history', {
            url: '/history',
            templateUrl: 'templates/history.html'
         })
        .state('active', {
            url: '/active',
            templateUrl: 'templates/active.html'
         })
        .state('expired', {
            url: '/expired',
            templateUrl: 'templates/expired.html'
         })

    });

app.controller("TodoCtrl", ["$scope", "$firebase", "$interval", function($scope, $firebase, $interval) {
    console.log("I'm the controller!");
    var ref = new Firebase("https://popping-torch-9799.firebaseio.com/");
    // create an AngularFire reference to the data
    var sync = $firebase(ref);
    // download the data into a local object
    $scope.data = sync.$asObject();

    $scope.newTodo = '';

    $scope.todos = [
        {done: false, text: 'first', archived: true},
        {done: false, text: 'second', archived: false}
    ];

    $scope.completedTodos = [];
    function isCompleted() {
        for (i = 0; i< $scope.todos.length; i++){
            if($scope.todo[i].done){
                $scope.completedTodos.push($scope.todos[i]);
            }
        }
    }

    $scope.addTodo = function(todo) {
        console.log("Todo is", todo);
        var totallyNewTodo = {
            done: false,
            text: todo,
            expired: false,
            created: Firebase.ServerValue.TIMESTAMP
        };
        $scope.todos.push(totallyNewTodo);
        // $scope.newTodo = '';
        console.log("Todos", $scope.todos);
    };

    $scope.callAtInterval = function() {
        console.log("Interval works");
    };

    $interval( function (){ $scope.callAtInterval(); }, 300, [3]);
}]);

       <|endoftext|>