<commit_before>var fs = require('fs');
var cfs = fs.readdirSync('./json');
var constants = {};
cfs.forEach(function(f) {
    constants[f.split(".")[0]] = require('./json/' + f);
});
var heroes = constants.heroes.result.heroes;
//key heroes by id
constants.heroes = {};
//key heroes by name
constants.hero_names = {};
heroes.forEach(function(h) {
    h.img = "http://cdn.dota2.com/apps/dota2/images/heroes/" + h.name.replace("npc_dota_hero_", "") + "_sb.png";
    constants.heroes[h.id] = h;
    constants.hero_names[h.name] = h;
});
/*
//leagues, key by id
var leagues = JSON.parse(JSON.stringify(constants.leagues.result.leagues));
constants.leagues = {};
leagues.forEach(function(l) {
    l.name = l.name.replace("#DOTA_Item_", "").split("_").join(" ");
    constants.leagues[l.leagueid] = l;
});
*/
//items, already keyed by name
var items = constants.items.itemdata;
constants.item_ids = {};
for (var key in items) {
    constants.item_ids[items[key].id] = key;
    items[key].img = "http://cdn.dota2.com/apps/dota2/images/items/" + items[key].img;
}
constants.items = items;
//abilities, already keyed by name
var abilities = constants.abilities.abilitydata;
for (var key2 in abilities) {
    abilities[key2].img = "http://cdn.dota2.com/apps/dota2/images/abilities/" + key2 + "_md.png";
}
abilities.nevermore_shadowraze2 = abilities.nevermore_shadowraze1;
abilities.nevermore_shadowraze3 = abilities.nevermore_shadowraze1;
abilities.stats = {
    dname: "Stats",
    img: '../../public/images/Stats.png',
    attrib: "+2 All Attributes"
};
constants.abilities = abilities;
constants.lanes = [];
for (var i = 0; i < 128; i++) {
    constants.lanes.push([]);
    for (var j = 0; j < 128; j++) {
        var lane;
        if (Math.abs(i - (127 - j)) < 8) {
            lane = 2; //mid
        }
        else if (j < 27 || i < 27) {
            lane = 3; //top
        }
        else if (j >= 100 || i >= 100) {
            lane = 1; //bot
        }
        else if (i < 50) {
            lane = 5; //djung
        }
        else if (i >= 77) {
            lane = 4; //rjung
        }
        else {
            lane = 2; //mid
        }
        constants.lanes[i].push(lane);
    }
}
var cluster = {};
var regions_id = {};
//Remove regions nesting
constants.regions = constants.regions.regions;
var regions = constants.regions;
for (var key in regions) {
    var id = regions[key].region;
    regions_id[id] = key;
    if (regions[key].clusters) {
        regions[key].clusters.forEach(function(c) {
            cluster[c] = regions[key].display_name.slice("#dota_region_".length).split("_").map(function(s) {
                return s.toUpperCase();
            }).join(" ");
        });
    }
}
cluster["121"] = "US EAST";
constants.regions_id = regions_id;
console.log(constants.regions_id);
constants.cluster = cluster;
constants.anonymous_account_id = 4294967295;
module.exports = constants;
<commit_msg>Remove debug Signed-off-by: WTFKr0 <thomas.kovatchitch@gmail.com><commit_after>var fs = require('fs');
var cfs = fs.readdirSync('./json');
var constants = {};
cfs.forEach(function(f) {
    constants[f.split(".")[0]] = require('./json/' + f);
});
var heroes = constants.heroes.result.heroes;
//key heroes by id
constants.heroes = {};
//key heroes by name
constants.hero_names = {};
heroes.forEach(function(h) {
    h.img = "http://cdn.dota2.com/apps/dota2/images/heroes/" + h.name.replace("npc_dota_hero_", "") + "_sb.png";
    constants.heroes[h.id] = h;
    constants.hero_names[h.name] = h;
});
/*
//leagues, key by id
var leagues = JSON.parse(JSON.stringify(constants.leagues.result.leagues));
constants.leagues = {};
leagues.forEach(function(l) {
    l.name = l.name.replace("#DOTA_Item_", "").split("_").join(" ");
    constants.leagues[l.leagueid] = l;
});
*/
//items, already keyed by name
var items = constants.items.itemdata;
constants.item_ids = {};
for (var key in items) {
    constants.item_ids[items[key].id] = key;
    items[key].img = "http://cdn.dota2.com/apps/dota2/images/items/" + items[key].img;
}
constants.items = items;
//abilities, already keyed by name
var abilities = constants.abilities.abilitydata;
for (var key2 in abilities) {
    abilities[key2].img = "http://cdn.dota2.com/apps/dota2/images/abilities/" + key2 + "_md.png";
}
abilities.nevermore_shadowraze2 = abilities.nevermore_shadowraze1;
abilities.nevermore_shadowraze3 = abilities.nevermore_shadowraze1;
abilities.stats = {
    dname: "Stats",
    img: '../../public/images/Stats.png',
    attrib: "+2 All Attributes"
};
constants.abilities = abilities;
constants.lanes = [];
for (var i = 0; i < 128; i++) {
    constants.lanes.push([]);
    for (var j = 0; j < 128; j++) {
        var lane;
        if (Math.abs(i - (127 - j)) < 8) {
            lane = 2; //mid
        }
        else if (j < 27 || i < 27) {
            lane = 3; //top
        }
        else if (j >= 100 || i >= 100) {
            lane = 1; //bot
        }
        else if (i < 50) {
            lane = 5; //djung
        }
        else if (i >= 77) {
            lane = 4; //rjung
        }
        else {
            lane = 2; //mid
        }
        constants.lanes[i].push(lane);
    }
}
var cluster = {};
var regions_id = {};
//Remove regions nesting
constants.regions = constants.regions.regions;
var regions = constants.regions;
for (var key in regions) {
    var id = regions[key].region;
    regions_id[id] = key;
    if (regions[key].clusters) {
        regions[key].clusters.forEach(function(c) {
            cluster[c] = regions[key].display_name.slice("#dota_region_".length).split("_").map(function(s) {
                return s.toUpperCase();
            }).join(" ");
        });
    }
}
cluster["121"] = "US EAST";
constants.regions_id = regions_id;
constants.cluster = cluster;
constants.anonymous_account_id = 4294967295;
module.exports = constants;
<|endoftext|>


<commit_before>Constants = (function() {
    var CONSTANTS_URI = 'http://constantine.teaisaweso.me/json'

    var gotConstants = new Bacon.Bus();
    var constants = gotConstants.toProperty();

    var getAll = function(callback) {
        constants.onValue(callback);
    };

    var reload = function() {
        var rawConstants = $.get(CONSTANTS_URI);
        rawConstants.done(function(value) {
            var baseValues = JSON.parse(value);
            var actualConstants = {};
            _.each(baseValues['constants'], function(tuple) {
                actualConstants[tuple.name] = tuple.value;
            });
            gotConstants.push(actualConstants);
        });
    };

    var get = function(key, callback) {
        var newStream = constants.map(function(x) { return x[key]; }).skipDuplicates();
        newStream.onValue(callback);
    };

    constants.onValue(function() {
        console.log("Constants loaded.");
    });

    $(_.defer(reload));

    return {'getAll': getAll,
            'get': get,
            'reload': reload};

}());

<commit_msg>Decode tuple values into the correct types<commit_after>Constants = (function() {
    var CONSTANTS_URI = 'http://constantine.teaisaweso.me/json'

    var gotConstants = new Bacon.Bus();
    var constants = gotConstants.toProperty();

    var getAll = function(callback) {
        constants.onValue(callback);
    };

    var reload = function() {
        var rawConstants = $.get(CONSTANTS_URI);
        var typeDecoders = {'string': function(x) { return x; },
                            'float': parseFloat,
                            'int': parseFloat,
                            'boolean': function(x) { return x == 'true'; }}
        rawConstants.done(function(value) {
            var baseValues = JSON.parse(value);
            var actualConstants = {};
            _.each(baseValues['constants'], function(tuple) {
                actualConstants[tuple.name] = typeDecoders[tuple.type](tuple.value);
            });
            gotConstants.push(actualConstants);
        });
    };

    var get = function(key, callback) {
        var newStream = constants.map(function(x) { return x[key]; }).skipDuplicates();
        newStream.onValue(callback);
    };

    constants.onValue(function() {
        console.log("Constants loaded.");
    });

    $(_.defer(reload));

    return {'getAll': getAll,
            'get': get,
            'reload': reload};

}());

<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const fileUrl = require('file-url');
const failFast = require('protractor-fail-fast');

const failFastActive = (process.argv.length > 4 && process.argv[4] == '--params=ff');

exports.config = {

    seleniumAddress: 'http://localhost:9515/wd/hub',
    baseUrl: fileUrl(path.resolve(__dirname, '../../..') + '/index.html'),

    suites: {
        default: [
            '../syncing/*.spec.js',
            '../images/*.spec.js',
            '../import/*.spec.js',
            '../list/*.spec.js',
            '../resources/map/*.spec.js',
            '../widgets/*.spec.js',
            '../settings/*.spec.js',
            '../resources/*.spec.js'
        ],
        flaky: [
            '../flaky/*.spec.js'
        ]
    },

    allScriptsTimeout: 110000,
    getPageTimeout: 100000,
    framework: 'jasmine2',
    jasmineNodeOpts: {
        isVerbose: false,
        showColors: true,
        includeStackTrace: false,
        defaultTimeoutInterval: 400000
    },
    plugins: [{
        package: 'protractor-console-plugin',
        failOnWarning: true,
        failOnError: true,
        logWarnings: true,
        exclude: [
            "http://localhost:3001/" // pouchdb issues ignorable errors when syncing
        ]
    }],
    params: {
        configPath: 'config/config.test.json',
        configTemplate: { 'dbs' : ['test'] }
    },
    onPrepare: function() {
        if (failFastActive) {
            console.log("Fail fast mode active");
            jasmine.getEnv().addReporter(failFast.init());
        }

        var FailureScreenshotReporter = function() {

            this.specStarted = function(spec) {
                process.stdout.write("SPEC " + spec.fullName + " ")
            };

            this.specDone = function(spec) {
                console.log(spec.status.toUpperCase())
            }
        };
        jasmine.getEnv().addReporter(new FailureScreenshotReporter());
    },
    afterLaunch: function() {
        if (failFastActive) failFast.clean();
    },
    /**
     * ng2 related configuration
     *
     * useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching
     * `rootEl`
     *
     */
    useAllAngular2AppRoots: true
};

if (failFastActive) exports.config.plugins.push({package: 'protractor-fail-fast'});<commit_msg>run settings test first<commit_after>const fs = require('fs');
const path = require('path');
const fileUrl = require('file-url');
const failFast = require('protractor-fail-fast');

const failFastActive = (process.argv.length > 4 && process.argv[4] == '--params=ff');

exports.config = {

    seleniumAddress: 'http://localhost:9515/wd/hub',
    baseUrl: fileUrl(path.resolve(__dirname, '../../..') + '/index.html'),

    suites: {
        default: [
            '../settings/*.spec.js',
            '../syncing/*.spec.js',
            '../images/*.spec.js',
            '../import/*.spec.js',
            '../list/*.spec.js',
            '../resources/map/*.spec.js',
            '../widgets/*.spec.js',
            '../resources/*.spec.js'
        ],
        flaky: [
            '../flaky/*.spec.js'
        ]
    },

    allScriptsTimeout: 110000,
    getPageTimeout: 100000,
    framework: 'jasmine2',
    jasmineNodeOpts: {
        isVerbose: false,
        showColors: true,
        includeStackTrace: false,
        defaultTimeoutInterval: 400000
    },
    plugins: [{
        package: 'protractor-console-plugin',
        failOnWarning: true,
        failOnError: true,
        logWarnings: true,
        exclude: [
            "http://localhost:3001/" // pouchdb issues ignorable errors when syncing
        ]
    }],
    params: {
        configPath: 'config/config.test.json',
        configTemplate: { 'dbs' : ['test'] }
    },
    onPrepare: function() {
        if (failFastActive) {
            console.log("Fail fast mode active");
            jasmine.getEnv().addReporter(failFast.init());
        }

        var FailureScreenshotReporter = function() {

            this.specStarted = function(spec) {
                process.stdout.write("SPEC " + spec.fullName + " ")
            };

            this.specDone = function(spec) {
                console.log(spec.status.toUpperCase())
            }
        };
        jasmine.getEnv().addReporter(new FailureScreenshotReporter());
    },
    afterLaunch: function() {
        if (failFastActive) failFast.clean();
    },
    /**
     * ng2 related configuration
     *
     * useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching
     * `rootEl`
     *
     */
    useAllAngular2AppRoots: true
};

