<commit_before>import React, { Fragment } from 'react'
import propPath from 'crocks/Maybe/propPath'
import { RichText } from 'prismic-reactjs'
import styled, { keyframes } from 'styled-components'
import { key } from 'styled-theme'

import { Lazy } from 'Components'
import {
  ResultSection,
  SectionRowCentered,
  SectionHeader,
  SectionImage,
  SectionBlock,
} from 'Styled'
import { linkResolver, s4 } from 'Helpers'

const MirroredSection = ResultSection.extend`
  padding-top: ${key(['space', 10])}px;
`

const MirroredImageBlock = SectionBlock.extend`
  max-width: 480px;
  font-weight: ${key('fontWeights.medium')};
  & h3 {
    padding-bottom: ${key(['space', 9])}px;
  }
  & .sectionimage {
    width: 570px;
    height: 460px;
    float: right;
    margin-top: ${key(['space', 7])}px;
    @media (min-width: 1200px) {
      margin-top: -${key(['space', 11])}px;
      margin-right: calc(-50vw + 215px);
    }
  }
  & .mirroredimage {
  display: none;
  @media (min-width: 1200px) {
    display: block;
    position: absolute;
    left: calc(-50vw + 215px);
    transform: rotateY(180deg);
    z-index: -1;
  }
`

export const ResultMirroredImage = ({ section }) => {
  const { primary, items } = section
  const header = propPath(['primary', 'header'])
  const getHeader = header(section).option([{text: ''}])

  return (
    <MirroredSection id={primary.anchor || null} >
      <Lazy height={770}>
        <SectionRowCentered>
        {getHeader.length &&
          <SectionHeader color='text' shade='pink' >
          { RichText.asText(primary.header) }
          </SectionHeader>
        }
        <SectionRowCentered>
        </SectionRowCentered>
        {items.map(item =>
          <MirroredImageBlock key={s4()} >
            <Fragment key={s4()}>
            { RichText.render(item.text, linkResolver) }
            {(item.sectionimage.url !== null) &&
              <Fragment key={s4()}>
                <SectionImage key={s4()} className='sectionimage' url={item.sectionimage.url} />
                <SectionImage key={s4()} className='sectionimage mirroredimage' url={item.sectionimage.url} />
              </Fragment>
            }
            </Fragment>
          </MirroredImageBlock>
        )}
        </SectionRowCentered>
      </Lazy>
    </MirroredSection>
  )
}<commit_msg>fix mirrored<commit_after>import React, { Fragment } from 'react'
import propPath from 'crocks/Maybe/propPath'
import { RichText } from 'prismic-reactjs'
import styled, { keyframes } from 'styled-components'
import { key } from 'styled-theme'

import { Lazy } from 'Components'
import {
  ResultSection,
  SectionRowCentered,
  SectionHeader,
  SectionBlock,
} from 'Styled'
import { linkResolver, s4 } from 'Helpers'

const MirroredSection = ResultSection.extend`
  padding-top: ${key(['space', 10])}px;
`

const SectionImage = styled.div`
  background: url(${({url}) => url}) center no-repeat;
  background-size: cover;
`

const MirroredImageBlock = SectionBlock.extend`
  max-width: 480px;
  font-weight: ${key('fontWeights.medium')};
  & h3 {
    padding-bottom: ${key(['space', 9])}px;
  }
  & .sectionimage {
    width: 570px;
    height: 460px;
    float: right;
    margin-top: ${key(['space', 7])}px;
    @media (min-width: 1200px) {
      margin-top: -${key(['space', 11])}px;
      margin-right: calc(-50vw + 215px);
    }
  }
  & .mirroredimage {
  display: none;
  @media (min-width: 1200px) {
    display: block;
    position: absolute;
    left: calc(-50vw + 215px);
    transform: rotateY(180deg);
    z-index: -1;
  }
`

export const ResultMirroredImage = ({ section }) => {
  const { primary, items } = section
  const header = propPath(['primary', 'header'])
  const getHeader = header(section).option([{text: ''}])

  return (
    <MirroredSection id={primary.anchor || null} >
      <Lazy height={770}>
        <SectionRowCentered>
        {getHeader.length &&
          <SectionHeader color='text' shade='pink' >
          { RichText.asText(primary.header) }
          </SectionHeader>
        }
        <SectionRowCentered>
        </SectionRowCentered>
        {items.map(item =>
          <MirroredImageBlock key={s4()} >
            <Fragment key={s4()}>
            { RichText.render(item.text, linkResolver) }
            {(item.sectionimage.url !== null) &&
              <Fragment key={s4()}>
                <SectionImage key={s4()} className='sectionimage' url={item.sectionimage.url} />
                <SectionImage key={s4()} className='sectionimage mirroredimage' url={item.sectionimage.url} />
              </Fragment>
            }
            </Fragment>
          </MirroredImageBlock>
        )}
        </SectionRowCentered>
      </Lazy>
    </MirroredSection>
  )
}<|endoftext|>


<commit_before>import database from './database';

/**
 * The PostIt class
 * @author Babatunde Adeyemi <tundewrites@gmail.com>
 * @class
 */
class PostIt {

  /**
   * Initializes the database connection
   * Initializes the database models
   * @constructor
   */
  constructor() {
    this.database = database;
  }

  /**
   * Registers new user's info to database
   * @param {string} firstName - User's first name
   * @param {string} lastName - User's last name
   * @param {string} email - User's email
   * @param {string} phone - User's phone
   * @param {string} password - User's password
   * @returns {Promise} - returns a Promise
   */
  registerUser(firstName, lastName, email, phone, password) {
    return this.database.connection.sync().then(() =>
      this.database.User.create({
        firstName,
        lastName,
        email,
        phone,
        password
      })
    );
  }

  /**
   * Fetches a user's details
   * @param {string} email - Signin email address
   * @returns {Promise} - returns a Promise
   */
  findUser(email) {
    return this.database.User.findOne({
      where: {
        email
      }
    });
  }

  /**
   * Fetches a group's details
   * @param {string} groupId - groupId of a particular group
   * @returns {Promise}- returns a Promise
   */
  findGroup(groupId) {
    return this.database.Group.findOne({
      where: {
        groupId
      }
    });
  }

  /**
   * Creates a new group for a user
   * @param {string} name - Name of the group
   * @param {string} userId - userId of the creator
   * @returns {Promise} - returns a Promise
   */
  creatGroup(name, userId) {
    return this.database.connection.sync().then(() =>
      this.database.Group.create({
        name,
        userId
      })
    );
  }

  /**
   * Posts a message to a group
   * @param {string} inGroup - groupId of target group
   * @param {string} author - userId of the User
   * @param {string} body - Message content
   * @param {string} priority - Type of message
   * @return {Promise} - returns a Promise
   */
  postMessage(inGroup, author, body, priority) {
    return this.database.connection.sync().then(() =>
      this.database.Message.create({
        inGroup,
        author,
        body,
        priority
      })
    );
  }

  /**
   * Adds a member to a group
   * @param {string} userId - userId of the user
   * @param {string} groupId - groupId of the group
   * @returns {Promise} - returns a Promise
   */
  addGroupMember(userId, groupId) {
    return this.database.connection.sync().then(() =>
      this.database.GroupMember.create({
        userId,
        groupId
      })
    );
  }

  /**
   * Fetches all messages in a particular group
   * @param {string} groupId - target group
   * @returns {Promise} - returns a Promise
   */
  getMessages(groupId) {
    return this.database.Message.findAll({
      where: {
        inGroup: groupId
      }
    });
  }

  /**
   * Checks if an an array of values are strings
   * @param {Array} fieldArray - value to checked
   * @returns {Boolean} - returns either true or false
   */
  static areFieldsValid(fieldArray) {
    let result = false;
    for (let index = 0; index < fieldArray.length; index += 1) {
      result = (fieldArray[index].length >= 3);
      if (!result) return result;
    }
  }

  /**
   * Checks if an input is a number
   * @param {Nmber} number - value to be checked
   * @returns {Boolean} - returns either true or false
   */
  static isPhone(number) {
    if (number.length !== 11) {
      return false;
    }
    if (isNaN(Number(number))) {
      return false;
    }
    return true;
  }

  /**
   * Checks if email is valid
   * @param {String} email - email to be checked
   * @returns {Boolean} - returns true or false
   */
  static isEmail(email) {
    return !!email.match(/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$/);
  }
}

export default PostIt;
<commit_msg>Remove unused methods<commit_after>import database from './database';

/**
 * The PostIt class
 * @author Babatunde Adeyemi <tundewrites@gmail.com>
 * @class
 */
class PostIt {

  /**
   * Initializes the database connection
   * Initializes the database models
   * @constructor
   */
  constructor() {
    this.database = database;
  }

  /**
   * Registers new user's info to database
   * @param {string} firstName - User's first name
   * @param {string} lastName - User's last name
   * @param {string} email - User's email
   * @param {string} phone - User's phone
   * @param {string} password - User's password
   * @returns {Promise} - returns a Promise
   */
  registerUser(firstName, lastName, email, phone, password) {
    return this.database.connection.sync().then(() =>
      this.database.User.create({
        firstName,
        lastName,
        email,
        phone,
        password
      })
    );
  }

  /**
   * Fetches a user's details
   * @param {string} email - Signin email address
   * @returns {Promise} - returns a Promise
   */
  findUser(email) {
    return this.database.User.findOne({
      where: {
        email
      }
    });
  }

  /**
   * Fetches a group's details
   * @param {string} groupId - groupId of a particular group
   * @returns {Promise}- returns a Promise
   */
  findGroup(groupId) {
    return this.database.Group.findOne({
      where: {
        groupId
      }
    });
  }

  /**
   * Creates a new group for a user
   * @param {string} name - Name of the group
   * @param {string} userId - userId of the creator
   * @returns {Promise} - returns a Promise
   */
  creatGroup(name, userId) {
    return this.database.connection.sync().then(() =>
      this.database.Group.create({
        name,
        userId
      })
    );
  }

