<commit_before>import React from 'react'
import styled, { css } from 'styled-components'
import {
  Flex,
  Box,
  Heading,
  Text,
  Link as A,
  Container,
  hexa,
  theme
} from '@hackclub/design-system'
import Icon from '@hackclub/icons'
import Link from 'gatsby-link'

const Base = styled(Box.withComponent('footer'))`
  background: ${({ theme, dark }) =>
    dark
      ? `${theme.colors.darker} radial-gradient(${hexa(
          theme.colors.black,
          0.5
        )} 1px, transparent 1px)`
      : `${theme.colors.snow} url('/pattern.svg') repeat`};
  ${props =>
    props.dark &&
    css`
      background-size: ${theme.space[4]}px ${theme.space[4]}px;
      h2 {
        color: ${theme.colors.gray[4]};
      }
      ${BottomLine} {
        border-color: ${theme.colors.black};
      }
    `} @media print {
    display: none;
  }
`

const Columns = styled(Container)`
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: ${theme.space[2]}px;

  ${theme.mediaQueries.md} {
    grid-gap: ${theme.space[4]}px;
    grid-template-columns: repeat(4, 1fr);
  }
`
const SocialColumn = styled(Box)``

const Services = styled(Flex)`
  a {
    line-height: 0;
  }
  svg {
    fill: currentColor;
    width: 32px;
    height: 32px;
  }
  ${theme.mediaQueries.md} {
    max-width: 12rem;
  }
`
Services.defaultProps = {
  align: 'center',
  mb: 3,
  wrap: true
}

const Service = ({ href, icon, ...props }) => (
  <A
    target="_blank"
    rel="noopener"
    href={href}
    mr={2}
    mb={2}
    color="muted"
    aria-label={`hack club on ${icon}`}
    children={<Icon glyph={icon} />}
    {...props}
  />
)

const Pages = styled(Box)`
  a {
    display: block;
    color: inherit;
    margin-bottom: ${theme.space[2]}px;
  }
`

const BottomLine = styled(Box)`
  border-top: 1px solid ${theme.colors.smoke};
`

const Footer = ({ dark = false, children, ...props }) => (
  <Base
    color={dark ? 'muted' : 'slate'}
    py={[4, 5]}
    dark={dark}
    align="left"
    {...props}
  >
    {children}
    <Columns px={3}>
      <Box>
        <Heading.h2 f={3} mb={3}>
          Hack Club
        </Heading.h2>
        <Pages>
          {/* <Link to="/" children="Home" /> */}
          <Link to="/donate" children="Donate" />
          <Link to="/team" children="Team" />
          <Link to="/updates" children="Updates" />
          <Link to="/hackers" children="Hackers" />
          <Link to="/philosophy" children="Philosophy" />
        </Pages>
      </Box>
      <Box>
        <Heading.h2 f={3} mb={3}>
          For Clubs
        </Heading.h2>
        <Pages>
          <Link to="/start" children="Start" />
          <Link to="/apply" children="Apply" />
          <Link to="/challenge" children="Challenge" />
          <Link to="/workshops" children="Workshops" />

        </Pages>
      </Box>
      <Box>
        <Heading.h2 f={3} mb={3}>
          Resources
        </Heading.h2>
        <Pages>

          <Link to="/bank" children="Bank" />
          <Link to="/night" children="Hack Night" />
        </Pages>
      </Box>
      <Box>
        <Heading.h2 f={3} mb={3}>
          Join the Club
        </Heading.h2>
        <Services>
          <Service href="/slack_invite" icon="slack" />
          <Service href="https://twitter.com/hackclub" icon="twitter" />
          <Service href="https://github.com/hackclub" icon="github" />
          <Service
            href="https://www.facebook.com/Hack-Club-741805665870458"
            icon="facebook"
          />
          <Service href="https://medium.com/hackclub" icon="medium" />
          <Service
            href="https://www.youtube.com/channel/UCQzO0jpcRkP-9eWKMpJyB0w"
            icon="youtube"
          />
          <Service
            href="https://www.instagram.com/starthackclub"
            icon="instagram"
          />
          <Service href="mailto:team@hackclub.com" icon="email" />
        </Services>
        <Text my={2}>
          1-855-625-HACK

          <Text.span color="muted" children="(call toll-free)" />
        </Text>
      </Box>
    </Columns>
    <Container px={3} mt={[3, 4]}>
      <Box f={2}>
        <Text>Office: 576 Natoma St, San Francisco, CA 94103</Text>
        <Text>Mail: 8605 Santa Monica Blvd #86294, Los Angeles, CA 90069</Text>
      </Box>
      <BottomLine mt={3}>
        <Text f={1} mt={2} color="muted">
          © {new Date().getFullYear()} Hack Club. Nonprofit EIN: 81-2908499.
        </Text>
      </BottomLine>
    </Container>
  </Base>
)

export default Footer
<commit_msg>Fix Footer<commit_after>import React from 'react'
import styled, { css } from 'styled-components'
import {
  Flex,
  Box,
  Heading,
  Text,
  Link as A,
  Container,
  hexa,
  theme
} from '@hackclub/design-system'
import Icon from '@hackclub/icons'
import Link from 'gatsby-link'

const Base = styled(Box.withComponent('footer'))`
  background: ${props =>
    props.dark
      ? `${theme.colors.darker} radial-gradient(${hexa(
          theme.colors.black,
          0.5
        )} 1px, transparent 1px)`
      : `${theme.colors.snow} url('/pattern.svg') repeat`};
  ${props =>
    props.dark &&
    css`
      background-size: ${theme.space[4]}px ${theme.space[4]}px;
      h2 {
        color: ${theme.colors.gray[4]};
      }
      ${BottomLine} {
        border-color: ${theme.colors.black};
      }
    `} @media print {
    display: none;
  }
`

const Columns = styled(Container)`
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: ${theme.space[2]}px;

  ${theme.mediaQueries.md} {
    grid-gap: ${theme.space[4]}px;
    grid-template-columns: repeat(4, 1fr);
  }
`
const SocialColumn = styled(Box)``

const Services = styled(Flex)`
  a {
    line-height: 0;
  }
  svg {
    fill: currentColor;
    width: 32px;
    height: 32px;
  }
  ${theme.mediaQueries.md} {
    max-width: 12rem;
  }
`
Services.defaultProps = {
  align: 'center',
  mb: 3,
  wrap: true
}

const Service = ({ href, icon, ...props }) => (
  <A
    target="_blank"
    rel="noopener"
    href={href}
    mr={2}
    mb={2}
    color="muted"
    aria-label={`hack club on ${icon}`}
    children={<Icon glyph={icon} />}
    {...props}
  />
)

const Pages = styled(Box)`
  a {
    display: block;
    color: inherit;
    margin-bottom: ${theme.space[2]}px;
  }
`

const BottomLine = styled(Box)`
  border-top: 1px solid ${theme.colors.smoke};
`

const Footer = ({ dark = false, children, ...props }) => (
  <Base
    color={dark ? 'muted' : 'slate'}
    py={[4, 5]}
    dark={dark}
    align="left"
    {...props}
  >
    {children}
    <Columns px={3}>
      <Box>
        <Heading.h2 f={3} mb={3}>
          Hack Club
        </Heading.h2>
        <Pages>
          {/* <Link to="/" children="Home" /> */}
          <Link to="/donate" children="Donate" />
          <Link to="/team" children="Team" />
          <Link to="/updates" children="Updates" />
          <Link to="/hackers" children="Hackers" />
          <Link to="/philosophy" children="Philosophy" />
        </Pages>
      </Box>
      <Box>
        <Heading.h2 f={3} mb={3}>
          For Clubs
        </Heading.h2>
        <Pages>
          <Link to="/start" children="Start" />
          <Link to="/apply" children="Apply" />
          <Link to="/challenge" children="Challenge" />
          <Link to="/workshops" children="Workshops" />

        </Pages>
      </Box>
      <Box>
        <Heading.h2 f={3} mb={3}>
          Resources
        </Heading.h2>
        <Pages>

          <Link to="/bank" children="Bank" />
          <Link to="/night" children="Hack Night" />
        </Pages>
      </Box>
      <Box>
        <Heading.h2 f={3} mb={3}>
          Join the Club
        </Heading.h2>
        <Services>
          <Service href="/slack_invite" icon="slack" />
          <Service href="https://twitter.com/hackclub" icon="twitter" />
          <Service href="https://github.com/hackclub" icon="github" />
          <Service
            href="https://www.facebook.com/Hack-Club-741805665870458"
            icon="facebook"
          />
          <Service href="https://medium.com/hackclub" icon="medium" />
          <Service
            href="https://www.youtube.com/channel/UCQzO0jpcRkP-9eWKMpJyB0w"
            icon="youtube"
          />
          <Service
            href="https://www.instagram.com/starthackclub"
            icon="instagram"
          />
          <Service href="mailto:team@hackclub.com" icon="email" />
        </Services>
        <Text my={2}>
          1-855-625-HACK

          <Text.span color="muted" children="(call toll-free)" />
        </Text>
      </Box>
    </Columns>
    <Container px={3} mt={[3, 4]}>
      <Box f={2}>
        <Text>Office: 576 Natoma St, San Francisco, CA 94103</Text>
        <Text>Mail: 8605 Santa Monica Blvd #86294, Los Angeles, CA 90069</Text>
      </Box>
      <BottomLine mt={3}>
        <Text f={1} mt={2} color="muted">
          © {new Date().getFullYear()} Hack Club. Nonprofit EIN: 81-2908499.
        </Text>
      </BottomLine>
    </Container>
  </Base>
)

export default Footer
<|endoftext|>


<commit_before>"use strict";