if (failFastActive) exports.config.plugins.push({package: 'protractor-fail-fast'});<|endoftext|>


<commit_before>describe('Search', function() {
  const kuzzleUrl = 'http://localhost:7512'
  const indexName = 'testindex'
  const collectionName = 'testcollection'

  beforeEach(() => {
    // reset database and setup
    cy.request('POST', `${kuzzleUrl}/admin/_resetDatabase`)
    cy.request('POST', `${kuzzleUrl}/${indexName}/_create`)
    cy.request('PUT', `${kuzzleUrl}/${indexName}/${collectionName}`)
    cy.request('POST', `${kuzzleUrl}/${indexName}/${collectionName}/_create`, {
      firstName: 'Luca',
      lastName: 'Marchesini',
      job: 'Blockchain as a Service'
    })

    // create environment
    const validEnvName = 'valid'
    localStorage.setItem(
      'environments',
      JSON.stringify({
        [validEnvName]: {
          name: validEnvName,
          color: '#002835',
          host: 'localhost',
          ssl: false,
          port: 7512,
          token: null
        }
      })
    )
  })

  it('perists the Quick Search query in the URL', function() {
    cy.request('POST', `${kuzzleUrl}/${indexName}/${collectionName}/_create`, {
      firstName: 'Adrien',
      lastName: 'Maret',
      job: 'Blockchain Keylogger as a Service'
    })
    cy.visit('/')
    cy.get('.LoginAsAnonymous-Btn').click()
    cy.contains('Indexes')
    cy.visit(`/#/data/${indexName}/${collectionName}`)
    cy.get('.QuickFilter-searchBar input').type('Keylogger', { delay: 60 })
    cy.url().should('contain', 'quick=Keylogger')
    cy.url().should('contain', 'active=quick')
  })

  it('persists the Basic Search query in the URL', function() {
    cy.request('POST', `${kuzzleUrl}/${indexName}/${collectionName}/_create`, {
      firstName: 'Adrien',
      lastName: 'Maret',
      job: 'Blockchain Keylogger as a Service'
    })
    cy.visit('/')
    cy.get('.LoginAsAnonymous-Btn').click()
    cy.contains('Indexes')
    cy.visit(`/#/data/${indexName}/${collectionName}`)
    cy.get('.QuickFilter-optionBtn').click()
    cy.get('.BasicFilter-query input[placeholder=Attribute]').type('job')
    cy.get('.BasicFilter-query input[placeholder=Value]').type('Blockchain')
    cy.get('.BasicFilter-submitBtn').click()
    cy.url().should('contain', 'active=basic')
    cy.url().should('contain', 'attribute')
    cy.url().should('contain', 'job')
    cy.url().should('contain', 'match')
    cy.url().should('contain', 'Blockchain')
  })

  it('remembers the Quick Search query across collections', function() {
    cy.request('POST', `${kuzzleUrl}/${indexName}/${collectionName}/_create`, {
      firstName: 'Adrien',
      lastName: 'Maret',
      job: 'Blockchain Keylogger as a Service'
    })

    cy.request('PUT', `${kuzzleUrl}/${indexName}/anothercollection`)
    cy.request('POST', `${kuzzleUrl}/${indexName}/anothercollection/_create`, {
      firstName: 'Nicolas',
      lastName: 'Juelle',
      job: 'CSS Level: Expert !important'
    })
    cy.request('POST', `${kuzzleUrl}/${indexName}/anothercollection/_create`, {
      firstName: 'Alexandre',
      lastName: 'Bouthinon',
      job: 'From scratch All the Things!'
    })

    cy.visit('/')
    cy.get('.LoginAsAnonymous-Btn').click()
    cy.contains('Indexes')
    cy.visit(`/#/data/${indexName}/${collectionName}`)
    cy.get('.QuickFilter-searchBar input').type('Keylogger', { delay: 60 })
    cy.get('.Treeview-root .tree-item')
      .contains('anothercollection')
      .click()
    cy.url().should('not.contain', 'Keylogger')
    cy.get('.DocumentListItem').should('have.length', 2)

    cy.get('.Treeview-root .tree-item')
      .contains(collectionName)
      .click()
    cy.url().should('contain', 'Keylogger')
    cy.get('.DocumentListItem').should('have.length', 1)
  })

  it('remembers the Basic Search query across collections', function() {
    cy.request('POST', `${kuzzleUrl}/${indexName}/${collectionName}/_create`, {
      firstName: 'Adrien',
      lastName: 'Maret',
      job: 'Blockchain Keylogger as a Service'
    })

    cy.request('PUT', `${kuzzleUrl}/${indexName}/anothercollection`)
    cy.request('POST', `${kuzzleUrl}/${indexName}/anothercollection/_create`, {
      firstName: 'Nicolas',
      lastName: 'Juelle',
      job: 'CSS Level: Expert !important'
    })
    cy.request('POST', `${kuzzleUrl}/${indexName}/anothercollection/_create`, {
      firstName: 'Alexandre',
      lastName: 'Bouthinon',
      job: 'From scratch All the Things!'
    })

    cy.visit('/')
    cy.get('.LoginAsAnonymous-Btn').click()
    cy.contains('Indexes')
    cy.visit(`/#/data/${indexName}/${collectionName}`)

    cy.get('.QuickFilter-optionBtn').click()
    cy.get('.BasicFilter-query input[placeholder=Attribute]').type('job')
    cy.get('.BasicFilter-query input[placeholder=Value]').type('Keylogger')
    cy.get('.BasicFilter-submitBtn').click()
    cy.get('.DocumentListItem').should('have.length', 1)

    cy.get('.Treeview-root .tree-item')
      .contains('anothercollection')
      .click()
    cy.url().should('not.contain', 'Keylogger')
    cy.get('.DocumentListItem').should('have.length', 2)

    cy.get('.Treeview-root .tree-item')
      .contains(collectionName)
      .click()
    cy.url().should('contain', 'Keylogger')
    cy.get('.DocumentListItem').should('have.length', 1)
  })

  it('refreshes search when the Search button is hit twice', function() {
    cy.visit('/')
    cy.get('.LoginAsAnonymous-Btn').click()
    cy.contains('Indexes')
    cy.visit(`/#/data/${indexName}/${collectionName}`)
    cy.contains(`${collectionName}`)
    cy.get('.QuickFilter-optionBtn').click()
    cy.get('.BasicFilter-query input[placeholder=Attribute]').type('job')
    cy.get('.BasicFilter-query input[placeholder=Value]').type('Blockchain')
    cy.get('.BasicFilter-submitBtn').click()
    cy.get('.DocumentListItem').should('have.length', 1)

    cy.request('POST', `${kuzzleUrl}/${indexName}/${collectionName}/_create`, {
      firstName: 'Adrien',
      lastName: 'Maret',
      job: 'Blockchain Keylogger as a Service'
    })
    cy.wait(1500)

    cy.get('.BasicFilter-submitBtn').click()
    cy.get('.DocumentListItem').should('have.length', 2)
  })

  it('when the RESET button is hit, the search query is reset but not the list view type', function() {
    cy.request('POST', `${kuzzleUrl}/${indexName}/${collectionName}/_create`, {
      firstName: 'Adrien',
      lastName: 'Maret',
      job: 'Blockchain Keylogger as a Service'
    })

    cy.visit('/')
    cy.get('.LoginAsAnonymous-Btn').click()
    cy.contains('Indexes')
    cy.visit(`/#/data/${indexName}/${collectionName}`)
    cy.get('.QuickFilter-searchBar input').type('Keylogger', { delay: 60 })

    cy.url().should('contain', 'Keylogger')
    cy.get('.DocumentListItem').should('have.length', 1)

    cy.get('.ListViewButtons-btn[title~="boxes"]').click()
    cy.get('.DocumentList-boxes')
      .children()
      .should('have.class', 'DocumentBoxItem')
    cy.get('.DocumentBoxItem').should('have.length', 1)

    cy.get('.QuickFilter-resetBtn').click()

    cy.url().should('not.contain', 'Keylogger')
    cy.url().should('contain', 'listViewType=boxes')
    cy.get('.DocumentList-boxes')
      .children()
      .should('have.class', 'DocumentBoxItem')
    cy.get('.DocumentBoxItem').should('have.length', 2)

    cy.get('.QuickFilter-optionBtn').click()
    cy.get('.BasicFilter-query input[placeholder=Attribute]').type('job')
    cy.get('.BasicFilter-query input[placeholder=Value]').type('Keylogger')
    cy.get('.BasicFilter-submitBtn').click()
    cy.get('.DocumentBoxItem').should('have.length', 1)

    cy.get('.BasicFilter-resetBtn').click()
    cy.url().should('not.contain', 'Keylogger')
    cy.url().should('contain', 'listViewType=boxes')
    cy.get('.DocumentList-boxes')
      .children()
      .should('have.class', 'DocumentBoxItem')
    cy.get('.DocumentBoxItem').should('have.length', 2)
  })
})
<commit_msg>MOAR keystroke timeout for Travis<commit_after>describe('Search', function() {
  const kuzzleUrl = 'http://localhost:7512'
  const indexName = 'testindex'
  const collectionName = 'testcollection'

  beforeEach(() => {
    // reset database and setup
    cy.request('POST', `${kuzzleUrl}/admin/_resetDatabase`)
    cy.request('POST', `${kuzzleUrl}/${indexName}/_create`)
    cy.request('PUT', `${kuzzleUrl}/${indexName}/${collectionName}`)
    cy.request('POST', `${kuzzleUrl}/${indexName}/${collectionName}/_create`, {
      firstName: 'Luca',
      lastName: 'Marchesini',
      job: 'Blockchain as a Service'
    })

    // create environment
    const validEnvName = 'valid'
    localStorage.setItem(
      'environments',
      JSON.stringify({
        [validEnvName]: {
          name: validEnvName,
          color: '#002835',
          host: 'localhost',
          ssl: false,
          port: 7512,
          token: null
        }
      })
    )
  })

  it('perists the Quick Search query in the URL', function() {
    cy.request('POST', `${kuzzleUrl}/${indexName}/${collectionName}/_create`, {
      firstName: 'Adrien',
      lastName: 'Maret',
      job: 'Blockchain Keylogger as a Service'
    })
    cy.visit('/')
    cy.get('.LoginAsAnonymous-Btn').click()
    cy.contains('Indexes')
    cy.visit(`/#/data/${indexName}/${collectionName}`)
    cy.get('.QuickFilter-searchBar input').type('Keylogger', { delay: 60 })
    cy.url().should('contain', 'quick=Keylogger')
    cy.url().should('contain', 'active=quick')
  })

  it('persists the Basic Search query in the URL', function() {
    cy.request('POST', `${kuzzleUrl}/${indexName}/${collectionName}/_create`, {
      firstName: 'Adrien',
      lastName: 'Maret',
      job: 'Blockchain Keylogger as a Service'
    })
    cy.visit('/')
    cy.get('.LoginAsAnonymous-Btn').click()
    cy.contains('Indexes')
    cy.visit(`/#/data/${indexName}/${collectionName}`)
    cy.get('.QuickFilter-optionBtn').click()
    cy.get('.BasicFilter-query input[placeholder=Attribute]').type('job')
    cy.get('.BasicFilter-query input[placeholder=Value]').type('Blockchain')
    cy.get('.BasicFilter-submitBtn').click()
    cy.url().should('contain', 'active=basic')
    cy.url().should('contain', 'attribute')
    cy.url().should('contain', 'job')
    cy.url().should('contain', 'match')
    cy.url().should('contain', 'Blockchain')
  })

  it('remembers the Quick Search query across collections', function() {
    cy.request('POST', `${kuzzleUrl}/${indexName}/${collectionName}/_create`, {
      firstName: 'Adrien',
      lastName: 'Maret',
      job: 'Blockchain Keylogger as a Service'
    })

    cy.request('PUT', `${kuzzleUrl}/${indexName}/anothercollection`)
    cy.request('POST', `${kuzzleUrl}/${indexName}/anothercollection/_create`, {
      firstName: 'Nicolas',
      lastName: 'Juelle',
      job: 'CSS Level: Expert !important'
    })
    cy.request('POST', `${kuzzleUrl}/${indexName}/anothercollection/_create`, {
      firstName: 'Alexandre',
      lastName: 'Bouthinon',
      job: 'From scratch All the Things!'
    })

    cy.visit('/')
    cy.get('.LoginAsAnonymous-Btn').click()
    cy.contains('Indexes')
    cy.visit(`/#/data/${indexName}/${collectionName}`)
    cy.get('.QuickFilter-searchBar input').type('Keylogger', { delay: 250 })
    cy.wait(250)
    cy.get('.Treeview-root .tree-item')
      .contains('anothercollection')
      .click()
    cy.url().should('not.contain', 'Keylogger')
    cy.get('.DocumentListItem').should('have.length', 2)

    cy.get('.Treeview-root .tree-item')
      .contains(collectionName)
      .click()
    cy.url().should('contain', 'Keylogger')
    cy.get('.DocumentListItem').should('have.length', 1)
  })

  it('remembers the Basic Search query across collections', function() {
    cy.request('POST', `${kuzzleUrl}/${indexName}/${collectionName}/_create`, {
      firstName: 'Adrien',
      lastName: 'Maret',
      job: 'Blockchain Keylogger as a Service'
    })

    cy.request('PUT', `${kuzzleUrl}/${indexName}/anothercollection`)
    cy.request('POST', `${kuzzleUrl}/${indexName}/anothercollection/_create`, {
      firstName: 'Nicolas',
      lastName: 'Juelle',
      job: 'CSS Level: Expert !important'
    })
    cy.request('POST', `${kuzzleUrl}/${indexName}/anothercollection/_create`, {
      firstName: 'Alexandre',
      lastName: 'Bouthinon',
      job: 'From scratch All the Things!'
    })

    cy.visit('/')
    cy.get('.LoginAsAnonymous-Btn').click()
    cy.contains('Indexes')
    cy.visit(`/#/data/${indexName}/${collectionName}`)

    cy.get('.QuickFilter-optionBtn').click()
    cy.get('.BasicFilter-query input[placeholder=Attribute]').type('job')
    cy.get('.BasicFilter-query input[placeholder=Value]').type('Keylogger')
    cy.get('.BasicFilter-submitBtn').click()
    cy.get('.DocumentListItem').should('have.length', 1)

    cy.get('.Treeview-root .tree-item')
      .contains('anothercollection')
      .click()
    cy.url().should('not.contain', 'Keylogger')
    cy.get('.DocumentListItem').should('have.length', 2)

    cy.get('.Treeview-root .tree-item')
      .contains(collectionName)
      .click()
    cy.url().should('contain', 'Keylogger')
    cy.get('.DocumentListItem').should('have.length', 1)
  })

  it('refreshes search when the Search button is hit twice', function() {
    cy.visit('/')
    cy.get('.LoginAsAnonymous-Btn').click()
    cy.contains('Indexes')
    cy.visit(`/#/data/${indexName}/${collectionName}`)
    cy.contains(`${collectionName}`)
    cy.get('.QuickFilter-optionBtn').click()
    cy.get('.BasicFilter-query input[placeholder=Attribute]').type('job')
    cy.get('.BasicFilter-query input[placeholder=Value]').type('Blockchain')
    cy.get('.BasicFilter-submitBtn').click()
    cy.get('.DocumentListItem').should('have.length', 1)

    cy.request('POST', `${kuzzleUrl}/${indexName}/${collectionName}/_create`, {
      firstName: 'Adrien',
      lastName: 'Maret',
      job: 'Blockchain Keylogger as a Service'
    })
    cy.wait(1500)

    cy.get('.BasicFilter-submitBtn').click()
    cy.get('.DocumentListItem').should('have.length', 2)
  })

  it('when the RESET button is hit, the search query is reset but not the list view type', function() {
    cy.request('POST', `${kuzzleUrl}/${indexName}/${collectionName}/_create`, {
      firstName: 'Adrien',
      lastName: 'Maret',
      job: 'Blockchain Keylogger as a Service'
    })

    cy.visit('/')
    cy.get('.LoginAsAnonymous-Btn').click()
    cy.contains('Indexes')
    cy.visit(`/#/data/${indexName}/${collectionName}`)
    cy.get('.QuickFilter-searchBar input').type('Keylogger', { delay: 60 })

    cy.url().should('contain', 'Keylogger')
    cy.get('.DocumentListItem').should('have.length', 1)

    cy.get('.ListViewButtons-btn[title~="boxes"]').click()
    cy.get('.DocumentList-boxes')
      .children()
      .should('have.class', 'DocumentBoxItem')
    cy.get('.DocumentBoxItem').should('have.length', 1)

    cy.get('.QuickFilter-resetBtn').click()

    cy.url().should('not.contain', 'Keylogger')
    cy.url().should('contain', 'listViewType=boxes')
    cy.get('.DocumentList-boxes')
      .children()
      .should('have.class', 'DocumentBoxItem')
    cy.get('.DocumentBoxItem').should('have.length', 2)

    cy.get('.QuickFilter-optionBtn').click()
    cy.get('.BasicFilter-query input[placeholder=Attribute]').type('job')
    cy.get('.BasicFilter-query input[placeholder=Value]').type('Keylogger')
    cy.get('.BasicFilter-submitBtn').click()
    cy.get('.DocumentBoxItem').should('have.length', 1)

    cy.get('.BasicFilter-resetBtn').click()
    cy.url().should('not.contain', 'Keylogger')
    cy.url().should('contain', 'listViewType=boxes')
    cy.get('.DocumentList-boxes')
      .children()
      .should('have.class', 'DocumentBoxItem')
    cy.get('.DocumentBoxItem').should('have.length', 2)
  })
})
<|endoftext|>


