<commit_before>import React from 'react';
import ReactDOM from 'react-dom';

require('./styles/base.less')

import Header from './components/header'
import Registration from './components/registration'
import Options from './components/options'

const App = () => {
  return(

            <Registration title={ 'Bedrift' } />

            <Options />

  )
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
)
<commit_msg>Added some real basic styling to index<commit_after>import React from 'react'
import ReactDOM from 'react-dom'

require('./styles/base.less')

import Header from './components/header'
import Registration from './components/registration'
import Options from './components/options'

const App = () => {
  return(

              <Registration title={ 'Bedrift' } />
              <Options />

  )
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
)
<|endoftext|>


<commit_before>var uuid = require('node-uuid')

module.exports = function (options) {

  if (options.constructor && options.constructor.name === 'Logger')
    options = { logger: options }

  if (!options.logger)
    throw new Error('`options.logger` is required')

  var logger = options.logger
    , headerName = options.headerName || 'X-Request-Id'
    , headerNameLower = headerName.toLowerCase()
    , propertyName = options.propertyName || 'reqId'
    , logName = options.logName || 'req_id'

  logger = logger.child({ serializers: logger.constructor.stdSerializers })

  return function (req, res, next) {
    var id = req[propertyName]
          || req.headers[headerNameLower]
          || uuid.v1()

    var prefs = {}
    prefs[logName] = id
    req.log = res.log = logger.child(prefs, true)

    req[propertyName] = res[propertyName] = id
    res.setHeader(headerName, id)

    req.log.info('request start')
    res.on('finish', function() {
      res.log.info(
          { res: res
          , req: req
          }
        , 'request finish'
        )
    })

    next()
  }
}
<commit_msg>add request duration to log output<commit_after>var uuid = require('node-uuid')

module.exports = function (options) {

  if (options.constructor && options.constructor.name === 'Logger')
    options = { logger: options }

  if (!options.logger)
    throw new Error('`options.logger` is required')

  var logger = options.logger
    , headerName = options.headerName || 'X-Request-Id'
    , headerNameLower = headerName.toLowerCase()
    , propertyName = options.propertyName || 'reqId'
    , logName = options.logName || 'req_id'

  logger = logger.child({ serializers: logger.constructor.stdSerializers })

  return function (req, res, next) {
    var id = req[propertyName]
          || req.headers[headerNameLower]
          || uuid.v1()

    var start = Date.now()

    var prefs = {}
    prefs[logName] = id
    req.log = res.log = logger.child(prefs, true)

    req[propertyName] = res[propertyName] = id
    res.setHeader(headerName, id)

    req.log.info('request start')
    res.on('finish', function() {
      res.log.info(
          { res: res
          , req: req
          , duration: Date.now() - start
          }
        , 'request finish'
        )
    })

    next()
  }
}
<|endoftext|>


<commit_before>/*
 * Chat component
 */
import Placeholder from './src/components/general/Placeholder';
import Loading from './src/components/general/Loading';
import WebView from './src/components/general/WebView';

import Analytics from './src/lib/analytics';
import AppUtil from './src/lib/util';
import AppAPI from './src/lib/api';

import ModuleConfig from './src/constants/config';

import rootReducer from './src/redux/index';
import * as SideMenuActions from './src/redux/sidemenu/actions';
import * as UserActions from './src/redux/user/actions';

import ProfileEditView from './src/auth/Profile/ProfileEditView';
import AuthWebView from './src/auth/WebView';
import AuthLogin from './src/auth/Login/LoginContainer';
import SelectServer from './src/auth/SelectServer';
import SSOTest from './src/auth/SSOTest';

import Network from './src/network';

import DrawerContainer from './src/containers/ui/DrawerContainer';
import CameraActions from './src/chat/ui/room/CameraActions';
import PhotoLibrary from './src/chat/ui/room/PhotoLibrary';
import UploadedPhotos from './src/chat/UploadedPhotos';
import MemberListView from './src/chat/ui/group/MemberListView';
import SearchRoomView from './src/chat/ui/group/SearchRoomView';
import MemberDetailView from './src/chat/ui/group/MemberDetailView';
import SearchListView from './src/chat/ui/group/SearchListView';
import VideoPlayer from './src/chat/VideoPlayer';
import MessageImageView from './src/chat/ui/room/MessageImageView';
import SupportGroup from './src/chat/ui/room/SupportGroup';
import ReplyMessageView from './src/chat/ui/room/ReplyMessageView';
import PhotoPreview from './src/chat/ui/room/PhotoPreview';
import AboutView from './src/containers/ui/Menu/AboutView';
import Menu from './src/containers/ui/Menu/MenuView';
import GroupList from './src/chat/ui/group/GroupView';
import RoomView from './src/chat/ui/room/RoomView';
import { NavbarMenuButton } from './src/containers/ui/NavbarMenuButton/NavbarMenuButtonContainer';

import ImagePreview from './src/chat/ui/room/attachment/ImagePreview';
import PictureGallery from './src/chat/ui/room/attachment/PictureGallery';

export {
    // general components
    Placeholder,
    Loading,
    WebView,

    DrawerContainer,
    CameraActions,
    PhotoLibrary,
    UploadedPhotos,
    MemberListView,
    SearchRoomView,
    MemberDetailView,
    SearchListView,
    VideoPlayer,
    MessageImageView,
    SupportGroup,
    ReplyMessageView,
    PhotoPreview,
    AboutView,
    Menu,
    GroupList,
    NavbarMenuButton,
    RoomView,
    ImagePreview,
    PictureGallery,

    // auth
    ProfileEditView,
    AuthWebView,
    AuthLogin,
    SelectServer,
    SSOTest,

    // utils
    Analytics,
    AppUtil,
    AppAPI,

    // constants
    ModuleConfig,

    // network
    Network,

    // redux
    rootReducer,
    SideMenuActions,
    UserActions,
};

// export all UI components
export * from './src/components/ui/';
export * from './src/chat/ui/';

// export all themes
export * from './src/theme/';

// -- EOF --
<commit_msg>Leftmenu removal refactor<commit_after>/*
 * Chat component
 */
import Placeholder from './src/components/general/Placeholder';
import Loading from './src/components/general/Loading';
import WebView from './src/components/general/WebView';

import Analytics from './src/lib/analytics';
import AppUtil from './src/lib/util';
import AppAPI from './src/lib/api';

import ModuleConfig from './src/constants/config';

import rootReducer from './src/redux/index';
import * as SideMenuActions from './src/redux/sidemenu/actions';
import * as UserActions from './src/redux/user/actions';

import ProfileEditView from './src/auth/Profile/ProfileEditView';
import AuthWebView from './src/auth/WebView';
import AuthLogin from './src/auth/Login/LoginContainer';
import SelectServer from './src/auth/SelectServer';
import SSOTest from './src/auth/SSOTest';

import Network from './src/network';

import DrawerContainer from './src/containers/ui/DrawerContainer';
import CameraActions from './src/chat/ui/room/CameraActions';
import PhotoLibrary from './src/chat/ui/room/PhotoLibrary';
import UploadedPhotos from './src/chat/UploadedPhotos';
import MemberListView from './src/chat/ui/group/MemberListView';
import SearchRoomView from './src/chat/ui/group/SearchRoomView';
import MemberDetailView from './src/chat/ui/group/MemberDetailView';
import SearchListView from './src/chat/ui/group/SearchListView';
import VideoPlayer from './src/chat/VideoPlayer';
import MessageImageView from './src/chat/ui/room/MessageImageView';
import SupportGroup from './src/chat/ui/room/SupportGroup';
import ReplyMessageView from './src/chat/ui/room/ReplyMessageView';
import PhotoPreview from './src/chat/ui/room/PhotoPreview';
import AboutView from './src/containers/ui/Menu/AboutView';
import ProfileView from './src/containers/ui/Menu/ProfileView';
import Menu from './src/containers/ui/Menu/MenuView';
import GroupList from './src/chat/ui/group/GroupView';
import RoomView from './src/chat/ui/room/RoomView';
import { NavbarMenuButton } from './src/containers/ui/NavbarMenuButton/NavbarMenuButtonContainer';

import ImagePreview from './src/chat/ui/room/attachment/ImagePreview';
import PictureGallery from './src/chat/ui/room/attachment/PictureGallery';

export {
    // general components
    Placeholder,
    Loading,
    WebView,

    DrawerContainer,
    CameraActions,
    PhotoLibrary,
    UploadedPhotos,
    MemberListView,
    SearchRoomView,
    MemberDetailView,
    SearchListView,
    VideoPlayer,
    MessageImageView,
    SupportGroup,
    ReplyMessageView,
    PhotoPreview,
    AboutView,
    ProfileView,
    Menu,
    GroupList,
    NavbarMenuButton,
    RoomView,
    ImagePreview,
    PictureGallery,

    // auth
    ProfileEditView,
    AuthWebView,
    AuthLogin,
    SelectServer,
    SSOTest,

    // utils
    Analytics,
    AppUtil,
    AppAPI,

    // constants
    ModuleConfig,

    // network
    Network,

    // redux
    rootReducer,
    SideMenuActions,
    UserActions,
};

// export all UI components
export * from './src/components/ui/';
export * from './src/chat/ui/';

// export all themes
export * from './src/theme/';

// -- EOF --
<|endoftext|>


<commit_before>'use strict';

var data = module.exports = {
  jquery: {
    versions: ['2.1.1', '2.1.0', '2.0.3', '2.0.2', '2.0.1', '2.0.0', '1.11.1', '1.11.0', '1.10.2', '1.10.1', '1.10.0', '1.9.1', '1.9.0', '1.8.3', '1.8.2', '1.8.1', '1.8.0', '1.7.2', '1.7.1', '1.7.0', '1.6.4', '1.6.3', '1.6.2', '1.6.1', '1.6.0', '1.5.2', '1.5.1', '1.5.0', '1.4.4', '1.4.3', '1.4.2', '1.4.1', '1.4.0', '1.3.2', '1.3.1', '1.3.0', '1.2.6', '1.2.3'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/jquery/' + version + '/jquery.min.js';
    }
  },
  'jquery-ui': {
    versions: ['1.11.0', '1.10.4', '1.10.3', '1.10.2', '1.10.1', '1.10.0', '1.9.2', '1.9.1', '1.9.0', '1.8.24', '1.8.23', '1.8.22', '1.8.21', '1.8.20', '1.8.19', '1.8.18', '1.8.17', '1.8.16', '1.8.15', '1.8.14', '1.8.13', '1.8.12', '1.8.11', '1.8.10', '1.8.9', '1.8.8', '1.8.7', '1.8.6', '1.8.5', '1.8.4', '1.8.2', '1.8.1', '1.8.0', '1.7.3', '1.7.2', '1.7.1', '1.7.0', '1.6.0', '1.5.3', '1.5.2'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/jqueryui/' + version + '/jquery-ui.min.js';
    }
  },
  dojo: {
    versions: ['1.10.0', '1.9.3', '1.9.2', '1.9.1', '1.9.0', '1.8.5', '1.8.4', '1.8.3', '1.8.2', '1.8.1', '1.8.0', '1.7.5', '1.7.4', '1.7.3', '1.7.2', '1.7.1', '1.7.0', '1.6.1', '1.6.0', '1.5.2', '1.5.1', '1.5.0', '1.4.4', '1.4.3', '1.4.1', '1.4.0', '1.3.2', '1.3.1', '1.3.0', '1.2.3', '1.2.0', '1.1.1'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/dojo/' + version + '/dojo/dojo.js';
    }
  },
  swfobject: {
    versions: ['2.2', '2.1'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/swfobject/' + version + '/swfobject.js';
    }
  }
};