define([], function() {
    var Storage = {
        init: function() {
            if (!navigator.getDeviceStorage) {
                return $.Deferred().resolve().promise();
            }
            this.sdcard = navigator.getDeviceStorage("sdcard");
            return $.Deferred().resolve().promise();
        },
        /**
         * Returns a promise which when resolved contains a string of data
         */
        readTextFile: function(filename, data) {
            var d = $.Deferred();
            if (!this.sdcard) {
                return d.reject().promise();
            }
            var request = this.sdcard.get(filename);
            request.onsuccess = function () {
                var file = this.result;
                var fileReader = new FileReader();
                fileReader.readAsText(file.slice())
                fileReader.onloadend = function() {
                    d.resolve(fileReader.result);
                }
            };
            request.onerror = function () {
                console.warn("Unable to get the file: " + this.error);
                d.reject();
            };

            return d.promise();
        },
        deleteFile: function(filename) {
            var d = $.Deferred();
            if (!this.sdcard) {
                return d.reject().promise();
            }
            var request = this.sdcard.delete(filename);
            request.onsuccess = function () {
                d.resolve();
            };
            request.onerror = function () {
                console.warn("Unable to delete the file: " + this.error);
                d.reject();
            };

            return d.promise();
        },
        writeTextFile: function(filename, data) {
            var d = $.Deferred();
            if (!this.sdcard) {
                return d.reject().promise();
            }

            var file = new Blob([data], {type: "text/plain"});
            var request = this.sdcard.addNamed(file, filename);
            request.onsuccess = function () {
                var name = this.result;
                d.resolve();
            };
            // An error typically occur if a file with the same name already exist
            request.onerror = function () {
                console.warn('Unable to write the file: ' + this.error);
                d.reject();
            };
            return d.promise();
        }
    };

    return Storage;
});
<commit_msg>Adjust storage API<commit_after>"use strict";

define([], function() {
    var Storage = {
        /**
         * Initializes the device storage for the sd card.
         * Must be called before any other API.
         */
        init: function() {
            if (!navigator.getDeviceStorage) {
                return $.Deferred().resolve().promise();
            }
            this.sdcard = navigator.getDeviceStorage("sdcard");
            return $.Deferred().resolve().promise();
        },
        /**
         * Returns a promise which when resolved contains a string of data
         */
        readText: function(filename, data) {
            var d = $.Deferred();
            if (!this.sdcard) {
                return d.reject().promise();
            }
            var request = this.sdcard.get(filename);
            request.onsuccess = function () {
                var file = this.result;
                var fileReader = new FileReader();
                fileReader.readAsText(file.slice())
                fileReader.onloadend = function() {
                    d.resolve(fileReader.result);
                }
            };
            request.onerror = function () {
                console.warn("Unable to get the file: " + this.error);
                d.reject();
            };

            return d.promise();
        },
        /**
         * Deletes the specified file from sdstorage.
         * Resolves if the file no longer exists, wehther or not it was deleted.
         */
        delete: function(filename) {
            var d = $.Deferred();
            if (!this.sdcard) {
                return d.reject().promise();
            }
            var request = this.sdcard.delete(filename);
            request.onsuccess = function () {
                d.resolve();
            };
            request.onerror = function () {
                if (this.error.name === "NotFoundError") {
                    d.resolve();
                } else {
                    console.warn("Unable to delete the file: " + this.error);
                    d.reject();
                }
            };

            return d.promise();
        },
        /**
         * Writes out the specified data as text in the specified file.
         */
        writeText: function(filename, data) {
            var d = $.Deferred();
            if (!this.sdcard) {
                return d.reject().promise();
            }

            var file = new Blob([data], {type: "text/plain"});
            var request = this.sdcard.addNamed(file, filename);
            request.onsuccess = function () {
                var name = this.result;
                d.resolve();
            };
            // An error typically occur if a file with the same name already exist
            request.onerror = function () {
                console.warn('Unable to write the file: ' + this.error);
                d.reject();
            };
            return d.promise();
        }
    };

    return Storage;
});
<|endoftext|>


<commit_before>/*
 * jQuery doTimeout: Like setTimeout, but better! - v1.0 - 3/3/2010
 * http://benalman.com/projects/jquery-dotimeout-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($){var a={},c="doTimeout",d=Array.prototype.slice;$[c]=function(){return b.apply(window,[0].concat(d.call(arguments)))};$.fn[c]=function(){var f=d.call(arguments),e=b.apply(this,[c+f[0]].concat(f));return typeof f[0]==="number"||typeof f[1]==="number"?this:e};function b(l){var m=this,h,k={},g=l?$.fn:$,n=arguments,i=4,f=n[1],j=n[2],p=n[3];if(typeof f!=="string"){i--;f=l=0;j=n[1];p=n[2]}if(l){h=m.eq(0);h.data(l,k=h.data(l)||{})}else{if(f){k=a[f]||(a[f]={})}}k.id&&clearTimeout(k.id);delete k.id;function e(){if(l){h.removeData(l)}else{if(f){delete a[f]}}}function o(){k.id=setTimeout(function(){k.fn()},j)}if(p){k.fn=function(q){if(typeof p==="string"){p=g[p]}p.apply(m,d.call(n,i))===true&&!q?o():e()};o()}else{if(k.fn){j===undefined?e():k.fn(j===false);return true}else{e()}}}})(jQuery);

// Making sure that console.log does not throw errors on Firefox + IE etc.
if (typeof console == "undefined") var console = { log: function() {} };

var DiscoJuice = {};

/*
 * Country codes available here http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
 */
DiscoJuice.Constants = {
	"Countries": {
		'CZ': 'Czech',
		'DK': 'Denmark',
		'FI': 'Finland',
		'FR': 'France',
		'DE': 'Germany',
		'GR': 'Greece',
		'HR': 'Croatia',
		'IE': 'Ireland',
		'IT': 'Italy',
		'HU': 'Hungary',
		'LU': 'Luxembourg',
		'NL': 'Netherlands',
		'NO': 'Norway',
		'PL': 'Poland',
		'PT': 'Portugal',
		'SI': 'Slovenia',
		'ES': 'Spain',
		'SE': 'Sweden',
		'CH': 'Switzerland',
		'TR': 'Turkey',
		'US': 'USA',
		'GB': 'UK',
		'XX': 'Experimental'
	},
	"Flags": {
		'CZ': 'cz.png',
		'DK': 'dk.png',
		'FI': 'fi.png',
		'FR': 'fr.png',
		'DE': 'de.png',
		'GR': 'gr.png',
		'HR': 'hr.png',
		'IE': 'ie.png',
		'IT': 'it.png',
		'HU': 'hu.png',
		'LU': 'lu.png',
		'NL': 'nl.png',
		'NO': 'no.png',
		'PL': 'pl.png',
		'PT': 'pt.png',
		'SI': 'si.png',
		'ES': 'es.png',
		'SE': 'se.png',
		'CH': 'ch.png',
		'TR': 'tr.png',
		'GB': 'gb.png',
		'US': 'us.png',
	}
};

DiscoJuice.Utils = {
	"log": function(string) {
		console.log(string);
		// opera.postError(string);
	},
	"options": function() {
		var options;
		return {
			"get": function (key, def) {
	//			DiscoJuice.log(options);
	//			DiscoJuice.log('Getting [' + key + '] default [' + def + '] val [' + options[key] + ']');
				if (!options) return def;
				if (!options[key]) return def;
				return options[key];
			},
			"set": function(opts) {
				options = opts;
			},
			"update": function(key, value) {
				options[key] = value;
			}
		}
	}(),

	/* Functions for setting, reading and erasing cookies */
	"createCookie": function(value, type) {
		var type = type || 'EntityID';
		var name = '_DiscoJuice_' + type;
		var days = 1825;
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+escape(value)+expires+"; path=/";
	},
	"readCookie": function(type) {
		var type = type || 'EntityID';
		var name = '_DiscoJuice_' + type;
		var days = 1825;
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
		}
		return null;
	},
	"eraseCookie": function (type) {
		var type = type || 'EntityID';
		var name = '_DiscoJuice_' + type;
		DiscoJuice.createCookie(name,"",-1);
	},
	/* ------ ------ ------ ------ ------ */

	/*
	 * Performs a search 'term' against an entity.
	 * If no match, return false.
	 * If match return the keyword that matches.
	 */
	"searchMatch": function(item, term) {
		if (item.title.toLowerCase().search(term.toLowerCase()) !== -1) return true;
		var key, i, keyword;

		if (item.keywords) {
			for(key in item.keywords) {
				keyword = item.keywords[key];
				for(i = 0; i < keyword.length; i++) {
					if (keyword[i].toLowerCase().search(term.toLowerCase()) !== -1) return keyword[i];
				}
			}
		}
		return false;
	},

	// calculate distance between two locations
	"calculateDistance": function (lat1, lon1, lat2, lon2) {
		var R = 6371; // km
		var dLat = this.toRad(lat2-lat1);
		var dLon = this.toRad(lon2-lon1);
		var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
				Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) *
				Math.sin(dLon/2) * Math.sin(dLon/2);
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		var d = R * c;
		return d;
	},

	"toRad": function (deg) {
		return deg * Math.PI/180;
	}

};

/*
	Plugin for JQuery.
	*/
(function($) {
	$.fn.DiscoJuice = function(options) {
		return this.each(function() {
			DiscoJuice.Utils.options.set(options);

			DiscoJuice.Control.ui = DiscoJuice.UI;
			DiscoJuice.UI.control = DiscoJuice.Control;

			DiscoJuice.UI.enable(this);

		});
	};
})(jQuery);

<commit_msg>Fix syntax error in DiscoJuice<commit_after>/*
 * jQuery doTimeout: Like setTimeout, but better! - v1.0 - 3/3/2010
 * http://benalman.com/projects/jquery-dotimeout-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($){var a={},c="doTimeout",d=Array.prototype.slice;$[c]=function(){return b.apply(window,[0].concat(d.call(arguments)))};$.fn[c]=function(){var f=d.call(arguments),e=b.apply(this,[c+f[0]].concat(f));return typeof f[0]==="number"||typeof f[1]==="number"?this:e};function b(l){var m=this,h,k={},g=l?$.fn:$,n=arguments,i=4,f=n[1],j=n[2],p=n[3];if(typeof f!=="string"){i--;f=l=0;j=n[1];p=n[2]}if(l){h=m.eq(0);h.data(l,k=h.data(l)||{})}else{if(f){k=a[f]||(a[f]={})}}k.id&&clearTimeout(k.id);delete k.id;function e(){if(l){h.removeData(l)}else{if(f){delete a[f]}}}function o(){k.id=setTimeout(function(){k.fn()},j)}if(p){k.fn=function(q){if(typeof p==="string"){p=g[p]}p.apply(m,d.call(n,i))===true&&!q?o():e()};o()}else{if(k.fn){j===undefined?e():k.fn(j===false);return true}else{e()}}}})(jQuery);

// Making sure that console.log does not throw errors on Firefox + IE etc.
if (typeof console == "undefined") var console = { log: function() {} };

var DiscoJuice = {};

/*
 * Country codes available here http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
 */