<commit_before>const Rx = require(`rx`)
const test = require(`tape`)
const Yolk = require(`yolk`)
const renderInDoc = require(`../helpers/renderInDoc`)

test(`CreateCustomComponent: a component that has livecycle hooks`, t => {
  t.plan(3)
  t.timeoutAfter(100)

  class CustomOnlyMount extends Yolk.CustomComponent {
    onMount (props, node) {
      const className = props.className.join(` `)
      node.setAttribute(`class`, className)
    }

    onUpdate (props, node) {
      const className = props.className.join(` `)
      node.setAttribute(`class`, className)
    }

    onUnmount () {
      t.pass(`custom component unmounts`)
    }
  }

  const names = new Rx.BehaviorSubject([`a`, `b`, `c`, `d`])

  const instance = <CustomOnlyMount className={names}>
</CustomOnlyMount>
  const [node, cleanup] = renderInDoc(instance)

  t.equal(node.tagName, `P`)
  t.equal(node.className, `a b c d`)

  names.onNext([`e`, `ee`, `eee`, `eeee`])

  t.equal(node.className, `e ee eee eeee`)

  Yolk.render(
, node)

  cleanup()
})

test(`CreateCustomComponent: uses a div if no child is passed in`, t => {
  t.plan(2)
  t.timeoutAfter(100)

  class CC extends Yolk.CustomComponent {}
  const [node, cleanup] = renderInDoc(<CC />)

  t.equal(node.tagName, `DIV`)

  const [node2, cleanup2] = renderInDoc(<CC>
</CC>)

  t.equal(node2.tagName, `P`)

  cleanup()
  cleanup2()
})

test(`CreateCustomComponent: should raise when there is more than one child`, t => {
  t.plan(6)
  t.timeoutAfter(100)

  class CC extends Yolk.CustomComponent {}

  t.throws(() => <CC>

</CC>)
  t.throws(() => <CC>

</CC>)
  t.doesNotThrow(() => <CC>
</CC>)
  t.doesNotThrow(() => <CC>

</CC>)
  t.doesNotThrow(() => <CC>

</CC>)
  t.doesNotThrow(() => <CC />)
})

test(`CreateCustomComponent: node is already inserted into the DOM with onMount`, t => {
  t.plan(1)
  t.timeoutAfter(2000)

  class CC extends Yolk.CustomComponent {
    onMount (__props, node) {
      t.ok(node.parentNode)
    }
  }

  const cleanup = renderInDoc(<CC />)[1]

  cleanup()
})

test(`CreateCustomComponent: node is already insert into the DOM even after the original load`, t => {
  t.plan(1)
  t.timeoutAfter(2000)

  class CC extends Yolk.CustomComponent {
    onMount (__props, node) {
      t.ok(node.parentNode)
    }
  }

  const child = new Rx.BehaviorSubject(
)

  const cleanup = renderInDoc(
{child}
)[1]

  setTimeout(function () {
    child.onNext(<CC />)
    cleanup()
  }, 0)
})

test(`CreateCustomComponent: extending the class with .extend`, t => {
  t.plan(3)
  t.timeoutAfter(2000)

  const CC = Yolk.CustomComponent.extend({
    onMount () {
      t.pass()
    },

    onUpdate () {
      t.pass()
    },

    onUnmount () {
      t.pass()
    },
  })

  const subject = new Rx.BehaviorSubject(1)

  // call onMount
  const [node, cleanup] = renderInDoc(<CC someProp={subject} />)

  // call onUpdate
  subject.onNext(2)

  // class onUnmount
  Yolk.render(
, node.parentNode)

  cleanup()
})
<commit_msg>Fix linter error :neckbeard:<commit_after>const Rx = require(`rx`)
const test = require(`tape`)
const Yolk = require(`yolk`)
const renderInDoc = require(`../helpers/renderInDoc`)

test(`CreateCustomComponent: a component that has livecycle hooks`, t => {
  t.plan(3)
  t.timeoutAfter(100)

  class CustomOnlyMount extends Yolk.CustomComponent {
    onMount (props, node) {
      const className = props.className.join(` `)
      node.setAttribute(`class`, className)
    }

    onUpdate (props, node) {
      const className = props.className.join(` `)
      node.setAttribute(`class`, className)
    }

    onUnmount () {
      t.pass(`custom component unmounts`)
    }
  }

  const names = new Rx.BehaviorSubject([`a`, `b`, `c`, `d`])

  const instance = <CustomOnlyMount className={names}>
</CustomOnlyMount>
  const [node, cleanup] = renderInDoc(instance)

  t.equal(node.tagName, `P`)
  t.equal(node.className, `a b c d`)

  names.onNext([`e`, `ee`, `eee`, `eeee`])

  t.equal(node.className, `e ee eee eeee`)

  Yolk.render(
, node)

  cleanup()
})

test(`CreateCustomComponent: uses a div if no child is passed in`, t => {
  t.plan(2)
  t.timeoutAfter(100)

  class CC extends Yolk.CustomComponent {}
  const [node, cleanup] = renderInDoc(<CC />)

  t.equal(node.tagName, `DIV`)

  const [node2, cleanup2] = renderInDoc(<CC>
</CC>)

  t.equal(node2.tagName, `P`)

  cleanup()
  cleanup2()
})

test(`CreateCustomComponent: should raise when there is more than one child`, t => {
  t.plan(6)
  t.timeoutAfter(100)

  class CC extends Yolk.CustomComponent {}

  t.throws(() => <CC>

</CC>)
  t.throws(() => <CC>

</CC>)
  t.doesNotThrow(() => <CC>
</CC>)
  t.doesNotThrow(() => <CC>

</CC>)
  t.doesNotThrow(() => <CC>

</CC>)
  t.doesNotThrow(() => <CC />)
})

test(`CreateCustomComponent: node is already inserted into the DOM with onMount`, t => {
  t.plan(1)
  t.timeoutAfter(2000)

  class CC extends Yolk.CustomComponent {
    onMount (__props, node) {
      t.ok(node.parentNode)
    }
  }

  const cleanup = renderInDoc(<CC />)[1]

  cleanup()
})

test(`CreateCustomComponent: node is already insert into the DOM even after the original load`, t => {
  t.plan(1)
  t.timeoutAfter(2000)

  class CC extends Yolk.CustomComponent {
    onMount (__props, node) {
      t.ok(node.parentNode)
    }
  }

  const child = new Rx.BehaviorSubject(
)

  const cleanup = renderInDoc(
{child}
)[1]

  setTimeout(() => {
    child.onNext(<CC />)
    cleanup()
  }, 0)
})