  /**
   * Posts a message to a group
   * @param {string} inGroup - groupId of target group
   * @param {string} author - userId of the User
   * @param {string} body - Message content
   * @param {string} priority - Type of message
   * @return {Promise} - returns a Promise
   */
  postMessage(inGroup, author, body, priority) {
    return this.database.connection.sync().then(() =>
      this.database.Message.create({
        inGroup,
        author,
        body,
        priority
      })
    );
  }

  /**
   * Adds a member to a group
   * @param {string} userId - userId of the user
   * @param {string} groupId - groupId of the group
   * @returns {Promise} - returns a Promise
   */
  addGroupMember(userId, groupId) {
    return this.database.connection.sync().then(() =>
      this.database.GroupMember.create({
        userId,
        groupId
      })
    );
  }

  /**
   * Fetches all messages in a particular group
   * @param {string} groupId - target group
   * @returns {Promise} - returns a Promise
   */
  getMessages(groupId) {
    return this.database.Message.findAll({
      where: {
        inGroup: groupId
      }
    });
  }
}

export default PostIt;
<|endoftext|>


<commit_before>/**
 * Created by PRadostev on 10.06.2015.
 */

describe("L.GML.MultiPoint", function () {
  var parser;

  before(function () {
    parser = new L.GML.MultiPoint();
  });

  it('should parse gml:MultiPoint element', function () {
    expect(parser.elementTag).to.equal('gml:MultiPoint');
  });

  it('should know how parse gml:Point', function () {
    var child = parser.parsers['gml:Point'];
    expect(child).to.be.instanceOf(L.GML.Point);
  });

  it('should return L.FeatureGroup object', function () {
    var stub = sinon.stub(L.GML.MultiGeometry.prototype, 'parse').returns([new L.Marker([0, 0])]);
    var result = parser.parse({});
    expect(result).to.be.instanceOf(L.FeatureGroup);
    stub.restore();
  });
});
<commit_msg>multipoint test fix<commit_after>/**
 * Created by PRadostev on 10.06.2015.
 */

describe("L.GML.MultiPoint", function () {
  var parser;

  before(function () {
    parser = new L.GML.MultiPoint();
  });

  it('should parse gml:MultiPoint element', function () {
    expect(parser.elementTag).to.equal('gml:MultiPoint');
  });

  it('should know how parse gml:Point', function () {
    var child = parser.parsers['gml:Point'];
    expect(child).to.be.instanceOf(L.GML.PointNode);
  });

  it('should return L.FeatureGroup object', function () {
    var stub = sinon.stub(L.GML.MultiGeometry.prototype, 'parse').returns([[0, 0]]);
    var result = parser.parse({});
    expect(result).to.be.instanceOf(L.FeatureGroup);
    stub.restore();
  });
});
<|endoftext|>