// AngularJS

var angularFiles = [
  'angular',
  'angular-animate',
  'angular-cookies',
  'angular-loader',
  'angular-resource',
  'angular-route',
  'angular-sanitize',
  'angular-touch'
];

angularFiles.forEach(function (item) {
  var stableVersions = ['1.2.23', '1.2.22', '1.2.21', '1.2.20', '1.2.19', '1.2.18', '1.2.17', '1.2.16', '1.2.15', '1.2.14', '1.2.13', '1.2.12', '1.2.11', '1.2.10', '1.2.9', '1.2.8', '1.2.7', '1.2.6', '1.2.5', '1.2.4', '1.2.3', '1.2.2', '1.2.1', '1.2.0', '1.0.8', '1.0.7', '1.0.6', '1.0.5', '1.0.4', '1.0.3', '1.0.2', '1.0.1'];
  var unstableVersions = ['1.3.0-rc.3', '1.3.0-rc.2', '1.3.0-rc.1', '1.3.0-rc.0', '1.3.0-beta.19', '1.3.0-beta.18', '1.3.0-beta.17', '1.3.0-beta.16', '1.3.0-beta.15', '1.3.0-beta.14', '1.3.0-beta.13', '1.3.0-beta.12', '1.3.0-beta.11', '1.3.0-beta.10', '1.3.0-beta.9', '1.3.0-beta.8', '1.3.0-beta.7', '1.3.0-beta.6', '1.3.0-beta.5', '1.3.0-beta.4', '1.3.0-beta.3', '1.3.0-beta.2', '1.3.0-beta.1'];
  data[item] = {
    versions: [].concat(stableVersions).concat(unstableVersions),
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/angularjs/' + version + '/' + item + '.min.js';
    }
  };
});
<commit_msg>Add Angular unstable 1.3.0-rc.4<commit_after>'use strict';

var data = module.exports = {
  jquery: {
    versions: ['2.1.1', '2.1.0', '2.0.3', '2.0.2', '2.0.1', '2.0.0', '1.11.1', '1.11.0', '1.10.2', '1.10.1', '1.10.0', '1.9.1', '1.9.0', '1.8.3', '1.8.2', '1.8.1', '1.8.0', '1.7.2', '1.7.1', '1.7.0', '1.6.4', '1.6.3', '1.6.2', '1.6.1', '1.6.0', '1.5.2', '1.5.1', '1.5.0', '1.4.4', '1.4.3', '1.4.2', '1.4.1', '1.4.0', '1.3.2', '1.3.1', '1.3.0', '1.2.6', '1.2.3'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/jquery/' + version + '/jquery.min.js';
    }
  },
  'jquery-ui': {
    versions: ['1.11.0', '1.10.4', '1.10.3', '1.10.2', '1.10.1', '1.10.0', '1.9.2', '1.9.1', '1.9.0', '1.8.24', '1.8.23', '1.8.22', '1.8.21', '1.8.20', '1.8.19', '1.8.18', '1.8.17', '1.8.16', '1.8.15', '1.8.14', '1.8.13', '1.8.12', '1.8.11', '1.8.10', '1.8.9', '1.8.8', '1.8.7', '1.8.6', '1.8.5', '1.8.4', '1.8.2', '1.8.1', '1.8.0', '1.7.3', '1.7.2', '1.7.1', '1.7.0', '1.6.0', '1.5.3', '1.5.2'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/jqueryui/' + version + '/jquery-ui.min.js';
    }
  },
  dojo: {
    versions: ['1.10.0', '1.9.3', '1.9.2', '1.9.1', '1.9.0', '1.8.5', '1.8.4', '1.8.3', '1.8.2', '1.8.1', '1.8.0', '1.7.5', '1.7.4', '1.7.3', '1.7.2', '1.7.1', '1.7.0', '1.6.1', '1.6.0', '1.5.2', '1.5.1', '1.5.0', '1.4.4', '1.4.3', '1.4.1', '1.4.0', '1.3.2', '1.3.1', '1.3.0', '1.2.3', '1.2.0', '1.1.1'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/dojo/' + version + '/dojo/dojo.js';
    }
  },
  swfobject: {
    versions: ['2.2', '2.1'],
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/swfobject/' + version + '/swfobject.js';
    }
  }
};

// AngularJS

var angularFiles = [
  'angular',
  'angular-animate',
  'angular-cookies',
  'angular-loader',
  'angular-resource',
  'angular-route',
  'angular-sanitize',
  'angular-touch'
];

angularFiles.forEach(function (item) {
  var stableVersions = ['1.2.23', '1.2.22', '1.2.21', '1.2.20', '1.2.19', '1.2.18', '1.2.17', '1.2.16', '1.2.15', '1.2.14', '1.2.13', '1.2.12', '1.2.11', '1.2.10', '1.2.9', '1.2.8', '1.2.7', '1.2.6', '1.2.5', '1.2.4', '1.2.3', '1.2.2', '1.2.1', '1.2.0', '1.0.8', '1.0.7', '1.0.6', '1.0.5', '1.0.4', '1.0.3', '1.0.2', '1.0.1'];
  var unstableVersions = ['1.3.0-rc.4', '1.3.0-rc.3', '1.3.0-rc.2', '1.3.0-rc.1', '1.3.0-rc.0', '1.3.0-beta.19', '1.3.0-beta.18', '1.3.0-beta.17', '1.3.0-beta.16', '1.3.0-beta.15', '1.3.0-beta.14', '1.3.0-beta.13', '1.3.0-beta.12', '1.3.0-beta.11', '1.3.0-beta.10', '1.3.0-beta.9', '1.3.0-beta.8', '1.3.0-beta.7', '1.3.0-beta.6', '1.3.0-beta.5', '1.3.0-beta.4', '1.3.0-beta.3', '1.3.0-beta.2', '1.3.0-beta.1'];
  data[item] = {
    versions: [].concat(stableVersions).concat(unstableVersions),
    url: function (version) {
      return '//ajax.googleapis.com/ajax/libs/angularjs/' + version + '/' + item + '.min.js';
    }
  };
});
<|endoftext|>


<commit_before>var request = require('request'),
	_ = require('underscore');

module.exports = function (host) {
	return {
		/** Queries index and returns results in callback(err,result : object{docs,stats}).
		 * @param {string} db
		 * @param {string} index
		 * @param {string} whereClause
		 * @param {int} start
		 * @param {int} limit
		 * @param {Array<string>} sortBys
		 * @param {Array<string>} fetchings
		 * @param {Function} cb
		 */
		indexQuery: function (db, index, whereClause, start, limit, sortBys, fetchings, cb) {
			if (typeof whereClause === 'function') {
				cb = whereClause;
				whereClause = '';
				start = 0;
				limit = 12;
				sortBys = [];
				fetchings = [];
			}
			if (typeof start === 'function') {
				cb = start;
				start = 0;
				limit = 12;
				sortBys = [];
				fetchings = [];
			}
			if (typeof sortBys === 'function') {
				cb = sortBys;
				sortBys = [];
				fetchings = [];
			}
			if (typeof fetchings === 'function') {
				cb = fetchings;
				fetchings = [];
			}
			var url = host +
				'databases/' + db +
				'/indexes/' + index +
				'?query=' + encodeURIComponent(whereClause) +
				'&operator=AND' +
				'&pageSize=' + limit +
				'&start=' + start;
			var sorts = sortBys.map(function (prop) {
				return '&sort=' + prop;
			}).join('');
			var fetchs = fetchings.map(function (prop) {
				return '&fetch=' + prop;
			}).join('');
			url = url + sorts + fetchs;
			request(url, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(body);
					var stats = _.reduce(result, function (memo, value, key) {
						if (key !== "Results") {
							memo[key] = value;
						}
						return memo;
					}, {});
					cb(null, {docs: result.Results, stats: stats});
				}
				else {
					cb(error || response.statusCode, null);
				}
			});
		},
		/** Returns Suggestions for given query and fieldName.
		 * @param {string} db
		 * @param {string} index
		 * @param {string} term
		 * @param {string} field
		 * @param {Function} cb
		 */
		suggest: function (db, index, term, field, cb) {
			var url = host +
				'databases/' + db +
				'/suggest/' + index +
				'?term=' + encodeURIComponent(term) +
				'&field=' + field +
				'&max=10&distance=Default&accuracy=0.5';
			request(url, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(body);
					cb(null, result);
				}
				else {
					cb(error || response.statusCode, null);
				}
			});
		},
		/** Returns Facet Results.
		 * @param {string} db
		 * @param {string} indexName
		 * @param {string} facetDoc
		 * @param {string} query
		 * @param {Function} cb
		 */
		facets: function (db, indexName, facetDoc, query, cb) {
			var url = host + "databases/" + db + "/facets/" + indexName + "?facetDoc=" + facetDoc + "&query=" + encodeURIComponent(query);
			request(url, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(body);
					_.each(result.Results, function (v, k) {
						if (_.filter(v.Values,function (x) {
							return x.Hits > 0;
						}).length < 2) {
							delete result.Results[k];
							return;
						}
						v.Values = _.chain(v.Values)
							.map(function (x) {
								var val = JSON.stringify(x.Range)
									.replace(/^\"|\"$/gi, "")
									.replace(/\:/gi, "\\:")
									.replace(/\(/gi, "\\(")
									.replace(/\)/gi, "\\)");
								if (x.Range.indexOf(" TO ") <= 0 || x.Range.indexOf("[") !== 0) {
									val = val.replace(/\ /gi, "\\ ");
								}
								val = encodeURIComponent(val);
								x.q = k + ":" + val;
								x.Range = x.Range
									.replace(/^\[Dx/, "")
									.replace(/ Dx/, " ")
									.replace(/\]$/, "")
									.replace(/ TO /, "-");
								return x;
							}).filter(function (x) {
								return x.Hits > 0;
							}).sortBy(function (x) {
								return x.Range;
							}).value();
					});
					cb(null, result.Results);
				} else
					cb(error || response.statusCode, null);
			});
		},
		/** Generates and returns Dynamic Report.
		 * @param {string} db
		 * @param {string} indexName
		 * @param {string} whereClause
		 * @param {string} groupBy
		 * @param {Array<string>} fieldsToSum
		 * @param {Function} cb
		 */
		dynamicAggregation: function (db, indexName, whereClause, groupBy, fieldsToSum, cb) {
			var url = host + 'databases/' + db + '/facets/' + indexName + '?';
			url += whereClause ? '&query=' + encodeURIComponent(whereClause) : '';
			url += '&facetStart=0&facetPageSize=1024';
			var facets = fieldsToSum
				.map(function (field) {
					return {
						"Mode": 0,
						"Aggregation": 16,
						"AggregationField": field,
						"Name": groupBy,
						"DisplayName": field,
						"Ranges": [],
						"MaxResults": null,
						"TermSortMode": 0,
						"IncludeRemainingTerms": false
					};
				});
			url+= '&facets=' + JSON.stringify(facets);
			request(url, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(body);
					cb(null, result);
				} else {
					cb(error || response.statusCode, null);
				}
			});
		},
		/** Loads document with given id.
		 * @param {string} db
		 * @param {string} id
		 * @param {Function} cb
		 */
		load: function (db, id, cb) {
			var url = host + 'databases/' + db + '/docs/' + id;
			request(url, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var doc = JSON.parse(body);
					var meta = _.reduce(response.headers
						, function (memo, val, key) {
							if (key.startsWith('raven'))
								memo[key] = val;
							return memo;
						}, {});
					meta['@id'] = response.headers['__document_id'];
					meta.etag = response.headers['etag'];
					doc['@metadata'] = meta;
					cb(null, doc);
				} else {
					cb(error || response.statusCode, null);
				}
			});
		},
		/** Overwrites given document with given id.
		 * @param {string} db
		 * @param {string} id
		 * @param {Object} doc
		 * @param {Object} metadata
		 * @param {Function} cb
		 */
		update: function (db, id, doc, metadata, cb) {
			var operations = [
				{
					Method: "PUT",
					Document: doc,
					Metadata: metadata,
					Key: id
				}
			];
			request.post({
				url: host + 'databases/' + db + '/bulk_docs',
				headers: {
					'Content-Type': 'application/json; charset=utf-8'
				},
				body: JSON.stringify(operations)
			}, function (error, response, resBody) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(resBody);
					cb(null, result);
				} else {
					cb(error || response.statusCode, null);
				}
			});
		},
		/** Applies patch operations to document with given id.
		 * @param {string} db
		 * @param {string} id
		 * @param {Array<Object>} operations
		 * @param {Function} cb
		 */
		patch: function (db, id, operations, cb) {
			request.patch({
				url: host + 'databases/' + db + '/docs/' + id,
				headers: {
					'Content-Type': 'application/json; charset=utf-8'
				},
				body: JSON.stringify(operations)
			}, function (error, response, resBody) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(resBody);
					cb(null, result);
				} else {
					cb(error || response.statusCode, null);
				}
			});
		},
		/** Stores given document, returns raven generated id in callback.
		 * @param {string} db
		 * @param {string} entityName
		 * @param {Object} doc
		 * @param {Function} cb
		 */
		store: function (db, entityName, doc, cb) {
			request.post({
				url: host + 'databases/' + db + '/docs',
				headers: {
					'Content-Type': 'application/json; charset=utf-8',
					'Raven-Entity-Name': entityName
				},
				body: JSON.stringify(doc)
			}, function (error, response, resBody) {
				if (!error && response.statusCode === 201) {
					var result = JSON.parse(resBody);
					cb(null, result);
				} else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		}

	}
};<commit_msg>added indexQueryAll, multi_get functionality<commit_after>var request = require('request'),
	_ = require('underscore');

