<commit_before>'use strict';

var fs = require('fs');
var mysql = require('mysql');
var db = require(process.cwd() + '/util/db');
var async = require('async');

/**
 * Provide the ability to load fixtures in a database
 */
function Fixtures(config) {
    this.config = config;
    this.files = fs.readdirSync('util/fixtures/data');
    this.fixtures = {};

    // Load the fixtures in this.fixtures
    for (var file in this.files) {
        var fixtureName = this.files[file].split('.')[0];
        this.fixtures[fixtureName] = require('./data/' + this.files[file]);
    }

    this.connection = mysql.createConnection(config);
}

// Load a specific fixture, can be array or single
Fixtures.prototype.load = function (params, callback) {
    var loadFixtures = [];

    if (typeof params === 'string') {
        loadFixtures.push(params);
    } else {
        loadFixtures = params;
    }

    var self = this;

    // Load the fixtures in
    async.each(loadFixtures, function (fixture, fixtureCallback) {
        var loadedFixture = self.fixtures[fixture];

        // Insert all the elements, we construct an INSERT INTO based on the keys and the values
        // INSERT INT {table} SET ?
        async.each(loadedFixture, function (object, objectCallback) {
            var sql = 'INSERT INTO ' + fixture + ' SET ?';

            // Temp object that will hold our insertion
            var temp = {};

            // Remove keys that are an object and have .persist = false set
            for (var key in object) {
                if (typeof object[key] !== 'object' && object[key].persist !== false) {
                    temp[key] = object[key];
                }
            }

            // Execute the query
            db.query({
                sql: sql,
                values: temp
            }).then(function (data) {
                return objectCallback(null, data);
            }).catch(function (err) {
                return objectCallback(err);
            });
        }, function(err) {
            if (err) {
                return fixtureCallback(err);
            }

            return fixtureCallback();
        });
    }, function (err) {
        if (err) {
            return callback(err);
        }

        return callback();
    });
};

// Load all fixtures
Fixtures.prototype.loadAll = function (callback) {
    var params = [];

    for (var file in this.files) {
        params.push(this.files[file].split('.')[0]);
    }

    return this.load(params, callback);
};

Fixtures.prototype.clear = function (callback) {
    var self = this;
    async.each(self.files, function (file, fileCallback) {
        var sql = 'SET FOREIGN_KEY_CHECKS = 0; TRUNCATE ' + file.split('.')[0] + '; SET FOREIGN_KEY_CHECKS = 1;';

        // console.log(sql);

        db.query({
            sql: sql
        }).then(function(data) {
            return fileCallback(null, data);
        }).catch(fileCallback);
    }, function (err) {
        if (err) {
            return callback(err);
        }

        return callback();
    });
};

// Export the object
module.exports = function (config) {
    var fixtures = new Fixtures(config);
    return fixtures;
};
<commit_msg>Added spaces before method parameters<commit_after>'use strict';

var fs = require('fs');
var mysql = require('mysql');
var db = require(process.cwd() + '/util/db');
var async = require('async');

/**
 * Provide the ability to load fixtures in a database
 */
function Fixtures(config) {
    this.config = config;
    this.files = fs.readdirSync('util/fixtures/data');
    this.fixtures = {};

    // Load the fixtures in this.fixtures
    for (var file in this.files) {
        var fixtureName = this.files[file].split('.')[0];
        this.fixtures[fixtureName] = require('./data/' + this.files[file]);
    }

    this.connection = mysql.createConnection(config);
}

// Load a specific fixture, can be array or single
Fixtures.prototype.load = function (params, callback) {
    var loadFixtures = [];

    if (typeof params === 'string') {
        loadFixtures.push(params);
    } else {
        loadFixtures = params;
    }

    var self = this;

    // Load the fixtures in
    async.each(loadFixtures, function (fixture, fixtureCallback) {
        var loadedFixture = self.fixtures[fixture];

        // Insert all the elements, we construct an INSERT INTO based on the keys and the values
        // INSERT INT {table} SET ?
        async.each(loadedFixture, function (object, objectCallback) {
            var sql = 'INSERT INTO ' + fixture + ' SET ?';

            // Temp object that will hold our insertion
            var temp = {};

            // Remove keys that are an object and have .persist = false set
            for (var key in object) {
                if (typeof object[key] !== 'object' && object[key].persist !== false) {
                    temp[key] = object[key];
                }
            }

            // Execute the query
            db.query({
                sql: sql,
                values: temp
            }).then(function (data) {
                return objectCallback(null, data);
            }).catch(function (err) {
                return objectCallback(err);
            });
        }, function (err) {
            if (err) {
                return fixtureCallback(err);
            }

            return fixtureCallback();
        });
    }, function (err) {
        if (err) {
            return callback(err);
        }

        return callback();
    });
};

// Load all fixtures
Fixtures.prototype.loadAll = function (callback) {
    var params = [];

    for (var file in this.files) {
        params.push(this.files[file].split('.')[0]);
    }

    return this.load(params, callback);
};

Fixtures.prototype.clear = function (callback) {
    var self = this;
    async.each(self.files, function (file, fileCallback) {
        var sql = 'SET FOREIGN_KEY_CHECKS = 0; TRUNCATE ' + file.split('.')[0] + '; SET FOREIGN_KEY_CHECKS = 1;';

        // console.log(sql);

        db.query({
            sql: sql
        }).then(function (data) {
            return fileCallback(null, data);
        }).catch(fileCallback);
    }, function (err) {
        if (err) {
            return callback(err);
        }

        return callback();
    });
};

// Export the object
module.exports = function (config) {
    var fixtures = new Fixtures(config);
    return fixtures;
};
<|endoftext|>


<commit_before>'use strict';

let cli        = require('heroku-cli-util');
let http       = require('../lib/http');
let timeago    = require('timeago');
let dateFormat = require('dateformat');
let co         = require('co');

function capitalize(str) {
  return str.substr(0, 1).toUpperCase() + str.substr(1);
}

function printStatus(status) {
  var message = capitalize(status);
  var colorize = cli.color[status];

  if (status === 'green') {
    message =  'No known issues at this time.';
  }
  return (colorize(` ${message} `));
}

function* run () {
  let response = yield http.getJson({
    hostname: process.env.HEROKU_STATUS_HOST || 'status.heroku.com',
    path: '/api/v3/current-status',
    method: 'GET',
    headers: { 'Accept': 'application/vnd.heroku+json;' },
  });

  console.log('=== Heroku Status');
  console.log(`Production:  ${printStatus(response.status.Production)}`);
  console.log(`Development: ${printStatus(response.status.Development)}`);

  response.issues.forEach(function(incident) {
    console.log(`\n=== ${incident.title} ${dateFormat(incident.created_at, "UTC:h:MM:ss TT Z")} (${incident.full_url})`);

    incident.updates.forEach(function(update) {
      console.log(`[${capitalize(update.update_type)}] ${dateFormat(incident.created_at, "UTC:h:MM:ss TT Z")} (${timeago(update.updated_at)}) \n${update.contents}\n `);
    });
  });
}

module.exports = {
  topic: 'status',
  description: 'Display current status of Heroku Platform',
  help: 'Example: heroku status',
  run: cli.command(co.wrap(run))
};
<commit_msg>use styledHeader<commit_after>'use strict';

let cli        = require('heroku-cli-util');
let http       = require('../lib/http');
let timeago    = require('timeago');
let dateFormat = require('dateformat');
let co         = require('co');

function capitalize(str) {
  return str.substr(0, 1).toUpperCase() + str.substr(1);
}

function printStatus(status) {
  var message = capitalize(status);
  var colorize = cli.color[status];

  if (status === 'green') {
    message =  'No known issues at this time.';
  }
  return (colorize(` ${message} `));
}

function* run () {
  let response = yield http.getJson({
    hostname: process.env.HEROKU_STATUS_HOST || 'status.heroku.com',
    path: '/api/v3/current-status',
    method: 'GET',
    headers: { 'Accept': 'application/vnd.heroku+json;' },
  });

  cli.styledHeader('Heroku Status');
  console.log(`Production:  ${printStatus(response.status.Production)}`);
  console.log(`Development: ${printStatus(response.status.Development)}`);

  response.issues.forEach(function(incident) {
    console.log(`\n=== ${incident.title} ${dateFormat(incident.created_at, "UTC:h:MM:ss TT Z")} (${incident.full_url})`);

    incident.updates.forEach(function(update) {
      console.log(`[${capitalize(update.update_type)}] ${dateFormat(incident.created_at, "UTC:h:MM:ss TT Z")} (${timeago(update.updated_at)}) \n${update.contents}\n `);
    });
  });
}

module.exports = {
  topic: 'status',
  description: 'Display current status of Heroku Platform',
  help: 'Example: heroku status',
  run: cli.command(co.wrap(run))
};
<|endoftext|>


<commit_before>'use strict';

