<commit_before>'use strict';

const {OP, ADDR_MODE, FLAGS, XOP} = require('./opcodes');
const {bts2n, n2bts, N_TO_BT_DIGIT, BT_DIGIT_TO_N} = require('balanced-ternary');
const {nonary2bts} = require('nonary');
const {sv2bts} = require('base27');
const {get_trit, slice_trits} = require('trit-getset');

// assembler

// syntax
// opcode operands
//
// operands
// # = immediate mode
// % = trits, 0i1, base 3                    iiiii 5
// no prefix = decimal, base 10
// $ = nonary, base 9, each digit two trits aabbcc 3
// & = base 27, each digit three trits       aabbb 2

function assemble(lines) {
  // TODO: port to run on cpu (self-hosting)
  var output = [];

  var emit = function(tryte) {
    console.log('emit',n2bts(tryte));
    output.push(tryte);
  }

  for (var line of lines) {
    var tokens = line.split(/\s+/);
    var opcode = tokens[0];
    var operand = tokens[1];

    if (operand !== undefined) {
      var addressing_mode;

      if (operand === 'A') {
        addressing_mode = ADDR_MODE.ACCUMULATOR;
      } else {
        if (operand.charAt(0) === '#') {
          addressing_mode = ADDR_MODE.IMMEDIATE;
          operand = operand.substring(1);
        } else {
          addressing_mode = ADDR_MODE.ABSOLUTE;
        }

        switch(operand.charAt(0)) {
          case '%': // base 3, trits (%iiiii to %11111)
            operand = bts2n(operand.substring(1));
            break;
          case '$': // base 9, nonary ($imm to $144)
            operand = bts2n(nonary2bts(operand.substring(1)));
            break;
          case '&': // base 27, septemvigesimal (&QZ to &DM)
            operand = bts2n(sv2bts(operand.substring(1)));
            break;

          default:
            operand = Number.parseInt(operand, 10);
        }

        if (addressing_mode === ADDR_MODE.IMMEDIATE) {
          if (operand < -121 || operand > 121) {
            throw new Error('immediate operand out of 5-trit range: '+operand+', in line: '+line);
          }
        }
        // TODO: range check absolute
      }
    }

    console.log(tokens,opcode_value,operand);

    if (OP[opcode] !== undefined) {
      // alu
      var opcode_value = OP[opcode]; // aaab0 3-trits

      var tryte = opcode_value * Math.pow(3,2) +
        addressing_mode * Math.pow(3,1) +
        0;

      emit(tryte);

      switch(addressing_mode) {
        case ADDR_MODE.IMMEDIATE:
          emit(operand);
          break;

        case ADDR_MODE.ABSOLUTE:
          // TODO: endian?
          emit(slice_trits(operand, 0, 5));
          emit(slice_trits(operand, 5, 10));
          break;
      }
    } else if (XOP[opcode] !== undefined) {
      var opcode_value = XOP[opcode]; // aaaai 4-trits

      var tryte = opcode_value * Math.pow(3,1) + (-1);
      emit(tryte);
    } else if (opcode.charAt(0) === 'B') {
      // TODO: branch, beq (s=0), bne (s!=0) br s>0, s=0, s<0 brsen brgz brlp
      if (opcode === 'BEQ') opcode = 'BRSEZ'; // branch if equal = branch if sign equal to zero
      if (opcode === 'BNE') opcode = 'BRSNZ'; // branch if not equal = branch if sign not equal to zero

      if (opcode.charAt(1) === 'R' && opcode.length === 5) {
        var flag = opcode.charAt(2);
        var direction = opcode.charAt(3);
        var compare = opcode.charAt(4);

        var flag_value = FLAGS[flag];
        if (flag_value === undefined) {
          throw new Error('invalid flag '+flag+' in branch instruction '+opcode);
        }
        var direction_value = {
          L:-1, '<':-1,
          E:0, '=':0,
          N:1, '!':1
        }[direction];
        if (direction_value === undefined) {
          throw new Error('invalid direction '+direction+' in branch instruction '+opcode);
        }
        var compare_value = {N:-1, Z:0, P:1}[compare];
        if (compare_value === undefined) {
          throw new Error('invalid comparison trit '+compare_value+' in branch instruction '+opcode);
        }
        console.log('branch',flag_value,direction_value,compare_value);

        // aabc1 a=flag, b=trit for comparison, c=direction
        var tryte = flag_value * Math.pow(3,3) +
          compare_value * Math.pow(3,2) +
          direction_value * Math.pow(3,1) +
          1;
        emit(tryte);
        emit(operand);
      }
    }
  }

  console.log('assembled '+lines.length+' lines into '+output.length+' trytes');
  return output;
}

module.exports = assemble;
<commit_msg>Assembler absolute addressing mode 10-trit range check<commit_after>'use strict';

const {OP, ADDR_MODE, FLAGS, XOP} = require('./opcodes');
const {bts2n, n2bts, N_TO_BT_DIGIT, BT_DIGIT_TO_N} = require('balanced-ternary');
const {nonary2bts} = require('nonary');
const {sv2bts} = require('base27');
const {get_trit, slice_trits} = require('trit-getset');

// assembler

// syntax
// opcode operands
//
// operands
// # = immediate mode
// % = trits, 0i1, base 3                    iiiii 5
// no prefix = decimal, base 10
// $ = nonary, base 9, each digit two trits aabbcc 3
// & = base 27, each digit three trits       aabbb 2

function assemble(lines) {
  // TODO: port to run on cpu (self-hosting)
  var output = [];

  var emit = function(tryte) {
    console.log('emit',n2bts(tryte));
    output.push(tryte);
  }

  for (var line of lines) {
    var tokens = line.split(/\s+/);
    var opcode = tokens[0];
    var operand = tokens[1];

    if (operand !== undefined) {
      var addressing_mode;

      if (operand === 'A') {
        addressing_mode = ADDR_MODE.ACCUMULATOR;
      } else {
        if (operand.charAt(0) === '#') {
          addressing_mode = ADDR_MODE.IMMEDIATE;
          operand = operand.substring(1);
        } else {
          addressing_mode = ADDR_MODE.ABSOLUTE;
        }

        switch(operand.charAt(0)) {
          case '%': // base 3, trits (%iiiii to %11111)
            operand = bts2n(operand.substring(1));
            break;
          case '$': // base 9, nonary ($imm to $144)
            operand = bts2n(nonary2bts(operand.substring(1)));
            break;
          case '&': // base 27, septemvigesimal (&QZ to &DM)
            operand = bts2n(sv2bts(operand.substring(1)));
            break;

          default:
            operand = Number.parseInt(operand, 10);
        }

        if (addressing_mode === ADDR_MODE.IMMEDIATE) {
          if (operand < -121 || operand > 121) {
            throw new Error('immediate operand out of 5-trit range: '+operand+', in line: '+line);
          }
        } else if (addressing_mode === ADDR_MODE.ABSOLUTE) {
          // %iiiiiiiiii to %1111111111
          // $mmmmm to $44444
          // &NZZZ to &AMMM
          if (operand < -29524 || operand > 29524) {
            throw new Error('absolute operand out of 10-trit range: '+operand+', in line: '+line);
          }
        }
      }
    }

    console.log(tokens,opcode_value,operand);

    if (OP[opcode] !== undefined) {
      // alu
      var opcode_value = OP[opcode]; // aaab0 3-trits

      var tryte = opcode_value * Math.pow(3,2) +
        addressing_mode * Math.pow(3,1) +
        0;

      emit(tryte);

      switch(addressing_mode) {
        case ADDR_MODE.IMMEDIATE:
          emit(operand);
          break;

        case ADDR_MODE.ABSOLUTE:
          // TODO: endian?
          emit(slice_trits(operand, 0, 5));
          emit(slice_trits(operand, 5, 10));
          break;
      }
    } else if (XOP[opcode] !== undefined) {
      var opcode_value = XOP[opcode]; // aaaai 4-trits

      var tryte = opcode_value * Math.pow(3,1) + (-1);
      emit(tryte);
    } else if (opcode.charAt(0) === 'B') {
      // TODO: branch, beq (s=0), bne (s!=0) br s>0, s=0, s<0 brsen brgz brlp
      if (opcode === 'BEQ') opcode = 'BRSEZ'; // branch if equal = branch if sign equal to zero
      if (opcode === 'BNE') opcode = 'BRSNZ'; // branch if not equal = branch if sign not equal to zero

      if (opcode.charAt(1) === 'R' && opcode.length === 5) {
        var flag = opcode.charAt(2);
        var direction = opcode.charAt(3);
        var compare = opcode.charAt(4);

        var flag_value = FLAGS[flag];
        if (flag_value === undefined) {
          throw new Error('invalid flag '+flag+' in branch instruction '+opcode);
        }
        var direction_value = {
          L:-1, '<':-1,
          E:0, '=':0,
          N:1, '!':1
        }[direction];
        if (direction_value === undefined) {
          throw new Error('invalid direction '+direction+' in branch instruction '+opcode);
        }
        var compare_value = {N:-1, Z:0, P:1}[compare];
        if (compare_value === undefined) {
          throw new Error('invalid comparison trit '+compare_value+' in branch instruction '+opcode);
        }
        console.log('branch',flag_value,direction_value,compare_value);

        // aabc1 a=flag, b=trit for comparison, c=direction
        var tryte = flag_value * Math.pow(3,3) +
          compare_value * Math.pow(3,2) +
          direction_value * Math.pow(3,1) +
          1;
        emit(tryte);
        emit(operand);
      }
    }
  }

  console.log('assembled '+lines.length+' lines into '+output.length+' trytes');
  return output;
}

module.exports = assemble;
<|endoftext|>


<commit_before>import { Group, SpotLight, PointLight, AmbientLight } from 'three';
import TWEEN, { Linear } from 'gsap';
export default class BasicLights extends Group {
  constructor(...args) {
    super(...args);

    const point = new PointLight(0xFFFFFF, 1, 10, 1);
    const dir = new SpotLight(0xFFFFFF, 1, 100, 1, 1, 1);
    const ambi = new AmbientLight( 0x404040 , 1); // soft white light

    dir.position.set(5, 1, 2);
    dir.target.position.set(0,0,0);

    //dir.castShadow = true;

    dir.shadow.mapSize.width = 512 * 2;
    dir.shadow.mapSize.height = 512 * 2;

    dir.shadow.camera.near = 1;
    dir.shadow.camera.far = 10;
    dir.shadow.camera.fov = 40;

    point.position.set(0, 1, 5);

    TWEEN.fromTo(point.position, 4, {x: -2}, {x: 2, yoyo: true, repeat: -1, ease: Linear.easeNone});

    this.add(dir);
    this.add(ambi)
  }
}
<commit_msg>lights<commit_after>import { Group, SpotLight, PointLight, AmbientLight } from 'three';
import TWEEN, { Linear } from 'gsap';
export default class BasicLights extends Group {
  constructor(...args) {
    super(...args);

    const point = new PointLight(0xFFFFFF, 1, 10, 1);
    const dir = new SpotLight(0xFFFFFF, 1, 100, 1, 1, 1);
    const ambi = new AmbientLight( 0x404040 , 1); // soft white light

    dir.position.set(5, 1, 2);
    dir.target.position.set(0,0,0);

    // dir.castShadow = true;

    // dir.shadow.mapSize.width = 512 * 2;
    // dir.shadow.mapSize.height = 512 * 2;

    // dir.shadow.camera.near = 1;
    // dir.shadow.camera.far = 10;
    // dir.shadow.camera.fov = 40;

    point.position.set(0, 1, 5);

    TWEEN.fromTo(point.position, 4, {x: -2}, {x: 2, yoyo: true, repeat: -1, ease: Linear.easeNone});

    this.add(dir);
    this.add(ambi)
  }
}
<|endoftext|>


