<commit_before>/**
 * @name      ElkArte Forum
 * @copyright ElkArte Forum contributors
 * @license   BSD http://opensource.org/licenses/BSD-3-Clause
 *
 * This software is a derived product, based on:
 *
 * Simple Machines Forum (SMF)
 * copyright:	2011 Simple Machines (http://www.simplemachines.org)
 * license:  	BSD, See included LICENSE.TXT for terms and conditions.
 *
 * @version 1.0 Beta
 *
 * This file contains javascript associated with the user profile
 */

/**
 * Function to detect the time offset and populate the offset box
 *
 * @param {string} currentTime
 */
var localTime = new Date();
function autoDetectTimeOffset(currentTime)
{
	if (typeof(currentTime) !== 'string')
		var serverTime = currentTime;
	else
		var serverTime = new Date(currentTime);

	// Something wrong?
	if (!localTime.getTime() || !serverTime.getTime())
		return 0;

	// Get the difference between the two, set it up so that the sign will tell us who is ahead of who.
	var diff = Math.round((localTime.getTime() - serverTime.getTime())/3600000);

	// Make sure we are limiting this to one day's difference.
	diff %= 24;

	return diff;
}

/**
 * Prevent Chrome from auto completing fields when viewing/editing other members profiles
 */
function disableAutoComplete()
{
	if (is_chrome && document.addEventListener)
		document.addEventListener("DOMContentLoaded", disableAutoCompleteNow, false);
}

/**
 * Once DOMContentLoaded is triggered, call the function
 */
function disableAutoCompleteNow()
{
	for (var i = 0, n = document.forms.length; i < n; i++)
	{
		var die = document.forms[i].elements;
		for (var j = 0, m = die.length; j < m; j++)
			// Only bother with text/password fields?
			if (die[j].type === "text" || die[j].type === "password")
				die[j].setAttribute("autocomplete", "off");
	}
}

/**
 * Calculates the number of available characters remaining when filling in the
 * signature box
 */
function calcCharLeft()
{
	var oldSignature = "",
		currentSignature = document.forms.creator.signature.value,
		currentChars = 0;

	if (!document.getElementById("signatureLeft"))
		return;

	if (oldSignature !== currentSignature)
	{
		oldSignature = currentSignature;

		var currentChars = currentSignature.replace(/\r/, "").length;
		if (is_opera)
			currentChars = currentSignature.replace(/\r/g, "").length;

		if (currentChars > maxLength)
			document.getElementById("signatureLeft").className = "error";
		else
			document.getElementById("signatureLeft").className = "";

		if (currentChars > maxLength && !$("#profile_error").is(":visible"))
			ajax_getSignaturePreview(false);
		else if (currentChars <= maxLength && $("#profile_error").is(":visible"))
		{
			$("#profile_error").css({display:"none"});
			$("#profile_error").html('');
		}
	}

	setInnerHTML(document.getElementById("signatureLeft"), maxLength - currentChars);
}

/**
 * Gets the signature preview via ajax and populates the preview box
 *
 * @param {boolean} showPreview
 */
