<commit_before>var Q = require('q');

module.exports = {
    mapWaitlistDBVO : mapWaitlistDBVO,
    mapWaitlistItemDBVO : mapWaitlistItemDBVO,
    mapPilotDBVO : mapPilotDBVO,
    mapWaitlistDBVOtoAscii : mapWaitlistDBVOtoAscii
}

/*
 {
 "id": 4,
 "name": "Thomion`s waitlist",
 "externalId": "z5DapO3ksycMyMfj5Jm1impazAQHikBK",
 "createdAt": "2015-04-11T17:16:07.000Z",
 "updatedAt": "2015-04-11T17:16:07.000Z",
 "ownerId": "698922015",
 "items": []
 }
 {
 ownerId;
 waitlistId;
 ownerName;
 waitlistName;
 waitlist = [];
}
 */

function mapWaitlistDBVO(waitlist){
    var mapped = {};
    mapped.ownerId = waitlist.ownerId;
    mapped.waitlistId = waitlist.externalId;
    mapped.ownerName = waitlist.owner ? waitlist.owner.name : '';
    mapped.waitlistName = waitlist.name;
    var items = waitlist.items ? waitlist.items.map(mapWaitlistItemDBVO) : [];
    return Q.all(items)
        .then(function (mappedItems) {
            mapped.waitlist = mappedItems;
            return mapped;
        })
}

function mapWaitlistDBVOtoAscii(waitlist){

    return mapWaitlistDBVO(waitlist)
        .then(function (mapped) {

            var list = mapped.waitlist.map(function (item) {
                var char = linkCharacter(item.characterId,item.characterName);
                var fit  = linkFit(item.shipDNA,item.shipName)
                return ' - ' + fit + ' \t ' + char + '\n';
            })
            list = list.join();

            var ascii = '.\n';
            var prename = mapped.ownerName.split(' ')[0];
            ascii = ascii.concat('-= <b>' + prename + ' Fleet </b> =-\n')
            ascii = ascii.concat(list);
            ascii = ascii.concat('-==              ==-\n')
            return ascii;
        })
}

function linkCharacter(id,name){
    return '<url=showinfo:1373\/\/' + id + '>' + name +'</url>'
}

function linkFit(shipDNA,shipName){
    return '<url=fitting:' + shipDNA + '>' + shipName + '</url>'
}

/*
 {
 "order": 3,
 "shipId": "001",
 "shipName": "Dicke Berta",
 "shipDNA": "003",
 "shipType": "002",
 "createdAt": "2015-04-11T17:59:11.000Z",
 "updatedAt": "2015-04-11T17:59:11.000Z",
 "pilotId": "698922015",
 "waitlistId": 4
 }
 {
 characterId;
 characterName;
 shipDNA;
 shipName;
 itemId;
 shipType;
 }
 */
function mapWaitlistItemDBVO(item){
    return item.getPilot()
        .then(function (pilot) {
            return mapPilotDBVO(pilot)
        })
        .then(function (mapped) {
            mapped.shipDNA  = item.shipDNA;
            mapped.shipName = item.shipName;
            mapped.itemId   = item.order;
            mapped.shipType = item.shipType;
            return mapped;
        })
}

/*
 {
 "id": "698922015",
 "name": "Thomion",
 "createdAt": "2015-04-11T15:52:36.000Z",
 "updatedAt": "2015-04-11T19:25:29.000Z",
 "corpId": "1000006",
 "corp": {
 "id": "1000006",
 "name": "Deep Core Mining Inc.",
 "createdAt": "2015-04-11 15:54:39.000 +00:00",
 "updatedAt": "2015-04-11 15:54:39.000 +00:00",
 "allianceId": null,
 "alliance": null
 }
 }
    {
    characterId;
    characterName;
    corporationId;
    corporationName;
    allianceId;
    allianceName;
    }
 */

function mapPilotDBVO(pilot){
    var mapped = {};
    mapped.characterId  = pilot.id;
    mapped.characterName    = pilot.name;
    return pilot.getCorp()
        .then(function (corp) {
            mapped.corporationId    = corp.id;
            mapped.corporationName  = corp.name;
            return corp.getAlliance();
        })
        .then(function (alliance) {
            if(alliance){
                mapped.allianceId   = alliance.id;
                mapped.allianceName = alliance.name;
            }
            return mapped;
        })
}<commit_msg>pimped ascii conversion<commit_after>var Q = require('q');

module.exports = {
    mapWaitlistDBVO : mapWaitlistDBVO,
    mapWaitlistItemDBVO : mapWaitlistItemDBVO,
    mapPilotDBVO : mapPilotDBVO,
    mapWaitlistDBVOtoAscii : mapWaitlistDBVOtoAscii
}

/*
 {
 "id": 4,
 "name": "Thomion`s waitlist",
 "externalId": "z5DapO3ksycMyMfj5Jm1impazAQHikBK",
 "createdAt": "2015-04-11T17:16:07.000Z",
 "updatedAt": "2015-04-11T17:16:07.000Z",
 "ownerId": "698922015",
 "items": []
 }
 {
 ownerId;
 waitlistId;
 ownerName;
 waitlistName;
 waitlist = [];
}
 */

function mapWaitlistDBVO(waitlist){
    var mapped = {};
    mapped.ownerId = waitlist.ownerId;
    mapped.waitlistId = waitlist.externalId;
    mapped.ownerName = waitlist.owner ? waitlist.owner.name : '';
    mapped.waitlistName = waitlist.name;
    var items = waitlist.items ? waitlist.items.map(mapWaitlistItemDBVO) : [];
    return Q.all(items)
        .then(function (mappedItems) {
            mapped.waitlist = mappedItems;
            return mapped;
        })
}

function mapWaitlistDBVOtoAscii(waitlist){

    return mapWaitlistDBVO(waitlist)
        .then(function (mapped) {

            var list = mapped.waitlist.map(function (item) {
                var char = linkCharacter(item.characterId,item.characterName);
                var fit  = linkFit(item.shipDNA,item.shipName)
                return ' * ' + fit + ' \t ' + char + '\n';
            })
            list = list.join();

            var ascii = '.\n';
            var prename = mapped.ownerName.split(' ')[0];
            ascii = ascii.concat('-=   <b>' + prename + "'s Fleet </b>   =-\n")
            ascii = ascii.concat(list);
            ascii = ascii.concat('-==              ==-\n')
            return ascii;
        })
}

function linkCharacter(id,name){
    return '<url=showinfo:1373\/\/' + id + '>' + name +'</url>'
}

function linkFit(shipDNA,shipName){
    return '<url=fitting:' + shipDNA + '>' + shipName + '</url>'
}

/*
 {
 "order": 3,
 "shipId": "001",
 "shipName": "Dicke Berta",
 "shipDNA": "003",
 "shipType": "002",
 "createdAt": "2015-04-11T17:59:11.000Z",
 "updatedAt": "2015-04-11T17:59:11.000Z",
 "pilotId": "698922015",
 "waitlistId": 4
 }
 {
 characterId;
 characterName;
 shipDNA;
 shipName;
 itemId;
 shipType;
 }
 */
function mapWaitlistItemDBVO(item){
    return item.getPilot()
        .then(function (pilot) {
            return mapPilotDBVO(pilot)
        })
        .then(function (mapped) {
            mapped.shipDNA  = item.shipDNA;
            mapped.shipName = item.shipName;
            mapped.itemId   = item.order;
            mapped.shipType = item.shipType;
            return mapped;
        })
}

/*
 {
 "id": "698922015",
 "name": "Thomion",
 "createdAt": "2015-04-11T15:52:36.000Z",
 "updatedAt": "2015-04-11T19:25:29.000Z",
 "corpId": "1000006",
 "corp": {
 "id": "1000006",
 "name": "Deep Core Mining Inc.",
 "createdAt": "2015-04-11 15:54:39.000 +00:00",
 "updatedAt": "2015-04-11 15:54:39.000 +00:00",
 "allianceId": null,
 "alliance": null
 }
 }
    {
    characterId;
    characterName;
    corporationId;
    corporationName;
    allianceId;
    allianceName;
    }
 */

function mapPilotDBVO(pilot){
    var mapped = {};
    mapped.characterId  = pilot.id;
    mapped.characterName    = pilot.name;
    return pilot.getCorp()
        .then(function (corp) {
            mapped.corporationId    = corp.id;
            mapped.corporationName  = corp.name;
            return corp.getAlliance();
        })
        .then(function (alliance) {
            if(alliance){
                mapped.allianceId   = alliance.id;
                mapped.allianceName = alliance.name;
            }
            return mapped;
        })
}<|endoftext|>


<commit_before>/**
 * uri-scheme.js
 */

/**
 * uri scheme
 *
 * @see {@link https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml}
 *      - Historical schemes omitted
 *      - Added 'moz-extension' scheme
 */