<commit_before>'use strict';

const { ipcRenderer } = require('electron');
const SetupSpellChecker = require('./spellchecker');

const ConfigUtil = require(__dirname + '/utils/config-util.js');

// eslint-disable-next-line import/no-unassigned-import
require('./notification');

// Prevent drag and drop event in main process which prevents remote code executaion
require(__dirname + '/shared/preventdrag.js');

const logout = () => {
	// Create the menu for the below
	document.querySelector('.dropdown-toggle').click();

	const nodes = document.querySelectorAll('.dropdown-menu li:last-child a');
	nodes[nodes.length - 1].click();
};

const shortcut = () => {
	// Create the menu for the below
	const node = document.querySelector('a[data-overlay-trigger=keyboard-shortcuts]');
	// Additional check
	if (node.text.trim().toLowerCase() === 'keyboard shortcuts') {
		node.click();
	} else {
		// Atleast click the dropdown
		document.querySelector('.dropdown-toggle').click();
	}
};

process.once('loaded', () => {
	global.logout = logout;
	global.shortcut = shortcut;
});

// To prevent failing this script on linux we need to load it after the document loaded
document.addEventListener('DOMContentLoaded', () => {
	// Get the default language of the server
	const serverLanguage = page_params.default_language; // eslint-disable-line no-undef, camelcase

	if (serverLanguage) {
		// Set spellcheker language
		ConfigUtil.setConfigItem('spellcheckerLanguage', serverLanguage);
		// Init spellchecker
		SetupSpellChecker.init();
	}

	// redirect users to network troubleshooting page
	const getRestartButton = document.querySelector('.restart_get_events_button');
	if (getRestartButton) {
		getRestartButton.addEventListener('click', () => {
			ipcRenderer.send('forward-message', 'reload-viewer');
		});
	}
});

// Clean up spellchecker events after you navigate away from this page;
// otherwise, you may experience errors
window.addEventListener('beforeunload', () => {
	SetupSpellChecker.unsubscribeSpellChecker();
});

<commit_msg>shortcuts: Update string for selecting the keyboard shortcuts node.<commit_after>'use strict';

const { ipcRenderer } = require('electron');
const SetupSpellChecker = require('./spellchecker');

const ConfigUtil = require(__dirname + '/utils/config-util.js');

// eslint-disable-next-line import/no-unassigned-import
require('./notification');

// Prevent drag and drop event in main process which prevents remote code executaion
require(__dirname + '/shared/preventdrag.js');

const logout = () => {
	// Create the menu for the below
	document.querySelector('.dropdown-toggle').click();

	const nodes = document.querySelectorAll('.dropdown-menu li:last-child a');
	nodes[nodes.length - 1].click();
};

const shortcut = () => {
	// Create the menu for the below
	const node = document.querySelector('a[data-overlay-trigger=keyboard-shortcuts]');
	// Additional check
	if (node.text.trim().toLowerCase() === 'keyboard shortcuts (?)') {
		node.click();
	} else {
		// Atleast click the dropdown
		document.querySelector('.dropdown-toggle').click();
	}
};

process.once('loaded', () => {
	global.logout = logout;
	global.shortcut = shortcut;
});

// To prevent failing this script on linux we need to load it after the document loaded
document.addEventListener('DOMContentLoaded', () => {
	// Get the default language of the server
	const serverLanguage = page_params.default_language; // eslint-disable-line no-undef, camelcase

	if (serverLanguage) {
		// Set spellcheker language
		ConfigUtil.setConfigItem('spellcheckerLanguage', serverLanguage);
		// Init spellchecker
		SetupSpellChecker.init();
	}

	// redirect users to network troubleshooting page
	const getRestartButton = document.querySelector('.restart_get_events_button');
	if (getRestartButton) {
		getRestartButton.addEventListener('click', () => {
			ipcRenderer.send('forward-message', 'reload-viewer');
		});
	}
});

// Clean up spellchecker events after you navigate away from this page;
// otherwise, you may experience errors
window.addEventListener('beforeunload', () => {
	SetupSpellChecker.unsubscribeSpellChecker();
});

<|endoftext|>


<commit_before>// @flow
import { pick } from 'lodash';
import moment from 'moment-timezone';
import type { TransformEvent } from 'app/models';

// Value type based on the EVENT_CONSTANTS
export type eventTypes = $Values<typeof EVENT_CONSTANTS>;

// Current eventTypes
export const EVENT_CONSTANTS: eventTypes = {
  company_presentation: 'Bedpres',
  lunch_presentation: 'Lunsjpresentasjon',
  alternative_presentation: 'Alternativt bedpres',
  course: 'Kurs',
  party: 'Fest',
  social: 'Sosialt',
  event: 'Arrangement',
  kid_event: 'KID-arrangement',
  other: 'Annet'
};

// Returns the sting representation of an eventType
export const eventTypeToString = (eventType: eventTypes) => {
  return EVENT_CONSTANTS[eventType] || EVENT_CONSTANTS['other'];
};

// Colors for different event types
export const COLOR_CONSTANTS: eventTypes = {
  company_presentation: '#A1C34A',
  lunch_presentation: '#A1C34A',
  alternative_presentation: '#8A2BE2',
  course: '#52B0EC',
  party: '#FCD748',
  social: '#B11C11',
  event: '#B11C11',
  kid_event: '#111111',
  other: '#111111'
};

// Returns the color code of an eventType
export const colorForEvent = (eventType: eventTypes) => {
  return COLOR_CONSTANTS[eventType] || COLOR_CONSTANTS['other'];
};

// Event fields that should be created or updated based on the API.
const eventCreateAndUpdateFields = [
  'id',
  'title',
  'cover',
  'description',
  'text',
  'company',
  'feedbackDescription',
  'feedbackRequired',
  'eventType',
  'eventStatusType',
  'location',
  'isPriced',
  'priceMember',
  'priceGuest',
  'useStripe',
  'paymentDueDate',
  'useCaptcha',
  'tags',
  'pools',
  'unregistrationDeadline',
  'pinned',
  'heedPenalties',
  'isAbakomOnly',
  'useConsent'
];

// Pool fields that should be created or updated based on the API
const poolCreateAndUpdateFields = [
  'id',
  'name',
  'capacity',
  'activationDate',
  'permissionGroups'
];

/* Calculate the event price
 * @param isPriced: If the event is priced
 * @param addFee: If the event uses Stipe and needs a fee
 */
const calculatePrice = data => {
  if (data.isPriced) {
    if (data.addFee) {
      return addStripeFee(data.priceMember) * 100;
    }
    return data.priceMember * 100;
  }
  return 0;
};
/* Calculate the event location
 * @param eventStatusType: what kind of registrationmode this event has
 */
const calculateLocation = data =>
  data.eventStatusType == 'TBA' ? 'TBA' : data.location;

/* Calculate the event pools
 * @param eventStatusType: what kind of registrationmode this event has
 * @param pools: the event groups as specified by the CreateEvent forms
 */
const calculatePools = data => {
  switch (data.eventStatusType) {
    case 'TBA':
    case 'OPEN':
      return [];
    case 'INFINITE':
      return [
        {
          ...pick(data.pools[0], poolCreateAndUpdateFields),
          activationDate: moment(data.pools[0].activationDate).toISOString(),
          permissionGroups: data.pools[0].permissionGroups.map(
            group => group.value
          )
        }
      ];
    case 'NORMAL':
      return data.pools.map(pool => ({
        ...pick(pool, poolCreateAndUpdateFields),
        activationDate: moment(pool.activationDate).toISOString(),
        permissionGroups: pool.permissionGroups.map(group => group.value)
      }));
    default:
      break;
  }
};

/* Calculte and convert to payment due date
 * @param paymentDueDate: date from form
 */
const calculatePaymentDueDate = data =>
  data.isPriced ? moment(data.paymentDueDate).toISOString() : null;

/* Calcualte and convert the registation deadline
 * @param unregistationDeadline: data from form
 */
const calculateUnregistrationDeadline = data =>
  data.unregistrationDeadline
    ? moment(data.unregistrationDeadline).toISOString()
    : null;

/* Calculate the merge time for the pools. Only set if there are more then one pool
 * @param mergeTime: date from form
 */
const calculateMergeTime = data =>
  data.pools.length > 1 ? moment(data.mergeTime).toISOString() : null;

// Takes the full data-object and input and transforms the event to the API format.
export const transformEvent = (data: TransformEvent) => ({
  ...pick(data, eventCreateAndUpdateFields),
  startTime: moment(data.startTime).toISOString(),
  endTime: moment(data.endTime).toISOString(),
  mergeTime: calculateMergeTime(data),
  company: data.company && data.company.value,
  eventStatusType: data.eventStatusType,
  responsibleGroup: data.responsibleGroup && data.responsibleGroup.value,
  priceMember: calculatePrice(data),
  location: calculateLocation(data),
  paymentDueDate: calculatePaymentDueDate(data),
  unregistrationDeadline: calculateUnregistrationDeadline(data),
  pools: calculatePools(data),
  useCaptcha: true, // always use Captcha, this blocks the use of CLI
  youtubeUrl: data.youtubeUrl
});

export const paymentPending = 'pending';
export const paymentSuccess = 'succeeded';
export const paymentFailure = 'failed';
export const paymentManual = 'manual';
export const paymentCardDeclined = 'card_declined';
export const paymentCardExpired = 'expired_card';

const paymentSuccessMappings = {
  [paymentManual]: true,
  [paymentSuccess]: true,
  [paymentPending]: false,
  [paymentFailure]: false
};

export const hasPaid = (chargeStatus: string) =>
  paymentSuccessMappings[chargeStatus];

export const addStripeFee = (price: number) => Math.ceil(price * 1.012 + 1.8);
<commit_msg>Phrasing & Spelling<commit_after>// @flow
import { pick } from 'lodash';
import moment from 'moment-timezone';
import type { TransformEvent } from 'app/models';

// Value type based on the EVENT_CONSTANTS
export type eventTypes = $Values<typeof EVENT_CONSTANTS>;

// Current eventTypes
export const EVENT_CONSTANTS: eventTypes = {
  company_presentation: 'Bedprespresentasjon',
  lunch_presentation: 'Lunsjpresentasjon',
  alternative_presentation: 'Alternativt bedpres',
  course: 'Kurs',
  party: 'Fest',
  social: 'Sosialt',
  event: 'Arrangement',
  kid_event: 'KID-arrangement',
  other: 'Annet'
};