function ajax_getSignaturePreview(showPreview)
{
	showPreview = (typeof showPreview === 'undefined') ? false : showPreview;
	$.ajax({
		type: "POST",
		url: elk_scripturl + "?action=xmlpreview;xml",
		data: {item: "sig_preview", signature: $("#signature").val(), user: $('input[name="u"]').attr("value")},
		context: document.body
	})
	.done(function(request) {
		if (showPreview)
		{
			var signatures = new Array("current", "preview");
			for (var i = 0; i < signatures.length; i++)
			{
				$("#" + signatures[i] + "_signature").css({display:""});
				$("#" + signatures[i] + "_signature_display").css({display:""}).html($(request).find('[type="' + signatures[i] + '"]').text() + '
');
			}
		}

		if ($(request).find("error").text() !== '')
		{
			if (!$("#profile_error").is(":visible"))
				$("#profile_error").css({display: "", position: "fixed", top: 0, left: 0, width: "100%"});

			var errors = $(request).find('[type="error"]'),
				errors_html = '' + $(request).find('[type="errors_occurred"]').text() + '
';

			for (var i = 0; i < errors.length; i++)
				errors_html += '
' + $(errors).text() + '
';

			errors_html += '
';
			$(document).find("#profile_error").html(errors_html);
		}
		else
		{
			$("#profile_error").css({display:"none"});
			$("#profile_error").html('');
		}
		return false;
	});

	return false;
}

/**
 * Allows previewing of server stored avatars stored.
 *
 * @param {type} selected
 */
function changeSel(selected)
{
	if (cat.selectedIndex === -1)
		return;

	if (cat.options[cat.selectedIndex].value.indexOf("/") > 0)
	{
		var i;
		var count = 0;

		file.style.display = "inline";
		file.disabled = false;

		for (i = file.length; i >= 0; i = i - 1)
			file.options[i] = null;

		for (i = 0; i < files.length; i++)
			if (files[i].indexOf(cat.options[cat.selectedIndex].value) === 0)
			{
				var filename = files[i].substr(files[i].indexOf("/") + 1);
				var showFilename = filename.substr(0, filename.lastIndexOf("."));
				showFilename = showFilename.replace(/[_]/g, " ");

				file.options[count] = new Option(showFilename, files[i]);

				if (filename === selected)
				{
					if (file.options.defaultSelected)
						file.options[count].defaultSelected = true;
					else
						file.options[count].selected = true;
				}

				count++;
			}

		if (file.selectedIndex === -1 && file.options[0])
			file.options[0].selected = true;

		showAvatar();
	}
	else
	{
		file.style.display = "none";
		file.disabled = true;
		document.getElementById("avatar").src = avatardir + cat.options[cat.selectedIndex].value;
		document.getElementById("avatar").style.width = "";
		document.getElementById("avatar").style.height = "";
	}
}

/**
 * Updates the avatar img preview with the selected one
 */
function showAvatar()
{
	if (file.selectedIndex === -1)
		return;

	oAvatar = document.getElementById("avatar");

	oAvatar.src = avatardir + file.options[file.selectedIndex].value;
	oAvatar.alt = file.options[file.selectedIndex].text;
	oAvatar.alt += file.options[file.selectedIndex].text === size ? "!" : "";
	oAvatar.style.width = "";
	oAvatar.style.height = "";
}

/**
 * Allows for the previewing of an externally stored avatar
 *
 * @param {string} src
 * @param {string} sid
 */
function previewExternalAvatar(src, sid)
{
	sid = (typeof(sid) === 'undefined') ? "avatar" : sid;

	if (!document.getElementById(sid))
		return;

	var tempImage = new Image();

	tempImage.src = src;
	if (maxWidth !== 0 && tempImage.width > maxWidth)
	{
		document.getElementById(sid).style.height = parseInt((maxWidth * tempImage.height) / tempImage.width) + "px";
		document.getElementById(sid).style.width = maxWidth + "px";
	}
	else if (maxHeight !== 0 && tempImage.height > maxHeight)
	{
		document.getElementById(sid).style.width = parseInt((maxHeight * tempImage.width) / tempImage.height) + "px";
		document.getElementById(sid).style.height = maxHeight + "px";
	}
	document.getElementById(sid).src = src;
}<commit_msg>! clean up some un-needed var statements<commit_after>/**
 * @name      ElkArte Forum
 * @copyright ElkArte Forum contributors
 * @license   BSD http://opensource.org/licenses/BSD-3-Clause
 *
 * This software is a derived product, based on:
 *
 * Simple Machines Forum (SMF)
 * copyright:	2011 Simple Machines (http://www.simplemachines.org)
 * license:		BSD, See included LICENSE.TXT for terms and conditions.
 *
 * @version 1.0 Beta
 *
 * This file contains javascript associated with the user profile
 */

/**
 * Function to detect the time offset and populate the offset box
 *
 * @param {string} currentTime
 */
var localTime = new Date();
function autoDetectTimeOffset(currentTime)
{
	var serverTime;

	if (typeof(currentTime) !== 'string')
		serverTime = currentTime;
	else
		serverTime = new Date(currentTime);

	// Something wrong?
	if (!localTime.getTime() || !serverTime.getTime())
		return 0;

	// Get the difference between the two, set it up so that the sign will tell us who is ahead of who.
	var diff = Math.round((localTime.getTime() - serverTime.getTime())/3600000);

	// Make sure we are limiting this to one day's difference.
	diff %= 24;

	return diff;
}

/**
 * Prevent Chrome from auto completing fields when viewing/editing other members profiles
 */
function disableAutoComplete()
{
	if (is_chrome && document.addEventListener)
		document.addEventListener("DOMContentLoaded", disableAutoCompleteNow, false);
}

/**
 * Once DOMContentLoaded is triggered, call the function
 */
function disableAutoCompleteNow()
{
	for (var i = 0, n = document.forms.length; i < n; i++)
	{
		var die = document.forms[i].elements;
		for (var j = 0, m = die.length; j < m; j++)
			// Only bother with text/password fields?
			if (die[j].type === "text" || die[j].type === "password")
				die[j].setAttribute("autocomplete", "off");
	}
}

/**
 * Calculates the number of available characters remaining when filling in the
 * signature box
 */
function calcCharLeft()
{
	var oldSignature = "",
		currentSignature = document.forms.creator.signature.value,
		currentChars = 0;

	if (!document.getElementById("signatureLeft"))
		return;

	if (oldSignature !== currentSignature)
	{
		oldSignature = currentSignature;

		currentChars = currentSignature.replace(/\r/, "").length;
		if (is_opera)
			currentChars = currentSignature.replace(/\r/g, "").length;

		if (currentChars > maxLength)
			document.getElementById("signatureLeft").className = "error";
		else
			document.getElementById("signatureLeft").className = "";

		if (currentChars > maxLength && !$("#profile_error").is(":visible"))
			ajax_getSignaturePreview(false);
		else if (currentChars <= maxLength && $("#profile_error").is(":visible"))
		{
			$("#profile_error").css({display:"none"});
			$("#profile_error").html('');
		}
	}

	setInnerHTML(document.getElementById("signatureLeft"), maxLength - currentChars);
}

/**
 * Gets the signature preview via ajax and populates the preview box
 *
 * @param {boolean} showPreview
 */
function ajax_getSignaturePreview(showPreview)
{
	showPreview = (typeof showPreview === 'undefined') ? false : showPreview;
	$.ajax({
		type: "POST",
		url: elk_scripturl + "?action=xmlpreview;xml",
		data: {item: "sig_preview", signature: $("#signature").val(), user: $('input[name="u"]').attr("value")},
		context: document.body
	})
	.done(function(request) {
		var i = 0;
		if (showPreview)
		{
			var signatures = new Array("current", "preview");
			for (i = 0; i < signatures.length; i++)
			{
				$("#" + signatures[i] + "_signature").css({display:""});
				$("#" + signatures[i] + "_signature_display").css({display:""}).html($(request).find('[type="' + signatures[i] + '"]').text() + '
');
			}
		}

		if ($(request).find("error").text() !== '')
		{
			if (!$("#profile_error").is(":visible"))
				$("#profile_error").css({display: "", position: "fixed", top: 0, left: 0, width: "100%"});

			var errors = $(request).find('[type="error"]'),
				errors_html = '' + $(request).find('[type="errors_occurred"]').text() + '
';

			for (i = 0; i < errors.length; i++)
				errors_html += '
' + $(errors).text() + '
';

			errors_html += '
';
			$(document).find("#profile_error").html(errors_html);
		}
		else
		{
			$("#profile_error").css({display:"none"});
			$("#profile_error").html('');
		}
		return false;
	});

	return false;
}

/**
 * Allows previewing of server stored avatars stored.
 *
 * @param {type} selected
 */
function changeSel(selected)
{
	if (cat.selectedIndex === -1)
		return;

	if (cat.options[cat.selectedIndex].value.indexOf("/") > 0)
	{
		var i,
			count = 0;

		file.style.display = "inline";
		file.disabled = false;

		for (i = file.length; i >= 0; i = i - 1)
			file.options[i] = null;

		for (i = 0; i < files.length; i++)
			if (files[i].indexOf(cat.options[cat.selectedIndex].value) === 0)
			{
				var filename = files[i].substr(files[i].indexOf("/") + 1);
				var showFilename = filename.substr(0, filename.lastIndexOf("."));
				showFilename = showFilename.replace(/[_]/g, " ");

				file.options[count] = new Option(showFilename, files[i]);

				if (filename === selected)
				{
					if (file.options.defaultSelected)
						file.options[count].defaultSelected = true;
					else
						file.options[count].selected = true;
				}

				count++;
			}

		if (file.selectedIndex === -1 && file.options[0])
			file.options[0].selected = true;

		showAvatar();
	}
	else
	{
		file.style.display = "none";
		file.disabled = true;
		document.getElementById("avatar").src = avatardir + cat.options[cat.selectedIndex].value;
		document.getElementById("avatar").style.width = "";
		document.getElementById("avatar").style.height = "";
	}
}

/**
 * Updates the avatar img preview with the selected one
 */
function showAvatar()
{
	if (file.selectedIndex === -1)
		return;

	oAvatar = document.getElementById("avatar");

	oAvatar.src = avatardir + file.options[file.selectedIndex].value;
	oAvatar.alt = file.options[file.selectedIndex].text;
	oAvatar.alt += file.options[file.selectedIndex].text === size ? "!" : "";
	oAvatar.style.width = "";
	oAvatar.style.height = "";
}

/**
 * Allows for the previewing of an externally stored avatar
 *
 * @param {string} src
 * @param {string} sid
 */
function previewExternalAvatar(src, sid)
{
	sid = (typeof(sid) === 'undefined') ? "avatar" : sid;

	if (!document.getElementById(sid))
		return;

	var tempImage = new Image();

	tempImage.src = src;
	if (maxWidth !== 0 && tempImage.width > maxWidth)
	{
		document.getElementById(sid).style.height = parseInt((maxWidth * tempImage.height) / tempImage.width) + "px";
		document.getElementById(sid).style.width = maxWidth + "px";
	}
	else if (maxHeight !== 0 && tempImage.height > maxHeight)
	{
		document.getElementById(sid).style.width = parseInt((maxHeight * tempImage.width) / tempImage.height) + "px";
		document.getElementById(sid).style.height = maxHeight + "px";
	}
	document.getElementById(sid).src = src;
}<|endoftext|>


<commit_before>describe("ES6 Compiling", function(){
    "use strict";
    var assert = require("assert");
    it("should compile ES6 classes", function () {
        class Fraction {
            constructor(number) {
                this.number = number;
            }
            update(number) {
                this.number = number;
            }
        }
        var x = new Fraction(5);
        assert(typeof x === "object");
    });
});<commit_msg>Now the first test is closure linter compliant<commit_after>describe('ES6 Compiling', function() {
  'use strict';
  var assert = require('assert');
  it('should compile ES6 classes', function() {
    class Fraction {
      constructor(number) {
        this.number = number;
      }

      update(number) {
        this.number = number;
      }
    };
    var x = new Fraction(5);
    assert(typeof x === 'object');
  });
});
<|endoftext|>


<commit_before>import React from "react";
import PropTypes from "prop-types";
import injectSheet from "react-jss";

const styles = theme => ({
  bar: {
    position: "absolute",
    bottom: 0,
    left: 0,
    width: '100%'
  }
});

const BottomBar = props => {
  const { classes } = props;

  return
bottom bar
;
};

BottomBar.propTypes = {
  classes: PropTypes.object.isRequired
};

export default injectSheet(styles)(BottomBar);
<commit_msg>bottomBar<commit_after>import React from "react";
import PropTypes from "prop-types";
import injectSheet from "react-jss";

const styles = theme => ({
  bar: {
    position: "absolute",
    left: 0,
    height: "60px",
    borderTop: "1px solid #666",
    bottom: 0,
    width: "100%",
    background: "#fff"
  }
});

const BottomBar = props => {
  const { classes } = props;

  return
bottom bar
;
};

BottomBar.propTypes = {
  classes: PropTypes.object.isRequired
};

export default injectSheet(styles)(BottomBar);
<|endoftext|>


<commit_before>import $ from 'dom7';
import Utils from '../../utils/utils';

const Accordion = {
  toggleClicked($clickedEl) {
    const app = this;
    let $accordionItemEl = $clickedEl.closest('.accordion-item').eq(0);
    if (!$accordionItemEl.length) $accordionItemEl = $clickedEl.parents('li').eq(0);
    app.accordion.toggle($accordionItemEl);
  },
  open(el) {
    const app = this;
    const $el = $(el);
    const $list = $el.parents('.accordion-list').eq(0);
    let $contentEl = $el.children('.accordion-item-content');
    if ($contentEl.length === 0) $contentEl = $el.find('.accordion-item-content');
    if ($contentEl.length === 0) return;
    const $openedItem = $list.length > 0 && $el.parent().children('.accordion-item-opened');
    if ($openedItem.length > 0) {
      app.accordion.close($openedItem);
    }
    $contentEl.transitionEnd(() => {
      if ($el.hasClass('accordion-item-opened')) {
        $contentEl.transition(0);
        $contentEl.css('height', 'auto');
        /* eslint no-underscore-dangle: ["error", { "allow": ["_clientLeft"] }] */
        app._clientLeft = $contentEl[0].clientLeft;
        $contentEl.transition('');
        $el.trigger('accordion:opened');
        app.emit('accordionOpened', $el[0]);
      } else {
        $contentEl.css('height', '');
        $el.trigger('accordion:closed');
        app.emit('accordionClosed', $el[0]);
      }
    });
    $contentEl.css('height', `${$contentEl[0].scrollHeight}px`);
    $el.trigger('accordion:open');
    $el.addClass('accordion-item-opened');
    app.emit('accordionOpen', $el[0]);
  },
  close(el) {
    const app = this;
    const $el = $(el);
    let $contentEl = $el.children('.accordion-item-content');
    if ($contentEl.length === 0) $contentEl = $el.find('.accordion-item-content');
    $el.removeClass('accordion-item-opened');
    $contentEl.transition(0);
    $contentEl.css('height', `${$contentEl[0].scrollHeight}px`);
    /* eslint no-underscore-dangle: ["error", { "allow": ["_clientLeft"] }] */
    app._clientLeft = $contentEl[0].clientLeft;
    $contentEl.transition('');
    // Close
    $contentEl.transitionEnd(() => {
      if ($el.hasClass('accordion-item-opened')) {
        $contentEl.transition(0);
        $contentEl.css('height', 'auto');
        /* eslint no-underscore-dangle: ["error", { "allow": ["_clientLeft"] }] */
        app._clientLeft = $contentEl[0].clientLeft;
        $contentEl.transition('');
        $el.trigger('accordion:opened');
        app.emit('accordionOpened', $el[0]);
      } else {
        $contentEl.css('height', '');
        $el.trigger('accordion:closed');
        app.emit('accordionClosed', $el[0]);
      }
    });
    Utils.nextFrame(() => {
      $contentEl.transition('');
      $contentEl.css('height', '');
      $el.trigger('accordion:close');
      app.emit('accordionClose');
    });
  },
  toggle(el) {
    const app = this;
    const $el = $(el);
    if ($el.length === 0) return;
    if ($el.hasClass('accordion-item-opened')) app.accordion.close(el);
    else app.accordion.open(el);
  },
};

export default {
  name: 'accordion',
  create() {
    const app = this;
    Utils.extend(app, {
      accordion: {
        open: Accordion.open.bind(app),
        close: Accordion.close.bind(app),
        toggle: Accordion.toggle.bind(app),
      },
    });
  },
  clicks: {
    '.accordion-item .item-link, .accordion-item-toggle, .links-list.accordion-list > ul > li > a': function open($clickedEl) {
      const app = this;
      Accordion.toggleClicked.call(app, $clickedEl);
    },
  },
};
<commit_msg>accordion tweaks<commit_after>/* eslint no-underscore-dangle: ["error", { "allow": ["_clientLeft"] }] */
import $ from 'dom7';
import Utils from '../../utils/utils';

const Accordion = {
  toggleClicked($clickedEl) {
    const app = this;
    let $accordionItemEl = $clickedEl.closest('.accordion-item').eq(0);
    if (!$accordionItemEl.length) $accordionItemEl = $clickedEl.parents('li').eq(0);
    app.accordion.toggle($accordionItemEl);
  },
  open(el) {
    const app = this;
    const $el = $(el);
    const $list = $el.parents('.accordion-list').eq(0);
    let $contentEl = $el.children('.accordion-item-content');
    if ($contentEl.length === 0) $contentEl = $el.find('.accordion-item-content');
    if ($contentEl.length === 0) return;
    const $openedItem = $list.length > 0 && $el.parent().children('.accordion-item-opened');
    if ($openedItem.length > 0) {
      app.accordion.close($openedItem);
    }
    $contentEl.transitionEnd(() => {
      if ($el.hasClass('accordion-item-opened')) {
        $contentEl.transition(0);
        $contentEl.css('height', 'auto');
        $contentEl._clientLeft = $contentEl[0].clientLeft;
        $contentEl.transition('');
        $el.trigger('accordion:opened');
        app.emit('accordionOpened', $el[0]);
      } else {
        $contentEl.css('height', '');
        $el.trigger('accordion:closed');
        app.emit('accordionClosed', $el[0]);
      }
    });
    $contentEl.css('height', `${$contentEl[0].scrollHeight}px`);
    $el.trigger('accordion:open');
    $el.addClass('accordion-item-opened');
    app.emit('accordionOpen', $el[0]);
  },
  close(el) {
    const app = this;
    const $el = $(el);
    let $contentEl = $el.children('.accordion-item-content');
    if ($contentEl.length === 0) $contentEl = $el.find('.accordion-item-content');
    $el.removeClass('accordion-item-opened');
    $contentEl.transition(0);
    $contentEl.css('height', `${$contentEl[0].scrollHeight}px`);
    $contentEl._clientLeft = $contentEl[0].clientLeft;
    $contentEl.transition('');
    // Close
    $contentEl.transitionEnd(() => {
      if ($el.hasClass('accordion-item-opened')) {
        $contentEl.transition(0);
        $contentEl.css('height', 'auto');
        $contentEl._clientLeft = $contentEl[0].clientLeft;
        $contentEl.transition('');
        $el.trigger('accordion:opened');
        app.emit('accordionOpened', $el[0]);
      } else {
        $contentEl.css('height', '');
        $el.trigger('accordion:closed');
        app.emit('accordionClosed', $el[0]);
      }
    });
    Utils.nextFrame(() => {
      $contentEl.transition('');
      $contentEl.css('height', '');
      $el.trigger('accordion:close');
      app.emit('accordionClose');
    });
  },
  toggle(el) {
    const app = this;
    const $el = $(el);
    if ($el.length === 0) return;
    if ($el.hasClass('accordion-item-opened')) app.accordion.close(el);
    else app.accordion.open(el);
  },
};

export default {
  name: 'accordion',
  create() {
    const app = this;
    Utils.extend(app, {
      accordion: {
        open: Accordion.open.bind(app),
        close: Accordion.close.bind(app),
        toggle: Accordion.toggle.bind(app),
      },
    });
  },
  clicks: {
    '.accordion-item .item-link, .accordion-item-toggle, .links-list.accordion-list > ul > li > a': function open($clickedEl) {
      const app = this;
      Accordion.toggleClicked.call(app, $clickedEl);
    },
  },
};
<|endoftext|>


<commit_before>import React from 'react'
import Field from './field'

export default class StringField extends Field {
  get type() {
    return 'text'
  }

  render() {
    if (!this.props.property.display) {
      return super.render()
    }

    return (
      <select
        className={`ct-field ct-select-field`}
        id={this.props.property.id}
        onBlur={(e) => this.onBlur(e)}
        onChange={(e) => this.onChange(e)}
        value={this.state.value}>
        {this.props.property.options.map((option) => {
          return (
            <option key={option.value} value={option.value}>
              {option.title}
            </option>
          )
        })}
      </select>
    )
  }
}
<commit_msg>Add support for textareas.<commit_after>import React from 'react'
import Field from './field'

export default class StringField extends Field {
  get type() {
    return 'text'
  }

  render() {
    if (!this.props.property.display) {
      return super.render()
    }

    if (this.props.property.display === 'textarea') {
      return (
        <textarea
          className={`ct-field ct-${this.type}-field`}
          id={this.props.property.id}
          onBlur={(e) => this.onBlur(e)}
          onChange={(e) => this.onChange(e)}
          value={this.state.value} />
      )
    }

    if (this.props.property.display === 'select') {
      return (
        <select
          className={`ct-field ct-select-field`}
          id={this.props.property.id}
          onBlur={(e) => this.onBlur(e)}
          onChange={(e) => this.onChange(e)}
          value={this.state.value}>
          {this.props.property.options.map((option) => {
            return (
              <option key={option.value} value={option.value}>
                {option.title}
              </option>
            )
          })}
        </select>
      )
    }

    return
Unsupported display type

  }
}
<|endoftext|>


<commit_before>import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import Header from './default';

test('It should be able to render the header title;', t => {
    const wrapper = shallow(<Header />);
    t.is(wrapper.find('h1').text(), 'Instamap');
});
<commit_msg>Fixed broken test<commit_after>import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import Header from './default';

test('It should be able to render the header title;', t => {
    const wrapper = shallow(<Header />);
    t.is(wrapper.find('h1').text(), 'Instamap.');
});
<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import React, { PureComponent } from 'react'
import rokka from '../../rokka'
import Modal from '../Modal'
import ImageList from './List'

const validFormats = ['jpg', 'png']
const defaultFormat = 'png'
function adjustImageFormat({ format, ...properties }) {
  return {
    ...properties,
    format: validFormats.includes(format) ? format : defaultFormat
  }
}

/**
 * previewImage is a HOC used for being able to select
 * a preview image from all the images available in the organization.
 *
 * Usage:
 *   export default previewImage(YourComponent)
 *
 * In your component you'll have two props exposed:
 *   - onOpenChoosePreviewImage: func, will open the modal to choose a preview image
 *   - previewImage: object (hash, format), the preview image itself
 *   - loadPreviewImage: func, call this onComponentDidMount to load an initial preview image
 *
 * @param WrappedComponent
 * @returns {PreviewImage}
 */
export default function previewImage(WrappedComponent) {
  class PreviewImage extends PureComponent {
    constructor(props) {
      super(props)

      this.state = {
        modalOpen: false,
        preview: null
      }

      this.onOpenModal = this.onOpenModal.bind(this)
      this.onCloseModal = this.onCloseModal.bind(this)
      this.onChange = this.onChange.bind(this)
      this.loadPreviewImage = this.loadPreviewImage.bind(this)
      this.mounted = true
    }

    componentWillUnmount() {
      this.mounted = false
    }

    loadPreviewImage() {
      if (this.state.preview) {
        return
      }

      const { organization } = this.props.auth

      rokka()
        .sourceimages.list(organization, 1)
        .then(({ body }) => {
          if (!this.mounted) {
            return
          }
          this.setState({
            preview: adjustImageFormat(body.items[0])
          })
        })
        .catch(err => {
          console.error(err)
        })
    }

    onOpenModal(e) {
      e.preventDefault()

      this.setState({
        modalOpen: true
      })
    }

    onCloseModal() {
      this.setState({
        modalOpen: false
      })
    }

    onChange(image) {
      this.setState({
        modalOpen: false,
        preview: adjustImageFormat(image)
      })
    }

    render() {
      let $previewModal = null
      if (this.state.modalOpen) {
        $previewModal = (
          <Modal fullscreen onClose={this.onCloseModal}>

Choose a preview picture

            <ImageList
              className="mt-md"
              enableLoadMore
              enableSearch
              limit={24}
              organization={this.props.auth.organization}
              onClickImage={(e, image) => this.onChange(image)}
              highlight={this.state.preview.hash}
            />
          </Modal>
        )
      }

      return (

          {$previewModal}
          <WrappedComponent
            onOpenChoosePreviewImage={this.onOpenModal}
            loadPreviewImage={this.loadPreviewImage}
            previewImage={this.state.preview}
            {...this.props}
          />

      )
    }
  }

  PreviewImage.propTypes = {
    auth: PropTypes.shape({
      organization: PropTypes.string.isRequired
    }).isRequired
  }

  const displayName = WrappedComponent.displayName || WrappedComponent.name || 'Component'
  PreviewImage.displayName = `PreviewImage(${displayName})`

  return PreviewImage
}
<commit_msg>remember preview image<commit_after>import PropTypes from 'prop-types'
import React, { PureComponent } from 'react'
import rokka from '../../rokka'
import Modal from '../Modal'
import ImageList from './List'

const validFormats = ['jpg', 'png']
const defaultFormat = 'png'
const ROKKA_DASHBOARD_PREVIEW_IMAGE = 'rokka-dashboard-preview-image'
function adjustImageFormat({ format, ...properties }) {
  const preview = {
    ...properties,
    format: validFormats.includes(format) ? format : defaultFormat
  }
  window.sessionStorage.setItem(ROKKA_DASHBOARD_PREVIEW_IMAGE, JSON.stringify(preview))
  return preview
}

/**
 * previewImage is a HOC used for being able to select
 * a preview image from all the images available in the organization.
 *
 * Usage:
 *   export default previewImage(YourComponent)
 *
 * In your component you'll have two props exposed:
 *   - onOpenChoosePreviewImage: func, will open the modal to choose a preview image
 *   - previewImage: object (hash, format), the preview image itself
 *   - loadPreviewImage: func, call this onComponentDidMount to load an initial preview image
 *
 * @param WrappedComponent
 * @returns {PreviewImage}
 */
export default function previewImage(WrappedComponent) {
  class PreviewImage extends PureComponent {
    constructor(props) {
      super(props)

      this.state = {
        modalOpen: false,
        preview: null
      }

      this.onOpenModal = this.onOpenModal.bind(this)
      this.onCloseModal = this.onCloseModal.bind(this)
      this.onChange = this.onChange.bind(this)
      this.loadPreviewImage = this.loadPreviewImage.bind(this)
      this.mounted = true
    }

    componentWillUnmount() {
      this.mounted = false
    }

    loadPreviewImage() {
      if (this.state.preview) {
        return
      }

      const { organization } = this.props.auth

      const preview = window.sessionStorage.getItem(ROKKA_DASHBOARD_PREVIEW_IMAGE)
      if (preview) {
        const previewImage = adjustImageFormat(JSON.parse(preview))
        if (previewImage.organization === organization) {
          this.setState({ preview: adjustImageFormat(JSON.parse(preview)) })
          return
        }
      }
      rokka()
        .sourceimages.list(organization, 1)
        .then(({ body }) => {
          if (!this.mounted) {
            return
          }
          this.setState({
            preview: adjustImageFormat(body.items[0])
          })
        })
        .catch(err => {
          console.error(err)
        })
    }

    onOpenModal(e) {
      e.preventDefault()

      this.setState({
        modalOpen: true
      })
    }

    onCloseModal() {
      this.setState({
        modalOpen: false
      })
    }

    onChange(image) {
      this.setState({
        modalOpen: false,
        preview: adjustImageFormat(image)
      })
    }

    render() {
      let $previewModal = null
      if (this.state.modalOpen) {
        $previewModal = (
          <Modal fullscreen onClose={this.onCloseModal}>

Choose a preview picture

            <ImageList
              className="mt-md"
              enableLoadMore
              enableSearch
              limit={24}
              organization={this.props.auth.organization}
              onClickImage={(e, image) => this.onChange(image)}
              highlight={this.state.preview.hash}
            />
          </Modal>
        )
      }

      return (

          {$previewModal}
          <WrappedComponent
            onOpenChoosePreviewImage={this.onOpenModal}
            loadPreviewImage={this.loadPreviewImage}
            previewImage={this.state.preview}
            {...this.props}
          />

      )
    }
  }

  PreviewImage.propTypes = {
    auth: PropTypes.shape({
      organization: PropTypes.string.isRequired
    }).isRequired
  }

  const displayName = WrappedComponent.displayName || WrappedComponent.name || 'Component'
  PreviewImage.displayName = `PreviewImage(${displayName})`

  return PreviewImage
}
<|endoftext|>


<commit_before>import React from 'react';
import { boolean, number, select, text } from '@storybook/addon-knobs/react';
import { Store, State } from '@sambego/storybook-state';
import { IconCalendarSmallOutline } from '@teamleader/ui-icons';
import {
  InputBase,
  Button,
  Checkbox,
  Counter,
  Icon,
  Input,
  LoadingSpinner,
  NumericInput,
  Textarea,
  TextBody,
  TextSmall,
  TimeInput,
} from '../../index';

const sizes = ['small', 'medium', 'large'];
const types = [
  'text',
  'button',
  'checkbox',
  'color',
  'date',
  'datetime-local',
  'email',
  'file',
  'hidden',
  'image',
  'month',
  'number',
  'password',
  'radio',
  'range',
  'reset',
  'search',
  'submit',
  'tel',
  'time',
  'url',
  'week',
];
const placeholder = 'I am the placeholder';
const prefix = [
  /* eslint-disable-next-line react/jsx-key */
  <Icon color="neutral" tint="darkest">
    <IconCalendarSmallOutline />
  </Icon>,
  /* eslint-disable-next-line react/jsx-key */
  <TextBody color="neutral">€</TextBody>,
];
const stepperOptions = ['none', 'connected', 'suffix'];
/* eslint-disable-next-line react/jsx-key */
const suffix = [<TextSmall color="neutral">incl. BTW</TextSmall>, <Counter count={99} />, <LoadingSpinner />];

const timeInputStore = new Store({
  value: '',
});

const numericInputStore = new Store({
  value: 6,
});

const handleTimeInputChange = event => {
  timeInputStore.set({ value: event.currentTarget.value });
};

const handleNumericInputChange = (event, value) => {
  numericInputStore.set({ value });
};

export default {
  title: 'Form elements/Input',

  parameters: {
    info: {
      propTables: [InputBase],
    },
  },
};

export const input = () => (
  <Input
    bold={boolean('Bold', false)}
    disabled={boolean('Disabled', false)}
    error={text('Error', '')}
    helpText={text('Help text', '')}
    success={text('Success', '')}
    warning={text('Warning', '')}
    id="input1"
    inverse={boolean('Inverse', false)}
    placeholder={text('Placeholder', placeholder)}
    readOnly={boolean('Read only', false)}
    size={select('Size', sizes) || undefined}
    type={select('Type', types, 'text')}
    connectedLeft={
      boolean('Toggle connected left', false) ? <Button size={select('Size', sizes, 'medium')} label="€" /> : undefined
    }
    connectedRight={
      boolean('Toggle connected right', false) ? (
        <Button size={select('Size', sizes, 'medium')}>
          <Checkbox size="small">Discount</Checkbox>
        </Button>
      ) : (
        undefined
      )
    }
    prefix={boolean('Toggle prefix', false) ? prefix : undefined}
    suffix={boolean('Toggle suffix', false) ? suffix : undefined}
    width={text('Width', undefined)}
  />
);

export const numericInput = () => {
  return (
    <State store={numericInputStore}>
      <NumericInput
        bold={boolean('Bold', false)}
        disabled={boolean('Disabled', false)}
        error={text('Error', '')}
        helpText={text('Help text', '')}
        success={text('Success', '')}
        warning={text('Warning', '')}
        id="input1"
        inverse={boolean('Inverse', false)}
        max={number('Max', 10)}
        min={number('Min', 0)}
        placeholder={text('Placeholder', placeholder)}
        readOnly={boolean('Read only', false)}
        size={select('Size', sizes) || undefined}
        stepper={select('Stepper', stepperOptions, 'suffix')}
        step={number('Step', 1)}
        connectedLeft={
          boolean('Toggle connected left', false) ? (
            <Button size={select('Size', sizes, 'medium')} label="€" />
          ) : (
            undefined
          )
        }
        connectedRight={
          boolean('Toggle connected right', false) ? (
            <Button size={select('Size', sizes, 'medium')}>
              <Checkbox size="small">Discount</Checkbox>
            </Button>
          ) : (
            undefined
          )
        }
        onChange={handleNumericInputChange}
        prefix={boolean('Toggle prefix', false) ? prefix : undefined}
        suffix={boolean('Toggle suffix', false) ? suffix : undefined}
        width={text('Width', undefined)}
      />
    </State>
  );
};

numericInput.story = {
  name: 'NumericInput',
};

export const timeInput = () => (
  <State store={timeInputStore}>
    <TimeInput
      bold={boolean('Bold', false)}
      disabled={boolean('Disabled', false)}
      error={text('Error', '')}
      helpText={text('Help text', '')}
      success={text('Success', '')}
      warning={text('Warning', '')}
      id="input1"
      inverse={boolean('Inverse', false)}
      placeholder={text('Placeholder', 'hh:mm')}
      readOnly={boolean('Read only', false)}
      size={select('Size', sizes) || undefined}
      connectedLeft={
        boolean('Toggle connected left', false) ? (
          <Button size={select('Size', sizes, 'medium')} label="€" />
        ) : (
          undefined
        )
      }
      connectedRight={
        boolean('Toggle connected right', false) ? (
          <Button size={select('Size', sizes, 'medium')}>
            <Checkbox size="small">Discount</Checkbox>
          </Button>
        ) : (
          undefined
        )
      }
      prefix={boolean('Toggle prefix', false) ? prefix : undefined}
      suffix={boolean('Toggle suffix', false) ? suffix : undefined}
      width={text('Width', '90px')}
      onChange={handleTimeInputChange}
    />
  </State>
);

timeInput.story = {
  name: 'TimeInput',
};

export const textarea = () => (
  <Textarea
    bold={boolean('Bold', false)}
    disabled={boolean('Disabled', false)}
    error={text('Error', '')}
    helpText={text('Help text', '')}
    success={text('Success', '')}
    warning={text('Warning', '')}
    id="input1"
    inverse={boolean('Inverse', false)}
    placeholder={text('Placeholder', placeholder)}
    readOnly={boolean('Read only', false)}
    size={select('Size', sizes) || undefined}
    value={text('Value', undefined)}
  />
);
<commit_msg>Update stories<commit_after>import React from 'react';
import { boolean, number, select, text } from '@storybook/addon-knobs/react';
import { Store, State } from '@sambego/storybook-state';
import { IconCalendarSmallOutline } from '@teamleader/ui-icons';
import {
  InputBase,
  Button,
  Checkbox,
  Counter,
  Icon,
  Input,
  LoadingSpinner,
  NumericInput,
  Textarea,
  TextBody,
  TextSmall,
  TimeInput,
} from '../../index';

const sizes = ['small', 'medium', 'large'];
const types = [
  'text',
  'button',
  'checkbox',
  'color',
  'date',
  'datetime-local',
  'email',
  'file',
  'hidden',
  'image',
  'month',
  'number',
  'password',
  'radio',
  'range',
  'reset',
  'search',
  'submit',
  'tel',
  'time',
  'url',
  'week',
];
const placeholder = 'I am the placeholder';
const prefix = [
  /* eslint-disable-next-line react/jsx-key */
  <Icon color="neutral" tint="darkest">
    <IconCalendarSmallOutline />
  </Icon>,
  /* eslint-disable-next-line react/jsx-key */
  <TextBody color="neutral">€</TextBody>,
];
const stepperOptions = ['none', 'connected', 'suffix'];
/* eslint-disable-next-line react/jsx-key */
const suffix = [<TextSmall color="neutral">incl. BTW</TextSmall>, <Counter count={99} />, <LoadingSpinner />];

const timeInputStore = new Store({
  value: '',
});

const numericInputStore = new Store({
  value: 6,
});

const handleTimeInputChange = event => {
  timeInputStore.set({ value: event.currentTarget.value });
};

const handleNumericInputChange = (event, value) => {
  numericInputStore.set({ value });
};

export default {
  title: 'Form elements/Input',

  parameters: {
    info: {
      propTables: [InputBase],
    },
  },
};

export const input = () => (
  <Input
    bold={boolean('Bold', false)}
    disabled={boolean('Disabled', false)}
    error={text('Error', '')}
    helpText={text('Help text', '')}
    success={text('Success', '')}
    warning={text('Warning', '')}
    id="input1"
    inverse={boolean('Inverse', false)}
    placeholder={text('Placeholder', placeholder)}
    readOnly={boolean('Read only', false)}
    size={select('Size', sizes) || undefined}
    type={select('Type', types, 'text')}
    connectedLeft={
      boolean('Toggle connected left', false) ? <Button size={select('Size', sizes, 'medium')} label="€" /> : undefined
    }
    connectedRight={
      boolean('Toggle connected right', false) ? (
        <Button size={select('Size', sizes, 'medium')}>
          <Checkbox size="small">Discount</Checkbox>
        </Button>
      ) : (
        undefined
      )
    }
    prefix={boolean('Toggle prefix', false) ? prefix : undefined}
    suffix={boolean('Toggle suffix', false) ? suffix : undefined}
    textAlignRight={boolean('Text align right', false)}
    width={text('Width', undefined)}
  />
);

export const numericInput = () => {
  return (
    <State store={numericInputStore}>
      <NumericInput
        bold={boolean('Bold', false)}
        disabled={boolean('Disabled', false)}
        error={text('Error', '')}
        helpText={text('Help text', '')}
        success={text('Success', '')}
        warning={text('Warning', '')}
        id="input1"
        inverse={boolean('Inverse', false)}
        max={number('Max', 10)}
        min={number('Min', 0)}
        placeholder={text('Placeholder', placeholder)}
        readOnly={boolean('Read only', false)}
        size={select('Size', sizes) || undefined}
        stepper={select('Stepper', stepperOptions, 'suffix')}
        step={number('Step', 1)}
        connectedLeft={
          boolean('Toggle connected left', false) ? (
            <Button size={select('Size', sizes, 'medium')} label="€" />
          ) : (
            undefined
          )
        }
        connectedRight={
          boolean('Toggle connected right', false) ? (
            <Button size={select('Size', sizes, 'medium')}>
              <Checkbox size="small">Discount</Checkbox>
            </Button>
          ) : (
            undefined
          )
        }
        onChange={handleNumericInputChange}
        prefix={boolean('Toggle prefix', false) ? prefix : undefined}
        suffix={boolean('Toggle suffix', false) ? suffix : undefined}
        textAlignRight={boolean('Text align right', false)}
        width={text('Width', undefined)}
      />
    </State>
  );
};

numericInput.story = {
  name: 'NumericInput',
};

export const timeInput = () => (
  <State store={timeInputStore}>
    <TimeInput
      bold={boolean('Bold', false)}
      disabled={boolean('Disabled', false)}
      error={text('Error', '')}
      helpText={text('Help text', '')}
      success={text('Success', '')}
      warning={text('Warning', '')}
      id="input1"
      inverse={boolean('Inverse', false)}
      placeholder={text('Placeholder', 'hh:mm')}
      readOnly={boolean('Read only', false)}
      size={select('Size', sizes) || undefined}
      connectedLeft={
        boolean('Toggle connected left', false) ? (
          <Button size={select('Size', sizes, 'medium')} label="€" />
        ) : (
          undefined
        )
      }
      connectedRight={
        boolean('Toggle connected right', false) ? (
          <Button size={select('Size', sizes, 'medium')}>
            <Checkbox size="small">Discount</Checkbox>
          </Button>
        ) : (
          undefined
        )
      }
      prefix={boolean('Toggle prefix', false) ? prefix : undefined}
      suffix={boolean('Toggle suffix', false) ? suffix : undefined}
      textAlignRight={boolean('Text align right', false)}
      width={text('Width', '90px')}
      onChange={handleTimeInputChange}
    />
  </State>
);

timeInput.story = {
  name: 'TimeInput',
};

export const textarea = () => (
  <Textarea
    bold={boolean('Bold', false)}
    disabled={boolean('Disabled', false)}
    error={text('Error', '')}
    helpText={text('Help text', '')}
    success={text('Success', '')}
    warning={text('Warning', '')}
    id="input1"
    inverse={boolean('Inverse', false)}
    placeholder={text('Placeholder', placeholder)}
    readOnly={boolean('Read only', false)}
    size={select('Size', sizes) || undefined}
    textAlignRight={boolean('Text align right', false)}
    value={text('Value', undefined)}
  />
);
<|endoftext|>


<commit_before>var randomSpeed = function() {
    var ranSpeed = (Math.floor(Math.random() * 5) +1) * 100;
    return ranSpeed;
}
var row = [60, 145, 230, 315];
var randomRow = function() {
    getRandomRow = row[Math.floor(Math.random() * row.length)];
    return getRandomRow;
}

var column = [0, 101, 202, 303, 404, 505, 606];
var randomColumn = function() {
    getRandomColumn = column[Math.floor(Math.random() * column.length)];
    return getRandomColumn;
}

var Gem = function(x, y) {
    var gemImage = ['images/Gem Blue.png', 'images/Gem Orange.png', 'images/Gem Green.png'];
    this.sprite = gemImage[Math.floor(Math.random() * gemImage.length)];
    this.x = x;
    this.y = y;
}

Gem.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}

Gem.prototype.update = function() {
    for(e=0; e<allGems.length; e++){
        gemPosition = {
            'left':   allGems[e].x,
            'top': allGems[e].y,
            'right':  allGems[e].x+75,
            'bottom':    allGems[e].y+60,
        }
        // Collision detection
        if(playerPosition.left<gemPosition.right &&
            playerPosition.top<gemPosition.bottom &&
            playerPosition.right>gemPosition.left &&
            playerPosition.bottom>gemPosition.top) {
        // removes the collected gem
        allGems.splice(e, 1);
        // if all gems are collected, no more enemies
        if(allGems.length < 1) {
            allEnemies = [];
        }
    }

    }
}

// Enemies our player must avoid
var Enemy = function(x, y, speed) {
    this.sprite = 'images/enemy-bug.png';
    this.x = x;
    this.y = y;
    this.speed = speed;
}

// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
    // If the enemies position is within the screen, this sets speed * dt
    if(this.x < ctx.canvas.width){
        this.x += this.speed * dt;
    }
    // If the enemy is off the screen, reset position
    else{
        this.x = -75;
        this.speed = randomSpeed();
        this.y = randomRow();
    }
}

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}