const CATEGORY_MUSIC = '/channel/UC-9-kyTW8ZkZNDHQJ6FgpwQ';
const CATEGORY_SPORTS = '/channel/UCDbM8yVukVKPWUQSODaw_Mw';
const CATEGORY_COMEDY = '/channel/UCEgdi0XIXXZ-qJOFPf4JSKw';
const CATEGORY_ENTERTAINMENT = '/channel/UCi-g4cjqGV7jvU8aeSuj0jQ';
const CATEGORY_HOWTO_AND_STYLE = '/channel/UC1vGae2Q3oT5MkhhfW8lwjg';
const CATEGORY_NEWS_AND_POLITICS = '/channel/UCYfdidRxbB8Qhf0Nx7ioOYw';
const CATEGORY_FILM_AND_ANIMATION = '/channel/UCxAgnFbkxldX6YUEvdcNjnA';
const CATEGORY_SCIENCE_AND_TECHNOLOGY = '/channel/UCiDF_uaU1V00dAc8ddKvNxA';

const CATEGORY_PENDING = 'YT_DUMMY_CATEGORY_PENDING';

const CATEGORIES = [
	CATEGORY_MUSIC,
	CATEGORY_SPORTS,
	CATEGORY_COMEDY,
	CATEGORY_ENTERTAINMENT,
	CATEGORY_HOWTO_AND_STYLE,
	CATEGORY_NEWS_AND_POLITICS,
	CATEGORY_FILM_AND_ANIMATION,
	CATEGORY_SCIENCE_AND_TECHNOLOGY
];

/**
 * Array of categories allowed to be scrobbled.
 * @type {Array}
 */
const allowedCategories = [];

/**
 * "Video Id=Category" map.
 * @type {Map}
 */
const categoryCache = new Map();

/**
 * CSS selector of video element. It's common for both players.
 * @type {String}
 */
const videoSelector = '.html5-main-video';

const videoTitleSelector = '.html5-video-player .ytp-title-link';
const channelNameSelector = '#top-row .ytd-channel-name a';

let currentVideoDescription = null;
let artistTrackFromDescription = null;

readConnectorOptions();
setupEventListener();

Connector.playerSelector = '#content';

Connector.getTrackInfo = () => {
	const trackInfo = getTrackInfoFromDescription();
	if (!Util.isArtistTrackEmpty(trackInfo)) {
		return trackInfo;
	}

	let { artist, track } = Util.processYtVideoTitle(
		Util.getTextFromSelectors(videoTitleSelector)
	);
	if (!artist) {
		artist = Util.getTextFromSelectors(channelNameSelector);
	}

	return { artist, track };
};

/*
 * Because player can be still present in the page, we need to detect
 * that it's invisible and don't return current time. Otherwise resulting
 * state may not be considered empty.
 */
Connector.getCurrentTime = () => {
	return $(videoSelector).prop('currentTime');
};

Connector.getDuration = () => {
	return $(videoSelector).prop('duration');
};

Connector.isPlaying = () => {
	return $('.html5-video-player').hasClass('playing-mode');
};

Connector.getUniqueID = () => {
	/*
	 * ytd-watch-flexy element contains ID of a first played video
	 * if the miniplayer is visible, so we should check
	 * if URL of a current video in miniplayer is accessible.
	 */
	const miniPlayerVideoUrl = $('ytd-miniplayer[active] [selected] a').attr('href');
	if (miniPlayerVideoUrl) {
		return Util.getYtVideoIdFromUrl(miniPlayerVideoUrl);
	}

	return $('ytd-watch-flexy').attr('video-id');
};

Connector.isScrobblingAllowed = () => {
	if ($('.ad-showing').length > 0) {
		return false;
	}

	// FIXME: Workaround to prevent scrobbling the vidio opened in a background tab.
	if (Connector.getCurrentTime() < 1) {
		return false;
	}

	if (allowedCategories.length === 0) {
		return true;
	}

	const videoId = Connector.getUniqueID();
	if (videoId) {
		const videoCategory = getVideoCategory(videoId);
		if (videoCategory !== null) {
			return allowedCategories.includes(videoCategory);
		}

		return false;
	}

	return true;
};

Connector.applyFilter(MetadataFilter.getYoutubeFilter());

function setupEventListener() {
	$(videoSelector).on('timeupdate', Connector.onStateChanged);
}

/**
 * Get video category.
 * @param  {String} videoId Video ID
 * @return {String} Video category
 */
function getVideoCategory(videoId) {
	if (videoId === null) {
		return null;
	}

	if (!categoryCache.has(videoId)) {
		/*
		 * Add dummy category for videoId to prevent
		 * fetching category multiple times.
		 */
		categoryCache.set(videoId, CATEGORY_PENDING);

		fetchCategoryId(videoId).then((category) => {
			if (category === null) {
				Util.debugLog(`Failed to resolve category for ${videoId}`, 'warn');
			}

			categoryCache.set(videoId, category);
		});

		return null;
	}

	return categoryCache.get(videoId);
}

async function fetchCategoryId() {
	await fillMoreSection();

	const ytChannelUrls =
		$('.ytd-metadata-row-renderer .yt-formatted-string[href^="/channel/"]');
	if (ytChannelUrls.length === 1) {
		return ytChannelUrls.attr('href');
	}

	for (const data of ytChannelUrls) {
		const ytChannelUrl = $(data).attr('href');
		if (CATEGORIES.includes(ytChannelUrl)) {
			return ytChannelUrl;
		}
	}

	throw new Error('The video has no category URL!');
}

async function fillMoreSection() {
	function waitForClick(ms = 0) {
		return new Promise((resolve) => setTimeout(resolve, ms));
	}

	const ytShowLessText = $('yt-formatted-string.less-button').text();
	const ytShowMoreText = $('yt-formatted-string.more-button').text();

	// Apply global style to prevent "More/Less" button flickering.
	$('yt-formatted-string.less-button').text(ytShowMoreText);
	const styleTag = $(`
		<style id="tmp-style">
			ytd-metadata-row-container-renderer {
				visibility: hidden;
			}
			ytd-metadata-row-container-renderer #collapsible {
				height: 0;
			}
			ytd-expander > #content.ytd-expander {
				overflow: hidden;
				max-height: var(--ytd-expander-collapsed-height);
			}
			yt-formatted-string.less-button {
				margin-top: 0 !important;
			}
		</style>
	`);
	$('html > head').append(styleTag);

	// Open "More" section.
	$('yt-formatted-string.more-button').click();
	await waitForClick();

	// Close "More" section.
	$('yt-formatted-string.less-button').click();

	// Remove global style.
	$('yt-formatted-string.less-button').text(ytShowLessText);
	$('#tmp-style').remove();
}

/**
 * Asynchronously read connector options.
 */
async function readConnectorOptions() {
	if (await Util.getOption('YouTube', 'scrobbleMusicOnly')) {
		allowedCategories.push(CATEGORY_MUSIC);
	}
	if (await Util.getOption('YouTube', 'scrobbleEntertainmentOnly')) {
		allowedCategories.push(CATEGORY_ENTERTAINMENT);
	}
}

function getVideoDescription() {
	return $('#description').text();
}

function getTrackInfoFromDescription() {
	const description = getVideoDescription();
	if (currentVideoDescription === description) {
		return artistTrackFromDescription;
	}

	currentVideoDescription = description;
	artistTrackFromDescription = Util.parseYtVideoDescription(description);

	return artistTrackFromDescription;
}
<commit_msg>Fix youtube connector<commit_after>'use strict';

/**
 * Array of categories allowed to be scrobbled.
 * @type {Array}
 */
const allowedCategories = [];

/**
 * "Video Id=Category" map.
 * @type {Map}
 */
const categoryCache = new Map();

/**
 * CSS selector of video element. It's common for both players.
 * @type {String}
 */
const videoSelector = '.html5-main-video';

const videoTitleSelector = '.html5-video-player .ytp-title-link';
const channelNameSelector = '#top-row .ytd-channel-name a';

/**
 * DOM-based category fetching.
 */

// Dummy category indicates an actual category is being fetched
const CATEGORY_PENDING = 'YT_DUMMY_CATEGORY_PENDING';
// Fallback value in case when we cannot fetch a category.
const CATEGORY_UNKNOWN = 'YT_DUMMY_CATEGORY_UNKNOWN';

const CATEGORY_MUSIC = '/channel/UC-9-kyTW8ZkZNDHQJ6FgpwQ';
const CATEGORY_ENTERTAINMENT = '/channel/UCi-g4cjqGV7jvU8aeSuj0jQ';

const CATEGORIES = [
	'/channel/UC-9-kyTW8ZkZNDHQJ6FgpwQ', // Music
	'/channel/UCi-g4cjqGV7jvU8aeSuj0jQ', // Entertainment
	'/channel/UCDbM8yVukVKPWUQSODaw_Mw', // Sports
	'/channel/UCEgdi0XIXXZ-qJOFPf4JSKw', // Comedy
	'/channel/UC1vGae2Q3oT5MkhhfW8lwjg', // Howto & Style / People & Blogs
	'/channel/UCFYJCBaHRzLJrnhRglM3GdA', // Pets & Animals
	'/channel/UCYfdidRxbB8Qhf0Nx7ioOYw', // News & Politics
	'/channel/UCHiJaXgDo_JnsfOmSe-HgzA', // Auto & Vehicles
	'/channel/UCxAgnFbkxldX6YUEvdcNjnA', // Film & Animation
	'/channel/UCiDF_uaU1V00dAc8ddKvNxA', // Science & Technology
	'/channel/UCM6FFmRAK_uTICRwyTubV0A', // Nonprofits & Activism
	'/channel/UCUrY9QznFi4-S3jWihvaBpA', // Travel & Events
	'/gaming',
	'/learning',
];