// Returns the string representation of an eventType
export const eventTypeToString = (eventType: eventTypes) => {
  return EVENT_CONSTANTS[eventType] || EVENT_CONSTANTS['other'];
};

// Colors for different event types
export const COLOR_CONSTANTS: eventTypes = {
  company_presentation: '#A1C34A',
  lunch_presentation: '#A1C34A',
  alternative_presentation: '#8A2BE2',
  course: '#52B0EC',
  party: '#FCD748',
  social: '#B11C11',
  event: '#B11C11',
  kid_event: '#111111',
  other: '#111111'
};

// Returns the color code of an eventType
export const colorForEvent = (eventType: eventTypes) => {
  return COLOR_CONSTANTS[eventType] || COLOR_CONSTANTS['other'];
};

// Event fields that should be created or updated based on the API.
const eventCreateAndUpdateFields = [
  'id',
  'title',
  'cover',
  'description',
  'text',
  'company',
  'feedbackDescription',
  'feedbackRequired',
  'eventType',
  'eventStatusType',
  'location',
  'isPriced',
  'priceMember',
  'priceGuest',
  'useStripe',
  'paymentDueDate',
  'useCaptcha',
  'tags',
  'pools',
  'unregistrationDeadline',
  'pinned',
  'heedPenalties',
  'isAbakomOnly',
  'useConsent'
];

// Pool fields that should be created or updated based on the API
const poolCreateAndUpdateFields = [
  'id',
  'name',
  'capacity',
  'activationDate',
  'permissionGroups'
];

/* Calculate the event price
 * @param isPriced: If the event is priced
 * @param addFee: If the event uses Stipe and needs a fee
 */
const calculatePrice = data => {
  if (data.isPriced) {
    if (data.addFee) {
      return addStripeFee(data.priceMember) * 100;
    }
    return data.priceMember * 100;
  }
  return 0;
};
/* Calculate the event location
 * @param eventStatusType: what kind of registrationmode this event has
 */
const calculateLocation = data =>
  data.eventStatusType == 'TBA' ? 'TBA' : data.location;

/* Calculate the event pools
 * @param eventStatusType: what kind of registrationmode this event has
 * @param pools: the event groups as specified by the CreateEvent forms
 */
const calculatePools = data => {
  switch (data.eventStatusType) {
    case 'TBA':
    case 'OPEN':
      return [];
    case 'INFINITE':
      return [
        {
          ...pick(data.pools[0], poolCreateAndUpdateFields),
          activationDate: moment(data.pools[0].activationDate).toISOString(),
          permissionGroups: data.pools[0].permissionGroups.map(
            group => group.value
          )
        }
      ];
    case 'NORMAL':
      return data.pools.map(pool => ({
        ...pick(pool, poolCreateAndUpdateFields),
        activationDate: moment(pool.activationDate).toISOString(),
        permissionGroups: pool.permissionGroups.map(group => group.value)
      }));
    default:
      break;
  }
};

/* Calculte and convert to payment due date
 * @param paymentDueDate: date from form
 */
const calculatePaymentDueDate = data =>
  data.isPriced ? moment(data.paymentDueDate).toISOString() : null;

/* Calcualte and convert the registation deadline
 * @param unregistationDeadline: data from form
 */
const calculateUnregistrationDeadline = data =>
  data.unregistrationDeadline
    ? moment(data.unregistrationDeadline).toISOString()
    : null;

/* Calculate the merge time for the pools. Only set if there are more then one pool
 * @param mergeTime: date from form
 */
const calculateMergeTime = data =>
  data.pools.length > 1 ? moment(data.mergeTime).toISOString() : null;

// Takes the full data-object and input and transforms the event to the API format.
export const transformEvent = (data: TransformEvent) => ({
  ...pick(data, eventCreateAndUpdateFields),
  startTime: moment(data.startTime).toISOString(),
  endTime: moment(data.endTime).toISOString(),
  mergeTime: calculateMergeTime(data),
  company: data.company && data.company.value,
  eventStatusType: data.eventStatusType,
  responsibleGroup: data.responsibleGroup && data.responsibleGroup.value,
  priceMember: calculatePrice(data),
  location: calculateLocation(data),
  paymentDueDate: calculatePaymentDueDate(data),
  unregistrationDeadline: calculateUnregistrationDeadline(data),
  pools: calculatePools(data),
  useCaptcha: true, // always use Captcha, this blocks the use of CLI
  youtubeUrl: data.youtubeUrl
});

export const paymentPending = 'pending';
export const paymentSuccess = 'succeeded';
export const paymentFailure = 'failed';
export const paymentManual = 'manual';
export const paymentCardDeclined = 'card_declined';
export const paymentCardExpired = 'expired_card';

const paymentSuccessMappings = {
  [paymentManual]: true,
  [paymentSuccess]: true,
  [paymentPending]: false,
  [paymentFailure]: false
};

export const hasPaid = (chargeStatus: string) =>
  paymentSuccessMappings[chargeStatus];

export const addStripeFee = (price: number) => Math.ceil(price * 1.012 + 1.8);
<|endoftext|>


<commit_before>import { take, race, takeEvery, call, put, select } from 'redux-saga/effects';
import AnalyticsService from '../analytics/AnalyticsService';
import * as analyticsAction from '../actions/analyticsActions';
import { PROD_ACTION_DEDAIL, PROD_CLICK } from '../actions/actionTypes';
import {
  getFilterInfoFromCategory,
  getFilterMap,
  getFiltersCategoryCode,
  getCatalogueProducts,
  getStoreCode,
  getWorldName,
  getCurrentPath } from '../reducers/selectors';

export default function* analyticsSaga() {
  yield takeEvery('*', function* callAnalyticsSession() {
    // eslint-disable-next-line no-constant-condition
    while (true) {
      const {
        locationChange,
        setSessionData,
        idleTimerComplete,
        startAnalyticsSession,
        setProduct,
        setRelatedProduct,
        startAnalyticsProduct,
        filters,
        trackFilters,
        resetFilters,
        productClick,
        trackProductClick
      } = yield race({
        locationChange: take('@@router/LOCATION_CHANGE'),
        setSessionData: take('SUCCESS_FETCH_WORLD'),
        idleTimerComplete: take('IDLE_TIMER_COMPLETE'),
        startAnalyticsSession: take('START_ANALYTICS_SESSION'),
        setProduct: take('SUCCESS_FETCH_PRODUCT'),
        setRelatedProduct: take('SUCCESS_FETCH_PRODUCTLIST'),
        startAnalyticsProduct: take('START_ANALYTICS_PRODUCT'),
        filters: take(
          [
            'TOGGLE_AID',
            'APPLY_TEMP_FILTERS',
            'TOGGLE_AVAILABILITY',
            'TOGGLE_FILTER'
          ]
        ),
        resetFilters: take('RESET_FILTERS'),
        trackFilters: take('TRACK_ANALYTICS_FILTERS'),
        productClick: take('SET_ANALYTICS_PRODUCT_CLICK'),
        trackProductClick: take('TRACK_PRODUCT_CLICK')
      });

      const state = yield select();

      if (locationChange) {
        yield call(AnalyticsService.setPageName, locationChange.payload.pathname);
      }

      if (setSessionData) {
        const storeCode = yield select(getStoreCode);
        const worldName = yield select(getWorldName);
        const location = yield select(getCurrentPath);
        yield call(AnalyticsService.setNavigationStore, storeCode);
        yield call(AnalyticsService.setCid);
        yield call(AnalyticsService.setReleaseVersion, worldName);

        if (location === '/world') {
          yield put(analyticsAction.startAnalyticsSession());
        }
      }

      if (idleTimerComplete) {
        yield call(AnalyticsService.deleteInDataLayer, idleTimerComplete.type);
      }

      if (setProduct) {
        yield call(AnalyticsService.setProduct, setProduct.result, PROD_ACTION_DEDAIL);
      }

      if (setRelatedProduct) {
        yield call(AnalyticsService.setRelatedProduct, setRelatedProduct.result);
      }

      if (filters) {
        const { sellingAids, filterGroup } = yield select(getFilterInfoFromCategory);
        const categoryCode = yield select(getFiltersCategoryCode);
        const productList = yield getCatalogueProducts()(state, categoryCode);
        const productsNumber = productList.size;
        const activeFilters = yield select(getFilterMap);

        yield call(AnalyticsService.setFilters,
          {
            sellingAids,
            filterGroup,
            productsNumber,
            activeFilters
          }
        );

        yield call(AnalyticsService.setRelatedProduct, productList);
        yield put(analyticsAction.trackAnalyticsFilters());
      }

      if (resetFilters) {
        const categoryCode = yield select(getFiltersCategoryCode);
        const productList = yield getCatalogueProducts()(state, categoryCode);
        const productsNumber = productList.size;

        yield call(AnalyticsService.clearFilters, productsNumber);
        yield call(AnalyticsService.setRelatedProduct, productList);
        yield put(analyticsAction.trackAnalyticsFilters());
      }

      if (startAnalyticsSession) {
        yield put(analyticsAction.setAnalyticsSessionCode());
        yield put(analyticsAction.trackAnalyticsSessionStart());
        yield call(AnalyticsService.track, 'view');
      }

      if (productClick) {
        const { product, index = 0 } = productClick.data;
        yield call(AnalyticsService.setProduct, { product, action: PROD_CLICK, index });
        yield put(analyticsAction.trackProductClick());
      }

      if (startAnalyticsProduct) {
        yield call(AnalyticsService.track, 'view');
      }

      if (trackFilters) {
        yield call(AnalyticsService.track, 'view');
      }

      if (trackProductClick) {
        yield call(AnalyticsService.track, 'link');
      }

      // disable multiple calls https://github.com/redux-saga/redux-saga/issues/471
      return;
    }
  });
}
<commit_msg>fix wrong argument to setProduct<commit_after>import { take, race, takeEvery, call, put, select } from 'redux-saga/effects';
import AnalyticsService from '../analytics/AnalyticsService';
import * as analyticsAction from '../actions/analyticsActions';
import { PROD_ACTION_DEDAIL, PROD_CLICK } from '../actions/actionTypes';
import {
  getFilterInfoFromCategory,
  getFilterMap,
  getFiltersCategoryCode,
  getCatalogueProducts,
  getStoreCode,
  getWorldName,
  getCurrentPath } from '../reducers/selectors';