DiscoJuice.Constants = {
	"Countries": {
		'CZ': 'Czech',
		'DK': 'Denmark',
		'FI': 'Finland',
		'FR': 'France',
		'DE': 'Germany',
		'GR': 'Greece',
		'HR': 'Croatia',
		'IE': 'Ireland',
		'IT': 'Italy',
		'HU': 'Hungary',
		'LU': 'Luxembourg',
		'NL': 'Netherlands',
		'NO': 'Norway',
		'PL': 'Poland',
		'PT': 'Portugal',
		'SI': 'Slovenia',
		'ES': 'Spain',
		'SE': 'Sweden',
		'CH': 'Switzerland',
		'TR': 'Turkey',
		'US': 'USA',
		'GB': 'UK',
		'XX': 'Experimental'
	},
	"Flags": {
		'CZ': 'cz.png',
		'DK': 'dk.png',
		'FI': 'fi.png',
		'FR': 'fr.png',
		'DE': 'de.png',
		'GR': 'gr.png',
		'HR': 'hr.png',
		'IE': 'ie.png',
		'IT': 'it.png',
		'HU': 'hu.png',
		'LU': 'lu.png',
		'NL': 'nl.png',
		'NO': 'no.png',
		'PL': 'pl.png',
		'PT': 'pt.png',
		'SI': 'si.png',
		'ES': 'es.png',
		'SE': 'se.png',
		'CH': 'ch.png',
		'TR': 'tr.png',
		'GB': 'gb.png',
		'US': 'us.png'
	}
};

DiscoJuice.Utils = {
	"log": function(string) {
		console.log(string);
		// opera.postError(string);
	},
	"options": function() {
		var options;
		return {
			"get": function (key, def) {
	//			DiscoJuice.log(options);
	//			DiscoJuice.log('Getting [' + key + '] default [' + def + '] val [' + options[key] + ']');
				if (!options) return def;
				if (!options[key]) return def;
				return options[key];
			},
			"set": function(opts) {
				options = opts;
			},
			"update": function(key, value) {
				options[key] = value;
			}
		}
	}(),

	/* Functions for setting, reading and erasing cookies */
	"createCookie": function(value, type) {
		var type = type || 'EntityID';
		var name = '_DiscoJuice_' + type;
		var days = 1825;
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+escape(value)+expires+"; path=/";
	},
	"readCookie": function(type) {
		var type = type || 'EntityID';
		var name = '_DiscoJuice_' + type;
		var days = 1825;
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
		}
		return null;
	},
	"eraseCookie": function (type) {
		var type = type || 'EntityID';
		var name = '_DiscoJuice_' + type;
		DiscoJuice.createCookie(name,"",-1);
	},
	/* ------ ------ ------ ------ ------ */

	/*
	 * Performs a search 'term' against an entity.
	 * If no match, return false.
	 * If match return the keyword that matches.
	 */
	"searchMatch": function(item, term) {
		if (item.title.toLowerCase().search(term.toLowerCase()) !== -1) return true;
		var key, i, keyword;

		if (item.keywords) {
			for(key in item.keywords) {
				keyword = item.keywords[key];
				for(i = 0; i < keyword.length; i++) {
					if (keyword[i].toLowerCase().search(term.toLowerCase()) !== -1) return keyword[i];
				}
			}
		}
		return false;
	},

	// calculate distance between two locations
	"calculateDistance": function (lat1, lon1, lat2, lon2) {
		var R = 6371; // km
		var dLat = this.toRad(lat2-lat1);
		var dLon = this.toRad(lon2-lon1);
		var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
				Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) *
				Math.sin(dLon/2) * Math.sin(dLon/2);
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		var d = R * c;
		return d;
	},

	"toRad": function (deg) {
		return deg * Math.PI/180;
	}

};

/*
	Plugin for JQuery.
	*/
(function($) {
	$.fn.DiscoJuice = function(options) {
		return this.each(function() {
			DiscoJuice.Utils.options.set(options);

			DiscoJuice.Control.ui = DiscoJuice.UI;
			DiscoJuice.UI.control = DiscoJuice.Control;

			DiscoJuice.UI.enable(this);

		});
	};
})(jQuery);

<|endoftext|>


<commit_before>'use strict'

let consistentEnv

module.exports = function() {
  if (!consistentEnv) {
    consistentEnv = require('consistent-env')
  }
  return consistentEnv().PATH || ''
}

module.exports.async = function() {
  if (!consistentEnv) {
    consistentEnv = require('consistent-env')
  }
  return consistentEnv.async().then(function(env) {
    return env.PATH || ''
  })
}
<commit_msg>:bug: Handle different names of PATH on windows<commit_after>'use strict'

let consistentEnv

module.exports = function() {
  if (process.platform === 'win32') {
    return process.env.PATH || process.env.Path
  }
  if (!consistentEnv) {
    consistentEnv = require('consistent-env')
  }
  return consistentEnv().PATH || ''
}

module.exports.async = function() {
  if (process.platform === 'win32') {
    return Promise.resolve(process.env.PATH || process.env.Path)
  }
  if (!consistentEnv) {
    consistentEnv = require('consistent-env')
  }
  return consistentEnv.async().then(function(env) {
    return env.PATH || ''
  })
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Link } from 'react-router';

import { header, tiny } from '../stylesheets/header.css';

export default class Header extends Component {
  render() {
    return (

CabinetVotes.org

Tracking how Senators voted on the confirmation of each member of Trump's Cabinet*.

Updated after each vote. Click on a Senator's name for contact information.

* (and Ambassadors, Justices, etc.)

          Show:
          <Link to="/rep">Republicans</Link>
           /
          <Link to="/dem">Democrats </Link>
           /
          <Link to="/ind">Independents</Link>
           /
          <Link to="/">All</Link>

    )
  }
}
<commit_msg>Pass lint<commit_after>import React, { Component } from 'react';
import { Link } from 'react-router';

import { header, tiny } from '../stylesheets/header.css';

export default class Header extends Component {
  render() {
    return (

CabinetVotes.org

Tracking how Senators voted on the confirmation of each member of Trump's Cabinet*.

Updated after each vote. Click on a Senator's name for contact information.

* (and Ambassadors, Justices, etc.)

          Show:
          <Link to="/rep">Republicans</Link>
           /
          <Link to="/dem">Democrats </Link>
           /
          <Link to="/ind">Independents</Link>
           /
          <Link to="/">All</Link>

    );
  }
}
<|endoftext|>


<commit_before>"use strict";

var supportsLocalStorage = typeof(Storage) !== "undefined";
var settings = {
    showRowRaceNone: true,
    showRowRaceProtoss: true,
    showRowRaceTerran: true,
    showRowRaceZerg: true,
    showRowOffline: false,
    showColRace: false,
    showColViewers: true,
    showColPeak: false,
    showColDuration: true,
    showColLastSeen: false,
    autoRefresh: true,
    useFullScreenLinks: false,

    keys: (function() {
        return Object.keys(this).filter(s => typeof(this[s]) == "boolean")
    }),

    visibilityKeys: (function() {
        return this.keys().filter(s => s.substring(0, 4) === "show");
    }),

    loadSettings: function() {
        //console.log("loadSettings");
        var settingKeys = this.keys();
        for (var i = 0; i < settingKeys.length; i++) {
            var setting = settingKeys[i];
            if (supportsLocalStorage && localStorage.hasOwnProperty(setting)) {
                this[setting] = localStorage[setting] === "true";
            }
            var checkboxId = this.settingToCheckboxId(setting);
            var element = $("#" + checkboxId);
            //console.log(setting + ": " + localStorage[setting]);
            if (element.length && element.is(":checked") !== this[setting])
            {
                element.click();
                //console.log("Fired click event");
            }
        }
    },

    saveSettings: function() {
        if (!supportsLocalStorage) {
            //console.log("localStorage not supported");
            return;
        }
        //console.log("saveSettings");
        var settingKeys = this.keys();
        for (var i = 0; i < settingKeys.length; i++) {
            var setting = settingKeys[i];
            localStorage[setting] = Boolean(this[setting]);
            //console.log(setting + ": " + localStorage[setting]);
        }
    },

    settingToCheckboxId: function(s) {
        return "checkbox-" + s.replace(/([A-Z])/g, function (x, y){return "-" + y.toLowerCase()}).replace(/^-/, "");
    },

    settingToClassName: function(s) {
        switch (s) {
            case "showRowRaceNone":
                return "race-none";
            case "showRowRaceProtoss":
                return "race-protoss";
            case "showRowRaceTerran":
                return "race-terran";
            case "showRowRaceZerg":
                return "race-zerg";
            case "showRowOffline":
                return "stream-row-offline";
            case "showColRace":
                return "stream-col-race";
            case "showColViewers":
                return "stream-col-viewers";
            case "showColPeak":
                return "stream-col-peak";
            case "showColDuration":
                return "stream-col-duration";
            case "showColLastSeen":
                return "stream-col-last-seen";
            default:
                throw "Unknown value in switch statement: " + setting;
        }
    },

    callback: function(setting) {
        if (setting === "autoRefresh") {
            timer.updateTimerStatus();
            return;
        }

        if (setting === "useFullScreenLinks") {
            $("a.stream-link").each(function() {
                var streamLink = $(this).attr("href");
                var streamId = streamLink.split("/")[3];
                var updatedStreamLink = getStreamUrl(streamId, settings["useFullScreenLinks"]);
                $(this).attr("href", updatedStreamLink);
            });
            return;
        }

        var className = this.settingToClassName(setting);
        if (this[setting]) {
            if (setting === "showRowOffline") {
                var showRaceSettings = this.keys().filter(s => s.substring(0, 11) === "showRowRace");
                for (var i = 0; i < showRaceSettings.length; i++) {
                    var showRateSetting = showRaceSettings[i];
                    if (this[showRateSetting]) {
                        var query = "." + className + "." + this.settingToClassName(showRateSetting);
                        $(query).show();
                    }
                }
            } else if (setting.substring(0, 11) === "showRowRace" && !this["showRowOffline"]) {
                $("." + className + ".stream-row-online").show();
            } else {
                $("." + className).show();
            }
        } else {
            $("." + className).hide();
        }
    }
};

function getStreamUrl(streamId, useFullScreenLink) {
    var url = "//play.afreecatv.com/" + streamId;
    if (useFullScreenLink) {
        url += "/embed";
    }
    return url;
}

function getLastSeenStatus(isOnline, lastSeen) {
    if (isOnline) {
        return "online";
    } else if (lastSeen === null) {
        return "never seen";
    } else {
        return moment(lastSeen).fromNow();
    }
}