export default [
  'aaa',
  'aaas',
  'about',
  'acap',
  'acct',
  'acd',
  'acr',
  'adiumxtra',
  'adt',
  'afp',
  'afs',
  'aim',
  'amss',
  'android',
  'appdata',
  'apt',
  'ar',
  'ark',
  'attachment',
  'aw',
  'barion',
  'beshare',
  'bitcoin',
  'bitcoincash',
  'blob',
  'bolo',
  'browserext',
  'cabal',
  'calculator',
  'callto',
  'cap',
  'cast',
  'casts',
  'chrome',
  'chrome-extension',
  'cid',
  'coap',
  'coap+tcp',
  'coap+ws',
  'coaps',
  'coaps+tcp',
  'coaps+ws',
  'com-eventbrite-attendee',
  'content',
  'content-type',
  'crid',
  'cstr',
  'cvs',
  'dab',
  'dat',
  'data',
  'dav',
  'diaspora',
  'dict',
  'did',
  'dis',
  'dlna-playcontainer',
  'dlna-playsingle',
  'dns',
  'dntp',
  'doi',
  'dpp',
  'drm',
  'drop',
  'dtmi',
  'dtn',
  'dvb',
  'dvx',
  'dweb',
  'ed2k',
  'elsi',
  'embedded',
  'ens',
  'ethereum',
  'example',
  'facetime',
  'feed',
  'feedready',
  'fido',
  'file',
  'finger',
  'first-run-pen-experience',
  'fish',
  'fm',
  'ftp',
  'fuchsia-pkg',
  'geo',
  'gg',
  'git',
  'gitoid',
  'gizmoproject',
  'go',
  'gopher',
  'graph',
  'gtalk',
  'h323',
  'ham',
  'hcap',
  'hcp',
  'http',
  'https',
  'hxxp',
  'hxxps',
  'hydrazone',
  'hyper',
  'iax',
  'icap',
  'icon',
  'im',
  'imap',
  'info',
  'iotdisco',
  'ipfs',
  'ipn',
  'ipns',
  'ipp',
  'ipps',
  'irc',
  'irc6',
  'ircs',
  'iris',
  'iris.beep',
  'iris.lwz',
  'iris.xpc',
  'iris.xpcs',
  'isostore',
  'itms',
  'jabber',
  'jar',
  'jms',
  'keyparc',
  'lastfm',
  'lbry',
  'ldap',
  'ldaps',
  'leaptofrogans',
  'lorawan',
  'lvlt',
  'magnet',
  'mailto',
  'maps',
  'market',
  'matrix',
  'message',
  'microsoft.windows.camera',
  'microsoft.windows.camera.multipicker',
  'microsoft.windows.camera.picker',
  'mid',
  'mms',
  'mongodb',
  'moz',
  'moz-extension',
  'ms-access',
  'ms-appinstaller',
  'ms-browser-extension',
  'ms-calculator',
  'ms-drive-to',
  'ms-enrollment',
  'ms-excel',
  'ms-eyecontrolspeech',
  'ms-gamebarservices',
  'ms-gamingoverlay',
  'ms-getoffice',
  'ms-help',
  'ms-infopath',
  'ms-inputapp',
  'ms-lockscreencomponent-config',
  'ms-media-stream-id',
  'ms-meetnow',
  'ms-mixedrealitycapture',
  'ms-mobileplans',
  'ms-newsandinterests',
  'ms-officeapp',
  'ms-people',
  'ms-project',
  'ms-powerpoint',
  'ms-publisher',
  'ms-restoretabcompanion',
  'ms-screenclip',
  'ms-screensketch',
  'ms-search',
  'ms-search-repair',
  'ms-secondary-screen-controller',
  'ms-secondary-screen-setup',
  'ms-settings',
  'ms-settings-airplanemode',
  'ms-settings-bluetooth',
  'ms-settings-camera',
  'ms-settings-cellular',
  'ms-settings-cloudstorage',
  'ms-settings-connectabledevices',
  'ms-settings-displays-topology',
  'ms-settings-emailandaccounts',
  'ms-settings-language',
  'ms-settings-location',
  'ms-settings-lock',
  'ms-settings-nfctransactions',
  'ms-settings-notifications',
  'ms-settings-power',
  'ms-settings-privacy',
  'ms-settings-proximity',
  'ms-settings-screenrotation',
  'ms-settings-wifi',
  'ms-settings-workplace',
  'ms-spd',
  'ms-stickers',
  'ms-sttoverlay',
  'ms-transit-to',
  'ms-useractivityset',
  'ms-virtualtouchpad',
  'ms-visio',
  'ms-walk-to',
  'ms-whiteboard',
  'ms-whiteboard-cmd',
  'ms-word',
  'msnim',
  'msrp',
  'msrps',
  'mss',
  'mt',
  'mtqp',
  'mumble',
  'mupdate',
  'mvn',
  'news',
  'nfs',
  'ni',
  'nih',
  'nntp',
  'notes',
  'num',
  'ocf',
  'oid',
  'onenote',
  'onenote-cmd',
  'opaquelocktoken',
  'openpgp4fpr',
  'otpauth',
  'palm',
  'paparazzi',
  'payment',
  'payto',
  'pkcs11',
  'platform',
  'pop',
  'pres',
  'proxy',
  'pwid',
  'psyc',
  'pttp',
  'qb',
  'query',
  'quic-transport',
  'redis',
  'rediss',
  'reload',
  'res',
  'resource',
  'rmi',
  'rsync',
  'rtmfp',
  'rtmp',
  'rtsp',
  'rtsps',
  'rtspu',
  'sarif',
  'secondlife',
  'secret-token',
  'service',
  'session',
  'sftp',
  'sgn',
  'shc',
  'sieve',
  'simpleledger',
  'simplex',
  'sip',
  'sips',
  'skype',
  'smb',
  'smp',
  'sms',
  'smtp',
  'snmp',
  'soap.beep',
  'soap.beeps',
  'soldat',
  'spiffe',
  'spotify',
  'ssb',
  'ssh',
  'steam',
  'stun',
  'stuns',
  'submit',
  'svn',
  'swh',
  'swid',
  'swidpath',
  'tag',
  'teamspeak',
  'tel',
  'teliaeid',
  'telnet',
  'tftp',
  'things',
  'thismessage',
  'tip',
  'tn3270',
  'tool',
  'turn',
  'turns',
  'tv',
  'udp',
  'unreal',
  'urn',
  'ut2004',
  'uuid-in-package',
  'v-event',
  'vemmi',
  'ventrilo',
  'ves',
  'vnc',
  'view-source',
  'vscode',
  'vscode-insiders',
  'vsls',
  'wcr',
  'webcal',
  'wifi',
  'ws',
  'wss',
  'wtai',
  'wyciwyg',
  'xcon',
  'xcon-userid',
  'xfire',
  'xmlrpc.beep',
  'xmlrpc.beeps',
  'xmpp',
  'xri',
  'ymsgr',
  'z39.50r',
  'z39.50s'
];
<commit_msg>Update uri-scheme.js<commit_after>/**
 * uri-scheme.js
 */

/**
 * uri scheme
 *
 * @see {@link https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml}
 *      - Historical schemes omitted
 *      - Added 'moz-extension' scheme
 */
export default [
  'aaa',
  'aaas',
  'about',
  'acap',
  'acct',
  'acd',
  'acr',
  'adiumxtra',
  'adt',
  'afp',
  'afs',
  'aim',
  'amss',
  'android',
  'appdata',
  'apt',
  'ar',
  'ark',
  'attachment',
  'aw',
  'barion',
  'beshare',
  'bitcoin',
  'bitcoincash',
  'blob',
  'bolo',
  'browserext',
  'cabal',
  'calculator',
  'callto',
  'cap',
  'cast',
  'casts',
  'chrome',
  'chrome-extension',
  'cid',
  'coap',
  'coaps',
  'com-eventbrite-attendee',
  'content',
  'content-type',
  'crid',
  'cstr',
  'cvs',
  'dab',
  'dat',
  'data',
  'dav',
  'diaspora',
  'dict',
  'did',
  'dis',
  'dlna-playcontainer',
  'dlna-playsingle',
  'dns',
  'dntp',
  'doi',
  'dpp',
  'drm',
  'drop',
  'dtmi',
  'dtn',
  'dvb',
  'dvx',
  'dweb',
  'ed2k',
  'elsi',
  'embedded',
  'ens',
  'ethereum',
  'example',
  'facetime',
  'feed',
  'feedready',
  'fido',
  'file',
  'finger',
  'first-run-pen-experience',
  'fish',
  'fm',
  'ftp',
  'fuchsia-pkg',
  'geo',
  'gg',
  'git',
  'gitoid',
  'gizmoproject',
  'go',
  'gopher',
  'graph',
  'gtalk',
  'h323',
  'ham',
  'hcap',
  'hcp',
  'http',
  'https',
  'hxxp',
  'hxxps',
  'hydrazone',
  'hyper',
  'iax',
  'icap',
  'icon',
  'im',
  'imap',
  'info',
  'iotdisco',
  'ipfs',
  'ipn',
  'ipns',
  'ipp',
  'ipps',
  'irc',
  'irc6',
  'ircs',
  'iris',
  'iris.beep',
  'iris.lwz',
  'iris.xpc',
  'iris.xpcs',
  'isostore',
  'itms',
  'jabber',
  'jar',
  'jms',
  'keyparc',
  'lastfm',
  'lbry',
  'ldap',
  'ldaps',
  'leaptofrogans',
  'lorawan',
  'lvlt',
  'magnet',
  'mailto',
  'maps',
  'market',
  'matrix',
  'message',
  'microsoft.windows.camera',
  'microsoft.windows.camera.multipicker',
  'microsoft.windows.camera.picker',
  'mid',
  'mms',
  'mongodb',
  'moz',
  'moz-extension',
  'ms-access',
  'ms-appinstaller',
  'ms-browser-extension',
  'ms-calculator',
  'ms-drive-to',
  'ms-enrollment',
  'ms-excel',
  'ms-eyecontrolspeech',
  'ms-gamebarservices',
  'ms-gamingoverlay',
  'ms-getoffice',
  'ms-help',
  'ms-infopath',
  'ms-inputapp',
  'ms-lockscreencomponent-config',
  'ms-media-stream-id',
  'ms-meetnow',
  'ms-mixedrealitycapture',
  'ms-mobileplans',
  'ms-newsandinterests',
  'ms-officeapp',
  'ms-people',
  'ms-project',
  'ms-powerpoint',
  'ms-publisher',
  'ms-restoretabcompanion',
  'ms-screenclip',
  'ms-screensketch',
  'ms-search',
  'ms-search-repair',
  'ms-secondary-screen-controller',
  'ms-secondary-screen-setup',
  'ms-settings',
  'ms-settings-airplanemode',
  'ms-settings-bluetooth',
  'ms-settings-camera',
  'ms-settings-cellular',
  'ms-settings-cloudstorage',
  'ms-settings-connectabledevices',
  'ms-settings-displays-topology',
  'ms-settings-emailandaccounts',
  'ms-settings-language',
  'ms-settings-location',
  'ms-settings-lock',
  'ms-settings-nfctransactions',
  'ms-settings-notifications',
  'ms-settings-power',
  'ms-settings-privacy',
  'ms-settings-proximity',
  'ms-settings-screenrotation',
  'ms-settings-wifi',
  'ms-settings-workplace',
  'ms-spd',
  'ms-stickers',
  'ms-sttoverlay',
  'ms-transit-to',
  'ms-useractivityset',
  'ms-virtualtouchpad',
  'ms-visio',
  'ms-walk-to',
  'ms-whiteboard',
  'ms-whiteboard-cmd',
  'ms-word',
  'msnim',
  'msrp',
  'msrps',
  'mss',
  'mt',
  'mtqp',
  'mumble',
  'mupdate',
  'mvn',
  'news',
  'nfs',
  'ni',
  'nih',
  'nntp',
  'notes',
  'num',
  'ocf',
  'oid',
  'onenote',
  'onenote-cmd',
  'opaquelocktoken',
  'openpgp4fpr',
  'otpauth',
  'palm',
  'paparazzi',
  'payment',
  'payto',
  'pkcs11',
  'platform',
  'pop',
  'pres',
  'proxy',
  'pwid',
  'psyc',
  'pttp',
  'qb',
  'query',
  'quic-transport',
  'redis',
  'rediss',
  'reload',
  'res',
  'resource',
  'rmi',
  'rsync',
  'rtmfp',
  'rtmp',
  'rtsp',
  'rtsps',
  'rtspu',
  'sarif',
  'secondlife',
  'secret-token',
  'service',
  'session',
  'sftp',
  'sgn',
  'shc',
  'sieve',
  'simpleledger',
  'simplex',
  'sip',
  'sips',
  'skype',
  'smb',
  'smp',
  'sms',
  'smtp',
  'snmp',
  'soap.beep',
  'soap.beeps',
  'soldat',
  'spiffe',
  'spotify',
  'ssb',
  'ssh',
  'steam',
  'stun',
  'stuns',
  'submit',
  'svn',
  'swh',
  'swid',
  'swidpath',
  'tag',
  'teamspeak',
  'tel',
  'teliaeid',
  'telnet',
  'tftp',
  'things',
  'thismessage',
  'tip',
  'tn3270',
  'tool',
  'turn',
  'turns',
  'tv',
  'udp',
  'unreal',
  'urn',
  'ut2004',
  'uuid-in-package',
  'v-event',
  'vemmi',
  'ventrilo',
  'ves',
  'vnc',
  'view-source',
  'vscode',
  'vscode-insiders',
  'vsls',
  'wcr',
  'webcal',
  'wifi',
  'ws',
  'wss',
  'wtai',
  'wyciwyg',
  'xcon',
  'xcon-userid',
  'xfire',
  'xmlrpc.beep',
  'xmlrpc.beeps',
  'xmpp',
  'xri',
  'ymsgr',
  'z39.50r',
  'z39.50s'
];
<|endoftext|>


<commit_before><commit_msg>init paramLists in the initReadonly path as well<commit_after><|endoftext|>


<commit_before>/**
 * Created by mike on 5/26/15.
 */