export default function* analyticsSaga() {
  yield takeEvery('*', function* callAnalyticsSession() {
    // eslint-disable-next-line no-constant-condition
    while (true) {
      const {
        locationChange,
        setSessionData,
        idleTimerComplete,
        startAnalyticsSession,
        setProduct,
        setRelatedProduct,
        startAnalyticsProduct,
        filters,
        trackFilters,
        resetFilters,
        productClick,
        trackProductClick
      } = yield race({
        locationChange: take('@@router/LOCATION_CHANGE'),
        setSessionData: take('SUCCESS_FETCH_WORLD'),
        idleTimerComplete: take('IDLE_TIMER_COMPLETE'),
        startAnalyticsSession: take('START_ANALYTICS_SESSION'),
        setProduct: take('SUCCESS_FETCH_PRODUCT'),
        setRelatedProduct: take('SUCCESS_FETCH_PRODUCTLIST'),
        startAnalyticsProduct: take('START_ANALYTICS_PRODUCT'),
        filters: take(
          [
            'TOGGLE_AID',
            'APPLY_TEMP_FILTERS',
            'TOGGLE_AVAILABILITY',
            'TOGGLE_FILTER'
          ]
        ),
        resetFilters: take('RESET_FILTERS'),
        trackFilters: take('TRACK_ANALYTICS_FILTERS'),
        productClick: take('SET_ANALYTICS_PRODUCT_CLICK'),
        trackProductClick: take('TRACK_PRODUCT_CLICK')
      });

      const state = yield select();

      if (locationChange) {
        yield call(AnalyticsService.setPageName, locationChange.payload.pathname);
      }

      if (setSessionData) {
        const storeCode = yield select(getStoreCode);
        const worldName = yield select(getWorldName);
        const location = yield select(getCurrentPath);
        yield call(AnalyticsService.setNavigationStore, storeCode);
        yield call(AnalyticsService.setCid);
        yield call(AnalyticsService.setReleaseVersion, worldName);

        if (location === '/world') {
          yield put(analyticsAction.startAnalyticsSession());
        }
      }

      if (idleTimerComplete) {
        yield call(AnalyticsService.deleteInDataLayer, idleTimerComplete.type);
      }

      if (setProduct) {
        yield call(AnalyticsService.setProduct, { product: setProduct.result, PROD_ACTION_DEDAIL });
      }

      if (setRelatedProduct) {
        yield call(AnalyticsService.setRelatedProduct, setRelatedProduct.result);
      }

      if (filters) {
        const { sellingAids, filterGroup } = yield select(getFilterInfoFromCategory);
        const categoryCode = yield select(getFiltersCategoryCode);
        const productList = yield getCatalogueProducts()(state, categoryCode);
        const productsNumber = productList.size;
        const activeFilters = yield select(getFilterMap);

        yield call(AnalyticsService.setFilters,
          {
            sellingAids,
            filterGroup,
            productsNumber,
            activeFilters
          }
        );

        yield call(AnalyticsService.setRelatedProduct, productList);
        yield put(analyticsAction.trackAnalyticsFilters());
      }

      if (resetFilters) {
        const categoryCode = yield select(getFiltersCategoryCode);
        const productList = yield getCatalogueProducts()(state, categoryCode);
        const productsNumber = productList.size;

        yield call(AnalyticsService.clearFilters, productsNumber);
        yield call(AnalyticsService.setRelatedProduct, productList);
        yield put(analyticsAction.trackAnalyticsFilters());
      }

      if (startAnalyticsSession) {
        yield put(analyticsAction.setAnalyticsSessionCode());
        yield put(analyticsAction.trackAnalyticsSessionStart());
        yield call(AnalyticsService.track, 'view');
      }

      if (productClick) {
        const { product, index = 0 } = productClick.data;
        yield call(AnalyticsService.setProduct, { product, action: PROD_CLICK, index });
        yield put(analyticsAction.trackProductClick());
      }

      if (startAnalyticsProduct) {
        yield call(AnalyticsService.track, 'view');
      }

      if (trackFilters) {
        yield call(AnalyticsService.track, 'view');
      }

      if (trackProductClick) {
        yield call(AnalyticsService.track, 'link');
      }

      // disable multiple calls https://github.com/redux-saga/redux-saga/issues/471
      return;
    }
  });
}
<|endoftext|>


<commit_before>/**
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

window.IOWA = window.IOWA || {};

IOWA.Util = IOWA.Util || (function() {

  "use strict";

  // From http://en.wikipedia.org/wiki/Smoothstep
  function smoothStep(start, end, point) {
    if (point <= start) {
      return 0;
    }
    if (point >= end) {
      return 1;
    }
    var x = (point - start) / (end - start); // interpolation
    return x * x * (3 - 2 * x);
  }

  /**
   * Smooth scrolls to the top of an element.
   *
   * @param {Element} el Element to scroll to.
   * @param {number=} opt_duration Optional duration for the animation to
   *     take. If not specified, the element is immediately scrolled to.
   * @param {Function=} opt_callback Callback to execute at the end of the scroll.
   */
  function smoothScroll(el, opt_duration, opt_callback) {
    var duration = opt_duration || 1;

    var scrollContainer = IOWA.Elements.ScrollContainer;

    var startTime = performance.now();
    var endTime = startTime + duration;
    var startTop = scrollContainer.scrollTop;
    var destY = el.getBoundingClientRect().top;

    if (destY === 0) {
      opt_callback && opt_callback();
      return; // already at top of element.
    }

    var callback = function(timestamp) {
      if (timestamp < endTime) {
        requestAnimationFrame(callback);
      } else if (opt_callback) {
        opt_callback();
      }

      var point = smoothStep(startTime, endTime, timestamp);
      var scrollTop = Math.round(startTop + (destY * point));

      scrollContainer.scrollTop = scrollTop;
    };

    callback(startTime);
  }

  function isIOS() {
    return (/(iPhone|iPad|iPod)/gi).test(navigator.platform);
  }

  function isSafari() {
    var userAgent = navigator.userAgent;
    return (/Safari/gi).test(userAgent) &&
      !(/Chrome/gi).test(userAgent);
  }

  function isIE() {
    var userAgent = navigator.userAgent;
    return (/Trident/gi).test(userAgent);
  }

  /**
   * Returns the static base URL of the running app.
   * https://events.google.com/io2015/about -> https://events.google.com/io2015/
   */
  function getStaticBaseURL() {
    return location.href.substring(0, location.href.lastIndexOf('/') + 1);
  }

  /**
   * Adjusts the size of the ripple to fully cover the parent element.
   * @param {Element} ripple The ripple DOM element.
   * @return {Object} parentRect Parent bounding rect, for reuse.
   */
  var resizeRipple = function(ripple) {
    var parentRect = ripple.parentNode.getBoundingClientRect();
    var radius = Math.floor(Math.sqrt(parentRect.width * parentRect.width +
      parentRect.height * parentRect.height));
    ripple.style.width = 2 * radius + 'px';
    ripple.style.height = 2 * radius + 'px';
    ripple.style.left = -radius + 'px';
    ripple.style.top = -radius + 'px';
    return parentRect;
  };

  return {
    isIE: isIE,
    isIOS: isIOS,
    isSafari: isSafari,
    supportsHTMLImports: 'import' in document.createElement('link'),
    smoothScroll: smoothScroll,
    getStaticBaseURL: getStaticBaseURL,
    resizeRipple: resizeRipple
  };

})();
<commit_msg>unbreak build<commit_after>/**
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

window.IOWA = window.IOWA || {};

IOWA.Util = IOWA.Util || (function() {

  "use strict";

  // From http://en.wikipedia.org/wiki/Smoothstep
  function smoothStep(start, end, point) {
    if (point <= start) {
      return 0;
    }
    if (point >= end) {
      return 1;
    }
    var x = (point - start) / (end - start); // interpolation
    return x * x * (3 - 2 * x);
  }

  /**
   * Smooth scrolls to the top of an element.
   *
   * @param {Element} el Element to scroll to.
   * @param {number=} opt_duration Optional duration for the animation to
   *     take. If not specified, the element is immediately scrolled to.
   * @param {Function=} opt_callback Callback to execute at the end of the scroll.
   */
  function smoothScroll(el, opt_duration, opt_callback) {
    var duration = opt_duration || 1;

    var scrollContainer = IOWA.Elements.ScrollContainer;

    var startTime = performance.now();
    var endTime = startTime + duration;
    var startTop = scrollContainer.scrollTop;
    var destY = el.getBoundingClientRect().top;

    if (destY === 0) {
      if (opt_callback) {
        opt_callback();
      }
      return; // already at top of element.
    }

    var callback = function(timestamp) {
      if (timestamp < endTime) {
        requestAnimationFrame(callback);
      } else if (opt_callback) {
        opt_callback();
      }

      var point = smoothStep(startTime, endTime, timestamp);
      var scrollTop = Math.round(startTop + (destY * point));

      scrollContainer.scrollTop = scrollTop;
    };

    callback(startTime);
  }

  function isIOS() {
    return (/(iPhone|iPad|iPod)/gi).test(navigator.platform);
  }

  function isSafari() {
    var userAgent = navigator.userAgent;
    return (/Safari/gi).test(userAgent) &&
      !(/Chrome/gi).test(userAgent);
  }

  function isIE() {
    var userAgent = navigator.userAgent;
    return (/Trident/gi).test(userAgent);
  }

  /**
   * Returns the static base URL of the running app.
   * https://events.google.com/io2015/about -> https://events.google.com/io2015/
   */
  function getStaticBaseURL() {
    return location.href.substring(0, location.href.lastIndexOf('/') + 1);
  }

  /**
   * Adjusts the size of the ripple to fully cover the parent element.
   * @param {Element} ripple The ripple DOM element.
   * @return {Object} parentRect Parent bounding rect, for reuse.
   */
  var resizeRipple = function(ripple) {
    var parentRect = ripple.parentNode.getBoundingClientRect();
    var radius = Math.floor(Math.sqrt(parentRect.width * parentRect.width +
      parentRect.height * parentRect.height));
    ripple.style.width = 2 * radius + 'px';
    ripple.style.height = 2 * radius + 'px';
    ripple.style.left = -radius + 'px';
    ripple.style.top = -radius + 'px';
    return parentRect;
  };

  return {
    isIE: isIE,
    isIOS: isIOS,
    isSafari: isSafari,
    supportsHTMLImports: 'import' in document.createElement('link'),
    smoothScroll: smoothScroll,
    getStaticBaseURL: getStaticBaseURL,
    resizeRipple: resizeRipple
  };

})();
<|endoftext|>