function replaceTable(streams, updateTime) {
    var idTableStreams = "streams";
    var newTbody = document.createElement("tbody");

    let idCounter = 0;
    for (var key in streams) {
        if (key.substring(0, 8) != "afreeca_") {
            continue;
        }
        if (streams.hasOwnProperty(key)) {
            var stream = streams[key];
            var game = stream["game"];
            if (game != "brood war") {
                continue;
            }

            var nickname = stream["nickname"];
            var race = stream["game_info"]["race"];
            var raceText = race ? race : "";
            var viewers = stream["viewers"];
            var maxViewers = stream["max_viewers"];
            var isOnline = stream["online_since"] !== null;
            var durationText = "offline";
            var durationValue = 0;
            if (stream["online_since"] !== null) {
                var duration = moment.duration(moment(updateTime).diff(moment(stream["online_since"])));
                durationText = duration.humanize();
                durationValue = duration.asMinutes();
            }
            var lastSeenText = getLastSeenStatus(isOnline, stream["last_seen"]);
            var lastSeenValue = stream["last_seen"] || 0;
            var url = getStreamUrl(stream["id"], settings["useFullScreenLinks"]);
            var broadcast = stream["image"];

            var cells = [
                [nickname,     { "class": [ "stream-col-nickname" ] } ],
                [raceText,     { "class": [ "stream-col-race", "text-capitalize" ] } ],
                [viewers,      { "class": [ "stream-col-viewers", "text-center" ] } ],
                [maxViewers,   { "class": [ "stream-col-peak", "text-center" ] } ],
                [durationText, { "class": [ "stream-col-duration", "text-center" ], "data-value": durationValue } ],
                [lastSeenText, { "class": [ "stream-col-last-seen", "text-center" ], "data-value": lastSeenValue } ],
            ];

            var newRow = newTbody.insertRow(-1);
            newRow.classList.add(isOnline ? "stream-row-online" : "stream-row-offline");
            newRow.classList.add("race-" + (race || "none"));
            for (var i = 0; i < cells.length; i++) {
                var text = cells[i][0];
                var data = cells[i][1];
                var newCell = newRow.insertCell(-1);
                if (data !== null) {
                    for (var key in data) {
                        if (data.hasOwnProperty(key)) {
                            if (key === "class") {
                                for (var j = 0; j < data[key].length; j++) {
                                    newCell.classList.add(data[key][j]);
                                }
                            } else if (key.slice(0, 5) === "data-") {
                                newCell.setAttribute(key, data[key]);
                            }
                        }
                    }
                }
                if (i == 0) {
                    let id = "preview_" + idCounter++;
                    var span = document.createElement("span");
                    var raceAnchor = document.createElement("a");
                    raceAnchor.classList.add("race-emoji");
                    raceAnchor.classList.add("race-emoji-popover");
                    raceAnchor.setAttribute("triggerId", id);
                    raceAnchor.innerHTML = race == "zerg"    ? "🦂"
                                         : race == "protoss" ? "🛸"
                                         : race == "terran"  ? "🌎"
                                                             : "📺";
                    var linkAnchor = document.createElement("a");
                    linkAnchor.id = id;
                    linkAnchor.href = url;
                    linkAnchor.rel = "noreferrer";
                    linkAnchor.classList.add("stream-link");
                    linkAnchor.appendChild(document.createTextNode(text));
                    if (broadcast) {
                        // Hover preview for desktop
                        linkAnchor.setAttribute("data-image", broadcast);
                        linkAnchor.setAttribute("data-placement", "right");
                        linkAnchor.setAttribute("data-content", "<img src='" + broadcast + "' width='470' height='270'>");
                        linkAnchor.setAttribute("data-html", "true");
                        linkAnchor.setAttribute("data-trigger", "hover");
                        linkAnchor.setAttribute("data-toggle", "popover");
                        linkAnchor.setAttribute("tabindex", "0");
                        linkAnchor.setAttribute("title", '');

                        // Preload images
                        new Image().src = broadcast;
                    }

                    span.appendChild(raceAnchor);
                    span.appendChild(document.createTextNode(" "));
                    span.appendChild(linkAnchor);
                    newCell.appendChild(span);
                } else {
                    newCell.appendChild(document.createTextNode(text));
                }
            }
        }
    }

    var table = document.getElementById(idTableStreams);
    var oldTbody = document.getElementById(idTableStreams).getElementsByTagName("tbody")[0];
    table.replaceChild(newTbody, oldTbody);
}

function setLastUpdate(timeStr) {
    $("#text-last-updated").text(moment(timeStr).format("lll"));
}

var previewDiv = $("#preview")
var previewImage = $("#preview-image");
var divShown = false;
var updater = {
    json: null,

    refreshStreams: function() {
        this.refreshStarted();
        var promise = $.getJSON('/streams.json');
        promise.done((function(data) {
            this.json = data;
            this.refreshComplete();
        }).bind(this));
    },

    refreshStarted: function() {
        $("#icon-refresh").addClass("fa-spin");
        $("#icon-refresh").addClass("active");
        timer.resetTimer();
    },

    refreshComplete: function() {
        replaceTable(this.json["streams"], this.json["last_update"]);
        setLastUpdate(this.json["last_update"]);
        $.bootstrapSortable(true);
        var visibilitySettings = settings.visibilityKeys();
        for (var i = 0; i < visibilitySettings.length; i++) {
            settings.callback(visibilitySettings[i]);
        }
        $("#icon-refresh").removeClass("fa-spin");
        $("#icon-refresh").removeClass("active");

        $('[data-toggle="popover"]').popover();

        let hidePopovers = function() {
            $('[data-toggle="popover"]').popover('hide');
        };

        $('.race-emoji-popover').click(function(e) {
            hidePopovers();
            let triggerId = $(this).attr('triggerId');
            $('#' + triggerId).popover('toggle');
            e.stopPropagation();
        });

        $('html').click(hidePopovers);
    }
}

var timer = {
    timerDuration: 60,
    timerElapsed: 0,
    timerId: null,

    updateTimerStatus: function() {
        if (settings.autoRefresh && this.timerId == null) {
            this.startTimer();
        }
    },

    resetTimer: function() {
        this.timerElapsed = 0;
    },

    stopTimer: function() {
        if (this.timerId != null) {
            clearInterval(this.timerId);
            this.timerId = null;
        }
    },

    startTimer: function() {
        this.timerId = setInterval((function() {
            ++this.timerElapsed;
            if (settings.autoRefresh && this.timerElapsed >= this.timerDuration) {
                updater.refreshStreams();
            }
        }).bind(this), 1000);
    }
}

jQuery(document).ready(function($) {
    $("#btn-refresh").click(function() {
        updater.refreshStreams();
    });

    var visibilitySettings = settings.visibilityKeys();
    for (var i = 0; i < visibilitySettings.length; i++) {
        (function() {
            var setting = visibilitySettings[i];
            var checkboxId = settings.settingToCheckboxId(setting);
            $("#" + checkboxId).click(function() {
                settings[setting] = $("#" + checkboxId).is(":checked");
                settings.callback(setting);
            });
        })();
    }

    $("#checkbox-auto-refresh").click(function() {
        settings["autoRefresh"] = $("#checkbox-auto-refresh").is(":checked");
        settings.callback("autoRefresh");
    });

    $("#checkbox-use-full-screen-links").click(function() {
        settings["useFullScreenLinks"] = $("#checkbox-use-full-screen-links").is(":checked");
        settings.callback("useFullScreenLinks");
    });

    settings.loadSettings();

    watch(settings, settings.keys(), function(){
        settings.saveSettings();
    });

    updater.refreshStreams();
});
<commit_msg>attempt fix for leftover previews<commit_after>"use strict";

var supportsLocalStorage = typeof(Storage) !== "undefined";
var settings = {
    showRowRaceNone: true,
    showRowRaceProtoss: true,
    showRowRaceTerran: true,
    showRowRaceZerg: true,
    showRowOffline: false,
    showColRace: false,
    showColViewers: true,
    showColPeak: false,
    showColDuration: true,
    showColLastSeen: false,
    autoRefresh: true,
    useFullScreenLinks: false,

    keys: (function() {
        return Object.keys(this).filter(s => typeof(this[s]) == "boolean")
    }),

    visibilityKeys: (function() {
        return this.keys().filter(s => s.substring(0, 4) === "show");
    }),

    loadSettings: function() {
        //console.log("loadSettings");
        var settingKeys = this.keys();
        for (var i = 0; i < settingKeys.length; i++) {
            var setting = settingKeys[i];
            if (supportsLocalStorage && localStorage.hasOwnProperty(setting)) {
                this[setting] = localStorage[setting] === "true";
            }
            var checkboxId = this.settingToCheckboxId(setting);
            var element = $("#" + checkboxId);
            //console.log(setting + ": " + localStorage[setting]);
            if (element.length && element.is(":checked") !== this[setting])
            {
                element.click();
                //console.log("Fired click event");
            }
        }
    },

    saveSettings: function() {
        if (!supportsLocalStorage) {
            //console.log("localStorage not supported");
            return;
        }
        //console.log("saveSettings");
        var settingKeys = this.keys();
        for (var i = 0; i < settingKeys.length; i++) {
            var setting = settingKeys[i];
            localStorage[setting] = Boolean(this[setting]);
            //console.log(setting + ": " + localStorage[setting]);
        }
    },

    settingToCheckboxId: function(s) {
        return "checkbox-" + s.replace(/([A-Z])/g, function (x, y){return "-" + y.toLowerCase()}).replace(/^-/, "");
    },

    settingToClassName: function(s) {
        switch (s) {
            case "showRowRaceNone":
                return "race-none";
            case "showRowRaceProtoss":
                return "race-protoss";
            case "showRowRaceTerran":
                return "race-terran";
            case "showRowRaceZerg":
                return "race-zerg";
            case "showRowOffline":
                return "stream-row-offline";
            case "showColRace":
                return "stream-col-race";
            case "showColViewers":
                return "stream-col-viewers";
            case "showColPeak":
                return "stream-col-peak";
            case "showColDuration":
                return "stream-col-duration";
            case "showColLastSeen":
                return "stream-col-last-seen";
            default:
                throw "Unknown value in switch statement: " + setting;
        }
    },

    callback: function(setting) {
        if (setting === "autoRefresh") {
            timer.updateTimerStatus();
            return;
        }

        if (setting === "useFullScreenLinks") {
            $("a.stream-link").each(function() {
                var streamLink = $(this).attr("href");
                var streamId = streamLink.split("/")[3];
                var updatedStreamLink = getStreamUrl(streamId, settings["useFullScreenLinks"]);
                $(this).attr("href", updatedStreamLink);
            });
            return;
        }

        var className = this.settingToClassName(setting);
        if (this[setting]) {
            if (setting === "showRowOffline") {
                var showRaceSettings = this.keys().filter(s => s.substring(0, 11) === "showRowRace");
                for (var i = 0; i < showRaceSettings.length; i++) {
                    var showRateSetting = showRaceSettings[i];
                    if (this[showRateSetting]) {
                        var query = "." + className + "." + this.settingToClassName(showRateSetting);
                        $(query).show();
                    }
                }
            } else if (setting.substring(0, 11) === "showRowRace" && !this["showRowOffline"]) {
                $("." + className + ".stream-row-online").show();
            } else {
                $("." + className).show();
            }
        } else {
            $("." + className).hide();
        }
    }
};