const ytFormattedString = '.ytd-metadata-row-renderer .yt-formatted-string';
const gamingSelector = `${ytFormattedString}[href^="/gaming"]`;
const learningSelector = `${ytFormattedString}[href^="/learning"]`;
const genericCatSelector = `${ytFormattedString}[href^="/channel/"]`;

const categorySelectors = [
	genericCatSelector, gamingSelector, learningSelector
];

let currentVideoDescription = null;
let artistTrackFromDescription = null;

readConnectorOptions();
setupEventListener();

Connector.playerSelector = '#content';

Connector.getTrackInfo = () => {
	const trackInfo = getTrackInfoFromDescription();
	if (!Util.isArtistTrackEmpty(trackInfo)) {
		return trackInfo;
	}

	let { artist, track } = Util.processYtVideoTitle(
		Util.getTextFromSelectors(videoTitleSelector)
	);
	if (!artist) {
		artist = Util.getTextFromSelectors(channelNameSelector);
	}

	return { artist, track };
};

/*
 * Because player can be still present in the page, we need to detect
 * that it's invisible and don't return current time. Otherwise resulting
 * state may not be considered empty.
 */
Connector.getCurrentTime = () => {
	return $(videoSelector).prop('currentTime');
};

Connector.getDuration = () => {
	return $(videoSelector).prop('duration');
};

Connector.isPlaying = () => {
	return $('.html5-video-player').hasClass('playing-mode');
};

Connector.getUniqueID = () => {
	/*
	 * ytd-watch-flexy element contains ID of a first played video
	 * if the miniplayer is visible, so we should check
	 * if URL of a current video in miniplayer is accessible.
	 */
	const miniPlayerVideoUrl = $('ytd-miniplayer[active] [selected] a').attr('href');
	if (miniPlayerVideoUrl) {
		return Util.getYtVideoIdFromUrl(miniPlayerVideoUrl);
	}

	return $('ytd-watch-flexy').attr('video-id');
};

Connector.isScrobblingAllowed = () => {
	if ($('.ad-showing').length > 0) {
		return false;
	}

	// FIXME: Workaround to prevent scrobbling the vidio opened in a background tab.
	if (Connector.getCurrentTime() < 1) {
		return false;
	}

	if (allowedCategories.length === 0) {
		return true;
	}

	const videoCategory = getVideoCategory(Connector.getUniqueID());
	if (!videoCategory) {
		return false;
	}

	if (videoCategory === CATEGORY_UNKNOWN) {
		return true;
	}

	return allowedCategories.includes(videoCategory);
};

Connector.applyFilter(MetadataFilter.getYoutubeFilter());

function setupEventListener() {
	$(videoSelector).on('timeupdate', Connector.onStateChanged);
}

/**
 * Get video category.
 * @param  {String} videoId Video ID
 * @return {String} Video category
 */
function getVideoCategory(videoId) {
	if (!videoId) {
		return null;
	}

	if (categoryCache.has(videoId)) {
		return categoryCache.get(videoId);
	}

	/*
	 * Add dummy category for videoId to prevent
	 * fetching category multiple times.
	 */
	categoryCache.set(videoId, CATEGORY_PENDING);

	fetchCategoryId().then((category) => {
		console.log(`Fetched category for ${videoId}: ${category}`);
		categoryCache.set(videoId, category);
	}).catch((err) => {
		Util.debugLog(`Failed to fetch category for ${videoId}: ${err}`, 'warn');
		categoryCache.set(videoId, CATEGORY_UNKNOWN);
	});

	return null;
}

async function fetchCategoryId() {
	await fillMoreSection();

	let ytChannelUrls = [];
	for (const selector of categorySelectors) {
		ytChannelUrls = $(selector);
		if (ytChannelUrls.length > 0) {
			break;
		}
	}

	if (ytChannelUrls.length === 0) {
		return CATEGORY_UNKNOWN;
	} else if (ytChannelUrls.length === 1) {
		return ytChannelUrls.attr('href');
	}
	for (const data of ytChannelUrls) {
		const ytChannelUrl = $(data).attr('href');
		if (CATEGORIES.includes(ytChannelUrl)) {
			return ytChannelUrl;
		}
	}

	return CATEGORY_UNKNOWN;
}

async function fillMoreSection() {
	function waitForClick(ms = 0) {
		return new Promise((resolve) => setTimeout(resolve, ms));
	}

	const ytShowLessText = $('yt-formatted-string.less-button').text();
	const ytShowMoreText = $('yt-formatted-string.more-button').text();

	// Apply global style to prevent "More/Less" button flickering.
	$('yt-formatted-string.less-button').text(ytShowMoreText);
	const styleTag = $(`
		<style id="tmp-style">
			ytd-metadata-row-container-renderer {
				visibility: hidden;
			}
			ytd-metadata-row-container-renderer #collapsible {
				height: 0;
			}
			ytd-expander > #content.ytd-expander {
				overflow: hidden;
				max-height: var(--ytd-expander-collapsed-height);
			}
			yt-formatted-string.less-button {
				margin-top: 0 !important;
			}
		</style>
	`);
	$('html > head').append(styleTag);

	// Open "More" section.
	$('yt-formatted-string.more-button').click();
	await waitForClick();

	// Close "More" section.
	$('yt-formatted-string.less-button').click();

	// Remove global style.
	$('yt-formatted-string.less-button').text(ytShowLessText);
	$('#tmp-style').remove();
}

/**
 * Asynchronously read connector options.
 */
async function readConnectorOptions() {
	if (await Util.getOption('YouTube', 'scrobbleMusicOnly')) {
		allowedCategories.push(CATEGORY_MUSIC);
	}
	if (await Util.getOption('YouTube', 'scrobbleEntertainmentOnly')) {
		allowedCategories.push(CATEGORY_ENTERTAINMENT);
	}
	Util.debugLog(`Allowed categories: ${allowedCategories.join(', ')}`);
}

function getVideoDescription() {
	return $('#description').text();
}

function getTrackInfoFromDescription() {
	const description = getVideoDescription();
	if (currentVideoDescription === description) {
		return artistTrackFromDescription;
	}

	currentVideoDescription = description;
	artistTrackFromDescription = Util.parseYtVideoDescription(description);

	return artistTrackFromDescription;
}
<|endoftext|>


<commit_before>// Tally Votes in JavaScript Pairing Challenge.

// I worked on this challenge with:
// This challenge took me [#] hours.

// These are the votes cast by each student. Do not alter these objects here.
var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

// Tally the votes in voteCount.
var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount.  After Alex's votes have been tallied,
voteCount would be ...
  var voteCount = {
    president: { Bob: 1 },
    vicePresident: { Devin: 1 },
    secretary: { Gail: 1 },
    treasurer: { Kerry: 1 }
  }
*/

/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

// FAILED TEST: Bob President votes not equal to 3
  // Iterate over votes object to see President: Bob input
  // Count the number of times President: Bob appears
  // Store Bob: 3 in VoteCount

// Repeat above for VP, Secretary and Treasurer votes

// Failed Test: Name elected candidate for each position
  // Determine the highest number of votes for a position
  // Add corresponding name to that position in the officers object

// __________________________________________
// Initial Solution

for (var key in votes) {
   if (votes.hasOwnProperty(key)) {
       var student = votes[key];
        for (var position in student) {
       var candidate = student[position]
         if (voteCount[position].hasOwnProperty(candidate)) {
            voteCount[position][candidate] += 1;
         }
         else {
            voteCount[position][candidate] = 1;
         }
       }
    }
}

for (var key in voteCount) {
   if (votes.hasOwnProperty(key)) {
       var position = voteCount[key];
       candidates = Object.keys(position).sort(function(a,b){return position[a]-position[b]})

    }
}

// __________________________________________
// Refactored Solution

// __________________________________________
// Reflection

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)<commit_msg>completed JS gradebook challenge, including reflections<commit_after>// Tally Votes in JavaScript Pairing Challenge.

// I worked on this challenge with:
// This challenge took me [#] hours.

// These are the votes cast by each student. Do not alter these objects here.
var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

// Tally the votes in voteCount.
var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount.  After Alex's votes have been tallied,
voteCount would be ...
  var voteCount = {
    president: { Bob: 1 },
    vicePresident: { Devin: 1 },
    secretary: { Gail: 1 },
    treasurer: { Kerry: 1 }
  }
*/

/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

// FAILED TEST: Bob President votes not equal to 3
  // Iterate over votes object to see President: Bob input
  // Count the number of times President: Bob appears
  // Store Bob: 3 in VoteCount

// Repeat above for VP, Secretary and Treasurer votes

// Failed Test: Name elected candidate for each position
  // Determine the highest number of votes for a position
  // Add corresponding name to that position in the officers object

// __________________________________________
// Initial Solution

