text
stringlengths
2
6.14k
/* * written by @alicelieutier */ var Listener = function(audioContext) { var analyserNode = null; var freqByteData = null; var inputPoint = null; var lastLog = 0; var start = 0; var that = {}; var intervalID = null; var ready = false; var onBeepCalled = false; var ob_callback = null; var ob_interval = null; var REDUCE_BAND = 500; var MAGIC_CONSTANT = 20; that.setFrequency = function(_freq) { freq = _freq; }; that.onBeep = function(callback, interval) { ob_callback = callback; ob_interval = interval; if (ready === true) { updateAnalyser(); } else { onBeepCalled = true; } }; that.stop = function() { window.clearInterval(intervalID); }; function updateAnalyser(){ analyserNode.getByteFrequencyData(freqByteData); var samplerate = audioContext.sampleRate; var fftsize = analyserNode.fftSize; var antifreqs = [freq - REDUCE_BAND, freq + REDUCE_BAND]; var sound = freqByteData[Math.round(freq * fftsize / samplerate)]; for (var i = 0; i < antifreqs.length; i++) { sound -= freqByteData[Math.round(antifreqs[i] * fftsize / samplerate)]; }; if (sound > MAGIC_CONSTANT && (Date.now() - lastLog) > ob_interval) { lastLog = Date.now(); ob_callback(); } intervalID = window.setTimeout(updateAnalyser, 0); } function gotStream(stream, callback) { inputPoint = audioContext.createGain(); // Create an AudioNode from the stream. audioInput = audioContext.createMediaStreamSource(stream); audioInput.connect(inputPoint); analyserNode = audioContext.createAnalyser(); analyserNode.fftSize = 2048; inputPoint.connect( analyserNode ); zeroGain = audioContext.createGain(); zeroGain.gain.value = 0.0; inputPoint.connect( zeroGain ); zeroGain.connect( audioContext.destination ); start = Date.now(); freqByteData = new Uint8Array(analyserNode.frequencyBinCount); ready = true; if (onBeepCalled === true) { that.onBeep(ob_callback, ob_interval); } } navigator.getMedia = ( navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia); navigator.getMedia( {audio:true}, gotStream, function(e) { alert('Error getting audio'); console.log(e); } ); return that; };
var mongoose = require('mongoose') var Note = mongoose.Schema({ title: String, content: String, alias: String, created: {type: Date, default: Date.now}, updated: {type: Date, default: Date.now}, user_id: { type: mongoose.Schema.Types.ObjectId, ref: 'user', index: true } }) module.exports = mongoose.model('note', Note)
var koa = require('koa'); var request = require('supertest'); var unless = require('../index'); describe('koa-unless', function() { var middleware; beforeEach(function() { middleware = function *(next) { this.body = {executed: true}; }; middleware.unless = unless; }); describe('with PATH exception', function() { it('should not call the middleware when one of the path match', function(done) { var app = koa(); app.use(middleware.unless({ path: ['/foo'] })); request(app.listen()) .get('/foo') .expect(404, done); }); it('should call the middleware when the path doesnt match', function(done) { var app = koa(); app.use(middleware.unless({ path: ['/foo'] })); request(app.listen()) .get('/bar') .expect(200, done); }); }); describe('with PATH (regexp) exception', function() { it('should not call the middleware when the regex match', function(done) { var app = koa(); app.use(middleware.unless({ path: ['/foo', /ar$/ig] })); request(app.listen()) .get('/bar') .expect(404, done); }); }); describe('with PATH (useOriginalUrl) exception', function() { it('should not call the middleware when one of the path match this.url instead of this.originalUrl', function(done) { var app = koa(); app.use(function *(next) { this.url = '/foo'; yield *next; }); app.use(middleware.unless({ path: ['/foo'], useOriginalUrl: false })); request(app.listen()) .get('/orig/foo') .expect(404, done); }); it('should call the middleware when the path doesnt match this.url even if path matches this.originalUrl', function(done) { var app = koa(); app.use(function *(next) { this.originalUrl = '/foo'; yield *next; }); app.use(middleware.unless({ path: ['/foo'], useOriginalUrl: false })); request(app.listen()) .get('/bar') .expect(200, done); }); }); describe('with EXT exception', function() { it('should not call the middleware when the ext match', function(done) { var app = koa(); app.use(middleware.unless({ ext: ['html', 'css'] })); request(app.listen()) .get('/index.html') .expect(404, done); }); it('should call the middleware when the ext doesnt match', function(done) { var app = koa(); app.use(middleware.unless({ ext: ['html', 'css'] })); request(app.listen()) .get('/index.js') .expect(200, done); }); }); describe('with METHOD exception', function() { it('should not call the middleware when the method match', function(done) { var app = koa(); app.use(middleware.unless({ method: ['GET', 'OPTIONS'] })); request(app.listen()) .get('/index') .expect(404, done); }); it('should call the middleware when the method doesnt match', function(done) { var app = koa(); app.use(middleware.unless({ method: ['GET', 'OPTIONS'] })); request(app.listen()) .post('/index') .expect(200, done); }); }); describe('with custom exception', function() { it('should not call the middleware when the custom rule match', function(done) { var app = koa(); app.use(middleware.unless(function() { return this.url === '/index'; })); request(app.listen()) .get('/index') .expect(404, done); }); it('should call the middleware when the custom rule doesnt match', function(done) { var app = koa(); app.use(middleware.unless(function() { return this.url === '/index'; })); request(app.listen()) .get('/home') .expect(200, done); }); }); });
class upnp_soaprequest_1 { constructor() { } // System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) CreateObjRef() { } // bool Equals(System.Object obj) Equals() { } // int GetHashCode() GetHashCode() { } // System.Object GetLifetimeService() GetLifetimeService() { } // type GetType() GetType() { } // System.Object InitializeLifetimeService() InitializeLifetimeService() { } // string ToString() ToString() { } } module.exports = upnp_soaprequest_1;
version https://git-lfs.github.com/spec/v1 oid sha256:bb0a48d8e900f44c985c3d851c63f300488bc5cbbaf2ce978fd3f65b7c8660b8 size 4500
module.exports = { listAirPlayDevices: function (callback){ itunes = Application('iTunes'); airPlayDevices = itunes.airplayDevices(); airPlayResults = []; for (i = 0; i < airPlayDevices.length; i++) { airPlayDevice = airPlayDevices[i]; if (!airPlayDevice.networkAddress()) continue; deviceData = {}; deviceData["id"] = airPlayDevice.networkAddress().replace(/:/g, '-'); deviceData["name"] = airPlayDevice.name(); deviceData["kind"] = airPlayDevice.kind(); deviceData["active"] = airPlayDevice.active(); deviceData["selected"] = airPlayDevice.selected(); deviceData["soundVolume"] = airPlayDevice.soundVolume(); deviceData["supportsVideo"] = airPlayDevice.supportsVideo(); deviceData["supportsAudio"] = airPlayDevice.supportsAudio(); deviceData["networkAddress"] = airPlayDevice.networkAddress(); airPlayResults.push(deviceData); } return airPlayResults; }, setSelectionStateAirPlayDevice: function (id, selected){ itunes = Application('iTunes'); id = id.replace(/-/g, ':'); foundAirPlayDevice = null; deviceData = {}; airPlayDevices = itunes.airplayDevices(); for (i = 0; i < airPlayDevices.length; i++) { airPlayDevice = airPlayDevices[i]; if (airPlayDevice.networkAddress() == id){ foundAirPlayDevice = airPlayDevice; break; } } if (foundAirPlayDevice) { foundAirPlayDevice.selected = selected; deviceData["id"] = foundAirPlayDevice.networkAddress().replace(/:/g, '-'); deviceData["name"] = foundAirPlayDevice.name(); deviceData["kind"] = foundAirPlayDevice.kind(); deviceData["active"] = foundAirPlayDevice.active(); deviceData["selected"] = foundAirPlayDevice.selected(); deviceData["soundVolume"] = foundAirPlayDevice.soundVolume(); deviceData["supportsVideo"] = foundAirPlayDevice.supportsVideo(); deviceData["supportsAudio"] = foundAirPlayDevice.supportsAudio(); deviceData["networkAddress"] = foundAirPlayDevice.networkAddress(); } return deviceData; } }
define(['jquery', 'knockout', './router', 'bootstrap', 'knockout-projections', 'knockout-select-on-focus'], function($, ko, router) { // Components can be packaged as AMD modules, such as the following: ko.components.register('home-page', { require: 'components/home-page/legacy/home' }); ko.components.register('ko-gmap', { require: 'components/ko-gmap/legacy/ko-gmap' }); ko.components.register('ko-gmap-search', { require: 'components/ko-gmap-search/legacy/ko-gmap-search' }); ko.components.register('gll-map', { require: 'components/gll-map/legacy/gll-map' }); ko.components.register('gll-search', { require: 'components/gll-search/legacy/gll-search' }); ko.components.register('gll-locations', { require: 'components/gll-locations/legacy/gll-locations' }); // [Scaffolded component registrations will be inserted here. To retain this feature, don't remove this comment.] ko.components.register('gll-card', { template: { require: 'text!components/gll-card/legacy/gll-card.html' } }); // Start the application ko.applyBindings({ route: router.currentRoute }); });
// Karma configuration // http://karma-runner.github.io/0.12/config/configuration-file.html // Generated on 2015-10-15 using // generator-karma 1.0.0 module.exports = function(config) { 'use strict'; config.set({ // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // base path, that will be used to resolve files and exclude basePath: '../', // testing framework to use (jasmine/mocha/qunit/...) // as well as any additional frameworks (requirejs/chai/sinon/...) frameworks: [ "jasmine" ], // list of files / patterns to load in the browser files: [ // bower:js 'bower_components/angular/angular.js', 'bower_components/angular-animate/angular-animate.js', 'bower_components/angular-aria/angular-aria.js', 'bower_components/angular-cookies/angular-cookies.js', 'bower_components/angular-resource/angular-resource.js', 'bower_components/angular-route/angular-route.js', 'bower_components/angular-sanitize/angular-sanitize.js', 'bower_components/angular-touch/angular-touch.js', 'bower_components/angular-mocks/angular-mocks.js', // endbower "app/scripts/**/*.js", "test/mock/**/*.js", "test/spec/**/*.js" ], // list of files / patterns to exclude exclude: [ ], // web server port port: 8080, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: [ "PhantomJS" ], // Which plugins to enable plugins: [ "karma-phantomjs-launcher", "karma-jasmine" ], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false, colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // Uncomment the following lines if you are using grunt's server to run the tests // proxies: { // '/': 'http://localhost:9000/' // }, // URL root prevent conflicts with the site root // urlRoot: '_karma_' }); };
var structlfgui_1_1event__function = [ [ "event_function", "structlfgui_1_1event__function.html#ab18ef7fc7527035959f81e5f6f8f8130", null ], [ "event_function", "structlfgui_1_1event__function.html#acd471e4c04c485dc49a27c77fa0ec694", null ], [ "event_function", "structlfgui_1_1event__function.html#a0b9174a7574f884754ab63baf8fc203d", null ], [ "event_function", "structlfgui_1_1event__function.html#a62c6c3dbec718bbea5a97896997838ee", null ], [ "operator bool", "structlfgui_1_1event__function.html#aa4db19e4d7df8d1be422a0ed333ec06a", null ], [ "bool_em", "structlfgui_1_1event__function.html#a2479302e103daff65a3c0b8ce34f604c", null ], [ "void_em", "structlfgui_1_1event__function.html#ad2ab08ac6cce84e39714f524a1686cde", null ], [ "void_void", "structlfgui_1_1event__function.html#a8d3b9a9240569402767b96eac686c885", null ] ];
/** * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'uicolor', 'sl', { title: 'UI Izbiralec Barve', preview: 'Živi predogled', config: 'Prilepite ta niz v vašo config.js datoteko', predefined: 'Vnaprej določeni barvni kompleti' } );
var moment = require('moment'); var _ = require('lodash'); var uuid = require('uuid'); /** * Initiate AWS DynamoDB bucket event. * @param {Object} options - Passed config options. * @param {Object} options.schema - DynamoDB table schema. * @param {string} options.region - Region of AWS S3 bucket. * @param {string} options.eventType - Event type that was defined in AWS S3 bucket (Put, Post, Copy, CompleteMultiPartUpload, Delete, DeleteMarkerCreated). * @param {string} options.eventName - Event name. * @param {string} options.functionName - Name of invoked function. */ function initAWSDynamoDB(options) { var self = this; var _opt = _.assignIn(this._options, options); // TODO: Get rid of Lodash. var invokeID = uuid.v1(); var keys; try { keys = getKeys() } catch (err) { self.invoke = function() { throw new Error('Provide schema for current DynamoDB table.') }; return self; } this.event = { Records: [{ eventID: uuid.v4(), eventName: _opt.eventType, eventVersion: '1.0', eventSource: 'aws:dynamodb', awsRegion: _opt.region, dynamodb: { Keys: keys, NewImage: getImage(), StreamViewType: 'NEW_AND_OLD_IMAGES' // TODO: ViewType option. }, eventSourceARN: 'test' }] }; this.context = { awsRequestId: invokeID, // TODO: Investigate what the difference with invokeid. invokeid: invokeID, logGroupName: '/aws/lambda/' + _opt.functionName, functionName: _opt.functionName, memoryLimitInMB: _opt.memoryLimitInMB, // TODO: Investigate how to define used memory with invocation. functionVersion: '$LATEST', // TODO: Investigate how to recognize function versions. invokedFunctionArn: _opt.invokedFunctionArn, getRemainingTimeInMillis: function() { // TODO: Investigate how to return remaining time. return self.startAt - self.endAt; }, succeed: function(data) { self.endAt = new Date().getTime(); self.succeedCallCount++; self.invocationResult = data; return data; }, fail: function(error) { // TODO: Substring error message[1]. self.endAt = new Date().getTime(); self.failCallCount++; self.invocationResult = { error: error }; return error; }, done: function(error, data) {} // TODO: Handle error and data. }; /** * Get primary key for current schema * TODO: Investigate the posibility of adding more than 1 primary key. */ function getKeys() { var keyObj = {}; var keyType = {}; // TODO: Implement unified parser for schema types. switch (options.schema[options.schema.primaryKey].toLowerCase()) { case 'string': keyType.S = options.item[options.schema.primaryKey]; break; case 'number': keyType.N = options.item[options.schema.primaryKey]; break; case 'binary': keyType.B = options.item[options.schema.primaryKey]; break; default: keyType.S = options.item[options.schema.primaryKey]; } keyObj[options.schema.primaryKey] = keyType; return keyObj; } function getImage() { var imageObj = {}; for (var key in options.item) { var type = {}; // TODO: Implement unified parser for schema types. switch (options.schema[key].toLowerCase()) { case 'string': type.S = options.item[key]; break; case 'number': type.N = options.item[key]; break; case 'binary': type.B = options.item[key]; break; default: type.S = options.item[key]; } imageObj[key] = type; } return imageObj; } } /** [1] * Note * For the error from context.fail(error) and context.done(error, null), * Lambda will log the first 256 KB of the error object. AWS Lambda will * truncate larger error objects when it logs the error, you will see * the text "- Truncated by Lambda" next to their error object. */ // TODO: Investigate the most appropriate options (+ add unique identificator for default options). initAWSDynamoDB.prototype._options = { region: 'us-west-1', eventType: 'INSERT', functionName: 'test-lambda', memoryLimitInMB: '128', invokedFunctionArn: 'arn:aws:lambda:us-west-1:*:function:test-lambda' }; // TODO: Implement function handler initAWSDynamoDB.prototype.invoke = function(fn) { this.startAt = new Date().getTime(); return fn(this.event, this.context); }; /** Invocation result. By default - 'Process exited before completing request.' */ initAWSDynamoDB.prototype.invocationResult = 'Process exited before completing request.'; /** Context handlers counters */ initAWSDynamoDB.prototype.succeedCallCount = 0; initAWSDynamoDB.prototype.failCallCount = 0; initAWSDynamoDB.prototype.doneCallCount = 0; /** Function time execution */ initAWSDynamoDB.prototype.startAt = 0; initAWSDynamoDB.prototype.endAt = 0; module.exports = initAWSDynamoDB;
'use strict' var React = require('react') var request = require('xhr') var object_assign = require('object-assign') var Spinner = require('../../shared/spinner.js') var make_query = function () { var email = this.refs.email.value var vals = { id: this.refs.id.value, last_name: this.refs.last_name.value, activation_status: this.refs.activation_status.value } var filtered_vals = get_actual_values(vals) function add_in_filtered (obj) { return object_assign({}, obj, filtered_vals) } return !!email ? { or: [ add_in_filtered({primary_email: email}), add_in_filtered({secondary_email: email}) ] } : filtered_vals } function get_actual_values (object) { return Object.keys(object) .filter(function (key) { return ( !!object[key] || object[key] === false ) }) .reduce(function (agg, key) { agg[key] = object[key] return agg }, {}) } var SearchBox = React.createClass({ getInitialState: function () { return { loading: false } }, search: function (e) { e.preventDefault() var query = make_query.bind(this)() var { updateResults, none_found, clear_none_found } = this.props this.props.clear_none_found() this.setState({ loading: true }) request({ method: 'GET', url: '/api/members?where=' + JSON.stringify(query) + '&populate=[payments]' }, function (err, resp, body) { this.setState({ loading: false }) if (JSON.parse(body).length === 0) none_found() updateResults(body) }.bind(this)) }, render: function () { return ( <div className='search-component'> <form className='search-container' onSubmit={this.search} > <select id='member-status' ref='activation_status' defaultValue='activated'> <option value='activated'>Active</option> <option value='deactivated'>Deleted</option> </select> <input className='input-member' ref='id' id='id' placeholder='Number' /> <input className='input-member' ref='email' id='email' placeholder='Email' /> <input className='input-member' ref='last_name' id='last_name' placeholder='Surname' /> <button type='submit' className='button-two member' id='search-button'>Search</button> <p id='test' ref='test'></p> </form> { this.state.loading ? <Spinner /> : '' } </div> )}}) module.exports = SearchBox
const add = (x=0, y=0) => { return x + y } export default add
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.disposeScene = disposeScene; exports.disposeObject = disposeObject; var _three = require('three'); var Three = _interopRequireWildcard(_three); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function disposeGeometry(geometry) { geometry.dispose(); } function disposeTexture(texture) { if (!texture) { return; } texture.dispose(); } function disposeMultimaterial(material) { if (!(material instanceof Three.MultiMaterial)) { return; } material.materials.forEach(function (material) { disposeMaterial(material); }); } function disposeMaterial(material) { if (!(material instanceof Three.Material)) { return; } disposeTexture(material.map); material.map = null; material.dispose(); } function disposeMesh(mesh) { if (!(mesh instanceof Three.Mesh || mesh instanceof Three.BoxHelper || mesh instanceof Three.LineSegments)) { return; } disposeGeometry(mesh.geometry); disposeMultimaterial(mesh.material); disposeMaterial(mesh.material); mesh.geometry = null; mesh.material = null; } function disposeScene(scene3D) { scene3D.traverse(function (child) { disposeMesh(child); child = null; }); } function disposeObject(object) { object.traverse(function (child) { disposeMesh(child); child = null; }); }
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; const propTypes = { active: PropTypes.bool, }; const ROOT = 'mdc-text-field__bottom-line'; const ACTIVE = `${ROOT}--active`; const BottomLine = ({ active }) => ( <div className={classnames(ROOT, { [ACTIVE]: active, })} /> ); BottomLine.propTypes = propTypes; export default BottomLine;
(function(window, undefined) { /*********************** START STATIC ACCESS METHODS ************************/ jQuery.extend(jimMobile, { "loadScrollBars": function() { jQuery(".s-724d6129-a5ed-4b21-a1a7-3ef200a06710 .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); jQuery(".s-883aed0b-77af-4e79-a3c7-3b701ac93f7d .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); jQuery(".s-f3a3edb4-1297-4c0d-96d4-2c1ec9870070 .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); jQuery(".s-ed74f470-4343-4380-a864-f8dbad599122 .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); jQuery(".s-a55013df-bea6-4693-86cc-1c4c6e922cbe .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); jQuery(".s-825d8d4d-d97b-4a27-8c53-9894f5e6cd0b .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); jQuery(".s-8cbba4f8-8373-40d3-9672-c51ef00654fa .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); jQuery(".s-e92c9fb5-5803-4083-ae7c-cf8c435fc4e2 .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); jQuery(".s-8a638ee1-d936-47c6-b4d7-1fa17ca84294 .ui-page").overscroll({ showThumbs:true, direction:'multi' }); jQuery(".s-95adc887-3e85-4566-95d6-d7b6077c8c85 .ui-page").overscroll({ showThumbs:true, direction:'multi' }); jQuery(".s-7198b126-8045-4499-9acf-878838131f88 .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); jQuery(".s-6f7f7e16-6686-402a-94ad-a2c5a1160750 .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); jQuery(".s-70cd42b1-78db-4d0f-a724-9ca3d034a4c9 .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); jQuery(".s-c059d41f-6c0e-4b56-a064-91bd05da5a78 .ui-page").overscroll({ showThumbs:true, direction:'vertical' }); } }); /*********************** END STATIC ACCESS METHODS ************************/ }) (window);
'use strict'; var express = require('express'); var routes = require('./app/routes/index.js'); var mongoose = require('mongoose'); var bodyParser = require('body-parser') var app = express(); // require('dotenv').load(); mongoose.connect(process.env.MONGO_URI); mongoose.Promise = global.Promise; // Configure server to parse JSON for us app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.use('/public', express.static(process.cwd() + '/public')); routes(app); var port = process.env.PORT || 8080; app.listen(port, function () { console.log('Node.js listening on port ' + port + '...'); });
var http = require('http'); var server = http.createServer(function (request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); var ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress; response.end(ip); }); server.listen(8080, "0.0.0.0");
module.exports = function(ngModule) { ngModule.run(function($rootScope) { $rootScope.Date = Date; $rootScope.Math = Math; $rootScope.$endevAnnotation = false; $rootScope.$endevErrors = []; angular.element(document.body) .attr("ng-class","{'__endev_annotation_on__':$endevAnnotation}") .append(require("../templates/annotations.html")); }); };
(function() { "use strict"; R.extendElement('addEventOnce', function(type, handler, elem) { R.addEvent(elem, type, function once(e) { handler.call(elem, e); R.removeEvent(type, once, elem); }); return elem; }); }());
"use strict"; export default (() => { let identity = (v) => v; return { id: identity, identity }; })();
/** * Opens provided file in browser. * * • Tabs should be opened using the terminal via this task. Doing * so will ensure the generated tab will auto-close when Gulp is * closed. Opening tabs by typing/copy-pasting the project URL * into the browser address bar will not auto-close the tab(s) * due to security issues as noted here: * [https://stackoverflow.com/q/19761241]. * * -F, --file <file> * The path of the file to open. * * -p, --port [number] * The port to open in. (Defaults to browser-sync port if * available or no port at all.) * * -d, --directory [string] * The directory path to open in a file manager. * * -e, --editor [string] * The file path to open in the user's text editor to edit. * * -w, --wait [boolean] * To be Used with the -e/--editor flag. If provided the * editor will wait to close and will only close manually (i.e. * close the editor or exit the terminal task). * * -l, --line [number] * To be used with -e/--editor flag. Open the file at the * provided line. * *-c, --column [number] * To be used with -e/--editor flag. Open the file at the * provided column. * * -u, --use [string] * To be used with -e/--editor flag. Manually set the editor * to use. Will default to the user's default editor via * ($EDITOR/$VISUAL) environment variables. * * $ gulp open --file index.html --port 3000 * Open index.html in port 3000. * * $ gulp open --file index.html * Open index.html in browser-sync port is available or no port. * * $ gulp open --editor ./index.html --wait --line 12 --column 20 --use atom * Open "./index.html" using the text editor Atom if available. * Set the line to 12 and column 20. Use the --wait flag to close * the process after the editor is close or the process is killed via * the terminal. * * $ gulp open --directory . * Open the root directory in a file manager. * * $ gulp open --directory ./docs * Open the docs directory in a file manager. * * $ gulp open --directory docs/subextensions.md * When a file is provided along with the directory, only the directory * section of the path will be used to try and open in a file manager. */ gulp.task("open", function(done) { // Cache task. var task = this; // Variables. var __flags; // Run yargs. __flags = yargs .option("directory", { alias: "d", type: "string" }) .option("editor", { alias: "e", type: "string" }).argv; // Get flag values. var directory = __flags.d || __flags.directory; var editor = __flags.e || __flags.editor; // If the directory flag is provided open directory in a file manager. if (directory) { // Parse the directory. var parts = path.parse(directory); if (!parts.ext) { // No file was passed in so reset the directory. directory = parts.dir + "/" + parts.base + "/"; } else { // If a file is passed only get the directory part. directory = parts.dir + "/"; } // Make the path absolute and relative to the main project root. directory = path.join("./", directory); // Check that the directory exists. if (!de.sync(directory)) { print.gulp.warn( "The directory", chalk.magenta(directory), "does not exist." ); return done(); } // Else the directory exists so open the file manager. require("opener")(directory, function() { done(); }); } else if (editor) { // If the editor flag is provided open the given file in the user's // default editor. var spawn = require("child_process").spawn; // Check that the file exists. if (!fe.sync(editor)) { print.gulp.warn( "The file", chalk.magenta(directory), "does not exist." ); return done(); } // Run yargs. __flags = yargs .option("wait", { alias: "w", type: "boolean" }) .option("line", { alias: "l", type: "number" }) .option("column", { alias: "c", type: "number" }) .option("use", { alias: "u", type: "string" }).argv; // Get flag values. var wait = __flags.w || __flags.wait; var line = __flags.l || __flags.line; var column = __flags.c || __flags.column; var use_editor = __flags.u || __flags.use; // Get user's editor/flags needed to open file via the terminal. // Note: The editor variable here is being reused. This is alright // as it gets passed into the function before being overwritten. editor = get_editor({ file: { name: editor, line: line, column: column }, editor: use_editor }); // Create the child process to open the editor. var child_process = spawn(editor.command, editor.flags, { stdio: "inherit", detached: true }); // If an error occurs throw it. child_process.on("error", function(err) { if (err) { throw err; } }); // If the wait flag is provided make the process hold until the // user closes the file or the terminal process is ended manually. if (wait) { // Once the file is closed continue with the task... child_process.on("exit", function() { done(); }); } else { // Else close the process immediately. child_process.unref(); return done(); } } else { // Else open the file in a browser. Which is what this task was // originally set out to do. // Run yargs. __flags = yargs .option("file", { alias: "F", type: "string", demandOption: true }) .option("port", { alias: "p", type: "number" }).argv; // Get flag values. var file = __flags.F || __flags.file; // Check for explicitly provided port. If none is provided check // the internally fetched free ports and get the local port. var port = __flags.p || __flags.port || ( INT_PORTS || { local: null } ).local; // Open the file in the browser. return open_file_in_browser(file, port, done, task); } });
'use strict'; var fs = require('fs') var path = require('path') var log = require('spm-log') var template = require('gulp-template') var inquirer = require('inquirer') var semver = require('semver') var vfs = require('vinyl-fs') module.exports = function(options) { if (!options.force && fs.readdirSync(process.cwd()).length > 0) { return log.error('init spa', '请在非空目录上执行初始化命令!') } log.info('init spa', '...') inquirer.prompt([{ message: ' 项目名:', name: 'appname', 'default': path.basename(process.cwd()), validate: function(input) { var done = this.async() if (!/^[a-z][a-z0-9\-\.]*$/.test(input)) { log.warn('init spa', 'Must be only lowercase letters, numbers, dashes or dots, and start with lowercase letter.') return } done(true) } }, { message: ' 版本号:', name: 'version', 'default': '0.0.0', validate: function(input) { var done = this.async() if (!semver.valid(input)) { log.warn('init spa', 'Must be a valid semantic version (semver.org).') return } done(true) } }, { message: '项目描述:', name: 'description' }], function(answers) { answers.varname = answers.appname .replace(/\-(\w)/g, function(_, $1){ return $1.toUpperCase() }) answers.user = require('../../util/get-user')() answers.time = require('../../util/get-time')() vfs.src(path.join(__dirname, '../../tpl/spa/**'), { dot: true }) .pipe(template(answers)) .pipe(vfs.dest('./')) .on('end', function() { log.info('init spa', 'done!') }) }) }
'use strict'; import * as actions from '../actions'; import DigitalAsset from '../models/DigitalAsset'; import Source from '../models/Source'; const initialDigitalAssetState = { digital_asset: new DigitalAsset(), dropzone: null, dropzone_file_stats: null, error: false, isSubmitting: false, source_options: [] }; export function digital_assets(state = initialDigitalAssetState, action) { switch (action.type) { case actions.LOADED_DIGITAL_ASSET_FORM_SUCCESS: return Object.assign({}, state, { isSubmitting: false, error: action.error, source_options: action.payload._items }); case actions.LOADED_DIGITAL_ASSET_FORM_FAILURE: return Object.assign({}, state, { isSubmitting: false, error: action.error }); case actions.LOAD_DIGITAL_ASSET_SUCCESS: const load_da = new DigitalAsset(); delete action.payload._links; delete action.payload._created; delete action.payload._updated; Object.assign(load_da, action.payload); load_da._id = action.payload._id; return Object.assign({}, state, { isSubmitting: false, error: action.error, digital_asset: load_da }); case actions.LOAD_DIGITAL_ASSET_FAILURE: return Object.assign({}, state, { isSubmitting: false, error: action.error }); case actions.CHANGE_DIGITAL_ASSET_FORM: const new_da = new DigitalAsset(); Object.assign(new_da, state.digital_asset); new_da[action.payload.key] = action.payload.value; return Object.assign({}, state, { error: action.error, digital_asset: new_da }); case actions.CHANGE_DIGITAL_ASSET_FORM_FROM_MAP: const new_da_map = new DigitalAsset(); Object.assign(new_da_map, state.digital_asset); new_da_map['latitude'] = action.payload.lat; new_da_map['longitude'] = action.payload.lng; return Object.assign({}, state, { error: action.error, digital_asset: new_da_map }); case actions.CREATE_DIGITAL_ASSET: return Object.assign({}, state, { isSubmitting: true, error: action.error, digital_asset: action.payload }); case actions.CREATE_DIGITAL_ASSET_SUCCESS: return Object.assign({}, state, { isSubmitting: false, error: action.error, digital_asset: new DigitalAsset(), dropzone: null, dropzone_file_stats: null }); case actions.CREATE_DIGITAL_ASSET_FAILURE: return Object.assign({}, state, { isSubmitting: false, error: action.error }); case actions.DROPZONE_LOAD_SUCCESS: return Object.assign({}, state, { dropzone: action.payload, error: action.error }); case actions.DROPZONE_UPLOAD_SUCCESS: const new_with_image = new DigitalAsset(); Object.assign(new_with_image, state.digital_asset); new_with_image['image_url'] = action.payload.image_url; new_with_image['image_width'] = action.payload.image_width; new_with_image['image_height'] = action.payload.image_height; return Object.assign({}, state, { dropzone_file_stats: action.payload, digital_asset: new_with_image, error: action.error }); case actions.UPDATE_DIGITAL_ASSET: return Object.assign({}, state, { isSubmitting: true, error: action.error, digital_asset: action.payload }); case actions.UPDATE_DIGITAL_ASSET_SUCCESS: return Object.assign({}, state, { isSubmitting: false, error: action.error, digital_asset: action.payload }); case actions.UPDATE_DIGITAL_ASSET_FAILURE: return Object.assign({}, state, { isSubmitting: false, error: action.error }); default: return state; } } const initialSourceState = { error: false, isSubmitting: false, source: new Source() }; export function sources(state = initialSourceState, action) { switch (action.type) { case actions.LOAD_SOURCE: return Object.assign({}, state, { isSubmitting: false, error: action.error }); case actions.LOAD_SOURCE_SUCCESS: const load_s = new Source( action.payload.name, action.payload.url, action.payload.email, action.payload.phone_number ); load_s._id = action.payload._id; return Object.assign({}, state, { isSubmitting: false, error: action.error, source: load_s }); case actions.LOAD_SOURCE_FAILURE: return Object.assign({}, state, { isSubmitting: false, error: action.error }); case actions.CHANGE_SOURCE_FORM: const new_s = new Source(); Object.assign(new_s, state.source); new_s[action.payload.key] = action.payload.value; return Object.assign({}, state, { error: action.error, source: new_s }); case actions.CREATE_SOURCE: return Object.assign({}, state, { isSubmitting: true, error: action.error, source: action.payload }); case actions.CREATE_SOURCE_SUCCESS: return Object.assign({}, state, { isSubmitting: false, error: action.error, source: new Source() }); case actions.CREATE_SOURCE_FAILURE: return Object.assign({}, state, { isSubmitting: false, error: action.error }); case actions.UPDATE_SOURCE: return Object.assign({}, state, { isSubmitting: true, error: action.error, source: action.payload }); case actions.UPDATE_SOURCE_SUCCESS: return Object.assign({}, state, { isSubmitting: false, error: action.error, source: action.payload }); case actions.UPDATE_SOURCE_FAILURE: return Object.assign({}, state, { isSubmitting: false, error: action.error }); default: return state; } }
features["DOM.Node.replaceChild"] = !!(document.replaceChild);
// based on https://github.com/winstonjs/winston-loggly/blob/master/test/winston-loggly-test.js var vows = require('vows'); var assert = require('assert'); var helpers = require('winston/test/helpers'); var Keenio = require('../lib/winston-keenio'); var client; var config; try { config = require('./config'); } catch (ex) { console.log('Error reading test/config.json.') console.log('Are you sure it exists?\n'); console.dir(ex); process.exit(1); } // create client client = new Keenio({ projectId: config.transports.keenio.projectId, writeKey: config.transports.keenio.writeKey, collection: config.transports.keenio.collection }); function assertKeenio(client) { assert.instanceOf(client, Keenio); assert.isFunction(client.log); } vows.describe('winston-keenio').addBatch({ "An instance of the Keenio Transport": { "when passed an input token": { "should have the proper methods defined": function () { assertKeenio(client); }, "the log() method": helpers.testNpmLevels(client, "should log messages to keenio", function (ign, err, logged) { assert.isNull(err); assert.isTrue(logged); }) } } }).export(module);
'use strict'; export default async function (hook) { delete hook.data.cash; return hook; };
var SOTH = {} || SOTH; var controls, renderer, stats, scene, camera; var geometry, material, mesh, wires; SOTH.addThreeJS = function() { renderer = new THREE.WebGLRenderer( { alpha: 1, antialias: true, clearColor: 0xffffff } ); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.shadowMapEnabled = true; renderer.shadowMapSoft = true; document.body.appendChild( renderer.domElement ); scene = new THREE.Scene(); SOTH.getTrackballController(); stats = new Stats(); stats.domElement.style.cssText = 'bottom: 10px; opacity: 0.5; position: absolute; right: 10px; '; stats.domElement.title = 'Frames per second. Click to see ms per frame'; SO.menu.appendChild( stats.domElement ); }; SOTH.addThreeFooter = function() { var footer = SO.menu.appendChild( document.createElement( 'div' ) ); footer.innerHTML = '<h2>' + '<a href=# onclick=SOTH.resetCamera(); title="Return to default view"><i class="fa fa-home"></i></a> ' + '</h2>'; }; SOTH.addAssets = function() { SOLI.toggleLightAmbient(); SOLI.toggleLightPositionCamera(); SOLI.toggleLightDirectional(); SOTH.updateGroundPlane( 126, 0, 1 ); }; SOTH.updateGroundPlane = function( segments, base, scale) { scene.remove( mesh ); scene.remove( wires ); geometry = new THREE.PlaneGeometry( 1, 1, segments - 1, segments - 1 ); geometry.applyMatrix( new THREE.Matrix4().makeRotationX( Math.PI / 2 ) ); // var texture = THREE.ImageUtils.loadTexture( "../textures/UV_Grid_512.png" ); // texture.wrapS = texture.wrapT = THREE.RepeatWrapping; // texture.anisotropy = 16; // texture.needsUpdate = true; // material = new THREE.MeshBasicMaterial( { map: texture, shading: THREE.SmoothShading, side: THREE.DoubleSide }); // material = new THREE.MeshLambertMaterial( { map: texture, color: 0xff2222, shading: THREE.SmoothShading, side: THREE.DoubleSide }); // material = new THREE.MeshNormalMaterial( { side: THREE.DoubleSide } ); // material = new THREE.MeshLambertMaterial( { color: Math.random() * 0xffffff }); // material = new THREE.MeshPhongMaterial( {map: texture, color: 0xffaaaa, ambient: 0xaaaaaa, shading: THREE.SmoothShading, shininess: 50, side: THREE.DoubleSide, specular: 0x333333 } ); // material = new THREE.MeshPhongMaterial( { ambient: 0x030303, color: 0xdddddd, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, side: THREE.DoubleSide }), material = new THREE.MeshPhongMaterial( { ambient: 0xffffff * Math.random(), color: 0xffffff * Math.random(), shininess: 0.5, side: THREE.DoubleSide, specular: 0xffffff * Math.random(), transparent: false } ); mesh = new THREE.Mesh( geometry, material ); mesh.scale.set( 200, scale, 200 ); mesh.position.y = -base; mesh.castShadow = true; mesh.receiveShadow = true; scene.add( mesh ); wires = mesh.clone(); wires.material = new THREE.MeshBasicMaterial( { wireframe: true } ); scene.add( wires ); } SOTH.getTrackballController = function() { camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 1000 ); camera.position.set( 200, 100, 200 ); controls = new THREE.TrackballControls( camera, renderer.domElement ); controls.target.set( 0, 20, 0 ); }; SOTH.resetCamera = function() { SOTH.getTrackballController(); };
// Dependencies import { h, Component } from "preact"; // Material Components import Toolbar from "preact-material-components/Toolbar"; // Components import ComponentTable from "../../components/component-table"; import CodeBlock from "../../components/code-block"; import EventsTable from "../../components/events-table"; // Styles import "./style"; // Samples import sample from "./sample.txt"; // Class export default class ToolbarPage extends Component { constructor() { super(); this.propsTable = [ { component: "Toolbar", props: [ { name: "fixed", description: "Makes toolbar fixed on top and have persistent elevation" }, { name: "fixed-lastrow-only", description: "Makes only last row of fixed toolbar anchored on top" }, { name: "waterfall", description: "Removes fixed toolbar persistent elevation and makes it to gain elevation when a user begins to scroll down the page" }, { name: "flexible", description: "Makes toolbar first row has flexible space" }, { name: "flexible-default-behavior", description: "Further defines the background and title movement behavior" } ] }, { component: "Toolbar.Row", props: [] }, { component: "Toolbar.Section", props: [ { name: "align-start", description: "Aligns the section to start of the toolbar row" }, { name: "align-end", description: "Aligns the section to end of the toolbar row" }, { name: "shrink-to-fit", description: "Makes section takes the width of its content" } ] }, { component: "Toolbar.Icon", props: [ { name: "menu", description: "Adds additional padding, intended for the left-most icon" } ] }, { component: "Toolbar.Title", props: [] } ]; this.eventsTable = [ { name: "onChange", description: "Fired when toolbar's expansion ratio is changed." } ]; } render() { return ( <div className="page-toolbar"> <ComponentTable data={this.propsTable} /> <EventsTable data={this.eventsTable} /> <div className="mdc-typography--display1">Sample code </div> <CodeBlock> <code class="lang-js">{sample}</code> </CodeBlock> <div className="mdc-typography--display1">Original documentation</div> <div className="mdc-typography--body"> This component encapsulates{" "} <span className="strong">mdc-toolbar</span>, you can refer to its documentation <a href="https://github.com/material-components/material-components-web/tree/master/packages/mdc-toolbar"> {" "} here </a>. </div> <div className="mdc-typography--display1">Demo </div> <div className="mdc-typography--title">Default </div> <Toolbar className="toolbar"> <Toolbar.Row> <Toolbar.Section align-start={true}> <Toolbar.Icon menu={true}>menu</Toolbar.Icon> <Toolbar.Title>My App</Toolbar.Title> </Toolbar.Section> <Toolbar.Section align-end={true}> <Toolbar.Icon>more_vert</Toolbar.Icon> </Toolbar.Section> </Toolbar.Row> </Toolbar> </div> ); } }
import template from './group.hbs'; import LayoutBehavior from '../behaviors/LayoutBehavior'; import MenuButtonView from './MenuButtonView'; const defaultOptions = ({ view }) => ({ collapsed: false, collapsible: Boolean(view) }); const classes = { CLASS_NAME: 'layout-group', COLLAPSED_CLASS: 'group-collapsed', MENU_SHOWN: 'layout-group__head_menu-shown', MAXIMIZED: 'layout-group__head_maximized' }; const menuItemsIds = { maximize: 'maximize' }; export default Marionette.View.extend({ initialize(options) { _.defaults(options, defaultOptions(options)); this.model = new Backbone.Model(options); this.listenTo(this.model, 'change:collapsed', this.__onCollapsedChange); this.update = this.update.bind(this); }, template: Handlebars.compile(template), className() { return `${classes.CLASS_NAME} ${this.options.class || ''}`; }, regions: { containerRegion: '.js-container-region', menuRegion: '.js-menu-region' }, behaviors: { LayoutBehavior: { behaviorClass: LayoutBehavior } }, ui: { toggleCollapseButtons: '.js-toggle', header: '.js-header', containerRegion: '.js-container-region', menuRegion: '.js-menu-region', restore: '.js-restore' }, events: { 'click @ui.toggleCollapseButtons': 'onClickToggleButton', 'click @ui.menuRegion': 'onMenuClick', 'click @ui.restore': '__onRestore' }, modelEvents: { 'change:isMaximized': '__onMaximizedChange' }, onRender() { const view = this.model.get('view'); if (view) { this.showChildView('containerRegion', view); } else { this.ui.containerRegion[0].setAttribute('hidden', ''); } this.__updateState(); this.__onCollapsedChange(); // TODO: toolbar? if (this.options.showMenu) { this.__createMenu(); this.showChildView('menuRegion', this.menu); } }, update() { const view = this.model.get('view'); if (view?.update) { view.update(); } this.__updateState(); }, validate() { const view = this.model.get('view'); if (view?.validate) { return view.validate(); } }, onClickToggleButton(e) { if (this.ui.toggleCollapseButtons.get(0) === e.currentTarget) { this.toggleCollapse(); } }, toggleCollapse(collapse = !this.model.get('collapsed')) { if (!this.model.get('collapsible')) { return; } this.model.set('collapsed', collapse); }, __onCollapsedChange(model = this.model, collapsed = this.model.get('collapsed')) { this.$el.toggleClass(classes.COLLAPSED_CLASS, Boolean(collapsed)); if (collapsed) { this.ui.containerRegion.slideUp(200); } else { this.ui.containerRegion.slideDown(200); } }, __onMaximizedChange(model, isMaximized) { this.ui.header.get(0).classList.toggle(classes.MAXIMIZED, isMaximized); }, __createMenu() { this.menuItemsCollection = new Backbone.Collection(this.__getMenuItems()); this.menu = Core.dropdown.factory.createMenu({ buttonView: MenuButtonView, items: this.menuItemsCollection, showDropdownAnchor: false, popoutFlow: 'right' }); this.listenTo(this.menu, 'open', () => this.ui.header.addClass(classes.MENU_SHOWN)); this.listenTo(this.menu, 'close', () => this.ui.header.removeClass(classes.MENU_SHOWN)); this.listenTo(this.menu, 'execute', this.__execute); }, __getMenuItems() { return [ { id: menuItemsIds.maximize, icon: 'window-maximize', name: Localizer.get('CORE.LAYOUT.GROUPLAYOUT.MENU.MAXIMIZE') } ]; }, __execute(id) { switch (id) { case menuItemsIds.maximize: this.__onMaximize(); break; default: break; } }, onMenuClick() { return false; }, __onRestore() { Core.services.WindowService.closeElPopup(this.modalCollectionViewId, true); }, __onMaximize() { this.modalCollectionViewId = Core.services.WindowService.showElInPopup(this.$el); this.listenTo(Core.services.WindowService, 'popup:close', this.__onPopupClosing); this.model.set('isMaximized', true); }, __onPopupClosing(closedPopupId) { if (closedPopupId === this.modalCollectionViewId) { this.stopListening(Core.services.WindowService, 'popup:close', this.__onPopupClosing); delete this.modalCollectionViewId; this.model.set('isMaximized', false); } }, });
import { lpad } from '../../utils'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { ControlLabel, FormControl, FormGroup, HelpBlock } from 'react-bootstrap'; /** * Date Field - Used to create a three field component capturing the Day Month Year. * @class */ export default class DateField extends Component { /** * @constructor * @param props */ constructor (props) { super(props); this.displayName = 'components/DateField'; this.onChangeProxy = this.onChangeProxy.bind(this); } /** * determine the aria-invalid value * @function * @returns {boolean} */ ariaInvalid () { return (this.props.validator(this.props.getModelToValidate(this.props.value)) === 'warning' || this.props.validator(this.props.getModelToValidate(this.props.value)) === 'error'); } /** * onChange Proxy, feed to the input fields. * @function * @param {string} datePart - the part of the string to search for. EG 'year', 'month', 'day' * @returns {function(this:DateField)} binds to this. */ onChangeProxy (datePart) { return function (e) { let year = (datePart === 'year') ? e.target.value : this.props.year; let month = (datePart === 'month') ? e.target.value : this.props.month; let day = (datePart === 'day') ? e.target.value : this.props.day; this.props.onChange({ target: { value: lpad(year, 4) + '-' + lpad(month, 2) + '-' + lpad(day, 2) } }); }.bind(this); } render () { return ( <FormGroup data-component-name={this.displayName} controlId={this.props.fieldId} validationState={this.props.validator(this.props.getModelToValidate(this.props.value))}> <ControlLabel aria-hidden="true">{this.props.label}</ControlLabel> <div className="container-fluid" style={{ padding: 0 }}> <div className="row"> <div className="col-xs-4"> <ControlLabel srOnly={true} htmlFor={this.props.fieldId + '_day'}>Day of the month of the birth day</ControlLabel> <FormControl type="number" value={this.props.day} placeholder='Day' onChange={this.onChangeProxy('day')} aria-invalid={this.ariaInvalid()} required="true" id={this.props.fieldId + '_day'} tabIndex="0" /> <div className="row"> <div className="col-xs-12"> <HelpBlock id={this.props.fieldId + '_help_day'} role="tooltip">Day</HelpBlock> </div> </div> </div> <div className="col-xs-4"> <ControlLabel srOnly={true} htmlFor={this.props.fieldId + '_month'}>Month of the birth day</ControlLabel> <FormControl type="number" value={this.props.month} placeholder='Month' onChange={this.onChangeProxy('month')} aria-invalid={this.ariaInvalid()} required="true" id={this.props.fieldId + '_month'} tabIndex="0" /> <div className="row"> <div className="col-xs-12"> <HelpBlock id={this.props.fieldId + '_help_month'} role="tooltip">Month</HelpBlock> </div> </div> </div> <div className="col-xs-4"> <ControlLabel srOnly={true} htmlFor={this.props.fieldId + '_year'}>Year of the birth day</ControlLabel> <FormControl type="number" value={this.props.year} placeholder='Year' onChange={this.onChangeProxy('year')} aria-invalid={this.ariaInvalid()} required="true" id={this.props.fieldId + '_year'} tabIndex="0" /> <div className="row"> <div className="col-xs-12"> <HelpBlock id={this.props.fieldId + '_help_year'} role="tooltip">Year</HelpBlock> </div> </div> </div> </div> </div> </FormGroup> ); } } /** * @type {{fieldId, validator, getModelToValidate, label, value, placeholder, onChange, help, day, month, year}} */ DateField.propTypes = { fieldId: PropTypes.string.isRequired, validator: PropTypes.func.isRequired, getModelToValidate: PropTypes.func.isRequired, label: PropTypes.string.isRequired, value: PropTypes.string.isRequired, placeholder: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, help: PropTypes.string.isRequired, day: PropTypes.number.isRequired, month: PropTypes.number.isRequired, year: PropTypes.number.isRequired };
$(document).ready(function(){ //Init functions LazyLoad(); ProgressBar(); scrollToTop(); //Lazy Load function LazyLoad() { $("img.lazy").lazyload({ effect : "fadeIn" }); } //Top progress bar function ProgressBar() { //Start loader NProgress.start(); $(window).load(function () { NProgress.done(); }); } //Scroll to Top function scrollToTop() { $(function () { $('#goTop').goTop(); }); } });
/** * Show an account */ var client = require('../../../client'); var async = require('async'); async.waterfall([ function(callback) { // Fetch accounts to get an account ID client.getAccounts({}, function(err, accounts) { if (err) { return console.log(err); } callback(null, accounts[0].id); }); }, function(accountId, callback) { // Optionally, you can manually specify an account ID here if needed // var accountId = ''; client.getAccount(accountId, function(err, account) { if (err) { return console.log(err); } console.log(account); }); } ]);
'use strict'; const BookshelfRepository = require('./bookshelfRepository'); class LoanRepository extends BookshelfRepository { constructor(model) { super(model); this.relationships = {withRelated: ['users','books']}; } getModels() { let promise = this.model.fetchAll(this.relationships); promise.catch(err => console.log(err)); return this.model.fetchAll(this.relationships); } getModelById(id) { let attributes = {}; let model = new this.model(); attributes[model.idAttribute] = +id; return this.model.forge(attributes).fetch(this.relationships); } getBooks() { return this.model.books(); } } module.exports = LoanRepository;
var searchData= [ ['transwarp_20is_20a_20header_2donly_20c_2b_2b_20library_20for_20task_20concurrency_509',['transwarp is a header-only C++ library for task concurrency',['../index.html',1,'']]] ];
import { createBackendModule } from './backendModule' import { SUCCESS_CREATE as JOURNAL_ENTRY_SUCCESS_CREATE } from './journalEntryCreatedEvents' import { BASE_PATH, objectToQueryParams } from 'modules/http' const path = 'journal-entry-proposals' const SUCCESS_FETCH_JEP = '@@' + path + '/SUCCESS_FETCH' const START_FETCH_JEP = '@@' + path + '/START_FETCH' const ERROR_FETCH_JEP = '@@' + path + '/ERROR_FETCH' export const fetchJournalEntryProposals = (params) => { return { types: [START_FETCH_JEP, SUCCESS_FETCH_JEP, ERROR_FETCH_JEP], callAPI: (headers) => fetch(BASE_PATH + path + objectToQueryParams(params), { headers }), payload: { financialFactId: params.financialFactId } } } const module = createBackendModule('inboxFinancialFacts') export const fetchInboxFinancialFacts = module.fetchActionCreator module.ACTION_HANDLERS[JOURNAL_ENTRY_SUCCESS_CREATE] = (state, action) => { const financialFactId = action.json.financialFactId return { ...state, data: state.data.filter(iff => iff.financialFact.id !== financialFactId) } } module.ACTION_HANDLERS[SUCCESS_FETCH_JEP] = (state, action) => { const inboxFinancialFacts = state.data const index = inboxFinancialFacts.findIndex(iff => iff.financialFact.id === action.financialFactId) let inboxFinancialFactToReplace = inboxFinancialFacts[index] const newIffs = [...inboxFinancialFacts.slice(0, index), { ...inboxFinancialFactToReplace, records: action.json._embedded.records }, ...inboxFinancialFacts.slice(index + 1)] return { ...state, data: newIffs } } export default module.reducer
/** * Adds bindings for the keystone routes * * ####Example: * * var app = express(); * app.configure(...); // configuration settings * app.use(...); // middleware, routes, etc. should come before keystone is initialised * keystone.routes(app); * * @param {Express()} app * @api public */ function routes(app) { this.app = app; var keystone = this; // ensure keystone nav has been initialised if (!this.nav) { this.nav = this.initNav(); } // Cache compiled view templates if we are in Production mode this.set('view cache', this.get('env') === 'production'); // Bind auth middleware (generic or custom) to /keystone* routes, allowing // access to the generic signin page if generic auth is used if (this.get('auth') === true) { if (!this.get('signout url')) { this.set('signout url', '/keystone/signout'); } if (!this.get('signin url')) { this.set('signin url', '/keystone/signin'); } if (!this.get('account_manager url')) { this.set('account_manager url', '/keystone/account_manager'); } if (!this.nativeApp || !this.get('session')) { app.all('/keystone*', this.session.persist); } app.all('/keystone/signin', require('../../routes/views/signin')); app.all('/keystone/signout', require('../../routes/views/signout')); app.all('/keystone/account_manager', require('../../routes/views/account_manager')); app.all('/keystone*', this.session.keystoneAuth); } else if ('function' === typeof this.get('auth')) { app.all('/keystone*', this.get('auth')); } var initList = function(protect) { return function(req, res, next) { req.list = keystone.list(req.params.list); if (!req.list || (protect && req.list.get('hidden'))) { req.flash('error', 'List ' + req.params.list + ' could not be found.'); return res.redirect('/keystone'); } next(); }; }; // Keystone Admin Route app.all('/keystone', require('../../routes/views/home')); // Email test routes if (this.get('email tests')) { this.bindEmailTestRoutes(app, this.get('email tests')); } // Cloudinary API for image uploading (only if Cloudinary is configured) if (keystone.get('wysiwyg cloudinary images')) { if (!keystone.get('cloudinary config')) { throw new Error('KeystoneJS Initialisaton Error:\n\nTo use wysiwyg cloudinary images, the \'cloudinary config\' setting must be configured.\n\n'); } app.post('/keystone/api/cloudinary/upload', require('../../routes/api/cloudinary').upload); } // Cloudinary API for selecting an existing image from the cloud if (keystone.get('cloudinary config')) { app.get('/keystone/api/cloudinary/get', require('../../routes/api/cloudinary').get); app.get('/keystone/api/cloudinary/autocomplete', require('../../routes/api/cloudinary').autocomplete); } // Generic Lists API app.all('/keystone/api/:list/:action', initList(), require('../../routes/api/list')); // Generic Lists Download Route app.all('/keystone/download/:list', initList(), require('../../routes/download/list')); // List and Item Details Admin Routes app.all('/keystone/:list/:page([0-9]{1,5})?', initList(true), require('../../routes/views/list')); app.all('/keystone/:list/:item', initList(true), require('../../routes/views/item')); return this; } module.exports = routes;
var seneca = require('seneca')(); seneca.use('../suncalculator'); // Capture the sunrise event seneca.add({role: 'suncalculator', event: 'sunrise'}, function (msg, respond) { console.log('got sunrise event'); respond(null, {answer: 'ok'}) }); // Capture the sunset event seneca.add({role: 'suncalculator', event: 'sunset'}, function (msg, respond) { console.log('got sunset event'); respond(null, {answer: 'ok'}) }); setInterval(function(options) { // Uses today's date for the eventcheck seneca.act({role: 'suncalculator', cmd: 'eventcheck', lat: 35.227085, long: -80.843124}, console.log); }, 500);
import { eventBus } from '../app'; export default { bind: (el, binding, vnode) => { el.addEventListener('click', () => { eventBus.$emit('app:exchange::confirm', binding.value) }); }, unbind: (el) => { el.removeEventListener('click'); } }
/*jshint node:true*/ const ModelBlueprint = require('../engine-model'); const testInfo = require('ember-cli-test-info'); const useTestFrameworkDetector = require('ember-data/blueprints/test-framework-detector'); module.exports = useTestFrameworkDetector({ description: 'Generates a model unit test.', locals: function(options) { let result = ModelBlueprint.locals.apply(this, arguments); result.friendlyDescription = testInfo.description(options.entity.name, "Unit", "Model"); return result; } });
//============================== // (c) 2014 Envisix Labs // // License: MIT // Author: Stuart Malin // stuart [at] envisixlabs [dot] com //============================== "use strict"; var Actimony = require('./Lib/Actimony.js'); var Node = require('./Lib/Node.js'); var TransportWS = require('./lib/TransportWS.js'); var actimony = new Actimony(); var node = new Node(); console.log('node2: nodeID:', node.getNodeID()); node.connectWith(TransportWS, 'ws://localhost:8080');
// D3 render template Template.d3svgStructure.rendered = function(){ Deps.autorun(function(){ graph = addLinks2structureGraph(structurePeg2graph(qmls.parse( // "w:VLp,qRLw,v;v:VLr,sRLw,u;u:VLp,rRLw" // "w:VLp,qRLw,v;v:VLr,sRL;u:VLp,rRLw" // "w:VLp,qRLw,v,u;v:VLr,sRL;u:VLp,rRLw" // "w:VLp,qRLv;v:VLr,sRLu,t;u:VLp,rRL;t:VLp,rRLl1,l2,l3;l1:VLRL;l2:VLRL;l3:VLRL" // "w:VLp,qRLvDOa,b,c;v:VLr,sRLu,t;u:VLp,rRL;t:VLp,rRLl1,l2,l3;l1:VLRL;l2:VLRL;l3:VLRL" "w:VLp,qRLvDOa,b,cMPP{a,b},Q{c};v:VLr,sRLu,t;u:VLp,rRL;t:VLp,rRLl1,l2,l3;l1:VLRL;l2:VLRL;l3:VLRL" ))) // ************** Generate the tree diagram ***************** var margin = {top: 25, right: 20, bottom: 10, left: 20}, width = 500 - margin.right - margin.left, height = 400 - margin.top - margin.bottom, edgeLenght = 80; var color = function() {return 'LightSteelBlue';}; //DarkSeaGreen Aquamarine d3.scale.category20(); var svg = d3.select("#d3svgStructure").append("svg").attr("height",height).attr("width",width); /* Build the directional arrows for the links/edges */ svg.append("svg:defs").selectAll("marker").data(["end"]) .enter() .append("svg:marker") .attr("id", String) .attr("viewBox", "0 -5 10 10") .attr("refX", 18) .attr("refY", 0) .attr("markerWidth", 6) .attr("markerHeight", 6) .attr("orient", "auto") .append("svg:path") .attr("d", "M0,-5L10,0L0,5") .style("fill", "#ccc") .style("stroke", "#ccc") // .style("opacity", "0.5") ; /* Establish the dynamic force behavor of the nodes */ var force = d3.layout.force().size([width,height]) .nodes(graph.nodes) .links(graph.links) .linkDistance([120]) .charge([-1000]) .gravity(0.3) .start(); /* Draw the edges/links between the nodes */ var edges = svg.selectAll("line").data(graph.links) .enter() .append("line") .style("stroke", "#ccc") .style("stroke-width", 2) .style("opacity", "0.7") .attr("marker-end", "url(#end)"); /* Draw the nodes themselves */ var nodes = svg.selectAll("circle").data(graph.nodes) .enter() .append("circle") .attr("r", 10) // .attr("opacity", 0.5) .style("fill", function(d,i) { return color(i); }) .call(force.drag); nodes.append("title").text(function(d) { return d.hoverContent; }); var labels = svg.selectAll("nodes").data(graph.nodes) .enter() .append("text") .attr("fill", "SteelBlue") /*PineGreen*/ .attr("font-family", "sans-serif") .attr("font-size", "17px") .attr('x', 7).attr('y', 3) // .attr("x", function(d) { return d.x + 10; }) .style("text-anchor", "start") // .text(function(d) { return d.valuation; }); .text(function(d) { return d.name; }); /* Run the Force effect */ force.on("tick", function() { edges.attr("x1", function(d) { return d.source.x; }) .attr("y1", function(d) { return d.source.y; }) .attr("x2", function(d) { return d.target.x; }) .attr("y2", function(d) { return d.target.y; }); nodes.attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); // texts.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); labels.attr("transform", function(d) { return "translate(" + (d.x + 7) + "," + (d.y + 5) + ")"; }); }); // End tick func }); };
import Page from '../classes/Page'; import request from 'request'; function getCompanies() { // not yet associated with user return { method: 'GET', url: `${process.env.CLIENTS_SERVICE_URL}/companies`, headers: { 'content-type': 'application/json', }, body: JSON.stringify(), }; } function getFlarumUser({ forumId, forumToken }) { return { method: 'GET', url: `${process.env.FLARUM_URL}/api/users/${forumId}`, headers: { 'content-type': 'application/json', Authorization: `Token ${forumToken}`, }, body: JSON.stringify({ forumId }), }; } function getFlarumDiscussions(forumToken) { return { method: 'GET', url: `${process.env.FLARUM_URL}/api/discussions`, headers: { 'content-type': 'application/json', Authorization: `Token ${forumToken}`, }, }; } export default (req, res) => { if (!req.session) { res.redirect('/login'); return; } request(getCompanies(), (error, response, body) => { const companies = JSON.parse(body); const user = req.session; const { forumId, forumToken } = req.session; request( getFlarumUser({ forumId, forumToken }), (userError, userResponse, userBody) => { const flarumUser = JSON.parse(userBody); request( getFlarumDiscussions(forumToken), (discussionError, discussionResponce, discussionBody) => { const flarumDiscussions = JSON.parse(discussionBody); const templatePath = '/templates/account.twig'; const page = new Page({ templatePath, templateVariables: { companies, user, flarumUser, flarumDiscussions, flarumURL: process.env.FLARUM_URL, }, }); res.send(page.render()); }); }); }); };
var JS = {}; /* * JS: Core */ JS.core = [ "node_modules/tiny.js/dist/tiny.js", "src/shared/scripts/core.js", "src/shared/scripts/events.js", "src/shared/scripts/factory.js", "src/product-component/scripts/init.js" ]; /* * JS: Abilities */ JS.abilities = [ "src/shared/scripts/Content.js", "src/shared/scripts/Collapsible.js", "src/shared/scripts/Viewport.js", "src/shared/scripts/Positioner.js" ]; /* * JS: Components */ JS.components = [ "src/shared/scripts/Component.js", "src/shared/scripts/Expandable.js", "src/shared/scripts/Menu.js", "src/shared/scripts/Popover.js", "src/shared/scripts/Layer.js", // "src/shared/scripts/Tooltip.js", // "src/shared/scripts/Bubble.js", "src/shared/scripts/Modal.js", "src/shared/scripts/Transition.js", "src/shared/scripts/Dropdown.js", "src/shared/scripts/Form.js", "src/shared/scripts/Condition.js", "src/shared/scripts/Validation.js", "src/shared/scripts/Countdown.js", "src/shared/scripts/Carousel.js", "src/shared/scripts/Calendar.js", "src/product-component/scripts/Product.js", "src/shared/scripts/Autocomplete.js" ]; exports.JS = JS;
import CardParser from './utils/card-parser'; import CardInputParser from './mixins/card-input-parser'; export function isDigit(event) { return String.fromCharCode(event.charCode).match(/\d/); } export { CardParser, CardInputParser };
exports.config = { allScriptsTimeout: 11000, specs: [ 'e2e/*.js' ], capabilities: { 'browserName': 'chrome' }, baseUrl: 'http://127.0.0.1:8000/app/', framework: 'jasmine', jasmineNodeOpts: { defaultTimeoutInterval: 30000 } };
/************************************************************* * * MathJax/localization/lt/FontWarnings.js * * Copyright (c) 2009-2016 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.Localization.addTranslation("lt","FontWarnings",{ version: "2.7.0-beta", isLoaded: true, strings: { webFont: "Matematikos \u017Eenklams rodyti \u201EMathJax\u201C \u0161iame tinklalapyje vartoja tinkle saugomus \u0161riftus, kuri\u0173 \u012Fk\u0117limas reikalauja laiko. \u017Denkl\u0173 rinkim\u0105 galima greitinti, matematikos \u0161riftus \u012Fdiegus vietiniame sistemos \u0161rift\u0173 aplanke.", imageFonts: "\u201EMathJax\u201C vartoja paveikslinius, o ne vietinius arba tinkle saugomus \u0161riftus. Matematikos \u017Eenklai vaizduojami l\u0117\u010Diau, o spausdinant netenkama rai\u0161kos.", noFonts: "Matematikos \u017Eenklams rodyti \u201EMathJax\u201C nepavyksta rasti \u0161rifto arba paveikslini\u0173 \u0161rift\u0173, tod\u0117l vartojami bendrieji unikodo ra\u0161menys, tikintis, kad nar\u0161ykl\u0117 juos rodys taisyklingai. Kai kurie \u017Eenklai gali b\u016Bti rodomi i\u0161darkyti arba visai nerodomi.", webFonts: "Dauguma dabartini\u0173 nar\u0161ykli\u0173 leid\u017Eia gauti \u0161riftus i\u0161 tinklo. Tik\u0117tina, kad atnaujinus nar\u0161ykl\u0117s laid\u0105 arba esam\u0105 nar\u0161ykl\u0119 pakeitus kita, tinklalapyje ger\u0117t\u0173 matematikos \u017Eenkl\u0173 vaizdavimas.", fonts: "\u201EMathJax\u201C gali vartoti [STIX fonts](%1) arba [MathJax TeX fonts](%2). \u012Ediegus vien\u0105 i\u0161 min\u0117t\u0173 alternatyv\u0173, ger\u0117s \u201EMathJax\u201C veikimas.", STIXPage: "Tinklalapyje numatyti [STIX fonts](%1). \u012Ediegus min\u0117tus \u0161riftus, ger\u0117s \u201EMathJax\u201C veikimas.", TeXPage: "Tinklalapyje numatyti [MathJax TeX fonts](%1). \u012Ediegus min\u0117tus \u0161riftus, ger\u0117s \u201EMathJax\u201C veikimas." } }); MathJax.Ajax.loadComplete("[MathJax]/localization/lt/FontWarnings.js");
'use strict'; angular.module('cbt') .directive('flagView', function(){ return { restrict: 'E', template: '{{title}}'+ '<a class="led" ng-repeat="led in values track by $index" ng-class="{\'active\':values[$index]}" title="{{info[title.toLowerCase()][$index]}}"></a>', link: function (scope, elem, attrs) { scope.values = Array(8); scope.$watch('value',function(newValue,oldValue) { for(var i=0; i<8; i++) scope.values[i] = !!(newValue & (0x01 << 7-i)); }); }, controller: function($scope){ // Description Library $scope.info = { error:[ 'RX1OVR: Receive Buffer 1 Overflow Flag bit', 'TXBO: Bus-Off Error Flag bit', 'TXBO: Bus-Off Error Flag bit', 'TXEP: Transmit Error-Passive Flag bit', 'RXEP: Receive Error-Passive Flag bit', 'TXWAR: Transmit Error Warning Flag bit', 'RXWAR: Receive Error Warning Flag bit', 'EWARN: Error Warning Flag bit', ], // Datasheet pg 58 control:[ '', '', '', '', '', '', '', '' ], status:[ 'CANINTF.RX0IF', 'CANINTFL.RX1IF', 'TXB0CNTRL.TXREQ', 'CANINTF.TX0IF', 'TXB1CNTRL.TXREQ', 'CANINTF.TX1IF', 'TXB2CNTRL.TXREQ', 'CANINTF.TX2IF' ] } }, scope: { title: "@", value: "@" } } });
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /*! * Next JS * Copyright (c)2011 Xenophy.CO.,LTD All rights Reserved. * http://www.xenophy.com */ // {{{ NX.smtp.Smtp NX.define('NX.smtp.Smtp', { }); // }}} /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */
var http = require('http'); var express = require('express'); var htmlToJson = require('../lib/htmlToJson'); describe('htmlToJson.request', function () { it('should take request library options and a filter, then return parsed results based on the response body', function (done) { var app = express(); var server = http.createServer(app); var port = 19999; app.get('/', function (req, resp) { resp.send('<div id="val">' + req.query.val + '</div>'); }); server.listen(port, function () { var val = 999; htmlToJson.request({ uri: 'http://localhost:' + port, qs: { val: val } }, { 'val': function ($doc) { return +$doc.find('#val').text(); } }, function (err, result) { result.val.should.equal(val); server.close(done); }); }); }); });
"use strict"; var reiny = require('reiny/runtime'); var __runtime = reiny.runtime; var __extend = reiny.xtend; module.exports = function(__props) { if(__props == null) __props = {}; return __runtime(function($){ $('span', {className:['hoge']}, ''aaa'') }); };
/*! * ------------------------------ * jQuery.loadHtmlComponents.js v0.1.0 * http://anasnakawa.github.com/jquery.loadHtmlComponents * license: MIT license (http://opensource.org/licenses/MIT) * ------------------------------ */ // ------------------------------ // table of content // ------------------------------ // a header title // - sub title // a method // ------------------------------ // a header title // -------------- // sub title // a method // describe your method // // * **param:** {type} paramName what to do with this parameter // // e.g: if you want to provide an example, that would be nice // ------------------------------ (function ($) { 'use strict'; var defaults = { attr: 'data-component-url' , extension: 'html' , componentsFolder: '' } , loadHtml = function(options) { options = $.extend(defaults, options); // component url attribute var attr = options.attr // load status attribute , state = attr + '-state' // load done value for status attribute , done = 'ready' // load pending value for status attribute , pending = 'pending' // cache all components , selector = '[' + attr + ']:not([' + state + '])'; // for all elements with component url not in ready state return this.find( selector ).each(function () { // debugger; var $self = $(this) // fetch url , componentUrl = $self.attr(attr) // ability to add component name without extension (.html) , url = ( options.componentsFolder + '/' ) + ( componentUrl.match('.' + options.extension + '$') ? componentUrl : componentUrl + '.' + options.extension ); $self.attr(state, pending); // load content and append $self.load(url, function () { // set state to ready $self.attr(state, done) if( $self.attr(options.attr + '-skip') !== 'true' ) { return $self.loadHtml(options); } }); }); }; $.fn.loadHtml = loadHtml; $.fn.loadHtml.defaults = defaults; })(jQuery);
;(function(window, _, $, undefined){ var Controller = new Class; //Controller.extend({. //Routes: {},. //Hash: window.location.hash,. // /**. // * route(); initiate routing based on what the url is right now. // * route('/path'); take the user to the given route. // */. //Route: function(){. //For(i in this.routes){. // }. // },. //Add_route: function(route, destination){. //This.routes[route] = destination;. // },. // //eg: "users/?id". // //eg: "users/?/edit". //Parse_route: function(route){. //Var segments = route.split('/'), output = [];. //For(var i=0, l=segments.length; i < l; i++){. //Var segment = {};. //If(/^[a-zA-Z_-]+$/.test(segments[i])){. //Segment.type = 'section';. //Segment.name = segments[i];. // }. //Else if(/^\?[a-zA-Z_-]+$/.test(segments[i])){. //Segment.type = 'parameter';. //Segment.name = segments[i].substr(1);. // }. //Else if(/^\?$/.test(segments[i])){. //Segment.type = 'parameter';. //Segment.name = undefined;. // }. //Output.push(segment);. // }. //Return output;. // }. // });. Controller.extend({ subclassed: function(child){ if(child.fn.elements) child.fn.elements = $.extend({}, this.fn.elements, child.fn.elements); if(child.fn.events) child.fn.events = $.extend({}, this.fn.events, child.fn.events); } }); Controller.include({ view: null, namespace: null, eventMatcher: /^(\w+(?:(?: or |\/)\w+)*)\s*(?:on\s+)?(.*)$/, eventSplitter: / or |\//, elements: {}, events: {}, //Default action for activate. activate: function(){ this.view.show(); }, //Default action for deactivate. deactivate: function(){ this.view.hide(); }, //Initiating controllers. init: function(){ if( ! $.domReady) throw('Can not create Controller instances before DOM is ready.'); //Handle arguments. var init, el, namespace, map, args = $.makeArray(arguments); if(args.length == 1){ if( $.isPlainObject(args[0]) ){ map = args[0]; }else if(scalar(args[0])){ el = args[0]; } } else if(args.length == 2){ if( $.isPlainObject(args[1]) ){ el = args[0]; map = args[1]; }else{ el = args[0]; namespace = args[1]; } } else if(args.length == 3){ el = args[0]; namespace = args[1]; map = args[2]; } el = el || (map && map.el) || this.view || false; namespace = namespace || (map && map.namespace) || this.namespace || false; map = map || {}; if(el === false || namespace === false){ throw "Invalid arguments. Element and namespace required."; } //Eof handle arguments. this.view = $(el); this.namespace = namespace; if(map){ for(var i in map){ switch(i){ case 'elements': case 'events': $.extend(this[i], map[i]); break; case 'init': init = map[i]; break; default: //This[i] = map[i];. var obj = {}; obj[i] = map[i]; Class.inherit(this, obj); break; } } map.el && delete map.el; } this.refreshElements(); this.bindEvents(); $.isFunction(init) && init.call(this); }, //Refresh elements. refreshElements: function(){ for(var key in this.elements) this[key] = $(this.elements[key], this.view); }, //Bind events (to a new namespace). bindEvents: function(namespace){ this.view.contents().off('.'+this.namespace); if(namespace) this.namespace = namespace; if(!this.namespace) throw "Namespace required."; for(var key in this.events){ var func, method = this.events[key]; if($.isFunction(method)){ func = this.proxy(method); } else if($.isArray(method)){ method = method.copy(); var methodName = method.shift(); var methodArgs = method; func = this.proxy(function(){ var func = this.proxy(this[methodName]); if( ! $.isFunction(func) ) throw "Function "+methodName+" is not a function."; func.apply(this, methodArgs); }); } else{ func = this.proxy(this[method]); } if( ! $.isFunction(func) ) throw "Function "+method+" is not a function."; var events = key.split(' and '); for(var i = 0; i < events.length; i++){ var match = events[i].match(this.eventMatcher), event = match[1], selector = this.elements[match[2]] || match[2]; event = $.map(event.split(' or '), this.proxy(function(val){ return val + '.' + this.namespace; })).join(' '); if(selector){ this.view.on(event, selector, func); }else{ this.view.on(event, func); } } } return this; }//,. // //bind routes to methods. //BindRoutes: function(){. //For(i in this.routes){. //Controller.addRoute(i, this.routes[i]);. // }. // }. }); exports.Controller = Controller; })(window, _, (jQuery || Zepto || $ || ($={})));
export { default } from 'ember-theater/ember-theater/director/directions/random';
/* @flow */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { toggleCustomInlineStyle, getSelectionCustomInlineStyle, } from 'draftjs-utils'; import LayoutComponent from './Component'; export default class FontSize extends Component { static propTypes = { onChange: PropTypes.func.isRequired, editorState: PropTypes.object, modalHandler: PropTypes.object, config: PropTypes.object, translations: PropTypes.object, }; state: Object = { expanded: undefined, currentFontSize: undefined, }; componentWillMount(): void { const { editorState, modalHandler } = this.props; if (editorState) { this.setState({ currentFontSize: getSelectionCustomInlineStyle(editorState, ['FONTSIZE']).FONTSIZE, }); } modalHandler.registerCallBack(this.expandCollapse); } componentWillReceiveProps(properties: Object): void { if (properties.editorState && this.props.editorState !== properties.editorState) { this.setState({ currentFontSize: getSelectionCustomInlineStyle(properties.editorState, ['FONTSIZE']).FONTSIZE, }); } } componentWillUnmount(): void { const { modalHandler } = this.props; modalHandler.deregisterCallBack(this.expandCollapse); } onExpandEvent: Function = (): void => { this.signalExpanded = !this.state.expanded; }; expandCollapse: Function = (): void => { this.setState({ expanded: this.signalExpanded, }); this.signalExpanded = false; } doExpand: Function = (): void => { this.setState({ expanded: true, }); }; doCollapse: Function = (): void => { this.setState({ expanded: false, }); }; toggleFontSize: Function = (fontSize: number) => { const { editorState, onChange } = this.props; const newState = toggleCustomInlineStyle( editorState, 'fontSize', fontSize, ); if (newState) { onChange(newState); } }; render(): Object { const { config, translations } = this.props; const { expanded, currentFontSize } = this.state; const FontSizeComponent = config.component || LayoutComponent; const fontSize = currentFontSize && Number(currentFontSize.substring(9)); return ( <FontSizeComponent config={config} translations={translations} currentState={{ fontSize }} onChange={this.toggleFontSize} expanded={expanded} onExpandEvent={this.onExpandEvent} doExpand={this.doExpand} doCollapse={this.doCollapse} /> ); } }
import important from "../../plugins/important/index"; describe("Important plugin", () => { it("should add !important to every number and string", () => { const style = { color: "blue", fontSize: 15 }; expect(important()(style)).toEqual({ color: "blue!important", fontSize: "15!important" }); }); it("should add !important to every value in an array", () => { const style = { color: "blue", fontSize: 15, display: ["-webkit-flex", "flex"] }; expect(important()(style)).toEqual({ color: "blue!important", fontSize: "15!important", display: ["-webkit-flex!important", "flex!important"] }); }); it("should add !important to nested objects", () => { const style = { color: "blue", fontSize: 15, ":hover": {color: "red"} }; expect(important()(style)).toEqual({ color: "blue!important", fontSize: "15!important", ":hover": {color: "red!important"} }); }); });
var fs = null; function showWarning(resolution, APISupport) { // set up text according to actual issue if(resolution && APISupport) { $('section#warning').html('\ <h1>Oops</h1>\ <p>In order to take advantage of framing app, you need to have a resolution of at least 1280x768px</p>\ <p>You also have to use a browser supporting the HTML5 FileSystem & FileWriter API.</p>\ <p>In plain english: Google Chrome (at least version 13.0) </p>'); } else if(resolution) { $('section#warning').html('\ <h1>Oops</h1>\ <p>In order to take advantage of framing app, you need to have a resolution of at least 1280x768px</p>'); } else if (APISupport) { $('section#warning').html('\ <h1>Oops</h1>\ <p>In order to take advantage of framing app, you need to use a browser supporting the HTML5 FileSystem & FileWriter API.</p>\ <p>In plain english: Google Chrome (at least version 13.0) </p>'); } // display error message if there's an issue if(resolution || APISupport) { $('section#warning').show(); } } function setupEnvironment() { // check resolution if(screen.width<1280 || screen.height < 768) { showWarning(true, false); } // setup file system try { window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder; window.requestFileSystem(window.TEMPORARY, 5*1024*1024 /*5MB*/, // callback if the new filesystem is correctly initiated function(newFS) { fs = newFS; setupPictureUpload(); // locate in settings.js because of asynchronous shit setupRestoreState(); }, // could not initiate the filesystem; no point in going further function(e) { showWarning(false, true); errorHandler(e);}); } catch(err) { showWarning(false, true); } window.onresize = function() { resizeCanvas(); resizeSettings(); refresh(); } } function resizeCanvas() { canvas.width = document.width; canvas.height = document.height; }
/** * @module opcua.address_space * @class AddressSpace */ import assert from "better-assert"; import _ from "underscore"; import NodeClass from "lib/datamodel/NodeClass"; import Argument from "lib/datamodel/argument-list/Argument"; import DataValue from "lib/datamodel/DataValue"; import { Variant } from "lib/datamodel/variant"; import { DataType } from "lib/datamodel/variant"; import { VariantArrayType } from "lib/datamodel/variant"; import { StatusCodes } from "lib/datamodel/opcua_status_code"; import { BrowseDirection } from "lib/services/browse_service"; import UAVariable from "lib/address_space/UAVariable"; import UATwoStateVariable from './UATwoStateVariable'; import util from "util"; function _install_TwoStateVariable_machinery(node,options) { assert(node.dataTypeObj.browseName.toString() === "LocalizedText"); assert(node.minimumSamplingInterval === 0); assert(node.typeDefinitionObj.browseName.toString() === "TwoStateVariableType"); assert(node.dataTypeObj.browseName.toString() === "LocalizedText"); assert(node.hasOwnProperty("valueRank") && (node.valueRank === -1 || node.valueRank === 0)); assert(node.hasOwnProperty("id")); options = options || {}; // promote node into a UATwoStateVariable Object.setPrototypeOf(node, UATwoStateVariable.prototype); node.initialize(options); } function install(AddressSpace) { assert(_.isUndefined(AddressSpace._install_TwoStateVariable_machinery)); AddressSpace._install_TwoStateVariable_machinery = _install_TwoStateVariable_machinery; /** * * @method addTwoStateVariable * * @param options * @param options.browseName {String} * @param [options.description {String}] * @param [options.modellingRule {String}] * @param [options.minimumSamplingInterval {Number} =0] * @param options.componentOf {Node|NodeId} * @param options.propertyOf {Node|NodeId} * @param options.trueState {String} * @param options.falseState {String} * @param [options.isTrueSubStateOf {NodeId}] * @param [options.isFalseSubStateOf {NodeId}] * @param [options.modellingRule] * @return {UATwoStateVariable} * * Optionals can be EffectiveDisplayName, TransitionTime, EffectiveTransitionTime */ AddressSpace.prototype.addTwoStateVariable = function (options) { assert(options.browseName," a browseName is required"); const addressSpace = this; const twoStateVariableType = addressSpace.findVariableType("TwoStateVariableType"); options.optionals = options.optionals || []; if (options.trueState) { options.optionals.push("TrueState"); } if (options.falseState) { options.optionals.push("FalseState"); } // we want event based change... options.minimumSamplingInterval = 0; const node = twoStateVariableType.instantiate({ browseName: options.browseName, nodeId: options.nodeId, description: options.description, organizedBy: options.organizedBy, componentOf: options.componentOf, modellingRule: options.modellingRule, minimumSamplingInterval: options.minimumSamplingInterval, optionals: options.optionals }); _install_TwoStateVariable_machinery(node,options); return node; }; } export default install;
/** * ParticlePack2 Shotgunflashyellow Effect. * @method Shotgunflashyellow * @param state {Kiwi.State} Current state * @param x {Number} X position * @param y {Number} Y position * @return Kiwi.Group * @public * @static */ Kiwi.Plugins.ParticlePack2.Shotgunflashyellow = function( state, x, y ) { this.config = { "numParts": 6, "posOffsetX": 0, "posOffsetY": 0, "posRadius": 5, "posRadialStart": 0, "posRadialEnd": 6.283185307179586, "posWidth": 200, "posHeight": 200, "posConstrainRect": true, "posAngle": 0, "posLength": 200, "posRandomLine": true, "posConstrainRadial": true, "posRandomRadial": true, "posShape": "point", "maxVel": 100, "minVel": 70, "velConstrainRect": true, "velConstrainRadial": false, "velRandomRadial": false, "velShape": "point", "velOffsetX": 400, "velOffsetY": 0, "velAngMin": 0, "velAngMax": 0, "velRadius": 144, "velRadialStart": 0, "velRadialEnd": 6.283185307179586, "velWidth": 200, "velHeight": 200, "velAngle": 0, "velLength": 20, "velRandomLine": true, "minStartTime": 0, "maxStartTime": 0, "minLifespan": 0.2, "maxLifespan": 0.4, "gravityX": 0, "gravityY": 0, "startSize": 1, "endSize": 200, "loop": false, "colEnvKeyframes": [ 0.2, 0.3 ], "alpha": 1, "colEnv0": [ 0.9921568627450981, 0.9764705882352941, 0.8313725490196079 ], "colEnv1": [ 0.9921568627450981, 0.9176470588235294, 0.5176470588235295 ], "colEnv2": [ 0.9921568627450981, 0.8588235294117647, 0.2196078431372549 ], "colEnv3": [ 0.996078431372549, 0.8235294117647058, 0.027450980392156862 ], "alphaGradient": [ 1, 1, 0, 0 ], "alphaStops": [ 0.3, 0.5 ], "additive": true, "cells": [ 4, 16, 17 ], "textureID": "_128x128" }; return new Kiwi.GameObjects.StatelessParticles( state, state.textures.particlePack2SpriteSheet, x, y, this.config ); };
$(document).ready(main); function parseDay() { var inputDay = parseInt($("#day").val()); if (inputDay > workout.days || inputDay < 1 || isNaN(inputDay)) { alert("Oops! I don't understand that. Please enter a day number between 1 and 28, inclusive."); $("#day").val(""); } else { showWorkout(inputDay); } } function parseExercise (text, day) { return text.replace(/{\d+, \d+}\w?/g, parseRange(day)); } var parseRange = (day) => (range) => { var totalDays = workout.days; var progress = (day - 1) / (totalDays - 1); let start = parseInt(range.match(/\d+/g)[0]); let end = parseInt(range.match(/\d+/g)[1]); let flags = range.match(/\w*$/g)[0]; if (flags === "i") { return (start + (end - start) * progress).toFixed(0); } else { return (start + (end - start) * progress).toPrecision(2); } }; function showWorkout (day) { $("#workout").empty(); $("#heading").empty(); $("#heading").append("<h1>" + workout.title + ": Day " + day + "</h1>"); for (let section of workout.workout) { $("#workout").append("<h3>" + section.name + "</h3><h4>" + section.fitnessType + "</h4><ol>"); var shuffledList = _.shuffle(section.exercises); for (var i = 0; i < section.count; i++) { $("#workout").append("<li>" + parseExercise(shuffledList[i], day) + "</li>"); } $("#workout").append("</ol>"); } } function main () { /*Add workout info to the main div*/ showWorkout(1); /*Make the input work*/ $("#day").bind("enterKey", parseDay); $("#day").keyup(function(e){ if (e.keyCode == 13) { $(this).trigger("enterKey"); } }); }
$(document).ready(function() { // Toggle Extra Informations for single Topic by Click + $('.toggle-sibling').click(function() { var infoBox = $(this).parent().next('.details-wrapper'); // console.log(infoBox); if (infoBox.hasClass('active')) { // if info box is open, close it and remove status-marker-class infoBox.slideUp('fast').removeClass('active'); } else { // if closed, open amd add status-marker-class infoBox.slideDown('fast').addClass('active'); }; return false; }); // Toggle Info Columns // ========================================================================= $('a.info-trigger').click(function() { // open box on click var objID = this.id; // Get ID of clicked element $('.active-section').removeClass('active-section'); $(this).addClass('active-section'); if (objID == 'info1-trigger') { // open info-box 1 openInfoBox('#col-1'); } else if (objID == 'info2-trigger') { // open info-box 2 openInfoBox('#col-2'); }; return false; }); // Close all open info-boxes and open the requested info-box function openInfoBox (id) { // close all <section> with class "active" $('section.active').slideUp('fast').removeClass('active'); // open the requested info-box and add class "active" $(id).slideDown('fast').addClass('active'); } // Detect Browser Language console.log(window.navigator.language); });
#!/usr/bin/env node var minimist = require('minimist'); var toureiro = require('../lib/toureiro'); var argv = minimist(process.argv.slice(2)); if (argv.h || argv.help) { console.log('Usage: toureiro [port]'); console.log('[port] Port for toureiro to listen to'); console.log('Options:'); console.log('--rh Redis host, default to 127.0.0.1'); console.log('--rp Redis port, default to 6379'); console.log('--rdb Redis database number, default to 0'); console.log('--pass Redis password, default to null'); process.exit(0); } var port = 3000; if (argv._.length > 0 && !isNaN(parseInt(argv._[0]))) { port = parseInt(argv._[0]); } var redisHost = '127.0.0.1'; if (argv.rh) { redisHost = argv.rh; } var redisPort = 6379; if (argv.rp && !isNaN(parseInt(argv.rp))) { redisPort = argv.rp; } var redisDB = 0; if (argv.rdb && !isNaN(parseInt(argv.rdb))) { redisDB = argv.rdb; } var redisPass = null; if (argv.pass) { redisPass = argv.pass; } var app = toureiro({ redis: { host: redisHost, port: redisPort, auth_pass: redisPass, db: redisDB } }); var server = app.listen(port, function () { console.log('Toureiro is now listening at port', port, '...'); });
var fs = require('fs'); var filename = 'data.txt'; fs.unlinkSync(filename); console.log('File Deleted Successfully');
'use strict';var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var dom_adapter_1 = require('angular2/src/core/dom/dom_adapter'); var di_1 = require('angular2/di'); var location_strategy_1 = require('./location_strategy'); var PathLocationStrategy = (function (_super) { __extends(PathLocationStrategy, _super); function PathLocationStrategy() { _super.call(this); this._location = dom_adapter_1.DOM.getLocation(); this._history = dom_adapter_1.DOM.getHistory(); this._baseHref = dom_adapter_1.DOM.getBaseHref(); } PathLocationStrategy.prototype.onPopState = function (fn) { dom_adapter_1.DOM.getGlobalEventTarget('window').addEventListener('popstate', fn, false); }; PathLocationStrategy.prototype.getBaseHref = function () { return this._baseHref; }; PathLocationStrategy.prototype.path = function () { return this._location.pathname; }; PathLocationStrategy.prototype.pushState = function (state, title, url) { this._history.pushState(state, title, url); }; PathLocationStrategy.prototype.forward = function () { this._history.forward(); }; PathLocationStrategy.prototype.back = function () { this._history.back(); }; PathLocationStrategy = __decorate([ di_1.Injectable(), __metadata('design:paramtypes', []) ], PathLocationStrategy); return PathLocationStrategy; })(location_strategy_1.LocationStrategy); exports.PathLocationStrategy = PathLocationStrategy; //# sourceMappingURL=path_location_strategy.js.map
import fetch, { Response } from 'node-fetch'; export default { load() {}, fetch, Response, set Promise(implementation) { if (fetch.Promise === global.Promise) { fetch.Promise = implementation; } } };
Package.describe({ name: 'ndemoreau:azimulti-views-bootstrap', summary: 'Azimuth Multilanguage CMS frontend templates (using Bootstrap 3.x)', version: '0.4.3', git: 'https://github.com/ndemoreau/azimulti-views-bootstrap' }); Package.on_use(function (api) { api.use(['less@1.0.11', 'templating@1.0.9', 'mizzao:bootstrap-3@3.3.0'], 'client'); api.use('ndemoreau:azimulti-core@0.4.3', {unordered: true}); api.add_files('css/style.less', 'client'); api.add_files('blocks/block/block.html', 'client'); api.add_files('blocks/block_with_title/block_with_title.html', 'client'); api.add_files('blocks/block_multi/block_multi.html', 'client'); api.add_files('blocks/block_multi_with_title/block_multi_with_title.html', 'client'); api.add_files('pages/home_page/home_page.html', 'client'); api.add_files('pages/page_default/page_default.html', 'client'); api.add_files('pages/sidebar_left/sidebar_left.html', 'client'); api.add_files('pages/sidebar_left_fixed/sidebar_left_fixed.html', 'client'); api.add_files('pages/sidebar_right/sidebar_right.html', 'client'); api.add_files('views/404.html', 'client'); api.add_files('views/block_display.html', 'client'); api.add_files('views/footer.html', 'client'); api.add_files('views/header.html', 'client'); api.add_files('views/layout.html', 'client'); api.add_files('views/not_authorized.html', 'client'); api.add_files('views/accounts/account_buttons.html', 'client'); api.add_files('views/accounts/error.html', 'client'); api.add_files('views/accounts/forgot_password.html', 'client'); api.add_files('views/accounts/login.html', 'client'); api.add_files('views/accounts/sign_up.html', 'client'); api.add_files('views/accounts/social.html', 'client'); api.add_files('lib/utils.js', 'client'); });
/* * @flow */ import React, { Component } from 'react'; import { Scrollbars } from 'react-custom-scrollbars'; // Blocks import Search from '../Search'; import './Chat.css'; class Chat extends Component { constructor(props) { super(props) this.state = { } this.onCreateComment = this.onCreateComment.bind(this); } componentDidMount() { // init scroll and scroll to bottom this._scrolltoBottom(); } _scrolltoBottom() { const { scrollbars } = this.refs; scrollbars.scrollToBottom(); } onCreateComment(value, file, imageBase64) { this.props.onSend(value, file, imageBase64); } render() { return ( <div className="chat"> <div className="chat__list"> <Scrollbars ref="scrollbars" > </Scrollbars> </div> <div className="chat__input"> <Search showTextarea placeholder="Trao đổi công việc" callback={this.onCreateComment} /> </div> </div> ); } } export default Chat;
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.4.4.17-1-5 description: Array.prototype.some applied to number primitive includes: [runTestCase.js] ---*/ function testcase() { function callbackfn(val, idx, obj) { return obj instanceof Number; } try { Number.prototype[1] = true; Number.prototype.length = 2; return Array.prototype.some.call(5, callbackfn); } finally { delete Number.prototype[1]; delete Number.prototype.length; } } runTestCase(testcase);
module.exports = (opt, columns, moduleCallback) => { const mysql = require('mysql') const readline = require('readline') const mySqlCreds = require(opt.cfg.dirs.creds + opt.destination) let db = mysql.createConnection(mySqlCreds) const async = require('async') let table = opt.source + '.' + opt.table.replace(/\./g, '_') let opfile = opt.opfile let log = opt.log let sqlTable = () => { let cols = [] let ndxs = [] columns.forEach((c) => { cols.push(' ' + c.name + ' ' + c.type + ' NULL') if (c.index) ndxs.push(' INDEX `' + c.name + '` (`' + c.name + '`) ') }) let sql = 'CREATE TABLE ' + table + ' ( ' + cols.join(', ') if (ndxs.length) sql += ', ' + ndxs.join(',') sql += ' )' return sql } async.waterfall([ //create database if not existing (cb) => { db.query('CREATE DATABASE IF NOT EXISTS ' + opt.source, (err) => { if (err) return cb(err) cb(null) }) }, //drop existing table (cb) => { if (opt.update || opt.truncate) return cb(null) db.query('DROP TABLE IF EXISTS ' + table, (err) => { if (err) return cb(err) cb(null) }) }, //create new table (cb) => { if (opt.update || opt.truncate) return cb(null) //don't drop table if update option let sql = sqlTable() db.query(sql, (err) => { if (err) return cb(err) cb(null) }) }, //truncate table if specified (cb) => { if (!opt.truncate) return cb(null) db.query('TRUNCATE TABLE ' + table, (e) => { //if error but it isn't table doesn't exist, throw error at cb if (e instanceof Error && e.toString().indexOf('doesn\'t exist') === -1) return cb('TRUNCATE TABLE error: ' + e) //if error but it's that the table doesn't exist, let's create it if (e instanceof Error && e.toString().indexOf('doesn\'t exist') !== -1) { db.query(sqlTable(), (e) => { if (e) return cb(e) cb(null) }) } else { //otherwise, truncated smoothly cb(null) } }) }, //sql_mode to blank (cb) => { db.query('SET sql_mode = \'\'', (err) => { if (err) return cb('SET sql_mode error: ' + err) cb(null) }) }, //load data into table (cb) => { let sql = 'INSERT INTO ' + table + ' ' let cs = [] let first = true columns.forEach((c) => { cs.push(c.name) }) sql += ' ( ' + cs.join(', ') + ' ) VALUES ' let lineReader = readline.createInterface({ input: opfile.readStream }) lineReader.on('error', (err) => { return cb(err) }) let insertLines = [] lineReader.on('line', (line) => { if (first) { first = false } else { insertLines.push(' ( "' + line.split('\t').join('", "') + '")') } }) lineReader.on('close', () => { sql += insertLines.join(',') cb(null, sql) }) }, (sql, cb) => { db.query(sql, (err) => { if (err) return cb('Insert data error: ' + err) cb(null) }) }, //check table rows (cb) => { db.query('SELECT count(*) as rows FROM ' + table, (err, result) => { if (err) return cb('SELECT COUNT(*) err: ' + err) cb(null, result[0].rows) }) }, (rows, cb) => { //check columns let table_name = table.split('.')[1] let sql = 'SELECT COLUMN_NAME as col FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=\'' + opt.source + '\' AND TABLE_NAME=\'' + table_name + '\'' db.query(sql, (err, result) => { if (err) return cb('SELECT COLUMN_NAME err: ' + err) let cols = [] result.forEach((row) => { cols.push(row.col) }) cb(null, rows, cols) }) } ], (err, rows, columns) => { db.end((err) => { if (err) moduleCallback(err) }) if (err) { log.error(err) return moduleCallback(err) } moduleCallback(null, rows, columns) }) }
export function add(a, b) { return a + b }
const functions = require('firebase-functions'); const Gdax = require('gdax'); const cors = require('cors')({origin: true}); // private endpoints exports.getAccounts = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.AuthenticatedClient(request.query.apikey, request.query.secret, request.query.passphrase, request.query.apiURI) console.log(client) client.getAccounts(function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) }) // public endpoints exports.getProducts = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.PublicClient(request.query.productID, request.query.apiURI) client.getProducts(function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) }) exports.getProductOrderBook = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.PublicClient(request.query.productID, request.query.apiURI) client.getProductOrderBook({level: request.query.level || 1}, function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) }) exports.getProductTicker = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.PublicClient(request.query.productID, request.query.apiURI) client.getProductTicker(function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) }) exports.getProductTrades = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.PublicClient(request.query.productID, request.query.apiURI) client.getProductTrades({after: request.query.after}, function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) }) // exports.getProductTradeStream = functions.https.onRequest((request, response) => { // cors(request, response, () => { // var client = new Gdax.PublicClient(request.body.product, request.body.apiURL) // client.getProductTrades(tradesFrom, tradesTo) // }) // }) exports.getProductHistoricRates = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.PublicClient(request.query.productID, request.query.apiURI) client.getProductHistoricRates({granularity: request.query.granularity || 3000}, function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) }) exports.getProduct24HrStats = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.PublicClient(request.query.productID, request.query.apiURI) client.getProduct24HrStats(function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) }) exports.getCurrencies = functions.https.onRequest((request, response) => { cors(request, response, () => { var client = new Gdax.PublicClient(request.query.productID, request.query.apiURI) client.getCurrencies(function(err, resp, data) { if (err) {response.send(err)} else {response.send(data)} }) }) })
var CLE_EDITORS; jQuery(document).ready(function() { jQuery.cleditor.defaultOptions.controls = 'bold italic style removeformat | bullets numbering | link unlink | pasteword | source'; jQuery.cleditor.defaultOptions.colors = '387ab6 474747'; jQuery.cleditor.defaultOptions.styles = [["Paragraph", "<p>"], ["Header 2", "<h2>"], ["Header 3", "<h3>"]]; CLE_EDITORS = jQuery("TEXTAREA.editor").cleditor(); }); function refreshCLE() { if (CLE_EDITORS) { CLE_EDITORS.each(function() { this.refresh(); }); } }
'use strict'; // MODULES // var similarity = require( 'compute-cosine-similarity'); // COSINE DISTANCE // /** * FUNCTION: distance( x, y[, accessor] ) * Computes the cosine distance between two arrays. * * @param {Number[]|Array} x - input array * @param {Number[]|Array} y - input array * @param {Function} [accessor] - accessor function for accessing array values * @returns {Number|Null} Cosine distance */ function distance( x, y, clbk ) { var s; if ( arguments.length > 2 ) { s = similarity( x, y, clbk ); } else { s = similarity( x, y ); } return ( s !== null ) ? 1 - s : s; } // end FUNCTION distance() // EXPORTS // module.exports = distance;
/// // Dependencies /// import { fromJS } from 'immutable'; import configureMockStore from 'redux-mock-store'; import { ActionsObservable } from 'redux-observable'; import nock from 'nock'; import url from 'url'; import { baseURL } from '../../app/__mocks__/api'; import epic from '../epics'; import * as actions from '../actions'; import * as formsActions from '../../forms/actions'; /// // Initialization / Configuration /// const userId = 1; const defaultState = fromJS({ user: { accessToken: 'a', id: userId, } }); jest.mock('../../app/api'); const mockStore = configureMockStore([]) let store; const parsedUrl = url.parse(baseURL); const baseHost = parsedUrl.protocol + '//' + parsedUrl.hostname; /// // Tests /// it('[epic] people: ignores invalid actions', () => { store = mockStore(fromJS({})); const action$ = ActionsObservable.of({type: null}); const expected = undefined; return epic(action$, store).toPromise().then(received => { expect(received).toEqual(expected); }); }); pit('[epic] people: correctly processes PEOPLE:GET_LIST_START', () => { const friendsFrom = [ {id: 1}, {id: 2} ]; const friendsTo = [ {id: 3}, {id: 4} ]; nock(baseHost) .get(/^\/people\/1\/friendsFrom.*$/) .reply(200, friendsFrom); nock(baseHost) .get(/^\/people\/1\/friendsTo.*$/) .reply(200, friendsTo); const state = fromJS(defaultState); store = mockStore(state); const action$ = ActionsObservable.of( actions.getListStart() ); const expected = actions.getListDone( friendsFrom.concat(friendsTo) ); return epic(action$, store).toPromise().then(received => { expect(received).toEqual(expected); }); }); pit('[epic] people: correctly processes PEOPLE:SUBMIT_FORM', () => { const item = {a: 'a', b: 'b'}; nock(baseHost) .post(/^\/people\/1\/people.*$/) .reply(200, item); const state = fromJS(defaultState); store = mockStore(state); const action$ = ActionsObservable.of( actions.submitForm(item) ); const expected = [ formsActions.submitFormDone('people'), formsActions.clearFormValues('people'), actions.addItemDone(item), ]; return epic(action$, store).reduce((acc, action) => { return acc.concat([action]); }, []).toPromise().then(received => { expect(received).toEqual(expected); }); });
export class InlineEditing { constructor() { let crudServiceBaseUrl = '//demos.telerik.com/kendo-ui/service'; this.datasource = new kendo.data.DataSource({ transport: { read: { url: crudServiceBaseUrl + '/Products', dataType: 'jsonp' }, update: { url: crudServiceBaseUrl + '/Products/Update', dataType: 'jsonp' }, destroy: { url: crudServiceBaseUrl + '/Products/Destroy', dataType: 'jsonp' }, create: { url: crudServiceBaseUrl + '/Products/Create', dataType: 'jsonp' }, parameterMap: function(options, operation) { if (operation !== 'read' && options.models) { return {models: kendo.stringify(options.models)}; } } }, batch: true, pageSize: 8, schema: { model: { id: 'ProductID', fields: { ProductID: { editable: false, nullable: true }, ProductName: { validation: { required: true } }, UnitPrice: { type: 'number', validation: { required: true, min: 1} }, Discontinued: { type: 'boolean' }, UnitsInStock: { type: 'number', validation: { min: 0, required: true } } } } } }); } }
// Karma configuration // Generated on Mon Jun 22 2015 15:35:14 GMT+0200 (SAST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine', 'requirejs'], // list of files / patterns to load in the browser files: [ 'test-main.js', {pattern: 'src/**/*.js', included: false}, {pattern: 'test/**/*Spec.js', included: false} ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
(function (angular) { "use strict"; angular.module("mfl.downloads", [ "ui.router", "ui.bootstrap", "ui.bootstrap.tpls", "mfl.downloads.controllers", "mfl.downloads.routes", "mfl.facilities.wrapper" ]); })(window.angular);
function f () { try { throw 'a' } catch (err) {} } try { f() } catch (err) {}
"use strict"; angular.module('tcApp').factory('Auth', ['$http', '$q','Identity', 'UserResource',function($http, $q, Identity, UserResource){ return { authenticateUser: function(username, password) { var deferred = $q.defer(); $http.post('/login', {username:username, password:password}).then(function(res) { if(res.data.success){ var user = new UserResource(); angular.extend(user, res.data.user); Identity.currentUser = user; deferred.resolve(true); } else { deferred.resolve(false); } }); return deferred.promise; }, logoutUser: function(){ var deferred = $q.defer(); $http.post('/logout',{logout:true}).then(function() { Identity.currentUser = undefined; deferred.resolve(true); }); return deferred.promise; }, createUser: function(userData) { var newUser = new UserResource(userData); var deferred = $q.defer(); newUser.$save().then(function() { Identity.currentUser = newUser; deferred.resolve(true); }, function(res) { deferred.reject(res.data); }); return deferred.promise; } }; }]);
/* * grunt-phantomcss * https://github.com/micahgodbolt/grunt-phantomcss * * Copyright (c) 2013 Chris Gladd * Copyright (c) since 2014 Anselm Hannemann * Copyright (c) since 2015 Micah Godbolt * * Licensed under the MIT license. */ 'use-strict'; // Get node fileSystem module and define the separator module var fs = require('fs'); var s = fs.separator; var path = require('path'); // Parse arguments passed in from the grunt task var args = JSON.parse(phantom.args[0]); // Get viewport arguments (width | height) var viewportSize = { width: args.viewportSize[0], height: args.viewportSize[1] }; // Messages are sent to the parent by appending them to the tempfile var sendMessage = function() { fs.write(args.tempFile, JSON.stringify(Array.prototype.slice.call(arguments)) + '\n', 'a'); }; // Initialise CasperJs var phantomCSSPath = args.phantomCSSPath; phantom.casperPath = phantomCSSPath + s + 'CasperJs'; phantom.injectJs(phantom.casperPath + s + 'bin' + s + 'bootstrap.js'); var casper = require('casper').create({ viewportSize: viewportSize, logLevel: args.logLevel, verbose: true }); // Require and initialise PhantomCSS module var phantomcss = require(phantomCSSPath + s + 'phantomcss.js'); phantomcss.init({ screenshotRoot: args.screenshots, failedComparisonsRoot: args.failures, libraryRoot: phantomCSSPath, // Give absolute path, otherwise PhantomCSS fails mismatchTolerance: args.mismatchTolerance, // defaults to 0.05 onFail: function(test) { sendMessage('onFail', test); }, onPass: function(test) { sendMessage('onPass', test); }, onTimeout: function(test) { sendMessage('onTimeout', test); }, onComplete: function(allTests, noOfFails, noOfErrors) { sendMessage('onComplete', allTests, noOfFails, noOfErrors); }, fileNameGetter: function(root, filename) { var name = phantomcss.pathToTest + args.baselines + '/' + filename; if (fs.isFile(name + '.png')) { return name + '.diff.png'; } else { return name + '.png'; } }, }); casper.start(); // Run the test scenarios args.test.forEach(function(testSuite) { phantom.casperTest = true; phantom.rootUrl = args.rootUrl; casper.then(function() { phantomcss.pathToTest = path.dirname(testSuite) + '/'; }); require(testSuite); casper.then(function() { phantomcss.compareSession(); }) .then(function() { casper.test.done(); }); }); // End tests casper.run(function() { phantom.exit(); });
/*! * Jquery EasterEgg v1.0.0 (https://github.com/gonpre/EasterEgg) * * Copyright 2015 Francisco Gonzalez * Licensed under MIT (https://github.com/gonpre/EasterEgg/blob/master/LICENSE) */ (function($){ $.fn.easteregg = function(settings) { var _settings = $.extend({}, $.fn.easteregg.default_settings, settings); var _o_easteregg = new EasterEgg(_settings); return _o_easteregg; }; $.fn.easteregg.default_settings = { delay_time : 1000, eggsters : [ { keys : [38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 66, 65], callback : null } ] }; function is_same_array(array1, array2) { return array1.lenght == array2.lenght && array1.every(function(element, index) { return element === array2[index]; }); } var EasterEgg = function(settings){ this._settings = settings; this._pressed_keys = []; this._timer; }; EasterEgg.VERSION = '1.0.0'; EasterEgg.prototype = { init : function() { var _self = this; $(document).on('keydown', function(event){ clearInterval(_self._timer); _self._timer = _self.getTimer(); _self._pressed_keys.push(event.keyCode); _self._settings.eggsters.forEach(function(eggster){ if (is_same_array(eggster.keys, _self._pressed_keys)) { _self.clearKeys(); if ($.type(eggster.callback) === 'function') { eggster.callback(); } } }); }); _self._timer = _self.getTimer(); }, setKonami : function(callback) { this._settings.eggsters[0].callback = callback; }, addEgg : function(keys, callback) { if (!($.type(keys) === 'array' || $.type(keys) === 'string') || keys.lenght == 0 || $.type(callback) !== 'function') { return false; } if ($.type(keys) === 'string') { var keys = keys.split(''); keys.forEach(function(element, index, array){ array[index] = element.toUpperCase().charCodeAt(); }); } this._settings.eggsters.push({keys:keys, callback:callback}); }, clearKeys : function() { this._pressed_keys = []; }, getTimer : function() { var _self = this; return setInterval(function(){ _self.clearKeys(); }, _self._settings.delay_time); }, }; })(jQuery);
/* * AppConstants * Each action has a corresponding type, which the reducer knows and picks up on. * To avoid weird typos between the reducer and the actions, we save them as * constants here. We prefix them with 'yourproject/YourComponent' so we avoid * reducers accidentally picking up actions they shouldn't. * * Follow this format: * export const YOUR_ACTION_CONSTANT = 'yourproject/YourContainer/YOUR_ACTION_CONSTANT'; */ export const DEFAULT_LOCALE = 'en' export const SET_LOADING = 'fashion/App/SET_LOADING' export const TOGGLE_MENU = 'fashion/App/TOGGLE_MENU'
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import { hbs } from 'ember-cli-htmlbars'; import moment from 'moment'; // import { run } from '@ember/runloop'; module('Integration | Component | time-input', function (hooks) { setupRenderingTest(hooks); test('it renders', async function (assert) { this.testDate = moment(); this.timeUpdated = () => { const val = this.testDate; assert.equal( val.format('YYYY-MM-DD HH:mm'), moment().format('YYYY-MM-DD HH:mm') ); }; // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.set('myAction', function(val) { ... }); await render(hbs`<input type="text" id="other"/>`); await render( hbs`<TimeInput @currentDate={{this.testDate}} @onChangedTime={{this.timeUpdated}}/>` ); assert.dom(this.element).hasText(''); // run(() => document.getElementById('timeInput').focus()); // Blur // run(() => document.getElementById('other').focus()); }); });
Package.describe({ name: 'numtel:pg-server', version: '0.0.2', summary: 'Run PostgreSQL server inside your Meteor app', git: 'https://github.com/numtel/meteor-pg-server', documentation: 'README.md' }); function determinePlatformNpmPackage() { switch(process.platform + '_' + process.arch) { case 'linux_x64': return 'pg-server-9.4-linux-x64'; case 'linux_ia32': return 'pg-server-9.4-linux-i386'; case 'darwin_x64': return 'pg-server-9.4-osx-x64'; default: return null; } } // Force Meteor to recognize that this package has binary deps // bcrypt is an npm package that // has different binaries for differnet architectures. Npm.depends({ bcrypt: '0.8.2' }); var npmPkg = determinePlatformNpmPackage(); if(npmPkg === null) { console.error('ERROR: Platform is not supported by numtel:pg-server!'); console.error(' Supports only Linux (32 and 64 bit) and OSX (64 bit)'); } else { var depend = {}; // platform dependent pg-server-xxx package depend[npmPkg] = '9.4.4'; Package.registerBuildPlugin({ name: 'pgServer', use: [ 'underscore@1.0.3' ], sources: [ 'plugin/pgServer.js' ], npmDependencies: depend }); } Package.onUse(function(api) { api.versionsFrom('1.1.0.2'); }); Package.onTest(function(api) { api.use('tinytest'); api.use('numtel:pg-server'); api.use('numtel:pg@0.0.3'); api.addFiles('test.pg.json', 'server'); api.addFiles('pg-server-tests.js', 'server'); });
import {NamespaceClass, ResourceClass, Namespace, URI, Class, Property, type, Resource, Vocab, Context, Prefix} from '../src/index' import expect from 'expect' import {Map, Set, List} from 'immutable' describe('URI', () => { it('should be a ResourceClass instance', () => { expect(URI('test')).toBeA(ResourceClass) }) it('should create the correct map', () => { expect( URI('test').toJSON() ).toEqual( { '@id': 'test' } ) }) }) describe('Vocab', () => { it('should be a ResourceClass instance', () => { let ns1 = Namespace( Class('Class1') ) expect(Vocab(ns1)).toBeA(ResourceClass) }) it('should create the correct map', () => { const ns1 = Namespace( Class('Class1'), Property('prop1') ) const ns2 = Namespace( Class('Class2'), Property('prop2') ) expect( Vocab(ns1, ns2).toJSON() ).toEqual( { '@graph': [ { "@id": "Class1", "@type": ["rdfs:Class"] }, { "@id": "prop1", "@type": ["rdfs:Property"] }, { "@id": "Class2", "@type": ["rdfs:Class"] }, { "@id": "prop2", "@type": ["rdfs:Property"] } ] } ) }) it('should support property supclassing', function() { let hydra = Namespace( Class('Link') ) var search = Property('search', hydra.Link()) expect( search.toJSON() ).toEqual( { '@id': 'search', '@type': ['rdfs:Property', 'Link'] } ) }) }) describe('type', () => { it('should be a ResourceClass instance', () => { expect(type('test')).toBeA(ResourceClass) }) it('should create a type set', () => { expect( type('test').toJSON() ).toEqual( { '@type': ['test'] } ) }) }) describe('Class', () => { it('should be a ResourceClass instance', () => { expect(Class('TestClass')).toBeA(ResourceClass) }) it('should create a Class resource', () => { expect( Class('TestClass').toJSON() ).toEqual( { '@id': 'TestClass', '@type': ['rdfs:Class'] } ) }) }) describe('Property', () => { it('should be a ResourceClass instance', () => { expect(Property('testProperty')).toBeA(ResourceClass) }) it('should create a Property resource', () => { expect( Property('testProperty').toJSON() ).toEqual( { '@id': 'testProperty', '@type': ['rdfs:Property'] } ) }) it('should allow additional properties', () => { expect( Property('testProperty').toJSON() ).toEqual( { '@id': 'testProperty', '@type': ['rdfs:Property'], } ) }) }) describe('Resource', () => { it('should be a ResourceClass instance', () => { expect(Resource(URI('/'))).toBeA(ResourceClass) }) it('should generate a resource correctly', () => { let res = Resource( URI('/'), type('Type1'), type('Type2') ) expect(res.toJSON()) .toEqual({ '@id': '/', '@type': ['Type1', 'Type2'] }) }) }) describe('Namespace', () => { it('should be a NamespaceClass instance', () => { expect(Namespace(Class('Class1'))).toBeA(NamespaceClass) }) it('should create a namespace correctly', () => { const ns = Namespace( Class('Class1'), Property('prop1') ) expect( ns.Class1(URI('/')).toJSON() ).toEqual( { '@id': '/', '@type': ['Class1'] } ) expect( ns.prop1('test').toJSON() ).toEqual( { 'prop1': 'test' } ) }) }) describe('Prefix', () => { it('should be a ResourceClass instance', () => { const ns = Namespace( Class('Class1') ) expect(Prefix('ns', 'http://example.com/', ns)).toBeA(ResourceClass) }) it('should generate the context correctly', () => { const ns = Namespace( Class('Class1'), Property('prop1') ) const prefix = Prefix( 'vocab', 'http://example.com/vocab#', ns ) expect( prefix.toJSON() ).toEqual({ '@context': { 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'vocab': 'http://example.com/vocab#', 'Class1': 'vocab:Class1', 'prop1': 'vocab:prop1' } }) }) it('should support context overrides', () => { const ns = Namespace( Property('member'), Property('up') ) const prefix = Prefix( 'vocab', 'http://example.com/vocab#', ns, { 'member': {'@container': '@list'}, 'up': {'@type': '@id'} } ) expect( prefix.toJSON() ).toEqual( { '@context': { 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'vocab': 'http://example.com/vocab#', 'member': {'@id': 'vocab:member', '@container': '@list'}, 'up': {'@id': 'vocab:up', '@type': '@id'} } } ) }) })
// ./models/user.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UserSchema = new Schema({ userName: String, email:String, passwordHash: String, passwordSalt: String, createdOn : Date, createdBy:{type: Schema.Types.ObjectId, ref: 'user'}, updatedOn:Date, updatedBy:{type: Schema.Types.ObjectId, ref: 'userprofile'}, deletedOn:Boolean, deletedBy:{type: Schema.Types.ObjectId, ref: 'userprofile'} }); var User=mongoose.model('user', UserSchema); module.exports = User; UserSchema.pre('save', function(next) { // get the current date var currentDate = new Date(); // change the updated_at field to current date this.createdOn = currentDate; // if created_at doesn't exist, add to that field if (!this.createdDate) this.createdOn = currentDate; next(); });
/*! * Copyright (c) 2015-2019 Cisco Systems, Inc. See LICENSE file. */ import {WebexPlugin} from '@webex/webex-core'; const Calendar = WebexPlugin.extend({ namespace: 'Calendar', /** * Decrypts an encrypted incoming calendar event * @param {Object} event * @returns {Promise} Resolves with a decrypted calendar event */ processMeetingEvent(event) { return this.webex.transform('inbound', event) .then(() => event); }, /** * Retrieves a collection of meetings based on the request parameters * @param {Object} options * @param {Date} options.fromDate the start of the time range * @param {Date} options.toDate the end of the time range * @returns {Promise} Resolves with an array of meetings */ list(options) { options = options || {}; return this.webex.request({ method: 'GET', service: 'calendar', resource: 'calendarEvents', qs: options }) .then((res) => res.body.items); } }); export default Calendar;
var fs = require('fs') net = require('net') child = require('child_process') spawn = child.spawn exec = child.exec var robot_ip = '20.10.10.115', robot_name = 'raspberry pi', robot_port = 5002 var server_ip = '192.168.2.2', server_name = 'drewpi', server_port = 5001 var cmd_path = __dirname + '/commands.txt' var motorPath = __dirname + '/text_test_1.py' fs.watch(cmd_path, {persistent:true}, function(event,fn) { if(event=='change') { var instance = spawn('python', [motorPath]) } }) var server = net.createServer(function(socket) { console.log('A client has connected.\n') socket.on('data', function(data) { console.log('I am receiving data\n') fs.writeFile(cmd_path, data.toString(), function(err) { if(err) { console.log(err) } }) }) socket.on('end', function() { console.log('disconnected') }) }); server.listen(robot_port, robot_ip, function(){ address = server.address() console.log('Server open at: %j\n', address) })
$( document ).ready(function() { "use strict"; firebase.auth().onAuthStateChanged(firebaseUser =>{ if (firebaseUser){ var rootRef = firebase.database().ref().child("users").child(firebaseUser.uid).child("movies").child("seen"); rootRef.on("child_added", snap =>{ var movieId = snap.child("movieId").val(); var moviename = snap.child("moviename").val(); var poster = snap.child("poster").val(); var posterPre = "https://image.tmdb.org/t/p/w500"; $("#seenList").append("<div class='col-md-2 col-xs-6'><div class='movieVast'><a href='detail'><img class='posterSize movieId' alt='"+movieId+"' src='"+poster + "'/><p class='textVast'>"+ moviename +"</p></a></div></div>"); $(".col-md-2:has(img[alt=null])").remove(); //wanneer er geklikt wordt op een .movieId --> sessionstorage van alt-waarde $(".movieId").on("click", function(){ var movieId = $(this).attr("alt"); sessionStorage.setItem("movieId", movieId); }); }); } }); });
'use strict'; /* * Defining the Package */ var Module = require('meanio').Module; var Players = new Module('players'); /* * All MEAN packages require registration * Dependency injection is used to define required modules */ Players.register(function(app, auth, database) { //We enable routing. By default the Package Object is passed to the routes Players.routes(app, auth, database); Players.menus.add({ title: 'Players', link: 'players page', menu: 'main' }); Players.aggregateAsset('css', 'players.css'); /** //Uncomment to use. Requires meanio@0.3.7 or above // Save settings with callback // Use this for saving data from administration pages Players.settings({ 'someSetting': 'some value' }, function(err, settings) { //you now have the settings object }); // Another save settings example this time with no callback // This writes over the last settings. Players.settings({ 'anotherSettings': 'some value' }); // Get settings. Retrieves latest saved settigns Players.settings(function(err, settings) { //you now have the settings object }); */ return Players; });
require("coffee-script"); require("hubiquitus").start("topology.json");
/** * @author mr.doob / http://mrdoob.com/ */ THREE.DirectionalLight = function ( hex, intensity ) { THREE.Light.call( this, hex ); this.position = new THREE.Vector3( 0, 1, 0 ); this.intensity = intensity || 1; }; THREE.DirectionalLight.prototype = new THREE.Light(); THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
var querstring = require('querystring'); var obj = querstring.parse('username=stark&age=18&hobby=lanqiu'); console.log(obj); // { username: 'stark', age: '18', hobby: 'lanqiu' }
import { withRouter } from 'react-router'; import Component from './ndc-overview-component'; export default withRouter(Component);
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'colordialog', 'tt', { clear: 'Бушату', highlight: 'Билгеләү', options: 'Төс көйләүләре', selected: 'Сайланган төсләр', title: 'Төс сайлау' } );
import React from 'react'; import HashtagList from './HashtagList'; export default class FollowList extends React.Component{ componentWillMount(){ } render(){ let heartIcon = <i className="glyphicon glyphicon-heart"/>; let heading = <div>{heartIcon} Follow <span className="pull-right"> <a onClick={this.props.doGetFollowHashtags}> <i className="glyphicon glyphicon-refresh"/> </a> </span> </div>; let itemArray = this.props.followHashtags.map((item) => { return { name: item.hashtag, number: item.follows, policyId: item.policyId } }); return( <HashtagList heading={heading} hashtags={itemArray} glyphicon={heartIcon} addHandler={this.props.doAddFollowHashtag} deleteHandler={this.props.doRemoveFollowHashtag}/> ); } }
/* 實作 ck.Express 物件 for API Server */ class ApiServer extends ck.Express { static _addSlash (url) { return url.indexOf(`/`) === 0 ? url : `/${url}` } static _genRouteFn (genFn) { return async (req, res, next) => { try { await genFn(req, res, next) } catch (e) { next(e) } } } getGroupPath (group, version = require(`package.json`).version) { return `/api/v${version}/${group}` } createRouter (path = ``) { const router = super.createRouter(path) const methods = [`get`, `post`, `put`, `delete`] for (const method of methods) { const originalFn = router[method] router[method] = (...args) => { const lastArgIndex = args.length - 1 args[0] = ApiServer._addSlash(args[0]) args[lastArgIndex] = ApiServer._genRouteFn(args[lastArgIndex]) originalFn.apply(router, args) } } return router } } module.exports = new ApiServer()
/** * 用户业务操作 */ const validator = require('validator') const userModel = require('./../models/user-info') const userCode = require('./../codes/user') const user = { /** * 创建用户 * @param {object} user 用户信息 * @return {object} 创建结果 */ async create( user ) { let result = await userModel.create(user) return result }, /** * 查找存在用户信息 * @param {object} formData 查找的表单数据 * @return {object|null} 查找结果 */ async getExistOne( formData ) { let resultData = await userModel.getExistOne({ 'email': formData.email, 'name': formData.userName }) return resultData }, /** * 登录业务操作 * @param {object} formData 登录表单信息 * @return {object} 登录业务操作结果 */ async signIn( formData ) { let resultData = await userModel.getOneByUserNameAndPassword({ 'password': formData.password, 'name': formData.userName}) return resultData }, /** * 根据用户名查找用户业务操作 * @param {string} userName 用户名 * @return {object|null} 查找结果 */ async getUserInfoByUserName( userName ) { let resultData = await userModel.getUserInfoByUserName( userName ) || {} let userInfo = { // id: resultData.id, email: resultData.email, userName: resultData.name, detailInfo: resultData.detail_info, createTime: resultData.create_time } return userInfo }, /** * 检验用户注册数据 * @param {object} userInfo 用户注册数据 * @return {object} 校验结果 */ validatorSignUp( userInfo ) { let result = { success: false, message: '', } if ( /[a-z0-9\_\-]{6,16}/.test(userInfo.userName) === false ) { result.message = userCode.ERROR_USER_NAME return result } if ( !validator.isEmail( userInfo.email ) ) { result.message = userCode.ERROR_EMAIL return result } if ( !/[\w+]{6,16}/.test( userInfo.password ) ) { result.message = userCode.ERROR_PASSWORD return result } if ( userInfo.password !== userInfo.confirmPassword ) { result.message = userCode.ERROR_PASSWORD_CONFORM return result } result.success = true return result } } module.exports = user
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { Card, CardTitle, CardActions } from 'material-ui/Card'; import compose from 'recompose/compose'; import inflection from 'inflection'; import ViewTitle from '../layout/ViewTitle'; import Title from '../layout/Title'; import { DeleteButton, EditButton, ListButton } from '../button'; import { crudGetOne as crudGetOneAction } from '../../actions/dataActions'; import DefaultActions from './ShowActions'; import translate from '../../i18n/translate'; /** * Turns a children data structure (either single child or array of children) into an array. * We can't use React.Children.toArray as it loses references. */ const arrayizeChildren = children => (Array.isArray(children) ? children : [children]); export class Show extends Component { componentDidMount() { this.props.crudGetOne(this.props.resource, this.props.id, this.getBasePath()); } componentWillReceiveProps(nextProps) { if (this.props.id !== nextProps.id) { this.props.crudGetOne(nextProps.resource, nextProps.id, this.getBasePath()); } } // FIXME Seems that the cloneElement in CrudRoute slices the children array, which makes this necessary to avoid rerenders shouldComponentUpdate(nextProps) { if (nextProps.isLoading !== this.props.isLoading) { return true; } const currentChildren = arrayizeChildren(this.props.children); const newChildren = arrayizeChildren(nextProps.children); return newChildren.every((child, index) => child === currentChildren[index]); } getBasePath() { const { location } = this.props; return location.pathname.split('/').slice(0, -2).join('/'); } render() { const { actions = <DefaultActions />, title, children, id, data, isLoading, resource, hasDelete, hasEdit, translate } = this.props; const basePath = this.getBasePath(); const resourceName = translate(`resources.${resource}.name`, { smart_count: 1, _: inflection.humanize(inflection.singularize(resource)), }); const defaultTitle = translate('aor.page.show', { name: `${resourceName}`, id, data, }); const titleElement = data ? <Title title={title} record={data} defaultTitle={defaultTitle} /> : ''; return ( <div> <Card style={{ opacity: isLoading ? 0.8 : 1 }}> {actions && React.cloneElement(actions, { basePath, data, hasDelete, hasEdit, refresh: this.refresh, resource, })} <ViewTitle title={titleElement} /> {data && React.cloneElement(children, { resource, basePath, record: data, })} </Card> </div> ); } } Show.propTypes = { actions: PropTypes.element, children: PropTypes.element, crudGetOne: PropTypes.func.isRequired, data: PropTypes.object, hasDelete: PropTypes.bool, hasEdit: PropTypes.bool, id: PropTypes.string.isRequired, isLoading: PropTypes.bool.isRequired, location: PropTypes.object.isRequired, params: PropTypes.object.isRequired, resource: PropTypes.string.isRequired, title: PropTypes.any, translate: PropTypes.func, }; function mapStateToProps(state, props) { return { id: props.params.id, data: state.admin[props.resource].data[props.params.id], isLoading: state.admin.loading > 0, }; } const enhance = compose( connect( mapStateToProps, { crudGetOne: crudGetOneAction }, ), translate, ); export default enhance(Show);
module.exports = function(grunt) { // Project configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), sass: { dist: { options: { style: 'compressed', noCache: true }, files: { 'css/style.css': 'scss/style.scss', 'css/ie.css': 'scss/ie.scss' } } }, watch: { css: { files: 'scss/*.scss', tasks: ['sass'] } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['sass']); };