test(`CreateCustomComponent: extending the class with .extend`, t => {
  t.plan(3)
  t.timeoutAfter(2000)

  const CC = Yolk.CustomComponent.extend({
    onMount () {
      t.pass()
    },

    onUpdate () {
      t.pass()
    },

    onUnmount () {
      t.pass()
    },
  })

  const subject = new Rx.BehaviorSubject(1)

  // call onMount
  const [node, cleanup] = renderInDoc(<CC someProp={subject} />)

  // call onUpdate
  subject.onNext(2)

  // class onUnmount
  Yolk.render(
, node.parentNode)

  cleanup()
})
<|endoftext|>


<commit_before>/**
 * Created by Gabriel on 17/05/2017.
 */
'use strict';

/* The basic roman numerals alphabet, represented as a dictionary
 */
const romanNumeralsDict = {
  1: 'I',
  5: 'V',
  10: 'X',
  50: 'L',
  100: 'C',
  500: 'D',
  1000: 'M',
};

/**
 * Decomposes a number in base 10 representation
 * @param num - The number to decompose
 * @returns {Array.<*>} The decomposition in base 10 ordered by increasing number of powers of ten
 */
const getBase10Factors = function (num) {
  let base10Factors = [];
  for (let i = 3; i >= 0; i--) {
    let power = Math.pow(10, i);
    let coeff = Math.floor(num / power);
    base10Factors.push(coeff * power);
    num = num - coeff * power;
  }
  return base10Factors.reverse();
};

/**
 * Mapping function used to convert a number in roman numeral.
 * @param num - The number being mapped
 * @param index - The index of the element being mapped
 * @returns {string} The corresponding roman numeral
 */
const mapping = function (num, index) {
  let ten         = Math.pow(10, index);
  let lowerBound  = ten;
  let middleBound = 5 * ten;
  let upperBound  = 10 * ten;
  let str         = '';

  let tenCount = Math.floor(num / ten);
  // Test if the input number is 1, 5, 10, 50, 100, 500 or 1000, if so, retrieves the value directly from
  // the dictionnary
  if (num === ten || num === 5 * ten || num === 10 * ten) {
    str = romanNumeralsDict[num];
  } else if (num > ten && num < 4 * ten) {
    for (let i = 0; i < tenCount; i++) {
      str += romanNumeralsDict[lowerBound];
    }
  } else if (num >= 4 * ten && num < 5 * ten) {
    str = romanNumeralsDict[lowerBound] + romanNumeralsDict[middleBound];
  } else if (num > 5 * ten && num < 9 * ten) {
    str             = romanNumeralsDict[middleBound];
    let middleCount = Math.floor((num - middleBound) / ten);
    for (let i = 0; i < middleCount; i++) {
      str += romanNumeralsDict[lowerBound];
    }
  } else if (num >= 9 * ten) {
    str = romanNumeralsDict[lowerBound] + romanNumeralsDict[upperBound];
  }
  return str;
};

/**
 * Converts a number in roman numeral.
 * @param num - The number to convert
 * @returns {string} The roman numeral
 */
export function intToRoman(num) {
  let base10Factors = getBase10Factors(num);
  return base10Factors.map(mapping).reverse().join('');
}

//console.log(intToRoman(process.argv[2]));

/*
 // Testing part with Node and an input csv file
 const fs       = require('fs');
 const readline = require('readline');
 const fstream  = fs.createReadStream('roman-numerals__test.csv');
 const rl       = readline.createInterface({
 input: fstream,
 });

 let testCounter     = 0;
 let successfulTests = 0;

 rl.on('line', function (line) {
 let tokens        = line.split(',');
 let int           = parseInt(tokens[0]);
 let romanFromFile = tokens[1];
 let roman         = intToRoman(int);
 if (romanFromFile === roman) {
 console.log(`Testing ${int}. Expected ${romanFromFile}. Result ${roman}. \u2713`);
 successfulTests++;
 }
 testCounter++;
 });

 rl.on('close', function () {
 console.log('Nothing more to read');
 console.log(`Tests passed: ${successfulTests}/${testCounter}`);
 }); */<commit_msg>Removing ES6 export/import<commit_after>/**
 * Created by Gabriel on 17/05/2017.
 */
'use strict';

/* The basic roman numerals alphabet, represented as a dictionary
 */
const romanNumeralsDict = {
  1: 'I',
  5: 'V',
  10: 'X',
  50: 'L',
  100: 'C',
  500: 'D',
  1000: 'M',
};

/**
 * Decomposes a number in base 10 representation
 * @param num - The number to decompose
 * @returns {Array.<*>} The decomposition in base 10 ordered by increasing number of powers of ten
 */
const getBase10Factors = function (num) {
  let base10Factors = [];
  for (let i = 3; i >= 0; i--) {
    let power = Math.pow(10, i);
    let coeff = Math.floor(num / power);
    base10Factors.push(coeff * power);
    num = num - coeff * power;
  }
  return base10Factors.reverse();
};

/**
 * Mapping function used to convert a number in roman numeral.
 * @param num - The number being mapped
 * @param index - The index of the element being mapped
 * @returns {string} The corresponding roman numeral
 */
const mapping = function (num, index) {
  let ten = Math.pow(10, index);
  let lowerBound  = ten;
  let middleBound = 5 * ten;
  let upperBound  = 10 * ten;
  let str         = '';

  let tenCount = Math.floor(num / ten);
  // Test if the input number is 1, 5, 10, 50, 100, 500 or 1000, if so, retrieves the value directly from
  // the dictionnary
  if (num === ten || num === 5 * ten || num === 10 * ten) {
    str = romanNumeralsDict[num];
  } else if (num > ten && num < 4 * ten) {
    for (let i = 0; i < tenCount; i++) {
      str += romanNumeralsDict[lowerBound];
    }
  } else if (num >= 4 * ten && num < 5 * ten) {
    str = romanNumeralsDict[lowerBound] + romanNumeralsDict[middleBound];
  } else if (num > 5 * ten && num < 9 * ten) {
    str             = romanNumeralsDict[middleBound];
    let middleCount = Math.floor((num - middleBound) / ten);
    for (let i = 0; i < middleCount; i++) {
      str += romanNumeralsDict[lowerBound];
    }
  } else if (num >= 9 * ten) {
    str = romanNumeralsDict[lowerBound] + romanNumeralsDict[upperBound];
  }
  return str;
};

/**
 * Converts a number in roman numeral.
 * @param num - The number to convert
 * @returns {string} The roman numeral
 */
const intToRoman = function (num) {
  let base10Factors = getBase10Factors(num);
  return base10Factors.map(mapping).reverse().join('');
};<|endoftext|>


<commit_before>/* Snake.js

	Snake (player) class.
*/

(function(sys) {

"use strict";

/* Constructor for Snake object.
	context - 2D canvas context.
	board - Game board object.
	settings - Settings for snake object.
*/
function Snake(context, board, settings) {
	// Default parameters
	if ((context instanceof CanvasRenderingContext2D) === false) {
		throw new sys.c.GameError(
			"Parameter 'context' must be a valid 2D canvas context.");
	}
	else if ((board instanceof sys.c.Board) === false) {
		throw new sys.c.GameError(
			"Parameter 'board' must be a valid game board instance.");
	}

	/*
	 * PRIVATE VARIABLES
	*/

	// Reference to self.
	var mSelf = this,

	// 2D canvas context.
	mContext = context,

	// Reference to game board object.
	mBoard = board,

	// Snake joint array (chain of slots).
	mJoints = [],

	// Head joint.
	mHead = null,

	// Tail joint.
	mTail = null,

	// Snake width.
	mWidth = mWidth = typeof settings.width === "number" ?
		settings.width : mBoard.getSlotSize().width,

	// Starting length (number of joints).
	mStartLength = -1,

	// Starting column for the head.
	mStartCol = -1,

	// Starting row for the head.
	mStartRow = -1,

	/* Starting direction for the snake.
		{
			axis: "x" or "y", // Axis of travel.
			incr: 1 or -1 // 1 for right or down, -1 for left or up.
		}
	*/
	mStartDirection = {
		axis: "x",
		incr: 1
	},

	// Current direction for the snake head. Same structure as mStartDirection.
	mHeadDirection = null,

	// Current direction for the snake tail. Same structure as mStartDirection.
	mTailDirection = null;

	/*
	 * PUBLIC VARIABLES
	*/

	/*
	 * PRIVILEGED FUNCTIONS
	*/

	/* Initialize the snake.
	*/
	this.init = function() {
		var col = mStartCol,
			row = mStartRow,
			lastJoint = null,
			currJoint, i;

		// Reset joints array
		clearJoints();

		// Create and connect joints from head to tail
		for (i=0; i<mStartLength; i++) {
			// Create and connect the joint
			currJoint = new sys.c.Joint(lastJoint);
			currJoint.setSlot(mBoard.getSlot(col, row));
			mJoints.push(currJoint);

			// Store current joint as 'previous' in last joint created
			if (lastJoint !== null) {
				lastJoint.setPrev(currJoint);
			}

			// Store current joint for next iteration
			lastJoint = currJoint;

			// Move to the next slot location
			if (mStartDirection.axis === "x") {
				col += mStartDirection.incr;
			}
			else {
				row += mStartDirection.incr;
			}

	/* Returns the head joint travel direction data for the next game step.
	*/
	this.getDirection = function() {
		return sys.u.deepCopy(mHeadDirection);
	};

	/* Sets the head joint travel direction data for the next game step.
		direction - Travel direction string ("left", "right", "up", or "down").
	*/
	this.setDirection = function(direction) {
		mHeadDirection = Snake.prototype.parseDirection(direction);
	};
		}

		// Store head and tail
		mHead = mJoints[0];
		mTail = lastJoint;
	};

	/*
	 * PRIVATE FUNCTIONS
	*/

	function clearJoints() {
		for (var i=0, l=mJoints.length; i<l; i++) {
			mJoints.pop();
		}
		mJoints = [];
	}

	*/
		}

	}

	// Initializer
	(function() {
		var startLength = settings.startLength,
			startCol = settings.startCol,
			startRow = settings.startRow;

		// Store start length
		if (typeof startLength === "number") {
			mStartLength = startLength > 0 ?
				parseInt(startLength, 10) : 5;
		}

		// Store start column
		if (typeof startCol === "number") {
			mStartCol = (startCol > -1 && startCol < mBoard.getColumns()) ?
				parseInt(startCol, 10) : 12;
		}

		// Store start row
		if (typeof startRow === "number") {
			mStartRow = (startRow > -1 && startRow < mBoard.getRows()) ?
				parseInt(startRow, 10) : 18;
		}

		// Set start, current head, and current tail directions
		mStartDirection = Snake.prototype.parseDirection(
			settings.startDirection || "right");
		mHeadDirection = sys.u.deepCopy(mStartDirection);
		mTailDirection = sys.u.deepCopy(mStartDirection);
	})();
}

/*
 * STATIC FUNCTIONS
*/

Snake.prototype = {
	/* Converts a travel direction string to a travel direction data object.
		direction - Travel direction string ("left", "right", "up", or "down").

		Returns the converted travel direction data object, or throws an error.
	*/
	parseDirection: function(direction) {
		var obj = null;

		if (typeof direction === "string") {
			// Convert string
			direction = direction.toLowerCase();

			switch (direction) {
				case "left":
				obj = { axis: "x", incr: 1 };
				break;

				case "right":
				obj = { axis: "x", incr: -1 };
				break;

				case "up":
				obj = { axis: "y", incr: 1 };
				break;

				case "down":
				obj = { axis: "y", incr: -1 };
				break;

			}
		}
		else if (typeof direction === "object" &&
			direction.axis !== undefined && direction.incr !== undefined) {
			// Copy data object
			obj = sys.u.deepCopy(direction);
		}

		if (obj === null) {
			throw new sys.c.GameError(
				"Invalid direction string (expected 'left', 'right', 'up', or " +
				"'down')");
		}

		return obj;
	}
};

/*
 * STATIC INITIALIZERS
*/

sys.c.Snake = Snake;

})(jsnake);
<commit_msg>Changed:<commit_after>/* Snake.js

	Snake (player) class.
*/