module.exports = function (host) {
	if (host.indexOf('/', host.length - 1) == -1)
		host += '/';
	return {
		/** Queries index and returns results in callback(err,result : object{docs,stats}).
		 * @param {string} db
		 * @param {string} index
		 * @param {string} whereClause
		 * @param {int} start
		 * @param {int} limit
		 * @param {Array<string>} sortBys
		 * @param {Array<string>} fetchings
		 * @param {Function} cb
		 */
		indexQuery: function (db, index, whereClause, start, limit, sortBys, fetchings, cb) {
			if (typeof whereClause === 'function') {
				cb = whereClause;
				whereClause = '';
				start = 0;
				limit = 12;
				sortBys = [];
				fetchings = [];
			}
			if (typeof start === 'function') {
				cb = start;
				start = 0;
				limit = 12;
				sortBys = [];
				fetchings = [];
			}
			if (typeof sortBys === 'function') {
				cb = sortBys;
				sortBys = [];
				fetchings = [];
			}
			if (typeof fetchings === 'function') {
				cb = fetchings;
				fetchings = [];
			}
			var url = host +
				'databases/' + db +
				'/indexes/' + index +
				'?query=' + encodeURIComponent(whereClause) +
				'&operator=AND' +
				'&pageSize=' + limit +
				'&start=' + start;
			var sorts = sortBys.map(function (prop) {
				return '&sort=' + prop;
			}).join('');
			var fetchs = fetchings.map(function (prop) {
				return '&fetch=' + prop;
			}).join('');
			url = url + sorts + fetchs;
			request(url, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(body);
					var stats = _.reduce(result, function (memo, value, key) {
						if (key !== "Results") {
							memo[key] = value;
						}
						return memo;
					}, {});
					cb(null, {docs: result.Results, stats: stats});
				}
				else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		},
		/** Queries index and returns  all indexResults in callback(err,result : object{docs,stats}).
		 * @param {string} db
		 * @param {string} index
		 * @param {string} whereClause
		 * @param {Array<string>} sortBys
		 * @param {Function} cb
		 */
		indexQueryAll: function (db, index, whereClause, sortBys, cb) {
			var query = encodeURIComponent(whereClause)
			var url = host +
				'databases/' + db +
				'/indexes/' + index +
				'?query=' + query +
				'&operator=AND&pageSize=0&start=0';
			url += sortBys.map(function (prop) {
				return '&sort=' + prop;
			}).join('');
			request(url, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(body);
					var pageSize = 1024;
					var stats = _.reduce(result, function (memo, value, key) {
						if (key !== "Results") {
							memo[key] = value;
						}
						return memo;
					}, {});
					var totalResults = stats.TotalResults;
					var pageCount = parseInt(totalResults / pageSize);
					var delta = totalResults - pageCount * pageSize;
					if (delta > 0)
						pageCount++;
					var requests = [];
					for (var i = 0; i < pageCount; i++) {
						requests.push({
							Url: '/indexes/' + index,
							Query: 'start=' + i * pageSize + '&pageSize=' + pageSize + '&query=' + query
						});
					}
					var multiGetBody = JSON.stringify(requests);
					var multiGetUrl = host + 'databases/' + db + '/multi_get';
					request.post({
							url: multiGetUrl,
							body: multiGetBody
						},
						function (err, resp, multiGetResponseBody) {
							if (!err && resp.statusCode === 200) {
								var multiGetResponse = JSON.parse(multiGetResponseBody);
								var results =
									_.flatten(_.reduce(multiGetResponse
										, function (memo, val) {
											if (val.Result && val.Result.Results)
												memo.push(val.Result.Results);
											return memo;
										}
										, []));
								cb(null, results);
							} else {
								cb(err || new Error(resp.statusCode), null);
							}
						});
				}
				else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		},
		/** Returns Suggestions for given query and fieldName.
		 * @param {string} db
		 * @param {string} index
		 * @param {string} term
		 * @param {string} field
		 * @param {Function} cb
		 */
		suggest: function (db, index, term, field, cb) {
			var url = host +
				'databases/' + db +
				'/suggest/' + index +
				'?term=' + encodeURIComponent(term) +
				'&field=' + field +
				'&max=10&distance=Default&accuracy=0.5';
			request(url, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(body);
					cb(null, result);
				}
				else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		},
		/** Returns Facet Results.
		 * @param {string} db
		 * @param {string} indexName
		 * @param {string} facetDoc
		 * @param {string} query
		 * @param {Function} cb
		 */
		facets: function (db, indexName, facetDoc, query, cb) {
			var url = host + "databases/" + db + "/facets/" + indexName + "?facetDoc=" + facetDoc + "&query=" + encodeURIComponent(query);
			request(url, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(body);
					_.each(result.Results, function (v, k) {
						if (_.filter(v.Values,function (x) {
							return x.Hits > 0;
						}).length < 2) {
							delete result.Results[k];
							return;
						}
						v.Values = _.chain(v.Values)
							.map(function (x) {
								var val = JSON.stringify(x.Range)
									.replace(/^\"|\"$/gi, "")
									.replace(/\:/gi, "\\:")
									.replace(/\(/gi, "\\(")
									.replace(/\)/gi, "\\)");
								if (x.Range.indexOf(" TO ") <= 0 || x.Range.indexOf("[") !== 0) {
									val = val.replace(/\ /gi, "\\ ");
								}
								val = encodeURIComponent(val);
								x.q = k + ":" + val;
								x.Range = x.Range
									.replace(/^\[Dx/, "")
									.replace(/ Dx/, " ")
									.replace(/\]$/, "")
									.replace(/ TO /, "-");
								return x;
							}).filter(function (x) {
								return x.Hits > 0;
							}).sortBy(function (x) {
								return x.Range;
							}).value();
					});
					cb(null, result.Results);
				} else
					cb(error || new Error(response.statusCode), null);
			});
		},
		/** Generates and returns Dynamic Report.
		 * @param {string} db
		 * @param {string} indexName
		 * @param {string} whereClause
		 * @param {string} groupBy
		 * @param {Array<string>} fieldsToSum
		 * @param {Function} cb
		 */
		dynamicAggregation: function (db, indexName, whereClause, groupBy, fieldsToSum, cb) {
			var url = host + 'databases/' + db + '/facets/' + indexName + '?';
			url += whereClause ? '&query=' + encodeURIComponent(whereClause) : '';
			url += '&facetStart=0&facetPageSize=1024';
			var facets = fieldsToSum
				.map(function (field) {
					return {
						"Mode": 0,
						"Aggregation": 16,
						"AggregationField": field,
						"Name": groupBy,
						"DisplayName": field,
						"Ranges": [],
						"MaxResults": null,
						"TermSortMode": 0,
						"IncludeRemainingTerms": false
					};
				});
			url += '&facets=' + JSON.stringify(facets);
			request(url, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(body);
					cb(null, result);
				} else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		},
		/** Loads document with given id.
		 * @param {string} db
		 * @param {string} id
		 * @param {Function} cb
		 */
		load: function (db, id, cb) {
			var url = host + 'databases/' + db + '/docs/' + id;
			request(url, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var doc = JSON.parse(body);
					var meta = _.reduce(response.headers
						, function (memo, val, key) {
							if (key.startsWith('raven'))
								memo[key] = val;
							return memo;
						}, {});
					meta['@id'] = response.headers['__document_id'];
					meta.etag = response.headers['etag'];
					doc['@metadata'] = meta;
					cb(null, doc);
				} else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		},
		/** Overwrites given document with given id.
		 * @param {string} db
		 * @param {string} id
		 * @param {Object} doc
		 * @param {Object} metadata
		 * @param {Function} cb
		 */
		update: function (db, id, doc, metadata, cb) {
			var operations = [
				{
					Method: "PUT",
					Document: doc,
					Metadata: metadata,
					Key: id
				}
			];
			request.post({
				url: host + 'databases/' + db + '/bulk_docs',
				headers: {
					'Content-Type': 'application/json; charset=utf-8'
				},
				body: JSON.stringify(operations)
			}, function (error, response, resBody) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(resBody);
					cb(null, result);
				} else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		},
		/** Applies patch operations to document with given id.
		 * @param {string} db
		 * @param {string} id
		 * @param {Array<Object>} operations
		 * @param {Function} cb
		 */
		patch: function (db, id, operations, cb) {
			request.patch({
				url: host + 'databases/' + db + '/docs/' + id,
				headers: {
					'Content-Type': 'application/json; charset=utf-8'
				},
				body: JSON.stringify(operations)
			}, function (error, response, resBody) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(resBody);
					cb(null, result);
				} else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		},
		/** Stores given document, returns raven generated id in callback.
		 * @param {string} db
		 * @param {string} entityName
		 * @param {Object} doc
		 * @param {Function} cb
		 */
		store: function (db, entityName, doc, cb) {
			request.post({
				url: host + 'databases/' + db + '/docs',
				headers: {
					'Content-Type': 'application/json; charset=utf-8',
					'Raven-Entity-Name': entityName
				},
				body: JSON.stringify(doc)
			}, function (error, response, resBody) {
				if (!error && response.statusCode === 201) {
					var result = JSON.parse(resBody);
					cb(null, result);
				} else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		}

	}
};<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var publicDir = hexo.public_dir;
var sourceDir = hexo.source_dir;
var htmlTag = hexo.util.html_tag;
var log = hexo.log;
var route = hexo.route;

hexo.extend.generator.register(function(locals, render, callback){
  //check images folder exists
  var srcdir = sourceDir + '_images' + path.sep;
  var tardir = publicDir + 'images' + path.sep;
  fs.exists(srcdir,function(exists){
    if (exists) {
      fs.readdir(srcdir,function(err,files){
        files.forEach(function(file){
          var cb = function(fn){
            if (!fs.existsSync(tardir)){
              fs.mkdirSync(tardir);
            }
            fn(null,fs.createReadStream(srcdir + file));
          };
          cb.modified = true;
          route.set('images' + path.sep + file,cb);
        });
        callback();
      });
    } else {
      log.log(1);
      callback();
    }
  });
});

var localImage = function(args,content){
  var imageName = args[0]; //images name
  var classes = args[1] || "";
  var imgAttr = args[2] || "{}";
  classes = classes.split(',');
  imgAttr = JSON.parse(imgAttr);

  imgAttr.src   = hexo.config.root + 'images/' + imageName;
  imgAttr.class = classes.join(' ');

  return htmlTag('img', imgAttr);
};

hexo.extend.tag.register('limg',localImage);
hexo.extend.tag.register('limage',localImage);<commit_msg>delete log<commit_after>var fs = require('fs');
var path = require('path');
var publicDir = hexo.public_dir;
var sourceDir = hexo.source_dir;
var htmlTag = hexo.util.html_tag;
var route = hexo.route;

hexo.extend.generator.register(function(locals, render, callback){
  //check images folder exists
  var srcdir = sourceDir + '_images' + path.sep;
  var tardir = publicDir + 'images' + path.sep;
  fs.exists(srcdir,function(exists){
    if (exists) {
      fs.readdir(srcdir,function(err,files){
        files.forEach(function(file){
          var cb = function(fn){
            if (!fs.existsSync(tardir)){
              fs.mkdirSync(tardir);
            }
            fn(null,fs.createReadStream(srcdir + file));
          };
          cb.modified = true;
          route.set('images' + path.sep + file,cb);
        });
        callback();
      });
    } else {
      callback();
    }
  });
});

var localImage = function(args,content){
  var imageName = args[0]; //images name
  var classes = args[1] || "";
  var imgAttr = args[2] || "{}";
  classes = classes.split(',');
  imgAttr = JSON.parse(imgAttr);

  imgAttr.src   = hexo.config.root + 'images/' + imageName;
  imgAttr.class = classes.join(' ');

  return htmlTag('img', imgAttr);
};

hexo.extend.tag.register('limg',localImage);
hexo.extend.tag.register('limage',localImage);<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');

const MetaPlaceholder = '__ember-cli-ifa__AssetMapPlaceholder__';

function replacePlaceholder(filePath, assetMap) {
  const assetMapString = assetMap ? encodeURIComponent(JSON.stringify(assetMap)) : '';
  const fileBody = fs.readFileSync(filePath, { encoding: 'utf-8' });
  fs.writeFileSync(filePath, fileBody.replace(MetaPlaceholder, assetMapString));
}

module.exports = {
  name: 'ember-cli-ifa',

  isDevelopingAddon() {
    return false;
  },

  treeForFastBoot(tree) {
    this._isFastBoot = true;

    if (this.project !== this.parent) {
      this.ui.writeLine(
        'ember-cli-ifa currently only supports being a top-level dependency! If you are seeing this message please open an issue on https://github.com/RuslanZavacky/ember-cli-ifa/issues'
      );
    }

    return tree;
  },

  contentFor(type) {
    if (type !== 'head') {
      return;
    }

    if (!this._config().enabled) {
      return '<meta name="ember-cli-ifa:assetMap">';
    }

    return `<meta name="ember-cli-ifa:assetMap" content="${MetaPlaceholder}">`;
  },

  /**
   * By default, during runtime the asset-map service reads the asset map
   * information from a meta tag on the index.html. As we do not have access to
   * global `document` when running in fastboot, we need to implement a
   * different way to access this asset-map information. See
   * `get-asset-map-data` where we require the `asset-map` module taht is
   * generated in the postBuild() below.
   */
  updateFastBootManifest(manifest) {
    manifest.vendorFiles.push('assets/assetMap.js');

    return manifest;
  },

  postBuild(build) {
    this._super.included.apply(this, arguments);

    const ifaConfig = this._config();

    if (!ifaConfig.enabled) {
      return;
    }

    let fingerprintPrepend = '/';

    const files = fs.readdirSync(path.join(build.directory, 'assets'));
    const totalFiles = files.length;

    let assetFileName = null;
    for (let i = 0; i < totalFiles; i++) {
      if (files[i].match(/^assetMap/i)) {
        assetFileName = files[i];
        break;
      }
    }

    // Prepend the URL of the assetMap with the location defined in fingerprint
    // options.
    if (this.app && this.app.options && this.app.options.fingerprint) {
      fingerprintPrepend = this.app.options.fingerprint.prepend;
    }

    const assetFileNamePath = `${build.directory}/assets/${assetFileName}`;

    // When using fastboot, always use the inline form
    // As ajax is not so easily possible there
    if (!ifaConfig.inline && this._isFastBoot) {
      this.ui.writeLine('When running fastboot, ember-cli-ifa is forced into inline mode.');
    }
    const inline = ifaConfig.inline || this._isFastBoot;

    let assetMap;
    if (inline && fs.existsSync(assetFileNamePath)) {
      let assetMapContent = fs.readFileSync(assetFileNamePath, { encoding: 'utf-8' });
      assetMap = JSON.parse(assetMapContent);

      if (this._isFastBoot) {
        const assetModulePath = assetFileNamePath.replace(/\.json$/, '.js');

        fs.writeFileSync(
          assetModulePath,
          `define('ember-cli-ifa/fastboot-asset-map', [], function () {
          return {
            'default': ${assetMapContent},
            __esModule: true,
          };
        });`
        );
      }
    } else if (assetFileName) {
      assetMap = `${fingerprintPrepend}assets/${assetFileName}`;
    }

    replacePlaceholder(path.join(build.directory, 'index.html'), assetMap);

    let testIndexPath = path.join(build.directory, 'tests/index.html');
    if (fs.existsSync(testIndexPath)) {
      replacePlaceholder(testIndexPath, assetMap);
    }
  },

  _config() {
    const env = process.env.EMBER_ENV;
    return this.project.config(env).ifa;
  },
};
<commit_msg>Fix typos to trigger build<commit_after>'use strict';

const fs = require('fs');
const path = require('path');

const MetaPlaceholder = '__ember-cli-ifa__AssetMapPlaceholder__';

function replacePlaceholder(filePath, assetMap) {
  const assetMapString = assetMap ? encodeURIComponent(JSON.stringify(assetMap)) : '';
  const fileBody = fs.readFileSync(filePath, { encoding: 'utf-8' });
  fs.writeFileSync(filePath, fileBody.replace(MetaPlaceholder, assetMapString));
}

module.exports = {
  name: 'ember-cli-ifa',

  isDevelopingAddon() {
    return false;
  },

  treeForFastBoot(tree) {
    this._isFastBoot = true;

    if (this.project !== this.parent) {
      this.ui.writeLine(
        'ember-cli-ifa currently only supports being a top-level dependency! If you are seeing this message please open an issue on https://github.com/RuslanZavacky/ember-cli-ifa/issues'
      );
    }

    return tree;
  },

  contentFor(type) {
    if (type !== 'head') {
      return;
    }

    if (!this._config().enabled) {
      return '<meta name="ember-cli-ifa:assetMap">';
    }

    return `<meta name="ember-cli-ifa:assetMap" content="${MetaPlaceholder}">`;
  },

  /**
   * By default, during runtime, the asset-map service reads the asset map
   * information from a meta tag on the index.html. As we do not have access to
   * global `document` when running in fastboot, we need to implement a
   * different way to access this asset-map information. See
   * `get-asset-map-data` where we require the `asset-map` module that is
   * generated in the postBuild() below.
   */
  updateFastBootManifest(manifest) {
    manifest.vendorFiles.push('assets/assetMap.js');

    return manifest;
  },

  postBuild(build) {
    this._super.included.apply(this, arguments);

    const ifaConfig = this._config();

    if (!ifaConfig.enabled) {
      return;
    }

    let fingerprintPrepend = '/';

    const files = fs.readdirSync(path.join(build.directory, 'assets'));
    const totalFiles = files.length;

    let assetFileName = null;
    for (let i = 0; i < totalFiles; i++) {
      if (files[i].match(/^assetMap/i)) {
        assetFileName = files[i];
        break;
      }
    }

    // Prepend the URL of the assetMap with the location defined in fingerprint
    // options.
    if (this.app && this.app.options && this.app.options.fingerprint) {
      fingerprintPrepend = this.app.options.fingerprint.prepend;
    }

    const assetFileNamePath = `${build.directory}/assets/${assetFileName}`;

    // When using fastboot, always use the inline form
    // As ajax is not so easily possible there
    if (!ifaConfig.inline && this._isFastBoot) {
      this.ui.writeLine('When running fastboot, ember-cli-ifa is forced into inline mode.');
    }
    const inline = ifaConfig.inline || this._isFastBoot;

    let assetMap;
    if (inline && fs.existsSync(assetFileNamePath)) {
      let assetMapContent = fs.readFileSync(assetFileNamePath, { encoding: 'utf-8' });
      assetMap = JSON.parse(assetMapContent);

      if (this._isFastBoot) {
        const assetModulePath = assetFileNamePath.replace(/\.json$/, '.js');

        fs.writeFileSync(
          assetModulePath,
          `define('ember-cli-ifa/fastboot-asset-map', [], function () {
          return {
            'default': ${assetMapContent},
            __esModule: true,
          };
        });`
        );
      }
    } else if (assetFileName) {
      assetMap = `${fingerprintPrepend}assets/${assetFileName}`;
    }

    replacePlaceholder(path.join(build.directory, 'index.html'), assetMap);

    let testIndexPath = path.join(build.directory, 'tests/index.html');
    if (fs.existsSync(testIndexPath)) {
      replacePlaceholder(testIndexPath, assetMap);
    }
  },

  _config() {
    const env = process.env.EMBER_ENV;
    return this.project.config(env).ifa;
  },
};
<|endoftext|>


<commit_before>enterUrlMsg = "Drag-and-drop the video or paste its URL here...";

removeImgSrc = "//cdn.rawgit.com/iconic/open-iconic/master/png/x-4x.png";
pauseImgSrc = "//cdn.rawgit.com/iconic/open-iconic/master/png/media-pause-4x.png";
playImgSrc = "//cdn.rawgit.com/iconic/open-iconic/master/png/media-play-4x.png";

var videoUrl;
var videoName;
var videoTime = null;

var videos = [];
var videoCounter = 0;
var videoIteration = 0;
var videoPaused;
var timer;

function Timer(callback, delay) {
  var timerId, start, remaining = delay;

  this.pause = function() {
      window.clearTimeout(timerId);
      remaining -= new Date() - start;
  };

  this.resume = function() {
      start = new Date();
      window.clearTimeout(timerId);
      timerId = window.setTimeout(callback, remaining);
  };

  this.resume();
}

function msConversion(millis) {
  var minutes = Math.floor(millis / 60000);
  var seconds = ((millis % 60000) / 1000).toFixed(0);
  return minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}

function highlight(i) {
  $("tr:nth-child(" + i + ")").attr("id", "newSelected");
  $("tr.selected").removeClass("selected");
  $("#newSelected").addClass("selected");
  $("#newSelected").removeAttr("id");
}

function addVideoToList(name, time) {
  $("#videosTable").append("
" + name + "<button class=\"tableButton\" onclick=\"removeVideo(this);\"></button>	" + time + "
");
}

function playVideo() {
  highlight(videoIteration);
  document.title = "Streamly - " + videos[videoIteration]["name"];

  var embedUrl = videos[videoIteration]["url"].replace("/watch?v=", "/embed/") + "?autoplay=1";
  $("#youtube").attr("src", embedUrl);
  $("#pauseImg").attr("src", pauseImgSrc);
}

function loopVideo() {
  videoIteration++;
  playVideo();
  timer = new Timer(function() {
    if (videoIteration < videoCounter) {
      loopVideo();
    }
    else {
      timer.pause();
      timer = 0;
      $("#youtube").attr("src", "");
      document.title = "Streamly";
    }
  }, videos[videoIteration]["time"] + 2000);
}

function pauseVideo() {
  if (!videoPaused) {
    timer.pause();
    $("#pauseImg").attr("src", playImgSrc);
    videoPaused = true;
  }
  else {
    timer.resume();
    $("#pauseImg").attr("src", pauseImgSrc);
    videoPaused = false;
  }
}

function backVideo() {
  if (videoIteration - 2 > -1) {
    videoIteration = videoIteration - 2;
    if (timer != 0) {
      timer.pause();
    }
    timer = 0;
    loopVideo();
  }
}

function forwardVideo() {
  if (videoIteration + 1 <= videoCounter) {
    if (timer != 0) {
      timer.pause();
    }
    timer = 0;
    loopVideo();
  }
}

function setPlaylist() {
  if (videos.length > 1) {
    var playlist = JSON.stringify(videos);
    playlist = window.btoa(playlist);
    playlist = encodeURIComponent(playlist);
    window.location.hash = playlist;
  }
  else {
    window.location.hash = "";
  }
}

function getPlaylist() {
  if (window.location.hash.substr(1) !== "") {
    var playlist = window.location.hash.substr(1);
    playlist = decodeURIComponent(playlist);
    playlist = window.atob(playlist);
    playlist = JSON.parse(playlist);
    videos = playlist;

    for (i = 1; i < videos.length; i++) {
      videoCounter = i;
      var printTime = msConversion(videos[videoCounter]["time"]);
      addVideoToList(videos[videoCounter]["name"], printTime);
    }
    loopVideo();
  }
}

function getVideoData() {
  $.ajax({
    url: videoUrl,
    type: 'GET',
    success: function(res) {
      var data = $(res.responseText);
      try {
        videoName = data.find("span#eow-title");
        videoName = videoName[0].textContent;
        videoName = videoName.trim();
      } catch(err) {
        videoName = prompt("Please enter the name of the video", "");
      }
      try {
        videoTime = null;
        for (iteration in data) {
          var str = data[iteration].innerHTML;
          if (videoTime == null && typeof str != "undefined") {
            videoTime = str.match(/,"length_seconds":"\d+",/g);
          }
        }
        videoTime = videoTime[0];
        videoTime = videoTime.replace(/,"length_seconds":"/g, "").replace(/",/g, "");
        videoTime = +videoTime * 1000;
      } catch(err) {
        videoTime = prompt("Please enter the length of the video", "3:00");
        videoTime = videoTime.split(":");
        videoTime = (+videoTime[0]) * 60 + (+videoTime[1]);
        videoTime = videoTime * 1000;
      }
    }
  });
}

function addVideo() {
  videoCounter++;
  var video = {};
  video["name"] = videoName;
  video["time"] = videoTime;
  video["url"] = videoUrl;
  videos[videoCounter] = video;

  var printTime = msConversion(videos[videoCounter]["time"]);

  addVideoToList(videoName, printTime);

  setPlaylist();

  if (videoCounter == 1 || timer == 0) {
    loopVideo();
  }
}

function removeVideo(element) {
  var index = $(".tableButton").index(element) + 1;
  if (index == videoIteration) {
    forwardVideo();
  }
  videoCounter--;
  videos.splice(index, 1);
  $("tr:nth-child(" + index + ")").remove();
  setPlaylist();
}

function input() {
  switch ($("#inputBox").attr("placeholder")) {
    case enterUrlMsg:
      if ($("#inputBox").val() != "") {
        videoUrl = $("#inputBox").val();
        videoUrl = videoUrl.trim();
        $("#inputBox").val("").attr("placeholder", "Loading video data from YouTube...");
        getVideoData();
      }
      else {
        window.open("https://www.youtube.com");
      }
      break;
  }
}

$(document).ajaxStop(function() {
  $("#inputBox").val("").attr("placeholder", enterUrlMsg);
  addVideo();
});

function onDrop(event) {
  var data = event.dataTransfer.getData("URL");
  event.target.textContent = data;
  $("#inputBox").val(data);
  input();
  event.preventDefault();
}
<commit_msg>added provisions for deleting last video<commit_after>enterUrlMsg = "Drag-and-drop the video or paste its URL here...";

removeImgSrc = "//cdn.rawgit.com/iconic/open-iconic/master/png/x-4x.png";
pauseImgSrc = "//cdn.rawgit.com/iconic/open-iconic/master/png/media-pause-4x.png";
playImgSrc = "//cdn.rawgit.com/iconic/open-iconic/master/png/media-play-4x.png";

var videoUrl;
var videoName;
var videoTime = null;

var videos = [];
var videoCounter = 0;
var videoIteration = 0;
var videoPaused;
var timer;

function Timer(callback, delay) {
  var timerId, start, remaining = delay;

  this.pause = function() {
      window.clearTimeout(timerId);
      remaining -= new Date() - start;
  };

  this.resume = function() {
      start = new Date();
      window.clearTimeout(timerId);
      timerId = window.setTimeout(callback, remaining);
  };

  this.resume();
}

function msConversion(millis) {
  var minutes = Math.floor(millis / 60000);
  var seconds = ((millis % 60000) / 1000).toFixed(0);
  return minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}

function highlight(i) {
  $("tr:nth-child(" + i + ")").attr("id", "newSelected");
  $("tr.selected").removeClass("selected");
  $("#newSelected").addClass("selected");
  $("#newSelected").removeAttr("id");
}

function addVideoToList(name, time) {
  $("#videosTable").append("
" + name + "<button class=\"tableButton\" onclick=\"removeVideo(this);\"></button>	" + time + "
");
}

function playVideo() {
  highlight(videoIteration);
  document.title = "Streamly - " + videos[videoIteration]["name"];

  var embedUrl = videos[videoIteration]["url"].replace("/watch?v=", "/embed/") + "?autoplay=1";
  $("#youtube").attr("src", embedUrl);
  $("#pauseImg").attr("src", pauseImgSrc);
}

function loopVideo() {
  videoIteration++;
  playVideo();
  timer = new Timer(function() {
    if (videoIteration < videoCounter) {
      loopVideo();
    }
    else {
      timer.pause();
      timer = 0;
      $("#youtube").attr("src", "");
      document.title = "Streamly";
    }
  }, videos[videoIteration]["time"] + 2000);
}

function pauseVideo() {
  if (!videoPaused) {
    timer.pause();
    $("#pauseImg").attr("src", playImgSrc);
    videoPaused = true;
  }
  else {
    timer.resume();
    $("#pauseImg").attr("src", pauseImgSrc);
    videoPaused = false;
  }
}

function backVideo() {
  if (videoIteration - 2 > -1) {
    videoIteration = videoIteration - 2;
    if (timer != 0) {
      timer.pause();
    }
    timer = 0;
    loopVideo();
  }
}

function forwardVideo() {
  if (videoIteration + 1 <= videoCounter) {
    if (timer != 0) {
      timer.pause();
    }
    timer = 0;
    loopVideo();
  }
}

function setPlaylist() {
  if (videos.length > 1) {
    var playlist = JSON.stringify(videos);
    playlist = window.btoa(playlist);
    playlist = encodeURIComponent(playlist);
    window.location.hash = playlist;
  }
  else {
    window.location.hash = "";
  }
}

function getPlaylist() {
  if (window.location.hash.substr(1) !== "") {
    var playlist = window.location.hash.substr(1);
    playlist = decodeURIComponent(playlist);
    playlist = window.atob(playlist);
    playlist = JSON.parse(playlist);
    videos = playlist;

    for (i = 1; i < videos.length; i++) {
      videoCounter = i;
      var printTime = msConversion(videos[videoCounter]["time"]);
      addVideoToList(videos[videoCounter]["name"], printTime);
    }
    loopVideo();
  }
}

function getVideoData() {
  $.ajax({
    url: videoUrl,
    type: 'GET',
    success: function(res) {
      var data = $(res.responseText);
      try {
        videoName = data.find("span#eow-title");
        videoName = videoName[0].textContent;
        videoName = videoName.trim();
      } catch(err) {
        videoName = prompt("Please enter the name of the video", "");
      }
      try {
        videoTime = null;
        for (iteration in data) {
          var str = data[iteration].innerHTML;
          if (videoTime == null && typeof str != "undefined") {
            videoTime = str.match(/,"length_seconds":"\d+",/g);
          }
        }
        videoTime = videoTime[0];
        videoTime = videoTime.replace(/,"length_seconds":"/g, "").replace(/",/g, "");
        videoTime = +videoTime * 1000;
      } catch(err) {
        videoTime = prompt("Please enter the length of the video", "3:00");
        videoTime = videoTime.split(":");
        videoTime = (+videoTime[0]) * 60 + (+videoTime[1]);
        videoTime = videoTime * 1000;
      }
    }
  });
}

function addVideo() {
  videoCounter++;
  var video = {};
  video["name"] = videoName;
  video["time"] = videoTime;
  video["url"] = videoUrl;
  videos[videoCounter] = video;

  var printTime = msConversion(videos[videoCounter]["time"]);

  addVideoToList(videoName, printTime);

  setPlaylist();

  if (videoCounter == 1 || timer == 0) {
    loopVideo();
  }
}

function removeVideo(element) {
  var index = $(".tableButton").index(element) + 1;
  if (index == videoIteration) {
    if (videoIteration + 1 <= videoCounter) {
      forwardVideo();
    }
    else {
      if (timer != 0) {
        timer.pause();
      }
      timer = 0;
      $("#youtube").attr("src", "");
      document.title = "Streamly";
    }
  }
  videoCounter--;
  videos.splice(index, 1);
  $("tr:nth-child(" + index + ")").remove();
  setPlaylist();
}

function input() {
  switch ($("#inputBox").attr("placeholder")) {
    case enterUrlMsg:
      if ($("#inputBox").val() != "") {
        videoUrl = $("#inputBox").val();
        videoUrl = videoUrl.trim();
        $("#inputBox").val("").attr("placeholder", "Loading video data from YouTube...");
        getVideoData();
      }
      else {
        window.open("https://www.youtube.com");
      }
      break;
  }
}

$(document).ajaxStop(function() {
  $("#inputBox").val("").attr("placeholder", enterUrlMsg);
  addVideo();
});

function onDrop(event) {
  var data = event.dataTransfer.getData("URL");
  event.target.textContent = data;
  $("#inputBox").val(data);
  input();
  event.preventDefault();
}
<|endoftext|>


<commit_before>'use strict';

var Parser = require('htmlparser2/lib/Parser');

/**
 * @see https://github.com/fb55/htmlparser2/wiki/Parser-options
 */
var defaultOptions = {lowerCaseTags: false, lowerCaseAttributeNames: false};

var defaultDirectives = [{name: '!doctype', start: '<', end: '>'}];

/**
 * Parse html to PostHTMLTree
 * @param  {String} html
 * @param  {Object} [options=defaultOptions]
 * @return {PostHTMLTree}
 */
function postHTMLParser(html, options) {
    var bufArray = [],
        results = [];

    bufArray.last = function() {
        return this[this.length - 1];
    };

    function isDirective(directive, tag) {
        if (directive.name instanceof RegExp) {
            var regex = RegExp(directive.name.source, 'i');

            return regex.test(tag);
        }

        if (tag !== directive.name) {
            return false;
        }

        return true;
    }

    function parserDirective(name, data) {
        var directives = [].concat(defaultDirectives, options.directives || []);
        var last = bufArray.last();

        for (var i = 0; i < directives.length; i++) {
            var directive = directives[i];
            var directiveText = directive.start + data + directive.end;

            name = name.toLowerCase();
            if (isDirective(directive, name)) {
                if (!last) {
                    results.push(directiveText);
                    return;
                }

                last.content || (last.content = []);
                last.content.push(directiveText);
            }
        }
    }

    function normalizeArributes(attrs) {
        var result = {};
        Object.keys(attrs).forEach(function(key) {
            var obj = {};
                obj[key] = attrs[key].replace(/"/g, '"');
            Object.assign(result, obj);
        });

        return result;
    }

    var parser = new Parser({
        onprocessinginstruction: parserDirective,
        oncomment: function(data) {
            var comment = '<!--' + data + '-->',
                last = bufArray.last();

            if (!last) {
                results.push(comment);
                return;
            }

            last.content || (last.content = []);
            last.content.push(comment);
        },
        onopentag: function(tag, attrs) {
            var buf = { tag: tag };

            if (Object.keys(attrs).length) {
                buf.attrs = normalizeArributes(attrs);
            }

            bufArray.push(buf);
        },
        onclosetag: function() {
            var buf = bufArray.pop();

            if (!bufArray.length) {
                results.push(buf);
                return;
            }

            var last = bufArray.last();
            if (!Array.isArray(last.content)) {
                last.content = [];
            }

            last.content.push(buf);
        },
        ontext: function(text) {
            var last = bufArray.last();
            if (!last) {
                results.push(text);
                return;
            }

            last.content || (last.content = []);
            last.content.push(text);
        }
    }, options || defaultOptions);

    parser.write(html);
    parser.end();

    return results;
}

function parserWrapper() {
    var option;

    function parser(html) {
        var opt = Object.assign(defaultOptions, option);
        return postHTMLParser(html, opt);
    }

    if (
      arguments.length === 1 &&
      Boolean(arguments[0]) &&
      arguments[0].constructor.name === 'Object'
    ) {
        option = arguments[0];
        return parser;
    }

    option = arguments[1];
    return parser(arguments[0]);
}

module.exports = parserWrapper;
module.exports.defaultOptions = defaultOptions;
module.exports.defaultDirectives = defaultDirectives;
<commit_msg>fix: incorrect merge defaultOptions, close #47<commit_after>'use strict';

var Parser = require('htmlparser2/lib/Parser');

/**
 * @see https://github.com/fb55/htmlparser2/wiki/Parser-options
 */
var defaultOptions = {lowerCaseTags: false, lowerCaseAttributeNames: false};

var defaultDirectives = [{name: '!doctype', start: '<', end: '>'}];

/**
 * Parse html to PostHTMLTree
 * @param  {String} html
 * @param  {Object} [options=defaultOptions]
 * @return {PostHTMLTree}
 */
function postHTMLParser(html, options) {
    var bufArray = [],
        results = [];

    bufArray.last = function() {
        return this[this.length - 1];
    };

    function isDirective(directive, tag) {
        if (directive.name instanceof RegExp) {
            var regex = RegExp(directive.name.source, 'i');

            return regex.test(tag);
        }

        if (tag !== directive.name) {
            return false;
        }

        return true;
    }

    function parserDirective(name, data) {
        var directives = [].concat(defaultDirectives, options.directives || []);
        var last = bufArray.last();

        for (var i = 0; i < directives.length; i++) {
            var directive = directives[i];
            var directiveText = directive.start + data + directive.end;

            name = name.toLowerCase();
            if (isDirective(directive, name)) {
                if (!last) {
                    results.push(directiveText);
                    return;
                }

                last.content || (last.content = []);
                last.content.push(directiveText);
            }
        }
    }

    function normalizeArributes(attrs) {
        var result = {};
        Object.keys(attrs).forEach(function(key) {
            var obj = {};
                obj[key] = attrs[key].replace(/"/g, '"');
            Object.assign(result, obj);
        });

        return result;
    }

    var parser = new Parser({
        onprocessinginstruction: parserDirective,
        oncomment: function(data) {
            var comment = '<!--' + data + '-->',
                last = bufArray.last();

            if (!last) {
                results.push(comment);
                return;
            }

            last.content || (last.content = []);
            last.content.push(comment);
        },
        onopentag: function(tag, attrs) {
            var buf = { tag: tag };

            if (Object.keys(attrs).length) {
                buf.attrs = normalizeArributes(attrs);
            }

            bufArray.push(buf);
        },
        onclosetag: function() {
            var buf = bufArray.pop();

            if (!bufArray.length) {
                results.push(buf);
                return;
            }

            var last = bufArray.last();
            if (!Array.isArray(last.content)) {
                last.content = [];
            }

            last.content.push(buf);
        },
        ontext: function(text) {
            var last = bufArray.last();
            if (!last) {
                results.push(text);
                return;
            }

            last.content || (last.content = []);
            last.content.push(text);
        }
    }, options || defaultOptions);

    parser.write(html);
    parser.end();

    return results;
}

function parserWrapper() {
    var option;

    function parser(html) {
        var opt = Object.assign({}, defaultOptions, option);
        return postHTMLParser(html, opt);
    }

    if (
      arguments.length === 1 &&
      Boolean(arguments[0]) &&
      arguments[0].constructor.name === 'Object'
    ) {
        option = arguments[0];
        return parser;
    }

    option = arguments[1];
    return parser(arguments[0]);
}

module.exports = parserWrapper;
module.exports.defaultOptions = defaultOptions;
module.exports.defaultDirectives = defaultDirectives;
<|endoftext|>


<commit_before>var processValue = require('./lib/util/valueProcessor');
var piGlowInterface = require('./lib/interface');
var PiGlowBackend = require('./lib/PiGlowBackend');
var PiGlowBackendMock = require('./lib/PiGlowBackendMock');
var animation = require('./lib/animations');

function createPiGlow(callback) {
    var myPiGlow = new PiGlowBackend();
    var myInterface = piGlowInterface(myPiGlow);

    myPiGlow
        .on('initialize', function() {
            callback(null, myInterface);
        })
        .on('error', function(error) {
            callback(error, null);
        });
}

createPiGlow.BackendMock = PiGlowBackendMock;
createPiGlow.Backend = PiGlowBackend;
createPiGlow.piGlowInterface = piGlowInterface;
createPiGlow.processValue = processValue;
createPiGlow.animation = animation;

module.exports = createPiGlow;<commit_msg>comment<commit_after>var processValue = require('./lib/util/valueProcessor');
var piGlowInterface = require('./lib/interface');
var PiGlowBackend = require('./lib/PiGlowBackend');
var PiGlowBackendMock = require('./lib/PiGlowBackendMock');
var animation = require('./lib/animations');

/**
 * convenience constructor function
*/
function createPiGlow(callback) {
    var myPiGlow = new PiGlowBackend();
    var myInterface = piGlowInterface(myPiGlow);

    myPiGlow
        .on('initialize', function() {
            callback(null, myInterface);
        })
        .on('error', function(error) {
            callback(error, null);
        });
}

createPiGlow.BackendMock = PiGlowBackendMock;
createPiGlow.Backend = PiGlowBackend;
createPiGlow.piGlowInterface = piGlowInterface;
createPiGlow.processValue = processValue;
createPiGlow.animation = animation;

module.exports = createPiGlow;
<|endoftext|>


<commit_before>const Github = require('github')
const express = require('express')
const bodyParser = require('body-parser')

// Setup express app
const app = express()
app.use(bodyParser.json())

// Setup github api client
const github = new GitHubApi()
github.authenticate({
  type: "token",
  token: process.env.GH_TOKEN
});

app.post('/commit', function (req, res, next) {
  const payload = Object.freeze(req.body)
  const repository = payload.repository

  github.repos.getContent({
    owner: repository.owner.login,
    repo: repository.name,
    path: 'package.json'
  }, function (err, pkg) {
    if (err) {
      return next(err)
    }

    console.log(JSON.stringify(pkg, null, 4))
    res.status(202).json({})
  })
})

app.listen(process.env.PORT || 3000)<commit_msg>heroku deploy<commit_after>const Github = require('github')
const express = require('express')
const bodyParser = require('body-parser')

// Setup express app
const app = express()
app.use(bodyParser.json())

// Setup github api client
const github = new Github()
github.authenticate({
  type: "token",
  token: process.env.GH_TOKEN
});

app.post('/commit', function (req, res, next) {
  const payload = Object.freeze(req.body)
  const repository = payload.repository

  github.repos.getContent({
    owner: repository.owner.login,
    repo: repository.name,
    path: 'package.json'
  }, function (err, pkg) {
    if (err) {
      return next(err)
    }

    console.log(JSON.stringify(pkg, null, 4))
    res.status(202).json({})
  })
})

app.listen(process.env.PORT || 3000)<|endoftext|>


<commit_before>// //escape parenthesis to counter invalid RegExp
// // break sections into divs
// //  remove blank option from filtered menu
// // finesse autocomplete
// // tab trigger to autocomplete
// // return focus to input to be able to send w/ a
// // toggle clears input
//
var save_image_url = 'https://c1.staticflickr.com/3/2900/33745640515_a90c44b434_t.jpg';
// var content_image_url = 'https://c1.staticflickr.com/4/3943/33793771665_e25336d636_t.jpg';
var remove_image_url = 'https://c1.staticflickr.com/4/3684/33135618604_414134ce5c_t.jpg';
var contentCollection = ['hi', 'sup', 'fruit'];
// var filteredList = [];
//
  window.onload = function(){
    buildExtensionField();
    buildContentActions();
    loadContent();
  }

  function loadContent() {
    getMenuElement();
    populateDropDownMenu();
  }

  function buildExtensionField() {
    var expertSection = document.getElementsByClassName('module__foot')[0];
    var newSection = document.createElement('div');
    newSection.setAttribute('class', 'content-filler');
    expertSection.children[1].before(newSection);
  }

  function getExtensionField() {
    return document.getElementsByClassName('module__foot')[0].children[1];
  }

  function buildContentActions() {
    var elements = [];
    elements.push(createButton('save'));
    elements.push(buildMenuField());
    elements.push(createButton('remove'));
    appendElementsToExtension(elements);
  }

  function createButton(type) {
    var newButton = document.createElement('button');
    var image = buttonImage(type);
    newButton.appendChild(image);
    newButton.id = `${type}_button`;
    newButton.style = "cursor: pointer";
    var titleName = type.charAt(0).toUpperCase() + type.slice(1);
    newButton.setAttribute('title', `${titleName} content`);
    newButton.onclick = function(event){
      var type = event.target.id.split("_")[0];
      eval(type + 'Action()');
    }
    return newButton;
 }

 function buttonImage(type){
    var image = document.createElement('img');
    var image_url = `${type}_image_url`;
    image.id = `${type}_image`;
    image.src = eval(image_url);
    return image;
 }

 function appendElementsToExtension(buttons) {
   var section = getExtensionField();
   for (i in buttons) {
     section.appendChild(buttons[i]);
   }
 }

 function buildMenuField() {
   var menuElement = document.createElement('select');
   menuElement.setAttribute('id', 'menu_element');
   var firstOption = document.createElement('option');
   firstOption.value = " ";
   menuElement.appendChild(firstOption);
   return menuElement;
 }

 function getMenuElement() {
   return document.getElementById('menu_element');
 }

 function populateDropDownMenu(content = contentCollection) {
   var uniqueContents = [...new Set(content)];
   for (var i = 0; i < uniqueContents.length; i++) {
     var item = uniqueContents[i];
     var element = document.createElement('option');
     element.text = item;
     element.value = item;
     getMenuElement().appendChild(element);
   }
 }

 function saveAction() {
   var content = document.getElementsByTagName('textarea')[1].value;
   var collection = contentCollection;
   collection.push(content)
   resetMenu();
   populateDropDownMenu(collection);
 }

 function resetMenu() {
   getMenuElement().innerHTML = " ";
 }

 // function createButton(type){
 //   var button = document.createElement('button');
 //   var image = createImage(type);
 //   button.appendChild(image);
 //   button.id = `${type}_button`;
 //   button.style = "cursor: pointer";
 //   var titleName = type.charAt(0).toUpperCase() + type.slice(1);
 //   button.setAttribute('title', `${titleName} content`);
 //   button.onclick = function(event){
 //     var type = event.target.id.split("_")[0];
 //     eval(type + 'Action()');
 //   }
 //   return button;
 // }

//   // event.preventDefault;
//   loadExtension();
//   activeChats();

//
// function activeChats() {
//   var checkExist = setInterval(function() {
//     if ($('.fc--question-node').length) {
//       checkForActiveQuestion();
//       console.log('questions are loaded');
//       clearInterval(checkExist);
//     }
//   }, 1000);
// }
//
// function checkForActiveQuestion() {
//   console.log('running');
//   if ($('.active').length) {
//   } else {
//     // keeps reloading until question is selected
//     var mediaSection = document.getElementsByClassName('media-block__content--fill');
//     if (!mediaSection[0].classList.contains('loaded')) {
//       loadExtension();
//     }
//   }
// }
//
// function loadExtension() {
//   getValues();
//   var mediaSection = document.getElementsByClassName('media-block__content--fill');
//   var dropDown = createMenuField();
//   var saveButton = createButtonField('save');
//   var contentButton = createButtonField('content');
//   mediaSection[0].appendChild(dropDown);
//   mediaSection[0].appendChild(saveButton);
//   mediaSection[0].prepend(contentButton);
//   var removeButton = createButtonField('remove');
//   removeButton.style.visibility = 'hidden';
//   mediaSection[0].appendChild(removeButton);
//   mediaSection[0].classList += ' loaded';
// }
//
// function getValues() {
//   resetCollection(contentCollection);
//   chrome.storage.sync.get(null, function(items) {
//     for (key in items) {
//       contentCollection.push(key);
//       console.log(key);
//     }
//   })
// }
//
// function resetCollection(collection) {
//   collection = [];
// }
//
// function createButtonField(type) {
//   var button = createButton(type);
//   var buttonField = createField(button, type);
//   return buttonField;
// }
//
// function createButton(type){
//   var button = document.createElement('button');
//   var image = createImage(type);
//   button.appendChild(image);
//   button.id = `${type}_button`;
//   button.style = "cursor: pointer";
//   var titleName = type.charAt(0).toUpperCase() + type.slice(1);
//   button.setAttribute('title', `${titleName} content`);
//   button.onclick = function(event){
//     var type = event.target.id.split("_")[0];
//     eval(type + 'Action()');
//   }
//   return button;
// }
//
// function createField(button, type){
//   var buttonField = document.createElement('div');
//   buttonField.setAttribute('class', `${type}_button_field`);
//   buttonField.appendChild(button);
//   return buttonField;
// }
//
// function createMenuField() {
//   var menuElement = document.createElement('select');
//   menuElement.setAttribute('id', 'menuElement');
//   menuElement.setAttribute('style', 'display:none');
//   return menuElement;
// }
//
// function createImage(type) {
//   var image = document.createElement('IMG');
//   image.id = `${type}_image`;
//   var image_url = `${type}_image_url`;
//   image.src = eval(image_url);
//   return image;
// }
//
// function saveAction(){
//   var content = document.getElementsByTagName('textarea')[1].value;
//   var obj = {};
//   obj[content] = content;
//   if (content.length <= 1) {
//     console.log('Error: No content selected');
//     return;
//   }
//   chrome.storage.sync.set(obj, function() {
//     console.log('content saved');
//   })
//   refreshMenuDiv();
//   // Option to contribute: reset menu upon save w/o toggling menu
// }
//
// function contentAction() {
//   var menu = getMenu();
//   appendMenuOptions(menu);
//   displayMenuDiv();
//   // window.setTimeout(checkForActiveQuestion(), 20000);
//
//   // checkForActiveQuestion();
// }
//
// function removeAction() {
//   var content = document.getElementsByTagName('textarea')[1].value;
//   if (content != " ") {
//     if (confirm('Are you sure you want to delete this item?')) {
//       chrome.storage.sync.remove(content, function() {
//         // Would like to refresh menu div instead of whole window
//         refreshWindow();
//         alert('content deleted');
//       })
//     }
//   }
// }
//
// function getMenu() {
//   return document.getElementById('menuElement');
// }
//
// function appendMenuOptions(parentElement, content = contentCollection) {
//   parentElement.innerText = "";
//   content.unshift(" ");
//   var uniqueContents = [...new Set(content)];
//   for (var i = 0; i < uniqueContents.length; i++) {
//     var item = uniqueContents[i];
//     var element = document.createElement('option');
//     element.text = item;
//     element.value = item;
//     parentElement.appendChild(element);
//   }
//   return parentElement
// }
//
//
// function refreshMenuDiv() {
//   getValues();
//   var menu = getMenu();
//   var newMenu = appendMenuOptions(menu);
//   menu.innerHTML = newMenu.innerHTML;
// }
//
// function filterMenu() {
//   resetCollection(filteredList);
//   var menu = getMenu();
//   if (menu.style.display == 'block') {
//     var input = document.getElementsByTagName('textarea')[1];
//     input.oninput = function(event) {
//       var filteredList = isIncluded(event);
//       appendMenuOptions(menu, filteredList);
//       menu.addEventListener('change', function(event) {
//         getSelection(event);
//       });
//     }
//   }
// }
//
// function isIncluded(event) {
//   var newList = [];
//   for (var i = 0; i < contentCollection.length; i++) {
//     if (contentCollection[i].search(event.target.value) > -1) {
//       newList.push(contentCollection[i]);
//     }
//   }
//   return newList;
// }
//
// function displayMenuDiv() {
//   var menu = getMenu();
//   var input = document.getElementsByTagName('textarea')[1];
//   if (menu.style.display == 'block' || menu.style.display == '') {
//     menu.style.display = 'none';
//     $('.remove_button_field').hide()
//   } else {
//     menu.style.display = 'block';
//     input.value = " ";
//     document.getElementsByClassName('remove_button_field')[0].setAttribute('style', 'visibility: "block"');
//     input.addEventListener('change', function(event) {
//       // figure out why it only sometimes filters
//       // need to initiate sooner, missing first input
//       filterMenu();
//     })
//     menu.addEventListener('change', function(event) {
//       getSelection(event);
//     });
//   }
// }
//
// function getSelection(event){
//   var selection = event.target.value;
//   document.getElementsByTagName('textarea')[1].value = selection;
// }
//
// function refreshWindow() {
//   window.location.href = window.location.href;
// }
//
// function resetInput() {
//   var input = document.getElementsByTagName('textarea')[1];
//   input.value = " ";
// }
<commit_msg>deleting from session data, no chrome storage<commit_after>// //escape parenthesis to counter invalid RegExp
// // break sections into divs
// //  remove blank option from filtered menu
// // finesse autocomplete
// // tab trigger to autocomplete
// // return focus to input to be able to send w/ a
// // toggle clears input
//
var save_image_url = 'https://c1.staticflickr.com/3/2900/33745640515_a90c44b434_t.jpg';
// var content_image_url = 'https://c1.staticflickr.com/4/3943/33793771665_e25336d636_t.jpg';
var remove_image_url = 'https://c1.staticflickr.com/4/3684/33135618604_414134ce5c_t.jpg';
var contentCollection = ['hi', 'sup', 'fruit'];
// var filteredList = [];
//
  window.onload = function(){
    buildExtensionField();
    buildContentActions();
    loadContent();
  }

  function loadContent() {
    getMenuElement();
    populateDropDownMenu();
  }

  function buildExtensionField() {
    var expertSection = document.getElementsByClassName('module__foot')[0];
    var newSection = document.createElement('div');
    newSection.setAttribute('class', 'content-filler');
    expertSection.children[1].before(newSection);
  }

  function getExtensionField() {
    return document.getElementsByClassName('module__foot')[0].children[1];
  }

  function buildContentActions() {
    var elements = [];
    elements.push(createButton('save'));
    elements.push(buildMenuField());
    elements.push(createButton('remove'));
    appendElementsToExtension(elements);
  }

  function createButton(type) {
    var newButton = document.createElement('button');
    var image = buttonImage(type);
    newButton.appendChild(image);
    newButton.id = `${type}_button`;
    newButton.style = "cursor: pointer";
    var titleName = type.charAt(0).toUpperCase() + type.slice(1);
    newButton.setAttribute('title', `${titleName} content`);
    newButton.onclick = function(event){
      var type = event.target.id.split("_")[0];
      eval(type + 'Action()');
    }
    return newButton;
 }

 function buttonImage(type){
    var image = document.createElement('img');
    var image_url = `${type}_image_url`;
    image.id = `${type}_image`;
    image.src = eval(image_url);
    return image;
 }

 function appendElementsToExtension(buttons) {
   var section = getExtensionField();
   for (i in buttons) {
     section.appendChild(buttons[i]);
   }
 }

 function buildMenuField() {
   var menuElement = document.createElement('select');
   menuElement.setAttribute('id', 'menu_element');
   var firstOption = document.createElement('option');
   firstOption.value = " ";
   menuElement.appendChild(firstOption);
   return menuElement;
 }

 function getMenuElement() {
   return document.getElementById('menu_element');
 }

 function populateDropDownMenu(contents = contentCollection) {
   var uniqueContents = [...new Set(contents)];
   for (var i = 0; i < uniqueContents.length; i++) {
     var item = uniqueContents[i];
     var element = document.createElement('option');
     element.text = item;
     element.value = item;
     getMenuElement().appendChild(element);
   }
 }

 function saveAction() {
   var content = document.getElementsByTagName('textarea')[1].value;
  //  var collection = contentCollection;
   contentCollection.push(content)
   resetMenu();
   populateDropDownMenu();
 }

 function resetMenu() {
   getMenuElement().innerHTML = " ";
 }

 function removeAction() {
   var menu = getMenuElement();
   var value = menu.options[menu.selectedIndex].value;
   menu.remove(menu.selectedIndex);
  //  need to remove from storage
  var index = contentCollection.indexOf(value);
  contentCollection.splice(index, 1);
  resetMenu();
  populateDropDownMenu();
 }

 // function createButton(type){
 //   var button = document.createElement('button');
 //   var image = createImage(type);
 //   button.appendChild(image);
 //   button.id = `${type}_button`;
 //   button.style = "cursor: pointer";
 //   var titleName = type.charAt(0).toUpperCase() + type.slice(1);
 //   button.setAttribute('title', `${titleName} content`);
 //   button.onclick = function(event){
 //     var type = event.target.id.split("_")[0];
 //     eval(type + 'Action()');
 //   }
 //   return button;
 // }

//   // event.preventDefault;
//   loadExtension();
//   activeChats();

//
// function activeChats() {
//   var checkExist = setInterval(function() {
//     if ($('.fc--question-node').length) {
//       checkForActiveQuestion();
//       console.log('questions are loaded');
//       clearInterval(checkExist);
//     }
//   }, 1000);
// }
//
// function checkForActiveQuestion() {
//   console.log('running');
//   if ($('.active').length) {
//   } else {
//     // keeps reloading until question is selected
//     var mediaSection = document.getElementsByClassName('media-block__content--fill');
//     if (!mediaSection[0].classList.contains('loaded')) {
//       loadExtension();
//     }
//   }
// }
//
// function loadExtension() {
//   getValues();
//   var mediaSection = document.getElementsByClassName('media-block__content--fill');
//   var dropDown = createMenuField();
//   var saveButton = createButtonField('save');
//   var contentButton = createButtonField('content');
//   mediaSection[0].appendChild(dropDown);
//   mediaSection[0].appendChild(saveButton);
//   mediaSection[0].prepend(contentButton);
//   var removeButton = createButtonField('remove');
//   removeButton.style.visibility = 'hidden';
//   mediaSection[0].appendChild(removeButton);
//   mediaSection[0].classList += ' loaded';
// }
//
// function getValues() {
//   resetCollection(contentCollection);
//   chrome.storage.sync.get(null, function(items) {
//     for (key in items) {
//       contentCollection.push(key);
//       console.log(key);
//     }
//   })
// }
//
// function resetCollection(collection) {
//   collection = [];
// }
//
// function createButtonField(type) {
//   var button = createButton(type);
//   var buttonField = createField(button, type);
//   return buttonField;
// }
//
// function createButton(type){
//   var button = document.createElement('button');
//   var image = createImage(type);
//   button.appendChild(image);
//   button.id = `${type}_button`;
//   button.style = "cursor: pointer";
//   var titleName = type.charAt(0).toUpperCase() + type.slice(1);
//   button.setAttribute('title', `${titleName} content`);
//   button.onclick = function(event){
//     var type = event.target.id.split("_")[0];
//     eval(type + 'Action()');
//   }
//   return button;
// }
//
// function createField(button, type){
//   var buttonField = document.createElement('div');
//   buttonField.setAttribute('class', `${type}_button_field`);
//   buttonField.appendChild(button);
//   return buttonField;
// }
//
// function createMenuField() {
//   var menuElement = document.createElement('select');
//   menuElement.setAttribute('id', 'menuElement');
//   menuElement.setAttribute('style', 'display:none');
//   return menuElement;
// }
//
// function createImage(type) {
//   var image = document.createElement('IMG');
//   image.id = `${type}_image`;
//   var image_url = `${type}_image_url`;
//   image.src = eval(image_url);
//   return image;
// }
//
// function saveAction(){
//   var content = document.getElementsByTagName('textarea')[1].value;
//   var obj = {};
//   obj[content] = content;
//   if (content.length <= 1) {
//     console.log('Error: No content selected');
//     return;
//   }
//   chrome.storage.sync.set(obj, function() {
//     console.log('content saved');
//   })
//   refreshMenuDiv();
//   // Option to contribute: reset menu upon save w/o toggling menu
// }
//
// function contentAction() {
//   var menu = getMenu();
//   appendMenuOptions(menu);
//   displayMenuDiv();
//   // window.setTimeout(checkForActiveQuestion(), 20000);
//
//   // checkForActiveQuestion();
// }
//
// function removeAction() {
//   var content = document.getElementsByTagName('textarea')[1].value;
//   if (content != " ") {
//     if (confirm('Are you sure you want to delete this item?')) {
//       chrome.storage.sync.remove(content, function() {
//         // Would like to refresh menu div instead of whole window
//         refreshWindow();
//         alert('content deleted');
//       })
//     }
//   }
// }
//
// function getMenu() {
//   return document.getElementById('menuElement');
// }
//
// function appendMenuOptions(parentElement, content = contentCollection) {
//   parentElement.innerText = "";
//   content.unshift(" ");
//   var uniqueContents = [...new Set(content)];
//   for (var i = 0; i < uniqueContents.length; i++) {
//     var item = uniqueContents[i];
//     var element = document.createElement('option');
//     element.text = item;
//     element.value = item;
//     parentElement.appendChild(element);
//   }
//   return parentElement
// }
//
//
// function refreshMenuDiv() {
//   getValues();
//   var menu = getMenu();
//   var newMenu = appendMenuOptions(menu);
//   menu.innerHTML = newMenu.innerHTML;
// }
//
// function filterMenu() {
//   resetCollection(filteredList);
//   var menu = getMenu();
//   if (menu.style.display == 'block') {
//     var input = document.getElementsByTagName('textarea')[1];
//     input.oninput = function(event) {
//       var filteredList = isIncluded(event);
//       appendMenuOptions(menu, filteredList);
//       menu.addEventListener('change', function(event) {
//         getSelection(event);
//       });
//     }
//   }
// }
//
// function isIncluded(event) {
//   var newList = [];
//   for (var i = 0; i < contentCollection.length; i++) {
//     if (contentCollection[i].search(event.target.value) > -1) {
//       newList.push(contentCollection[i]);
//     }
//   }
//   return newList;
// }
//
// function displayMenuDiv() {
//   var menu = getMenu();
//   var input = document.getElementsByTagName('textarea')[1];
//   if (menu.style.display == 'block' || menu.style.display == '') {
//     menu.style.display = 'none';
//     $('.remove_button_field').hide()
//   } else {
//     menu.style.display = 'block';
//     input.value = " ";
//     document.getElementsByClassName('remove_button_field')[0].setAttribute('style', 'visibility: "block"');
//     input.addEventListener('change', function(event) {
//       // figure out why it only sometimes filters
//       // need to initiate sooner, missing first input
//       filterMenu();
//     })
//     menu.addEventListener('change', function(event) {
//       getSelection(event);
//     });
//   }
// }
//
// function getSelection(event){
//   var selection = event.target.value;
//   document.getElementsByTagName('textarea')[1].value = selection;
// }
//
// function refreshWindow() {
//   window.location.href = window.location.href;
// }
//
// function resetInput() {
//   var input = document.getElementsByTagName('textarea')[1];
//   input.value = " ";
// }
<|endoftext|>


<commit_before>//
// files in this folder only work with CraftBukkit servers
//
// This example script shows how the special 'self' variable can be used
// to get information about the current player.
//
// Usage:
// In minecraft, press the / key to display the in-game command prompt
// type the following...
//
//     /js cb_hello()
//
// ... and the game will print "Hello <minecraft user name>"
//
function cb_hello()
{
	 print("Hello " + self.name);
}
<commit_msg>js-plugins/bukkit/<commit_after><|endoftext|>


<commit_before>// Copyright 2022, University of Colorado Boulder

/**
 * QUnit tests for ScientificNotationNode.toScientificNotation, the part of ScientificNotationNode that is unit-testable.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */

import ScientificNotationNode from './ScientificNotationNode.js';

QUnit.module( 'ScientificNotationNode' );

QUnit.test( 'value === 0', assert => {

  // For value === 0, the specified exponent should be used.
  assert.deepEqual( ScientificNotationNode.toScientificNotation( 0, {
    exponent: 2,
    mantissaDecimalPlaces: 1
  } ), { mantissa: '0.0', exponent: '2' } );

  // For value === 0, if no exponent is requested, exponent should be 0.
  assert.deepEqual( ScientificNotationNode.toScientificNotation( 0, {
    exponent: null,
    mantissaDecimalPlaces: 1
  } ), { mantissa: '0.0', exponent: '0' } );
} );

QUnit.test( 'exponent === 0', assert => {

  // For exponent === 0, we use dot.Utils.toFixed to create the mantissa. This example adds zeros to decimal places.
  assert.deepEqual( ScientificNotationNode.toScientificNotation( 424.8, {
    exponent: 0,
    mantissaDecimalPlaces: 3
  } ), { mantissa: '424.800', exponent: '0' } );

  // For exponent === 0, we use dot.Utils.toFixed to create the mantissa. This example rounds decimal places.
  assert.deepEqual( ScientificNotationNode.toScientificNotation( 424.856, {
    exponent: 0,
    mantissaDecimalPlaces: 1
  } ), { mantissa: '424.9', exponent: '0' } );
} );<commit_msg>add unit tests for rounding, https://github.com/phetsims/scenery-phet/issues/747<commit_after>// Copyright 2022, University of Colorado Boulder

/**
 * QUnit tests for ScientificNotationNode.toScientificNotation, the part of ScientificNotationNode that is unit-testable.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */

import ScientificNotationNode from './ScientificNotationNode.js';

QUnit.module( 'ScientificNotationNode' );

QUnit.test( 'value === 0', assert => {

  // For value === 0, the specified exponent should be used.
  assert.deepEqual( ScientificNotationNode.toScientificNotation( 0, {
    exponent: 2,
    mantissaDecimalPlaces: 1
  } ), { mantissa: '0.0', exponent: '2' } );

  // For value === 0, if no exponent is requested, exponent should be 0.
  assert.deepEqual( ScientificNotationNode.toScientificNotation( 0, {
    exponent: null,
    mantissaDecimalPlaces: 1
  } ), { mantissa: '0.0', exponent: '0' } );
} );

QUnit.test( 'exponent === 0', assert => {

  // For exponent === 0, we use dot.Utils.toFixed to create the mantissa. This example adds zeros to decimal places.
  assert.deepEqual( ScientificNotationNode.toScientificNotation( 424.8, {
    exponent: 0,
    mantissaDecimalPlaces: 3
  } ), { mantissa: '424.800', exponent: '0' } );

  // For exponent === 0, we use dot.Utils.toFixed to create the mantissa. This example rounds decimal places.
  assert.deepEqual( ScientificNotationNode.toScientificNotation( 424.856, {
    exponent: 0,
    mantissaDecimalPlaces: 1
  } ), { mantissa: '424.9', exponent: '0' } );
} );

QUnit.test( 'rounding', assert => {

  // This case was reported in https://github.com/phetsims/build-a-nucleus/issues/24 with bad mantissa 4.3
  // assert.deepEqual( ScientificNotationNode.toScientificNotation( 424.8, {
  //   exponent: null,
  //   mantissaDecimalPlaces: 1
  // } ), { mantissa: '4.2', exponent: '2' } );

  assert.deepEqual( ScientificNotationNode.toScientificNotation( 425.8, {
    exponent: null,
    mantissaDecimalPlaces: 2
  } ), { mantissa: '4.26', exponent: '2' } );

  // This case was reported in https://github.com/phetsims/build-a-nucleus/issues/24, with bad mantissa 9.7
  // assert.deepEqual( ScientificNotationNode.toScientificNotation( 9648, {
  //   exponent: null,
  //   mantissaDecimalPlaces: 1
  // } ), { mantissa: '9.6', exponent: '3' } );

  assert.deepEqual( ScientificNotationNode.toScientificNotation( 9658, {
    exponent: null,
    mantissaDecimalPlaces: 2
  } ), { mantissa: '9.66', exponent: '3' } );
} );<|endoftext|>