<commit_before>/* eslint-disable new-cap,global-require,no-param-reassign */
import React from 'react';
import { Helmet } from 'react-helmet';
import { Provider } from 'react-redux';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';

import store from '../src/store';
import routes from '../src/routes';

const fs = require('fs');
const express = require('express');
const path = require('path');
const logger = require('morgan');
const bodyParser = require('body-parser');
const http = require('http');
const https = require('https');
const cors = require('cors');

http.globalAgent.maxSockets = Infinity;
https.globalAgent.maxSockets = Infinity;

const OneWeek = 1000 * 60 * 60 * 24 * 7;

const app = express();
const server = http.Server(app);
const io = require('socket.io')(server);

const rootDir = path.join(__dirname, '..');

if (process.env.NODE_ENV !== 'production') { require('../webpack')(app); }

app.locals.env = process.env;
app.enable('trust proxy');
app.set('view engine', 'ejs');

app.use((req, res, next) => {
  res.io = io;
  next();
});

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());

if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(rootDir, 'public'), { maxAge: OneWeek }));
} else {
  app.use(express.static(path.join(rootDir, 'assets')));
}

app.use(express.static(path.join(rootDir, 'node_modules')));

if (!process.env.IS_BROWSER) { global.window = {}; }

const indexPath = process.env.NODE_ENV === 'production' ?
  `${rootDir}/public/index.html` :
  `${rootDir}/templates/development_index.html`;

const indexHtml = fs.readFileSync(indexPath, 'utf-8');

function fetchComponentData(dispatch, components, params) {
  const needs = components.reduce((prev, current) => (current.needs || [])
    .concat((current.WrappedComponent ? current.WrappedComponent.needs : []) || [])
    .concat(prev), []);
  const promises = needs.map((need) => {
    const pros = dispatch(need(params));
    // console.log('pros', pros);
    return pros;
  });
  console.log('promises', needs, Date.now());
  return Promise.all(promises);
}
function renderPage(props) {
  console.log('renderPage', Date.now());
  const appHtml = renderToString(
    <Provider store={store}>
      <RouterContext {...props} />
    </Provider>);

  const preloadedState = store.getState();
  const helmet = Helmet.renderStatic();
  const header = helmet.meta.toString() + helmet.title.toString() + helmet.link.toString();
  return indexHtml
    .replace('<!--server:header-->', header)
    .replace('<!--server:html-->', appHtml)
    .replace('<!--server:scripts-->',
    `<script>
        // WARNING: See the following for security issues around embedding JSON in HTML:
        // http://redux.js.org/docs/recipes/ServerRendering.html#security-considerations
        window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
    </script>`
    );
}

app.get('/*', (req, res) => {
  match({ routes, location: req.url }, (err, redirect, props) => {
    fetchComponentData(store.dispatch, props.components, props.params)
      .then(() => renderPage(props))
      .then(html => res.end(html))
      .catch(error => res.end(error.message));
  });
});

module.exports = { app, server };
<commit_msg>Server render for post only<commit_after>/* eslint-disable new-cap,global-require,no-param-reassign */
import React from 'react';
import { Helmet } from 'react-helmet';
import { Provider } from 'react-redux';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';

import store from '../src/store';
import routes from '../src/routes';

const fs = require('fs');
const express = require('express');
const path = require('path');
const logger = require('morgan');
const bodyParser = require('body-parser');
const http = require('http');
const https = require('https');
const cors = require('cors');

http.globalAgent.maxSockets = Infinity;
https.globalAgent.maxSockets = Infinity;

const OneWeek = 1000 * 60 * 60 * 24 * 7;

const app = express();
const server = http.Server(app);
const io = require('socket.io')(server);

const rootDir = path.join(__dirname, '..');

if (process.env.NODE_ENV !== 'production') { require('../webpack')(app); }

app.locals.env = process.env;
app.enable('trust proxy');
app.set('view engine', 'ejs');

app.use((req, res, next) => {
  res.io = io;
  next();
});

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());

if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(rootDir, 'public'), { maxAge: OneWeek }));
} else {
  app.use(express.static(path.join(rootDir, 'assets')));
}

app.use(express.static(path.join(rootDir, 'node_modules')));

if (!process.env.IS_BROWSER) { global.window = {}; }

const indexPath = process.env.NODE_ENV === 'production' ?
  `${rootDir}/public/index.html` :
  `${rootDir}/templates/development_index.html`;

const indexHtml = fs.readFileSync(indexPath, 'utf-8');

function fetchComponentData(dispatch, components, params) {
  const needs = components.reduce((prev, current) => (current.needs || [])
    .concat((current.WrappedComponent ? current.WrappedComponent.needs : []) || [])
    .concat(prev), []);
  const promises = needs.map((need) => {
    const pros = dispatch(need(params));
    // console.log('pros', pros);
    return pros;
  });
  console.log('promises', needs, Date.now());
  return Promise.all(promises);
}
function renderPage(props) {
  console.log('renderPage', Date.now());
  const appHtml = renderToString(
    <Provider store={store}>
      <RouterContext {...props} />
    </Provider>);

  const preloadedState = store.getState();
  const helmet = Helmet.renderStatic();
  const header = helmet.meta.toString() + helmet.title.toString() + helmet.link.toString();
  return indexHtml
    .replace('<!--server:header-->', header)
    .replace('<!--server:html-->', appHtml)
    .replace('<!--server:scripts-->',
    `<script>
        // WARNING: See the following for security issues around embedding JSON in HTML:
        // http://redux.js.org/docs/recipes/ServerRendering.html#security-considerations
        window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\u003c')}
    </script>`
    );
}

app.get('/:category/@:author/:permlink', (req, res) => {
  match({ routes, location: req.url }, (err, redirect, props) => {
    fetchComponentData(store.dispatch, props.components, props.params)
      .then(() => renderPage(props))
      .then(html => res.end(html))
      .catch(error => res.end(error.message));
  });
});

app.get('/*', (req, res) => {
  res.send(indexHtml);
});

module.exports = { app, server };
<|endoftext|>


<commit_before>const isTestnet = process.env.isTestNet === 'true';

module.exports = {
  components: {
    'overview-nav': require('./nav'),
    'overview-footer': require('./footer'),
    'error': require('../components/notification')
  },
  name: 'overview',
  data: function() {
    return {
      store: window.Store.shareList,
      uiState: {
        selected: []
      },
      appState: {
        isTestnet: isTestnet
      }
    }
  },

  computed: {
    listHasItems: function() {
      return this.uiState.selected.length > 0;
    }
  },

  created: function() {
    this.store.actions.status(() => {
      this.store.actions.poll().start();
    });

  },

  destroyed: function() {
    this.store.actions.poll().stop();
  },

  methods: {
    toggleAll: function() {
      if(this.listHasItems) {
        this.uiState.selected = [];
      } else {
        this.store.shares.forEach((share) => {
          this.uiState.selected.push(share.id);
        });
      }
    }
  },

  template: `
<transition name="fade">

    <error class="error-stream alert alert-danger alert-dismissible" v-bind:notes="store.errors" v-on:erase="store.actions.clearErrors"></error>

        Currently Running Storj on Test Network...

    <overview-nav></overview-nav>

Overview

                <input type="checkbox" v-model="listHasItems" v-on:change="toggleAll()" class="checkbox" id="selectAll">
                #
		NodeID
                Status

                Location
                Uptime
                Restarts
                Peers
                Bridges
                Allocs
                Shared
                Delta
                Port

                    Start
                    Stop
                    Restart

                    Delete

                  <input v-model="uiState.selected"
                    v-bind:value="share.id"
                    type="checkbox"
                    class="checkbox">

                #{{index}}

		{{share.id}}

ON

OFF

Loading

                {{share.config.storagePath}}
                {{share.meta.uptimeReadable}}
                {{share.meta.numRestarts}}
                {{share.meta.farmerState.totalPeers}}

Disconnected

Connecting

Confirming

Connected

                {{share.meta.farmerState.contractCount}} ({{share.meta.farmerState.dataReceivedCount}} received)
                {{share.meta.farmerState.spaceUsed}} ({{share.meta.farmerState.percentUsed}}%)

                    {{share.meta.farmerState.ntpStatus.delta}}

                  {{share.meta.farmerState.ntpStatus.delta}}

                {{share.meta.farmerState.portStatus.listenPort}} {{share.meta.farmerState.portStatus.connectionType}}

                      Start
                      Stop
                      Restart
                      Logs
                      Edit

                      Delete

                <router-link :to="{path: '/share-wizard/wizard1?edit=true'}">Add Drive to Get Started</router-link>

    <overview-footer></overview-footer>

</transition>
  `
};
<commit_msg>Fix for Issue #703 “Bridge" filed says "connected" when node is "OFF"<commit_after>const isTestnet = process.env.isTestNet === 'true';

module.exports = {
  components: {
    'overview-nav': require('./nav'),
    'overview-footer': require('./footer'),
    'error': require('../components/notification')
  },
  name: 'overview',
  data: function() {
    return {
      store: window.Store.shareList,
      uiState: {
        selected: []
      },
      appState: {
        isTestnet: isTestnet
      }
    }
  },

  computed: {
    listHasItems: function() {
      return this.uiState.selected.length > 0;
    }
  },

  created: function() {
    this.store.actions.status(() => {
      this.store.actions.poll().start();
    });

  },

  destroyed: function() {
    this.store.actions.poll().stop();
  },

  methods: {
    toggleAll: function() {
      if(this.listHasItems) {
        this.uiState.selected = [];
      } else {
        this.store.shares.forEach((share) => {
          this.uiState.selected.push(share.id);
        });
      }
    }
  },

  template: `
<transition name="fade">

    <error class="error-stream alert alert-danger alert-dismissible" v-bind:notes="store.errors" v-on:erase="store.actions.clearErrors"></error>

        Currently Running Storj on Test Network...

    <overview-nav></overview-nav>

Overview

                <input type="checkbox" v-model="listHasItems" v-on:change="toggleAll()" class="checkbox" id="selectAll">
                #
		NodeID
                Status

                Location
                Uptime
                Restarts
                Peers
                Bridges
                Allocs
                Shared
                Delta
                Port

                    Start
                    Stop
                    Restart

                    Delete

                  <input v-model="uiState.selected"
                    v-bind:value="share.id"
                    type="checkbox"
                    class="checkbox">

                #{{index}}

		{{share.id}}

ON

OFF

Loading

                {{share.config.storagePath}}
                {{share.meta.uptimeReadable}}
                {{share.meta.numRestarts}}
                {{share.meta.farmerState.totalPeers}}

Disconnected

Connecting

Confirming

Connected

                {{share.meta.farmerState.contractCount}} ({{share.meta.farmerState.dataReceivedCount}} received)
                {{share.meta.farmerState.spaceUsed}} ({{share.meta.farmerState.percentUsed}}%)

                    {{share.meta.farmerState.ntpStatus.delta}}

                  {{share.meta.farmerState.ntpStatus.delta}}

                {{share.meta.farmerState.portStatus.listenPort}} {{share.meta.farmerState.portStatus.connectionType}}

                      Start
                      Stop
                      Restart
                      Logs
                      Edit

                      Delete

                <router-link :to="{path: '/share-wizard/wizard1?edit=true'}">Add Drive to Get Started</router-link>

    <overview-footer></overview-footer>

</transition>
  `
};
<|endoftext|>