// Player Class
var Player = function(x,y){
    this.sprite ='images/char-boy.png';
    this.x = x;
    this.y = y;
}

Player.prototype.update = function(dt){
    // If player reaches top row, reset back to start
    /*if(this.y < 50){
        player.reset();
    }  */

    // Defines player's area
    playerPosition = {
        'left':   this.x,
        'top': this.y,
        'right':  this.x+50,
        'bottom':    this.y+70,
    }
    // Iterate through allEnemies and define enemy area
    for(e=0; e<allEnemies.length; e++){
        bugPosition = {
            'left':   allEnemies[e].x,
            'top': allEnemies[e].y,
            'right':  allEnemies[e].x+70,
            'bottom':    allEnemies[e].y+70,
        }
        // Collision detection
    if(playerPosition.left<bugPosition.right &&
        playerPosition.top<bugPosition.bottom &&
        playerPosition.right>bugPosition.left &&
        playerPosition.bottom>bugPosition.top){
        player.reset(); }
    }

}

// Reset player back to starting position.
Player.prototype.reset = function(){
    this.x = 303;
    this.y = 400;
}

// Draw the player on the screen
Player.prototype.render = function(){
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}

// What to do when arrow keys are used
Player.prototype.handleInput = function(key) {
    if(key === 'left' && this.x > 25){
        this.x -= 101;
    }
    if(key === 'up' && this.y > 0){
        this.y -= 83;
    }
    if(key === 'right' && this.x < 600){
        this.x += 101;
    }
    if(key === 'down' && this.y < 400){
        this.y +=  83;
    }
}