for (var student in votes) {
  var studentsVotes = votes[student];
  for (var position in studentsVotes) {
    var candidate = studentsVotes[position]
    if (voteCount[position].hasOwnProperty(candidate)) {
      voteCount[position][candidate] += 1;
    }
    else {
      voteCount[position][candidate] = 1;
    }
  }
}

for (var position in voteCount) {
  var candidateVotes = [];
  var candidates = voteCount[position];
  for (var candidate in candidates) {
    var votes = voteCount[position][candidate];
    candidateVotes.push([candidate, votes]);
  }
  officers[position] = candidateVotes.sort(function(a, b) { return a[1]-b[1]; } ).reverse()[0][0];
}

// __________________________________________
// Refactored Solution

for (var student in votes) {
  for (var position in votes[student]) {
    if (voteCount[position].hasOwnProperty(votes[student][position])) {
      voteCount[position][votes[student][position]] += 1;
    }
    else {
      voteCount[position][votes[student][position]] = 1;
    }
  }
}

for (var position in voteCount) {
  var candidateVotes = [];
  var candidates = voteCount[position];
  for (var candidate in candidates) {
    var votes = voteCount[position][candidate];
    candidateVotes.push([candidate, votes]);
  }
  officers[position] = candidateVotes.sort(function(a, b) { return a[1]-b[1]; } ).reverse()[0][0];
}

// __________________________________________
// Reflection

// What did you learn about iterating over nested objects in JavaScript?
// It can become confusing when using bracket or dot notation to keep track of what nest you are working in while iterating. To minimize this, we decided to set local variables with indicative labels to help guide us through the different levels of the nested objects. We also learned that it is best to use for...in while iterating over nested objects in JS. Once we figured out the proper syntax, we were able to successfully target the appropriate objects.

// Were you able to find useful methods to help you with this?
// Yup! .hasOwnProperty was a very useful method. This allowed us to determine whether a candidate had already received a vote fora particular position. Initially, we struggled to increase the votes, as the number of votes would be changed to 1 each time a new vote was cast. .hasOwnProperty helped solve this issue and increased the counter for total votes.

// What concepts were solidified in the process of working through this challenge?
// Navigating through nested objects is definitely clearer after this challenge. Taking it step by step, and digging through each level of the nested object was a good exercise in the challenge. This involved a bit of research as well. Writing bracket notation was also emphasized during this challenge, as to when quotations are to be included and excluded.

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)<|endoftext|>


<commit_before>// Tally Votes in JavaScript Pairing Challenge.

// I worked on this challenge with:
// This challenge took me [#] hours.

// These are the votes cast by each student. Do not alter these objects here.
var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

// Tally the votes in voteCount.
var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount.  After Alex's votes have been tallied,
voteCount would be ...
  var voteCount = {
    president: { Bob: 1 },
    vicePresident: { Devin: 1 },
    secretary: { Gail: 1 },
    treasurer: { Kerry: 1 }
  }
*/

/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

// Pseudocode

// __________________________________________
// Initial Solution

for (var student in votes) {
  for (var position in votes[student]) {
    var ballotName = votes[student][position];
  if (voteCount[position].hasOwnProperty(ballotName)){
    voteCount[position][ballotName] ++;
  }
  else {
    votecount[position][ballotName] = 1;
  }
    }
}

// __________________________________________
// Refactored Solution

// __________________________________________
// Reflection

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)<commit_msg>complete initial solution<commit_after>// Tally Votes in JavaScript Pairing Challenge.

// I worked on this challenge with: Caitlin Hoffman
// This challenge took me [2] hours.

// These are the votes cast by each student. Do not alter these objects here.
var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

// Tally the votes in voteCount.
var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount.  After Alex's votes have been tallied,
voteCount would be ...
  var voteCount = {
    president: { Bob: 1 },
    vicePresident: { Devin: 1 },
    secretary: { Gail: 1 },
    treasurer: { Kerry: 1 }
  }
*/

/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

// Pseudocode

// __________________________________________
// Initial Solution

for (var voter in votes) {
  if(voteCount["president"].hasOwnProperty(votes[voter]["president"])) {
    voteCount["president"][votes[voter]["president"]]++;
  }
  else {
    voteCount["president"][votes[voter]["president"]] = 1;
  }
}
for (var voter in votes) {
  if(voteCount["vicePresident"].hasOwnProperty(votes[voter]["vicePresident"])) {
    voteCount["vicePresident"][votes[voter]["vicePresident"]]++;
  }
  else {
    voteCount["vicePresident"][votes[voter]["vicePresident"]] = 1;
  }
}
for (var voter in votes) {
  if(voteCount["secretary"].hasOwnProperty(votes[voter]["secretary"])) {
    voteCount["secretary"][votes[voter]["secretary"]]++;
  }
  else {
    voteCount["secretary"][votes[voter]["secretary"]] = 1;
  }
}
for (var voter in votes) {
  if(voteCount["treasurer"].hasOwnProperty(votes[voter]["treasurer"])) {
    voteCount["treasurer"][votes[voter]["treasurer"]]++;
  }
  else {
    voteCount["treasurer"][votes[voter]["treasurer"]] = 1;
  }
}
console.log(voteCount)

var tallies = voteCount["president"];
var record = 0;

for (var name in tallies){
  if(tallies[name] > record){
    record = tallies[name];
    winner = name;
  }
}
officers["president"] = winner;

var tallies = voteCount["vicePresident"];
var record = 0;

for (var name in tallies){
  if(tallies[name] > record){
    record = tallies[name];
    winner = name;
  }
}
officers["vicePresident"] = winner;

var tallies = voteCount["secretary"];
var record = 0;

for (var name in tallies){
  if(tallies[name] > record){
    record = tallies[name];
    winner = name;
  }
}
officers["secretary"] = winner;

var tallies = voteCount["treasurer"];
var record = 0;

for (var name in tallies){
  if(tallies[name] > record){
    record = tallies[name];
    winner = name;
  }
}
officers["treasurer"] = winner;
// __________________________________________
// Refactored Solution

// __________________________________________
// Reflection

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)<|endoftext|>