function getStreamUrl(streamId, useFullScreenLink) {
    var url = "//play.afreecatv.com/" + streamId;
    if (useFullScreenLink) {
        url += "/embed";
    }
    return url;
}

function getLastSeenStatus(isOnline, lastSeen) {
    if (isOnline) {
        return "online";
    } else if (lastSeen === null) {
        return "never seen";
    } else {
        return moment(lastSeen).fromNow();
    }
}

function replaceTable(streams, updateTime) {
    var idTableStreams = "streams";
    var newTbody = document.createElement("tbody");

    let idCounter = 0;
    for (var key in streams) {
        if (key.substring(0, 8) != "afreeca_") {
            continue;
        }
        if (streams.hasOwnProperty(key)) {
            var stream = streams[key];
            var game = stream["game"];
            if (game != "brood war") {
                continue;
            }

            var nickname = stream["nickname"];
            var race = stream["game_info"]["race"];
            var raceText = race ? race : "";
            var viewers = stream["viewers"];
            var maxViewers = stream["max_viewers"];
            var isOnline = stream["online_since"] !== null;
            var durationText = "offline";
            var durationValue = 0;
            if (stream["online_since"] !== null) {
                var duration = moment.duration(moment(updateTime).diff(moment(stream["online_since"])));
                durationText = duration.humanize();
                durationValue = duration.asMinutes();
            }
            var lastSeenText = getLastSeenStatus(isOnline, stream["last_seen"]);
            var lastSeenValue = stream["last_seen"] || 0;
            var url = getStreamUrl(stream["id"], settings["useFullScreenLinks"]);
            var broadcast = stream["image"];

            var cells = [
                [nickname,     { "class": [ "stream-col-nickname" ] } ],
                [raceText,     { "class": [ "stream-col-race", "text-capitalize" ] } ],
                [viewers,      { "class": [ "stream-col-viewers", "text-center" ] } ],
                [maxViewers,   { "class": [ "stream-col-peak", "text-center" ] } ],
                [durationText, { "class": [ "stream-col-duration", "text-center" ], "data-value": durationValue } ],
                [lastSeenText, { "class": [ "stream-col-last-seen", "text-center" ], "data-value": lastSeenValue } ],
            ];

            var newRow = newTbody.insertRow(-1);
            newRow.classList.add(isOnline ? "stream-row-online" : "stream-row-offline");
            newRow.classList.add("race-" + (race || "none"));
            for (var i = 0; i < cells.length; i++) {
                var text = cells[i][0];
                var data = cells[i][1];
                var newCell = newRow.insertCell(-1);
                if (data !== null) {
                    for (var key in data) {
                        if (data.hasOwnProperty(key)) {
                            if (key === "class") {
                                for (var j = 0; j < data[key].length; j++) {
                                    newCell.classList.add(data[key][j]);
                                }
                            } else if (key.slice(0, 5) === "data-") {
                                newCell.setAttribute(key, data[key]);
                            }
                        }
                    }
                }
                if (i == 0) {
                    let id = "preview_" + idCounter++;
                    var span = document.createElement("span");
                    var raceAnchor = document.createElement("a");
                    raceAnchor.classList.add("race-emoji");
                    raceAnchor.classList.add("race-emoji-popover");
                    raceAnchor.setAttribute("triggerId", id);
                    raceAnchor.innerHTML = race == "zerg"    ? "🦂"
                                         : race == "protoss" ? "🛸"
                                         : race == "terran"  ? "🌎"
                                                             : "📺";
                    var linkAnchor = document.createElement("a");
                    linkAnchor.id = id;
                    linkAnchor.href = url;
                    linkAnchor.rel = "noreferrer";
                    linkAnchor.classList.add("stream-link");
                    linkAnchor.appendChild(document.createTextNode(text));
                    if (broadcast) {
                        // Hover preview for desktop
                        linkAnchor.setAttribute("data-image", broadcast);
                        linkAnchor.setAttribute("data-placement", "right");
                        linkAnchor.setAttribute("data-content", "<img src='" + broadcast + "' width='470' height='270'>");
                        linkAnchor.setAttribute("data-html", "true");
                        linkAnchor.setAttribute("data-trigger", "hover");
                        linkAnchor.setAttribute("data-toggle", "popover");
                        linkAnchor.setAttribute("tabindex", "0");
                        linkAnchor.setAttribute("title", '');

                        // Preload images
                        new Image().src = broadcast;
                    }

                    span.appendChild(raceAnchor);
                    span.appendChild(document.createTextNode(" "));
                    span.appendChild(linkAnchor);
                    newCell.appendChild(span);
                } else {
                    newCell.appendChild(document.createTextNode(text));
                }
            }
        }
    }

    var table = document.getElementById(idTableStreams);
    var oldTbody = document.getElementById(idTableStreams).getElementsByTagName("tbody")[0];
    table.replaceChild(newTbody, oldTbody);
}

function setLastUpdate(timeStr) {
    $("#text-last-updated").text(moment(timeStr).format("lll"));
}

var previewDiv = $("#preview")
var previewImage = $("#preview-image");
var divShown = false;
var updater = {
    json: null,

    refreshStreams: function() {
        this.refreshStarted();
        var promise = $.getJSON('/streams.json');
        promise.done((function(data) {
            this.json = data;
            this.refreshComplete();
        }).bind(this));
    },

    refreshStarted: function() {
        $("#icon-refresh").addClass("fa-spin");
        $("#icon-refresh").addClass("active");
        timer.resetTimer();
    },

    refreshComplete: function() {
        let hidePopovers = function() {
            $('.popover').popover('hide');
        };

        hidePopovers();

        replaceTable(this.json["streams"], this.json["last_update"]);
        setLastUpdate(this.json["last_update"]);
        $.bootstrapSortable(true);
        var visibilitySettings = settings.visibilityKeys();
        for (var i = 0; i < visibilitySettings.length; i++) {
            settings.callback(visibilitySettings[i]);
        }
        $("#icon-refresh").removeClass("fa-spin");
        $("#icon-refresh").removeClass("active");

        $('[data-toggle="popover"]').popover();

        $('.race-emoji-popover').click(function(e) {
            hidePopovers();
            let triggerId = $(this).attr('triggerId');
            $('#' + triggerId).popover('toggle');
            e.stopPropagation();
        });

        $('html').click(hidePopovers);
    }
}

var timer = {
    timerDuration: 60,
    timerElapsed: 0,
    timerId: null,

    updateTimerStatus: function() {
        if (settings.autoRefresh && this.timerId == null) {
            this.startTimer();
        }
    },

    resetTimer: function() {
        this.timerElapsed = 0;
    },

    stopTimer: function() {
        if (this.timerId != null) {
            clearInterval(this.timerId);
            this.timerId = null;
        }
    },

    startTimer: function() {
        this.timerId = setInterval((function() {
            ++this.timerElapsed;
            if (settings.autoRefresh && this.timerElapsed >= this.timerDuration) {
                updater.refreshStreams();
            }
        }).bind(this), 1000);
    }
}

jQuery(document).ready(function($) {
    $("#btn-refresh").click(function() {
        updater.refreshStreams();
    });

    var visibilitySettings = settings.visibilityKeys();
    for (var i = 0; i < visibilitySettings.length; i++) {
        (function() {
            var setting = visibilitySettings[i];
            var checkboxId = settings.settingToCheckboxId(setting);
            $("#" + checkboxId).click(function() {
                settings[setting] = $("#" + checkboxId).is(":checked");
                settings.callback(setting);
            });
        })();
    }

    $("#checkbox-auto-refresh").click(function() {
        settings["autoRefresh"] = $("#checkbox-auto-refresh").is(":checked");
        settings.callback("autoRefresh");
    });

    $("#checkbox-use-full-screen-links").click(function() {
        settings["useFullScreenLinks"] = $("#checkbox-use-full-screen-links").is(":checked");
        settings.callback("useFullScreenLinks");
    });

    settings.loadSettings();

    watch(settings, settings.keys(), function(){
        settings.saveSettings();
    });

    updater.refreshStreams();
});
<|endoftext|>