var enemy1 = new Enemy(-75, randomRow(), randomSpeed());
var enemy2 = new Enemy(-75, randomRow(), randomSpeed());
var enemy3 = new Enemy(-75, randomRow(), randomSpeed());
var enemy4 = new Enemy(-75, randomRow(), randomSpeed());
var enemy5 = new Enemy(-75, randomRow(), randomSpeed());

// Instantiation
var allEnemies = [enemy1, enemy2, enemy3, enemy4, enemy5];

var player = new Player(303, 400);

var gem1 = new Gem(randomColumn() +15, randomRow() +25);
var gem2 = new Gem(randomColumn() +15, randomRow() +25);
var gem3 = new Gem(randomColumn() +15, randomRow() +25);

var allGems = [gem1, gem2, gem3];

// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener('keyup', function(e) {
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'
    };

    player.handleInput(allowedKeys[e.keyCode]);
});<commit_msg>fixed player.reset<commit_after>var randomSpeed = function() {
    var ranSpeed = (Math.floor(Math.random() * 5) +1) * 100;
    return ranSpeed;
}
var row = [60, 145, 230, 315];
var randomRow = function() {
    getRandomRow = row[Math.floor(Math.random() * row.length)];
    return getRandomRow;
}

var column = [0, 101, 202, 303, 404, 505, 606];
var randomColumn = function() {
    getRandomColumn = column[Math.floor(Math.random() * column.length)];
    return getRandomColumn;
}