<commit_before>'use strict';

angular.module('feeds-directives', []).directive('feed', ['feedService', '$compile', '$templateCache', '$http', function (feedService, $compile, $templateCache, $http) {
  return  {
    restrict: 'E',
    scope: {
      summary: '=summary'
    },
    controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) {
      $scope.$watch('finishedLoading', function (value) {
        if ($attrs.postRender && value) {
          $timeout(function () {
            new Function("element", $attrs.postRender + '(element);')($element);
          }, 0);
        }
      });

      $scope.feeds = [];

      var spinner = $templateCache.get('feed-spinner.html');
      $element.append($compile(spinner)($scope));

      function renderTemplate(templateHTML, feedsObj) {
        $element.append($compile(templateHTML)($scope));
        if (feedsObj) {
          for (var i = 0; i < feedsObj.length; i++) {
            $scope.feeds.push(feedsObj[i]);
          }
        }
      }

      $attrs.observe('url', function(url){
        feedService.getFeeds(url, $attrs.count).then(function (feedsObj) {
          if ($attrs.templateUrl) {
            $http.get($attrs.templateUrl, {cache: $templateCache}).success(function (templateHtml) {
              renderTemplate(templateHtml, feedsObj);
            });
          }
          else {
            renderTemplate($templateCache.get('feed-list.html'), feedsObj);
          }
        },function (error) {
          console.error('Error loading feed ', error);
          $scope.error = error;
          renderTemplate($templateCache.get('feed-list.html'));
        }).finally(function () {
          $element.find('.spinner').slideUp();
          $scope.$evalAsync('finishedLoading = true')
        });
      });
    }]
  }
}]);
<commit_msg>rerendering template when url attribute changes<commit_after>'use strict';

angular.module('feeds-directives', []).directive('feed', ['feedService', '$compile', '$templateCache', '$http', function (feedService, $compile, $templateCache, $http) {
  return  {
    restrict: 'E',
    scope: {
      summary: '=summary',
      url: '=url'
    },
    controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) {
      $scope.$watch('finishedLoading', function (value) {
        if ($attrs.postRender && value) {
          $timeout(function () {
            new Function("element", $attrs.postRender + '(element);')($element);
          }, 0);
        }
      });

      $scope.feeds = [];

      $scope.$watch(function() {
        return $scope.url;
      }, function(val) {
        // reset state
        $scope.error = "";
        $scope.feeds = [];
        setFeeds(val);
      });

      var spinner = $templateCache.get('feed-spinner.html');
      $element.append($compile(spinner)($scope));

      function renderTemplate(templateHTML, feedsObj) {
        $element.empty();
        $element.append($compile(templateHTML)($scope));
        if (feedsObj) {
          for (var i = 0; i < feedsObj.length; i++) {
            $scope.feeds.push(feedsObj[i]);
          }
        }
      }

      function setFeeds(url) {
        feedService.getFeeds(url, $attrs.count).then(function (feedsObj) {
          if ($attrs.templateUrl) {
            $http.get($attrs.templateUrl, {cache: $templateCache}).success(function (templateHtml) {
              renderTemplate(templateHtml, feedsObj);
            });
          }
          else {
            renderTemplate($templateCache.get('feed-list.html'), feedsObj);
          }
        },function (error) {
          console.error('Error loading feed ', error);
          $scope.error = error;
          renderTemplate($templateCache.get('feed-list.html'));
        }).finally(function () {
          $element.find('.spinner').slideUp();
          $scope.$evalAsync('finishedLoading = true');
        });
      }
    }]
  };
}]);
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import Card from 'material-ui/lib/card/card';
import CardText from 'material-ui/lib/card/card-text';
import { Link } from 'react-router';
import MediaStatus from './MediaStatus';
import MediaMetadataSummary from './MediaMetadataSummary';

class MediaCard extends Component {

  render() {
    const that = this;
    const props = that.props;
    const media = props.media;
    media.created_at = new Date(parseInt(media.published) * 1000);
    const data = JSON.parse(media.jsondata);
    const prefix = '/team/' + Checkdesk.currentProject.team.dbid + '/project/' + Checkdesk.currentProject.dbid + '/media/';

    return (

        <Link to={prefix + media.dbid} className='media-card__clickable'>

<MediaStatus status={media.last_status} />

{data.description}

            <MediaMetadataSummary media={media} data={data} />

        </Link>

    );
  }
}

export default MediaCard;
<commit_msg>Show Pender title (not description) on MediaCard<commit_after>import React, { Component, PropTypes } from 'react';
import Card from 'material-ui/lib/card/card';
import CardText from 'material-ui/lib/card/card-text';
import { Link } from 'react-router';
import MediaStatus from './MediaStatus';
import MediaMetadataSummary from './MediaMetadataSummary';

class MediaCard extends Component {

  render() {
    const that = this;
    const props = that.props;
    const media = props.media;
    media.created_at = new Date(parseInt(media.published) * 1000);
    const data = JSON.parse(media.jsondata);
    const prefix = '/team/' + Checkdesk.currentProject.team.dbid + '/project/' + Checkdesk.currentProject.dbid + '/media/';

    return (

        <Link to={prefix + media.dbid} className='media-card__clickable'>

<MediaStatus status={media.last_status} />

{data.title}

            <MediaMetadataSummary media={media} data={data} />

        </Link>

    );
  }
}

export default MediaCard;
<|endoftext|>


<commit_before>if (typeof define !== 'function') { var define = require('amdefine')(module) }
/*
 * QuickBlox JavaScript SDK
 *
 * Messages Module
 *
 */

define(['qbConfig', 'qbUtils'],
function(config, Utils) {

  function MessagesProxy(service) {
    this.service = service;
    this.tokens = new TokensProxy(service);
    this.subscriptions = new SubscriptionsProxy(service);
    this.events = new EventsProxy(service);
  }

  // Push Tokens

  function TokensProxy(service){
    this.service = service;
  }

  TokensProxy.prototype = {

    create: function(params, callback){
      var message = {
        push_token: {
          environment: params.environment,
          client_identification_sequence: params.client_identification_sequence
        },
        device: { platform: params.platform, udid: params.udid}
      };
      if (config.debug) { console.log('TokensProxy.create', message);}
      this.service.ajax({url: Utils.getUrl(config.urls.pushtokens), type: 'POST', data: message},
                        function(err, data){
                          if (err) { callback(err, null);}
                          else { callback(null, data.push_token); }
                        });
    },

    delete: function(id, callback) {
      if (config.debug) { console.log('MessageProxy.deletePushToken', id); }
      this.service.ajax({url: Utils.getUrl(config.urls.pushtokens, id), type: 'DELETE', dataType:'text'},
                        function (err, res) {
                          if (err) {callback(err, null);}
                          else {callback(null, true);}
                          });
    }

  };

  // Subscriptions

  function SubscriptionsProxy(service){
    this.service = service;
  }

  SubscriptionsProxy.prototype = {

    create: function(params, callback) {
      if (config.debug) { console.log('MessageProxy.createSubscription', params); }
      this.service.ajax({url: Utils.getUrl(config.urls.subscriptions), type: 'POST', data: params}, callback);
    },

    list: function(callback) {
      if (config.debug) { console.log('MessageProxy.listSubscription'); }
      this.service.ajax({url: Utils.getUrl(config.urls.subscriptions)}, callback);
    },

    delete: function(id, callback) {
      if (config.debug) { console.log('MessageProxy.deleteSubscription', id); }
      this.service.ajax({url: Utils.getUrl(config.urls.subscriptions, id), type: 'DELETE', dataType:'text'},
                        function(err, res){
                          if (err) { callback(err, null);}
                          else { callback(null, true);}
                        });
    }

  };

  // Events
  function EventsProxy(service){
    this.service = service;
  }

  EventsProxy.prototype = {

    create: function(params, callback) {
      if (config.debug) { console.log('MessageProxy.createEvent', params); }
      var message = {event: params};
      this.service.ajax({url: Utils.getUrl(config.urls.events), type: 'POST', data: message}, callback);
    },

    list: function(callback) {
     if (config.debug) { console.log('MessageProxy.listEvents'); }
      this.service.ajax({url: Utils.getUrl(config.urls.events)}, callback);
    },

    get: function(id, callback) {
      if (config.debug) { console.log('MessageProxy.getEvents', id); }
      this.service.ajax({url: Utils.getUrl(config.urls.events, id)}, callback);
    },

    update: function(params, callback) {
      if (config.debug) { console.log('MessageProxy.createEvent', params); }
      var message = {event: params};
      this.service.ajax({url: Utils.getUrl(config.urls.events, params.id), type: 'PUT', data: message}, callback);
    },

    delete: function(id, callback) {
      if (config.debug) { console.log('MessageProxy.deleteEvent', id); }
      this.service.ajax({url: Utils.getUrl(config.urls.events, id), type: 'DELETE'}, callback);
    }

  };

  return MessagesProxy;
});
<commit_msg>[browserify] qbMessages.js<commit_after>/*
 * QuickBlox JavaScript SDK
 *
 * Messages Module
 *
 */

var config = require('../qbConfig'),
    Utils = require('../qbUtils');

function MessagesProxy(service) {
  this.service = service;
  this.tokens = new TokensProxy(service);
  this.subscriptions = new SubscriptionsProxy(service);
  this.events = new EventsProxy(service);
}

// Push Tokens

function TokensProxy(service){
  this.service = service;
}