<commit_before>describe('type(obj)', function () {
  it('array', function () {
    assert('array' === type([]));
    assert('array' === type(new Array()));
  });

  it('regexp', function () {
    assert('regexp' === type(/a-z/gi));
    assert('regexp' === type(new RegExp('a-z')));
  });

  it('function', function () {
    assert('function' === type(function () {
    }));
  });

  it('arguments', function () {
    (function () {
      assert('arguments' === type(arguments));
    })();
  });

  it('date', function () {
    assert('date' === type(new Date));
  });

  it('number', function () {
    assert('number' === type(1));
    assert('number' === type(1.234));
    assert('number' === type(-1));
    assert('number' === type(-1.234));
    assert('number' === type(Infinity));
    assert('number' === type(NaN));
  });

  it('string', function () {
    assert('string' === type('hello world'));
  });

  it('null', function () {
    assert('null' === type(null));
    assert('null' !== type(undefined));
  });

  it('undefined', function () {
    assert('undefined' === type(undefined));
    assert('undefined' !== type(null));
  });

  it('object', function () {
    var Noop = function () {
    };
    assert('object' === type({}));
    assert('object' !== type(Noop));
    assert('object' === type(new Noop));
    assert('object' === type(new Object));
    assert('object' === type(new String('hello')));
  });

  describe('New ECMA6 Types', function () {
    it('map', function () {
      stubObjectToStringOnce('[object Map]');
      assert('map' === type({}));
    });

    it('weakmap', function () {
      stubObjectToStringOnce('[object WeakMap]');
      assert('weakmap' === type({}));
    });

    it('set', function () {
      stubObjectToStringOnce('[object Set]');
      assert('set' === type({}));
    });

    it('weakset', function () {
      stubObjectToStringOnce('[object WeakSet]');
      assert('weakset' === type({}));
    });

    it('symbol', function () {
      stubObjectToStringOnce('[object Symbol]');
      assert('symbol' === type({}));
    });

    it('promise', function () {
      stubObjectToStringOnce('[object Promise]');
      assert('promise' === type({}));
    });

    it('int8array', function () {
      stubObjectToStringOnce('[object Int8Array]');
      assert('int8array' === type({}));
    });

    it('uint8array', function () {
      stubObjectToStringOnce('[object Uint8Array]');
      assert('uint8array' === type({}));
    });

    it('uint8clampedarray', function () {
      stubObjectToStringOnce('[object Uint8ClampedArray]');
      assert('uint8clampedarray' === type({}));
    });

    it('int16array', function () {
      stubObjectToStringOnce('[object Int16Array]');
      assert('int16array' === type({}));
    });

    it('uint16array', function () {
      stubObjectToStringOnce('[object Uint16Array]');
      assert('uint16array' === type({}));
    });

    it('int32array', function () {
      stubObjectToStringOnce('[object Int32Array]');
      assert('int32array' === type({}));
    });

    it('uint32array', function () {
      stubObjectToStringOnce('[object Uint32Array]');
      assert('uint32array' === type({}));
    });

    it('float32array', function () {
      stubObjectToStringOnce('[object Float32Array]');
      assert('float32array' === type({}));
    });

    it('float64array', function () {
      stubObjectToStringOnce('[object Float64Array]');
      assert('float64array' === type({}));
    });

    it('dataview', function () {
      stubObjectToStringOnce('[object DataView]');
      assert('dataview' === type({}));
    });

    var originalObjectToString = Object.prototype.toString;

    function stubObjectToStringOnce(staticValue) {
      Object.prototype.toString = function () {
        Object.prototype.toString = originalObjectToString;
        return staticValue;
      };
    }
  });
});
<commit_msg>Added a test for ArrayBuffer.<commit_after>describe('type(obj)', function () {
  it('array', function () {
    assert('array' === type([]));
    assert('array' === type(new Array()));
  });

  it('regexp', function () {
    assert('regexp' === type(/a-z/gi));
    assert('regexp' === type(new RegExp('a-z')));
  });

  it('function', function () {
    assert('function' === type(function () {
    }));
  });

  it('arguments', function () {
    (function () {
      assert('arguments' === type(arguments));
    })();
  });

  it('date', function () {
    assert('date' === type(new Date));
  });

  it('number', function () {
    assert('number' === type(1));
    assert('number' === type(1.234));
    assert('number' === type(-1));
    assert('number' === type(-1.234));
    assert('number' === type(Infinity));
    assert('number' === type(NaN));
  });

  it('string', function () {
    assert('string' === type('hello world'));
  });

  it('null', function () {
    assert('null' === type(null));
    assert('null' !== type(undefined));
  });

  it('undefined', function () {
    assert('undefined' === type(undefined));
    assert('undefined' !== type(null));
  });

  it('object', function () {
    var Noop = function () {
    };
    assert('object' === type({}));
    assert('object' !== type(Noop));
    assert('object' === type(new Noop));
    assert('object' === type(new Object));
    assert('object' === type(new String('hello')));
  });

  describe('New ECMA6 Types', function () {
    it('map', function () {
      stubObjectToStringOnce('[object Map]');
      assert('map' === type({}));
    });

    it('weakmap', function () {
      stubObjectToStringOnce('[object WeakMap]');
      assert('weakmap' === type({}));
    });

    it('set', function () {
      stubObjectToStringOnce('[object Set]');
      assert('set' === type({}));
    });

    it('weakset', function () {
      stubObjectToStringOnce('[object WeakSet]');
      assert('weakset' === type({}));
    });

    it('symbol', function () {
      stubObjectToStringOnce('[object Symbol]');
      assert('symbol' === type({}));
    });

    it('promise', function () {
      stubObjectToStringOnce('[object Promise]');
      assert('promise' === type({}));
    });

    it('int8array', function () {
      stubObjectToStringOnce('[object Int8Array]');
      assert('int8array' === type({}));
    });

    it('uint8array', function () {
      stubObjectToStringOnce('[object Uint8Array]');
      assert('uint8array' === type({}));
    });

    it('uint8clampedarray', function () {
      stubObjectToStringOnce('[object Uint8ClampedArray]');
      assert('uint8clampedarray' === type({}));
    });

    it('int16array', function () {
      stubObjectToStringOnce('[object Int16Array]');
      assert('int16array' === type({}));
    });

    it('uint16array', function () {
      stubObjectToStringOnce('[object Uint16Array]');
      assert('uint16array' === type({}));
    });

    it('int32array', function () {
      stubObjectToStringOnce('[object Int32Array]');
      assert('int32array' === type({}));
    });

    it('uint32array', function () {
      stubObjectToStringOnce('[object Uint32Array]');
      assert('uint32array' === type({}));
    });

    it('float32array', function () {
      stubObjectToStringOnce('[object Float32Array]');
      assert('float32array' === type({}));
    });

    it('float64array', function () {
      stubObjectToStringOnce('[object Float64Array]');
      assert('float64array' === type({}));
    });

    it('dataview', function () {
      stubObjectToStringOnce('[object DataView]');
      assert('dataview' === type({}));
    });

    it('arraybuffer', function () {
      stubObjectToStringOnce('[object ArrayBuffer]');
      assert('arraybuffer' === type({}));
    });

    var originalObjectToString = Object.prototype.toString;

    function stubObjectToStringOnce(staticValue) {
      Object.prototype.toString = function () {
        Object.prototype.toString = originalObjectToString;
        return staticValue;
      };
    }
  });
});
<|endoftext|>


<commit_before>/*globals window, $, clearInterval, setInterval */

