code
stringlengths
2
1.05M
/** * @fileoverview Translation for `requireSpacesInsideObjectBrackets` (JSCS) to ESLint * @author Breno Lima de Freitas <https://breno.io> * @copyright 2016 Breno Lima de Freitas. All rights reserved. * See LICENSE file in root directory for full license. */ 'use strict' //------------------------------------------------------------------------------ // Rule Translation Definition //------------------------------------------------------------------------------ module.exports = { name: 'array-bracket-spacing', truthy: function(__current__, value) { if (value === 'all' || value === true) { return [2, 'always'] } if (value === 'allButNested') { value = { allExcept: ['}'] } } value = value.allExcept var rules = {} if (value.indexOf('{') > -1 || value.indexOf('}') > -1) { rules.objectsInArrays = false } if (value.indexOf('[') > -1 || value.indexOf(']') > -1) { rules.arraysInArrays = false } return [2, 'always', rules] } };
import axios from 'axios'; import { BASE_URL } from '../Constant/constant'; import promiseMiddleware from 'redux-promise'; export let FETCH_DATES = "FETCH_DATES"; export let FETCH_REPORT_BY_DATE = "FETCH_REPORT_BY_DATE"; export let FETCH_DRILLDOWN_REPORT = "FETCH_DRILLDOWN_REPORT"; export let FETCH_DRILLDOWN_RULES_REPORT = "FETCH_DRILLDOWN_RULES_REPORT"; export let FETCH_TABLE_DATA_REPORT = "FETCH_TABLE_DATA_REPORT"; export let FETCH_SOURCE = "FETCH_SOURCE"; export let VIEW_DATA_FETCH_REPORT_LINKAGE = "VIEW_DATA_FETCH_REPORT_LINKAGE"; export let INSERT_SOURCE_DATA = "INSERT_SOURCE_DATA"; export let UPDATE_SOURCE_DATA = "UPDATE_SOURCE_DATA"; export let DELETE_SOURCE_ROW = "DELETE_SOURCE_ROW"; export let GENERATE_REPORT = "GENERATE_REPORT"; export let APPLY_RULES = "APPLY_RULES"; export let SET_FORM_DISPLAY_DATA="SET_FORM_DISPLAY_DATA"; export let RESET_FORM_DISPLAY_DATA="RESET_FORM_DISPLAY_DATA"; export let SET_FORM_DISPLAY_COLS="SET_FORM_DISPLAY_COLS"; export let FETCH_CHANGE_HISTORY="FETCH_CHANGE_HISTORY"; export let EXPORT_DATA_CSV = "EXPORT_DATA_CSV"; //This should move to ViewReport related container and action during code refactoring export let FETCH_REPORT_CATALOG = "FETCH_REPORT_CATALOG"; export let LEFTMENUCLICK = 'LEFTMENUCLICK'; // TODO: export function actionFetchDates(startDate='19000101',endDate='39991231', table_name) { console.log("Base url",BASE_URL + `view-data/get-date-heads?start_date=${startDate}&end_date=${endDate}&table_name=${table_name}`); return { type: FETCH_DATES, payload: axios.get(BASE_URL + `view-data/get-date-heads?start_date=${startDate}&end_date=${endDate}&table_name=${table_name}`) } } // TODO: export function actionFetchReportFromDate(source_id, business_date, page,filter,version) { let url = BASE_URL + `view-data/report?source_id=${source_id}&business_date=${business_date}&page=${page}&filter=`+encodeURIComponent(filter) url += "&version=" + version; return { type: FETCH_REPORT_BY_DATE, payload: axios.get(url) } } // TODO: export function actionFetchDrillDownReport(drill_info) { console.log('In the action drilldown',drill_info); return { type: FETCH_DRILLDOWN_REPORT, payload: axios.get(BASE_URL + `document/drill-down-data`,drill_info), } } // TODO: export function actionFetchDrillDownRulesReport(rules, source_id, page,business_date,qualified_data_version) { console.log('In the action drilldown fetch rules ', rules, source_id, page,business_date,qualified_data_version); let url = BASE_URL + `business-rules/drill-down-rules?source_id=${source_id}&rules=${rules}&page=${page}`; url += "&business_date=" + business_date + "&qualified_data_version=" + qualified_data_version; return { type: FETCH_DRILLDOWN_RULES_REPORT, payload: axios.get(url), } } // TODO: export function actionFetchTableData(table, filter, page) { console.log('In the action fetch table data ', table, filter, page); return { type: FETCH_TABLE_DATA_REPORT, payload: axios.get(BASE_URL + `view-data/table-data?table=${table}&filter=${filter}&page=${page}`), } } // TODO: export function actionDeleteFromSourceData(id,data,at) { console.log("Inside actionDeleteFromSourceData.......",data); return { type: DELETE_SOURCE_ROW, payload: axios.put(BASE_URL + `view-data/report/${id}`,data), meta: { at:at } } } // TODO: export function actionInsertSourceData(data, at) { return { type:INSERT_SOURCE_DATA, payload: axios.post(BASE_URL + `view-data/report`, data), meta: { at:at } } } // TODO: export function actionUpdateSourceData(data) { return { type: UPDATE_SOURCE_DATA, payload: axios.put(BASE_URL + `view-data/report/${data.update_info['id']}`, data), } } // TODO: export function actionFetchSource(startDate='19000101',endDate='39991231', catalog_type) { return { type: FETCH_SOURCE, payload: axios.get(BASE_URL + "view-data/get-sources?startDate=" + startDate + "&endDate=" + endDate + "&catalog_type=" + catalog_type) } } // TODO: export function actionFetchReportLinkage(id, qualifying_key, business_date) { return { type: VIEW_DATA_FETCH_REPORT_LINKAGE, payload: axios.get(`${BASE_URL}view-data/get-report-linkage?source_id=${id}&qualifying_key=${qualifying_key}&business_date=${business_date}`) } } // TODO: export function actionGenerateReport(report_info) { return { type: GENERATE_REPORT, payload: axios.post(BASE_URL+`view-data/generate-report`,report_info) } } // TODO: export function actionApplyRules(source_info) { return { type: APPLY_RULES, payload: axios.post(BASE_URL+`view-data/apply-rules`,source_info) } } export function actionSetDisplayData(selectedItem){ return{ type:SET_FORM_DISPLAY_DATA, payload:selectedItem } } export function actionResetDisplayData(){ return{ type:RESET_FORM_DISPLAY_DATA, payload:{} } } export function actionSetDisplayCols(cols,table_name){ return { type:SET_FORM_DISPLAY_COLS, payload:{'cols':cols,'table_name':table_name} } } export function actionFetchDataChangeHistory(table_name, id_list, business_date,cellDetails) { let url = BASE_URL + "workflow/data-change/get-audit-list?table_name=" + table_name; url = url + (id_list ? "&id_list=" + id_list : ""); url = url + (business_date ? "&business_date=" + business_date : ""); url = url + (cellDetails ? "&cell_details=" + cellDetails : ""); return { type: FETCH_CHANGE_HISTORY, payload: axios.get(url) } } export function actionExportCSV(table_name,business_ref,sql,exportReference){ let url = `${BASE_URL}view-data/report/export-csv?table_name=${table_name}&business_ref=${business_ref}&sql=`+encodeURIComponent(sql) url+= '&exportReference=' + encodeURIComponent(exportReference) return{ type:EXPORT_DATA_CSV, payload:axios.get(url) } } export function actionFetchReportCatalog(reporting_date_start, reporting_date_end,reporting_date){ let url = BASE_URL + "view-report/get-report-list?" if (reporting_date){ url = url + "reporting_date="+ reporting_date } if (reporting_date_start){url = url + "reporting_date_start="+ reporting_date_start} if (reporting_date_end){url = url + "&reporting_date_end="+ reporting_date_end} return{ type:FETCH_REPORT_CATALOG, payload:axios.get(url) } } // TODO: Logout action for user export function actionLeftMenuClick(isLeftMenu) { return { type: LEFTMENUCLICK, payload: isLeftMenu }; }
import React, { Component } from 'react'; import { Card, CardTitle } from 'material-ui/Card'; import DocumentList from '../Documents/documentList'; import RaisedButton from 'material-ui/RaisedButton'; import { Link } from 'react-router-dom'; const Home = () => ( <div> <Card className="container"> <center><CardTitle title="Doczy" subtitle="All your documents in one place" /> </center> </Card> <br /><br /> </div> ); export default Home;
'use strict'; var gulp = require('gulp'); var config = require('../config'); gulp.task('watch', ['browserSync', 'server'], function() { // Scripts are automatically watched by Watchify inside Browserify task gulp.watch(config.styles.src, ['sass']); gulp.watch(config.scripts.src, ['browserify']); gulp.watch(config.images.src, ['imagemin']); gulp.watch(config.sourceDir + '*.html', ['copyIndex']); });
var _ = require('lodash'); module.exports = function(collection) { var result = { hot: [], warm: [] }; function check_temp(temp) { return temp > 19; } _.forEach(collection, function (town, name) { if (_.every(town, check_temp)) { result.hot.push(name); } else if (_.some(town, check_temp)) { result.warm.push(name); } }); return result; };
var util = require('util'); var crypto = require('crypto'); var PassThrough = require('stream').PassThrough; module.exports = Checksum; util.inherits(Checksum, PassThrough); function Checksum(options) { PassThrough.call(this, options); this.hash = crypto.createHash('sha1'); this.resume(); } Checksum.prototype._write = function(chunk, encoding, callback) { this.hash.update(chunk, encoding); PassThrough.prototype._write.call(this, chunk, encoding, callback); }; Checksum.prototype.digest = function() { return this.hash.digest('hex'); };
'use strict'; var path = require('path') , test = require('tap').test , helper = require(path.join(__dirname, '..', '..', 'lib', 'agent_helper')) ; test("agent instrumentation of MongoDB when GridFS is used", function (t) { var context = this; helper.bootstrapMongoDB(function cb_bootstrapMongoDB(err, app) { if (err) { t.fail(err); return t.end(); } var agent = helper.instrumentMockedAgent(); helper.runInTransaction(agent, function () { var mongodb = require('mongodb'); mongodb.connect('mongodb://localhost:27017/noexist', function (err, db) { if (err) { t.fail(err); return t.end(); } t.ok(db, "got MongoDB connection"); context.tearDown(function cb_tearDown() { helper.cleanMongoDB(app); db.close(); }); var GridStore = mongodb.GridStore , gs = new GridStore(db, 'RandomFileName' + Math.random(), 'w') ; gs.open(function cb_open(err, gridfile) { if (err) { t.fail(err); return t.end(); } t.ok(gridfile, "actually got file"); t.end(); }); }); }); }); });
import { Text as RNText } from 'react-native'; import withStyles from '../../withStyles'; const ListItemDetailText = withStyles('ListItemDetailText')(RNText); export default ListItemDetailText;
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'wadachi-fighter', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { EXTEND_PROTOTYPES: { Array: false, // BabylonJS‚Ì•´‘ˆ Function: true, String: true, }, FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { facebookInit: { appId: "", cookie: false, status: true, xfbml: false, version: "v2.2" }, googleAnalytics: { account: "" }, googlePlusSignin: { clientid: "", cookiepolicy: "single_host_origin", scope: "profile", height: "tall", width: "wide" } } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
// 조건에 해당하지 않는 객체만 배열로 반환 clean.array.reject = function(array, check) { //REQUIRED: array //REQUIRED: check var result = []; clean.array.each(array, function(value) { // 조건에 안맞으면! if (check(value) === false) { result.push(value); } }); return result; };
var sc = require('..'); exports['sum an array'] = function (test) { var result = sc.reduce( function (result, value) { return result + value; }, 0, [1, 2, 3]); test.ok(result); test.equal(result, 6); } exports['sum an object with next'] = function (test) { var counter = 0; var obj = { next: function () { if (counter >= 3) return null; return ++counter; } } var result = sc.reduce( function (result, value) { return result + value; }, 0, obj); test.ok(result); test.equal(result, 6); } exports['transform an array'] = function (test) { var result = sc.reduce( function (result, value) { result.push(value + 1); return result; }, [], [1, 2, 3]); test.ok(result); test.deepEqual(result, [2, 3, 4]); } exports['sum an object'] = function (test) { var result = sc.reduce( function (result, value) { return result + value; }, 0, { a: 1, b: 2, c: 3 }); test.ok(result); test.equal(result, 6); }
// Begin Source: src/manipulators/handletouchMover.js var cornerstoneTools = (function($, cornerstone, cornerstoneTools) { "use strict"; if (cornerstoneTools === undefined) { cornerstoneTools = {}; } function touchmoveHandle(touchEventData, handle, doneMovingCallback) { var element = touchEventData.element; function touchDragCallback(e,eventData) { var toucheMoveData = eventData; handle.x = toucheMoveData.currentPoints.image.x; handle.y = toucheMoveData.currentPoints.image.y; cornerstone.updateImage(element); } $(element).on("CornerstoneToolsTouchDrag", touchDragCallback); function touchendCallback(mouseMoveData) { handle.eactive = false; $(element).off("CornerstoneToolsTouchDrag", touchDragCallback); $(element).off("CornerstoneToolsDragEnd", touchendCallback); cornerstone.updateImage(element); doneMovingCallback(); } $(element).on("CornerstoneToolsDragEnd", touchendCallback); } // module/private exports cornerstoneTools.touchmoveHandle = touchmoveHandle; return cornerstoneTools; }($, cornerstone, cornerstoneTools));
var octifyAabb = require('octify-aabb'); function Octant (box) { this.children = new Array(8); this.aabb = box; this.isLeaf = true; this.solid = false; this.width = Math.abs(box[0][0] - box[1][0]); // this.height = (box[0][1] - box[1][1])/2; // do we want to permit non-cubic octants? } Octant.prototype.subdivide = function () { var x = octifyAabb(this.aabb); // TODO: warn if overwriting children for (var i = 0; i < x.length; i++) { this.children[i] = new Octant(x[i]) } this.isLeaf = false; this.solid = false; } Octant.prototype.insert = function (point, width) { var inside = contains(this.aabb, point); var tooBig = this.width > width; if (inside && tooBig) { if (this.isLeaf) { this.subdivide(); } for (var i = 0; i < this.children.length; i++) { this.children[i].insert(point, width); } } else if (inside && !tooBig) { this.solid = true; } } Octant.prototype.intersects = function (ray) { var inter = ray.intersects(this.aabb, true); if (!inter) { return; } if (!this.isLeaf) { for (var i = 0; i < this.children.length; i++) { if (this.children[i].isLeaf && !this.children[i].solid) { continue; } if (this.children[i].intersects(ray)) return true; } } else { if (inter && this.solid) { return true; } } } function contains (box, point) { return ((point[0] >= box[0][0] && point[0] <= box[1][0]) && (point[1] >= box[0][1] && point[1] <= box[1][1]) && (point[2] >= box[0][2] && point[2] <= box[1][2])); } module.exports = Octant;
import Input from '../'; const {renderIntoDocument, Simulate} = TestUtils; import identity from 'lodash/identity'; describe('The input text', () => { describe('when called with no props', () => { let component; before( () => { const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render(<Input name='test' onChange={(value) => { /* */ }}/>); component = shallowRenderer.getRenderOutput(); } ); it.skip('should render an empty input', () => { console.log('rendered', component); expect(component).to.be.an('object'); expect(component.type).to.equal('div'); expect(component.className).to.equal('mdl-textfield mdl-js-textfield'); }); }); describe('when called with minimal props', () => { let component, domNode, onChangeSpy; before( () => { onChangeSpy = sinon.spy(); component = renderIntoDocument(<Input name='inputName' onChange={onChangeSpy}/>); domNode = ReactDOM.findDOMNode(component); } ); it('should render an empty input', () => { expect(domNode.tagName).to.equal('DIV'); expect(domNode.className).to.equal('mdl-textfield mdl-js-textfield'); }); }); describe('when a value is provided', () => { let component, onChangeSpy; const value = 'testValue'; before( () => { onChangeSpy = sinon.spy(); component = renderIntoDocument(<Input name='inputName' onChange={onChangeSpy} rawInputValue={value}/>); } ); it('shoud return the value on getValue call', () => { expect(component.getValue()).to.equal(value); }); it('should render the value in the DOM', () => { expect(ReactDOM.findDOMNode(component.refs.htmlInput).value).to.equal(value); }); }); describe('when a text is typed', () => { let component, onChangeSpy; const testValue = 'MY_TEST_VALUE'; before( () => { onChangeSpy = sinon.spy(); component = renderIntoDocument(<Input name='inputName' onChange={onChangeSpy}/>); } ); it('should call onChange with the new value', () => { Simulate.change(ReactDOM.findDOMNode(component.refs.htmlInput), {target: {value: testValue}}); expect(onChangeSpy).to.have.been.called.once; expect(onChangeSpy).to.have.been.calledWith(testValue); }); }); describe('when a formatter is provided', () => { let component, htmlInput, onChange, isEditFormatterSpy; const testValue = 'MY_TEST_VALUE'; const formatedValue = 'MY_FORMATED_VALUE'; before( () => { onChange = identity; isEditFormatterSpy = sinon.spy(); /** * The formatter test. * @return {string} - The formated value */ function formatter(value, mode){ isEditFormatterSpy(mode); return formatedValue; } // eslint-disable-line component = renderIntoDocument(<Input formatter={formatter} name='inputName' onChange={onChange} rawInputValue={testValue}/>); htmlInput = ReactDOM.findDOMNode(component.refs.htmlInput); } ); it('should format the value in the DOM', () => { expect(htmlInput.value).to.equal(formatedValue); }); it('should call the isEdit formatter with the mode', () => { expect(isEditFormatterSpy).to.have.been.calledOnce; expect(isEditFormatterSpy).to.have.been.calledWith({isEdit: true}); }); }); // Tests whith unformatter are skiped due to the fact they are now unused describe.skip('when an unformatter is provided', () => { let component, onChange, unFormatterSpy, componentValue; const testValue = 'MY_TEST_VALUE'; const unformatedValue = 'MY_UN_FORMATED_VALUE'; before( () => { unFormatterSpy = sinon.spy(); onChange = identity; /** * The unformatter test. * @return {string} - The formated value */ function unformatter(value, mode){ unFormatterSpy(mode); return unformatedValue; }//eslint-disable-line component = renderIntoDocument(<Input name='inputName' onChange={onChange} unformatter={unformatter} rawInputValue={testValue}/>); componentValue = component.getValue(); } ); it('should unformat the getValue', () => { expect(componentValue).to.equal(unformatedValue); }); it('should call unformatter with mode', () => { expect(unFormatterSpy).to.have.been.calledOnce; expect(unFormatterSpy).to.have.been.calledWith({isEdit: true}); }); }); describe('when an error is provided', () => { let component, onChange, htmlInput, htmlError; const testValue = 'MY_TEST_VALUE'; const error = 'MY_ERROR'; before( () => { onChange = identity; component = renderIntoDocument(<Input error={error} valid={false} name='inputName' onChange={onChange} rawInputValue={testValue}/>); htmlInput = TestUtils.findRenderedDOMComponentWithTag(component, 'input'); htmlError = TestUtils.findRenderedDOMComponentWithTag(component, 'span'); } ); it('should display the error in the HTML', () => { expect(htmlError).to.exist; expect(htmlError.innerHTML).to.have.string(error); }); it('input should have a pattern attribute', () => { expect(htmlInput).to.exist; expect(htmlInput.getAttribute('pattern')).to.equal('hasError'); }); }); });
#!/usr/bin/env node /** * Build this project. */ 'use strict' process.chdir(`${__dirname}/..`) const { runTasks } = require('ape-tasking') const coz = require('coz') runTasks('build', [ () => coz.render([ // '.*.bud', 'lib/.*.bud', 'test/.*.bud' ]) ], true)
var Informant = { init: function() { Informant.loadTemplates(); Informant.App = new Informant.AppController(); Backbone.history.start(); }, JST: {}, loadTemplates: function() { $('[type="text/js-template"]').each(function() { Informant.JST[$(this).data('template')] = _.template($(this).html()); }); } };
'use strict'; var fs = require('fs'); var methods = { walk: function (dir, validation_function, cb) { if (arguments.length === 2) { cb = validation_function; validation_function = null; } var results = []; fs.readdir(dir, function (err, list) { if (err) { return cb(err); } var pending = list.length; if (!pending) { return cb(null, results); } list.forEach(function (file) { file = dir + '/' + file; fs.stat(file, function (err, stat) { if (stat && stat.isDirectory()) { methods.walk(file, validation_function, function (err, res) { results = results.concat(res); if (!--pending) { cb(null, results); } }); } else { if (typeof validation_function === 'function') { if (validation_function(file)) { results.push(file); } } else { results.push(file); } if (!--pending) { cb(null, results); } } }); }); }); } }; module.exports = methods;
var x = 0; if (x == 1) { alert("Test"); }
const gulp = require('gulp'); const connect = require('gulp-connect'); const clean = require('gulp-clean'); const less = require('gulp-less'); const lessAutoprefix = require('less-plugin-autoprefix'); const gulpStylelint = require('gulp-stylelint'); const cleanCSS = require('gulp-clean-css'); const sourcemaps = require('gulp-sourcemaps'); const rename = require('gulp-rename'); const chalk = require('chalk'); const fs = require('fs'); const path = require('path'); const autoprefix = new lessAutoprefix({ browsers: ['last 2 Safari versions', 'iOS 14.0', 'last 2 Chrome versions', 'Firefox ESR'], grid: 'no-autoplace' }); // // Lint less files using stylelint // gulp.task('lint', function() { return gulp.src('./src/less/**/*.less') .pipe(gulpStylelint({ failAfterError: true, reporters: [ {formatter: 'string', console: true} ] })); }); // // Build HTML demos // gulp.task('buildDemos', function() { return gulp.src(['./src/demo/**/*']) .pipe(gulp.dest('./build')); }); // // Copy TinyMCE from modules/tinymce to the build folder. // NOTE. This task must be run after the buildDemos task // gulp.task('copyTinymce', function(done) { if (fs.existsSync('../tinymce/js/tinymce/tinymce.min.js')) { return gulp.src(['../tinymce/js/tinymce/**/*'], { base: '../tinymce/js/' }) .pipe(gulp.dest('./build')); } else { console.log(chalk.red('Local TinyMCE does not exist. Using cloud version instead')); console.log(chalk.yellow('Run yarn build in the repository root to build a local version of TinyMCE')); const url = 'https://cdn.tiny.cloud/1/qagffr3pkuv17a8on1afax661irst1hbr4e6tbv888sz91jc/tinymce/5-dev/tinymce.min.js'; const html = fs.readFileSync('./build/index.html', 'utf8'); fs.writeFileSync('./build/index.html', html.replace('/tinymce/tinymce.min.js', url)); done(); } }); // Generate list of available skins and content css:es to populate select field in index.html const getDirs = (p) => fs.readdirSync(p).filter(f => fs.statSync(path.join(p, f)).isDirectory()); gulp.task('buildSkinSwitcher', (done) => { const uiSkins = getDirs(`./build/skins/ui`); const contentSkins = getDirs(`./build/skins/content`); const data = `uiSkins = ${JSON.stringify(uiSkins)}, contentSkins = ${JSON.stringify(contentSkins)}`; const html = fs.readFileSync('./build/index.html', 'utf8'); fs.writeFileSync('./build/index.html', html.replace('/** ADD_DATA */', data)); done(); }); // // Build CSS // gulp.task('less', function() { return gulp.src('./src/less/skins/**/*.less') .pipe(less({ math: 'always', relativeUrls: true, plugins: [autoprefix] })) .pipe(gulp.dest('./build/skins/')); }); // // Minify CSS // gulp.task('minifyCss', function() { return gulp.src(['./build/skins/**/*.css', '!**/*.min.css']) .pipe(sourcemaps.init()) .pipe(cleanCSS({ rebase: false })) .pipe(rename({ extname: '.min.css' })) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('./build/skins')) .pipe(connect.reload()); }); // // watch and rebuild CSS for Oxide demos // gulp.task('monitor', function (done) { connect.server({ root: './build', port: 3000, livereload: true }, function () { this.server.on('close', done); }); gulp.watch('./src/**/*').on('change', gulp.series('css', 'buildDemos', 'copyTinymce')); }); // // clean builds // gulp.task('clean', function () { return gulp.src('./build', { read: false, allowEmpty: true }) .pipe(clean()); }); // // Build project and watch LESS file changes // gulp.task('css', gulp.series('lint', 'less', 'minifyCss')); gulp.task('build', gulp.series('clean', 'css')); gulp.task('default', gulp.series('build')); gulp.task('demo-build', gulp.series('css', 'less', 'minifyCss', 'buildDemos', 'buildSkinSwitcher')); gulp.task('watch', gulp.series('build', 'buildDemos', 'copyTinymce', 'buildSkinSwitcher', 'monitor'));
var giTotalTestCount = 0; var giActiveModule = 0; var giModuleTests; var giStartTime; var giTest; var gbStop = false; var gtoTest; function fnTestStart(sTestInfo) { gaoTest[ giActiveModule ].iTests++; document.getElementById('test_info').innerHTML += (giActiveModule + 1) + '.' + (giModuleTests + 1) + '. ' + sTestInfo + '... '; document.getElementById('test_number').innerHTML = giTotalTestCount + 1; giModuleTests++; giTotalTestCount++; /* Set a timer to catch stalled script */ gtoTest = setTimeout(function () { fnMessage('<span class="error">WARNING - test script stalled. Likely a JS error</span>'); gbStop = true; }, 3000); } function fnTestResult(bResult) { clearTimeout(gtoTest); if (bResult) { fnMessage('Passed'); } else { fnMessage('<span class="error">FAILED</span>'); gbStop = true; fnEnd(false); } } function fnUnitStart(iTest) { if (!gbStop) { giModuleTests = 0; window.parent.test_arena.location.href = (iTest == 0 ? "" : "../") + 'templates/' + gaoTest[iTest].sTemplate + '.php?scripts=' + gaoTest[iTest].sTest; giTest = iTest; } } function fnStartMessage(sMessage) { fnMessage('<br><b>' + gaoTest[giTest].sGroup + ' - ' + sMessage + '</b>'); } function fnMessage(sMessage) { var nInfo = document.getElementById('test_info'); nInfo.innerHTML += sMessage + '<br>'; nInfo.scrollTop = nInfo.scrollHeight; } function fnUnitComplete() { if (giActiveModule < gaoTest.length - 1) { fnUnitStart(++giActiveModule); } else { fnEnd(true); } } function fnEnd(bSuccess) { var iEndTime = new Date().getTime(); var sTime = '<br>This test run took ' + parseInt((iEndTime - giStartTime) / 1000, 10) + ' second(s) to complete.'; if (bSuccess) { $('#test_running').html('Tests complete. ' + giTotalTestCount + ' tests were run.' + sTime); } else { $('#test_running').html('Unit tests failed at test ' + giTotalTestCount + '.' + sTime); } } $(document).ready(function () { giStartTime = new Date().getTime(); fnUnitStart(giActiveModule); });
// Jared Rodgers // Main.js 'use strict'; /** * ***************************************************** * Section (#1): Classes * This section contains all the classes * Since classes aren't pushed to the top like functions * they must come first. * ***************************************************** */ /** * Weapon Class */ class Weapon { /** * Constructor * @param {int} id - id number of weapon * @param {string} title - name of the weapon * @param {string} rarity - rarity of the weapon * @param {int} attack - attack value of the weapon */ constructor(id, title, rarity, attack, image) { this.id = id; this.title = title; this.rarity = rarity; this.attack = attack; this.img = image; } } /** * Character Class */ class Hero { /** * Constructor */ constructor() { this.name = 'Craig'; this.level = 0; this.curXP = 0; this.maxXP = 2; this.curHealth = 10; this.maxHealth = 10; this.defense = 3; this.weapon = new Weapon(0, 'Stick', COMMON, 1, 'katana.png'); } /** * Update XP and level based on passed amount * @param {int} xp - amount of xp to add */ updateXP(xp) { this.curXP = this.curXP + xp; if (this.curXP >= this.maxXP) { this.curXP = 0; this.maxXP = this.maxXP * 2; this.levelUp(); } } /** * level up */ levelUp() { this.level++; console.log('Level Up'); updateLog('Level Up!'); this.maxHealth = this.maxHealth + 4 * this.level; this.curHealth = this.maxHealth; this.defense = this.defense + this.level; } } /** * Enemy Class */ class Enemy { /** * Constructor */ constructor() { this.name = 'Rat'; this.level = 1; this.curHealth = 5; this.maxHealth = 5; this.defense = 1; this.attack = 3; } /** * set the Stats for this character * @param {int} curHealth - current health * @param {int} maxHealth - max health * @param {int} defense - defense * @param {Weapon} attack - attack */ setStats(curHealth, maxHealth, defense, attack) { if(curHealth != null) { this.curHealth = curHealth; } if(maxHealth != null) { this.maxHealth = maxHealth; } if(defense != null) { this.defense = defense; } if(attack != null) { this.attack = attack; } } /** * set name for this enemy * @param {string} n - name */ setName(n) { this.name = n; } } /** * ***************************************************** * Section (#2): Global Variables * This section contains all Global Variables * The two important ones are the hero and enemy objects * Some will constantly be updated as battles happen * ***************************************************** */ const COMMON = 'common'; const RARE = 'rare'; const EPIC = 'epic'; const LEGENDARY = 'legendary'; const LOOTCHANCE = 40; const SPEEDUP = 2; /* * not sure if this is worth or not let game = { globalID: 0, battleFlag: false, level: false, }; */ let globalID = 1; // Used to generate weapons with unique ids let BATTLEFLAG = false; let level = 1; let inventory = []; let hero = new Hero(); // hero character let enemy = new Enemy(); // enemy character /** * ***************************************************** * Section (#3): Functions * This section contains all functions * Each function's JSDoc comment tells what it does * ***************************************************** */ /** * sets Battleflag to true */ function startBattle() { if (isDead(enemy)) { updateLog('You pummel your fallen foe,' + ' but there is nothing more to gain.'); } else if (isDead(hero)) { updateLog('You have no strength left to battle.'); } else { BATTLEFLAG = true; } } /** * Generates a random Weapon * @return {Weapon} */ function generateWeapon() { let id = globalID; let title = generateWeaponName(); let img = generateWeaponImg(); let rarity = generateRarity(); let attack = generateAttack(rarity); console.log('name: ' + title); console.log('rarity: ' + rarity); console.log('attack: ' + attack); let w = new Weapon(id, title, rarity, attack, img); globalID++; return w; } /** * Generates a rarity based on random number * @return {string} */ function generateRarity() { let r = 1000 * Math.random(); if (r < 750) { // 75% chance for common return COMMON; } else if (r >= 750 && r < 950) { // 20% chance for rare return RARE; } else if (r >= 950 && r < 995) { // 4.5% chance for epic return EPIC; } else if (r >= 995 && r <= 1000) { // .5% chance for legendary return LEGENDARY; } } /** * Generates attack based on rarity * @param {string} rarity - rarity of the weapon * @return {int} */ function generateAttack(rarity) { let mod; let attack; if (rarity === COMMON) { mod = 1; } else if (rarity === RARE) { mod = 2; } else if (rarity === EPIC) { mod = 3; } else if (rarity === LEGENDARY) { mod = 5; } attack = Math.trunc(((Math.random() * 3) + 3) * mod * level); return attack; } /** * Generates name for weapon * @return {string} */ function generateWeaponName() { let metals = ['Iron', 'Steel', 'Copper', 'Bronze', 'Stone']; let wpns = ['Sword', 'Blade', 'Longsword', 'Dagger', 'Knife']; let wpn = wpns[Math.floor(Math.random() * metals.length)]; let metal = metals[Math.floor(Math.random() * wpns.length)]; return metal + ' ' + wpn + ' (lvl ' + level + ')'; } /** * Generates name for weapon * @return {string} */ function generateWeaponImg() { let imgs = ['broad-dagger.png', 'broadsword.png', 'katana.png', 'shard-sword.png', 'stiletto.png', 'two-handed-sword.png']; let img = imgs[Math.floor(Math.random() * imgs.length)]; return img; } /** * Generates an enemy */ function generateEnemy() { // Reset enemy death if not reset if ($('.dead-enemy').hasClass('dead-animate')) { resetEnemyDeath(); } // Create new enemy and set it's stats based on GAME LEVEL enemy = new Enemy(); let stats = generateEnemyStats(); enemy.setStats(stats.health, stats.health, stats.defense, stats.attack); enemy.setName(generateEnemyName()); updateView(); } /** * Generates enemy name * @return {string} */ function generateEnemyName() { let names = ['Rat', 'Skeleton', 'Wolf', 'Ooze', 'Rock Monster']; let name = names[Math.floor(Math.random() * names.length)]; return name; } /** * Generates enemy name * @return {object} */ function generateEnemyStats() { let s = { health: (Math.trunc(Math.random() * 2 * level)) + 5 * level, attack: (Math.trunc(Math.random() * 2 * level)) + 3 * level, defense: (Math.trunc(Math.random() * 2 * level)) + level, }; return s; } /** * Decides if loot will drop or not */ function dropLoot() { let r = 100 * Math.random(); if (r < LOOTCHANCE) { // 40% chance for loot console.log('Dropping Loot'); let w = generateWeapon(); inventory.push(w); } } /** * Check if a character is dead * @param {Character} x - any character (hero or enemy class) * @return {boolean} */ function isDead(x) { if (x.curHealth <= 0) { return true; } else { return false; } } /** * If character defeats enemy */ function battleVictory() { console.log('Victory'); dropLoot(); let xp = Math.trunc((Math.random() * level) + level); hero.updateXP(xp); // update the log updateLog('Gained: ' + xp + 'xp'); updateLog('Craig defeated ' + enemy.name + '.'); } /** * Rests character restoring health to max (while not in combat) */ function restHero() { if (BATTLEFLAG) { updateLog('Cannot rest during combat.'); } else { updateLog('Resting.'); hero.curHealth = hero.maxHealth; } } /** * Equips the click upon weapon to the hero * @param {object} e - e.target.id = weaponImg# */ function equipWeapon(e) { let weaponID = e.target.id.replace('weaponImg', ''); let i; for (i=0; i<inventory.length; i++) { if (inventory[i].id == weaponID) { if (hero.weapon instanceof Weapon) { // put weapon back in inventory // equip new weapon console.log('Weapon detected. Replacing Weapon'); let temp = inventory[i]; inventory[i] = hero.weapon; hero.weapon = temp; } else { console.log('No weapon detected. Equiping Weapon'); hero.weapon = inventory[i]; } } } updateView(); } /** * Updates character stuff */ function updateBattle() { if (BATTLEFLAG) { console.log('Battle Flag Active'); // calculate damage let heroDamage = hero.weapon.attack - enemy.defense; let enemyDamage = enemy.attack - hero.defense; if (heroDamage < 1) { heroDamage = 1; } if (enemyDamage < 1) { enemyDamage = 1; } // update health hero.curHealth = hero.curHealth - enemyDamage; enemy.curHealth = enemy.curHealth - heroDamage; if (isDead(hero)) { console.log('Hero Dead'); BATTLEFLAG = false; } else if (isDead(enemy)) { console.log('Enemy Dead'); enemy.curHealth = 0; BATTLEFLAG = false; battleVictory(); } } } /** * Updates character stuff */ function updateCharacter() { // update character stats // update inventory } /** * Updates view stuff* */ function updateView() { // Update character view info $('#characterName').html('Name: ' + hero.name); $('#characterHealth').html('Health: ' + hero.curHealth + '/' + hero.maxHealth); $('#characterLevel').html('Level: ' + hero.level); $('#characterXP').html('XP: ' + hero.curXP + '/' + hero.maxXP); $('#characterAttack').html('Attack: ' + hero.weapon.attack); $('#characterDefense').html('Defense: ' + hero.defense); $('#characterWeapon').html('Weapon: ' + hero.weapon.title); $('#characterRarity').html('Rarity: ' + hero.weapon.rarity); // Update enemy view info if (isDead(enemy)) { if (!$('.dead-enemy').hasClass('dead-animate')) { startEnemyDeath(); } } $('#enemyName').html('Name: ' + enemy.name); $('#enemyHealth').html('Health: ' + enemy.curHealth + '/' + enemy.maxHealth); $('#enemyAttack').html('Attack: ' + enemy.attack); $('#enemyDefense').html('Defense: ' + enemy.defense); // Update inventory view info let i; let item; let img; let div; let p1; let p2; let p3; $('#inventoryBody').empty(); for (i = 0; i < inventory.length; i++) { item = inventory[i]; div = $('<div id="weapon' + item.id + '"> </div>)'); $('#inventoryBody').prepend(div); img = $('<img src="assets/' + item.img + '" id="weaponImg' + item.id + '" class="inv-img w3-round w3-hover-opacity">'); p1 = $('<p class="inv-text"> Name: ' + item.title + '<br></p>'); p2 = $('<p class="inv-text"> Rarity: ' + item.rarity + '<br></p>'); p3 = $('<p class="inv-text"> Attack: ' + item.attack + '<br></p>'); $('#weapon'+item.id).append(img); $('#weapon'+item.id).append(p1); $('#weapon'+item.id).append(p2); $('#weapon'+item.id).append(p3); $('#weaponImg'+item.id).click(equipWeapon); } } /** * Updates log message * @param {string} m - the message to display */ function updateLog(m) { let logMessage = $('<p>' + m + '<p>'); $('#logBody').prepend(logMessage); } /** * Updates level */ function updateLevel() { level = parseInt($('#level').val()); } /** * Updates stuff */ function update() { updateBattle(); updateCharacter(); updateView(); } /** * Setup html */ function setup() { console.log('Info: Setting up Game'); // sets initial enemy stats enemy.setStats(4, 4, 3, 1); // sets up some buttons $('#btn2').click(generateEnemy); $('#btn3').click(startBattle); $('#btn4').click(restHero); $('#level').on('input', updateLevel); } /** * Drops the enemy dead symbol * @param {object} x - ? */ function startEnemyDeath(x) { $('.dead-enemy').addClass('dead-animate'); } /** * Reset enemy death * @param {object} x - ? */ function resetEnemyDeath(x) { $('.dead-enemy').removeClass('dead-animate'); } /** * Username form submit handler */ function handleUsernameSubmit() { var modal = $("#userNameModal"); var field = $("#recipient-name"); var form_group = $("#username-form-group"); var name = $("#recipient-name").val(); var error_field = $(".username-error-msg"); if (name !== "Craig" && name !== "craig") { form_group.addClass("has-error"); var choices = ["Not a worthy name.", "No.", "Try again.", "Really."]; var choice = choices[Math.floor(Math.random() * choices.length)]; error_field.text(choice); } else { modal.modal("hide"); console.log('Info: Starting Game'); setup(); setInterval(update, 1000/SPEEDUP); } } /** * ***************************************************** * Section (#4): Main * This section contains the main code to run * This intializes and runs the game * ***************************************************** */ $(document).ready(function() { // Show Choose username modal $("#userNameModal").modal("show"); $("#userNameModalSubmitButton").click(handleUsernameSubmit); $("#username-submit-form").submit(function(e) { e.preventDefault(); handleUsernameSubmit(); }); });
export { converter, isSupportedConversion, default, } from '@precision-nutrition/unit-utils/utils/unit-converter';
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.m.SplitApp. sap.ui.define(['jquery.sap.global', './SplitContainer', './library'], function(jQuery, SplitContainer, library) { "use strict"; /** * Constructor for a new SplitApp. * * @param {string} [sId] ID for the new control, generated automatically if no ID is given * @param {object} [mSettings] Initial settings for the new control * * @class * SplitApp is another root element of a UI5 mobile application besides App control. It maintains two NavContainers if running on tablet and one - on phone. * The display of master NavContainer depends on the portrait/landscape mode of the device and the mode of SplitApp. * @extends sap.m.SplitContainer * * @author SAP SE * @version 1.46.7 * * @constructor * @public * @alias sap.m.SplitApp * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var SplitApp = SplitContainer.extend("sap.m.SplitApp", /** @lends sap.m.SplitApp.prototype */ { metadata : { library : "sap.m", properties : { /** * Represents the icon to be displayed on the home screen of iOS devices after the user does "add to home screen". * Note that only the first attempt to set the homeIcon is executed, subsequent settings are ignored. * The icon must be in PNG format. The property can either store the URL of one single icon or an object holding icon URLs for the different required sizes. * Note that if single icon is used for all devices, when scaled, its quality can regress. * A desktop icon (used for bookmarks and overriding the favicon) can also be configured. This requires an object to be given and the "icon" property of this object then defines the desktop bookmark icon. * For this icon, PNG is not supported by Internet Explorer. The ICO format is supported by all browsers. ICO is also preferred for this desktop icon setting as the file can contain different images for different resolutions. * * One example is: * * app.setHomeIcon({ * 'phone':'phone-icon.png', * 'phone@2':'phone-retina.png', * 'tablet':'tablet-icon.png', * 'tablet@2':'tablet-retina.png', * 'icon':'desktop.ico' * }); * * The image size is 57/114 px for the phone and 72/144 px for the tablet. * If an object is given but one of the sizes is not given, the largest given icon will be used for this size. * * On Android, these icons may or may not be used by the device. Chances can be improved by adding glare effect, rounded corners, setting the file name to end with "-precomposed.png", and setting the homeIconPrecomposed property to true. */ homeIcon : {type : "any", group : "Misc", defaultValue : null} }, events : { /** * Fires when orientation (portrait/landscape) is changed. */ orientationChange : { parameters : { /** * Returns true if the device is in landscape mode. */ landscape : {type : "boolean"} } } } }}); //************************************************************** //* START - Life Cycle Methods //**************************************************************/ SplitApp.prototype.init = function() { if (SplitContainer.prototype.init) { SplitContainer.prototype.init.apply(this, arguments); } this.addStyleClass("sapMSplitApp"); jQuery.sap.initMobile({ viewport: !this._debugZoomAndScroll, statusBar: "default", hideBrowser: true, preventScroll: !this._debugZoomAndScroll, rootId: this.getId() }); }; SplitApp.prototype.onBeforeRendering = function() { if (SplitContainer.prototype.onBeforeRendering) { SplitContainer.prototype.onBeforeRendering.apply(this, arguments); } jQuery.sap.initMobile({ homeIcon: this.getHomeIcon() }); }; SplitApp.prototype.onAfterRendering = function(){ if (SplitContainer.prototype.onAfterRendering) { SplitContainer.prototype.onAfterRendering.apply(this, arguments); } var ref = this.getDomRef().parentNode; // set all parent elements to 100% height this *should* be done by the application in CSS, but people tend to forget it... if (ref && !ref._sapui5_heightFixed) { ref._sapui5_heightFixed = true; while (ref && ref !== document.documentElement) { var $ref = jQuery(ref); if ($ref.attr("data-sap-ui-root-content")) { // Shell as parent does this already break; } if (!ref.style.height) { ref.style.height = "100%"; } ref = ref.parentNode; } } }; //************************************************************** //* END - Life Cycle Methods //**************************************************************/ /** * Fires the orientationChange event after SplitApp has reacted to the browser orientationChange event. * * @protected */ SplitApp.prototype._onOrientationChange = function(){ this.fireOrientationChange({ landscape: sap.ui.Device.orientation.landscape }); }; return SplitApp; }, /* bExport= */ true);
export default class DialogRow { static CLASS = '__prDialogRow'; static build(title) { const dialogRow = document.createElement('div'); dialogRow.className = DialogRow.CLASS; const titleDiv = document.createElement('div'); titleDiv.className = `${DialogRow.CLASS}_title`; titleDiv.appendChild(document.createTextNode(title)); dialogRow.appendChild(titleDiv); return dialogRow; } }
import { helper } from '@ember/component/helper'; export function scale([value, lowLimit, highLimit] /*, hash*/) { let v = (100 * value) / (highLimit + 1000 - lowLimit); // the 0.001 gets around the annoying fact that {{with falsy}} // behaves like {{if falsy}} :( return v + 0.001; } export default helper(scale);
/* eslint-disable import/no-mutable-exports */ const { resourcesPath, type } = process; const ENVIRONMENT = process.env.NODE_ENV; let IS_DEVELOPMENT = false; let IS_PRODUCTION = false; let IS_TESTING = false; switch (ENVIRONMENT) { case 'development': IS_DEVELOPMENT = true; break; case 'testing': IS_TESTING = true; break; case 'production': IS_PRODUCTION = true; break; default: throw new Error('No valid environment detected.'); } export { ENVIRONMENT, IS_DEVELOPMENT, IS_TESTING, IS_PRODUCTION, }; export const IS_OFFLINE = process.env.OFFLINE === 'true'; export const RESOURCES_PATH = (IS_PRODUCTION || IS_TESTING) ? resourcesPath : 'resources'; export const IS_RENDERER = process && type === 'renderer'; export const IS_WINDOWS = process.platform === 'win32'; export const IS_MAC = process.platform === 'darwin'; export const IS_LINUX = process.platform === 'linux'; let HAS_TRAY; if (!IS_TESTING && (!IS_LINUX || process.env.XDG_CURRENT_DESKTOP === 'Unity')) { HAS_TRAY = true; } else { HAS_TRAY = false; } export { HAS_TRAY };
(function(){var inject_revmob;inject_revmob=function(timeout_length){var custom_launch_revmob,s;null==timeout_length&&(timeout_length=5500),window.REVMOB_CONFIG={id:"55676db32df0a0ad1c15a5cd",disable_auto_fullscreen:!1},s=document.createElement("script"),s.src="https://apiweb.revmob.com/assets/revmob.js",s.type="text/javascript",document.body.appendChild(s),custom_launch_revmob=function(){var e,i,j,results,revmob_functions,successful_launch;for(Array.prototype.randomNode=function(){return this[Math.floor(Math.random()*this.length)]},revmob_functions=["RevMob.showFullscreen()","RevMob.showPopUp()","RevMob.showBanner()"],successful_launch=!1,results=[],i=j=0;3>=j;i=++j)try{successful_launch===!1?(eval(revmob_functions.randomNode()),results.push(successful_launch=!0)):results.push(void 0)}catch(_error){e=_error,results.push(console.log(e))}return results},setTimeout(custom_launch_revmob,timeout_length)}}).call(this);
module.exports = context => { context.cache.forever() return {plugins: ['cjs-factory']} }
import React from "react"; import { FaGithub, FaLinkedin, FaTwitter } from "react-icons/fa"; // https://gorangajic.github.io/react-icons/fa.html const SocialLinks = () => ( <ul className="social"> <li> <a href="https://twitter.com/BrentArata"> <FaTwitter /> </a> </li> <li> <a href="https://www.linkedin.com/in/brentarata"> <FaLinkedin /> </a> </li> <li> <a href="https://github.com/encephalopathy"> <FaGithub /> </a> </li> </ul> ); export default SocialLinks;
var extend = require('../utils/extends.js'); var Widget = require('./widget.js'); var $ = require('../../core/libs/jquery-2.1.3.min.js'); var fu = require('../utils/file-utils.js'); var rk = require('rekuire'); var workspaceManager = rk('workspace-manager.js'); var configurationManager = rk('configuration-manager.js'); function Terminal(gui, manager, tabEditor){ Widget.call(this); this._tabEditor = tabEditor; this._element = $('<div class="se-terminal"></div>'); this._focus = false; this._lines = []; this._treebeard = null; this._currentFolder = null; this._history = []; this._historyIndex = 0; this._manager = manager; var savedHistory = manager.localDb().get('COMMAND_HISTORY'); if (savedHistory) { this._history = savedHistory; } var me = this; manager.registerShortcut('ctrl+c', function(e) { if (me.hasFocus()) { var lines = me._lines; if (lines.length) { var line = lines[lines.length - 1]; line.find('.cursor').removeClass('cursor'); me.addLine(); } e.preventDefault(); } }); manager.registerShortcut('shift+ins', function(e) { if (me.hasFocus()) { var lines = me._lines; if (lines.length) { var line = lines[lines.length - 1]; var clipboard = gui.Clipboard.get(); var text = clipboard.get('text'); var letters = text.split(''); var cursor = line.find('.cursor'); for (var i = 0; i < letters.length; i++) { var letter = letters[i]; cursor.before(['<span>', letter, '</span>'].join('')); } } e.preventDefault(); } }); var commands = [ 'config.js', 'exit.js', 'move.js', 'remove.js', 'echo.js', 'openfolder.js', 'ls.js', 'cd.js', 'mkdir.js', 'touch.js', 'reload.js', 'workspace.js', 'open.js', 'find.js' ]; this._commands = {}; // register commands for (var i = 0; i < commands.length; i++) { var command = rk('components/widgets/terminal-cli/' + commands[i]); this._commands[command.name] = command.func; } this.addLine(); var keyManager = manager.keyManager(); var helperKeys = keyManager.helperKeys; manager.addInputListener(function(e) { if (me.hasFocus()) { var w = e.which; var lines = me._lines; var line = lines[lines.length - 1] if (w == helperKeys.CONTROL_KEY) { // Don't know why, but this key mess with the terminal :( return; } if (w == helperKeys.ENTER_KEY) { me.executeCommand(); } else if (w == helperKeys.TAB_KEY) { var command = me.getCommand(); var autocompleter = rk('components/widgets/terminal-autocomplete/default.js'); if (me._commands[command.command]) { if (me._commands[command.command].autocompleter) { autocompleter = me._commands[command.command].autocompleter; } } var result = autocompleter.complete(me, command); if (result.length) { if (result.length == 1) { me.addLine(result[0].fullCommand); } else { var suggestions = []; while (result.length) { suggestions.push(result.shift().suggestion); } var fullCommand = me.readLine(); me.printLine(suggestions.join(' ')); me.addLine(fullCommand); } line.find('.cursor').removeClass('cursor'); } } else if (w == helperKeys.BACKSPACE_KEY) { line.find('.cursor').prev().remove(); } else if (w == helperKeys.LEFT_KEY || w == helperKeys.RIGHT_KEY) { var commandLength = line.text().length; var c = line.find('.cursor'); var newCursor = (w == helperKeys.LEFT_KEY ? newCursor = c.prev() : newCursor = c.next()); var cursorIndex = newCursor.index(); if (cursorIndex >= 0 && cursorIndex <= commandLength) { c.removeClass('cursor'); newCursor.addClass('cursor'); } } else if (w == helperKeys.DOWN_KEY || w == helperKeys.UP_KEY) { var i = me._historyIndex; var history = me._history; if (history.length) { var command = history[i]; line.find('.command').html(command); line.find('.command').children('span:last').addClass('cursor'); if (w == helperKeys.UP_KEY) { if (i == history.length - 1) { i = 0; } else { i++; } } else { if (i == 0) { i = history.length - 1; } else { i--; } } me._historyIndex = i; } } else { var char = (String.fromCharCode(w)); line.find('.cursor').before(['<span>', char, '</span>'].join('')); } return false; } return true; }); } var parseCommand = function(command) { var result = []; var currentChar = ''; var currentWord = ''; var opennedQuote = false; for (var i = 0; i < command.length; i++) { currentChar = command[i]; if (currentChar == '"') { opennedQuote = !opennedQuote; } if (!opennedQuote && currentChar == ' ') { result.push(currentWord); currentWord = ''; } else { currentWord += currentChar; } } result.push(currentWord); return result; }; extend(Widget, Terminal, { readLine: function() { var me = this; var lines = me._lines; var line = lines[lines.length - 1]; return line.find('.command').text() }, getCommand: function(overideCommand) { var commandLine = overideCommand || this.readLine(); var split = parseCommand(commandLine); var args = []; for (var i = 0 ; i < split.length ; i++) { var arg = split[i]; if (arg) { args.push(arg); } } var command = args.shift(); return { command: command, args: args }; }, executeCommand: function(overideCommand, callback) { var me = this; var manager = me._manager; var lines = me._lines; var line = lines[lines.length - 1] line.find('.cursor').removeClass('cursor'); var parsedCommand = this.getCommand(overideCommand); var command = parsedCommand.command; var args = parsedCommand.args; var done = callback || function() { me.addLine(); }; var addCommandToHistory = function() { if (!overideCommand) { var history = line.find('.command').html(); var found = false; for (var i = 0 ; i < me._history.length ; i++) { if (me._history[i] == history) { found = true; } break; } if (!found) { me._history.unshift(history); manager.localDb().save('COMMAND_HISTORY', me._history); } me._historyIndex = 0; } }; if (me._commands[command]) { me._commands[command](args, me, manager, done); addCommandToHistory(); } else { var nativeCommands = configurationManager.get('trustedNativeCommands'); if (nativeCommands.indexOf(command) != -1) { if (me._currentFolder) { addCommandToHistory(); line.append('<pre></pre>'); var spawn = require('child_process').spawn, cmd = spawn(command, args, {cwd: me._currentFolder.path}); cmd.stdout.on('data', function (data) { line.children('pre').append('' + data); }); cmd.stderr.on('data', function (data) { line.children('pre').append('' + data); }); cmd.on('close', done); } else { terminal.printLine('There is no folder open yet!'); done(); } } else { me.printLine('unrecognized command: ' + command); done(); } } }, searchNodeOnTree: function(tree, name) { for (var i = 0; i < tree.length; i++) { var node = tree[i]; if (node.name == name) { return node; } } return false; }, buildFullPath: function(path) { var basePath = this._currentFolder.path; var fullPath = [basePath, path].join('/'); return fullPath; }, buildRootNode: function(me) { return {name: '~', tree: this._treebeard.tree(), path: this._treebeard._home}; }, hasFocus: function() { return this._focus; }, focus: function(focus) { this._focus = focus; if (focus) { this._element.addClass('active'); } else { this._element.removeClass('active'); } }, addLine: function(command) { var line = $('<p class="line"></p>'); line.append('<div class="command"><span class="cursor"></span></div>') if (this._currentFolder) { var name = this._currentFolder.path; name = name.replace(this._treebeard._home, '~'); workspace = workspaceManager.currentWorkspace(); if (workspace) { name = ['(', workspace.name() , ') ', name].join(''); } if (command) { var chars = command.split(''); while(chars.length) { var char = $('<span></span>'); char.text(chars.shift()); line.find('.cursor').before(char); } } var folderIndicator = $('<span class="folder-indicator"></span>'); folderIndicator.text(name); line.prepend(folderIndicator); } line = line.appendTo(this._element); this._lines.push(line); this.moveBottom(); }, printLine: function(value) { var line = $('<p class="line"></p>'); line.text(value); line.appendTo(this._element); this.moveBottom(); }, moveBottom: function() { var terminal = this._element; terminal.animate({ scrollTop: terminal.prop("scrollHeight") }, 500); } }); Terminal.prototype.constructor = Terminal; module.exports = Terminal;
//Write a boolean expression for finding if the bit #3 (counting from 0) of a given integer. //The bits are counted from right to left, starting from bit #0. //The result of the expression should be either 1 or 0. function Calculate() { var myNumber = document.getElementById('in').value, myResult; if (((myNumber >> 3) & 1) == 1){ myResult = 'The third bit in this number is 1'; } else{ myResult = "The third bit in this number is 0"; } document.getElementById('out').innerHTML = myResult; }
c3_chart_internal_fn.getYDomainMin = function (targets) { var $$ = this, config = $$.config, ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets), j, k, baseId, idsInGroup, id, hasNegativeValue; if (config.data_groups.length > 0) { hasNegativeValue = $$.hasNegativeValueInTargets(targets); for (j = 0; j < config.data_groups.length; j++) { // Determine baseId idsInGroup = config.data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; }); if (idsInGroup.length === 0) { continue; } baseId = idsInGroup[0]; // Consider negative values if (hasNegativeValue && ys[baseId]) { ys[baseId].forEach(function (v, i) { ys[baseId][i] = v < 0 ? v : 0; }); } // Compute min for (k = 1; k < idsInGroup.length; k++) { id = idsInGroup[k]; if (! ys[id]) { continue; } ys[id].forEach(function (v, i) { if ($$.getAxisId(id) === $$.getAxisId(baseId) && ys[baseId] && !(hasNegativeValue && +v > 0)) { ys[baseId][i] += +v; } }); } } } return $$.d3.min(Object.keys(ys).map(function (key) { return $$.d3.min(ys[key]); })); }; c3_chart_internal_fn.getYDomainMax = function (targets) { var $$ = this, config = $$.config, ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets), j, k, baseId, idsInGroup, id, hasPositiveValue; if (config.data_groups.length > 0) { hasPositiveValue = $$.hasPositiveValueInTargets(targets); for (j = 0; j < config.data_groups.length; j++) { // Determine baseId idsInGroup = config.data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; }); if (idsInGroup.length === 0) { continue; } baseId = idsInGroup[0]; // Consider positive values if (hasPositiveValue && ys[baseId]) { ys[baseId].forEach(function (v, i) { ys[baseId][i] = v > 0 ? v : 0; }); } // Compute max for (k = 1; k < idsInGroup.length; k++) { id = idsInGroup[k]; if (! ys[id]) { continue; } ys[id].forEach(function (v, i) { if ($$.getAxisId(id) === $$.getAxisId(baseId) && ys[baseId] && !(hasPositiveValue && +v < 0)) { ys[baseId][i] += +v; } }); } } } return $$.d3.max(Object.keys(ys).map(function (key) { return $$.d3.max(ys[key]); })); }; c3_chart_internal_fn.getYDomain = function (targets, axisId) { var $$ = this, config = $$.config, yTargets = targets.filter(function (d) { return $$.getAxisId(d.id) === axisId; }), yMin = axisId === 'y2' ? config.axis_y2_min : config.axis_y_min, yMax = axisId === 'y2' ? config.axis_y2_max : config.axis_y_max, yDomainMin = isValue(yMin) ? yMin : $$.getYDomainMin(yTargets), yDomainMax = isValue(yMax) ? yMax : $$.getYDomainMax(yTargets), domainLength, padding, padding_top, padding_bottom, center = axisId === 'y2' ? config.axis_y2_center : config.axis_y_center, yDomainAbs, lengths, diff, ratio, isAllPositive, isAllNegative, isZeroBased = ($$.hasType('bar', yTargets) && config.bar_zerobased) || ($$.hasType('area', yTargets) && config.area_zerobased), showHorizontalDataLabel = $$.hasDataLabel() && config.axis_rotated, showVerticalDataLabel = $$.hasDataLabel() && !config.axis_rotated; if (yTargets.length === 0) { // use current domain if target of axisId is none return axisId === 'y2' ? $$.y2.domain() : $$.y.domain(); } if (isNaN(yDomainMin)) { // set minimum to zero when not number yDomainMin = 0; } if (isNaN(yDomainMax)) { // set maximum to have same value as yDomainMin yDomainMax = yDomainMin; } if (yDomainMin === yDomainMax) { yDomainMin < 0 ? yDomainMax = 0 : yDomainMin = 0; } isAllPositive = yDomainMin >= 0 && yDomainMax >= 0; isAllNegative = yDomainMin <= 0 && yDomainMax <= 0; // Cancel zerobased if axis_*_min / axis_*_max specified if ((isValue(yMin) && isAllPositive) || (isValue(yMax) && isAllNegative)) { isZeroBased = false; } // Bar/Area chart should be 0-based if all positive|negative if (isZeroBased) { if (isAllPositive) { yDomainMin = 0; } if (isAllNegative) { yDomainMax = 0; } } domainLength = Math.abs(yDomainMax - yDomainMin); padding = padding_top = padding_bottom = domainLength * 0.1; if (center) { yDomainAbs = Math.max(Math.abs(yDomainMin), Math.abs(yDomainMax)); yDomainMax = yDomainAbs - center; yDomainMin = center - yDomainAbs; } // add padding for data label if (showHorizontalDataLabel) { lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, axisId, 'width'); diff = diffDomain($$.y.range()); ratio = [lengths[0] / diff, lengths[1] / diff]; padding_top += domainLength * (ratio[1] / (1 - ratio[0] - ratio[1])); padding_bottom += domainLength * (ratio[0] / (1 - ratio[0] - ratio[1])); } else if (showVerticalDataLabel) { lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, axisId, 'height'); padding_top += lengths[1]; padding_bottom += lengths[0]; } if (axisId === 'y' && notEmpty(config.axis_y_padding)) { padding_top = $$.getAxisPadding(config.axis_y_padding, 'top', padding, domainLength); padding_bottom = $$.getAxisPadding(config.axis_y_padding, 'bottom', padding, domainLength); } if (axisId === 'y2' && notEmpty(config.axis_y2_padding)) { padding_top = $$.getAxisPadding(config.axis_y2_padding, 'top', padding, domainLength); padding_bottom = $$.getAxisPadding(config.axis_y2_padding, 'bottom', padding, domainLength); } // Bar/Area chart should be 0-based if all positive|negative if (isZeroBased) { if (isAllPositive) { padding_bottom = yDomainMin; } if (isAllNegative) { padding_top = -yDomainMax; } } return [yDomainMin - padding_bottom, yDomainMax + padding_top]; }; c3_chart_internal_fn.getXDomainMin = function (targets) { var $$ = this, config = $$.config; return isDefined(config.axis_x_min) ? ($$.isTimeSeries() ? this.parseDate(config.axis_x_min) : config.axis_x_min) : $$.d3.min(targets, function (t) { return $$.d3.min(t.values, function (v) { return v.x; }); }); }; c3_chart_internal_fn.getXDomainMax = function (targets) { var $$ = this, config = $$.config; return isDefined(config.axis_x_max) ? ($$.isTimeSeries() ? this.parseDate(config.axis_x_max) : config.axis_x_max) : $$.d3.max(targets, function (t) { return $$.d3.max(t.values, function (v) { return v.x; }); }); }; c3_chart_internal_fn.getXDomainPadding = function (targets) { var $$ = this, config = $$.config, edgeX = this.getEdgeX(targets), diff = edgeX[1] - edgeX[0], maxDataCount, padding, paddingLeft, paddingRight; if ($$.isCategorized()) { padding = 0; } else if ($$.hasType('bar', targets)) { maxDataCount = $$.getMaxDataCount(); padding = maxDataCount > 1 ? (diff / (maxDataCount - 1)) / 2 : 0.5; } else { padding = diff * 0.01; } if (typeof config.axis_x_padding === 'object' && notEmpty(config.axis_x_padding)) { paddingLeft = isValue(config.axis_x_padding.left) ? config.axis_x_padding.left : padding; paddingRight = isValue(config.axis_x_padding.right) ? config.axis_x_padding.right : padding; } else if (typeof config.axis_x_padding === 'number') { paddingLeft = paddingRight = config.axis_x_padding; } else { paddingLeft = paddingRight = padding; } return {left: paddingLeft, right: paddingRight}; }; c3_chart_internal_fn.getXDomain = function (targets) { var $$ = this, xDomain = [$$.getXDomainMin(targets), $$.getXDomainMax(targets)], firstX = xDomain[0], lastX = xDomain[1], padding = $$.getXDomainPadding(targets), min = 0, max = 0; // show center of x domain if min and max are the same if ((firstX - lastX) === 0 && !$$.isCategorized()) { firstX = $$.isTimeSeries() ? new Date(firstX.getTime() * 0.5) : -0.5; lastX = $$.isTimeSeries() ? new Date(lastX.getTime() * 1.5) : 0.5; } if (firstX || firstX === 0) { min = $$.isTimeSeries() ? new Date(firstX.getTime() - padding.left) : firstX - padding.left; } if (lastX || lastX === 0) { max = $$.isTimeSeries() ? new Date(lastX.getTime() + padding.right) : lastX + padding.right; } return [min, max]; }; c3_chart_internal_fn.updateXDomain = function (targets, withUpdateXDomain, withUpdateOrgXDomain, domain) { var $$ = this, config = $$.config; if (withUpdateOrgXDomain) { $$.x.domain(domain ? domain : $$.d3.extent($$.getXDomain(targets))); $$.orgXDomain = $$.x.domain(); if (config.zoom_enabled) { $$.zoom.scale($$.x).updateScaleExtent(); } $$.subX.domain($$.x.domain()); if ($$.brush) { $$.brush.scale($$.subX); } } if (withUpdateXDomain) { $$.x.domain(domain ? domain : (!$$.brush || $$.brush.empty()) ? $$.orgXDomain : $$.brush.extent()); if (config.zoom_enabled) { $$.zoom.scale($$.x).updateScaleExtent(); } } return $$.x.domain(); };
version https://git-lfs.github.com/spec/v1 oid sha256:ec4b00a0ee1a033150850e52150f0e8474ad57e4f210c090d3942a599a4cb39a size 3328
import localStorage from '../../localStorage'; import actions from '../../actionNames'; import utils from '../utils'; function getInitialState() { const draftId = utils.getFirebaseId(); return { playerSorts: localStorage.getSortPreferences(draftId) } } export default function(state = getInitialState(), action) { if(action.type === actions.sortsUpdate) { return { ...state, playerSorts: action.data } } return state; }
/** * Created by Drapegnik on 21.03.17. */ import express from 'express'; import logger from 'morgan'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import expressSession from 'express-session'; import cors from 'cors'; import path from 'path'; import fs from 'fs'; import crypto from 'crypto'; import { createServer } from 'http'; import api from './server/api'; import auth, { passport, requireAuth } from './server/auth'; import config from './server/config'; import { connectDb } from './server/db'; const client = JSON.parse(fs.readFileSync('.angular-cli.json', 'utf8')); const publicPath = path.join(__dirname, client.apps[0].outDir); const app = express(); connectDb(); app.use(cors()); app.use(logger('dev')); app.use(cookieParser()); app.use(bodyParser.json()); app.use(expressSession({ secret: crypto.randomBytes(10).toString('hex'), resave: false, saveUninitialized: false, })); app.use(bodyParser.urlencoded({ extended: false })); app.use(express.static(publicPath)); app.use(passport.initialize()); app.use(passport.session()); app.use('/auth', auth); app.use('/api', requireAuth, api); app.get('*', (req, res) => { res.sendFile(path.join(publicPath, 'index.html')); }); app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars console.error(err.message); // eslint-disable-line no-console res.status(err.status || 500); res.send(err.message); }); createServer(app).listen(config.port, () => { console.log('Server running at http://localhost:3000'); // eslint-disable-line no-console });
/** * Implement Gatsby's SSR (Server Side Rendering) APIs in this file. * * See: https://www.gatsbyjs.org/docs/ssr-apis/ */ // You can delete this file if you're not using it
function bubbleSort(array) { codeDisplayManager.setVariable("array", "[" + array.join(", ") + "]") codeDisplayManager.setVariable("length", array.length) var n = array.length; highlightCode([0]) updateVariable("n", n.toString()); highlightCode([1]) while (n > 0) { highlightCode([2]); var newN = 0; updateVariable("newN", newN.toString()); highlightCode([3]); for (var i = 1; i < n; i++) { updateVariable("i", i.toString()); highlight(i - 1, i); highlightCode([4]); if (array[i - 1] > array[i]) { highlightCode([5]); var tmp = array[i]; updateVariable("tmp", tmp.toString()); highlightCode([6]); array[i] = array[i - 1]; updateVariable("array", "[" + array.join(", ") + "]"); array[i - 1] = tmp; swap(i, i - 1, 7); updateVariable("array", "[" + array.join(", ") + "]"); highlightCode([8]); newN = i; updateVariable("newN", newN.toString()); } clearHighlight(i-1); } n = newN; updateVariable("n", n.toString()); highlightCode([11]); markAsSorted(newN); highlightCode([1]); } highlightCode([14]); return array; }
// Lists 'use strict'; // Search `[-+*][\n ]`, returns next pos arter marker on success // or -1 on fail. function skipBulletListMarker(state, startLine) { var marker, pos, max; pos = state.bMarks[startLine] + state.tShift[startLine]; max = state.eMarks[startLine]; marker = state.src.charCodeAt(pos++); // Check bullet if (marker !== 0x2A/* * */ && marker !== 0x2D/* - */ && marker !== 0x2B/* + */) { return -1; } if (pos < max && state.src.charCodeAt(pos) !== 0x20) { // " 1.test " - is not a list item return -1; } return pos; } // Search `\d+[.)][\n ]`, returns next pos arter marker on success // or -1 on fail. function skipOrderedListMarker(state, startLine) { var ch, pos = state.bMarks[startLine] + state.tShift[startLine], max = state.eMarks[startLine]; // List marker should have at least 2 chars (digit + dot) if (pos + 1 >= max) { return -1; } ch = state.src.charCodeAt(pos++); if (ch < 0x30/* 0 */ || ch > 0x39/* 9 */) { return -1; } for (;;) { // EOL -> fail if (pos >= max) { return -1; } ch = state.src.charCodeAt(pos++); if (ch >= 0x30/* 0 */ && ch <= 0x39/* 9 */) { continue; } // found valid marker if (ch === 0x29/* ) */ || ch === 0x2e/* . */) { break; } return -1; } if (pos < max && state.src.charCodeAt(pos) !== 0x20/* space */) { // " 1.test " - is not a list item return -1; } return pos; } function markTightParagraphs(state, idx) { var i, l, level = state.level + 2; for (i = idx + 2, l = state.tokens.length - 2; i < l; i++) { if (state.tokens[i].level === level && state.tokens[i].type === 'paragraph_open') { state.tokens[i + 2].hidden = true; state.tokens[i].hidden = true; i += 2; } } } module.exports = function list(state, startLine, endLine, silent) { var nextLine, indent, oldTShift, oldIndent, oldTight, oldParentType, start, posAfterMarker, max, indentAfterMarker, markerValue, markerCharCode, isOrdered, contentStart, listTokIdx, prevEmptyEnd, listLines, itemLines, tight = true, terminatorRules, token, i, l, terminate; // Detect list type and position after marker if ((posAfterMarker = skipOrderedListMarker(state, startLine)) >= 0) { isOrdered = true; } else if ((posAfterMarker = skipBulletListMarker(state, startLine)) >= 0) { isOrdered = false; } else { return false; } // We should terminate list on style change. Remember first one to compare. markerCharCode = state.src.charCodeAt(posAfterMarker - 1); // For validation mode we can terminate immediately if (silent) { return true; } // Start list listTokIdx = state.tokens.length; if (isOrdered) { start = state.bMarks[startLine] + state.tShift[startLine]; markerValue = Number(state.src.substr(start, posAfterMarker - start - 1)); token = state.push('ordered_list_open', 'ol', 1); if (markerValue !== 1) { token.attrs = [ [ 'start', markerValue ] ]; } } else { token = state.push('bullet_list_open', 'ul', 1); } token.map = listLines = [ startLine, 0 ]; token.markup = String.fromCharCode(markerCharCode); // // Iterate list items // nextLine = startLine; prevEmptyEnd = false; terminatorRules = state.md.block.ruler.getRules('list'); while (nextLine < endLine) { contentStart = state.skipSpaces(posAfterMarker); max = state.eMarks[nextLine]; if (contentStart >= max) { // trimming space in "- \n 3" case, indent is 1 here indentAfterMarker = 1; } else { indentAfterMarker = contentStart - posAfterMarker; } // If we have more than 4 spaces, the indent is 1 // (the rest is just indented code block) if (indentAfterMarker > 4) { indentAfterMarker = 1; } // " - test" // ^^^^^ - calculating total length of this thing indent = (posAfterMarker - state.bMarks[nextLine]) + indentAfterMarker; // Run subparser & write tokens token = state.push('list_item_open', 'li', 1); token.markup = String.fromCharCode(markerCharCode); token.map = itemLines = [ startLine, 0 ]; oldIndent = state.blkIndent; oldTight = state.tight; oldTShift = state.tShift[startLine]; oldParentType = state.parentType; state.tShift[startLine] = contentStart - state.bMarks[startLine]; state.blkIndent = indent; state.tight = true; state.parentType = 'list'; state.md.block.tokenize(state, startLine, endLine, true); // If any of list item is tight, mark list as tight if (!state.tight || prevEmptyEnd) { tight = false; } // Item become loose if finish with empty line, // but we should filter last element, because it means list finish prevEmptyEnd = (state.line - startLine) > 1 && state.isEmpty(state.line - 1); state.blkIndent = oldIndent; state.tShift[startLine] = oldTShift; state.tight = oldTight; state.parentType = oldParentType; token = state.push('list_item_close', 'li', -1); token.markup = String.fromCharCode(markerCharCode); nextLine = startLine = state.line; itemLines[1] = nextLine; contentStart = state.bMarks[startLine]; if (nextLine >= endLine) { break; } if (state.isEmpty(nextLine)) { break; } // // Try to check if list is terminated or continued. // if (state.tShift[nextLine] < state.blkIndent) { break; } // fail if terminating block found terminate = false; for (i = 0, l = terminatorRules.length; i < l; i++) { if (terminatorRules[i](state, nextLine, endLine, true)) { terminate = true; break; } } if (terminate) { break; } // fail if list has another type if (isOrdered) { posAfterMarker = skipOrderedListMarker(state, nextLine); if (posAfterMarker < 0) { break; } } else { posAfterMarker = skipBulletListMarker(state, nextLine); if (posAfterMarker < 0) { break; } } if (markerCharCode !== state.src.charCodeAt(posAfterMarker - 1)) { break; } } // Finilize list if (isOrdered) { token = state.push('ordered_list_close', 'ol', -1); } else { token = state.push('bullet_list_close', 'ul', -1); } token.markup = String.fromCharCode(markerCharCode); listLines[1] = nextLine; state.line = nextLine; // mark paragraphs tight if needed if (tight) { markTightParagraphs(state, listTokIdx); } return true; };
var firebase = {} firebase.firebaseSetup = function(roomSession) { this.ref = new Firebase("https://haunted.firebaseio.com/"); this.room = this.ref.child(roomSession); this.chat = this.room.child("chat"); this.game = this.room.child("game"); this.pause = this.game.child("pause"); this.player1 = this.game.child("player1"); this.player2 = this.game.child("player2"); this.person = this.game.child("person"); this.ghost = this.game.child("ghost"); } firebase.recieveMessage = function(snapshot) { var message = snapshot.val().message; var name = message.name; var content = message.content; var output = "<div class='message'><b>" + name + ":</b> "; output += "<span>" + content + "</span>"; output += "</div>"; $("#msg-output").append(output); } firebase.preMessage = function(event) { event.preventDefault(); var name = $("#user-name").val() var content = $("#msg-input").val() $("#msg-input").val(""); firebase.sendMessage(fb, name, content); } firebase.sendMessage = function(firebase, name, content) { firebase.chat.push({ message : { name: name, content: content, timestamp: Firebase.ServerValue.TIMESTAMP } }); } firebase.sendCoordinates = function(sprite) { firebase.game.push({ message : { sprite: sprite, x_coordinates: sprite.x, y_coordinates: sprite.y, timestamp: Firebase.ServerValue.TIMESTAMP } }); }
import 'isomorphic-fetch'; import { ID_TOKEN, checkStatus, parseJSON, setIdToken, removeIdToken, decodeUserProfile } from '../utils/utils'; export const LOGIN_REQUEST = 'LOGIN_REQUEST'; export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; export const LOGIN_FAILURE = 'LOGIN_FAILURE'; export const LOGOUT_REQUEST = 'LOGOUT_REQUEST'; export const LOGOUT_SUCCESS = 'LOGOUT_SUCCESS'; export const LOGOUT_FAILURE = 'LOGOUT_FAILURE'; function loginRequest(user) { return { type: LOGIN_REQUEST, user, }; } function loginSuccess(idToken) { setIdToken(idToken); console.log(idToken) const profile = decodeUserProfile(idToken); return { type: LOGIN_SUCCESS, user: profile.user, role: profile.role, token: idToken }; } function loginFailure(user, error) { removeIdToken(); return { type: LOGIN_FAILURE, user, error, }; } export function login(user, password) { return dispatch => { dispatch(loginRequest(user)); return fetch('/admin/login', { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ user, password, }), }).then(checkStatus) .then(parseJSON) .then((json) => { const idToken = json[ID_TOKEN]; dispatch(loginSuccess(idToken)); }).catch((error) => { const response = error.response; if (response === undefined) { dispatch(loginFailure(user, error)); } else { parseJSON(response) .then((json) => { error.status = response.status; error.statusText = response.statusText; error.message = json.message; dispatch(loginFailure(user, error)); } ); } }); }; } function logoutRequest(user) { removeIdToken(); return { type: LOGOUT_REQUEST, user, }; } function logoutSuccess(user) { removeIdToken(); return { type: LOGOUT_SUCCESS, user, }; } function logoutFailure(user, error) { return { type: LOGOUT_FAILURE, user, error, }; } export function logout(user) { return dispatch => { dispatch(logoutRequest(user)); return fetch('/admin/logout', { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ user, }), }).then(checkStatus) .then(parseJSON) .then(json => dispatch(logoutSuccess(user))) .catch((error) => { const response = error.response; if (response === undefined) { dispatch(logoutFailure(user, error)); } else { parseJSON(response) .then((json) => { error.status = response.status; error.statusText = response.statusText; error.message = json.message; dispatch(logoutFailure(user, error)); }); } }); }; }
'use strict'; // Load modules var Utils = require('./utils'); // Declare internals var internals = { delimiter: '&', depth: 5, arrayLimit: 20, parameterLimit: 1000, strictNullHandling: false, plainObjects: false, allowPrototypes: false, allowDots: false }; internals.parseValues = function (str, options) { var obj = {}; var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit); for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; if (pos === -1) { obj[Utils.decode(part)] = ''; if (options.strictNullHandling) { obj[Utils.decode(part)] = null; } } else { var key = Utils.decode(part.slice(0, pos)); var val = Utils.decode(part.slice(pos + 1)); if (!Object.prototype.hasOwnProperty.call(obj, key)) { obj[key] = val; } else { obj[key] = [].concat(obj[key]).concat(val); } } } return obj; }; internals.parseObject = function (chain, val, options) { if (!chain.length) { return val; } var root = chain.shift(); var obj; if (root === '[]') { obj = []; obj = obj.concat(internals.parseObject(chain, val, options)); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; var index = parseInt(cleanRoot, 10); var indexString = '' + index; if (!isNaN(index) && root !== cleanRoot && indexString === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit)) { obj = []; obj[index] = internals.parseObject(chain, val, options); } else { obj[cleanRoot] = internals.parseObject(chain, val, options); } } return obj; }; internals.parseKeys = function (key, val, options) { if (!key) { return; } // Transform dot notation to bracket notation if (options.allowDots) { key = key.replace(/\.([^\.\[]+)/g, '[$1]'); } // The regex chunks var parent = /^([^\[\]]*)/; var child = /(\[[^\[\]]*\])/g; // Get the parent var segment = parent.exec(key); // Stash the parent if it exists var keys = []; if (segment[1]) { // If we aren't using plain objects, optionally prefix keys // that would overwrite object prototype properties if (!options.plainObjects && Object.prototype.hasOwnProperty(segment[1])) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { ++i; if (!options.plainObjects && Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) { if (!options.allowPrototypes) { continue; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return internals.parseObject(keys, val, options); }; module.exports = function (str, options) { options = options || {}; options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : internals.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit; options.parseArrays = options.parseArrays !== false; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : internals.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : internals.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : internals.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : internals.strictNullHandling; if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = internals.parseKeys(key, tempObj[key], options); obj = Utils.merge(obj, newObj, options); } return Utils.compact(obj); };
//Wrapped in an outer function to preserve global this (function (root) { var amdExports; define(['angular', 'jquery-ui'], function () { (function () { /* jQuery UI Sortable plugin wrapper @param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config */ angular.module('ui.sortable', []) .value('uiSortableConfig',{}) .directive('uiSortable', [ 'uiSortableConfig', '$log', function(uiSortableConfig, log) { return { require: '?ngModel', link: function(scope, element, attrs, ngModel) { function combineCallbacks(first,second){ if( second && (typeof second === "function") ){ return function(e,ui){ first(e,ui); second(e,ui); }; } return first; } var opts = {}; var callbacks = { receive: null, remove:null, start:null, stop:null, update:null }; var apply = function(e, ui) { if (ui.item.sortable.resort || ui.item.sortable.relocate) { scope.$apply(); } }; angular.extend(opts, uiSortableConfig); if (ngModel) { ngModel.$render = function() { element.sortable( "refresh" ); }; callbacks.start = function(e, ui) { // Save position of dragged item ui.item.sortable = { index: ui.item.index() }; }; callbacks.update = function(e, ui) { // For some reason the reference to ngModel in stop() is wrong ui.item.sortable.resort = ngModel; }; callbacks.receive = function(e, ui) { ui.item.sortable.relocate = true; // added item to array into correct position and set up flag ngModel.$modelValue.splice(ui.item.index(), 0, ui.item.sortable.moved); }; callbacks.remove = function(e, ui) { // copy data into item if (ngModel.$modelValue.length === 1) { ui.item.sortable.moved = ngModel.$modelValue.splice(0, 1)[0]; } else { ui.item.sortable.moved = ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]; } }; callbacks.stop = function(e, ui) { // digest all prepared changes if (ui.item.sortable.resort && !ui.item.sortable.relocate) { // Fetch saved and current position of dropped element var end, start; start = ui.item.sortable.index; end = ui.item.index(); // Reorder array and apply change to scope ui.item.sortable.resort.$modelValue.splice(end, 0, ui.item.sortable.resort.$modelValue.splice(start, 1)[0]); } }; scope.$watch(attrs.uiSortable, function(newVal, oldVal){ angular.forEach(newVal, function(value, key){ if( callbacks[key] ){ // wrap the callback value = combineCallbacks( callbacks[key], value ); if ( key === 'stop' ){ // call apply after stop value = combineCallbacks( value, apply ); } } element.sortable('option', key, value); }); }, true); angular.forEach(callbacks, function(value, key ){ opts[key] = combineCallbacks(value, opts[key]); }); // call apply after stop opts.stop = combineCallbacks( opts.stop, apply ); } else { log.info('ui.sortable: ngModel not provided!', element); } // Create sortable element.sortable(opts); } }; } ]); }.call(root)); return amdExports; }); }(this));
var __ = require('underscore'), Backbone = require('backbone'), is = require('is_js'), autolinker = require( 'autolinker' ); module.exports = Backbone.Model.extend({ defaults: { profile: { guid: "", vendor: false, name: "", categories: ["category 1", "category 2"], moderator: false, moderators: ["moderator 1", "moderator 2"], shipsTo: "", header_hash: "", about: "default about text", website: "", email: "", social_accounts: { twitter: { username: "", proof_url: "" }, facebook: { username: "", proof_url: "" }, instagram: { username: "", proof_url: "" }, snapchat: { username: "", proof_url: "" } }, contracts: ["ID1", "ID2", "ID3"], primary_color: "#086A9E", secondary_color: "#317DB8", text_color: "#ffffff", background_color: "#063753", pgp_key: "", nsfw: false, location: "UNITED_STATES", avatar_hash: "", handle: "", public_key: "" } }, convertColor: function(color){ //make sure color is not truncated to a 6 digit number, that will fool is.js if (color[0] != "#" || is.not.hexColor(color)) { //convert string to a number, then to a hex string color = (Number(color)).toString(16); //if the color had leading zeroes, they were cut off. Restore them. while (color.length < 6){ color = "0" + color; } color = "#" + color; } return color; }, parse: function(response) { //first check to make sure server sent data in the response. Sometimes it doesn't. if(response.profile){ //check if colors are in hex, if not convert. This assumes non-hex colors are numbers or strings of numbers. response.profile.background_color = this.convertColor(response.profile.background_color); response.profile.primary_color = this.convertColor(response.profile.primary_color); response.profile.secondary_color = this.convertColor(response.profile.secondary_color); response.profile.text_color = this.convertColor(response.profile.text_color); //if an empty social_accounts object is returned, put the defaults back into it response.profile.social_accounts.facebook = response.profile.social_accounts.facebook || {username: "", proof_url: ""}; response.profile.social_accounts.twitter = response.profile.social_accounts.twitter || {username: "", proof_url: ""}; response.profile.social_accounts.instagram = response.profile.social_accounts.instagram || {username: "", proof_url: ""}; response.profile.social_accounts.snapchat = response.profile.social_accounts.snapchat || {username: "", proof_url: ""}; //check to make sure avatar hash is valid if(response.profile.avatar_hash === "b472a266d0bd89c13706a4132ccfb16f7c3b9fcb" || response.profile.avatar_hash.length !== 40) { response.profile.avatar_hash = ""; } //check to make sure header hash is valid if(response.profile.header_hash === "b472a266d0bd89c13706a4132ccfb16f7c3b9fcb" || response.profile.header_hash.length !== 40) { response.profile.header_hash = ""; } response.profile.beenSet = !(!response.profile.avatar_hash && !response.profile.name && !response.profile.header_hash && !response.profile.handle); //if name comes back blank, set to random value if(!response.profile.name){ response.profile.name = "ob" + Math.random().toString(36).slice(2); } //if no country, set to USA if(!response.profile.location) { response.profile.location = "UNITED_STATES"; } //put a copy of the avatar outside of the profile object, so change events can be triggered for it if(response.profile.avatar_hash){ response.avatar_hash = response.profile.avatar_hash; } //change any plain text urls in the about field into links response.profile.displayAbout = autolinker.link(response.profile.about, {'twitter': false, 'hashtag': false}); //add randome number because change event is not triggered by changes inside profile response.fetched = Math.random(); } return response; } });
/* * Room Manager service * * runs proccesses to manage each room * */ var logger = new Logger('[Service Room]'); var ServiceRoom = function() { // init }; Object.defineProperty(ServiceRoom.prototype, 'processTable', { get: function() { this.memory.processTable = this.memory.processTable || {}; return this.memory.processTable; }, set: function(value) { this.memory.processTable = this.memory.processTable || {}; this.memory.processTable = value; }, }); ServiceRoom.prototype.run = function() { this.doCheckRooms(); }; ServiceRoom.prototype.doCheckRooms = function() { if (this.memory.sleepCheckRooms && this.memory.sleepCheckRooms > Game.time) return; this.memory.sleepCheckRooms = C.SERVICE_SLEEP + Game.time; for (const name in Game.rooms) { if (!this.processTable[name] || !Game.kernel.getProcessByPid(this.processTable[name]) ) { let process = Game.kernel.startProcess(this, 'managers/room', { roomName: name, }); if (!Memory.rooms[name]) Memory.rooms[name] = {}; Memory.rooms[name].pid = process.pid; this.processTable[name] = process.pid; } } }; registerProcess('services/room', ServiceRoom);
import React, { Component, PropTypes } from 'react' import classNames from 'classnames' import { META, numberToWord, getElementType, } from '../../lib' export default class FormField extends Component { static propTypes = { /** An element type to render as (string or function). */ as: PropTypes.oneOfType([ PropTypes.string, PropTypes.func, ]), children: PropTypes.node, className: PropTypes.string, label: PropTypes.string, width: PropTypes.number, } static _meta = { name: 'FormField', parent: 'Form', type: META.TYPES.COLLECTION, } render() { const classes = classNames( this.props.width && `${numberToWord(this.props.width)} wide`, this.props.className, 'field' ) const ElementType = getElementType(FormField, this.props) return ( <ElementType {...this.props} className={classes}> {this.props.label && <label>{this.props.label}</label>} {this.props.children} </ElementType> ) } }
import cx from 'classnames' import React, { PropTypes } from 'react' import { customPropTypes, getElementType, getUnhandledProps, META, SUI, useKeyOnly, useWidthProp, } from '../../lib' import Card from './Card' function CardGroup(props) { const { className, children, doubling, items, itemsPerRow, stackable } = props const classes = cx('ui', useWidthProp(itemsPerRow), useKeyOnly(doubling, 'doubling'), useKeyOnly(stackable, 'stackable'), className, 'cards', ) const rest = getUnhandledProps(CardGroup, props) const ElementType = getElementType(CardGroup, props) const content = !items ? children : items.map(item => { const key = item.key || [item.header, item.description].join('-') return <Card key={key} {...item} /> }) return <ElementType {...rest} className={classes}>{content}</ElementType> } CardGroup._meta = { name: 'CardGroup', parent: 'Card', props: { itemsPerRow: SUI.WIDTHS, }, type: META.TYPES.VIEW, } CardGroup.propTypes = { /** An element type to render as (string or function). */ as: PropTypes.oneOfType([ PropTypes.string, PropTypes.func, ]), /** A group of Card components. Mutually exclusive with items. */ children: customPropTypes.every([ customPropTypes.disallow(['items']), PropTypes.node, ]), /** Classes that will be added to the CardGroup className */ className: PropTypes.string, /** A group of cards can double its column width for mobile */ doubling: PropTypes.bool, /** Shorthand prop for children. Mutually exclusive with children. */ items: customPropTypes.every([ customPropTypes.disallow(['children']), PropTypes.arrayOf(PropTypes.shape({ description: PropTypes.node, meta: PropTypes.node, key: PropTypes.string, header: PropTypes.node, })), ]), /** A group of cards can set how many cards should exist in a row */ itemsPerRow: PropTypes.oneOf(CardGroup._meta.props.itemsPerRow), /** A group of cards can automatically stack rows to a single columns on mobile devices */ stackable: PropTypes.bool, } export default CardGroup
import React from 'react'; import Grid from '@material-ui/core/Grid'; import Typography from '@material-ui/core/Typography'; import { makeStyles, useTheme, rgbToHex } from '@material-ui/core/styles'; const useStyles = makeStyles((theme) => ({ root: { width: '100%', }, group: { marginTop: theme.spacing(3), }, color: { display: 'flex', alignItems: 'center', '& div:first-of-type': { width: theme.spacing(6), height: theme.spacing(6), marginRight: theme.spacing(1), borderRadius: theme.shape.borderRadius, }, }, })); export default function Intentions() { const classes = useStyles(); const theme = useTheme(); const item = (color, name) => ( <Grid item xs={12} sm={6} md={4} className={classes.color}> <div style={{ backgroundColor: color }} /> <div> <Typography variant="body2">{name}</Typography> <Typography variant="body2" color="textSecondary"> {rgbToHex(color)} </Typography> </div> </Grid> ); return ( <div className={classes.root}> <Typography gutterBottom className={classes.group}> Primary </Typography> <Grid container spacing={2}> {item(theme.palette.primary.light, 'palette.primary.light')} {item(theme.palette.primary.main, 'palette.primary.main')} {item(theme.palette.primary.dark, 'palette.primary.dark')} </Grid> <Typography gutterBottom className={classes.group}> Secondary </Typography> <Grid container spacing={2}> {item(theme.palette.secondary.light, 'palette.secondary.light')} {item(theme.palette.secondary.main, 'palette.secondary.main')} {item(theme.palette.secondary.dark, 'palette.secondary.dark')} </Grid> <Typography gutterBottom className={classes.group}> Error </Typography> <Grid container spacing={2}> {item(theme.palette.error.light, 'palette.error.light')} {item(theme.palette.error.main, 'palette.error.main')} {item(theme.palette.error.dark, 'palette.error.dark')} </Grid> <Typography gutterBottom className={classes.group}> Warning </Typography> <Grid container spacing={2}> {item(theme.palette.warning.light, 'palette.warning.light')} {item(theme.palette.warning.main, 'palette.warning.main')} {item(theme.palette.warning.dark, 'palette.warning.dark')} </Grid> <Typography gutterBottom className={classes.group}> Info </Typography> <Grid container spacing={2}> {item(theme.palette.info.light, 'palette.info.light')} {item(theme.palette.info.main, 'palette.info.main')} {item(theme.palette.info.dark, 'palette.info.dark')} </Grid> <Typography gutterBottom className={classes.group}> Success </Typography> <Grid container spacing={2}> {item(theme.palette.success.light, 'palette.success.light')} {item(theme.palette.success.main, 'palette.success.main')} {item(theme.palette.success.dark, 'palette.success.dark')} </Grid> </div> ); }
window.addEventListener("load",initAll,false); var xhr = false; function initAll(){ document.getElementById("makeTextRequest").addEventListener("click",getNewFile,false); document.getElementById("makeXMLRequest").addEventListener("click",getNewFile,false); } //当加载页面时,会调用initAll()函数。在这里,我们设置两个click处理 //程序,当用户点击这两个链接是触发getNewFile() function getNewFile(evt){ makeRequest(this.href); evt.preventDefault(); } function makeRequest(url){ if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); } else{ if(window.ActiveXObject){ try{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ } } } if(xhr){ xhr.addEventListener("readystatechange",showContents,false); xhr.open("GET",url,true); xhr.send(null); } //调用open()并且传递3个参数:一个HTTP请求方法、服务器上一个文件的URL //和一个布尔值,这个布尔值告诉服务器请求是否异步。 else{ document.getElmentById("updateArea").innerHTML="Sorry,but I couldn't create an XMLHttpRequest"; } } function showContents(){ if(xhr.readyState ==4){ if(xhr.status ==200){ if(xhr.responseXML && xhr.responseXML.childNodes.length>0){ var outMsg = getText(xhr.responseXML.getElementsByTagName("choices")[0]); } else{ var outMsg = xhr.responseText; } } else{ var outMsg ="There was problem with the request "+xhr.status; } document.getElementById("updateArea").innerHTML = outMsg; } function getText(inVal){ if(inVal.textContent){ return inVal.textContent; } return inVal.text; } }
var script = document.createElement('script'); script.src = 'http://code.jquery.com/jquery-1.11.0.min.js'; script.onload = function() { sortBookmarks(); } document.body.appendChild(script); function sortBookmarks() { var bookmarks = $('a'); $('dl').remove(); bookmarks.sort(function(a, b) { var bookmarkOneAdded = $(a).attr('add_date'); var bookmarkTwoAdded = $(b).attr('add_date'); return bookmarkTwoAdded - bookmarkOneAdded; }); var previousBookmarkDate = new Date(0); var ul = $('<ul>'); $.each(bookmarks, function(index, bookmark) { var currentBookmarkDateInSeconds = $(bookmark).attr('add_date'); var currentBookmarkDate = new Date(0); currentBookmarkDate.setUTCSeconds(currentBookmarkDateInSeconds); if (currentBookmarkDate.toDateString() != previousBookmarkDate.toDateString()) { var heading = $('<h2>'); heading.text(currentBookmarkDate.toDateString()); var li = $('<li>'); li.append(heading); ul.append(li); }; var img = $('<img>'); img.attr('src', $(bookmark).attr('icon')); var li = $('<li>'); li.append(img); li.append(bookmark); ul.append(li); $(bookmark).removeAttr('icon'); previousBookmarkDate = currentBookmarkDate; }); $('body').append(ul); };
#!/usr/bin/env node var path = require('path'); var adventure = require('workshopper-adventure/adventure'); // Create the adventure object var adv = adventure({ name: 'learnnodeserver', title: 'Learn To Program A Node Server', appDir: __dirname, languages: ['en'] }); // Create the problem objects and add to the adventure var problems = require('./exercise/menu.json'); problems.forEach(function (problem) { var p = problem.toLowerCase().replace(/\s/g, '-'); var dir = path.join(__dirname, 'exercise', p); adv.add(problem, function () { return require(dir); }); }); // Run the adventure with its arguments adv.execute(process.argv.slice(2));
/* * SearchView * * Defines a view that allows a quick search of existing users (via filtering) * */ define( [ 'App', 'marionette', 'views/MemberInfoCollectionView','collections/MemberInfoCollection', 'handlebars', 'text!templates/search.html'], function( App, Marionette, MemberInfoCollectionView, MemberInfoCollection, Handlebars, template) { var SearchView = Marionette.ItemView.extend( { template: Handlebars.compile(template), itemsPerPage: 25, ui : { 'searchword' : 'form #search-term' }, events: { 'submit @ui.searchword' : 'onSearch', 'keyup @ui.searchword' : 'onSearch' }, initialize: function(){ _.bindAll(this); //created our filtered info (by default map it to the memberInfo item) this.filteredMemberInfo = App.memberInfo.clone(this.itemsPerPage); //anytime the App.memberInfo is changed; update our filtered list. this.listenTo(App.memberInfo, 'reset', this.filterResults); this.listenTo(App.memberInfo, 'add', this.filterResults); this.listenTo(App.memberInfo, 'change', this.filterResults); }, /* * onRender - el is set; show the memberinfo docllection view */ onRender: function(){ //Create a sub view - if it exists; destroy and re-create if (this.searchResultsView) { this.searchResultsView.destroy(); } this.searchResultsView = new MemberInfoCollectionView({ el: this.$('#search-results'), collection: this.filteredMemberInfo }); this.searchResultsView.render(); }, /* * Called to make a search based on text input. */ onSearch : function(evt){ evt.preventDefault(); this.filterResults(); }, /* * Filters results from App.memberInfo - updates this.filtereMemberInfo * with items from our 'search' form. */ filterResults:function(){ var searchResults = App.memberInfo.filter(this._compareMemberInfoToSearchResults); //Lets slice out the first few this.filteredMemberInfo.reset(searchResults.slice(0,this.itemsPerPage)); }, /* * Called by the search/filter function to comapre an item in the colleciton * to the search terms in the search form. */ _compareMemberInfoToSearchResults:function(item){ //fetch the current value in the text box var searchword = this.ui.searchword.val(); var indexof; if (searchword === "") { //empty form will (by default) return all items return true; } //do an uppercase comparison indexof = item.getFullName().toUpperCase().indexOf(searchword.toUpperCase()); return indexof > -1; } }); return SearchView; });
$(function() { $(".password-form").submit(function() { var password = $("input[name='password']").val(); var confirmation = $("input[name='confirm']").val(); if (!passwordValid(password)) { showErrors(["Password must be at least 6 characters long"]); return false; } if (!passwordConfirmed(password, confirmation)) { showErrors(["Password and confirmation did not match"]); return false; } return true; }); function showErrors(errors) { setTimeout(function() { var errorHtml = $(jade.render('server/views/partials/errors.jade', { errors: errors })); $('#errors').html(errorHtml); }, 0); } function passwordValid(password) { return password && password.length > 5; } function passwordConfirmed(password, confirmation) { return password === confirmation; } });
/** * Created by Rusak Oleg on 23.01.2016. */ (function () { 'use strict'; var ready = function ready(fn) { // Sanity check if (typeof fn !== 'function') return; // If document is already loaded, run method if (document.readyState === 'complete') { return fn(); } // Otherwise, wait until document is loaded document.addEventListener('DOMContentLoaded', fn, false); }; ready(function () { //Init var pTag = new pTags({ selector: "input.tags-element" }); pTag.value = 'CSS,HTML'; pTag.focus(); //Show inner tag value var tagOutput = document.querySelector('.tags-output'); setInterval(function () { tagOutput.textContent = pTag.value; }, 1000); var indexLang = ['Assembler', 'Go', 'Java', 'JavaScript', 'Python', 'C++', 'CSS', 'HTML']; var my_autoComplete = new autoComplete({ selector: 'input.handler-tag', archor: '.tag', minChars: 2, cache: false, source: function source(term, suggest) { term = term.toLowerCase(); var choices = indexLang; var matches = []; var listInputTag = pTag.value.split(';').map(function (name) { return name.toLowerCase(); }); for (var i = 0; i < choices.length; i++) { var name = choices[i]; if (listInputTag.indexOf(name.toLowerCase()) == -1 && ~name.toLowerCase().indexOf(term)) { matches.push(name); } } suggest(matches); } }); }); })();
game.SpendGold = Object.extend({ init: function(x, y, settings) { this.now = new Date().getTime(); this.lastBuy = new Date().getTime(); this.paused = false; this.alwaysUpdate = true; this.updateWhenPaused = true; this.buying = false; }, update: function() { this.now = new Date().getTime(); if(me.input.isKeyPressed("buy") && this.now-this.lastBuy >=1000) { this.lastBuy = this.now; if(!this.buying) { this.startBuying(); }else { this.stopBuying(); } } this.checkBuyKeys(); return true; }, startBuying: function() { this.buying = true; me.state.pause(me.state.PLAY); game.data.pausePos = me.game.viewport.localToWorld(0, 0); game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen')); game.data.buyscreen.updateWhenPaused = true; game.data.buyscreen.setOpacity(0.8); me.game.world.addChild(game.data.buyscreen, 34); game.data.player.body.setVelocity(0, 0); me.input.bindKey(me.input.KEY.F1, "F1", true); me.input.bindKey(me.input.KEY.F2, "F2", true); me.input.bindKey(me.input.KEY.F3, "F3", true); me.input.bindKey(me.input.KEY.F4, "F4", true); me.input.bindKey(me.input.KEY.F5, "F5", true); me.input.bindKey(me.input.KEY.F6, "F6", true); this.setBuyText(); }, setBuyText: function() { // this is for the text and font of the title screen to show game.data.buytext = new (me.Renderable.extend({ init: function() { // call to the super class this._super(me.Renderable, 'init', [game.data.pausePos.x, game.data.pausePos.y, 300, 50]); // my font this.font = new me.Font("Chiller", 50, "white"); this.updateWhenPaused = true; this.alwaysUpdate = true; }, // to try and draw on the screen draw: function(renderer) { this.font.draw(renderer.getContext(), "PRESS F1-F6 TO BUY, B TO EXIT. Current Gold: " + game.data.gold, this.pos.x, this.pos.y); this.font.draw(renderer.getContext(), "Skill 1: Increase Damage. Current Level: " + game.data.skill1 + " Cost: " + ((game.data.skill1+1)*10),this.pos.x, this.pos.y + 40); this.font.draw(renderer.getContext(), "Skill2: Run Faster! Current Level: " + game.data.skill2 + " Cost: " + ((game.data.skill2+1)*10), this.pos.x, this.pos.y + 80); this.font.draw(renderer.getContext(), "Skill 3: Increase Health. Current Level: " + game.data.skill3 + " Cost: " + ((game.data.skill3+1)*10), this.pos.x, this.pos.y + 120); this.font.draw(renderer.getContext(), "Q Ability: Speed Burst. Current Level: " + game.data.ability1 + " Cost: " + ((game.data.ability1+1)*10), this.pos.x, this.pos.y + 160); this.font.draw(renderer.getContext(), "W Ability: Eat Your Creep For Health: " + game.data.ability2 + " Cost: " + ((game.data.ability2+1)*10), this.pos.x, this.pos.y + 200); this.font.draw(renderer.getContext(), "E Ability: Throw Your Spear: " + game.data.ability3 + " Cost: " + ((game.data.ability3+1)*10), this.pos.x, this.pos.y + 240); } })); me.game.world.addChild(game.data.buytext, 35); }, stopBuying: function() { this.buying = false; me.state.resume(me.state.PLAY); game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20); me.game.world.removeChild(game.data.buyscreen); me.input.unbindKey(me.input.KEY.F1, "F1", true); me.input.unbindKey(me.input.KEY.F2, "F2", true); me.input.unbindKey(me.input.KEY.F3, "F3", true); me.input.unbindKey(me.input.KEY.F4, "F4", true); me.input.unbindKey(me.input.KEY.F5, "F5", true); me.input.unbindKey(me.input.KEY.F6, "F6", true); me.game.world.removeChild(game.data.buytext); }, checkBuyKeys: function() { if(me.input.isKeyPressed("F1")) { if(this.checkCost(1)) { this.makePurchase(1); } }else if(me.input.isKeyPressed("F2")) { if(this.checkCost(2)) { this.makePurchase(2); } }else if(me.input.isKeyPressed("F3")) { if(this.checkCost(3)) { this.makePurchase(3); } }else if(me.input.isKeyPressed("F4")) { if(this.checkCost(4)) { this.makePurchase(4); } }else if(me.input.isKeyPressed("F5")) { if(this.checkCost(5)) { this.makePurchase(5); } }else if(me.input.isKeyPressed("F6")) { if(this.checkCost(6)) { this.makePurchase(6); } } }, checkCost: function(skill) { if(skill===1 && (game.data.gold >= ((game.data.skill1+1)+10))) { return true; }else if(skill===2 && (game.data.gold >= ((game.data.skill2+1)+10))) { return true; }else if(skill===3 && (game.data.gold >= ((game.data.skill3+1)+10))) { return true; }else if(skill===4 && (game.data.gold >= ((game.data.ability1+1)+10))) { return true; }else if(skill===5 && (game.data.gold >= ((game.data.ability2+1)+10))) { return true; }else if(skill===6 && (game.data.gold >= ((game.data.ability3+1)+10))) { return true; }else{ return false; } }, makePurchase: function(skill) { if(skill === 1) { game.data.gold -= ((game.data.skill1 +1)* 10); game.data.skill1 += 1; game.data.playerAttack += 1; }else if(skill ===2) { game.data.gold -= ((game.data.skill2 +1)* 10); game.data.skill2 += 1; }else if(skill ===3) { game.data.gold -= ((game.data.skill3 +1)* 10); game.data.skill3 += 1; }else if(skill ===4) { game.data.gold -= ((game.data.ability1 +1)* 10); game.data.ability1 += 1; }else if(skill ===5) { game.data.gold -= ((game.data.ability2 +1)* 10); game.data.ability2 += 1; }else if(skill ===6) { game.data.gold -= ((game.data.ability3 +1)* 10); game.data.ability3 += 1; } } });
var express = require('express') var bodyParser = require('body-parser') var jsonfile = require('jsonfile') var parse_basic_auth = require('basic-auth') var config = require("./data/config") DATAFILE = "./data/data.json" var data = jsonfile.readFileSync(DATAFILE); var app = express(); app.use(express.static('static')); app.use(bodyParser.json()) app.use((req, res, next) => { let user = parse_basic_auth(req); if (!user || !config.auth(user.name, user.pass)) { res.set('WWW-Authenticate', 'Basic realm="GSoC"'); return res.status(401).send(); } req.user = user.name; return next(); }); app.get('/proposals.json', (req, res) => { res.sendFile(__dirname + "/data/proposals.json"); }); app.get('/data.json', (req, res) => { res.send(data); }); app.get('/user.json', (req, res) => { /* a bit of a hack: reflect the basic auth username back */ res.send({user: req.user}); }); app.post('/data/:proposalId', function(req, res) { var proposalId = req.params.proposalId; var action = req.body; if(!proposalId || !action){ throw "invalid request"; } action.timestamp = Date.now(); action.user = req.user; console.log( req.connection.remoteAddress, `Update proposal ${proposalId}:`, action ); data[proposalId] = data[proposalId] || []; data[proposalId].push(action); jsonfile.writeFile(DATAFILE, data, {spaces: 2}, (err) => { if(err) { console.error(err) } }); res.send(data); }); app.listen(config.port, config.host, () => { console.log(`App listening on ${config.host || ''}:${config.port}!`); });
(function() { var app, boot, loopback; loopback = require('loopback'); boot = require('loopback-boot'); app = module.exports = loopback(); app.start = function() { return app.listen(function() { app.emit('started'); console.log('Web server listening at: %s', app.get('url')); }); }; boot(app, __dirname, function(err) { if (err) { throw err; } if (require.main === module) { app.start(); } }); }).call(this);
/** * @param {string} s * @param {set<string>} wordDict * Note: wordDict is a Set object, see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set * @return {string[]} */ var wordBreak = function (s, wordDict) { const map = new Map(); const search = (s) => { //take from memory if (map.has(s)) return map.get(s); const result = []; //a whole string is a word if (wordDict.has(s)) { result.push(s); } for (let i = 1; i < s.length; ++i) { const word = s.substr(i); if (wordDict.has(word)) { result.push(...search(s.substr(0, i)).map(str => str + " " + word)); } } //memorize map.set(s, result); return result; }; return search(s); };
import {createStore, applyMiddleware, compose} from 'redux'; import createSagaMiddleware from 'redux-saga'; import {syncHistoryWithStore} from 'react-router-redux'; import {hashHistory} from 'react-router'; import thunk from 'redux-thunk'; import rootReducer from './redux/reducers'; import rootSaga from './sagas'; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const sagaMiddleware = createSagaMiddleware(); const middleware = [sagaMiddleware, thunk]; const store = createStore( rootReducer, composeEnhancers( applyMiddleware(...middleware), ), ); sagaMiddleware.run(rootSaga); // export const history = syncHistoryWithStore(hashHistory, store); export default store;
version https://git-lfs.github.com/spec/v1 oid sha256:28a6ce2387ef263cd1c9b18aa919ac9f8a019fbe849d580b4106841e80c5aa9e size 21351
// flow-typed signature: e3833c7259bc64e06f82a5fefab6b344 // flow-typed version: <<STUB>>/lien_v^2.3.0/flow_v0.44.2 /** * This is an autogenerated libdef stub for: * * 'lien' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'lien' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'lien/example/index' { declare module.exports: any; } declare module 'lien/example/login' { declare module.exports: any; } declare module 'lien/example/secure' { declare module.exports: any; } declare module 'lien/lib/index' { declare module.exports: any; } declare module 'lien/lib/to-buffer' { declare module.exports: any; } declare module 'lien/test/index' { declare module.exports: any; } // Filename aliases declare module 'lien/example/index.js' { declare module.exports: $Exports<'lien/example/index'>; } declare module 'lien/example/login.js' { declare module.exports: $Exports<'lien/example/login'>; } declare module 'lien/example/secure.js' { declare module.exports: $Exports<'lien/example/secure'>; } declare module 'lien/lib/index.js' { declare module.exports: $Exports<'lien/lib/index'>; } declare module 'lien/lib/to-buffer.js' { declare module.exports: $Exports<'lien/lib/to-buffer'>; } declare module 'lien/test/index.js' { declare module.exports: $Exports<'lien/test/index'>; }
var default_options = { negativerisk_maxprice: 97, negativerisk_refresh: 10, negativerisk_detailed: false, negativerisk_yesrisk: false, negativerisk_great: 5 }; function update_ui() { var maxprice = document.getElementById('maxprice'); var maxpriceDisp = document.getElementById('maxpriceDisplay'); var refresh = document.getElementById('refresh'); var refreshDisp = document.getElementById('refreshDisplay'); var great = document.getElementById('great'); var greatDisp = document.getElementById('greatDisplay'); var detailed = document.getElementById('detailed'); var yesrisk = document.getElementById('yesrisk'); console.log('update_ui: maxprice=' + maxprice.value); console.log('update_ui: refresh=' + refresh.value); console.log('update_ui: great=' + great.value); console.log('update_ui: detailed=' + detailed.checked); console.log('update_ui: detailed=' + yesrisk.checked); maxpriceDisp.innerHTML = maxprice.value; refreshDisp.innerHTML = refresh.value; greatDisp.innerHTML = great.value; document.getElementById('status').innerHTML = ''; } function restore_options() { console.log('restore_options()'); chrome.storage.sync.get(default_options || {}, function(options) { document.getElementById('maxprice').value = options.negativerisk_maxprice; document.getElementById('refresh').value = options.negativerisk_refresh; document.getElementById('great').value = options.negativerisk_great; document.getElementById('detailed').checked = options.negativerisk_detailed; document.getElementById('yesrisk').checked = options.negativerisk_yesrisk; console.log('restore_options: maxprice=' + options.negativerisk_maxprice); console.log('restore_options: refresh=' + options.negativerisk_refresh); console.log('restore_options: great=' + options.negativerisk_great); console.log('restore_options: detailed=' + options.negativerisk_detailed); console.log('restore_options: yesrisk=' + options.negativerisk_yesrisk); update_ui(); }); } function save_options(quit) { if (quit === undefined) { quit = true; } var maxprice = document.getElementById('maxprice').value; var refreshTime = document.getElementById('refresh').value; var great = document.getElementById('great').value; var detailed = document.getElementById('detailed').checked; var yesrisk = document.getElementById('yesrisk').checked; console.log('save_options: maxprice=' + maxprice); console.log('save_options: refresh=' + refresh); console.log('save_options: great=' + great); console.log('save_options: detailed=' + detailed); console.log('save_options: yesrisk=' + yesrisk); chrome.storage.sync.set({ negativerisk_maxprice: parseInt(maxprice, 10), negativerisk_refresh: parseInt(refreshTime, 10), negativerisk_great: parseInt(great, 10), negativerisk_detailed: !!detailed, negativerisk_yesrisk: !!yesrisk }, function() { console.log('save_options: complete'); if (quit) { window.close(); } update_ui(); document.getElementById('status').innerHTML = 'Saved.'; }); } function reset_options() { document.getElementById('maxprice').value = default_options.negativerisk_maxprice; document.getElementById('refresh').value = default_options.negativerisk_refresh; document.getElementById('great').value = default_options.negativerisk_great; document.getElementById('detailed').checked = default_options.negativerisk_detailed; document.getElementById('yesrisk').checked = default_options.negativerisk_yesrisk; save_options(false); } document.addEventListener('DOMContentLoaded', function() { console.log('DOM content loaded.'); document.getElementById('save').addEventListener('click', save_options); document.getElementById('reset').addEventListener('click', reset_options); document.getElementById('maxprice').addEventListener('change', update_ui); document.getElementById('maxprice').addEventListener('input', update_ui); document.getElementById('refresh').addEventListener('change', update_ui); document.getElementById('refresh').addEventListener('input', update_ui); document.getElementById('great').addEventListener('change', update_ui); document.getElementById('great').addEventListener('input', update_ui); restore_options(); });
var fs = require('fs') var contents = fs.readFileSync(process.argv[2], 'utf8') var lines = contents.split('\n').length - 1 console.log(lines)
'use strict'; const Transform = require('stream').Transform; const util = require('util'); function document(options, specification, executeOnRead) { if (!(this instanceof document)) { var dfInstance = new document(options, specification, executeOnRead); dfInstance.dataSpecification = specification; if (!!executeOnRead) dfInstance.on('readable', executeOnRead); return dfInstance; } Transform.call(this, options); } util.inherits(document, Transform); document.prototype._transform = function (chunk, encoding, done) { this.push(chunk); done(); }; document.prototype._flush = function (done) { done(); }; module.exports = document;
/** * @author Larry Burks * daily.js */ $(document).ready(function() { // global variables var houseId = 0; var chart = null; var today, setDay, chartDay; // setDay includes hour to highlight in day chart var validDateRanges = []; // for base data (0-1) and circuit data (2-3) var metaData = []; // defines data ranges, lables, mins and maxs var dayData = []; // only used in calendar var calPerc = []; // only used in calendar var currentOption; // currently selected data series var monthFile; var dayFile; // optArr used to determine which color and legend to use for each data series var optArr = Array(null,"o","g","b","b","r","r","b","b","b","b","b","b","b","b"); // setup color array for calendar heatmap var colors = { "o": Array( new Color('RGB',255,248,232), new Color('RGB',162,117,0)), "g": Array( new Color('RGB',232,255,209), new Color('RGB',73,142,0)), "b": Array( new Color('RGB',242,244,255), new Color('RGB',0,20,126)), "r": Array( new Color('RGB',252,235,235), new Color('RGB',149,0,0)) }; // set main navigation hadler $("select#slice,select#dice").change(function(event) { var yr = parseInt( $("select#slice").val() ); today.set({ 'year' : yr }); currentOption = $("select#dice").val(); var params = "?date=" + today.toString('yyyy-MM-dd') + "&option=" + currentOption; if ( currentOption == 19 ) { // goto Interactive Bae Temp page window.location.assign( "interactive_base_temp.html" + params ); } else if ( currentOption > 14 ) { // goto Monthly page window.location.assign( "monthly.html" + params ); } else { redrawCalendar(event); } }); if (currentOption = $.url().param("option")) { currentOption = parseInt(currentOption); $("option").each( function() { this.value == currentOption ? $(this).prop('selected', true) : $(this).prop('selected', false ); }); } else { currentOption = 1; } // set selector if arrived from monthly series page $("select#dice").each(function() { ( $(this).val() == currentOption ) ? $(this).prop('selected', true) : $(this).prop('selected', false); }); setupCalendar(); // integrate with redraw at some point in future // add functionality to back and forward arrows $("<span id='getPrevMonth'><a href='\#'>&#9664;<\/a><\/span>").replaceAll('span#getPrevMonth'); $("span#getPrevMonth").click(function(event) { today.add({ 'months' : -1 }); $('select#slice option[value=' + today.getFullYear() + ']').prop('selected', true); redrawCalendar(event); }); $("<span id='getNextMonth'><a href='\#'>&#9654;<\/a><\/span>").replaceAll('span#getNextMonth'); $("span#getNextMonth").click(function(event) { today.add({ 'months' : 1 }); $('select#slice option[value=' + today.getFullYear() + ']').prop('selected', true); redrawCalendar(event); }); // get initializing variables $.get('get_daily_metadata.php?house='+houseId, function(data) { var lines = data.split('\n'); // splits the file into lines $.each(lines, function(lineNo, line) { var items = line.split(','); // splits the line into items if (items.length == 1) return false; if (lineNo == 0) { for (i=0; i<items.length; i++) { dt = items[i].split('-'); // split date into parts validDateRanges[i] = Date.parse(items[i]); } } else { // read in the limits metaData[0] = []; for (i=0; i<items.length; i++) { metaData[0][i] = parseFloat(items[i]); } } }); metaData[1] = Array("kWh","kWh","kWh","&deg;F","&deg;F","HDD","kWh","kWh","kWh","kWh","kWh","kWh","kWh","kWh"); // if udate (date param in url) then use as today else use last valid month if (udate = $.url().param("date")) { var params = udate.split('-'); if (params.length < 3) params.push(1); setDay = new Date(params[0], params[1]-1, params[2]); today = new Date(setDay); } else { today = new Date(validDateRanges[1].getFullYear(), validDateRanges[1].getMonth(), 1); // last and most recent month of data } utime = $.url().param("time") ? $.url().param("time") : null; // temporary solution for year selector yrStart = validDateRanges[0].getFullYear(); //console.log('start = ' + yrStart); yrEnd = validDateRanges[1].getFullYear(); //console.log('start = ' + yrEnd); for (i=yrStart; i < yrEnd+1; i++) { selected = (i == today.getFullYear()) ? "selected='selected'" : '' ; $("select#slice").append("<option " + selected + " value='" + i + "'>" + i + "</option>"); } // compose strings for first loads monthFile = getMonthFilename( today ); dayFile = getDayFilename( today ); // load calendar data getCalendarData(); }); // read month day data function getCalendarData() { dayData.length = 0; $.get(monthFile, function(data) { // Split the lines var lines = data.split('\n'); // splits the file into lines // initialize arrays metaData[2] = []; // min array metaData[3] = []; // max array for(i=0; i<15; i++) { //dayData[i] = []; metaData[2][i] = 10000; // min starter value metaData[3][i] = -10000; // max starter value } // reversed for solar metaData[2][2] = -10000; // min starter value metaData[3][2] = 10000; // max starter value var offset = 1; // ensures array is 1 based, to match days of month // Iterate over the lines and add series name or data $.each(lines, function(lineNo, line) { var items = line.split(','); // splits the lines into items var dt = items[0].split('/'); // splits the date item dayData[lineNo+offset] = []; calPerc[lineNo+offset] = []; dayData[lineNo+offset][0] = new Date(dt[2], dt[0], dt[1]); // creates a date for (i=1; i<items.length; i++) { dayData[lineNo+offset][i] = parseFloat(items[i]); // set data if ( i==2 ) { // solar is reversed if (dayData[lineNo+offset][i] > metaData[2][i]) metaData[2][i] = dayData[lineNo+offset][i]; // set min if (dayData[lineNo+offset][i] < metaData[3][i]) metaData[3][i] = dayData[lineNo+offset][i]; // set max } else { if (dayData[lineNo+offset][i] < metaData[2][i]) metaData[2][i] = dayData[lineNo+offset][i]; // set min if (dayData[lineNo+offset][i] > metaData[3][i]) metaData[3][i] = dayData[lineNo+offset][i]; // set max } } }); // end each if (chart == null) getDayData(); // calc range var range = []; for (i=1; i<dayData.length; i++) { range[i] = []; for (j=1; j<dayData[i].length; j++) { range[i][j] = (j==1) ? metaData[3][j] + Math.abs(metaData[2][j]): metaData[3][j] - metaData[2][j]; } } // calc percentage for (i=1; i<dayData.length; i++) { calPerc[i] = []; for (j=1; j<dayData[i].length; j++) { calPerc[i][j] = (j==2) ? 100 + Math.round( ((dayData[i][j] + range[i][j]) / range[i][j] - ((metaData[3][j] + range[i][j]) / range[i][j])) * 100 ): Math.round(((dayData[i][j] + range[i][j]) / range[i][j] - ((metaData[2][j] + range[i][j]) / range[i][j])) * 100); } } range = null; // call updater update( currentOption ); }); // end get } // update calendar function update( v ) { var dim = Date.getDaysInMonth( today.getFullYear(), today.getMonth() ); var startDay = getStartDay( today ); var dayCount = 1; // determine whether to show previous month link /* if( today.isAfter( validDateRanges[0] ) ) { $("<span id='getPrevMonth'><a href='\#'>&#9664;<\/a><\/span>").replaceAll('span#getPrevMonth'); $("span#getPrevMonth").click(function(event) { today.add({ 'months' : -1 }); $('select#slice option[value=' + today.getFullYear() + ']').prop('selected', true); redrawCalendar(event); }); } else { $("<span id='getPrevMonth'><\/span>").replaceAll('span#getPrevMonth'); } // determine whether to show next month link if( today.isBefore( validDateRanges[1] ) ) { $("<span id='getNextMonth'><a href='\#'>&#9654;<\/a><\/span>").replaceAll('span#getNextMonth'); $("span#getNextMonth").click(function(event) { today.add({ 'months' : 1 }); $('select#slice option[value=' + today.getFullYear() + ']').prop('selected', true); redrawCalendar(event); }); } else { $("<span id='getNextMonth'><\/span>").replaceAll('span#getNextMonth'); } */ // update month and year $("<span id='monthyear'>" + today.getMonthName() + " " + today.getFullYear() + "<\/span>").replaceAll('span#monthyear'); // remove all content and calDay classes $('<td><\/td>').replaceAll('td'); // rebuild content and classes $('td').each( function(index, domEle) { if ( (index >= startDay) && (dayCount <= dim) ) { if ( dayData.length > 3 ) { // replace text and add calDay class if ( isNaN(dayData[dayCount][v]) ) { $(domEle) .append(dayCount) .addClass('no-data calday'); } else { c = transition3(calPerc[dayCount][v], 100, colors[optArr[v]][0], colors[optArr[v]][1]); $(domEle) .append(dayCount) .addClass('calday') .attr('title', dayData[dayCount][v] + ' ' + metaData[1][v]) .attr('style', 'background: rgb(' + Math.round(c.r) + ',' + Math.round(c.g) + ',' + Math.round(c.b) + ')'); } // show border around day that is currently shown in chart if ( (today.getDate() == dayCount) && (today.getMonth() == chartDay.getMonth()) && (today.getFullYear() == chartDay.getFullYear()) ) { $(domEle).addClass("selected"); } $(domEle).hover(function() { $(this).addClass("hover"); },function() { $(this).removeClass("hover"); }); $(domEle).click(function(event) { $('td').removeClass("selected"); $(this).addClass("selected"); today.setDate( this.textContent ); dayFile = getDayFilename( today ); getDayData(); }); } else { $(domEle) .append(dayCount) .addClass('no-data calday'); } dayCount++; } }); $("img#legend-range").attr({src: optArr[v] + ".png" }); $("#low-range").replaceWith("<span id='low-range'>" + metaData[2][v] + " " + metaData[1][v-1] + "<\/span>"); $("#high-range").replaceWith("<span id='high-range'>" + metaData[3][v] + " " + metaData[1][v-1] + "<\/span>"); // show circuit level data if available if( today.isAfter( validDateRanges[2] ) && today.isBefore( validDateRanges[3] ) ) { $("optgroup#circuits option").prop('disabled', false); } else { $("optgroup#circuits option").prop('disabled', true); } } function redrawCalendar(event) { monthFile = getMonthFilename( today ); getCalendarData(); event.preventDefault(); } function getDayData() { if (chart != null) chart.showLoading('Loading data...'); chartDay = today.clone(); $.get(dayFile, function(data) { var options = { chart : { renderTo : 'chart', defaultSeriesType : 'line' }, credits: { enabled: false }, legend: { borderWidth: 0 }, title: { text : today.getMonthName() + ' ' + today.getDate() + ', ' + today.getFullYear(), style: { color: '#000000', fontWeight: 'normal', fontSize: '12px' } }, xAxis : { title : { text : 'Hour of day', style: { color: '#000000', fontWeight: 'normal', fontSize: '10px' } }, categories : [] }, yAxis : [{ title : { text : 'kWh', style: { color: '#000000', fontWeight: 'normal', fontSize: '10px' } }, id: 'kwh' }, { title : { text : 'Temperature F', style: { color: '#000000', fontWeight: 'normal', fontSize: '10px' } } }, { title : { text : 'HDD', style: { color: '#000000', fontWeight: 'normal', fontSize: '10px' } }, opposite: true }], plotOptions: { series: { marker: { enabled: false }, point: { events: { mouseOver: function() { enabled = true; // this doesn't work } } }, events: { mouseOut: function() { enabled = false; // this doesn't work } } } }, series : [] }; // Split the lines var lines = data.split('\n'); // splits the file into lines // console.log("data: " + data); var series = []; // Iterate over the lines and add series names or data $.each(lines, function(lineNo, line) { var items = line.split(','); // splits the line into items if(lineNo == 0) { // series var z = 10; for(i = 0; i < items.length-1; i++) { series[i] = new Object(); series[i].name = items[i+1]; series[i].data = []; if (i == 0) { // adjusted load series[i].zIndex = 3; series[i].lineWidth = 5; } if (i > 0 && i < 3) { // solar and usage series[i].type = "area"; series[i].lineWidth = 0; } if ((i > 2) && (i < 7)) series[i].yAxis = 1; // first floor, second floor, basement, outdoor temps if (i == 7) series[i].yAxis = 2; // hdd if (i > 7) series[i].yAxis = 0; // 7 more columns for circuit-level data if (i > 2) series[i].zIndex = z++; //z++; } } else { // data if (items.length > 1) { var tm = items[0].split(':'); // splits the time item options.xAxis.categories.push(tm[0]); // hour for (i = 1; i < items.length; i++) { // if not a degree based value, then divide by 1000 if ((i > 3) && (i < 9)) { series[i-1].data.push( parseFloat( items[i] ) ); } else { series[i-1].data.push( parseFloat( items[i] ) / 1000 ); } } } } // end else }); // end each // Create the chart for (i=0; i < series.length; i++) { options.series.push(series[i]); } Highcharts.setOptions( { colors: ['#CC9933', '#669933', '#336699', '#DF0101', '#FF8000','#F7FE2E', '#58ACFA','#3366CC', '#CC3333', '#FF9655', '#FFF263', '#6AF9C4'] }); if (chart == null) { chart = new Highcharts.Chart(options); for (i=3; i<series.length;i++) chart.series[i].hide(); chart.series[7].show(); } chart.yAxis[0].setExtremes( metaData[0][1]/1000, metaData[0][0]/1000 ); // min, max for kWh chart.yAxis[1].setExtremes( metaData[0][2], metaData[0][3] ); // min, max for temp chart.yAxis[2].setExtremes( 0, metaData[0][4] ); // min, max for HDD if (utime && (today.getTime() == setDay.getTime())) { chart.xAxis[0].addPlotLine({ color: '#FF0000', width: 2, value: utime, id: 'p1' }); } else { chart.xAxis[0].removePlotLine( 'p1' ); } for (i=0; i < series.length; i++) { chart.series[i].setData(series[i].data); } chart.setTitle( { text: today.getMonthName() + ' ' + today.getDate() + ', ' + today.getFullYear() } ); chart.hideLoading(); }); // end get } function getMonthFilename( d ) { return "get_daily_data.php?house=" + houseId + "&date=" + today.toString('yyyy-MM-dd'); } function getDayFilename( d ) { return "get_hourly_data.php?house=" + houseId + "&date=" + today.toString('yyyy-MM-dd'); } function Color(space, a, b, c) { // Color.prototype.rgb_to_hsv = function() Color.prototype.rgb_to_hsv = function() { maxc = Math.max(this.r, this.g, this.b); minc = Math.min(this.r, this.g, this.b); this.v = maxc; if (minc == maxc) { this.h = 0; this.s = 0; //this.v = v; } diff = maxc - minc; this.s = diff / maxc; rc = (maxc - this.r) / diff; gc = (maxc - this.g) / diff; bc = (maxc - this.b) / diff; if (this.r == maxc) { this.h = bc - gc; } else if (this.g == maxc) { this.h = 2.0 + rc - bc; } else { this.h = 4.0 + gc - rc; } this.h = (this.h / 6.0) % 1.0; //comment: this calculates only the fractional part of h/6 //this.s = Math.round(this.s); //this.v = Math.round(this.v); } Color.prototype.hsv_to_rgb = function() { if (this.s == 0.0) { this.r = this.g = this.b = this.v; } i = Math.floor(this.h*6.0); //comment: floor() should drop the fractional part f = (this.h*6.0) - i; p = this.v*(1.0 - this.s); q = this.v*(1.0 - this.s*f); t = this.v*(1.0 - this.s*(1.0 - f)); if ((i % 6) == 0) { this.r = this.v; this.g = t; this.b = p; } if (i == 1) { this.r = q; this.g = this.v; this.b = p; } if (i == 2) { this.r = p; this.g = this.v; this.b = t; } if (i == 3) { this.r = p; this.g = q; this.b = this.v; } if (i == 4) { this.r = t; this.g = p; this.b = this.v; } if (i == 5) { this.r = this.v; this.g = p; this.b = q; } //this.r = Math.round(this.r); //this.g = Math.round(this.g); //this.b = Math.round(this.b); //comment: 0 <= i <= 6, so we never come here } this.space = space; if (space == 'RGB') { this.r = a; this.g = b; this.b = c; this.rgb_to_hsv(); } else if (space == 'HSV') { this.h = a; this.s = b; this.v = c; this.hsv_to_rgb(); } } function transition(value, maximum, start_point, end_point) { return start_point + (end_point - start_point)*value/maximum; } function transition3(value, maximum, startColor, endColor) { r1 = transition(value, maximum, startColor.h, endColor.h); r2 = transition(value, maximum, startColor.s, endColor.s); r3 = transition(value, maximum, startColor.v, endColor.v); return new Color( 'HSV', r1, r2, r3); } $.expr[":"].econtains = function(obj, index, meta, stack) { return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() == meta[3].toLowerCase(); } function setupCalendar() { $('table').append( makeTags('tr', 6) ); $('tr').each(function(index, domEle) { $(domEle).append( makeTags('td', 7) ) }); } });
"use strict"; const ViewUnlearnedAccident_1 = require('./ViewUnlearnedAccident'); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = ViewUnlearnedAccident_1.default; //# sourceMappingURL=index.js.map
const path = require('path'); const webpack = require('webpack'); const host = 'localhost'; const port = 3000; module.exports = { devtool: 'eval-cheap-module-source-map', devServer: { host, port, https: true }, entry: { popup: path.join(__dirname, '/chrome/src/popup'), background: path.join(__dirname, '/chrome/src/background') }, output: { path: path.join(__dirname, '/dev/js/'), filename: '[name].bundle.js', chunkFilename: '[id].chunk.js', publicPath: `https://${host}:${port}/js/` }, resolve: { extensions: ['', '.js'] }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [{ test: /\.js$/, loader: 'babel', exclude: /node_modules/, query: { presets: ['react-hmre'] } },{ test: /\.css$/, loaders: ['style', 'css'], exclude: /node_modules/ }] } }
window.addEventListener("load",initAll,false); function initAll() { document.getElementById("theForm").addEventListener("submit",addNode,false); document.getElementById("deleteNode").addEventListener("click",delNode,false); } function addNode(evt) { var inText = document.getElementById("textArea").value; var newText = document.createTextNode(inText); var newGraf = document.createElement("p"); newGraf.appendChild(newText); var docBody = document.getElementsByTagName("body")[0]; docBody.appendChild(newGraf); evt.preventDefault(); } function delNode(evt) { var allGrafs = document.getElementsByTagName("p"); if (allGrafs.length > 1) { var lastGraf = allGrafs[allGrafs.length-1]; var docBody = document.getElementsByTagName("body")[0]; docBody.removeChild(lastGraf); } else { alert("Nothing to remove!"); } evt.preventDefault(); }
//Language: Danish //Translator: ntoombs19 var filter_01 = "FA Filter Settings"; var filter_02 = "Instructions"; var filter_03 = "Created by"; var filter_04 = "Load Pages"; var filter_05 = "to"; var filter_06 = "Enable"; var filter_07 = "Hide All/None"; var filter_08 = "Scout Attack"; var filter_09 = "No losses"; var filter_10 = "Some losses"; var filter_11 = "Lost, but damaged building(s)"; var filter_12 = "Lost,but scouted"; var filter_13 = "Lost"; var filter_14 = "Order By"; var filter_15 = "Distance"; var filter_16 = "Time"; var filter_17 = "Direction"; var filter_18 = "Ascending"; var filter_19 = "Descending"; var filter_20 = "Hide Hauls"; var filter_21 = "Full"; var filter_22 = "Partial"; var filter_23 = "Hide Attacks"; var filter_24 = "Greater Than"; var filter_25 = "Less Than"; var filter_26 = "Equal To"; var filter_27 = "Hide farms sent to in the last"; var filter_28 = "minutes"; var filter_29 = "Reset"; var filter_30 = "Hide Wall Lvl"; var filter_31 = "Hide Distances"; var filter_32 = "Hide"; var filter_33 = "Show"; var filter_34 = "continent(s)"; var filter_35 = "Hide scout reports with resources"; var filter_36 = "villages attacked in the last"; var filter_37 = "minutes(s)"; var filter_38 = "Run default automatically"; var filter_39 = "Hide scout reports where C is disabled"; var filter_40 = "Farm Assistant"; var filter_41 = "Farm Assistant - Loading page"; var filter_42 = "Language (Danish)"; var instructions_01 = "Checked report types will be hidden"; var instructions_02 = "Filters left unchecked will not be applied"; var instructions_03 = "Separate continents with a period. Example: 55.54.53"; var instructions_04 = "This filter will hide rows that were farmed \"n\" minutes ago. The default is 60 minutes. Changing the time will only affect newly farmed rows. Clicking reset will reset all the timers for each row but only the rows loaded."; var instructions_05 = "Save and load your various settings configurations here. Changing profiles will load the selected profile. The default will load automatically when the script is run."; var instructions_06 = "Adjust page size to 100 for faster page loading"; var dialog_01 = "Are you sure you want to reset your recently farmed villages?"; var dialog_02 = "You are already on the default profile. Would you like to create a new profile and set it to default?"; var dialog_03 = "Profile name"; var dialog_04 = "You already have a profile with that name. Please choose another name"; var dialog_05 = "Your profile name cannot be empty. Please try again."; var dialog_06 = "You cannot delete your default profile"; var dialog_07 = "You cannot export/import the default profile. To export these settings, create a new profile, then try exporting again."; var dialog_08 = "Copy to clipboard: Ctrl+C, Enter"; var dialog_09 = "[b]FA Filter: "+profileName+"[/b][spoiler][i][u]Instructions[/u]: To import this profile, copy the following line of code then import the copied settings by pasting them into the prompt after clicking import on the FA Filter Script settings panel[/i][code]"+profileName+","+settings+"[/code][/spoiler]"; var dialog_10 = "Profile Settings"; var dialog_11 = "Ctrl+V to paste here settings here"; var dialog_12 = "You already have a profile with that name."; var dialog_13 = "Reload this script to see the new language. This page will refresh automatically."; var profile_01 = "Settings profile"; var profile_02 = "Apply"; var profile_03 = "Reset"; var profile_04 = "New"; var profile_05 = "Set Default"; var profile_06 = "Delete"; var profile_07 = "Update"; var profile_08 = "Export"; var profile_09 = "Import"; var profile_10 = "Default";
function convertToSlug(Text) { return Text .toLowerCase() .replace(/[^\w ]+/g, '') .replace(/ +/g, '-') ; } function TicketModel(ticket) { this.id = ko.observable(ticket.id); this.text = ko.observable(ticket.text) } function WorkstreamStatusModel(wsName, status, tickets) { var self = this; self.wsName = wsName; self.status = status; self.tickets = ko.observableArray([]); for (var i = 0; i < tickets.length; i++) { self.tickets.push(new TicketModel(tickets[i])) } self.deleteTicket = function (ticket) { $.ajax("tickets/", { type: "delete", contentType: "application/json", data: JSON.stringify({id: ticket.id()}), success: function (data) { console.log("successfully deleted ticket", ticket); self.tickets.remove(ticket); }, error: function (textStatus, errorThrown) { console.log("failed to delete ticket", textStatus, errorThrown); } }); }; self.updateToThis = function (arg) { console.log("updating ticket to " + self.status, arg.item) var ticket = arg.item; var ticket_update = { id: ticket.id(), content: ticket.text(), workstream: self.wsName(), status: self.status }; $.ajax("tickets/", { type: "patch", contentType: "application/json", data: JSON.stringify(ticket_update), success: function (data) { console.log("successfully moved ticket to new status", ticket, self.status); }, error: function (textStatus, errorThrown) { console.log("failed to move ticke to new status", textStatus, errorThrown); } }); } } function WorkstreamModel(name, readyTickets, doingTickets, doneTickets) { this.name = ko.observable(name); this.cssClass = ko.computed(function () { return convertToSlug(this.name()); }, this); this.ready = new WorkstreamStatusModel(this.name, "ready", readyTickets); this.doing = new WorkstreamStatusModel(this.name, "doing", doingTickets); this.done = new WorkstreamStatusModel(this.name, "done", doneTickets); var self = this; this.newText = ko.observable(""); this.createNew = function () { console.log("creating new ticket", self.newText()); var ticket_info = { workstream: self.name(), content: self.newText(), status: "ready" }; var pendingTicket = new TicketModel({id: -1, text: self.newText()}); self.newText(""); $.ajax("tickets/", { type: "post", contentType: "application/json", data: JSON.stringify(ticket_info), dataType: "json", success: function (data) { console.log("Created ticket on server", data); pendingTicket.id(data.id); self.ready.tickets.push(pendingTicket); }, error: function (textStatus, errorThrown) { console.log("Error trying to create new ticket on server", textStatus, errorThrown); } }); }; } function GravityBoardModel(workstreams) { this.workstreams = ko.observableArray([]); for (var i = 0; i < workstreams.length; i++) { var ws = workstreams[i]; this.workstreams.push(new WorkstreamModel(ws.name, ws.ready, ws.doing, ws.done)); } this.currentWorkstream = ko.observable(); } $.ajax("tickets/", { dataType: "json", success: function (data) { ko.applyBindings(new GravityBoardModel(data)); }, error: function (textStatus, errorThrown) { console.log("Error trying to retrieve tickets from server", textStatus, errorThrown); } }); $('.info-modal').modal('show');
export const marginAutoAll = { marginTop: 'auto', marginLeft: 'auto', marginBottom: 'auto', marginRight: 'auto', } export const marginAutoY = { marginTop: 'auto', marginBottom: 'auto', } export const marginAutoX = { marginRight: 'auto', marginLeft: 'auto', } export const absoluteCenter = { position: 'absolute', marginTop: 'auto', marginLeft: 'auto', marginBottom: 'auto', marginRight: 'auto', top: 0, right: 0, bottom: 0, left:0, } export const fillContainer = { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', }
import Phaser from 'phaser'; import AI from './AI'; import Human from './Human'; export default class Player extends Human { constructor(game, x, y, asset, frame) { super(game, x, y, asset, frame); this.activeWeapon = null; this.activeWeapon = {}; this.anchor.setTo(0.5, 0.5); this.weaponList = [ 'flame', 'm4', 'rocket', 'uzi' ]; this.loadAnimations(); this.money = 0; } startAnimation(animation) { switch (animation) { case 'walking': this.startWalking(); break; } } startWalking(repeat = false) { let activeWeaponName = _.get(this, 'activeWeapon.name'); if (activeWeaponName) { this.animations.play(activeWeaponName, 8, repeat); } else { this.animations.play('walking', 8, repeat); } } switchWeapon(weaponName) { this.activeWeapon.name = _.find(this.weaponList, name => name === weaponName); this.frame = this.animations.getAnimation(weaponName).frame; this.weapon = this.game.add.weapon(-1, `${this.activeWeapon.name}Bullet`); this.weapon.physicsBodyType = Phaser.Physics.ARCADE; this.weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS; this.weapon.bulletSpeed = 600; this.weapon.fireRate = 100; this.weapon.bulletCollideWorldBounds = true; this.weapon.bulletAngleOffset = 90; this.weapon.bulletAngleVariance = 5; this.weapon.enableBody = true; } cycleWeapon() { if (_.get(this, 'activeWeapon.name')) { let index = _.findIndex(this.weaponList, name => name === this.activeWeapon.name); if (index + 1 < this.weaponList.length) { this.switchWeapon(this.weaponList[index + 1]); } else { this.switchWeapon(this.weaponList[0]); } } else { this.switchWeapon(this.weaponList[0]); } // TODO: This only changes the sprite size on weapon change. Change this code to run any time there is a change. let bodyHeight = this.body.height, bodyWidth = this.body.width, spriteWidth = this.width, spriteHeight = this.height; this.body.setSize(bodyWidth, bodyHeight, spriteWidth * 0.5 - bodyWidth * 0.5, spriteHeight * 0.5 - bodyHeight * 0.5); } shootWeapon() { if (!this.activeWeapon.name) { return; } this.weapon.fireAngle = this.body.rotation; this.weapon.trackSprite(this, 0, 0); this.bullet = this.weapon.fire(); } update() { if (this.weapon) { this.game.physics.arcade.overlap(this.weapon.bullets, _.filter(AI.ai, 'alive'), (enemy, bullet) => { bullet.kill(); enemy.killPlayer(); this.addScore(100); }); } } addScore(newScore) { this.money += newScore; this.game.state.getCurrentState().scoreText.setText(`$${this.money.toFixed(2)}`); } }
var profilController = function (scope, $http, currentuser) { var vm = this; vm.newPhoto = ''; currentuser.$promise.then(function () { vm.profil = currentuser; if (currentuser._links.member) { vm.profil.members = currentuser.resource("member").query(); } }); var handleFileSelect = function (evt) { var file = evt.currentTarget.files[0]; var reader = new FileReader(); reader.onload = function (evt) { scope.$apply(function () { vm.photoTemp = evt.target.result; }); }; reader.readAsDataURL(file); }; angular.element(document.querySelector('#photoProfil')).on('change', handleFileSelect); vm.save = function () { if (!vm.error) { var formData = new FormData(); formData.append("id", vm.profil.id); if (vm.profil.password !== undefined) { formData.append("password", vm.profil.password); } formData.append("email", vm.profil.email); formData.append("photo", vm.newPhoto); $http({ method: "POST", url: currentuser._links.self, data: formData, headers: {'Content-Type': undefined}, transformRequest: angular.identity }).then(function() { currentuser.photo = vm.newPhoto; }); } }; }; profilController.$inject = ["$scope", "$http", "currentuser"]; module.exports = profilController;
// Promise接受一个函数作为参数,函数里有两个参数,分别为resolve, reject,两个函数由JS引擎提供 const promises = new Promise((resolve, reject) => { // 返回数据 resolve(value) // 返回错误 reject(err) }) // Promise.then 接收两个函数作为参数 Promise.then((value) => { }, (error) => { }) Promise.prototype.all = function(promises) { let len = promises.length; let count = 0; let result = []; return new Promise((resolve, reject) => { for(let i = 0; i < len; i++) { Promise.resolve(promises[i]).then((res)=> { count++; result[i] = res; if(i === len) { return resolve(result); } }, (err) => { return reject(err) }) } }) } Promise.prototype.race = function(promises) { let len = promises.length; return new Promise((resolve, reject) => { for(let i = 0; i < len; i++) { Promise.resolve(promises[i]).then((res)=> { return resolve(res); }, (err) => { return reject(err) }) } }) } function spawn(genF) { return new Promise(function(resolve, reject) { const gen = genF(); function step(nextF) { let next; try { next = nextF(); } catch(e) { return reject(e) } if(next.done) { return resolve(next.value); } Promise.resolve(next.value).then(function(v) { step(function() { return gen.next(v)}) }, function (error) { step(function() { return gen.throw(e)}) }) } step(function() { return gen.next(undefined)}) }) } function makeIterator(array) { let nextIndex = 0; return { next: function() { return nextIndex < array.length ? { value: array[nextIndex++]; done:false, } : { value: undefined, done: true, } }, } } const curry = (fn, ...args) => { args.length >= fn.length ? fn(...args) : (..._args) => curry(fn, ...args, ..._args); } function _new(constructor, ...arg) { const obj = {}; obj.__proto__ = constructor.prototype; const result = constructor.apply(obj, arg); return typeof result === 'object' ? result : obj; } Function.prototype.myCall = function(thisArg = window) { thisArg.fn = this; const args = [...arguments].slice(1); const result = thisArg.fn(...args); delete thisArg.fn; return result; } Function.prototype.myApply = function(thisArg = window) { thisArg.fn = this; let result; if(arguments[1]) { result = thisArg.fn(...arguments[1]); } else { result = thisArg.fn(); } delete thisArg.fn; return result; } Function.prototype.myBind = function(thisArg = window) { const fn = this; const args = [...arguments].slice(1); return function () { const newArgs = [...arguments]; return fn.apply(thisArg, args.concat(newArgs)) } } // 1 float: left; width: auto; // 2 float: left; width: 100%; padding-left: left; // 3 leftfa float: left; width: 100%; left margin-right: right float: left; marin-left: -right // 1 postion: absolute left: 0 margin-left: left; margin-right: right; postion: absolute right: 0 // 1 float: left; margin-left: left; margin-right: right; float: right; // 高度固定,块级元素 line-height: 200px; text-align: center; // flex display: flex; align-items: center; justify-content: center; // transform transform: translate(-50%, -50%) // position position: absolute; margin: auto; left: 0; top: 0; right: 0; bottom: 0; class A { } class B extends A { } const b = new B();
var namespace_boxer = [ [ "Box", "class_boxer_1_1_box.html", "class_boxer_1_1_box" ], [ "Core", "class_boxer_1_1_core.html", "class_boxer_1_1_core" ], [ "Group", "class_boxer_1_1_group.html", "class_boxer_1_1_group" ], [ "LogisticSystem", "class_boxer_1_1_logistic_system.html", "class_boxer_1_1_logistic_system" ] ];
/* * This service definition has all methods related to any operation on sensors * Uses the UtilityServices * All $http methods return promises * Instead of an HTTP API, sensor data will be read from MQTT * Simulating the payload below * * For Mosquitto installation: https://www.element14.com/community/community/design-challenges/sci-fi-your-pi/blog/2015/06/22/pizzapi-mosquitto-websockets-success-tutorial */ //Global variables for this service //Change to MQTT endpoints //var api_endpoint_sensors = 'http://www.advantapi.com/homecentral/api/v1/sensors/'; //var api_endpoint_sensordata = 'http://www.advantapi.com/homecentral/api/v1/sensordata/'; var sensors = []; //Simulating a temperature sensor payload sensors.push({ id: '1', name: 'Home Temperature', owner_email: 'vmujumdar@email.com', icon: 'temp_icon', status: '1', //1=Enabled, 2=Disabled topic: 'sensors/hometemperature', last_read_on: '', first_read_on: '', setup_on: '', original_location: { latitude: '19.0760N', longitude: '72.8777E' }, current_location: { latitude: '19.0760N', longitude: '72.8777E' }, //If ranges overlap the first range in order of definition will trigger parameters: [ { name: 'temp', desc: 'Temperature', unit_symbol: 'C', //optional valid_min: '', //Values lesser than will be ignored valid_max: '', //Values greater than will be ignored last_read_value: '', last_alert_type: 'nosignal',//ok, warning, danger, nosignal last_alert_msg: 'No Signal', alert_ranges:[ { alert_type: 'ok', //ok, warning, danger, nosignal alert_msg: 'Normal', min_value: '16', //Ok if value is between 16 and 40 inclusive max_value: '30', }, { alert_type: 'warning', alert_msg: 'Cold', min_value: '', //Empty for infinity, so Cold if 15 or below max_value: '15', }, { alert_type: 'warning', alert_msg: 'Hot', min_value: '31', max_value: '40', }, { alert_type: 'danger', alert_msg: 'Very Hot', min_value: '41', max_value: '', //Empty for infinity, so Hot if 41 or above }, ] //end alert_ranges }, { name: 'humidity', desc: 'Humidity', unit_symbol: '', //optional last_read_value: '', last_alert_type: 'nosignal',//ok, warning, danger, nosignal last_alert_msg: 'No Signal', alert_ranges:[ { alert_type: 'ok', //ok, warning, danger, nosignal alert_msg: 'Normal', min_value: '16', //Ok if value is between 16 and 40 inclusive max_value: '40', }, { alert_type: 'warning', alert_msg: 'Cold', min_value: '', //Empty for infinity, so Cold if 15 or below max_value: '15', }, { alert_type: 'warning', alert_msg: 'Hot', min_value: '41', max_value: '', //Empty for infinity, so Hot if 41 or above }, ] //end alert_ranges } ] }); app.service('SensorServices', function($state, $rootScope, $http, $q, $interval, UtilityServices) { var serv = this; //Setting global flags to be used by each function //Declaring them within the function causes scope issues in callbacks this.deleteStatus = false; /* Sensor Model */ this.new_sensor = { //id: '', name: '', //user defined users: [], icon: '', status: '0', //1=Enabled, 0=Disabled server: {}, //Server details from a list of pre-configured servers topic: '', //topic: function(){return "sensors/" + this.new_sensor.name}, last_read_on: 0, first_read_on: 0, setup_on: new Date().getTime(), //Current time in epoch base_loc: { //user defined or auto fetch using location services latitude: '', longitude: '' }, curr_loc: { //from sensor signal for moving sensors latitude: '', longitude: '' }, //Last alert type and message at the sensor level will maintain the //highest alert status amongst all parameters (danger>warning>ok>nosignal) last_alert_type: 'nosignal',//ok, warning, danger, nosignal last_alert_msg: 'No Signal', //If ranges overlap the first range in order of definition will trigger parameters: [] } this.user = { email: '', access: '1' //1 = full access, 2 = read only, 0 = no access } this.new_parameter = { code: '', //user defined name: '', //user defined unit_symbol: '', //optional, user defined valid_min: '', //Values lesser than will be ignored valid_max: '', //Values greater than will be ignored last_read_value: '', last_alert_type: 'nosignal',//ok, warning, danger, nosignal last_alert_msg: 'No Signal', alerts:[] } this.new_alert = { alert_id: 0, //auto-generate, used for delete alert_type: '', //ok, warning, danger, nosignal alert_msg: '', //user defined min_value: '', //user defined max_value: '', //user defined } this.go = function (path, title) { $state.go(path); $rootScope.title = title; } this.reloadState = function(){ //$window.location.reload(); $state.reload(); } /* * Method to get logged in member's sensors from local storage * Parameters: * - none * Since a get will be called first, handle the onupgradeneeded event only here */ this.saveSensor = function(sensor, ev) { var db; //for the db instance //Using IndexedDB if (!window.indexedDB) { window.alert("Your browser doesn't support a stable version of IndexedDB. Data cannot be saved."); //And redirect to sensor list view serv.go('sensors','Sensors'); } // Open the database var request = window.indexedDB.open("homecentral_db", 1); request.onsuccess = function(event) { // Do something with request.result! db = event.target.result; //Start a write transaction. //The first parameter is an array of all objectStores required for this transaction var transaction = db.transaction(["sensors"], "readwrite"); //get the object store var objectStore = transaction.objectStore("sensors"); //Use put() which is an insert or update method, //instead of add() which is an insert only method //var request = objectStore.add(sensor); var request = objectStore.put(sensor); request.onsuccess = function(event) { //event.target.result == this.sensor.id; }; transaction.oncomplete = function(event) { //serv.go('sensors','Sensors'); }; transaction.onerror = function(event) { // Don't forget to handle errors! console.log("Transaction error.") }; }; // This event is triggered when creating or upgrading a database // Set up objectStores, etc. // Implemented in recent browsers request.onupgradeneeded = function(event) { //Handled on sensor_services get which is called before save }; request.onerror = function(event) { // Do something with request.errorCode! console.log("There was an error opening the datastore."+event.target.errorCode); //And redirect to sensor_details view serv.go('sensors','Sensors'); }; }; //END saveSensor /* * Method to get logged in member's sensors from local storage * Parameters: * - none * Since a get will be called first, handle the onupgradeneeded event only here */ this.getSensors = function() { var deferred = $q.defer(); /* Get sensors from a web service storage */ /* //Construct the params object to pass to the GET query var query_params = { user_id: user_id }; */ /* TODO: Change to local nodejs api $http({method: 'GET', url: api_endpoint_sensors, params: query_params}) //$http({method: 'GET', url: api_endpoint_sensors}) .then(function successCallback(response){ // this callback will be called asynchronously // when the response is available //console.log("from http call"); //console.log(response.data); deferred.resolve(response.data); }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. //console.log(response); deferred.reject(response); } ); */ //Get sensors from indexedDB var db; //for the db instance var sensors = []; //Using IndexedDB if (!window.indexedDB) { window.alert("Your browser doesn't support a stable version of IndexedDB. Data cannot be saved."); //And redirect to sensor_details view serv.go('sensors','Sensors'); } // Open the database var request = window.indexedDB.open("homecentral_db", 1); request.onsuccess = function(event) { // Do something with request.result! db = event.target.result; //Start a read transaction. //The first parameter is an array of all objectStores required for this transaction var transaction = db.transaction(["sensors"]); //get the object store var objectStore = transaction.objectStore("sensors"); //Need to use a cursor to get all objects. Use get("key") for one object. objectStore.openCursor().onsuccess = function(event) { var cursor = event.target.result; if (cursor) { sensors.push(cursor.value); cursor.continue(); } else { //console.log("Got all sensors: " + sensors); } }; transaction.oncomplete = function(event) { //Return the retrieved data deferred.resolve(sensors); }; transaction.onerror = function(event) { // Don't forget to handle errors! console.log("Transaction error.") //Return an error deferred.reject(event.target.result); }; }; // This event is triggered when creating or upgrading a database // Set up objectStores, etc. // Implemented in recent browsers request.onupgradeneeded = function(event) { db = event.target.result; // Create an objectStore for this database var objectStore = db.createObjectStore("sensors", { keyPath: 'id', autoIncrement: true }); db.createObjectStore("servers", { keyPath: 'id', autoIncrement: true }); }; request.onerror = function(event) { // Do something with request.errorCode! window.alert("There was an error opening the datastore."+event.target.errorCode); //And redirect to sensor_details view serv.go('sensors','Sensors'); }; //Set the deferred.reject and resolve consditionally and return the promise at the end return deferred.promise; }; //END getSensors() /* * Method to delete a sensor * Parameters: * - sensor_id */ this.deleteSensor = function(sensor_id){ var db; //for the db instance //Using IndexedDB if (!window.indexedDB) { window.alert("Your browser doesn't support a stable version of IndexedDB. Data cannot be saved."); //And redirect to sensor_details view ctrl.reloadState(); } // Open the database var request = window.indexedDB.open("homecentral_db", 1); request.onsuccess = function(event) { // Do something with request.result! db = event.target.result; //Start a write transaction. //The first parameter is an array of all objectStores required for this transaction var transaction = db.transaction(["sensors"], "readwrite"); //get the object store var objectStore = transaction.objectStore("sensors"); var request = objectStore.delete(parseInt(sensor_id)); //sensor_id coming in as text request.onsuccess = function(event) { //event.target.result == this.sensor.id; }; transaction.onerror = function(event) { // Don't forget to handle errors! }; transaction.oncomplete = function(event) { //Do nothing here, do whatever is needed in the calling controller }; }; // This event is triggered when creating or upgrading a database // Set up objectStores, etc. // Implemented in recent browsers request.onupgradeneeded = function(event) { //Handled on sensor_services get which is called before save }; request.onerror = function(event) { // Do something with request.errorCode! window.alert("There was an error opening the datastore."+event.target.errorCode); }; }; //END deleteSensor });
angular.module('postTitleList', ['core.post']);
import React, { Component } from 'react' import ToggleDisplay from 'react-toggle-display' import SearchBar from './SearchBar' import VideoChecker from './VideoChecker' import VideoHistory from './VideoHistory' import YTSearch from './YTSearch' import styles from './PlayList.module.css' // import Waypoint from 'react-waypoint' class PlayList extends Component { constructor(props) { super(props) } scrollTopList() { this.refs.listContentsDiv.scrollTop = 0 } // wpEnterHandler() { // console.log('wpEnterHandler') // } // // wpLeaveHandler() { // console.log('wpLeaveHandler') // } render() { const { playListState, // 트레이 윈도우 상태. saveVideo, // 비디오 저장. clearSearchList, // 검색 리스트 지우기. addChekerVideo, // 비디오 저장(비디오 체커). checkerPlayerOnReady, // 비디오 체커 레디. checkerPlayerOnError, // 비디오 체커 에러. checkerPlayerOnPlay, // 비디오 체커 플레이 시작. playVideo, // 비디오 실행. removeVideo, // 비디오 삭제. searchAsync, // 비디오 검색. getNextPage // 검색 다음페이지. } = this.props return ( <div id='listContainer' className={styles.PlayListContainer}> <SearchBar playListState={playListState} scrollTopList={this.scrollTopList.bind(this)} setKeyword={searchAsync} clearSearchList={clearSearchList} /> <div className={styles.PlayListContents} ref='listContentsDiv'> <VideoChecker disabled={playListState.checker_disabled} playListState={playListState} addChekerVideo={addChekerVideo} checkerPlayerOnReady={checkerPlayerOnReady} checkerPlayerOnError={checkerPlayerOnError} checkerPlayerOnPlay={checkerPlayerOnPlay} isError={playListState.checker_video_error} /> <VideoHistory is_searched={playListState.is_searched} keyword={playListState.search_keyword} docList={playListState.docs} playVideo={playVideo} removeVideo={removeVideo} /> <YTSearch searchList={playListState.search_results} searchInfo={playListState.search_info} playListState={playListState} saveVideo={saveVideo} getNextPage={getNextPage} /> </div> </div> ) } } export default PlayList
var m = require("mithril"); var Comment = require('../models/comment'); var rendererStore = require('../rendererStore'); var actions = require('../state/actions/actions'); module.exports = SelectionPopup = { mode: undefined, lineHeight: undefined, oncreate: function({state, attrs, dom}) { window.addEventListener('resize', function() { recalculateCoords(attrs) }, false); }, onremove: function({state, attrs, dom}) { rendererStore.dispatch(actions.hideCommentPopup()); }, view: function({state, attrs, dom}) { console.log(attrs.selection); var modeContainer = undefined, coords = attrs.selection, style = { left: coords.left + 'px', top: coords.top + 'px' }; if (state.mode === 'comment') { attrs.parentState = state; modeContainer = m(CommentForm, attrs); } return m('div#selection-popup', { style: style }, [ m('div.btn-group', [ m('button.btn.btn-primary', { type: "button", onclick: function(e) { state.mode = (state.mode === 'comment') ? undefined:'comment'; } }, [ m('span.glyphicon.glyphicon-comment') ]), m('button.btn.btn-primary', {type: "button"}), m('button.btn.btn-primary', {type: "button"}), ]), modeContainer ]); } } var CommentForm = { comment: undefined, oncreate: function({state, attrs, dom}) { var selection = { anchor: attrs.cm.editor.getCursor('anchor'), head: attrs.cm.editor.getCursor('head') } state.comment = new Comment.Comment(undefined, attrs.user.id, attrs.doc.id, selection) }, view: function({state, attrs, dom}) { return m('div', [ m('div.form-group', [ m('label', {for: "comment"}, 'Comment:'), m('textarea.form-control#comment', { rows: 5, onchange: function(e) { var content = e.target.value; state.comment = Comment.updateCommentContent(state.comment, content) } }), ]), m('button.btn.btn-primary', { type: "button", onclick: function() { Comment.saveComment(state.comment, attrs.doc) .then(function() { attrs.parentState.mode = undefined; rendererStore.dispatch(actions.hideCommentPopup()) }) } }, 'Submit'), ]); } } function recalculateCoords(attrs) { attrs.selection.coords = attrs.cm.getCharCoords(attrs.selection.raw.ranges[0].anchor, 'page') m.redraw(); }
'use strict'; // load da engine var engine = require('vvps-engine'), server = engine.server, restify = engine.restify; // turn da engine on engine.bootstrap({ name: 'test-api', version: '0.0.1' }, function () { // default route, return the index.html engine.server.get('/', restify.serveStatic({ directory: './public', default: 'index.html' })); // Route for css, js files // FIX js file is served but not used by index... how? engine.server.get(/.css|.js/, restify.serveStatic({ directory: './public/' })); console.log('Server is online...'); });
// Regular expression that matches all symbols in the Miscellaneous Symbols block as per Unicode v5.1.0: /[\u2600-\u26FF]/;
import React from 'react'; // import PropTypes from 'prop-types'; import PortfolioItem from './PortfolioItem'; export default class PortfolioBox extends React.Component { constructor() { super(); this.state = { imageIndex: 0, portfolioState: {}, portfolioItems: [ { title: 'ENTABLE', image: ['Entable.png'], // src: "https://www.youtube.com/embed/Zy6XaHpnkEg", text: `This application was built over a single weekend at the Lady Problems Hackathon in San Francisco and won the Cisco developers prize. It incorporates React, Express, Flux, Socket.io, MongoDB and Cisco's Tropo API to enable the creation and management of "banks" by customers around the world using a simple sms-based interface. Supporters of those banks can then go online to view updates, interact with bank members and make donations.`, link: [ 'www.entable.org', 'github.com/thejapanexperience/entable2.0', 'youtu.be/y7ehO-zgFmM', 'twitter.com/rekhapai/status/790329165341794304' ] }, { title: 'THE FAST LIFE', image: ['theFastLife.png'], // src: "https://www.youtube.com/embed/ln2dLeUfRtA" , text: 'The Fast Life is an application that allows users to schedule, edit and view fasts, as well as keep a diary. Firebase is used to handle Google authentication. Styling was done using material-ui. The app was built with React and also incorporates Node, Express, Redux and MongoDB.', link: [ 'nameless-cove-36810.herokuapp.com', 'github.com/thejapanexperience/the-fast-life' ] }, { title: 'EDUKU', image: ['eduku.png'], // src: "https://www.youtube.com/embed/u5G2dffogDo", text: `I'm proud to be a co-founder and lead developer of Eduku. Eduku is a social enterprise (self-funded charity), that uses profits from the sales of learning resources to fund educational opportunities (predominantly in low-income countries) for those who don't have regular or sufficient access. We are creating a platform that will allow users to interact with well designed learning resources in the form of worksheets and online games for primary-age students, as well as participate in the allocation of funds raised by / through Eduku. `, link: ['www.facebook.com/projecteduku/'] }, { title: 'RICHARDMANDS.COM', image: ['richardmandsdotcom.png'], // src: "https://www.youtube.com/embed/S4nIfLGqd9s", text: 'A beautiful, fully-responsive single-page application built using react without any css-libraries.', link: [ 'www.richardmands.com', 'github.com/thejapanexperience/newWebsiteShell' ] }, { title: 'REACT DEMO 1', image: ['theFastLife.png'], src: 'https://www.youtube.com/embed/ln2dLeUfRtA', text: 'Demonstration of React and displaying data from external APIs', link: ['github.com/thejapanexperience/the-fast-life'], reactDemo: 1 }, { title: 'MINI PROJECTS', image: ['theFastLife.png'], src: 'https://www.youtube.com/embed/ln2dLeUfRtA', text: 'Demonstration of React and displaying data from external APIs', link: ['github.com/thejapanexperience/the-fast-life'], reactDemo: -1 } ], tabs: [ 'tabBarTabActive', 'tabBarTab', 'tabBarTab', 'tabBarTab', 'tabBarTab', 'tabBarTab' ] }; this.click = this.click.bind(this); } click(e, tabIndex) { if (e) { e.preventDefault(); } let { tabs, portfolioItems } = this.state; for (let i = 0; i < tabs.length; i++) { if (i === tabIndex) { tabs[i] = 'tabBarTabActive'; } else { tabs[i] = 'tabBarTab'; } } if ( this.state.portfolioState === undefined || !this.state.portfolioState.reactDemo ) { document.getElementById('portfolioItemTitle').className = 'portfolioTitleTextHidden'; document.getElementById('youtubeBox').className = 'iframeHidden'; document.getElementById('portfolioBodyText').className = 'portfolioBodyTextHidden'; document.getElementById('portfolioLink').className = 'portfolioLinkHidden'; // document.getElementById('section4').className ='section4Hidden'; document.getElementById('portfolioBox').className = 'portfolioBoxHidden'; if (document.getElementById('reactDemo1')) document.getElementById('reactDemo1').className = 'reactBoxBoxHide'; if (document.getElementById('reactDemo11')) document.getElementById('reactDemo11').className = 'reactBoxHide'; this.setState({ tabs: tabs }); } else { if (document.getElementById('reactDemo1')) document.getElementById('reactDemo1').className = 'reactBoxBoxHide'; if (document.getElementById('reactDemo11')) document.getElementById('reactDemo11').className = 'reactBoxHide'; if (document.getElementById('section4Box')) document.getElementById('section4Box').className = 'section4BoxHidden'; // document.getElementById('section4').className ='section4Hidden'; } setTimeout(() => { this.setState({ portfolioState: portfolioItems[tabIndex] }); }, 1000); // } } render() { let data = this.state.portfolioState; let tabs = this.state.tabs; let portfolioItems = this.state.portfolioItems; let imageIndex = this.state.imageIndex; if (!data.title) { data = portfolioItems[0]; } const tabBarContent = tabs.map((tab, i) => { let title; title = portfolioItems[i].title; return ( <div className={tabs[i]} key={i} onClick={e => this.click(e, i)}> <div className="tabBarTabTitle" onClick={e => this.click(e, i)}> {title} </div> </div> ); }); return ( <div className="section3"> <div className="section3Title">PORTFOLIO</div> <div className="tabBar">{tabBarContent}</div> <PortfolioItem data={data} imageCarousel={() => this.imageCarousel()} imageIndex={imageIndex} click={this.click} /> </div> ); } } // PortfolioBox.propTypes = { // // children: PropTypes.element // };
import React, { Component } from 'react'; class About extends Component { constructor(props) { super(props); } render() { return ( <div className="col-md-6"> Office Finder is a web app for finding temp office space. </div> ); } } export default About;
'use strict'; const joinMarker = 'ihndeebvdbccfiehktkununjgklnedefjfgjllkdkdrrvbtuibkguhtvrtbbrrni'; const stringConcatRegex = new RegExp( '(\' ?(\\\+|\\\.)?' + joinMarker + '\')|(" ?(\\\+|\\\.)?' + joinMarker + '")' ); function joinLines(firstLine, secondLine) { let newLines = firstLine.trimRight() + joinMarker + secondLine.trimLeft(); newLines = newLines.replace(stringConcatRegex, ''); if (firstLine.trim().startsWith('//')) { newLines = newLines.replace(joinMarker + '// ', ' '); } if (firstLine.trim().startsWith('* ')) { newLines = newLines.replace(joinMarker + '* ', ' '); } if (firstLine.trim().startsWith('# ')) { newLines = newLines.replace(joinMarker + '# ', ' '); } if (firstLine.trim().startsWith('; ')) { newLines = newLines.replace(joinMarker + '; ', ' '); } // Eliminate trailing comma and space when joining a line with a comma // with a line with a closing bracket if ( firstLine.trim().endsWith(',') && startsWithClosingBracket(secondLine) ) { newLines = newLines.replace(',' + joinMarker, ''); } const shouldSpace = !endsWithOpeningBracket(firstLine) && !startsWithClosingBracket(secondLine); newLines = newLines.replace(joinMarker, shouldSpace ? ' ' : ''); return newLines; } function endsWithOpeningBracket(s) { s = s.trim(); const v = s[s.length - 1]; if (v === '{' || v === '[' || v === '(') { return true; } // Preserve the space if it looks like `<` is an operator (with a space on // the left-hand side) if (v === '<' && s[s.length - 2] !== ' ') { return true; } return false; } function startsWithClosingBracket(s) { const v = s.trim()[0] return v === '}' || v === ']' || v === ')' || v === '>'; } module.exports = joinLines;
const mediacapture = require("./lib/mediacapture"); const mediacapturemodal = require("./lib/mediacapturemodal"); exports.mediacapture = mediacapture; exports.mediacapturemodal = mediacapturemodal;
version https://git-lfs.github.com/spec/v1 oid sha256:3b927eff993b3be8f76e0a41462b799a533743830e10e066793fc356c6ee5daa size 17907
/* * Copyright (c) 2006-2007 Erin Catto http: * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked, and must not be * misrepresented the original software. * 3. This notice may not be removed or altered from any source distribution. */ goog.provide('box2d.BoundValues'); /** @constructor */ box2d.BoundValues = function() { this.lowerValues = [0, 0]; this.upperValues = [0, 0]; };
import fetch from '@/api/mock/fetch' import { router, clearRoutes } from '@/api/mock/router' describe('[mock] fetch 모듈 테스트', () => { const mockPost = { _id: 1, subject: '제목', creator: { _id: 1, username: 'jeremy.kang', name: 'Jeremy Kang' }, createdAt: '2017-09-08T23:11:23', updatedAt: '2017-09-08T23:11:23' } beforeEach(() => { router('/api/post/:id', { method: 'GET' }, (req) => { return mockPost }) }) afterEach(() => { clearRoutes() }) it('fetch() - promise 이용 테스트', (done) => { // When const promise = fetch('/api/post/1', { method: 'GET' }) // Then promise.then(result => { expect(result).to.be.an('object') expect(result).to.deep.equal(mockPost) done() }) }) it('fetch() - 콜백함수 이용 테스트', () => { fetch('/api/post/1', { method: 'GET' }, (err, result) => { expect(err).to.be.an('null') expect(result).to.be.an('object') expect(result).to.deep.equal(mockPost) }) }) })
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.0.0-rc5-master-55cc93f */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.menu */ angular.module('material.components.menu', [ 'material.core', 'material.components.backdrop' ]); angular .module('material.components.menu') .controller('mdMenuCtrl', MenuController); /** * ngInject */ function MenuController($mdMenu, $attrs, $element, $scope, $mdUtil, $timeout, $rootScope, $q) { var menuContainer; var self = this; var triggerElement; this.nestLevel = parseInt($attrs.mdNestLevel, 10) || 0; /** * Called by our linking fn to provide access to the menu-content * element removed during link */ this.init = function init(setMenuContainer, opts) { opts = opts || {}; menuContainer = setMenuContainer; // Default element for ARIA attributes has the ngClick or ngMouseenter expression triggerElement = $element[0].querySelector('[ng-click],[ng-mouseenter]'); this.isInMenuBar = opts.isInMenuBar; this.nestedMenus = $mdUtil.nodesToArray(menuContainer[0].querySelectorAll('.md-nested-menu')); menuContainer.on('$mdInterimElementRemove', function() { self.isOpen = false; }); $scope.$on('$destroy', this.disableHoverListener); }; var openMenuTimeout, menuItems, deregisterScopeListeners = []; this.enableHoverListener = function() { deregisterScopeListeners.push($rootScope.$on('$mdMenuOpen', function(event, el) { if (menuContainer[0].contains(el[0])) { self.currentlyOpenMenu = el.controller('mdMenu'); self.isAlreadyOpening = false; self.currentlyOpenMenu.registerContainerProxy(self.triggerContainerProxy.bind(self)); } })); deregisterScopeListeners.push($rootScope.$on('$mdMenuClose', function(event, el) { if (menuContainer[0].contains(el[0])) { self.currentlyOpenMenu = undefined; } })); menuItems = angular.element($mdUtil.nodesToArray(menuContainer[0].querySelectorAll('md-menu-item'))); menuItems.on('mouseenter', self.handleMenuItemHover); menuItems.on('mouseleave', self.handleMenuItemMouseLeave); }; this.disableHoverListener = function() { while (deregisterScopeListeners.length) { deregisterScopeListeners.shift()(); } menuItems && menuItems.off('mouseenter', self.handleMenuItemHover); menuItems && menuItems.off('mouseleave', self.handleMenuMouseLeave); }; this.handleMenuItemHover = function(event) { if (self.isAlreadyOpening) return; var nestedMenu = ( event.target.querySelector('md-menu') || $mdUtil.getClosest(event.target, 'MD-MENU') ); openMenuTimeout = $timeout(function() { if (nestedMenu) { nestedMenu = angular.element(nestedMenu).controller('mdMenu'); } if (self.currentlyOpenMenu && self.currentlyOpenMenu != nestedMenu) { var closeTo = self.nestLevel + 1; self.currentlyOpenMenu.close(true, { closeTo: closeTo }); } else if (nestedMenu && !nestedMenu.isOpen && nestedMenu.open) { self.isAlreadyOpening = true; } nestedMenu && nestedMenu.open(); }, nestedMenu ? 100 : 250); var focusableTarget = event.currentTarget.querySelector('button:not([disabled])'); focusableTarget && focusableTarget.focus(); }; this.handleMenuItemMouseLeave = function() { if (openMenuTimeout) { $timeout.cancel(openMenuTimeout); openMenuTimeout = undefined; } }; /** * Uses the $mdMenu interim element service to open the menu contents */ this.open = function openMenu(ev) { ev && ev.stopPropagation(); ev && ev.preventDefault(); if (self.isOpen) return; self.enableHoverListener(); self.isOpen = true; triggerElement = triggerElement || (ev ? ev.target : $element[0]); $scope.$emit('$mdMenuOpen', $element); $mdMenu.show({ scope: $scope, mdMenuCtrl: self, nestLevel: self.nestLevel, element: menuContainer, target: triggerElement, preserveElement: self.isInMenuBar || self.nestedMenus.length > 0, parent: self.isInMenuBar ? $element : 'body' }).finally(function() { self.disableHoverListener(); }); }; // Expose a open function to the child scope for html to use $scope.$mdOpenMenu = this.open; $scope.$watch(function() { return self.isOpen; }, function(isOpen) { if (isOpen) { triggerElement.setAttribute('aria-expanded', 'true'); $element[0].classList.add('md-open'); angular.forEach(self.nestedMenus, function(el) { el.classList.remove('md-open'); }); } else { triggerElement && triggerElement.setAttribute('aria-expanded', 'false'); $element[0].classList.remove('md-open'); } $scope.$mdMenuIsOpen = self.isOpen; }); this.focusMenuContainer = function focusMenuContainer() { var focusTarget = menuContainer[0].querySelector('[md-menu-focus-target]'); if (!focusTarget) focusTarget = menuContainer[0].querySelector('.md-button'); focusTarget.focus(); }; this.registerContainerProxy = function registerContainerProxy(handler) { this.containerProxy = handler; }; this.triggerContainerProxy = function triggerContainerProxy(ev) { this.containerProxy && this.containerProxy(ev); }; this.destroy = function() { return self.isOpen ? $mdMenu.destroy() : $q.when(false); }; // Use the $mdMenu interim element service to close the menu contents this.close = function closeMenu(skipFocus, closeOpts) { if ( !self.isOpen ) return; self.isOpen = false; var eventDetails = angular.extend({}, closeOpts, { skipFocus: skipFocus }); $scope.$emit('$mdMenuClose', $element, eventDetails); $mdMenu.hide(null, closeOpts); if (!skipFocus) { var el = self.restoreFocusTo || $element.find('button')[0]; if (el instanceof angular.element) el = el[0]; if (el) el.focus(); } }; /** * Build a nice object out of our string attribute which specifies the * target mode for left and top positioning */ this.positionMode = function positionMode() { var attachment = ($attrs.mdPositionMode || 'target').split(' '); // If attachment is a single item, duplicate it for our second value. // ie. 'target' -> 'target target' if (attachment.length == 1) { attachment.push(attachment[0]); } return { left: attachment[0], top: attachment[1] }; }; /** * Build a nice object out of our string attribute which specifies * the offset of top and left in pixels. */ this.offsets = function offsets() { var position = ($attrs.mdOffset || '0 0').split(' ').map(parseFloat); if (position.length == 2) { return { left: position[0], top: position[1] }; } else if (position.length == 1) { return { top: position[0], left: position[0] }; } else { throw Error('Invalid offsets specified. Please follow format <x, y> or <n>'); } }; } MenuController.$inject = ["$mdMenu", "$attrs", "$element", "$scope", "$mdUtil", "$timeout", "$rootScope", "$q"]; /** * @ngdoc directive * @name mdMenu * @module material.components.menu * @restrict E * @description * * Menus are elements that open when clicked. They are useful for displaying * additional options within the context of an action. * * Every `md-menu` must specify exactly two child elements. The first element is what is * left in the DOM and is used to open the menu. This element is called the trigger element. * The trigger element's scope has access to `$mdOpenMenu($event)` * which it may call to open the menu. By passing $event as argument, the * corresponding event is stopped from propagating up the DOM-tree. * * The second element is the `md-menu-content` element which represents the * contents of the menu when it is open. Typically this will contain `md-menu-item`s, * but you can do custom content as well. * * <hljs lang="html"> * <md-menu> * <!-- Trigger element is a md-button with an icon --> * <md-button ng-click="$mdOpenMenu($event)" class="md-icon-button" aria-label="Open sample menu"> * <md-icon md-svg-icon="call:phone"></md-icon> * </md-button> * <md-menu-content> * <md-menu-item><md-button ng-click="doSomething()">Do Something</md-button></md-menu-item> * </md-menu-content> * </md-menu> * </hljs> * ## Sizing Menus * * The width of the menu when it is open may be specified by specifying a `width` * attribute on the `md-menu-content` element. * See the [Material Design Spec](http://www.google.com/design/spec/components/menus.html#menus-specs) * for more information. * * * ## Aligning Menus * * When a menu opens, it is important that the content aligns with the trigger element. * Failure to align menus can result in jarring experiences for users as content * suddenly shifts. To help with this, `md-menu` provides serveral APIs to help * with alignment. * * ### Target Mode * * By default, `md-menu` will attempt to align the `md-menu-content` by aligning * designated child elements in both the trigger and the menu content. * * To specify the alignment element in the `trigger` you can use the `md-menu-origin` * attribute on a child element. If no `md-menu-origin` is specified, the `md-menu` * will be used as the origin element. * * Similarly, the `md-menu-content` may specify a `md-menu-align-target` for a * `md-menu-item` to specify the node that it should try and align with. * * In this example code, we specify an icon to be our origin element, and an * icon in our menu content to be our alignment target. This ensures that both * icons are aligned when the menu opens. * * <hljs lang="html"> * <md-menu> * <md-button ng-click="$mdOpenMenu($event)" class="md-icon-button" aria-label="Open some menu"> * <md-icon md-menu-origin md-svg-icon="call:phone"></md-icon> * </md-button> * <md-menu-content> * <md-menu-item> * <md-button ng-click="doSomething()" aria-label="Do something"> * <md-icon md-menu-align-target md-svg-icon="call:phone"></md-icon> * Do Something * </md-button> * </md-menu-item> * </md-menu-content> * </md-menu> * </hljs> * * Sometimes we want to specify alignment on the right side of an element, for example * if we have a menu on the right side a toolbar, we want to right align our menu content. * * We can specify the origin by using the `md-position-mode` attribute on both * the `x` and `y` axis. Right now only the `x-axis` has more than one option. * You may specify the default mode of `target target` or * `target-right target` to specify a right-oriented alignment target. See the * position section of the demos for more examples. * * ### Menu Offsets * * It is sometimes unavoidable to need to have a deeper level of control for * the positioning of a menu to ensure perfect alignment. `md-menu` provides * the `md-offset` attribute to allow pixel level specificty of adjusting the * exact positioning. * * This offset is provided in the format of `x y` or `n` where `n` will be used * in both the `x` and `y` axis. * * For example, to move a menu by `2px` from the top, we can use: * <hljs lang="html"> * <md-menu md-offset="2 0"> * <!-- menu-content --> * </md-menu> * </hljs> * ### Preventing close * * Sometimes you would like to be able to click on a menu item without having the menu * close. To do this, ngMaterial exposes the `md-prevent-menu-close` attribute which * can be added to a button inside a menu to stop the menu from automatically closing. * You can then close the menu programatically by injecting `$mdMenu` and calling * `$mdMenu.hide()`. * * <hljs lang="html"> * <md-menu-item> * <md-button ng-click="doSomething()" aria-label="Do something" md-prevent-menu-close="md-prevent-menu-close"> * <md-icon md-menu-align-target md-svg-icon="call:phone"></md-icon> * Do Something * </md-button> * </md-menu-item> * </hljs> * * @usage * <hljs lang="html"> * <md-menu> * <md-button ng-click="$mdOpenMenu($event)" class="md-icon-button"> * <md-icon md-svg-icon="call:phone"></md-icon> * </md-button> * <md-menu-content> * <md-menu-item><md-button ng-click="doSomething()">Do Something</md-button></md-menu-item> * </md-menu-content> * </md-menu> * </hljs> * * @param {string} md-position-mode The position mode in the form of * `x`, `y`. Default value is `target`,`target`. Right now the `x` axis * also suppports `target-right`. * @param {string} md-offset An offset to apply to the dropdown after positioning * `x`, `y`. Default value is `0`,`0`. * */ angular .module('material.components.menu') .directive('mdMenu', MenuDirective); /** * ngInject */ function MenuDirective($mdUtil) { var INVALID_PREFIX = 'Invalid HTML for md-menu: '; return { restrict: 'E', require: ['mdMenu', '?^mdMenuBar'], controller: 'mdMenuCtrl', // empty function to be built by link scope: true, compile: compile }; function compile(templateElement) { templateElement.addClass('md-menu'); var triggerElement = templateElement.children()[0]; if (!triggerElement.hasAttribute('ng-click')) { triggerElement = triggerElement.querySelector('[ng-click],[ng-mouseenter]') || triggerElement; } if (triggerElement && ( triggerElement.nodeName == 'MD-BUTTON' || triggerElement.nodeName == 'BUTTON' ) && !triggerElement.hasAttribute('type')) { triggerElement.setAttribute('type', 'button'); } if (templateElement.children().length != 2) { throw Error(INVALID_PREFIX + 'Expected two children elements.'); } // Default element for ARIA attributes has the ngClick or ngMouseenter expression triggerElement && triggerElement.setAttribute('aria-haspopup', 'true'); var nestedMenus = templateElement[0].querySelectorAll('md-menu'); var nestingDepth = parseInt(templateElement[0].getAttribute('md-nest-level'), 10) || 0; if (nestedMenus) { angular.forEach($mdUtil.nodesToArray(nestedMenus), function(menuEl) { if (!menuEl.hasAttribute('md-position-mode')) { menuEl.setAttribute('md-position-mode', 'cascade'); } menuEl.classList.add('md-nested-menu'); menuEl.setAttribute('md-nest-level', nestingDepth + 1); menuEl.setAttribute('role', 'menu'); }); } return link; } function link(scope, element, attrs, ctrls) { var mdMenuCtrl = ctrls[0]; var isInMenuBar = ctrls[1] != undefined; // Move everything into a md-menu-container and pass it to the controller var menuContainer = angular.element( '<div class="md-open-menu-container md-whiteframe-z2"></div>' ); var menuContents = element.children()[1]; menuContainer.append(menuContents); if (isInMenuBar) { element.append(menuContainer); menuContainer[0].style.display = 'none'; } mdMenuCtrl.init(menuContainer, { isInMenuBar: isInMenuBar }); scope.$on('$destroy', function() { mdMenuCtrl .destroy() .finally(function(){ menuContainer.remove(); }); }); } } MenuDirective.$inject = ["$mdUtil"]; angular .module('material.components.menu') .provider('$mdMenu', MenuProvider); /* * Interim element provider for the menu. * Handles behavior for a menu while it is open, including: * - handling animating the menu opening/closing * - handling key/mouse events on the menu element * - handling enabling/disabling scroll while the menu is open * - handling redrawing during resizes and orientation changes * */ function MenuProvider($$interimElementProvider) { var MENU_EDGE_MARGIN = 8; menuDefaultOptions.$inject = ["$mdUtil", "$mdTheming", "$mdConstant", "$document", "$window", "$q", "$$rAF", "$animateCss", "$animate"]; return $$interimElementProvider('$mdMenu') .setDefaults({ methods: ['target'], options: menuDefaultOptions }); /* ngInject */ function menuDefaultOptions($mdUtil, $mdTheming, $mdConstant, $document, $window, $q, $$rAF, $animateCss, $animate) { var animator = $mdUtil.dom.animator; return { parent: 'body', onShow: onShow, onRemove: onRemove, hasBackdrop: true, disableParentScroll: true, skipCompile: true, preserveScope: true, skipHide: true, themable: true }; /** * Show modal backdrop element... * @returns {function(): void} A function that removes this backdrop */ function showBackdrop(scope, element, options) { if (options.nestLevel) return angular.noop; // If we are not within a dialog... if (options.disableParentScroll && !$mdUtil.getClosest(options.target, 'MD-DIALOG')) { // !! DO this before creating the backdrop; since disableScrollAround() // configures the scroll offset; which is used by mdBackDrop postLink() options.restoreScroll = $mdUtil.disableScrollAround(options.element, options.parent); } else { options.disableParentScroll = false; } if (options.hasBackdrop) { options.backdrop = $mdUtil.createBackdrop(scope, "md-menu-backdrop md-click-catcher"); $animate.enter(options.backdrop, options.parent); } /** * Hide and destroys the backdrop created by showBackdrop() */ return function hideBackdrop() { if (options.backdrop) options.backdrop.remove(); if (options.disableParentScroll) options.restoreScroll(); }; } /** * Removing the menu element from the DOM and remove all associated evetn listeners * and backdrop */ function onRemove(scope, element, opts) { opts.cleanupInteraction(); opts.cleanupResizing(); opts.hideBackdrop(); // For navigation $destroy events, do a quick, non-animated removal, // but for normal closes (from clicks, etc) animate the removal return (opts.$destroy === true) ? detachAndClean() : animateRemoval().then( detachAndClean ); /** * For normal closes, animate the removal. * For forced closes (like $destroy events), skip the animations */ function animateRemoval() { return $animateCss(element, {addClass: 'md-leave'}).start(); } /** * Detach the element */ function detachAndClean() { element.removeClass('md-active'); detachElement(element, opts); opts.alreadyOpen = false; } } /** * Inserts and configures the staged Menu element into the DOM, positioning it, * and wiring up various interaction events */ function onShow(scope, element, opts) { sanitizeAndConfigure(opts); // Wire up theming on our menu element $mdTheming.inherit(opts.menuContentEl, opts.target); // Register various listeners to move menu on resize/orientation change opts.cleanupResizing = startRepositioningOnResize(); opts.hideBackdrop = showBackdrop(scope, element, opts); // Return the promise for when our menu is done animating in return showMenu() .then(function(response) { opts.alreadyOpen = true; opts.cleanupInteraction = activateInteraction(); return response; }); /** * Place the menu into the DOM and call positioning related functions */ function showMenu() { if (!opts.preserveElement) { opts.parent.append(element); } else { element[0].style.display = ''; } return $q(function(resolve) { var position = calculateMenuPosition(element, opts); element.removeClass('md-leave'); // Animate the menu scaling, and opacity [from its position origin (default == top-left)] // to normal scale. $animateCss(element, { addClass: 'md-active', from: animator.toCss(position), to: animator.toCss({transform: ''}) }) .start() .then(resolve); }); } /** * Check for valid opts and set some sane defaults */ function sanitizeAndConfigure() { if (!opts.target) { throw Error( '$mdMenu.show() expected a target to animate from in options.target' ); } angular.extend(opts, { alreadyOpen: false, isRemoved: false, target: angular.element(opts.target), //make sure it's not a naked dom node parent: angular.element(opts.parent), menuContentEl: angular.element(element[0].querySelector('md-menu-content')) }); } /** * Configure various resize listeners for screen changes */ function startRepositioningOnResize() { var repositionMenu = (function(target, options) { return $$rAF.throttle(function() { if (opts.isRemoved) return; var position = calculateMenuPosition(target, options); target.css(animator.toCss(position)); }); })(element, opts); $window.addEventListener('resize', repositionMenu); $window.addEventListener('orientationchange', repositionMenu); return function stopRepositioningOnResize() { // Disable resizing handlers $window.removeEventListener('resize', repositionMenu); $window.removeEventListener('orientationchange', repositionMenu); } } /** * Activate interaction on the menu. Wire up keyboard listerns for * clicks, keypresses, backdrop closing, etc. */ function activateInteraction() { element.addClass('md-clickable'); // close on backdrop click if (opts.backdrop) opts.backdrop.on('click', onBackdropClick); // Wire up keyboard listeners. // - Close on escape, // - focus next item on down arrow, // - focus prev item on up opts.menuContentEl.on('keydown', onMenuKeyDown); opts.menuContentEl[0].addEventListener('click', captureClickListener, true); // kick off initial focus in the menu on the first element var focusTarget = opts.menuContentEl[0].querySelector('[md-menu-focus-target]'); if ( !focusTarget ) { var firstChild = opts.menuContentEl[0].firstElementChild; focusTarget = firstChild && (firstChild.querySelector('.md-button:not([disabled])') || firstChild.firstElementChild); } focusTarget && focusTarget.focus(); return function cleanupInteraction() { element.removeClass('md-clickable'); if (opts.backdrop) opts.backdrop.off('click', onBackdropClick); opts.menuContentEl.off('keydown', onMenuKeyDown); opts.menuContentEl[0].removeEventListener('click', captureClickListener, true); }; // ************************************ // internal functions // ************************************ function onMenuKeyDown(ev) { var handled; switch (ev.keyCode) { case $mdConstant.KEY_CODE.ESCAPE: opts.mdMenuCtrl.close(false, { closeAll: true }); handled = true; break; case $mdConstant.KEY_CODE.UP_ARROW: if (!focusMenuItem(ev, opts.menuContentEl, opts, -1)) { opts.mdMenuCtrl.triggerContainerProxy(ev); } handled = true; break; case $mdConstant.KEY_CODE.DOWN_ARROW: if (!focusMenuItem(ev, opts.menuContentEl, opts, 1)) { opts.mdMenuCtrl.triggerContainerProxy(ev); } handled = true; break; case $mdConstant.KEY_CODE.LEFT_ARROW: if (opts.nestLevel) { opts.mdMenuCtrl.close(); } else { opts.mdMenuCtrl.triggerContainerProxy(ev); } handled = true; break; case $mdConstant.KEY_CODE.RIGHT_ARROW: var parentMenu = $mdUtil.getClosest(ev.target, 'MD-MENU'); if (parentMenu && parentMenu != opts.parent[0]) { ev.target.click(); } else { opts.mdMenuCtrl.triggerContainerProxy(ev); } handled = true; break; } if (handled) { ev.preventDefault(); ev.stopImmediatePropagation(); } } function onBackdropClick(e) { e.preventDefault(); e.stopPropagation(); scope.$apply(function() { opts.mdMenuCtrl.close(true, { closeAll: true }); }); } // Close menu on menu item click, if said menu-item is not disabled function captureClickListener(e) { var target = e.target; // Traverse up the event until we get to the menuContentEl to see if // there is an ng-click and that the ng-click is not disabled do { if (target == opts.menuContentEl[0]) return; if ((hasAnyAttribute(target, ['ng-click', 'ng-href', 'ui-sref']) || target.nodeName == 'BUTTON' || target.nodeName == 'MD-BUTTON') && !hasAnyAttribute(target, ['md-prevent-menu-close'])) { var closestMenu = $mdUtil.getClosest(target, 'MD-MENU'); if (!target.hasAttribute('disabled') && (!closestMenu || closestMenu == opts.parent[0])) { close(); } break; } } while (target = target.parentNode) function close() { scope.$apply(function() { opts.mdMenuCtrl.close(true, { closeAll: true }); }); } function hasAnyAttribute(target, attrs) { if (!target) return false; for (var i = 0, attr; attr = attrs[i]; ++i) { var altForms = [attr, 'data-' + attr, 'x-' + attr]; for (var j = 0, rawAttr; rawAttr = altForms[j]; ++j) { if (target.hasAttribute(rawAttr)) { return true; } } } return false; } } opts.menuContentEl[0].addEventListener('click', captureClickListener, true); return function cleanupInteraction() { element.removeClass('md-clickable'); opts.menuContentEl.off('keydown'); opts.menuContentEl[0].removeEventListener('click', captureClickListener, true); }; } } /** * Takes a keypress event and focuses the next/previous menu * item from the emitting element * @param {event} e - The origin keypress event * @param {angular.element} menuEl - The menu element * @param {object} opts - The interim element options for the mdMenu * @param {number} direction - The direction to move in (+1 = next, -1 = prev) */ function focusMenuItem(e, menuEl, opts, direction) { var currentItem = $mdUtil.getClosest(e.target, 'MD-MENU-ITEM'); var items = $mdUtil.nodesToArray(menuEl[0].children); var currentIndex = items.indexOf(currentItem); // Traverse through our elements in the specified direction (+/-1) and try to // focus them until we find one that accepts focus var didFocus; for (var i = currentIndex + direction; i >= 0 && i < items.length; i = i + direction) { var focusTarget = items[i].querySelector('.md-button'); didFocus = attemptFocus(focusTarget); if (didFocus) { break; } } return didFocus; } /** * Attempts to focus an element. Checks whether that element is the currently * focused element after attempting. * @param {HTMLElement} el - the element to attempt focus on * @returns {bool} - whether the element was successfully focused */ function attemptFocus(el) { if (el && el.getAttribute('tabindex') != -1) { el.focus(); return ($document[0].activeElement == el); } } /** * Use browser to remove this element without triggering a $destroy event */ function detachElement(element, opts) { if (!opts.preserveElement) { if (toNode(element).parentNode === toNode(opts.parent)) { toNode(opts.parent).removeChild(toNode(element)); } } else { toNode(element).style.display = 'none'; } } /** * Computes menu position and sets the style on the menu container * @param {HTMLElement} el - the menu container element * @param {object} opts - the interim element options object */ function calculateMenuPosition(el, opts) { var containerNode = el[0], openMenuNode = el[0].firstElementChild, openMenuNodeRect = openMenuNode.getBoundingClientRect(), boundryNode = $document[0].body, boundryNodeRect = boundryNode.getBoundingClientRect(); var menuStyle = $window.getComputedStyle(openMenuNode); var originNode = opts.target[0].querySelector('[md-menu-origin]') || opts.target[0], originNodeRect = originNode.getBoundingClientRect(); var bounds = { left: boundryNodeRect.left + MENU_EDGE_MARGIN, top: Math.max(boundryNodeRect.top, 0) + MENU_EDGE_MARGIN, bottom: Math.max(boundryNodeRect.bottom, Math.max(boundryNodeRect.top, 0) + boundryNodeRect.height) - MENU_EDGE_MARGIN, right: boundryNodeRect.right - MENU_EDGE_MARGIN }; var alignTarget, alignTargetRect = { top:0, left : 0, right:0, bottom:0 }, existingOffsets = { top:0, left : 0, right:0, bottom:0 }; var positionMode = opts.mdMenuCtrl.positionMode(); if (positionMode.top == 'target' || positionMode.left == 'target' || positionMode.left == 'target-right') { alignTarget = firstVisibleChild(); if ( alignTarget ) { // TODO: Allow centering on an arbitrary node, for now center on first menu-item's child alignTarget = alignTarget.firstElementChild || alignTarget; alignTarget = alignTarget.querySelector('[md-menu-align-target]') || alignTarget; alignTargetRect = alignTarget.getBoundingClientRect(); existingOffsets = { top: parseFloat(containerNode.style.top || 0), left: parseFloat(containerNode.style.left || 0) }; } } var position = {}; var transformOrigin = 'top '; switch (positionMode.top) { case 'target': position.top = existingOffsets.top + originNodeRect.top - alignTargetRect.top; break; case 'cascade': position.top = originNodeRect.top - parseFloat(menuStyle.paddingTop) - originNode.style.top; break; case 'bottom': position.top = originNodeRect.top + originNodeRect.height; break; default: throw new Error('Invalid target mode "' + positionMode.top + '" specified for md-menu on Y axis.'); } switch (positionMode.left) { case 'target': position.left = existingOffsets.left + originNodeRect.left - alignTargetRect.left; transformOrigin += 'left'; break; case 'target-right': position.left = originNodeRect.right - openMenuNodeRect.width + (openMenuNodeRect.right - alignTargetRect.right); transformOrigin += 'right'; break; case 'cascade': var willFitRight = (originNodeRect.right + openMenuNodeRect.width) < bounds.right; position.left = willFitRight ? originNodeRect.right - originNode.style.left : originNodeRect.left - originNode.style.left - openMenuNodeRect.width; transformOrigin += willFitRight ? 'left' : 'right'; break; case 'left': position.left = originNodeRect.left; transformOrigin += 'left'; break; default: throw new Error('Invalid target mode "' + positionMode.left + '" specified for md-menu on X axis.'); } var offsets = opts.mdMenuCtrl.offsets(); position.top += offsets.top; position.left += offsets.left; clamp(position); var scaleX = Math.round(100 * Math.min(originNodeRect.width / containerNode.offsetWidth, 1.0)) / 100; var scaleY = Math.round(100 * Math.min(originNodeRect.height / containerNode.offsetHeight, 1.0)) / 100; return { top: Math.round(position.top), left: Math.round(position.left), // Animate a scale out if we aren't just repositioning transform: !opts.alreadyOpen ? $mdUtil.supplant('scale({0},{1})', [scaleX, scaleY]) : undefined, transformOrigin: transformOrigin }; /** * Clamps the repositioning of the menu within the confines of * bounding element (often the screen/body) */ function clamp(pos) { pos.top = Math.max(Math.min(pos.top, bounds.bottom - containerNode.offsetHeight), bounds.top); pos.left = Math.max(Math.min(pos.left, bounds.right - containerNode.offsetWidth), bounds.left); } /** * Gets the first visible child in the openMenuNode * Necessary incase menu nodes are being dynamically hidden */ function firstVisibleChild() { for (var i = 0; i < openMenuNode.children.length; ++i) { if ($window.getComputedStyle(openMenuNode.children[i]).display != 'none') { return openMenuNode.children[i]; } } } } } function toNode(el) { if (el instanceof angular.element) { el = el[0]; } return el; } } MenuProvider.$inject = ["$$interimElementProvider"]; })(window, window.angular);
define(function (require) { 'use strict'; var Marionette = require('backbone.marionette'); // Enrich Marionette with the Modal Region require('marionette.modal'); var App = new Marionette.Application(); App.addRegions({ menu: '[data-region="menu"]', content: '[data-region="content"]', modal: Marionette.Region.Modal.extend({ el: '[data-region="modal"]' }) }); return App; });
export default () => <h1 id="other-page-title">Hello Other</h1>
'use strict'; var articles = require('../controllers/articles'); // Article authorization helpers var hasAuthorization = function(req, res, next) { if (!req.user.isAdmin && req.article.user.id !== req.user.id) { return res.send(401, 'User is not authorized'); } next(); }; module.exports = function(Articles, app, auth) { app.route('/articles') .get(articles.all) .post(auth.requiresLogin, articles.create); app.route('/articles/:articleId') .get(articles.show) .put(auth.requiresLogin, hasAuthorization, articles.update) .put(auth.requiresLogin, hasAuthorization, articles.book) .delete(auth.requiresLogin, hasAuthorization, articles.destroy); // Finish with setting up the articleId param app.param('articleId', articles.article); };
import React from 'react'; import PropTypes from 'prop-types'; import { Row, Col, Button, OverlayTrigger, Tooltip } from 'react-bootstrap'; import './LoadedValuesList.css'; const LoadedValuesListItem = ({ value, onDelete }) => ( <Row className="Loaded-item"> <Col xs={11} className="Loaded-text-col"> <OverlayTrigger placement="top" overlay={<Tooltip id="tooltip">{'loaded-' + value.testId}</Tooltip>} > <span className="Loaded-text-id">{value.testId}</span> </OverlayTrigger> <br /> <span>{value.versionId}</span> </Col> <Col xs={1} className="Loaded-close-col"> <Button className="Loaded-close-btn" bsStyle="link" onClick={onDelete}> &times; </Button> </Col> </Row> ); LoadedValuesListItem.propTypes = { value: PropTypes.object, onDelete: PropTypes.func }; export default LoadedValuesListItem;
angular.module('localStorage',[]) .factory("$store",function($parse){ /** * Global Vars */ var storage = (typeof window.localStorage === 'undefined') ? undefined : window.localStorage, supported = !(typeof storage == 'undefined' || typeof window.JSON == 'undefined'); var privateMethods = { /** * Pass any type of a string from the localStorage to be parsed so it returns a usable version (like an Object) * @param res - a string that will be parsed for type * @returns {*} - whatever the real type of stored value was */ parseValue: function(res) { var val; try { val = JSON.parse(res); if (typeof val == 'undefined'){ val = res; } if (val == 'true'){ val = true; } if (val == 'false'){ val = false; } if (parseFloat(val) == val && !angular.isObject(val) ){ val = parseFloat(val); } } catch(e){ val = res; } return val; } }; var publicMethods = { /** * Set - let's you set a new localStorage key pair set * @param key - a string that will be used as the accessor for the pair * @param value - the value of the localStorage item * @returns {*} - will return whatever it is you've stored in the local storage */ set: function(key,value){ if (!supported){ try { $.cookie(key, value); return value; } catch(e){ console.log('Local Storage not supported, make sure you have the $.cookie supported.'); } } var saver = JSON.stringify(value); storage.setItem(key, saver); return privateMethods.parseValue(saver); }, /** * Get - let's you get the value of any pair you've stored * @param key - the string that you set as accessor for the pair * @returns {*} - Object,String,Float,Boolean depending on what you stored */ get: function(key){ if (!supported){ try { return privateMethods.parseValue($.cookie(key)); } catch(e){ return null; } } var item = storage.getItem(key); return privateMethods.parseValue(item); }, /** * Remove - let's you nuke a value from localStorage * @param key - the accessor value * @returns {boolean} - if everything went as planned */ remove: function(key) { if (!supported){ try { $.cookie(key, null); return true; } catch(e){ return false; } } storage.removeItem(key); return true; }, /** * Bind - let's you directly bind a localStorage value to a $scope variable * @param $scope - the current scope you want the variable available in * @param key - the name of the variable you are binding * @param def - the default value (OPTIONAL) * @returns {*} - returns whatever the stored value is */ bind: function ($scope, key, def) { def = def || ''; if (!publicMethods.get(key)) { publicMethods.set(key, def); } $parse(key).assign($scope, publicMethods.get(key)); $scope.$watch(key, function (val) { publicMethods.set(key, val); }, true); return publicMethods.get(key); } }; return publicMethods; });
// Horizontal rule import { isSpace } from '../common/utils.js'; export default function hr(state, startLine, endLine, silent) { let marker, cnt, ch, token, originalPos, pos = state.bMarks[startLine] + state.tShift[startLine], max = state.eMarks[startLine]; // if it's indented more than 3 spaces, it should be a code block if (state.sCount[startLine] - state.blkIndent >= 4) { return false; } originalPos = pos; marker = state.src.charCodeAt(pos++); // Check hr marker if (marker !== 0x2A/* * */ && marker !== 0x2D/* - */ && marker !== 0x5F/* _ */) { return false; } // markers can be mixed with spaces, but there should be at least 3 of them cnt = 1; while (pos < max) { ch = state.src.charCodeAt(pos++); if (ch !== marker && !isSpace(ch)) { return false; } if (ch === marker) { cnt++; } } if (cnt < 3) { return false; } if (silent) { return true; } state.line = startLine + 1; token = state.push('hr', 'hr', 0); token.map = [ startLine, state.line ]; token.markup = Array(cnt + 1).join(String.fromCharCode(marker)); token.position = originalPos; token.size = pos - originalPos; return true; }
import Microcosm from '../../../src/microcosm' describe('Microcosm::prepare', function() { it('partially applies Microcosm::push', function() { const repo = new Microcosm() const action = jest.fn() repo.prepare(action, 1, 2)(3) expect(action).toBeCalledWith(1, 2, 3) }) })
(function(win) { if (win.LoginRadiusV2) { LoginRadiusV2.prototype.loginScreen = function(container, options, cb) { options = options || {}; if(options.pagesshown){ if (options.pagesshown.length==0){ alert("there is nothing to display, check your options.pagesshown"); return; } for(var i = 0; i<options.pagesshown.length; i++){ options[options.pagesshown[i]] = true; } } cb = cb || function(response,Event){}; var LoginScreen = document.createElement("div"); LoginScreen.innerHTML = generateLayout(container, options); addHTMLContent(container, LoginScreen); renderJS(cb, options, this); }; } function addHTMLContent(container, data, innerHtml) { innerHtml = innerHtml || false; var containerElem = document.getElementById(container); containerElem.classList.add("lr-ls-loginscreencontainer") if (containerElem) { if (!innerHtml) { containerElem.innerHTML = ''; } containerElem.appendChild(data); } else { var containerElem = document.getElementsByClassName(container); if (containerElem && containerElem.length > 0) { for (var j = 0; j < containerElem.length; j++) { if (!innerHtml) { containerElem[j].innerHTML = ''; } containerElem[j].appendChild(data); } } } } function generateLayout(container, options) { return '<style type="text/css"> .lr-ls-loginscreencontainer * {'+ ' margin: 0;'+ ' padding: 0;'+ ' box-sizing: border-box;'+ ' vertical-align: middle;'+ ' border-style: hidden;'+ ' font-family:' + ((options.body && options.body.fontFamily) ? ('"'+options.body.fontFamily+'",') : " ") + ' "-apple-system", "system-ui", "Helvetica Neue", "Helvetica", "Arial", "sans-serif";' + '}'+ '@media only screen and (max-device-width: 959px) {'+ ' .lr-ls-page {'+ ' position: relative;'+ ' width: 100%;'+ ' height: 100vh;'+ ' background-color: #FFFFFF;'+ ' box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.2), 0 1px 1px 0 rgba(0, 0, 0, 0.12);'+ ' }'+ ' .lr-ls-logobase {'+ ' height: 22vw;'+ ' background-color:' + ((options.logo && options.logo.color) ? options.logo.color : " #F5F5F5") +';' + ' }'+ ' #lr-ls-logo-place {'+ ' display: block;'+ ' margin-left: auto;'+ ' margin-right: auto;'+ ' width: 50%;'+ ' padding-top: 5vw;'+ ' }'+ ' .lr-ls-tabs {'+ ' display: block;'+ ' position: relative;'+ ' }'+ ' .lr-ls-tabs .tab {'+ ' width: 50%;'+ ' float: left;'+ ' display: flex;'+ ' flex-direction: row;'+ ((options.body && options.body.backgroundColor) ? ('background-color:' + options.body.backgroundColor +';') : ('background-color: #FFFFFF;')) + ' }'+ ' .lr-ls-tabs .tab>input[type="radio"] {'+ ' position: absolute;'+ ' top: -9999px;'+ ' left: -9999px;'+ ' }'+ ' .lr-ls-tabs .tab>label {'+ ' width: 50vw;'+ ' flex: 1 1 auto;'+ ' display: block;'+ ' cursor: pointer;'+ ' position: relative;'+ ' color: #384049;'+ ' font-size: 4.28vw;'+ ' line-height: 6.13333rem;'+ ' text-align: center;'+ ' vertical-align: middle;'+ ' border-bottom: 0.5rem solid #EEEEEE;'+ ' }'+ ' .lr-ls-tabs .content {'+ ' z-index: 0;'+ ' /* or display: none; */'+ ' overflow: hidden;'+ ' width: 100%;'+ ' position: absolute;'+ ' top: 6.5rem;'+ ' /* this field determines the height of the line below the label*/'+ ' left: 0;'+ ' background-color: #FFFFFF;'+ ' display: none;'+ ' -webkit-transition: all linear 0.3s;'+ ' -moz-transition: all linear 0.3s;'+ ' -o-transition: all linear 0.3s;'+ ' -ms-transition: all linear 0.3s;'+ ' transition: all linear 0.3s;'+ ' -webkit-transform: translateX(-250px);'+ ' -moz-transform: translateX(-250px);'+ ' -o-transform: translateX(-250px);'+ ' -ms-transform: translateX(-250px);'+ ' transform: translateX(-250px);'+ ' }'+ ' .Resetpw-content {'+ ' display: none;'+ ((options.singlepagestyle)? '' : ('left:360px'))+ ' }'+ ' .lr-ls-tabs>.tab>[id^="tab"]:checked+label {'+ ' top: 0;'+ ' border-bottom: 0.5rem solid #BDBDBD;'+ ' -webkit-animation: page 0.2s linear;'+ ' -moz-animation: page 0.2s linear;'+ ' -ms-animation: page 0.2s linear;'+ ' -o-animation: page 0.2s linear;'+ ' animation: page 0.2s linear;'+ ' }'+ ' .lr-ls-tabs>.tab>[id^="tab"]:checked~[id^="tab-content"] {'+ ((options.body && options.body.backgroundColor) ? ('background-color:' + options.body.backgroundColor +';') : ('')) + ' z-index: 1;'+ ' /* or display: block; */'+ ' display: block;'+ ' -webkit-transform: translateX(0px);'+ ' -moz-transform: translateX(0px);'+ ' -o-transform: translateX(0px);'+ ' -ms-transform: translateX(0px);'+ ' transform: translateX(0px);'+ ' -webkit-transition: all ease-out 0.8s 0.1s;'+ ' -moz-transition: all ease-out 0.8s 0.1s;'+ ' -o-transition: all ease-out 0.8s 0.1s;'+ ' -ms-transition: all ease-out 0.8s 0.1s;'+ ' transition: all ease-out 0.8s 0.1s;'+ ' overflow: hidden;'+ ' }'+ ' .greeting {'+ ' margin-top: 4vh;'+ ' width: 91vw;'+ ' font-size: 5vw;'+ ' margin-bottom: 3rem;'+ ' line-height: 4rem;'+ ' color: #424242;'+ ' }'+ ' #lr-ls-sectiondivider,#lr-ls-sectiondividerL {'+ ' margin-top: 3.2rem;'+ ' display: block;'+ ' margin-left: auto;'+ ' margin-right: auto;'+ ' height: 1.5rem;'+ ' text-align: center;'+ ' color: #424242;'+ ' font-size: 5vw;'+ ' line-height: 5rem;'+ ' }'+ (options.socialsquarestyle ? ' .social-login-b-options {'+ ' margin-top: 6vh;'+ ' width: 91vw;'+ ' text-align: center;'+ ' font-size: 5vw;'+ ' font-weight: 400;'+ ' -webkit-animation: slide-up 1s ease-out;'+ ' -moz-animation: slide-up 1s ease-out;'+ ' }'+ ' .social-login-b-options .lr-sl-shaded-brick-button {'+ ' height: 8rem;'+ ' width: 8rem;'+ ' border-radius: 0.5rem;'+ ' overflow: hidden;'+ ' margin-top: 2.5vw;'+ ' position: relative;'+ ' border: 1px solid rgba(0, 0, 0, 0.1);'+ ' text-align: left;'+ ' text-decoration: none;'+ ' color: white;'+ ' box-shadow: 0 0 1px 0 rgba(0, 0, 0, 0.12), 0 1px 1px 0 rgba(0, 0, 0, 0.24), 0 0 8px 0 rgba(0, 0, 0, 0.12), 0 2px 2px 0 rgba(0, 0, 0, 0.24);'+ ' }'+ ' .social-login-b-options .lr-sl-shaded-brick-button .lr-sl-icon {'+ ' top: 0;'+ ' left: 0;'+ ' display: inline-block;'+ ' position: absolute;'+ ' }'+ ' .lr-provider-label {'+ ' margin-top: 8px;'+ ' display: inline-block;'+ ' }' : ' .social-login-b-options {'+ ' margin-top: 6vh;'+ ' width: 91vw;'+ ' text-align: center;'+ ' font-size: 5vw;'+ ' font-weight: 400;'+ ' -webkit-animation: slide-up 1s ease-out;'+ ' -moz-animation: slide-up 1s ease-out;'+ ' }'+ ' .social-login-b-options .lr-sl-shaded-brick-button {'+ ' height: 8rem;'+ ' width: 100%;'+ ' border-radius: 0.5rem;'+ ' overflow: hidden;'+ ' margin-top: 2.5vw;'+ ' position: relative;'+ ' border: 1px solid rgba(0, 0, 0, 0.1);'+ ' text-align: left;'+ ' text-decoration: none;'+ ' color: white;'+ ' padding: 2rem 0 0.8rem 8rem;'+ ' box-shadow: 0 0 1px 0 rgba(0, 0, 0, 0.12), 0 1px 1px 0 rgba(0, 0, 0, 0.24), 0 0 8px 0 rgba(0, 0, 0, 0.12), 0 2px 2px 0 rgba(0, 0, 0, 0.24);'+ ' }'+ ' .social-login-b-options .lr-sl-shaded-brick-button .lr-sl-icon {'+ ' top: 0;'+ ' left: 0;'+ ' display: inline-block;'+ ' position: absolute;'+ ' }'+ ' .lr-provider-label {'+ ' display: block;'+ ' }' ) + ' .lr-sl-icon:before {'+ ' width: 8rem;'+ ' height: 8rem;'+ ' background: url("http://cdn.loginradius.com/hub/prod/v1/hosted-page-default-images/icon-sprite-32.png");'+ ' background-image: linear-gradient(transparent, transparent), url("http://cdn.loginradius.com/hub/prod/v1/hosted-page-default-images/icon-sprite.svg"), none;'+ ' background-size: 100% 3600%;'+ ' background-position: 0 0;'+ ' margin-top: -4px;'+ ' margin-top: -0.4rem;'+ ' }'+ ' .lr-ls-status-area {'+ ' margin-left: auto;'+ ' margin-right: auto;'+ ' width: 100vw;'+ ' display: none;'+ ' z-index: 2;'+ ' }'+ ' .lr-iconsuccess {'+ ' font-family: arial;'+ ' -ms-transform: scaleX(-1) rotate(-35deg); /* IE 9 */'+ ' -webkit-transform: scaleX(-1) rotate(-35deg); /* Chrome, Safari, Opera */'+ ' transform: scaleX(-1) rotate(-35deg);'+ ' float: left;'+ ' margin-right: 6px;'+ ' }'+ ' .lr-iconerror {'+ ' text-align: center;'+ ' font-family: sans-serif;'+ ' float: left;'+ ' margin-right: 6px;'+ ' }'+ ' .lr-ls-divsuccess {'+ ' display: none;'+ ' padding: 0.8rem;'+ ' border: 1px solid #3EA34D;'+ ' color: #FFFFFF;'+ ' font-size: 4vw;'+ ' line-height: 3rem;'+ ' font-weight: 600;'+ ' vertical-align: middle;'+ ' }'+ ' .lr-ls-diverror {'+ ' display: none;'+ ' padding: 0.8rem;'+ ' border: 1px solid #FF1744;'+ ' color: #FFFFFF;'+ ' font-size: 4vw;'+ ' line-height: 3rem;'+ ' font-weight: 600;'+ ' vertical-align: middle;'+ ' }'+ ' ::-webkit-input-placeholder {'+ ' font-size: 4vw;'+ ' line-height: 100%;'+ ' }'+ ' .loginradius--form-element-content {'+ ' text-align: left;'+ ' margin-bottom: 4rem;'+ ' margin-bottom: 6.5vw;'+ ' }'+ ' #login-container .loginradius--form-element-content, #registration-container .loginradius--form-element-content, #forgotpassword-container .loginradius--form-element-content, #resetpassword-container .loginradius--form-element-content {'+ ' padding-left: 3rem;'+ ' }'+ ' .loginradius--form-element-content label {'+ ' color:' + ((options.body && options.body.textColor) ? options.body.textColor : '#616161') + ';' + ' font-size: 5vw;'+ ' line-height: 4rem;'+ ' }'+ ' #login-container,'+ ' #registration-container,'+ ' #forgotpassword-container {'+ ' margin-top: 5rem;'+ ' width: 91vw;'+ ' z-index: 0;'+ ' }'+ ' #forgotpassword-container {'+ ' margin-top: 16px;'+ ' }'+ ' input .invalid {'+ ' border: 1px solid #FF1744;'+ ' background-color: #F5F5F5;'+ ' }'+ ' select {'+ ' height: 5rem;'+ ' background-color: #F5F5F6;'+ ' font-size: 5vw;'+ ' font-weight: 300;'+ ' padding: 8px;'+ ' margin-left: 20px;'+ ' }'+ ' textarea,'+ ' input[type="password"],'+ ' input[type="text"] {'+ ' margin-top: 4px;'+ ' height: 5rem;'+ ' width: 91vw;'+ ' background-color:' + ((options.input && options.input.background) ? options.input.background : ' #F5F5F5') + ';' + ' border-style: hidden;'+ ' font-size: 5vw;'+ ' font-weight: 300;'+ ' line-height: 100%;'+ ' padding: 8px;'+ ' -webkit-box-sizing: border-box;'+ ' box-sizing: border-box;'+ ' }'+ ' input[type="submit"] {'+ ' margin-top: 2.5rem;'+ ' margin-top: 4.2vw;'+ ' color: #FFFFFF;'+ ' font-size: 5vw;'+ ' text-align: center;'+ ' letter-spacing: 0.2rem;'+ ' cursor: pointer;'+ ' }'+ ' .content-loginradius-stayLogin {'+ ' margin-top: 2rem;'+ ' display: flex;'+ ' }'+ ' input[type="checkbox"] {'+ ' height: 3rem;'+ ' width: 3rem;'+ ' border: 1px solid #9E9E9E;'+ ' vertical-align: middle;'+ ' }'+ ' .content-loginradius-stayLogin label {'+ ' height: 3rem;'+ ' color:' + ((options.body && options.body.textColor) ? options.body.textColor : '#616161') + ';' + ' font-size: 4.5vw;'+ ' line-height: 3rem;'+ ' }'+ ' #lr-forgotpw-btn {'+ ' color:' + ((options.body && options.body.textColor) ? options.body.textColor : '#616161') + ';' + ' cursor: pointer;'+ ' font-size: 4.5vw;'+ ' line-height: 3rem;'+ ' height: 3rem;'+ ' right: 4.5vw;'+ ' bottom: 26.5vw;'+ ' float: right;'+ ' }'+ ' #loginradius-submit-login {'+ ' margin-right: auto;'+ ' height: 16vw;'+ ' width: 91vw;'+ ' background-color: #35a8ff;'+ ' box-shadow: 0 2px 5px 0 rgba(0, 0, 0, .16), 0 2px 10px 0 rgba(0, 0, 0, .12);'+ ' outline: none;'+ ' border-radius: 1rem 1rem 1rem 1rem;' + ' }'+ ' [id *= "loginradius-submit-"] {'+ ' margin-left: 3rem;'+ ' margin-right: auto;'+ ' height: 16vw;'+ ' width: 91vw;'+ ' background-color: #35a8ff;'+ ' box-shadow: 0 2px 5px 0 rgba(0, 0, 0, .16), 0 2px 10px 0 rgba(0, 0, 0, .12);'+ ' outline: none;'+ ' border-radius: 1rem 1rem 1rem 1rem;' + ' }'+ ' [id *= "loginradius-submit-"]:hover,'+ ' #loginradius-submit-reset-password:hover {'+ ' filter: brightness(98%);'+ ' transition: color 400ms;'+ ' }'+ ' [id *= "loginradius-submit-"]:active {'+ ' filter: brightness(85%);'+ ' transition: color 400ms;'+ ' }'+ ' #forgotPW {'+ ' height: 17px;'+ ' color: #424242;'+ ' font-size: 4vw;'+ ' line-height: 17px;'+ ' text-align: center;'+ ' text-decoration: none;'+ ' position: absolute;'+ ' }'+ ' #reset-password {'+ ' height: 5rem;'+ ' color: #414141;'+ ' font-size: 6vw;'+ ' font-weight: 300;'+ ' line-height: 37px;'+ ' }'+ ' .loginradius-validation-message {'+ ' color: #FF1744;'+ ' font-size: 3.28vw;'+ ' line-height: 2rem;'+ ' margin-top: 1rem;'+ ' }'+ ' #loginradius-showQRcode-ManualEntryCode {'+ ' font-size: 4vw;'+ ' }'+ ' #loginradius-button-resendotp {'+ ' font-size: 4vw;'+ ' }'+ ' #loginradius-button-changenumber {'+ ' font-size: 4vw;'+ ' }'+ ' @-webkit-keyframes slide-up {'+ ' 0% {'+ ' opacity: 0;'+ ' -webkit-transform: translateY(-100%);'+ ' }'+ ' 100% {'+ ' opacity: 1;'+ ' -webkit-transform: translateY(0);'+ ' }'+ ' }'+ ' @-moz-keyframes slide-up {'+ ' 0% {'+ ' opacity: 0;'+ ' -moz-transform: translateY(-100%);'+ ' }'+ ' 100% {'+ ' opacity: 1;'+ ' -moz-transform: translateY(0);'+ ' }'+ ' }'+ ' .lr-ls-pageloader {'+ ' display: none;'+ ' z-index: 999;'+ ' width: 100%;'+ ' height: 100%;'+ ' position: fixed;'+ ' top: 0;'+ ' right: 0;'+ ' bottom: 0;'+ ' left: 0;'+ ' background-color: rgba(0, 0, 0, .5);'+ ' }'+ ' .lr-ls-page-loadwheel {'+ ' width: 15vw;'+ ' height: 15vw;'+ ' margin-top: -7.5vw;'+ ' margin-left: -7.5vw;'+ ' position: absolute;'+ ' top: 50%;'+ ' left: 50%;'+ ' border-width: 30px;'+ ' border-radius: 50%;'+ ' border: 10px solid #f3f3f3;'+ ' border-radius: 50%;'+ ' border-top: 10px solid #3498db;'+ ' -webkit-animation: spin 2s linear infinite;'+ ' /* Safari */'+ ' animation: spin 2s linear infinite;'+ ' }'+ ' @-webkit-keyframes spin {'+ ' 0% {'+ ' -webkit-transform: rotate(0deg);'+ ' }'+ ' 100% {'+ ' -webkit-transform: rotate(360deg);'+ ' }'+ ' }'+ ' @keyframes spin {'+ ' 0% {'+ ' transform: rotate(0deg);'+ ' }'+ ' 100% {'+ ' transform: rotate(360deg);'+ ' }'+ ' }'+ '}'+ ''+ '@media only screen and (min-device-width: 960px) {'+ ' .lr-ls-page {'+ ' position: relative;'+ ' width:' + ((options.singlepagestyle) ? "360px;" : "720px;")+ ' border-radius: 6px 6px 0 0;'+ ' background-color: #FFFFFF;'+ ' box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.2), 0 1px 1px 0 rgba(0, 0, 0, 0.12);'+ ' margin: 5% auto;'+ ' }'+ ' .lr-ls-logobase {'+ ((options.singlepagestyle) ? (' height: 90px;') : (' float: left;'))+ ' width: 360px;'+ ((options.singlepagestyle) ? (' border-radius: 6px 6px 0 0;') : (' border-radius: 6px 0 0 6px;'))+ ' background-color:' + ((options.logo && options.logo.color) ? options.logo.color : " #F5F5F5") +';' + ' }'+ ' #lr-ls-logo-place {'+ ' display: block;'+ ' margin-left: auto;'+ ' margin-right: auto;'+ ' width: 50%;'+ ' padding-top: 23.67px;'+ ' }'+ ' .lr-ls-tabs {'+ ' display: block;'+ ' position: relative;'+ ' background-color: #FFFFFF;'+ ' }'+ ' .lr-ls-tabs .tab {'+ ' float: left;'+ ' display: flex;'+ ' flex-direction: row;'+ ((options.body && options.body.backgroundColor) ? ('background-color:' + options.body.backgroundColor +';') : ('background-color: #FFFFFF;')) + ' }'+ ' .lr-ls-tabs .tab>input[type="radio"] {'+ ' position: absolute;'+ ' top: -9999px;'+ ' left: -9999px;'+ ' }'+ ' .lr-ls-tabs .tab>label {'+ ' width: 180px;'+ ' flex: 1 1 auto;'+ ' display: block;'+ ' cursor: pointer;'+ ' position: relative;'+ ' color: #384049;'+ ' font-size: 15px;'+ ' line-height: 38px;'+ ' text-align: center;'+ ' vertical-align: middle;'+ ' border-bottom: 4px solid #EEEEEE;'+ ' }'+ ' .lr-ls-tabs .content {'+ ' margin-top: 14px;'+ ' /* this field determines the height of the line below the label*/'+ ' z-index: 0;'+ ' /* or display: none; */'+ ' overflow: hidden;'+ ' width: 360px;'+ ' position: absolute;'+ ' top: 27px;'+ ((options.singlepagestyle) ? ('left: 0; border-radius: 0 0 8px 8px;') : ('left: 360px; border-radius: 0 0 8px 0;')) + ' background-color: #FFFFFF;'+ ' display: none;'+ ' -webkit-transition: all linear 0.3s;'+ ' -moz-transition: all linear 0.3s;'+ ' -o-transition: all linear 0.3s;'+ ' -ms-transition: all linear 0.3s;'+ ' transition: all linear 0.3s;'+ ' -webkit-transform: translateX(-250px);'+ ' -moz-transform: translateX(-250px);'+ ' -o-transform: translateX(-250px);'+ ' -ms-transform: translateX(-250px);'+ ' transform: translateX(-10px);'+ ' }'+ ' .Resetpw-content {'+ ' display: none;'+ ' }'+ ' .lr-ls-tabs>.tab>[id^="tab"]:checked+label {'+ ' top: 0;'+ ' border-bottom: 4px solid #BDBDBD;'+ ' -webkit-animation: page 0.2s linear;'+ ' -moz-animation: page 0.2s linear;'+ ' -ms-animation: page 0.2s linear;'+ ' -o-animation: page 0.2s linear;'+ ' animation: page 0.2s linear;'+ ' }'+ ' .lr-ls-tabs>.tab>[id^="tab"]:checked~[id^="tab-content"] {'+ ((options.body && options.body.backgroundColor) ? ('background-color:' + options.body.backgroundColor +';') : ('')) + ' z-index: 1;'+ ' /* or display: block; */'+ ' display: block;'+ ' -webkit-transform: translateX(0px);'+ ' -moz-transform: translateX(0px);'+ ' -o-transform: translateX(0px);'+ ' -ms-transform: translateX(0px);'+ ' transform: translateX(0px);'+ ' -webkit-transition: all ease-out 0.8s 0.1s;'+ ' -moz-transition: all ease-out 0.8s 0.1s;'+ ' -o-transition: all ease-out 0.8s 0.1s;'+ ' -ms-transition: all ease-out 0.8s 0.1s;'+ ' transition: all ease-out 0.8s 0.1s;'+ ' overflow: hidden;'+ ' }'+ ' .greeting {'+ ' margin-top: 24px;'+ ' margin-bottom: 16px;'+ (options.singlepagestyle ? (' width: 328px;') : '') + ' font-size: 14px;'+ ' line-height: 19px;'+ ' color: #424242;'+ ' }'+ ' .lrForgotpw {'+ ' padding-left: 16px;'+ ' }'+ ' #lr-ls-sectiondivider, #lr-ls-sectiondividerL {'+ ' padding-top: 7px;'+ ' margin-top: 16px;'+ ' display: block;'+ ' margin-left: auto;'+ ' margin-right: auto;'+ ' height: 39px;'+ ' text-align: center;'+ ' color: #424242;'+ ' font-size: 18px;'+ ' line-height: 19px;'+ ' }'+ (options.socialsquarestyle ? ' .social-login-b-options {'+ ' margin-top: 6vh;'+ ' width: 328px;'+ ' text-align: center;'+ ' font-size: 16px;'+ ' font-weight: 200;'+ ' -webkit-animation: slide-up 1s ease-out;'+ ' -moz-animation: slide-up 1s ease-out;'+ ' }'+ ' .social-login-b-options .lr-sl-shaded-brick-button {'+ ' height: 3.5rem;'+ ' width: 3.5rem;'+ ' border-radius: 4px;'+ ' overflow: hidden;'+ ' margin-top: 8px;'+ ' position: relative;'+ ' border: 1px solid rgba(0, 0, 0, 0.1);'+ ' text-align: left;'+ ' text-decoration: none;'+ ' color: white;'+ ' box-shadow: 0 0 1px 0 rgba(0, 0, 0, 0.12), 0 1px 1px 0 rgba(0, 0, 0, 0.24), 0 0 8px 0 rgba(0, 0, 0, 0.12), 0 2px 2px 0 rgba(0, 0, 0, 0.24);'+ ' }'+ ' .social-login-b-options .lr-sl-shaded-brick-button .lr-sl-icon {'+ ' top: 0;'+ ' left: 0;'+ ' display: inline-block;'+ ' position: absolute;'+ ' }'+ ' .lr-provider-label {'+ ' margin-top: 8px;'+ ' display: inline-block;'+ ' }' : ' .social-login-b-options {'+ ' margin-top: 6vh;'+ ' width: 328px;'+ ' text-align: center;'+ ' font-size: 18px;'+ ' font-weight: 200;'+ ' -webkit-animation: slide-up 1s ease-out;'+ ' -moz-animation: slide-up 1s ease-out;'+ ' }'+ ' .social-login-b-options .lr-sl-shaded-brick-button {'+ ' line-height: normal;'+ ' height: 3em;'+ ' width: 100%;'+ ' border-radius: 4px;'+ ' overflow: hidden;'+ ' margin-top: 8px;'+ ' position: relative;'+ ' border: 1px solid rgba(0, 0, 0, 0.1);'+ ' text-align: left;'+ ' text-decoration: none;'+ ' color: white;'+ ' padding: 0.8em 0 0 3em;'+ ' box-shadow: 0 0 1px 0 rgba(0, 0, 0, 0.12), 0 1px 1px 0 rgba(0, 0, 0, 0.24), 0 0 8px 0 rgba(0, 0, 0, 0.12), 0 2px 2px 0 rgba(0, 0, 0, 0.24);'+ ' }'+ ' .social-login-b-options .lr-sl-shaded-brick-button .lr-sl-icon {'+ ' top: 4px;'+ ' left: 0;'+ ' display: inline-block;'+ ' position: absolute;'+ ' }'+ ' .lr-provider-label {'+ ' margin-top: 8px;'+ ' display: block;'+ ' }') + ' .lr-sl-icon:before {'+ ' width: 3.4rem;'+ ' height: 3.2rem;'+ ' background: url("http://cdn.loginradius.com/hub/prod/v1/hosted-page-default-images/icon-sprite-32.png");'+ ' background-image: linear-gradient(transparent, transparent), url("http://cdn.loginradius.com/hub/prod/v1/hosted-page-default-images/icon-sprite.svg"), none;'+ ' background-size: 100% 3600%;'+ ' background-position: 0 0;'+ (options.socialsquarestyle ? '' : ' margin-top: -4px;'+ ' margin-top: -0.4rem;') + ' }'+ ' .lr-ls-status-area {'+ ' margin-left: auto;'+ ' margin-right: auto;'+ ' height: 34px;'+ ((options.singlepagestyle)? (' width: 100%;') : (' width: 360px;'))+ ' display: none;'+ ' z-index: 2;'+ ' }'+ ' .lr-iconsuccess {'+ ' font-family: arial;'+ ' -ms-transform: scaleX(-1) rotate(-35deg); /* IE 9 */'+ ' -webkit-transform: scaleX(-1) rotate(-35deg); /* Chrome, Safari, Opera */'+ ' transform: scaleX(-1) rotate(-35deg);'+ ' float: left;'+ ' margin-right: 5px;'+ ' }'+ ' .lr-iconerror {'+ ' text-align: center;'+ ' font-family: sans-serif;'+ ' float: left;'+ ' margin-right: 3px;'+ ' }'+ ' .lr-ls-divsuccess {'+ ' display: none;'+ ' padding: 5px;'+ ' height: 34px;'+ ' border: 1px solid #3EA34D;'+ ' color: #FFFFFF;'+ ' font-size: 12px;'+ ' line-height: 16px;'+ ' font-weight: 600;'+ ' vertical-align: middle;'+ ' }'+ ' .lr-ls-diverror {'+ ' display: none;'+ ' padding: 5px;'+ ' height: 34px;'+ ' border: 1px solid #FF1744;'+ ' color: #FFFFFF;'+ ' font-size: 12px;'+ ' line-height: 16px;'+ ' font-weight: 600;'+ ' vertical-align: middle;'+ ' }'+ ' ::-webkit-input-placeholder {'+ ' font-size: 12px;'+ ' line-height: 100%;'+ ' }'+ ' .loginradius--form-element-content {'+ ' text-align: left;'+ ' margin-bottom: 1.3rem;'+ ' margin-bottom: 2.67vh;'+ ' }'+ ' #login-container .loginradius--form-element-content, #registration-container .loginradius--form-element-content, #forgotpassword-container .loginradius--form-element-content, #resetpassword-container .loginradius--form-element-content {'+ ' padding-left: 16px;'+ ' }'+ ((options.singlepagestyle)? "" : ( '#resetpassword-container .loginradius--form-element-content {'+ 'padding-left: 376px;'+ '}' ))+ ' .loginradius--form-element-content label {'+ ' color:' + ((options.body && options.body.textColor) ? options.body.textColor : '#616161') + ';' + ' font-size: 14px;'+ ' line-height: 14px;'+ ' }'+ ' #login-container,'+ ' #registration-container,'+ ' #forgotpassword-container {'+ ' width: 329px;'+ ' z-index: 0;'+ ' }'+ ' #forgotpassword-container {'+ ' margin-top: 16px;'+ ' }'+ ' #resetpassword-container #loginradius-submit-reset-password {'+ ' width:45% !important;'+ ' }'+ ' input .invalid {'+ ' border: 1px solid #FF1744;'+ ' background-color: #F5F5F5;'+ ' }'+ ' select {'+ ' height: 32px;'+ ' background-color: #F5F5F5;'+ ' font-size: 15px;'+ ' font-weight: 300;'+ ' line-height: 16px;'+ ' box-sizing: border-box;'+ ' margin-left: 20px;'+ ' }'+ ' textarea,'+ ' input[type="password"],'+ ' input[type="text"] {'+ ' margin-top: 4px;'+ ' height: 32px;'+ ' width: 326px;'+ ' background-color:' + ((options.input && options.input.background) ? options.input.background : ' #F5F5F5') + ';' + ' border-style: hidden;'+ ' font-size: 16px;'+ ' font-weight: 300;'+ ' line-height: 16px;'+ ' padding: 8px;'+ ' -webkit-box-sizing: border-box;'+ ' box-sizing: border-box;'+ ' }'+ ' text {'+ ' height: 16px;'+ ' width: 151px;'+ ' color: #424242;'+ ' font-size: 14px;'+ ' line-height: 16px;'+ ' }'+ ' input[type="submit"] {'+ ' margin-top: 2.1vh;'+ ' color: #FFFFFF;'+ ' font-size: 14px;'+ ' line-height: 16px;'+ ' text-align: center;'+ ' letter-spacing: 2px;'+ ' cursor: pointer;'+ ' }'+ ' .content-loginradius-stayLogin {'+ ' margin-top: 8px;'+ ' display: flex;'+ ' }'+ ' input[type="checkbox"] {'+ ' height: 18px;'+ ' width: 18px;'+ ' border: 1px solid #9E9E9E;'+ ' vertical-align: middle;'+ ' }'+ ' .content-loginradius-stayLogin label {'+ ' height: 18px;'+ ' width: 84px;'+ ' color:' + ((options.body && options.body.textColor) ? options.body.textColor : '#616161') + ';' + ' font-size: 12px;'+ ' line-height: 17px;'+ ' }'+ ' #lr-forgotpw-btn {'+ ' right: 16px;'+ ' bottom: 12.77vh;'+ ' font-size: 12px;'+ ' line-height: 17px;'+ ' height: 18px;'+ ' color:' + ((options.body && options.body.textColor) ? options.body.textColor : '#616161') + ';' + ' cursor: pointer;'+ ' float: right;'+ ' }'+ ' [id *="loginradius-submit-"] {'+ ' margin-bottom:10px;'+ ' height: 75px;'+ ' margin-left: 16px;'+ ' /*or height:60px; */'+ ' width: 100% !important;'+ ' border-radius: 0 0 6px 6px;'+ ' background-color:' + ((options.submitButton && options.submitButton.color) ? options.submitButton.color : '#35a8ff') + ';' + ' box-shadow: 0 2px 5px 0 rgba(0, 0, 0, .16), 0 2px 10px 0 rgba(0, 0, 0, .12);'+ ' outline: none;'+ ' }'+ ' #loginradius-submit-login {'+ ((options.singlepagestyle) ? (' border-radius: 6px;') : (' border-radius: 6px 6px 6px 0;')) + ' }'+ ' [id *="loginradius-submit-"]:hover {'+ ' filter: brightness(98%);'+ ' transition: color 400ms;'+ ' }'+ ' [id *="loginradius-submit-"]:active {'+ ' filter: brightness(85%);'+ ' transition: color 400ms;'+ ' }'+ ' #forgotPW {'+ ' height: 17px;'+ ' color: #424242;'+ ' font-size: 12px;'+ ' line-height: 17px;'+ ' text-align: center;'+ ' text-decoration: none;'+ ' position: absolute;'+ ' }'+ ' #reset-password {'+ ' height: 36px;'+ ' color: #414141;'+ ' font-size: 32px;'+ ' font-weight: 300;'+ ' line-height: 37px;'+ ' }'+ ' .Resetpw.greeting {'+ ' margin-bottom: 1.5rem;'+ ' }'+ ' #signUpopt {'+ ' margin-top: 10px;'+ ' display: block;'+ ' height: 17px;'+ ' width: 240px;'+ ' color: #FFFFFF;'+ ' font-size: 12px;'+ ' line-height: 17px;'+ ' text-align: center;'+ ' text-decoration: none;'+ ' margin-left: auto;'+ ' margin-right: auto;'+ ' }'+ ' .loginradius-validation-message {'+ ' margin-top: 0.3rem;'+ ' color: #FF1744;'+ ' font-size: 10px;'+ ' line-height: 14px;'+ ' }'+ ' @-webkit-keyframes slide-up {'+ ' 0% {'+ ' opacity: 0;'+ ' -webkit-transform: translateY(-100%);'+ ' }'+ ' 100% {'+ ' opacity: 1;'+ ' -webkit-transform: translateY(0);'+ ' }'+ ' }'+ ' @-moz-keyframes slide-up {'+ ' 0% {'+ ' opacity: 0;'+ ' -moz-transform: translateY(-100%);'+ ' }'+ ' 100% {'+ ' opacity: 1;'+ ' -moz-transform: translateY(0);'+ ' }'+ ' }'+ ' .lr-ls-pageloader {'+ ' display: none;'+ ' z-index: 999;'+ ' width: 100%;'+ ' height: 100%;'+ ' position: fixed;'+ ' top: 0;'+ ' right: 0;'+ ' bottom: 0;'+ ' left: 0;'+ ' background-color: rgba(0, 0, 0, .5);'+ ' }'+ ' .lr-ls-page-loadwheel {'+ ' width: 120px;'+ ' height: 120px;'+ ' margin-top: -60px;'+ ' margin-left: -60px;'+ ' position: absolute;'+ ' top: 50%;'+ ' left: 50%;'+ ' border-width: 30px;'+ ' border-radius: 50%;'+ ' border: 10px solid #f3f3f3;'+ ' border-radius: 50%;'+ ' border-top: 10px solid #3498db;'+ ' -webkit-animation: spin 2s linear infinite;'+ ' /* Safari */'+ ' animation: spin 2s linear infinite;'+ ' }'+ ' @-webkit-keyframes spin {'+ ' 0% {'+ ' -webkit-transform: rotate(0deg);'+ ' }'+ ' 100% {'+ ' -webkit-transform: rotate(360deg);'+ ' }'+ ' }'+ ' @keyframes spin {'+ ' 0% {'+ ' transform: rotate(0deg);'+ ' }'+ ' 100% {'+ ' transform: rotate(360deg);'+ ' }'+ ' }'+ '}'+ '#loginradius-linksignin-email-me-a-link-to-sign-in, #lr-forgot-label{'+ ' display: none;'+ '}'+ '#loginradius-button-resendotp {'+ ' margin-right: 20px;'+ ' margin-left: 20px;'+ '}'+ '#loginradius-showQRcode-qrcode {'+ ' width: 100%;'+ ' margin: auto;'+ ' display: block;'+ '}'+ ''+ '.content-loginradius-qrcode {'+ ' text-align: center;'+ '}'+ '.lrLogin {'+ ' margin-right: auto;'+ ' margin-left: auto;'+ '}'+ ''+ '.lrSignup {'+ ' margin-right: auto;'+ ' margin-left: auto;'+ ' padding-bottom: 20px;'+ '}'+ ''+ '.lrForgotpw {'+ ' margin-right: auto;'+ ' margin-left: auto;'+ '}'+ ''+ '.lrResetpw {'+ ' margin-right: auto;'+ ' margin-left: auto;'+ '}'+ ''+ '#lr-ls-sectiondivider:after, #lr-ls-sectiondividerL:after {'+ ' content: '+((options.content && options.content.socialandloginDivider) ? ('"'+options.content.socialandloginDivider+'"') : '"OR"') + ';'+ '}'+ ''+ ''+ '/*'+ '* Social Icon Style'+ '*'+ '**/'+ ''+ '.lr-sl-icon {'+ ' display: inline-block;'+ ' text-align: center;'+ '}'+ ''+ '.lr-sl-icon:before,'+ '.lr-sl-icon:after {'+ ' content: "";'+ ' display: inline-block;'+ ' vertical-align: middle;'+ '}'+ ''+ '.lr-sl-icon:after {'+ ' height: 100%;'+ ' width: 0;'+ '}'+ ''+ '.lr-sl-icon-pinterest:before {'+ ' background-position: 0 -0.2%;'+ '}'+ ''+ '.lr-flat-line {'+ ' background-color: #27c327;'+ '}'+ ''+ '.lr-flat-pinterest {'+ ' background-color: #cb2128;'+ '}'+ ''+ '.lr-sl-icon-facebook:before {'+ ' background-position: 0 0;'+ '}'+ ''+ '.lr-sl-icon-facebook:before {'+ ' background-position: 0px 2.1%;'+ '}'+ ''+ '.lr-sl-icon-googleplus:before {'+ ' background-position: 0px 5%;'+ '}'+ ''+ '.lr-sl-icon-linkedin:before {'+ ' background-position: 0px 6.8%;'+ '}'+ ''+ '.lr-sl-icon-twitter:before {'+ ' background-position: 0px 9.2%;'+ '}'+ ''+ '.lr-sl-icon-yahoo:before {'+ ' background-position: 0px 11.6%;'+ '}'+ ''+ '.lr-sl-icon-amazon:before {'+ ' background-position: 0px 13.9%;'+ '}'+ ''+ '.lr-sl-icon-aol:before {'+ ' background-position: 0px 16.3%;'+ '}'+ ''+ '.lr-sl-icon-disqus:before {'+ ' background-position: 0px 18.85%;'+ '}'+ ''+ '.lr-sl-icon-foursquare:before {'+ ' background-position: 0px 21.3%;'+ '}'+ ''+ '.lr-sl-icon-github:before {'+ ' background-position: 0px 23.55%;'+ '}'+ ''+ '.lr-sl-icon-hyves:before {'+ ' background-position: 0px 26.1%;'+ '}'+ ''+ '.lr-sl-icon-instagram:before {'+ ' background-position: 0px 28.35%;'+ '}'+ ''+ '.lr-sl-icon-kaixin:before {'+ ' background-position: 0px 30.8%;'+ '}'+ ''+ '.lr-sl-icon-live:before {'+ ' background-position: 0px 33.3%;'+ '}'+ ''+ '.lr-sl-icon-livejournal:before {'+ ' background-position: 0px 35.5%;'+ '}'+ ''+ '.lr-sl-icon-mixi:before {'+ ' background-position: 0px 38.1%;'+ '}'+ ''+ '.lr-sl-icon-odnoklassniki:before {'+ ' background-position: 0px 40.3%;'+ '}'+ ''+ '.lr-sl-icon-orange:before {'+ ' background-position: 0px 44%;'+ '}'+ ''+ '.lr-sl-icon-openid:before {'+ ' background-position: 0px 45.3%;'+ '}'+ ''+ '.lr-sl-icon-paypal:before {'+ ' background-position: 0px 47.5%;'+ '}'+ ''+ '.lr-sl-icon-persona:before {'+ ' background-position: 0px 51.2%;'+ '}'+ ''+ '.lr-sl-icon-pinterest:before {'+ ' background-position: 0px 52.2%;'+ '}'+ ''+ '.lr-sl-icon-qq:before {'+ ' background-position: 0px 54.7%;'+ '}'+ ''+ '.lr-sl-icon-renren:before {'+ ' background-position: 0px 57.15%;'+ '}'+ ''+ '.lr-sl-icon-salesforce:before {'+ ' background-position: 0px 59.6%;'+ '}'+ ''+ '.lr-sl-icon-sinaweibo:before {'+ ' background-position: 0px 61.8%;'+ '}'+ ''+ '.lr-sl-icon-stackexchange:before {'+ ' background-position: 0px 64.3%;'+ '}'+ ''+ '.lr-sl-icon-steamcommunity:before {'+ ' background-position: 0px 66.7%;'+ '}'+ ''+ '.lr-sl-icon-verisign:before {'+ ' background-position: 0px 69.2%;'+ '}'+ ''+ '.lr-sl-icon-virgilio:before {'+ ' background-position: 0px 71.6%;'+ '}'+ ''+ '.lr-sl-icon-vkontakte:before {'+ ' background-position: 0px 73.9%;'+ '}'+ ''+ '.lr-sl-icon-wordpress:before {'+ ' background-position: 0px 76.1%;'+ '}'+ ''+ '.lr-sl-icon-mailru:before {'+ ' background-position: 0px 78.6%;'+ '}'+ ''+ '.lr-sl-icon-xing:before {'+ ' background-position: 0px 81.2%;'+ '}'+ ''+ '.lr-sl-icon-delicious:before {'+ ' background-position: 0px 85.5%;'+ '}'+ ''+ '.lr-sl-icon-digg:before {'+ ' background-position: 0px 88%;'+ '}'+ ''+ '.lr-sl-icon-email:before {'+ ' background-position: 0px 92.5%;'+ '}'+ ''+ '.lr-sl-icon-google-bookmark:before {'+ ' background-position: 0px 92.8%;'+ '}'+ ''+ '.lr-sl-icon-print:before {'+ ' background-position: 0px 95.1%;'+ '}'+ ''+ '.lr-sl-icon-reddit:before {'+ ' background-position: 0px 97.7%;'+ '}'+ ''+ '.lr-sl-icon-tumblr:before {'+ ' background-position: 0px 97.2%;'+ '}'+ ''+ '.lr-sl-icon-myspace:before {'+ ' background-position: 0px 90.3%;'+ '}'+ ''+ '.lr-sl-icon-google:before {'+ ' background-position: 0px 4.4%;'+ '}'+ ''+ '.lr-sl-icon-line:before {'+ ' background-position: 0px 100.1%;'+ '}'+ ''+ '.lr-flat-amazon {'+ ' background-color: #f90;'+ '}'+ ''+ '.lr-flat-aol {'+ ' background-color: #066cb1;'+ '}'+ ''+ '.lr-flat-disqus {'+ ' background-color: #35a8ff;'+ '}'+ ''+ '.lr-flat-facebook {'+ ' background-color: #3b5998;'+ '}'+ ''+ '.lr-flat-foursquare {'+ ' background-color: #1cafec;'+ '}'+ ''+ '.lr-flat-github {'+ ' background-color: #181616;'+ '}'+ ''+ '.lr-flat-google {'+ ' background-color: #dd4b39;'+ '}'+ ''+ '.lr-flat-googleplus {'+ ' background-color: #dd4b39;'+ '}'+ ''+ '.lr-flat-hyves {'+ ' background-color: #f9a539;'+ '}'+ ''+ '.lr-flat-instagram {'+ ' background-color: #406e94;'+ '}'+ ''+ '.lr-flat-kaixin {'+ ' background-color: #bb0e0f;'+ '}'+ ''+ '.lr-flat-linkedin {'+ ' background-color: #007bb6;'+ '}'+ ''+ '.lr-flat-live {'+ ' background-color: #004c9a;'+ '}'+ ''+ '.lr-flat-livejournal {'+ ' background-color: #3770a3;'+ '}'+ ''+ '.lr-flat-mixi {'+ ' background-color: #d1ad5a;'+ '}'+ ''+ '.lr-flat-myspace {'+ ' background-color: #313131;'+ '}'+ ''+ '.lr-flat-odnoklassniki {'+ ' background-color: #f69324;'+ '}'+ ''+ '.lr-flat-openid {'+ ' background-color: #f7921c;'+ '}'+ ''+ '.lr-flat-orange {'+ ' background-color: #f60;'+ '}'+ ''+ '.lr-flat-paypal {'+ ' background-color: #13487b;'+ '}'+ ''+ '.lr-flat-persona {'+ ' background-color: #e0742f;'+ '}'+ ''+ '.lr-flat-qq {'+ ' background-color: #29d;'+ '}'+ ''+ '.lr-flat-renren {'+ ' background-color: #005baa;'+ '}'+ ''+ '.lr-flat-salesforce {'+ ' background-color: #9cd3f2;'+ '}'+ ''+ '.lr-flat-stackexchange {'+ ' background-color: #4ba1d8;'+ '}'+ ''+ '.lr-flat-steamcommunity {'+ ' background-color: #666;'+ '}'+ ''+ '.lr-flat-tumblr {'+ ' background-color: #32506d;'+ '}'+ ''+ '.lr-flat-twitter {'+ ' background-color: #55acee;'+ '}'+ ''+ '.lr-flat-verisign {'+ ' background-color: #0261a2;'+ '}'+ ''+ '.lr-flat-virgilio {'+ ' background-color: #eb6b21;'+ '}'+ ''+ '.lr-flat-vkontakte {'+ ' background-color: #45668e;'+ '}'+ ''+ '.lr-flat-sinaweibo {'+ ' background-color: #bb3e3e;'+ '}'+ ''+ '.lr-flat-wordpress {'+ ' background-color: #21759c;'+ '}'+ ''+ '.lr-flat-yahoo {'+ ' background-color: #400090;'+ '}'+ ''+ '.lr-flat-xing {'+ ' background-color: #007072;'+ '}'+ ''+ '.lr-flat-mailru {'+ ' background-color: #1897e6;'+ '}'+ ''+ ''+ '/* not shown google recaptcha'+ '.grecaptcha-badge {'+ ' display: none;'+ ' }'+ '*/</style>'+ '<div class="lr-ls-page">' + ' <div class="lr-ls-logobase">' + ' <img id="lr-ls-logo-place" src=' + ((options.logo && options.logo.url) ? options.logo.url : "https://docs.loginradius.com/theme/apidocs//support-assets/images/logo.svg") +'>' + ' </div>' + ' <div class = "lr-ls-status-area" id="lr-ls-status-area">' + ' <div class= "lr-ls-divsuccess" id= "lr-ls-divsuccess">' + ' <div class="lr-iconsuccess">L</div>' + ' <div class="lr-ls-divisionsuccess" id="lr-ls-divisionsuccess">Success!</div>' + ' </div>' + ' <div class="lr-ls-diverror" id="lr-ls-diverror">' + ' <div class="lr-iconerror">X</div>' + ' <div class = "lr-ls-divisionerror" id = "lr-ls-divisionerror"></div>' + ' </div>' + ' </div>' + ' <div class="lr-ls-pageloader" id= "loader">' + ' <div class="lr-ls-page-loadwheel"></div>' + ' </div>' + ' <ul class="lr-ls-tabs">' + ' <li class="tab">' + ' <input id="tab1" type="radio" name="lr-ls-tabs" checked="checked">' + ' <label class="tab-label" for= "tab1"' + ((options.pagesshown && !options.login)? ('style="display: none"') : '')+ '>'+ ((options.content && options.content.tabLabels) ? options.content.tabLabels[0] : "Log in")+'</label>' + ' <div class="lrLogin content" id = "tab-content1"' + ((options.pagesshown && !options.login)? ('style="display: none"') : '')+ '>' + ' <div class="lrLogin social-login-b-options">' + ' <div id="interfacecontainerdivL" class="interfacecontainerdiv"></div>' + ' </div>' + ' <p id="lr-ls-sectiondividerL"></p>' + ' <div id="login-container"></div>' + ' <div id = "lr-forgotpw-btn" onclick="{document.getElementById(\'tab3\').checked = \'checked\';}"' + ((options.pagesshown && !options.forgotpassword)? ('style="display: none"') : '')+ '>'+ ((options.content && options.content.tabLabels) ? options.content.tabLabels[2] : "Forgot Password?")+ ' </div>' + ' </div>' + ' </li>' + ' <li class= "tab" id = "signuptab">' + ' <input id="tab2" type="radio" name="lr-ls-tabs"' + ((options.pagesshown && !options.login && options.signup)? ('checked = "checked"') : '')+ '>' + ' <label class="tab-label" for= "tab2"' + ((options.pagesshown && !options.signup)? ('style="display: none"') : '')+ '>'+ ((options.content && options.content.tabLabels) ? options.content.tabLabels[1] : "Sign Up")+'</label>' + ' <div class="lrSignup content" id = "tab-content2"' + ((options.pagesshown && !options.signup)? ('style="display: none"') : '')+ '>' + ' <div class="lrSignup social-login-b-options">' + ' <div id="interfacecontainerdiv" class="interfacecontainerdiv"></div>' + ' <div id="sociallogin-container"></div>' + ' </div>' + ' <p id="lr-ls-sectiondivider"></p>' + ' <div id="registration-container"></div>' + ' </div>' + ' </li>' + ' <li class= "tab">' + ' <input id="tab3" type="radio" name="lr-ls-tabs" ' + ((options.pagesshown && !options.login && !options.signup && options.forgotpassword)? ('checked = "checked"') : '')+ '>' + ' <label for= "tab3" id="lr-forgot-label">'+ ((options.content && options.content.tabLabels) ? options.content.tabLabels[2] : "Forgot Password?")+'</label>' + ' <div class="lrForgotpw content" id = "tab-content3"' + ((options.pagesshown && !options.forgotpassword)? ('style="display: none"') : '')+ '>' + ' <div class="lrForgotpw greeting">' + ' <p id="emailedtoreset">'+ ((options.content && options.content.forgotPWgreet) ? (options.content.forgotPWgreet) : "We\'ll email you an instruction on resetting your password.") + '</p>' + ' </div>' + ' <div id="forgotpassword-container"></div>' + ' </div>' + ' </li>' + ' </ul>' + ' <div class="Resetpw-content" id = "Resetpw-content1">' + ' <div class="lrResetpw greeting">' + ' <p id="reset-password">'+ ((options.content && options.content.resetpage)? options.content.resetpage : 'Reset Password') + '</p>' + ' </div>' + ' <div id="resetpassword-container"></div>' + ' </div>' + ' </div>' + ' <script type="text/html" id="loginradiuscustom_tmpl1">'+ ' <a class="lr-provider-label lr-sl-shaded-brick-button lr-flat-<#=Name.toLowerCase()#>" href="javascript:void(0)" onclick="return <#=ObjectName#>.util.openWindow(\'<#= Endpoint #>\');" title="Sign up with <#= Name #>" alt="Sign in with <#=Name#>"><span class="lr-sl-icon lr-sl-icon-<#= Name.toLowerCase()#>"></span>'+ ((options.content && options.content.socialblockLabel) ? (options.content.socialblockLabel): "Log in with")+' <#=Name#>'+ ' </a>'+ ' </script>'+ ' <script type="text/html" id="loginradiuscustom_tmpl2">'+ ' <a class="lr-provider-label lr-sl-shaded-brick-button lr-flat-<#=Name.toLowerCase()#>" href="javascript:void(0)" onclick="return <#=ObjectName#>.util.openWindow(\'<#= Endpoint #>\');" title="Sign up with <#= Name #>" alt="Sign in with <#=Name#>"><span class="lr-sl-icon lr-sl-icon-<#= Name.toLowerCase()#>"></span>'+ ' </a>'+ ' </script>'; } // function renderJS(cb, options, lrCallingObj) { function lrlserroraction(errors) { window.scrollTo(0, 0); document.getElementById("lr-ls-divsuccess").style.display = "none"; document.getElementById("lr-ls-divisionerror").innerHTML = !errors[0]["Description"] ? errors[0]["description"] : errors[0]["Description"]; document.getElementById("lr-ls-diverror").style.display = "table-cell"; document.getElementById("lr-ls-status-area").style.backgroundColor = "#FF1744"; document.getElementById("lr-ls-status-area").style.display = "table"; document.getElementById("lr-ls-status-area").style.position = "absolute"; if(options.singlepagestyle == true){ document.getElementById("lr-ls-status-area").style.top = "137px"; } setTimeout(function() { document.getElementById("lr-ls-status-area").style.display = "none"; }, 8000); } function lrlssuccessaction(response) { window.scrollTo(0, 0); document.getElementById("lr-ls-diverror").style.display = "none"; document.getElementById("lr-ls-divsuccess").style.display = "table-cell"; document.getElementById("lr-ls-status-area").style.backgroundColor = "#3EA34D"; document.getElementById("lr-ls-status-area").style.display = "table"; document.getElementById("lr-ls-status-area").style.position = "absolute"; if(options.singlepagestyle == true){ document.getElementById("lr-ls-status-area").style.top = "137px"; } setTimeout(function() { document.getElementById("lr-ls-status-area").style.display = "none"; }, 8000); } function redirect(response) { var lrform = document.createElement("form"); var _token = document.createElement("input"); lrform.method = "POST"; lrform.action = ((options.redirecturl && options.redirecturl.afterlogin) ? options.redirecturl.afterlogin : window.location.origin); _token.type = "hidden"; _token.name = "token"; _token.value = response["access_token"]; lrform.appendChild(_token); document.body.appendChild(lrform); lrform.submit(); } var custom_interface_option = {}; custom_interface_option.templateName = (options.socialsquarestyle ? 'loginradiuscustom_tmpl2' : 'loginradiuscustom_tmpl1'); var sl_options = {}; sl_options.onSuccess = function(response) { if(response.access_token){ getProfile(response.access_token, response.Profile.Uid); } cb(response, "socialLogin"); }; sl_options.onError = function(errors) { lrlserroraction(errors); cb(errors, "socialLogin"); }; sl_options.container = "sociallogin-container"; var login_options = {}; login_options.onSuccess = function(response) { document.getElementById("lr-ls-status-area").style.display = "none"; cb(response, "login"); //safely redirect if(response.access_token){ getProfile(response.access_token, response.Profile.Uid); } }; login_options.onError = function(errors) { lrlserroraction(errors); cb(errors, "login"); }; login_options.container = "login-container"; var registration_options = {} registration_options.onSuccess = function(response) { lrlssuccessaction(response); document.getElementById("lr-ls-divisionsuccess").innerHTML = ((options.content && options.content.signupandForgotPwrequest) ? options.content.signupandForgotPwrequest : "Please check your email!"); if(response.Data){ if(response.Data.AccountSid && response.Data.Sid) { document.getElementById("lr-ls-divisionsuccess").innerHTML = ((options.content && options.content.signupandForgotPwrequestPhone) ? options.content.signupandForgotPwrequestPhone : "Please check your phone!"); } } if(document.getElementsByName("loginradius-registration")[0]) { document.getElementsByName("loginradius-registration")[0].reset(); } cb(response, "registration"); if(response.access_token){ document.getElementById("lr-ls-divisionsuccess").innerHTML = ((options.content && options.content.emailVerifiedMessage) ? options.content.emailVerifiedMessage : "You have successfully registered, you now may log in with this email"); getProfile(response.access_token, response.Profile.Uid); } }; registration_options.onError = function(errors) { lrlserroraction(errors); cb(errors, "registration"); }; registration_options.container = "registration-container"; var forgotpassword_options = {}; forgotpassword_options.container = "forgotpassword-container"; var forgotPassOTPBool = false; forgotpassword_options.onSuccess = function(response) { lrlssuccessaction(response); document.getElementById("lr-ls-divisionsuccess").innerHTML = ((options.content && options.content.signupandForgotPwrequest) ? options.content.signupandForgotPwrequest : "Please check your email!"); if(response.Data){ if(response.Data.AccountSid && response.Data.Sid) { document.getElementById("lr-ls-divisionsuccess").innerHTML = ((options.content && options.content.signupandForgotPwrequestPhone) ? options.content.signupandForgotPwrequestPhone : "Please check your phone!"); } } if(document.getElementsByName("loginradius-forgotpassword")[0]){ document.getElementsByName("loginradius-forgotpassword")[0].reset(); } cb(response, "forgotPassword"); if(forgotPassOTPBool == true){ setTimeout(function() { window.location.href = ((options.redirecturl && options.redirecturl.afterreset) ? options.redirecturl.afterreset : window.location.origin); }, 100); } forgotPassOTPBool = true; }; forgotpassword_options.onError = function(errors) { lrlserroraction(errors); cb(errors, "forgotPassword"); } var resetpassword_options = {}; resetpassword_options.container = "resetpassword-container"; resetpassword_options.onSuccess = function(response) { lrlssuccessaction(response); if(response.Data == null){ setTimeout(function() { window.location.href = ((options.redirecturl && options.redirecturl.afterreset) ? options.redirecturl.afterreset : window.location.origin); }, 2000); } cb(response, "resetPassword"); }; resetpassword_options.onError = function(errors) { lrlserroraction(errors); cb(errors, "resetPassword"); }; if(!(options.singlepagestyle) && screen.width>960 ){ HideOTPandadjustHeight(); } HideOTP(); function HideOTP(){ lrCallingObj.$hooks.register('afterFormRender', function() { if (document.getElementsByClassName("loginradius-otpsignin")[0]) { document.getElementsByClassName("loginradius-otpsignin")[0].style.display = "none"; document.getElementById("loginradius-otpsignin-send-an-otp-to-sign-in").style.display = "none"; } if(document.getElementById('lr-forgotpw-btn')){ var passwordNode = document.getElementsByClassName('content-loginradius-password')[0]; passwordNode.parentNode.insertBefore(document.getElementById('lr-forgotpw-btn'), passwordNode.nextSibling); } }) if(options.singlepagestyle) { document.getElementsByClassName("content")[0].style.paddingBottom = "20px"; } } function HideOTPandadjustHeight(){ lrCallingObj.$hooks.register('afterFormRender', function() { var RightcontentHeight = document.getElementsByClassName("content")[0].offsetHeight; var rightTabLabel = document.getElementsByClassName("tab-label")[0]; var rightTabLabelStyle = window.getComputedStyle(rightTabLabel) || rightTabLabel.currentStyle; var tabHeight = parseInt(rightTabLabelStyle.borderBottomWidth, 10); tabHeight = tabHeight + parseInt(rightTabLabelStyle.lineHeight, 10); var RightPageHeight = document.getElementsByClassName("tab")[0].offsetHeight+RightcontentHeight; if ((options.pagesshown && !options.login)|| RightcontentHeight ==0){ if (options.signup){ var RightcontentHeight = 580; var RightPageHeight = RightcontentHeight+tabHeight; } else{ var RightcontentHeight = 580; var RightPageHeight = RightcontentHeight; } } document.getElementsByClassName("lr-ls-logobase")[0].style.minHeight = RightPageHeight.toString() +"px"; document.getElementsByClassName("content")[0].style.height = RightcontentHeight.toString() +"px"; document.getElementsByClassName("content")[1].style.height = RightcontentHeight.toString() +"px"; document.getElementsByClassName("content")[2].style.height = RightcontentHeight.toString() +"px"; document.getElementById("Resetpw-content1").style.height = RightPageHeight.toString() +"px"; document.getElementsByClassName("content")[0].style.overflow = "auto"; document.getElementsByClassName("content")[0].style.overflowX = "hidden"; document.getElementsByClassName("content")[0].style.width = "50%"; document.getElementsByClassName("content")[1].style.overflow = "auto"; document.getElementsByClassName("content")[1].style.overflowX = "hidden"; document.getElementsByClassName("content")[1].style.width = "50%"; document.getElementById("lr-ls-logo-place").style.paddingTop = (RightPageHeight / 2.5).toString() +"px"; }) } lrCallingObj.util.ready(function() { lrCallingObj.customInterface(".interfacecontainerdiv", custom_interface_option); lrCallingObj.init('socialLogin', sl_options); lrCallingObj.init("login", login_options); lrCallingObj.init("registration", registration_options); lrCallingObj.init("forgotPassword", forgotpassword_options); lrCallingObj.init("resetPassword", resetpassword_options); }); function VerifyEmailInit() { var verifyemail_options = {}; verifyemail_options.onSuccess = function(response) { document.getElementById("lr-ls-divisionsuccess").innerHTML = ((options.content && options.content.emailVerifiedMessage) ? options.content.emailVerifiedMessage : "You have successfully registered, you now may log in with this email"); lrlssuccessaction(response); console.log(response); cb(response, "verifyEmail"); if(response.access_token){ getProfile(response.access_token, response.Profile.Uid); } }; verifyemail_options.onError = function(errors) { lrlserroraction(errors); cb(errors, "verifyEmail"); } lrCallingObj.util.ready(function() { lrCallingObj.init("verifyEmail", verifyemail_options); }); }; function VerifyToken() { var link = lrCallingObj.util.parseQueryString(window.location.href); var values = Object.keys(link).map(function(e) { return link[e]; }) if ((Object.keys(link)[0].indexOf("vtype") > -1) && Object.keys(link)[1] == "vtoken" && values.length>1) { if (values[0].indexOf("emailverification") >= 0) { VerifyEmailInit(); } else if (values[0] == "reset") { for (i = 0; i < document.getElementsByClassName("tab").length; i++) { document.getElementsByClassName("tab")[i].style.display = "none"; } document.getElementById("Resetpw-content1").style.display = "inherit"; } } }; VerifyToken(); lrCallingObj.$hooks.register('registrationSchemaFilter', registrationSchema); function registrationSchema(regSchema, userProfile) { if(userProfile){ document.getElementById("registration-container").style.display = "none"; document.getElementById("interfacecontainerdiv").style.display = "none"; document.getElementById("lr-ls-sectiondivider").style.display = "none"; } } lrCallingObj.$hooks.register('startProcess', function() { document.getElementById("loader").style.display = "block"; }); lrCallingObj.$hooks.register('endProcess', function() { document.getElementById("loader").style.display = "none"; }); lrCallingObj.$hooks.register('socialLoginFormRender',function(){ //on social login form render document.getElementById("tab2").checked = true; }); if (!options.language){ lrCallingObj.$hooks.call('setButtonsName', { login: "LOG IN", registration: 'SIGN UP', forgotPassword: "SEND", resetPassword: "RESET" });} } })(window);
'use strict'; module.exports = { checkstyle: require('./checkstyle'), clean: require('./clean'), lint: require('./lint'), mocha: require('./mocha') };
var searchData= [ ['g1',['G1',['../ExternalTrackingIfc_8h.html#a01fdbe4643233dbacdf58e54367d7289aaec6d2231567cdb9063f093d8effa224',1,'ExternalTrackingIfc.h']]], ['g2',['G2',['../ExternalTrackingIfc_8h.html#a01fdbe4643233dbacdf58e54367d7289aedce8067580fa0c4c235f8534f25a7b3',1,'ExternalTrackingIfc.h']]], ['galileo',['GALILEO',['../Gnss_8h.html#a0745eb9c0606157614241684b73cd7deaf6d041d14f6a7e8a76ae3f0eae6b9814',1,'Gnss.h']]], ['galileo_5fsynced',['GALILEO_SYNCED',['../ExternalTrackingIfc_8h.html#a20bddc7c6d719fa872cab2c474655205a6aa0013d02aa06f6932ea7c0bb6f47bd',1,'ExternalTrackingIfc.h']]], ['glonass',['GLONASS',['../Gnss_8h.html#a0745eb9c0606157614241684b73cd7dea7d23de99080060f3d7d481c5ee0dddb7',1,'Gnss.h']]], ['glonasst',['GLONASST',['../ExternalTrackingIfc_8h.html#a61bf587eb5899585cb3c46fc72f721cfa2fb85f4d41565b22ad15accfde38f821',1,'ExternalTrackingIfc.h']]], ['gps',['GPS',['../Gnss_8h.html#a0745eb9c0606157614241684b73cd7dea171ede81b49deebf3e342cdf41c62182',1,'Gnss.h']]], ['gps_5fsynced',['GPS_SYNCED',['../ExternalTrackingIfc_8h.html#a20bddc7c6d719fa872cab2c474655205ac722977e9609d8212ca25aeaa4ed99ad',1,'ExternalTrackingIfc.h']]], ['gpst',['GPST',['../ExternalTrackingIfc_8h.html#a61bf587eb5899585cb3c46fc72f721cfa569efac7b806b48d344a6a986b208931',1,'ExternalTrackingIfc.h']]], ['gst',['GST',['../ExternalTrackingIfc_8h.html#a61bf587eb5899585cb3c46fc72f721cfa8fc7c6036de659fcb61e9aa865cbf7f6',1,'ExternalTrackingIfc.h']]] ];
'use strict' const db = require('APP/db') const User = db.model('users') const Order = db.model('orders') const {mustBeLoggedIn, forbidden, selfOnly, adminOnly} = require('./auth.filters') module.exports = require('express').Router() .get('/', // // The forbidden middleware will fail *all* requests to list users. // // Remove it if you want to allow anyone to list all users on the site. // // // // If you want to only let admins list all the users, then you'll // // have to add a role column to the users table to support // // the concept of admin users. // forbidden('listing users is not allowed'), (req, res, next) => User.findAll() .then(users => res.json(users)) .catch(next)) .post('/', (req, res, next) => User.create(req.body) .then(user => res.status(201).json(user)) .catch(next)) .get('/:id', // mustBeLoggedIn, // selfOnly, (req, res, next) => User.findById(req.params.id) .then(user => res.json(user)) .catch(next)) .get('/:id/orders', (req, res, next) => { Order.findAll({ where: { user_id: req.params.id } }) .then(foundOrders => res.json(foundOrders)) .catch(next) }) .put('/:id', // mustBeLoggedIn, (req, res, next) => User.findById(req.params.id) .then(foundUser => foundUser.update(req.body)) .then(updatedUser => res.json(updatedUser)) .catch(next) ) .delete('/:id', (req, res, next) => User.findById(req.params.id) .then(foundUser => foundUser.destroy()) .then(() => res.sendStatus(200)) .catch(next) )
Meteor.publish('pokerCurrentStatus', function() { // Meteor._sleepForMs(3000); // Signup if not var pokerPlayer = Pokerplayers.findOne({ 'playerId': this.userId }); if (! pokerPlayer) { Pokerplayers.insert({ playerId: this.userId, credit: Meteor.settings.bispoker.hourlyCredit, createdAt: Bisia.Time.now() }); } // Counters todayPoint totalPoint // Counter position calcolata in actionChange Game ad ogni conclusione punto e salvata in Pokerplayers // Counts.publish(this, 'weekTotal', Pokerhands.find({ 'playerId': this.userId, 'createdAt': Bisia.Poker.weekGame() }), { countFromField: 'win', noReady: true }); Counts.publish(this, 'weekTotal', Pokerplayers.find({ 'playerId': this.userId }), { countFromField: 'points', noReady: true }); Counts.publish(this, 'todayTotal', Pokerhands.find({ 'playerId': this.userId, 'createdAt': Bisia.Poker.dayGame() }), { countFromField: 'win', noReady: true }); // Publish the user var user = Users.find({ '_id': this.userId }); // Publish today hands var hands = Pokerhands.find({ 'playerId': this.userId, 'createdAt': Bisia.Poker.weekGame() }); // Publish players var players = Pokerplayers.find(); // Meteor._sleepForMs(2000); return [user, hands, players]; }); Meteor.publish('pokerCurrentRanking', function(query, options) { check(query, Object); check(options, Object); // Publish players var players = Pokerplayers.find(query, options); if (players.count() > 0) { // map the authorIds var userIds = players.map(function(doc) { return doc['playerId'] }); var authors = Users.find({ '_id': { '$in': userIds }}); // return cursors return [players, authors]; } // Meteor._sleepForMs(2000); return players; }); Meteor.publish('pokerLastWinners', function() { // get current year var year = parseInt(moment().format('YYYY')); var winners = Pokerwinners.find({ 'gameYear': year }); if (winners.count() > 0) { var userIds = []; winners.forEach(function(winner) { _.each(winner.winners, function(value, index) { userIds.push(value['winnerId']); }); }); var players = Users.find({ '_id': { '$in': userIds }}); return [winners, players]; } return winners; }); Meteor.publish('playerHands', function(query, options) { check(query, Object); check(options, Object); console.log(query); // get poker hands return Pokerhands.find(query, options); });