(function(sys) {

"use strict";

/* Constructor for Snake object.
	context - 2D canvas context.
	board - Game board object.
	settings - Settings for snake object.
*/
function Snake(context, board, settings) {
	// Default parameters
	if ((context instanceof CanvasRenderingContext2D) === false) {
		throw new sys.c.GameError(
			"Parameter 'context' must be a valid 2D canvas context.");
	}
	else if ((board instanceof sys.c.Board) === false) {
		throw new sys.c.GameError(
			"Parameter 'board' must be a valid game board instance.");
	}

	/*
	 * PRIVATE VARIABLES
	*/

	// Reference to self.
	var mSelf = this,

	// 2D canvas context.
	mContext = context,

	// Reference to game board object.
	mBoard = board,

	// Number of joints in the snake.
	mLength = 0,

	// Head joint.
	mHead = null,

	// Tail joint.
	mTail = null,

	// Snake width.
	mWidth = mWidth = typeof settings.width === "number" ?
		settings.width : mBoard.getSlotSize().width,

	// Starting length (number of joints).
	mStartLength = -1,

	// Starting column for the head.
	mStartCol = -1,

	// Starting row for the head.
	mStartRow = -1,

	/* Starting direction for the snake.
		{
			axis: "x" or "y", // Axis of travel.
			incr: 1 or -1 // 1 for right or down, -1 for left or up.
		}
	*/
	mStartDirection = {
		axis: "x",
		incr: 1
	},

	// Current direction for the snake head. Same structure as mStartDirection.
	mHeadDirection = null,

	// Current direction for the snake tail. Same structure as mStartDirection.
	mTailDirection = null;

	/*
	 * PUBLIC VARIABLES
	*/

	/*
	 * PRIVILEGED FUNCTIONS
	*/

	/* Initialize the snake.
	*/
	this.init = function() {
		// Reset joints array
		clearJoints();

		// Create and connect joints from head to tail
		for (var i=0; i<mStartLength; i++) {
			mSelf.addJoint();
		}

		console.log(mSelf);
	};

	/* Returns the head joint travel direction data for the next game step.
	*/
	this.getDirection = function() {
		return sys.u.deepCopy(mHeadDirection);
	};

	/* Sets the head joint travel direction data for the next game step.
		direction - Travel direction string ("left", "right", "up", or "down").
	*/
	this.setDirection = function(direction) {
		mHeadDirection = Snake.prototype.parseDirection(direction);
	};

	/* Adds a joint to the tail.
		Returns the new joint.
	*/
	this.addJoint = function() {
		var newJoint = new sys.c.Joint();
		mLength++;

		if (mLength === 1) {
			// Set new joint as head
			newJoint
			mHead = newJoint;
			mHead.setSlot(mBoard.getSlot(mStartCol, mStartRow));
			mHead.setDirection(mStartDirection);
		}
		else {
			// Attach new joint to tail
			mTail.setPrev(newJoint);
			newJoint.setNext(mTail);
			newJoint.setDirection(mTail.getDirection());
		}

		// Set new joint as the tail
		mTail = newJoint;
		return mTail;
	};

	/*
	 * PRIVATE FUNCTIONS
	*/

	/* Clears all joints.
	*/
	function clearJoints() {
		eachJoint(function(joint) {
			joint.destroyJoint();
		});
	}

	/* Iterates over all joints from head to tail and performs a specified
		action on each iteration.

		action - Function to run on each iteration.
			joint - Current joint that the iterator is pointing to.
		reverse - True to iterate over joints from tail to head, omit otherwise.
	*/
	function eachJoint(action, reverse) {
		var curr = mHead,
			next = "getPrev",
			i;

		if (reverse === true) {
			curr = mTail;
			next = "getNext";
		}

		for (i=0; i<mLength; i++) {
			if (typeof action === "function") {
				action(curr);
			}

			curr = curr[next]();
		}
	}

	// Initializer
	(function() {
		var startLength = settings.startLength,
			startCol = settings.startCol,
			startRow = settings.startRow;

		// Store start length
		if (typeof startLength === "number") {
			mStartLength = startLength > 0 ?
				parseInt(startLength, 10) : 5;
		}

		// Store start column
		if (typeof startCol === "number") {
			mStartCol = (startCol > -1 && startCol < mBoard.getColumns()) ?
				parseInt(startCol, 10) : 12;
		}

		// Store start row
		if (typeof startRow === "number") {
			mStartRow = (startRow > -1 && startRow < mBoard.getRows()) ?
				parseInt(startRow, 10) : 18;
		}

		// Set start, current head, and current tail directions
		mStartDirection = Snake.prototype.parseDirection(
			settings.startDirection || "right");
		mHeadDirection = sys.u.deepCopy(mStartDirection);
		mTailDirection = sys.u.deepCopy(mStartDirection);
	})();
}

/*
 * STATIC FUNCTIONS
*/

Snake.prototype = {
	/* Converts a travel direction string to a travel direction data object.
		direction - Travel direction string ("left", "right", "up", or "down").

		Returns the converted travel direction data object, or throws an error.
	*/
	parseDirection: function(direction) {
		var obj = null;

		if (typeof direction === "string") {
			// Convert string
			direction = direction.toLowerCase();

			switch (direction) {
				case "left":
				obj = { axis: "x", incr: 1 };
				break;

				case "right":
				obj = { axis: "x", incr: -1 };
				break;

				case "up":
				obj = { axis: "y", incr: 1 };
				break;

				case "down":
				obj = { axis: "y", incr: -1 };
				break;

			}
		}
		else if (typeof direction === "object" &&
			direction.axis !== undefined && direction.incr !== undefined) {
			// Copy data object
			obj = sys.u.deepCopy(direction);
		}

		if (obj === null) {
			throw new sys.c.GameError(
				"Invalid direction string (expected 'left', 'right', 'up', or " +
				"'down')");
		}

		return obj;
	}
};

/*
 * STATIC INITIALIZERS
*/

sys.c.Snake = Snake;

})(jsnake);
<|endoftext|>


<commit_before>'use strict';

/*
 * Controller which handles the actual video call part of the app
 * Sets up the canvases, and sets up the correct data callbacks and such...
 */

angular.module('call', [])
.controller('CallCtrl', function ($scope, trackingFactory, recordingFactory, fileFactory,
                                  $ionicLoading, settingsFactory, $window, $document, callLogFactory
                                  , $sce, $stateParams, peerFactory, drawingFactory) {
    var saveCalls = settingsFactory.getSetting('saveCalls');

    var startDate = Date.now();

    var alreadyLeaving = false;

    var leave = function () {
        if (alreadyLeaving === false) {
            alreadyLeaving = true;
            peerFactory.sendDataToPeer({ type: 'otherPeerLeft' });
            trackingFactory.track.call.ended({
                with: $stateParams.user.phoneNumber,
                duration: Date.now() - startDate
            });

            drawingFactory.tearDownDrawingFactory();
            peerFactory.clearCallback('otherPeerLeft');
            peerFactory.clearCallback('toggleRemoteVideo');
            peerFactory.clearCallback('toggleVideoMute');

            if (saveCalls) {
                $ionicLoading.show({ templateUrl: 'templates/modals/save-video-loader.html' });
                recordingFactory.stopRecording()
                .then(function (results) {
                    var name = _.kebabCase($stateParams.user.displayName);
                    var fileNamePrefix = 'call-with-' + name + '-' + Date.now();
                    return Promise.all([
                        fileFactory.writeToFile({
                            fileName : fileNamePrefix + '.webm',
                            data     : results.videoBlob
                        }),
                        fileFactory.writeToFile({
                            fileName : fileNamePrefix + '-local.wav',
                            data     : results.localAudioBlob
                        })
                        //                    fileFactory.writeToFile({
                        //                        fileName : fileNamePrefix + '-remote.wav',
                        //                        data     : results.remoteAudioBlob
                        //                    })
                    ]);
                })
                .then(function (results) {
                    $ionicLoading.hide();
                    recordingFactory.clearRecordedData();
                    peerFactory.endCurrentCall();
                })
                .catch(function (error) {
                    $ionicLoading.hide();
                    recordingFactory.clearRecordedData();
                    callLogFactory.callSucceeded();
                    peerFactory.endCurrentCall();
                });
            } else {
                peerFactory.endCurrentCall();
            }

        }
    };

    var toggleVideoPlayingState = function (videoSelector) {
        var video = $document[0].querySelector(videoSelector);

        if (video.paused === true) {
            video.play();
        } else {
            video.pause();
        }
    };

    var toggleAudioPlayingState = function (audioSelector) {
        var audio = $document[0].querySelector(audioSelector);

        if (audio.paused === true) {
            audio.play();
        } else {
            audio.pause();
        }
    };

    var toggleRemoteVideoPlayingState = function () {
        toggleVideoPlayingState($scope.currentRemoteVideoLocation);
    };

    var toggleLocalVideoPlayingState = function () {
        toggleVideoPlayingState($scope.currentLocalVideoLocation);
    };

    var draggableVideo = new Draggabilly('#small-video');

    var localStreamSrc  = $sce.trustAsResourceUrl(peerFactory.getLocalStreamSrc());
    var remoteStreamSrc = $sce.trustAsResourceUrl(peerFactory.getRemoteStreamSrc());

    if (saveCalls) {
        recordingFactory.initializeRecordingVideo(document.getElementById('local-wrapper'));
        // TODO: Re-enable this once CrossWalk gets to chromium 49
        // https://crosswalk-project.org/documentation/downloads.php
        // recordingFactory.initializeRecordingAudio({ source: 'remote', audioStream: peerFactory.getRemoteStream() });
        recordingFactory.initializeRecordingAudio({ source: 'local',  audioStream: peerFactory.getLocalStream() });
    }

    draggableVideo.on('staticClick', function () {
        // TODO: Refactor this into something more elegant
        if ($scope.currentBigScreen === 'remote-big') {
            $scope.currentBigScreen = 'local-big';
            $scope.smallStreamSrc  = remoteStreamSrc;
            $scope.bigStreamSrc    = localStreamSrc;
            $scope.currentRemoteVideoLocation = '#small-video';
            $scope.currentLocalVideoLocation = '#big-video';
        } else if ($scope.currentBigScreen === 'local-big') {
            $scope.currentBigScreen = 'remote-big';
            $scope.smallStreamSrc  = localStreamSrc;
            $scope.bigStreamSrc    = remoteStreamSrc;
            $scope.currentRemoteVideoLocation = '#big-video';
            $scope.currentLocalVideoLocation = '#small-video';
        }
        $scope.$apply();
    });

    drawingFactory.setUpDataCallbacks();
    drawingFactory.setUpRemoteCanvas('remote-canvas', {});
    drawingFactory.setUpLocalCanvas('local-canvas', {});

    peerFactory.registerCallback('otherPeerLeft', function () {
        leave();
    });

    peerFactory.registerCallback('toggleVideoMute', function () {
        toggleAudioPlayingState('#call-audio');
    });

    peerFactory.registerCallback('toggleRemoteVideo', function () {
        $window.isRemoteVideoPaused = !$window.isRemoteVideoPaused;
        toggleRemoteVideoPlayingState();
    });

    $scope.currentBigScreen = 'remote-big';

    // I have no idea what is so special about this variable
    // but we have to declare it as a global so angular doesn't
    // override it
    $window.isRemoteVideoPaused = false;
    $scope.isOwnVideoPaused     = false;
    $scope.isOwnStreamMuted     = false;
    $scope.isArrowModeOn        = false;

    $scope.currentRemoteVideoLocation = '#big-video';
    $scope.currentLocalVideoLocation  = '#small-video';

    $scope.determinePauseButtonClass = function () {
        if ($scope.isOwnVideoPaused === true) {
            return 'ion-play';
        } else if ($scope.isOwnVideoPaused === false) {
            return 'ion-pause';
        }
    };

    $scope.determineArrowSwitchClass = function () {
        if ($scope.isArrowModeOn === true) {
            return 'ion-edit';
        } else if ($scope.isArrowModeOn === false) {
            return 'ion-arrow-swap';
        }
    };

    $scope.determineMuteButtonClass = function () {
        if ($scope.isOwnStreamMuted === true) {
            return 'ion-android-microphone-off';
        } else if ($scope.isOwnStreamMuted === false) {
            return 'ion-android-microphone';
        }
    };

    $scope.determineIfBigVideoIsAutoplay = function () {
        if (($scope.isOwnVideoPaused === true && $scope.currentLocalVideoLocation === '#big-video')
           || ($window.isRemoteVideoPaused === true && $scope.currentRemoteVideoLocation === '#big-video')) {
            return false;
        }

        return true;
    };

    $scope.determineIfSmallVideoIsAutoplay = function () {
        if (($scope.isOwnVideoPaused === true && $scope.currentLocalVideoLocation === '#small-video')
           || ($window.isRemoteVideoPaused === true && $scope.currentRemoteVideoLocation === '#small-video')) {
            return false;
        }

        return true;
    };

    $scope.toggleArrowMode = function () {
        $scope.isArrowModeOn = !$scope.isArrowModeOn;
        drawingFactory.toggleArrowDrawingMode();
    };

    $scope.toggleMute = function () {
        peerFactory.sendDataToPeer({ type: 'toggleVideoMute' });
        peerFactory.toggleAudioStream();
        $scope.isOwnStreamMuted = !$scope.isOwnStreamMuted;
    };

    $scope.togglePause = function () {
        $scope.isOwnVideoPaused = !$scope.isOwnVideoPaused;
        peerFactory.sendDataToPeer({ type: 'toggleRemoteVideo' });
        toggleLocalVideoPlayingState();
    };

    $scope.determineFullscreenCanvas = function () {
        return $scope.currentBigScreen;
    };

    $scope.clearActiveCanvas = function () {
        if ($scope.currentBigScreen === 'remote-big') {
            drawingFactory.clearRemoteCanvas();
        } else if ($scope.currentBigScreen === 'local-big') {
            drawingFactory.clearLocalCanvas();
        }
    };

    $scope.smallStreamSrc = localStreamSrc;
    $scope.bigStreamSrc   = remoteStreamSrc;
    $scope.remoteAudioSrc = remoteStreamSrc;

    $scope.leave = leave;

    if (saveCalls) {
        recordingFactory.startRecording();
    }

    $scope.$on('$ionicView.leave', function () {
        leave();
    });
});

