<commit_before>import '../scss/storefront.scss';
import 'jquery.cookie';
import React from 'react';
import ReactDOM from 'react-dom';
import SVGInjector from 'svg-injector-2';

import variantPickerStore from './stores/variantPicker';

import passwordIvisible from '../images/pass_invisible.svg';
import passwordVisible from '../images/pass_visible.svg';

import VariantPicker from './components/variantPicker/VariantPicker';
import VariantPrice from './components/variantPicker/VariantPrice';
import ProductSchema from './components/variantPicker/ProductSchema';

let csrftoken = $.cookie('csrftoken');

function csrfSafeMethod(method) {
  return /^(GET|HEAD|OPTIONS|TRACE)$/.test(method);
}

$.ajaxSetup({
  beforeSend: function (xhr, settings) {
    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
      xhr.setRequestHeader('X-CSRFToken', csrftoken);
    }
  }
});

new SVGInjector().inject(document.querySelectorAll('svg[data-src]'));

let getAjaxError = (response) => {
  let ajaxError = $.parseJSON(response.responseText).error.quantity;
  return ajaxError;
};

// Mobile menu

$(document).ready((e) => {
  let $toogleIcon = $('.navbar__brand__menu-toggle');
  let $mobileNav = $('nav');
  let windowWidth = $(window).width();

  if (windowWidth < 767) {
    $mobileNav.append('

');
    $('.navbar__login a').appendTo('.navbar__menu__login')
      .wrap('

')
      .addClass('nav-link');
  }

  $toogleIcon.click((e) => {
    $mobileNav.toggleClass('open');
    e.stopPropagation();
  });
  $(document).click((e) => {
    $mobileNav.removeClass('open');
  });
});

// Mobile search form

let $searchIcon = $('.mobile-search-icon');
let $closeSearchIcon = $('.mobile-close-search');
let $searchForm = $('.search-form');
$searchIcon.click((e) => {
  $searchForm.animate({left: 0}, {duration: 500});
});
$closeSearchIcon.click((e) => {
  $searchForm.animate({left: '-100vw'}, {duration: 500});
});

// Sticky footer

let navbarHeight = $('.navbar').outerHeight(true);
let footerHeight = $('.footer').outerHeight(true);
let windowHeight = $(window).height();
$('.maincontent').css('min-height', windowHeight - navbarHeight - footerHeight);

// New address dropdown

let $addressShow = $('.address_show label');
let $addressHide = $('.address_hide label');
let $addressForm = $('.checkout__new-address');
let $initialValue = $('#address_new_address').prop('checked');
$addressShow.click((e) => {
  $addressForm.slideDown('slow');
});
$addressHide.click((e) => {
  $addressForm.slideUp('slow');
});
if ($initialValue) {
  $addressForm.slideDown(0);
} else {
  $addressForm.slideUp(0);
}

// Smart address form

$(function () {
  const $i18nAddresses = $('.i18n-address');
  $i18nAddresses.each(function () {
    const $form = $(this).closest('form');
    const $countryField = $form.find('select[name=country]');
    const $previewField = $form.find('input.preview');
    $countryField.on('change', () => {
      $previewField.val('on');
      $form.submit();
    });
  });
});

// Sorter dropdown

$(document).ready((e) => {
  $('.sort-by button').on('click', (e) => {
    const t = $(e.currentTarget).parent();
    const l = t.find('.sort-list');
    if (l.hasClass('d-none')) {
      l.removeClass('d-none');
      t.find('.click-area').removeClass('d-none');
    } else {
      l.addClass('d-none');
      t.find('.click-area').addClass('d-none');
    }
  });
  $('.sort-by .click-area').on('click', (e) => {
    $('.sort-by .sort-list').addClass('d-none');
    $(e.currentTarget).addClass('d-none');
  });
});

// Mobile filters menu

$(document).ready((e) => {
  $('.filters-menu').on('click', (e) => {
    const t = $('.filters-menu__body');
    if (t.hasClass('d-none')) {
      t.removeClass('d-none');
    } else {
      t.addClass('d-none');
    }
  });
});

// Input Passwords

let $inputPassword = $('input[type=password]');
$("").insertAfter($inputPassword);
$inputPassword.parent().addClass('relative');
$('.passIcon').on('click', (e) => {
  let $input = $(e.target).parent().find('input');
  if ($input.attr('type') == 'password') {
    $input.attr('type', 'text');
    $(e.target).attr('src', passwordVisible);
  } else {
    $input.attr('type', 'password');
    $(e.target).attr('src', passwordIvisible);
  }
});

// Cart dropdown

let summaryLink = '/cart/summary/';
let $cartDropdown = $('.cart-dropdown');
let $cartIcon = $('.cart__icon');
let $addToCartError = $('.product__info__form-error small');

const onAddToCartSuccess = () => {
  $.get(summaryLink, (data) => {
    $cartDropdown.html(data);
    $addToCartError.html('');
    var newQunatity = $('.cart-dropdown__total').data('quantity');
    $('.badge').html(newQunatity).removeClass('empty');
    $cartDropdown.addClass('show');
    $cartIcon.addClass('hover');
    $cartDropdown.find('.cart-dropdown__list').scrollTop($cartDropdown.find('.cart-dropdown__list')[0].scrollHeight);
    setTimeout((e) => {
      $cartDropdown.removeClass('show');
      $cartIcon.removeClass('hover');
    }, 2500);
  });
};

const onAddToCartError = (response) => {
  $addToCartError.html(getAjaxError(response));
};

$.get(summaryLink, (data) => {
  $cartDropdown.html(data);
});
$('.navbar__brand__cart').hover((e) => {
  $cartDropdown.addClass('show');
  $cartIcon.addClass('hover');
}, (e) => {
  $cartDropdown.removeClass('show');
  $cartIcon.removeClass('hover');
});
$('.product-form button').click((e) => {
  e.preventDefault();
  let quantity = $('#id_quantity').val();
  let variant = $('#id_variant').val();
  $.ajax({
    url: $('.product-form').attr('action'),
    type: 'POST',
    data: {
      variant: variant,
      quantity: quantity
    },
    success: () => {
      onAddToCartSuccess();
    },
    error: (response) => {
      onAddToCartError(response);
    }
  });
});

// Delivery information

let $deliveryForm = $('.deliveryform');
let crsfToken = $deliveryForm.data('crsf');
let countrySelect = '#id_country';
let $cartSubtotal = $('.cart__subtotal');
let deliveryAjax = (e) => {
  let newCountry = $(countrySelect).val();
  $.ajax({
    url: '/cart/shipingoptions/',
    type: 'POST',
    data: {
      'csrfmiddlewaretoken': crsfToken,
      'country': newCountry
    },
    success: (data) => {
      $cartSubtotal.html(data);
    }
  });
};

$cartSubtotal.on('change', countrySelect, deliveryAjax);

// Open tab from the link

let hash = window.location.hash;
$('.nav-tabs a[href="' + hash + '"]').tab('show');

// Variant Picker

const variantPickerContainer = document.getElementById('variant-picker');
const variantPriceContainer = document.getElementById('variant-price-component');

if (variantPickerContainer) {
  const variantPickerData = JSON.parse(variantPickerContainer.dataset.variantPickerData);
  ReactDOM.render(
    <VariantPicker
      onAddToCartError={onAddToCartError}
      onAddToCartSuccess={onAddToCartSuccess}
      store={variantPickerStore}
      url={variantPickerContainer.dataset.action}
      variantAttributes={variantPickerData.variantAttributes}
      variants={variantPickerData.variants}
    />,
    variantPickerContainer
  );

  if (variantPriceContainer) {
    ReactDOM.render(
      <VariantPrice
        availability={variantPickerData.availability}
        store={variantPickerStore}
      />,
      variantPriceContainer
    );
  }
}

// Product Schema
const productSchemaContainer = document.getElementById('product-schema-component');
if (productSchemaContainer) {
  let productSchema = JSON.parse(document.getElementById('product-schema-component').children[0].text);
  ReactDOM.render(
    <ProductSchema
      variantStore={variantPickerStore}
      productSchema={productSchema}
    />,
    productSchemaContainer
  );
}

// Account delete address bar

let $deleteAdressIcons = $('.icons');
let $deleteAdressIcon = $('.delete-icon');
let $deleteAddress = $('.address-delete');

$deleteAdressIcon.on('click', (e) => {
  if ($deleteAddress.hasClass('none')) {
    $deleteAddress.removeClass('none');
    $deleteAdressIcons.addClass('none');
  } else {
    $deleteAddress.addClass('none');
  }
});

$deleteAddress.find('.cancel').on('click', (e) => {
  $deleteAddress.addClass('none');
  $deleteAdressIcons.removeClass('none');
});

// Cart quantity form

let $cartLine = $('.cart__line');
let $total = $('.cart-subtotal');
let $cartBadge = $('.navbar__brand__cart .badge');
let $removeProductSucces = $('.remove-product-alert');
let $closeMsg = $('.close-msg');
$cartLine.each(function () {
  let $quantityInput = $(this).find('#id_quantity');
  let cartFormUrl = $(this).find('.form-cart').attr('action');
  let $qunatityError = $(this).find('.cart__line__quantity-error');
  let $subtotal = $(this).find('.cart-item-price p');
  let $deleteIcon = $(this).find('.cart-item-delete');
  $(this).on('change', $quantityInput, (e) => {
    let newQuantity = $quantityInput.val();
    $.ajax({
      url: cartFormUrl,
      method: 'POST',
      data: {quantity: newQuantity},
      success: (response) => {
        if (newQuantity == 0) {
          if (response.cart.numLines == 0) {
            $.cookie('alert', 'true', {path: '/cart'});
            location.reload();
          } else {
            $removeProductSucces.removeClass('hidden-xs-up');
            $(this).fadeOut();
          }
        } else {
          $subtotal.html(response.subtotal);
        }
        $cartBadge.html(response.cart.numItems);
        $qunatityError.html('');
        $cartDropdown.load(summaryLink);
        deliveryAjax();
      },
      error: (response) => {
        $qunatityError.html(getAjaxError(response));
      }
    });
  });
  $deleteIcon.on('click', (e) => {
    $.ajax({
      url: cartFormUrl,
      method: 'POST',
      data: {quantity: 0},
      success: (response) => {
        if (response.cart.numLines >= 1) {
          $(this).fadeOut();
          $total.html(response.total);
          $cartBadge.html(response.cart.numItems);
          $cartDropdown.load(summaryLink);
          $removeProductSucces.removeClass('hidden-xs-up');
        } else {
          $.cookie('alert', 'true', {path: '/cart'});
          location.reload();
        }
        deliveryAjax();
      }
    });
  });
});

// StyleGuide fixed menu

$(document).ready(function () {
  let styleGuideMenu = $('.styleguide__nav');
  $(window).scroll(function () {
    if ($(this).scrollTop() > 100) {
      styleGuideMenu.addClass("fixed");
    } else {
      styleGuideMenu.removeClass("fixed");
    }
  });
});

if ($.cookie('alert') === 'true') {
  $removeProductSucces.removeClass('hidden-xs-up');
  $.cookie('alert', 'false', {path: '/cart'});
}

$closeMsg.on('click', (e) => {
  $removeProductSucces.addClass('hidden-xs-up');
});

$('.toggle-filter').each(function () {
  let icon = $(this).find('.collapse-filters-icon');
  let ele = $(this).find('.filter-form-field');

  let filterArrowDown = $('.product-filters__attributes').data('icon-down');
  let filterArrowUp = $('.product-filters__attributes').data('icon-up');

  $(this).find('.filter-label').on('click', () => {
    if (ele.css('display') == 'block') {
      ele.css('display', 'none');
      icon.find('img').attr('src', filterArrowDown);
    } else {
      ele.css('display', 'block');
      icon.find('img').attr('src', filterArrowUp);
    }
  });
});
<commit_msg>Fix filter visual bug<commit_after>import '../scss/storefront.scss';
import 'jquery.cookie';
import React from 'react';
import ReactDOM from 'react-dom';
import SVGInjector from 'svg-injector-2';

import variantPickerStore from './stores/variantPicker';

import passwordIvisible from '../images/pass_invisible.svg';
import passwordVisible from '../images/pass_visible.svg';

import VariantPicker from './components/variantPicker/VariantPicker';
import VariantPrice from './components/variantPicker/VariantPrice';
import ProductSchema from './components/variantPicker/ProductSchema';

let csrftoken = $.cookie('csrftoken');

function csrfSafeMethod(method) {
  return /^(GET|HEAD|OPTIONS|TRACE)$/.test(method);
}

$.ajaxSetup({
  beforeSend: function (xhr, settings) {
    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
      xhr.setRequestHeader('X-CSRFToken', csrftoken);
    }
  }
});

new SVGInjector().inject(document.querySelectorAll('svg[data-src]'));

let getAjaxError = (response) => {
  let ajaxError = $.parseJSON(response.responseText).error.quantity;
  return ajaxError;
};

// Mobile menu

$(document).ready((e) => {
  let $toogleIcon = $('.navbar__brand__menu-toggle');
  let $mobileNav = $('nav');
  let windowWidth = $(window).width();

  if (windowWidth < 767) {
    $mobileNav.append('

');
    $('.navbar__login a').appendTo('.navbar__menu__login')
      .wrap('

')
      .addClass('nav-link');
  }

  $toogleIcon.click((e) => {
    $mobileNav.toggleClass('open');
    e.stopPropagation();
  });
  $(document).click((e) => {
    $mobileNav.removeClass('open');
  });
});

// Mobile search form

let $searchIcon = $('.mobile-search-icon');
let $closeSearchIcon = $('.mobile-close-search');
let $searchForm = $('.search-form');
$searchIcon.click((e) => {
  $searchForm.animate({left: 0}, {duration: 500});
});
$closeSearchIcon.click((e) => {
  $searchForm.animate({left: '-100vw'}, {duration: 500});
});

// Sticky footer

let navbarHeight = $('.navbar').outerHeight(true);
let footerHeight = $('.footer').outerHeight(true);
let windowHeight = $(window).height();
$('.maincontent').css('min-height', windowHeight - navbarHeight - footerHeight);

// New address dropdown

let $addressShow = $('.address_show label');
let $addressHide = $('.address_hide label');
let $addressForm = $('.checkout__new-address');
let $initialValue = $('#address_new_address').prop('checked');
$addressShow.click((e) => {
  $addressForm.slideDown('slow');
});
$addressHide.click((e) => {
  $addressForm.slideUp('slow');
});
if ($initialValue) {
  $addressForm.slideDown(0);
} else {
  $addressForm.slideUp(0);
}

// Smart address form

$(function () {
  const $i18nAddresses = $('.i18n-address');
  $i18nAddresses.each(function () {
    const $form = $(this).closest('form');
    const $countryField = $form.find('select[name=country]');
    const $previewField = $form.find('input.preview');
    $countryField.on('change', () => {
      $previewField.val('on');
      $form.submit();
    });
  });
});

// Sorter dropdown

$(document).ready((e) => {
  $('.sort-by button').on('click', (e) => {
    const t = $(e.currentTarget).parent();
    const l = t.find('.sort-list');
    if (l.hasClass('d-none')) {
      l.removeClass('d-none');
      t.find('.click-area').removeClass('d-none');
    } else {
      l.addClass('d-none');
      t.find('.click-area').addClass('d-none');
    }
  });
  $('.sort-by .click-area').on('click', (e) => {
    $('.sort-by .sort-list').addClass('d-none');
    $(e.currentTarget).addClass('d-none');
  });
});

// Mobile filters menu

$(document).ready((e) => {
  $('.filters-menu').on('click', (e) => {
    const t = $('.filters-menu__body');
    if (t.hasClass('d-none')) {
      t.removeClass('d-none');
    } else {
      t.addClass('d-none');
    }
  });
});

// Input Passwords

let $inputPassword = $('input[type=password]');
$("").insertAfter($inputPassword);
$inputPassword.parent().addClass('relative');
$('.passIcon').on('click', (e) => {
  let $input = $(e.target).parent().find('input');
  if ($input.attr('type') == 'password') {
    $input.attr('type', 'text');
    $(e.target).attr('src', passwordVisible);
  } else {
    $input.attr('type', 'password');
    $(e.target).attr('src', passwordIvisible);
  }
});

// Cart dropdown

let summaryLink = '/cart/summary/';
let $cartDropdown = $('.cart-dropdown');
let $cartIcon = $('.cart__icon');
let $addToCartError = $('.product__info__form-error small');

const onAddToCartSuccess = () => {
  $.get(summaryLink, (data) => {
    $cartDropdown.html(data);
    $addToCartError.html('');
    var newQunatity = $('.cart-dropdown__total').data('quantity');
    $('.badge').html(newQunatity).removeClass('empty');
    $cartDropdown.addClass('show');
    $cartIcon.addClass('hover');
    $cartDropdown.find('.cart-dropdown__list').scrollTop($cartDropdown.find('.cart-dropdown__list')[0].scrollHeight);
    setTimeout((e) => {
      $cartDropdown.removeClass('show');
      $cartIcon.removeClass('hover');
    }, 2500);
  });
};

const onAddToCartError = (response) => {
  $addToCartError.html(getAjaxError(response));
};

$.get(summaryLink, (data) => {
  $cartDropdown.html(data);
});
$('.navbar__brand__cart').hover((e) => {
  $cartDropdown.addClass('show');
  $cartIcon.addClass('hover');
}, (e) => {
  $cartDropdown.removeClass('show');
  $cartIcon.removeClass('hover');
});
$('.product-form button').click((e) => {
  e.preventDefault();
  let quantity = $('#id_quantity').val();
  let variant = $('#id_variant').val();
  $.ajax({
    url: $('.product-form').attr('action'),
    type: 'POST',
    data: {
      variant: variant,
      quantity: quantity
    },
    success: () => {
      onAddToCartSuccess();
    },
    error: (response) => {
      onAddToCartError(response);
    }
  });
});

// Delivery information

let $deliveryForm = $('.deliveryform');
let crsfToken = $deliveryForm.data('crsf');
let countrySelect = '#id_country';
let $cartSubtotal = $('.cart__subtotal');
let deliveryAjax = (e) => {
  let newCountry = $(countrySelect).val();
  $.ajax({
    url: '/cart/shipingoptions/',
    type: 'POST',
    data: {
      'csrfmiddlewaretoken': crsfToken,
      'country': newCountry
    },
    success: (data) => {
      $cartSubtotal.html(data);
    }
  });
};

$cartSubtotal.on('change', countrySelect, deliveryAjax);

// Open tab from the link

let hash = window.location.hash;
$('.nav-tabs a[href="' + hash + '"]').tab('show');

// Variant Picker

const variantPickerContainer = document.getElementById('variant-picker');
const variantPriceContainer = document.getElementById('variant-price-component');

if (variantPickerContainer) {
  const variantPickerData = JSON.parse(variantPickerContainer.dataset.variantPickerData);
  ReactDOM.render(
    <VariantPicker
      onAddToCartError={onAddToCartError}
      onAddToCartSuccess={onAddToCartSuccess}
      store={variantPickerStore}
      url={variantPickerContainer.dataset.action}
      variantAttributes={variantPickerData.variantAttributes}
      variants={variantPickerData.variants}
    />,
    variantPickerContainer
  );

  if (variantPriceContainer) {
    ReactDOM.render(
      <VariantPrice
        availability={variantPickerData.availability}
        store={variantPickerStore}
      />,
      variantPriceContainer
    );
  }
}

// Product Schema
const productSchemaContainer = document.getElementById('product-schema-component');
if (productSchemaContainer) {
  let productSchema = JSON.parse(document.getElementById('product-schema-component').children[0].text);
  ReactDOM.render(
    <ProductSchema
      variantStore={variantPickerStore}
      productSchema={productSchema}
    />,
    productSchemaContainer
  );
}

// Account delete address bar

let $deleteAdressIcons = $('.icons');
let $deleteAdressIcon = $('.delete-icon');
let $deleteAddress = $('.address-delete');

$deleteAdressIcon.on('click', (e) => {
  if ($deleteAddress.hasClass('none')) {
    $deleteAddress.removeClass('none');
    $deleteAdressIcons.addClass('none');
  } else {
    $deleteAddress.addClass('none');
  }
});

$deleteAddress.find('.cancel').on('click', (e) => {
  $deleteAddress.addClass('none');
  $deleteAdressIcons.removeClass('none');
});

// Cart quantity form

let $cartLine = $('.cart__line');
let $total = $('.cart-subtotal');
let $cartBadge = $('.navbar__brand__cart .badge');
let $removeProductSucces = $('.remove-product-alert');
let $closeMsg = $('.close-msg');
$cartLine.each(function () {
  let $quantityInput = $(this).find('#id_quantity');
  let cartFormUrl = $(this).find('.form-cart').attr('action');
  let $qunatityError = $(this).find('.cart__line__quantity-error');
  let $subtotal = $(this).find('.cart-item-price p');
  let $deleteIcon = $(this).find('.cart-item-delete');
  $(this).on('change', $quantityInput, (e) => {
    let newQuantity = $quantityInput.val();
    $.ajax({
      url: cartFormUrl,
      method: 'POST',
      data: {quantity: newQuantity},
      success: (response) => {
        if (newQuantity == 0) {
          if (response.cart.numLines == 0) {
            $.cookie('alert', 'true', {path: '/cart'});
            location.reload();
          } else {
            $removeProductSucces.removeClass('hidden-xs-up');
            $(this).fadeOut();
          }
        } else {
          $subtotal.html(response.subtotal);
        }
        $cartBadge.html(response.cart.numItems);
        $qunatityError.html('');
        $cartDropdown.load(summaryLink);
        deliveryAjax();
      },
      error: (response) => {
        $qunatityError.html(getAjaxError(response));
      }
    });
  });
  $deleteIcon.on('click', (e) => {
    $.ajax({
      url: cartFormUrl,
      method: 'POST',
      data: {quantity: 0},
      success: (response) => {
        if (response.cart.numLines >= 1) {
          $(this).fadeOut();
          $total.html(response.total);
          $cartBadge.html(response.cart.numItems);
          $cartDropdown.load(summaryLink);
          $removeProductSucces.removeClass('hidden-xs-up');
        } else {
          $.cookie('alert', 'true', {path: '/cart'});
          location.reload();
        }
        deliveryAjax();
      }
    });
  });
});

// StyleGuide fixed menu

$(document).ready(function () {
  let styleGuideMenu = $('.styleguide__nav');
  $(window).scroll(function () {
    if ($(this).scrollTop() > 100) {
      styleGuideMenu.addClass("fixed");
    } else {
      styleGuideMenu.removeClass("fixed");
    }
  });
});

if ($.cookie('alert') === 'true') {
  $removeProductSucces.removeClass('hidden-xs-up');
  $.cookie('alert', 'false', {path: '/cart'});
}

$closeMsg.on('click', (e) => {
  $removeProductSucces.addClass('hidden-xs-up');
});

$('.toggle-filter').each(function () {
  let icon = $(this).find('.collapse-filters-icon');
  let ele = $(this).find('.filter-form-field');

  let filterArrowDown = $('.product-filters__attributes').data('icon-down');
  let filterArrowUp = $('.product-filters__attributes').data('icon-up');

  ele.attr('aria-expanded', '');

  $(this).find('.filter-label').on('click', () => {
    if (ele.attr('aria-expanded') !== undefined) {
      ele.removeAttr('aria-expanded').find('input[type="checkbox"]').each((i, el) => {
        if (!el.checked) {
          $(el.parentNode.parentNode).addClass('d-none');
        }
      });
      icon.find('img').attr('src', filterArrowDown);
    } else {
      ele.attr('aria-expanded', '').find('input[type="checkbox"]').each((i, el) => {
        $(el.parentNode.parentNode).removeClass('d-none');
      });
      icon.find('img').attr('src', filterArrowUp);
    }
  });
});
<|endoftext|>


<commit_before>app.factory('DataFactory', ['$firebaseAuth', '$http', function ($firebaseAuth, $http) {
  console.log('data factory loaded');
  var eventList = { list: [] };
  var auth = $firebaseAuth();
  var users = { list: [] };
  var currentUser = {};
  // var self = this;
  // self.newUser = {};
  // console.log(dateList);

  auth.$onAuthStateChanged(getUsers);
  auth.$onAuthStateChanged(getEvents);
  //
  //
  function getUsers() {
    var firebaseUser = auth.$getAuth();
    // firebaseUser will be null if not logged in
    if (firebaseUser) {
      // This is where we make our call to our server
      firebaseUser.getToken().then(function (idToken) {
        $http({
          method: 'GET',
          url: '/privateData',
          headers: {
            id_token: idToken
          }
        }).then(function (response) {
          console.log(response.data);
          users.list = response.data;
        });
      });
    } else {
      console.log('Not logged in or not authorized.');
      self.secretData = "Log in to search for volunteer activities.";
    }
  }

  // Get events for calendar
  function getEvents() {
    var firebaseUser = auth.$getAuth();
    // firebaseUser will be null if not logged in
    if (firebaseUser) {
      // This is where we make our call to our server
      firebaseUser.getToken().then(function (idToken) {
        $http({
          method: 'GET',
          url: '/privateData/events',
          headers: {
            id_token: idToken
          }
        }).then(function (response) {
          console.log(response.data);
          response.data.forEach(function(event){
            eventList.list.push({
              title: event.role_title,
              start: new Date('2017-04-13T15:36:07+00:00'),
              id: event.id
              // end: new Date(y, m, 29),
            });
            console.log(eventList.list);
          });
        });
      });
    } else {
      console.log('Not logged in or not authorized.');
      self.secretData = "Log in to search for volunteer activities.";
    }
  }//end Get events

//add role to user post
  function volunteerSignUp(userRoleId) {
    console.log('factory userRoleId', userRoleId);
    var firebaseUser = auth.$getAuth();
    // firebaseUser will be null if not logged in
    if (firebaseUser) {
      // This is where we make our call to our server
      firebaseUser.getToken().then(function (idToken) {
        $http({
          method: 'POST',
          url: '/privateData/volunteerSignUp',
          headers: { id_token: idToken },
          data: {
            role_id: userRoleId,
            // user_id: firebaseUser.email //NEED user id to associate role with -- firebase?
            user_id: 1
          }
        }).then(function (response) {
          console.log(response);
          console.log('firebase', firebaseUser);
        });
      });
    } else {
      console.log('no firebase user');
    }
  }//End volunteerSignUp

//User registration
  function addUser(newUser) {
    console.log('factory user', newUser);
    var firebaseUser = auth.$getAuth();
    // firebaseUser will be null if not logged in
    if (firebaseUser) {
      // This is where we make our call to our server
      firebaseUser.getToken().then(function (idToken) {
        $http({
          method: 'POST',
          url: '/privateData',
          headers: { id_token: idToken },
          data: newUser
        }).then(function (response) {
          console.log(response);
          self.newUser = {};
        });
      });
    } else {
      console.log('no firebase user');
    }
  } // ends addUser function

  return {
    eventList: eventList,
    getEvents: getEvents,
    addUser: addUser,
    getUsers: getUsers,
    users: users,
    volunteerSignUp: volunteerSignUp
  };

}]);
<commit_msg>currentuser object in data.factory<commit_after>app.factory('DataFactory', ['$firebaseAuth', '$http', function ($firebaseAuth, $http) {
  console.log('data factory loaded');
  var eventList = { list: [] };
  var auth = $firebaseAuth();
  var users = { list: [] };
  var currentUser = {};
  // var self = this;
  // self.newUser = {};
  // console.log(dateList);

  auth.$onAuthStateChanged(getUsers);
  auth.$onAuthStateChanged(getEvents);
  //
  //
  function getUsers() {
    var firebaseUser = auth.$getAuth();
    // firebaseUser will be null if not logged in
    if (firebaseUser) {
      // This is where we make our call to our server
      firebaseUser.getToken().then(function (idToken) {
        $http({
          method: 'GET',
          url: '/privateData',
          headers: {
            id_token: idToken
          }
        }).then(function (response) {
          console.log(response.data);
          users.list = response.data;
        });
      });
    } else {
      console.log('Not logged in or not authorized.');
      self.secretData = "Log in to search for volunteer activities.";
    }
  }

  // Get events for calendar
  function getEvents() {
    var firebaseUser = auth.$getAuth();
    // firebaseUser will be null if not logged in
    if (firebaseUser) {
      // This is where we make our call to our server
      firebaseUser.getToken().then(function (idToken) {
        $http({
          method: 'GET',
          url: '/privateData/events',
          headers: {
            id_token: idToken
          }
        }).then(function (response) {
          console.log(response.data);
          response.data.forEach(function(event){
            eventList.list.push({
              title: event.role_title,
              start: new Date('2017-04-13T15:36:07+00:00'),
              id: event.id
              // end: new Date(y, m, 29),
            });
            console.log(eventList.list);
          });
        });
      });
    } else {
      console.log('Not logged in or not authorized.');
      self.secretData = "Log in to search for volunteer activities.";
    }
  }//end Get events

//add role to user post
  function volunteerSignUp(userRoleId) {
    console.log('factory userRoleId', userRoleId);
    var firebaseUser = auth.$getAuth();
    // firebaseUser will be null if not logged in
    if (firebaseUser) {
      // This is where we make our call to our server
      firebaseUser.getToken().then(function (idToken) {
        $http({
          method: 'POST',
          url: '/privateData/volunteerSignUp',
          headers: { id_token: idToken },
          data: {
            role_id: userRoleId,
            // user_id: firebaseUser.email //NEED user id to associate role with -- firebase?
            user_id: 1
          }
        }).then(function (response) {
          console.log(response);
          console.log('firebase', firebaseUser);
        });
      });
    } else {
      console.log('no firebase user');
    }
  }//End volunteerSignUp

//User registration
  function addUser(newUser) {
    console.log('factory user', newUser);
    var firebaseUser = auth.$getAuth();
    // firebaseUser will be null if not logged in
    if (firebaseUser) {
      // This is where we make our call to our server
      firebaseUser.getToken().then(function (idToken) {
        $http({
          method: 'POST',
          url: '/privateData',
          headers: { id_token: idToken },
          data: newUser
        }).then(function (response) {
          console.log(response);
          self.newUser = {};
        });
      });
    } else {
      console.log('no firebase user');
    }
  } // ends addUser function

  return {
    eventList: eventList,
    getEvents: getEvents,
    addUser: addUser,
    getUsers: getUsers,
    users: users,
    volunteerSignUp: volunteerSignUp,
    currentUser: currentUser
  };

}]);
<|endoftext|>


<commit_before>#!/usr/bin/env node
var program = require('commander')

program
  .version('0.0.1')
  .command('init [filename]', 'initialise file with template')
  .command('plan [filename]', 'plan the microservice')
  .command('publish [filename]', 'publish the microservice')
  .command('login', 'login and save the credentials')
  .parse(process.argv)

if (!program.args.length) {
  program.help()
}
<commit_msg>remove unused code<commit_after>#!/usr/bin/env node
var program = require('commander')

program
  .version('0.0.1')
  .command('init [filename]', 'initialise file with template')
  .command('publish [filename]', 'publish the microservice')
  .command('login', 'login and save the credentials')
  .parse(process.argv)

if (!program.args.length) {
  program.help()
}
<|endoftext|>


<commit_before>var Camera = {
    x: 0,
    y: 0,

    applyX: 0,
    applyY: 0,

    yLocked: false,
    xLocked: false,

    translateX: function(x) {
        return x + this.applyX;
    },

    translateY: function(y) {
        return y + this.applyY;
    },

    translate: function(x, y) {
        return {
            x: this.translateX(x),
            y: this.translateY(y)
        };
    },

    setPos: function(x, y) {
        this.x = x;
        this.y = y;
    },

    trackingEntity: null,

    centerToMap: function() {
        this.x = Canvas.canvas.width / 2 - Game.map.widthPx / 2;
        this.y = Canvas.canvas.height / 2 - Game.map.heightPx / 2;
        this.xLocked = (Canvas.canvas.width > Game.map.widthPx);
        this.yLocked = (Canvas.canvas.height > Game.map.heightPx);
        this.trackingEntity = null;
    },

    followEntity: function(e) {
        this.trackingEntity = e;
    },

    update: function() {
        if (this.trackingEntity != null) {
            if (!this.xLocked) {
                var desiredX = Canvas.canvas.width / 2 - this.trackingEntity.posX - this.trackingEntity.width / 2;
                var maxXSpace = Game.map.widthPx - Canvas.canvas.width;
                this.x = MathHelper.clamp(desiredX, -maxXSpace, 0);
            }

            if (!this.yLocked) {
                var desiredY = Canvas.canvas.height / 2 - this.trackingEntity.posY - this.trackingEntity.height / 2;
                var maxYSpace = Game.map.heightPx - Canvas.canvas.height;
                this.y = MathHelper.clamp(desiredY, -maxYSpace, 0);
            }
        }

        this.applyX = MathHelper.lerp(this.applyX, this.x, 0.1);
        this.applyY = MathHelper.lerp(this.applyY, this.y, 0.1);
    }
};<commit_msg>Camera: Round off translations to prevent "fuzzing" and leaking<commit_after>var Camera = {
    x: 0,
    y: 0,

    applyX: 0,
    applyY: 0,

    yLocked: false,
    xLocked: false,

    translateX: function(x) {
        return Math.round(x + this.applyX);
    },

    translateY: function(y) {
        return Math.round(y + this.applyY);
    },

    translate: function(x, y) {
        return {
            x: this.translateX(x),
            y: this.translateY(y)
        };
    },

    setPos: function(x, y) {
        this.x = x;
        this.y = y;
    },

    trackingEntity: null,

    centerToMap: function() {
        this.x = Canvas.canvas.width / 2 - Game.map.widthPx / 2;
        this.y = Canvas.canvas.height / 2 - Game.map.heightPx / 2;
        this.xLocked = (Canvas.canvas.width > Game.map.widthPx);
        this.yLocked = (Canvas.canvas.height > Game.map.heightPx);
        this.trackingEntity = null;
    },

    followEntity: function(e) {
        this.trackingEntity = e;
    },

    update: function() {
        if (this.trackingEntity != null) {
            if (!this.xLocked) {
                var desiredX = Canvas.canvas.width / 2 - this.trackingEntity.posX - this.trackingEntity.width / 2;
                var maxXSpace = Game.map.widthPx - Canvas.canvas.width;
                this.x = MathHelper.clamp(desiredX, -maxXSpace, 0);
            }

            if (!this.yLocked) {
                var desiredY = Canvas.canvas.height / 2 - this.trackingEntity.posY - this.trackingEntity.height / 2;
                var maxYSpace = Game.map.heightPx - Canvas.canvas.height;
                this.y = MathHelper.clamp(desiredY, -maxYSpace, 0);
            }
        }

        this.applyX = MathHelper.lerp(this.applyX, this.x, 0.1);
        this.applyY = MathHelper.lerp(this.applyY, this.y, 0.1);
    }
};<|endoftext|>


<commit_before>/**
 * An object which labels a dish name as low, average, or high-calorie.
 */
class CalorieLabeller {
  /**
   * Creates a CalorieLabeller object.
   * @constructor
   * @param {Map<string, number>} tokenizer A mapping from dish name tokens to
   * unique integers
   * @param {tf.LayersModel} model Tensorflow.js layers ML model
   */
  constructor(tokenizer, model) {
    /** @private @const @type {Map<string, number>} */
    this.tokenizer_ = tokenizer;
    /** @private @const @type {tf.LayersModel} */
    this.model_ = model;
  }

  /**
   * Labels a single dish as high or low calorie.
   * @param {string} dishName The name of the dish to label
   * @return {CalorieLabel} The calorie label for the dish named dishName
   */
  label(dishName) {
    // Step 1: remove special characters from dish name
    dishName = AmaranthUtil.removeSpecialCharacters(dishName);

    // Step 2: convert dish name to lower case
    dishName = dishName.toLowerCase();

    // Step 3: split dish name on spaces
    const splitDishName = dishName.split(/\s+/);

    // Step 4: tokenize dish names
    const tokenizedDishName = splitDishName.map((word) => {
      if (this.tokenizer_.has(word)) {
        return this.tokenizer_.get(word);
      } else {
        // If word not present in tokenizer, return out-of-vocabulary token
        return this.tokenizer_.get('OOV');
      }
    });

    // Step 5: pad tokenized dish name to exactly length 43
    const input = AmaranthUtil.padArray(tokenizedDishName, 43, 0).slice(0, 43);

    // Step 5: feed dish name to ML model
    const inputTensor = tf.tensor(input);
    const calorieLabels = this.model_.predict(inputTensor);

    // Step 6: take softmax of outputs to get dish label
    // Confidence that the dish is low cal, avg cal, or high cal
    const [lowCalConf, avgCalConf, hiCalConf] = calorieLabels.arraySync();

    if (lowCalConf > avgCalConf && lowCalConf > hiCalConf) {
      // Dish is most confidently low calorie
      return CalorieLabel.LOW_CALORIE;
    } else if (avgCalConf > lowCalConf && avgCalConf > hiCalConf) {
      // Dish is most confidently average calorie
      return CalorieLabel.AVERAGE_CALORIE;
    } else if (hiCalConf > lowCalConf && hiCalConf > avgCalConf) {
      // Dish is most confidently high calorie
      return CalorieLabel.HIGH_CALORIE;
    } else {
      // If there is a tie anywhere, dish is deemed average calorie
      return CalorieLabel.AVERAGE_CALORIE;
    }
  }
}
<commit_msg>Fix expected dimensions for tf.LayersModel.predict<commit_after>/**
 * An object which labels a dish name as low, average, or high-calorie.
 */
class CalorieLabeller {
  /**
   * Creates a CalorieLabeller object.
   * @constructor
   * @param {Map<string, number>} tokenizer A mapping from dish name tokens to
   * unique integers
   * @param {tf.LayersModel} model Tensorflow.js layers ML model
   */
  constructor(tokenizer, model) {
    /** @private @const @type {Map<string, number>} */
    this.tokenizer_ = tokenizer;
    /** @private @const @type {tf.LayersModel} */
    this.model_ = model;
  }

  /**
   * Labels a single dish as high or low calorie.
   * @param {string} dishName The name of the dish to label
   * @return {CalorieLabel} The calorie label for the dish named dishName
   */
  label(dishName) {
    // Step 1: remove special characters from dish name
    dishName = AmaranthUtil.removeSpecialCharacters(dishName);

    // Step 2: convert dish name to lower case
    dishName = dishName.toLowerCase();

    // Step 3: split dish name on spaces
    const splitDishName = dishName.split(/\s+/);

    // Step 4: tokenize dish names
    const tokenizedDishName = splitDishName.map((word) => {
      if (this.tokenizer_.has(word)) {
        return this.tokenizer_.get(word);
      } else {
        // If word not present in tokenizer, return out-of-vocabulary token
        return this.tokenizer_.get('OOV');
      }
    });

    // Step 5: pad tokenized dish name to exactly length 43
    const input = AmaranthUtil.padArray(tokenizedDishName, 43, 0).slice(0, 43);

    // Step 5: feed dish name to ML model
    const inputTensor = tf.tensor([input]);
    const calorieLabels = this.model_.predict(inputTensor);

    // Step 6: take softmax of outputs to get dish label
    // Confidence that the dish is low cal, avg cal, or high cal
    const [lowCalConf, avgCalConf, hiCalConf] = calorieLabels.arraySync();

    if (lowCalConf > avgCalConf && lowCalConf > hiCalConf) {
      // Dish is most confidently low calorie
      return CalorieLabel.LOW_CALORIE;
    } else if (avgCalConf > lowCalConf && avgCalConf > hiCalConf) {
      // Dish is most confidently average calorie
      return CalorieLabel.AVERAGE_CALORIE;
    } else if (hiCalConf > lowCalConf && hiCalConf > avgCalConf) {
      // Dish is most confidently high calorie
      return CalorieLabel.HIGH_CALORIE;
    } else {
      // If there is a tie anywhere, dish is deemed average calorie
      return CalorieLabel.AVERAGE_CALORIE;
    }
  }
}
<|endoftext|>


<commit_before>// Server-side rendering example for Ideogram.js
//
// This module instantiates a Node.js server, and listens on port 9494 for
// incoming POST requests that contain an Ideogram configuration object. See
// ideo_config.json in this directory for an example POST body.  That
// configuration is then used to instantiate an ideogram, including SVG
// rendered to the DOM via PhantomJS (a headless browser that uses WebKit).
// The response is SVG that depicts a set of chromosomes.
//
// Tested on Ubuntu 14.04 with PhantomJS 1.9.7 and Node 0.12.7
//
// To run this example:
// 1. Open a terminal
// 2. cd ideogram/examples/server
// 3. phantomjs server.js
// 4. Open another another terminal
// 5. cd ideogram/examples/server
// 6. curl -X POST -d @ideo_config.json -H "Content-Type: application/json" localhost:9494

var port, server, service, page, url, svgDrawer,
    fs = require('fs'),
    async = require('async');

port = 9494;
server = require('webserver').create();

page = require('webpage').create();
page.viewportSize = {width: 540, height: 70};

url = 'file://' + fs.absolute('./human.html');

page.onConsoleMessage = function (msg){
    console.log(msg);
};

ideogramDrawer = function(config) {

  function rearrangeAnnots(annots) {
    // Rearranges annots into an array where each chromosome in the
    // ideogram gets 1 annotation.

    //annots = annots["annots"];

    var annot, chrs, chr, i, j, k, m,
        chrAnnots, totalAnnots,
        rearrangedAnnots = [], ras,
        ids;

    chrs = {};

    totalAnnots = 0;

    var seenAnnots = {}

    for (i = 0; i < annots.length; i++) {
      annotsByChr = annots[i];
      chr = annotsByChr["chr"];
      chrs[chr] = 0;
    }
    for (i = 0; i < annots.length; i++) {

      annotsByChr = annots[i];
      chr = annotsByChr["chr"];
      chrAnnots = annotsByChr["annots"];

      for (j = 0; j < chrAnnots.length; j++) {

        if (j <= chrs[chr]) {

          ras = [];
          ids = [];
          rasChrs = [];
          for (k = 0; k < annots.length; k++) {
            if (j < annots[k]["annots"].length ) {
              ra = annots[k]["annots"][j];
              if (ra["id"] in seenAnnots === false) {
                seenAnnots[ra["id"]] = 1;
                ids.push(ra["id"]);
                ras.push({"chr": annots[k]["chr"], "annots": [ra]});
                rasChrs.push(annots[k]["chr"])
                totalAnnots += 1;
              }
            }
          }
          chrs[annots[i]["chr"]] += 1;
          if (ids.length > 0) {
            rearrangedAnnots.push([ids, ras, rasChrs]);
          }
        }
      }

    }

    return rearrangedAnnots;

  }

  var rawAnnotsByChr, rearrangedAnnots, ra,
      ideogram,
      annot, annots, i,
      svg, id, ids, tmp,
      chrRects, rect, chrs, chr, chrID,
      images = [];

  ideogram = new Ideogram(config);
  ideogram.annots = ideogram.processAnnotData(config.rawAnnots.annots);

  var t0 = new Date().getTime();
  rearrangedAnnots = rearrangeAnnots(ideogram.annots);
  var t1 = new Date().getTime();
  console.log("Time to rearrange annots: " + (t1-t0) + " ms");

  for (i = 0; i < rearrangedAnnots.length; i++) {
  //for (i = 0; i < 2; i++) { // DEBUG
    d3.selectAll(".annot").remove();
    ra = rearrangedAnnots[i];
    ideogram.drawAnnots(ra[1]);
    svg = d3.select(ideogram.config.container)[0][0].innerHTML;
    images.push([ra[0], svg, ra[2]]);
  }

  chrRects = {};
  chrs = d3.selectAll(".chromosome")[0];
  for (i = 0; i < chrs.length; i++) {
    chr = chrs[i];
    chrID = chr["id"].split("-")[0].slice(3); // e.g. chr12-9606 -> 12
    rect = chr.getBoundingClientRect();
    chrRects[chrID] = {
      "top": rect.top,
      //"left": rect.left,
      "left": 5,
      "width": rect.width + 15,
      "height": rect.height + 7
    }
  }

  images = [chrRects, images]

  return images;
}

svgDrawer = function(svg) {
  //var oldDiv = document.getElementsByTagName("body")[0];
  //var newDiv = oldDiv.cloneNode(false);
  //newDiv.innerHTML = svg;
  //oldDiv.parentNode.replaceChild(newDiv, oldDiv);

  document.getElementsByTagName("body")[0].innerHTML = svg;

}

service = server.listen(port, function (request, response) {

  var t0, t1, time,
      t0a, t1a, timeA = 0,
      t1b, t1b, timeB = 0,
      t1c, t1c, timeC = 0,
      chr;

  var ideoConfig = JSON.parse(request.post);

  var rawAnnots = JSON.parse(fs.read(ideoConfig.localAnnotationsPath));
  ideoConfig["rawAnnots"] = rawAnnots;

  page.open(url, function (status) {

    t0 = new Date().getTime();
    var tmp = page.evaluate(ideogramDrawer, ideoConfig);
    var chrRects = tmp[0];
    var images = tmp[1];
    t1 = new Date().getTime();
    time = t1 - t0;
    console.log("Time to get images: " + time + " ms")

    t0 = new Date().getTime();
    var image, id, png;

    var chrRect = {};

    for (var i = 0; i < images.length; i++) {
      t0a = new Date().getTime();

      page.evaluate(svgDrawer, images[i][1]);

      t1a = new Date().getTime();
      timeA += t1a - t0a;

      async.forEachOf(images[i][0], function (id, index) {

          t0b = new Date().getTime();
          chr = images[i][2][index];
          chrRect = chrRects[chr];
          page.clipRect = chrRect;

          t1b = new Date().getTime();
          timeB += t1b - t0b;

          t0c = new Date().getTime();
          page.render("images/" + id + '.png');
          t1c = new Date().getTime();
          timeC += t1c - t0c;

      });

    }

    console.log("Time to evaluate SVG: " + timeA + " ms")
    //console.log("Time to render, write: " + timeB + " ms")
    console.log("Time to render: " + timeB + " ms")
    console.log("Time to write: " + timeC + " ms")

    t1 = new Date().getTime();
    time = t1 - t0;
    console.log("Time to produce all images: " + time + " ms")

    response.statusCode = 200;

    response.write("Done");
    response.close();

  });
});

if (service) {
  console.log('Web server running on port ' + port);
} else {
  console.log('Error: Could not create web server listening on port ' + port);
  phantom.exit();
}
<commit_msg>Optimized by removing undisplayed elements; ~0.041 -> 0.028 s/ideo<commit_after>// Server-side rendering example for Ideogram.js
//
// This module instantiates a Node.js server, and listens on port 9494 for
// incoming POST requests that contain an Ideogram configuration object. See
// ideo_config.json in this directory for an example POST body.  That
// configuration is then used to instantiate an ideogram, including SVG
// rendered to the DOM via PhantomJS (a headless browser that uses WebKit).
// The response is SVG that depicts a set of chromosomes.
//
// Tested on Ubuntu 14.04 with PhantomJS 1.9.7 and Node 0.12.7
//
// To run this example:
// 1. Open a terminal
// 2. cd ideogram/examples/server
// 3. phantomjs server.js
// 4. Open another another terminal
// 5. cd ideogram/examples/server
// 6. curl -X POST -d @ideo_config.json -H "Content-Type: application/json" localhost:9494

var port, server, service, page, url, svgDrawer,
    fs = require('fs'),
    async = require('async');

port = 9494;
server = require('webserver').create();

page = require('webpage').create();
page.viewportSize = {width: 540, height: 70};

url = 'file://' + fs.absolute('./human.html');

page.onConsoleMessage = function (msg){
    console.log(msg);
};

ideogramDrawer = function(config) {

  function rearrangeAnnots(annots) {
    // Rearranges annots into an array where each chromosome in the
    // ideogram gets 1 annotation.

    //annots = annots["annots"];

    var annot, chrs, chr, i, j, k, m,
        chrAnnots, totalAnnots,
        rearrangedAnnots = [], ras,
        ids;

    chrs = {};

    totalAnnots = 0;

    var seenAnnots = {}

    for (i = 0; i < annots.length; i++) {
      annotsByChr = annots[i];
      chr = annotsByChr["chr"];
      chrs[chr] = 0;
    }
    for (i = 0; i < annots.length; i++) {

      annotsByChr = annots[i];
      chr = annotsByChr["chr"];
      chrAnnots = annotsByChr["annots"];

      for (j = 0; j < chrAnnots.length; j++) {

        if (j <= chrs[chr]) {

          ras = [];
          ids = [];
          rasChrs = [];
          for (k = 0; k < annots.length; k++) {
            if (j < annots[k]["annots"].length ) {
              ra = annots[k]["annots"][j];
              if (ra["id"] in seenAnnots === false) {
                seenAnnots[ra["id"]] = 1;
                ids.push(ra["id"]);
                ras.push({"chr": annots[k]["chr"], "annots": [ra]});
                rasChrs.push(annots[k]["chr"])
                totalAnnots += 1;
              }
            }
          }
          chrs[annots[i]["chr"]] += 1;
          if (ids.length > 0) {
            rearrangedAnnots.push([ids, ras, rasChrs]);
          }
        }
      }

    }

    return rearrangedAnnots;

  }

  var rawAnnotsByChr, rearrangedAnnots, ra,
      ideogram,
      annot, annots, i,
      svg, id, ids, tmp,
      chrRects, rect, chrs, chr, chrID,
      images = [];

  ideogram = new Ideogram(config);
  ideogram.annots = ideogram.processAnnotData(config.rawAnnots.annots);

  var t0 = new Date().getTime();
  rearrangedAnnots = rearrangeAnnots(ideogram.annots);
  var t1 = new Date().getTime();
  console.log("Time to rearrange annots: " + (t1-t0) + " ms");

  d3.selectAll("*[style*='display: none']").remove();

  for (i = 0; i < rearrangedAnnots.length; i++) {
  //for (i = 0; i < 2; i++) { // DEBUG
    d3.selectAll(".annot").remove();
    ra = rearrangedAnnots[i];
    ideogram.drawAnnots(ra[1]);
    svg = d3.select(ideogram.config.container)[0][0].innerHTML;
    images.push([ra[0], svg, ra[2]]);
  }

  chrRects = {};
  chrs = d3.selectAll(".chromosome")[0];
  for (i = 0; i < chrs.length; i++) {
    chr = chrs[i];
    chrID = chr["id"].split("-")[0].slice(3); // e.g. chr12-9606 -> 12
    rect = chr.getBoundingClientRect();
    chrRects[chrID] = {
      "top": rect.top,
      //"left": rect.left,
      "left": 5,
      "width": rect.width + 15,
      "height": rect.height + 7
    }
  }

  images = [chrRects, images]

  return images;
}

svgDrawer = function(svg) {
  //var oldDiv = document.getElementsByTagName("body")[0];
  //var newDiv = oldDiv.cloneNode(false);
  //newDiv.innerHTML = svg;
  //oldDiv.parentNode.replaceChild(newDiv, oldDiv);

  document.getElementsByTagName("body")[0].innerHTML = svg;

}

service = server.listen(port, function (request, response) {

  var t0, t1, time,
      t0a, t1a, timeA = 0,
      t1b, t1b, timeB = 0,
      t1c, t1c, timeC = 0,
      chr;

  var ideoConfig = JSON.parse(request.post);

  var rawAnnots = JSON.parse(fs.read(ideoConfig.localAnnotationsPath));
  ideoConfig["rawAnnots"] = rawAnnots;

  page.open(url, function (status) {

    t0 = new Date().getTime();
    var tmp = page.evaluate(ideogramDrawer, ideoConfig);
    var chrRects = tmp[0];
    var images = tmp[1];
    t1 = new Date().getTime();
    time = t1 - t0;
    console.log("Time to get images: " + time + " ms")

    t0 = new Date().getTime();
    var image, id, png;

    var chrRect = {};

    for (var i = 0; i < images.length; i++) {
      t0a = new Date().getTime();

      page.evaluate(svgDrawer, images[i][1]);

      t1a = new Date().getTime();
      timeA += t1a - t0a;

      async.forEachOf(images[i][0], function (id, index) {

          t0b = new Date().getTime();
          chr = images[i][2][index];
          chrRect = chrRects[chr];
          page.clipRect = chrRect;

          t1b = new Date().getTime();
          timeB += t1b - t0b;

          t0c = new Date().getTime();
          page.render("images/" + id + '.png');
          t1c = new Date().getTime();
          timeC += t1c - t0c;

      });

    }

    console.log("Time to evaluate SVG: " + timeA + " ms")
    //console.log("Time to render, write: " + timeB + " ms")
    console.log("Time to render: " + timeB + " ms")
    console.log("Time to write: " + timeC + " ms")

    t1 = new Date().getTime();
    time = t1 - t0;
    console.log("Time to produce all images: " + time + " ms")

    response.statusCode = 200;

    response.write("Done");
    response.close();

  });
});

if (service) {
  console.log('Web server running on port ' + port);
} else {
  console.log('Error: Could not create web server listening on port ' + port);
  phantom.exit();
}
<|endoftext|>


<commit_before>(function () {
  app = angular.module('app',["ngDragDrop"]);

  app.controller('PLCtrl',function($scope) {
    /* EDIT THE FOLLOWING FOR REAL DATA */

    /* playlists -> get playlists from Parse */
    $scope.playlists = [];

    $scope.onClick = function(playlist) {
      var restaurant = Parse.Object.extend("Restaurant");
      var query = new Parse.Query(restaurant);

      query.equalTo("sporklists", playlist.id);
      query.limit(1000);
      query.withinMiles("location", new Parse.GeoPoint(position.latitude, position.longitude), 50);
      query.find({
        success: function(results) {
          updateSporklist(playlist.get("name"), results);
        },
        error: function(error) {
          alert("Error: " + error.code + " " + error.message);
        }
      });
    }
  });

  app.controller('NewPLCtrl', function($scope) {
    $scope.onClick = function() {
      if (parseUser == null) {
        return;
      }

      $("#new-sporklist").css("visibility", "visible");
      $("#new-sporklist").focus();
      $('#new-sporklist').keyup(function(e){
        if(e.keyCode == 13) {
            var sporklist = Parse.Object.extend("Sporklist");
            var newList = new sporklist();
            newList.set("name", $("#new-sporklist").val());
            newList.set("author", parseUser.getUsername());
            newList.save();

            parseUser.fetch({
              success: function(myObject) {
                var sporklist = Parse.Object.extend("Sporklist");
                var query = new Parse.Query(sporklist);

                query.equalTo("author", parseUser.getUsername());
                query.limit(1000);

                query.find({
                    success: function(results) {
                        updateSporklists(results);
                    },
                    error: function(error) {
                        alert("Error: " + error.code + " " + error.message);
                    }
                });
              },
              error: function(myObject, error) {
                // The object was not refreshed successfully.
                // error is a Parse.Error with an error code and message.
              }
            });

            $(this).css("visibility", "hidden");
            $(this).val("");
        } else if (e.keyCode == 27) {
            $(this).css("visibility", "hidden");
            $(this).val("");
        }
      });
    };
  });

  app.controller('MainCtrl',function($scope) {
    /* The defaults for the home page.
     * The only thing that should show is the sidebar and the fb login.
     */
    $scope.user = false;
    $scope.friend = false;
    $scope.sporklist = false;
    $scope.search = false;
    $scope.map = false;
  });

  app.controller('MeCtrl', function($scope) {
    $scope.name = "";
    $scope.friendList = [];
    $scope.onClick = function(friend) {
      updateFriend(friend);
    };
  });

  app.controller('FriendCtrl', function($scope) {
    $scope.name = "";
    $scope.sporklists = [];

    $scope.onClick = function(sporklist) {
      var restaurant = Parse.Object.extend("Restaurant");
      var query = new Parse.Query(restaurant);

      query.equalTo("sporklists", sporklist.id);
      query.limit(1000);
      query.withinMiles("location", new Parse.GeoPoint(position.latitude, position.longitude), 50);
      query.find({
        success: function(results) {
          updateSporklist(sporklist.get("name"), results);
        },
        error: function(error) {
          alert("Error: " + error.code + " " + error.message);
        }
      });
    }
  })

  app.controller('sporkCtrl', function($scope) {
    $scope.name = "";
    $scope.restaurants = [];
  });

  app.controller('SearchCtrl', function($scope) {
    $scope.results = [];
  });

}());
<commit_msg>UGHHH<commit_after>(function () {
  app = angular.module('app',[]);

  app.controller('PLCtrl',function($scope) {
    /* EDIT THE FOLLOWING FOR REAL DATA */

    /* playlists -> get playlists from Parse */
    $scope.playlists = [];

    $scope.onClick = function(playlist) {
      var restaurant = Parse.Object.extend("Restaurant");
      var query = new Parse.Query(restaurant);

      query.equalTo("sporklists", playlist.id);
      query.limit(1000);
      query.withinMiles("location", new Parse.GeoPoint(position.latitude, position.longitude), 50);
      query.find({
        success: function(results) {
          updateSporklist(playlist.get("name"), results);
        },
        error: function(error) {
          alert("Error: " + error.code + " " + error.message);
        }
      });
    }
  });

  app.controller('NewPLCtrl', function($scope) {
    $scope.onClick = function() {
      if (parseUser == null) {
        return;
      }

      $("#new-sporklist").css("visibility", "visible");
      $("#new-sporklist").focus();
      $('#new-sporklist').keyup(function(e){
        if(e.keyCode == 13) {
            var sporklist = Parse.Object.extend("Sporklist");
            var newList = new sporklist();
            newList.set("name", $("#new-sporklist").val());
            newList.set("author", parseUser.getUsername());
            newList.save();

            parseUser.fetch({
              success: function(myObject) {
                var sporklist = Parse.Object.extend("Sporklist");
                var query = new Parse.Query(sporklist);

                query.equalTo("author", parseUser.getUsername());
                query.limit(1000);

                query.find({
                    success: function(results) {
                        updateSporklists(results);
                    },
                    error: function(error) {
                        alert("Error: " + error.code + " " + error.message);
                    }
                });
              },
              error: function(myObject, error) {
                // The object was not refreshed successfully.
                // error is a Parse.Error with an error code and message.
              }
            });

            $(this).css("visibility", "hidden");
            $(this).val("");
        } else if (e.keyCode == 27) {
            $(this).css("visibility", "hidden");
            $(this).val("");
        }
      });
    };
  });

  app.controller('MainCtrl',function($scope) {
    /* The defaults for the home page.
     * The only thing that should show is the sidebar and the fb login.
     */
    $scope.user = false;
    $scope.friend = false;
    $scope.sporklist = false;
    $scope.search = false;
    $scope.map = false;
  });

  app.controller('MeCtrl', function($scope) {
    $scope.name = "";
    $scope.friendList = [];
    $scope.onClick = function(friend) {
      updateFriend(friend);
    };
  });

  app.controller('FriendCtrl', function($scope) {
    $scope.name = "";
    $scope.sporklists = [];

    $scope.onClick = function(sporklist) {
      var restaurant = Parse.Object.extend("Restaurant");
      var query = new Parse.Query(restaurant);

      query.equalTo("sporklists", sporklist.id);
      query.limit(1000);
      query.withinMiles("location", new Parse.GeoPoint(position.latitude, position.longitude), 50);
      query.find({
        success: function(results) {
          updateSporklist(sporklist.get("name"), results);
        },
        error: function(error) {
          alert("Error: " + error.code + " " + error.message);
        }
      });
    }
  })

  app.controller('sporkCtrl', function($scope) {
    $scope.name = "";
    $scope.restaurants = [];
  });

  app.controller('SearchCtrl', function($scope) {
    $scope.results = [];
  });

}());
<|endoftext|>


<commit_before>function BxeXMLSnippets() {
	var snippets;

	this.init = function (options) {
		bxe_config.XMLSnippets = this;
		this.snippets = options;
		this.snippetsNames = new Array();

		for (var name in options) {

			this.snippetsNames.push(name);
		}
		// add button
		var b = bxe_config.getButtons();
		var tmpArray = new Array();
		tmpArray['col'] = 0;
		tmpArray['row'] = 3;
		tmpArray['action'] = "InsertXMLSnippet";
		tmpArray['type'] = "action";
		tmpArray['ns'] = "";
		tmpArray['data'] = "foobar";
		b["test"] = tmpArray;

		//register event

		document.eDOMaddEventListener( "InsertXMLSnippet" , BxeXMLSnippets_OpenDialog , false);

	}

	this.getCss = function() {
		return new Array();
	}

	this.getScripts = function() {
		return new Array();
	}

}

function BxeXMLSnippets_OpenDialog(e) {
	var mod = mozilla.getWidgetModalBox("Choose an XML Snippet", function(values) {
		bxe_history_snapshot();
		bxe_insertContent_async(values.snippet,BXE_SELECTION,BXE_SPLIT_IF_INLINE);
		var sel = window.getSelection();

		if (!sel.anchorNode.parentNode.XMLNode.parentNode.isNodeValid(false, 2)) {
			bxe_history_undo();
		}
		bxe_history_snapshot_async();
	});

	mod.addItem("snippet", "", "select","", bxe_config.XMLSnippets.snippets, bxe_config.XMLSnippets.snippetsNames);
	mod.show(100,50,"fixed");

}
<commit_msg>give the plugin  a decent button tooltip<commit_after>function BxeXMLSnippets() {
	var snippets;

	this.init = function (options) {
		bxe_config.XMLSnippets = this;
		this.snippets = options;
		this.snippetsNames = new Array();

		for (var name in options) {

			this.snippetsNames.push(name);
		}
		// add button
		var b = bxe_config.getButtons();
		var tmpArray = new Array();
		tmpArray['col'] = 0;
		tmpArray['row'] = 3;
		tmpArray['action'] = "InsertXMLSnippet";
		tmpArray['type'] = "action";
		tmpArray['ns'] = "";
		tmpArray['data'] = "foobar";
		b["XMLSnippets"] = tmpArray;

		//register event

		document.eDOMaddEventListener( "InsertXMLSnippet" , BxeXMLSnippets_OpenDialog , false);

	}

	this.getCss = function() {
		return new Array();
	}

	this.getScripts = function() {
		return new Array();
	}

}

function BxeXMLSnippets_OpenDialog(e) {
	var mod = mozilla.getWidgetModalBox("Choose an XML Snippet", function(values) {
		bxe_history_snapshot();
		bxe_insertContent_async(values.snippet,BXE_SELECTION,BXE_SPLIT_IF_INLINE);
		var sel = window.getSelection();

		if (!sel.anchorNode.parentNode.XMLNode.parentNode.isNodeValid(false, 2)) {
			bxe_history_undo();
		}
		bxe_history_snapshot_async();
	});

	mod.addItem("snippet", "", "select","", bxe_config.XMLSnippets.snippets, bxe_config.XMLSnippets.snippetsNames);
	mod.show(100,50,"fixed");

}
<|endoftext|>


<commit_before>//code from
//https://github.com/acrcloud/webapi_example/blob/master/identify%20protocol%201%20(recommended)/IdentifyProtocolV1.js

const url = require('url');
const fs = require('fs');
const crypto = require('crypto');
const request = require('request');

// const { ACR_SECRET_KEY, ACR_HOST, ACR_ACCOUNT } =require('../acr_auth');

console.log("host", ACR_HOST)
module.exports.acrRequest = ( req ,res,err ) => {
  // console.log("acrObj", acrObj) base64 starts 22 deep
const bitmap = req.body.send64.slice(22)
// console.log("back end msg", bitmap)

// console.log("bitmap findctrl", bitmap)

const options = {
  host: process.env.ACR_HOST ,
  endpoint: '/v1/identify',
  signature_version: '1',
  data_type:'audio',
  secure: true,
  access_key: process.env.ACR_ACCOUNT,
  access_secret: process.env.ACR_SECRET_KEY
};

function buildStringToSign(method, uri, accessKey, dataType, signatureVersion, timestamp) {
  return [method, uri, accessKey, dataType, signatureVersion, timestamp].join('\n');
}

function sign(signString, accessSecret) {
return   crypto.createHmac('sha1', accessSecret).update(new Buffer(signString, 'utf-8')).digest().toString('base64');
}

// *
 // * Identifies a sample of bytes

function identify(data, options, cb) {

  const current_data = new Date();
  const timestamp = current_data.getTime()/1000;

  const stringToSign = buildStringToSign('POST',
    options.endpoint,
    options.access_key,
    options.data_type,
    options.signature_version,
    timestamp);

  const signature = sign(stringToSign, options.access_secret);

  const formData = {
    sample: data,
    access_key:options.access_key,
    data_type:options.data_type,
    signature_version:options.signature_version,
    signature:signature,
    sample_bytes:data.length,
    timestamp:timestamp,
  }
  request.post({
    url: "http://"+options.host + options.endpoint,
    method: 'POST',
    formData: formData
  }, cb);
} // end identify

// const bitmap = fs.readFileSync('test_file_2.wav'); //testfile

 identify(bitmap, options, function (err, httpResponse, body) {
  if (err) console.log(err);
  console.log(body);
  res.status(200).json({ song: body })
});

// } //end acrRequest
<commit_msg>closing bracket, removed slice<commit_after>//code from
//https://github.com/acrcloud/webapi_example/blob/master/identify%20protocol%201%20(recommended)/IdentifyProtocolV1.js

const url = require('url');
const fs = require('fs');
const crypto = require('crypto');
const request = require('request');

// const { ACR_SECRET_KEY, ACR_HOST, ACR_ACCOUNT } =require('../acr_auth');

console.log("host", ACR_HOST)
module.exports.acrRequest = ( req ,res,err ) => {
  // console.log("acrObj", acrObj) base64 starts 22 deep
const bitmap = req.body.send64
// console.log("back end msg", bitmap)

// console.log("bitmap findctrl", bitmap)

const options = {
  host: process.env.ACR_HOST ,
  endpoint: '/v1/identify',
  signature_version: '1',
  data_type:'audio',
  secure: true,
  access_key: process.env.ACR_ACCOUNT,
  access_secret: process.env.ACR_SECRET_KEY
};

function buildStringToSign(method, uri, accessKey, dataType, signatureVersion, timestamp) {
  return [method, uri, accessKey, dataType, signatureVersion, timestamp].join('\n');
}

function sign(signString, accessSecret) {
return   crypto.createHmac('sha1', accessSecret).update(new Buffer(signString, 'utf-8')).digest().toString('base64');
}

// *
 // * Identifies a sample of bytes

function identify(data, options, cb) {

  const current_data = new Date();
  const timestamp = current_data.getTime()/1000;

  const stringToSign = buildStringToSign('POST',
    options.endpoint,
    options.access_key,
    options.data_type,
    options.signature_version,
    timestamp);

  const signature = sign(stringToSign, options.access_secret);

  const formData = {
    sample: data,
    access_key:options.access_key,
    data_type:options.data_type,
    signature_version:options.signature_version,
    signature:signature,
    sample_bytes:data.length,
    timestamp:timestamp,
  }
  request.post({
    url: "http://"+options.host + options.endpoint,
    method: 'POST',
    formData: formData
  }, cb);
} // end identify

// const bitmap = fs.readFileSync('test_file_2.wav'); //testfile

 identify(bitmap, options, function (err, httpResponse, body) {
  if (err) console.log(err);
  console.log(body);
  res.status(200).json({ song: body })
});

} //end acrRequest
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name nashaLeptaApp.editorOptions
 * @description
 * # editorOptions
 * Constant in the nashaLeptaApp.
 */
angular.module('nashaLeptaApp')
  .constant('editorOptions', {
    "language": "ru",
    allowedContent: true,
    entities: false,
    extraPlugins:'image2,youtube,justify,font,embed,find,iframe,' +
    'table,tableresize,tabletools,' +
    'clipboard,liststyle,selectall,uicolor,colorbutton,dialogui,dialog,' +
    'lineutils,showblocks,autolink,widget,widgetbootstrap,widgettemplatemenu',

    //allowedContent: 'p a div span h2 h3 h4 h5 h6 section article iframe object embed strong b i em cite pre blockquote small,' +
    //'sub sup code ul ol li dl dt dd table thead tbody th tr td img caption mediawrapper br[href,src,target,width,height,colspan,' +
    //'span,alt,name,title,class,id,data-options]{text-align,float,margin}(*);',

    toolbar: 'full',
    toolbar_full: [
      { name: 'base',
        items: [ 'Bold', 'Italic', 'Underline', 'ShowBlocks'] },
      { name: 'paragraph', items: [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote']},
      {name : 'support', items: [
        'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock' ] },
      { name: 'editing', items: [ 'Find','Replace','-','SelectAll' ] },
      { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },

      { name: 'clipboard', items: [ 'Cut','Copy','Paste', 'HorizontalRule']},
      { name: 'UnRe', items: [ 'Undo','Redo' ]},
      { name: 'styles', items: [ 'Styles','Font','Format', 'FontSize' ] },
      { name: 'styles', items: ['PasteText', 'PasteFromWord', 'RemoveFormat' ] },
      { name: 'colors', items : [ 'TextColor','BGColor' ] },
      { name: 'insert', items: [ 'Image', 'Table', 'SpecialChar' ] },
      { name: 'video', items: [ 'Youtube' ] },
      { name: 'others', items: [  'Source' ] },
      { name: 'tools', items: [ 'Maximize' ] },
      { name: 'bootstrap', items: [ 'WidgetTemplateMenu' ] }

    ]

  });
<commit_msg>ckeditor, added bootstrap options, and additional headers<commit_after>'use strict';

/**
 * @ngdoc service
 * @name nashaLeptaApp.editorOptions
 * @description
 * # editorOptions
 * Constant in the nashaLeptaApp.
 */
angular.module('nashaLeptaApp')
  .constant('editorOptions', {
    "language": "ru",
    allowedContent: true,
    entities: false,
    extraPlugins:'image2,youtube,justify,font,embed,find,iframe,' +
    'table,tableresize,tabletools,' +
    'clipboard,liststyle,selectall,uicolor,colorbutton,dialogui,dialog,' +
    'lineutils,showblocks,autolink,widget,widgetbootstrap,widgettemplatemenu',

    toolbar: 'full',
    toolbar_full: [
      { name: 'base',
        items: [ 'Bold', 'Italic', 'Underline', 'ShowBlocks'] },
      { name: 'paragraph', items: [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote']},
      {name : 'support', items: [
        'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock' ] },
      { name: 'editing', items: [ 'Find','Replace','-','SelectAll' ] },
      { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },

      { name: 'clipboard', items: [ 'Cut','Copy','Paste', 'HorizontalRule']},
      { name: 'UnRe', items: [ 'Undo','Redo' ]},
      { name: 'styles', items: [ 'Styles','Font','Format', 'FontSize' ] },
      { name: 'styles', items: ['PasteText', 'PasteFromWord', 'RemoveFormat' ] },
      { name: 'colors', items : [ 'TextColor','BGColor' ] },
      { name: 'insert', items: [ 'Image', 'Table', 'SpecialChar' ] },
      { name: 'video', items: [ 'Youtube' ] },
      { name: 'others', items: [  'Source' ] },
      { name: 'tools', items: [ 'Maximize' ] },
      { name: 'bootstrap', items: [ 'WidgetTemplateMenu' ] }

    ]

  });
<|endoftext|>


<commit_before>/**
 * @flow
 */

import React, {Component} from 'react'
import {StyleSheet, Text, View, LayoutAnimation, Image} from 'react-native'
import reactMixin from 'react-mixin'
import TimerMixin from 'react-timer-mixin'

import ToggleButton from '../../components/ToggleButton'
import MuteButton from '../buttons/MuteButton'
import IconButton from '../../components/IconButton'
import Game from '../../classes/Game'
import Timer from '../Timer'

const START_NUMBER = 10
const WARNING_THRESHOLD = 5
const WIN_SCREEN_DELAY = 1500
const LOSE_SCREEN_DELAY = 1500

export default class PlayLayout extends Component {
  static get defaultProps () {
    return {
      muted: false,
      buttonColors: [
        'lightsteelblue',
        'lightgreen',
        'lavender',
        'lightsalmon',
        '#a5d9e5'
      ]
    }
  }

  static get propTypes () {
    return {
      ga: React.PropTypes.object,
      muted: React.PropTypes.bool,
      navigator: React.PropTypes.object,
      soundsManager: React.PropTypes.object,
      buttonColors: React.PropTypes.array
    }
  }

  constructor (props) {
    super(props)

    this.game = new Game({
      targetNum: START_NUMBER - 1,
      onTimeOverCallback: this.updateGameState.bind(this),
      onTickCallback: this.onTimerTick.bind(this)
    })

    this.game.generateNext()

    this.state = {
      ...this.game.getState(),
      ...{
        demo: true,
        buttonColor: this.props.buttonColors[0]
      }
    }

    // weird
    this._demoPressSec = 0
    this._solution = this.game.solution

    this.props.ga.trackScreenView('Open-application')
  }

  componentWillUnmount () {
    this.game.stopTimer()
  }

  incSum (value) {
    this.props.soundsManager.play('toggle_off')
    this.game.incSum(Number(value))
    if (this.state.demo) {
      this.setTimeout(this.updateGameState, 2 * WIN_SCREEN_DELAY)
    } else {
      this.updateGameState()
    }
  }

  decSum (value) {
    this.props.soundsManager.play('toggle_on')
    this.game.decSum(Number(value))
    this.updateGameState()
  }

  updateGameState () {
    if (this.state.gameOver) {
      return
    }

    this.setState({
      isWin: this.game.isWin,
      gameOver: this.game.gameOver
    })

    if (this.game.gameOver) {
      if (this.game.isWin) {
        this.setTimeout(this.generateNewGame, WIN_SCREEN_DELAY)
      } else {
        this.props.ga.trackEvent(
          'Game',
          'game-over',
          {
            label: 'target-number',
            value: this.state.targetNum
          }
        )
        this.setTimeout(this.props.navigator.pop, LOSE_SCREEN_DELAY)
      }
    }
  }

  generateNewGame () {
    const {buttonColors} = this.props

    LayoutAnimation.configureNext({
      duration: 100,
      create: {
        type: LayoutAnimation.Types.spring,
        property: LayoutAnimation.Properties.scaleXY,
        springDamping: 0.5
      },
      update: {
        type: LayoutAnimation.Types.spring,
        springDamping: 0.5
      }
    })

    this.game.generateNext()
    this.setState({
      ...this.game.getState(),
      ...{
        demo: false,
        buttonColor: buttonColors[Math.floor(Math.random() * buttonColors.length)]
      }
    })
  }

  onTimerTick (timeout) {
    this.setState({timeout})
    if (this.state.timeout <= WARNING_THRESHOLD) {
      this.props.soundsManager.play('timeout')
    }
  }

  render () {
    const targetNumberTextStyle = [styles.targetNumberText]
    if (this.state.gameOver) {
      if (this.state.isWin) {
        targetNumberTextStyle.push(styles.targetNumberWinText)
      } else {
        targetNumberTextStyle.push(styles.targetNumberLoseText)
      }
    }

    return (
      <Image source={require('./img/background-80.png')} style={styles.container}>
        <View style={styles.topBar}>
          <IconButton
            name={'arrow-back'}
            onClick={this.props.navigator.pop} />
          <Timer
            demo={this.state.demo}
            timeout={this.state.timeout}
            warningThreshold={WARNING_THRESHOLD} />
          <MuteButton
            soundsManager={this.props.soundsManager}
            muted={this.props.muted} />
        </View>
        <View style={styles.targetNumberContainer}>
          <Text style={targetNumberTextStyle}>
            {this.state.targetNum}
          </Text>
        </View>
        {this.state.gameOver ? null : this.renderGridContainer()}
        <View style={styles.bottomBar}>
          <Text>{this.state.buttonColor}</Text>
        </View>
      </Image>
    )
  }

  renderGridContainer () {
    return (
      <View style={styles.gridContainer}>
        {this.renderGridRow(0)}
        {this.renderGridRow(1)}
        {this.renderGridRow(2)}
      </View>
    )
  }

  renderGridRow (rowIndex) {
    return (
      <View style={styles.gridRow}>
        {this.renderGridRowButton(3 * rowIndex + 0)}
        {this.renderGridRowButton(3 * rowIndex + 1)}
        {this.renderGridRowButton(3 * rowIndex + 2)}
      </View>
    )
  }

  renderGridRowButton (valuesIndex) {
    let demoPressSec = 0
    const {demo, buttonColor, gameOver} = this.state
    const value = this.state.values[valuesIndex]

    if (demo) {
      const index = this._solution.indexOf(value)
      if (index !== -1) {
        this._demoPressSec++
        this._solution = this._solution.filter((v, k) => (k !== index))
        demoPressSec = this._demoPressSec
      }
    }

    return (
      <ToggleButton
        value={value.toString()}
        onDown={this.incSum.bind(this)}
        onUp={this.decSum.bind(this)}
        disabled={gameOver}
        color={buttonColor}
        demoPressSec={demoPressSec}
        demo={demo} />
    )
  }
}

reactMixin.onClass(PlayLayout, TimerMixin)

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: null,
    height: null,
    resizeMode: Image.resizeMode.stretch
  },
  topBar: {
    height: 60,
    justifyContent: 'space-between',
    alignItems: 'center',
    flexDirection: 'row',
    paddingTop: 10,
    paddingLeft: 1,
    paddingRight: 3,
    marginBottom: 15
  },
  targetNumberContainer: {
    flex: 2,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 5
  },
  targetNumberText: {
    fontSize: 120,
    margin: 20,
    marginTop: 20,
    textShadowOffset: {width: 3, height: 3},
    textShadowRadius: 5,
    textShadowColor: '#aaaaaa'
  },
  targetNumberWinText: {
    color: 'lightgreen',
    marginTop: 0
  },
  targetNumberLoseText: {
    color: 'red',
    marginTop: 0
  },
  gridContainer: {
    flex: 5,
    margin: 10
  },
  gridRow: {
    flex: 1,
    flexDirection: 'row'
  },
  bottomBar: {
    height: 60,
    backgroundColor: 'lightgray',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10
  }
})
<commit_msg>Remove bad color<commit_after>/**
 * @flow
 */

import React, {Component} from 'react'
import {StyleSheet, Text, View, LayoutAnimation, Image} from 'react-native'
import reactMixin from 'react-mixin'
import TimerMixin from 'react-timer-mixin'

import ToggleButton from '../../components/ToggleButton'
import MuteButton from '../buttons/MuteButton'
import IconButton from '../../components/IconButton'
import Game from '../../classes/Game'
import Timer from '../Timer'

const START_NUMBER = 10
const WARNING_THRESHOLD = 5
const WIN_SCREEN_DELAY = 1500
const LOSE_SCREEN_DELAY = 1500

export default class PlayLayout extends Component {
  static get defaultProps () {
    return {
      muted: false,
      buttonColors: [
        'lightsteelblue',
        'lightgreen',
        'lightsalmon',
        '#a5d9e5'
      ]
    }
  }

  static get propTypes () {
    return {
      ga: React.PropTypes.object,
      muted: React.PropTypes.bool,
      navigator: React.PropTypes.object,
      soundsManager: React.PropTypes.object,
      buttonColors: React.PropTypes.array
    }
  }

  constructor (props) {
    super(props)

    this.game = new Game({
      targetNum: START_NUMBER - 1,
      onTimeOverCallback: this.updateGameState.bind(this),
      onTickCallback: this.onTimerTick.bind(this)
    })

    this.game.generateNext()

    this.state = {
      ...this.game.getState(),
      ...{
        demo: true,
        buttonColor: this.props.buttonColors[0]
      }
    }

    // weird
    this._demoPressSec = 0
    this._solution = this.game.solution

    this.props.ga.trackScreenView('Open-application')
  }

  componentWillUnmount () {
    this.game.stopTimer()
  }

  incSum (value) {
    this.props.soundsManager.play('toggle_off')
    this.game.incSum(Number(value))
    if (this.state.demo) {
      this.setTimeout(this.updateGameState, 2 * WIN_SCREEN_DELAY)
    } else {
      this.updateGameState()
    }
  }

  decSum (value) {
    this.props.soundsManager.play('toggle_on')
    this.game.decSum(Number(value))
    this.updateGameState()
  }

  updateGameState () {
    if (this.state.gameOver) {
      return
    }

    this.setState({
      isWin: this.game.isWin,
      gameOver: this.game.gameOver
    })

    if (this.game.gameOver) {
      if (this.game.isWin) {
        this.setTimeout(this.generateNewGame, WIN_SCREEN_DELAY)
      } else {
        this.props.ga.trackEvent(
          'Game',
          'game-over',
          {
            label: 'target-number',
            value: this.state.targetNum
          }
        )
        this.setTimeout(this.props.navigator.pop, LOSE_SCREEN_DELAY)
      }
    }
  }

  generateNewGame () {
    const {buttonColors} = this.props

    LayoutAnimation.configureNext({
      duration: 100,
      create: {
        type: LayoutAnimation.Types.spring,
        property: LayoutAnimation.Properties.scaleXY,
        springDamping: 0.5
      },
      update: {
        type: LayoutAnimation.Types.spring,
        springDamping: 0.5
      }
    })

    this.game.generateNext()
    this.setState({
      ...this.game.getState(),
      ...{
        demo: false,
        buttonColor: buttonColors[Math.floor(Math.random() * buttonColors.length)]
      }
    })
  }

  onTimerTick (timeout) {
    this.setState({timeout})
    if (this.state.timeout <= WARNING_THRESHOLD) {
      this.props.soundsManager.play('timeout')
    }
  }

  render () {
    const targetNumberTextStyle = [styles.targetNumberText]
    if (this.state.gameOver) {
      if (this.state.isWin) {
        targetNumberTextStyle.push(styles.targetNumberWinText)
      } else {
        targetNumberTextStyle.push(styles.targetNumberLoseText)
      }
    }

    return (
      <Image source={require('./img/background-80.png')} style={styles.container}>
        <View style={styles.topBar}>
          <IconButton
            name={'arrow-back'}
            onClick={this.props.navigator.pop} />
          <Timer
            demo={this.state.demo}
            timeout={this.state.timeout}
            warningThreshold={WARNING_THRESHOLD} />
          <MuteButton
            soundsManager={this.props.soundsManager}
            muted={this.props.muted} />
        </View>
        <View style={styles.targetNumberContainer}>
          <Text style={targetNumberTextStyle}>
            {this.state.targetNum}
          </Text>
        </View>
        {this.state.gameOver ? null : this.renderGridContainer()}
        <View style={styles.bottomBar}>
          <Text>{this.state.buttonColor}</Text>
        </View>
      </Image>
    )
  }

  renderGridContainer () {
    return (
      <View style={styles.gridContainer}>
        {this.renderGridRow(0)}
        {this.renderGridRow(1)}
        {this.renderGridRow(2)}
      </View>
    )
  }

  renderGridRow (rowIndex) {
    return (
      <View style={styles.gridRow}>
        {this.renderGridRowButton(3 * rowIndex + 0)}
        {this.renderGridRowButton(3 * rowIndex + 1)}
        {this.renderGridRowButton(3 * rowIndex + 2)}
      </View>
    )
  }

  renderGridRowButton (valuesIndex) {
    let demoPressSec = 0
    const {demo, buttonColor, gameOver} = this.state
    const value = this.state.values[valuesIndex]

    if (demo) {
      const index = this._solution.indexOf(value)
      if (index !== -1) {
        this._demoPressSec++
        this._solution = this._solution.filter((v, k) => (k !== index))
        demoPressSec = this._demoPressSec
      }
    }

    return (
      <ToggleButton
        value={value.toString()}
        onDown={this.incSum.bind(this)}
        onUp={this.decSum.bind(this)}
        disabled={gameOver}
        color={buttonColor}
        demoPressSec={demoPressSec}
        demo={demo} />
    )
  }
}

reactMixin.onClass(PlayLayout, TimerMixin)

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: null,
    height: null,
    resizeMode: Image.resizeMode.stretch
  },
  topBar: {
    height: 60,
    justifyContent: 'space-between',
    alignItems: 'center',
    flexDirection: 'row',
    paddingTop: 10,
    paddingLeft: 1,
    paddingRight: 3,
    marginBottom: 15
  },
  targetNumberContainer: {
    flex: 2,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 5
  },
  targetNumberText: {
    fontSize: 120,
    margin: 20,
    marginTop: 20,
    textShadowOffset: {width: 3, height: 3},
    textShadowRadius: 5,
    textShadowColor: '#aaaaaa'
  },
  targetNumberWinText: {
    color: 'lightgreen',
    marginTop: 0
  },
  targetNumberLoseText: {
    color: 'red',
    marginTop: 0
  },
  gridContainer: {
    flex: 5,
    margin: 10
  },
  gridRow: {
    flex: 1,
    flexDirection: 'row'
  },
  bottomBar: {
    height: 60,
    backgroundColor: 'lightgray',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10
  }
})
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */

/* global moment */

(function() {
	if (!OC.Share) {
		OC.Share = {};
	}

	var TEMPLATE =
			// currently expiration is only effective for link share.
			// this is about to change in future. Therefore this is not included
			// in the LinkShareView to ease reusing it in future. Then,
			// modifications (getting rid of IDs) are still necessary.
			'{{#if isLinkShare}}' +
			'<input type="checkbox" name="expirationCheckbox" class="expirationCheckbox checkbox" id="expirationCheckbox-{{cid}}" value="1" ' +
				'{{#if isExpirationSet}}checked="checked"{{/if}} {{#if disableCheckbox}}disabled="disabled"{{/if}} />' +
			'{{setExpirationLabel}}' +
			'
' +
			'    {{expirationLabel}}' +
			'    <input id="expirationDate" class="datepicker" type="text" placeholder="{{expirationDatePlaceholder}}" value="{{expirationValue}}" />' +
			'
' +
			'    {{#if isExpirationEnforced}}' +
				// originally the expire message was shown when a default date was set, however it never had text
			'{{defaultExpireMessage}}' +
			'    {{/if}}' +
			'{{/if}}'
		;

	/**
	 * @class OCA.Share.ShareDialogExpirationView
	 * @member {OC.Share.ShareItemModel} model
	 * @member {jQuery} $el
	 * @memberof OCA.Sharing
	 * @classdesc
	 *
	 * Represents the expiration part in the GUI of the share dialogue
	 *
	 */
	var ShareDialogExpirationView = OC.Backbone.View.extend({
		/** @type {string} **/
		id: 'shareDialogLinkShare',

		/** @type {OC.Share.ShareConfigModel} **/
		configModel: undefined,

		/** @type {Function} **/
		_template: undefined,

		/** @type {boolean} **/
		showLink: true,

		className: 'hidden',

		events: {
			'change .expirationCheckbox': '_onToggleExpiration',
			'change .datepicker': '_onChangeExpirationDate'
		},

		initialize: function(options) {
			if(!_.isUndefined(options.configModel)) {
				this.configModel = options.configModel;
			} else {
				throw 'missing OC.Share.ShareConfigModel';
			}

			var view = this;
			this.configModel.on('change:isDefaultExpireDateEnforced', function() {
				view.render();
			});

			this.model.on('change:itemType', function() {
				view.render();
			});

			this.model.on('change:linkShare', function() {
				view.render();
			});
		},

		_onToggleExpiration: function(event) {
			var $checkbox = $(event.target);
			var state = $checkbox.prop('checked');
			// TODO: slide animation
			this.$el.find('.expirationDateContainer').toggleClass('hidden', !state);
			if (!state) {
				// discard expiration date
				this.model.saveLinkShare({
					expireDate: ''
				});
			}
		},

		_onChangeExpirationDate: function(event) {
			var $target = $(event.target);
			$target.tooltip('hide');
			$target.removeClass('error');

			this.model.saveLinkShare({
				expiration: moment($target.val(), 'DD-MM-YYYY').format('YYYY-MM-DD')
			}, {
				error: function(model, message) {
					if (!message) {
						$target.attr('title', t('core', 'Error setting expiration date'));
					} else {
						$target.attr('title', message);
					}
					$target.tooltip({gravity: 'n'});
					$target.tooltip('show');
					$target.addClass('error');
				}
			});
		},

		render: function() {
			var defaultExpireMessage = '';
			var defaultExpireDays = this.configModel.get('defaultExpireDate');
			var isExpirationEnforced = this.configModel.get('isDefaultExpireDateEnforced');

			if(    (this.model.isFolder() || this.model.isFile())
				&& isExpirationEnforced) {
				defaultExpireMessage = t(
					'core',
					'The public link will expire no later than {days} days after it is created',
					{'days': defaultExpireDays }
				);
			}

			var isExpirationSet = !!this.model.get('linkShare').expiration || isExpirationEnforced;

			var expiration;
			if (isExpirationSet) {
				expiration = moment(this.model.get('linkShare').expiration, 'YYYY-MM-DD').format('DD-MM-YYYY');
			}

			this.$el.html(this.template({
				cid: this.cid,
				setExpirationLabel: t('core', 'Set expiration date'),
				expirationLabel: t('core', 'Expiration'),
				expirationDatePlaceholder: t('core', 'Expiration date'),
				defaultExpireMessage: defaultExpireMessage,
				isLinkShare: this.model.get('linkShare').isLinkShare,
				isExpirationSet: isExpirationSet,
				isExpirationEnforced: isExpirationEnforced,
				disableCheckbox: isExpirationEnforced && isExpirationSet,
				expirationValue: expiration
			}));

			// what if there is another date picker on that page?
			var minDate = new Date();
			var maxDate = null;
			// min date should always be the next day
			minDate.setDate(minDate.getDate()+1);

			if(isExpirationSet) {
				if(isExpirationEnforced) {
					// TODO: hack: backend returns string instead of integer
					var shareTime = this.model.get('linkShare').stime;
					if (_.isNumber(shareTime)) {
						shareTime = new Date(shareTime * 1000);
					}
					if (!shareTime) {
						shareTime = new Date(); // now
					}
					shareTime = OC.Util.stripTime(shareTime).getTime();
					maxDate = new Date(shareTime + defaultExpireDays * 24 * 3600 * 1000);
				}
			}
			$.datepicker.setDefaults({
				minDate: minDate,
				maxDate: maxDate
			});

			this.$el.find('.datepicker').datepicker({dateFormat : 'dd-mm-yy'});

			this.delegateEvents();

			return this;
		},

		/**
		 * @returns {Function} from Handlebars
		 * @private
		 */
		template: function (data) {
			if (!this._template) {
				this._template = Handlebars.compile(TEMPLATE);
			}
			return this._template(data);
		}

	});

	OC.Share.ShareDialogExpirationView = ShareDialogExpirationView;

})();
<commit_msg>[master] In cases where the server dictates the link share expiration the date is not updated on consequitive changes and enable/disable actions<commit_after>/*
 * Copyright (c) 2015
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */

/* global moment */

(function() {
	if (!OC.Share) {
		OC.Share = {};
	}

	var TEMPLATE =
			// currently expiration is only effective for link share.
			// this is about to change in future. Therefore this is not included
			// in the LinkShareView to ease reusing it in future. Then,
			// modifications (getting rid of IDs) are still necessary.
			'{{#if isLinkShare}}' +
			'<input type="checkbox" name="expirationCheckbox" class="expirationCheckbox checkbox" id="expirationCheckbox-{{cid}}" value="1" ' +
				'{{#if isExpirationSet}}checked="checked"{{/if}} {{#if disableCheckbox}}disabled="disabled"{{/if}} />' +
			'{{setExpirationLabel}}' +
			'
' +
			'    {{expirationLabel}}' +
			'    <input id="expirationDate" class="datepicker" type="text" placeholder="{{expirationDatePlaceholder}}" value="{{expirationValue}}" />' +
			'
' +
			'    {{#if isExpirationEnforced}}' +
				// originally the expire message was shown when a default date was set, however it never had text
			'{{defaultExpireMessage}}' +
			'    {{/if}}' +
			'{{/if}}'
		;

	/**
	 * @class OCA.Share.ShareDialogExpirationView
	 * @member {OC.Share.ShareItemModel} model
	 * @member {jQuery} $el
	 * @memberof OCA.Sharing
	 * @classdesc
	 *
	 * Represents the expiration part in the GUI of the share dialogue
	 *
	 */
	var ShareDialogExpirationView = OC.Backbone.View.extend({
		/** @type {string} **/
		id: 'shareDialogLinkShare',

		/** @type {OC.Share.ShareConfigModel} **/
		configModel: undefined,

		/** @type {Function} **/
		_template: undefined,

		/** @type {boolean} **/
		showLink: true,

		className: 'hidden',

		events: {
			'change .expirationCheckbox': '_onToggleExpiration',
			'change .datepicker': '_onChangeExpirationDate'
		},

		initialize: function(options) {
			if(!_.isUndefined(options.configModel)) {
				this.configModel = options.configModel;
			} else {
				throw 'missing OC.Share.ShareConfigModel';
			}

			var view = this;
			this.configModel.on('change:isDefaultExpireDateEnforced', function() {
				view.render();
			});

			this.model.on('change:itemType', function() {
				view.render();
			});

			this.model.on('change:linkShare', function() {
				view.render();
			});
		},

		_onToggleExpiration: function(event) {
			var $checkbox = $(event.target);
			var state = $checkbox.prop('checked');
			// TODO: slide animation
			this.$el.find('.expirationDateContainer').toggleClass('hidden', !state);
			if (!state) {
				// discard expiration date
				this.model.get('linkShare').expiration = '';
				this.model.saveLinkShare({
					expireDate: ''
				});
			}
		},

		_onChangeExpirationDate: function(event) {
			var $target = $(event.target);
			$target.tooltip('hide');
			$target.removeClass('error');

			expiration = moment($target.val(), 'DD-MM-YYYY').format('YYYY-MM-DD');
			this.model.get('linkShare').expiration = expiration;
			this.model.saveLinkShare({
				expiration: expiration
			}, {
				error: function(model, message) {
					if (!message) {
						$target.attr('title', t('core', 'Error setting expiration date'));
					} else {
						$target.attr('title', message);
					}
					$target.tooltip({gravity: 'n'});
					$target.tooltip('show');
					$target.addClass('error');
				}
			});
		},

		render: function() {
			var defaultExpireMessage = '';
			var defaultExpireDays = this.configModel.get('defaultExpireDate');
			var isExpirationEnforced = this.configModel.get('isDefaultExpireDateEnforced');

			if(    (this.model.isFolder() || this.model.isFile())
				&& isExpirationEnforced) {
				defaultExpireMessage = t(
					'core',
					'The public link will expire no later than {days} days after it is created',
					{'days': defaultExpireDays }
				);
			}

			var isExpirationSet = !!this.model.get('linkShare').expiration || isExpirationEnforced;

			var expiration;
			if (isExpirationSet) {
				expiration = moment(this.model.get('linkShare').expiration, 'YYYY-MM-DD').format('DD-MM-YYYY');
			}

			this.$el.html(this.template({
				cid: this.cid,
				setExpirationLabel: t('core', 'Set expiration date'),
				expirationLabel: t('core', 'Expiration'),
				expirationDatePlaceholder: t('core', 'Expiration date'),
				defaultExpireMessage: defaultExpireMessage,
				isLinkShare: this.model.get('linkShare').isLinkShare,
				isExpirationSet: isExpirationSet,
				isExpirationEnforced: isExpirationEnforced,
				disableCheckbox: isExpirationEnforced && isExpirationSet,
				expirationValue: expiration
			}));

			// what if there is another date picker on that page?
			var minDate = new Date();
			var maxDate = null;
			// min date should always be the next day
			minDate.setDate(minDate.getDate()+1);

			if(isExpirationSet) {
				if(isExpirationEnforced) {
					// TODO: hack: backend returns string instead of integer
					var shareTime = this.model.get('linkShare').stime;
					if (_.isNumber(shareTime)) {
						shareTime = new Date(shareTime * 1000);
					}
					if (!shareTime) {
						shareTime = new Date(); // now
					}
					shareTime = OC.Util.stripTime(shareTime).getTime();
					maxDate = new Date(shareTime + defaultExpireDays * 24 * 3600 * 1000);
				}
			}
			$.datepicker.setDefaults({
				minDate: minDate,
				maxDate: maxDate
			});

			this.$el.find('.datepicker').datepicker({dateFormat : 'dd-mm-yy'});

			this.delegateEvents();

			return this;
		},

		/**
		 * @returns {Function} from Handlebars
		 * @private
		 */
		template: function (data) {
			if (!this._template) {
				this._template = Handlebars.compile(TEMPLATE);
			}
			return this._template(data);
		}

	});

	OC.Share.ShareDialogExpirationView = ShareDialogExpirationView;

})();
<|endoftext|>