(function () {
    "use strict";
    var app = angular.module("eos");
    app.directive('modal', function () {
        /**
         * IMPLEMENT METHODS
         * JSON getModel(); // will return the model
         *
         * BASIC MODEL STRUCTURE
         * var model = {
             fields: [
         *        {name: "id", display: false},
         *        {name: "name", displayName: "Name", placeholder: "Panel [a,b,etc...]", type: "text", required: true},
         *        {name: "mac", displayName: "MAC", placeholder: "0x36000...", type: "text", required: true}
         *        ],
         *   addModalSettings: {
         *       title: 'Add New Panel',
         *       buttonLabel: 'Add Panel',
         *       callback: this.onSubmit
         *   },
         *   editModalSettings: {
         *      ...
         *   }
         * };
         *
         * COMPILE MODEL
         * model = ModalService.compileModel(model);
         *
         * ATTACH TO DOM
         * <button class="btn btn-primary" modal ng-service="PanelDataService">Add Panel</button>
         *
         * RECOMMENDED
         * Hanging the rest of the data used to drive around your page using your new service is recommended as your
         * modals will stay up to date with your data.
         *
         * Credits and Examples used:
         * http://stackoverflow.com/questions/14115701/angularjs-create-a-directive-that-uses-ng-model // directives that use ng-model
         * http://stackoverflow.com/questions/20033493/angularjs-passing-service-as-an-argument-to-directive // for argument passing
         * http://www.html5rocks.com/en/tutorials/es6/promises/#toc-async // learning about promises
         * http://stackoverflow.com/questions/26807524/twitter-bootstrap-3-modal-with-scrollable-body // css modal body scrollbar magic
         * http://stackoverflow.com/questions/16529825/angularjs-ngclass-conditional // angular conditional classes for template
         * http://stackoverflow.com/questions/12139152/how-to-set-the-value-property-in-angularjs-ng-options // using ngOptions for select tags
         * http://odetocode.com/blogs/scott/archive/2013/06/19/using-ngoptions-in-angularjs.aspx // using ngOptions for select tags
         *
         */

        return {
            restrict: 'A',
            scope: {
                ngService: '@',
                ngModel: '=' // puts object directly in scope
            },
            controller: [
                '$scope', '$attrs', '$injector', '$modal', function ($scope, $attrs, $injector, $modal) {
                    // inject service and get button label for this scope
                    $scope.dataServiceName = $attrs.ngService;
                    $scope.dataService = $injector.get($scope.dataServiceName);

                    /**
                     * Opens the modal
                     * Based on the code from:
                     * http://angular-ui.github.io/bootstrap/#/modal
                     */
                    $scope.openModal = function () {

                        function onwards() {
                            // this is simalar to routes except with dynamic templates.
                            $modal.open({
                                templateUrl: 'app/private/modules/modal/modalTemplate.html',
                                //template: '

{{title}}

BLUE means required

       <form>
                           <input ng-if="field.type == \'checkbox\'" type="checkbox" ng-model="field.value">                           {{field.displayName}}
                 Error! {{field.errorMessage}}
                           <input ng-if="field.type == \'text\' || field.type == \'number\'" type="{{field.type}}" class="form-control"                    placeholder="{{field.placeholder}}" id="{{field.name}}" ng-model="field.value">                           <select class="form-control" ng-if="field.type == \'dropdown\'" data-ng-model="field.value" data-ng-options="item for item in field.dropdownOptions">             </select>                           <input ng-if="field.type == \'datetime\'" class="form-control" type="datetime-local" ng-model="field.value">
     </form>

     <button type="submit" class="btn btn-primary" ng-click="ok(fields)">OK</button>     <button type="button" class="btn btn-default" ng-click="cancel()">Cancel</button>
',
                                controller: 'AddModalInstanceController',
                                size: 'lg',
                                resolve: { // this resolves the local vars of Instance Ctrl
                                    ngModel: function () {
                                        return $scope.ngModel;
                                    },
                                    dataServiceName: function () { // send the modal instance the name of the service that it must inject
                                        return $scope.dataServiceName;
                                    }
                                }
                            });
                        }

                        /**
                         * if preClick exists execute it
                         */
                        if (typeof $scope.dataService.preClick === "function") { // if preclick function exists
                            $scope.dataService.preClick();
                        }

                        function myTimeout() {
                            setTimeout(function () {
                                if (!$scope.ready) {
                                    $scope.ready = $scope.dataService.modelReady(); // if still not ready update
                                    myTimeout(); // run again
                                } else {
                                    onwards(); // continue execution.
                                }
                            }, 100); // 100ms wait
                        }

                        /**
                         * get relevant data for building our modal from our injected service
                         * and do not return until that data is ready
                         */
                        if (typeof $scope.dataService.modelReady === 'function') {
                            $scope.ready = $scope.dataService.modelReady();
                            myTimeout(); // kick off synchronous timer
                        } else {
                            onwards(); // ignore and continue
                        }

                    };
                }
            ],
            link: function compile($scope, element, $attrs, ctrl) {

                // bind the click handler to the element which has our modal-add attribute
                element.bind('click', function (e) {
                    $scope.openModal(); // just open the stupid modal
                });
            }
        }
    });
    /**
     * The per instance modal controller. This handles the actual submission of the data
     */
    app.controller("AddModalInstanceController", ['$scope', '$modalInstance', '$http', '$state', '$injector', 'dataServiceName', 'ngModel', 'ModalService',
        function ($scope, $modalInstance, $http, $state, $injector, dataServiceName, ngModel, ModalService) {
            // using service name to inject the service to our instance controller.
            var dataService = $injector.get(dataServiceName);

            var model = dataService.getModel();
            // extract relevant settings
            $scope.fields = model['fields'];
            if (ngModel === undefined) {
                //console.log('add modal');
                $scope.settings = model['addModalSettings'];
            } else {
                //console.log('edit modal');
                $scope.settings = model['editModalSettings'];
                // set field values based on given model
                $scope.fields = ModalService.addValuesToFields(ngModel, $scope.fields);
                //console.log(ngModel);
                //console.log($scope.fields);
            }
            $scope.title = $scope.settings['title'];

            $scope.cancel = function () {// when cancel button is clicked
                $modalInstance.dismiss('cancel'); // this causes result promise to fail
            };

            $scope.ok = function (fields) { // when ok button is clicked
                var newDataPoint = ModalService.getValuesFromFields(fields); // Extract data from fields

                /**
                 * Checks only our requirements for validity
                 */
                var preformValidityCheckAndCallback = function () { // yay for long pointless function names
                    // only do requirements validation
                    $scope.fields = ModalService.checkValidRequirements($scope.fields); // call our requirements validation

                    if (!ModalService.checkValidFromFields($scope.fields)) { // If any invalid states exist
                        //console.error('invalid states exist');
                        $scope.fields = fields;
                    } else {
                        if ($scope.settings.hasOwnProperty('callback')) {
                            $scope.settings['callback'](newDataPoint); // fire off successful callback function
                        }
                        $modalInstance.close(); // this causes result promise to succeed and modal to close and reset
                    }
                };

                // if user validation exists
                if ('validate' in $scope.settings) {
                    $scope.fields = ModalService.resetValidity(fields); // reset validity fields for re-evaluation
                    $scope.fields = $scope.settings['validate']($scope.fields); // call user defined validation service to update fields
                    preformValidityCheckAndCallback();
                } else {
                    $scope.fields = ModalService.resetValidity(fields); // reset validity fields for re-evaluation
                    preformValidityCheckAndCallback();
                }
            };

            // MODAL PROMISE
            $modalInstance.result.then(function (results) { // if successful submission
                $scope.fields = ModalService.resetModel(dataService.getModel()); // Reset modal
            }, function (err) { // if modal fails due to cancel or outside click
                $scope.fields = ModalService.resetModel(dataService.getModel()); // Reset modal
            })

        }]);
}());<commit_msg>Update modalDirective.js<commit_after>/**
 * Changelog
 * Mon Aug 10 2015 Mike Meding <mikeymeding@gmail.com>
 * - inital beta version release
 */
(function () {
    "use strict";
    var app = angular.module("eos");
    app.directive('modal', function () {
        /**
         * IMPLEMENT METHODS
         * JSON getModel(); // will return the model
         *
         * BASIC MODEL STRUCTURE
         * var model = {
             fields: [
         *        {name: "id", display: false},
         *        {name: "name", displayName: "Name", placeholder: "Panel [a,b,etc...]", type: "text", required: true},
         *        {name: "mac", displayName: "MAC", placeholder: "0x36000...", type: "text", required: true}
         *        ],
         *   addModalSettings: {
         *       title: 'Add New Panel',
         *       buttonLabel: 'Add Panel',
         *       callback: this.onSubmit
         *   },
         *   editModalSettings: {
         *      ...
         *   }
         * };
         *
         * COMPILE MODEL
         * model = ModalService.compileModel(model);
         *
         * ATTACH TO DOM
         * <button class="btn btn-primary" modal ng-service="PanelDataService">Add Panel</button>
         *
         * RECOMMENDED
         * Hanging the rest of the data used to drive around your page using your new service is recommended as your
         * modals will stay up to date with your data.
         *
         * Credits and Examples used:
         * http://stackoverflow.com/questions/14115701/angularjs-create-a-directive-that-uses-ng-model // directives that use ng-model
         * http://stackoverflow.com/questions/20033493/angularjs-passing-service-as-an-argument-to-directive // for argument passing
         * http://www.html5rocks.com/en/tutorials/es6/promises/#toc-async // learning about promises
         * http://stackoverflow.com/questions/26807524/twitter-bootstrap-3-modal-with-scrollable-body // css modal body scrollbar magic
         * http://stackoverflow.com/questions/16529825/angularjs-ngclass-conditional // angular conditional classes for template
         * http://stackoverflow.com/questions/12139152/how-to-set-the-value-property-in-angularjs-ng-options // using ngOptions for select tags
         * http://odetocode.com/blogs/scott/archive/2013/06/19/using-ngoptions-in-angularjs.aspx // using ngOptions for select tags
         *
         */

        return {
            restrict: 'A',
            scope: {
                ngService: '@',
                ngModel: '=' // puts object directly in scope
            },
            controller: [
                '$scope', '$attrs', '$injector', '$modal', function ($scope, $attrs, $injector, $modal) {
                    // inject service and get button label for this scope
                    $scope.dataServiceName = $attrs.ngService;
                    $scope.dataService = $injector.get($scope.dataServiceName);

                    /**
                     * Opens the modal
                     * Based on the code from:
                     * http://angular-ui.github.io/bootstrap/#/modal
                     */
                    $scope.openModal = function () {

                        function onwards() {
                            // this is simalar to routes except with dynamic templates.
                            $modal.open({
                                templateUrl: 'app/private/modules/modal/modalTemplate.html',
                                //template: '

{{title}}

BLUE means required

       <form>
                           <input ng-if="field.type == \'checkbox\'" type="checkbox" ng-model="field.value">                           {{field.displayName}}
                 Error! {{field.errorMessage}}
                           <input ng-if="field.type == \'text\' || field.type == \'number\'" type="{{field.type}}" class="form-control"                    placeholder="{{field.placeholder}}" id="{{field.name}}" ng-model="field.value">                           <select class="form-control" ng-if="field.type == \'dropdown\'" data-ng-model="field.value" data-ng-options="item for item in field.dropdownOptions">             </select>                           <input ng-if="field.type == \'datetime\'" class="form-control" type="datetime-local" ng-model="field.value">
     </form>

     <button type="submit" class="btn btn-primary" ng-click="ok(fields)">OK</button>     <button type="button" class="btn btn-default" ng-click="cancel()">Cancel</button>
',
                                controller: 'AddModalInstanceController',
                                size: 'lg',
                                resolve: { // this resolves the local vars of Instance Ctrl
                                    ngModel: function () {
                                        return $scope.ngModel;
                                    },
                                    dataServiceName: function () { // send the modal instance the name of the service that it must inject
                                        return $scope.dataServiceName;
                                    }
                                }
                            });
                        }

                        /**
                         * if preClick exists execute it
                         */
                        if (typeof $scope.dataService.preClick === "function") { // if preclick function exists
                            $scope.dataService.preClick();
                        }

                        function myTimeout() {
                            setTimeout(function () {
                                if (!$scope.ready) {
                                    $scope.ready = $scope.dataService.modelReady(); // if still not ready update
                                    myTimeout(); // run again
                                } else {
                                    onwards(); // continue execution.
                                }
                            }, 100); // 100ms wait
                        }

                        /**
                         * get relevant data for building our modal from our injected service
                         * and do not return until that data is ready
                         */
                        if (typeof $scope.dataService.modelReady === 'function') {
                            $scope.ready = $scope.dataService.modelReady();
                            myTimeout(); // kick off synchronous timer
                        } else {
                            onwards(); // ignore and continue
                        }

                    };
                }
            ],
            link: function compile($scope, element, $attrs, ctrl) {

                // bind the click handler to the element which has our modal-add attribute
                element.bind('click', function (e) {
                    $scope.openModal(); // just open the stupid modal
                });
            }
        }
    });
    /**
     * The per instance modal controller. This handles the actual submission of the data
     */
    app.controller("AddModalInstanceController", ['$scope', '$modalInstance', '$http', '$state', '$injector', 'dataServiceName', 'ngModel', 'ModalService',
        function ($scope, $modalInstance, $http, $state, $injector, dataServiceName, ngModel, ModalService) {
            // using service name to inject the service to our instance controller.
            var dataService = $injector.get(dataServiceName);

            var model = dataService.getModel();
            // extract relevant settings
            $scope.fields = model['fields'];
            if (ngModel === undefined) {
                //console.log('add modal');
                $scope.settings = model['addModalSettings'];
            } else {
                //console.log('edit modal');
                $scope.settings = model['editModalSettings'];
                // set field values based on given model
                $scope.fields = ModalService.addValuesToFields(ngModel, $scope.fields);
                //console.log(ngModel);
                //console.log($scope.fields);
            }
            $scope.title = $scope.settings['title'];

            $scope.cancel = function () {// when cancel button is clicked
                $modalInstance.dismiss('cancel'); // this causes result promise to fail
            };

            $scope.ok = function (fields) { // when ok button is clicked
                var newDataPoint = ModalService.getValuesFromFields(fields); // Extract data from fields

                /**
                 * Checks only our requirements for validity
                 */
                var preformValidityCheckAndCallback = function () { // yay for long pointless function names
                    // only do requirements validation
                    $scope.fields = ModalService.checkValidRequirements($scope.fields); // call our requirements validation

                    if (!ModalService.checkValidFromFields($scope.fields)) { // If any invalid states exist
                        //console.error('invalid states exist');
                        $scope.fields = fields;
                    } else {
                        if ($scope.settings.hasOwnProperty('callback')) {
                            $scope.settings['callback'](newDataPoint); // fire off successful callback function
                        }
                        $modalInstance.close(); // this causes result promise to succeed and modal to close and reset
                    }
                };

                // if user validation exists
                if ('validate' in $scope.settings) {
                    $scope.fields = ModalService.resetValidity(fields); // reset validity fields for re-evaluation
                    $scope.fields = $scope.settings['validate']($scope.fields); // call user defined validation service to update fields
                    preformValidityCheckAndCallback();
                } else {
                    $scope.fields = ModalService.resetValidity(fields); // reset validity fields for re-evaluation
                    preformValidityCheckAndCallback();
                }
            };

            // MODAL PROMISE
            $modalInstance.result.then(function (results) { // if successful submission
                $scope.fields = ModalService.resetModel(dataService.getModel()); // Reset modal
            }, function (err) { // if modal fails due to cancel or outside click
                $scope.fields = ModalService.resetModel(dataService.getModel()); // Reset modal
            })

        }]);
}());
<|endoftext|>