var Gem = function(x, y) {
    var gemImage = ['images/Gem Blue.png', 'images/Gem Orange.png', 'images/Gem Green.png'];
    this.sprite = gemImage[Math.floor(Math.random() * gemImage.length)];
    this.x = x;
    this.y = y;
}

Gem.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}

Gem.prototype.update = function() {
    for(e=0; e<allGems.length; e++){
        gemPosition = {
            'left':   allGems[e].x,
            'top': allGems[e].y,
            'right':  allGems[e].x+75,
            'bottom':    allGems[e].y+60,
        }
        // Collision detection
        if(playerPosition.left<gemPosition.right &&
            playerPosition.top<gemPosition.bottom &&
            playerPosition.right>gemPosition.left &&
            playerPosition.bottom>gemPosition.top) {
        // removes the collected gem
        allGems.splice(e, 1);
        // if all gems are collected, no more enemies
        if(allGems.length < 1) {
            allEnemies = [];
        }
    }

    }
}

// Enemies our player must avoid
var Enemy = function(x, y, speed) {
    this.sprite = 'images/enemy-bug.png';
    this.x = x;
    this.y = y;
    this.speed = speed;
}

// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
    // If the enemies position is within the screen, this sets speed * dt
    if(this.x < ctx.canvas.width){
        this.x += this.speed * dt;
    }
    // If the enemy is off the screen, reset position
    else{
        this.x = -75;
        this.speed = randomSpeed();
        this.y = randomRow();
    }
}

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}

// Player Class
var Player = function(x,y){
    this.sprite ='images/char-boy.png';
    this.x = x;
    this.y = y;
}

Player.prototype.update = function(dt){
    // If player reaches top row, reset back to start
    if(this.y < 50){
        player.reset();
    }

    // Defines player's area
    playerPosition = {
        'left':   this.x,
        'top': this.y,
        'right':  this.x+50,
        'bottom':    this.y+70,
    }
    // Iterate through allEnemies and define enemy area
    for(e=0; e<allEnemies.length; e++){
        bugPosition = {
            'left':   allEnemies[e].x,
            'top': allEnemies[e].y,
            'right':  allEnemies[e].x+70,
            'bottom':    allEnemies[e].y+70,
        }
        // Collision detection
    if(playerPosition.left<bugPosition.right &&
        playerPosition.top<bugPosition.bottom &&
        playerPosition.right>bugPosition.left &&
        playerPosition.bottom>bugPosition.top){
        player.reset(); }
    }

}

// Reset player back to starting position.
Player.prototype.reset = function(){
    this.x = 303;
    this.y = 400;
}

// Draw the player on the screen
Player.prototype.render = function(){
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}

// What to do when arrow keys are used
Player.prototype.handleInput = function(key) {
    if(key === 'left' && this.x > 25){
        this.x -= 101;
    }
    if(key === 'up' && this.y > 0){
        this.y -= 83;
    }
    if(key === 'right' && this.x < 600){
        this.x += 101;
    }
    if(key === 'down' && this.y < 400){
        this.y +=  83;
    }
}

var enemy1 = new Enemy(-75, randomRow(), randomSpeed());
var enemy2 = new Enemy(-75, randomRow(), randomSpeed());
var enemy3 = new Enemy(-75, randomRow(), randomSpeed());
var enemy4 = new Enemy(-75, randomRow(), randomSpeed());
var enemy5 = new Enemy(-75, randomRow(), randomSpeed());

// Instantiation
var allEnemies = [enemy1, enemy2, enemy3, enemy4, enemy5];

var player = new Player(303, 400);

var gem1 = new Gem(randomColumn() +15, randomRow() +25);
var gem2 = new Gem(randomColumn() +15, randomRow() +25);
var gem3 = new Gem(randomColumn() +15, randomRow() +25);

var allGems = [gem1, gem2, gem3];

// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener('keyup', function(e) {
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'
    };

    player.handleInput(allowedKeys[e.keyCode]);
});<|endoftext|>


<commit_before>'use strict';

module.exports = function(driver, connectorSpec) {
	connectorSpec.shouldBehaveLikeMusicSite(driver, {
		url: 'https://www.wwoz.org/listen/player/',
		playButtonSelector: '.jp-pause' // Force DOM change
	});
};
<commit_msg>Update WWOZ test<commit_after>'use strict';

module.exports = function(driver, connectorSpec) {
	connectorSpec.shouldBehaveLikeMusicSite(driver, {
		url: 'https://www.wwoz.org/listen/player/'
	});
};
<|endoftext|>


<commit_before>var cheerio = require('cheerio'),
    request = require('request'),
    async 	= require('async'),
    _ 		= require('underscore'),
    gm 		= require('gm').subClass({ imageMagick: true }),
    fs 		= require('fs');

var oauth = process.env['GITHUB_TOKEN'];

function getRepository(user, name, callback) {
	request({
		method: 'GET',
		url: 'https://api.github.com/repos/' + user + '/' + name,
		headers: {
			'User-Agent': 'CodeHub-Trending'
		},
		auth: {
			user: 'token',
			pass: oauth,
			sendImmediately: true
		}
	},
	function(err, response, body) {
		if (err) return callback(err);

		var jsonBody = JSON.parse(body);
		var rateLimitRemaining = parseInt(response.headers['x-ratelimit-remaining']);
		var resetSeconds = parseInt(response.headers['x-ratelimit-reset']);
		var nowSeconds = Math.round(new Date().getTime() / 1000);
		var duration = resetSeconds - nowSeconds + 60;

		// Make sure we don't drain the rate limit
		if (rateLimitRemaining < 400) {
			console.warn('Pausing for %s to allow rateLimit to reset', duration);
			setTimeout(function() {
				callback(null, jsonBody);
			}, duration * 1000);
		} else {
			callback(null, jsonBody);
		}
	});
};

exports.getTrending = function(time, language, callback) {
	var queryString = { 'since': time };
	if (language != null) {
		queryString.l = language;
	}

	request({
		method: 'GET',
		url: 'https://github.com/trending',
		qs: queryString,
		headers: {
			'X-PJAX': 'true'
		}
	},
	function(err, response, body) {
		if (err) return callback(err);
		$ = cheerio.load(body);
		var data = [];
		$('.container.explore-page .explore-content > ol > li').each(function() {
			var stars = $('.repo-leaderboard-meta-item .octicon-star', this).parent().text();
			var forks = $('.repo-leaderboard-meta-item .octicon-git-branch', this).parent().text();
			stars = stars.length > 0 ? parseInt(stars) : 0;
			forks = forks.length > 0 ? parseInt(forks) : 0;

			data.push({
				owner: $('.repository-name .owner-name', this).text(),
				name: $('.repository-name strong', this).text(),
				stars: stars,
				forks: forks,
			})
		});

		async.series(_.map(data, function(x) {
			return function(callback) {
				getRepository(x.owner, x.name, function(err, data) {
					if (err) return callback(err);
					x.url = data.html_url;
					x.avatarUrl = data.owner.avatar_url;
					x.description = data.description;
					callback(err);
				});
			};
		}), function(err) { callback(err, data); });
	});
};

exports.getLanguages = function(callback) {
	request({
		method: 'GET',
		url: 'https://github.com/trending',
		headers: {
			'X-PJAX': 'true'
		}
	},
	function(err, response, body) {
		if (err) return callback(err);
		$ = cheerio.load(body);
		var languages = [];
		$('.column.one-fourth .select-menu .select-menu-list .select-menu-item > a').each(function() {
			var href = $(this).attr('href');
			if (href.indexOf('=') > 0) {
				languages.push({
					name: $(this).text(),
					slug: href.substring(href.indexOf('=') + 1)
				});
			}
		});
		callback(null, languages);
	});
};