<commit_before>angular.module('lattes.controllers', [])
.controller('ProfessoresCtrl', function($scope, $http, $stateParams) {
  var carregarProfessores = function () {
    const URL = "http://200.129.176.42:8085/Lattes1/json/buscaLattes/professores.json";
    const url = "http://10.101.0.251:8085/Lattes1/json/buscaLattes/professores.json";

    $http.get(URL).success(function (data) {
      $scope.prof = data;
    });
    $http.get(url).success(function (data) {
      $scope.prof = data;
    });
  };
  $scope.$on('$ionicView.enter', function() {
    carregarProfessores();
  });
})
.controller('ProfessoreCtrl', function($scope, $http, $stateParams, DadosCurriculo) {
  var pegarJson = function (){
    $scope.nomeProfessor = $stateParams.nome;
    var idProfessor = $stateParams.id;
    var requestNome = "http://10.101.0.251:8085/Lattes1/json/buscaLattes/"+ idProfessor +"/"+ idProfessor +".json";
    var requestName = "http://200.129.176.42:8085/Lattes1/json/buscaLattes/"+ idProfessor +"/"+ idProfessor + ".json";
    var requestImagem = "http://10.101.0.251:8085/Lattes1/json/buscaLattes/"+ idProfessor +"/"+ idProfessor +".gif";
    var requestPicture = "http://200.129.176.42:8085/Lattes1/json/buscaLattes/"+ idProfessor +"/"+ idProfessor +".gif";
		DadosCurriculo.requestNome = requestNome;
		DadosCurriculo.requestName = requestName;
    $http.get(requestPicture).success(function (data) {
      $scope.picProfessor = requestPicture;
    });
    $http.get(requestImagem).success(function(data) {
      $scope.picProfessor = requestPicture;
    });
  };
  $scope.$on('$ionicView.enter', function(){
    pegarJson();
  });
})
.controller('DadosCtrl', function($scope, $http, $stateParams, DadosCurriculo) {
  $scope.dg = {id_1 : false, id_2 : false, id_3 : false, id_4 : false};
	var requestNome = DadosCurriculo.requestNome;
	var requestName = DadosCurriculo.requestName;
	$http.get(requestName).success(function(data) {
		$scope.dadosCurriculo = data;
  });
  $http.get(requestNome).success(function(data) {
    $scope.dadosCurriculo = data;
  });
});
<commit_msg>Adicionado identação<commit_after>angular.module('lattes.controllers', [])
.controller('ProfessoresCtrl', function($scope, $http, $stateParams) {
  var carregarProfessores = function () {
    const URL = "http://200.129.176.42:8085/Lattes1/json/buscaLattes/professores.json";
    const url = "http://10.101.0.251:8085/Lattes1/json/buscaLattes/professores.json";

    $http.get(URL).success(function (data) {
      $scope.prof = data;
    });
    $http.get(url).success(function (data) {
      $scope.prof = data;
    });
  };
  $scope.$on('$ionicView.enter', function() {
    carregarProfessores();
  });
})
.controller('ProfessoreCtrl', function($scope, $http, $stateParams, DadosCurriculo) {
  var pegarJson = function (){
    $scope.nomeProfessor = $stateParams.nome;
    var idProfessor = $stateParams.id;
    var requestNome = "http://10.101.0.251:8085/Lattes1/json/buscaLattes/"+ idProfessor +"/"+ idProfessor +".json";
    var requestName = "http://200.129.176.42:8085/Lattes1/json/buscaLattes/"+ idProfessor +"/"+ idProfessor + ".json";
    var requestImagem = "http://10.101.0.251:8085/Lattes1/json/buscaLattes/"+ idProfessor +"/"+ idProfessor +".gif";
    var requestPicture = "http://200.129.176.42:8085/Lattes1/json/buscaLattes/"+ idProfessor +"/"+ idProfessor +".gif";
		DadosCurriculo.requestNome = requestNome;
		DadosCurriculo.requestName = requestName;
    $http.get(requestPicture).success(function (data) {
      $scope.picProfessor = requestPicture;
    });
    $http.get(requestImagem).success(function(data) {
      $scope.picProfessor = requestPicture;
    });
  };
  $scope.$on('$ionicView.enter', function(){
    pegarJson();
  });
})
.controller('DadosCtrl', function($scope, $http, $stateParams, DadosCurriculo) {
  $scope.id = {
    id_1 : false,
    id_2 : false,
    id_3 : false,
    id_4 : false
  };
	var requestNome = DadosCurriculo.requestNome;
	var requestName = DadosCurriculo.requestName;
	$http.get(requestName).success(function(data) {
		$scope.dadosCurriculo = data;
  });
  $http.get(requestNome).success(function(data) {
    $scope.dadosCurriculo = data;
  });
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { IndexLink } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import Navbar from 'react-bootstrap/lib/Navbar';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import Helmet from 'react-helmet';
import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info';
import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth';
import { InfoBar } from 'components';
import { push } from 'react-router-redux';
import config from '../../config';
import { asyncConnect } from 'redux-async-connect';

@asyncConnect([{
  promise: ({store: {dispatch, getState}}) => {
    const promises = [];

    if (!isInfoLoaded(getState())) {
      promises.push(dispatch(loadInfo()));
    }
    if (!isAuthLoaded(getState())) {
      promises.push(dispatch(loadAuth()));
    }

    return Promise.all(promises);
  }
}])
@connect(
  state => ({user: state.auth.user}),
  {logout, pushState: push})
export default class App extends Component {
  static propTypes = {
    children: PropTypes.object.isRequired,
    user: PropTypes.object,
    logout: PropTypes.func.isRequired,
    pushState: PropTypes.func.isRequired
  };

  static contextTypes = {
    store: PropTypes.object.isRequired
  };

  state = {
    navExpanded: false
  }

  componentWillReceiveProps(nextProps) {
    if (!this.props.user && nextProps.user) {
      // login
      this.props.pushState('/loginSuccess');
    } else if (this.props.user && !nextProps.user) {
      // logout
      this.props.pushState('/');
    }
  }

  handleLogout = (event) => {
    event.preventDefault();
    this.props.logout();
  };

  onNavItemClick = () => {
      this.setState({ navExpanded: !this.state.navExpanded });
  }

  render() {
    const {user} = this.props;
    const styles = require('./App.scss');

    return (

        <Helmet {...config.app.head}/>
        <Navbar fixedTop>
          <Navbar.Header>
            <Navbar.Brand>
              <IndexLink to="/" activeStyle={{color: '#d52b1e'}}>

                {config.app.title} {user}
              </IndexLink>
            </Navbar.Brand>
            <Navbar.Toggle/>
          </Navbar.Header>

          <Navbar.Collapse eventKey={0} className={this.state.navExpanded ? 'in' : ''}>

              <LinkContainer to="/community">
                <NavItem eventKey={1} onClick={ this.onNavItemClick }>Community</NavItem>
              </LinkContainer>
              <LinkContainer to="/registrieren">
                <NavItem eventKey={2} onClick={ this.onNavItemClick }>Mitglied werden</NavItem>
              </LinkContainer>
              <LinkContainer to="/kontakt">
                <NavItem eventKey={3} onClick={ this.onNavItemClick }>Kontakt</NavItem>
              </LinkContainer>

              { /*
              {user && <LinkContainer to="/chat">
                <NavItem eventKey={1}>Chat</NavItem>
              </LinkContainer>}

              <LinkContainer to="/widgets">
                <NavItem eventKey={2}>Widgets</NavItem>
              </LinkContainer>
              <LinkContainer to="/survey">
                <NavItem eventKey={3}>Survey</NavItem>
              </LinkContainer>
              <LinkContainer to="/about">
                <NavItem eventKey={4}>About Us</NavItem>
              </LinkContainer>
              <LinkContainer to="/hello">
                <NavItem eventKey={99}>Hello</NavItem>
              </LinkContainer>

              {!user &&
              <LinkContainer to="/login">
                <NavItem eventKey={5}>Login</NavItem>
              </LinkContainer>}
              {user &&
              <LinkContainer to="/logout">
                <NavItem eventKey={6} className="logout-link" onClick={this.handleLogout}>
                  Logout
                </NavItem>
              </LinkContainer>}
              */ }

            { /* user &&

Logged in as {user.name}.
 */ }
          </Navbar.Collapse>
        </Navbar>

          {this.props.children}

        <InfoBar/>

          copyright 2016 - swiss-react.ch

    );
  }
}
<commit_msg>final 07.08.16 night mobile nav fixa<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { IndexLink } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import Navbar from 'react-bootstrap/lib/Navbar';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import Helmet from 'react-helmet';
import { isLoaded as isInfoLoaded, load as loadInfo } from 'redux/modules/info';
import { isLoaded as isAuthLoaded, load as loadAuth, logout } from 'redux/modules/auth';
import { InfoBar } from 'components';
import { push } from 'react-router-redux';
import config from '../../config';
import { asyncConnect } from 'redux-async-connect';

@asyncConnect([{
  promise: ({store: {dispatch, getState}}) => {
    const promises = [];

    if (!isInfoLoaded(getState())) {
      promises.push(dispatch(loadInfo()));
    }
    if (!isAuthLoaded(getState())) {
      promises.push(dispatch(loadAuth()));
    }

    return Promise.all(promises);
  }
}])
@connect(
  state => ({user: state.auth.user}),
  {logout, pushState: push})
export default class App extends Component {
  static propTypes = {
    children: PropTypes.object.isRequired,
    user: PropTypes.object,
    logout: PropTypes.func.isRequired,
    pushState: PropTypes.func.isRequired
  };

  static contextTypes = {
    store: PropTypes.object.isRequired
  };

  state = {
    navExpanded: false
  }

  componentWillReceiveProps(nextProps) {
    if (!this.props.user && nextProps.user) {
      // login
      this.props.pushState('/loginSuccess');
    } else if (this.props.user && !nextProps.user) {
      // logout
      this.props.pushState('/');
    }
  }

  handleLogout = (event) => {
    event.preventDefault();
    this.props.logout();
  };

  onNavItemClick = () => {
      this.setState({ navExpanded: !this.state.navExpanded });
  }

  render() {
    const {user, navExpanded} = this.props;
    const styles = require('./App.scss');

    return (

        <Helmet {...config.app.head}/>
        <Navbar fixedTop>
          <Navbar.Header>
            <Navbar.Brand>
              <IndexLink to="/" activeStyle={{color: '#d52b1e'}}>

                {config.app.title} {user}
              </IndexLink>
            </Navbar.Brand>
            <Navbar.Toggle/>
          </Navbar.Header>

          <Navbar.Collapse eventKey={0} expanded={navExpanded}>

              <LinkContainer to="/community">
                <NavItem eventKey={1} onClick={ this.onNavItemClick }>Community</NavItem>
              </LinkContainer>
              <LinkContainer to="/registrieren">
                <NavItem eventKey={2} onClick={ this.onNavItemClick }>Mitglied werden</NavItem>
              </LinkContainer>
              <LinkContainer to="/kontakt">
                <NavItem eventKey={3} onClick={ this.onNavItemClick }>Kontakt</NavItem>
              </LinkContainer>

              { /*
              {user && <LinkContainer to="/chat">
                <NavItem eventKey={1}>Chat</NavItem>
              </LinkContainer>}

              <LinkContainer to="/widgets">
                <NavItem eventKey={2}>Widgets</NavItem>
              </LinkContainer>
              <LinkContainer to="/survey">
                <NavItem eventKey={3}>Survey</NavItem>
              </LinkContainer>
              <LinkContainer to="/about">
                <NavItem eventKey={4}>About Us</NavItem>
              </LinkContainer>
              <LinkContainer to="/hello">
                <NavItem eventKey={99}>Hello</NavItem>
              </LinkContainer>

              {!user &&
              <LinkContainer to="/login">
                <NavItem eventKey={5}>Login</NavItem>
              </LinkContainer>}
              {user &&
              <LinkContainer to="/logout">
                <NavItem eventKey={6} className="logout-link" onClick={this.handleLogout}>
                  Logout
                </NavItem>
              </LinkContainer>}
              */ }

            { /* user &&

Logged in as {user.name}.
 */ }
          </Navbar.Collapse>
        </Navbar>

          {this.props.children}

        <InfoBar/>

          copyright 2016 - swiss-react.ch

    );
  }
}
<|endoftext|>


<commit_before>var numVals = {}

numVals.add = function(key, value)
{
	numVals[key] = value + "";
}

for( var i = 0; i < 10; i++ )
{
	var val = i + 48;
	numVals.add(i, val);
}

for( var i = 0; i < 26; i++ )
{
	var val = i + 65;
	var char = String.fromCharCode(val);
	numVals.add(char, val);
	numVals.add(i + 10, val);
}

function number( positive, value )
{
	this.positive = positive;
	this.value = value + "";
	this.isHex = false;
	this.toString = function()
	{
		var sign = this.positive ? "+" : "-";
		return sign + this.value;
	}
}

//note: does not handle hex.
number.prototype.biggerThan = function( otherNumber, inclusive )
{
	if( this.positive && !otherNumber.positive ){ return true; }
	else if( !this.positive && otherNumber.positive ){ return false; }
	else if( !this.positive && !otherNumber.positive )
	{
		var tempNumber = new number( true, this.value );
		var tempOtherNumber = new number( true, otherNumber.value );
		return tempOtherNumber.biggerThan(tempNumber);
	}
	else
	{
		if( this.value.length > otherNumber.value.length )
		{
			return true;
		}
		else if( this.value.length < otherNumber.value.length )
		{
			return false;
		}
		else
		{
			for(var i = 0; i < this.value.length; i++)
			{
				if( parseInt(this.value[i]) > parseInt(otherNumber.value[i]))
				{
					return true;
				}
				if( parseInt(this.value[i]) < parseInt(otherNumber.value[i]))
				{
					return false;
				}
			}

			if( inclusive == undefined || inclusive == false ){ return false; }
			if( inclusive == true ){ return true; }
		}
	}
}

number.prototype.smallerThan = function( otherNumber , inclusive)
{
	return otherNumber.biggerThan(this, inclusive);
}

number.prototype.biggerThanOrEqualTo = function( otherNumber )
{
	return this.biggerThan( otherNumber, true );
}

number.prototype.smallerThanOrEqualTo = function( otherNumber )
{
	return this.smallerThan( otherNumber, true );
}

function getPaddingString(length)
{
	var string = "";
	for(var i = 0; i < length; i++)
	{
		string += "0";
	}
	return string;
}

number.prototype.plus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThis = new number(true, this.value);
			var tempThat = new number(true, otherNumber.value);
			var correctVal = tempThis.plus(tempThat).value;
			return new number(false, correctVal)
		}
		else
		{
			var tempThis = new number( true, this.value );
			return otherNumber.minus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.minus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var padding = thisLastDigit - thatLastDigit;

	var paddingString = getPaddingString(Math.abs(padding));

	if(padding > 0)
	{
		tempOtherNumber = paddingString + tempOtherNumber;
	}
	else
	{
		tempThis = paddingString + tempThis;
	}

	for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
	{
		var newNum = tempThis.charCodeAt(i) + tempOtherNumber.charCodeAt(i) + carried - 96;
		if(newNum >= 10)
		{
			carried = ( newNum - (newNum % 10) ) / 10;
			newNum = newNum % 10;
		}
		else
		{
			carried = 0;
		}

		finalString = newNum + finalString + "";
	}

	while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }

	return new number( true, finalString );
}