TokensProxy.prototype = {

  create: function(params, callback){
    var message = {
      push_token: {
        environment: params.environment,
        client_identification_sequence: params.client_identification_sequence
      },
      device: { platform: params.platform, udid: params.udid}
    };
    if (config.debug) { console.log('TokensProxy.create', message);}
    this.service.ajax({url: Utils.getUrl(config.urls.pushtokens), type: 'POST', data: message},
                      function(err, data){
                        if (err) { callback(err, null);}
                        else { callback(null, data.push_token); }
                      });
  },

  delete: function(id, callback) {
    if (config.debug) { console.log('MessageProxy.deletePushToken', id); }
    this.service.ajax({url: Utils.getUrl(config.urls.pushtokens, id), type: 'DELETE', dataType:'text'},
                      function (err, res) {
                        if (err) {callback(err, null);}
                        else {callback(null, true);}
                        });
  }

};

// Subscriptions

function SubscriptionsProxy(service){
  this.service = service;
}

SubscriptionsProxy.prototype = {

  create: function(params, callback) {
    if (config.debug) { console.log('MessageProxy.createSubscription', params); }
    this.service.ajax({url: Utils.getUrl(config.urls.subscriptions), type: 'POST', data: params}, callback);
  },

  list: function(callback) {
    if (config.debug) { console.log('MessageProxy.listSubscription'); }
    this.service.ajax({url: Utils.getUrl(config.urls.subscriptions)}, callback);
  },

  delete: function(id, callback) {
    if (config.debug) { console.log('MessageProxy.deleteSubscription', id); }
    this.service.ajax({url: Utils.getUrl(config.urls.subscriptions, id), type: 'DELETE', dataType:'text'},
                      function(err, res){
                        if (err) { callback(err, null);}
                        else { callback(null, true);}
                      });
  }

};

// Events
function EventsProxy(service){
  this.service = service;
}

EventsProxy.prototype = {

  create: function(params, callback) {
    if (config.debug) { console.log('MessageProxy.createEvent', params); }
    var message = {event: params};
    this.service.ajax({url: Utils.getUrl(config.urls.events), type: 'POST', data: message}, callback);
  },

  list: function(callback) {
   if (config.debug) { console.log('MessageProxy.listEvents'); }
    this.service.ajax({url: Utils.getUrl(config.urls.events)}, callback);
  },

  get: function(id, callback) {
    if (config.debug) { console.log('MessageProxy.getEvents', id); }
    this.service.ajax({url: Utils.getUrl(config.urls.events, id)}, callback);
  },

  update: function(params, callback) {
    if (config.debug) { console.log('MessageProxy.createEvent', params); }
    var message = {event: params};
    this.service.ajax({url: Utils.getUrl(config.urls.events, params.id), type: 'PUT', data: message}, callback);
  },

  delete: function(id, callback) {
    if (config.debug) { console.log('MessageProxy.deleteEvent', id); }
    this.service.ajax({url: Utils.getUrl(config.urls.events, id), type: 'DELETE'}, callback);
  }

};

module.exports = MessagesProxy;
<|endoftext|>


<commit_before>import {LightningElement, api, track} from 'lwc';
import getDataImportModel
    from '@salesforce/apex/BGE_DataImportBatchEntry_CTRL.getDataImportModel';
import getDataImportRows
    from '@salesforce/apex/BGE_DataImportBatchEntry_CTRL.getDataImportRows';
import GeFormService from 'c/geFormService';
import STATUS_FIELD from '@salesforce/schema/DataImport__c.Status__c';
import FAILURE_INFORMATION_FIELD
    from '@salesforce/schema/DataImport__c.FailureInformation__c';
import {deleteRecord} from 'lightning/uiRecordApi';
import {handleError} from 'c/utilTemplateBuilder';
import runBatchDryRun from '@salesforce/apex/BGE_DataImportBatchEntry_CTRL.runBatchDryRun';
import geDonorColumnLabel from '@salesforce/label/c.geDonorColumnLabel';
import geDonationColumnLabel from '@salesforce/label/c.geDonationColumnLabel';
import bgeActionDelete from '@salesforce/label/c.bgeActionDelete';

export default class GeBatchGiftEntryTable extends LightningElement {
    @api batchId;
    @track ready = false;

    _batchLoaded = false;
    @track data = [];
    @track hasData;

    _columnsLoaded = false;
    @track columns = [];
    _columns = [
        {label: 'Status', fieldName: STATUS_FIELD.fieldApiName, type: 'text'},
        {label: 'Errors', fieldName: FAILURE_INFORMATION_FIELD.fieldApiName, type: 'text'},
        {
            label: geDonorColumnLabel, fieldName: 'donorLink', type: 'url',
            typeAttributes: {label: {fieldName: 'donorName'}}
        },
        {
            label: geDonationColumnLabel, fieldName: 'matchedRecordUrl', type: 'url',
            typeAttributes: {label: {fieldName: 'matchedRecordLabel'}}
        }
    ];
    _actionsColumn = {
        type: 'action',
        typeAttributes: {
            rowActions: [
                {label: bgeActionDelete, name: 'delete'}
            ],
            menuAlignment: 'right'
        }
    };

    _totalCountOfGifts;
    _totalAmountOfGifts;
    @track isLoaded = true;

    connectedCallback() {
        if (this.batchId) {
            this.loadBatch();
        }
    }

    setReady() {
        this.ready = this._columnsLoaded && this._batchLoaded;
    }

    loadBatch() {
        getDataImportModel({batchId: this.batchId})
            .then(
                response => {
                    const dataImportModel = JSON.parse(response);
                    this._totalCountOfGifts = dataImportModel.totalCountOfRows;
                    this._totalAmountOfGifts = dataImportModel.totalRowAmount;
                    dataImportModel.dataImportRows.forEach(row => {
                            this.data.push(
                                Object.assign(row, row.record));
                        }
                    );
                    this.data = [...this.data];
                    this.hasData = this.data.length > 0 ? true : false;
                    this.batchLoaded();
                }
            )
            .catch(
                error => {
                    handleError(error);
                }
            );
    }

    batchLoaded() {
        this._batchLoaded = true;
        this.setReady();
    }

    @api
    handleSectionsRetrieved(sections) {
        this.initColumns(this.buildColumns(sections));
    }

    initColumns(userDefinedColumns) {
        this.columns = [
            ...this._columns,
            ...userDefinedColumns,
            this._actionsColumn];
        this.columnsLoaded();
    }

    buildColumns(sections) {
        const columns = [];
        sections.forEach(
            section => {
                section.elements.forEach(
                    element => {
                        const column = {
                            label: element.label,
                            fieldName: GeFormService.getFieldMappingWrapper(
                                element.dataImportFieldMappingDevNames[0]
                            ).Source_Field_API_Name,
                            type: GeFormService.getInputTypeFromDataType(
                                element.dataType
                            ) === 'date' ? 'date-local' :
                                GeFormService.getInputTypeFromDataType(element.dataType)
                        };
                        columns.push(column);
                    }
                );
            }
        );
        return columns;
    }

    columnsLoaded() {
        this._columnsLoaded = true;
        this.setReady();
    }

    @api
    upsertData(dataRow, idProperty) {
        let existingRow = this.data.find(row =>
            row[idProperty] === dataRow[idProperty]
        );
        if (existingRow) {
            Object.assign(existingRow, dataRow);
            this.data = [...this.data];
        } else {
            this.data = [dataRow, ...this.data];
            if (this.hasData == false) {
                this.hasData = true;
            }
        }
    }

    @api
    setTotalCount(value) {
        this._totalCountOfGifts = value;
    }

    @api
    setTotalAmount(value) {
        this._totalAmountOfGifts = value;
    }

    handleRowActions(event) {
        switch (event.detail.action.name) {
            // TODO: decide if going to edit inline in table or load into form
            // case 'Edit':
            //     this.editDIRow(event.detail.row);
            //     break;
            case 'delete':
                deleteRecord(event.detail.row.Id).then(() => {
                    this.deleteDIRow(event.detail.row);
                }).catch(error => {
                        handleError(error);
                    }
                );
                break;
        }
    }

    deleteDIRow(rowToDelete) {
        const isRowToDelete = row => row.Id == rowToDelete.Id;
        const index = this.data.findIndex(isRowToDelete);
        this.data.splice(index, 1);
        this.data = [...this.data];
    }

    loadMoreData(event) {
        event.target.isLoading = true;
        const disableInfiniteLoading = function () {
            this.enableInfiniteLoading = false;
        }.bind(event.target);

        const disableIsLoading = function () {
            this.isLoading = false;
        }.bind(event.target);

        getDataImportRows({batchId: this.batchId, offset: this.data.length})
            .then(rows => {
                rows.forEach(row => {
                        this.data.push(
                            Object.assign(row, row.record)
                        );
                    }
                );
                this.data = [...this.data];
                if (this.data.length >= this._totalCountOfGifts) {
                    disableInfiniteLoading();
                }
                disableIsLoading();
            })
            .catch(error => {
                handleError(error);
            });
    }

    @api
    runBatchDryRun(callback) {
        runBatchDryRun({
            batchId: this.batchId,
            numberOfRowsToReturn: this.data.length
        })
            .then(result => {
                const dataImportModel = JSON.parse(result);
                this.setTotalCount(dataImportModel.totalCountOfRows);
                this.setTotalCount(dataImportModel.totalRowAmount);
                dataImportModel.dataImportRows.forEach((row, idx) => {
                    this.upsertData(
                        Object.assign(row, row.record), 'Id');
                });
            })
            .catch(error => {
                handleError(error);
            })
            .finally(() => {
                callback();
            });
    }
}<commit_msg>Fix alignment of row actions on datatable<commit_after>import {LightningElement, api, track} from 'lwc';
import getDataImportModel
    from '@salesforce/apex/BGE_DataImportBatchEntry_CTRL.getDataImportModel';
import getDataImportRows
    from '@salesforce/apex/BGE_DataImportBatchEntry_CTRL.getDataImportRows';
import GeFormService from 'c/geFormService';
import STATUS_FIELD from '@salesforce/schema/DataImport__c.Status__c';
import FAILURE_INFORMATION_FIELD
    from '@salesforce/schema/DataImport__c.FailureInformation__c';
import {deleteRecord} from 'lightning/uiRecordApi';
import {handleError} from 'c/utilTemplateBuilder';
import runBatchDryRun from '@salesforce/apex/BGE_DataImportBatchEntry_CTRL.runBatchDryRun';
import geDonorColumnLabel from '@salesforce/label/c.geDonorColumnLabel';
import geDonationColumnLabel from '@salesforce/label/c.geDonationColumnLabel';
import bgeActionDelete from '@salesforce/label/c.bgeActionDelete';

export default class GeBatchGiftEntryTable extends LightningElement {
    @api batchId;
    @track ready = false;

    _batchLoaded = false;
    @track data = [];
    @track hasData;