exports.getShowcases = function(callback) {
	var getShowcasePage = function(page, callback) {
		request({
			method: 'GET',
			url: 'https://github.com/showcases',
			qs: { 'page': page },
			headers: { 'X-PJAX': 'true' }
		},
		function(err, response, body) {
			if (err) return callback(err);
			$ = cheerio.load(body);
			var showcases = [];
			$('li.collection-card').each(function() {
				var href = $('a.collection-card-image', this).attr('href');
				if (href.lastIndexOf('/') > 0) {
					var showcase = {
						name: $('h3', this).text(),
						slug: href.substring(href.lastIndexOf('/') + 1),
						description: $('p.collection-card-body', this).text()
					};

					var imageExtract = /url\(data:image\/svg\+xml;base64,(.+)\)/g;
					var arr = imageExtract.exec($('.collection-card-image', this).attr('style'));
					showcase.image = new Buffer(arr[1], 'base64').toString('ascii');
					showcases.push(showcase);
				}
			});

			callback(err, {
				showcases: showcases,
				more: $('div.pagination a:contains("Next")').length > 0
			});
		});
	};

	var more = false;
	var page = 1;
	var showcases = [];

	async.doWhilst(function(callback) {
		getShowcasePage(page, function(err, results) {
			if (err) return callback(err);

			_.each(results.showcases, function(s) { showcases.push(s) });
			more = results.more;
			page++;

			async.series(_.map(results.showcases, function(x) {
				return function(callback) {
					var svgImage = 'public/' + x.slug + '.svg';
					var pngImage = 'public/' + x.slug + '.png';
					fs.writeFile(svgImage, x.image, function(err) {
						if (err) return callback(err);
						gm(svgImage).resize(96).write(pngImage, function(err) {
							fs.unlink(svgImage);
							if (err) return callback(err);
							x.image = x.slug + '.png';
							callback(null);
						});
					});
				};
			}), callback);
		});
	},
	function() { return more },
	function(err) { callback(err, showcases) });
};

exports.getShowcase = function(slug, callback) {
	request({
		method: 'GET',
		url: 'https://github.com/showcases/' + slug,
		headers: { 'X-PJAX': 'true' }
	},
	function(err, response, body) {
		if (err) return callback(err);
		$ = cheerio.load(body);
		var data = [];
		$('.collection-repos > li').each(function() {
			data.push({
				owner: $('h3.collection-repo-title .repo-author', this).text(),
				name: $('h3.collection-repo-title .repo-name', this).text()
			});
		});

		async.series(_.map(data, function(x) {
			return function(callback) {
				getRepository(x.owner, x.name, function(err, data) {
					if (err) return callback(err);
					x.url = data.html_url;
					x.avatarUrl = data.owner.avatar_url;
					x.description = data.description;
					x.stars = data.stargazers_count;
					x.forks = data.forks_count;
					callback(err);
				});
			};
		}), function(err) { callback(err, data); });
	});
};<commit_msg>Parallel!<commit_after>var cheerio = require('cheerio'),
    request = require('request'),
    async 	= require('async'),
    _ 		= require('underscore'),
    gm 		= require('gm').subClass({ imageMagick: true }),
    fs 		= require('fs');

var oauth = process.env['GITHUB_TOKEN'];

function getRepository(user, name, callback) {
	request({
		method: 'GET',
		url: 'https://api.github.com/repos/' + user + '/' + name,
		headers: {
			'User-Agent': 'CodeHub-Trending'
		},
		auth: {
			user: 'token',
			pass: oauth,
			sendImmediately: true
		}
	},
	function(err, response, body) {
		if (err) return callback(err);

		var jsonBody = JSON.parse(body);
		var rateLimitRemaining = parseInt(response.headers['x-ratelimit-remaining']);
		var resetSeconds = parseInt(response.headers['x-ratelimit-reset']);
		var nowSeconds = Math.round(new Date().getTime() / 1000);
		var duration = resetSeconds - nowSeconds + 60;

		// Make sure we don't drain the rate limit
		if (rateLimitRemaining < 400) {
			console.warn('Pausing for %s to allow rateLimit to reset', duration);
			setTimeout(function() {
				callback(null, jsonBody);
			}, duration * 1000);
		} else {
			callback(null, jsonBody);
		}
	});
};

exports.getTrending = function(time, language, callback) {
	var queryString = { 'since': time };
	if (language != null) {
		queryString.l = language;
	}

	request({
		method: 'GET',
		url: 'https://github.com/trending',
		qs: queryString,
		headers: {
			'X-PJAX': 'true'
		}
	},
	function(err, response, body) {
		if (err) return callback(err);
		$ = cheerio.load(body);
		var data = [];
		$('.container.explore-page .explore-content > ol > li').each(function() {
			var stars = $('.repo-leaderboard-meta-item .octicon-star', this).parent().text();
			var forks = $('.repo-leaderboard-meta-item .octicon-git-branch', this).parent().text();
			stars = stars.length > 0 ? parseInt(stars) : 0;
			forks = forks.length > 0 ? parseInt(forks) : 0;

			data.push({
				owner: $('.repository-name .owner-name', this).text(),
				name: $('.repository-name strong', this).text(),
				stars: stars,
				forks: forks,
			})
		});

		async.parallelLimit(_.map(data, function(x) {
			return function(callback) {
				getRepository(x.owner, x.name, function(err, data) {
					if (err) return callback(err);
					x.url = data.html_url;
					x.avatarUrl = data.owner.avatar_url;
					x.description = data.description;
					callback(err);
				});
			};
		}), 4, function(err) { callback(err, data); });
	});
};

exports.getLanguages = function(callback) {
	request({
		method: 'GET',
		url: 'https://github.com/trending',
		headers: {
			'X-PJAX': 'true'
		}
	},
	function(err, response, body) {
		if (err) return callback(err);
		$ = cheerio.load(body);
		var languages = [];
		$('.column.one-fourth .select-menu .select-menu-list .select-menu-item > a').each(function() {
			var href = $(this).attr('href');
			if (href.indexOf('=') > 0) {
				languages.push({
					name: $(this).text(),
					slug: decodeURIComponent(href.substring(href.indexOf('=') + 1))
				});
			}
		});
		callback(null, languages);
	});
};

exports.getShowcases = function(callback) {
	var getShowcasePage = function(page, callback) {
		request({
			method: 'GET',
			url: 'https://github.com/showcases',
			qs: { 'page': page },
			headers: { 'X-PJAX': 'true' }
		},
		function(err, response, body) {
			if (err) return callback(err);
			$ = cheerio.load(body);
			var showcases = [];
			$('li.collection-card').each(function() {
				var href = $('a.collection-card-image', this).attr('href');
				if (href.lastIndexOf('/') > 0) {
					var showcase = {
						name: $('h3', this).text(),
						slug: href.substring(href.lastIndexOf('/') + 1),
						description: $('p.collection-card-body', this).text()
					};

					var imageExtract = /url\(data:image\/svg\+xml;base64,(.+)\)/g;
					var arr = imageExtract.exec($('.collection-card-image', this).attr('style'));
					showcase.image = new Buffer(arr[1], 'base64').toString('ascii');
					showcases.push(showcase);
				}
			});

			callback(err, {
				showcases: showcases,
				more: $('div.pagination a:contains("Next")').length > 0
			});
		});
	};

	var more = false;
	var page = 1;
	var showcases = [];

	async.doWhilst(function(callback) {
		getShowcasePage(page, function(err, results) {
			if (err) return callback(err);

			_.each(results.showcases, function(s) { showcases.push(s) });
			more = results.more;
			page++;

			async.series(_.map(results.showcases, function(x) {
				return function(callback) {
					var svgImage = 'public/' + x.slug + '.svg';
					var pngImage = 'public/' + x.slug + '.png';
					fs.writeFile(svgImage, x.image, function(err) {
						if (err) return callback(err);
						gm(svgImage).resize(96).write(pngImage, function(err) {
							fs.unlink(svgImage);
							if (err) return callback(err);
							x.image = x.slug + '.png';
							callback(null);
						});
					});
				};
			}), callback);
		});
	},
	function() { return more },
	function(err) { callback(err, showcases) });
};

exports.getShowcase = function(slug, callback) {
	request({
		method: 'GET',
		url: 'https://github.com/showcases/' + slug,
		headers: { 'X-PJAX': 'true' }
	},
	function(err, response, body) {
		if (err) return callback(err);
		$ = cheerio.load(body);
		var data = [];
		$('.collection-repos > li').each(function() {
			data.push({
				owner: $('h3.collection-repo-title .repo-author', this).text(),
				name: $('h3.collection-repo-title .repo-name', this).text()
			});
		});

		async.series(_.map(data, function(x) {
			return function(callback) {
				getRepository(x.owner, x.name, function(err, data) {
					if (err) return callback(err);
					x.url = data.html_url;
					x.avatarUrl = data.owner.avatar_url;
					x.description = data.description;
					x.stars = data.stargazers_count;
					x.forks = data.forks_count;
					callback(err);
				});
			};
		}), function(err) { callback(err, data); });
	});
};<|endoftext|>


<commit_before>import React from 'react';
import styled from 'styled-components';

import { Carousel } from 'react-responsive-carousel';
import img1 from '~/resources/images/home/home1.large.jpg';
import Callout from './callout';
import { BlockLink } from "rebass";
import Typography from "~/components/typography";

const CarouselItem = styled.div`
    max-height: 500px;
    overflow:hidden;
    position:relative;

    img {
        max-width:100%;
        min-height:200px;
        height: auto;
        display:block;
        object-fit:cover;
    }
`;

const CalloutButton = styled(BlockLink)`
    background-color: ${ ({theme}) => theme.colors.primaryAccent };
    margin-top:10px;
    padding: 0.5em;
`

const MainCarousel = ({className }) => (
    <Carousel axis="horizontal" showThumbs={false} showStatus={false} className={className}>
        <CarouselItem>

             <Callout>
                 <Typography color="white" m={4} >FREE 15 minute consultation</Typography>
                 <CalloutButton href="contact">CONTACT US TODAY</CalloutButton>
             </Callout>
        </CarouselItem>
    </Carousel>
);

export default MainCarousel;
<commit_msg>bug(carousel): force padding and margin<commit_after>import React from 'react';
import styled from 'styled-components';

import { Carousel } from 'react-responsive-carousel';
import img1 from '~/resources/images/home/home1.large.jpg';
import Callout from './callout';
import { BlockLink } from "rebass";
import Typography from "~/components/typography";

const CarouselItem = styled.div`
    max-height: 500px;
    overflow:hidden;
    position:relative;

    img {
        max-width:100%;
        min-height:200px;
        height: auto;
        display:block;
        object-fit:cover;
    }
`;

const CalloutButton = BlockLink.extend`
    background-color: ${ ({theme}) => theme.colors.primaryAccent };
    margin-top:10px !important;
    border-radius: 3px;
    padding: 0.5em !important;
`

const MainCarousel = ({className }) => (
    <Carousel axis="horizontal" showThumbs={false} showStatus={false} className={className}>
        <CarouselItem>

             <Callout>
                 <Typography color="white" m={4} >FREE 15 minute consultation</Typography>
                 <CalloutButton href="contact">CONTACT US TODAY</CalloutButton>
             </Callout>
        </CarouselItem>
    </Carousel>
);

export default MainCarousel;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes, { connect, browserHistory } from '../PropTypes.js';
import moment from 'moment';
import Icon from '../controls/Icon.js';
import MatchesTable from './MatchesTable.js';

@connect(state => ({matches: state.matches, user: state.user}))
export default class MatchesWeek extends Component {
  static contextTypes = PropTypes.contextTypes;
  static propTypes = {
    matches: PropTypes.MatchModelList.isRequired,
    user: PropTypes.UserModel.isRequired,
  }

  constructor(props) {
    super(props);
    this.state = {
      currentWeek: 1,
      lastWeek: 22,
    };
  }

  componentWillReceiveProps(props) {
    const today = moment();
    const sortedMatches = props.matches.sort((a, b) => a.date - b.date);
    const currentWeekMatch = sortedMatches.find(x => x.date > today);
    const lastWeekMatch = sortedMatches.last();
    const lastWeek = lastWeekMatch ? lastWeekMatch.week : 22;
    this.setState({
      currentWeek: currentWeekMatch ? currentWeekMatch.week : lastWeek,
      lastWeek: lastWeek,
    });
  }