//todo: do this next
//note: only works for positive numbers for now.
//lies. This is not yet done.
number.prototype.minus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThat = new number(true, otherNumber.value);
			return tempThat.plus(this);
		}
		else
		{
			return otherNumber.plus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.plus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var positive = this.biggerThan(otherNumber, true);

	if(positive)
	{
		var padding = thisLastDigit - thatLastDigit;
		var paddingString = getPaddingString(Math.abs(padding));
		tempOtherNumber = paddingString + tempOtherNumber;

		for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
		{
			var newNum = tempThis.charCodeAt(i) - tempOtherNumber.charCodeAt(i) - carried;
			if(newNum < 0 )
			{
				carried = 1;
				newNum = (newNum + 10) % 10;
			}
			else
			{
				carried = 0;
			}

			finalString = newNum + finalString + "";
		}

		while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }
		return new number( true, finalString );
	}
	else
	{
		var correctValue = otherNumber.minus(this).value;
		return new number( false, correctValue );
	}
}

//note: note implemented. Use newton-raphson division algorithm?
number.prototype.divideBy = function(divisor)
{
	if(divisor.value == "0")
	{
		alert("You cannot divide by 0!!!");
	}

	alert("not implemented!");

	return { quotient: this, remainder: 5 };
}

//note: returns array of numbers.
function splitInHalf(x)
{
	var result = [];
	result.push( new number( x.positive,  x.value.substr(0, Math.ceil( x.value.length / 2 )) ));
	result.push( new number( x.positive,  x.value.substr( Math.ceil( x.value.length / 2 ), 0) ));

	return result;
}

function getChars(x, char)
{
	var n = x;
	result = "";
	while(n > 0){
		result += char;
		n--;
	}
	return result;
}

//note: this needs to be more accurate for x >> y and x << y, or will cause rounding errors.
function longMultiply(x, y)
{
	var positive = x.positive == y.positive;
	return new number(positive , parseInt(x.value) * parseInt(y.value) );
}

number.prototype.timesTenToThe = function(x)
{
	var tempThis = this;
	tempThis.value += getChars(x, "0");
	return tempThis;
}

function karatsuba(x, y)
{
	x_length = x.value.length;
	y_length = y.value.length;

	if(x_length == 1 || y_length == 1)
	{
		return longMultiply(x, y);
	}

	var xSplit = splitInHalf(x);
	var ySplit = splitInHalf(y);

	var a = karatsuba(xSplit[0], ySplit[0]).timesTenToThe(2 * Math.floor(x_length / 2));
	var c = karatsuba(xSplit[1], ySplit[1]);
	var b = karatsuba(xSplit[0].plus(xSplit[1]).value, ySplit[0].plus(ySplit[1]).value).minus(a).minus(c).timesTenToThe(Math.floor(x_length / 2));

	return a.plus(c).plus(b);
}

<commit_msg>Update number.js<commit_after>var numVals = {}

numVals.add = function(key, value)
{
	numVals[key] = value + "";
}

for( var i = 0; i < 10; i++ )
{
	var val = i + 48;
	numVals.add(i, val);
}

for( var i = 0; i < 26; i++ )
{
	var val = i + 65;
	var char = String.fromCharCode(val);
	numVals.add(char, val);
	numVals.add(i + 10, val);
}

function number( positive, value )
{
	this.positive = positive;
	this.value = value + "";
	this.isHex = false;
	this.toString = function()
	{
		var sign = this.positive ? "+" : "-";
		return sign + this.value;
	}
}

//note: does not handle hex.
number.prototype.biggerThan = function( otherNumber, inclusive )
{
	if( this.positive && !otherNumber.positive ){ return true; }
	else if( !this.positive && otherNumber.positive ){ return false; }
	else if( !this.positive && !otherNumber.positive )
	{
		var tempNumber = new number( true, this.value );
		var tempOtherNumber = new number( true, otherNumber.value );
		return tempOtherNumber.biggerThan(tempNumber);
	}
	else
	{
		if( this.value.length > otherNumber.value.length )
		{
			return true;
		}
		else if( this.value.length < otherNumber.value.length )
		{
			return false;
		}
		else
		{
			for(var i = 0; i < this.value.length; i++)
			{
				if( parseInt(this.value[i]) > parseInt(otherNumber.value[i]))
				{
					return true;
				}
				if( parseInt(this.value[i]) < parseInt(otherNumber.value[i]))
				{
					return false;
				}
			}

			if( inclusive == undefined || inclusive == false ){ return false; }
			if( inclusive == true ){ return true; }
		}
	}
}

number.prototype.smallerThan = function( otherNumber , inclusive)
{
	return otherNumber.biggerThan(this, inclusive);
}

number.prototype.biggerThanOrEqualTo = function( otherNumber )
{
	return this.biggerThan( otherNumber, true );
}

number.prototype.smallerThanOrEqualTo = function( otherNumber )
{
	return this.smallerThan( otherNumber, true );
}

function getPaddingString(length)
{
	var string = "";
	for(var i = 0; i < length; i++)
	{
		string += "0";
	}
	return string;
}

number.prototype.plus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThis = new number(true, this.value);
			var tempThat = new number(true, otherNumber.value);
			var correctVal = tempThis.plus(tempThat).value;
			return new number(false, correctVal)
		}
		else
		{
			var tempThis = new number( true, this.value );
			return otherNumber.minus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.minus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var padding = thisLastDigit - thatLastDigit;

	var paddingString = getPaddingString(Math.abs(padding));

	if(padding > 0)
	{
		tempOtherNumber = paddingString + tempOtherNumber;
	}
	else
	{
		tempThis = paddingString + tempThis;
	}

	for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
	{
		var newNum = tempThis.charCodeAt(i) + tempOtherNumber.charCodeAt(i) + carried - 96;
		if(newNum >= 10)
		{
			carried = ( newNum - (newNum % 10) ) / 10;
			newNum = newNum % 10;
		}
		else
		{
			carried = 0;
		}

		finalString = newNum + finalString + "";
	}

	while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }

	return new number( true, finalString );
}

