<commit_before>var isReqSuccess = false;
var i = 0;
var isPremium = false;

document.body.innerHTML += '
Pay Wall 1: ' + document.documentElement.className + '
';

// var androidUserInfo = {
//   "displayName": "Faker",
//   "email": "faker@example.org",
//   "id": "0c726d53-2ec3-41e2-aa8c-5c4b0e23876a",
//   "isVerified": false,
//   "loginMethod": "email",
//   "membership": {
//     "autoRenew": false,
//     "cycle": "year",
//     "expireDate": "2020-08-22",
//     "id": "mmb_DYBOVDytt1PH",
//     "payMethod": "alipay",
//     "tier": "standard",
//     "vip": false
//   },
//   "userName": "Faker"
// };

// interface Account {
//   id: string; // FTC UUID
//   unionId: string | null; // Present if user logged in with Wechat, or linked to Wechat account.
//   stripeId: string | null; // Only if membership is purchased via Stripe.
//   userName: string | null;
//   email: string;
//   isVerified: boolean; // Whether email is verified.
//   avatarUrl: string | null; // FTC avatar. No used now.
//   loginMethod: "email" | "wechat"; // Will be `email` if use logged in with email + password, or wechat if user logged in with Wechat. It won't be changed during the lifecycle of being logged in, even if user linked FTC account with wechat account.
//   wechat: {
//       nickname: string | null; // Wechat nickname
//       avatarUrl: string | null; // Wechat avatar url.
//   };
//   membership: {
//       id: string | null;
//       tier: "standard" | "premium" | "vip" | null; // `vip` is not available until API finished migration.
//       cycle: "month" | "year" | null;
//       expireDate: string | null;
//       payMethod: "alipay" | "wechat" | "stripe" | "apple" | "b2b",
//       autoRenew: boolean; // Default false.
//       status: "active" | "canceled" | "incomplete" | "incomplate_expired" | "past_due" | "trialing" | "unpaid" | null;
//       vip: boolean; // Deprecated. Will be moved to `tier` as an enum value `vip`
//   }
// }

// paywallDataObj = {"paywall":0,"premium":1,"standard":1,"expire":1623394745,"source":"ftc"};

function payWall() {
  var dataObj = {paywall: 1, premium: 0, standard: 0};
  if (window.androidUserInfo) {
    if (window.androidUserInfo.membership) {
      var expireDate = new Date(window.androidUserInfo.membership.expireDate);
      var todayDate = new Date();
      if (expireDate >= todayDate) {
        dataObj = {paywall: 0, standard: 1};
        dataObj.premium = (window.androidUserInfo.membership.tier === 'premium') ? 1 : 0;
      }
      dataObj.expire = parseInt(expireDate.getTime()/1000, 10);
      dataObj.source = (window.androidUserInfo.membership.vip) ? 'ftc' : '';
    }
    // console.log(dataObj);
    handleSubscriptionInfo(dataObj);
  } else if (!isReqSuccess && i<3) {
    var userId1 = GetCookie('USER_ID') ;
    if (userId1 === null) {
      // MARK: - Unlogged-in Web and Android users
      dataObj = {paywall:1, premium:0, standard:0};
      handleSubscriptionInfo(dataObj);
      return;
    }
    var xhrpw = new XMLHttpRequest();
    xhrpw.open('get', '/index.php/jsapi/paywall');
    xhrpw.setRequestHeader('Content-Type', 'application/text');
    xhrpw.onload = function() {
      if (xhrpw.status === 200) {
        isReqSuccess = true;
        var data = xhrpw.responseText;
        dataObj = JSON.parse(data);
        handleSubscriptionInfo(dataObj);
      } else {
        isReqSuccess = false;
        i += 1;
        setTimeout(function(){payWall();}, 500);
      }
    };
    xhrpw.send(null);
  }
}

function handleSubscriptionInfo(dataObj) {
  updateLockClass(dataObj);
  window.htmlClass = document.documentElement.className;
  window.htmlClass = window.htmlClass.replace(/\ is\-subscriber/g, '').replace(/\ is\-premium/g, '').replace(/\ is\-standard/g, '');
  var subscriptionType = 'noneSubscriber';
  var noneSubscriberStatus;
  if (dataObj.paywall === 0) {
    if (dataObj.premium === 1) {
      window.htmlClass += ' is-subscriber is-premium';
      subscriptionType = 'premium';
    } else {
      window.htmlClass += ' is-subscriber is-standard';
      subscriptionType = 'standard';
    }
    SetCookie('paywall', subscriptionType);
  } else {
    // MARK: - Get none-subscriber status: new and churned
    noneSubscriberStatus = dataObj.expire ? 'churned' : 'new';
  }
  var expireDate = '';
  if (dataObj.expire) {
    expireDate = dataObj.expire;
  }
  SetCookie('expire', expireDate);
  var ccode = dataObj.campaign_code || '';
  var duration = dataObj.latest_duration || '';
  var platform = 'WebSite';
  var pendingRenewal = '';
  var ua = navigator.userAgent || navigator.vendor || '';
  if (window.location.href.indexOf('webview=ftcapp')>=0 || typeof androidUserInfo !== 'undefined') {
    if (/iphone|ipod|ipad/i.test(ua)) {
      platform = 'iOSApp';
      try {
        pendingRenewal = paravalue(window.location.href, 'pendingRenewal');
        //console.log ('p: ' + pendingRenewal);
      } catch (ignore) {}
    } else {
      platform = 'AndroidApp';
    }
  }

  // Test: Change expire date for testing
  //expireDate = Math.round((new Date('2019-06-01 00:20:00')).getTime() / 1000);
  //duration = 'monthly';
  //ccode = '7SXXXXX';
  // platform = 'iOSApp';
  // pendingRenewal = 'On';
  var xhr = new XMLHttpRequest();
  var noneSubscriberParameter = (typeof noneSubscriberStatus === 'string') ? '&noneSubscriberStatus=' + noneSubscriberStatus : '';
  var url = '/m/corp/partial.html?include=promoboxone&type=' + subscriptionType + '&expire=' + expireDate + '&ccode=' + ccode + '&duration=' + duration + '&platform=' + platform + '&pendingRenewal=' + pendingRenewal + noneSubscriberParameter;
  xhr.open('get', url);
  xhr.setRequestHeader('Content-Type', 'application/text');
  xhr.onload = function() {
    if (xhr.status === 200) {
      var data = xhr.responseText;
      if (data !== '') {
        var promoboxContainer = document.getElementById('promo-box-container');
        if (promoboxContainer) {
          promoboxContainer.innerHTML = data;
          startCountdown(promoboxContainer, expireDate);
          sendTracking(promoboxContainer);
        }
      }
    }
  };
  xhr.send(null);
  document.documentElement.className = window.htmlClass;
}

function startCountdown(promoboxContainer, expireDate) {
  if (expireDate > 0) {
    var hourEle = promoboxContainer.querySelector('.countdown-hour');
    var minuteEle = promoboxContainer.querySelector('.countdown-minute');
    var secondEle = promoboxContainer.querySelector('.countdown-second');
    if (hourEle && minuteEle && secondEle) {
      setInterval(function() {
        var nowTime = Math.round((new Date()).getTime() / 1000);
        var leftTime = expireDate - nowTime;
        var leftHours = Math.floor(leftTime / 3600);
        leftHours = (leftHours > 999) ? 999 : leftHours;
        leftHours = ('0'+leftHours).slice(-2);
        var leftMinutes = Math.floor(leftTime / 60) % 60;
        leftMinutes = ('0'+leftMinutes).slice(-2);
        var leftSeconds = leftTime % 60;
        leftSeconds = ('0'+leftSeconds).slice(-2);
        hourEle.innerHTML = leftHours;
        minuteEle.innerHTML = leftMinutes;
        secondEle.innerHTML = leftSeconds;
      }, 1000);
    }
  }
}

function sendTracking(promoboxContainer) {
  var boxEle = promoboxContainer.querySelector('.subscription-promo-box');
  if (boxEle) {
    var ccode = boxEle.getAttribute('data-promo-id');
    if (ccode && ccode !== '') {
      gtag('event', 'Display', {'event_label': ccode, 'event_category': 'PromoBox', 'non_interaction': true});
    }
  }
}

function updateLockClass(dataObj){
  function keepLock(ele, keep, remove) {
    ele.classList.remove(remove);
    ele.classList.add(keep);
  }
  var userTier;
  if (dataObj.paywall >= 1) {
    userTier = 'free';
  } else {
    isPremium = (dataObj.premium >= 1) ? true : false ;
    userTier = isPremium ? 'premium' : 'standard';
  }
  var headlines = document.querySelectorAll('.locked, .unlocked');
  for (var k = 0; k < headlines.length; k++) {
    if (userTier === 'premium') {
      keepLock(headlines[k], 'unlocked', 'locked');
    } else if (userTier === 'free') {
      keepLock(headlines[k], 'locked', 'unlocked');
    } else if (userTier === 'standard') {
      if (headlines[k].classList.contains('vip')) {
        keepLock(headlines[k], 'locked', 'unlocked');
      } else {
        keepLock(headlines[k], 'unlocked', 'locked');
      }
    }
  }
}

function showPaywallHint(){
  var subscribeNowContainerId = document.getElementById('paywall-hint-container');
  if(subscribeNowContainerId){
      var paywallOverlayShadow = document.getElementById('paywall-overlay-shadow');
      var paywallHintContainer = document.getElementById('paywall-hint-container');
      paywallOverlayShadow.onclick = function(){
          paywallHintContainer.style.display = 'none';
      };
  }
}

function openHint() {
  var para = location.search.substring(1);
  var url = location.href;
  if (para.indexOf('issue=EditorChoice')>=0 || url.indexOf('speedread')>=0 ){
    var paywallHintContainer = document.getElementById('paywall-hint-container');
    var dataHints = document.querySelectorAll('[data-hint="dataHint"]');
    if(dataHints.length>0){
      for (var i = 0,len=dataHints.length; i < len; i++) {
        dataHints[i].onclick = function(){
          paywallHintContainer.style.display = 'block';
          gtag('event', 'view_promotion', {
            promotions: [
              {
                id: window.gSubscriptionEventLabel,
                name: window.gSubscriptionEventLabel,
                creative_name: location.href,
                creative_slot: 'become a member'
              }
            ]
          });
          gtag('event', 'Display', {'event_label': window.gSubscriptionEventLabel, 'event_category': 'Web Privileges'});
        };
      }
    }
  }
}

payWall();
showPaywallHint();
openHint();<commit_msg>test dark mode<commit_after>var isReqSuccess = false;
var i = 0;
var isPremium = false;

document.body.innerHTML = '
Pay Wall 1: ' + document.documentElement.className + '
';

// var androidUserInfo = {
//   "displayName": "Faker",
//   "email": "faker@example.org",
//   "id": "0c726d53-2ec3-41e2-aa8c-5c4b0e23876a",
//   "isVerified": false,
//   "loginMethod": "email",
//   "membership": {
//     "autoRenew": false,
//     "cycle": "year",
//     "expireDate": "2020-08-22",
//     "id": "mmb_DYBOVDytt1PH",
//     "payMethod": "alipay",
//     "tier": "standard",
//     "vip": false
//   },
//   "userName": "Faker"
// };