  _onChangeWeek(weekDiff) {
    this.setState({currentWeek: this.state.currentWeek + weekDiff});
  }

  render() {
    if (!this.props.matches.size) {
      return null;
    }
    const t = this.context.t;

    const matches = this.props.matches.filter(match => match.week === this.state.currentWeek);
    const selectedWeek = matches.first().date.clone();
    return (

          {this.state.currentWeek > 1 ? (
            <Icon fa="fa fa-arrow-left" style={{marginRight: 10}} onClick={::this._onChangeWeek.bind(this, -1)} />
          ) : null}
          {t('match.week')}
          {this.state.currentWeek}
          :
          {selectedWeek.startOf('week').format('D/M')}
           -
          {selectedWeek.endOf('week').format('D/M')}
          {this.state.currentWeek < this.state.lastWeek ? (
            <Icon fa="fa fa-arrow-right" style={{marginLeft: 10}} onClick={::this._onChangeWeek.bind(this, 1)} />
          ) : null}

        {false && this.props.user.isAdmin() ? (

            <button className="btn btn-default" style={{marginRight: 5}}>WEEK BLOKKEREN</button>
            <button className="btn btn-default">
              <Icon fa="fa fa-envelope-o" onClick={() => console.log('emailing opstelling...')} />
            </button>

        ) : null}

Vttl

        <MatchesTable matches={matches.filter(x => x.competition === 'Vttl').sort((a, b) => a.date - b.date)} user={this.props.user} />

Sporta

        <MatchesTable matches={matches.filter(x => x.competition === 'Sporta').sort((a, b) => a.date - b.date)} user={this.props.user} />

    );
  }
}<commit_msg>MatchesWeek: allow edit by CAN_MANAGETEAM<commit_after>import React, { Component } from 'react';
import PropTypes, { connect, browserHistory } from '../PropTypes.js';
import moment from 'moment';
import Icon from '../controls/Icon.js';
import MatchesTable from './MatchesTable.js';

@connect(state => ({matches: state.matches, user: state.user}))
export default class MatchesWeek extends Component {
  static contextTypes = PropTypes.contextTypes;
  static propTypes = {
    matches: PropTypes.MatchModelList.isRequired,
    user: PropTypes.UserModel.isRequired,
  }

  constructor(props) {
    super(props);
    this.state = {
      currentWeek: 1,
      lastWeek: 22,
      editMode: false,
    };
  }

  componentWillReceiveProps(props) {
    const today = moment();
    const sortedMatches = props.matches.sort((a, b) => a.date - b.date);
    const currentWeekMatch = sortedMatches.find(x => x.date > today);
    const lastWeekMatch = sortedMatches.last();
    const lastWeek = lastWeekMatch ? lastWeekMatch.week : 22;
    this.setState({
      currentWeek: currentWeekMatch ? currentWeekMatch.week : lastWeek,
      lastWeek: lastWeek,
    });
  }

  _onChangeWeek(weekDiff) {
    this.setState({currentWeek: this.state.currentWeek + weekDiff});
  }

  render() {
    if (!this.props.matches.size) {
      return null;
    }
    const t = this.context.t;

    const matches = this.props.matches.filter(match => match.week === this.state.currentWeek);
    const selectedWeek = matches.first().date.clone();

    //<button className="btn btn-default">
    //  <Icon fa="fa fa-envelope-o" onClick={() => console.log('emailing opstelling...')} />
    //</button>
    return (

          {this.state.currentWeek > 1 ? (
            <Icon fa="fa fa-arrow-left" style={{marginRight: 10}} onClick={::this._onChangeWeek.bind(this, -1)} />
          ) : null}
          {t('match.week')}
          {this.state.currentWeek}
          :
          {selectedWeek.startOf('week').format('D/M')}
             -
          {selectedWeek.endOf('week').format('D/M')}
          {this.state.currentWeek < this.state.lastWeek ? (
            <Icon fa="fa fa-arrow-right" style={{marginLeft: 10}} onClick={::this._onChangeWeek.bind(this, 1)} />
          ) : null}

        {this.props.user.canManageTeams() ? (

            <button onClick={() => this.setState({editMode: !this.state.editMode})} className="btn btn-default">
              <Icon fa="fa fa-pencil-square-o" />
            </button>

        ) : null}

Vttl

        <MatchesTable editMode={this.state.editMode} matches={matches.filter(x => x.competition === 'Vttl').sort((a, b) => a.date - b.date)} user={this.props.user} />

Sporta

        <MatchesTable editMode={this.state.editMode} matches={matches.filter(x => x.competition === 'Sporta').sort((a, b) => a.date - b.date)} user={this.props.user} />

    );
  }
}<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import TextareaAutosize from 'react-textarea-autosize';
import DateTimePicker from 'react-widgets/lib/DateTimePicker';
import Modal from 'react-modal';
import StaticFiles from '../../containers/views/StaticFiles';
import moment from 'moment';
import momentLocalizer from 'react-widgets/lib/localizers/moment';
import 'react-widgets/dist/css/react-widgets.css';

momentLocalizer(moment);

export class MetaSimple extends Component {

  constructor() {
    super();
    this.state = {
      staticfiles: [],
      showModal: false
    };
    this.handleOpenModal = this.handleOpenModal.bind(this);
    this.handleCloseModal = this.handleCloseModal.bind(this);
  }

  shouldComponentUpdate(nextProps) {
    return nextProps.fieldValue !== this.props.fieldValue;
  }

  handleOpenModal () {
    this.setState({ showModal: true });
  }

  handleCloseModal () {
    this.setState({ showModal: false });
  }

  handleEditableChange(e) {
    const { nameAttr, updateFieldValue } = this.props;
    updateFieldValue(nameAttr, e.target.value);
  }

  handleEditableBlur(e) {
    const { nameAttr, updateFieldValue } = this.props;
    updateFieldValue(nameAttr, e.target.value.trim());
  }

  handleDatepickerChange(date, dateStr) {
    const { nameAttr, updateFieldValue } = this.props;
    let formatted = moment(date).format("YYYY-MM-DD hh:mm:ss");
    updateFieldValue(nameAttr, formatted);
  }

  renderEditable() {
    const { fieldValue } = this.props;
    return (
      <TextareaAutosize
        onChange={(e) => this.handleEditableChange(e)}
        onBlur={(e) => this.handleEditableBlur(e)}
        className="field value-field"
        value={`${fieldValue}`} />
    );
  }

  renderDatepicker() {
    const { fieldValue } = this.props;
    let dateValue = (new Date(fieldValue) == 'Invalid Date') ? null : new Date(fieldValue);
    return (
      <DateTimePicker
        onChange={(v, d) => this.handleDatepickerChange(v, d)}
        className="date-field"
        value={dateValue} />
    );
  }

  onClickPickerItem(url) {
    const { nameAttr, updateFieldValue } = this.props;
    this.refs.imagepicker.value = url;
    updateFieldValue(nameAttr, url);
    this.handleCloseModal();
  }

  renderStaticFilePicker() {
    const { fieldValue } = this.props;
    return (

        <TextareaAutosize
          onChange={(e) => this.handleEditableChange(e)}
          className="field value-field"
          value={fieldValue}
          ref="imagepicker" />

          <button onClick={this.handleOpenModal}>

          </button>
          <Modal
             isOpen={this.state.showModal}
             onAfterOpen={this.fetchStaticFiles}
             contentLabel="onRequestClose Example"
             onRequestClose={this.handleCloseModal}
             style={{
              overlay: {
                backgroundColor: 'rgba(0,0,0,0.6)',
                zIndex: 10,
              },
              content: {
                margin: 50,
              }
            }} >
             <StaticFiles onClickStaticFile={(url) => this.onClickPickerItem(url)} />
          </Modal>

    );
  }

  render() {
    const { fieldKey } = this.props;
    let node;
    switch (fieldKey) {
      case 'date':
        node = this.renderDatepicker();
        break;
      case 'image':
      case 'file':
        node = this.renderStaticFilePicker();
        break;
      default:
        node = this.renderEditable();
    }
    return (

        {node}

    );
  }
}

MetaSimple.propTypes = {
  parentType: PropTypes.string.isRequired,
  fieldKey: PropTypes.string.isRequired,
  fieldValue: PropTypes.any.isRequired,
  updateFieldValue: PropTypes.func.isRequired,
  nameAttr: PropTypes.any.isRequired
};

export default MetaSimple;
<commit_msg>respect am/pm rule<commit_after>import React, { Component, PropTypes } from 'react';
import TextareaAutosize from 'react-textarea-autosize';
import DateTimePicker from 'react-widgets/lib/DateTimePicker';
import Modal from 'react-modal';
import StaticFiles from '../../containers/views/StaticFiles';
import moment from 'moment';
import momentLocalizer from 'react-widgets/lib/localizers/moment';
import 'react-widgets/dist/css/react-widgets.css';

momentLocalizer(moment);

export class MetaSimple extends Component {

  constructor() {
    super();
    this.state = {
      staticfiles: [],
      showModal: false
    };
    this.handleOpenModal = this.handleOpenModal.bind(this);
    this.handleCloseModal = this.handleCloseModal.bind(this);
  }

  shouldComponentUpdate(nextProps) {
    return nextProps.fieldValue !== this.props.fieldValue;
  }

  handleOpenModal () {
    this.setState({ showModal: true });
  }

  handleCloseModal () {
    this.setState({ showModal: false });
  }

  handleEditableChange(e) {
    const { nameAttr, updateFieldValue } = this.props;
    updateFieldValue(nameAttr, e.target.value);
  }

  handleEditableBlur(e) {
    const { nameAttr, updateFieldValue } = this.props;
    updateFieldValue(nameAttr, e.target.value.trim());
  }

  handleDatepickerChange(date, dateStr) {
    const { nameAttr, updateFieldValue } = this.props;
    let formatted = moment(date).format("YYYY-MM-DD HH:mm:ss");
    updateFieldValue(nameAttr, formatted);
  }

  renderEditable() {
    const { fieldValue } = this.props;
    return (
      <TextareaAutosize
        onChange={(e) => this.handleEditableChange(e)}
        onBlur={(e) => this.handleEditableBlur(e)}
        className="field value-field"
        value={`${fieldValue}`} />
    );
  }

  renderDatepicker() {
    const { fieldValue } = this.props;
    let dateValue = (new Date(fieldValue) == 'Invalid Date') ? null : new Date(fieldValue);
    return (
      <DateTimePicker
        onChange={(v, d) => this.handleDatepickerChange(v, d)}
        className="date-field"
        value={dateValue} />
    );
  }

  onClickPickerItem(url) {
    const { nameAttr, updateFieldValue } = this.props;
    this.refs.imagepicker.value = url;
    updateFieldValue(nameAttr, url);
    this.handleCloseModal();
  }

  renderStaticFilePicker() {
    const { fieldValue } = this.props;
    return (

        <TextareaAutosize
          onChange={(e) => this.handleEditableChange(e)}
          className="field value-field"
          value={fieldValue}
          ref="imagepicker" />

          <button onClick={this.handleOpenModal}>

          </button>
          <Modal
             isOpen={this.state.showModal}
             onAfterOpen={this.fetchStaticFiles}
             contentLabel="onRequestClose Example"
             onRequestClose={this.handleCloseModal}
             style={{
              overlay: {
                backgroundColor: 'rgba(0,0,0,0.6)',
                zIndex: 10,
              },
              content: {
                margin: 50,
              }
            }} >
             <StaticFiles onClickStaticFile={(url) => this.onClickPickerItem(url)} />
          </Modal>

    );
  }