<commit_before>var Data = {

  starts : [
    "Experiential truth ",
    "Coffee ",
    "Geopolitics ",
    "Javascript ",
    "Glory ",
    "Espresso ",
    "Heuristic thought ",
    "Absinthe ",
    "Surrogate birth ",
    "Rishathra ",
    "Irradiation ",
    "Megalomania ",
    "Solar radiation ",
    "Autosomy ",
    "Practical economics ",
    "Activism ",
    "Dental plaque ",
    "Consternation ",
    "Vanilla nougat ",
    "The physical world ",
    "Sadness ",
    "Chicken ",
    "Non-judgment ",
    "Parsimony ",
    "Hodor ",
    "Salacity ",
    "Grunge music ",
    "Clarity ",
    "Antagonism ",
    "Heterodoxity ",
    "Erudition ",
    "Amalgamation ",
    "Remuneration ",
    "Primacy ",
    "The empty set ",
    "Bergamot marmalade ",
    "Amelioration ",
    "Apostasy ",
    "Reprobacy ",
    "Aquaculture ",
    "Infinity ",
    "Rubric ",
    "Email ",
    "Calamity ",
    "Loquacity ",
    "Honesty ",
    "Cosmology ",
    "Aperture science ",
    "Temporal quaquaversality ",
    "Derrida ",
    "Mellow vibe ",
    "Prosody ",
    "Selectivity ",
    "Unity ",
    "Good health ",
    "A quantum leap ",    // thanks Francis Veilleux-Gaboury
    "A clean brain ",
    "Entreaty ",
    "Brusque temperment ",
    "A flexible thought pattern ",
    "Insightful visage ",
    "Mindfulness in action ",
    "Automated translation ",
    "Facebook ",
    "Compassion ",
    "Altruism ",
    "Totality ",
    "Rhetorical training ",
    "Insoucinace ",
    "Dynamic mutative creation ",
    "The graspably non-considerable ",
    "Social science ",
    "Stone age philosophy ",
    "Interpretive dance ",
    "Meditative physics ",
    "Rambunctious cause ",
    "Biology ",
    "Multitudinality ",
    "Nascent luminence ",
    "True randomness ",
    "Deconstrutionist wisdom ",
    "Science intersecting religion ",
    "The role of a leader ",
    "The soul of a calm person ",
    "The idea of God ",
    "Mechanistic reaction ",
    "Semiotic involvement ",
    "Quantum physics ",
    "Cerebrolinguistics ",
    "Dubstep as a metaphor for liberty "
  ],

  middles : [
    "nurtures ",
    "unifies ",
    "stymies ",
    "separates ",
    "distributes widely ",
    "appreciates ",
    "deprecates ",
    "conglomerates ",
    "gives meaning to ",
    "displays ",
    "projects ",
    "permeates ",
    "clarifies ",
    "macerates ",
    "asceticizes ",
    "recapitulates ",
    "satisfies ",
    "sanctifies via ",
    "trivializes ",
    "justifies with ",
    "rarifies ",
    "enjoins ",
    "codifies ",
    "socializes by way of ",
    "reclaims ",
    "disintegrates ",
    "integrates ",
    "reduces ",
    "explores ",
    "dissociates from within ",
    "exposes ",
    "masticates ",
    "builds, using ",
    "teaches through ",
    "projects onto ",
    "imparts reality to ",
    "constructs with "
  ],

  qualifiers : [
    "abundance of ",
    "ostentatious ",
    "the barrier of ",
    "self-righteous ",
    "collective ",
    "species specific ",
    "heterodynamic ",
    "clarity within ",
    "epistemological ",
    "synchronistic ",
    "timely ",
    "unpredictable ",
    "unassailable ",
    "glassy eyed ",
    "dishonest ",
    "indefatigable ",
    "factual ",
    "highly descriptive ",
    "location based ",
    "describably pure ",
    "bounded ",
    "unbounded ",
    "trans-boundary ",
    "expedient ",
    "ontogenous ",
    "parallelizes ",
    "serendipitous ",
    "geopolitical ",
    "popular ",
    "advocatory ",
    "pluripotentialistic ",
    "atomized ",
    "rhythmatic ",
    "dimensional ",
    "sophist ",
    "Etruscan ",
    "reliquary ",
    "escapist ",
    "anarchist ",
    "conformist ",
    "erudite ",
    "epistemic ",
    "cromulent ",
    "poker faced ",
    "miniscule ",
    "Manichean ",
    "Hadrean ",
    "media driven ",
    "global ",
    "local ",
    "post-",
    "hyper-",
    "trans-",
    "extra-",
    "super-",
    "supra-",
    "world regarding ",
    "provably optimal ",
    "potential ",
    "munctional "
  ],

  finishes : [
    "marvel.",
    "choices.",
    "harmony.",
    "phylogeny.",
    "disharmony.",
    "traversal.",
    "ostracism.",
    "semiotics.",
    "deconstructionism.",
    "post-logic.",
    "escapism.",
    "criarchy.",
    "permaculture.",
    "platitudinality.",
    "creosophy.",
    "journalism.",
    "preternaturality.",
    "glossolalia.",
    "idolatry.",
    "conscience confluence.",
    "hapto-ergonomics.",
    "mental rigor.",
    "spiritual fortitude.",
    "wisdom.",
    "secret genius.",
    "inner brilliance.",
    "unseen internal gift.",
    "combobulation.",
    "transdoctrinal inference.",
    "creativity.",
    "significance.",
    "materialization.",
    "generosity.",
    "infinitude.",
    "plurality.",
    "asceticism.",
    "truism.",
    "horizontal scaling.",
    "monopoly.",
    "temerity.",
    "neo-Platonism."
    "monosophism.",
    "polyarchy.",
    "heredity.",
    "togetherness.",
    "voluminous reaction.",
    "joyous revelation.",
    "stimulation.",
    "numbing.",
    "intuition.",
    "actions."
  ]

};

function randFrom(X) {
  return X[Math.floor(Math.random() * X.length)];
}

function makeDC() {
  return randFrom(Data.starts) + randFrom(Data.middles) + randFrom(Data.qualifiers) + randFrom(Data.finishes);
}

function go() {
  document.getElementById('txt').innerHTML = '"' + makeDC() + '"';
}
<commit_msg>Herotodeus<commit_after>var Data = {

  starts : [
    "Experiential truth ",
    "Coffee ",
    "Geopolitics ",
    "Javascript ",
    "Glory ",
    "Espresso ",
    "Heuristic thought ",
    "Absinthe ",
    "Surrogate birth ",
    "Rishathra ",
    "Irradiation ",
    "Megalomania ",
    "Solar radiation ",
    "Autosomy ",
    "Practical economics ",
    "Activism ",
    "Dental plaque ",
    "Consternation ",
    "Vanilla nougat ",
    "The physical world ",
    "Sadness ",
    "Chicken ",
    "Non-judgment ",
    "Parsimony ",
    "Hodor ",
    "Salacity ",
    "Grunge music ",
    "Clarity ",
    "Antagonism ",
    "Heterodoxity ",
    "Erudition ",
    "Amalgamation ",
    "Remuneration ",
    "Primacy ",
    "The empty set ",
    "Bergamot marmalade ",
    "Amelioration ",
    "Apostasy ",
    "Reprobacy ",
    "Aquaculture ",
    "Infinity ",
    "Rubric ",
    "Email ",
    "Calamity ",
    "Loquacity ",
    "Honesty ",
    "Cosmology ",
    "Aperture science ",
    "Temporal quaquaversality ",
    "Derrida ",
    "Mellow vibe ",
    "Prosody ",
    "Selectivity ",
    "Unity ",
    "Good health ",
    "A quantum leap ",    // thanks Francis Veilleux-Gaboury
    "A clean brain ",
    "Entreaty ",
    "Brusque temperment ",
    "A flexible thought pattern ",
    "Insightful visage ",
    "Mindfulness in action ",
    "Automated translation ",
    "Facebook ",
    "Compassion ",
    "Altruism ",
    "Totality ",
    "Rhetorical training ",
    "Insoucinace ",
    "Dynamic mutative creation ",
    "The graspably non-considerable ",
    "Social science ",
    "Stone age philosophy ",
    "Interpretive dance ",
    "Meditative physics ",
    "Rambunctious cause ",
    "Biology ",
    "Multitudinality ",
    "Nascent luminence ",
    "True randomness ",
    "Deconstrutionist wisdom ",
    "Science intersecting religion ",
    "The role of a leader ",
    "The soul of a calm person ",
    "The idea of God ",
    "Mechanistic reaction ",
    "Semiotic involvement ",
    "Herotodeus ",
    "Quantum physics ",
    "Cerebrolinguistics ",
    "Dubstep as a metaphor for liberty "
  ],

  middles : [
    "nurtures ",
    "unifies ",
    "stymies ",
    "separates ",
    "distributes widely ",
    "appreciates ",
    "deprecates ",
    "conglomerates ",
    "gives meaning to ",
    "displays ",
    "projects ",
    "permeates ",
    "clarifies ",
    "macerates ",
    "asceticizes ",
    "recapitulates ",
    "satisfies ",
    "sanctifies via ",
    "trivializes ",
    "justifies with ",
    "rarifies ",
    "enjoins ",
    "codifies ",
    "socializes by way of ",
    "reclaims ",
    "disintegrates ",
    "integrates ",
    "reduces ",
    "explores ",
    "dissociates from within ",
    "exposes ",
    "masticates ",
    "builds, using ",
    "teaches through ",
    "projects onto ",
    "imparts reality to ",
    "constructs with "
  ],

  qualifiers : [
    "abundance of ",
    "ostentatious ",
    "the barrier of ",
    "self-righteous ",
    "collective ",
    "species specific ",
    "heterodynamic ",
    "clarity within ",
    "epistemological ",
    "synchronistic ",
    "timely ",
    "unpredictable ",
    "unassailable ",
    "glassy eyed ",
    "dishonest ",
    "indefatigable ",
    "factual ",
    "highly descriptive ",
    "location based ",
    "describably pure ",
    "bounded ",
    "unbounded ",
    "trans-boundary ",
    "expedient ",
    "ontogenous ",
    "parallelizes ",
    "serendipitous ",
    "geopolitical ",
    "popular ",
    "advocatory ",
    "pluripotentialistic ",
    "atomized ",
    "rhythmatic ",
    "dimensional ",
    "sophist ",
    "Etruscan ",
    "reliquary ",
    "escapist ",
    "anarchist ",
    "conformist ",
    "erudite ",
    "epistemic ",
    "cromulent ",
    "poker faced ",
    "miniscule ",
    "Manichean ",
    "Hadrean ",
    "media driven ",
    "global ",
    "local ",
    "post-",
    "hyper-",
    "trans-",
    "extra-",
    "super-",
    "supra-",
    "world regarding ",
    "provably optimal ",
    "potential ",
    "munctional "
  ],

  finishes : [
    "marvel.",
    "choices.",
    "harmony.",
    "phylogeny.",
    "disharmony.",
    "traversal.",
    "ostracism.",
    "semiotics.",
    "deconstructionism.",
    "post-logic.",
    "escapism.",
    "criarchy.",
    "permaculture.",
    "platitudinality.",
    "creosophy.",
    "journalism.",
    "preternaturality.",
    "glossolalia.",
    "idolatry.",
    "conscience confluence.",
    "hapto-ergonomics.",
    "mental rigor.",
    "spiritual fortitude.",
    "wisdom.",
    "secret genius.",
    "inner brilliance.",
    "unseen internal gift.",
    "combobulation.",
    "transdoctrinal inference.",
    "creativity.",
    "significance.",
    "materialization.",
    "generosity.",
    "infinitude.",
    "plurality.",
    "asceticism.",
    "truism.",
    "horizontal scaling.",
    "monopoly.",
    "temerity.",
    "neo-Platonism."
    "monosophism.",
    "polyarchy.",
    "heredity.",
    "togetherness.",
    "voluminous reaction.",
    "joyous revelation.",
    "stimulation.",
    "numbing.",
    "intuition.",
    "actions."
  ]

};

