<commit_before>import * as utils from '../src/utils.js';
import {config} from '../src/config.js';
import {registerBidder} from '../src/adapters/bidderFactory.js';
import {BANNER} from '../src/mediaTypes.js';

const BIDDER_CODE = 'wipes';
const ALIAS_BIDDER_CODE = ['wi'];
const SUPPORTED_MEDIA_TYPES = [BANNER]
const ENDPOINT_URL = 'https://adn-srv.reckoner-api.com/v1/prebid';

function isBidRequestValid(bid) {
  switch (true) {
    case !!(bid.params.asid):
      break;
    default:
      utils.logWarn(`isBidRequestValid Error. ${bid.params}, please check your implementation.`);
      return false;
  }
  return true;
}

function buildRequests(validBidRequests, bidderRequest) {
  return validBidRequests.map(bidRequest => {
    const bidId = bidRequest.bidId
    const params = bidRequest.params;
    const asid = params.asid;
    return {
      method: 'GET',
      url: ENDPOINT_URL,
      data: {
        asid: asid,
        bid_id: bidId,
      }
    }
  });
}

function interpretResponse(serverResponse, bidRequest) {
  const bidResponses = [];
  const response = serverResponse.body;
  const cpm = response.cpm * 1000 || 0;
  if (cpm !== 0) {
    const netRevenue = (response.netRevenue === undefined) ? true : response.netRevenue;
    const bidResponse = {
      requestId: response.bid_id,
      cpm: cpm,
      width: response.width,
      height: response.height,
      creativeId: response.video_creative_id || 0,
      dealId: response.deal_id,
      currency: 'JPY',
      netRevenue: netRevenue,
      ttl: config.getConfig('_bidderTimeout'),
      referrer: bidRequest.data.r || '',
      mediaType: BANNER,
      ad: response.ad_tag,
    };
    bidResponses.push(bidResponse);
  }
  return bidResponses;
}