// interface Account {
//   id: string; // FTC UUID
//   unionId: string | null; // Present if user logged in with Wechat, or linked to Wechat account.
//   stripeId: string | null; // Only if membership is purchased via Stripe.
//   userName: string | null;
//   email: string;
//   isVerified: boolean; // Whether email is verified.
//   avatarUrl: string | null; // FTC avatar. No used now.
//   loginMethod: "email" | "wechat"; // Will be `email` if use logged in with email + password, or wechat if user logged in with Wechat. It won't be changed during the lifecycle of being logged in, even if user linked FTC account with wechat account.
//   wechat: {
//       nickname: string | null; // Wechat nickname
//       avatarUrl: string | null; // Wechat avatar url.
//   };
//   membership: {
//       id: string | null;
//       tier: "standard" | "premium" | "vip" | null; // `vip` is not available until API finished migration.
//       cycle: "month" | "year" | null;
//       expireDate: string | null;
//       payMethod: "alipay" | "wechat" | "stripe" | "apple" | "b2b",
//       autoRenew: boolean; // Default false.
//       status: "active" | "canceled" | "incomplete" | "incomplate_expired" | "past_due" | "trialing" | "unpaid" | null;
//       vip: boolean; // Deprecated. Will be moved to `tier` as an enum value `vip`
//   }
// }

// paywallDataObj = {"paywall":0,"premium":1,"standard":1,"expire":1623394745,"source":"ftc"};

function payWall() {
  var dataObj = {paywall: 1, premium: 0, standard: 0};
  if (window.androidUserInfo) {
    if (window.androidUserInfo.membership) {
      var expireDate = new Date(window.androidUserInfo.membership.expireDate);
      var todayDate = new Date();
      if (expireDate >= todayDate) {
        dataObj = {paywall: 0, standard: 1};
        dataObj.premium = (window.androidUserInfo.membership.tier === 'premium') ? 1 : 0;
      }
      dataObj.expire = parseInt(expireDate.getTime()/1000, 10);
      dataObj.source = (window.androidUserInfo.membership.vip) ? 'ftc' : '';
    }
    // console.log(dataObj);
    handleSubscriptionInfo(dataObj);
  } else if (!isReqSuccess && i<3) {
    var userId1 = GetCookie('USER_ID') ;
    if (userId1 === null) {
      // MARK: - Unlogged-in Web and Android users
      dataObj = {paywall:1, premium:0, standard:0};
      handleSubscriptionInfo(dataObj);
      return;
    }
    var xhrpw = new XMLHttpRequest();
    xhrpw.open('get', '/index.php/jsapi/paywall');
    xhrpw.setRequestHeader('Content-Type', 'application/text');
    xhrpw.onload = function() {
      if (xhrpw.status === 200) {
        isReqSuccess = true;
        var data = xhrpw.responseText;
        dataObj = JSON.parse(data);
        handleSubscriptionInfo(dataObj);
      } else {
        isReqSuccess = false;
        i += 1;
        setTimeout(function(){payWall();}, 500);
      }
    };
    xhrpw.send(null);
  }
}

function handleSubscriptionInfo(dataObj) {
  updateLockClass(dataObj);
  window.htmlClass = document.documentElement.className;
  window.htmlClass = window.htmlClass.replace(/\ is\-subscriber/g, '').replace(/\ is\-premium/g, '').replace(/\ is\-standard/g, '');
  var subscriptionType = 'noneSubscriber';
  var noneSubscriberStatus;
  if (dataObj.paywall === 0) {
    if (dataObj.premium === 1) {
      window.htmlClass += ' is-subscriber is-premium';
      subscriptionType = 'premium';
    } else {
      window.htmlClass += ' is-subscriber is-standard';
      subscriptionType = 'standard';
    }
    SetCookie('paywall', subscriptionType);
  } else {
    // MARK: - Get none-subscriber status: new and churned
    noneSubscriberStatus = dataObj.expire ? 'churned' : 'new';
  }
  var expireDate = '';
  if (dataObj.expire) {
    expireDate = dataObj.expire;
  }
  SetCookie('expire', expireDate);
  var ccode = dataObj.campaign_code || '';
  var duration = dataObj.latest_duration || '';
  var platform = 'WebSite';
  var pendingRenewal = '';
  var ua = navigator.userAgent || navigator.vendor || '';
  if (window.location.href.indexOf('webview=ftcapp')>=0 || typeof androidUserInfo !== 'undefined') {
    if (/iphone|ipod|ipad/i.test(ua)) {
      platform = 'iOSApp';
      try {
        pendingRenewal = paravalue(window.location.href, 'pendingRenewal');
        //console.log ('p: ' + pendingRenewal);
      } catch (ignore) {}
    } else {
      platform = 'AndroidApp';
    }
  }

  // Test: Change expire date for testing
  //expireDate = Math.round((new Date('2019-06-01 00:20:00')).getTime() / 1000);
  //duration = 'monthly';
  //ccode = '7SXXXXX';
  // platform = 'iOSApp';
  // pendingRenewal = 'On';
  var xhr = new XMLHttpRequest();
  var noneSubscriberParameter = (typeof noneSubscriberStatus === 'string') ? '&noneSubscriberStatus=' + noneSubscriberStatus : '';
  var url = '/m/corp/partial.html?include=promoboxone&type=' + subscriptionType + '&expire=' + expireDate + '&ccode=' + ccode + '&duration=' + duration + '&platform=' + platform + '&pendingRenewal=' + pendingRenewal + noneSubscriberParameter;
  xhr.open('get', url);
  xhr.setRequestHeader('Content-Type', 'application/text');
  xhr.onload = function() {
    if (xhr.status === 200) {
      var data = xhr.responseText;
      if (data !== '') {
        var promoboxContainer = document.getElementById('promo-box-container');
        if (promoboxContainer) {
          promoboxContainer.innerHTML = data;
          startCountdown(promoboxContainer, expireDate);
          sendTracking(promoboxContainer);
        }
      }
    }
  };
  xhr.send(null);
  document.documentElement.className = window.htmlClass;
}

function startCountdown(promoboxContainer, expireDate) {
  if (expireDate > 0) {
    var hourEle = promoboxContainer.querySelector('.countdown-hour');
    var minuteEle = promoboxContainer.querySelector('.countdown-minute');
    var secondEle = promoboxContainer.querySelector('.countdown-second');
    if (hourEle && minuteEle && secondEle) {
      setInterval(function() {
        var nowTime = Math.round((new Date()).getTime() / 1000);
        var leftTime = expireDate - nowTime;
        var leftHours = Math.floor(leftTime / 3600);
        leftHours = (leftHours > 999) ? 999 : leftHours;
        leftHours = ('0'+leftHours).slice(-2);
        var leftMinutes = Math.floor(leftTime / 60) % 60;
        leftMinutes = ('0'+leftMinutes).slice(-2);
        var leftSeconds = leftTime % 60;
        leftSeconds = ('0'+leftSeconds).slice(-2);
        hourEle.innerHTML = leftHours;
        minuteEle.innerHTML = leftMinutes;
        secondEle.innerHTML = leftSeconds;
      }, 1000);
    }
  }
}

function sendTracking(promoboxContainer) {
  var boxEle = promoboxContainer.querySelector('.subscription-promo-box');
  if (boxEle) {
    var ccode = boxEle.getAttribute('data-promo-id');
    if (ccode && ccode !== '') {
      gtag('event', 'Display', {'event_label': ccode, 'event_category': 'PromoBox', 'non_interaction': true});
    }
  }
}

function updateLockClass(dataObj){
  function keepLock(ele, keep, remove) {
    ele.classList.remove(remove);
    ele.classList.add(keep);
  }
  var userTier;
  if (dataObj.paywall >= 1) {
    userTier = 'free';
  } else {
    isPremium = (dataObj.premium >= 1) ? true : false ;
    userTier = isPremium ? 'premium' : 'standard';
  }
  var headlines = document.querySelectorAll('.locked, .unlocked');
  for (var k = 0; k < headlines.length; k++) {
    if (userTier === 'premium') {
      keepLock(headlines[k], 'unlocked', 'locked');
    } else if (userTier === 'free') {
      keepLock(headlines[k], 'locked', 'unlocked');
    } else if (userTier === 'standard') {
      if (headlines[k].classList.contains('vip')) {
        keepLock(headlines[k], 'locked', 'unlocked');
      } else {
        keepLock(headlines[k], 'unlocked', 'locked');
      }
    }
  }
}

function showPaywallHint(){
  var subscribeNowContainerId = document.getElementById('paywall-hint-container');
  if(subscribeNowContainerId){
      var paywallOverlayShadow = document.getElementById('paywall-overlay-shadow');
      var paywallHintContainer = document.getElementById('paywall-hint-container');
      paywallOverlayShadow.onclick = function(){
          paywallHintContainer.style.display = 'none';
      };
  }
}

function openHint() {
  var para = location.search.substring(1);
  var url = location.href;
  if (para.indexOf('issue=EditorChoice')>=0 || url.indexOf('speedread')>=0 ){
    var paywallHintContainer = document.getElementById('paywall-hint-container');
    var dataHints = document.querySelectorAll('[data-hint="dataHint"]');
    if(dataHints.length>0){
      for (var i = 0,len=dataHints.length; i < len; i++) {
        dataHints[i].onclick = function(){
          paywallHintContainer.style.display = 'block';
          gtag('event', 'view_promotion', {
            promotions: [
              {
                id: window.gSubscriptionEventLabel,
                name: window.gSubscriptionEventLabel,
                creative_name: location.href,
                creative_slot: 'become a member'
              }
            ]
          });
          gtag('event', 'Display', {'event_label': window.gSubscriptionEventLabel, 'event_category': 'Web Privileges'});
        };
      }
    }
  }
}

payWall();
showPaywallHint();
openHint();<|endoftext|>


<commit_before>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Configuration subsytem, providing a set of defaults, and merging of a configuration
 * JSON file.
 */

var fs = require('fs');
var merge = require('util/misc').merge;
var expanduser = require('util/misc').expanduser;
var norris = require('norris');

var defaults = {
  'port': 8010,

  'data_root': '/opt/cast/',

  // This directories are relative to the data root
  'service_dir': 'services', // Runit services directory
  'bundle_dir': 'bundles', // Stored bundle tarballs
  'extracted_dir': 'extracted', // Stores extracted bundles
  'app_dir': 'applications', // Stores application instances

  'fileread_buffer_size': (1024 * 64),
  'runsvdir_binary': 'runsvdir',
  'gzip': 'gzip',
  'tar': null,
  'norris_ttl': (60 * 10),

  // These are used by a client
  'temp_directory': '.cast-temp',

  // Runit defaults
  'runit': {
    'service_user': 'root',
    'svlogd_daemon_user': 'syslog',
    'log_directory': 'main',
    'max_log_size': 10 * 1024 * 1024,
    'max_log_num': 10
  }
};
var poffset = 0;