function randFrom(X) {
  return X[Math.floor(Math.random() * X.length)];
}

function makeDC() {
  return randFrom(Data.starts) + randFrom(Data.middles) + randFrom(Data.qualifiers) + randFrom(Data.finishes);
}

function go() {
  document.getElementById('txt').innerHTML = '"' + makeDC() + '"';
}
<|endoftext|>


<commit_before>var fs = require('fs');

module.exports = {

    /**
     * Command: !set name <displayName>
     */
    setName: {
        description: '!set name {displayName} | Changes bot\'s display name. Limit for the name is 32 characters.',
        // Maximum name length is 32 characters
        regex: /^!set name (.{1,32})/,
        action: function(VaporAPI, user, match) {
            var steamFriends = VaporAPI.getHandler('steamFriends');
            var config = VaporAPI.getConfig();
            var pluginConfig = VaporAPI.data || {};

            steamFriends.setPersonaName(match[1]);
            config.displayName = match[1];

            if(pluginConfig.configPath) {
                fs.writeFileSync(pluginConfig.configPath, JSON.stringify(config, null, 2));
            }

            VaporAPI.emitEvent('message:info', 'Display name has been changed to: ' + match[1]);
        }
    },

    /**
     * Command: !set state <stateName>
     */
    setState: {
        description: '!set state {stateName} | Changes bot\'s online state.',
        // "Looking To Trade" is the longest state name so 16 characters should be sufficient
        regex: /^!set state ([a-zA-Z ]{1,16})/,
        action: function(VaporAPI, user, match) {
            var Steam = VaporAPI.getSteam();
            var steamFriends = VaporAPI.getHandler('steamFriends');
            var utils = VaporAPI.getUtils();

            var pluginConfig = VaporAPI.data || {};

            var state = utils.stringToEnum(match[1], Steam.EPersonaState);

            if(state !== null) {
                var description = utils.enumToString(state, Steam.EPersonaState);
                var config = VaporAPI.getConfig();

                steamFriends.setPersonaState(state);
                config.state = description;

                if(pluginConfig.configPath) {
                    fs.writeFileSync(pluginConfig.configPath, JSON.stringify(config, null, 2));
                }

                VaporAPI.emitEvent('message:info', 'Online state has been changed to: ' + description);
            } else {
                steamFriends.sendMessage(user, 'Incorrect state name: ' + match[1]);
            }
        }
    },

    /**
     * Command: !disconnect
     */
    disconnect: {
        description: '!disconnect | Disconnects from Steam network.',
        regex: /^!disconnect$/,
        action: function(VaporAPI) {
            VaporAPI.emitEvent('message:info', 'Disconnecting from Steam network.');
            VaporAPI.disconnect();
        }
    },

    /**
     * Command: !help
     */
    help: {
        description: '!help | Lists all available admin commands',
        regex: /^!help$/,
        action: function(VaporAPI, user) {
            var commands = require('./commands.js'); // This is not ideal
            var steamFriends = VaporAPI.getHandler('steamFriends');

            var response = 'List of commands:\n';
            for(var command in commands) {
                response += '* ' + commands[command].description + '\n';
            }

            steamFriends.sendMessage(user, response);
        }
    }
};
<commit_msg>use vapors wrapper for logging<commit_after>var fs = require('fs');

module.exports = {

    /**
     * Command: !set name <displayName>
     */
    setName: {
        description: '!set name {displayName} | Changes bot\'s display name. Limit for the name is 32 characters.',
        // Maximum name length is 32 characters
        regex: /^!set name (.{1,32})/,
        action: function(VaporAPI, user, match) {
            var log = VaporAPI.getLogger();
            var steamFriends = VaporAPI.getHandler('steamFriends');
            var config = VaporAPI.getConfig();
            var pluginConfig = VaporAPI.data || {};

            steamFriends.setPersonaName(match[1]);
            config.displayName = match[1];

            if(pluginConfig.configPath) {
                fs.writeFileSync(pluginConfig.configPath, JSON.stringify(config, null, 2));
            }

            log.info('Display name has been changed to: %s', match[1]);
        }
    },

    /**
     * Command: !set state <stateName>
     */
    setState: {
        description: '!set state {stateName} | Changes bot\'s online state.',
        // "Looking To Trade" is the longest state name so 16 characters should be sufficient
        regex: /^!set state ([a-zA-Z ]{1,16})/,
        action: function(VaporAPI, user, match) {
            var log = VaporAPI.getLogger();
            var Steam = VaporAPI.getSteam();
            var steamFriends = VaporAPI.getHandler('steamFriends');
            var utils = VaporAPI.getUtils();

            var pluginConfig = VaporAPI.data || {};

            var state = utils.stringToEnum(match[1], Steam.EPersonaState);

            if(state !== null) {
                var description = utils.enumToString(state, Steam.EPersonaState);
                var config = VaporAPI.getConfig();

                steamFriends.setPersonaState(state);
                config.state = description;

                if(pluginConfig.configPath) {
                    fs.writeFileSync(pluginConfig.configPath, JSON.stringify(config, null, 2));
                }

                log.info('Online state has been changed to: %s', description);
            } else {
                steamFriends.sendMessage(user, 'Incorrect state name: ' + match[1]);
            }
        }
    },

    /**
     * Command: !disconnect
     */
    disconnect: {
        description: '!disconnect | Disconnects from Steam network.',
        regex: /^!disconnect$/,
        action: function(VaporAPI) {
            VaporAPI.getLogger().info('Disconnecting from Steam network.');
            VaporAPI.disconnect();
        }
    },

    /**
     * Command: !help
     */
    help: {
        description: '!help | Lists all available admin commands',
        regex: /^!help$/,
        action: function(VaporAPI, user) {
            var commands = require('./commands.js'); // This is not ideal
            var steamFriends = VaporAPI.getHandler('steamFriends');

            var response = 'List of commands:\n';
            for(var command in commands) {
                response += '* ' + commands[command].description + '\n';
            }

            steamFriends.sendMessage(user, response);
        }
    }
};
<|endoftext|>


<commit_before>var Data = {

  starts : [
    "Experiential truth ",
    "Coffee ",
    "Absinthe ",
    "The physical world ",
    "Non-judgment ",
    "Parsimony ",
    "Clarity ",
    "Heterodoxity ",
    "Erudition ",
    "Primacy ",
    "Apostasy ",
    "Infinity ",
    "Calamity ",
    "Honesty ",
    "Cosmology ",
    "Aperture science ",
    "Temporal quaquaversality ",
    "Derrida ",
    "Prosody ",
    "Calamity ",
    "Selectivity ",
    "Unity ",
    "Good health ",
    "A quantum leap ",    // thanks Francis Veilleux-Gaboury
    "A clean brain ",
    "Entreaty ",
    "Brusque temperment ",
    "A flexible thought pattern ",
    "Insightful visage ",
    "Mindfulness in action ",
    "Automated translation ",
    "Facebook ",
    "Compassion ",
    "Altruism ",
    "Totality ",
    "Rhetorical training ",
    "Insoucinace ",
    "Dynamic mutative creation ",
    "The graspably non-considerable ",
    "Social science ",
    "Stone age philosophy ",
    "Interpretive dance ",
    "Meditative physics ",
    "Rambunctious cause ",
    "Biology ",
    "Multitudinality ",
    "Nascent luminence ",
    "True randomness ",
    "Deconstrutionist wisdom ",
    "Science intersecting religion ",
    "The role of a leader ",
    "The soul of a calm person ",
    "The idea of God ",
    "Mechanistic reaction ",
    "Semiotic involvement ",
    "Quantum physics ",
    "Cerebrolinguistics ",
    "Dubstep as a metaphor for liberty "
  ],

  middles : [
    "nurtures ",
    "unifies ",
    "stymies ",
    "separates ",
    "distributes widely ",
    "appreciates ",
    "deprecates ",
    "conglomerates ",
    "gives meaning to ",
    "displays ",
    "permeates ",
    "clarifies ",
    "asceticizes ",
    "recapitulates ",
    "satisfies ",
    "sanctifies via ",
    "trivializes ",
    "justifies with ",
    "rarifies ",
    "codifies ",
    "socializes by way of ",
    "reclaims ",
    "disintegrates ",
    "integrates ",
    "reduces ",
    "explores ",
    "dissociates from within ",
    "exposes ",
    "builds, using ",
    "teaches through ",
    "projects onto ",
    "imparts reality to ",
    "constructs with "
  ],

  qualifiers : [
    "abundance of ",
    "ostentatious ",
    "the barrier of ",
    "self-righteous ",
    "collective ",
    "species specific ",
    "heterodynamic ",
    "epistemological ",
    "synchronistic ",
    "timely ",
    "unpredictable ",
    "unassailable ",
    "dishonest ",
    "factual ",
    "highly descriptive ",
    "location based ",
    "describably pure ",
    "bounded ",
    "unbounded ",
    "trans-boundary ",
    "expedient ",
    "ontogenous ",
    "geopolitical ",
    "popular ",
    "advocatory ",
    "pluripotentialistic ",
    "rhythmatic ",
    "dimensional ",
    "sophist ",
    "reliquary ",
    "escapist ",
    "anarchist ",
    "conformist ",
    "erudite ",
    "miniscule ",
    "Manichean ",
    "Hadrean ",
    "media driven ",
    "global ",
    "local ",
    "post-",
    "hyper-",
    "trans-",
    "extra-",
    "super-",
    "supra-",
    "world regarding ",
    "provably optimal ",
    "potential "
  ],

  finishes : [
    "marvel.",
    "choices.",
    "harmony.",
    "phylogeny.",
    "disharmony.",
    "traversal.",
    "ostracism.",
    "semiotics.",
    "deconstructionism.",
    "post-logic.",
    "escapism.",
    "criarchy.",
    "platitudinality.",
    "creosophy.",
    "journalism.",
    "preternaturality.",
    "glossolalia.",
    "idolatry.",
    "conscience confluence.",
    "hapto-ergonomics.",
    "mental rigor.",
    "spiritual fortitude.",
    "wisdom.",
    "secret genius.",
    "inner brilliance.",
    "unseen internal gift.",
    "combobulation.",
    "transdoctrinal inference.",
    "creativity.",
    "significance.",
    "materialization.",
    "generosity.",
    "infinitude.",
    "plurality.",
    "asceticism.",
    "truism.",
    "monopoly.",
    "temerity.",
    "monosophism.",
    "polyarchy.",
    "togetherness.",
    "voluminous reaction.",
    "joyous revelation.",
    "stimulation.",
    "numbing.",
    "intuition.",
    "actions."
  ]

};