$(function () {
  "use strict";

  var          hl,
         newsList = $('.news-headlines'),
    newsListItems = $('.news-headlines li'),
    firstNewsItem = $('.news-headlines li:nth-child(1)'),
      newsPreview = $('.news-preview'),
          elCount = $('.news-headlines').children(':not(.highlight)').index(),
         vPadding = (parseInt(firstNewsItem.css('padding-top').replace('px', ''), 10)) +
                    (parseInt(firstNewsItem.css('padding-bottom').replace('px', ''), 10)),
          vMargin = (parseInt(firstNewsItem.css('margin-top').replace('px', ''), 10)) +
                    (parseInt(firstNewsItem.css('margin-bottom').replace('px', ''), 10)),
            speed = 5000, // this is the speed of the switch
          myTimer = null,
         siblings = null,
      totalHeight = null,
          indexEl = 1,
                i = null;

  // the css animation gets added dynamicallly so
  // that the news item sizes are measured correctly
  // (i.e. not in mid-animation)
  // Also, appending the highlight item to keep HTML clean
  newsList.append('

');
  hl = $('.highlight');
  newsListItems.addClass('nh-anim');

  function doEqualHeight() {

    if (newsPreview.height() < newsList.height()) {
      newsPreview.height(newsList.height());
    } else if ((newsList.height() < newsPreview.height()) && (newsList.height() > parseInt(newsPreview.css('min-height').replace('px', ''), 10))) {
      newsPreview.height(newsList.height());
    }

  }

  function doTimedSwitch() {

    myTimer = setInterval(function () {
      if (($('.selected').prev().index() + 1) === elCount) {
        firstNewsItem.trigger('click');
      } else {
        $('.selected').next(':not(.highlight)').trigger('click');
      }
    }, speed);

  }

  function doClickItem() {

    newsListItems.on('click', function () {

      newsListItems.removeClass('selected');
      $(this).addClass('selected');

      siblings = $(this).prevAll();
      totalHeight = 0;

      // this loop calculates the height of individual elements, including margins/padding
      for (i = 0; i < siblings.length; i += 1) {
          totalHeight += $(siblings[i]).height();
          totalHeight += vPadding;
          totalHeight += vMargin;
      }

      // this moves the highlight vertically the distance calculated in the previous loop
      // and also corrects the height of the highlight to match the current selection
      hl.css({
        top: totalHeight,
        height: $(this).height() + vPadding
      });

      indexEl = $(this).index() + 1;

      $('.news-content:nth-child(' + indexEl + ')').siblings().removeClass('top-content');
      $('.news-content:nth-child(' + indexEl + ')').addClass('top-content');

      clearInterval(myTimer);
      doTimedSwitch();

    });

  }

  function doWindowResize() {

    $(window).resize(function () {

      clearInterval(myTimer);
      // click is triggered to recalculate and fix the highlight position
      $('.selected').trigger('click');

      doEqualHeight();

    });

  }

  // this is the poor man's 'init' section
  doClickItem();
  doWindowResize();
  doEqualHeight();
  $('.selected').trigger('click');

});<commit_msg>comment for timed switch<commit_after>/*globals window, $, clearInterval, setInterval */

$(function () {
  "use strict";

  var          hl,
         newsList = $('.news-headlines'),
    newsListItems = $('.news-headlines li'),
    firstNewsItem = $('.news-headlines li:nth-child(1)'),
      newsPreview = $('.news-preview'),
          elCount = $('.news-headlines').children(':not(.highlight)').index(),
         vPadding = (parseInt(firstNewsItem.css('padding-top').replace('px', ''), 10)) +
                    (parseInt(firstNewsItem.css('padding-bottom').replace('px', ''), 10)),
          vMargin = (parseInt(firstNewsItem.css('margin-top').replace('px', ''), 10)) +
                    (parseInt(firstNewsItem.css('margin-bottom').replace('px', ''), 10)),
            speed = 5000, // this is the speed of the switch
          myTimer = null,
         siblings = null,
      totalHeight = null,
          indexEl = 1,
                i = null;

  // the css animation gets added dynamicallly so
  // that the news item sizes are measured correctly
  // (i.e. not in mid-animation)
  // Also, appending the highlight item to keep HTML clean
  newsList.append('

');
  hl = $('.highlight');
  newsListItems.addClass('nh-anim');

  function doEqualHeight() {

    if (newsPreview.height() < newsList.height()) {
      newsPreview.height(newsList.height());
    } else if ((newsList.height() < newsPreview.height()) && (newsList.height() > parseInt(newsPreview.css('min-height').replace('px', ''), 10))) {
      newsPreview.height(newsList.height());
    }

  }

  function doTimedSwitch() {

    myTimer = setInterval(function () {
      if (($('.selected').prev().index() + 1) === elCount) {
        firstNewsItem.trigger('click');
      } else {
        $('.selected').next(':not(.highlight)').trigger('click');
      }
    }, speed);

  }

  function doClickItem() {

    newsListItems.on('click', function () {

      newsListItems.removeClass('selected');
      $(this).addClass('selected');

      siblings = $(this).prevAll();
      totalHeight = 0;

      // this loop calculates the height of individual elements, including margins/padding
      for (i = 0; i < siblings.length; i += 1) {
          totalHeight += $(siblings[i]).height();
          totalHeight += vPadding;
          totalHeight += vMargin;
      }

      // this moves the highlight vertically the distance calculated in the previous loop
      // and also corrects the height of the highlight to match the current selection
      hl.css({
        top: totalHeight,
        height: $(this).height() + vPadding
      });

      indexEl = $(this).index() + 1;

      $('.news-content:nth-child(' + indexEl + ')').siblings().removeClass('top-content');
      $('.news-content:nth-child(' + indexEl + ')').addClass('top-content');

      clearInterval(myTimer);
      // comment out the line below if you don't
      // want it to rotate automatically
      doTimedSwitch();

    });

  }

  function doWindowResize() {

    $(window).resize(function () {

      clearInterval(myTimer);
      // click is triggered to recalculate and fix the highlight position
      $('.selected').trigger('click');

      doEqualHeight();

    });

  }

  // this is the poor man's 'init' section
  doClickItem();
  doWindowResize();
  doEqualHeight();
  $('.selected').trigger('click');

});<|endoftext|>


<commit_before>(global => {
  'use strict';
  // Allows development without connecting to an external display
  var isDev = global.isDev;

  /**
   * Not used or called by Polymer.
   * @constructor
   */
  function DisplayController() {}
  global.DisplayController = DisplayController;
  DisplayController.prototype = {

    get DISPLAY_WINDOW_ID() {
      return 'displayWindow';
    },

    /**
     * Preemptively creates a display window and moves it to an external display
     * if one exists. Effectively the constructor in Polymer.
     */
    created() {
      Promise.all([
        // Create the display window async
        new Promise(resolve =>
          chrome.app.window.create('build/display.html',
            {
              id: this.DISPLAY_WINDOW_ID,
              alwaysOnTop: !isDev,
              frame: 'none',
              focused: false,
              hidden: true,
              resizable: false,
              state: !isDev ? 'maximized' : 'normal',
              visibleOnAllWorkspaces: true
            },
            displayWindow => {
              this._displayWindow = displayWindow;
              resolve(displayWindow);
          })
        ),

        // Get the external display info async
        this.getExternalDisplayInfo()

     // Finally, move the new display window to the external display found
     ]).then(() => this._moveToExternalDisplayOnLoad());
    },

    /**
     * Toggles the showing of the display window and the text of the toggle
     * button
     * @param {Event} event contains the start/stop button as the target
     */
    toggleDisplay(event) {
      if (!this._toggleDisplayAndText(event.currentTarget)) {
        return;
      }
      // TODO: Else handle no display window
      // TODO: Prevent display close? Or explicitly toggle button text on close?
    },

    /**
     * Finds the first enabled external monitor and caches it.
     * @return {Promise} a promise resolved with an object containing external
     * display info, otherwise rejected with an error
     */
    getExternalDisplayInfo() {
      return new Promise((resolve, reject) =>
        chrome.system.display.getInfo(displayInfos => {
          for (var i = displayInfos.length - 1; i >= 0; i--) {
            if (isDev || !displayInfos[i].isPrimary && displayInfos[i].isEnabled) {
              resolve(this._externalDisplayInfo = displayInfos[i]);
              break;
            }
          }
          reject(new Error('Cannot find an external display.'));
        })
      );
    },

    //--------------------------------------------------------------------------
    //----------------------------  PRIVATE  -----------------------------------

    _isShowingDisplay: false,
    _displayWindow: null,
    _externalDisplayInfo: null,

    /**
     * Toggles the showing and hiding of the display window and adjusts the
     * button text accordingly. Takes in account of dynamic changes to available
     * external displays.
     * @private
     * @param {Node} button Toggle element containing text
     * @return {?AppWindow} Current display window if it exists, otherwise
     * return null
     */
    _toggleDisplayAndText: function(button) {
      // Hide current display window if it's showing
      if (this._displayWindow) {
        if(this._isShowingDisplay) {
          this._displayWindow.hide();
          this._isShowingDisplay = false;
          // Setting textContent on paper-button directly is bugged so find it
          // Note: might be bugged only for shady DOM
          button.$$('.content').textContent = 'Show';
        } else {
          // Query for external monitor each time before showing in case
          // existing monitor is disabled or not available
          this.getExternalDisplayInfo()
          .then(() => {
            this._moveToExternalDisplay(true);
            this._isShowingDisplay = true;
            button.$$('.content').textContent = 'Stop';
          });
        }
      }
      return this._displayWindow;
    },

    /**
     * Attaches an event listener to the current display window so that it will
     * move the display window to the external display on display window load.
     * Showing after the window contents loads reduces chance of white flash due
     * to page loading.
     * @private
     * @param {boolean=} opt_shouldShow Shows display window on load if true
     */
    _moveToExternalDisplayOnLoad(opt_shouldShow) {
      this._displayWindow.contentWindow.addEventListener('load', () =>
        this._moveToExternalDisplay(opt_shouldShow)
      );
    },

    /**
     * Moves the current display window to the current external display
     * immediately.
     * @private
     * @param {boolean=} opt_shouldShow Shows display window on load if true
     */
    _moveToExternalDisplay(opt_shouldShow) {
        this._displayWindow.outerBounds.left = this._externalDisplayInfo.bounds.left;
        if (!isDev) {
          this._displayWindow.maximize();
        }
        if (opt_shouldShow) {
          this._displayWindow.show(false);
        }
    }

  };
})(this);
<commit_msg>Fix display toggle button text not changing (don't use textContent as it affects descendants)<commit_after>(global => {
  'use strict';
  // Allows development without connecting to an external display
  var isDev = global.isDev;

  /**
   * Not used or called by Polymer.
   * @constructor
   */
  function DisplayController() {}
  global.DisplayController = DisplayController;
  DisplayController.prototype = {

    get DISPLAY_WINDOW_ID() {
      return 'displayWindow';
    },

    /**
     * Polymer lifecycle callback before created().
     */
    ready() {
      // Merges text nodes to allow changing of button text w/o affecting
      // descendants
      this.$.displayToggle.normalize();
    },

    /**
     * Preemptively creates a display window and moves it to an external display
     * if one exists. Effectively the constructor in Polymer.
     */
    created() {
      Promise.all([
        // Create the display window async
        new Promise(resolve =>
          chrome.app.window.create('build/display.html',
            {
              id: this.DISPLAY_WINDOW_ID,
              alwaysOnTop: !isDev,
              frame: 'none',
              focused: false,
              hidden: true,
              resizable: false,
              state: !isDev ? 'maximized' : 'normal',
              visibleOnAllWorkspaces: true
            },
            displayWindow => {
              this._displayWindow = displayWindow;
              resolve(displayWindow);
          })
        ),

        // Get the external display info async
        this.getExternalDisplayInfo()

     // Finally, move the new display window to the external display found
     ]).then(() => this._moveToExternalDisplayOnLoad());
    },

    /**
     * Toggles the showing of the display window and the text of the toggle
     * button
     * @param {Event} event contains the start/stop button as the target
     */
    toggleDisplay(event) {
      if (!this._toggleDisplayAndText(event.currentTarget)) {
        return;
      }
      // TODO: Else handle no display window
      // TODO: Prevent display close? Or explicitly toggle button text on close?
    },

    /**
     * Finds the first enabled external monitor and caches it.
     * @return {Promise} a promise resolved with an object containing external
     * display info, otherwise rejected with an error
     */
    getExternalDisplayInfo() {
      return new Promise((resolve, reject) =>
        chrome.system.display.getInfo(displayInfos => {
          for (var i = displayInfos.length - 1; i >= 0; i--) {
            if (isDev || !displayInfos[i].isPrimary && displayInfos[i].isEnabled) {
              resolve(this._externalDisplayInfo = displayInfos[i]);
              break;
            }
          }
          reject(new Error('Cannot find an external display.'));
        })
      );
    },

    //--------------------------------------------------------------------------
    //----------------------------  PRIVATE  -----------------------------------

    _isShowingDisplay: false,
    _displayWindow: null,
    _externalDisplayInfo: null,

    /**
     * Toggles the showing and hiding of the display window and adjusts the
     * button text accordingly. Takes in account of dynamic changes to available
     * external displays.
     * @private
     * @param {Node} button Toggle element containing text
     * @return {?AppWindow} Current display window if it exists, otherwise
     * return null
     */
    _toggleDisplayAndText: function(button) {
      // Hide current display window if it's showing
      if (this._displayWindow) {
        if (this._isShowingDisplay) {
          this._displayWindow.hide();
          this._isShowingDisplay = false;
          // NOTE: Potentially fragile use of paper-button
          button.firstChild.data = 'Show';
        } else {
          // Query for external monitor each time before showing in case
          // existing monitor is disabled or not available
          this.getExternalDisplayInfo()
          .then(() => {
            this._moveToExternalDisplay(true);
            this._isShowingDisplay = true;
            button.firstChild.data = 'Stop';
          });
        }
      }
      return this._displayWindow;
    },

    /**
     * Attaches an event listener to the current display window so that it will
     * move the display window to the external display on display window load.
     * Showing after the window contents loads reduces chance of white flash due
     * to page loading.
     * @private
     * @param {boolean=} opt_shouldShow Shows display window on load if true
     */
    _moveToExternalDisplayOnLoad(opt_shouldShow) {
      this._displayWindow.contentWindow.addEventListener('load', () =>
        this._moveToExternalDisplay(opt_shouldShow)
      );
    },

    /**
     * Moves the current display window to the current external display
     * immediately.
     * @private
     * @param {boolean=} opt_shouldShow Shows display window on load if true
     */
    _moveToExternalDisplay(opt_shouldShow) {
        this._displayWindow.outerBounds.left = this._externalDisplayInfo.bounds.left;
        if (!isDev) {
          this._displayWindow.maximize();
        }
        if (opt_shouldShow) {
          this._displayWindow.show(false);
        }
    }

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


<commit_before>(function () {
    'use strict';

    angular
        .module('dpHeader')
        .component('dpHeader', {
            templateUrl: 'modules/header/components/header/header.html',
            controller: DpHeaderController,
            controllerAs: 'vm',
            bindings: {
                isHomePage: '<',
                hasMaxWidth: '<',
                isEmbed: '<',
                isPrintMode: '<',
                isEmbedPreview: '<',
                user: '<',
                isPrintOrEmbedOrPreview: '<'
            }
        });

    function DpHeaderController (HEADER) {
        const vm = this;

        vm.headerSize = vm.isHomePage ? HEADER.SIZE.TALL : HEADER.SIZE.SHORT;
    }

    DpHeaderController.$inject = ['HEADER'];
})();
<commit_msg>Make header component watch isHomepage binding<commit_after>(function () {
    'use strict';

    angular
        .module('dpHeader')
        .component('dpHeader', {
            templateUrl: 'modules/header/components/header/header.html',
            controller: DpHeaderController,
            controllerAs: 'vm',
            bindings: {
                isHomePage: '<',
                hasMaxWidth: '<',
                isEmbed: '<',
                isPrintMode: '<',
                isEmbedPreview: '<',
                user: '<',
                isPrintOrEmbedOrPreview: '<'
            }
        });

    function DpHeaderController ($scope, HEADER) {
        const vm = this;
        $scope.$watch('vm.isHomePage', updateSize);

        function updateSize () {
            vm.headerSize = vm.isHomePage ? HEADER.SIZE.TALL : HEADER.SIZE.SHORT;
        }

        updateSize();
    }

    DpHeaderController.$inject = ['$scope', 'HEADER'];
})();
<|endoftext|>


<commit_before>/*
map.on('style.load', function() {
	map.addSource('perm', source);
});*/

$(function() {
    //Sets map based on graph data from server
    $.ajax(otp_config.hostname+"/metadata", {
        dataType: 'JSON',
        success: function(data) {
            window.map.fitBounds([
                [data.envelope.minX, data.envelope.minY],
                [data.envelope.maxX, data.envelope.maxY]
            ],
            {speed:100
            });
        }
    });
    makeGUI();
    //request new geojson on map move
    map.on('moveend', function() {
        updateMap();
    });

    //shows hower tag on map and shows a popup
    map.on('click', function(e) {
        // query the map for the under the mouse
        map.featuresAt(e.point, { radius: 5, includeGeometry: true }, function (err, features) {
            if (err) throw err;
            //console.log(e.point, features);
            var ids = features.map(function (feat) { return feat.properties.edge_id });
            if (ids.length == 1) {
                var pop_html = fillPopup(features[0], current_layer);
                if (pop_html != null) {
                    var tooltip = new mapboxgl.Popup()
                    .setLngLat(e.lngLat)
                    .setHTML(pop_html)
                    .addTo(map);
                }
            }

            // set the filter on the hover style layer to only select the features
            // currently under the mouse
            map.setFilter('perm-hover', [ 'all',
                        [ 'in', 'edge_id' ].concat(ids)
            ]);
        });
    });

    //disables map rotation
    map.dragRotate.disable();
    getStyle(current_type);
});
<commit_msg>Show multiple popups if multiple edges are under cursor<commit_after>/*
map.on('style.load', function() {
	map.addSource('perm', source);
});*/

$(function() {
    //Sets map based on graph data from server
    $.ajax(otp_config.hostname+"/metadata", {
        dataType: 'JSON',
        success: function(data) {
            window.map.fitBounds([
                [data.envelope.minX, data.envelope.minY],
                [data.envelope.maxX, data.envelope.maxY]
            ],
            {speed:100
            });
        }
    });
    makeGUI();
    //request new geojson on map move
    map.on('moveend', function() {
        updateMap();
    });

    //shows hower tag on map and shows a popup
    map.on('click', function(e) {
        // query the map for the under the mouse
        map.featuresAt(e.point, { radius: 5, includeGeometry: true }, function (err, features) {
            if (err) throw err;
            var seen_ids = Object.create(null);
            var pop_html = "";
            for(var i=0; i < features.length; i++) {
                var feature = features[i];
                if (!(feature.properties.edge_id in seen_ids)) {
                    pop_html += fillPopup(feature, current_layer);
                    seen_ids[feature.properties.edge_id] = true;
                }
            }
            if (pop_html.length > 10) {
                var tooltip = new mapboxgl.Popup()
                .setLngLat(e.lngLat)
                .setHTML(pop_html)
                .addTo(map);
            }
            var ids = Object.keys(seen_ids).map(function (string_id) { return parseInt(string_id); });

            // set the filter on the hover style layer to only select the features
            // currently under the mouse
            map.setFilter('perm-hover', [ 'all',
                        [ 'in', 'edge_id' ].concat(ids)
            ]);
        });
    });

    //disables map rotation
    map.dragRotate.disable();
    getStyle(current_type);
});
<|endoftext|>


<commit_before>'use strict';

// Load modules

const Joi = require('joi');
const FilesizeParser = require('filesize-parser');

module.exports = {

    name: 'number',

    base: Joi.number().min(0),

    language: {
        fileSize: 'must be a valid file size'
    },

    coerce(value, state, options) {

        if (!value || typeof value === 'number') {
            return value;
        }

        if (options.convert) {
            try {
                return FilesizeParser(FilesizeParser(value, {
                    base: this._flags.filesizeBase
                }));
            }
            catch (ignore) {
                return this.createError('number.fileSize', { value }, state, options);
            }
        }

        return value;
    },

    rules: [
        {
            name: 'filesize',
            description: 'Should be a valid file size',
            params: {
                parserParams: Joi.object().keys({
                    base: Joi.only(2, 10)
                })
            },
            setup(params) {

                const parserParams = params.parserParams || {};

                this._flags.filesizeBase = parserParams.base || 10;
            },
            validate(params, value, state, options) {

                // No-op just to enable description
                return value;
            }
        }
    ]

};
<commit_msg>remove redundant call to filesize-parser<commit_after>'use strict';

// Load modules

const Joi = require('joi');
const FilesizeParser = require('filesize-parser');

module.exports = {

    name: 'number',

    base: Joi.number().min(0),

    language: {
        fileSize: 'must be a valid file size'
    },

    coerce(value, state, options) {

        if (!value || typeof value === 'number') {
            return value;
        }

        if (options.convert) {
            try {
                return FilesizeParser(value, {
                    base: this._flags.filesizeBase
                });
            }
            catch (ignore) {
                return this.createError('number.fileSize', { value }, state, options);
            }
        }

        return value;
    },

    rules: [
        {
            name: 'filesize',
            description: 'Should be a valid file size',
            params: {
                parserParams: Joi.object().keys({
                    base: Joi.only(2, 10)
                })
            },
            setup(params) {

                const parserParams = params.parserParams || {};

                this._flags.filesizeBase = parserParams.base || 10;
            },
            validate(params, value, state, options) {

                // No-op just to enable description
                return value;
            }
        }
    ]

};
<|endoftext|>


<commit_before>/* Copyright (c) 2006-2007 MetaCarta, Inc., published under the Clear BSD
 * license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Geometry.js
 *
 * Class: OpenLayers.Geometry.Rectangle
 * A Rectangle is a simple geometry. It is specified by a a point (x and y)
 *     and dimensions (width and height), all of which are directly accessible
 *     as properties.
 *
 * Inherits:
 *  - <OpenLayers.Geometry>
 */

OpenLayers.Geometry.Rectangle = OpenLayers.Class(OpenLayers.Geometry, {

    /**
     * Property: x
     * {Float}
     */
    x: null,

    /**
     * Property: y
     * {Float}
     */
    y: null,

    /**
     * Property: width
     * {Float}
     */
    width: null,

    /**
     * Property: height
     * {Float}
     */
    height: null,

    /**
     * Constructor: OpenLayers.Geometry.Rectangle
     *
     * Parameters:
     * points - {Array(<OpenLayers.Geometry.Point>}
     */
    initialize: function(x, y, width, height) {
        OpenLayers.Geometry.prototype.initialize.apply(this, arguments);

        this.x = x;
        this.y = y;

        this.width = width;
        this.height = height;
    },

    /**
     * Method: calculateBounds
     * Recalculate the bounds for the geometry.
     */
    calculateBounds: function() {
        this.bounds = new OpenLayers.Bounds(this.x, this.y,
                                            this.x + this.width,
                                            this.y + this.height);
    },

    /**
     * APIMethod: getLength
     *
     * Returns:
     * {Float} The length of the geometry
     */
    getLength: function() {
        var length = (2 * this.width) + (2 * this.height);
        return length;
    },

    /**
     * APIMethod: getArea
     *
     * Returns:
     * {Float} The area of the geometry
     */
    getArea: function() {
        var area = this.width * this.height;
        return area;
    },

    CLASS_NAME: "OpenLayers.Geometry.Rectangle"
});
<commit_msg>fix ND comment typo<commit_after>/* Copyright (c) 2006-2007 MetaCarta, Inc., published under the Clear BSD
 * license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Geometry.js
 *
 * Class: OpenLayers.Geometry.Rectangle
 * A Rectangle is a simple geometry. It is specified by a point (x and y)
 *     and dimensions (width and height), all of which are directly accessible
 *     as properties.
 *
 * Inherits:
 *  - <OpenLayers.Geometry>
 */

OpenLayers.Geometry.Rectangle = OpenLayers.Class(OpenLayers.Geometry, {

    /**
     * Property: x
     * {Float}
     */
    x: null,

    /**
     * Property: y
     * {Float}
     */
    y: null,

    /**
     * Property: width
     * {Float}
     */
    width: null,

    /**
     * Property: height
     * {Float}
     */
    height: null,

    /**
     * Constructor: OpenLayers.Geometry.Rectangle
     *
     * Parameters:
     * points - {Array(<OpenLayers.Geometry.Point>}
     */
    initialize: function(x, y, width, height) {
        OpenLayers.Geometry.prototype.initialize.apply(this, arguments);

        this.x = x;
        this.y = y;

        this.width = width;
        this.height = height;
    },

    /**
     * Method: calculateBounds
     * Recalculate the bounds for the geometry.
     */
    calculateBounds: function() {
        this.bounds = new OpenLayers.Bounds(this.x, this.y,
                                            this.x + this.width,
                                            this.y + this.height);
    },

    /**
     * APIMethod: getLength
     *
     * Returns:
     * {Float} The length of the geometry
     */
    getLength: function() {
        var length = (2 * this.width) + (2 * this.height);
        return length;
    },

    /**
     * APIMethod: getArea
     *
     * Returns:
     * {Float} The area of the geometry
     */
    getArea: function() {
        var area = this.width * this.height;
        return area;
    },

    CLASS_NAME: "OpenLayers.Geometry.Rectangle"
});
<|endoftext|>