exports.config_files = ['~/.cast/config.json', '/etc/cast.conf'];
exports.config_current = {};

exports.setup = function(cb) {
  function resolve_via_norris(cb, err) {
    if (err) {
      cb(err);
    }
    norris.get(function(facts) {
      if (exports.config_current.tar === null) {
        exports.config_current.tar = facts.gnutar;
      }

      cb(null);
    });
  }

  exports.config_current = merge(exports.config_current, defaults);
  function dostep() {
    var p = expanduser(exports.config_files[poffset]);
    fs.readFile(p, function(err, data) {
      if (!err) {
        var parsed = {};
        try {
          parsed = JSON.parse(data.toString());
        } catch (eerr) {
          cb(eerr);
        }
        exports.config_current = merge(exports.config_current, parsed);
      }

      poffset++;
      if (exports.config_files.length == poffset) {
        resolve_via_norris(cb, null);
      }
      else {
        dostep();
      }
    });
  }
  dostep();
};

exports.get = function() {
  return exports.config_current;
};
<commit_msg>Add data_dir setting<commit_after>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Configuration subsytem, providing a set of defaults, and merging of a configuration
 * JSON file.
 */

var fs = require('fs');
var merge = require('util/misc').merge;
var expanduser = require('util/misc').expanduser;
var norris = require('norris');

var defaults = {
  'port': 8010,

  'data_root': '/opt/cast/',

  // This directories are relative to the data root
  'data_dir': 'data', // Stores application data files
  'service_dir': 'services', // Runit services directory
  'bundle_dir': 'bundles', // Stores bundle tarballs
  'extracted_dir': 'extracted', // Stores extracted bundles
  'app_dir': 'applications', // Stores application instances

  'fileread_buffer_size': (1024 * 64),
  'runsvdir_binary': 'runsvdir',
  'gzip': 'gzip',
  'tar': null,
  'norris_ttl': (60 * 10),

  // These are used by a client
  'temp_directory': '.cast-temp',

  // Runit defaults
  'runit': {
    'service_user': 'root',
    'svlogd_daemon_user': 'syslog',
    'log_directory': 'main',
    'max_log_size': 10 * 1024 * 1024,
    'max_log_num': 10
  }
};
var poffset = 0;

exports.config_files = ['~/.cast/config.json', '/etc/cast.conf'];
exports.config_current = {};

exports.setup = function(cb) {
  function resolve_via_norris(cb, err) {
    if (err) {
      cb(err);
    }
    norris.get(function(facts) {
      if (exports.config_current.tar === null) {
        exports.config_current.tar = facts.gnutar;
      }

      cb(null);
    });
  }

  exports.config_current = merge(exports.config_current, defaults);
  function dostep() {
    var p = expanduser(exports.config_files[poffset]);
    fs.readFile(p, function(err, data) {
      if (!err) {
        var parsed = {};
        try {
          parsed = JSON.parse(data.toString());
        } catch (eerr) {
          cb(eerr);
        }
        exports.config_current = merge(exports.config_current, parsed);
      }

      poffset++;
      if (exports.config_files.length == poffset) {
        resolve_via_norris(cb, null);
      }
      else {
        dostep();
      }
    });
  }
  dostep();
};

exports.get = function() {
  return exports.config_current;
};
<|endoftext|>


<commit_before>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 *
 */

if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}
define(["require", "../query", "../utils"], function(require, Querier, utils){
	//_______________________________________________________ QUERY UTILS
	utils.remove = function(obj, what, schema) {
		var removed = [];

		function finalise(r) {
			if (!r.ancestor)
				return;
			removed.push(r);
			if (r.ancestor.value instanceof Array)
				r.ancestor.value.splice(r.key, 1);
			else {
				delete r.ancestor.value[r.key];
			}
		}
		r = Querier.query(obj, what, {
			fullOutput: true,
			schema: schema
		});
		//console.log("deep.utils.remove : ", obj, what, r);
		if (!r)
			return r;
		if (r._deep_query_node_) {
			finalise(r);
			return removed.shift();
		}
		r.forEach(finalise);
		return removed;
	};

	utils.replace = function(target, what, by, schema) {
		var replaced = [];

		function finalise(r) {
			if (!r.ancestor)
				return;
			r.ancestor.value[r.key] = r.value = by;
			replaced.push(r);
		}
		var r = Querier.query(target, what, {
			fullOutput: true,
			schema: schema
		});
		if (!r)
			return r;
		if (r._deep_query_node_) {
			finalise(r);
			return replaced.shift();
		}
		r.forEach(finalise);
		return replaced;
	};
	return utils;
});<commit_msg>follow nodes/query move<commit_after>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 *
 */

if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}
define(["require", "../nodes/query", "../utils"], function(require, Querier, utils){
	//_______________________________________________________ QUERY UTILS
	utils.remove = function(obj, what, schema) {
		var removed = [];

		function finalise(r) {
			if (!r.ancestor)
				return;
			removed.push(r);
			if (r.ancestor.value instanceof Array)
				r.ancestor.value.splice(r.key, 1);
			else {
				delete r.ancestor.value[r.key];
			}
		}
		r = Querier.query(obj, what, {
			fullOutput: true,
			schema: schema
		});
		//console.log("deep.utils.remove : ", obj, what, r);
		if (!r)
			return r;
		if (r._deep_query_node_) {
			finalise(r);
			return removed.shift();
		}
		r.forEach(finalise);
		return removed;
	};

	utils.replace = function(target, what, by, schema) {
		var replaced = [];

		function finalise(r) {
			if (!r.ancestor)
				return;
			r.ancestor.value[r.key] = r.value = by;
			replaced.push(r);
		}
		var r = Querier.query(target, what, {
			fullOutput: true,
			schema: schema
		});
		if (!r)
			return r;
		if (r._deep_query_node_) {
			finalise(r);
			return replaced.shift();
		}
		r.forEach(finalise);
		return replaced;
	};
	return utils;
});<|endoftext|>


<commit_before>/**
 *
 * this is a sub process of Zenith server. Currently it accepts a message in
 * following format
 * { xml: string, xpath:string, nameSpace:{},regEx:string , checkRegEx:boolean,caseSense:boolean}
 * Ex.{ xml:"anyxmlstring", xpath:"//m0:request[1]/m0:symbol", nameSpace:{'m0':'http://services.samples'},checkRegEx:true, regEx:"IBM",caseSense:false}
 * And evaluates the regular expression on the element located by xpath
 * if it matches the expression returns object contains the result
 */

var libxmljs = require("libxmljs");
var msgq = [];

process.on('message', function(m) {
	        //
		var resp = {
			result : null,
			hasRegEx : false
		};
	    msgq.push(m);
	    var servMsg = msgq.shift();
		try{
			var doc = libxmljs.parseXml(servMsg.xml);
			var result;
			if(servMsg.nameSpace!=null){
				result = doc.get(servMsg.xpath,servMsg.nameSpace);
			}else{
				result = doc.get(servMsg.xpath);
			}
			var result = doc.get(servMsg.xpath,servMsg.nameSpace);
			if(result == null){
				//no value for the expath expression
				logger.debug('XMLXPathProcess', 'XML message does not contain result for'
						+ 'XPath exp : ' + servMsg.xpath);
				process.send(resp);
			}

			var regExp;

			if(servMsg.checkRegEx) {
				//code to check xml against regExp
				if(caseSensitive = false){
					regExp = new RegExp(servMsg.regEx,'i');
				}
				else{
					regExp = new RegExp(servMsg.regEx);
				}
				resp.hasRegEx =  regExp.test(result.text());
				logger.debug('XMLXPathProcess', 'RegExp evaluation result :' + resp.hasRegEx);
				process.send(resp);
			} else {
				//code to get the element value

				resp.result = result.text();
				logger.debug('XMLXPathProcess', 'Element value : ' +resp.result);
				process.send(resp);
			}

		}catch(err){
			process.send({ result: err });
		}

});
<commit_msg>Delete xpath_process_libxmljs.js<commit_after><|endoftext|>


<commit_before>var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')

var module = require('tachyons-white-space/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-white-space/tachyons-white-space.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)

var srcCSS = fs.readFileSync('./src/_white-space.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')

var template = fs.readFileSync('./templates/docs/white-space/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
  moduleVersion: module.version,
  moduleSize: moduleSize,
  moduleObj: moduleObj,
  srcCSS: srcCSS,
  navDocs: navDocs
})

fs.writeFileSync('./docs/typography/white-space/index.html', html)
<commit_msg>Add site footer to each documentation generator<commit_after>var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')

var module = require('tachyons-white-space/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-white-space/tachyons-white-space.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)

var srcCSS = fs.readFileSync('./src/_white-space.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8')

var template = fs.readFileSync('./templates/docs/white-space/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
  moduleVersion: module.version,
  moduleSize: moduleSize,
  moduleObj: moduleObj,
  srcCSS: srcCSS,
  navDocs: navDocs,
  siteFooter: siteFooter
})

fs.writeFileSync('./docs/typography/white-space/index.html', html)
<|endoftext|>