function randFrom(X) {
  return X[Math.floor(Math.random() * X.length)];
}

function makeDC() {
  return randFrom(Data.starts) + randFrom(Data.middles) + randFrom(Data.qualifiers) + randFrom(Data.finishes);
}

function go() {
  document.getElementById('txt').innerHTML = '"' + makeDC() + '"';
}
<commit_msg>whoops, calamity was in there twice<commit_after>var Data = {

  starts : [
    "Experiential truth ",
    "Coffee ",
    "Absinthe ",
    "The physical world ",
    "Non-judgment ",
    "Parsimony ",
    "Clarity ",
    "Heterodoxity ",
    "Erudition ",
    "Primacy ",
    "Apostasy ",
    "Infinity ",
    "Calamity ",
    "Honesty ",
    "Cosmology ",
    "Aperture science ",
    "Temporal quaquaversality ",
    "Derrida ",
    "Prosody ",
    "Selectivity ",
    "Unity ",
    "Good health ",
    "A quantum leap ",    // thanks Francis Veilleux-Gaboury
    "A clean brain ",
    "Entreaty ",
    "Brusque temperment ",
    "A flexible thought pattern ",
    "Insightful visage ",
    "Mindfulness in action ",
    "Automated translation ",
    "Facebook ",
    "Compassion ",
    "Altruism ",
    "Totality ",
    "Rhetorical training ",
    "Insoucinace ",
    "Dynamic mutative creation ",
    "The graspably non-considerable ",
    "Social science ",
    "Stone age philosophy ",
    "Interpretive dance ",
    "Meditative physics ",
    "Rambunctious cause ",
    "Biology ",
    "Multitudinality ",
    "Nascent luminence ",
    "True randomness ",
    "Deconstrutionist wisdom ",
    "Science intersecting religion ",
    "The role of a leader ",
    "The soul of a calm person ",
    "The idea of God ",
    "Mechanistic reaction ",
    "Semiotic involvement ",
    "Quantum physics ",
    "Cerebrolinguistics ",
    "Dubstep as a metaphor for liberty "
  ],

  middles : [
    "nurtures ",
    "unifies ",
    "stymies ",
    "separates ",
    "distributes widely ",
    "appreciates ",
    "deprecates ",
    "conglomerates ",
    "gives meaning to ",
    "displays ",
    "permeates ",
    "clarifies ",
    "asceticizes ",
    "recapitulates ",
    "satisfies ",
    "sanctifies via ",
    "trivializes ",
    "justifies with ",
    "rarifies ",
    "codifies ",
    "socializes by way of ",
    "reclaims ",
    "disintegrates ",
    "integrates ",
    "reduces ",
    "explores ",
    "dissociates from within ",
    "exposes ",
    "builds, using ",
    "teaches through ",
    "projects onto ",
    "imparts reality to ",
    "constructs with "
  ],

  qualifiers : [
    "abundance of ",
    "ostentatious ",
    "the barrier of ",
    "self-righteous ",
    "collective ",
    "species specific ",
    "heterodynamic ",
    "epistemological ",
    "synchronistic ",
    "timely ",
    "unpredictable ",
    "unassailable ",
    "dishonest ",
    "factual ",
    "highly descriptive ",
    "location based ",
    "describably pure ",
    "bounded ",
    "unbounded ",
    "trans-boundary ",
    "expedient ",
    "ontogenous ",
    "geopolitical ",
    "popular ",
    "advocatory ",
    "pluripotentialistic ",
    "rhythmatic ",
    "dimensional ",
    "sophist ",
    "reliquary ",
    "escapist ",
    "anarchist ",
    "conformist ",
    "erudite ",
    "miniscule ",
    "Manichean ",
    "Hadrean ",
    "media driven ",
    "global ",
    "local ",
    "post-",
    "hyper-",
    "trans-",
    "extra-",
    "super-",
    "supra-",
    "world regarding ",
    "provably optimal ",
    "potential "
  ],

  finishes : [
    "marvel.",
    "choices.",
    "harmony.",
    "phylogeny.",
    "disharmony.",
    "traversal.",
    "ostracism.",
    "semiotics.",
    "deconstructionism.",
    "post-logic.",
    "escapism.",
    "criarchy.",
    "platitudinality.",
    "creosophy.",
    "journalism.",
    "preternaturality.",
    "glossolalia.",
    "idolatry.",
    "conscience confluence.",
    "hapto-ergonomics.",
    "mental rigor.",
    "spiritual fortitude.",
    "wisdom.",
    "secret genius.",
    "inner brilliance.",
    "unseen internal gift.",
    "combobulation.",
    "transdoctrinal inference.",
    "creativity.",
    "significance.",
    "materialization.",
    "generosity.",
    "infinitude.",
    "plurality.",
    "asceticism.",
    "truism.",
    "monopoly.",
    "temerity.",
    "monosophism.",
    "polyarchy.",
    "togetherness.",
    "voluminous reaction.",
    "joyous revelation.",
    "stimulation.",
    "numbing.",
    "intuition.",
    "actions."
  ]

};

function randFrom(X) {
  return X[Math.floor(Math.random() * X.length)];
}

function makeDC() {
  return randFrom(Data.starts) + randFrom(Data.middles) + randFrom(Data.qualifiers) + randFrom(Data.finishes);
}

function go() {
  document.getElementById('txt').innerHTML = '"' + makeDC() + '"';
}
<|endoftext|>


<commit_before>"use strict";

// Set the name of the hidden property and the change event for visibility
var hidden,
	visibilityChange;

if ( typeof document.hidden !== "undefined" ) { // Opera 12.10 and Firefox 18 and later support
	hidden           = "hidden";
	visibilityChange = "visibilitychange";
}
else if ( typeof document.mozHidden !== "undefined" ) {
	hidden           = "mozHidden";
	visibilityChange = "mozvisibilitychange";
}
else if ( typeof document.msHidden !== "undefined" ) {
	hidden           = "msHidden";
	visibilityChange = "msvisibilitychange";
}
else if ( typeof document.webkitHidden !== "undefined" ) {
	hidden           = "webkitHidden";
	visibilityChange = "webkitvisibilitychange";
}

module.exports = function ( onhide, onshow ) {
	if ( typeof document.addEventListener === "undefined" || typeof document[ hidden ] === "undefined" ) {
		return false;
	}
	else {
		document.addEventListener( visibilityChange, function () {
			if ( document[ hidden ] ) {
				onhide();
			}
			else {
				onshow();
			}
		}, false );

		return true;
	}
};
<commit_msg>visibility<commit_after>(function ( root, factory ) {
	if ( typeof exports === 'object' ) {
		module.exports = factory();
	}
	else {
		root.visibility = factory();
	}
}( this, function () {
	'use strict';

// Set the name of the hidden property and the change event for visibility
	var hidden,
		visibilityChange;

	if ( typeof document.hidden !== "undefined" ) { // Opera 12.10 and Firefox 18 and later support
		hidden           = "hidden";
		visibilityChange = "visibilitychange";
	}
	else if ( typeof document.mozHidden !== "undefined" ) {
		hidden           = "mozHidden";
		visibilityChange = "mozvisibilitychange";
	}
	else if ( typeof document.msHidden !== "undefined" ) {
		hidden           = "msHidden";
		visibilityChange = "msvisibilitychange";
	}
	else if ( typeof document.webkitHidden !== "undefined" ) {
		hidden           = "webkitHidden";
		visibilityChange = "webkitvisibilitychange";
	}

	function visibility( onhide, onshow ) {
		if ( typeof document.addEventListener === "undefined" || typeof document[ hidden ] === "undefined" ) {
			return false;
		}
		else {
			document.addEventListener( visibilityChange, function () {
				if ( document[ hidden ] ) {
					onhide();
				}
				else {
					onshow();
				}
			}, false );

			return true;
		}
	};

	return visibility;
} ));
<|endoftext|>


<commit_before>import { dispatch as d3_dispatch } from 'd3-dispatch';
import { mouse as d3_mouse } from 'd3-selection';

import { utilRebind } from './rebind';
import { geoVecLength } from '../geo/vector';

// a double-click / double-tap event detector with wider
export function utilDoubleUp() {

    var dispatch = d3_dispatch('doubleUp');

    var _maxTimespan = 500; // milliseconds
    var _maxDistance = 20; // web pixels; be somewhat generous to account for touch devices
    var _pointer; // object representing the pointer that could trigger double up

    function pointerIsValidFor(loc) {
        // second pointerup must occur within a small timeframe after the first pointerdown
        return new Date().getTime() - _pointer.startTime <= _maxTimespan &&
            // all pointer events must occur within a small distance of the first pointerdown
            geoVecLength(_pointer.startLoc, loc) <= _maxDistance;
    }

    function pointerdown() {
        // d3_mouse works since pointer events inherit from mouse events
        var loc = d3_mouse(this);

        if (_pointer && !pointerIsValidFor(loc)) {
            // if this pointer is no longer valid, clear it so another can be started
            _pointer = undefined;
        }
        if (!_pointer) {
            // don't rely on the pointerId since it can change between down events on touch devices
            _pointer = {
                startLoc: loc,
                startTime: new Date().getTime(),
                upCount: 0
            };
        }
    }

    function pointerup() {
        if (!_pointer) return;

        _pointer.upCount += 1;

        if (_pointer.upCount === 2) { // double up!
            var loc = d3_mouse(this);
            if (pointerIsValidFor(loc)) {
                dispatch.call('doubleUp', this, loc);
            }
            // clear the pointer info in any case
            _pointer = undefined;
        }
    }

    function doubleUp(selection) {
        if ('PointerEvent' in window) {
            // dblclick isn't well supported on touch devices so manually use
            // pointer events if they're available
            selection
                .on('pointerdown.doubleUp', pointerdown)
                .on('pointerup.doubleUp', pointerup);
        } else {
            // fallback to dblclick
            selection
                .on('dblclick.doubleUp', function() {
                    dispatch.call('doubleUp', this, d3_mouse(this));
                });
        }
    }

    doubleUp.off = function(selection) {
        selection
            .on('pointerdown.doubleUp', null)
            .on('pointerup.doubleUp', null)
            .on('dblclick.doubleUp', null);
    };

    return utilRebind(doubleUp, dispatch, 'on');
}
<commit_msg>Improve utilDoubleUp comment<commit_after>import { dispatch as d3_dispatch } from 'd3-dispatch';
import { mouse as d3_mouse } from 'd3-selection';

import { utilRebind } from './rebind';
import { geoVecLength } from '../geo/vector';