<commit_msg>Add call succession promise to correct level<commit_after>'use strict';

/*
 * Controller which handles the actual video call part of the app
 * Sets up the canvases, and sets up the correct data callbacks and such...
 */

angular.module('call', [])
.controller('CallCtrl', function ($scope, trackingFactory, recordingFactory, fileFactory,
                                  $ionicLoading, settingsFactory, $window, $document, callLogFactory
                                  , $sce, $stateParams, peerFactory, drawingFactory) {
    var saveCalls = settingsFactory.getSetting('saveCalls');

    var startDate = Date.now();

    var alreadyLeaving = false;

    var leave = function () {
        if (alreadyLeaving === false) {
            alreadyLeaving = true;
            peerFactory.sendDataToPeer({ type: 'otherPeerLeft' });
            callLogFactory.callSucceeded();
            trackingFactory.track.call.ended({
                with: $stateParams.user.phoneNumber,
                duration: Date.now() - startDate
            });

            drawingFactory.tearDownDrawingFactory();
            peerFactory.clearCallback('otherPeerLeft');
            peerFactory.clearCallback('toggleRemoteVideo');
            peerFactory.clearCallback('toggleVideoMute');

            if (saveCalls) {
                $ionicLoading.show({ templateUrl: 'templates/modals/save-video-loader.html' });
                recordingFactory.stopRecording()
                .then(function (results) {
                    var name = _.kebabCase($stateParams.user.displayName);
                    var fileNamePrefix = 'call-with-' + name + '-' + Date.now();
                    return Promise.all([
                        fileFactory.writeToFile({
                            fileName : fileNamePrefix + '.webm',
                            data     : results.videoBlob
                        }),
                        fileFactory.writeToFile({
                            fileName : fileNamePrefix + '-local.wav',
                            data     : results.localAudioBlob
                        })
                        //                    fileFactory.writeToFile({
                        //                        fileName : fileNamePrefix + '-remote.wav',
                        //                        data     : results.remoteAudioBlob
                        //                    })
                    ]);
                })
                .then(function (results) {
                    $ionicLoading.hide();
                    recordingFactory.clearRecordedData();
                    peerFactory.endCurrentCall();
                })
                .catch(function (error) {
                    $ionicLoading.hide();
                    recordingFactory.clearRecordedData();
                    peerFactory.endCurrentCall();
                });
            } else {
                peerFactory.endCurrentCall();
            }

        }
    };

    var toggleVideoPlayingState = function (videoSelector) {
        var video = $document[0].querySelector(videoSelector);

        if (video.paused === true) {
            video.play();
        } else {
            video.pause();
        }
    };

    var toggleAudioPlayingState = function (audioSelector) {
        var audio = $document[0].querySelector(audioSelector);

        if (audio.paused === true) {
            audio.play();
        } else {
            audio.pause();
        }
    };

    var toggleRemoteVideoPlayingState = function () {
        toggleVideoPlayingState($scope.currentRemoteVideoLocation);
    };

    var toggleLocalVideoPlayingState = function () {
        toggleVideoPlayingState($scope.currentLocalVideoLocation);
    };

    var draggableVideo = new Draggabilly('#small-video');

    var localStreamSrc  = $sce.trustAsResourceUrl(peerFactory.getLocalStreamSrc());
    var remoteStreamSrc = $sce.trustAsResourceUrl(peerFactory.getRemoteStreamSrc());

    if (saveCalls) {
        recordingFactory.initializeRecordingVideo(document.getElementById('local-wrapper'));
        // TODO: Re-enable this once CrossWalk gets to chromium 49
        // https://crosswalk-project.org/documentation/downloads.php
        // recordingFactory.initializeRecordingAudio({ source: 'remote', audioStream: peerFactory.getRemoteStream() });
        recordingFactory.initializeRecordingAudio({ source: 'local',  audioStream: peerFactory.getLocalStream() });
    }

    draggableVideo.on('staticClick', function () {
        // TODO: Refactor this into something more elegant
        if ($scope.currentBigScreen === 'remote-big') {
            $scope.currentBigScreen = 'local-big';
            $scope.smallStreamSrc  = remoteStreamSrc;
            $scope.bigStreamSrc    = localStreamSrc;
            $scope.currentRemoteVideoLocation = '#small-video';
            $scope.currentLocalVideoLocation = '#big-video';
        } else if ($scope.currentBigScreen === 'local-big') {
            $scope.currentBigScreen = 'remote-big';
            $scope.smallStreamSrc  = localStreamSrc;
            $scope.bigStreamSrc    = remoteStreamSrc;
            $scope.currentRemoteVideoLocation = '#big-video';
            $scope.currentLocalVideoLocation = '#small-video';
        }
        $scope.$apply();
    });

    drawingFactory.setUpDataCallbacks();
    drawingFactory.setUpRemoteCanvas('remote-canvas', {});
    drawingFactory.setUpLocalCanvas('local-canvas', {});

    peerFactory.registerCallback('otherPeerLeft', function () {
        leave();
    });

    peerFactory.registerCallback('toggleVideoMute', function () {
        toggleAudioPlayingState('#call-audio');
    });

    peerFactory.registerCallback('toggleRemoteVideo', function () {
        $window.isRemoteVideoPaused = !$window.isRemoteVideoPaused;
        toggleRemoteVideoPlayingState();
    });

    $scope.currentBigScreen = 'remote-big';

    // I have no idea what is so special about this variable
    // but we have to declare it as a global so angular doesn't
    // override it
    $window.isRemoteVideoPaused = false;
    $scope.isOwnVideoPaused     = false;
    $scope.isOwnStreamMuted     = false;
    $scope.isArrowModeOn        = false;

    $scope.currentRemoteVideoLocation = '#big-video';
    $scope.currentLocalVideoLocation  = '#small-video';

    $scope.determinePauseButtonClass = function () {
        if ($scope.isOwnVideoPaused === true) {
            return 'ion-play';
        } else if ($scope.isOwnVideoPaused === false) {
            return 'ion-pause';
        }
    };

    $scope.determineArrowSwitchClass = function () {
        if ($scope.isArrowModeOn === true) {
            return 'ion-edit';
        } else if ($scope.isArrowModeOn === false) {
            return 'ion-arrow-swap';
        }
    };

    $scope.determineMuteButtonClass = function () {
        if ($scope.isOwnStreamMuted === true) {
            return 'ion-android-microphone-off';
        } else if ($scope.isOwnStreamMuted === false) {
            return 'ion-android-microphone';
        }
    };

    $scope.determineIfBigVideoIsAutoplay = function () {
        if (($scope.isOwnVideoPaused === true && $scope.currentLocalVideoLocation === '#big-video')
           || ($window.isRemoteVideoPaused === true && $scope.currentRemoteVideoLocation === '#big-video')) {
            return false;
        }

        return true;
    };

    $scope.determineIfSmallVideoIsAutoplay = function () {
        if (($scope.isOwnVideoPaused === true && $scope.currentLocalVideoLocation === '#small-video')
           || ($window.isRemoteVideoPaused === true && $scope.currentRemoteVideoLocation === '#small-video')) {
            return false;
        }

        return true;
    };

    $scope.toggleArrowMode = function () {
        $scope.isArrowModeOn = !$scope.isArrowModeOn;
        drawingFactory.toggleArrowDrawingMode();
    };

    $scope.toggleMute = function () {
        peerFactory.sendDataToPeer({ type: 'toggleVideoMute' });
        peerFactory.toggleAudioStream();
        $scope.isOwnStreamMuted = !$scope.isOwnStreamMuted;
    };

    $scope.togglePause = function () {
        $scope.isOwnVideoPaused = !$scope.isOwnVideoPaused;
        peerFactory.sendDataToPeer({ type: 'toggleRemoteVideo' });
        toggleLocalVideoPlayingState();
    };

    $scope.determineFullscreenCanvas = function () {
        return $scope.currentBigScreen;
    };

    $scope.clearActiveCanvas = function () {
        if ($scope.currentBigScreen === 'remote-big') {
            drawingFactory.clearRemoteCanvas();
        } else if ($scope.currentBigScreen === 'local-big') {
            drawingFactory.clearLocalCanvas();
        }
    };

    $scope.smallStreamSrc = localStreamSrc;
    $scope.bigStreamSrc   = remoteStreamSrc;
    $scope.remoteAudioSrc = remoteStreamSrc;

    $scope.leave = leave;

    if (saveCalls) {
        recordingFactory.startRecording();
    }

    $scope.$on('$ionicView.leave', function () {
        leave();
    });
});

<|endoftext|>


<commit_before>'use strict';

angular.module('core').service('Notification', Notification);

Notification.$inject = ['$http', 'NotifsService'];
function Notification($http, NotifsService) {
  this.notifCnt = 0;
  this.notifications = [];
  this.loadNotifs = function () {
    $http.get('/api/notifs/load', { ignoreLoadingBar: true })
      .then(res => {
        this.notifCnt = res.data.count || 0;
        this.notifications = res.data.notifs || 0;
      });
  };
  this.clearNotifs = function () {
    $http.get('/api/clearAll', { ignoreLoadingBar: true })
      .then(res => {
        this.notifCnt = 0;
        this.notifications = [];
      });
  };
  this.markReadNotifs = function () {
    $http.get('/api/markAllRead', { ignoreLoadingBar: true })
      .then(res => {
        this.notifications.forEach(function (notif) {
          notif.status = 1;
        });
      });
  };
  this.markReadNotif = function (notifId) {
    var ntf = _.find(this.notifications, function (item) { return item._id.toString() === notifId.toString(); });
    if (ntf) {
      ntf.status = 1;
      this.notifCnt -= 1;
    }
    let rs_notf = new NotifsService({ _id: notifId });
    rs_notf.status = 1;
    rs_notf.$save();
  };
  this.getData = function () { return { notifCnt: notifCnt, notifications: notifications }; };
  // return this;
}
<commit_msg>Commited from HaNhatLenh at Sun, Aug 20, 2017 11:24:12 AM<commit_after>'use strict';

angular.module('core').service('Notification', Notification);