<commit_before>define('vm.session',
    ['ko', 'datacontext', 'config', 'router', 'messenger', 'sort'],
    function (ko, datacontext, config, router, messenger, sort) {

        var
            currentSessionId = ko.observable(),
            logger = config.logger,
            rooms = ko.observableArray(),
            session = ko.observable(),
            timeslots = ko.observableArray(),
            tracks = ko.observableArray(),
            validationErrors = ko.observableArray([]),

            canEditSession = ko.computed(function () {
                return session() && config.currentUser() && config.currentUser().id() === session().speakerId();
            }),

            canEditEval = ko.computed(function () {
                return session() && config.currentUser() && config.currentUser().id() !== session().speakerId();
            }),

            isDirty = ko.computed(function () {
                if (canEditSession()) {
                    return session().dirtyFlag().isDirty();
                }
                if (canEditEval()) {
                    if (session() && session().attendance && session().attendance()) {
                        return session().attendance().dirtyFlag().isDirty();
                    }
                }
                return false;
            }),

            isValid = ko.computed(function () {
                return (canEditEval() || canEditSession()) ? validationErrors().length === 0 : true;
            }),

            activate = function (routeData, callback) {
                messenger.publish.viewModelActivated({ canleaveCallback: canLeave });
                currentSessionId(routeData.id);
                getRooms();
                getTimeslots();
                getTracks();
                getSession(callback);
            },

            cancelCmd = ko.asyncCommand({
                execute: function (complete) {
                    var callback = function () {
                        complete();
                        logger.success(config.toasts.retreivedData);
                    };
                    canEditSession() ? getSession(callback, true) : getAttendance(callback, true);
                },
                canExecute: function (isExecuting) {
                    return !isExecuting && isDirty();
                }
            }),

            goBackCmd = ko.asyncCommand({
                execute: function (complete) {
                    router.navigateBack();
                    complete();
                },
                canExecute: function (isExecuting) {
                    return !isExecuting && !isDirty();
                }
            }),

            canLeave = function () {
                return !isDirty() && isValid;
            },

            getSession = function (completeCallback, forceRefresh) {
                var callback = function() {
                    if (completeCallback) { completeCallback(); }
                    validationErrors = ko.validation.group(session());
                };

                datacontext.sessions.getFullSessionById(
                    currentSessionId(), {
                        success: function(s) {
                            session(s);
                            callback();
                        },
                        error: callback
                    },
                    forceRefresh
                );
            },

            getAttendance = function (completeCallback, forceRefresh) {
                // Refresh the attendance in the datacontext
                var callback = completeCallback || function() {
                };

                datacontext.attendance.getSessionFavorite(
                    session().attendance().sessionId(),
                    {
                        success: function() { callback(); },
                        error: function() { callback(); }
                    },
                    forceRefresh
                );
            },

            getRooms = function () {
                if (!rooms().length) {
                    datacontext.rooms.getData({
                        results: rooms,
                        sortFunction: sort.roomSort
                    });
                }
            },

            getTimeslots = function () {
                if (!timeslots().length) {
                    datacontext.timeslots.getData({
                        results: timeslots,
                        sortFunction: sort.timeslotSort
                    });
                }
            },

            getTracks = function () {
                if (!tracks().length) {
                    datacontext.tracks.getData({
                        results: tracks,
                        sortFunction: sort.trackSort
                    });
                }
            },

            saveCmd = ko.asyncCommand({
                execute: function (complete) {
                    if (canEditSession()) {
                        $.when(datacontext.sessions.updateData(session()))
                            .always(complete);
                        return;
                    }
                    if (canEditEval()) {
                        $.when(datacontext.attendance.updateData(session()))
                            .always(complete);
                        return;
                    }
                },
                canExecute: function (isExecuting) {
                    return !isExecuting && isDirty() && isValid;
                }
            }),

            saveFavoriteCmd = ko.asyncCommand({
                execute: function(complete) {
                    var
                        wrapper = function () { saveFavoriteDone(complete); },

                        cudMethod = session().isFavorite()
                            ? datacontext.attendance.deleteData
                            : datacontext.attendance.addData;

                    cudMethod(session(),
                        {
                            success: wrapper,
                            error: wrapper
                        });
                },
                canExecute: function(isExecuting) {
                    return !isExecuting && session() && session().isUnlocked();
                }
            }),

            saveFavoriteDone = function (complete) {
                session.valueHasMutated(); // Trigger re-evaluation of isDirty
                complete();
            },

            tmplName = function () {
                return canEditSession() ? 'session.edit' : 'session.view';
            };

        return {
            activate: activate,
            cancelCmd: cancelCmd,
            canEditSession: canEditSession,
            canEditEval: canEditEval,
            canLeave: canLeave,
            goBackCmd: goBackCmd,
            isDirty: isDirty,
            isValid: isValid,
            rooms: rooms,
            session: session,
            saveCmd: saveCmd,
            saveFavoriteCmd: saveFavoriteCmd,
            timeslots: timeslots,
            tmplName: tmplName,
            tracks: tracks
        };
    });<commit_msg>Added parens to isValid to make it isValid().<commit_after>define('vm.session',
    ['ko', 'datacontext', 'config', 'router', 'messenger', 'sort'],
    function (ko, datacontext, config, router, messenger, sort) {

        var
            currentSessionId = ko.observable(),
            logger = config.logger,
            rooms = ko.observableArray(),
            session = ko.observable(),
            timeslots = ko.observableArray(),
            tracks = ko.observableArray(),
            //validationErrors = ko.observableArray([]),

            validationErrors = ko.computed(function () {
                // We don;t have a session early on. So we return an empty [].
                // Once we get a session, we want to point to its validation errors.
                var valArray = session() ? ko.validation.group(session())() : [];
                return valArray;
            }),

            canEditSession = ko.computed(function () {
                return session() && config.currentUser() && config.currentUser().id() === session().speakerId();
            }),

            canEditEval = ko.computed(function () {
                return session() && config.currentUser() && config.currentUser().id() !== session().speakerId();
            }),

            isDirty = ko.computed(function () {
                if (canEditSession()) {
                    return session().dirtyFlag().isDirty();
                }
                if (canEditEval()) {
                    if (session() && session().attendance && session().attendance()) {
                        return session().attendance().dirtyFlag().isDirty();
                    }
                }
                return false;
            }),

            isValid = ko.computed(function () {
                return (canEditEval() || canEditSession()) ? validationErrors().length === 0 : true;
            }),

            activate = function (routeData, callback) {
                messenger.publish.viewModelActivated({ canleaveCallback: canLeave });
                currentSessionId(routeData.id);
                getRooms();
                getTimeslots();
                getTracks();
                getSession(callback);
            },

            cancelCmd = ko.asyncCommand({
                execute: function (complete) {
                    var callback = function () {
                        complete();
                        logger.success(config.toasts.retreivedData);
                    };
                    canEditSession() ? getSession(callback, true) : getAttendance(callback, true);
                },
                canExecute: function (isExecuting) {
                    return !isExecuting && isDirty();
                }
            }),

            goBackCmd = ko.asyncCommand({
                execute: function (complete) {
                    router.navigateBack();
                    complete();
                },
                canExecute: function (isExecuting) {
                    return !isExecuting && !isDirty();
                }
            }),

            canLeave = function () {
                return !isDirty() && isValid();
            },

            getSession = function (completeCallback, forceRefresh) {
                var callback = function() {
                    if (completeCallback) { completeCallback(); }
                };

                datacontext.sessions.getFullSessionById(
                    currentSessionId(), {
                        success: function(s) {
                            session(s);
                            callback();
                        },
                        error: callback
                    },
                    forceRefresh
                );
            },

            getAttendance = function (completeCallback, forceRefresh) {
                // Refresh the attendance in the datacontext
                var callback = completeCallback || function() {
                };

                datacontext.attendance.getSessionFavorite(
                    session().attendance().sessionId(),
                    {
                        success: function() { callback(); },
                        error: function() { callback(); }
                    },
                    forceRefresh
                );
            },

            getRooms = function () {
                if (!rooms().length) {
                    datacontext.rooms.getData({
                        results: rooms,
                        sortFunction: sort.roomSort
                    });
                }
            },

            getTimeslots = function () {
                if (!timeslots().length) {
                    datacontext.timeslots.getData({
                        results: timeslots,
                        sortFunction: sort.timeslotSort
                    });
                }
            },

            getTracks = function () {
                if (!tracks().length) {
                    datacontext.tracks.getData({
                        results: tracks,
                        sortFunction: sort.trackSort
                    });
                }
            },

            saveCmd = ko.asyncCommand({
                execute: function (complete) {
                    if (canEditSession()) {
                        $.when(datacontext.sessions.updateData(session()))
                            .always(complete);
                        return;
                    }
                    if (canEditEval()) {
                        $.when(datacontext.attendance.updateData(session()))
                            .always(complete);
                        return;
                    }
                },
                canExecute: function (isExecuting) {
                    return !isExecuting && isDirty() && isValid();
                }
            }),

            saveFavoriteCmd = ko.asyncCommand({
                execute: function(complete) {
                    var
                        wrapper = function () { saveFavoriteDone(complete); },

                        cudMethod = session().isFavorite()
                            ? datacontext.attendance.deleteData
                            : datacontext.attendance.addData;

                    cudMethod(session(),
                        {
                            success: wrapper,
                            error: wrapper
                        });
                },
                canExecute: function(isExecuting) {
                    return !isExecuting && session() && session().isUnlocked();
                }
            }),

            saveFavoriteDone = function (complete) {
                session.valueHasMutated(); // Trigger re-evaluation of isDirty
                complete();
            },

            tmplName = function () {
                return canEditSession() ? 'session.edit' : 'session.view';
            };

        return {
            activate: activate,
            cancelCmd: cancelCmd,
            canEditSession: canEditSession,
            canEditEval: canEditEval,
            canLeave: canLeave,
            goBackCmd: goBackCmd,
            isDirty: isDirty,
            isValid: isValid,
            rooms: rooms,
            session: session,
            saveCmd: saveCmd,
            saveFavoriteCmd: saveFavoriteCmd,
            timeslots: timeslots,
            tmplName: tmplName,
            tracks: tracks
        };
    });<|endoftext|>


<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

exports.getCurrentDateTime = function() {
    return new tizen.TZDate();
};

 exports.getLocalTimezone = function() {
    var minutesToUTC = (new Date()).getTimezoneOffset();
    var hoursToUTC = - (minutesToUTC / 60);
    if (hoursToUTC < 0)
      return 'GMT' + hoursToUTC;
    return 'GMT+' + hoursToUTC;
};

exports.getAvailableTimezones = function() {
    return [
      tizen.time.getLocalTimezone()
    ];
};

exports.getDateFormat = function(shortformat) {
    if (shortformat)
      return 'd/m/y';
    return 'D, M d y';
};

exports.getTimeFormat = function() {
    return 'h:m:s';
};

exports.isLeapYear = function(year) {
    if (!(year % 400))
      return true;
    if (!(year % 100))
      return false;
    if (!(year % 4))
      return true;
    return false;
};

function _throwProperTizenException(e) {
  if (e instanceof TypeError)
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
  else if (e instanceof RangeError)
    throw new tizen.WebAPIException(tizen.WebAPIException.INVALID_VALUES_ERR);
  else
    throw new tizen.WebAPIException(tizen.WebAPIException.UNKNOWN_ERR);
}

var TimeDurationUnit = [
  "MSECS",
  "SECS",
  "MINS",
  "HOURS",
  "DAYS"
];

tizen.TimeDuration = function(length, unit) {
  this.length = length || 0;
  this.unit = unit || 'MSECS';

  Object.defineProperty(this, "length", { get : function() {
                                            return length; },
                                          set : function(NewValue) {
                                            if (NewValue != null)
                                              length = NewValue; }});
  Object.defineProperty(this, "unit", { get : function() {
                                          return unit; },
                                        set : function(NewValue) {
                                          if (NewValue in TimeDurationUnit)
                                            unit = NewValue; }});

  if (TimeDurationUnit.indexOf(this.unit) == -1)
    this.unit = 'MSECS';
};

function getMultiplier(unit) {
  if (unit == 'MSECS')
    return 1.0;
  if (unit == 'SECS')
    return 1.0 * 1000.0;
  if (unit == 'MINS')
    return 60.0 * 1000.0;
  if (unit == 'HOURS')
    return 3600.0 * 1000.0;
  return 86400.0 * 1000.0;
}

function makeMillisecondsDurationObject(length) {
  var dayInMsecs = 1000 * 60 * 60 * 24;

  if ((length % dayInMsecs) == 0)
    return new tizen.TimeDuration(length / dayInMsecs, 'DAYS');

  return new tizen.TimeDuration(length, 'MSECS');
}