// A custom double-click / double-tap event detector that works on touch devices
// if pointer events are supported. Falls back to default `dblclick` event.
export function utilDoubleUp() {

    var dispatch = d3_dispatch('doubleUp');

    var _maxTimespan = 500; // milliseconds
    var _maxDistance = 20; // web pixels; be somewhat generous to account for touch devices
    var _pointer; // object representing the pointer that could trigger double up

    function pointerIsValidFor(loc) {
        // second pointerup must occur within a small timeframe after the first pointerdown
        return new Date().getTime() - _pointer.startTime <= _maxTimespan &&
            // all pointer events must occur within a small distance of the first pointerdown
            geoVecLength(_pointer.startLoc, loc) <= _maxDistance;
    }

    function pointerdown() {
        // d3_mouse works since pointer events inherit from mouse events
        var loc = d3_mouse(this);

        if (_pointer && !pointerIsValidFor(loc)) {
            // if this pointer is no longer valid, clear it so another can be started
            _pointer = undefined;
        }
        if (!_pointer) {
            // don't rely on the pointerId since it can change between down events on touch devices
            _pointer = {
                startLoc: loc,
                startTime: new Date().getTime(),
                upCount: 0
            };
        }
    }

    function pointerup() {
        if (!_pointer) return;

        _pointer.upCount += 1;

        if (_pointer.upCount === 2) { // double up!
            var loc = d3_mouse(this);
            if (pointerIsValidFor(loc)) {
                dispatch.call('doubleUp', this, loc);
            }
            // clear the pointer info in any case
            _pointer = undefined;
        }
    }

    function doubleUp(selection) {
        if ('PointerEvent' in window) {
            // dblclick isn't well supported on touch devices so manually use
            // pointer events if they're available
            selection
                .on('pointerdown.doubleUp', pointerdown)
                .on('pointerup.doubleUp', pointerup);
        } else {
            // fallback to dblclick
            selection
                .on('dblclick.doubleUp', function() {
                    dispatch.call('doubleUp', this, d3_mouse(this));
                });
        }
    }

    doubleUp.off = function(selection) {
        selection
            .on('pointerdown.doubleUp', null)
            .on('pointerup.doubleUp', null)
            .on('dblclick.doubleUp', null);
    };

    return utilRebind(doubleUp, dispatch, 'on');
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { getDay, getMonth } from '../DateFunctions'
import '../../styles/time.css';

class CalendarDateBox extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        const date = this.props.date;

        let weekday = getDay(date.getDay());
        let month = getMonth(date.getMonth());
        let year = date.getFullYear();

        let diff = date.getTime() - new Date().getTime();
        let titleInfo = null;
        if (diff < 0) {
            titleInfo = "For " + Math.abs(Math.ceil(diff / (1000 * 3600 * 24))) + " dager siden";
        }
        else {
            titleInfo = "Om " + Math.ceil(diff / (1000 * 3600 * 24)) + " dager";
        }

        return(
            <time className="icon" title={titleInfo}>
                {weekday}
                {month} {year}
                {date.getDate()}
            </time>
        )
    }
}

export default CalendarDateBox;
<commit_msg>cleaned calendarDateBox<commit_after>import React, {Component} from 'react';
import {getDay, getMonth} from '../DateFunctions'
import '../../styles/time.css';

class CalendarDateBox extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        const date = this.props.date;

        let weekday = getDay(date.getDay());
        let month = getMonth(date.getMonth());
        let year = date.getFullYear();
        let diff = date.getTime() - new Date().getTime();
        let titleInfo = null;

        if (diff < 0) {
            titleInfo = "For " + Math.abs(Math.ceil(diff / (1000 * 3600 * 24))) + " dager siden";
        }
        else {
            titleInfo = "Om " + Math.ceil(diff / (1000 * 3600 * 24)) + " dager";
        }

        return (
            <time className="icon" title={titleInfo}>
                {weekday}
                {month} {year}
                {date.getDate()}
            </time>
        )
    }
}

export default CalendarDateBox;
<|endoftext|>


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

'use strict';

// sample-metadata:
//  title: Inspects strings
//  description: Inspect a string using the Data Loss Prevention API.
//  usage: node inspectString.js my-project string minLikelihood maxFindings infoTypes customInfoTypes includeQuote

function main(
  projectId,
  string,
  minLikelihood,
  maxFindings,
  infoTypes,
  customInfoTypes,
  includeQuote
) {
  [infoTypes, customInfoTypes] = transformCLI(infoTypes, customInfoTypes);

  // [START dlp_inspect_string]
  // Imports the Google Cloud Data Loss Prevention library
  const DLP = require('@google-cloud/dlp');

  // Instantiates a client
  const dlp = new DLP.DlpServiceClient();

  // The project ID to run the API call under
  // const projectId = 'my-project';

  // The string to inspect
  // const string = 'My name is Gary and my email is gary@example.com';

  // The minimum likelihood required before returning a match
  // const minLikelihood = 'LIKELIHOOD_UNSPECIFIED';

  // The maximum number of findings to report per request (0 = server maximum)
  // const maxFindings = 0;

  // The infoTypes of information to match
  // const infoTypes = [{ name: 'PHONE_NUMBER' }, { name: 'EMAIL_ADDRESS' }, { name: 'CREDIT_CARD_NUMBER' }];

  // The customInfoTypes of information to match
  // const customInfoTypes = [{ infoType: { name: 'DICT_TYPE' }, dictionary: { wordList: { words: ['foo', 'bar', 'baz']}}},
  //   { infoType: { name: 'REGEX_TYPE' }, regex: {pattern: '\\(\\d{3}\\) \\d{3}-\\d{4}'}}];

  // Whether to include the matching string
  // const includeQuote = true;

  async function inspectString() {
    // Construct item to inspect
    const item = {value: string};

    // Construct request
    const request = {
      parent: `projects/${projectId}/locations/global`,
      inspectConfig: {
        infoTypes: infoTypes,
        customInfoTypes: customInfoTypes,
        minLikelihood: minLikelihood,
        includeQuote: includeQuote,
        limits: {
          maxFindingsPerRequest: maxFindings,
        },
      },
      item: item,
    };

    console.log(request.inspectConfig.infoTypes);
    console.log(Array.isArray(request.inspectConfig.infoTypes));

    // Run request
    const [response] = await dlp.inspectContent(request);
    const findings = response.result.findings;
    if (findings.length > 0) {
      console.log('Findings:');
      findings.forEach(finding => {
        if (includeQuote) {
          console.log(`\tQuote: ${finding.quote}`);
        }
        console.log(`\tInfo type: ${finding.infoType.name}`);
        console.log(`\tLikelihood: ${finding.likelihood}`);
      });
    } else {
      console.log('No findings.');
    }
  }
  inspectString();
  // [END dlp_inspect_string]
}

main(...process.argv.slice(2));
process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});

function transformCLI(infoTypes, customInfoTypes) {
  infoTypes = infoTypes
    ? infoTypes.split(',').map(type => {
        return {name: type};
      })
    : undefined;

  if (customInfoTypes) {
    customInfoTypes = customInfoTypes.includes(',')
      ? customInfoTypes.split(',').map((dict, idx) => {
          return {
            infoType: {name: 'CUSTOM_DICT_'.concat(idx.toString())},
            dictionary: {wordList: {words: dict.split(',')}},
          };
        })
      : customInfoTypes.split(',').map((rgx, idx) => {
          return {
            infoType: {name: 'CUSTOM_REGEX_'.concat(idx.toString())},
            regex: {pattern: rgx},
          };
        });
  }

  return [infoTypes, customInfoTypes];
}
<commit_msg>docs(samples): removed test console logs (#662)<commit_after>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// sample-metadata:
//  title: Inspects strings
//  description: Inspect a string using the Data Loss Prevention API.
//  usage: node inspectString.js my-project string minLikelihood maxFindings infoTypes customInfoTypes includeQuote

function main(
  projectId,
  string,
  minLikelihood,
  maxFindings,
  infoTypes,
  customInfoTypes,
  includeQuote
) {
  [infoTypes, customInfoTypes] = transformCLI(infoTypes, customInfoTypes);

  // [START dlp_inspect_string]
  // Imports the Google Cloud Data Loss Prevention library
  const DLP = require('@google-cloud/dlp');

  // Instantiates a client
  const dlp = new DLP.DlpServiceClient();

  // The project ID to run the API call under
  // const projectId = 'my-project';

  // The string to inspect
  // const string = 'My name is Gary and my email is gary@example.com';

  // The minimum likelihood required before returning a match
  // const minLikelihood = 'LIKELIHOOD_UNSPECIFIED';

  // The maximum number of findings to report per request (0 = server maximum)
  // const maxFindings = 0;

  // The infoTypes of information to match
  // const infoTypes = [{ name: 'PHONE_NUMBER' }, { name: 'EMAIL_ADDRESS' }, { name: 'CREDIT_CARD_NUMBER' }];

  // The customInfoTypes of information to match
  // const customInfoTypes = [{ infoType: { name: 'DICT_TYPE' }, dictionary: { wordList: { words: ['foo', 'bar', 'baz']}}},
  //   { infoType: { name: 'REGEX_TYPE' }, regex: {pattern: '\\(\\d{3}\\) \\d{3}-\\d{4}'}}];

  // Whether to include the matching string
  // const includeQuote = true;

  async function inspectString() {
    // Construct item to inspect
    const item = {value: string};

    // Construct request
    const request = {
      parent: `projects/${projectId}/locations/global`,
      inspectConfig: {
        infoTypes: infoTypes,
        customInfoTypes: customInfoTypes,
        minLikelihood: minLikelihood,
        includeQuote: includeQuote,
        limits: {
          maxFindingsPerRequest: maxFindings,
        },
      },
      item: item,
    };

    // Run request
    const [response] = await dlp.inspectContent(request);
    const findings = response.result.findings;
    if (findings.length > 0) {
      console.log('Findings:');
      findings.forEach(finding => {
        if (includeQuote) {
          console.log(`\tQuote: ${finding.quote}`);
        }
        console.log(`\tInfo type: ${finding.infoType.name}`);
        console.log(`\tLikelihood: ${finding.likelihood}`);
      });
    } else {
      console.log('No findings.');
    }
  }
  inspectString();
  // [END dlp_inspect_string]
}

main(...process.argv.slice(2));
process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});

function transformCLI(infoTypes, customInfoTypes) {
  infoTypes = infoTypes
    ? infoTypes.split(',').map(type => {
        return {name: type};
      })
    : undefined;

  if (customInfoTypes) {
    customInfoTypes = customInfoTypes.includes(',')
      ? customInfoTypes.split(',').map((dict, idx) => {
          return {
            infoType: {name: 'CUSTOM_DICT_'.concat(idx.toString())},
            dictionary: {wordList: {words: dict.split(',')}},
          };
        })
      : customInfoTypes.split(',').map((rgx, idx) => {
          return {
            infoType: {name: 'CUSTOM_REGEX_'.concat(idx.toString())},
            regex: {pattern: rgx},
          };
        });
  }

  return [infoTypes, customInfoTypes];
}
<|endoftext|>