Notification.$inject = ['$http', 'NotifsService'];
function Notification($http, NotifsService) {
  var notifCnt = 0;
  var notifications = [];
  this.loadNotifs = function () {
    $http.get('/api/notifs/load', { ignoreLoadingBar: true })
      .then(res => {
        notifCnt = res.data.count || 0;
        notifications = res.data.notifs || 0;
      });
  };
  this.clearNotifs = function () {
    $http.get('/api/clearAll', { ignoreLoadingBar: true })
      .then(res => {
        notifCnt = 0;
        notifications = [];
      });
  };
  this.markReadNotifs = function () {
    $http.get('/api/markAllRead', { ignoreLoadingBar: true })
      .then(res => {
        notifications.forEach(function (notif) {
          notif.status = 1;
        });
      });
  };
  this.markReadNotif = function (notifId) {
    var ntf = _.find(notifications, function (item) { return item._id.toString() === notifId.toString(); });
    if (ntf) {
      ntf.status = 1;
      notifCnt -= 1;
    }
    let rs_notf = new NotifsService({ _id: notifId });
    rs_notf.status = 1;
    rs_notf.$save();
  };
  this.getData = function () { return { notifCnt: notifCnt, notifications: notifications }; };
  // return this;
}
<|endoftext|>


<commit_before>
angular.module('umbraco')
.controller('DigitalMomentum.Videolizer.Search',
	function ($http, $scope, notificationsService, vimeoApi) {
			$scope.hideLabel = "true"; //Hides the modal Dialog label at the top of the page
			$scope.errorStr = null;
	$scope.model = {
		searchTerm: "",
		ytApi: $scope.dialogData.ytApi,
		ytChannelId: $scope.dialogData.ytChannelId,
		vimeoClientId: $scope.dialogData.vimeoClientId,
		vimeoClientSecret: $scope.dialogData.vimeoClientSecret,
		vimeoUserId: $scope.dialogData.vimeoUserId,
		searchType: $scope.dialogData.defaultSearchType
			}'
				'

	console.log($scope.model)

	$scope.results = {
		yt: [],
		vimeo: []
	}

	function init() {

		vimeoApi.init($scope.model.vimeoClientId, $scope.model.vimeoClientSecret , $scope.model.vimeoUserId);

		$scope.search(); //Run defaut search to get list of latest videos

		//Select the appropriate Default Radio
		//if ($scope.model.ytApi) {
		//	if ($scope.model.ytChannelId) {
		//		$scope.searchType = "ytChannel";
		//	} else {
		//		$scope.searchType = "ytAll";
		//	}

		//}
	}

	function searchYouTube(searchTerm) {

		var ApiUrl = 'https://www.googleapis.com/youtube/v3/search?part=snippet&key=' + $scope.dialogData.ytApi
		var hasASearch = false;

		var req = {
			method: 'GET',
			url: ApiUrl,
			headers: {
				'Content-Type': "json",

			},
			umbIgnoreErrors: true //Tell Umbraco to ignore the errors - http://issues.umbraco.org/issue/U4-5588
			//data: { test: 'test' }
		}

		if (searchTerm) {

			req.url += '&q=' + searchTerm;

			hasASearch = true;
		}

		if ($scope.model.searchType == "ytChannel") {
			req.url += "&channelId=" + $scope.model.ytChannelId
			if (searchTerm == "") {
				//We are getting the latest from our channel
				req.url += "&order=date";
			}
			hasASearch = true;
		}

		$http(req).then(function successCallback(response) {
			// this callback will be called asynchronously
			// when the response is available
			//console.log(response);
			$scope.results.yt = response.data.items;
		}, function errorCallback(response) {
			// called asynchronously if an error occurs
			// or server returns response with an error status.
			console.log("err", response);
			$scope.errorStr = "" + response.data.error.errors[0].reason + "" + " " + response.data.error.errors[0].message
			notificationsService.error("YouTube Search Error", response.data.error.errors[0].reason);

		});

	}

	$scope.search = function () {
		$scope.errorStr = null;
		console.log($scope.model.searchType)
		$scope.results.yt = [];
		$scope.results.vimeo = [];
		var hasASearch = false;
		var searchTerm = $scope.model.searchTerm;
		if ($scope.model.searchType == "ytChannel" || $scope.model.searchType == "ytAll") {
			searchYouTube(searchTerm);
			return;
		} else {
			vimeoApi.search(searchTerm, $scope.model.searchType, function (data) {
				$scope.results.vimeo = data;
			});
			return;
		}
	}

	$scope.selectVideo = function (video) {
		console.log(video);
		var videoInfo = {};
		if (video.kind == "Vimeo") {
			videoInfo.id = video.id;
			videoInfo.type = "Vimeo";
			videoInfo.url = "https://vimeo.com/" + video.id;
			videoInfo.embedUrl = "https://player.vimeo.com/video/" + video.id;
		} else {
			//YouTube
			videoInfo.id = video.id.videoId;
			videoInfo.type = "YouTube";
			videoInfo.url = "https://www.youtube.com/watch?v=" + video.id.videoId;
			videoInfo.embedUrl = "https://www.youtube.com/embed/" + video.id.videoId;
		}
		console.log(videoInfo);
		$scope.submit(videoInfo);
	}

	init();

	//Temp Code

});<commit_msg>Remove Accidental Chars<commit_after>
angular.module('umbraco')
.controller('DigitalMomentum.Videolizer.Search',
	function ($http, $scope, notificationsService, vimeoApi) {
			$scope.hideLabel = "true"; //Hides the modal Dialog label at the top of the page
			$scope.errorStr = null;
	$scope.model = {
		searchTerm: "",
		ytApi: $scope.dialogData.ytApi,
		ytChannelId: $scope.dialogData.ytChannelId,
		vimeoClientId: $scope.dialogData.vimeoClientId,
		vimeoClientSecret: $scope.dialogData.vimeoClientSecret,
		vimeoUserId: $scope.dialogData.vimeoUserId,
		searchType: $scope.dialogData.defaultSearchType
			}

	console.log($scope.model)

	$scope.results = {
		yt: [],
		vimeo: []
	}

	function init() {

		vimeoApi.init($scope.model.vimeoClientId, $scope.model.vimeoClientSecret , $scope.model.vimeoUserId);

		$scope.search(); //Run defaut search to get list of latest videos

		//Select the appropriate Default Radio
		//if ($scope.model.ytApi) {
		//	if ($scope.model.ytChannelId) {
		//		$scope.searchType = "ytChannel";
		//	} else {
		//		$scope.searchType = "ytAll";
		//	}

		//}
	}

	function searchYouTube(searchTerm) {

		var ApiUrl = 'https://www.googleapis.com/youtube/v3/search?part=snippet&key=' + $scope.dialogData.ytApi
		var hasASearch = false;

		var req = {
			method: 'GET',
			url: ApiUrl,
			headers: {
				'Content-Type': "json",

			},
			umbIgnoreErrors: true //Tell Umbraco to ignore the errors - http://issues.umbraco.org/issue/U4-5588
			//data: { test: 'test' }
		}

		if (searchTerm) {

			req.url += '&q=' + searchTerm;

			hasASearch = true;
		}

		if ($scope.model.searchType == "ytChannel") {
			req.url += "&channelId=" + $scope.model.ytChannelId
			if (searchTerm == "") {
				//We are getting the latest from our channel
				req.url += "&order=date";
			}
			hasASearch = true;
		}

		$http(req).then(function successCallback(response) {
			// this callback will be called asynchronously
			// when the response is available
			//console.log(response);
			$scope.results.yt = response.data.items;
		}, function errorCallback(response) {
			// called asynchronously if an error occurs
			// or server returns response with an error status.
			console.log("err", response);
			$scope.errorStr = "" + response.data.error.errors[0].reason + "" + " " + response.data.error.errors[0].message
			notificationsService.error("YouTube Search Error", response.data.error.errors[0].reason);

		});

	}

	$scope.search = function () {
		$scope.errorStr = null;
		console.log($scope.model.searchType)
		$scope.results.yt = [];
		$scope.results.vimeo = [];
		var hasASearch = false;
		var searchTerm = $scope.model.searchTerm;
		if ($scope.model.searchType == "ytChannel" || $scope.model.searchType == "ytAll") {
			searchYouTube(searchTerm);
			return;
		} else {
			vimeoApi.search(searchTerm, $scope.model.searchType, function (data) {
				$scope.results.vimeo = data;
			});
			return;
		}
	}

	$scope.selectVideo = function (video) {
		console.log(video);
		var videoInfo = {};
		if (video.kind == "Vimeo") {
			videoInfo.id = video.id;
			videoInfo.type = "Vimeo";
			videoInfo.url = "https://vimeo.com/" + video.id;
			videoInfo.embedUrl = "https://player.vimeo.com/video/" + video.id;
		} else {
			//YouTube
			videoInfo.id = video.id.videoId;
			videoInfo.type = "YouTube";
			videoInfo.url = "https://www.youtube.com/watch?v=" + video.id.videoId;
			videoInfo.embedUrl = "https://www.youtube.com/embed/" + video.id.videoId;
		}
		console.log(videoInfo);
		$scope.submit(videoInfo);
	}

	init();

	//Temp Code

});<|endoftext|>


<commit_before>// Global Marker Wrappers and Map
var globalMarkers = null;
var globalMap = null;
var markerCluster = null;

// Geographic bounds centered according to incident report locations
var geographicBounds = null;

// Initial map center coordinates
INITIAL_CENTER_LAT = 39.952;
INITIAL_CENTER_LONG = -75.195;
initial_coords = new google.maps.LatLng(INITIAL_CENTER_LAT, INITIAL_CENTER_LONG);

// Bounds for the Date Slider. End date is current date.
var BOUNDS_MIN;
var BOUNDS_MAX = new Date();

// Take a list of markers and a map, put them on the map, set the
// minimum date, and set the location bounds
function storeMarkerState(markers, map, minDate, bounds, oms) {
    globalMarkers = markers;
    globalMap = map;
    markerCluster = new MarkerClusterer(map, markers, {gridSize: 50, maxZoom: 15, minimumClusterSize: 15, imagePath: 'static/images/clusterer/m'});
    for (mw = 0; mw < globalMarkers.length; mw++)
    {
        (globalMarkers[mw]).setMap(globalMap);
        oms.addMarker(globalMarkers[mw]);

    }
    BOUNDS_MIN = minDate;
    geographicBounds = bounds;
    map.fitBounds(bounds);
}

// Use Google geocoder to update geolocation given an address through
// the address search box
function update_center() {
    geocoder = new google.maps.Geocoder();
    address = $("#address").val();
    if (geocoder) {
        geocoder.geocode( { 'address': address},
        function(results, status) {
            if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
                $('#address_error').modal('show');
            }
            else if (status != google.maps.GeocoderStatus.OK) {
                $('#geocode_error').modal('show');
            }
            else {
                globalMap.setCenter(results[0].geometry.location);
            }
            /*$('.close.icon').on('click', function() {
                $(this).parent().hide();
            });*/
        });
    }
}

// Heavily inspired by https://jsfiddle.net/mi3afzal/ogsvzacz/2/
// Adds a "geolocate" button to the map.
function addLocationButton(map) {
	var controlDiv = document.createElement('div');

	var firstChild = document.createElement('button');
	firstChild.style.backgroundColor = '#fff';
	firstChild.style.border = 'none';
	firstChild.style.outline = 'none';
	firstChild.style.width = '28px';
	firstChild.style.height = '28px';
	firstChild.style.borderRadius = '2px';
	firstChild.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
	firstChild.style.cursor = 'pointer';
	firstChild.style.marginRight = '10px';
	firstChild.style.padding = '0px';
	firstChild.title = 'Your Location';
	controlDiv.appendChild(firstChild);

	var secondChild = document.createElement('div');
	secondChild.style.margin = '5px';
	secondChild.style.width = '18px';
	secondChild.style.height = '18px';
	secondChild.style.backgroundImage = 'url(https://maps.gstatic.com/tactile/mylocation/mylocation-sprite-1x.png)';
	secondChild.style.backgroundSize = '180px 18px';
	secondChild.style.backgroundPosition = '0px 0px';
	secondChild.style.backgroundRepeat = 'no-repeat';
	secondChild.id = 'you_location_img';
	firstChild.appendChild(secondChild);

	google.maps.event.addListener(map, 'dragend', function() {
		$('#you_location_img').css('background-position', '0px 0px');
	});

	firstChild.addEventListener('click', function() {
		var imgX = '0';
		var animationInterval = setInterval(function(){
			if(imgX == '-18') imgX = '0';
			else imgX = '-18';
			$('#you_location_img').css('background-position', imgX+'px 0px');
		}, 500);
		if(navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position) {
				var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
				map.setCenter(latlng);
				clearInterval(animationInterval);
				$('#you_location_img').css('background-position', '-144px 0px');
			});
		}
		else{
			clearInterval(animationInterval);
			$('#you_location_img').css('background-position', '0px 0px');
		}
	});

	controlDiv.index = 1;
	map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);
}