//todo: do this next
//note: only works for positive numbers for now.
//lies. This is not yet done.
number.prototype.minus = function( otherNumber )
{
	if(!this.positive)
	{
		if(!otherNumber.positive)
		{
			var tempThat = new number(true, otherNumber.value);
			return tempThat.plus(this);
		}
		else
		{
			return otherNumber.plus(this);
		}
	}
	else if(!otherNumber.positive)
	{
		var tempThat = new number( true, otherNumber.value );
		return this.plus(tempThat);
	}

	var thisLastDigit = this.value.length;
	var thatLastDigit = otherNumber.value.length;
	var carried = 0;
	var finalString = "";

	var tempThis = "0" + this.value;
	var tempOtherNumber = "0" + otherNumber.value;

	var positive = this.biggerThan(otherNumber, true);

	if(positive)
	{
		var padding = thisLastDigit - thatLastDigit;
		var paddingString = getPaddingString(Math.abs(padding));
		tempOtherNumber = paddingString + tempOtherNumber;

		for(var i = Math.min(thisLastDigit, thatLastDigit) + Math.abs(padding); i > -1; i--)
		{
			var newNum = tempThis.charCodeAt(i) - tempOtherNumber.charCodeAt(i) - carried;
			if(newNum < 0 )
			{
				carried = 1;
				newNum = (newNum + 10) % 10;
			}
			else
			{
				carried = 0;
			}

			finalString = newNum + finalString + "";
		}

		while(finalString.length > 1 && finalString[0] == "0"){ finalString = finalString.substr(1); }
		return new number( true, finalString );
	}
	else
	{
		var correctValue = otherNumber.minus(this).value;
		return new number( false, correctValue );
	}
}

//note: note implemented. Use newton-raphson division algorithm?
number.prototype.divideBy = function(divisor)
{
	if(divisor.value == "0")
	{
		alert("You cannot divide by 0!!!");
	}

	alert("not implemented!");

	return { quotient: this, remainder: 5 };
}

//note: returns array of numbers.
function splitInHalf(x)
{
	var result = [];
	result.push( new number( x.positive,  x.value.substr(0, Math.ceil( x.value.length / 2 ) - 1) ));
	result.push( new number( x.positive,  x.value.substr( Math.ceil( x.value.length / 2 ) - 1, 0) ));

	return result;
}

function getChars(x, char)
{
	var n = x;
	result = "";
	while(n > 0){
		result += char;
		n--;
	}
	return result;
}

//note: this needs to be more accurate for x >> y and x << y, or will cause rounding errors.
function longMultiply(x, y)
{
	var positive = x.positive == y.positive;
	return new number(positive , parseInt(x.value) * parseInt(y.value) );
}

number.prototype.timesTenToThe = function(x)
{
	var tempThis = this;
	tempThis.value += getChars(x, "0");
	return tempThis;
}

function karatsuba(x, y)
{
	x_length = x.value.length;
	y_length = y.value.length;

	if(x_length == 1 || y_length == 1)
	{
		return longMultiply(x, y);
	}

	var xSplit = splitInHalf(x);
	var ySplit = splitInHalf(y);

	var a = karatsuba(xSplit[0], ySplit[0]).timesTenToThe(2 * Math.floor(x_length / 2));
	var c = karatsuba(xSplit[1], ySplit[1]);
	var b = karatsuba(xSplit[0].plus(xSplit[1]).value, ySplit[0].plus(ySplit[1]).value).minus(a).minus(c).timesTenToThe(Math.floor(x_length / 2));

	return a.plus(c).plus(b);
}

<|endoftext|>


<commit_before>/* global app:true */
(function (app) { 'use strict';

    var controller = 'HeaderController';

    if (typeof app === 'undefined') throw (controller + ': app is undefined');

    app.controller(controller, ['$scope', 'viewFactory', function ($scope, viewFactory) {
        $scope.viewFactory = viewFactory;
        $scope.title = 'Dashboard';
    }]);

})(app);<commit_msg>change: use const to declare controller name<commit_after>/* global app:true */
(function (app) { 'use strict';
    const controller = 'HeaderController';
    if (typeof app === 'undefined') throw (controller + ': app is undefined');

    app.controller(controller, ['$scope', 'viewFactory', function ($scope, viewFactory) {
        $scope.viewFactory = viewFactory;
        $scope.title = 'Dashboard';
    }]);
})(app);<|endoftext|>


<commit_before>'use strict';   // dont touch
const fs = require('fs');
var auth = require('./auth.js');
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch

// [General]
this.name = "Auth"; // Name of plugin REQUIRED
this.author = "andrews54757"; // author REQUIRED
this.description = 'An auth plugin'; // Desciprtion
this.compatVersion = '16.0.9'; // compatable with
this.version = '1.2.0'; // version REQUIRED

// [Extra Commands]
this.commandName[0] = "auth"; // plugin add-on command names
this.addToHelp[0] = "auth       : Auth plugin command"; // help command add-on (adds this string to the help command)
this.command[0] = require('./command.js'); // extra command location

// [Extra Gamemodes]
this.gamemodeId[0] = ''; // gamemodeids of extra plugin gamemodes
this.gamemode[0] = ''; // gamemode location

// [Configs]
this.config = {
requirelogin: 0,
plugin: 1,
allowregister: 1,
recordint: 100,
reservename: 0,
hidelogin: 0,
}
this.configfile = 'config.ini'

// [Functions]
this.init = function (gameServer, config) {
  this.config = config;
  auth.init(this, gameServer);
  gameServer.onregister = function(player) {
    return;

  };
  gameServer.extraregpar = [];
  gameServer.afterauth = function(player) {

  };
  gameServer.beforespawn = function(player) {

   return auth.beforespawn(player,gameServer);
  };
  gameServer.beforeq = function(player) {
    return auth.beforeq(player, gameServer);

  };
  gameServer.beforeeject = function(player) {return auth.beforeeject(player,gameServer);};
  gameServer.beforesplit = function(player) {return auth.beforesplit(player,gameServer);};
  try {
  gameServer.account = JSON.parse(fs.readFileSync('accounts.json'));
  } catch (e) {
    fs.writeFileSync('accounts.json', '[]');
    gameServer.account = [];
  }
  gameServer.auon = this.config.plugin;
  console.log("[Auth] Auth loaded. Accounts located in accounts.json")
  // init, Used to do stuff such as overriding things

};

this.onSecond = function (gameServer) {
  if (gameServer.auon == 1 && this.config.recordint > 0) {
if (!this.up) this.up = 0;
if (this.up < this.config.recordint) {
  this.up ++;

} else {
  this.up = 0;
  fs.writeFile('accounts.json',JSON.stringify(gameServer.account, null, 2), (err) => {
  if (err) throw err;
});
}
}

  // called every second
};

module.exports = this; // dont touch
<commit_msg>Update index.js<commit_after>'use strict';   // dont touch
const fs = require('fs');
var auth = require('./auth.js');
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch

// [General]
this.name = "Auth"; // Name of plugin REQUIRED
this.author = "andrews54757"; // author REQUIRED
this.description = 'An auth plugin'; // Desciprtion
this.compatVersion = '16.0.9'; // compatable with
this.version = '1.2.0'; // version REQUIRED

// [Extra Commands]
this.commandName[0] = "auth"; // plugin add-on command names
this.addToHelp[0] = "auth       : Auth plugin command"; // help command add-on (adds this string to the help command)
this.command[0] = require('./command.js'); // extra command location

// [Extra Gamemodes]
this.gamemodeId[0] = ''; // gamemodeids of extra plugin gamemodes
this.gamemode[0] = ''; // gamemode location

// [Configs]
this.config = {
requirelogin: 0,
plugin: 1,
allowregister: 1,
kicktime: 20,
recordint: 100,
reservename: 0,
hidelogin: 0,
}
this.configfile = 'config.ini'

// [Functions]
this.init = function (gameServer, config) {
  this.config = config;
  auth.init(this, gameServer);
  gameServer.onregister = function(player) {
    return;

  };
  gameServer.extraregpar = [];
  gameServer.afterauth = function(player) {

  };
  gameServer.beforespawn = function(player) {

   return auth.beforespawn(player,gameServer);
  };
  gameServer.beforeq = function(player) {
    return auth.beforeq(player, gameServer);

  };
  gameServer.beforeeject = function(player) {return auth.beforeeject(player,gameServer);};
  gameServer.beforesplit = function(player) {return auth.beforesplit(player,gameServer);};
  try {
  gameServer.account = JSON.parse(fs.readFileSync('accounts.json'));
  } catch (e) {
    fs.writeFileSync('accounts.json', '[]');
    gameServer.account = [];
  }
  gameServer.auon = this.config.plugin;
  console.log("[Auth] Auth loaded. Accounts located in accounts.json")
  // init, Used to do stuff such as overriding things

};