<commit_before>var Landing = {
    is_desktop: undefined,

    render: function() {
        showLoading();
        Landing.make_html();
    },

    make_html: function () {
        $('html,body').animate({scrollTop: 0}, 'fast');
        var landing_source = $("#landing").html();
        var template = Handlebars.compile(landing_source);

        $("#main-content").html(template());

        NoticeBanner.render_init($("#notice_banner_location"));

        AccountSummaryCard.render_init($("#landing_summaries"));

        Landing.load_cards_for_viewport();
        // Set initial display state
        Landing.is_desktop = get_is_desktop();

        // Monitor for viewport changes and reorder cards if needed
        $(window).resize(function(){
            if (Landing.is_desktop !== get_is_desktop()){
                Landing.load_cards_for_viewport();
                Landing.is_desktop = get_is_desktop();
            }
        });
    },

    load_cards_for_viewport: function() {
        if (get_is_desktop()) {
            Landing._load_desktop_cards();
        } else {
            Landing._load_mobile_cards();
        }
    },

    _load_desktop_cards: function() {
        Landing._reset_content_divs();

        Cards.load_cards_in_order(Landing._get_desktop_body_cards(),
                                  $("#landing_content_cards"));
        Cards.load_cards_in_order(Landing._get_desktop_sidebar_cards(),
                                  $("#landing_accounts_cards"));
    },

    _get_desktop_body_cards: function() {
        var desktop_body_cards = [];

        if (window.user.is_hxt_viewer) {
            desktop_body_cards.push(HuskyExperienceCard);
            }

        if (window.user.fyp ||
            window.user.aut_transfer ||
            window.user.win_transfer) {
            desktop_body_cards.push(ThriveCard);
        }

        if (window.user.student ||
            window.user.instructor ||
            window.user.employee) {
            desktop_body_cards.push(OutageCard);
        }

        if (window.user.student) {
            desktop_body_cards.push(GradeCard);
            desktop_body_cards.push(FutureQuarterCardA);
            desktop_body_cards.push(ThankYouCard);
            desktop_body_cards.push(ToRegisterCard);
            desktop_body_cards.push(RegStatusCard);
            desktop_body_cards.push(SummerEFSCard);
            desktop_body_cards.push(SummerRegStatusCardA);
            desktop_body_cards.push(CriticalInfoCard);
            desktop_body_cards.push(InternationalStuCard);
        }

        if (window.user.instructor) {
            desktop_body_cards.push(SummaryScheduleCard);
        }

        if (window.user.student || window.user.instructor) {
            desktop_body_cards.push(VisualScheduleCard);
        }

        if (window.user.student) {
            desktop_body_cards.push(TextbookCard);
        }

        if (window.user.instructor) {
            desktop_body_cards.push(FutureSummaryScheduleCard);
        }

        if (window.user.student) {
            desktop_body_cards.push(FutureQuarterCard1);
            desktop_body_cards.push(SummerRegStatusCard1);
        }
        if (window.user.applicant) {
            desktop_body_cards.push(SeattleApplicationCard);
            desktop_body_cards.push(BothellApplicationCard);
            desktop_body_cards.push(TacomaApplicationCard);
        }

        if (window.user.intl_stud) {
            desktop_body_cards.push(IntlStudCard);
        }

        if(window.user.employee &&
           !window.user.student &&
           !window.user.instructor||
           window.user.past_employee) {
            desktop_body_cards.push(HRPayrollCard);
        }

        if(window.user.retiree) {
            desktop_body_cards.push(RetireAssoCard);
        }

        if(window.user.past_stud) {
            desktop_body_cards.push(TranscriptsCard);
        }

        if (window.user.no_1st_class_affi) {
            desktop_body_cards.push(ContinuingEducationCard);
            desktop_body_cards.push(UwnetidCard);
        }

        if(window.user.alumni) {
            desktop_body_cards.push(AlumniCard);
        }

        // Always show these cards last
        desktop_body_cards.push(ResourcesCard, ResourcesExploreCard);
        return desktop_body_cards;
    },

    _get_desktop_sidebar_cards: function() {
        return [QuickLinksCard,
                AcadCalSnippet,
                EventsCard
               ];
    },

    _load_mobile_cards: function() {
        Landing._reset_content_divs();
        Cards.load_cards_in_order(Landing._get_mobile_cards(),
                                  $("#landing_content_cards"));
    },

    _get_mobile_cards: function() {
        var mobile_cards = [];
        if (window.user.is_hxt_viewer) {
            mobile_cards.push(HuskyExperienceCard);
        }
        if (window.user.applicant) {
            mobile_cards.push(SeattleApplicationCard);
            mobile_cards.push(BothellApplicationCard);
            mobile_cards.push(TacomaApplicationCard);
        }

        mobile_cards.push(QuickLinksCard);

        if (window.user.fyp ||
            window.user.aut_transfer ||
            window.user.win_transfer) {
            mobile_cards.push(ThriveCard);
        }
        if (window.user.student ||
            window.user.instructor ||
            window.user.employee) {
            mobile_cards.push(OutageCard);
        }
        if (window.user.student) {
            mobile_cards.push(GradeCard);
            mobile_cards.push(FutureQuarterCardA);
            mobile_cards.push(ThankYouCard);
            mobile_cards.push(ToRegisterCard);
            mobile_cards.push(RegStatusCard);
            mobile_cards.push(SummerEFSCard);
            mobile_cards.push(SummerRegStatusCardA);
            mobile_cards.push(CriticalInfoCard);
            mobile_cards.push(InternationalStuCard);
        }
        if (window.user.instructor) {
            mobile_cards.push(SummaryScheduleCard);
            mobile_cards.push(FutureSummaryScheduleCard);
        }

        if (window.user.student || window.user.instructor) {
            mobile_cards.push(VisualScheduleCard);
        }
        if (window.user.student) {
            mobile_cards.push(TextbookCard);
        }
        if (window.user.student) {
            mobile_cards.push(FutureQuarterCard1);
            mobile_cards.push(SummerRegStatusCard1);
        }
        mobile_cards.push(AcadCalSnippet);
        mobile_cards.push(EventsCard);

        if (window.user.intl_stud) {
            mobile_cards.push(IntlStudCard);
        }

        if(window.user.employee &&
           !window.user.student &&
           !window.user.instructor &&
           !window.user.applicant ||
           window.user.past_employee) {
            mobile_cards.push(HRPayrollCard);
        }

        if(window.user.retiree) {
            mobile_cards.push(RetireAssoCard);
        }

        if(window.user.past_stud) {
            mobile_cards.push(TranscriptsCard);
        }

        if (window.user.no_1st_class_affi) {
            mobile_cards.push(ContinuingEducationCard);
            mobile_cards.push(UwnetidCard);
        }

        if(window.user.alumni) {
            mobile_cards.push(AlumniCard);
        }
        // Always show these cards last
        mobile_cards.push(ResourcesCard, ResourcesExploreCard);
        return mobile_cards;
    },

    _reset_content_divs: function() {
        // Reset all the multiple resourse card render records
        // needed on every page refresh MUWM-3803
        resetCardRenderCalled();
        $("#landing_content_cards").html('');
        $("#landing_accounts_cards").html('');
    }

};

/* node.js exports */
if (typeof exports === "undefined") {
    var exports = {};
}
exports.Landing = Landing;
<commit_msg>remove a redundant if<commit_after>var Landing = {
    is_desktop: undefined,

    render: function() {
        showLoading();
        Landing.make_html();
    },

    make_html: function () {
        $('html,body').animate({scrollTop: 0}, 'fast');
        var landing_source = $("#landing").html();
        var template = Handlebars.compile(landing_source);

        $("#main-content").html(template());

        NoticeBanner.render_init($("#notice_banner_location"));

        AccountSummaryCard.render_init($("#landing_summaries"));

        Landing.load_cards_for_viewport();
        // Set initial display state
        Landing.is_desktop = get_is_desktop();

        // Monitor for viewport changes and reorder cards if needed
        $(window).resize(function(){
            if (Landing.is_desktop !== get_is_desktop()){
                Landing.load_cards_for_viewport();
                Landing.is_desktop = get_is_desktop();
            }
        });
    },

    load_cards_for_viewport: function() {
        if (get_is_desktop()) {
            Landing._load_desktop_cards();
        } else {
            Landing._load_mobile_cards();
        }
    },

    _load_desktop_cards: function() {
        Landing._reset_content_divs();

        Cards.load_cards_in_order(Landing._get_desktop_body_cards(),
                                  $("#landing_content_cards"));
        Cards.load_cards_in_order(Landing._get_desktop_sidebar_cards(),
                                  $("#landing_accounts_cards"));
    },

    _get_desktop_body_cards: function() {
        var desktop_body_cards = [];

        if (window.user.is_hxt_viewer) {
            desktop_body_cards.push(HuskyExperienceCard);
            }

        if (window.user.fyp ||
            window.user.aut_transfer ||
            window.user.win_transfer) {
            desktop_body_cards.push(ThriveCard);
        }

        if (window.user.student ||
            window.user.instructor ||
            window.user.employee) {
            desktop_body_cards.push(OutageCard);
        }

        if (window.user.student) {
            desktop_body_cards.push(GradeCard);
            desktop_body_cards.push(FutureQuarterCardA);
            desktop_body_cards.push(ThankYouCard);
            desktop_body_cards.push(ToRegisterCard);
            desktop_body_cards.push(RegStatusCard);
            desktop_body_cards.push(SummerEFSCard);
            desktop_body_cards.push(SummerRegStatusCardA);
            desktop_body_cards.push(CriticalInfoCard);
            desktop_body_cards.push(InternationalStuCard);
        }

        if (window.user.instructor) {
            desktop_body_cards.push(SummaryScheduleCard);
        }

        if (window.user.student || window.user.instructor) {
            desktop_body_cards.push(VisualScheduleCard);
        }

        if (window.user.student) {
            desktop_body_cards.push(TextbookCard);
        }

        if (window.user.instructor) {
            desktop_body_cards.push(FutureSummaryScheduleCard);
        }

        if (window.user.student) {
            desktop_body_cards.push(FutureQuarterCard1);
            desktop_body_cards.push(SummerRegStatusCard1);
        }
        if (window.user.applicant) {
            desktop_body_cards.push(SeattleApplicationCard);
            desktop_body_cards.push(BothellApplicationCard);
            desktop_body_cards.push(TacomaApplicationCard);
        }

        if (window.user.intl_stud) {
            desktop_body_cards.push(IntlStudCard);
        }

        if(window.user.employee &&
           !window.user.student &&
           !window.user.instructor||
           window.user.past_employee) {
            desktop_body_cards.push(HRPayrollCard);
        }

        if(window.user.retiree) {
            desktop_body_cards.push(RetireAssoCard);
        }

        if(window.user.past_stud) {
            desktop_body_cards.push(TranscriptsCard);
        }

        if (window.user.no_1st_class_affi) {
            desktop_body_cards.push(ContinuingEducationCard);
            desktop_body_cards.push(UwnetidCard);
        }

        if(window.user.alumni) {
            desktop_body_cards.push(AlumniCard);
        }

        // Always show these cards last
        desktop_body_cards.push(ResourcesCard, ResourcesExploreCard);
        return desktop_body_cards;
    },

    _get_desktop_sidebar_cards: function() {
        return [QuickLinksCard,
                AcadCalSnippet,
                EventsCard
               ];
    },

    _load_mobile_cards: function() {
        Landing._reset_content_divs();
        Cards.load_cards_in_order(Landing._get_mobile_cards(),
                                  $("#landing_content_cards"));
    },

    _get_mobile_cards: function() {
        var mobile_cards = [];
        if (window.user.is_hxt_viewer) {
            mobile_cards.push(HuskyExperienceCard);
        }
        if (window.user.applicant) {
            mobile_cards.push(SeattleApplicationCard);
            mobile_cards.push(BothellApplicationCard);
            mobile_cards.push(TacomaApplicationCard);
        }

        mobile_cards.push(QuickLinksCard);

        if (window.user.fyp ||
            window.user.aut_transfer ||
            window.user.win_transfer) {
            mobile_cards.push(ThriveCard);
        }
        if (window.user.student ||
            window.user.instructor ||
            window.user.employee) {
            mobile_cards.push(OutageCard);
        }
        if (window.user.student) {
            mobile_cards.push(GradeCard);
            mobile_cards.push(FutureQuarterCardA);
            mobile_cards.push(ThankYouCard);
            mobile_cards.push(ToRegisterCard);
            mobile_cards.push(RegStatusCard);
            mobile_cards.push(SummerEFSCard);
            mobile_cards.push(SummerRegStatusCardA);
            mobile_cards.push(CriticalInfoCard);
            mobile_cards.push(InternationalStuCard);
        }
        if (window.user.instructor) {
            mobile_cards.push(SummaryScheduleCard);
            mobile_cards.push(FutureSummaryScheduleCard);
        }

        if (window.user.student || window.user.instructor) {
            mobile_cards.push(VisualScheduleCard);
        }
        if (window.user.student) {
            mobile_cards.push(TextbookCard);
            mobile_cards.push(FutureQuarterCard1);
            mobile_cards.push(SummerRegStatusCard1);
        }
        mobile_cards.push(AcadCalSnippet);
        mobile_cards.push(EventsCard);

        if (window.user.intl_stud) {
            mobile_cards.push(IntlStudCard);
        }

        if(window.user.employee &&
           !window.user.student &&
           !window.user.instructor &&
           !window.user.applicant ||
           window.user.past_employee) {
            mobile_cards.push(HRPayrollCard);
        }

        if(window.user.retiree) {
            mobile_cards.push(RetireAssoCard);
        }

        if(window.user.past_stud) {
            mobile_cards.push(TranscriptsCard);
        }

        if (window.user.no_1st_class_affi) {
            mobile_cards.push(ContinuingEducationCard);
            mobile_cards.push(UwnetidCard);
        }

        if(window.user.alumni) {
            mobile_cards.push(AlumniCard);
        }
        // Always show these cards last
        mobile_cards.push(ResourcesCard, ResourcesExploreCard);
        return mobile_cards;
    },

    _reset_content_divs: function() {
        // Reset all the multiple resourse card render records
        // needed on every page refresh MUWM-3803
        resetCardRenderCalled();
        $("#landing_content_cards").html('');
        $("#landing_accounts_cards").html('');
    }

};

/* node.js exports */
if (typeof exports === "undefined") {
    var exports = {};
}
exports.Landing = Landing;
<|endoftext|>