export const spec = {
  code: BIDDER_CODE,
  aliases: ALIAS_BIDDER_CODE,
  isBidRequestValid,
  buildRequests,
  interpretResponse,
  supportedMediaTypes: SUPPORTED_MEDIA_TYPES
}
registerBidder(spec);
<commit_msg>fix wipesAdapter CPM culclation (#5330)<commit_after>import * as utils from '../src/utils.js';
import {config} from '../src/config.js';
import {registerBidder} from '../src/adapters/bidderFactory.js';
import {BANNER} from '../src/mediaTypes.js';

const BIDDER_CODE = 'wipes';
const ALIAS_BIDDER_CODE = ['wi'];
const SUPPORTED_MEDIA_TYPES = [BANNER]
const ENDPOINT_URL = 'https://adn-srv.reckoner-api.com/v1/prebid';

function isBidRequestValid(bid) {
  switch (true) {
    case !!(bid.params.asid):
      break;
    default:
      utils.logWarn(`isBidRequestValid Error. ${bid.params}, please check your implementation.`);
      return false;
  }
  return true;
}

function buildRequests(validBidRequests, bidderRequest) {
  return validBidRequests.map(bidRequest => {
    const bidId = bidRequest.bidId
    const params = bidRequest.params;
    const asid = params.asid;
    return {
      method: 'GET',
      url: ENDPOINT_URL,
      data: {
        asid: asid,
        bid_id: bidId,
      }
    }
  });
}

function interpretResponse(serverResponse, bidRequest) {
  const bidResponses = [];
  const response = serverResponse.body;
  const cpm = response.cpm || 0;
  if (cpm !== 0) {
    const netRevenue = (response.netRevenue === undefined) ? true : response.netRevenue;
    const bidResponse = {
      requestId: response.bid_id,
      cpm: cpm,
      width: response.width,
      height: response.height,
      creativeId: response.video_creative_id || 0,
      dealId: response.deal_id,
      currency: 'JPY',
      netRevenue: netRevenue,
      ttl: config.getConfig('_bidderTimeout'),
      referrer: bidRequest.data.r || '',
      mediaType: BANNER,
      ad: response.ad_tag,
    };
    bidResponses.push(bidResponse);
  }
  return bidResponses;
}

export const spec = {
  code: BIDDER_CODE,
  aliases: ALIAS_BIDDER_CODE,
  isBidRequestValid,
  buildRequests,
  interpretResponse,
  supportedMediaTypes: SUPPORTED_MEDIA_TYPES
}
registerBidder(spec);
<|endoftext|>


<commit_before>import { takeEvery } from 'redux-saga';
import { select, put } from 'redux-saga/effects';
import changeAmount from '../updates/changeAmount';
import { updateMultipleTradeParams } from '../../_actions';
import { getParams, getProposalId } from './SagaSelectors';
import { api } from '../../_data/LiveData';
import { updatePurchasedContract, updateTradeError } from '../../_actions/TradeActions';
import { updateChartDataByContract } from '../../_actions/ChartDataActions';
import { unsubscribeProposal, subscribeProposal } from './ProposalSubscriptionSaga';

const CHANGE_STAKE = 'CHANGE_STAKE';
const PURCHASE = 'PURCHASE';

export const reqStakeChange = (index, stake) => ({
    type: CHANGE_STAKE,
    index,
    stake,
});

export const reqPurchase = (index, price) => ({
    type: PURCHASE,
    index,
    price,
});

function* handleStakeChange(action) {
    const { index, stake } = action;

    yield put(unsubscribeProposal(index));

    if (+stake <= 0 || stake === '') {
        yield put(updateTradeError(index, 'stakeError', 'Stake must be more than 0'));
        return;
    }

    const params = yield select(getParams(index));
    const updated = changeAmount(stake, params);
    yield [
        put(updateMultipleTradeParams(index, updated)),
        put(subscribeProposal(index, updated)),
    ];
}

function* handlePurchase(action) {
    const { index, price } = action;
    const params = yield select(getParams(index));
    const pid = yield select(getProposalId(index));
    try {
        const { buy } = yield api.buyContract(pid, price);

        const { ticks, candles, symbol, isSold } =
            yield api.getDataForContract(
                () => api.subscribeToOpenContract(buy.contract_id).then(r => r.proposal_open_contract),
                'ticks',
                false
            );

        yield [
            put(updatePurchasedContract(index, buy)),

            // update chart data so that chart will use ticks related to contract only
            put(updateChartDataByContract(buy.contract_id, ticks || candles, 'ticks', symbol, isSold)),
        ];
    } catch (err) {
        if (!err.error || !err.error.error) {
            throw err;                  // rethrow error that we do not expect
        }
        yield put(updateTradeError(index, 'serverError', err.error.error.message));
    } finally {
        yield put(subscribeProposal(index, params));
    }
}

export default function* watchPurchase() {
    yield [
        takeEvery(CHANGE_STAKE, handleStakeChange),
        takeEvery(PURCHASE, handlePurchase),
    ];
}
<commit_msg>Fix missing arg (#544)<commit_after>import { takeEvery } from 'redux-saga';
import { select, put } from 'redux-saga/effects';
import changeAmount from '../updates/changeAmount';
import { updateMultipleTradeParams } from '../../_actions';
import { getParams, getProposalId } from './SagaSelectors';
import { api } from '../../_data/LiveData';
import { updatePurchasedContract, updateTradeError } from '../../_actions/TradeActions';
import { updateChartDataByContract } from '../../_actions/ChartDataActions';
import { unsubscribeProposal, subscribeProposal } from './ProposalSubscriptionSaga';

const CHANGE_STAKE = 'CHANGE_STAKE';
const PURCHASE = 'PURCHASE';

export const reqStakeChange = (index, stake) => ({
    type: CHANGE_STAKE,
    index,
    stake,
});

export const reqPurchase = (index, price) => ({
    type: PURCHASE,
    index,
    price,
});

function* handleStakeChange(action) {
    const { index, stake } = action;

    yield put(unsubscribeProposal(index));

    if (+stake <= 0 || stake === '') {
        yield put(updateTradeError(index, 'stakeError', 'Stake must be more than 0'));
        return;
    }

    const params = yield select(getParams(index));
    const updated = changeAmount(stake, params);
    yield [
        put(updateMultipleTradeParams(index, updated)),
        put(subscribeProposal(index, updated)),
    ];
}

function* handlePurchase(action) {
    const { index, price } = action;
    const params = yield select(getParams(index));
    const pid = yield select(getProposalId(index));
    try {
        const { buy } = yield api.buyContract(pid, price);

        const { ticks, candles, symbol, isSold } =
            yield api.getDataForContract(
                () => api.subscribeToOpenContract(buy.contract_id).then(r => r.proposal_open_contract),
                undefined,
                'ticks',
                false
            );

        yield [
            put(updatePurchasedContract(index, buy)),

            // update chart data so that chart will use ticks related to contract only
            put(updateChartDataByContract(buy.contract_id, ticks || candles, 'ticks', symbol, isSold)),
        ];
    } catch (err) {
        if (!err.error || !err.error.error) {
            throw err;                  // rethrow error that we do not expect
        }
        yield put(updateTradeError(index, 'serverError', err.error.error.message));
    } finally {
        yield put(subscribeProposal(index, params));
    }
}

export default function* watchPurchase() {
    yield [
        takeEvery(CHANGE_STAKE, handleStakeChange),
        takeEvery(PURCHASE, handlePurchase),
    ];
}
<|endoftext|>


<commit_before>/**
 * @providesModule Site
 * @jsx React.DOM
 */

var React = require('React');
var HeaderNav = require('HeaderNav');
var Head = require('Head');
var Footer = require('Footer');

var siteConfig = require('../siteConfig.js');

var Site = React.createClass({
  render: function() {
    var title = this.props.title
      ? this.props.title + ' · ' + siteConfig.title
      : siteConfig.title + ' · ' + siteConfig.tagline;
    var description = this.props.description || siteConfig.tagline;
    var url =
      siteConfig.url + siteConfig.baseUrl + (this.props.url || 'index.html');
    return (

          <HeaderNav
            baseUrl={siteConfig.baseUrl}
            section={this.props.section}
            title={siteConfig.title}
          />

            {this.props.children}


<commit_before>/*jslint
 browser: true,
 white: true,
 plusplus: true,
 vars: true,
 nomen: true */
/*global jQuery */

if(typeof window.GOVUK === 'undefined'){ window.GOVUK = {}; }
(function($) {
  "use strict";

  var documentFilter = {
    loading: false,
    $form: null,
    formType: '',

    renderTable: function(data) {
      $('.js-filter-results').mustache('documents-_filter_table', data);
    },
    updateAtomFeed: function(data) {
      if (data.atom_feed_url) {
        $(".feeds .feed").attr("href", data.atom_feed_url);
      }
    },
    updateEmailSignup: function(data) {
      if (data.email_signup_url) {
        $(".feeds .govdelivery").attr("href", data.email_signup_url);
      }
    },
    updateFeeds: function(data) {
      $(".feeds").removeClass('js-hidden');
      documentFilter.updateAtomFeed(data);
      documentFilter.updateEmailSignup(data);
    },
    submitFilters: function(e){
      e.preventDefault();
      var $form = documentFilter.$form,
          $submitButton = $form.find('input[type=submit]'),
          url = $form.attr('action'),
          jsonUrl = url + ".json",
          params = $form.serializeArray();

      $submitButton.addClass('disabled');
      $(".filter-results-summary").find('.selections').text("Loading results…");
      $(".feeds").addClass('js-hidden');
      documentFilter.loading = true;
      // TODO: make a spinny updating thing
      $.ajax(jsonUrl, {
        cache: false,
        dataType:'json',
        data: params,
        complete: function(){
          documentFilter.loading = false;
        },
        success: function(data) {
          documentFilter.updateFeeds(data);
          if (data.results) {
            documentFilter.renderTable(data);
            documentFilter.liveResultSummary(data);
          }

          var newUrl = url + "?" + $form.serialize();
          history.pushState(documentFilter.currentPageState(), null, newUrl);
          window._gaq && _gaq.push(['_trackPageview', newUrl]);
        },
        error: function() {
          $submitButton.removeAttr('disabled');
        }
      });
    },
    urlWithout: function(object, value){
      var url = window.location.search,
          reg = new RegExp('&?'+object+'%5B%5D='+value+'&?');

      return url.replace(reg, '&')
    },
    urlWithoutKeyword: function(words, index){
      var url = window.location.search,
          reg = new RegExp('keywords=[^&]+'),
          newKeywords = [],
          i, _i;

      for(i=0,_i=words.length; i<_i; i++){
        if(i !== index){
          newKeywords.push(words[i]);
        }
      }
      return url.replace(reg, 'keywords='+ newKeywords.join('+'));
    },
    liveResultSummary: function(data){
      var $selections = $('.selections'),
          $title = $('.headings-block h1'),
          summary = '',
          formStatus = documentFilter.currentPageState(),
          context = {},
          i, _i, j, _j, field;

      $selections.html('');
      $title.find('span').remove();

      if (!data.result_type) {
        data.result_type = "result";
      }

      context.result_count = documentFilter._numberWithDelimiter(data.total_count);
      context.pluralized_result_type = documentFilter._pluralize(data.result_type, data.total_count);

      if(formStatus.selected) {
        for(i=0,_i=formStatus.selected.length; i<_i; i++) {
          field = formStatus.selected[i];

          if (field.title.length > 0) {
            if (field.id == "publication_filter_option" || field.id == "announcement_type_option") {
              if (field.value != "all") {
                $title.html($title.text().trim() + ': '+field.title[0]+'');
              }
            } else if (field.id === 'world_locations'){
              context.world_locations = [];
              for(j=0, _j=field.title.length; j<_j; j++){
                if(field.value[j] !== 'all'){
                  context['world_locations'].push({
                    name: field.title[j],
                    url: documentFilter.urlWithout(field.id, field.value[j]),
                    value: field.value[j],
                    joining: (j < _j-1 ? 'and' : '')
                  });
                }
              }
              if (context.world_locations.length > 0) {
                context['world_locations_any?'] = true;
              }
            } else if (field.id != 'sub_orgs' && field.id != 'date') {
              context[field.id] = [];

              for(j=0, _j=field.title.length; j<_j; j++){
                if(field.value[j] !== 'all'){
                  context[field.id].push({
                    name: field.title[j],
                    url: documentFilter.urlWithout(field.id, field.value[j]),
                    value: field.value[j],
                    joining: (j < _j-1 ? 'and' : '')
                  });
                }
              }
            }
          }
        }
      }
      if(formStatus.text) {
        for(i=0,_i=formStatus.text.length; i<_i; i++) {
          field = formStatus.text[i];

          if(field.value.length){
            if(field.id === 'keywords'){
              context['keywords_any?'] = true;
              context.keywords = [];

              var words = field.value.trim().split(/\s+/);
              for(j=0, _j=words.length; j<_j; j++){
                context.keywords.push({
                  name: words[j],
                  url: documentFilter.urlWithoutKeyword(words, j-1),
                  joining: (j < _j-1 ? 'or' : '')
                });
              }
            } else if (field.id === 'from_date'){
              context['date_from'] = field.value
            } else if (field.id === 'to_date'){
              context['date_to'] = field.value
            }
          }
        }
      }

      if (formStatus.checked) {
        for (i=0, _i=formStatus.checked.length; i<_i; i++) {
          field = formStatus.checked[i];
          if (field.id === 'relevant_to_local_government' && field.value === '1') {
            context.relevant_to_local_government = true;
          } else if (field.id === 'include_world_location_news' && field.value === '1') {
            context.include_world_location_news = true;
          }
        }
      }

      $selections.mustache('documents/_filter_selections', context);
    },
    removeFilters: function(field, removed){
      var selects = ['topics', 'departments', 'world_locations'],
          inputs = ['keywords', 'from_date', 'to_date'],
          checkboxes = ['relevant_to_local_government'];

      if($.inArray(field, selects) > -1){
        var $options = $("select option[value='"+removed+"']");
        if($options.length){
          $options.removeAttr("selected");
          var $select = $options.closest("select");
          if($select.find(':selected').length === 0){
            $select.find(">:first-child").prop("selected", true);
          };
          $select.change();
        }
      } else if ($.inArray(field, inputs) > -1){
        var $input = $("input#"+field);
        if($input.length){
          var value = $input.val(),
              reg = new RegExp(removed);
          $input.val(value.replace(reg, '').trim())
        }
        $input.parents('form').submit();
      } else if ($.inArray(field, checkboxes)) {
        var $checkbox = $('input#' + field);
        if ($checkbox.length) {
          $checkbox.attr('checked', false);
        }
        $checkbox.parents('form').submit();
      }
    },
    currentPageState: function() {
      return {
        html: $('.js-filter-results').html(),
        selected: $.map(documentFilter.$form.find('select'), function(n) {
          var $n = $(n),
              id = $n.attr('id'),
              titles = [],
              values = [];
          $("#" + id  + " option:selected").each(function(){
            titles.push($(this).text());
            values.push($(this).attr('value'));
          });
          return {id: id, value: values, title: titles};
        }),
        text: $.map(documentFilter.$form.find('input[type=text]'), function(n) {
          var $n = $(n);
          return {id: $n.attr('id'), value: $n.val()};
        }),
        checked: $.map(documentFilter.$form.find('input[type=radio]:checked, input[type=checkbox]:checked'), function(n) {
          var $n = $(n);
          return {id: $n.attr('id'), value: $n.val()};
        })
      };
    },
    onPopState: function(event) {
      if (event.state && event.state.html) {
        $('.js-filter-results').html(event.state.html);
        $.each(event.state.selected, function(i, selected) {
          $("#" + selected.id).val(selected.value);
        });
        $.each(event.state.text, function(i, text) {
          $("#" + text.id).val(text.value);
        });
        $.each(event.state.checked, function(i, checked) {
          $("#" + checked.id).attr('checked', true);
        });
      }
    },
    _numberWithDelimiter: function(x) {
      var parts = x.toString().split(".");
      parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      return parts.join(".");
    },
    _pluralize: function(word, count) {
      if (count === 1) {
        return word;
      }
      else {
        if (word.slice(-1) === 'y') {
          return word.slice(0, -1) + 'ies';
        }
        else {
          return word + 's';
        }
      }
    }
  };
  window.GOVUK.documentFilter = documentFilter;

  var enableDocumentFilter = function() {
    if (window.ieVersion && ieVersion === 6) {
      return this;
    }
    this.each(function(){
      if (window.GOVUK.support.history()) {
        var $form = $(this);
        $(window).on('popstate', function(evet) {
          documentFilter.onPopState(event);
        });
        documentFilter.$form = $form;
        documentFilter.formType = $form.attr('action').split('/').pop();

        history.replaceState(documentFilter.currentPageState(), null);

        $form.submit(documentFilter.submitFilters);

        var delay = (function(){
          var timer = 0;
          return function(callback, ms){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
          }
        })();

        $form.find('select, input[type=checkbox]').change(function() {
          $form.submit();
        });

        $('#keyword-filter').add('#date-range-filter').find('input[type=text]').keyup(function () {
          delay(function () {
            $form.submit();
          }, 600);
        });

        $('.filter-results-summary').delegate('a', 'click', function(e){
          e.preventDefault();
          documentFilter.removeFilters($(this).data('field'), $(this).data("val"));
        });

        $(".submit").addClass("js-hidden");

      }
    });
    return this;
  }

  $.fn.extend({
    enableDocumentFilter: enableDocumentFilter
  });
})(jQuery);
<commit_msg>Fix document list feed panel not updating<commit_after>/*jslint
 browser: true,
 white: true,
 plusplus: true,
 vars: true,
 nomen: true */
/*global jQuery */

if(typeof window.GOVUK === 'undefined'){ window.GOVUK = {}; }
(function($) {
  "use strict";

  var documentFilter = {
    loading: false,
    $form: null,
    formType: '',

    renderTable: function(data) {
      $('.js-filter-results').mustache('documents-_filter_table', data);
    },
    updateAtomFeed: function(data) {
      if (data.atom_feed_url) {
        $(".feeds .feed").attr("href", data.atom_feed_url);
        $(".feed-panel input").val(data.atom_feed_url);
      }
    },
    updateEmailSignup: function(data) {
      if (data.email_signup_url) {
        $(".feeds .govdelivery").attr("href", data.email_signup_url);
      }
    },
    updateFeeds: function(data) {
      $(".feeds").removeClass('js-hidden');
      documentFilter.updateAtomFeed(data);
      documentFilter.updateEmailSignup(data);
    },
    submitFilters: function(e){
      e.preventDefault();
      var $form = documentFilter.$form,
          $submitButton = $form.find('input[type=submit]'),
          url = $form.attr('action'),
          jsonUrl = url + ".json",
          params = $form.serializeArray();

      $submitButton.addClass('disabled');
      $(".filter-results-summary").find('.selections').text("Loading results…");
      $(".feeds").addClass('js-hidden');
      documentFilter.loading = true;
      // TODO: make a spinny updating thing
      $.ajax(jsonUrl, {
        cache: false,
        dataType:'json',
        data: params,
        complete: function(){
          documentFilter.loading = false;
        },
        success: function(data) {
          documentFilter.updateFeeds(data);
          if (data.results) {
            documentFilter.renderTable(data);
            documentFilter.liveResultSummary(data);
          }

          var newUrl = url + "?" + $form.serialize();
          history.pushState(documentFilter.currentPageState(), null, newUrl);
          window._gaq && _gaq.push(['_trackPageview', newUrl]);
        },
        error: function() {
          $submitButton.removeAttr('disabled');
        }
      });
    },
    urlWithout: function(object, value){
      var url = window.location.search,
          reg = new RegExp('&?'+object+'%5B%5D='+value+'&?');

      return url.replace(reg, '&')
    },
    urlWithoutKeyword: function(words, index){
      var url = window.location.search,
          reg = new RegExp('keywords=[^&]+'),
          newKeywords = [],
          i, _i;

      for(i=0,_i=words.length; i<_i; i++){
        if(i !== index){
          newKeywords.push(words[i]);
        }
      }
      return url.replace(reg, 'keywords='+ newKeywords.join('+'));
    },
    liveResultSummary: function(data){
      var $selections = $('.selections'),
          $title = $('.headings-block h1'),
          summary = '',
          formStatus = documentFilter.currentPageState(),
          context = {},
          i, _i, j, _j, field;

      $selections.html('');
      $title.find('span').remove();

      if (!data.result_type) {
        data.result_type = "result";
      }

      context.result_count = documentFilter._numberWithDelimiter(data.total_count);
      context.pluralized_result_type = documentFilter._pluralize(data.result_type, data.total_count);

      if(formStatus.selected) {
        for(i=0,_i=formStatus.selected.length; i<_i; i++) {
          field = formStatus.selected[i];

          if (field.title.length > 0) {
            if (field.id == "publication_filter_option" || field.id == "announcement_type_option") {
              if (field.value != "all") {
                $title.html($title.text().trim() + ': '+field.title[0]+'');
              }
            } else if (field.id === 'world_locations'){
              context.world_locations = [];
              for(j=0, _j=field.title.length; j<_j; j++){
                if(field.value[j] !== 'all'){
                  context['world_locations'].push({
                    name: field.title[j],
                    url: documentFilter.urlWithout(field.id, field.value[j]),
                    value: field.value[j],
                    joining: (j < _j-1 ? 'and' : '')
                  });
                }
              }
              if (context.world_locations.length > 0) {
                context['world_locations_any?'] = true;
              }
            } else if (field.id != 'sub_orgs' && field.id != 'date') {
              context[field.id] = [];

              for(j=0, _j=field.title.length; j<_j; j++){
                if(field.value[j] !== 'all'){
                  context[field.id].push({
                    name: field.title[j],
                    url: documentFilter.urlWithout(field.id, field.value[j]),
                    value: field.value[j],
                    joining: (j < _j-1 ? 'and' : '')
                  });
                }
              }
            }
          }
        }
      }
      if(formStatus.text) {
        for(i=0,_i=formStatus.text.length; i<_i; i++) {
          field = formStatus.text[i];

          if(field.value.length){
            if(field.id === 'keywords'){
              context['keywords_any?'] = true;
              context.keywords = [];

              var words = field.value.trim().split(/\s+/);
              for(j=0, _j=words.length; j<_j; j++){
                context.keywords.push({
                  name: words[j],
                  url: documentFilter.urlWithoutKeyword(words, j-1),
                  joining: (j < _j-1 ? 'or' : '')
                });
              }
            } else if (field.id === 'from_date'){
              context['date_from'] = field.value
            } else if (field.id === 'to_date'){
              context['date_to'] = field.value
            }
          }
        }
      }

      if (formStatus.checked) {
        for (i=0, _i=formStatus.checked.length; i<_i; i++) {
          field = formStatus.checked[i];
          if (field.id === 'relevant_to_local_government' && field.value === '1') {
            context.relevant_to_local_government = true;
          } else if (field.id === 'include_world_location_news' && field.value === '1') {
            context.include_world_location_news = true;
          }
        }
      }

      $selections.mustache('documents/_filter_selections', context);
    },
    removeFilters: function(field, removed){
      var selects = ['topics', 'departments', 'world_locations'],
          inputs = ['keywords', 'from_date', 'to_date'],
          checkboxes = ['relevant_to_local_government'];

      if($.inArray(field, selects) > -1){
        var $options = $("select option[value='"+removed+"']");
        if($options.length){
          $options.removeAttr("selected");
          var $select = $options.closest("select");
          if($select.find(':selected').length === 0){
            $select.find(">:first-child").prop("selected", true);
          };
          $select.change();
        }
      } else if ($.inArray(field, inputs) > -1){
        var $input = $("input#"+field);
        if($input.length){
          var value = $input.val(),
              reg = new RegExp(removed);
          $input.val(value.replace(reg, '').trim())
        }
        $input.parents('form').submit();
      } else if ($.inArray(field, checkboxes)) {
        var $checkbox = $('input#' + field);
        if ($checkbox.length) {
          $checkbox.attr('checked', false);
        }
        $checkbox.parents('form').submit();
      }
    },
    currentPageState: function() {
      return {
        html: $('.js-filter-results').html(),
        selected: $.map(documentFilter.$form.find('select'), function(n) {
          var $n = $(n),
              id = $n.attr('id'),
              titles = [],
              values = [];
          $("#" + id  + " option:selected").each(function(){
            titles.push($(this).text());
            values.push($(this).attr('value'));
          });
          return {id: id, value: values, title: titles};
        }),
        text: $.map(documentFilter.$form.find('input[type=text]'), function(n) {
          var $n = $(n);
          return {id: $n.attr('id'), value: $n.val()};
        }),
        checked: $.map(documentFilter.$form.find('input[type=radio]:checked, input[type=checkbox]:checked'), function(n) {
          var $n = $(n);
          return {id: $n.attr('id'), value: $n.val()};
        })
      };
    },
    onPopState: function(event) {
      if (event.state && event.state.html) {
        $('.js-filter-results').html(event.state.html);
        $.each(event.state.selected, function(i, selected) {
          $("#" + selected.id).val(selected.value);
        });
        $.each(event.state.text, function(i, text) {
          $("#" + text.id).val(text.value);
        });
        $.each(event.state.checked, function(i, checked) {
          $("#" + checked.id).attr('checked', true);
        });
      }
    },
    _numberWithDelimiter: function(x) {
      var parts = x.toString().split(".");
      parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      return parts.join(".");
    },
    _pluralize: function(word, count) {
      if (count === 1) {
        return word;
      }
      else {
        if (word.slice(-1) === 'y') {
          return word.slice(0, -1) + 'ies';
        }
        else {
          return word + 's';
        }
      }
    }
  };
  window.GOVUK.documentFilter = documentFilter;

  var enableDocumentFilter = function() {
    if (window.ieVersion && ieVersion === 6) {
      return this;
    }
    this.each(function(){
      if (window.GOVUK.support.history()) {
        var $form = $(this);
        $(window).on('popstate', function(evet) {
          documentFilter.onPopState(event);
        });
        documentFilter.$form = $form;
        documentFilter.formType = $form.attr('action').split('/').pop();

        history.replaceState(documentFilter.currentPageState(), null);

        $form.submit(documentFilter.submitFilters);

        var delay = (function(){
          var timer = 0;
          return function(callback, ms){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
          }
        })();

        $form.find('select, input[type=checkbox]').change(function() {
          $form.submit();
        });

        $('#keyword-filter').add('#date-range-filter').find('input[type=text]').keyup(function () {
          delay(function () {
            $form.submit();
          }, 600);
        });

        $('.filter-results-summary').delegate('a', 'click', function(e){
          e.preventDefault();
          documentFilter.removeFilters($(this).data('field'), $(this).data("val"));
        });

        $(".submit").addClass("js-hidden");

      }
    });
    return this;
  }

  $.fn.extend({
    enableDocumentFilter: enableDocumentFilter
  });
})(jQuery);
<|endoftext|>


<commit_before>'use strict';

var broadCastMessage = function(data) {
    self.clients.matchAll().then(function(clients) {
        clients.forEach(function(client) {
            client.postMessage({
                msg: 'log',
                data: data
            });
        });
    });
};

broadCastMessage('HELLO CLIENT');
broadCastMessage('U HEAR ME');

//importScripts('bundle.js');

importScripts('babel-core/browser.js');
importScripts('babel-core/browser-polyfill.js');

importScripts('serviceworker-cache-polyfill.js');

// Loaders
importScripts('loader/default.js');
importScripts('loader/eval.js');

// Transformers
importScripts('transformer/identity.js');

'use strict';

class LogAppend {
    match(response) {
        return response.url.indexOf('.js') > -1 &&
            response.url.indexOf('node_modules') === -1;
    }

    transform(response) {
        return response.clone().blob()
            .then(function(blob) {
                function readBlob(blob) {
                    console.log('Read blob of type ' + blob.type);
                    return new Promise(function(resolve, reject) {
                        var reader = new FileReader();

                        reader.addEventListener("load", function() {
                            resolve(reader.result);
                        });
                        reader.addEventListener("error", function(err) {
                            reject(err, 'Error during reading Blob');
                        });

                        reader.readAsBinaryString(blob);
                    });
                }

                return readBlob(blob)
                    .then(function srcTransform(content) {
                        console.log("BEFORE TRANSFORM");
                        console.log(content);
                        console.log("AFTER TRANSFORM");
                        var transformed = babel.transform(content, {
                            modules: 'amd'
                        }).code;
                        console.log(transformed);

                        return transformed;
                    })
                    .then(function packNewBlob(newContent) {
                        return new Blob([newContent], {
                            type: blob.type
                        });
                    });
            })
            .then(function packNewResponse(newBlob) {
                // pack new Response from a Blob and the given Response
                return new Response(newBlob, {
                    status: response.status,
                    statusText: response.statusText,
                    headers: response.headers
                });
            });
    }
}

console.log('Service Worker: File Start');

self.addEventListener('install', function(event) {
    console.log('Service Worker: Install');
});

self.addEventListener('activate', function(event) {
    console.log('Service Worker: Activate');
    self.clients.claim();
});

self.addEventListener('fetch', function(event) {
    console.log('Service Worker: Fetch', event.request, event.request.url);
    broadCastMessage('FETCHING THIS STUFF: ' + event.request.url);

    var response = parseEvent(event)
        .then(applyLoaders)
        .then(applyTransformers);

    event.respondWith(response);
});

function parseEvent(event) {
    console.log(event.request.url);
    return new Promise(function(resolve, reject) {
        resolve(event.request);
    });
}

function applyLoaders(request) {
    console.log('Service Worker: Loader', request.url);

    var response;

    var evalScript = new EvalLoader();
    if(evalScript.match(request)) {
        response = evalScript.transform(request);
    } else {
        response = (new DefaultLoader()).transform(request);
    }

    return response;
}

function applyTransformers(response) {
    console.log('Service Worker: Transformer', response, response.url);

    var log = new LogAppend();
    if(log.match(response)) {
        return log.transform(response);
    }

    return (new Identity()).transform(response);
}

console.log('Service Worker: File End');
<commit_msg>nicer blacklist of file not to transform<commit_after>'use strict';

var broadCastMessage = function(data) {
    self.clients.matchAll().then(function(clients) {
        clients.forEach(function(client) {
            client.postMessage({
                msg: 'log',
                data: data
            });
        });
    });
};

broadCastMessage('HELLO CLIENT');
broadCastMessage('U HEAR ME');

//importScripts('bundle.js');

importScripts('babel-core/browser.js');
importScripts('babel-core/browser-polyfill.js');

importScripts('serviceworker-cache-polyfill.js');

// Loaders
importScripts('loader/default.js');
importScripts('loader/eval.js');

// Transformers
importScripts('transformer/identity.js');

'use strict';

class LogAppend {
    match(response) {
        var blackList = [
            'babel-core/browser.js',
            'es6-module-loader/es6-module-loader-dev.src.js',
            'bootworker.js',
            'serviceworker.js',
            'system-polyfills.src.js',
            'system.src.js',
            'serviceworker-loader.js'
        ];

        var isJS = response.url.indexOf('.js') > -1;
        var inBlackList = false;
        for(var i = 0; i < blackList.length; i++) {
            inBlackList = inBlackList || response.url.indexOf(blackList[i]) > -1;
        }
        return isJS && !inBlackList;
    }

    transform(response) {
        return response.clone().blob()
            .then(function(blob) {
                function readBlob(blob) {
                    console.log('Read blob of type ' + blob.type);
                    return new Promise(function(resolve, reject) {
                        var reader = new FileReader();

                        reader.addEventListener("load", function() {
                            resolve(reader.result);
                        });
                        reader.addEventListener("error", function(err) {
                            reject(err, 'Error during reading Blob');
                        });

                        reader.readAsBinaryString(blob);
                    });
                }

                return readBlob(blob)
                    .then(function srcTransform(content) {
                        console.log("BEFORE TRANSFORM");
                        //console.log(content);
                        console.log("AFTER TRANSFORM");
                        var transformed = babel.transform(content, {
                            modules: 'system'
                        }).code;
                        //console.log(transformed);

                        return transformed;
                    })
                    .then(function packNewBlob(newContent) {
                        return new Blob([newContent], {
                            type: blob.type
                        });
                    });
            })
            .then(function packNewResponse(newBlob) {
                // pack new Response from a Blob and the given Response
                return new Response(newBlob, {
                    status: response.status,
                    statusText: response.statusText,
                    headers: response.headers
                });
            });
    }
}

console.log('Service Worker: File Start');

self.addEventListener('install', function(event) {
    console.log('Service Worker: Install');
});

self.addEventListener('activate', function(event) {
    console.log('Service Worker: Activate');
    self.clients.claim();
});

self.addEventListener('fetch', function(event) {
    console.log('Service Worker: Fetch', event.request, event.request.url);
    broadCastMessage('FETCHING THIS STUFF: ' + event.request.url);

    var response = parseEvent(event)
        .then(applyLoaders)
        .then(applyTransformers);

    event.respondWith(response);
});

function parseEvent(event) {
    console.log(event.request.url);
    return new Promise(function(resolve, reject) {
        resolve(event.request);
    });
}

function applyLoaders(request) {
    console.log('Service Worker: Loader', request.url);

    var response;

    var evalScript = new EvalLoader();
    if(evalScript.match(request)) {
        response = evalScript.transform(request);
    } else {
        response = (new DefaultLoader()).transform(request);
    }

    return response;
}

function applyTransformers(response) {
    console.log('Service Worker: Transformer', response, response.url);

    var log = new LogAppend();
    if(log.match(response)) {
        return log.transform(response);
    }

    return (new Identity()).transform(response);
}

console.log('Service Worker: File End');
<|endoftext|>


<commit_before>/* @flow */
import { exec } from 'create-npm/src/io'

export default async function(slug: string, data: string): Promise<string> {
  const quotedPayload = await exec(
    `travis enable --no-interactive --repo '${slug}' '${data}'`
  )
  return quotedPayload.slice(1, -1)
}
<commit_msg>Fix typo<commit_after>/* @flow */
import { exec } from 'create-npm/src/io'

export default async function(slug: string, data: string): Promise<string> {
  const quotedPayload = await exec(
    `travis encrypt --no-interactive --repo '${slug}' '${data}'`
  )
  return quotedPayload.slice(1, -1)
}
<|endoftext|>


<commit_before>ccm.files[ "forum_datastore.js" ] = {
  "demo":
  {
    "key": "demo",
    "questions": [
      [ "ccm.get", "../question/configs.json", "1"  ],
      [ "ccm.get", "../question/configs.json", "2"  ]
    ]
  }
}<commit_msg>set absolute paths<commit_after>ccm.files[ "forum_datastore.js" ] = {
  "demo":
  {
    "key": "demo",
    "questions": [
      [ "ccm.get", "https://tkless.github.io/ccm-components/question/question_configs.js", "1"  ],
      [ "ccm.get", "https://tkless.github.io/ccm-components/question/question_configs.js", "2"  ]
    ]
  }
}<|endoftext|>


<commit_before>requirejs.config({
  baseUrl: '/',
  include: [
    'streamhub-map/collection/collection-map-view',
    'streamhub-hot-collections-tests/mocks/streams/mock-hot-collections',
    'json!streamhub-hot-collections-tests/mocks/clients/hot-collections-response.json'
  ],
  paths: {
    jquery: 'lib/jquery/jquery',
	jasmine: 'lib/jasmine/lib/jasmine-core/jasmine',
    'jasmine-html': 'lib/jasmine/lib/jasmine-core/jasmine-html',
    'jasmine-jquery': 'lib/jasmine-jquery/lib/jasmine-jquery',
    text: 'lib/requirejs-text/text',
    hgn: 'lib/requirejs-hogan-plugin/hgn',
    hogan: 'lib/hogan/web/builds/2.0.0/hogan-2.0.0.amd',
    json: 'lib/requirejs-plugins/src/json',
    base64: 'lib/base64/base64',
    'event-emitter': 'lib/event-emitter/src/event-emitter',
    inherits: 'lib/inherits/inherits',
    leaflet: 'lib/leaflet/leaflet-src',
    'leaflet-css': 'lib/leaflet/leaflet.css',
    'leaflet-markercluster': 'lib/leaflet-markercluster/dist/leaflet.markercluster-src',
    'leaflet-markercluster-css': 'lib/leaflet-markercluster/dist/MarkerCluster.css',
  },
  packages: [{
    name: "streamhub-sdk",
    location: "lib/streamhub-sdk/src/"
  },{
    name: "streamhub-sdk/auth",
    location: "lib/streamhub-sdk/src/auth"
  },{
    name: "streamhub-sdk/collection",
    location: "lib/streamhub-sdk/src/collection"
  },{
    name: "streamhub-sdk/content",
    location: "lib/streamhub-sdk/src/content"
  },{
    name: "streamhub-sdk/modal",
    location: "lib/streamhub-sdk/src/modal"
  },{
    name: "streamhub-sdk-tests",
    location: "lib/streamhub-sdk/tests/"
  },{
    name: "stream",
    location: "lib/stream/src"
  },{
	name: "streamhub-map",
  	location: "src"
  },{
    name: "streamhub-map-resources",
    location: "src/resources/"
  },{
    name: "streamhub-hot-collections",
    location: "lib/streamhub-hot-collections/src/"
  },{
    name: "streamhub-hot-collections-tests",
    location: "lib/streamhub-hot-collections/tests/"
  },{
    name: "streamhub-metrics",
    location: "lib/streamhub-metrics/src/"
  },{
    name: "view",
    location: "lib/view/src",
    main: "view"
  }],
  shim: {
    jasmine: {
      exports: 'jasmine'
    },
    'jasmine-html': {
      deps: ['jasmine'],
      exports: 'jasmine'
    },
    'jasmine-jquery': {
      deps: ['jquery', 'jasmine']
    },
    jquery: {
        exports: '$'
    },
    leaflet: {
        exports: 'L'
    },
    'leaflet-markercluster': {
        deps: ['leaflet']
    }
  },
  urlArgs: "_=" +  (new Date()).getTime()
});
<commit_msg>Fix path to CollectionMapView module in requirejs.conf 'include'<commit_after>requirejs.config({
  baseUrl: '/',
  include: [
    'streamhub-map/views/collection-map-view',
    'streamhub-hot-collections-tests/mocks/streams/mock-hot-collections',
    'json!streamhub-hot-collections-tests/mocks/clients/hot-collections-response.json'
  ],
  paths: {
    jquery: 'lib/jquery/jquery',
	jasmine: 'lib/jasmine/lib/jasmine-core/jasmine',
    'jasmine-html': 'lib/jasmine/lib/jasmine-core/jasmine-html',
    'jasmine-jquery': 'lib/jasmine-jquery/lib/jasmine-jquery',
    text: 'lib/requirejs-text/text',
    hgn: 'lib/requirejs-hogan-plugin/hgn',
    hogan: 'lib/hogan/web/builds/2.0.0/hogan-2.0.0.amd',
    json: 'lib/requirejs-plugins/src/json',
    base64: 'lib/base64/base64',
    'event-emitter': 'lib/event-emitter/src/event-emitter',
    inherits: 'lib/inherits/inherits',
    leaflet: 'lib/leaflet/leaflet-src',
    'leaflet-css': 'lib/leaflet/leaflet.css',
    'leaflet-markercluster': 'lib/leaflet-markercluster/dist/leaflet.markercluster-src',
    'leaflet-markercluster-css': 'lib/leaflet-markercluster/dist/MarkerCluster.css',
  },
  packages: [{
    name: "streamhub-sdk",
    location: "lib/streamhub-sdk/src/"
  },{
    name: "streamhub-sdk/auth",
    location: "lib/streamhub-sdk/src/auth"
  },{
    name: "streamhub-sdk/collection",
    location: "lib/streamhub-sdk/src/collection"
  },{
    name: "streamhub-sdk/content",
    location: "lib/streamhub-sdk/src/content"
  },{
    name: "streamhub-sdk/modal",
    location: "lib/streamhub-sdk/src/modal"
  },{
    name: "streamhub-sdk-tests",
    location: "lib/streamhub-sdk/tests/"
  },{
    name: "stream",
    location: "lib/stream/src"
  },{
	name: "streamhub-map",
  	location: "src"
  },{
    name: "streamhub-map-resources",
    location: "src/resources/"
  },{
    name: "streamhub-hot-collections",
    location: "lib/streamhub-hot-collections/src/"
  },{
    name: "streamhub-hot-collections-tests",
    location: "lib/streamhub-hot-collections/tests/"
  },{
    name: "streamhub-metrics",
    location: "lib/streamhub-metrics/src/"
  },{
    name: "view",
    location: "lib/view/src",
    main: "view"
  }],
  shim: {
    jasmine: {
      exports: 'jasmine'
    },
    'jasmine-html': {
      deps: ['jasmine'],
      exports: 'jasmine'
    },
    'jasmine-jquery': {
      deps: ['jquery', 'jasmine']
    },
    jquery: {
        exports: '$'
    },
    leaflet: {
        exports: 'L'
    },
    'leaflet-markercluster': {
        deps: ['leaflet']
    }
  },
  urlArgs: "_=" +  (new Date()).getTime()
});
<|endoftext|>


<commit_before>requirejs.config({
  baseUrl: '/',
  include: [
    'streamhub-wall',
    'streamhub-multiview',
    'streamhub-map/views/solar-terminator-view',
    'streamhub-map/collections/collection-point-transform',
    'streamhub-hot-collections-tests/mocks/streams/mock-hot-collections'],
  paths: {
    jquery: 'lib/jquery/jquery',
	jasmine: 'lib/jasmine/lib/jasmine-core/jasmine',
    'jasmine-html': 'lib/jasmine/lib/jasmine-core/jasmine-html',
    'jasmine-jquery': 'lib/jasmine-jquery/lib/jasmine-jquery',
    text: 'lib/requirejs-text/text',
    hgn: 'lib/requirejs-hogan-plugin/hgn',
    hogan: 'lib/hogan/web/builds/2.0.0/hogan-2.0.0.amd',
    json: 'lib/requirejs-plugins/src/json',
    base64: 'lib/base64/base64',
    'event-emitter': 'lib/event-emitter/src/event-emitter',
    inherits: 'lib/inherits/inherits',
    d3: 'lib/d3/d3',
    colorbrewer: 'lib/colorbrewer/colorbrewer',
    topojson: 'lib/topojson/topojson'
  },
  packages: [{
    name: "streamhub-sdk",
    location: "lib/streamhub-sdk/src/"
  },{
    name: "streamhub-sdk/auth",
    location: "lib/streamhub-sdk/src/auth"
  },{
    name: "streamhub-sdk/collection",
    location: "lib/streamhub-sdk/src/collection"
  },{
    name: "streamhub-sdk/content",
    location: "lib/streamhub-sdk/src/content"
  },{
    name: "streamhub-sdk/modal",
    location: "lib/streamhub-sdk/src/modal"
  },{
    name: "streamhub-sdk-tests",
    location: "lib/streamhub-sdk/tests/"
  },{
    name: "stream",
    location: "lib/stream/src"
  },{
	name: "streamhub-map",
  	location: "./src"
  },{
    name: "streamhub-map-resources",
    location: "./resources/"
  },{
    name: "streamhub-hot-collections",
    location: "lib/streamhub-hot-collections/src/"
  },{
    name: "streamhub-hot-collections-tests",
    location: "lib/streamhub-hot-collections/tests"
  },{
    name: "streamhub-metrics",
    location: "lib/streamhub-metrics/src/"
  },{
    name: "streamhub-multiview",
    location: "lib/streamhub-multiview/src/"
  },{
    name: "streamhub-wall",
    location: "lib/streamhub-wall/src/"
  }],
  shim: {
    jasmine: {
      exports: 'jasmine'
    },
    'jasmine-html': {
      deps: ['jasmine'],
      exports: 'jasmine'
    },
    'jasmine-jquery': {
      deps: ['jquery', 'jasmine']
    },
    jquery: {
        exports: '$'
    },
    d3: {
        exports: 'd3'
    },
    colorbrewer: {
        exports: 'colorbrewer'
    },
    topojson: {
        exports: 'topojson'
    }
  },
  urlArgs: "_=" +  (new Date()).getTime()
});
<commit_msg>Remove relative paths in packages section<commit_after>requirejs.config({
  baseUrl: '/',
  include: [
    'streamhub-wall',
    'streamhub-multiview',
    'streamhub-map/views/solar-terminator-view',
    'streamhub-map/collections/collection-point-transform',
    'streamhub-hot-collections-tests/mocks/streams/mock-hot-collections'],
  paths: {
    jquery: 'lib/jquery/jquery',
	jasmine: 'lib/jasmine/lib/jasmine-core/jasmine',
    'jasmine-html': 'lib/jasmine/lib/jasmine-core/jasmine-html',
    'jasmine-jquery': 'lib/jasmine-jquery/lib/jasmine-jquery',
    text: 'lib/requirejs-text/text',
    hgn: 'lib/requirejs-hogan-plugin/hgn',
    hogan: 'lib/hogan/web/builds/2.0.0/hogan-2.0.0.amd',
    json: 'lib/requirejs-plugins/src/json',
    base64: 'lib/base64/base64',
    'event-emitter': 'lib/event-emitter/src/event-emitter',
    inherits: 'lib/inherits/inherits',
    d3: 'lib/d3/d3',
    colorbrewer: 'lib/colorbrewer/colorbrewer',
    topojson: 'lib/topojson/topojson'
  },
  packages: [{
    name: "streamhub-sdk",
    location: "lib/streamhub-sdk/src/"
  },{
    name: "streamhub-sdk/auth",
    location: "lib/streamhub-sdk/src/auth"
  },{
    name: "streamhub-sdk/collection",
    location: "lib/streamhub-sdk/src/collection"
  },{
    name: "streamhub-sdk/content",
    location: "lib/streamhub-sdk/src/content"
  },{
    name: "streamhub-sdk/modal",
    location: "lib/streamhub-sdk/src/modal"
  },{
    name: "streamhub-sdk-tests",
    location: "lib/streamhub-sdk/tests/"
  },{
    name: "stream",
    location: "lib/stream/src"
  },{
	name: "streamhub-map",
  	location: "src"
  },{
    name: "streamhub-map-resources",
    location: "resources/"
  },{
    name: "streamhub-hot-collections",
    location: "lib/streamhub-hot-collections/src/"
  },{
    name: "streamhub-hot-collections-tests",
    location: "lib/streamhub-hot-collections/tests"
  },{
    name: "streamhub-metrics",
    location: "lib/streamhub-metrics/src/"
  },{
    name: "streamhub-multiview",
    location: "lib/streamhub-multiview/src/"
  },{
    name: "streamhub-wall",
    location: "lib/streamhub-wall/src/"
  }],
  shim: {
    jasmine: {
      exports: 'jasmine'
    },
    'jasmine-html': {
      deps: ['jasmine'],
      exports: 'jasmine'
    },
    'jasmine-jquery': {
      deps: ['jquery', 'jasmine']
    },
    jquery: {
        exports: '$'
    },
    d3: {
        exports: 'd3'
    },
    colorbrewer: {
        exports: 'colorbrewer'
    },
    topojson: {
        exports: 'topojson'
    }
  },
  urlArgs: "_=" +  (new Date()).getTime()
});
<|endoftext|>


<commit_before>import * as utils from "../utils.js";
let params = {
  width: 1200,
  height: 356,
  ctx: null,
  points: [],
  target: null,
  canvasTop: null,
  animateHeader: true
};

const point1 = {
  x: 73.74925795996039,
  originX: 73.74925795996039,
  y: 47.151927550054076,
  originY: 47.151927550054076,
  closest: [
    {
      x: 73.74925795996039,
      originX: 73.74925795996039,
      y: 47.151927550054076,
      originY: 47.151927550054076,
      closest: [],
      active: 0.4
    },
    {
      x: 83.74925795996039,
      originX: 83.74925795996039,
      y: 57.151927550054076,
      originY: 57.151927550054076,
      closest: [],
      active: 0.4
    },
    {
      x: 93.74925795996039,
      originX: 93.74925795996039,
      y: 67.151927550054076,
      originY: 67.151927550054076,
      closest: [],
      active: 0.4
    }
  ],
  active: 0.4
};

const point2 = {
  x: 83.74925795996039,
  originX: 83.74925795996039,
  y: 57.151927550054076,
  originY: 57.151927550054076,
  closest: [
    {
      x: 83.74925795996039,
      originX: 78.74925795996039,
      y: 57.151927550054076,
      originY: 57.151927550054076,
      closest: [],
      active: 0.4
    }
  ],
  active: 0.4
};

function CtxMock() {
  this.beginPathCounter = 0;
  this.moveToCounter = 0;
  this.lineToCounter = 0;
  this.strokeStyle = null;
  this.strokeCounter = 0;
}

CtxMock.prototype.beginPath = function() {
  this.beginPathCounter += 1;
};

CtxMock.prototype.moveTo = function() {
  this.moveToCounter += 1;
};

CtxMock.prototype.lineTo = function() {
  this.lineToCounter += 1;
};

CtxMock.prototype.stroke = function() {
  this.strokeCounter += 1;
};

describe("calcPointsLimiter function", () => {
  it("should calc a number based on height and width", () => {
    const pointsLimiter = utils.calcPointsLimiter(params.width, params.height);

    expect(pointsLimiter).toEqual(7.12);
  });

  it("should return no less than 6 on smaller screens", () => {
    const smallScreen = { width: 400, height: 356 };

    const pointsLimiter = utils.calcPointsLimiter(
      smallScreen.width,
      smallScreen.height
    );

    expect(pointsLimiter).toBeGreaterThanOrEqual(6);
  });
});

describe("drawLines function", () => {
  it("should call the canvas functions for each point passed in", () => {
    const ctx = new CtxMock();
    const numOfPoints = point1.closest.length;

    expect(ctx.beginPathCounter).toEqual(0);
    expect(ctx.moveToCounter).toEqual(0);
    expect(ctx.lineToCounter).toEqual(0);
    expect(ctx.strokeStyle).toEqual(null);
    expect(ctx.strokeCounter).toEqual(0);

    utils.drawLines(point1, ctx);

    expect(ctx.beginPathCounter).toEqual(numOfPoints);
    expect(ctx.moveToCounter).toEqual(numOfPoints);
    expect(ctx.lineToCounter).toEqual(numOfPoints);
    expect(ctx.strokeStyle).toEqual("rgba(94, 161, 184,0.4)");
    expect(ctx.strokeCounter).toEqual(numOfPoints);
  });
});

describe("getDistance function", () => {
  it("should calculate distance between 2 points using hypot as default method", () => {
    const distance = utils.getDistance(point1, point2);

    expect(distance).toEqual(141.4213562373095);
    expect(global.Math.hypot).toBeDefined();
  });

  it("should use sqrt method to calculate distance between 2 points using sqrt as fallback", () => {
    global.Math.hypot = undefined;
    global.Math.sqrt = jest.fn();
    const distance = utils.getDistance(point1, point2);

    expect(global.Math.hypot).toBeUndefined();
    expect(global.Math.sqrt.mock.calls.length).toBe(1);
  });
});

describe("shiftPoint function", () => {
  it("should call shiftMethod method once", () => {
    const TweenLite = {};
    TweenLite.to = jest.fn();
    const ease = {};
    utils.shiftPoint({}, ease, TweenLite.to);

    expect(TweenLite.to.mock.calls.length).toBe(1);
  });
});
<commit_msg>update getDistance fallback test (fix-bug)<commit_after>import * as utils from "../utils.js";
let params = {
  width: 1200,
  height: 356,
  ctx: null,
  points: [],
  target: null,
  canvasTop: null,
  animateHeader: true
};

const point1 = {
  x: 73.74925795996039,
  originX: 73.74925795996039,
  y: 47.151927550054076,
  originY: 47.151927550054076,
  closest: [
    {
      x: 73.74925795996039,
      originX: 73.74925795996039,
      y: 47.151927550054076,
      originY: 47.151927550054076,
      closest: [],
      active: 0.4
    },
    {
      x: 83.74925795996039,
      originX: 83.74925795996039,
      y: 57.151927550054076,
      originY: 57.151927550054076,
      closest: [],
      active: 0.4
    },
    {
      x: 93.74925795996039,
      originX: 93.74925795996039,
      y: 67.151927550054076,
      originY: 67.151927550054076,
      closest: [],
      active: 0.4
    }
  ],
  active: 0.4
};

const point2 = {
  x: 83.74925795996039,
  originX: 83.74925795996039,
  y: 57.151927550054076,
  originY: 57.151927550054076,
  closest: [
    {
      x: 83.74925795996039,
      originX: 78.74925795996039,
      y: 57.151927550054076,
      originY: 57.151927550054076,
      closest: [],
      active: 0.4
    }
  ],
  active: 0.4
};

function CtxMock() {
  this.beginPathCounter = 0;
  this.moveToCounter = 0;
  this.lineToCounter = 0;
  this.strokeStyle = null;
  this.strokeCounter = 0;
}

CtxMock.prototype.beginPath = function() {
  this.beginPathCounter += 1;
};

CtxMock.prototype.moveTo = function() {
  this.moveToCounter += 1;
};

CtxMock.prototype.lineTo = function() {
  this.lineToCounter += 1;
};

CtxMock.prototype.stroke = function() {
  this.strokeCounter += 1;
};

describe("calcPointsLimiter function", () => {
  it("should calc a number based on height and width", () => {
    const pointsLimiter = utils.calcPointsLimiter(params.width, params.height);

    expect(pointsLimiter).toEqual(7.12);
  });

  it("should return no less than 6 on smaller screens", () => {
    const smallScreen = { width: 400, height: 356 };

    const pointsLimiter = utils.calcPointsLimiter(
      smallScreen.width,
      smallScreen.height
    );

    expect(pointsLimiter).toBeGreaterThanOrEqual(6);
  });
});

describe("drawLines function", () => {
  it("should call the canvas functions for each point passed in", () => {
    const ctx = new CtxMock();
    const numOfPoints = point1.closest.length;

    expect(ctx.beginPathCounter).toEqual(0);
    expect(ctx.moveToCounter).toEqual(0);
    expect(ctx.lineToCounter).toEqual(0);
    expect(ctx.strokeStyle).toEqual(null);
    expect(ctx.strokeCounter).toEqual(0);

    utils.drawLines(point1, ctx);

    expect(ctx.beginPathCounter).toEqual(numOfPoints);
    expect(ctx.moveToCounter).toEqual(numOfPoints);
    expect(ctx.lineToCounter).toEqual(numOfPoints);
    expect(ctx.strokeStyle).toEqual("rgba(94, 161, 184,0.4)");
    expect(ctx.strokeCounter).toEqual(numOfPoints);
  });
});

describe("getDistance function", () => {
  it("should calculate distance between 2 points using hypot as default method", () => {
    const distance = utils.getDistance(point1, point2);

    expect(distance).toEqual(141.4213562373095);
    expect(global.Math.hypot).toBeDefined();
  });

  it("should use sqrt method to calculate distance between 2 points using sqrt as fallback", () => {
    const backupHypot = global.Math.hypot;
    const backupSqrt = global.Math.sqrt;
    const hypotMock = jest.fn(global.Math.hypot);
    const sqrtMock = jest.fn(global.Math.sqrt);

    delete global.Math.hypot;
    global.Math.sqrt = sqrtMock;

    const distance = utils.getDistance(point1, point2);

    expect(global.Math.hypot).toBeUndefined();
    expect(sqrtMock.mock.calls.length).toBe(1);

    global.Math.hypot = backupHypot;
    global.Math.sqrt = backupSqrt;
  });
});

describe("shiftPoint function", () => {
  it("should call shiftMethod method once", () => {
    const TweenLite = {};
    TweenLite.to = jest.fn();
    const ease = {};
    utils.shiftPoint({}, ease, TweenLite.to);

    expect(TweenLite.to.mock.calls.length).toBe(1);
  });
});
<|endoftext|>


<commit_before>
// [START app]
'use strict';

// [START setup]

var express = require('express');

var app = express();
var google = require('googleapis');
//var bigquery = google.bigquery('v2');

app.enable('trust proxy');

var Datastore = require('@google-cloud/datastore');
//const BigQuery = require('@google-cloud/bigquery');
const projectId = "doolinhomeiot";
const datasetId = "OfficeData";
const tableId = "iotdata";

// Instantiate a datastore client
var datastore = Datastore();

var PubSub = require('@google-cloud/pubsub');

//Instantiate a pubsub client
var pubsub = PubSub();

var PUBSUB_VERIFICATION_TOKEN = process.env.PUBSUB_VERIFICATION_TOKEN;

var topic = pubsub.topic(process.env.PUBSUB_TOPIC);

var subscription = pubsub.subscription(process.env.PUBSUB_SUBSCRIPTION_NAME);

// [END setup]

function storeEvent(message) {
    var key = datastore.key('officedata');
    key.identifier = "id"
    // You can uncomment some of the other things if you want to store them in the database

    var obj = {
        messageid: message.id
        //deviceid: message.attributes.device_id,
        ////event: message.attributes.event,
        //published: message.attributes.published_at,
        //data: message.data
    }
    datastore.save(
        {
            key: key,
            data: obj
        }, function (err) {
            if (err) {
                console.log('There was an error storing the event', err);
            }
            console.log('stored in datastore', obj);
            console.log('Begin BIGQUERY:');
            var content = {"nameid": "789", "messagedata": "test1k"};
            //console.log('content:' + content);
            //let rows = null;
            //try {
            //    var rows = JSON.parse(content)
            //} catch (err) {
           //}
        insertRowsAsStream(datasetId,tableId,rows,projectId)
        }
    );

}

function insertRowsAsStream (datasetId, tableId, rows, projectId) {
    // [START bigquery_insert_stream]
    // Imports the Google Cloud client library
    const BigQuery = require('@google-cloud/bigquery');

    // Instantiates a client
    const bigquery = BigQuery({
        projectId: projectId
    });

    // Inserts data into a table
    bigquery
        .dataset(datasetId)
        .table(tableId)
        .insert(rows)
        .then((insertErrors) => {
        console.log('Inserted:');
    rows.forEach((row) => console.log(row));

    if (insertErrors && insertErrors.length > 0) {
        console.log('Insert errors:');
        insertErrors.forEach((err) => console.error(err));
    }
})
.catch((err) => {
        console.error('ERROR:', err);
});
    // [END bigquery_insert_stream]
}

subscription.on('message', function (message) {
    console.log('event received', message);
    // Called every time a message is received.
    // message.id = ID used to acknowledge its receival.
    // message.data = Contents of the message.
    // message.attributes = Attributes of the message.
    storeEvent(message);
    message.ack();
});

// [START listen]
var server = app.listen(process.env.PORT || 8080, function () {
    console.log('App listening on port %s', server.address().port);
    console.log('Press Ctrl+C to quit.');
});
// [END listen]
// [END app]

module.exports = app;
<commit_msg>Update app.js<commit_after>
// [START app]
'use strict';

// [START setup]

var express = require('express');

var app = express();
var google = require('googleapis');
//var bigquery = google.bigquery('v2');

app.enable('trust proxy');

var Datastore = require('@google-cloud/datastore');
//const BigQuery = require('@google-cloud/bigquery');
const projectId = "doolinhomeiot";
const datasetId = "OfficeData";
const tableId = "iotdata";

// Instantiate a datastore client
var datastore = Datastore();

var PubSub = require('@google-cloud/pubsub');

//Instantiate a pubsub client
var pubsub = PubSub();

var PUBSUB_VERIFICATION_TOKEN = process.env.PUBSUB_VERIFICATION_TOKEN;

var topic = pubsub.topic(process.env.PUBSUB_TOPIC);

var subscription = pubsub.subscription(process.env.PUBSUB_SUBSCRIPTION_NAME);

// [END setup]

function storeEvent(message) {
    var key = datastore.key('officedata');
    key.identifier = "id"
    // You can uncomment some of the other things if you want to store them in the database

    var obj = {
        messageid: message.id
        //deviceid: message.attributes.device_id,
        ////event: message.attributes.event,
        //published: message.attributes.published_at,
        //data: message.data
    }
    datastore.save(
        {
            key: key,
            data: obj
        }, function (err) {
            if (err) {
                console.log('There was an error storing the event', err);
            }
            console.log('stored in datastore', obj);
            console.log('Begin BIGQUERY:');
            var content = {"nameid": "789", "messagedata": "test1k"};
            //console.log('content:' + content);
            //let rows = null;
            //try {
            //    var rows = JSON.parse(content)
            //} catch (err) {
           //}
        insertRowsAsStream(datasetId,tableId,content,projectId)
        }
    );

}

function insertRowsAsStream (datasetId, tableId, rows, projectId) {
    // [START bigquery_insert_stream]
    // Imports the Google Cloud client library
    const BigQuery = require('@google-cloud/bigquery');

    // Instantiates a client
    const bigquery = BigQuery({
        projectId: projectId
    });

    // Inserts data into a table
    bigquery
        .dataset(datasetId)
        .table(tableId)
        .insert(rows)
        .then((insertErrors) => {
        console.log('Inserted:');
    rows.forEach((row) => console.log(row));

    if (insertErrors && insertErrors.length > 0) {
        console.log('Insert errors:');
        insertErrors.forEach((err) => console.error(err));
    }
})
.catch((err) => {
        console.error('ERROR:', err);
});
    // [END bigquery_insert_stream]
}

subscription.on('message', function (message) {
    console.log('event received', message);
    // Called every time a message is received.
    // message.id = ID used to acknowledge its receival.
    // message.data = Contents of the message.
    // message.attributes = Attributes of the message.
    storeEvent(message);
    message.ack();
});

// [START listen]
var server = app.listen(process.env.PORT || 8080, function () {
    console.log('App listening on port %s', server.address().port);
    console.log('Press Ctrl+C to quit.');
});
// [END listen]
// [END app]

module.exports = app;
<|endoftext|>


<commit_before>var myPlaylist;

function save(key, object) {
	localStorage.setItem(key, JSON.stringify(object));
}

function load(key) {
	return JSON.parse(localStorage.getItem(key));
}

function loadPlaylist() {
	$.ajax('/playlist').done(function(playlist) {

		myPlaylist.setPlaylist(playlist);

		var currentVideo = load('currentVideo');
		if (currentVideo) {
			var candidate = myPlaylist.playlist[currentVideo.index];
			if (candidate && candidate.filename == currentVideo.filename) {
				if (currentVideo.ended && myPlaylist.playlist.length - currentVideo.index > 1) {
					myPlaylist.select(currentVideo.index + 1);
				} else {
					myPlaylist.select(currentVideo.index);
				}
			} else {
				localStorage.removeItem('currentVideo');
			}
		}

		// Sroll to Current
		$('li.jp-playlist-current').each(function() { this.scrollIntoView() });

		$('#videoContainer').bind($.jPlayer.event.play, function(e) {
			var currentVideo = myPlaylist.playlist[myPlaylist.current];
			if (currentVideo) {
				save('currentVideo', currentVideo);
			}

			var lastVideo = myPlaylist.playlist[myPlaylist.playlist.length - 1];
			$.ajax('/playlist?start=' + lastVideo.title).done(function(partialPlaylist) {
				partialPlaylist.forEach(function(v) {
					myPlaylist.add(v);
				});
			});

			$('li.jp-playlist-current').each(function() { this.scrollIntoView() });
		});

		$('#videoContainer').bind($.jPlayer.event.ended, function(e) {
			var currentVideo = load('currentVideo');
			if (currentVideo) {
				currentVideo.ended = true;
				save('currentVideo', currentVideo);
			}
		});
	});
}

$(document).ready(function() {
	myPlaylist = new jPlayerPlaylist({ jPlayer: "#jquery_jplayer_N", cssSelectorAncestor: "#videoContainer" }, [], {
		playlistOptions: {
			displayTime: 0
		},
		supplied: "m4v",
		useStateClassSkin: true,
		autoBlur: false,
		smoothPlayBar: false,
		keyEnabled: false,
		size: {	width: 800, height: 448, cssClass: "jp-video-480p" },
		ready: loadPlaylist
	});
});
<commit_msg>Player Adjustments<commit_after>var myPlaylist;

function save(key, object) {
	localStorage.setItem(key, JSON.stringify(object));
}

function load(key) {
	return JSON.parse(localStorage.getItem(key));
}

function loadPlaylist() {
	$.ajax('/playlist').done(function(playlist) {

		myPlaylist.setPlaylist(playlist);

		var currentVideo = load('currentVideo');
		if (currentVideo) {
			var candidate = myPlaylist.playlist[currentVideo.index];
			if (candidate && candidate.filename == currentVideo.filename) {
				if (currentVideo.ended && myPlaylist.playlist.length - currentVideo.index > 1) {
					myPlaylist.select(currentVideo.index + 1);
				} else {
					myPlaylist.select(currentVideo.index);
				}
			} else {
				localStorage.removeItem('currentVideo');
			}
		}

		// Sroll to Current
		$('li.jp-playlist-current').each(function() { this.scrollIntoView() });

		$('#videoContainer').bind($.jPlayer.event.play, function(e) {
			var currentVideo = myPlaylist.playlist[myPlaylist.current];
			if (currentVideo) {
				save('currentVideo', currentVideo);
			}

			var lastVideo = myPlaylist.playlist[myPlaylist.playlist.length - 1];
			$.ajax('/playlist?start=' + lastVideo.filename).done(function(partialPlaylist) {
				partialPlaylist.forEach(function(v) {
					myPlaylist.add(v);
				});
			});

			$('li.jp-playlist-current').each(function() { this.scrollIntoView() });
		});

		$('#videoContainer').bind($.jPlayer.event.ended, function(e) {
			var currentVideo = load('currentVideo');
			if (currentVideo) {
				currentVideo.ended = true;
				save('currentVideo', currentVideo);
			}
		});
	});
}

$(document).ready(function() {
	myPlaylist = new jPlayerPlaylist({ jPlayer: "#jquery_jplayer_N", cssSelectorAncestor: "#videoContainer" }, [], {
		playlistOptions: {
			displayTime: 0
		},
		supplied: "m4v",
		useStateClassSkin: true,
		autoBlur: false,
		smoothPlayBar: false,
		keyEnabled: false,
		size: {	width: 800, height: 448, cssClass: "jp-video-480p" },
		ready: loadPlaylist
	});
});
<|endoftext|>


<commit_before>require([
    'jquery',
    'underscore',
    'knockout',
    'knockout-mapping',
    'views/graph-page-view',
    'graph-settings-data'
], function($, _, ko, koMapping, PageView, data) {
    var resourceJSON = JSON.stringify(data.resources);
    data.resources.forEach(function(resource) {
        resource.isRelatable = ko.observable(resource.is_relatable);
    });
    var srcJSON = JSON.stringify(data.metadata);
    var metadata = koMapping.fromJS(data.metadata);
    var dirty = ko.observable(false);
    var dirtyInitialized = false;
    ko.computed(function () {
        if (!dirtyInitialized) {
            ko.toJS(metadata);
            ko.toJS(data.resources);
            dirtyInitialized = true;
            return;
        }
        dirty(true);
    });
    var resetDirty = function () {
        dirtyInitialized = false;
        dirty(false);
    };
    var iconFilter = ko.observable('');
    var viewModel = {
        dirty: dirty,
        iconFilter: iconFilter,
        icons: ko.computed(function () {
            return _.filter(data.icons, function (icon) {
                return icon.name.indexOf(iconFilter()) >= 0;
            });
        }),
        metadata: metadata,
        resources: data.resources,
        ontologies: data.ontologies,
        ontologyClass: ko.observable(data.node.ontologyclass),
        ontologyClasses: ko.computed(function () {
            return _.filter(data.ontologyClasses, function (ontologyClass) {
                return ontologyClass.ontology_id === metadata.ontology_id();
            });
        }),
        isResource: ko.computed({
            read: function() {
                return metadata.isresource().toString();
            },
            write: function(value) {
                metadata.isresource(value === "true");
            }
        }),
        isActive: ko.computed({
            read: function() {
                return metadata.isactive().toString();
            },
            write: function(value) {
                metadata.isactive(value === "true");
            }
        }),
        save: function () {
            pageView.viewModel.loading(true);
            var relatableResourceIds = _.filter(data.resources, function(resource){
                return resource.isRelatable();
            }).map(function(resource){
                return resource.id
            });
            if (metadata.ontology_id() === undefined) {
                metadata.ontology_id(null);
            }
            $.ajax({
                type: "POST",
                url: '',
                data: JSON.stringify({
                    metadata: koMapping.toJS(metadata),
                    relatable_resource_ids: relatableResourceIds,
                    ontology_class: viewModel.ontologyClass()
                }),
                success: function(response) {
                    resetDirty();
                    pageView.viewModel.loading(false);
                },
                failure: function(response) {
                    pageView.viewModel.loading(false);
                }
            });
        },
        reset: function () {
            _.each(JSON.parse(srcJSON), function(value, key) {
                metadata[key](value);
            });
            JSON.parse(resourceJSON).forEach(function(jsonResource) {
                var resource = _.find(data.resources, function (resource) {
                    return resource.id === jsonResource.id;
                });
                resource.isRelatable(jsonResource.is_relatable);
            });
            resetDirty();
        }
    };

    var pageView = new PageView({
        viewModel: viewModel
    });
});
<commit_msg>re: #459<commit_after>require([
    'jquery',
    'underscore',
    'knockout',
    'knockout-mapping',
    'views/graph-page-view',
    'graph-settings-data'
], function($, _, ko, koMapping, PageView, data) {
    /**
    * prep data for models
    */
    var resourceJSON = JSON.stringify(data.resources);
    data.resources.forEach(function(resource) {
        resource.isRelatable = ko.observable(resource.is_relatable);
    });
    var srcJSON = JSON.stringify(data.metadata);

    /**
    * setting up page view model
    */
    var metadata = koMapping.fromJS(data.metadata);
    var dirty = ko.observable(false);
    var dirtyInitialized = false;
    ko.computed(function () {
        if (!dirtyInitialized) {
            ko.toJS(metadata);
            ko.toJS(data.resources);
            dirtyInitialized = true;
            return;
        }
        dirty(true);
    });
    var resetDirty = function () {
        dirtyInitialized = false;
        dirty(false);
    };
    var iconFilter = ko.observable('');
    var viewModel = {
        dirty: dirty,
        iconFilter: iconFilter,
        icons: ko.computed(function () {
            return _.filter(data.icons, function (icon) {
                return icon.name.indexOf(iconFilter()) >= 0;
            });
        }),
        metadata: metadata,
        resources: data.resources,
        ontologies: data.ontologies,
        ontologyClass: ko.observable(data.node.ontologyclass),
        ontologyClasses: ko.computed(function () {
            return _.filter(data.ontologyClasses, function (ontologyClass) {
                return ontologyClass.ontology_id === metadata.ontology_id();
            });
        }),
        isResource: ko.computed({
            read: function() {
                return metadata.isresource().toString();
            },
            write: function(value) {
                metadata.isresource(value === "true");
            }
        }),
        isActive: ko.computed({
            read: function() {
                return metadata.isactive().toString();
            },
            write: function(value) {
                metadata.isactive(value === "true");
            }
        }),
        save: function () {
            pageView.viewModel.loading(true);
            var relatableResourceIds = _.filter(data.resources, function(resource){
                return resource.isRelatable();
            }).map(function(resource){
                return resource.id
            });
            if (metadata.ontology_id() === undefined) {
                metadata.ontology_id(null);
            }
            $.ajax({
                type: "POST",
                url: '',
                data: JSON.stringify({
                    metadata: koMapping.toJS(metadata),
                    relatable_resource_ids: relatableResourceIds,
                    ontology_class: viewModel.ontologyClass()
                }),
                success: function(response) {
                    resetDirty();
                    pageView.viewModel.loading(false);
                },
                failure: function(response) {
                    pageView.viewModel.loading(false);
                }
            });
        },
        reset: function () {
            _.each(JSON.parse(srcJSON), function(value, key) {
                metadata[key](value);
            });
            JSON.parse(resourceJSON).forEach(function(jsonResource) {
                var resource = _.find(data.resources, function (resource) {
                    return resource.id === jsonResource.id;
                });
                resource.isRelatable(jsonResource.is_relatable);
            });
            resetDirty();
        }
    };

    /**
    * a GraphPageView representing the graph settings page
    */
    var pageView = new PageView({
        viewModel: viewModel
    });
});
<|endoftext|>


<commit_before>/* eslint-disable no-param-reassign, no-continue, no-console */

const fs = require('fs-extra');
const path = require('path');
const recursiveRead = require('recursive-readdir');

const ENVIRONMENTS = require('../../../constants/environments');
const { ENABLED_ENVIRONMENTS } = require('../../../constants/drupals');
const { logDrupal: log } = require('./utilities-drupal');
const getApiClient = require('./api');
const convertDrupalFilesToLocal = require('./assets');
const { compilePage, createFileObj } = require('./page');
const {
  createHealthCareRegionListPages,
  createPastEventListPages,
  addGetUpdatesFields,
  addPager,
  sortServices,
} = require('./health-care-region');

const { addHubIconField } = require('./benefit-hub');
const { addHomeContent } = require('./home');

const DRUPAL_CACHE_FILENAME = 'drupal/pages.json';
const DRUPAL_HUB_NAV_FILENAME = 'hubNavNames.json';

// If "--pull-drupal" is passed into the build args, then the build
// should pull the latest Drupal data.
const PULL_DRUPAL_BUILD_ARG = 'pull-drupal';
// If "--use-cms-export" is passed into the build args, then the build
// should use the files in the cms-export directory
const USE_CMS_EXPORT_BUILD_ARG = 'use-cms-export';
const CMS_EXPORT_DIR_BUILD_ARG = 'cms-export-dir';
const CMS_EXPORT_CACHE_FILENAME =
  '.cache/localhost/drupal/pagesTransformed.json';

const getDrupalCachePath = buildOptions =>
  buildOptions[USE_CMS_EXPORT_BUILD_ARG]
    ? buildOptions[CMS_EXPORT_DIR_BUILD_ARG]
    : path.join(buildOptions.cacheDirectory, DRUPAL_CACHE_FILENAME);

// We need to pull the Drupal content if we have --pull-drupal or --use-cms-export, OR if
// the content is not available in the cache.
const shouldPullDrupal = buildOptions =>
  buildOptions[PULL_DRUPAL_BUILD_ARG] ||
  !fs.existsSync(getDrupalCachePath(buildOptions));

function pipeDrupalPagesIntoMetalsmith(contentData, files) {
  const pages = contentData.data.nodeQuery.entities.filter(
    e => e && Object.keys(e).length,
  );

  for (const page of pages) {
    const {
      entityUrl: { path: drupalUrl },
      entityBundle,
    } = page;

    const pageCompiled = compilePage(page, contentData);
    const drupalPageDir = path.join('.', drupalUrl);
    const drupalFileName = path.join(drupalPageDir, 'index.html');

    switch (page.entityBundle) {
      case 'health_care_local_facility':
        addGetUpdatesFields(pageCompiled, pages);
        break;
      case 'health_care_region_detail_page':
        addGetUpdatesFields(pageCompiled, pages);
        break;
      case 'event_listing':
        pageCompiled.pastEventTeasers = pageCompiled.pastEvents;
        pageCompiled.allEventTeasers = pageCompiled.reverseFieldListingNode;
        addPager(
          pageCompiled,
          files,
          pageCompiled.allEventTeasers,
          'event_listing.drupal.liquid',
          'event',
        );
        break;
      case 'story_listing':
        pageCompiled.allNewsStoryTeasers = page.reverseFieldListingNode;
        addPager(
          pageCompiled,
          files,
          pageCompiled.allNewsStoryTeasers,
          'story_listing.drupal.liquid',
          'story',
        );
        break;
      case 'press_releases_listing':
        pageCompiled.allPressReleaseTeasers = page.reverseFieldListingNode;
        addPager(
          pageCompiled,
          files,
          pageCompiled.allPressReleaseTeasers,
          'press_releases_listing.drupal.liquid',
          'press_release',
        );
        break;
      case 'health_services_listing':
        pageCompiled.clinicalHealthServices = sortServices(
          pageCompiled.fieldOffice.entity.reverseFieldRegionPageNode.entities,
        );
        break;
      case 'leadership_listing':
        pageCompiled.allStaffProfiles = page.fieldLeadership;
        addPager(
          pageCompiled,
          files,
          pageCompiled.allStaffProfiles,
          'leadership_listing.drupal.liquid',
          'bio',
        );
        break;
      case 'page':
        addHubIconField(pageCompiled, pages);
        break;
      default:
    }

    files[drupalFileName] = createFileObj(
      pageCompiled,
      `${entityBundle}.drupal.liquid`,
    );

    if (page.entityBundle === 'health_care_region_page') {
      createHealthCareRegionListPages(pageCompiled, drupalPageDir, files);
    }
    if (page.entityBundle === 'event_listing') {
      createPastEventListPages(pageCompiled, drupalPageDir, files);
    }
  }
}

/**
 * Uses Drupal content via a new GraphQL query or the cached result of a
 * previous query. This is where the cache is saved.
 *
 * @param {Object} buildOptions
 * @return {Object} - The result of the GraphQL query
 */
async function getContentViaGraphQL(buildOptions) {
  const contentApi = getApiClient(buildOptions);
  const drupalCache = getDrupalCachePath(buildOptions);
  const drupalHubMenuNames = path.join(
    buildOptions.paramsDirectory,
    DRUPAL_HUB_NAV_FILENAME,
  );

  let drupalPages = null;

  if (shouldPullDrupal(buildOptions)) {
    log(
      `Attempting to load Drupal content from API at ${contentApi.getSiteUri()}`,
    );

    const drupalTimer = `${contentApi.getSiteUri()} response time: `;

    console.time(drupalTimer);

    drupalPages = await contentApi.getAllPages();

    console.timeEnd(drupalTimer);

    // Error handling
    if (drupalPages.errors && drupalPages.errors.length) {
      log(JSON.stringify(drupalPages.errors, null, 2));
      throw new Error('Drupal query returned with errors');
    }

    // Save new cache
    fs.outputJsonSync(drupalCache, drupalPages, { spaces: 2 });

    if (drupalPages.data.allSideNavMachineNamesQuery) {
      fs.outputJsonSync(
        drupalHubMenuNames,
        drupalPages.data.allSideNavMachineNamesQuery,
        { spaces: 2 },
      );
    }
  } else {
    log('Attempting to load Drupal content from cache...');
    log(`To pull latest, run with "--${PULL_DRUPAL_BUILD_ARG}" flag.`);

    // eslint-disable-next-line import/no-dynamic-require
    drupalPages = require(drupalCache);
  }

  return drupalPages;
}

/**
 * Use Drupal content via the CMS export. Fetch and untar the CMS export as needed.
 *
 * @param {Object} buildOptions
 * @return {Object} - The transformed content from the cms export
 */
async function getContentFromExport(buildOptions) {
  const contentApi = getApiClient(buildOptions);

  if (shouldPullDrupal(buildOptions)) {
    await contentApi.fetchExportContent();
  }

  const drupalPages = await contentApi.getNonNodeContent();
  drupalPages.data.nodeQuery = {
    entities: contentApi.getExportedPages(),
  };

  return drupalPages;
}

async function loadDrupal(buildOptions) {
  const drupalCache = getDrupalCachePath(buildOptions);

  if (!fs.existsSync(drupalCache)) {
    log(`Drupal content unavailable in local cache: ${drupalCache}`);
  } else {
    log(`Drupal content cache found: ${drupalCache}`);
  }

  const drupalPages = buildOptions[USE_CMS_EXPORT_BUILD_ARG]
    ? await getContentFromExport(buildOptions)
    : await getContentViaGraphQL(buildOptions);

  // Dynamic GraphQL from CMS build
  fs.outputJsonSync(CMS_EXPORT_CACHE_FILENAME, drupalPages);

  log('Drupal successfully loaded!');
  return drupalPages;
}

async function loadCachedDrupalFiles(buildOptions, files) {
  const cachedFilesPath = path.join(
    buildOptions.cacheDirectory,
    'drupal/downloads',
  );
  if (!buildOptions[PULL_DRUPAL_BUILD_ARG] && fs.existsSync(cachedFilesPath)) {
    const cachedDrupalFiles = await recursiveRead(cachedFilesPath);
    cachedDrupalFiles.forEach(file => {
      const relativePath = path.relative(
        path.join(buildOptions.cacheDirectory, 'drupal/downloads'),
        file,
      );
      if (global.verbose) {
        log(`Loaded Drupal asset from cache: ${relativePath}`);
      }
      files[relativePath] = {
        path: relativePath,
        isDrupalAsset: true,
        contents: fs.readFileSync(file),
      };
    });
  }
}

function getDrupalContent(buildOptions) {
  if (!ENABLED_ENVIRONMENTS.has(buildOptions.buildtype)) {
    log(`Drupal integration disabled for buildtype ${buildOptions.buildtype}`);
    return () => {};
  }

  return async (files, metalsmith, done) => {
    let drupalData = null;
    try {
      drupalData = await loadDrupal(buildOptions);
      drupalData = convertDrupalFilesToLocal(drupalData, files, buildOptions);

      await loadCachedDrupalFiles(buildOptions, files);
      pipeDrupalPagesIntoMetalsmith(drupalData, files);
      addHomeContent(drupalData, files, metalsmith, buildOptions);
      log('Successfully piped Drupal content into Metalsmith!');
      buildOptions.drupalData = drupalData;
      done();
    } catch (err) {
      if (err instanceof ReferenceError) throw err;

      buildOptions.drupalError = drupalData;
      log(err.stack);
      log('Failed to pipe Drupal content into Metalsmith!');
      if (
        buildOptions.buildtype !== ENVIRONMENTS.LOCALHOST ||
        buildOptions[USE_CMS_EXPORT_BUILD_ARG] ||
        buildOptions['drupal-fail-fast']
      ) {
        done(err);
      } else {
        done();
      }
    }
  };
}

module.exports = { getDrupalContent, shouldPullDrupal };
<commit_msg>Add a timer for getting and processing content (#15494)<commit_after>/* eslint-disable no-param-reassign, no-continue, no-console */

const fs = require('fs-extra');
const path = require('path');
const recursiveRead = require('recursive-readdir');

const ENVIRONMENTS = require('../../../constants/environments');
const { ENABLED_ENVIRONMENTS } = require('../../../constants/drupals');
const { logDrupal: log } = require('./utilities-drupal');
const getApiClient = require('./api');
const convertDrupalFilesToLocal = require('./assets');
const { compilePage, createFileObj } = require('./page');
const {
  createHealthCareRegionListPages,
  createPastEventListPages,
  addGetUpdatesFields,
  addPager,
  sortServices,
} = require('./health-care-region');

const { addHubIconField } = require('./benefit-hub');
const { addHomeContent } = require('./home');

const DRUPAL_CACHE_FILENAME = 'drupal/pages.json';
const DRUPAL_HUB_NAV_FILENAME = 'hubNavNames.json';

// If "--pull-drupal" is passed into the build args, then the build
// should pull the latest Drupal data.
const PULL_DRUPAL_BUILD_ARG = 'pull-drupal';
// If "--use-cms-export" is passed into the build args, then the build
// should use the files in the cms-export directory
const USE_CMS_EXPORT_BUILD_ARG = 'use-cms-export';
const CMS_EXPORT_DIR_BUILD_ARG = 'cms-export-dir';
const CMS_EXPORT_CACHE_FILENAME =
  '.cache/localhost/drupal/pagesTransformed.json';

const getDrupalCachePath = buildOptions =>
  buildOptions[USE_CMS_EXPORT_BUILD_ARG]
    ? buildOptions[CMS_EXPORT_DIR_BUILD_ARG]
    : path.join(buildOptions.cacheDirectory, DRUPAL_CACHE_FILENAME);

// We need to pull the Drupal content if we have --pull-drupal or --use-cms-export, OR if
// the content is not available in the cache.
const shouldPullDrupal = buildOptions =>
  buildOptions[PULL_DRUPAL_BUILD_ARG] ||
  !fs.existsSync(getDrupalCachePath(buildOptions));

function pipeDrupalPagesIntoMetalsmith(contentData, files) {
  const pages = contentData.data.nodeQuery.entities.filter(
    e => e && Object.keys(e).length,
  );

  for (const page of pages) {
    const {
      entityUrl: { path: drupalUrl },
      entityBundle,
    } = page;

    const pageCompiled = compilePage(page, contentData);
    const drupalPageDir = path.join('.', drupalUrl);
    const drupalFileName = path.join(drupalPageDir, 'index.html');

    switch (page.entityBundle) {
      case 'health_care_local_facility':
        addGetUpdatesFields(pageCompiled, pages);
        break;
      case 'health_care_region_detail_page':
        addGetUpdatesFields(pageCompiled, pages);
        break;
      case 'event_listing':
        pageCompiled.pastEventTeasers = pageCompiled.pastEvents;
        pageCompiled.allEventTeasers = pageCompiled.reverseFieldListingNode;
        addPager(
          pageCompiled,
          files,
          pageCompiled.allEventTeasers,
          'event_listing.drupal.liquid',
          'event',
        );
        break;
      case 'story_listing':
        pageCompiled.allNewsStoryTeasers = page.reverseFieldListingNode;
        addPager(
          pageCompiled,
          files,
          pageCompiled.allNewsStoryTeasers,
          'story_listing.drupal.liquid',
          'story',
        );
        break;
      case 'press_releases_listing':
        pageCompiled.allPressReleaseTeasers = page.reverseFieldListingNode;
        addPager(
          pageCompiled,
          files,
          pageCompiled.allPressReleaseTeasers,
          'press_releases_listing.drupal.liquid',
          'press_release',
        );
        break;
      case 'health_services_listing':
        pageCompiled.clinicalHealthServices = sortServices(
          pageCompiled.fieldOffice.entity.reverseFieldRegionPageNode.entities,
        );
        break;
      case 'leadership_listing':
        pageCompiled.allStaffProfiles = page.fieldLeadership;
        addPager(
          pageCompiled,
          files,
          pageCompiled.allStaffProfiles,
          'leadership_listing.drupal.liquid',
          'bio',
        );
        break;
      case 'page':
        addHubIconField(pageCompiled, pages);
        break;
      default:
    }

    files[drupalFileName] = createFileObj(
      pageCompiled,
      `${entityBundle}.drupal.liquid`,
    );

    if (page.entityBundle === 'health_care_region_page') {
      createHealthCareRegionListPages(pageCompiled, drupalPageDir, files);
    }
    if (page.entityBundle === 'event_listing') {
      createPastEventListPages(pageCompiled, drupalPageDir, files);
    }
  }
}

/**
 * Uses Drupal content via a new GraphQL query or the cached result of a
 * previous query. This is where the cache is saved.
 *
 * @param {Object} buildOptions
 * @return {Object} - The result of the GraphQL query
 */
async function getContentViaGraphQL(buildOptions) {
  const contentApi = getApiClient(buildOptions);
  const drupalCache = getDrupalCachePath(buildOptions);
  const drupalHubMenuNames = path.join(
    buildOptions.paramsDirectory,
    DRUPAL_HUB_NAV_FILENAME,
  );

  let drupalPages = null;

  if (shouldPullDrupal(buildOptions)) {
    log(
      `Attempting to load Drupal content from API at ${contentApi.getSiteUri()}`,
    );

    const drupalTimer = `${contentApi.getSiteUri()} response time: `;

    console.time(drupalTimer);

    drupalPages = await contentApi.getAllPages();

    console.timeEnd(drupalTimer);

    // Error handling
    if (drupalPages.errors && drupalPages.errors.length) {
      log(JSON.stringify(drupalPages.errors, null, 2));
      throw new Error('Drupal query returned with errors');
    }

    // Save new cache
    fs.outputJsonSync(drupalCache, drupalPages, { spaces: 2 });

    if (drupalPages.data.allSideNavMachineNamesQuery) {
      fs.outputJsonSync(
        drupalHubMenuNames,
        drupalPages.data.allSideNavMachineNamesQuery,
        { spaces: 2 },
      );
    }
  } else {
    log('Attempting to load Drupal content from cache...');
    log(`To pull latest, run with "--${PULL_DRUPAL_BUILD_ARG}" flag.`);

    // eslint-disable-next-line import/no-dynamic-require
    drupalPages = require(drupalCache);
  }

  return drupalPages;
}

/**
 * Use Drupal content via the CMS export. Fetch and untar the CMS export as needed.
 *
 * @param {Object} buildOptions
 * @return {Object} - The transformed content from the cms export
 */
async function getContentFromExport(buildOptions) {
  const contentApi = getApiClient(buildOptions);

  if (shouldPullDrupal(buildOptions)) {
    await contentApi.fetchExportContent();
  }

  const drupalPages = await contentApi.getNonNodeContent();
  drupalPages.data.nodeQuery = {
    entities: contentApi.getExportedPages(),
  };

  return drupalPages;
}

async function loadDrupal(buildOptions) {
  const drupalCache = getDrupalCachePath(buildOptions);

  if (!fs.existsSync(drupalCache)) {
    log(`Drupal content unavailable in local cache: ${drupalCache}`);
  } else {
    log(`Drupal content cache found: ${drupalCache}`);
  }

  const contentTimer = `Total time to load content from ${
    USE_CMS_EXPORT_BUILD_ARG ? 'CMS export' : 'GraphQL'
  }`;

  console.time(contentTimer);

  const drupalPages = buildOptions[USE_CMS_EXPORT_BUILD_ARG]
    ? await getContentFromExport(buildOptions)
    : await getContentViaGraphQL(buildOptions);

  console.timeEnd(contentTimer);

  // Dynamic GraphQL from CMS build
  fs.outputJsonSync(CMS_EXPORT_CACHE_FILENAME, drupalPages);

  log('Drupal successfully loaded!');
  return drupalPages;
}

async function loadCachedDrupalFiles(buildOptions, files) {
  const cachedFilesPath = path.join(
    buildOptions.cacheDirectory,
    'drupal/downloads',
  );
  if (!buildOptions[PULL_DRUPAL_BUILD_ARG] && fs.existsSync(cachedFilesPath)) {
    const cachedDrupalFiles = await recursiveRead(cachedFilesPath);
    cachedDrupalFiles.forEach(file => {
      const relativePath = path.relative(
        path.join(buildOptions.cacheDirectory, 'drupal/downloads'),
        file,
      );
      if (global.verbose) {
        log(`Loaded Drupal asset from cache: ${relativePath}`);
      }
      files[relativePath] = {
        path: relativePath,
        isDrupalAsset: true,
        contents: fs.readFileSync(file),
      };
    });
  }
}

function getDrupalContent(buildOptions) {
  if (!ENABLED_ENVIRONMENTS.has(buildOptions.buildtype)) {
    log(`Drupal integration disabled for buildtype ${buildOptions.buildtype}`);
    return () => {};
  }

  return async (files, metalsmith, done) => {
    let drupalData = null;
    try {
      drupalData = await loadDrupal(buildOptions);
      drupalData = convertDrupalFilesToLocal(drupalData, files, buildOptions);

      await loadCachedDrupalFiles(buildOptions, files);
      pipeDrupalPagesIntoMetalsmith(drupalData, files);
      addHomeContent(drupalData, files, metalsmith, buildOptions);
      log('Successfully piped Drupal content into Metalsmith!');
      buildOptions.drupalData = drupalData;
      done();
    } catch (err) {
      if (err instanceof ReferenceError) throw err;

      buildOptions.drupalError = drupalData;
      log(err.stack);
      log('Failed to pipe Drupal content into Metalsmith!');
      if (
        buildOptions.buildtype !== ENVIRONMENTS.LOCALHOST ||
        buildOptions[USE_CMS_EXPORT_BUILD_ARG] ||
        buildOptions['drupal-fail-fast']
      ) {
        done(err);
      } else {
        done();
      }
    }
  };
}

module.exports = { getDrupalContent, shouldPullDrupal };
<|endoftext|>


<commit_before>/**
 * @fileoverview DatatableHeader.js
 * Pure component that renders the header of the table.
 */

import React from 'react';
import { DatatableHeaderPropTypes } from '../PropTypes.js';

const DatatableHeader = ({ columns, onSort, sort }) =>

      {columns.map(c =>
         onSort(e, c) : undefined}
			    style={{ cursor: c.sort ? 'pointer' : 'default' }}
		    >
          {sort.sortColumn === c.key ? (sort.sortOrder ? '▾ ' : '▴ ') : ''}{c.label}

      )}

DatatableHeader.propTypes = DatatableHeaderPropTypes;

export default DatatableHeader;
<commit_msg>Update the sort arrow heads.<commit_after>/**
 * @fileoverview DatatableHeader.js
 * Pure component that renders the header of the table.
 */

import React from 'react';
import { DatatableHeaderPropTypes } from '../PropTypes.js';

const DatatableHeader = ({ columns, onSort, sort }) =>

      {columns.map(c =>
         onSort(e, c) : undefined}
			    style={{ cursor: c.sort ? 'pointer' : 'default' }}
		    >
          {sort.sortColumn === c.key ?
            {sort.sortOrder ? '▼ ' : '▲ '}
            : ''
          }
          {c.label}

      )}

DatatableHeader.propTypes = DatatableHeaderPropTypes;

export default DatatableHeader;
<|endoftext|>


<commit_before>'use strict';

var Backbone = require('backbone');
var Todo = require('../models/todo');

var TodoCollection = Backbone.Collection.extend({
  model: Todo,

  update: function (id, data) {
    this.get(id).set(data);
  }
});

module.exports = TodoCollection;
<commit_msg>Remove unnecessary code<commit_after>'use strict';

var Backbone = require('backbone');
var Todo = require('../models/todo');

var TodoCollection = Backbone.Collection.extend({
  model: Todo
});

module.exports = TodoCollection;
<|endoftext|>