<commit_before>(function(angular, OpenLayers, undefined) {
	'use strict';

	/**
	 * Map Service
	 *
	 */
	angular
		.module('app')
		.service('Map', MapService);

	function MapService() {

		var self = this;

		/**
   	* setup
   	*/
	  function _setup(opts) {
	    OpenLayers.Util.applyDefaults(opts, {
	    });

	    self._map = new OpenLayers.Map(opts.id, {
	    	theme: null,
	    	projection: 'EPSG:4326',
	    	displayProjection: 'EPSG:4326'
	    });

	    self._startZoom  = opts.startZoom;
	    self._startLonlat = new OpenLayers.LonLat(opts.startLonlat.lon, opts.startLonlat.lat);

	    self._layers = [];
	    self._baselayers = [];
	    self._controls = [];

	    self.onSelectPoint = opts.onSelectPoint;

	    _setupLayers();
			_setupStyles();
	    _setupControls();
	  }

	  /**
	   * setBaseLayers method
	   */
	  function _setupLayers() {
	    self._baselayer = {
				OSM: 				   		 0,
				GOOGLE_MAP:    		 1,
				GOOGLE_MAP_NIGHT:  2,
				GOOGLE_MAP_HYBRID: 3
			};

			self._baselayers = [
				new OpenLayers.Layer.OSM('OpenStreetMap'),
				new OpenLayers.Layer.Google('Google Maps', {
					numZoomLevels: 19
				}),
				new OpenLayers.Layer.Google('Google Maps Night', {
					type: 'styled',
					numZoomLevels: 19
				}),
				new OpenLayers.Layer.Google('Google Maps Satellite', {
					numZoomLevels: 19,
					type: google.maps.MapTypeId.HYBRID
				})
			];

			self._layers = {
				position: new OpenLayers.Layer.Vector('Position', {
					styleMap: new OpenLayers.StyleMap({
						'default': {
							externalGraphic: "${icon}",
							graphicWidth: 40,
							cursor: 'pointer'
						}
					})
				})
			};

			self._map.addLayers(self._baselayers);
			for(var key in self._layers) {
				self._map.addLayer(self._layers[key]);
			}
	  }

	  function _setupStyles() {
	  	var styleNight = [{
				featureType: 'all',
				elementType: 'all',
					"stylers": [
			      { "invert_lightness": true },
			      { "visibility": "on" },
			      { "hue": "#00bbff" },
			      { "saturation": 1 }
			    ]
			}];
		 	var styledNightOptions = { name: 'Styled Map' };
		  var styledNightType = new google.maps.StyledMapType(styleNight, styledNightOptions);

			self._baselayers[self._baselayer.GOOGLE_MAP_NIGHT].mapObject.mapTypes.set('styled', styledNightType);
			self._baselayers[self._baselayer.GOOGLE_MAP_NIGHT].mapObject.setMapTypeId('styled');
	  }

	  function _setupControls() {
	    self._controls = {
	      zoom: new OpenLayers.Control.Zoom(),
	      nav: new OpenLayers.Control.Navigation({
          documentDrag: true,
          dragPanOptions: { enableKinetic: true }
        }),
        selectPoint: new OpenLayers.Control.SelectFeature([self._layers.position], {
        	autoActivate: true,
        	onSelect: self.onSelectPoint
        }),
	      mousePosition: new OpenLayers.Control.MousePosition()
	    };

	    for(var key in self._controls) {
	      self._map.addControl(self._controls[key]);
	    }
	  }

		this.init = function(opts) {
			_setup(opts);

			self.fixMapHeight();
			self.setCenterMap();
		};

	  this.setBaseLayer = function(index) {
	    self._map.setBaseLayer(self._map.layers[index]);
	  };

		this.getBaselayersList = function() {
			var arr = [];
			for (var key in self._baselayers) {
				arr.push(self._baselayers[key].name);
			}
			return arr;
		};

		this.setBaseLayer = function(index) {
			self._map.setBaseLayer(self._map.layers[index]);
		};

	  this.setCenterMap = function(point, zoom, opts) {
	  	var defaultOpts = {};
	  	opts = opts || {};

	  	if(point && !point.hasOwnProperty('CLASS_NAME') && point.CLASS_NAME !== 'OpenLayers.LonLat') {
	  		point = new OpenLayers.LonLat(point.lon, point.lat);
	  	}

	  	if(opts.hasOwnProperty('transformTo')) {
	  		point = point.transform(new OpenLayers.Projection(opts.transformTo), self._map.getProjection());
	  	}

	    self._map.setCenter(point || self._startLonlat, zoom || self._startZoom);
	  };

	  this.setZoom = function(zoom) {
	  	self._map.setCenter(null, zoom);
	  };

	  this.zoomIn = function() {
	  	self._map.zoomIn();
	  };

	  this.zoomOut = function() {
	  	self._map.zoomOut();
	  };

		this.addPoints = function(points, opts, callback) {
			var arrPontos = [];
			var defaultOpts = {
				layer: 'position',
				clearBefore: true,
			};
			opts = opts || {};

			OpenLayers.Util.applyDefaults(opts, defaultOpts);

			for(var key in points) {
				var label = points[key].hasOwnProperty('label') ? points[key].label : '';
				var pointOpts = {
					label: label,
					icon:  points[key].icon
				};

				var point = new OpenLayers.Geometry.Point(points[key].lon, points[key].lat);
				if (opts.hasOwnProperty('transformTo')) {
					point = point.transform(opts.transformTo, self._map.getProjection());
				}

				var feature = new OpenLayers.Feature.Vector(point, pointOpts);
				feature.data = points[key];

				arrPontos.push(feature);
			}

			if(opts.clearBefore) {
				self._layers[opts.layer].destroyFeatures();
			}

			self._layers[opts.layer].addFeatures(arrPontos);

			if(typeof(callback) === 'function') callback();
		};

		this.addPoint = function(point, opts, callback) {
			self.addPoints([point], opts, callback);
		};

		this.showPopup = function(lonlat, content, opts) {
			var popup = null;
			var defaultOpts = {
				clear: true,
				type: 'Point'
			};
			opts = opts || {};

			OpenLayers.Util.applyDefaults(opts, defaultOpts);

			popup = new OpenLayers.Popup('Popup ' + opts.type,
				new OpenLayers.LonLat(lonlat.lon, lonlat.lat),
				null,
				content,
				true
			);
			popup.opacity = '.9';

			if (opts.hasOwnProperty('clear') && opts.clear) {
				self.removePopups();
			}

			self._map.addPopup(popup);

			popup.fixPadding();
			popup.updateSize();
		};

		this.removePopups = function() {
			for(var key in self._map.popups) {
				self._map.removePopup(self._map.popups[key]);
			}
		};

	  this.getPosition = function(callbackSuccess, callbackFailed, callbackAlways) {
	  	var point;

	  	if(!self._layers.hasOwnProperty('geolocate')) {
	  		self._layers.geolocate = new OpenLayers.Layer.Vector('Geolocate');
	      self._map.addLayer(self._layers.geolocate);
	  	}

	  	if (!self._controls.hasOwnProperty('geolocate')) {
	  		self._controls.geolocate = new OpenLayers.Control.Geolocate({
	        bind: false,
	        geolocationOption: {
	          enableHighAccuracy: true,
	          maximumAge: 0,
	          timeout: 10000
	        }
	      });

	      self._controls.geolocate.events.register('locationuncapable', self, function() {
	      	callbackAlways();
	      	callbackFailed('The device does not support Geolocation.');
	      });

	  		self._controls.geolocate.events.register('locationfailed', self, function(e) {
	  			callbackAlways();
	  			if(e.hasOwnProperty('error')) {
	  				var message = 'PositionError (Code ' + e.error.code + ')\n\n';
	  				message += e.error.message;

	  				callbackFailed(message);
	  			} else {
		      	callbackFailed('Failed to get your position.');
	  			}
		    });

		    self._controls.geolocate.events.register('locationupdated', self._controls.geolocate, function(e) {
					callbackAlways();

					var lonlat = {
						lon: e.point.x,
						lat: e.point.y
					};

		      callbackSuccess(lonlat);
		    });

		    self._map.addControl(self._controls.geolocate);
	  		self._controls.geolocate.activate();
	  	}

	  	self._controls.geolocate.getCurrentLocation();
	  };

	  this.enableDragPoint = function(callback, opts) {
	  	var point = {};
	  	var defaultOpts = {};

	 		opts  = opts || {};
	  	OpenLayers.Util.applyDefaults(opts, defaultOpts);

	  	if(!self._controls.hasOwnProperty('dragPoint')) {
	  		self._controls.dragPoint = new OpenLayers.Control.DragFeature(self._layers.position, {
	  			hover: true,
	  			selectStyle: {
	  				cursor: 'pointer'
	  			},
	  			documentDrag: true
	  		});

	  		self._controls.dragPoint.onComplete = function(featurePoint, pxl) {
	  			point = {
	  				lon: featurePoint.geometry.x,
	  				lat: featurePoint.geometry.y
	  			};

	  			self._layers.position.addFeatures([featurePoint]);

	  			callback(point);
	  		};

	  		self._map.addControl(self._controls.dragPoint);
	  	}

	  	self._controls.dragPoint.activate();
	  };

	  this.disableDragPoint = function() {
	  	if(self._controls.hasOwnProperty('dragPoint')) {
	  		self._controls.dragPoint.deactivate();
	  		self._controls.selectPoint.activate();
	  	}
	  };

	  this.getCenter = function() {
	  	var center = self._map.getCenter();
	  	return {
	  		lon: center.lon,
	  		lat: center.lat
	  	};
	  };

		this.getActualZoom = function(callback) {
			self._map.events.register('zoomend', self._map, function(e) {
        var zoom = self._map.getZoom();
        callback(zoom);
      });
		};

	  this.clearLayer = function(layer) {
	  	if(self._layers.hasOwnProperty(layer)) {
	  		self._layers[layer].removeFeatures(self._layers[layer].features);
	  	}
	  };

		this.transform = function(lonlat, from, to) {
			var dest = new OpenLayers.LonLat(lonlat.lon, lonlat.lat);
			dest = dest.transform(from, to);
			return { lon: dest.lon, lat: dest.lat };
		};

		this.fixMapHeight = function() {
			var height = window.innerHeight;
			var element = self._map.div.id;

			if(element) {
				height -=  106;
				element = document.getElementById(element);
				element.style.height = height + 'px';
				self._map.updateSize();
			}
		};
	}

})(window.angular, OpenLayers);
<commit_msg>remove unused variables and added google to scope<commit_after>(function(angular, google, OpenLayers, undefined) {
	'use strict';

	/**
	 * Map Service
	 *
	 */
	angular
		.module('app')
		.service('Map', MapService);

	function MapService() {

		var self = this;

		/**
   	* setup
   	*/
	  function _setup(opts) {
	    OpenLayers.Util.applyDefaults(opts, {
	    });

	    self._map = new OpenLayers.Map(opts.id, {
	    	theme: null,
	    	projection: 'EPSG:4326',
	    	displayProjection: 'EPSG:4326'
	    });

	    self._startZoom  = opts.startZoom;
	    self._startLonlat = new OpenLayers.LonLat(opts.startLonlat.lon, opts.startLonlat.lat);

	    self._layers = [];
	    self._baselayers = [];
	    self._controls = [];

	    self.onSelectPoint = opts.onSelectPoint;

	    _setupLayers();
			_setupStyles();
	    _setupControls();
	  }

	  /**
	   * setBaseLayers method
	   */
	  function _setupLayers() {
	    self._baselayer = {
				OSM: 				   		 0,
				GOOGLE_MAP:    		 1,
				GOOGLE_MAP_NIGHT:  2,
				GOOGLE_MAP_HYBRID: 3
			};

			self._baselayers = [
				new OpenLayers.Layer.OSM('OpenStreetMap'),
				new OpenLayers.Layer.Google('Google Maps', {
					numZoomLevels: 19
				}),
				new OpenLayers.Layer.Google('Google Maps Night', {
					type: 'styled',
					numZoomLevels: 19
				}),
				new OpenLayers.Layer.Google('Google Maps Satellite', {
					numZoomLevels: 19,
					type: google.maps.MapTypeId.HYBRID
				})
			];

			self._layers = {
				position: new OpenLayers.Layer.Vector('Position', {
					styleMap: new OpenLayers.StyleMap({
						'default': {
							externalGraphic: "${icon}",
							graphicWidth: 40,
							cursor: 'pointer'
						}
					})
				})
			};

			self._map.addLayers(self._baselayers);
			for(var key in self._layers) {
				self._map.addLayer(self._layers[key]);
			}
	  }

	  function _setupStyles() {
	  	var styleNight = [{
				featureType: 'all',
				elementType: 'all',
					"stylers": [
			      { "invert_lightness": true },
			      { "visibility": "on" },
			      { "hue": "#00bbff" },
			      { "saturation": 1 }
			    ]
			}];
		 	var styledNightOptions = { name: 'Styled Map' };
		  var styledNightType = new google.maps.StyledMapType(styleNight, styledNightOptions);

			self._baselayers[self._baselayer.GOOGLE_MAP_NIGHT].mapObject.mapTypes.set('styled', styledNightType);
			self._baselayers[self._baselayer.GOOGLE_MAP_NIGHT].mapObject.setMapTypeId('styled');
	  }

	  function _setupControls() {
	    self._controls = {
	      zoom: new OpenLayers.Control.Zoom(),
	      nav: new OpenLayers.Control.Navigation({
          documentDrag: true,
          dragPanOptions: { enableKinetic: true }
        }),
        selectPoint: new OpenLayers.Control.SelectFeature([self._layers.position], {
        	autoActivate: true,
        	onSelect: self.onSelectPoint
        }),
	      mousePosition: new OpenLayers.Control.MousePosition()
	    };

	    for(var key in self._controls) {
	      self._map.addControl(self._controls[key]);
	    }
	  }

		this.init = function(opts) {
			_setup(opts);

			self.fixMapHeight();
			self.setCenterMap();
		};

	  this.setBaseLayer = function(index) {
	    self._map.setBaseLayer(self._map.layers[index]);
	  };

		this.getBaselayersList = function() {
			var arr = [];
			for (var key in self._baselayers) {
				arr.push(self._baselayers[key].name);
			}
			return arr;
		};

		this.setBaseLayer = function(index) {
			self._map.setBaseLayer(self._map.layers[index]);
		};

	  this.setCenterMap = function(point, zoom, opts) {
	  	opts = opts || {};

	  	if(point && !point.hasOwnProperty('CLASS_NAME') && point.CLASS_NAME !== 'OpenLayers.LonLat') {
	  		point = new OpenLayers.LonLat(point.lon, point.lat);
	  	}

	  	if(opts.hasOwnProperty('transformTo')) {
	  		point = point.transform(new OpenLayers.Projection(opts.transformTo), self._map.getProjection());
	  	}

	    self._map.setCenter(point || self._startLonlat, zoom || self._startZoom);
	  };

	  this.setZoom = function(zoom) {
	  	self._map.setCenter(null, zoom);
	  };

	  this.zoomIn = function() {
	  	self._map.zoomIn();
	  };

	  this.zoomOut = function() {
	  	self._map.zoomOut();
	  };

		this.addPoints = function(points, opts, callback) {
			var arrPontos = [];
			var defaultOpts = {
				layer: 'position',
				clearBefore: true,
			};
			opts = opts || {};

			OpenLayers.Util.applyDefaults(opts, defaultOpts);

			for(var key in points) {
				var label = points[key].hasOwnProperty('label') ? points[key].label : '';
				var pointOpts = {
					label: label,
					icon:  points[key].icon
				};

				var point = new OpenLayers.Geometry.Point(points[key].lon, points[key].lat);
				if (opts.hasOwnProperty('transformTo')) {
					point = point.transform(opts.transformTo, self._map.getProjection());
				}

				var feature = new OpenLayers.Feature.Vector(point, pointOpts);
				feature.data = points[key];

				arrPontos.push(feature);
			}

			if(opts.clearBefore) {
				self._layers[opts.layer].destroyFeatures();
			}

			self._layers[opts.layer].addFeatures(arrPontos);

			if(typeof(callback) === 'function') callback();
		};

		this.addPoint = function(point, opts, callback) {
			self.addPoints([point], opts, callback);
		};

		this.showPopup = function(lonlat, content, opts) {
			var popup = null;
			var defaultOpts = {
				clear: true,
				type: 'Point'
			};
			opts = opts || {};

			OpenLayers.Util.applyDefaults(opts, defaultOpts);

			popup = new OpenLayers.Popup('Popup ' + opts.type,
				new OpenLayers.LonLat(lonlat.lon, lonlat.lat),
				null,
				content,
				true
			);
			popup.opacity = '.9';

			if (opts.hasOwnProperty('clear') && opts.clear) {
				self.removePopups();
			}

			self._map.addPopup(popup);

			popup.fixPadding();
			popup.updateSize();
		};

		this.removePopups = function() {
			for(var key in self._map.popups) {
				self._map.removePopup(self._map.popups[key]);
			}
		};

	  this.getPosition = function(callbackSuccess, callbackFailed, callbackAlways) {
	  	if(!self._layers.hasOwnProperty('geolocate')) {
	  		self._layers.geolocate = new OpenLayers.Layer.Vector('Geolocate');
	      self._map.addLayer(self._layers.geolocate);
	  	}

	  	if (!self._controls.hasOwnProperty('geolocate')) {
	  		self._controls.geolocate = new OpenLayers.Control.Geolocate({
	        bind: false,
	        geolocationOption: {
	          enableHighAccuracy: true,
	          maximumAge: 0,
	          timeout: 10000
	        }
	      });

	      self._controls.geolocate.events.register('locationuncapable', self, function() {
	      	callbackAlways();
	      	callbackFailed('The device does not support Geolocation.');
	      });

	  		self._controls.geolocate.events.register('locationfailed', self, function(e) {
	  			callbackAlways();
	  			if(e.hasOwnProperty('error')) {
	  				var message = 'PositionError (Code ' + e.error.code + ')\n\n';
	  				message += e.error.message;

	  				callbackFailed(message);
	  			} else {
		      	callbackFailed('Failed to get your position.');
	  			}
		    });

		    self._controls.geolocate.events.register('locationupdated', self._controls.geolocate, function(e) {
					callbackAlways();

					var lonlat = {
						lon: e.point.x,
						lat: e.point.y
					};

		      callbackSuccess(lonlat);
		    });

		    self._map.addControl(self._controls.geolocate);
	  		self._controls.geolocate.activate();
	  	}

	  	self._controls.geolocate.getCurrentLocation();
	  };

	  this.enableDragPoint = function(callback, opts) {
	  	var point = {};
	  	var defaultOpts = {};

	 		opts  = opts || {};
	  	OpenLayers.Util.applyDefaults(opts, defaultOpts);

	  	if(!self._controls.hasOwnProperty('dragPoint')) {
	  		self._controls.dragPoint = new OpenLayers.Control.DragFeature(self._layers.position, {
	  			hover: true,
	  			selectStyle: {
	  				cursor: 'pointer'
	  			},
	  			documentDrag: true
	  		});

	  		self._controls.dragPoint.onComplete = function(featurePoint, pxl) {
	  			point = {
	  				lon: featurePoint.geometry.x,
	  				lat: featurePoint.geometry.y
	  			};

	  			self._layers.position.addFeatures([featurePoint]);

	  			callback(point);
	  		};

	  		self._map.addControl(self._controls.dragPoint);
	  	}

	  	self._controls.dragPoint.activate();
	  };

	  this.disableDragPoint = function() {
	  	if(self._controls.hasOwnProperty('dragPoint')) {
	  		self._controls.dragPoint.deactivate();
	  		self._controls.selectPoint.activate();
	  	}
	  };

	  this.getCenter = function() {
	  	var center = self._map.getCenter();
	  	return {
	  		lon: center.lon,
	  		lat: center.lat
	  	};
	  };

		this.getActualZoom = function(callback) {
			self._map.events.register('zoomend', self._map, function(e) {
        var zoom = self._map.getZoom();
        callback(zoom);
      });
		};

	  this.clearLayer = function(layer) {
	  	if(self._layers.hasOwnProperty(layer)) {
	  		self._layers[layer].removeFeatures(self._layers[layer].features);
	  	}
	  };

		this.transform = function(lonlat, from, to) {
			var dest = new OpenLayers.LonLat(lonlat.lon, lonlat.lat);
			dest = dest.transform(from, to);
			return { lon: dest.lon, lat: dest.lat };
		};

		this.fixMapHeight = function() {
			var height = window.innerHeight;
			var element = self._map.div.id;

			if(element) {
				height -=  106;
				element = document.getElementById(element);
				element.style.height = height + 'px';
				self._map.updateSize();
			}
		};
	}

})(window.angular, window.google, window.OpenLayers);
<|endoftext|>