    _columnsLoaded = false;
    @track columns = [];
    _columns = [
        {label: 'Status', fieldName: STATUS_FIELD.fieldApiName, type: 'text'},
        {label: 'Errors', fieldName: FAILURE_INFORMATION_FIELD.fieldApiName, type: 'text'},
        {
            label: geDonorColumnLabel, fieldName: 'donorLink', type: 'url',
            typeAttributes: {label: {fieldName: 'donorName'}}
        },
        {
            label: geDonationColumnLabel, fieldName: 'matchedRecordUrl', type: 'url',
            typeAttributes: {label: {fieldName: 'matchedRecordLabel'}}
        }
    ];
    _actionsColumn = {
        type: 'action',
        typeAttributes: {
            rowActions: [
                {label: bgeActionDelete, name: 'delete'}
            ],
            menuAlignment: 'auto'
        }
    };

    _totalCountOfGifts;
    _totalAmountOfGifts;
    @track isLoaded = true;

    connectedCallback() {
        if (this.batchId) {
            this.loadBatch();
        }
    }

    setReady() {
        this.ready = this._columnsLoaded && this._batchLoaded;
    }

    loadBatch() {
        getDataImportModel({batchId: this.batchId})
            .then(
                response => {
                    const dataImportModel = JSON.parse(response);
                    this._totalCountOfGifts = dataImportModel.totalCountOfRows;
                    this._totalAmountOfGifts = dataImportModel.totalRowAmount;
                    dataImportModel.dataImportRows.forEach(row => {
                            this.data.push(
                                Object.assign(row, row.record));
                        }
                    );
                    this.data = [...this.data];
                    this.hasData = this.data.length > 0 ? true : false;
                    this.batchLoaded();
                }
            )
            .catch(
                error => {
                    handleError(error);
                }
            );
    }

    batchLoaded() {
        this._batchLoaded = true;
        this.setReady();
    }

    @api
    handleSectionsRetrieved(sections) {
        this.initColumns(this.buildColumns(sections));
    }

    initColumns(userDefinedColumns) {
        this.columns = [
            ...this._columns,
            ...userDefinedColumns,
            this._actionsColumn];
        this.columnsLoaded();
    }

    buildColumns(sections) {
        const columns = [];
        sections.forEach(
            section => {
                section.elements.forEach(
                    element => {
                        const column = {
                            label: element.label,
                            fieldName: GeFormService.getFieldMappingWrapper(
                                element.dataImportFieldMappingDevNames[0]
                            ).Source_Field_API_Name,
                            type: GeFormService.getInputTypeFromDataType(
                                element.dataType
                            ) === 'date' ? 'date-local' :
                                GeFormService.getInputTypeFromDataType(element.dataType)
                        };
                        columns.push(column);
                    }
                );
            }
        );
        return columns;
    }

    columnsLoaded() {
        this._columnsLoaded = true;
        this.setReady();
    }

    @api
    upsertData(dataRow, idProperty) {
        let existingRow = this.data.find(row =>
            row[idProperty] === dataRow[idProperty]
        );
        if (existingRow) {
            Object.assign(existingRow, dataRow);
            this.data = [...this.data];
        } else {
            this.data = [dataRow, ...this.data];
            if (this.hasData == false) {
                this.hasData = true;
            }
        }
    }

    @api
    setTotalCount(value) {
        this._totalCountOfGifts = value;
    }

    @api
    setTotalAmount(value) {
        this._totalAmountOfGifts = value;
    }

    handleRowActions(event) {
        switch (event.detail.action.name) {
            // TODO: decide if going to edit inline in table or load into form
            // case 'Edit':
            //     this.editDIRow(event.detail.row);
            //     break;
            case 'delete':
                deleteRecord(event.detail.row.Id).then(() => {
                    this.deleteDIRow(event.detail.row);
                }).catch(error => {
                        handleError(error);
                    }
                );
                break;
        }
    }

    deleteDIRow(rowToDelete) {
        const isRowToDelete = row => row.Id == rowToDelete.Id;
        const index = this.data.findIndex(isRowToDelete);
        this.data.splice(index, 1);
        this.data = [...this.data];
    }

    loadMoreData(event) {
        event.target.isLoading = true;
        const disableInfiniteLoading = function () {
            this.enableInfiniteLoading = false;
        }.bind(event.target);

        const disableIsLoading = function () {
            this.isLoading = false;
        }.bind(event.target);

        getDataImportRows({batchId: this.batchId, offset: this.data.length})
            .then(rows => {
                rows.forEach(row => {
                        this.data.push(
                            Object.assign(row, row.record)
                        );
                    }
                );
                this.data = [...this.data];
                if (this.data.length >= this._totalCountOfGifts) {
                    disableInfiniteLoading();
                }
                disableIsLoading();
            })
            .catch(error => {
                handleError(error);
            });
    }

    @api
    runBatchDryRun(callback) {
        runBatchDryRun({
            batchId: this.batchId,
            numberOfRowsToReturn: this.data.length
        })
            .then(result => {
                const dataImportModel = JSON.parse(result);
                this.setTotalCount(dataImportModel.totalCountOfRows);
                this.setTotalCount(dataImportModel.totalRowAmount);
                dataImportModel.dataImportRows.forEach((row, idx) => {
                    this.upsertData(
                        Object.assign(row, row.record), 'Id');
                });
            })
            .catch(error => {
                handleError(error);
            })
            .finally(() => {
                callback();
            });
    }
}<|endoftext|>


<commit_before>/*!
  * domready (c) Dustin Diaz 2014 - License MIT
  *
  * Source: https://raw.githubusercontent.com/ded/domready/v1.0.8/ready.js
  */
var domready = (function () {

    var fns = [], listener
        , doc = document
        , hack = doc.documentElement.doScroll
        , domContentLoaded = 'DOMContentLoaded'
        , loaded = (hack ? /^loaded|^c/ : /^loaded|^i|^c/).test(doc.readyState)

    if (!loaded)
        doc.addEventListener(domContentLoaded, listener = function () {
            doc.removeEventListener(domContentLoaded, listener)
            loaded = 1
            while (listener = fns.shift()) listener()
        })

    return function (fn) {
        loaded ? setTimeout(fn, 0) : fns.push(fn)
    }

})();

/**
 * re-frame codox iframe js (c) Michael Thompson 2020 - MIT
 *
 * This code runs inside the iframe that contains codox-generated API
 * documentation so that links, including named anchors, can be forwarded from
 * the parent mkdocs site to the child iframe. Specifically:
 *
 * 1. Notifies the parent when the iframe dom is ready to receive events to go
 *    to a given link.
 * 2. Registers event handlers on every anchor to forward the 'click' event to
 *    the parent, and cancel default behaviour.
 * 3. Receives events to go to a given link from the parent, replacing the
 *    default behaviour cancelled by 2.
 *
 * The combination of 2. and 3. promotes control of link behaviour to the parent
 * so that copy/pasting a link into the location bar behaves as-if the
 * codox-generated content was not within an iframe.
 */