<commit_before>/* jshint eqnull:true, noarg:true, noempty:true, eqeqeq:true, bitwise:false, strict:true, undef:true, curly:false, node:true, devel:true, newcap:false, maxerr:50 */
(function () {
	"use strict";

	var fs = require("fs"),
		path = require("path"),
		child_process = require("child_process"),
		html_minifier = require("html-minifier"),
		// uglyify_js = require("uglify-js"),
		CleanCSS = require("clean-css"),
		debug_wrap = require("./src/debug_wrap");

	var SCRIPT_SOURCE = "./src/h-links.js",
		OUTPUT_MAIN = "./builds/h-links.user.js",
		OUTPUT_DEBUG = "./builds/h-links.debug.user.js",
		PACKAGE_JSON = "./package.json",
		RESOURCES = "./resources",
		RES_STYLESHEET = RESOURCES + "/stylesheets/style.css",
		RES_HTML_SETTINGS = RESOURCES + "/html/settings.html",
		RES_ICON_X48 = RESOURCES + "/images/icon48.png",
		RES_ICON_X64 = RESOURCES + "/images/icon64.png";

	var pkg = null;

	var mimes = {
		".png": "image/png",
		".jpg": "image/jpeg",
		".jpeg": "image/jpeg",
		".css": "text/css",
		"": "text/plain"
	};

	var read_json = function (path) {
		var input = fs.readFileSync(path, "utf8");
		return JSON.parse(input);
	};

	var html = function (path) {
		var input = fs.readFileSync(path, "utf8");
		input = html_minifier.minify(input, { removeComments: true, collapseWhitespace: true });
		input = input.replace(/\#{([^}]*)}/g, "'+$1+'");
		return input;
	};

	var resources = function (input) {
		input = input.replace(/\#RESOURCE_BASE64\:([^\#]+)\#/g, function (m, name) {
			var file = path.resolve(path.normalize(path.join(RESOURCES, name))),
				data = fs.readFileSync(file).toString("base64"),
				ext = path.extname(file).toLowerCase(),
				mime = mimes[(Object.prototype.hasOwnProperty.call(mimes, ext)) ? ext : ""];

			return "data:" + mime + ";base64," + data;
		});

		return input;
	};

	var build = function (output, version, tag, no_update, debug) {
		var output_meta = output.replace(/\.user\./, ".meta."),
			header = "",
			source, style, list, i, ii;

		header += "// ==UserScript==\n";
		header += "// @name        " + pkg.name + (tag || "") + "\n";
		header += "// @namespace   " + pkg.custom.namespace + "\n";
		header += "// @author      " + pkg.author + "\n";
		header += "// @version     " + version + "\n";
		header += "// @description " + pkg.description + "\n";
		for (list = pkg.custom.targets, i = 0, ii = list.length; i < ii; ++i) {
			header += "// @include     " + list[i] + "\n";
		}
		header += "// @homepage    " + pkg.homepage + "\n";
		header += "// @supportURL  " + pkg.bugs.url + "\n";
		if (!no_update) {
			header += "// @updateURL   " + pkg.custom.update_url_base + path.normalize(output_meta).replace(/\\/g, "/") + "\n";
			header += "// @downloadURL " + pkg.custom.update_url_base + path.normalize(output).replace(/\\/g, "/") + "\n";
		}
		header += "// @icon        data:image/png;base64," + fs.readFileSync(RES_ICON_X48).toString("base64") + "\n";
		header += "// @icon64      data:image/png;base64," + fs.readFileSync(RES_ICON_X64).toString("base64") + "\n";
		for (list = pkg.custom.gm_permissions, i = 0, ii = list.length; i < ii; ++i) {
			header += "// @grant       " + list[i] + "\n";
		}
		header += "// @run-at      document-start\n";
		header += "// ==/UserScript==";

		style = fs.readFileSync(RES_STYLESHEET, "utf8");
		style = resources(style);
		style = new CleanCSS({}).minify(style).styles;

		source = fs.readFileSync(SCRIPT_SOURCE, "utf8");

		source = source.replace(/\#OPTIONS\#/g, html(RES_HTML_SETTINGS));
		source = source.replace(/\/\*\#VERSION\#\*\//g, version.split(".").join(","));
		source = source.replace(/\#HOMEPAGE\#/g, pkg.homepage);
		source = source.replace(/\#ISSUES\#/g, pkg.bugs.url);
		source = source.replace(/\#CHANGELOG\#/g, pkg.custom.changelog_url);
		source = source.replace(/\"\#STYLESHEET\#\"/g, JSON.stringify(style));
		source = source.replace(/\#TITLE\#/g, pkg.name);
		source = source.replace(/\#TITLE_2CHAR\#/g, pkg.custom.name_short);
		source = source.replace(/\#PREFIX\#/g, pkg.custom.settings_prefix);
		source = source.replace(/\/\*\s*(jshint|globals)\s+.*\*\/(?:\r?\n)?/g, "");

		source = header + "\n" + source;

		if (debug) {
			source = debug_wrap.debug_wrap_code(source, debug === "simple");
		}

		fs.writeFileSync(output, source, "utf8", function (err) {
			if (err) throw err;
		});

		if (!no_update) {
			fs.writeFileSync(output_meta, header, "utf8", function (err) {
				if (err) throw err;
			});
		}
	};

	var full_debug = (process.argv[2] === "full" || process.argv[3] === "full");
	var full_build = function () {
		build(OUTPUT_MAIN, pkg.version, "", false, false);
		build(OUTPUT_DEBUG, pkg.version + ".0xDB", " (debug)", true, full_debug ? true : "simple");

		process.stdout.write("Build successful!\n");

		var cmd = null,
			f;
		if (fs.existsSync((f = "./post_build.bat"))) {
			cmd = [ "cmd", "/s", "/c", f.replace(/\//g, "\\") ];
		}
		else if (fs.existsSync((f = "./post_build.sh"))) {
			cmd = [ f ];
		}

		if (cmd !== null) {
			child_process.spawnSync(cmd[0], cmd.slice(1), { stdio: "inherit" });
		}
	};
	var full_build_safe = function () {
		try {
			pkg = read_json(PACKAGE_JSON);
			full_build();
		}
		catch (e) {
			var pad = "========================================\n";
			process.stderr.write(pad + "" + e + "\n" + pad);
		}
	};

	full_build_safe();
	if (process.argv[2] === "dev") {
		var check = function (curr, prev) {
			if (curr.mtime > prev.mtime) {
				full_build_safe();
			}
		};
		var settings = { interval: 250 };

		fs.watchFile(SCRIPT_SOURCE, settings, check);
		fs.watchFile(RES_STYLESHEET, settings, check);
		fs.watchFile(RES_HTML_SETTINGS, settings, check);
		fs.watchFile(RES_ICON_X48, settings, check);
		fs.watchFile(RES_ICON_X64, settings, check);
		fs.watchFile(PACKAGE_JSON, settings, check);
	}

})();

<commit_msg>Update build file<commit_after>/* jshint eqnull:true, noarg:true, noempty:true, eqeqeq:true, bitwise:false, strict:true, undef:true, curly:false, node:true, devel:true, newcap:false, maxerr:50 */
(function () {
	"use strict";

	var fs = require("fs"),
		path = require("path"),
		child_process = require("child_process"),
		html_minifier = require("html-minifier"),
		// uglyify_js = require("uglify-js"),
		CleanCSS = require("clean-css"),
		debug_wrap = require("./src/debug_wrap");

	var SCRIPT_SOURCE = "./src/x-links.js",
		OUTPUT_MAIN = "./builds/x-links.user.js",
		OUTPUT_DEBUG = "./builds/x-links.debug.user.js",
		PACKAGE_JSON = "./package.json",
		RESOURCES = "./resources",
		RES_STYLESHEET = RESOURCES + "/stylesheets/style.css",
		RES_HTML_SETTINGS = RESOURCES + "/html/settings.html",
		RES_ICON_X48 = RESOURCES + "/images/icon48.png",
		RES_ICON_X64 = RESOURCES + "/images/icon64.png";

	var pkg = null;

	var mimes = {
		".png": "image/png",
		".jpg": "image/jpeg",
		".jpeg": "image/jpeg",
		".css": "text/css",
		"": "text/plain"
	};

	var read_json = function (path) {
		var input = fs.readFileSync(path, "utf8");
		return JSON.parse(input);
	};

	var html = function (path) {
		var input = fs.readFileSync(path, "utf8");
		input = html_minifier.minify(input, { removeComments: true, collapseWhitespace: true });
		input = input.replace(/\#{([^}]*)}/g, "'+$1+'");
		return input;
	};

	var resources = function (input) {
		input = input.replace(/\#RESOURCE_BASE64\:([^\#]+)\#/g, function (m, name) {
			var file = path.resolve(path.normalize(path.join(RESOURCES, name))),
				data = fs.readFileSync(file).toString("base64"),
				ext = path.extname(file).toLowerCase(),
				mime = mimes[(Object.prototype.hasOwnProperty.call(mimes, ext)) ? ext : ""];

			return "data:" + mime + ";base64," + data;
		});

		return input;
	};

	var build = function (output, version, tag, no_update, debug) {
		var output_meta = output.replace(/\.user\./, ".meta."),
			header = "",
			source, style, list, i, ii;

		header += "// ==UserScript==\n";
		header += "// @name        " + pkg.name + (tag || "") + "\n";
		header += "// @namespace   " + pkg.custom.namespace + "\n";
		header += "// @author      " + pkg.author + "\n";
		header += "// @version     " + version + "\n";
		header += "// @description " + pkg.description + "\n";
		for (list = pkg.custom.targets, i = 0, ii = list.length; i < ii; ++i) {
			header += "// @include     " + list[i] + "\n";
		}
		header += "// @homepage    " + pkg.homepage + "\n";
		header += "// @supportURL  " + pkg.bugs.url + "\n";
		if (!no_update) {
			header += "// @updateURL   " + pkg.custom.update_url_base + path.normalize(output_meta).replace(/\\/g, "/") + "\n";
			header += "// @downloadURL " + pkg.custom.update_url_base + path.normalize(output).replace(/\\/g, "/") + "\n";
		}
		header += "// @icon        data:image/png;base64," + fs.readFileSync(RES_ICON_X48).toString("base64") + "\n";
		header += "// @icon64      data:image/png;base64," + fs.readFileSync(RES_ICON_X64).toString("base64") + "\n";
		for (list = pkg.custom.gm_permissions, i = 0, ii = list.length; i < ii; ++i) {
			header += "// @grant       " + list[i] + "\n";
		}
		header += "// @run-at      document-start\n";
		header += "// ==/UserScript==";

		style = fs.readFileSync(RES_STYLESHEET, "utf8");
		style = resources(style);
		style = new CleanCSS({}).minify(style).styles;

		source = fs.readFileSync(SCRIPT_SOURCE, "utf8");

		source = source.replace(/\#OPTIONS\#/g, html(RES_HTML_SETTINGS));
		source = source.replace(/\/\*\#VERSION\#\*\//g, version.split(".").join(","));
		source = source.replace(/\#HOMEPAGE\#/g, pkg.homepage);
		source = source.replace(/\#ISSUES\#/g, pkg.bugs.url);
		source = source.replace(/\#CHANGELOG\#/g, pkg.custom.changelog_url);
		source = source.replace(/\"\#STYLESHEET\#\"/g, JSON.stringify(style));
		source = source.replace(/\#TITLE\#/g, pkg.name);
		source = source.replace(/\#TITLE_2CHAR\#/g, pkg.custom.name_short);
		source = source.replace(/\#PREFIX\#/g, pkg.custom.settings_prefix);
		source = source.replace(/\/\*\s*(jshint|globals)\s+.*\*\/(?:\r?\n)?/g, "");

		source = header + "\n" + source;

		if (debug) {
			source = debug_wrap.debug_wrap_code(source, debug === "simple");
		}

		fs.writeFileSync(output, source, "utf8", function (err) {
			if (err) throw err;
		});

		if (!no_update) {
			fs.writeFileSync(output_meta, header, "utf8", function (err) {
				if (err) throw err;
			});
		}
	};

	var full_debug = (process.argv[2] === "full" || process.argv[3] === "full");
	var full_build = function () {
		build(OUTPUT_MAIN, pkg.version, "", false, false);
		build(OUTPUT_DEBUG, pkg.version + ".0xDB", " (debug)", true, full_debug ? true : "simple");

		process.stdout.write("Build successful!\n");

		var cmd = null,
			f;
		if (fs.existsSync((f = "./post_build.bat"))) {
			cmd = [ "cmd", "/s", "/c", f.replace(/\//g, "\\") ];
		}
		else if (fs.existsSync((f = "./post_build.sh"))) {
			cmd = [ f ];
		}

		if (cmd !== null) {
			child_process.spawnSync(cmd[0], cmd.slice(1), { stdio: "inherit" });
		}
	};
	var full_build_safe = function () {
		try {
			pkg = read_json(PACKAGE_JSON);
			full_build();
		}
		catch (e) {
			var pad = "========================================\n";
			process.stderr.write(pad + "" + e + "\n" + pad);
		}
	};

	full_build_safe();
	if (process.argv[2] === "dev") {
		var check = function (curr, prev) {
			if (curr.mtime > prev.mtime) {
				full_build_safe();
			}
		};
		var settings = { interval: 250 };

		fs.watchFile(SCRIPT_SOURCE, settings, check);
		fs.watchFile(RES_STYLESHEET, settings, check);
		fs.watchFile(RES_HTML_SETTINGS, settings, check);
		fs.watchFile(RES_ICON_X48, settings, check);
		fs.watchFile(RES_ICON_X64, settings, check);
		fs.watchFile(PACKAGE_JSON, settings, check);
	}

})();

<|endoftext|>


<commit_before>/**
 * Dependencies.
 */
const request = require('request');
const cheerio = require('cheerio');
const fakeUa = require('fake-useragent');

/**
 * Module.
 */
module.exports = function (options) {

  /**
   * Constants.
   */
  var url = 'http://terrikon.com/livescore'; // http://www.livescore.cz/
  var mainClass  = '.content';
  var teamsClass = '.ply';
  var scoreClass = '.row-light .sco';
  var scoresClass = '.row-gray .sco';
  var scoresNamesClass = '.row-gray .info';

  var mapTeam = function(team) {
    if (team === "N.Ireland")
      team = "Northern Ireland";
    if (team === "Ireland")
      team = "Republic of Ireland";

    return team;
  }

  return {

    scrap: function(callback) {

      request({
        url: url,
        headers: {
          'User-Agent': fakeUa()
        }
      }, function(e, r, b) {
        if (e)
          return callback(e);
        statusCode = r && r.statusCode
        if (statusCode != 200) {
          return callback(new Error(statusCode))
        }

        b = b.replace(/<(\/?)script/g, '<$1nobreakage');

        $ = cheerio.load(b);

        /**
         * Variables.
         */
        var teamsA = [];
        var teamsB = [];
        var scores = [];
        var scoresDetails = [];
        var scoresDetailsNames = [];
        var results = [];

        /**
         * Extract data.
         */
        $(mainClass + ' ' + teamsClass).each(function(i, element) {
          console.log("ya: ", $(this).html())
          var team = mapTeam($(this).html().replace('*', '').trim());
          console.log("team: ", team)
          if (team) {
            if (teamsA.length > teamsB.length) {
              teamsB.push(team);
            } else {
              teamsA.push(team);
            }
          }
        });
        $(mainClass + ' ' + scoreClass).each(function() {
          var score = $(this).html();
          if (score.match(''))
            score = score.substring(score.indexOf('>')+1, score.indexOf(''));
          score = score.trim();
          scores.push(score);
        });
        $(scoresNamesClass).each(function() {
          var scoreName = $(this).html();
          var html = cheerio.load(scoreName);
          var i = 0
            , ss = [];
          html('div').each(function() {
            ss.push($(this).html());
          });
          if (ss.length > 0) {
            scoresDetailsNames.push(ss);
          }
        });
        $(scoresClass).each(function() {
          var score = $(this).html();
          var html = cheerio.load(score);
          var i = 0
            , ss = [];
          html('div').each(function() {
            var arr = /\((\d)\s-\s(\d)\)/.exec($(this).html());
            if (arr) {
              ss.push([parseInt(arr[1]), parseInt(arr[2])]);
            } else {
              ss.push([])
            }
            i += 1;
          });
          if (ss.length > 0) {
            scoresDetails.push(ss);
          }
        });

        /**
         * Gather the result in a array of objects.
         */
        for (var i = 0; i < scores.length; i++) {
          var score = scores[i];
          score = [parseInt(score.substring(0,score.indexOf('-')-1)), parseInt(score.substring(score.indexOf('-')+2))];

          // Get penaly index.
          var penaltyIndex = 2;
          for (var j = 0; j<scoresDetails[i].length; j++) {
            if (scoresDetailsNames[i][j].match('penalty'))
              penaltyIndex = j;
          };
          var scorePenalty = scoresDetails[i][penaltyIndex];

          // add the penalty result to the score
          if (scorePenalty) {
            if (scorePenalty[0] > scorePenalty[1]) {
              score[0] += 1;
            } else {
              score[1] += 1;
            }
          }

          results.push({
              teams  : [teamsA[i], teamsB[i]]
            , score  : score
            , scoreExtraTime : scoresDetails[i][1] || null
            , scorePenalty : scorePenalty || null
          });
        };

        callback(null, results);

      });
    }

  };

};
<commit_msg>change scraper to another website (fixes #8)<commit_after>/**
 * Dependencies.
 */
const request = require('request');
const cheerio = require('cheerio');
const fakeUa = require('fake-useragent');

/**
 * Module.
 */
module.exports = function (options) {

  /**
   * Constants.
   */
  var url = 'http://terrikon.com/livescore'; // http://www.livescore.cz/
  var mainClass  = '.content-site';
  var teamsClass = '.gameresult .team';
  var scoreClass = '.score';

  var mapTeam = function(team) {
    if (team === "N.Ireland" || team === "North. Ireland")
      team = "Northern Ireland";
    if (team === "Ireland")
      team = "Republic of Ireland";

    return team;
  }

  return {

    scrap: function(callback) {

      request({
        url: url,
        headers: {
          'User-Agent': fakeUa()
        }
      }, function(e, r, b) {
        if (e)
          return callback(e);
        statusCode = r && r.statusCode
        if (statusCode != 200) {
          return callback(new Error(statusCode))
        }

        b = b.replace(/<(\/?)script/g, '<$1nobreakage');

        $ = cheerio.load(b);

        /**
         * Variables.
         */
        var teamsA = [];
        var teamsB = [];
        var scores = [];
        var scoresPenalty = [];
        var results = [];

        /**
         * Extract data.
         */
        $(mainClass + ' ' + teamsClass).each(function(i, element) {
          var team = mapTeam($(this).html().replace('*', '').trim());
          team = team.substring(team.indexOf('>')+1, team.indexOf(''));
          if (team) {
            if (teamsA.length > teamsB.length) {
              teamsB.push(team);
            } else {
              teamsA.push(team);
            }
          }
        });
        $(mainClass + ' ' + scoreClass).each(function() {
          var score = $(this).html();
          if (score.match(''))
            score = score.substring(score.indexOf('>')+1, score.indexOf(''));
          score = score.trim();
          scoreSplit = score.split('
')
          if (scoreSplit.length > 1) {
            scores.push(scoreSplit[0]);
            scoresPenalty.push(scoreSplit[1].replace('(', '').replace(')', '').trim());
          } else {
            scores.push(score);
            scoresPenalty.push('')
          }
        });

        /**
         * Gather the result in a array of objects.
         */
        for (let i = 0; i < scores.length; i++) {
          let score = scores[i];
          score = [parseInt(score.substring(0,score.indexOf(':'))), parseInt(score.substring(score.indexOf(':')+1,score.length))];

          // add the penalty result to the score
          let scorePenalty = scoresPenalty[i];
          if (scorePenalty) {
            scorePenalty = [parseInt(scorePenalty.substring(0,scorePenalty.indexOf(':'))), parseInt(scorePenalty.substring(scorePenalty.indexOf(':')+1,scorePenalty.length))];
            if (scorePenalty[0] > scorePenalty[1]) {
              score[0] += 1;
            } else {
              score[1] += 1;
            }
          }

          results.push({
              teams  : [teamsA[i], teamsB[i]]
            , score  : score
            // TODO(philmod): detect extra time score.
            , scoreExtraTime : null
            , scorePenalty : scorePenalty || null
          });
        };

        callback(null, results);

      });
    }

  };

};
<|endoftext|>


<commit_before>import { PureComponent } from 'react'
import PropTypes from 'prop-types'
import deburr from 'lodash/deburr'
import sortBy from 'lodash/sortBy'
import isNumber from 'lodash/isNumber'
import defaults from 'lodash/defaults'

export default class Selectable extends PureComponent {
  static propTypes = {
    defaultValue: PropTypes.any,
    onChange: PropTypes.func,
    options: PropTypes.array.isRequired,
    renderer: PropTypes.func.isRequired,
    value: PropTypes.any,
  }

  constructor(props) {
    super(props)

    const sortedOptions = this.sortOptions(this.props.options)

    this.state = {
      focusedElement: null,
      isFocused: false,
      options: sortedOptions,
      search: '',
      selectedOption: null,
      sortedOptions,
      value: this.props.value === undefined
        ? this.props.defaultValue
        : this.props.value,
    }

    this.focusableRefs = {}
  }

  componentDidMount() {
    document.addEventListener('click', this.handleOutsideClick)
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.handleOutsideClick)
  }

  setSearch = search => {
    this.setState({
      options: this.filterOptions({
        options: this.state.sortedOptions,
        search,
      }),
      focusedElement: null,
      search,
    })
  }

  setValue = value => {
    if (this.props.value === undefined) {
      this.setState({
        selectedOption: value == null
          ? null
          : this.props.options.find(option => option.value === value),
        value,
      })
    }

    if (this.props.onChange) {
      this.props.onChange(value)
    }
  }

  setFocused = isFocused => {
    this.setState({
      isFocused,
      focusedElement: null,
    })
  }

  setFocusedElement = (id, options = {}) => {
    defaults(options, {
      scrollToViewport: false,
    })

    if (id == null) {
      this.setState({ focusedElement: null })
      return
    }

    let elementToFocus = id

    if (isNumber(id)) {
      const optionsCount = this.state.options.length

      elementToFocus = id < 0
        ? (optionsCount + id) % optionsCount
        : id % optionsCount
    }

    this.setState({ focusedElement: elementToFocus })

    if (this.overflow && options.scrollToViewport && elementToFocus != null) {
      const node = this.focusableRefs[elementToFocus]
      const viewportInfo = this.isNodeInViewport(node)

      if (!viewportInfo.visibleFromBottom) {
        this.scrollNodeToViewport(node, 'bottom')
      }
      else if (!viewportInfo.visibleFromTop) {
        this.scrollNodeToViewport(node, 'top')
      }
    }
  }

  isNodeInViewport(node) {
    if (!this.overflow.contains(node)) {
      return {
        inViewport: true,
        visibleFromBottom: true,
        visibleFromTop: true,
      }
    }

    const overflow = this.overflow
    const nodeTop = node.offsetTop
    const visibleFromTop = nodeTop >= overflow.scrollTop
    const visibleFromBottom = nodeTop + node.offsetHeight <=
      overflow.scrollTop + overflow.offsetHeight

    return {
      inViewport: visibleFromBottom && visibleFromTop,
      visibleFromBottom,
      visibleFromTop,
    }
  }

  scrollNodeToViewport = (node, fromDirection) => {
    const scrollTop = fromDirection === 'bottom'
      ? node.offsetTop - (this.overflow.offsetHeight - node.offsetHeight)
      : node.offsetTop

    this.overflow.scrollTop = scrollTop
  }

  filterOptions = ({ options, search }) => {
    if (!search.trim()) {
      return options
    }

    const words = deburr(search.trim()).split(/\s+/)
    const pattern = words.map(word => `(?=.*${word})`).join('')
    const regexp = new RegExp(pattern, 'ig')

    return options.filter(option => regexp.test(deburr(option.label)))
  }

  searchMatches = text => {
    const { search } = this.state

    if (!search) {
      return [{
        text,
        match: false,
        fromIndex: 0,
        toIndex: text.length - 1,
      }]
    }

    const pattern = `(${deburr(search.trim()).split(/\s+/).join('|')})`
    const regexp = new RegExp(pattern, 'ig')
    const terms = []
    let currentIndex = 0

    deburr(text).split(regexp).forEach(term => {
      if (term === '') {
        return
      }

      const fromIndex = currentIndex
      const toIndex = currentIndex + term.length
      const termText = text.substring(fromIndex, toIndex)
      const match = !!term.match(regexp)

      currentIndex = toIndex

      terms.push({
        text: termText,
        match,
        fromIndex,
        toIndex,
      })
    })

    return terms
  }

  sortOptions = options => (
    sortBy(options, option => deburr(option.label.toLowerCase()))
  )

  handleOutsideClick = event => {
    if (
      this.state.isFocused &&
      this.container &&
      !this.container.contains(event.target)
      && event.target.parentNode
    ) {
      this.setState({ isFocused: false })
    }
  }

  containerRef = () => (
    container => {
      this.container = container
    }
  )

  focusableRef = id => (
    node => {
      this.focusableRefs[id] = node
    }
  )

  overflowRef = () => (
    overflow => {
      this.overflow = overflow
    }
  )

  render() {
    const { focusedElement, isFocused, options, search, selectedOption, value } = this.state

    return this.props.renderer({
      containerRef: this.containerRef,
      focusableRef: this.focusableRef,
      focusedElement,
      getSearchMatches: this.searchMatches,
      isFocused,
      options,
      overflowRef: this.overflowRef,
      search,
      selectedOption,
      setFocused: this.setFocused,
      setFocusedElement: this.setFocusedElement,
      setSearch: this.setSearch,
      setValue: this.setValue,
      value,
    })
  }
}
<commit_msg>Performance guard clauses<commit_after>import { PureComponent } from 'react'
import PropTypes from 'prop-types'
import deburr from 'lodash/deburr'
import sortBy from 'lodash/sortBy'
import isNumber from 'lodash/isNumber'
import defaults from 'lodash/defaults'

export default class Selectable extends PureComponent {
  static propTypes = {
    defaultValue: PropTypes.any,
    onChange: PropTypes.func,
    options: PropTypes.array.isRequired,
    renderer: PropTypes.func.isRequired,
    value: PropTypes.any,
  }

  constructor(props) {
    super(props)

    const sortedOptions = this.sortOptions(this.props.options)

    this.state = {
      focusedElement: null,
      isFocused: false,
      options: sortedOptions,
      search: '',
      selectedOption: null,
      sortedOptions,
      value: this.props.value === undefined
        ? this.props.defaultValue
        : this.props.value,
    }

    this.focusableRefs = {}
  }

  componentDidMount() {
    document.addEventListener('click', this.handleOutsideClick)
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.handleOutsideClick)
  }

  setSearch = search => {
    if (search === this.state.search) {
      return
    }

    this.setState({
      options: this.filterOptions({
        options: this.state.sortedOptions,
        search,
      }),
      focusedElement: null,
      search,
    })
  }

  setValue = value => {
    if (value === this.state.value) {
      return
    }

    if (this.props.value === undefined) {
      this.setState({
        selectedOption: value == null
          ? null
          : this.props.options.find(option => option.value === value),
        value,
      })
    }

    if (this.props.onChange) {
      this.props.onChange(value)
    }
  }

  setFocused = isFocused => {
    if (isFocused === this.state.isFocused) {
      return
    }

    this.setState({
      isFocused,
      focusedElement: null,
    })
  }

  setFocusedElement = (id, options = {}) => {
    if (this.state.focusedElement === id) {
      return
    }

    defaults(options, {
      scrollToViewport: false,
    })

    if (id == null) {
      this.setState({ focusedElement: null })
      return
    }

    let elementToFocus = id

    if (isNumber(id)) {
      const optionsCount = this.state.options.length

      elementToFocus = id < 0
        ? (optionsCount + id) % optionsCount
        : id % optionsCount
    }

    this.setState({ focusedElement: elementToFocus })

    if (this.overflow && options.scrollToViewport && elementToFocus != null) {
      const node = this.focusableRefs[elementToFocus]
      const viewportInfo = this.isNodeInViewport(node)

      if (!viewportInfo.visibleFromBottom) {
        this.scrollNodeToViewport(node, 'bottom')
      }
      else if (!viewportInfo.visibleFromTop) {
        this.scrollNodeToViewport(node, 'top')
      }
    }
  }

  isNodeInViewport(node) {
    if (!this.overflow.contains(node)) {
      return {
        inViewport: true,
        visibleFromBottom: true,
        visibleFromTop: true,
      }
    }

    const overflow = this.overflow
    const nodeTop = node.offsetTop
    const visibleFromTop = nodeTop >= overflow.scrollTop
    const visibleFromBottom = nodeTop + node.offsetHeight <=
      overflow.scrollTop + overflow.offsetHeight

    return {
      inViewport: visibleFromBottom && visibleFromTop,
      visibleFromBottom,
      visibleFromTop,
    }
  }

  scrollNodeToViewport = (node, fromDirection) => {
    const scrollTop = fromDirection === 'bottom'
      ? node.offsetTop - (this.overflow.offsetHeight - node.offsetHeight)
      : node.offsetTop

    this.overflow.scrollTop = scrollTop
  }

  filterOptions = ({ options, search }) => {
    if (!search.trim()) {
      return options
    }

    const words = deburr(search.trim()).split(/\s+/)
    const pattern = words.map(word => `(?=.*${word})`).join('')
    const regexp = new RegExp(pattern, 'ig')

    return options.filter(option => regexp.test(deburr(option.label)))
  }

  searchMatches = text => {
    const { search } = this.state

    if (!search) {
      return [{
        text,
        match: false,
        fromIndex: 0,
        toIndex: text.length - 1,
      }]
    }

    const pattern = `(${deburr(search.trim()).split(/\s+/).join('|')})`
    const regexp = new RegExp(pattern, 'ig')
    const terms = []
    let currentIndex = 0

    deburr(text).split(regexp).forEach(term => {
      if (term === '') {
        return
      }

      const fromIndex = currentIndex
      const toIndex = currentIndex + term.length
      const termText = text.substring(fromIndex, toIndex)
      const match = !!term.match(regexp)

      currentIndex = toIndex

      terms.push({
        text: termText,
        match,
        fromIndex,
        toIndex,
      })
    })

    return terms
  }

  sortOptions = options => (
    sortBy(options, option => deburr(option.label.toLowerCase()))
  )

  handleOutsideClick = event => {
    if (
      this.state.isFocused &&
      this.container &&
      !this.container.contains(event.target)
      && event.target.parentNode
    ) {
      this.setState({ isFocused: false })
    }
  }

  containerRef = () => (
    container => {
      this.container = container
    }
  )

  focusableRef = id => (
    node => {
      this.focusableRefs[id] = node
    }
  )

  overflowRef = () => (
    overflow => {
      this.overflow = overflow
    }
  )

  render() {
    const { focusedElement, isFocused, options, search, selectedOption, value } = this.state

    return this.props.renderer({
      containerRef: this.containerRef,
      focusableRef: this.focusableRef,
      focusedElement,
      getSearchMatches: this.searchMatches,
      isFocused,
      options,
      overflowRef: this.overflowRef,
      search,
      selectedOption,
      setFocused: this.setFocused,
      setFocusedElement: this.setFocusedElement,
      setSearch: this.setSearch,
      setValue: this.setValue,
      value,
    })
  }
}
<|endoftext|>


<commit_before>$(document).ready(function () {
    /* exercise 1
    $("#Financial_summary_c tr:gt(0) td:gt(0)").addClass("interiorCells");
    $("#Financial_summary_c th").addClass("headers");
    $("#Financial_summary_c tr td:first-child").addClass("headers");
    $("#Financial_summary_c td, th").css("padding", "0px");
    $("#Financial_summary_c .corner").css("visibility", "hidden");
    */
    /*
    var $bigcells = $('#Financial_summary_c td').filter(function () {
    return parseInt($(this).val().replace("$", ""), 10) > 0;
    });

    $("$bigcells").addClass("blueText");
    $("$bigcells").each(function () {
    alert("You got me!");
    });
    */

    //$('#Financial_summary_c tr:even td:not(:first-child)').css("background-color", "purple");

    $('#Financial_summary_c td').hover(function() {
        $(this).parent("tr").css("background-color", "yellow");
    },
        function() {
            $(this).parent("tr").css("background-color", "white");

        }
    );
    //Create total column
	    //Add total column
			$('Totals	').appendTo('#Financial_summary_c tr:eq(0)');
	    $('	').appendTo('#Financial_summary_c tr:gt(0)');

			//Format all the cells
			$("#Financial_summary_c td:last-child").addClass(function() {
				return $(this).prev().attr('class');
			});

			//Drop in totals
			$("#Financial_summary_c tr:gt(0)").each(function() {
				var sum = 0;
				//$(this).children(":not(:last-child)").each(function() {
				$(this).children().not(":first").not(":last").each(function() {
					var temp = 0;
					//sum += parseInt($(this).html().replace(/[^0-9\.-]+/g, "0"), 10);
					temp = parseInt($(this).html().replace(/[^0-9\.-]+/g, ""), 10);
					//temp = parseInt($(this).html().replace(/[^0-9\.-]+/g, 0),10);
					sum = isNaN(temp) ? sum : sum+=temp;
				});
				sum = sum===0 ? "" : "$" + sum;
				$(this).children(":last-child").text(sum);
			});

		var $bigcells = $('#Financial_summary_c td').filter(function () {
    	return parseInt($(this).html().replace(/[^0-9\.\(\)-]+/g, ""), 10) > 0;
    }).css("color", "blue");
});<commit_msg>Ex 3: Cloned the table.<commit_after>$(document).ready(function () {
    /* Exercise 1
	    $("#Financial_summary_c tr:gt(0) td:gt(0)").addClass("interiorCells");
	    $("#Financial_summary_c th").addClass("headers");
	    $("#Financial_summary_c tr td:first-child").addClass("headers");
	    $("#Financial_summary_c td, th").css("padding", "0px");
	    $("#Financial_summary_c .corner").css("visibility", "hidden");
	    */
	    /*
	    var $bigcells = $('#Financial_summary_c td').filter(function () {
	    return parseInt($(this).val().replace("$", ""), 10) > 0;
	    });

	    $("$bigcells").addClass("blueText");
	    $("$bigcells").each(function () {
	    alert("You got me!");
	    });
    */

		//Exercise 2
	    $('#Financial_summary_c td').hover(function() {
	        $(this).parent("tr").css("background-color", "yellow");
	    },
	        function() {
	            $(this).parent("tr").css("background-color", "white");

	        }
	    );

	    //Create total column
		    //Add total column
				$('Totals	').appendTo('#Financial_summary_c tr:eq(0)');
		    $('	').appendTo('#Financial_summary_c tr:gt(0)');

				//Format all the cells
				$("#Financial_summary_c td:last-child, th:last-child").addClass(function() {
					return $(this).prev().attr('class');
				});

				//Drop in totals
				$("#Financial_summary_c tr:gt(0)").each(function() {
					var sum = 0;
					//$(this).children(":not(:last-child)").each(function() {
					$(this).children().not(":first").not(":last").each(function() {
						var temp = 0;
						//sum += parseInt($(this).html().replace(/[^0-9\.-]+/g, "0"), 10);
						temp = parseInt($(this).html().replace(/[^0-9\.-]+/g, ""), 10);
						//temp = parseInt($(this).html().replace(/[^0-9\.-]+/g, 0),10);
						sum = isNaN(temp) ? sum : sum+=temp;
					});
					sum = sum===0 ? "" : "$" + sum;
					$(this).children(":last-child").text(sum);
				});

			var $bigcells = $('#Financial_summary_c td').filter(function () {
	    	return parseInt($(this).html().replace(/[^0-9\.\(\)-]+/g, ""), 10) > 0;
	   	}).css("color", "blue");

	  //Exercise 3
			$("#Financial_summary_c").parents("div").append($("#Financial_summary_c").clone());
			$("table").not("#Financial_summary_c:first").attr("id","ratios");
			$("#ratios td").css("background-color","red");
});
<|endoftext|>


<commit_before>({
    appDir: '.',
    baseUrl: 'src',
    mainConfigFile: 'src/require-config.js',
    findNestedDependencies: true,
    // doesn't handle plugin resources
    removeCombined: true,
    dir: '_build',
    skipDirOptimize: true,
    optimize: 'uglify2',
    generateSourceMaps: true,
    preserveLicenseComments: false,
    // Everything to do with CSS is handled by the require-css plugin
    optimizeCss: 'none',
    inlineText: true,
    stubModules: [
        'text',
        'tpl',
        'css',
        'json',
        'less'
    ],
    pragmasOnSave: {
        excludeRequireCss: true,
        excludeTpl: true
    }
})
<commit_msg>don't generate source maps<commit_after>({
    appDir: '.',
    baseUrl: 'src',
    mainConfigFile: 'src/require-config.js',
    findNestedDependencies: true,
    // doesn't handle plugin resources
    removeCombined: true,
    dir: '_build',
    skipDirOptimize: true,
    optimize: 'uglify2',
    preserveLicenseComments: false,
    // Everything to do with CSS is handled by the require-css plugin
    optimizeCss: 'none',
    inlineText: true,
    stubModules: [
        'text',
        'tpl',
        'css',
        'json',
        'less'
    ],
    pragmasOnSave: {
        excludeRequireCss: true,
        excludeTpl: true
    }
})
<|endoftext|>


<commit_before>var express = require('express');
var app = module.exports = express();

var r = require('rethinkdb'),
        util = require('util'),
        assert = require('assert');
var _ = require('underscore');
var http = require("http");
var async = require("async");

// disable all template engines
app.engine('.html', require('ejs').__express);
app.set("views", __dirname + '/../views/');
app.set('view engine', 'html');
app.locals.$ = require('native-view-helpers');

var connection = null;
r.connect( {host: 'localhost', port: 28015}, function(err, conn) {
    if (err) throw err;
    connection = conn;

    r.db('datsound').tableList().run(connection, function(err, result) {
        if(!_.contains(result, 'youtube')) {
            r.db('datsound').tableCreate('youtube').run(connection, function(err, result) {
                if (err) throw err;
                console.log(JSON.stringify(result, null, 2));
            });
        }
    });

});

// List of youtube channel to scrape
var channels = ['majesticcasual',
                'thvbgd',
                'thesoundyouneed1',
                'MrRevillz',
                'SelectedBase',
                'HumanprofityCasual',
                'DelicieuseMusique',
                'FhinqMusic',
                'soundisstyle',
                'LaBelleChannel'];

app.get('/scrape', function(req, res) {

    var rdata = [];

    async.each(channels, function(channel, callback) {
        console.log('Processing channel ' + channel);
        async.parallel({
            youtubedb: function(callback) {
                r.db('datsound')
                 .table('youtube')
                 .filter({'channel': channel})
                 .count().run(connection, function(err, result) {
                    callback(null, result);
                });
            },
            timestamp: function(callback) {
                r.db('datsound')
                 .table('scraping')
                 .filter({'channel': channel})
                 .orderBy(r.desc('datetime')).run(connection, function(err, result) {
                    if(result && result[0]) {
                        callback(null, result[0].datetime);
                    } else {
                        callback(null);
                    }
                });
            }
        }, function(err, results) {
            rdata.push({
                name: channel,
                count: results.youtubedb,
                timestamp: results.timestamp
            });
            callback();
        });
    }, function(err) {
        // if any of the saves produced an error, err would equal that error
        if( err ) {
            // One of the iterations produced an error.
            // All processing will now stop.
            console.log('A channel failed to process.');
        } else {
            console.log('All channels have been processed successfully.');
            res.render('scrape', { channels: rdata });
        }
    });

});

app.get('/scrape/:uid', function(req, res) {
    if(_.contains(channels, req.params.uid)) {
        scrapeYouTube('http://gdata.youtube.com/feeds/api/users/' + req.params.uid + '/uploads?v=2&alt=json&max-results=50&start-index=1', req.params.uid);
    }
    function scrapeYouTube(startIndex, channelId) {
        console.log('Starting to scrape some dataz for', channelId);
        var url = startIndex;
        var db = r.db('datsound').table('youtube');
        http.get(url, function(res) {
            var body = '';
            res.on('data', function(chunk) {
                body += chunk;
            });

            res.on('end', function() {
                var data = JSON.parse(body);
                var song = [];

                // TODO: check if already in db, then go scraping
                async.each(data.feed.entry, function(element, callback) {
                    var thumbnails = [];
                    // console.log(element.media$group.yt$videoid.$t);
                    db.getAll(element.media$group.yt$videoid.$t, {index:'ytid'})
                      .count()
                      .run(connection, function(err, result) {
                        if(result === 0) {
                            // console.log('THIS SONG IS NOT ADDED, ADD IT NOW!', element.media$group.yt$videoid.$t);

                            async.each(element.media$group.media$thumbnail, function(thumbnail, callback) {
                                 thumbnails.push({
                                    url: thumbnail.url,
                                    name: thumbnail.yt$name,
                                });
                                callback();
                            }, function(err) {
                                if( err ) {
                                    console.log('Thumbnails for ',
                                                element.media$group.yt$videoid.$t,
                                                'failed to process successfully.');
                                } else {
                                    console.log('Thumbnails for ',
                                                element.media$group.yt$videoid.$t,
                                                'processed successfully.');
                                    song.push({
                                        channel: channelId,
                                        ytid: element.media$group.yt$videoid.$t,
                                        title: element.title.$t,
                                        description: element.media$group.media$description$t,
                                        thumbnails: thumbnails,
                                        uploaded: element.media$group.yt$uploaded.$t,
                                        duration: element.media$group.yt$duration.seconds,
                                        // disliked: element.yt$rating['numDislikes'],
                                        // likes: element.yt$rating['numLikes'],
                                        // ratingAvg: element.gd$rating['average'],
                                        views: element.yt$statistics.viewCount
                                    });
                                }
                            });

                        }
                        callback();
                    });

                }, function(err) {
                    if( err ) {
                        console.log('Current set failed to process.');
                    } else {
                        console.log('Current set was processed successfully.');
                        // console.log(song);
                        db.insert(song)
                          .run(connection, function(err, result) {
                            if (err) throw err;
                            console.log(JSON.stringify(result, null, 2));
                        });
                    }
                });

                if(data.feed.link[7].rel === 'next') {
                    console.log(data.feed.link[7].href);
                    scrapeYouTube(data.feed.link[7].href, channelId);
                }
                else if(data.feed.link[8]) {
                    if(data.feed.link[8].rel === 'next') {
                        console.log(data.feed.link[8].href);
                        scrapeYouTube(data.feed.link[8].href, channelId);
                    }
                } else {
                    var scrape = [{
                                channel: channelId,
                                datetime: new Date()
                            }];

                    r.db('datsound').table('scraping').insert(scrape)
                      .run(connection, function(err, result) {
                        if (err) throw err;
                        // console.log(JSON.stringify(result, null, 2));
                        console.log('Scraping finished.');
                    });
                }

            });
        }).on('error', function(e) {
              console.log("Got error: ", e);
        });
    }
    var body = 'Scraping ' + req.params.uid;
    res.setHeader('Content-Type', 'text/plain');
    res.setHeader('Content-Length', Buffer.byteLength(body));
    // res.end(body);
    res.redirect('/scrape');
});

app.get('/scrape/delete/:uid', function(req, res) {
    console.log(req.params.uid);
    if(_.contains(channels, req.params.uid)) {
        r.db('datsound')
         .table('youtube')
         .filter({'channel': req.params.uid})
         .delete()
         .run(connection, function(err, result) {
            console.log('Deleted ', req.params.uid, ' entries.');
        });
    }
    res.redirect('/scrape');
});
<commit_msg>table change<commit_after>var express = require('express');
var app = module.exports = express();

var r = require('rethinkdb'),
        util = require('util'),
        assert = require('assert');
var _ = require('underscore');
var http = require("http");
var async = require("async");

// disable all template engines
app.engine('.html', require('ejs').__express);
app.set("views", __dirname + '/../views/');
app.set('view engine', 'html');
app.locals.$ = require('native-view-helpers');

var connection = null;
r.connect( {host: 'localhost', port: 28015}, function(err, conn) {
    if (err) throw err;
    connection = conn;

    r.db('datsound').tableList().run(connection, function(err, result) {
        if(!_.contains(result, 'scraping')) {
            r.db('datsound').tableCreate('scraping').run(connection, function(err, result) {
                if (err) throw err;
                console.log(JSON.stringify(result, null, 2));
            });
        }
    });

});

// List of youtube channel to scrape
var channels = ['majesticcasual',
                'thvbgd',
                'thesoundyouneed1',
                'MrRevillz',
                'SelectedBase',
                'HumanprofityCasual',
                'DelicieuseMusique',
                'FhinqMusic',
                'soundisstyle',
                'LaBelleChannel'];

app.get('/scrape', function(req, res) {

    var rdata = [];

    async.each(channels, function(channel, callback) {
        console.log('Processing channel ' + channel);
        async.parallel({
            youtubedb: function(callback) {
                r.db('datsound')
                 .table('youtube')
                 .filter({'channel': channel})
                 .count().run(connection, function(err, result) {
                    callback(null, result);
                });
            },
            timestamp: function(callback) {
                r.db('datsound')
                 .table('scraping')
                 .filter({'channel': channel})
                 .orderBy(r.desc('datetime')).run(connection, function(err, result) {
                    if(result && result[0]) {
                        callback(null, result[0].datetime);
                    } else {
                        callback(null);
                    }
                });
            }
        }, function(err, results) {
            rdata.push({
                name: channel,
                count: results.youtubedb,
                timestamp: results.timestamp
            });
            callback();
        });
    }, function(err) {
        // if any of the saves produced an error, err would equal that error
        if( err ) {
            // One of the iterations produced an error.
            // All processing will now stop.
            console.log('A channel failed to process.');
        } else {
            console.log('All channels have been processed successfully.');
            res.render('scrape', { channels: rdata });
        }
    });

});

app.get('/scrape/:uid', function(req, res) {
    if(_.contains(channels, req.params.uid)) {
        scrapeYouTube('http://gdata.youtube.com/feeds/api/users/' + req.params.uid + '/uploads?v=2&alt=json&max-results=50&start-index=1', req.params.uid);
    }
    function scrapeYouTube(startIndex, channelId) {
        console.log('Starting to scrape some dataz for', channelId);
        var url = startIndex;
        var db = r.db('datsound').table('youtube');
        http.get(url, function(res) {
            var body = '';
            res.on('data', function(chunk) {
                body += chunk;
            });

            res.on('end', function() {
                var data = JSON.parse(body);
                var song = [];

                // TODO: check if already in db, then go scraping
                async.each(data.feed.entry, function(element, callback) {
                    var thumbnails = [];
                    // console.log(element.media$group.yt$videoid.$t);
                    db.getAll(element.media$group.yt$videoid.$t, {index:'ytid'})
                      .count()
                      .run(connection, function(err, result) {
                        if(result === 0) {
                            // console.log('THIS SONG IS NOT ADDED, ADD IT NOW!', element.media$group.yt$videoid.$t);

                            async.each(element.media$group.media$thumbnail, function(thumbnail, callback) {
                                 thumbnails.push({
                                    url: thumbnail.url,
                                    name: thumbnail.yt$name,
                                });
                                callback();
                            }, function(err) {
                                if( err ) {
                                    console.log('Thumbnails for ',
                                                element.media$group.yt$videoid.$t,
                                                'failed to process successfully.');
                                } else {
                                    console.log('Thumbnails for ',
                                                element.media$group.yt$videoid.$t,
                                                'processed successfully.');
                                    song.push({
                                        channel: channelId,
                                        ytid: element.media$group.yt$videoid.$t,
                                        title: element.title.$t,
                                        description: element.media$group.media$description$t,
                                        thumbnails: thumbnails,
                                        uploaded: element.media$group.yt$uploaded.$t,
                                        duration: element.media$group.yt$duration.seconds,
                                        // disliked: element.yt$rating['numDislikes'],
                                        // likes: element.yt$rating['numLikes'],
                                        // ratingAvg: element.gd$rating['average'],
                                        views: element.yt$statistics.viewCount
                                    });
                                }
                            });

                        }
                        callback();
                    });

                }, function(err) {
                    if( err ) {
                        console.log('Current set failed to process.');
                    } else {
                        console.log('Current set was processed successfully.');
                        // console.log(song);
                        db.insert(song)
                          .run(connection, function(err, result) {
                            if (err) throw err;
                            console.log(JSON.stringify(result, null, 2));
                        });
                    }
                });

                if(data.feed.link[7].rel === 'next') {
                    console.log(data.feed.link[7].href);
                    scrapeYouTube(data.feed.link[7].href, channelId);
                }
                else if(data.feed.link[8]) {
                    if(data.feed.link[8].rel === 'next') {
                        console.log(data.feed.link[8].href);
                        scrapeYouTube(data.feed.link[8].href, channelId);
                    }
                } else {
                    var scrape = [{
                                channel: channelId,
                                datetime: new Date()
                            }];

                    r.db('datsound').table('scraping').insert(scrape)
                      .run(connection, function(err, result) {
                        if (err) throw err;
                        // console.log(JSON.stringify(result, null, 2));
                        console.log('Scraping finished.');
                    });
                }

            });
        }).on('error', function(e) {
              console.log("Got error: ", e);
        });
    }
    var body = 'Scraping ' + req.params.uid;
    res.setHeader('Content-Type', 'text/plain');
    res.setHeader('Content-Length', Buffer.byteLength(body));
    // res.end(body);
    res.redirect('/scrape');
});

app.get('/scrape/delete/:uid', function(req, res) {
    console.log(req.params.uid);
    if(_.contains(channels, req.params.uid)) {
        r.db('datsound')
         .table('youtube')
         .filter({'channel': req.params.uid})
         .delete()
         .run(connection, function(err, result) {
            console.log('Deleted ', req.params.uid, ' entries.');
        });
    }
    res.redirect('/scrape');
});
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';

const baseUrl = typeof process.env.BASE_URL !== 'undefined' ?
  process.env.BASE_URL : 'https://udacity-api.herokuapp.com/';

function Html({ content, state, scriptHash, cssHash }) {
  return (

        <meta charSet="UTF-8" />
        <meta httpEquiv="Content-Language" content="en" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <title>Udacity Alumni</title>
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,300,700|Raleway:400,300,700|Lato:400,300,700" rel="stylesheet" type="text/css" />
        <link href={`${baseUrl}main.${scriptHash}.js`} rel="stylesheet" />


<commit_before>var global = global || this;

function MODEL(m) {
  global[m.name] = m;
  // Insert magic here
}

MODEL({
  name: 'FProto',
  extends: null

  methods: [
    {
      name: 'create',
      code: function() { return { __proto__: this, instance_: {} } },
    },
    {
      name: 'toString',
      code: function() { return 'FProto' + this.model_.name; }
    }
  ]
});

MODEL({
  name: 'FObject',
  extends: 'FProto',

  properties: [
  ],

  methods: [
    {
      name: 'toString',
      code: function() { return this.model_.name; }
    }
  ],

  axioms: [
  ]
});

MODEL({
  name: 'Model',

  properties: [
    {
      name: 'name'
    },
    {
      name: 'extends',
      defaultValue: 'FObject'
    },
    {
      type: 'Array',
      subType: 'Property',
      name: 'properties'
    },
    {
      type: 'Array',
      subType: 'Method',
      name: 'methods',
      adaptElement: function(e) {
        if ( typeof e === 'function' ) {
          console.assert(e.name, 'Method must be named');
          return Method.create({name: e.name, code: e});
        }
        return e;
      }
    },
    {
      name: 'proto',
      // TODO: replace with lazyFactory
      factory: function() {
        return {
          __proto__: FProto,
          model_: this
        }
      }
    }
  ],

  methods: [
    /*
    {
      name: 'createPrototype',
      code: function() {

      }
    }
    */
  ]
});

MODEL({
  name: 'Property',

  properties: [
    {
      name: 'type'
    },
    {
      name: 'name'
    },
    {
      name: 'defaultValue'
    },
    {
      name: 'factory'
    },
    {
      name: 'preSet'
    }
  ],

  methods: [
    {
      name: 'installInModel',
      function(model) {
        model[constantize(this.name)] = this;
      }
    },
    {
      name: 'installInProto',
      function() {
        // TODO:
      }
    }
  ]
});

MODEL({
  name: 'Method',

  properties: [
    {
      name: 'name'
    },
    {
      name: 'code'
    }
  ],

  methods: [
    {
      name: 'installInProto',
      function(proto) {
        proto[this.name] = this.code;
      }
    }
  ]
});

MODEL({
  name: 'Constant',

  properties: [
    {
      name: 'name'
    },
    {
      name: 'value'
    }
  ],

  methods: [
    {
      name: 'installInModel',
      function(model) {
        model[constantize(this.name)] = this.value;
      }
    },
    {
      name: 'installInProto',
      function(proto) {
        this.installInModel(proto);
      }
    }
  ]
});

MODEL({
  name: 'StringProperty',
  extends: 'Property',

  properties: [
    {
      name: 'defaultValue',
      defaultValue: ''
    },
    {
      name: 'preSet',
      defaultValue: function(_, a) {
        return a ? a.toString() : '';
      }
    }
  ]
});

MODEL({
  name: 'ArrayProperty',
  extends: 'Property',

  properties: [
    {
      name: 'factory',
      defaultValue: function() { return []; }
    },
    {
      name: 'subType'
    },
    {
      name: 'preSet',
      defaultValue: function(_, a) {
        return a.map(function() { return global[this.subType].create(a); });
      }
    },
    {
      name: 'adaptElement'
    },
    {
      name: 'adapt',
      defaultValue: function(a) {
        if ( ! a ) return [];
        return a.map(this.adaptElement);
      }
    }
  ]
});

/*
  create: create object then update
  remote create from regular objects or remove from prototypes
  acreate or afromJSON
*/
<commit_msg>FO3 work.<commit_after>var global = global || this;

function MODEL(m) {
  global[m.name] = m;
  // Insert magic here
}

MODEL({
  name: 'FProto',
  extends: null

  methods: [
    {
      name: 'create',
      code: function() { return { __proto__: this, instance_: {} } },
    },
    {
      name: 'toString',
      code: function() { return 'FProto' + this.model_.name; }
    }
  ]
});

MODEL({
  name: 'FObject',
  extends: 'FProto',

  properties: [
  ],

  methods: [
    {
      name: 'toString',
      code: function() { return this.model_.name; }
    }
  ],

  axioms: [
  ]
});

MODEL({
  name: 'Model',

  properties: [
    {
      name: 'name'
    },
    {
      name: 'extends',
      defaultValue: 'FObject'
    },
    {
      type: 'Array',
      subType: 'Property',
      name: 'properties'
    },
    {
      type: 'Array',
      subType: 'Method',
      name: 'methods',
      adaptElement: function(e) {
        if ( typeof e === 'function' ) {
          console.assert(e.name, 'Method must be named');
          return Method.create({name: e.name, code: e});
        }
        return e;
      }
    },
    {
      name: 'proto',
      // TODO: replace with lazyFactory
      factory: function() {
        return {
          __proto__: FProto,
          model_: this
        }
      }
    }
  ],

  methods: [
    /*
    {
      name: 'createPrototype',
      code: function() {

      }
    }
    */
  ]
});

MODEL({
  name: 'Property',

  properties: [
    {
      name: 'type'
    },
    {
      name: 'name'
    },
    {
      name: 'defaultValue'
    },
    {
      name: 'factory'
    },
    {
      name: 'preSet'
    }
  ],

  methods: [
    {
      name: 'installInModel',
      function(model) {
        model[constantize(this.name)] = this;
      }
    },
    {
      name: 'installInProto',
      function(proto) {
        this.installInModel(proto);

        var name            = prop.name;
        var slotName        = name + '$';
        var adapt           = this.adapt
        var preSet          = this.preSet;
        var postSet         = this.postSet;
        var getter          = this.getter;
        var setter          = this.setter;
        var factory         = this.factory;
        var hasDefaultValue = this.hasOwnProperty('defaultValue');
        var defaultValue    = this.defaultValue;

        /* Future
        Object.defineProperty(proto, slotName, {
          get: function propSlotGetter() {
            return this.getSlot(name);
          },
          set: function propSlotSetter(value) {
            value.link.link(this.getSlot(name));
          },
          configurable: true
        });
        */

        Object.defineProperty(proto, name, {
          get: function propGetter() {
            if ( getter ) return getter.call(this);

            if ( ( hasDefaultValue || factory ) &&
                 ! this.instance_.hasOwnProperty(name) )
            {
              if ( hasDefaultValue ) return defaultValue;

              var value = factory.call(this);
              this.instance_[name] = value;
              return value;
            }

            return this.instance_[name];
          },
          set: function propSetter(newValue) {
            if ( setter ) {
              setter.call(this, newValue);
              return;
            }

            // TODO: add logic to not trigger factory
            var oldValue = this[name];

            if ( adapt )  newValue = adapt.call(this, oldValue, newValue);

            if ( preSet ) newValue = preSet.call(this, oldValue, newValue);

            this.instance_[name] = newValue;

            // TODO: fire property change event

            // TODO: call global setter

            if ( postSet ) postSet.call(this, oldValue, newValue);
          },
          configurable: true
        });
      }
    }
  ]
});

MODEL({
  name: 'Method',

  properties: [
    {
      name: 'name'
    },
    {
      name: 'code'
    }
  ],

  methods: [
    {
      name: 'installInProto',
      function(proto) {
        proto[this.name] = this.code;
      }
    }
  ]
});

MODEL({
  name: 'Constant',

  properties: [
    {
      name: 'name'
    },
    {
      name: 'value'
    }
  ],

  methods: [
    {
      name: 'installInModel',
      function(model) {
        model[constantize(this.name)] = this.value;
      }
    },
    {
      name: 'installInProto',
      function(proto) {
        this.installInModel(proto);
      }
    }
  ]
});

MODEL({
  name: 'StringProperty',
  extends: 'Property',

  properties: [
    {
      name: 'defaultValue',
      defaultValue: ''
    },
    {
      name: 'preSet',
      defaultValue: function(_, a) {
        return a ? a.toString() : '';
      }
    }
  ]
});

MODEL({
  name: 'ArrayProperty',
  extends: 'Property',

  properties: [
    {
      name: 'factory',
      defaultValue: function() { return []; }
    },
    {
      name: 'subType'
    },
    {
      name: 'preSet',
      defaultValue: function(_, a) {
        return a.map(function() { return global[this.subType].create(a); });
      }
    },
    {
      name: 'adaptElement'
    },
    {
      name: 'adapt',
      defaultValue: function(a) {
        if ( ! a ) return [];
        return a.map(this.adaptElement);
      }
    }
  ]
});

/*
  create: create object then update
  remote create from regular objects or remove from prototypes
  acreate or afromJSON
*/
<|endoftext|>


<commit_before>'use strict';

describe("geoNames service", function() {
    beforeEach(function(){
        module('geoNamesAPI');
    });

    var service, httpBackend, geonames;

    beforeEach(inject(function($injector){
        service = $injector.get('geodataservice');
        httpBackend = $injector.get('$httpBackend');
    }));

    it('should return a list of countries', function(){
        httpBackend.when('GET', 'http://api.geonames.org/countryInfoJSON?username=davelmer').respond(
          { geonames:[
              'areaInSqKm':'468.0',
              'capital':'Andorra la Vella',
              'continent':'EU',
              'continentName':'Europe',
              'countryCode':'AD',
              'countryName':'Andorra',
              'currencyCode':'EUR',
              'east':'1.7865427778319827',
              'fipsCode':'AN',
              'geonameId':'3041565',
              'isoAlpha3':'AND',
              'isoNumeric':'020',
              'languages':'ca',
              'north':'42.65604389629997',
              'population':'84000',
              'south':'42.42849259876837',
              'west':'1.4071867141112762'
        ]);

        service.geoCountries.then(function(response){
          expect(response.data.length).toBe(1);
        })
    });
});

/*describe('Unit Tests: geoNames Dataservice', function() {
    beforeEach(module('geoNamesAPI.geodataservice'));

    var geoFactory, httpMock, geonames;

    beforeEach(inject(function($httpBackend, geoCountriesService){
      httpMock = $httpBackend;
      httpMock.when('GET', 'http://api.geonames.org/countryInfoJSON?username=davelmer').respond(
        geonames=[];
        geonames[0]={};
        'areaInSqKm='468.0';
        'capital='Andorra la Vella';
        'continent='EU';
        'continentName='Europe';
        'countryCode='AD';
        'countryName='Andorra';
        'currencyCode='EUR';
        'east='1.7865427778319827';
        'fipsCode='AN';
        'geonameId='3041565';
        'isoAlpha3='AND';
        'isoNumeric='020';
        'languages='ca';
        'north='42.65604389629997';
        'population='84000';
        'south='42.42849259876837';
        'west='1.4071867141112762';
      );

      geoFactory = geoCountriesService;
    }));

    var countriesList;

    it('should retrieve the countries list', function(){
      console.log(geoFactory);
    });
});*/
<commit_msg>going over unit testing with david<commit_after>'use strict';

describe("geoNames service", function() {
    beforeEach(function(){
        module('geoNamesAPI');
    });

    var service, httpBackend, geonames;

    beforeEach(inject(function($injector, _geodataservice_){
        service = $injector.get('geodataservice');
        httpBackend = $injector.get('$httpBackend');
    }));

    it('should return a list of countries', function(){
      var responseData = {
        data:{
            'areaInSqKm':'468.0',
            'capital':'Andorra la Vella',
            'continent':'EU',
            'continentName':'Europe',
            'countryCode':'AD',
            'countryName':'Andorra',
            'currencyCode':'EUR',
            'east':'1.7865427778319827',
            'fipsCode':'AN',
            'geonameId':'3041565',
            'isoAlpha3':'AND',
            'isoNumeric':'020',
            'languages':'ca',
            'north':'42.65604389629997',
            'population':'84000',
            'south':'42.42849259876837',
            'west':'1.4071867141112762'
        }
      };
      httpBackend.when('GET', 'http://api.geonames.org/countryInfoJSON?username=davelmer').respond(responseData);
      service.geoCountries();
      httpBackend.flush();
      expect(service.countries).toEqual(responseData);
    });

    it('should fail gracefully', function(){
      var responseData = {
        data: { description: 'my description' }
      };
      httpBackend.when('GET', 'http://api.geonames.org/countryInfoJSON?username=davelmer').respond(500, responseData);
      service.geoCountries();
      httpBackend.flush();
    });
});

/*describe('Unit Tests: geoNames Dataservice', function() {
    beforeEach(module('geoNamesAPI.geodataservice'));

    var geoFactory, httpMock, geonames;

    beforeEach(inject(function($httpBackend, geoCountriesService){
      httpMock = $httpBackend;
      httpMock.when('GET', 'http://api.geonames.org/countryInfoJSON?username=davelmer').respond(
        geonames=[];
        geonames[0]={};
        'areaInSqKm='468.0';
        'capital='Andorra la Vella';
        'continent='EU';
        'continentName='Europe';
        'countryCode='AD';
        'countryName='Andorra';
        'currencyCode='EUR';
        'east='1.7865427778319827';
        'fipsCode='AN';
        'geonameId='3041565';
        'isoAlpha3='AND';
        'isoNumeric='020';
        'languages='ca';
        'north='42.65604389629997';
        'population='84000';
        'south='42.42849259876837';
        'west='1.4071867141112762';
      );

      geoFactory = geoCountriesService;
    }));

    var countriesList;

    it('should retrieve the countries list', function(){
      console.log(geoFactory);
    });
});*/
<|endoftext|>


<commit_before>import fs from 'fs'
import path from 'path'
import grpc from 'grpc'
import config from '../config'

const lightning = (rpcpath, host) => {
  const lndCert = fs.readFileSync(config.cert)
  const credentials = grpc.credentials.createSsl(lndCert)
  const rpc = grpc.load(path.join(__dirname, 'rpc.proto'))

  return new rpc.lnrpc.Lightning(host, credentials)
}

export default lightning
<commit_msg>fix(ssl-handshake): update list of supported cipher suites<commit_after>import fs from 'fs'
import path from 'path'
import grpc from 'grpc'
import config from '../config'

// Default is ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384
// https://github.com/grpc/grpc/blob/master/doc/environment_variables.md
//
// Current LND cipher suites here:
// https://github.com/lightningnetwork/lnd/blob/master/lnd.go#L80
//
// We order the suites by priority, based on the recommendations provided by SSL Labs here:
// https://github.com/ssllabs/research/wiki/SSL-and-TLS-Deployment-Best-Practices#23-use-secure-cipher-suites
process.env.GRPC_SSL_CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES || [
  'ECDHE-ECDSA-AES128-GCM-SHA256',
  'ECDHE-ECDSA-AES256-GCM-SHA384',
  'ECDHE-ECDSA-AES128-CBC-SHA256',
  'ECDHE-ECDSA-CHACHA20-POLY1305'
].join(':')

const lightning = (rpcpath, host) => {
  const lndCert = fs.readFileSync(config.cert)
  const credentials = grpc.credentials.createSsl(lndCert)
  const rpc = grpc.load(path.join(__dirname, 'rpc.proto'))

  return new rpc.lnrpc.Lightning(host, credentials)
}

export default lightning
<|endoftext|>