this.onSecond = function (gameServer) {
  if (gameServer.auon == 1 && this.config.recordint > 0) {
if (!this.up) this.up = 0;
if (this.up < this.config.recordint) {
  this.up ++;

} else {
  this.up = 0;
  fs.writeFile('accounts.json',JSON.stringify(gameServer.account, null, 2), (err) => {
  if (err) throw err;
});
}
}

  // called every second
};

module.exports = this; // dont touch
<|endoftext|>


<commit_before>/*
    The SerGIS Project - sergis-server

    Copyright (c) 2015, SerGIS Project Contributors. All rights reserved.
    Use of this source code is governed by the MIT License, which can be found
    in the LICENSE.txt file.
 */

// This file handles everything having to do with serving the socket for
// sergis-client

// node modules
var path = require("path");

// our modules
var config = require("../../config"),
    db = require("../db"),
    gameCommon = require(path.join(config.SERGIS_CLIENT, "lib", "backends", "game-common"));

/**
 * Report an error.
 */
function reportError(err) {
    if (err) {
        console.error("--------------------------------------------------------------------------------");
        console.error("SerGIS Server - Game Socket ERROR at " + (new Date()) + ":\n" + (err.stack || err) + "\n\n");
    }
}

/**
 * Initialize the handler for connections to the "/game" socket.
 * This is called each time a new connection is made to the "/game" socket.
 *
 * @param socket - The Socket instance.
 * @param {Function} next - The function to call once we have initialized
 *        the socket on our end.
 */
module.exports = function (socket, next) {
    // logIn handler
    socket.on("logIn", function (gameID, username, password, callback) {
        if (!gameID) {
            callback();
            return;
        }

        // Check the login info
        db.models.User.checkLoginInfo(username, password).then(function (user) {
            if (!user) {
                callback(false);
                return;
            }

            // We have the user; get the game
            return db.models.Game.findById(gameID).exec().then(function (game) {
                if (!game) {
                    callback();
                    return;
                }

                // We have the game; make a game token
                return db.models.GameToken.makeGameToken(game, user).then(function (gameToken) {
                    if (!gameToken) return callback();

                    // All good!
                    callback(gameToken.clientUserObject, gameToken.token);
                }, function (err) {
                    // The user probably doesn't have access to this game
                    callback(false, false);
                });
            });
        }).then(null, function (err) {
            reportError(err);
            callback();
        });
    });

    // getUser handler
    socket.on("getUser", function (gameID, sessionID, callback) {
        if (!gameID) {
            callback();
            return;
        }

        var game;
        Promise.resolve(db.models.Game.findById(gameID).exec()).then(function (_game) {
            game = _game;
            if (!game) return;

            // Get the session by its ID
            return db.getSessionByID(sessionID);
        }).then(function (session) {
            if (!session || !session.user_id) {
                // No session
                return;
            }

            // Get user from session username
            return db.models.User.findById(session.user_id).exec();
        }).then(function (user) {
            if (!game) return;

            // Whether we have a user or not, try making a game token
            return db.models.GameToken.makeGameToken(game, user);
        }).then(function (gameToken) {
            if (!gameToken) return callback();
            callback(gameToken.clientUserObject, gameToken.token);
        }).then(null, function (err) {
            reportError(err);
            callback();
        });
    });

    // game function handler
    socket.on("game", function (token, func, args, callback) {
        if (gameCommon.hasOwnProperty(func) && typeof gameCommon[func] == "function") {
            var gameToken, data;
            Promise.resolve(db.models.GameToken.findOne({token: token}).populate({
                path: "game",
                select: "+jsondata",
                options: {lean: true}
            }).exec()).then(function (_gameToken) {
                gameToken = _gameToken;
                if (!gameToken) {
                    callback(false, "Invalid token");
                    return Promise.reject();
                }

                var game = gameToken.game;
                if (!game.jsondata || !game.jsondata.promptList || !game.jsondata.promptList.length) {
                    callback(false, "Invalid game data");
                    return Promise.reject();
                }

                // Run the function (in gameCommon)
                args = [game.jsondata, gameToken.state].concat(args);
                return gameCommon[func].apply(gameCommon, args).then(null, function (data) {
                    // gameCommon...'s Promise rejected
                    callback(false, data);
                });
            }).then(function (_data) {
                data = _data;
                // gameCommon function's Promise resolved
                // If it was a "getGameOverContent", delete the token (we're done)
                if (func == "getGameOverContent") {
                    return gameToken.remove();
                } else {
                    // Otherwise, make sure state is updated
                    gameToken.markModified("state");
                    return gameToken.save();
                }
            }).then(function () {
                // Yay, all good!
                callback(true, data);
            }, function (err) {
                if (err) {
                    // Server DB error
                    reportError(err);
                    callback(false, "Server error");
                }
            });
        } else {
            return callback(false, func + " does not exist.");
        }
    });

    // Everything's initialized for us; move on!
    next();
};
<commit_msg>Poopulation<commit_after>/*
    The SerGIS Project - sergis-server

    Copyright (c) 2015, SerGIS Project Contributors. All rights reserved.
    Use of this source code is governed by the MIT License, which can be found
    in the LICENSE.txt file.
 */

// This file handles everything having to do with serving the socket for
// sergis-client

// node modules
var path = require("path");

// our modules
var config = require("../../config"),
    db = require("../db"),
    gameCommon = require(path.join(config.SERGIS_CLIENT, "lib", "backends", "game-common"));

/**
 * Report an error.
 */
function reportError(err) {
    if (err) {
        console.error("--------------------------------------------------------------------------------");
        console.error("SerGIS Server - Game Socket ERROR at " + (new Date()) + ":\n" + (err.stack || err) + "\n\n");
    }
}

/**
 * Initialize the handler for connections to the "/game" socket.
 * This is called each time a new connection is made to the "/game" socket.
 *
 * @param socket - The Socket instance.
 * @param {Function} next - The function to call once we have initialized
 *        the socket on our end.
 */
module.exports = function (socket, next) {
    // logIn handler
    socket.on("logIn", function (gameID, username, password, callback) {
        if (!gameID) {
            callback();
            return;
        }

        // Check the login info
        db.models.User.checkLoginInfo(username, password).then(function (user) {
            if (!user) {
                callback(false);
                return;
            }

            // We have the user; get the game
            return db.models.Game.findById(gameID).populate("owner")exec().then(function (game) {
                if (!game) {
                    callback();
                    return;
                }

                // We have the game; make a game token
                return db.models.GameToken.makeGameToken(game, user).then(function (gameToken) {
                    if (!gameToken) return callback();

                    // All good!
                    callback(gameToken.clientUserObject, gameToken.token);
                }, function (err) {
                    // The user probably doesn't have access to this game
                    callback(false, false);
                });
            });
        }).then(null, function (err) {
            reportError(err);
            callback();
        });
    });

    // getUser handler
    socket.on("getUser", function (gameID, sessionID, callback) {
        if (!gameID) {
            callback();
            return;
        }

        var game;
        Promise.resolve(db.models.Game.findById(gameID).populate("owner").exec()).then(function (_game) {
            game = _game;
            if (!game) return;

            // Get the session by its ID
            return db.getSessionByID(sessionID);
        }).then(function (session) {
            if (!session || !session.user_id) {
                // No session
                return;
            }

            // Get user from session username
            return db.models.User.findById(session.user_id).exec();
        }).then(function (user) {
            if (!game) return;

            // Whether we have a user or not, try making a game token
            return db.models.GameToken.makeGameToken(game, user);
        }).then(function (gameToken) {
            if (!gameToken) return callback();
            callback(gameToken.clientUserObject, gameToken.token);
        }).then(null, function (err) {
            reportError(err);
            callback();
        });
    });

    // game function handler
    socket.on("game", function (token, func, args, callback) {
        if (gameCommon.hasOwnProperty(func) && typeof gameCommon[func] == "function") {
            var gameToken, data;
            Promise.resolve(db.models.GameToken.findOne({token: token}).populate({
                path: "game",
                select: "+jsondata",
                options: {lean: true}
            }).exec()).then(function (_gameToken) {
                gameToken = _gameToken;
                if (!gameToken) {
                    callback(false, "Invalid token");
                    return Promise.reject();
                }

                var game = gameToken.game;
                if (!game.jsondata || !game.jsondata.promptList || !game.jsondata.promptList.length) {
                    callback(false, "Invalid game data");
                    return Promise.reject();
                }

                // Run the function (in gameCommon)
                args = [game.jsondata, gameToken.state].concat(args);
                return gameCommon[func].apply(gameCommon, args).then(null, function (data) {
                    // gameCommon...'s Promise rejected
                    callback(false, data);
                });
            }).then(function (_data) {
                data = _data;
                // gameCommon function's Promise resolved
                // If it was a "getGameOverContent", delete the token (we're done)
                if (func == "getGameOverContent") {
                    return gameToken.remove();
                } else {
                    // Otherwise, make sure state is updated
                    gameToken.markModified("state");
                    return gameToken.save();
                }
            }).then(function () {
                // Yay, all good!
                callback(true, data);
            }, function (err) {
                if (err) {
                    // Server DB error
                    reportError(err);
                    callback(false, "Server error");
                }
            });
        } else {
            return callback(false, func + " does not exist.");
        }
    });

    // Everything's initialized for us; move on!
    next();
};
<|endoftext|>