function addCenterButton(map) {
    var centerDiv = document.createElement('div');

    var centerButton = document.createElement('button');
    centerButton.style.backgroundColor = '#fff';
    centerButton.style.border = 'none';
    centerButton.style.outline = 'none';
    centerButton.style.width = '28px';
    centerButton.style.height = '28px';
    centerButton.style.borderRadius = '2px';
    centerButton.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
    centerButton.style.cursor = 'pointer';
    centerButton.style.marginBottom = '10px';
    centerButton.style.marginRight = '10px';
    centerButton.style.padding = '0px';
    centerButton.style.textAlign = 'center';
    centerButton.innerHTML = '  ';
    centerButton.value = 'Reports Center';
    centerButton.title = 'Reports Center';
    centerButton.id = 'centerButton';
    centerDiv.appendChild(centerButton);

    centerButton.addEventListener('click', function() {
        map.fitBounds(geographicBounds);
    });
    centerDiv.index = 1;
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(centerDiv);
}

// Get address submit event
$(document).ready(function() {
    $('#addressForm').on('submit', function (event) {
        update_center();
        return false;
    });
});

function getNextDate(startDate) {
    startDate.setDate(startDate.getDate()+1);
    return startDate;
}

function initializeDateSlider() {
    $("#slider").dateRangeSlider({
        bounds: {
            min: BOUNDS_MIN,
            max: BOUNDS_MAX,
        },
        arrows: false,
        defaultValues: {
            min: BOUNDS_MIN,
            max: BOUNDS_MAX,
        },
    });
    $("#slider").bind("valuesChanged", function(e, data) {
        var beginYear = parseInt(String(data.values.min).substring(11, 15), 10);
        var beginDay = parseInt(String(data.values.min).substring(8, 10), 10);
        var endYear = parseInt(String(data.values.max).substring(11, 15), 10);
        var endDay = parseInt(String(data.values.max).substring(8, 10), 10);
        var beginMonth = 0;
        var endMonth = 0;
        monthObj = {
            "Jan": 0,
            "Feb": 1,
            "Mar": 2,
            "Apr": 3,
            "May": 4,
            "Jun": 5,
            "Jul": 6,
            "Aug": 7,
            "Sep": 8,
            "Oct": 9,
            "Nov": 10,
            "Dec": 11
        };
        beginMonth = monthObj[String(data.values.min).substring(4, 7)];
        endMonth = monthObj[String(data.values.max).substring(4, 7)];
        beginDate = new Date(beginYear, beginMonth, beginDay);
        endDate = getNextDate(new Date(endYear, endMonth, endDay));

        var markersDisplayedOnMap = [];
        for (mw = 0; mw < globalMarkers.length; mw++) {
            if ((globalMarkers[mw].incidentDate.getTime() < beginDate.getTime()) ||
                (globalMarkers[mw].incidentDate.getTime() >= endDate.getTime())) {
                globalMarkers[mw].setMap(null);
            }
            else
            {
                globalMarkers[mw].setMap(globalMap);
                markersDisplayedOnMap.push(globalMarkers[mw]);
            }
        }
        markerCluster.setMap(null);
        markerCluster.clearMarkers();
        markerCluster = new MarkerClusterer(map, markersDisplayedOnMap, {gridSize: 50, maxZoom: 15, minimumClusterSize: 15, imagePath: 'static/images/clusterer/m'});
    });
}

function filterMarkers(bounds) {
    var markersDisplayedOnMap = [];
    for (mw = 0; mw < globalMarkers.length; mw++) {
        if (bounds === null || bounds.contains(globalMarkers[mw].getPosition())) {
            globalMarkers[mw].setMap(globalMap);
            markersDisplayedOnMap.push(globalMarkers[mw]);
        } else {
            globalMarkers[mw].setMap(null);
        }
    }
    /*markerCluster.setMap(null);
    markerCluster.clearMarkers();
    markerCluster = new MarkerClusterer(map, markersDisplayedOnMap, {gridSize: 50, maxZoom: 15, minimumClusterSize: 15, imagePath: 'static/images/clusterer/m'});*/
    markerCluster.clearMarkers();
    markerCluster.addMarkers(markersDisplayedOnMap);
}
<commit_msg>Remove commented out code<commit_after>// Global Marker Wrappers and Map
var globalMarkers = null;
var globalMap = null;
var markerCluster = null;

// Geographic bounds centered according to incident report locations
var geographicBounds = null;

// Initial map center coordinates
INITIAL_CENTER_LAT = 39.952;
INITIAL_CENTER_LONG = -75.195;
initial_coords = new google.maps.LatLng(INITIAL_CENTER_LAT, INITIAL_CENTER_LONG);

// Bounds for the Date Slider. End date is current date.
var BOUNDS_MIN;
var BOUNDS_MAX = new Date();

// Take a list of markers and a map, put them on the map, set the
// minimum date, and set the location bounds
function storeMarkerState(markers, map, minDate, bounds, oms) {
    globalMarkers = markers;
    globalMap = map;
    markerCluster = new MarkerClusterer(map, markers, {gridSize: 50, maxZoom: 15, minimumClusterSize: 15, imagePath: 'static/images/clusterer/m'});
    for (mw = 0; mw < globalMarkers.length; mw++)
    {
        (globalMarkers[mw]).setMap(globalMap);
        oms.addMarker(globalMarkers[mw]);

    }
    BOUNDS_MIN = minDate;
    geographicBounds = bounds;
    map.fitBounds(bounds);
}

// Use Google geocoder to update geolocation given an address through
// the address search box
function update_center() {
    geocoder = new google.maps.Geocoder();
    address = $("#address").val();
    if (geocoder) {
        geocoder.geocode( { 'address': address},
        function(results, status) {
            if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
                $('#address_error').modal('show');
            }
            else if (status != google.maps.GeocoderStatus.OK) {
                $('#geocode_error').modal('show');
            }
            else {
                globalMap.setCenter(results[0].geometry.location);
            }
            /*$('.close.icon').on('click', function() {
                $(this).parent().hide();
            });*/
        });
    }
}

// Heavily inspired by https://jsfiddle.net/mi3afzal/ogsvzacz/2/
// Adds a "geolocate" button to the map.
function addLocationButton(map) {
	var controlDiv = document.createElement('div');

	var firstChild = document.createElement('button');
	firstChild.style.backgroundColor = '#fff';
	firstChild.style.border = 'none';
	firstChild.style.outline = 'none';
	firstChild.style.width = '28px';
	firstChild.style.height = '28px';
	firstChild.style.borderRadius = '2px';
	firstChild.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
	firstChild.style.cursor = 'pointer';
	firstChild.style.marginRight = '10px';
	firstChild.style.padding = '0px';
	firstChild.title = 'Your Location';
	controlDiv.appendChild(firstChild);

	var secondChild = document.createElement('div');
	secondChild.style.margin = '5px';
	secondChild.style.width = '18px';
	secondChild.style.height = '18px';
	secondChild.style.backgroundImage = 'url(https://maps.gstatic.com/tactile/mylocation/mylocation-sprite-1x.png)';
	secondChild.style.backgroundSize = '180px 18px';
	secondChild.style.backgroundPosition = '0px 0px';
	secondChild.style.backgroundRepeat = 'no-repeat';
	secondChild.id = 'you_location_img';
	firstChild.appendChild(secondChild);

	google.maps.event.addListener(map, 'dragend', function() {
		$('#you_location_img').css('background-position', '0px 0px');
	});

	firstChild.addEventListener('click', function() {
		var imgX = '0';
		var animationInterval = setInterval(function(){
			if(imgX == '-18') imgX = '0';
			else imgX = '-18';
			$('#you_location_img').css('background-position', imgX+'px 0px');
		}, 500);
		if(navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position) {
				var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
				map.setCenter(latlng);
				clearInterval(animationInterval);
				$('#you_location_img').css('background-position', '-144px 0px');
			});
		}
		else{
			clearInterval(animationInterval);
			$('#you_location_img').css('background-position', '0px 0px');
		}
	});

	controlDiv.index = 1;
	map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);
}

function addCenterButton(map) {
    var centerDiv = document.createElement('div');

    var centerButton = document.createElement('button');
    centerButton.style.backgroundColor = '#fff';
    centerButton.style.border = 'none';
    centerButton.style.outline = 'none';
    centerButton.style.width = '28px';
    centerButton.style.height = '28px';
    centerButton.style.borderRadius = '2px';
    centerButton.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
    centerButton.style.cursor = 'pointer';
    centerButton.style.marginBottom = '10px';
    centerButton.style.marginRight = '10px';
    centerButton.style.padding = '0px';
    centerButton.style.textAlign = 'center';
    centerButton.innerHTML = '  ';
    centerButton.value = 'Reports Center';
    centerButton.title = 'Reports Center';
    centerButton.id = 'centerButton';
    centerDiv.appendChild(centerButton);

    centerButton.addEventListener('click', function() {
        map.fitBounds(geographicBounds);
    });
    centerDiv.index = 1;
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(centerDiv);
}

// Get address submit event
$(document).ready(function() {
    $('#addressForm').on('submit', function (event) {
        update_center();
        return false;
    });
});

function getNextDate(startDate) {
    startDate.setDate(startDate.getDate()+1);
    return startDate;
}

function initializeDateSlider() {
    $("#slider").dateRangeSlider({
        bounds: {
            min: BOUNDS_MIN,
            max: BOUNDS_MAX,
        },
        arrows: false,
        defaultValues: {
            min: BOUNDS_MIN,
            max: BOUNDS_MAX,
        },
    });
    $("#slider").bind("valuesChanged", function(e, data) {
        var beginYear = parseInt(String(data.values.min).substring(11, 15), 10);
        var beginDay = parseInt(String(data.values.min).substring(8, 10), 10);
        var endYear = parseInt(String(data.values.max).substring(11, 15), 10);
        var endDay = parseInt(String(data.values.max).substring(8, 10), 10);
        var beginMonth = 0;
        var endMonth = 0;
        monthObj = {
            "Jan": 0,
            "Feb": 1,
            "Mar": 2,
            "Apr": 3,
            "May": 4,
            "Jun": 5,
            "Jul": 6,
            "Aug": 7,
            "Sep": 8,
            "Oct": 9,
            "Nov": 10,
            "Dec": 11
        };
        beginMonth = monthObj[String(data.values.min).substring(4, 7)];
        endMonth = monthObj[String(data.values.max).substring(4, 7)];
        beginDate = new Date(beginYear, beginMonth, beginDay);
        endDate = getNextDate(new Date(endYear, endMonth, endDay));

        var markersDisplayedOnMap = [];
        for (mw = 0; mw < globalMarkers.length; mw++) {
            if ((globalMarkers[mw].incidentDate.getTime() < beginDate.getTime()) ||
                (globalMarkers[mw].incidentDate.getTime() >= endDate.getTime())) {
                globalMarkers[mw].setMap(null);
            }
            else
            {
                globalMarkers[mw].setMap(globalMap);
                markersDisplayedOnMap.push(globalMarkers[mw]);
            }
        }
        markerCluster.setMap(null);
        markerCluster.clearMarkers();
        markerCluster = new MarkerClusterer(map, markersDisplayedOnMap, {gridSize: 50, maxZoom: 15, minimumClusterSize: 15, imagePath: 'static/images/clusterer/m'});
    });
}

function filterMarkers(bounds) {
    var markersDisplayedOnMap = [];
    for (mw = 0; mw < globalMarkers.length; mw++) {
        if (bounds === null || bounds.contains(globalMarkers[mw].getPosition())) {
            globalMarkers[mw].setMap(globalMap);
            markersDisplayedOnMap.push(globalMarkers[mw]);
        } else {
            globalMarkers[mw].setMap(null);
        }
    }
    markerCluster.clearMarkers();
    markerCluster.addMarkers(markersDisplayedOnMap);
}
<|endoftext|>