  render() {
    const { fieldKey } = this.props;
    let node;
    switch (fieldKey) {
      case 'date':
        node = this.renderDatepicker();
        break;
      case 'image':
      case 'file':
        node = this.renderStaticFilePicker();
        break;
      default:
        node = this.renderEditable();
    }
    return (

        {node}

    );
  }
}

MetaSimple.propTypes = {
  parentType: PropTypes.string.isRequired,
  fieldKey: PropTypes.string.isRequired,
  fieldValue: PropTypes.any.isRequired,
  updateFieldValue: PropTypes.func.isRequired,
  nameAttr: PropTypes.any.isRequired
};

export default MetaSimple;
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react'
import Modal from 'react-modal'
import DistributionSummary from 'gComponents/distributions/summary/index.js'
import Histogram from 'gComponents/simulations/histogram'
import DistributionEditor from 'gComponents/distributions/editor/index.js'
import GuesstimateDescription from './description'
import {ButtonClose} from 'gComponents/utility/buttons/close'
import './style.css'
import {percentile, sortDescending} from 'lib/dataAnalysis.js'

const percentages = (values, perc) => {
  const samples = sortDescending(Object.assign([], values)
  return perc.map(e => { return {percentage: e, value: percentile(samples, samples.length, e)} })
}

const PercentileTable = ({values}) => (

 Percentiles

        {!_.isEmpty(values) && percentages(values, [1,5,50,95,99]).map(e => {
          return (

 {e.percentage}{'%'} 	 {e.value && e.value.toFixed(3)}

          )
        })}

)

//Note: Controlled inputs don't pass through very well.  Try to keep them in child connects().
export default class MetricModal extends Component {
  showSimulation() {
    const stats = _.get(this.props, 'metric.simulation.stats')
    if (stats && _.isFinite(stats.mean) && _.isFinite(stats.stdev) && _.isFinite(stats.length)) {
      return (stats.stdev === 0 || (stats.length > 5))
    } else {
      return false
    }
  }

  shouldComponentUpdate(nextProps) {
    return (nextProps.isOpen || this.props.isOpen)
  }

  _changeGuesstimateDescription(value) {
    let newGuesstimate = Object.assign({}, this.props.metric.guesstimate, {description: value})
    this.props.onChange(newGuesstimate)
  }

  render() {
    const customStyles = {
      overlay: {
        backgroundColor: 'rgba(55, 68, 76, 0.4)'
      },
      content : {
        top                   : '10%',
        left                  : '10%',
        right                 : 'auto',
        bottom                : 'auto',
        marginRight           : '-50%',
        backgroundColor      : 'rgba(0,0,0,0)',
        border: 'none',
        padding: '0',
      }
    };
    const showSimulation = this.showSimulation()

    const {isOpen, closeModal, metric} = this.props
    const sampleValues = _.get(metric, 'simulation.sample.values')
    const guesstimate = metric.guesstimate
    return(
      <Modal
        isOpen={isOpen}
        onRequestClose={closeModal}
        style={customStyles}
      >
      {isOpen &&

            <Histogram height={150} top={0} bottom={0} bins={100} widthPercent={80} cutOffRatio={0.98}
                simulation={metric.simulation}
            />

 {metric.name}

              <ButtonClose onClick={closeModal}/>

                {showSimulation &&
                  <DistributionSummary
                      guesstimateForm={this.props.guesstimateForm}
                      simulation={metric.simulation}
                  />
                }

                <PercentileTable values={sampleValues}/>

                <DistributionEditor
                  metricId={metric.id}
                  size={'large'}
                />

              {guesstimate &&
                <GuesstimateDescription
                  onChange={this._changeGuesstimateDescription.bind(this)}
                  value={guesstimate.description}
                />
              }

      }
      </Modal>
    )
  }
}
<commit_msg>Fix typo<commit_after>import React, {Component, PropTypes} from 'react'
import Modal from 'react-modal'
import DistributionSummary from 'gComponents/distributions/summary/index.js'
import Histogram from 'gComponents/simulations/histogram'
import DistributionEditor from 'gComponents/distributions/editor/index.js'
import GuesstimateDescription from './description'
import {ButtonClose} from 'gComponents/utility/buttons/close'
import './style.css'
import {percentile, sortDescending} from 'lib/dataAnalysis.js'

const percentages = (values, perc) => {
  const samples = sortDescending(Object.assign([], values))
  return perc.map(e => { return {percentage: e, value: percentile(samples, samples.length, e)} })
}

const PercentileTable = ({values}) => (

 Percentiles

        {!_.isEmpty(values) && percentages(values, [1,5,50,95,99]).map(e => {
          return (

 {e.percentage}{'%'} 	 {e.value && e.value.toFixed(3)}

          )
        })}

)

//Note: Controlled inputs don't pass through very well.  Try to keep them in child connects().
export default class MetricModal extends Component {
  showSimulation() {
    const stats = _.get(this.props, 'metric.simulation.stats')
    if (stats && _.isFinite(stats.mean) && _.isFinite(stats.stdev) && _.isFinite(stats.length)) {
      return (stats.stdev === 0 || (stats.length > 5))
    } else {
      return false
    }
  }

  shouldComponentUpdate(nextProps) {
    return (nextProps.isOpen || this.props.isOpen)
  }

  _changeGuesstimateDescription(value) {
    let newGuesstimate = Object.assign({}, this.props.metric.guesstimate, {description: value})
    this.props.onChange(newGuesstimate)
  }

  render() {
    const customStyles = {
      overlay: {
        backgroundColor: 'rgba(55, 68, 76, 0.4)'
      },
      content : {
        top                   : '10%',
        left                  : '10%',
        right                 : 'auto',
        bottom                : 'auto',
        marginRight           : '-50%',
        backgroundColor      : 'rgba(0,0,0,0)',
        border: 'none',
        padding: '0',
      }
    };
    const showSimulation = this.showSimulation()

    const {isOpen, closeModal, metric} = this.props
    const sampleValues = _.get(metric, 'simulation.sample.values')
    const guesstimate = metric.guesstimate
    return(
      <Modal
        isOpen={isOpen}
        onRequestClose={closeModal}
        style={customStyles}
      >
      {isOpen &&

            <Histogram height={150} top={0} bottom={0} bins={100} widthPercent={80} cutOffRatio={0.98}
                simulation={metric.simulation}
            />

 {metric.name}

              <ButtonClose onClick={closeModal}/>

                {showSimulation &&
                  <DistributionSummary
                      guesstimateForm={this.props.guesstimateForm}
                      simulation={metric.simulation}
                  />
                }

                <PercentileTable values={sampleValues}/>

                <DistributionEditor
                  metricId={metric.id}
                  size={'large'}
                />

              {guesstimate &&
                <GuesstimateDescription
                  onChange={this._changeGuesstimateDescription.bind(this)}
                  value={guesstimate.description}
                />
              }

      }
      </Modal>
    )
  }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import FontAwesome from 'react-fontawesome';
import { Input } from 'reactstrap';
import gql from 'graphql-tag';

export default class Nudge extends Component {
  state = {
    nudge: localStorage.getItem('thorium-core-sensors-nudge')
  };
  nudgeContacts = ({ x = 0, y = 0, yaw = 0 }) => {
    const { nudge } = this.state;
    const { speed, client, sensor } = this.props;
    const mutation = gql`
      mutation NudgeContacts(
        $id: ID!
        $amount: CoordinatesInput!
        $speed: Float!
        $yaw: Float
      ) {
        nudgeSensorContacts(id: $id, amount: $amount, speed: $speed, yaw: $yaw)
      }
    `;
    const amount = yaw
      ? {}
      : {
          x: x * 0.01 * nudge,
          y: y * 0.01 * nudge,
          z: 0
        };
    const variables = {
      id: sensor,
      amount,
      speed,
      yaw: yaw * nudge
    };
    client.mutate({
      mutation,
      variables
    });
  };
  render() {
    const { nudge } = this.state;

    return (

        <Input
          type="select"
          onChange={evt => {
            this.setState({
              nudge: evt.target.value
            });
            localStorage.setItem(
              'thorium-core-sensors-nudge',
              evt.target.value
            );
          }}
          defaultValue={nudge}>
          {[100, 90, 75, 60, 50, 45, 30, 20, 15, 10, 5, 2, 1].map(n =>
            <option key={`nudge-${n}`} value={n}>
              {n}
            </option>
          )}
        </Input>

          <FontAwesome
            onClick={() => this.nudgeContacts({ yaw: -1 })}
            name="rotate-left"
          />
          <FontAwesome
            onClick={() => this.nudgeContacts({ x: 0, y: -1 })}
            name="arrow-up"
          />
          <FontAwesome
            onClick={() => this.nudgeContacts({ yaw: 1 })}
            name="rotate-right"
          />
          <FontAwesome
            onClick={() => this.nudgeContacts({ x: -1, y: 0 })}
            name="arrow-left"
          />
          <FontAwesome
            onClick={() => this.nudgeContacts({ x: 0, y: 1 })}
            name="arrow-down"
          />
          <FontAwesome
            onClick={() => this.nudgeContacts({ x: 1, y: 0 })}
            name="arrow-right"
          />

    );
  }
}
<commit_msg>Fix sensors nudge buttons<commit_after>import React, { Component } from "react";
import FontAwesome from "react-fontawesome";
import { Input } from "reactstrap";
import gql from "graphql-tag";

export default class Nudge extends Component {
  state = {
    nudge: localStorage.getItem("thorium-core-sensors-nudge") || 5
  };
  nudgeContacts = ({ x = 0, y = 0, yaw = 0 }) => {
    const { nudge } = this.state;
    const { speed, client, sensor } = this.props;
    const mutation = gql`
      mutation NudgeContacts(
        $id: ID!
        $amount: CoordinatesInput!
        $speed: Float!
        $yaw: Float
      ) {
        nudgeSensorContacts(id: $id, amount: $amount, speed: $speed, yaw: $yaw)
      }
    `;
    const amount = yaw
      ? {}
      : {
          x: x * 0.01 * nudge,
          y: y * 0.01 * nudge,
          z: 0
        };
    const variables = {
      id: sensor,
      amount,
      speed,
      yaw: yaw * nudge
    };
    client.mutate({
      mutation,
      variables
    });
  };
  render() {
    const { nudge } = this.state;

    return (

        <Input
          type="select"
          onChange={evt => {
            this.setState({
              nudge: evt.target.value
            });
            localStorage.setItem(
              "thorium-core-sensors-nudge",
              evt.target.value
            );
          }}
          defaultValue={nudge}
        >
          {[100, 90, 75, 60, 50, 45, 30, 20, 15, 10, 5, 2, 1].map(n => (
            <option key={`nudge-${n}`} value={n}>
              {n}
            </option>
          ))}
        </Input>

          <FontAwesome
            onClick={() => this.nudgeContacts({ yaw: -1 })}
            name="rotate-left"
          />
          <FontAwesome
            onClick={() => this.nudgeContacts({ x: 0, y: -1 })}
            name="arrow-up"
          />
          <FontAwesome
            onClick={() => this.nudgeContacts({ yaw: 1 })}
            name="rotate-right"
          />
          <FontAwesome
            onClick={() => this.nudgeContacts({ x: -1, y: 0 })}
            name="arrow-left"
          />
          <FontAwesome
            onClick={() => this.nudgeContacts({ x: 0, y: 1 })}
            name="arrow-down"
          />
          <FontAwesome
            onClick={() => this.nudgeContacts({ x: 1, y: 0 })}
            name="arrow-right"
          />

    );
  }
}
<|endoftext|>