tizen.TimeDuration.prototype.getMilliseconds = function() {
  return getMultiplier(this.unit) * this.length;
}

tizen.TimeDuration.prototype.difference = function(other) {
  try {
      return makeMillisecondsDurationObject(this.getMilliseconds() -
                                            other.getMilliseconds());
  } catch (e) {
      _throwProperTizenException(e);
  }
}

tizen.TimeDuration.prototype.equalsTo = function(other) {
  try {
      return this.getMilliseconds() == other.getMilliseconds();
  } catch (e) {
      _throwProperTizenException(e);
  }
}

tizen.TimeDuration.prototype.lessThan = function(other) {
  try {
      return this.getMilliseconds() < other.getMilliseconds();
  } catch (e) {
      _throwProperTizenException(e);
  }
}

tizen.TimeDuration.prototype.greaterThan = function(other) {
  try {
      return this.getMilliseconds() > other.getMilliseconds();
  } catch (e) {
      _throwProperTizenException(e);
  }
}

tizen.TimeDuration.prototype.toString = function() {
  return this.length + ' ' + this.unit;
}

tizen.TZDate = (function() {
  var TZDate = function(year, month, day, hours, minutes, seconds, milliseconds, timezone) {
    var date_;
    var hours = hours || 0;
    var minutes = minutes || 0;
    var seconds = seconds || 0;
    var milliseconds = milliseconds || 0;
    var timezone_ = timezone || tizen.time.getLocalTimezone();

    if (!arguments.length)
      date_ = new Date();
    else if (arguments[0] instanceof Date) {
      date_ = arguments[0];
      if (arguments[1])
        timezone_ = arguments[1];
    }
    else
      date_ = new Date(year, month, day, hours, minutes, seconds, milliseconds);

    var toTimezone = function(timezone) {
        return new TZDate(date_.getFullYear(), date_.getMonth(),
              date_.getDate(), date_.getHours(), date_.getMinutes(),
              date_.getSeconds(), date_.getMilliseconds(), timezone);
    };

    return {
      getDate: function() {
        return date_.getDate();
      },
      setDate: function(date) {
        date_.setDate(date);
      },
      getDay: function() {
        return date_.getDay();
      },
      getFullYear: function() {
        return date_.getFullYear();
      },
      setFullYear: function(year) {
        date_.setFullYear(year);
      },
      getHours: function() {
        return date_.getHours();
      },
      setHours: function(hours) {
        date_.setHours(hours);
      },
      getMilliseconds: function() {
        return date_.getMilliseconds();
      },
      setMilliseconds: function(ms) {
        date_.setMilliseconds(ms);
      },
      getMonth: function() {
        return date_.getMonth();
      },
      setMonth: function(month) {
        date_.setMonth(month);
      },
      getMinutes: function() {
        return date_.getMinutes();
      },
      setMinutes: function(minutes) {
        date_.setMinutes(minutes);
      },
      getSeconds: function() {
        return date_.getSeconds();
      },
      setSeconds: function(seconds) {
        date_.setSeconds(seconds);
      },
      getUTCDate: function() {
        return date_.getUTCDate();
      },
      setUTCDate: function(date) {
        date_.setUTCDate(date);
      },
      getUTCDay: function() {
        return date_.getUTCDay();
      },
      setUTCDay: function(day) {
        date_.setUTCDay(day);
      },
      getUTCFullYear: function() {
        return date_.getUTCFullYear();
      },
      setUTCFullYear: function(year) {
        date_.setUTCFullYear(year);
      },
      getUTCHours: function() {
        return date_.getUTCHours();
      },
      setUTCHours: function(hours) {
        date_.setUTCHours(hours);
      },
      getUTCMilliseconds: function() {
        return date_.getUTCMilliseconds();
      },
      setUTCMilliseconds: function(ms) {
        date_.setUTCMilliseconds(ms);
      },
      getUTCMinutes: function() {
        return date_.getUTCMinutes();
      },
      setUTCMinutes: function(minutes) {
        date_.setUTCMinutes(minutes);
      },
      getUTCMonth: function() {
        return date_.getUTCMonth();
      },
      setUTCMonth: function(month) {
        date_.setUTCMonth(month);
      },
      getUTCSeconds: function() {
        return date_.getUTCSeconds();
      },
      setUTCSeconds: function(secs) {
        date_.setUTCSeconds(secs);
      },
      getTime: function() {
        return date_.getTime();
      },
      getTimezone: function() {
        return timezone_;
      },
      toTimezone: function(timezone) {
        return toTimezone(timezone);
      },
      toLocalTimezone: function() {
        return toTimezone(getLocalTimezone());
      },
      toUTC: function() {
        return toTimezone('GMT')
      },
      difference: function(other) {
        try {
            return makeMillisecondsDurationObject(this.getTime() - other.getTime());
        } catch (e) {
            _throwProperTizenException(e);
        }
      },
      equalsTo: function(other) {
        try {
            return this.getTime() == other.getTime();
        } catch (e) {
            _throwProperTizenException(e);
        }
      },
      earlierThan: function(other) {
        try {
            return this.getTime() < other.getTime();
        } catch (e) {
            _throwProperTizenException(e);
        }
      },
      laterThan: function(other) {
        try {
            return this.getTime() > other.getTime();
        } catch(e) {
            _throwProperTizenException(e);
        }
      },
      addDuration: function(duration) {
        var date = new TZDate(date_.getFullYear(), date_.getMonth(),
              date_.getDate(), date_.getHours(), date_.getMinutes(),
              date_.getSeconds(), date_.getMilliseconds(), timezone_);
        date.setMilliseconds(duration.getMilliseconds() +
              date.getMilliseconds());
        return date;
      },
      toLocaleDateString: function() {
        return date_.toLocaleDateString();
      },
      toLocaleTimeString: function() {
        return date_.toLocaleTimeString();
      },
      toLocaleString: function() {
        return date_.toLocaleString();
      },
      toDateString: function() {
        return date_.toDateString();
      },
      toTimeString: function() {
        return date_.toTimeString();
      },
      toString: function() {
        var weekday = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri','Sat'][date_.getDay()];
        var month = [
              '', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
              'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][date_.getMonth()];
        function pad2(num) {
          return (100 + num).toString().substring(1);
        };
        var day = pad2(date_.getDay());
        var year = date_.getFullYear();
        var hour = pad2(date_.getHours());
        var minute = pad2(date_.getMinutes());
        var second = pad2(date_.getSeconds());
        var dateAsString = weekday + ', ' + month + ' ' + day + ' ' + year;
        var timeAsString = hour + ':' + minute + ':' + second;

        return dateAsString + ' ' + timeAsString;
      },
      getTimezoneAbbreviation: function() {
        var minutesToUTC = (new Date()).getTimezoneOffset();
        var hoursToUTC = - (minutesToUTC / 60);
        if (hoursToUTC < 0)
          return 'GMT' + hoursToUTC;
        return 'GMT+' + hoursToUTC;
      },
      secondsFromUTC: function() {
        return date_.getTimezoneOffset() * 60;
      },
      isDST: function() {
        return false;
      },
      getPreviousDSTTransition: function() {
        return void 0;
      },
      getNextDSTTransition: function() {
        return void 0;
      }
    };
  };
  return TZDate;
})();
<commit_msg>[Time] Fix the style of Time API JS File using the new checking tool.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

exports.getCurrentDateTime = function() {
  return new tizen.TZDate();
};

exports.getLocalTimezone = function() {
  var minutesToUTC = (new Date()).getTimezoneOffset();
  var hoursToUTC = - (minutesToUTC / 60);
  if (hoursToUTC < 0)
    return 'GMT' + hoursToUTC;
  return 'GMT+' + hoursToUTC;
};

exports.getAvailableTimezones = function() {
  return [
    tizen.time.getLocalTimezone()
  ];
};

exports.getDateFormat = function(shortformat) {
  if (shortformat)
    return 'd/m/y';
  return 'D, M d y';
};

exports.getTimeFormat = function() {
  return 'h:m:s';
};

exports.isLeapYear = function(year) {
  if (!(year % 400))
    return true;
  if (!(year % 100))
    return false;
  if (!(year % 4))
    return true;
  return false;
};

function _throwProperTizenException(e) {
  if (e instanceof TypeError)
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
  else if (e instanceof RangeError)
    throw new tizen.WebAPIException(tizen.WebAPIException.INVALID_VALUES_ERR);
  else
    throw new tizen.WebAPIException(tizen.WebAPIException.UNKNOWN_ERR);
}

var TimeDurationUnit = [
  'MSECS',
  'SECS',
  'MINS',
  'HOURS',
  'DAYS'
];

tizen.TimeDuration = function(length, unit) {
  this.length = length || 0;
  this.unit = unit || 'MSECS';

  Object.defineProperty(this, 'length', {
    get: function() {
      return length; },
    set: function(NewValue) {
      if (NewValue != null)
        length = NewValue; }});

  Object.defineProperty(this, 'unit', {
    get: function() {
      return unit; },
    set: function(NewValue) {
      if (NewValue in TimeDurationUnit)
        unit = NewValue; }});

  if (TimeDurationUnit.indexOf(this.unit) == -1)
    this.unit = 'MSECS';
};

function getMultiplier(unit) {
  if (unit == 'MSECS')
    return 1.0;
  if (unit == 'SECS')
    return 1.0 * 1000.0;
  if (unit == 'MINS')
    return 60.0 * 1000.0;
  if (unit == 'HOURS')
    return 3600.0 * 1000.0;
  return 86400.0 * 1000.0;
}

function makeMillisecondsDurationObject(length) {
  var dayInMsecs = 1000 * 60 * 60 * 24;

  if ((length % dayInMsecs) == 0)
    return new tizen.TimeDuration(length / dayInMsecs, 'DAYS');

  return new tizen.TimeDuration(length, 'MSECS');
}

tizen.TimeDuration.prototype.getMilliseconds = function() {
  return getMultiplier(this.unit) * this.length;
};

tizen.TimeDuration.prototype.difference = function(other) {
  try {
    return makeMillisecondsDurationObject(this.getMilliseconds() -
                                          other.getMilliseconds());
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TimeDuration.prototype.equalsTo = function(other) {
  try {
    return this.getMilliseconds() == other.getMilliseconds();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TimeDuration.prototype.lessThan = function(other) {
  try {
    return this.getMilliseconds() < other.getMilliseconds();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TimeDuration.prototype.greaterThan = function(other) {
  try {
    return this.getMilliseconds() > other.getMilliseconds();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TimeDuration.prototype.toString = function() {
  return this.length + ' ' + this.unit;
};

tizen.TZDate = (function() {
  var TZDate = function(year, month, day, hours, minutes, seconds, milliseconds, timezone) {
    var date_;
    var hours = hours || 0;
    var minutes = minutes || 0;
    var seconds = seconds || 0;
    var milliseconds = milliseconds || 0;
    var timezone_ = timezone || tizen.time.getLocalTimezone();

    if (!arguments.length)
      date_ = new Date();
    else if (arguments[0] instanceof Date) {
      date_ = arguments[0];
      if (arguments[1])
        timezone_ = arguments[1];
    }
    else
      date_ = new Date(year, month, day, hours, minutes, seconds, milliseconds);

    var toTimezone = function(timezone) {
      return new TZDate(date_.getFullYear(), date_.getMonth(), date_.getDate(),
                        date_.getHours(), date_.getMinutes(), date_.getSeconds(),
                        date_.getMilliseconds(), timezone);
    };

    return {
      getDate: function() {
        return date_.getDate();
      },
      setDate: function(date) {
        date_.setDate(date);
      },
      getDay: function() {
        return date_.getDay();
      },
      getFullYear: function() {
        return date_.getFullYear();
      },
      setFullYear: function(year) {
        date_.setFullYear(year);
      },
      getHours: function() {
        return date_.getHours();
      },
      setHours: function(hours) {
        date_.setHours(hours);
      },
      getMilliseconds: function() {
        return date_.getMilliseconds();
      },
      setMilliseconds: function(ms) {
        date_.setMilliseconds(ms);
      },
      getMonth: function() {
        return date_.getMonth();
      },
      setMonth: function(month) {
        date_.setMonth(month);
      },
      getMinutes: function() {
        return date_.getMinutes();
      },
      setMinutes: function(minutes) {
        date_.setMinutes(minutes);
      },
      getSeconds: function() {
        return date_.getSeconds();
      },
      setSeconds: function(seconds) {
        date_.setSeconds(seconds);
      },
      getUTCDate: function() {
        return date_.getUTCDate();
      },
      setUTCDate: function(date) {
        date_.setUTCDate(date);
      },
      getUTCDay: function() {
        return date_.getUTCDay();
      },
      setUTCDay: function(day) {
        date_.setUTCDay(day);
      },
      getUTCFullYear: function() {
        return date_.getUTCFullYear();
      },
      setUTCFullYear: function(year) {
        date_.setUTCFullYear(year);
      },
      getUTCHours: function() {
        return date_.getUTCHours();
      },
      setUTCHours: function(hours) {
        date_.setUTCHours(hours);
      },
      getUTCMilliseconds: function() {
        return date_.getUTCMilliseconds();
      },
      setUTCMilliseconds: function(ms) {
        date_.setUTCMilliseconds(ms);
      },
      getUTCMinutes: function() {
        return date_.getUTCMinutes();
      },
      setUTCMinutes: function(minutes) {
        date_.setUTCMinutes(minutes);
      },
      getUTCMonth: function() {
        return date_.getUTCMonth();
      },
      setUTCMonth: function(month) {
        date_.setUTCMonth(month);
      },
      getUTCSeconds: function() {
        return date_.getUTCSeconds();
      },
      setUTCSeconds: function(secs) {
        date_.setUTCSeconds(secs);
      },
      getTime: function() {
        return date_.getTime();
      },
      getTimezone: function() {
        return timezone_;
      },
      toTimezone: function(timezone) {
        return toTimezone(timezone);
      },
      toLocalTimezone: function() {
        return toTimezone(getLocalTimezone());
      },
      toUTC: function() {
        return toTimezone('GMT');
      },
      difference: function(other) {
        try {
          return makeMillisecondsDurationObject(this.getTime() - other.getTime());
        } catch (e) {
          _throwProperTizenException(e);
        }
      },
      equalsTo: function(other) {
        try {
          return this.getTime() == other.getTime();
        } catch (e) {
          _throwProperTizenException(e);
        }
      },
      earlierThan: function(other) {
        try {
          return this.getTime() < other.getTime();
        } catch (e) {
          _throwProperTizenException(e);
        }
      },
      laterThan: function(other) {
        try {
          return this.getTime() > other.getTime();
        } catch (e) {
          _throwProperTizenException(e);
        }
      },
      addDuration: function(duration) {
        var date = new TZDate(date_.getFullYear(), date_.getMonth(), date_.getDate(),
                              date_.getHours(), date_.getMinutes(), date_.getSeconds(),
                              date_.getMilliseconds(), timezone_);
        date.setMilliseconds(duration.getMilliseconds() + date.getMilliseconds());
        return date;
      },
      toLocaleDateString: function() {
        return date_.toLocaleDateString();
      },
      toLocaleTimeString: function() {
        return date_.toLocaleTimeString();
      },
      toLocaleString: function() {
        return date_.toLocaleString();
      },
      toDateString: function() {
        return date_.toDateString();
      },
      toTimeString: function() {
        return date_.toTimeString();
      },
      toString: function() {
        var weekday = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][date_.getDay()];
        var month = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
                     'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][date_.getMonth()];
        function pad2(num) {
          return (100 + num).toString().substring(1);
        };
        var day = pad2(date_.getDay());
        var year = date_.getFullYear();
        var hour = pad2(date_.getHours());
        var minute = pad2(date_.getMinutes());
        var second = pad2(date_.getSeconds());
        var dateAsString = weekday + ', ' + month + ' ' + day + ' ' + year;
        var timeAsString = hour + ':' + minute + ':' + second;

        return dateAsString + ' ' + timeAsString;
      },
      getTimezoneAbbreviation: function() {
        var minutesToUTC = (new Date()).getTimezoneOffset();
        var hoursToUTC = - (minutesToUTC / 60);
        if (hoursToUTC < 0)
          return 'GMT' + hoursToUTC;
        return 'GMT+' + hoursToUTC;
      },
      secondsFromUTC: function() {
        return date_.getTimezoneOffset() * 60;
      },
      isDST: function() {
        return false;
      },
      getPreviousDSTTransition: function() {
        return void 0;
      },
      getNextDSTTransition: function() {
        return void 0;
      }
    };
  };
  return TZDate;
})();
<|endoftext|>


<commit_before>(function () {
  /**
   * Send a jsonp request (useful for cross-domain requests) by
   * inserting a <script> into the page.
   *
   * @param {string} opts.url (REQUIRED)  Request URL
   * @param {function} opts.cb (REQUIRED)  Callback which will receive
   * the parsed object from the original JSON string
   * @param {function} opts.cbParam  Parameter name to append the jsonp
   * callback parameter to; defaults to "callback"
   *
   * @returns {string} The ID of the request, which can be used to remove
   * the script manually from the page if desired (each is given a
   * "data-cb_contentpush_jsonp-id" attribute set to this returned ID);
   * NB <script> elements are inserted into the body of the page
   */

  /* unique identifier for callbacks, incremented each time we create one */
  var cbId = 1;

  /* prefix for our callbacks (which are attached to the window) */
  var cbKey = '_contentpush_jsonp';

  var jsonp = function (opts) {
    var thisCbId = cbId;

    var url = opts.url +
              /* if no question mark, add one */
              (/\?/.test(opts.url) ? '' : '?') +

              /* if at least one character in querystring, add '&' */
              (/\?.+/.test(opts.url) ? '&' : '') +

              (opts.cbParam || 'callback') +
              '=' + cbKey + thisCbId;

    var script = document.createElement('script');
    script.setAttribute('data-cb' + cbKey + '-id', thisCbId);
    script.src = url;

    /* we make a uniquely-named callback function, globally visible,
       which will be invoked with the object parsed from the response */
    window[cbKey + thisCbId] = function (obj) {
      /* invoke the original callback */
      opts.cb(obj);

      /* remove _this_ global callback */
      window[cbKey + thisCbId] = null;
    };

    /* make the magic happen */
    document.body.appendChild(script);

    /* increment the counter ready to create the next callback */
    cbId++;

    return thisCbId;
  };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = jsonp;
  }
  else {
    window.jsonp = jsonp;
  }
})();
<commit_msg>Add license header to jsonp.js.<commit_after>/*
 * Natural Language Processing Library for JavaScript
 *
 * A client-side NLP utility library for web applications
 *
 * Copyright 2015 Intel Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *
 *
 * Authors:
 *   Elliot Smith <elliot.smith@intel.com>
 *   Max Waterman <max.waterman@intel.com>
 *   Plamena Manolova <plamena.manolova@intel.com>
 */

(function () {
  /**
   * Send a jsonp request (useful for cross-domain requests) by
   * inserting a <script> into the page.
   *
   * @param {string} opts.url (REQUIRED)  Request URL
   * @param {function} opts.cb (REQUIRED)  Callback which will receive
   * the parsed object from the original JSON string
   * @param {function} opts.cbParam  Parameter name to append the jsonp
   * callback parameter to; defaults to "callback"
   *
   * @returns {string} The ID of the request, which can be used to remove
   * the script manually from the page if desired (each is given a
   * "data-cb_contentpush_jsonp-id" attribute set to this returned ID);
   * NB <script> elements are inserted into the body of the page
   */

  /* unique identifier for callbacks, incremented each time we create one */
  var cbId = 1;

  /* prefix for our callbacks (which are attached to the window) */
  var cbKey = '_contentpush_jsonp';

  var jsonp = function (opts) {
    var thisCbId = cbId;

    var url = opts.url +
              /* if no question mark, add one */
              (/\?/.test(opts.url) ? '' : '?') +

              /* if at least one character in querystring, add '&' */
              (/\?.+/.test(opts.url) ? '&' : '') +

              (opts.cbParam || 'callback') +
              '=' + cbKey + thisCbId;

    var script = document.createElement('script');
    script.setAttribute('data-cb' + cbKey + '-id', thisCbId);
    script.src = url;

    /* we make a uniquely-named callback function, globally visible,
       which will be invoked with the object parsed from the response */
    window[cbKey + thisCbId] = function (obj) {
      /* invoke the original callback */
      opts.cb(obj);

      /* remove _this_ global callback */
      window[cbKey + thisCbId] = null;
    };

    /* make the magic happen */
    document.body.appendChild(script);

    /* increment the counter ready to create the next callback */
    cbId++;

    return thisCbId;
  };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = jsonp;
  }
  else {
    window.jsonp = jsonp;
  }
})();
<|endoftext|>


<commit_before>import React, { Component, Fragment } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as chartActions from '../actions/chart';
import AlbumsContainer from './AlbumsContainer';
import MoviesContainer from './MoviesContainer';
import Chart from '../components/Chart/Chart';
import Header from '../components/Header/Header';
// import * as api from '../api/api';

import createHistory from 'history/createBrowserHistory';
import { Router, Route, Link } from 'react-router-dom';

const history = createHistory({
  basename: '/chartify/example/',
  // forceRefresh: false,
});

class AppContainer extends Component {
  constructor(props) {
    super();
    const { actions } = props;

    // this.state = {
    //   timeMetadata: {
    //     container: 'real-time-container',
    //     header: 'Real-time chart',
    //     total: 'items total ( X - mark date, Y - mark )',
    //     chart: 'time',
    //     getDataset: null, // api.connect
    //   },
    // };
  }

  render() {
    const {
      actions,
    } = this.props;

    return (
      <Router history={history}>
        <Fragment>
          <Header />
          <Route exact path="/" component={AlbumsContainer} />
          <Route path="/albums" component={AlbumsContainer} />
          <Route path="/movies" component={MoviesContainer} />
        </Fragment>
      </Router>
    );
  }
}

const mapStateToProps = state => ({
  // time: state.time,
});

const mapDispatchToProps = dispatch => ({
  actions: bindActionCreators(chartActions, dispatch),
});

export default connect(mapStateToProps, mapDispatchToProps)(AppContainer);
<commit_msg>add switch and no match routes<commit_after>import React, { Component, Fragment } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as chartActions from '../actions/chart';
import AlbumsContainer from './AlbumsContainer';
import MoviesContainer from './MoviesContainer';
import Chart from '../components/Chart/Chart';
import Header from '../components/Header/Header';
// import * as api from '../api/api';

import createHistory from 'history/createBrowserHistory';
import { Router, Switch, Route, Link } from 'react-router-dom';

const history = createHistory({
  basename: '/chartify/example/',
  // forceRefresh: false,
});

class AppContainer extends Component {
  constructor(props) {
    super();
    const { actions } = props;

    // this.state = {
    //   timeMetadata: {
    //     container: 'real-time-container',
    //     header: 'Real-time chart',
    //     total: 'items total ( X - mark date, Y - mark )',
    //     chart: 'time',
    //     getDataset: null, // api.connect
    //   },
    // };
  }

  render() {
    const {
      actions,
    } = this.props;

    return (
      <Router history={history}>
        <Fragment>
          <Header />
          <Switch>
            <Route exact path="/" component={AlbumsContainer} />
            <Route path="/albums" component={AlbumsContainer} />
            <Route path="/movies" component={MoviesContainer} />
            <Route path="" component={AlbumsContainer} />
            <Route path="**" component={AlbumsContainer} />
          </Switch>
        </Fragment>
      </Router>
    );
  }
}

const mapStateToProps = state => ({
  // time: state.time,
});

const mapDispatchToProps = dispatch => ({
  actions: bindActionCreators(chartActions, dispatch),
});

export default connect(mapStateToProps, mapDispatchToProps)(AppContainer);
<|endoftext|>


<commit_before>import {
  default as React,
} from "react";

import {
  WebpackScriptEntry,
  WebpackStyleEntry,
  ReactRenderToStringEntry,
} from "reacthtmlpack/lib/entry";

export default (
  <html>
    <head>
      <title>React Google Maps | tomchentw</title>
      <meta name="viewport" content="width=device-width, initial-scale=1"/>
      <meta charSet="UTF-8" />
      <WebpackStyleEntry
        chunkName="client"
        chunkFilepath="./scripts/client.js"
        configFilepath="../Client.webpackConfig.js"
      />
      <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places" />
      <script type="text/javascript" src="prism.min.js" />
    </head>
    <body>
      <ReactRenderToStringEntry
        id="react-container"
        tagName="div"
        chunkName="server"
        chunkFilepath="./scripts/ReactRoot.js"
        configFilepath="../Server.webpackConfig.js"
      />
      <WebpackScriptEntry
        chunkName="client"
        chunkFilepath="./scripts/client.js"
        configFilepath="../Client.webpackConfig.js"
      />
    </body>
  </html>
);
<commit_msg>docs(gh-pages): use WebpackScriptEntry to load prism<commit_after>import {
  default as React,
} from "react";

import {
  WebpackScriptEntry,
  WebpackStyleEntry,
  ReactRenderToStringEntry,
} from "reacthtmlpack/lib/entry";

export default (
  <html>
    <head>
      <title>React Google Maps | tomchentw</title>
      <meta name="viewport" content="width=device-width, initial-scale=1"/>
      <meta charSet="UTF-8" />
      <WebpackStyleEntry
        chunkName="client"
        chunkFilepath="./scripts/client.js"
        configFilepath="../Client.webpackConfig.js"
      />
      <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places" />
      <WebpackScriptEntry
        chunkName="prism"
        chunkFilepath={require.resolve("prismjs")}
        configFilepath="../Client.webpackConfig.js"
      />
    </head>
    <body>
      <ReactRenderToStringEntry
        id="react-container"
        tagName="div"
        chunkName="server"
        chunkFilepath="./scripts/ReactRoot.js"
        configFilepath="../Server.webpackConfig.js"
      />
      <WebpackScriptEntry
        chunkName="client"
        chunkFilepath="./scripts/client.js"
        configFilepath="../Client.webpackConfig.js"
      />
    </body>
  </html>
);
<|endoftext|>


<commit_before>document.addEventListener('DOMContentLoaded', () => {

  // sets up canvas variables; sets width to window
  const canvas = document.querySelector('.board');
  const context = canvas.getContext('2d');
  canvas.height = `${window.innerWidth}`;
  canvas.width = `${window.innerWidth}`;
  context.globalAlpha=0.8;

  // sets up board variables
  let board = [];
  let game = {
    rows: 50,
    columns: 50,
    margin: 1,
    speed: 200,
    density: 1.2,
    pxWide: canvas.width,
    pxHigh: canvas.height,
    cellColor: '#FF4136',
    background: 'rgb(250, 250, 250)',
  };

// // implementation of offscreen canvas is still shaky, but might speed up performance
// board.offscreenCanvas = document.createElement("canvas");
// board.offscreenCanvas.width = game.pxHigh;
// board.offscreenCanvas.height = game.pxWide;
// board.offscreenContext = board.offscreenCanvas.getContext("2d");

  // adapted from http://cobwwweb.com/mutlicolored-dotted-grid-canvas
  // Because we don't know which direction (x vs. y) is the limiting sizing
  // factor, we'll calculate both first.
  const dotWidth = ((game.pxWide - (2 * game.margin)) / game.columns) - game.margin;
  const dotHeight = ((game.pxHigh - (2 * game.margin)) / game.rows) - game.margin;
  // Now, we use the limiting dimension to set the diameter.
  if( dotWidth > dotHeight )
  {
    var dotDiameter = dotHeight;
    var xMargin = (game.pxWide - ((2 * game.margin) + (game.columns * dotDiameter))) / game.columns;
    var yMargin = game.margin;
  }
  else
  { var dotDiameter = dotWidth;
    var xMargin = game.margin;
    var yMargin = (game.pxHigh - ((2 * game.margin) + (game.rows * dotDiameter))) / game.rows;
  }
  // Radius is still half of the diameter, because ... math.
  const dotRadius = Math.abs(dotDiameter) * 0.5;

  // initializes a new board, and randomly seeds it with new 'life' i.e. red squares / 1's
  function initBoard () {
    board = [];
   for (var r=0; r < game.rows; r++) {
        board.push([]);
   };

   for (var row = 0; row < game.rows; row++) {
    for (var column = 0; column < game.columns; column++) {
      var randNum = Math.floor(Math.random()*game.density);
      board[row].push(randNum);
    }
  }
}

  // creates and returns an array full of 0's
  function clearBoard() {
    board = [];
  for (var r=0; r < game.rows; r++) {
        board.push([]);
   }
   for (var row = 0; row < game.rows; row++) {
    for (var column = 0; column < game.columns; column++) {
      board[row].push(0);
      }
    }
  }

  // sums up and returns all the neighbors values in the array
  // checks to see if the neighbor position is out of bounds
  function neighborSum (x, y)  {
    let sum = 0;
    xBound = game.columns - 1;
    yBound = game.rows - 1;
    let b = board;

    if ((x === 0) && (y === 0)){
      sum =  b[x+1][y+1]+ b[x+1][y] + b[x][y+1];
    } else if ((x === xBound) && (y === yBound)){
      sum = b[x-1][y]+ b[x-1][y-1] + b[x][y-1];
    } else if ((x === 0) && (y === yBound)){
      sum = b[x][y-1]+ b[x+1][y-1] + b[x+1][y];
    } else if ((x === xBound) && (y === 0)){
      sum = b[x-1][y]+ b[x-1][y+1] + b[x][y+1];
    } else if (x === xBound){
      sum = b[x][y+1] + b[x][y-1] + b[x-1][y+1] + b[x-1][y-1] + b[x-1][y];
    } else if (y === yBound){
      sum = b[x+1][y] + b[x-1][y] + b[x+1][y-1] + b[x][y-1] + b[x-1][y-1];
    } else if (x === 0){
      sum = b[x][y+1] + b[x][y-1] + b[x+1][y+1] + b[x+1][y] + b[x+1][y-1];
    } else if (y === 0){
      sum = b[x+1][y] + b[x-1][y] + b[x+1][y+1] + b[x][y+1] + b[x-1][y+1];
    } else {
      sum = b[x+1][y] + b[x-1][y] + b[x][y+1] + b[x][y-1] + b[x+1][y+1] + b[x-1][y-1]+ b[x+1][y-1]+ b[x-1][y+1];

    }
    return sum;
  }

    function lifeGen() {
      context.fillStyle = game.background;
      // clears the board with an overlay
      context.fillRect( 0, 0, game.pxWide, game.pxHigh)
      context.fillStyle = game.cellColor;
      let x = 0,
          y = -1,
          yBound = 0,
          arrLen = board[0].length;
      // using the format array = array.map(items=>items.map(item=>item))
      board = board.map( function (items) {
      y++;
      return items.map( function (cellVal) {
         // resets the board length counter to prevent overflow
         if (x === arrLen) {
           x = 0;
         };
         var neighbors = neighborSum (y, x);
         var state = null;
          // Basic rules of Conway's Game of Life:
          // If the cell is alive, then it stays alive only if it has  2 or 3 live neighbors.
          if ((cellVal === 1) && (( neighbors <= 3 ) && (neighbors >= 2))) {
           state = 1;
           drawDot(x, y, dotRadius);
         // If the cell is dead, then it becomes alive only if it has 3 live neighbors.
         } else if ((cellVal === 0) && (neighbors === 3)) {
           state = 1;
            drawDot(x, y, dotRadius);
         } else {
           state = 0;
         };
         x++;
         return state;
       });
      });
      // board.render(board.offscreenContext);
    }

  // draws each 'dot' - currently in the shape of a rectangle.
  function drawDot(x, y, radius, color) {
    // calculates the dot positioning based on the px margin, px diameter and board position
    const xPos = (x * (dotDiameter + xMargin)) + game.margin + (xMargin / 2) + dotRadius;
    const yPos = (y * (dotDiameter + yMargin)) + game.margin + (yMargin / 2) + dotRadius;
    context.fillRect(xPos, yPos, radius*2, radius*2);
    // context.beginPath();
    // context.arc(x, y, radius, 0, 2 * Math.PI, false);
    // context.fill();
  }

  // button handlers
  document.querySelector('.pause').addEventListener('click', pauseHandler);
  document.querySelector('.reset').addEventListener('click', resetHandler);
  document.querySelector('.clear').addEventListener('click', clearHandler);

  // pauses the animation on click
  function pauseHandler(e) {
    e.stopPropagation();
    e.preventDefault();
    if (gameOfLife) {
      clearInterval(gameOfLife);
      gameOfLife = null;
    }
    else {
      gameOfLife = setInterval(lifeGen, game.speed);
    }
  }

  function resetHandler(e) {
    e.stopPropagation();
    e.preventDefault();
    clearInterval(gameOfLife);
    context.fillStyle = game.background;
    context.fillRect( 0, 0, game.pxWide, game.pxHigh);
    initBoard();
    if (gameOfLife) gameOfLife = setInterval(lifeGen, game.speed);
    else lifeGen();
  }

  function clearHandler(e) {
    e.stopPropagation();
    e.preventDefault();
    clearBoard();
    context.fillStyle = game.background;
    context.fillRect( 0, 0, game.pxWide, game.pxHigh);
  }

  // event listeners for edit functionality
  document.addEventListener('mousedown', toggleCell)
  document.addEventListener('mouseup', () => document.removeEventListener('mousemove', dragCell));

  // helper class that sets/gets the position and state of a cell given a location event
  class cell {
    constructor(xPos, yPos) {
      // converts the screen position to the 2d grid position
      this.x = Math.floor((xPos / (dotDiameter + xMargin)) + game.margin + (xMargin / 2) - xMargin) - 1;
      this.y = Math.floor((yPos / (dotDiameter + yMargin)) + game.margin + (yMargin / 2) - yMargin) - 1;
    }
    // getter and setter for the cell state
    get state() {
      return board[this.y][this.x]
    }
    set state(val) {
      console.log(val);
      board[this.y][this.x] = val;
    }
    draw(bit) {
      if (this.state != bit) {
        context.fillStyle = this.state ? game.background : game.cellColor
        drawDot(this.x, this.y, dotRadius)
      }
    }
  }

  function toggleCell(e) {
    let mousePos = new cell(e.clientX, e.clientY);
    e.shiftKey ? mousePos.draw(0) : mousePos.draw(1)
    document.addEventListener('mousemove', dragCell);
  }

  function dragCell(e){
    let dragPos = new cell(e.clientX, e.clientY);
    e.shiftKey ? dragPos.draw(0) : dragPos.draw(1)
  }

  initBoard();
  let gameOfLife = setInterval(lifeGen, game.speed);

});
<commit_msg>corrected out-of-bounds draw<commit_after>document.addEventListener('DOMContentLoaded', () => {

  // sets up canvas variables; sets width to window
  const canvas = document.querySelector('.board');
  const context = canvas.getContext('2d');
  canvas.height = `${window.innerWidth}`;
  canvas.width = `${window.innerWidth}`;
  context.globalAlpha=0.8;

  // sets up board variables
  let board = [];
  let game = {
    rows: 50,
    columns: 50,
    margin: 1,
    speed: 200,
    density: 1.2,
    pxWide: canvas.width,
    pxHigh: canvas.height,
    cellColor: '#FF4136',
    background: 'rgb(250, 250, 250)',
  };

// // implementation of offscreen canvas is still shaky, but might speed up performance
// board.offscreenCanvas = document.createElement("canvas");
// board.offscreenCanvas.width = game.pxHigh;
// board.offscreenCanvas.height = game.pxWide;
// board.offscreenContext = board.offscreenCanvas.getContext("2d");

  // adapted from http://cobwwweb.com/mutlicolored-dotted-grid-canvas
  // Because we don't know which direction (x vs. y) is the limiting sizing
  // factor, we'll calculate both first.
  const dotWidth = ((game.pxWide - (2 * game.margin)) / game.columns) - game.margin;
  const dotHeight = ((game.pxHigh - (2 * game.margin)) / game.rows) - game.margin;
  // Now, we use the limiting dimension to set the diameter.
  if( dotWidth > dotHeight )
  {
    var dotDiameter = dotHeight;
    var xMargin = (game.pxWide - ((2 * game.margin) + (game.columns * dotDiameter))) / game.columns;
    var yMargin = game.margin;
  }
  else
  { var dotDiameter = dotWidth;
    var xMargin = game.margin;
    var yMargin = (game.pxHigh - ((2 * game.margin) + (game.rows * dotDiameter))) / game.rows;
  }
  // Radius is still half of the diameter, because ... math.
  const dotRadius = Math.abs(dotDiameter) * 0.5;

  // initializes a new board, and randomly seeds it with new 'life' i.e. red squares / 1's
  function initBoard () {
    board = [];
   for (var r=0; r < game.rows; r++) {
        board.push([]);
   };

   for (var row = 0; row < game.rows; row++) {
    for (var column = 0; column < game.columns; column++) {
      var randNum = Math.floor(Math.random()*game.density);
      board[row].push(randNum);
    }
  }
}

  // creates and returns an array full of 0's
  function clearBoard() {
    board = [];
  for (var r=0; r < game.rows; r++) {
        board.push([]);
   }
   for (var row = 0; row < game.rows; row++) {
    for (var column = 0; column < game.columns; column++) {
      board[row].push(0);
      }
    }
  }

  // sums up and returns all the neighbors values in the array
  // checks to see if the neighbor position is out of bounds
  function neighborSum (x, y)  {
    let sum = 0;
    xBound = game.columns - 1;
    yBound = game.rows - 1;
    let b = board;

    if ((x === 0) && (y === 0)){
      sum =  b[x+1][y+1]+ b[x+1][y] + b[x][y+1];
    } else if ((x === xBound) && (y === yBound)){
      sum = b[x-1][y]+ b[x-1][y-1] + b[x][y-1];
    } else if ((x === 0) && (y === yBound)){
      sum = b[x][y-1]+ b[x+1][y-1] + b[x+1][y];
    } else if ((x === xBound) && (y === 0)){
      sum = b[x-1][y]+ b[x-1][y+1] + b[x][y+1];
    } else if (x === xBound){
      sum = b[x][y+1] + b[x][y-1] + b[x-1][y+1] + b[x-1][y-1] + b[x-1][y];
    } else if (y === yBound){
      sum = b[x+1][y] + b[x-1][y] + b[x+1][y-1] + b[x][y-1] + b[x-1][y-1];
    } else if (x === 0){
      sum = b[x][y+1] + b[x][y-1] + b[x+1][y+1] + b[x+1][y] + b[x+1][y-1];
    } else if (y === 0){
      sum = b[x+1][y] + b[x-1][y] + b[x+1][y+1] + b[x][y+1] + b[x-1][y+1];
    } else {
      sum = b[x+1][y] + b[x-1][y] + b[x][y+1] + b[x][y-1] + b[x+1][y+1] + b[x-1][y-1]+ b[x+1][y-1]+ b[x-1][y+1];

    }
    return sum;
  }

    function lifeGen() {
      context.fillStyle = game.background;
      // clears the board with an overlay
      context.fillRect( 0, 0, game.pxWide, game.pxHigh)
      context.fillStyle = game.cellColor;
      let x = 0,
          y = -1,
          yBound = 0,
          arrLen = board[0].length;
      // using the format array = array.map(items=>items.map(item=>item))
      board = board.map( function (items) {
      y++;
      return items.map( function (cellVal) {
         // resets the board length counter to prevent overflow
         if (x === arrLen) {
           x = 0;
         };
         var neighbors = neighborSum (y, x);
         var state = null;
          // Basic rules of Conway's Game of Life:
          // If the cell is alive, then it stays alive only if it has  2 or 3 live neighbors.
          if ((cellVal === 1) && (( neighbors <= 3 ) && (neighbors >= 2))) {
           state = 1;
           drawDot(x, y, dotRadius);
         // If the cell is dead, then it becomes alive only if it has 3 live neighbors.
         } else if ((cellVal === 0) && (neighbors === 3)) {
           state = 1;
            drawDot(x, y, dotRadius);
         } else {
           state = 0;
         };
         x++;
         return state;
       });
      });
      // board.render(board.offscreenContext);
    }

  // draws each 'dot' - currently in the shape of a rectangle.
  function drawDot(x, y, radius, color) {
    // calculates the dot positioning based on the px margin, px diameter and board position
    const xPos = (x * (dotDiameter + xMargin)) + game.margin + (xMargin / 2) + dotRadius;
    const yPos = (y * (dotDiameter + yMargin)) + game.margin + (yMargin / 2) + dotRadius;
    context.fillRect(xPos, yPos, radius*2, radius*2);
    // context.beginPath();
    // context.arc(x, y, radius, 0, 2 * Math.PI, false);
    // context.fill();
  }

  // button handlers
  document.querySelector('.pause').addEventListener('click', pauseHandler);
  document.querySelector('.reset').addEventListener('click', resetHandler);
  document.querySelector('.clear').addEventListener('click', clearHandler);

  // pauses the animation on click
  function pauseHandler(e) {
    e.stopPropagation();
    e.preventDefault();
    if (gameOfLife) {
      clearInterval(gameOfLife);
      gameOfLife = null;
    }
    else {
      gameOfLife = setInterval(lifeGen, game.speed);
    }
  }

  function resetHandler(e) {
    e.stopPropagation();
    e.preventDefault();
    clearInterval(gameOfLife);
    context.fillStyle = game.background;
    context.fillRect( 0, 0, game.pxWide, game.pxHigh);
    initBoard();
    if (gameOfLife) gameOfLife = setInterval(lifeGen, game.speed);
    else lifeGen();
  }

  function clearHandler(e) {
    e.stopPropagation();
    e.preventDefault();
    clearBoard();
    context.fillStyle = game.background;
    context.fillRect( 0, 0, game.pxWide, game.pxHigh);
  }

  // event listeners for edit functionality
  document.addEventListener('mousedown', toggleCell)
  document.addEventListener('mouseup', () => document.removeEventListener('mousemove', dragCell));

  // helper class that gets/sets the cell state and draws to canvas given the px coordinates
  class cell {
    constructor(xPos, yPos) {
      // converts the screen position to the 2d grid position
      this.x = Math.floor((xPos / (dotDiameter + xMargin)) + game.margin + (xMargin / 2) - xMargin) - 1;
      this.y = Math.floor((yPos / (dotDiameter + yMargin)) + game.margin + (yMargin / 2) - yMargin) - 1;
    }
    // getter and setter for the cell state
    get state() {
      return board[this.y][this.x]
    }
    set state(val) {
      console.log(val);
      board[this.y][this.x] = val;
    }
    // flips the cell bit to the designated state and draws to canvas
    draw(bit) {
      if (this.state != bit) {
        this.state = bit;
        context.fillStyle = bit ? game.cellColor: game.background
        drawDot(this.x, this.y, dotRadius)
      }
    }
  }

  function toggleCell(e) {
    let mousePos = new cell(e.clientX, e.clientY);
    e.shiftKey ? mousePos.draw(0) : mousePos.draw(1)
    document.addEventListener('mousemove', dragCell);
  }

  function dragCell(e){
    console.log(e);
    if ((0 < e.clientX && e.clientX < game.pxWide) && (0 < e.clientY && e.clientY < game.pxHigh)) {
      let dragPos = new cell(e.clientX, e.clientY);
      e.shiftKey ? dragPos.draw(0) : dragPos.draw(1)
    }
  }

  initBoard();
  let gameOfLife = setInterval(lifeGen, game.speed);

});
<|endoftext|>