<commit_before>const { Command, util } = require('discord.js-commando');
const stripIndents = require('common-tags').stripIndents;

const config = require('../../settings');
const Money = require('../../postgreSQL/models/Money');
const Redis = require('../../redis/Redis');

const redis = new Redis();

module.exports = class MoneyLeaderboardCommand extends Command {
	constructor(client) {
		super(client, {
			name: 'money-leaderboard',
			aliases: ['donut-leaderboard', 'donuts-leaderboard'],
			group: 'currency',
			memberName: 'leaderboard',
			description: 'Displays the money members have earned.',
			details: 'Display the amount of money members have earned in a leaderboard.',
			guildOnly: true,

			args: [
				{
					key: 'page',
					prompt: 'What page would you like to view?\n',
					type: 'integer',
					default: 1
				}
			]
		});
	}

	async run(msg, args) {
		const page = args.page;
		let ranking = 1;

		const money = await this.findCached();
		const paginated = util.paginate(JSON.parse(money), page, Math.floor(config.paginationItems));

		for (const user of paginated.items) await this.client.fetchUser(user.userID);

		return msg.embed({
			color: 3447003,
			description: stripIndents`
				__**Donut leaderboard, page ${paginated.page}**__

				${paginated.items.map(user => `**${ranking++} -** ${`${this.client.users.get(user.userID).username}#${this.client.users.get(user.userID).discriminator}`} (**${user.money}** 🍩)`).join('\n')}
				${paginated.maxPage > 1 ? `Use \`donut-leaderboard <page>\` to view a specific page.` : ''}
			`
		});
	}

	async findCached() {
		return redis.db.getAsync('moneyleaderboard').then(async reply => {
			if (reply) {
				return reply;
			} else {
				const money = await Money.findAll({ where: { userID: { $ne: 'SLOTMACHINE' } }, order: 'money DESC' });
				if (!money) return `No money biatch`;

				redis.db.setAsync('moneyleaderboard', JSON.stringify(money));
				redis.db.expire('moneyleaderboard', 3700);

				return JSON.stringify(money);
			}
		});
	}
};
<commit_msg>Fix ranking<commit_after>const { Command, util } = require('discord.js-commando');
const stripIndents = require('common-tags').stripIndents;

const config = require('../../settings');
const Money = require('../../postgreSQL/models/Money');
const Redis = require('../../redis/Redis');

const redis = new Redis();

module.exports = class MoneyLeaderboardCommand extends Command {
	constructor(client) {
		super(client, {
			name: 'money-leaderboard',
			aliases: ['donut-leaderboard', 'donuts-leaderboard'],
			group: 'currency',
			memberName: 'leaderboard',
			description: 'Displays the money members have earned.',
			details: 'Display the amount of money members have earned in a leaderboard.',
			guildOnly: true,

			args: [
				{
					key: 'page',
					prompt: 'What page would you like to view?\n',
					type: 'integer',
					default: 1
				}
			]
		});
	}

	async run(msg, args) {
		const page = args.page;
		let ranking = config.paginationItems * (page - 1);

		const money = await this.findCached();
		const paginated = util.paginate(JSON.parse(money), page, Math.floor(config.paginationItems));

		for (const user of paginated.items) await this.client.fetchUser(user.userID);

		return msg.embed({
			color: 3447003,
			description: stripIndents`
				__**Donut leaderboard, page ${paginated.page}**__

				${paginated.items.map(user => `**${++ranking} -** ${`${this.client.users.get(user.userID).username}#${this.client.users.get(user.userID).discriminator}`} (**${user.money}** 🍩)`).join('\n')}
			`,
			footer: { text: paginated.maxPage > 1 ? 'Use \'donut-leaderboard <page>\' to view a specific page.' : '' }
		});
	}

	async findCached() {
		return redis.db.getAsync('moneyleaderboard').then(async reply => {
			if (reply) {
				return reply;
			} else {
				const money = await Money.findAll({ where: { userID: { $ne: 'SLOTMACHINE' } }, order: 'money DESC' });
				if (!money) return `No money biatch`;

				redis.db.setAsync('moneyleaderboard', JSON.stringify(money));
				redis.db.expire('moneyleaderboard', 3700);

				return JSON.stringify(money);
			}
		});
	}
};
<|endoftext|>


<commit_before>import React from 'react';
import AuthService from '../services/auth';

class Logout extends React.Component {

    render() {
        return (
            <button onClick={this.props.logoutCallback}>Log Out</button>
        )
    }

}

class Login extends React.Component {

        loginCallback(err,data) {
            if (err) {
                console.log(err);
            } else {
                if (data.user) {
                    console.log(`logged in ${data}`);

                    // store refresh_token in local storage,
                    // everything else in the state
                    this.props.setUserData(data);

                } else {
                    console.log("Login failed");
                }
            }
        }

        handleSubmit(event) {
            event.preventDefault();
            const data = new FormData(event.nativeEvent.target);
            AuthService.login(data,this.loginCallback.bind(this));

        }

        render() {
            return (
                <form className="userForm" id="loginForm" onSubmit={this.handleSubmit.bind(this)}>
                    <label htmlFor="email">Email </label><input id="email" name="email" type="email" placeholder="email"/>
                    <label htmlFor="password">Password </label><input id="password" name="password" type="password"/>
                    <button type="submit">Log in</button>
                </form>
            )
        }
    }

    class RecoverPassword extends React.Component {

        recoverCallback() {

        }

        handleSubmit(event) {
            event.preventDefault();
            const data = new FormData(event.nativeEvent.target);
            AuthService.recover(data,this.recoverCallback.bind(this));

        }
        render() {
            return (
                <form className="userForm" id="recoverForm" onSubmit={this.handleSubmit.bind(this)}>
                    <label htmlFor="email">Email </label><input id="email" name="email" type="email" placeholder="email"/>
                    <button type="submit">Recover account</button>
                </form>
            )
        }
    }

    class Register extends React.Component {

        registerCallback(err,data) {
            if (err) {
                console.log(err);
            } else {
                if (data.user) {
                    this.props.setUserData(data);
                    console.log(`logged in ${data.user}`);
                } else {
                    console.log("error registering");
                }
            }
        }

        handleSubmit(event) {
            event.preventDefault();
            const data = new FormData(event.nativeEvent.target);
            for (var v of data) {
                console.log(v);
            }
            AuthService.register(data,this.registerCallback.bind(this));

        }

        render() {
            return (
                <form className="userForm" id="registerForm" onSubmit={this.handleSubmit.bind(this)}>
                    <label htmlFor="registerFirstName">First Name </label><input id="registerFirstName" name="first_name" type="text"/>
                    <label htmlFor="registerLastName">Last Name </label><input id="registerLastName" name="last_name" type="text"/>
                    <label htmlFor="registerEmail">Email </label><input id="registerEmail" name="email" type="email"/>
                    <label htmlFor="registerPassword">Password </label><input id="registerPassword" name="password" type="password"/>
                    <label htmlFor="registerPasswordConfirm">Confirm Password </label><input id="registerPasswordpasswordConfirm" name="passwordConfirm" type="password"/>
                    <button type="submit">Register</button>
                </form>
            )
        }
    }

    export { Login, Logout, RecoverPassword, Register }<commit_msg>login/register redirect on success<commit_after>import React from 'react';
import AuthService from '../services/auth';

import { withRouter } from 'react-router'

class Logout extends React.Component {

    render() {
        return (
            <button onClick={this.props.logoutCallback}>Log Out</button>
        )
    }

}

class Login extends React.Component {

        loginCallback(err,data) {
            if (err) {
                console.log(err);
            } else {
                if (data.user) {
                    console.log(`logged in ${data}`);

                    // store refresh_token in local storage,
                    // everything else in the state
                    this.props.setUserData(data);
                    this.props.history.push("/");

                } else {
                    console.log("Login failed");
                }
            }
        }

        handleSubmit(event) {
            event.preventDefault();
            const data = new FormData(event.nativeEvent.target);
            AuthService.login(data,this.loginCallback.bind(this));

        }

        render() {
            return (
                <form className="userForm" id="loginForm" onSubmit={this.handleSubmit.bind(this)}>
                    <label htmlFor="email">Email </label><input id="email" name="email" type="email" placeholder="email"/>
                    <label htmlFor="password">Password </label><input id="password" name="password" type="password"/>
                    <button type="submit">Log in</button>
                </form>
            )
        }
    }

    class RecoverPassword extends React.Component {

        recoverCallback() {

        }

        handleSubmit(event) {
            event.preventDefault();
            const data = new FormData(event.nativeEvent.target);
            AuthService.recover(data,this.recoverCallback.bind(this));

        }
        render() {
            return (
                <form className="userForm" id="recoverForm" onSubmit={this.handleSubmit.bind(this)}>
                    <label htmlFor="email">Email </label><input id="email" name="email" type="email" placeholder="email"/>
                    <button type="submit">Recover account</button>
                </form>
            )
        }
    }

    class Register extends React.Component {

        registerCallback(err,data) {
            if (err) {
                console.log(err);
            } else {
                if (data.user) {
                    this.props.setUserData(data);
                    console.log(`logged in ${data.user}`);
                    this.props.history.push("/");
                } else {
                    console.log("error registering");
                }
            }
        }

        handleSubmit(event) {
            event.preventDefault();
            const data = new FormData(event.nativeEvent.target);
            for (var v of data) {
                console.log(v);
            }
            AuthService.register(data,this.registerCallback.bind(this));

        }

        render() {
            return (
                <form className="userForm" id="registerForm" onSubmit={this.handleSubmit.bind(this)}>
                    <label htmlFor="registerFirstName">First Name </label><input id="registerFirstName" name="first_name" type="text"/>
                    <label htmlFor="registerLastName">Last Name </label><input id="registerLastName" name="last_name" type="text"/>
                    <label htmlFor="registerEmail">Email </label><input id="registerEmail" name="email" type="email"/>
                    <label htmlFor="registerPassword">Password </label><input id="registerPassword" name="password" type="password"/>
                    <label htmlFor="registerPasswordConfirm">Confirm Password </label><input id="registerPasswordpasswordConfirm" name="passwordConfirm" type="password"/>
                    <button type="submit">Register</button>
                </form>
            )
        }
    }

    Login = withRouter(Login);
    export { Login, Logout, RecoverPassword, Register }<|endoftext|>


<commit_before>import React from 'react';
import {NavLink} from 'fluxible-router';
import {connectToStores} from 'fluxible-addons-react';
import classNames from 'classnames';
import DeckTreeStore from '../../../stores/SlideViewStore';
import UserProfileStore from '../../../stores/UserProfileStore';
import PermissionsStore from '../../../stores/PermissionsStore';
import ContributorsPanel from '../ContentModulesPanel/ContributorsPanel/ContributorsPanel';
import ContributorsStore from '../../../stores/ContributorsStore';

class InfoPanel extends React.Component {

    render() {
        const rootNodeStyles = {
            fontSize: '1.06em'
        };
        const slideTitle= = SlideViewStore.title;

        return (

                        <NavLink style={rootNodeStyles} href={'/deck/' + rootNode.id}>{rootNodeTitle}</NavLink>

                            Info

                            Suggest

                            Edit

THis is the slide title

                                        {ContributorsPanel}

        );
    }
}

InfoPanel.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};
TreePanel = connectToStores(InfoPanel, [SlideViewStore, UserProfileStore, PermissionsStore], (context, props) => {
    return {
        SlideViewStore: context.getStore(SlideViewStore).getState(),
        UserProfileStore: context.getStore(UserProfileStore).getState(),
        PermissionsStore: context.getStore(PermissionsStore).getState()
    };
});
export default InfoPanel;
<commit_msg>Fix typo<commit_after>import React from 'react';
import {NavLink} from 'fluxible-router';
import {connectToStores} from 'fluxible-addons-react';
import classNames from 'classnames';
import DeckTreeStore from '../../../stores/SlideViewStore';
import UserProfileStore from '../../../stores/UserProfileStore';
import PermissionsStore from '../../../stores/PermissionsStore';
import ContributorsPanel from '../ContentModulesPanel/ContributorsPanel/ContributorsPanel';
import ContributorsStore from '../../../stores/ContributorsStore';

class InfoPanel extends React.Component {

    render() {
        const rootNodeStyles = {
            fontSize: '1.06em'
        };
        const slideTitle = SlideViewStore.title;

        return (

                        <NavLink style={rootNodeStyles} href={'/deck/' + rootNode.id}>{rootNodeTitle}</NavLink>

                            Info

                            Suggest

                            Edit

THis is the slide title

                                        {ContributorsPanel}

        );
    }
}

InfoPanel.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};
TreePanel = connectToStores(InfoPanel, [SlideViewStore, UserProfileStore, PermissionsStore], (context, props) => {
    return {
        SlideViewStore: context.getStore(SlideViewStore).getState(),
        UserProfileStore: context.getStore(UserProfileStore).getState(),
        PermissionsStore: context.getStore(PermissionsStore).getState()
    };
});
export default InfoPanel;
<|endoftext|>


<commit_before>import React from 'react'
import styled, { css } from 'styled-components'

import { Content, Title, Header } from './Layout'
import LiveEdit from './LiveEdit'
import CodeBlock from './CodeBlock'
import Code from './Code'
import Link from './Link'

const AlignCenter = styled.div`
  text-align: center;
`

const Badge = styled.img`
  margin-left: 0.5em;
  margin-right: 0.5em;
  margin-top: 0em;
  margin-bottom: 3em;
  height: 1.5em;
`

const ExampleButton = styled.button`
  border-radius: 3px;
  padding: 0.25em 1em;
  margin: 0 1em;
  background: transparent;
  color: palevioletred;
  border: 2px solid palevioletred;

  ${p => p.primary && css`
    background: palevioletred;
    color: white;
  `}
`

const FirstButton = styled.button``;

const SecondButton = styled.button`
  border-radius: 3px;
  padding: 0.25em 1em;
  background: transparent;
  color: palevioletred;
  border: 2px solid palevioletred;
`

const finishedButtonExample = `
const Button = styled.button\`
  border-radius: 3px;
  padding: 0.25em 1em;
  margin: 0 1em;
  background: transparent;
  color: palevioletred;
  border: 2px solid palevioletred;

  \${props => props.primary && css\`
    background: palevioletred;
    color: white;
  \`\}
\`

render(

    <Button>Normal Button</Button>
    <Button primary>Primary Button</Button>

)
`.trim()

const finishedStyling = `
const Button = styled.button\`
  border-radius: 3px;
  padding: 0.25em 1em;
  margin: 0 1em;
  background: transparent;
  color: palevioletred;
  border: 2px solid palevioletred;

  \${props => props.primary && css\`
    background: palevioletred;
    color: white;
  \`\}
\`
`.trim()

const importSc = `
import styled from 'styled-components';

const Button = styled.button\`\`;
`.trim()

const firstStyling = `
const Button = styled.button\`
  border-radius: 3px;
  padding: 0.25em 1em;
  margin: 0 1em;
  background: transparent;
  color: palevioletred;
  border: 2px solid palevioletred;
\`
`.trim()

const HomepageGettingStarted = () => (
  <Content>
    <AlignCenter>

        <Badge src="https://img.shields.io/github/stars/styled-components/styled-components.svg?style=social&label=Star&maxAge=3600" alt="Stars on GitHub" />

      	<Badge src="https://img.shields.io/npm/v/styled-components.svg" alt="Current version" />

      <Badge src="https://img.shields.io/npm/dm/styled-components.svg?maxAge=3600" alt="Monthly downloads" />
      <Badge src="http://img.badgesize.io/https://unpkg.com/styled-components/dist/styled-components.min.js?compression=gzip&label=gzip%20size" alt="Gzipped size" />
    </AlignCenter>
    <Title>Getting started</Title>
    Installation

To download styled-components run npm install --save styled-components. That's all you need to do, you are now ready to use it in your app! (yep, no build step needed 👌)

    Your first styled component

Let's say you want to create a simple and reusable <Button /> component that you can use throughout your application. There should be a normal version and a big and primary version for the important buttons. This is what it should look like when rendered: (this is a live example, click on them!)

    <AlignCenter>
      <ExampleButton onClick={() => { alert('You clicked the normal button!') }}>Normal button</ExampleButton>
      <ExampleButton primary onClick={() => { alert('You clicked the primary button!') }}>Primary button</ExampleButton>
    </AlignCenter>

First, let's import styled-components and create a styled.button:

    <CodeBlock language="jsx" code={importSc} />

This Button variable here is now a React component that you can use like any other React component! This unusual backtick syntax is a new JavaScript feature called a tagged template literal. You know how you can call functions with parenthesis? (myFunc()) Well, now you can also call functions with backticks! (myFunc``, <Link inline href="/docs/advanced#tagged-template-literals">here is an explanation</Link> of how that works exactly)

If you render our lovely component now (just like any other component: <Button />) this is what you get:

    <AlignCenter>
      <FirstButton>I'm a <Button />!</FirstButton>
    </AlignCenter>

It renders a button! That's not a very nice button though 😕 we can do better than this, let's give it a bit of styling and tickle out the hidden beauty within!

    <CodeBlock language="jsx" code={firstStyling} />
    <AlignCenter>
      <SecondButton>I'm a styled <Button /></SecondButton>
    </AlignCenter>

As you can see, styled-components let's you write actual CSS in your JavaScript. This means you can use all the features of CSS you use and love, including (but by far not limited to) media queries, all pseudo-selectors, nesting, etc. It also binds styles to components, which has some interesting properties. (learn more about <Link inline href="/docs/basics#motivation">the ideas behind styled-components here</Link>)

The last step is that we need to define what a primary button looks like. To do that we interpolate a function into our template literal, which gets passed the props of our component:

    <CodeBlock language="jsx" code={finishedStyling} />

All we're saying here is that when the primary property is set we want to add some more css to our component, in this case change the background and color.

That's all, we're done! Take a look at our finished component:

    <LiveEdit
      code={finishedButtonExample}
      noInline
    />

Nice 😍 That's a live updating editor too, so play around with it a bit to get a feel for what it's like to work with styled-components!

Once you're done take a look at the <Link href="/docs" inline prefetch>documentation</Link>, specifically the <Link href="/docs/basics#getting-started" inline prefetch>Getting started</Link> section! Enjoy ✨

  </Content>
)

export default HomepageGettingStarted
<commit_msg>Little grammar fix<commit_after>import React from 'react'
import styled, { css } from 'styled-components'

import { Content, Title, Header } from './Layout'
import LiveEdit from './LiveEdit'
import CodeBlock from './CodeBlock'
import Code from './Code'
import Link from './Link'

const AlignCenter = styled.div`
  text-align: center;
`

const Badge = styled.img`
  margin-left: 0.5em;
  margin-right: 0.5em;
  margin-top: 0em;
  margin-bottom: 3em;
  height: 1.5em;
`

const ExampleButton = styled.button`
  border-radius: 3px;
  padding: 0.25em 1em;
  margin: 0 1em;
  background: transparent;
  color: palevioletred;
  border: 2px solid palevioletred;

  ${p => p.primary && css`
    background: palevioletred;
    color: white;
  `}
`

const FirstButton = styled.button``;

const SecondButton = styled.button`
  border-radius: 3px;
  padding: 0.25em 1em;
  background: transparent;
  color: palevioletred;
  border: 2px solid palevioletred;
`

const finishedButtonExample = `
const Button = styled.button\`
  border-radius: 3px;
  padding: 0.25em 1em;
  margin: 0 1em;
  background: transparent;
  color: palevioletred;
  border: 2px solid palevioletred;

  \${props => props.primary && css\`
    background: palevioletred;
    color: white;
  \`\}
\`

render(

    <Button>Normal Button</Button>
    <Button primary>Primary Button</Button>

)
`.trim()

const finishedStyling = `
const Button = styled.button\`
  border-radius: 3px;
  padding: 0.25em 1em;
  margin: 0 1em;
  background: transparent;
  color: palevioletred;
  border: 2px solid palevioletred;

  \${props => props.primary && css\`
    background: palevioletred;
    color: white;
  \`\}
\`
`.trim()

const importSc = `
import styled from 'styled-components';

const Button = styled.button\`\`;
`.trim()

const firstStyling = `
const Button = styled.button\`
  border-radius: 3px;
  padding: 0.25em 1em;
  margin: 0 1em;
  background: transparent;
  color: palevioletred;
  border: 2px solid palevioletred;
\`
`.trim()

const HomepageGettingStarted = () => (
  <Content>
    <AlignCenter>

        <Badge src="https://img.shields.io/github/stars/styled-components/styled-components.svg?style=social&label=Star&maxAge=3600" alt="Stars on GitHub" />

      	<Badge src="https://img.shields.io/npm/v/styled-components.svg" alt="Current version" />

      <Badge src="https://img.shields.io/npm/dm/styled-components.svg?maxAge=3600" alt="Monthly downloads" />
      <Badge src="http://img.badgesize.io/https://unpkg.com/styled-components/dist/styled-components.min.js?compression=gzip&label=gzip%20size" alt="Gzipped size" />
    </AlignCenter>
    <Title>Getting started</Title>
    Installation

To download styled-components run npm install --save styled-components. That's all you need to do, you are now ready to use it in your app! (yep, no build step needed 👌)

    Your first styled component

Let's say you want to create a simple and reusable <Button /> component that you can use throughout your application. There should be a normal version and a big and primary version for the important buttons. This is what it should look like when rendered: (this is a live example, click on them!)

    <AlignCenter>
      <ExampleButton onClick={() => { alert('You clicked the normal button!') }}>Normal button</ExampleButton>
      <ExampleButton primary onClick={() => { alert('You clicked the primary button!') }}>Primary button</ExampleButton>
    </AlignCenter>

First, let's import styled-components and create a styled.button:

    <CodeBlock language="jsx" code={importSc} />

This Button variable here is now a React component that you can use like any other React component! This unusual backtick syntax is a new JavaScript feature called a tagged template literal. You know how you can call functions with parenthesis? (myFunc()) Well, now you can also call functions with backticks! (myFunc``, <Link inline href="/docs/advanced#tagged-template-literals">here is an explanation</Link> of how that works exactly)

If you render our lovely component now (just like any other component: <Button />) this is what you get:

    <AlignCenter>
      <FirstButton>I'm a <Button />!</FirstButton>
    </AlignCenter>

It renders a button! That's not a very nice button though 😕 we can do better than this, let's give it a bit of styling and tickle out the hidden beauty within!

    <CodeBlock language="jsx" code={firstStyling} />
    <AlignCenter>
      <SecondButton>I'm a styled <Button /></SecondButton>
    </AlignCenter>

As you can see, styled-components lets you write actual CSS in your JavaScript. This means you can use all the features of CSS you use and love, including (but by far not limited to) media queries, all pseudo-selectors, nesting, etc. It also binds styles to components, which has some interesting properties. (learn more about <Link inline href="/docs/basics#motivation">the ideas behind styled-components here</Link>)

The last step is that we need to define what a primary button looks like. To do that we interpolate a function into our template literal, which gets passed the props of our component:

    <CodeBlock language="jsx" code={finishedStyling} />

All we're saying here is that when the primary property is set we want to add some more css to our component, in this case change the background and color.

That's all, we're done! Take a look at our finished component:

    <LiveEdit
      code={finishedButtonExample}
      noInline
    />

Nice 😍 That's a live updating editor too, so play around with it a bit to get a feel for what it's like to work with styled-components!

Once you're done take a look at the <Link href="/docs" inline prefetch>documentation</Link>, specifically the <Link href="/docs/basics#getting-started" inline prefetch>Getting started</Link> section! Enjoy ✨

  </Content>
)

export default HomepageGettingStarted
<|endoftext|>


<commit_before>import demoTest from '../../../tests/shared/demoTest';

demoTest('tabs');
<commit_msg>:white_check_mark: Fix test fails in React 15<commit_after>import demoTest from '../../../tests/shared/demoTest';

demoTest('tabs',  { skip: process.env.REACT === '15' ? ['custom-tab-bar-node.md'] : [] });
<|endoftext|>