domready(function() {
    window.parent.postMessage({type: 'ready'}, '*')

    let anchors = document.getElementsByTagName('a')
    for (let anchor of anchors) {
        anchor.addEventListener('click', function(event) {
            event.preventDefault()
            let href = anchor.getAttribute('href')
            if (href) {
                window.parent.postMessage(
                    {type: 'setHash',
                        hash: href.replace(/#/g, '/')}, '*')
            }
        })
    }

});

window.addEventListener('message', function(event) {
    if (event.data.type === 'setHref' && event.data.href) {
        window.location.href = event.data.href
    }
});
<commit_msg>Disable API docs iframe js<commit_after>/*!
  * domready (c) Dustin Diaz 2014 - License MIT
  *
  * Source: https://raw.githubusercontent.com/ded/domready/v1.0.8/ready.js
  */
var domready = (function () {

    var fns = [], listener
        , doc = document
        , hack = doc.documentElement.doScroll
        , domContentLoaded = 'DOMContentLoaded'
        , loaded = (hack ? /^loaded|^c/ : /^loaded|^i|^c/).test(doc.readyState)

    if (!loaded)
        doc.addEventListener(domContentLoaded, listener = function () {
            doc.removeEventListener(domContentLoaded, listener)
            loaded = 1
            while (listener = fns.shift()) listener()
        })

    return function (fn) {
        loaded ? setTimeout(fn, 0) : fns.push(fn)
    }

})();

/**
 * re-frame codox iframe js (c) Michael Thompson 2020 - MIT
 *
 * This code runs inside the iframe that contains codox-generated API
 * documentation so that links, including named anchors, can be forwarded from
 * the parent mkdocs site to the child iframe. Specifically:
 *
 * 1. Notifies the parent when the iframe dom is ready to receive events to go
 *    to a given link.
 * 2. Registers event handlers on every anchor to forward the 'click' event to
 *    the parent, and cancel default behaviour.
 * 3. Receives events to go to a given link from the parent, replacing the
 *    default behaviour cancelled by 2.
 *
 * The combination of 2. and 3. promotes control of link behaviour to the parent
 * so that copy/pasting a link into the location bar behaves as-if the
 * codox-generated content was not within an iframe.
 */
/*
domready(function() {
    window.parent.postMessage({type: 'ready'}, '*')

    let anchors = document.getElementsByTagName('a')
    for (let anchor of anchors) {
        anchor.addEventListener('click', function(event) {
            event.preventDefault()
            let href = anchor.getAttribute('href')
            if (href) {
                window.parent.postMessage(
                    {type: 'setHash',
                        hash: href.replace(/#/g, '/')}, '*')
            }
        })
    }

});

window.addEventListener('message', function(event) {
    if (event.data.type === 'setHref' && event.data.href) {
        window.location.href = event.data.href
    }
});
*/
<|endoftext|>


<commit_before>
var editContentButton = {
  clickListen: function() {
    $('div.current-content').on('click', 'a.edit-content', function(event) {
      event.preventDefault();
      var button = $(this);

      var action = $(this).attr('href') + '/edit';
      var request = $.ajax({
        url: action
      });
      request.done(function(editContentForm) {
        button.parent().append(editContentForm);
        button.siblings('a.cancel').toggle();
        button.remove();
      });

    });
  }
};

var cancelButton = {
  clickListen: function() {
    $('div.current-content').on('click', 'a.cancel', function(event) {
      event.preventDefault();
      var button = $(this);

      button.siblings('form').toggle();
      button.text(function(idx, text) {
        return text == 'cancel' ? 'edit' : 'cancel'
      });
    })
  }
}

var deleteButton = {
  clickListen: function() {
    $('div.current-content').on('click', 'a.delete-content', function(event) {
      event.preventDefault();
      var button = $(this);

      var request = $.ajax({
        type: 'DELETE',
        url: button.attr('href')
      });
      request.done(function(_null) {
        button.closest('div.course-content').remove();
      });
      request.fail(function(error) {
        alert('fail');
      });

    });
  }
};

var editContentForm = {
  submitListen: function() {
    $(document).on('ajax:success', 'div.content form', function(event, updatedContent) {
      var form = $(this);
      form.closest('div.course-content').replaceWith(updatedContent);
    });
  }
};

<commit_msg>complete usability check<commit_after>
var editContentButton = {
  clickListen: function() {
    $('div.current-content').on('click', 'a.edit-content', function(event) {
      event.preventDefault();
      var button = $(this);

      var action = $(this).attr('href') + '/edit';
      var request = $.ajax({
        url: action
      });
      request.done(function(editContentForm) {
        button.parent().append(editContentForm);
        button.siblings('a.cancel').toggle();
        button.remove();
      });

    });
  }
};

var cancelButton = {
  clickListen: function() {
    $('div.current-content').on('click', 'a.cancel', function(event) {
      event.preventDefault();
      var button = $(this);

      button.siblings('form').toggle();
      button.text(function(idx, text) {
        return text == 'cancel' ? 'edit' : 'cancel'
      });
    })
  }
}

var deleteButton = {
  clickListen: function() {
    $('div.current-content').on('click', 'a.delete-content', function(event) {
      event.preventDefault();
      var button = $(this);

      var request = $.ajax({
        type: 'DELETE',
        url: button.attr('href')
      });
      request.done(function(_null) {
        button.closest('div.course-content').remove();
      });
      request.fail(function(error) {
        alert('fail');
      });

    });
  }
};

var editContentForm = {
  submitListen: function() {
    $(document).on('ajax:success', 'div.current-content form', function(event, updatedContent) {
      var form = $(this);
      form.closest('div.course-content').replaceWith(updatedContent);
    });
  }
};

<|endoftext|>


<commit_before>// Load `*.js` under current directory as properties
// i.e., `User.js` will become `exports['UserModel']` or `exports.UserModel`
const path = require('path')
const fs = require('fs')

var fnames = []

fs.readdirSync(path.join(__dirname, '/')).forEach(function (file) {
  if (file.match(/\.js$/) !== null && file !== 'index.js') {
    var name = file.replace('.js', '')
    exports[name + 'Model'] = require('./' + file)
    fnames.push(name)
  }
})

exports['names'] = fnames
<commit_msg>Fixes modules relative path to work with webpack<commit_after>// Load `*.js` under current directory as properties
// i.e., `User.js` will become `exports['UserModel']` or `exports.UserModel`
const path = require('path')
const fs = require('fs')

var fnames = []

fs.readdirSync('./models').forEach(function (file) {
  if (file.match(/\.js$/) !== null && file !== 'index.js') {
    var name = file.replace('.js', '')
    exports[name + 'Model'] = require('./' + file)
    fnames.push(name)
  }
})

exports['names'] = fnames
<|endoftext|>


<commit_before>/**
	The MIT License (MIT)

	Copyright (c) 2014 MyChannel-Apps.de

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

	@author		Adrian Preuß <Bizarrus>, Christoph Kühl <djchrisnet>
*/

var Cron = (new function() {
	var _cronjobs	= [];
	var _watcher;
	var _offlineCheck = false;

	this.init = function() {
		if(_watcher != undefined) {
			clearInterval(_watcher);
		}

		_watcher	= setInterval(this.run, 500);
	};

	this.enableOfflineRunCheck = function() {
		_offlineCheck = true;
	};

	this.checkOfflineRun = function(job) {
		if(job.getLastCheck() == 0) {
			return;
		}

		while(new Date().getTime() >= job.getLastCheck()) {
			var time = new Date(job.getLastCheck()+500);
			job.setLastCheck(time);

			if(time.getTime() - job.getLastRun() > 60000) {
				if(Cron.match(job.getMinutes(), time.getMinutes())) {
					if(Cron.match(job.getHours(), time.getHours())) {
						if(Cron.match(job.getDate(), time.getDate())) {
							if(Cron.match(job.getMonth(), time.getMonth())) {
								if(Cron.match(job.getDay(), time.getDay())) {
									job.run(time);
									return;
								}
							}
						}
					}
				}
			}
		}
	};

	this.run = function() {
		var time = new Date();

		for(var index in _cronjobs) {
			var job = _cronjobs[index];

			if(!job.isRunning()) {
				continue;
			}

			if(time.getTime() - job.getLastRun() > 60000) {
				if(Cron.match(job.getMinutes(), time.getMinutes())) {
					if(Cron.match(job.getHours(), time.getHours())) {
						if(Cron.match(job.getDate(), time.getDate())) {
							if(Cron.match(job.getMonth(), time.getMonth())) {
								if(Cron.match(job.getDay(), time.getDay())) {
									job.run(time);
								}
							}
						}
					}
				}
			}
		}
	};

	this.add = function(cronjob) {
		_cronjobs.push(cronjob);

		if(_offlineCheck) {
			this.checkOfflineRun(cronjob);
		}
	};

	this.match = function(a, b) {
		for(var index = 0; index < a.length; index++) {
			var c = a[index];

			if(c[0] === -1 || (b >= c[0] && b <= c[1])) {
				var b0 = b - c[0]; // make the modulo start from 1st miniture of from matched time, not first minute of from 0 minutes
				//WHAT THE FUCK IS b0 ?!?!?!?!?! BULLSHIT ..|..

				if(c[2] === -1 || b === 0 || b % c[2] === 0) {
					return true;
				}
			}
		}

		return  false;
	};

	this.parse = function(entry) {
		return entry.split(',').map(function(index) {
			var z = index.split('/');
			var x = z[0].split('-');

			if(x[0] == '*') {
				x[0] = -1;
			}

			if(x.length == 1) {
				x.push(x[0]);
			}

			x[2] = z.length === 1 ? -1 : z[1];
			x[0] = parseInt(x[0]); // 0 - from
			x[1] = parseInt(x[1]); // 1 - to
			x[2] = parseInt(x[2]); // 2 modulus

			return x;
		});
	};

	this.saveData = function() {
		for(var index in _cronjobs) {
			_cronjobs[index].save();
		}
	};

	this.onShutdown = function() {
		for(var index in _cronjobs) {
			_cronjobs[index].onShutdown();
		}

		if(_watcher != undefined) {
			clearInterval(_watcher);
		}
	};

	this.init();
}());

function Cronjob(name, cycle, callback) {

	var _name		= '';
	var _cycle		= '* * * * *';
	var _cycle_data	= [];
	var _is_running	= false;
	var _callback	= function(time) { /* Override Me */ };
	var _last_run	= undefined;
	var _last_check = undefined;
	var _time_data	= {
		minute:	'*',
		hour:	'*',
		date:	'*',
		month:	'*',
		day:	'*'
	};

	function Cronjob(instance, name, cycle, callback) {
		_name			= name;
		_cycle			= cycle;
		_callback		= callback;
		_cycle_data		= _cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);
		_crondb			= DB.load('_cron_' + _name, {run:0, check:0});
		_last_run		= new Date(parseInt(_crondb.run));
		_last_check		= new Date(parseInt(_crondb.check));
		_time_data		= {
			minute:	Cron.parse(_cycle_data[1]),
			hour:	Cron.parse(_cycle_data[2]),
			date:	Cron.parse(_cycle_data[3]),
			month:	Cron.parse(_cycle_data[4]),
			day:	Cron.parse(_cycle_data[5])
		};
		Cron.add(instance);
		instance.start();
	}

	this.getLastRun = function() {
		return _last_run.getTime();
	};

	this.getName = function() {
		return _name;
	};

	this.getLastCheck = function() {
		return _last_check.getTime();
	};

	this.setLastCheck = function(time) {
		_last_check = time;
	};

	this.isRunning = function() {
		return _is_running;
	};

	this.start = function() {
		_is_running	= true;
	};

	this.stop = function() {
		_is_running	= false;
	};

	this.run = function(time) {
		_last_check = time;
		_last_run = time;
		_callback(time);
	};

	this.getMinutes = function() {
		return _time_data.minute;
	};

	this.getHours = function() {
		return _time_data.hour;
	};

	this.getDate = function() {
		return _time_data.date;
	};

	this.getMonth = function() {
		return _time_data.month;
	};

	this.getDay = function() {
		return _time_data.day;
	};

	this.save = function() {
		DB.save('_cron_' + _name, {run: this.getLastRun(), check: this.getLastCheck()});
	};

	this.onShutdown = function() {
		this.stop();
		this.save();
	};

	Cronjob(this, name, cycle, callback);
}<commit_msg>Optimizations<commit_after>/**
	The MIT License (MIT)

	Copyright (c) 2014 MyChannel-Apps.de

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

	@author		Adrian Preuß <Bizarrus>, Christoph Kühl <djchrisnet>
*/

var Cron = (new function() {
	var _cronjobs	= [];
	var _watcher;
	var _offlineCheck = false;

	this.init = function() {
		if(_watcher != undefined) {
			clearInterval(_watcher);
		}

		_watcher	= setInterval(this.run, 500);
	};

	this.enableOfflineRunCheck = function() {
		_offlineCheck = true;
	};

	this.checkOfflineRun = function(job) {
		if(job.getLastCheck() == 0) {
			return;
		}

		while(new Date().getTime() >= job.getLastCheck()) {
			var time = new Date(job.getLastCheck()+500);
			job.setLastCheck(time);

			if((time.getTime() - job.getLastRun() > 60000) && Cron.match(job.getMinutes(), time.getMinutes())&& Cron.match(job.getHours(), time.getHours()) && Cron.match(job.getDate(), time.getDate()) && Cron.match(job.getMonth(), time.getMonth()) && Cron.match(job.getDay(), time.getDay())) {
				job.run(time);
				return;
			}
		}
	};

	this.run = function() {
		var time = new Date();

		_cronjobs.each(function(job) {
			if(!job.isRunning()) {
				continue;
			}

			if((time.getTime() - job.getLastRun() > 60000) && Cron.match(job.getMinutes(), time.getMinutes()) && Cron.match(job.getHours(), time.getHours()) && Cron.match(job.getDate(), time.getDate()) && Cron.match(job.getMonth(), time.getMonth()) && Cron.match(job.getDay(), time.getDay())) {
				job.run(time);
			}
		});
	};

	this.add = function(cronjob) {
		_cronjobs.push(cronjob);

		if(_offlineCheck) {
			this.checkOfflineRun(cronjob);
		}
	};

	this.match = function(a, b) {
		var index	= 0;
		var length	= a.length;

		for(; index < length; ++index) {
			var c = a[index];

			if(c[0] === -1 || (b >= c[0] && b <= c[1])) {
				var b0 = b - c[0]; // make the modulo start from 1st miniture of from matched time, not first minute of from 0 minutes
				//WHAT THE FUCK IS b0 ?!?!?!?!?! BULLSHIT ..|..

				if(c[2] === -1 || b === 0 || b % c[2] === 0) {
					return true;
				}
			}
		}

		return  false;
	};

	this.parse = function(entry) {
		return entry.split(',').map(function(index) {
			var z = index.split('/');
			var x = z[0].split('-');

			if(x[0] == '*') {
				x[0] = -1;
			}

			if(x.length == 1) {
				x.push(x[0]);
			}

			x[2] = z.length === 1 ? -1 : z[1];
			x[0] = parseInt(x[0]); // 0 - from
			x[1] = parseInt(x[1]); // 1 - to
			x[2] = parseInt(x[2]); // 2 modulus

			return x;
		});
	};

	this.saveData = function() {
		_cronjobs.each(function(cron) {
			cron.save();
		});
	};

	this.onShutdown = function() {
		_cronjobs.each(function(cron) {
			cron.onShutdown();
		});

		if(_watcher != undefined) {
			clearInterval(_watcher);
		}
	};

	this.init();
}());

function Cronjob(name, cycle, callback) {
	var _name		= '';
	var _cycle		= '* * * * *';
	var _cycle_data	= [];
	var _is_running	= false;
	var _callback	= function(time) { /* Override Me */ };
	var _last_run	= undefined;
	var _last_check = undefined;
	var _time_data	= {
		minute:	'*',
		hour:	'*',
		date:	'*',
		month:	'*',
		day:	'*'
	};

	function Cronjob(instance, name, cycle, callback) {
		_name			= name;
		_cycle			= cycle;
		_callback		= callback;
		_cycle_data		= _cycle.match(/^([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s+([0-9,\-\/]+|\*{1}|\*{1}\/[0-9]+)\s*$/);
		_crondb			= DB.load('_cron_' + _name, {run:0, check:0});
		_last_run		= new Date(parseInt(_crondb.run));
		_last_check		= new Date(parseInt(_crondb.check));
		_time_data		= {
			minute:	Cron.parse(_cycle_data[1]),
			hour:	Cron.parse(_cycle_data[2]),
			date:	Cron.parse(_cycle_data[3]),
			month:	Cron.parse(_cycle_data[4]),
			day:	Cron.parse(_cycle_data[5])
		};
		Cron.add(instance);
		instance.start();
	}

	this.getLastRun = function() {
		return _last_run.getTime();
	};

	this.getName = function() {
		return _name;
	};

	this.getLastCheck = function() {
		return _last_check.getTime();
	};

	this.setLastCheck = function(time) {
		_last_check = time;
	};

	this.isRunning = function() {
		return _is_running;
	};

	this.start = function() {
		_is_running	= true;
	};

	this.stop = function() {
		_is_running	= false;
	};

	this.run = function(time) {
		_last_check	= time;
		_last_run	= time;
		_callback(time);
	};

	this.getMinutes = function() {
		return _time_data.minute;
	};

	this.getHours = function() {
		return _time_data.hour;
	};

	this.getDate = function() {
		return _time_data.date;
	};

	this.getMonth = function() {
		return _time_data.month;
	};

	this.getDay = function() {
		return _time_data.day;
	};

	this.save = function() {
		DB.save('_cron_' + _name, {
			run:	this.getLastRun(),
			check:	this.getLastCheck()
		});
	};

	this.onShutdown = function() {
		this.stop();
		this.save();
	};

	Cronjob(this, name, cycle, callback);
}<|endoftext|>


<commit_before>var base = require('./base.js');

exports.assemble = {
    addSchedule:
        function (parameters) {
            var userEventEntry = {
                availability: JSON.stringify(parameters.availability),
                Users_id: parameters.usersid,
                Events_id: parameters.eventsid
            };

            base.dbInsert('userevents', userEventEntry);

            return JSON.stringify({
                msgType: 'updateSchedule',
                status: 'complete'
            });
        },
   viewUser:
        function (parameters) {
            var userReadInfo = {
                Users_id: parameters.usersid
            };

            response = base.dbSelect('assemble' , 'users' , userReadInfo);

            return JSON.stringify({
                msgType: 'readuser',
                data: response,
                status: 'read'
            });

        };

<commit_msg>#7 - Create userReadInfo function to obtain user endpoint.<commit_after>var base = require('./base.js');

exports.assemble = {
    addSchedule:
        function (parameters, response) {
            var userEventEntry = {
                availability: JSON.stringify(parameters.availability),
                Users_id: parameters.usersid,
                Events_id: parameters.eventsid
            };

            base.dbInsert('userevents', userEventEntry, response);
        },

   viewUser:
    function (parameters , response) {
        var userReadInfo = {
            Users_id: parameters.usersid
        };

        var queryString = 'SELECT * FROM Users WHERE id = ' +  userReadInfo;
        base.dbSelect(queryString, response)
    },
    addEvent:
        function (parameters, response) {
            var eventEntry = {
                                name: parameters.eventName,
                                start_date: parameters.eventStartDate,
                                end_date: parameters.eventEndDate,
                                description: parameters.eventDescription
                            };

            base.dbInsert('events', eventEntry, response);
        }
} <|endoftext|>


<commit_before>//
//  Grid Forms
//  Copyright (c) 2013 Kumail Hunaid
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

$(function() {
    var GridForms = {
        el: {
            fieldsRows: $('[data-row-span]'),
            fieldsContainers: $('[data-field-span]'),
            focusableFields: $('input, textarea, select', '[data-field-span]'),
            window: $(window)
        },
        init: function() {
            this.focusField(this.el.focusableFields.filter(':focus'));
            this.equalizeFieldHeights();
            this.events();
        },
        focusField: function(currentField) {
            currentField.closest('[data-field-span]').addClass('focus');
        },
        removeFieldFocus: function() {
            this.el.fieldsContainers.removeClass('focus');
        },
        events: function() {
            var that = this;
            that.el.fieldsContainers.click(function() {
                $(this).find('input[type="text"], textarea, select').focus();
            });
            that.el.focusableFields.focus(function() {
                that.focusField($(this));
            });
            that.el.focusableFields.blur(function() {
                that.removeFieldFocus();
            });
            that.el.window.resize(function() {
                that.equalizeFieldHeights();
            });

        },
        equalizeFieldHeights: function() {
            this.el.fieldsContainers.css("height", "auto");

            var fieldsRows = this.el.fieldsRows;
            var fieldsContainers = this.el.fieldsContainers;

            // Make sure that the fields aren't stacked
            if (!this.areFieldsStacked()) {
                fieldsRows.each(function() {
                    // Get the height of the row (thus the tallest element's height)
                    var fieldRow = $(this);
                    var rowHeight = fieldRow.css('height');

                    // Set the height for each field in the row...
                    fieldRow.find(fieldsContainers).css('height', rowHeight);
                });
            }
        },
        areFieldsStacked: function() {
            // Get the first row
            // which does not only contain one field
            var firstRow = this.el.fieldsRows
                .not('[data-row-span="1"]')
                .first();

            // Get to the total width
            // of each field witin the row
            var totalWidth = 0;
            firstRow.children().each(function() {
                totalWidth += $(this).width();
            });

            // Determine whether fields are stacked or not
            return firstRow.width() <= totalWidth;
        }
    };
    GridForms.init();
});
<commit_msg>Expose GridForms to the global scope<commit_after>//
//  Grid Forms
//  Copyright (c) 2013 Kumail Hunaid
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

$(function() {
    var GridForms = {
        el: {
            fieldsRows: $('[data-row-span]'),
            fieldsContainers: $('[data-field-span]'),
            focusableFields: $('input, textarea, select', '[data-field-span]'),
            window: $(window)
        },
        init: function() {
            this.focusField(this.el.focusableFields.filter(':focus'));
            this.equalizeFieldHeights();
            this.events();
        },
        focusField: function(currentField) {
            currentField.closest('[data-field-span]').addClass('focus');
        },
        removeFieldFocus: function() {
            this.el.fieldsContainers.removeClass('focus');
        },
        events: function() {
            var that = this;
            that.el.fieldsContainers.click(function() {
                $(this).find('input[type="text"], textarea, select').focus();
            });
            that.el.focusableFields.focus(function() {
                that.focusField($(this));
            });
            that.el.focusableFields.blur(function() {
                that.removeFieldFocus();
            });
            that.el.window.resize(function() {
                that.equalizeFieldHeights();
            });

        },
        equalizeFieldHeights: function() {
            this.el.fieldsContainers.css("height", "auto");

            var fieldsRows = this.el.fieldsRows;
            var fieldsContainers = this.el.fieldsContainers;

            // Make sure that the fields aren't stacked
            if (!this.areFieldsStacked()) {
                fieldsRows.each(function() {
                    // Get the height of the row (thus the tallest element's height)
                    var fieldRow = $(this);
                    var rowHeight = fieldRow.css('height');

                    // Set the height for each field in the row...
                    fieldRow.find(fieldsContainers).css('height', rowHeight);
                });
            }
        },
        areFieldsStacked: function() {
            // Get the first row
            // which does not only contain one field
            var firstRow = this.el.fieldsRows
                .not('[data-row-span="1"]')
                .first();

            // Get to the total width
            // of each field witin the row
            var totalWidth = 0;
            firstRow.children().each(function() {
                totalWidth += $(this).width();
            });

            // Determine whether fields are stacked or not
            return firstRow.width() <= totalWidth;
        }
    };
    GridForms.init();
    window.GridForms = GridForms;
});
<|endoftext|>


<commit_before>// Import css
var link = document.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", API.url(widgetID,'bgcss.css'));
document.getElementsByTagName("head")[0].appendChild(link);

// Make the div container for the background and style it.
var fondoDiv = document.createElement('div');
var fondoDiv2 = document.createElement('div');

// Style the background div
fondoDiv.className = 'background_widget_bg1';

// Style of the inner background div (used for transitioning backgrounds)
fondoDiv2.className = 'background_widget_bg2 background_widget_transparent';

// Append the divs
document.body.appendChild(fondoDiv);
fondoDiv.appendChild(fondoDiv2);

var relations = {
	0:'backgroundImage',
	1:'backgroundColor',
	2:'backgroundPosition',
	3:'backgroundRepeat',
	4:'backgroundSize',
	'a':'left top',
	'b':'left center',
	'c':'left bottom',
	'd':'center top',
	'e':'center center',
	'f':'center bottom',
	'g':'right top',
	'h':'right center',
	'i':'right bottom',
	'j':'repeat',
	'k':'repeat-x',
	'l':'repeat-y',
	'm':'no-repeat',
	'n':'cover',
	'o':'contain',
	'p':'auto'
};

var backgrounds = [];
backgrounds.push([
	'http://static.freepik.com/foto-gratis/poligono-de-fondo_72818.jpg',
	'#000000',
	'e',
	'm',
	'n'
]);
backgrounds.push([
	'http://img.wallpaperstock.net:81/wallpapers/thumbs1/36523wide.jpg',
	'#000000',
	'e',
	'm',
	'n'
]);

var transitionTime = 3000; //ms
var delayBackground = 60000; //ms
var next = parseInt(Math.random() *backgrounds.length);

setBackground(fondoDiv, backgrounds[next]);

if(++next > backgrounds.length -1)
	next = 0;

setBackground(fondoDiv2, backgrounds[next]);

// Interval to change backgrounds over time
setInterval(function(){
	fondoDiv2.className = fondoDiv2.className.split("background_widget_transparent").join("");

	setTimeout(function(){
		setBackground(fondoDiv, backgrounds[next]);

		++next;
		if(next > backgrounds.length -1)
			next = 0;

		//Preload the next background
		fondoDiv2.className += "background_widget_transparent";
		setBackground(fondoDiv2, backgrounds[next]);

	}, transitionTime);
}, delayBackground);

// Change the style of a div to make it a background with the options of the background variable
function setBackground(div, background){
	div.style[relations[0]] = 'url("'+background[0]+'")';
	div.style[relations[1]] = background[1];
	for(var i = 2; i < 5; ++i){
		div.style[relations[i]] = relations[background[i]];
	}
}

// Function for the config widgetID. It returns the html object to append on the config window
var CONFIG_function = function(){
	// Make a copy of the backgrounds and use it to change configurations without touch the current background setup
	var backgrounds_copy = backgrounds.slice(0);

	var div = document.createElement('div');

	// Each row of the table will be a td with an input and another td with a description and the save button
	var table = document.createElement('table');

	// Time between transitions
	var tr = document.createElement('tr');
	var td = document.createElement('td');
	var inputDelayBackground = document.createElement('input');
	inputDelayBackground.type = 'text';
	inputDelayBackground.value = delayBackground/1000; // ms to s
	td.appendChild(inputDelayBackground);
	tr.appendChild(td);

	td = document.createElement('td');
	td.innerHTML = 'Time between transitions (in seconds)';
	tr.appendChild(td);
	table.appendChild(tr);

	// Time transitioning (in seconds)
	tr = document.createElement('tr');
	td = document.createElement('td');
	var inputTransitionTime = document.createElement('input');
	inputTransitionTime.type = 'text';
	inputTransitionTime.value = transitionTime/1000; // ms to s
	td.appendChild(inputTransitionTime);
	tr.appendChild(td);

	td = document.createElement('td');
	td.innerHTML = 'Time transitioning (in seconds)';
	tr.appendChild(td);
	table.appendChild(tr);

	div.appendChild(table);

	div.appendChild(document.createElement('br'));
	div.appendChild(document.createElement('br'));

	var tableBackgrounds = document.createElement('table');

	// Background list
	for(var i in backgrounds_copy){
		tableBackgrounds.appendChild(createBGTableElement(backgrounds_copy[i]));
	}

	div.appendChild(tableBackgrounds);

	div.appendChild(document.createElement('br'));
	div.appendChild(document.createElement('br'));

	// Add button
	input = document.createElement('button');
	input.innerHTML = "Add background";
	input.onclick = function(){
		backgrounds_copy.push(['','#000000','e','m','n']);
		tableBackgrounds.appendChild(createBGTableElement(backgrounds_copy[backgrounds_copy.length-1]));
	}
	div.appendChild(input);

	div.appendChild(document.createElement('br'));
	div.appendChild(document.createElement('br'));
	div.appendChild(document.createElement('br'));

	// Save button
	input = document.createElement('button');
	input.innerHTML = "Save changes";
	div.appendChild(input);

	function removeBackground(){

	}

	// Returns a tr for the table of backgrounds
	function createBGTableElement(background){
		var trBody = document.createElement('tr');
		var td = document.createElement('td');

		// First TD is for the image, second TD for the inputs and the text (that are in another table)
		var previewPic = document.createElement('img');
		previewPic.style.cssFloat  = 'right';
		previewPic.style.height    = '10em';
		previewPic.style.maxWidth  = '25em';
		previewPic.style.boxShadow = '0 0 0.5em #151515';
		if(background){
			previewPic.src = background[0];
		}
		td.appendChild(previewPic);
		trBody.appendChild(td);

		td = document.createElement('td');
		trBody.appendChild(td);

		// inputs and text
		var table = document.createElement('table');

		td.appendChild(table);

		// URL input
		var tr = document.createElement('tr');
		td = document.createElement('td');
		tr.appendChild(td);
		var input = document.createElement('input');
		input.type = 'text';
		input.value = background ? background[0] : '';
		input.placeholder = 'http://www.domain.com/image.jpg';
		input.onchange = input.onkeyup = function(){
			previewPic.src = this.value;
		}
		td.appendChild(input);

		td = document.createElement('td');
		td.innerHTML = 'URL of the background';
		tr.appendChild(td);
		table.appendChild(tr);

		// COLOR input
		tr = document.createElement('tr');
		td = document.createElement('td');
		tr.appendChild(td);
		input = document.createElement('input');
		input.type = 'text';
		input.value = background ? background[1] : '#000000';
		input.placeholder = '#000000';
		td.appendChild(input);

		td = document.createElement('td');
		td.innerHTML = 'Hexadecimal color to fill the background outsides';
		tr.appendChild(td);
		table.appendChild(tr);

		// POSITION input
		tr = document.createElement('tr');
		td = document.createElement('td');
		tr.appendChild(td);
		input = document.createElement('select');
		input.innerHTML = '<option value="e">center center</option><option value="d">center top</option><option value="f">center bottom</option><option value="a">left top</option><option value="b">left center</option><option value="c">left bottom</option><option value="g">right top</option><option value="h">right center</option><option value="i">right bottom</option>';
		td.appendChild(input);

		td = document.createElement('td');
		td.innerHTML = 'Position of the background';
		tr.appendChild(td);
		table.appendChild(tr);

		// REPEAT input
		tr = document.createElement('tr');
		td = document.createElement('td');
		tr.appendChild(td);
		input = document.createElement('select');
		input.innerHTML = '<option value="j">Repeat</option><option value="k">Repeat horizontally</option><option value="l">Repeat vertically</option><option value="m">No repeat</option>';
		td.appendChild(input);

		td = document.createElement('td');
		td.innerHTML = 'Background repeating to fill the window';
		tr.appendChild(td);
		table.appendChild(tr);

		// SIZE input
		tr = document.createElement('tr');
		td = document.createElement('td');
		tr.appendChild(td);
		input = document.createElement('select');
		input.innerHTML = '<option value="n">Cover</option><option value="o">Contain</option><option value="p">Auto</option>';
		td.appendChild(input);

		td = document.createElement('td');
		td.innerHTML = 'How the background scales to fill the window';
		tr.appendChild(td);
		table.appendChild(tr);

		// REMOVE input
		tr = document.createElement('tr');
		td = document.createElement('td');
		tr.appendChild(td);
		input = document.createElement('button');
		input.innerHTML = "Remove";
		td.appendChild(input);
		table.appendChild(tr);

		return trBody;
	}

	return div;
}
<commit_msg>Developing the background widget<commit_after>// Import css
var link = document.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", API.url(widgetID,'bgcss.css'));
document.getElementsByTagName("head")[0].appendChild(link);

// Make the div container for the background and style it.
var fondoDiv = document.createElement('div');
var fondoDiv2 = document.createElement('div');

// Style the background div
fondoDiv.className = 'background_widget_bg1';

// Style of the inner background div (used for transitioning backgrounds)
fondoDiv2.className = 'background_widget_bg2 background_widget_transparent';

// Append the divs
document.body.appendChild(fondoDiv);
fondoDiv.appendChild(fondoDiv2);

var relations = {
	0:'backgroundImage',
	1:'backgroundColor',
	2:'backgroundPosition',
	3:'backgroundRepeat',
	4:'backgroundSize',
	'a':'left top',
	'b':'left center',
	'c':'left bottom',
	'd':'center top',
	'e':'center center',
	'f':'center bottom',
	'g':'right top',
	'h':'right center',
	'i':'right bottom',
	'j':'repeat',
	'k':'repeat-x',
	'l':'repeat-y',
	'm':'no-repeat',
	'n':'cover',
	'o':'contain',
	'p':'auto'
};

var backgrounds = [];
backgrounds.push([
	'http://static.freepik.com/foto-gratis/poligono-de-fondo_72818.jpg',
	'#000000',
	'e',
	'm',
	'n'
]);
backgrounds.push([
	'http://img.wallpaperstock.net:81/wallpapers/thumbs1/36523wide.jpg',
	'#000000',
	'e',
	'm',
	'n'
]);

var transitionTime = 3000; //ms
var delayBackground = 60000; //ms
var next = parseInt(Math.random() *backgrounds.length);

setBackground(fondoDiv, backgrounds[next]);

if(++next > backgrounds.length -1)
	next = 0;

setBackground(fondoDiv2, backgrounds[next]);

// Interval to change backgrounds over time
setInterval(function(){
	fondoDiv2.className = fondoDiv2.className.split("background_widget_transparent").join("");

	setTimeout(function(){
		setBackground(fondoDiv, backgrounds[next]);

		++next;
		if(next > backgrounds.length -1)
			next = 0;

		//Preload the next background
		fondoDiv2.className += "background_widget_transparent";
		setBackground(fondoDiv2, backgrounds[next]);

	}, transitionTime);
}, delayBackground);

// Change the style of a div to make it a background with the options of the background variable
function setBackground(div, background){
	div.style[relations[0]] = 'url("'+background[0]+'")';
	div.style[relations[1]] = background[1];
	for(var i = 2; i < 5; ++i){
		div.style[relations[i]] = relations[background[i]];
	}
}

// Function for the config widgetID. It returns the html object to append on the config window
var CONFIG_function = function(){
	// Make a copy of the backgrounds and use it to change configurations without touch the current background setup
	var backgrounds_copy = backgrounds.slice(0);

	var div = document.createElement('div');

	// Each row of the table will be a td with an input and another td with a description and the save button
	var table = document.createElement('table');

	// Time between transitions
	var tr = document.createElement('tr');
	var td = document.createElement('td');
	var inputDelayBackground = document.createElement('input');
	inputDelayBackground.type = 'text';
	inputDelayBackground.value = delayBackground/1000; // ms to s
	td.appendChild(inputDelayBackground);
	tr.appendChild(td);

	td = document.createElement('td');
	td.innerHTML = 'Time between transitions (in seconds)';
	tr.appendChild(td);
	table.appendChild(tr);

	// Time transitioning (in seconds)
	tr = document.createElement('tr');
	td = document.createElement('td');
	var inputTransitionTime = document.createElement('input');
	inputTransitionTime.type = 'text';
	inputTransitionTime.value = transitionTime/1000; // ms to s
	td.appendChild(inputTransitionTime);
	tr.appendChild(td);

	td = document.createElement('td');
	td.innerHTML = 'Time transitioning (in seconds)';
	tr.appendChild(td);
	table.appendChild(tr);

	div.appendChild(table);

	div.appendChild(document.createElement('br'));
	div.appendChild(document.createElement('br'));

	var tableBackgrounds = document.createElement('table');

	// Background list
	for(var i in backgrounds_copy){
		tableBackgrounds.appendChild(createBGTableElement(backgrounds_copy[i]));
	}

	div.appendChild(tableBackgrounds);

	div.appendChild(document.createElement('br'));
	div.appendChild(document.createElement('br'));

	// Add button
	input = document.createElement('button');
	input.innerHTML = "Add background";
	input.onclick = addBackground;
	div.appendChild(input);

	div.appendChild(document.createElement('br'));
	div.appendChild(document.createElement('br'));
	div.appendChild(document.createElement('br'));

	// Save button
	input = document.createElement('button');
	input.innerHTML = "Save changes";
	input.onclick = saveBackgrounds();
	div.appendChild(input);

	function addBackground(){
		// This is the default background
		backgrounds_copy.push(['','#000000','e','m','n']);
		tableBackgrounds.appendChild(createBGTableElement(backgrounds_copy[backgrounds_copy.length-1]));
	}

	function removeBackground(background){
		// Remove the object from the array and delete the tr of the table that corresponds to the background
		var index = backgrounds_copy.indexOf(background);
		backgrounds_copy.splice(index, 1);
		tableBackgrounds.childNodes[index].remove();
	}

	function saveBackgrounds(){
		// Change the local variables to the new ones
		backgrounds = backgrounds_copy;
		delayBackground = inputDelayBackground.value *1000; // s to ms
		transitionTime = inputTransitionTime.value *1000; // s to ms

		// Save the variables using the API

	}

	// Returns a tr for the table of backgrounds
	function createBGTableElement(background){
		var trBody = document.createElement('tr');
		var td = document.createElement('td');

		// First TD is for the image, second TD for the inputs and the text (that are in another table)
		var previewPic = document.createElement('img');
		previewPic.style.cssFloat  = 'right';
		previewPic.style.height    = '10em';
		previewPic.style.maxWidth  = '25em';
		previewPic.style.boxShadow = '0 0 0.5em #151515';
		if(background){
			previewPic.src = background[0];
		}
		td.appendChild(previewPic);
		trBody.appendChild(td);

		td = document.createElement('td');
		trBody.appendChild(td);

		// inputs and text
		var table = document.createElement('table');

		td.appendChild(table);

		// URL input
		var tr = document.createElement('tr');
		td = document.createElement('td');
		tr.appendChild(td);
		var input = document.createElement('input');
		input.type = 'text';
		input.value = background ? background[0] : '';
		input.placeholder = 'http://www.domain.com/image.jpg';
		input.onchange = input.onkeyup = function(){
			previewPic.src = background[0] = this.value;
		}
		td.appendChild(input);

		td = document.createElement('td');
		td.innerHTML = 'URL of the background';
		tr.appendChild(td);
		table.appendChild(tr);

		// COLOR input
		tr = document.createElement('tr');
		td = document.createElement('td');
		tr.appendChild(td);
		input = document.createElement('input');
		input.type = 'text';
		input.value = background ? background[1] : '#000000';
		input.placeholder = '#000000';
		input.onchange = function(){
			background[1] = this.value;
		}
		td.appendChild(input);

		td = document.createElement('td');
		td.innerHTML = 'Hexadecimal color to fill the background outsides';
		tr.appendChild(td);
		table.appendChild(tr);

		// POSITION input
		tr = document.createElement('tr');
		td = document.createElement('td');
		tr.appendChild(td);
		input = document.createElement('select');
		input.innerHTML = '<option value="e">center center</option><option value="d">center top</option><option value="f">center bottom</option><option value="a">left top</option><option value="b">left center</option><option value="c">left bottom</option><option value="g">right top</option><option value="h">right center</option><option value="i">right bottom</option>';
		input.onchange = function(){
			background[2] = this.value;
		}
		td.appendChild(input);

		td = document.createElement('td');
		td.innerHTML = 'Position of the background';
		tr.appendChild(td);
		table.appendChild(tr);

		// REPEAT input
		tr = document.createElement('tr');
		td = document.createElement('td');
		tr.appendChild(td);
		input = document.createElement('select');
		input.innerHTML = '<option value="j">Repeat</option><option value="k">Repeat horizontally</option><option value="l">Repeat vertically</option><option value="m">No repeat</option>';
		input.onchange = function(){
			background[3] = this.value;
		}
		td.appendChild(input);

		td = document.createElement('td');
		td.innerHTML = 'Background repeating to fill the window';
		tr.appendChild(td);
		table.appendChild(tr);

		// SIZE input
		tr = document.createElement('tr');
		td = document.createElement('td');
		tr.appendChild(td);
		input = document.createElement('select');
		input.innerHTML = '<option value="n">Cover</option><option value="o">Contain</option><option value="p">Auto</option>';
		input.onchange = function(){
			background[4] = this.value;
		}
		td.appendChild(input);

		td = document.createElement('td');
		td.innerHTML = 'How the background scales to fill the window';
		tr.appendChild(td);
		table.appendChild(tr);

		// REMOVE input
		tr = document.createElement('tr');
		td = document.createElement('td');
		tr.appendChild(td);
		input = document.createElement('button');
		input.innerHTML = "Remove";
		input.onclick = function(){
			removeBackground(background);
		}
		td.appendChild(input);
		table.appendChild(tr);

		return trBody;
	}

	return div;
}
<|endoftext|>


<commit_before>//= require ../core
//= require_self

(function () {

	"use strict";

	var LINK_SPLITTER = /,[\s\r\n]*?</;
	var LINK_MATCHER = /<([^>]+)>((?:[\s\r\n]|.)*)/;
	var ATTR_SPLITTER = /[\s\r\n]*;[\s\r\n]*/;
	var ATTR_MATCHER = /([^=]+)=['"]?([^'"]+)['"]?/;

	Marbles.HTTP = Marbles.HTTP || {};
	Marbles.HTTP.LinkHeader = {
		parse: function (linkHeaderStr) {
			var links = [];
			var ref = linkHeaderStr.split(LINK_SPLITTER);
			var i, _len, match, link;
			var j, _r, _l;
			for (i = 0, _len = ref.length; i < _len; i++) {
				match = ref[i].match(LINK_MATCHER);
				if (!match) {
					continue;
				}

				link = {
					href: match[1]
				};
				_r = match[2].split(ATTR_SPLITTER);
				for (j = 0, _l = _r.length; j < _l; j++) {
					match = _r[j].match(ATTR_MATCHER);
					if (!match) {
						continue;
					}

					link[match[1]] = match[2];
				}

				links.push(link);
			}

			return links;
		}
	};

})();
<commit_msg>Fix HTTP.LinkHeader link splitter<commit_after>//= require ../core
//= require_self

(function () {

	"use strict";

	var LINK_SPLITTER = /,[\s\r\n]*/;
	var LINK_MATCHER = /<([^>]+)>((?:[\s\r\n]|.)*)/;
	var ATTR_SPLITTER = /[\s\r\n]*;[\s\r\n]*/;
	var ATTR_MATCHER = /([^=]+)=['"]?([^'"]+)['"]?/;

	Marbles.HTTP = Marbles.HTTP || {};
	Marbles.HTTP.LinkHeader = {
		parse: function (linkHeaderStr) {
			var links = [];
			var ref = linkHeaderStr.split(LINK_SPLITTER);
			var i, _len, match, link;
			var j, _r, _l;
			for (i = 0, _len = ref.length; i < _len; i++) {
				match = ref[i].match(LINK_MATCHER);
				if (!match) {
					continue;
				}

				link = {
					href: match[1]
				};
				_r = match[2].split(ATTR_SPLITTER);
				for (j = 0, _l = _r.length; j < _l; j++) {
					match = _r[j].match(ATTR_MATCHER);
					if (!match) {
						continue;
					}

					link[match[1]] = match[2];
				}

				links.push(link);
			}

			return links;
		}
	};

})();
<|endoftext|>


<commit_before>'use strict'

var nodeD3 = require('d3');
var jsdom = require('jsdom').jsdom;
var decorators = require('./decorators.js');
var thunkify = require('thunkify');

var doctype = '<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'

function svgGraphic(decoratorName, data, callback){
	var decorator = decorators[decoratorName];
	var document = jsdom();
	var window = document.parentWindow;
	window.d3 = nodeD3;
	window.d3.select('body').html('');
	var htmlbody = window.d3.select('body');
	htmlbody.call( decorator, data );
	var markup = htmlbody.html()
	window.__stopAllTimers();
	window.close();
	callback ( null, doctype + markup );
}

module.exports = thunkify( svgGraphic );<commit_msg>much simpler svg rendering...<commit_after>'use strict'

var d3 = require('d3');
var jsdom = require('jsdom').jsdom;
var decorators = require('./decorators.js');
var thunkify = require('thunkify');

var doctype = '<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'

function svgGraphic(decoratorName, data, callback){
	var decorator = decorators[decoratorName];
	var htmlbody = d3.select('body');
	htmlbody.call( decorator, data );
	var markup = htmlbody.html();
	callback ( null, doctype + markup );
}

module.exports = thunkify( svgGraphic );<|endoftext|>