text
stringlengths
2
6.14k
/* global describe, test, expect, jest */ import React from "react"; import { mount } from "enzyme"; import Form from "../Form"; describe("HOC (WithWrapper)", () => { test("[handleOnKeyup] should reset the error state", () => { const onKeyUp = jest.fn(); const comp = mount( <Form.Input onChange={spy} value="hey" error="asdas" onKeyUp={onKeyUp} /> ); const inst = comp.instance(); const spy = jest.spyOn(inst, "setState"); inst.handleOnKeyup({}); expect(spy).toHaveBeenCalledWith({ error: null }); expect(onKeyUp).toHaveBeenCalledWith({}); comp.setProps({ onKeyUp: undefined, error: undefined }); inst.handleOnKeyup({}); expect(onKeyUp).toHaveBeenCalledTimes(1); }); test("[handleOnChange] should set a hasValue and call the onChange prop", () => { // The Input is actually wrapped in a HOC const spy = jest.fn(); const comp = mount(<Form.Input onChange={spy} value="hey" />); const inst = comp.instance(); inst.handleOnChange("some value", { formValue: "some value" }); expect(comp.state("formValue")).toBe("some value"); expect(spy).toHaveBeenCalled(); comp.setProps({ onChange: undefined }); inst.handleOnChange(""); expect(comp.state("formValue")).toBe(undefined); expect(spy).toHaveBeenCalledTimes(1); }); test("hasValue gets updated when new props arrive", () => { const comp = mount(<Form.Input />); expect(comp.find(".hasValue").exists()).toBe(false); comp.setProps({ value: "hey" }); expect(comp.state("formValue")).toBe("hey"); }); test("Handles initialvalues for Form.Select", () => { const options = [ { value: "blue", text: "Blue" }, { value: "red", text: "Red" } ]; const comp = mount( <Form.Select name="color" selected="blue" options={options} /> ); expect(comp.find(".hasValue").exists()).toBe(true); expect(comp.state("formValue")).toBe("blue"); }); describe("snapshot", () => { test("should include a label span when label is not defined in the child component", () => { const comp = mount( <Form.Input label="My awesome label" value="hello-world" /> ); expect(comp).toMatchSnapshot(); }); test("should not include a label span when the label is defined in the child component", () => { const comp = mount(<Form.Checkbox checked />); expect(comp).toMatchSnapshot(); }); test("should display an error span when there is an error", () => { const comp = mount( <Form.Checkbox checked error="Cannot proceed like this" /> ); expect(comp).toMatchSnapshot(); }); }); });
import { Blaze } from 'meteor/blaze'; /** * A global Blaze UI helper to capitalizes the first letter of an input String * * Credit to: * * http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript */ Blaze.registerHelper('capitalizeFirstLetter', function (context) { if (!context) { return; } return context.charAt(0).toUpperCase() + context.slice(1); });
// ==UserScript== // @name Custom Message Tones // @namespace pxgamer // @version 0.5 // @description Adds options to load in custom tones when a message is received. // @author pxgamer // @include *kat.cr/* // @grant none // ==/UserScript== (function() { var AUDIO_FILE = ""; // URL of audio file (MP3, WAV, OGG) var AUDIO_LENGTH = 5000; // Length in Ticks // Do Not Edit Below Here var acMethod = jQuery.fn.addClass; var audio1; jQuery.fn.addClass = function() { var result = acMethod.apply(this, arguments); jQuery(this).trigger('cssClassChanged'); return result; }; $('body').append('<span id="chatMsgHandler"></span>'); $('#chatMsgHandler').css('display', 'none'); $(document).on('cssClassChanged', function() { var msgBarElem = $('.chat-bar-new'); if (msgBarElem.length > 0) { audio1.play(); setTimeout(function() { audio1.pause(); audio1.currentTime = 0; }, AUDIO_LENGTH); } }); var audioTypes = { "mp3": "audio/mpeg", "ogg": "audio/ogg", "wav": "audio/wav" }; function pxS(sound) { var audio_element = document.createElement('audio'); if (audio_element.canPlayType) { for (var i = 0; i < arguments.length; i++) { var source_element = document.createElement('source'); source_element.setAttribute('src', arguments[i]); if (arguments[i].match(/\.(\w+)$/i)) { source_element.setAttribute('type', audioTypes[RegExp.$1]); } audio_element.appendChild(source_element); } audio_element.load(); audio_element.pFunc = function() { audio_element.pause(); audio_element.currentTime = 0; audio_element.play(); }; return audio_element; } } audio1 = pxS(AUDIO_FILE); })();
'use strict'; export default class MainController { /*@ngInject*/ constructor($scope, Auth) { $scope.loggedIn = false; $scope.isStudent = false; $scope.isInstructor = false; Auth.getCurrentUser((user) => { $scope.user = user; $scope.loggedIn = Auth.isLoggedInSync(); if ($scope.loggedIn){ $scope.isStudent = Auth.isStudentSync(); $scope.isInstructor = Auth.isInstructorSync(); } }); } }
VideoPlayer = function(ctx) { this.autoplay = ctx.autoplay || true; this.video = document.getElementById('bgvid'); this.video.src = ctx.file; if(this.autoplay) { this.video.play(); } } VideoPlayer.prototype.stop = function(){ this.video.pause(); this.video.currentTime = 0; this.video.src = ''; } VideoPlayer.prototype.pause = function(){ this.video.pause(); } VideoPlayer.prototype.resume = function(){ this.video.play(); }
require('newrelic'); var express = require('express'); var app = express(); var http = require("http"); app.use(express.static(__dirname)); module.exports = app; var server = app.listen(process.env.PORT || 3000, function() { console.log('express server listening on port ' + server.address().port); }); setInterval(function() { http.get("http://cherrystreet.herokuapp.com"); }, 300000);
module.exports = function(grunt) { grunt.config.set('sass', { options: { loadPath: 'src/styles' }, dev: { files: { 'build/dist/styles.css': 'build/tmp/styles.scss' } }, prod: { files: { 'build/dist/styles.css': 'build/tmp/styles.scss' } } }); grunt.loadNpmTasks('grunt-contrib-sass'); };
const express = require('express') const path = require('path') const logger = require('morgan') const cookieParser = require('cookie-parser') const bodyParser = require('body-parser') const index = require('./routes/index') const app = express() // view engine setup app.engine('html', require('ejs').renderFile) app.set('views', path.join(__dirname, 'views')) app.set('view engine', 'html') app.use(logger('dev')) app.use(bodyParser.json()) // convert to json to obj(application/json) app.use(bodyParser.urlencoded({ extended: false }))// convert x-www-form-urlencoded to Obj app.use(cookieParser()) app.use(express.static(path.join(__dirname, 'public'))) app.use('/', index) // catch 404 and forward to error handler app.use((req, res, next) => { const err = new Error('Not Found') err.status = 404 next(err) }) // error handler app.use((err, req, res) => { // set locals, only providing error in development res.locals.message = err.message res.locals.error = req.app.get('env') === 'development' ? err : {} // render the error page res.status(err.status || 500) res.render('error') }) module.exports = app
import Storyview from './Story' export default { path: '/stories/:storyid', component: Storyview }
'use strict'; // ============================== // ABSTRACT PC BUILDER // ============================== var Workforce = function () { if (this.constructor === Workforce) { throw new Error("You cannot instantiate an abstract class!"); } }; Workforce.prototype.assemblePC = function () { throw new Error("You cannot call an abstract method!"); }; Workforce.prototype.setMotherboard = function (motherboard) { throw new Error("You cannot call an abstract method!"); }; Workforce.prototype.setCpu = function (cpu) { throw new Error("You cannot call an abstract method!"); }; Workforce.prototype.setRam = function (ram) { throw new Error("You cannot call an abstract method!"); }; Workforce.prototype.setSsd = function (ssd) { throw new Error("You cannot call an abstract method!"); }; Workforce.prototype.setNic = function (nic) { throw new Error("You cannot call an abstract method!"); }; Workforce.prototype.setPowerSupply = function (powerSupply) { throw new Error("You cannot call an abstract method!"); }; Workforce.prototype.setCaseDesign = function (caseDesign) { throw new Error("You cannot call an abstract method!"); }; module.exports = Workforce;
var task = function(request, callback, configuration){ var template = "helloParamterized.ejs"; var AWS = configuration.aws; var S3 = new AWS.S3(); callback(null, {template: template, params:{info:"Hello World from code!"}}); } exports.action = task;
'use strict'; const MongoClient = require('mongodb').MongoClient; module.exports = class Events { constructor() { this.database = null; this.collections = {}; } getDatabase(callback) { if (this.database) { callback(this.database); } else { MongoClient.connect('mongodb://writer:writer@ds017584.mlab.com:17584/events', (err, db) => { if (!err) { console.log('connected to database!'); this.database = db; callback(this.database); } else { console.log(err); } }); } } getCollection(collection, callback) { if (this.collections[collection]) { callback(this.collections[collection]); } else { this.getDatabase(database => { this.collections[collection] = database.collection(collection); callback(this.collections[collection]); }); } } addEvent(event, callback) { this.getCollection('events', collection => { collection.insertOne(event, callback); }); } getTags(callback) { this.getCollection('events', collection => { //collection.find().toArray(callback); collection.aggregate([ { "$group": { "_id": "$tags", "count": { $sum: 1 } } } ], callback); }); } }
module.exports = require('./../make')({ build: true });
var playersController = exports; exports.constructor = function playersController(){}; var _ = require('lodash'); var players = require('../sonos/players'); playersController.list = function(req, res, next) { players.client.find(function(err, players) { if (err) { return next(err); } res.send(players); }); }; playersController.get = function(req, res, next) { players.client.find(req.params.name, function(err, players) { if (err) { return next(err); } if (!players || players.length < 1) { err = new Error('The requested player could not be found'); err.type = 'not found'; return next(err); } // only return the one item res.send(players[0]); }); }; playersController.queue = function(req, res, next) { players.client.queue(req.params.name, req.query, function(err, queue) { if (err) { return next(err); } res.send({ roomName: req.params.name, currentIndex: queue.currentIndex, limit: queue.limit, offset: queue.offset, tracks: queue.tracks }); }); }; playersController.clearQueue = function(req, res, next) { players.client.clearQueue(req.params.name, function(err, queue) { if (err) { return next(err); } res.send({ roomName: req.params.name, currentIndex: queue.currentIndex, limit: queue.limit, offset: queue.offset, tracks: queue.tracks }); }); }; playersController.playlists = function(req, res, next) { players.client.playlists(req.params.name, function(err, playlists) { if (err) { return next(err); } res.send({ roomName: req.params.name, playlists: playlists }); }); }; playersController.action = function(req, res, next) { var action = req.params.action; var playerName = req.params.name; var opts = _.extend({}, req.body, req.query); players.client.action(playerName, action, opts, function(err, state) { if (err) { return next(err); } res.send(state); }); };
'use strict'; const setAction = (creep) => { if (creep.memory.action && creep.carry.energy === 0 || creep.memory.role === 'attacker' || creep.memory.role === 'healer'){ creep.memory.action = false; } if (!creep.memory.action && creep.carry.energy === creep.carryCapacity){ creep.memory.action = true; } }; module.exports = setAction;
var gulp = require('gulp'); var jade = require('gulp-jade'); var config = require('../../config'); gulp.task('samples:jade', function () { gulp.src(config.samples.jade.src) .pipe(jade({})) .pipe(gulp.dest(config.samples.html.dest)); });
var parseString = require('xml2js').parseString; // The body of the response from each of our api requests can either be xml or json // if body is json, simply return the json // else body is xml, so asynchronously parse the xml and wait for the result // This function returns a promise for the json value var getJsonFromBody = function(body) { var prom_json = new Promise(function(resolve, reject) { try { var json = JSON.parse(body); resolve(json); } catch(e) { var xml = body; parseString(xml, function(err, json) { if (err) reject(err); else resolve(json); }); } }); return prom_json; }; module.exports = getJsonFromBody;
'use strict'; var url = require('url'); var zlib = require('zlib'); var _ = require('./helpers'); module.exports = function(options, callback){ var callbackDone = false, httpProtocol = options.url.indexOf('https') === 0 ? 'https' : 'http', requestData = url.parse(options.url), method = (options.method || 'get').toLowerCase(), isJson = options.json || false, headers = options.headers || {}, isPost = method === 'post', postBody = isPost ? JSON.stringify(options.body) : null, contentLength = !!postBody ? Buffer.byteLength(postBody) : null, timeout = options.timeout || 5, setHeader = function(v, k){ requestData.headers[k] = v; }; var respond = function(body, details){ body = body.toString('utf-8'); var error = details.response.statusCode !== 200 ? details.response.statusCode : null, response; if(isJson){ try { callback(error, JSON.parse(body), details); } catch(e){ return callback('json parsing error', null, details); } } else { callback(error, body, details); } }; requestData.headers = {}; requestData.method = method; _.each(headers, setHeader); setHeader('gzip', 'accept-encoding'); if(isPost){ setHeader(contentLength, 'content-length'); setHeader('application/json', 'content-type'); } var req = require(httpProtocol).request(requestData).on('response', function(response) { var body = []; var details = { response: { headers: response.headers, statusCode: response.statusCode } }; response.on('data', function(chunk){ body.push(chunk); }).on('end', function(){ body = Buffer.concat(body); if(!callbackDone){ callbackDone = true; if(response.headers['content-encoding'] === 'gzip'){ zlib.gunzip(body, function(err, dezipped) { if(!!err){ return callback(err); } respond(dezipped, details); }); } else { respond(body, details); } } }); }).on('error', function(e){ if(!callbackDone){ callbackDone = true; callback(e); } }); req.setTimeout(1000 * timeout, function(){ if(!callbackDone){ callbackDone = true; callback('timeout'); } }); if(isPost){ req.write(postBody); } req.end(); };
import { Logging, Controller, Component, Evented } from "ng-harmony-decorator"; import { EventedController } from "ng-harmony-controller"; import CustomersFormTpl from "./customer_form.pug"; import "./customer_form.sass"; import Config from "../../../../assets/data/config.global.json"; @Component({ module: "webtrekk", selector: "customerForm", restrict: "E", replace: true, controller: "CustomersFormCtrl", template: CustomersFormTpl }) @Controller({ module: "webtrekk", name: "CustomersFormCtrl", deps: ["$location", "$rootScope", "CustomerService"], scope: { model: "@" } }) @Logging({ loggerName: "CustomersFormLogger", ...Config }) export class CustomersFormCtrl extends EventedController { constructor(...args) { super(...args); this.$scope.$on("change", this.handleEvent.bind(this)); } handleEvent (ev, { scope, triggerTokens }) { if (scope._name.fn === "CustomersFormCtrl" && triggerTokens.type === "mouseup") { this.log({ level: "warn", msg: "Button Clicked, Handle Behaviour Propagation?" }); } } @Evented({ selector: "label#save", type: "mouseup", }) async saveAndReturn () { let valid = Object.getOwnPropertyNames(this.$scope.model) .map((tupel) => { let valid = this.$scope.model[tupel].validate(); if (!valid) { this.log({ level: "error", msg: `${this.$scope.model[tupel].label} cannot be ${this.$scope.model[tupel].content} -- invalid`, }); } this.$scope.model[tupel].valid = valid; return valid; }).reduce((acc, tupel) => acc && tupel); if (valid) { await this.CustomerService.upsertCustomer({ customer_id: this.$scope.model.id.content, first_name: this.$scope.model.first_name.content, last_name: this.$scope.model.last_name.content, birthday: this.$scope.model.age.content.toString(), gender: this.$scope.model.gender.content, last_contact: this.$scope.model.last_contact.content.toString(), customer_lifetime_value: this.$scope.model.customer_lifetime_value.content, }); this.$location.url("/"); this.$rootScope.$apply(); } this._digest(); } @Evented({ selector: "label#cancel", type: "mouseup", }) cancelByReturn () { this.$location.path("/"); this.$rootScope.$apply(); } }
handlers.getRegister = function (ctx) { ctx.loadPartials({ header: '../views/common/header.hbs', footer: '../views/common/footer.hbs' }).then(function () { this.partial('../views/user/register.hbs'); }); } handlers.getLogin = function (ctx) { ctx.loadPartials({ header: '../views/common/header.hbs', footer: '../views/common/footer.hbs' }).then(function () { this.partial('../views/user/login.hbs'); }); } handlers.registerUser = function (ctx) { let username = ctx.params.username; let firstName = ctx.params.firstName; let lastName = ctx.params.lastName; let password = ctx.params.password; let repeatPassword = ctx.params.repeatPassword; if (firstName.length < 2) { notify.showError("The firstName should be at least 2 characters long"); return; } if (lastName.length < 2) { notify.showError("The lastName should be at least 2 characters long"); return; } if (username.length < 3) { notify.showError("The username should be at least 3 characters long"); return; } if (password.length < 6) { notify.showError('The password should be at least 6 characters long'); return; } if (password !== repeatPassword) { notify.showError('The repeat password should be equal to the password'); return; } userService.register(username, password, firstName, lastName).then((res) => { userService.saveSession(res); notify.showInfo('User registration successful.'); ctx.redirect('#/home'); }).catch(function (err) { notify.handleError(err); }); } handlers.logoutUser = function (ctx) { userService.logout().then(() => { sessionStorage.clear(); notify.showInfo('Logout successful.'); ctx.redirect('#/home'); }) } handlers.loginUser = function (ctx) { let username = ctx.params.username; let password = ctx.params.password; userService.login(username, password).then((res) => { userService.saveSession(res); notify.showInfo('Login successful.'); ctx.redirect('#/home'); }).catch(function (err) { notify.handleError(err); }); }
module.exports = class BackstopException { constructor (msg, scenario, viewport, originalError) { this.msg = msg; this.scenario = scenario; this.viewport = viewport; this.originalError = originalError; } toString () { return 'BackstopException: ' + this.scenario.label + ' on ' + this.viewport.label + ': ' + this.originalError.toString(); } };
Router.route('/users', { name: 'menu.users', template: 'users', parent: 'menu', title: 'Users', });
export default function isNull(x) { return x === null; }
(function() { 'use strict'; angular .module('app.home') .controller('Home', Home); Home.$inject = ['$scope', 'template']; function Home($scope, template) { var vm = this; activate(); function activate() { console.log('Activating Home Controller'); template.get('app/home/language/home.es.json') .then(function(result) { vm.text = result; $scope.app.setTitle(vm.text.title); }); // Loads text files. } } })();
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _Sdk = require('./Sdk'); var _Sdk2 = _interopRequireDefault(_Sdk); var _global = require('./global'); var _global2 = _interopRequireDefault(_global); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { load: function load() { var _this = this; if (typeof _global2.default.URLSearchParams === 'function') { this.URLSearchParams = _global2.default.URLSearchParams; return _Sdk2.default.Promise.resolve(); } return new _Sdk2.default.Promise(function (resolve) { if (typeof require.ensure !== 'function') { require.ensure = function (dependencies, callback) { callback(require); }; } require.ensure(['url-search-params'], function (require) { _this.URLSearchParams = require('url-search-params'); resolve(); }, 'QueryStringShim-polyfill'); }); } };
import {VType, validateEventFactory, BaseEvent} from '../../common/events' import oncePerServices from '../../common/services/oncePerServices' export default oncePerServices(function defineEvents({bus = missingService('bus')}) { bus.registerEvent([ { kind: 'event', type: 'connector.telegram.started', toString: (ev) => `${ev.service}: bots webhooks: ${Object.entries(ev.bots).map(([botName, bot]) => `\n\t${botName} (${bot.ref}): ${bot.webhook}`)}`, }, ]); })
module.exports = { Errors: { WrongAccount: "wrong-acount", }, set: (req, error_type) => (req.appSession.flashError = error_type), clear: (req) => { if (!req.appSession.flashError) return; const error_type = req.appSession.flashError; delete req.appSession.flashError; return error_type; }, };
/*jshint node:true, mocha:true*/ /** * Generated by PluginGenerator 0.14.0 from webgme on Wed Feb 24 2016 10:25:35 GMT-0600 (Central Standard Time). */ 'use strict'; var testFixture = require('../../globals'); describe('SysMLImporter', function () { var gmeConfig = testFixture.getGmeConfig(), expect = testFixture.expect, logger = testFixture.logger.fork('NewPlugin'), PluginCliManager = testFixture.WebGME.PluginCliManager, projectName = 'testProject', pluginName = 'SysMLImporter', project, gmeAuth, storage, commitHash; before(function (done) { testFixture.clearDBAndGetGMEAuth(gmeConfig, projectName) .then(function (gmeAuth_) { gmeAuth = gmeAuth_; // This uses in memory storage. Use testFixture.getMongoStorage to persist test to database. storage = testFixture.getMemoryStorage(logger, gmeConfig, gmeAuth); return storage.openDatabase(); }) .then(function () { var importParam = { projectSeed: testFixture.path.join(testFixture.SEED_DIR, 'EmptyProject.json'), projectName: projectName, branchName: 'master', logger: logger, gmeConfig: gmeConfig }; return testFixture.importProject(storage, importParam); }) .then(function (importResult) { project = importResult.project; commitHash = importResult.commitHash; return project.createBranch('test', commitHash); }) .nodeify(done); }); after(function (done) { storage.closeDatabase() .then(function () { return gmeAuth.unload(); }) .nodeify(done); }); it('should run plugin and update the branch', function (done) { var manager = new PluginCliManager(null, logger, gmeConfig), pluginConfig = { }, context = { project: project, commitHash: commitHash, branchName: 'test', activeNode: '/960660211', }; manager.executePlugin(pluginName, pluginConfig, context, function (err, pluginResult) { expect(err).to.equal(null); expect(typeof pluginResult).to.equal('object'); expect(pluginResult.success).to.equal(true); project.getBranchHash('test') .then(function (branchHash) { expect(branchHash).to.not.equal(commitHash); }) .nodeify(done); }); }); });
import Ember from "ember"; var oneWay = Ember.computed.oneWay, equal = Ember.computed.equal; export default Ember.Controller.extend({ needs: ['mixin-stack', 'mixin-details'], emberApplication: false, navWidth: 180, inspectorWidth: 360, mixinStack: oneWay('controllers.mixin-stack').readOnly(), mixinDetails: oneWay('controllers.mixin-details').readOnly(), isChrome: equal('port.adapter.name', 'chrome'), // Indicates that the extension window is focused, active: true, inspectorExpanded: false, pushMixinDetails: function(name, property, objectId, details) { details = { name: name, property: property, objectId: objectId, mixins: details }; this.get('mixinStack').pushObject(details); this.set('mixinDetails.model', details); }, popMixinDetails: function() { var mixinStack = this.get('controllers.mixin-stack'); var item = mixinStack.popObject(); this.set('mixinDetails.model', mixinStack.get('lastObject')); this.get('port').send('objectInspector:releaseObject', { objectId: item.objectId }); }, activateMixinDetails: function(name, details, objectId) { var self = this; this.get('mixinStack').forEach(function(item) { self.get('port').send('objectInspector:releaseObject', { objectId: item.objectId }); }); this.set('mixinStack.model', []); this.pushMixinDetails(name, undefined, objectId, details); }, droppedObject: function(objectId) { var mixinStack = this.get('mixinStack.model'); var obj = mixinStack.findProperty('objectId', objectId); if (obj) { var index = mixinStack.indexOf(obj); var objectsToRemove = []; for(var i = index; i >= 0; i--) { objectsToRemove.pushObject(mixinStack.objectAt(i)); } objectsToRemove.forEach(function(item) { mixinStack.removeObject(item); }); } if (mixinStack.get('length') > 0) { this.set('mixinDetails.model', mixinStack.get('lastObject')); } else { this.set('mixinDetails.model', null); } } });
// Second function function mySecondFunction(number1, number2){ return number1 + number2; }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M17 4.14V2h-3v2h-4V2H7v2.14c-1.72.45-3 2-3 3.86v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8c0-1.86-1.28-3.41-3-3.86zM18 20H6V8c0-1.1.9-2 2-2h8c1.1 0 2 .9 2 2v12zm-1.5-8v4h-2v-2h-7v-2h9z" /> , 'BackpackOutlined');
Class('TemplatesModel', { views: { empty: { name: 'empty', label: 'Empty' }, ListView: { name: 'ListView', label: 'List View', subviews: ['ListItemView'] } } });
const filter = require('./filter') module.exports = (collection, test, callback) => { return filter(collection, function(value, index, collection) { return !test(value, index, collection) }, callback) }
window.ww = window.innerWidth ? window.innerWidth: $(window).width(); window.wh = window.innerHeight ? window.innerHeight: $(window).height(); $(window).on('resize', function(){ window.ww = window.innerWidth ? window.innerWidth: $(window).width(); window.wh = window.innerHeight ? window.innerHeight: $(window).height(); });
const express = require('express'); const libxmljs = require('libxmljs'); express().get('/some/path', function(req) { // OK: libxml does not expand entities by default libxmljs.parseXml(req.param("some-xml")); });
/** * @author mrdoob / http://mrdoob.com/ * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as */ THREE.OAMesh = function ( geometry, material ) { THREE.Mesh.call( this, geometry, material ); this.oa = { type: "", depth: 0 }; return 0; }; THREE.OAMesh.prototype = Object.create( THREE.Mesh.prototype );
/** * @class Li */ /** * DOM utility methods */ (function (factory) { if (typeof define === "function" && define.amd) { define(['./lithium', 'jquery'], factory); } else if (typeof exports === 'object') { //For NodeJS module.exports = factory(require('./lithium'), require('jquery-node')); } else { //global factory(window.Li, jQuery); } }(function (Li, $) { Li.mix(Li, { /** * Given a DOM node, this method finds the next tag/node that would appear in the dom. * WARNING: Do not remove or add nodes while traversing, because it could cause the traversal logic to go crazy. * @param node Could be a any node (element node or text node) * @param ancestor Node An ancestorial element that can be used to limit the search. * The search algorithm, while traversing the ancestorial heirarcy, will not go past/above this element. * @param {function} callback A callback called on each element traversed. * * callback gets following parameters: * node: Current node being traversed. * isOpenTag: boolean. On true, node would be the next open tag/node that one would find when going * linearly downwards through the DOM. Filtering with isOpenTag=true, one would get exactly what native TreeWalker does. * Similarly isOpenTag=false when a close tag is encountered when traversing the DOM. AFAIK TreeWalker doesn't give this info. * * callback can return one of the following values (with their meanings): * 'halt': Stops immediately and returns null. * 'return': Halts and returns node. * 'continue': Skips further traversal of current node (i.e won't traverse it's child nodes). * 'break': Skips all sibling elements of current node and goes to it's parent node. * * relation: The relation compared to the previously traversed node. * @param {Object} [scope] Value of 'this' keyword within callback * @method traverse */ traverse: function (node, ancestor, callback, scope) { //if node = ancestor, we still can traverse it's child nodes if (!node) { return null; } var isOpenTag = true, ret = null; do { if (ret === 'halt') { return null; } if (isOpenTag && node.firstChild && !ret) { node = node.firstChild; //isOpenTag = true; ret = callback.call(scope, node, true, 'firstChild'); } else { if (isOpenTag) { // close open tag first callback.call(scope, node, false, 'current'); } if (node.nextSibling && node !== ancestor && ret !== 'break') { node = node.nextSibling; isOpenTag = true; ret = callback.call(scope, node, true, 'nextSibling'); } else if (node.parentNode && node !== ancestor) { //Traverse up the dom till you find an element with nextSibling node = node.parentNode; isOpenTag = false; ret = callback.call(scope, node, false, 'parentNode'); } else { node = null; } } } while (node && ret !== 'return'); return node || null; }, /** * Converts DOM to HTML string * @param {DocumentFragment} frag * @return {String} * @method toHTML */ toHTML: (function () { function unwrap(str) { var o = {}; str.split(',').forEach(function (val) { o[val] = true; }); return o; } var voidTags = unwrap('area,base,basefont,br,col,command,embed,frame,hr,img,input,keygen,link,meta,param,source,track,wbr'); return function (frag) { var html = ''; Li.traverse(frag, frag, function (node, isOpenTag) { if (node.nodeType === 1) { var tag = node.nodeName.toLowerCase(); if (isOpenTag) { html += '<' + tag; Li.slice(node.attributes).forEach(function (attr) { html += ' ' + attr.name + '="' + attr.value.replace(/"/g, '&quot;') + '"'; }); html += (voidTags[tag] ? '/>' : '>'); } else if (!voidTags[tag]) { html += '</' + tag + '>'; } } if (isOpenTag && node.nodeType === 3) { var text = node.nodeValue || ''; //escape <,> and &. Except text node inside script or style tag. if (!(/^(?:script|style)$/i).test(node.parentNode.nodeName)) { text = text.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;"); } html += text; } if (isOpenTag && node.nodeType === 8) { html += '<!-- ' + node.data.trim() + ' -->'; } }, this); return html; }; }()), /** * jQuery's index() method doesn't return the child index properly for non-element nodes (like text node, comment). * @method childIndex */ childIndex: function (node) { return Li.slice(node.parentNode.childNodes).indexOf(node); } }); return Li; }));
var React = require('react'); var Firebase = require('firebase'); var Game = require('../../game.js'); var FirebaseIntegration = require('../../firebase-integration'); var GameContainer = require('../game-container/game-container'); //var gameListRef = new Firebase("https://blazing-inferno-190.firebaseio.com/-JqBmJEqKYiHdKFW8xg_/games/"); var gameListRef = new Firebase( FirebaseIntegration.getGamesPath() ); var GameList = React.createClass({ getInitialState: function() { return {}; }, componentDidMount: function() { var component = this; gameListRef.on('value', function(snapshot) { component.setState(snapshot.val()); }); }, createGame: function() { gameListRef.push(new Game().data); }, render: function() { var games = Object.keys(this.state).map(function (gameId, index) { return ( <GameContainer key={index} gameId={gameId}/> ); }, this); return ( <div> {games} <button onClick={this.createGame}>Create Game</button> </div> ); } }); module.exports = GameList;
"use strict"; var responsive_window_1 = require("./responsive-window"); exports.ResponsiveWindow = responsive_window_1.ResponsiveWindow; exports.RESPONSIVEWINDOW_DIRECTIVE = [ responsive_window_1.ResponsiveWindow ]; //# sourceMappingURL=index.js.map
import {keccak256, bufferToHex} from "ethereumjs-util" import MerkleTree from "../../utils/merkleTree" import Fixture from "./helpers/Fixture" import {web3, ethers} from "hardhat" import chai, {expect, assert} from "chai" import {solidity} from "ethereum-waffle" chai.use(solidity) describe("MerkleSnapshot", () => { let fixture let merkleSnapshot let signers before(async () => { signers = await ethers.getSigners() fixture = new Fixture(web3) await fixture.deploy() const merkleFac = await ethers.getContractFactory("MerkleSnapshot") merkleSnapshot = await merkleFac.deploy(fixture.controller.address) }) beforeEach(async () => { await fixture.setUp() }) afterEach(async () => { await fixture.tearDown() }) describe("setSnapshot", () => { it("reverts when caller is not controller owner", async () => { expect( merkleSnapshot .connect(signers[1]) .setSnapshot( ethers.utils.formatBytes32String("1"), ethers.utils.formatBytes32String("helloworld") ) ).to.be.revertedWith("caller must be Controller owner") }) it("sets a snapshot root for an snapshot ID", async () => { const id = ethers.utils.formatBytes32String("1") const root = ethers.utils.formatBytes32String("helloworld") await merkleSnapshot.setSnapshot(id, root) assert.equal(await merkleSnapshot.snapshot(id), root) }) }) describe("verify", () => { let leaves let tree const id = bufferToHex(keccak256("LIP-52")) before(async () => { leaves = ["a", "b", "c", "d"] tree = new MerkleTree(leaves) await merkleSnapshot.setSnapshot(id, tree.getHexRoot()) }) it("returns false when a proof is invalid", async () => { const badLeaves = ["d", "e", "f"] const badTree = new MerkleTree(badLeaves) const badProof = badTree.getHexProof(badLeaves[0]) const leaf = bufferToHex(keccak256(leaves[0])) assert.isFalse(await merkleSnapshot.verify(id, badProof, leaf)) }) it("returns false when leaf is not in the tree", async () => { const proof = tree.getHexProof(leaves[0]) const leaf = bufferToHex(keccak256("x")) assert.isFalse(await merkleSnapshot.verify(id, proof, leaf)) }) it("returns false when a proof is of invalid length", async () => { let proof = tree.getHexProof(leaves[0]) proof = proof.slice(0, proof.length - 1) const leaf = bufferToHex(keccak256(leaves[0])) assert.isFalse(await merkleSnapshot.verify(id, proof, leaf)) }) it("returns true when a proof is valid", async () => { const proof = tree.getHexProof(leaves[0]) const leaf = bufferToHex(keccak256(leaves[0])) assert.isTrue(await merkleSnapshot.verify(id, proof, leaf)) }) }) })
export { default } from "./../../_gen/openfl/events/IOErrorEvent";
/* Threesixty.prototype.getRow = function(index){ var perRow = this.perRow; var rowsCount = Math.round(this.source.length/perRow); var result = []; if(index<rowsCount-1){ result = this.source.slice(index*perRow, (index*perRow)+perRow); } return result; } */
'use strict'; // Setting up route angular.module('prints').config(['$stateProvider', function($stateProvider) { $stateProvider. state('listPrints', { url: '/prints', templateUrl: 'modules/prints/views/print-client-list.html' }); } ]);
import { expect } from 'chai'; import * as types from '../../app/js/utils/actionTypes'; import { changeLanguage } from '../../app/js/actions/app'; describe('App action', () => { it('changes language on the parameter passed', () => { const lang = 'en'; const expectedAction = { type: types.LANGUAGE, payload: lang, }; expect(changeLanguage(lang)).to.deep.equal(expectedAction); }) });
version https://git-lfs.github.com/spec/v1 oid sha256:277086ec0fb49c6da22640a41bd9d52e5e3503cc15ae358cd76662b81439df83 size 10713
version https://git-lfs.github.com/spec/v1 oid sha256:22a8f31fdc015cfce492a52529a1c36e39643310cec60a6331d4a428ac8a4db6 size 5099
var Exo = require('exoskeleton'); var Profile = Exo.Model.extend({ url: "/api/me", initialize: function(){ this.transformData(); this.on('change', this.transformData.bind(this)); }, transformData: function(){ this.name = this.get('displayName') || '@' + this.get('gh_username'); } }) module.exports = new Profile();
/* global Me */ function Grid(c, r) { console.log('New grid', c, r); this.cells = []; this.c = c; this.r = r; // init cells: this.empty(); this.chain = /((?!00)\d{1,2}.)\1{2,9}/g; } Grid.prototype = { get: function(x, y) { if ((x < 0 || x >= this.c) || (y < 0 || y >= this.r)) return 1; else return this.cells[y][x] * 1; }, set: function(x, y, value) { /* if ((x < 0 || x >= this.c) || (y < 0 || y >= this.r)) return 1; */ this.cells[y][x] = value < 10 ? '0' + value: value + ''; }, del: function(x, y) { this.cells[y][x] = '00'; }, empty: function(data) { data = data || this.cells; for (var j = 0; j < this.r; j++) { data[j] = []; for (var k = 0; k < this.c; k++) { data[j][k] = '00'; } } }, _isChainAllowed: function(chain) { var tk = chain.replace('.', '') * 1; return Me.g.indexOf(tk) === -1; }, getChain: function() { var r = null; var rslt = null; var t = ''; var lm = 0; var i, j = 0; var chain = []; this.empty(chain); // horizontal for (j = 0; j < this.r; j++) { r = this.cells[j]; t = r.join('.') + '.'; while ((rslt = this.chain.exec(t)) !== null) { if (this._isChainAllowed(rslt[1])) { lm = rslt[0].match(/\./g).length; // how many cells founds: for (i = 0; i < lm; i++) { chain[j][i + rslt.index / 3] = 1; } } } } try { // vertical for (i = 0; i < this.c; i++) { t = ''; for (j = 0; j < this.r; j++) { t += this.cells[j][i] + '.'; } while ((rslt = this.chain.exec(t)) !== null) { if (this._isChainAllowed(rslt[1])) { lm = rslt[0].match(/\./g).length; // how many cells founds: for (j = 0; j < lm; j++) { chain[j + rslt.index / 3][i] = 1; } } } } } catch (e) { console.log(e); } /* // diagonal var l = this.c * this.r; for (i = 0; i < l; i++) { var c = i; j = this.r - 1; t = ''; while (j >= 0 && c >= 0) { var st = this.cells[j][c]; if (st === undefined) st = 0; t += st + '.'; j--; c--; } while ((rslt = this.chain.exec(t)) !== null) { lm = rslt[0].match(/\./g).length; // how many cells founds: r = (this.r - 1) - rslt.index / 2; c = i - rslt.index / 2; for (j = 0; j < lm; j++) { chain[r][c] = 1; r--; c--; } } } */ return chain; } };
var app = new Vue({ el: '#app', data: { message: 'Kevin W. Palmer, South Florida, firstnameMiddleInitialLastname@gmail.com' } });
"use strict"; var test = require("tap").test; var semver = require("semver"); var VError = require("verror"); var nock = require("nock"); var Raygun = require("../lib/raygun.ts"); nock(/.*/) .post(/.*/, function () { return true; }) .reply(202, {}) .persist(); var API_KEY = "apikey"; test("send basic", {}, function (t) { t.plan(1); if (semver.satisfies(process.version, "=0.10")) { t.pass("Ignored on node 0.10"); t.end(); return; } var client = new Raygun.Client().init({ apiKey: API_KEY, }); client.send(new Error(), {}, function (response) { t.equal(response.statusCode, 202); t.end(); }); }); test("send complex", {}, function (t) { t.plan(1); if (semver.satisfies(process.version, "=0.10")) { t.pass("Ignored on node 0.10"); t.end(); return; } var client = new Raygun.Client() .init({ apiKey: API_KEY }) .setUser("callum@mindscape.co.nz") .setVersion("1.0.0.0"); client.send(new Error(), {}, function (response) { t.equal(response.statusCode, 202); t.end(); }); }); test("send with inner error", {}, function (t) { t.plan(1); if (semver.satisfies(process.version, "=0.10")) { t.pass("Ignored on node 0.10"); t.end(); return; } var error = new Error("Outer"); var innerError = new Error("Inner"); error.cause = function () { return innerError; }; var client = new Raygun.Client().init({ apiKey: API_KEY, }); client.send(error, {}, function (response) { t.equal(response.statusCode, 202); t.end(); }); }); test("send with verror", {}, function (t) { t.plan(1); if (semver.satisfies(process.version, "=0.10")) { t.pass("Ignored on node 0.10"); t.end(); return; } var error = new VError( new VError(new VError("Deep Error"), "Inner Error"), "Outer Error" ); var client = new Raygun.Client().init({ apiKey: API_KEY, }); client.send(error, {}, function (response) { t.equal(response.statusCode, 202); t.end(); }); }); test("send with OnBeforeSend", {}, function (t) { t.plan(1); if (semver.satisfies(process.version, "=0.10")) { t.pass("Ignored on node 0.10"); t.end(); return; } var client = new Raygun.Client().init({ apiKey: API_KEY, }); var onBeforeSendCalled = false; client.onBeforeSend(function (payload) { onBeforeSendCalled = true; return payload; }); client.send(new Error(), {}, function () { t.equal(onBeforeSendCalled, true); t.end(); }); }); test("send with expressHandler custom data", function (t) { t.plan(1); var client = new Raygun.Client().init({ apiKey: API_KEY, }); client.expressCustomData = function () { return { test: "data" }; }; client._send = client.send; client.send = function (err, data) { client.send = client._send; t.equal(data.test, "data"); t.end(); }; client.expressHandler(new Error(), {}, {}, function () {}); }); test("check that tags get passed through", {}, function (t) { var tag = ["Test"]; var client = new Raygun.Client().init({ apiKey: "TEST" }); client.setTags(tag); client.onBeforeSend(function (payload) { t.same(payload.details.tags, tag); return payload; }); client.send(new Error(), {}, function () { t.end(); }); }); test("check that tags get merged", {}, function (t) { var client = new Raygun.Client().init({ apiKey: "TEST" }); client.setTags(["Tag1"]); client.onBeforeSend(function (payload) { t.same(payload.details.tags, ["Tag1", "Tag2"]); return payload; }); client.send( new Error(), {}, function () { t.end(); }, null, ["Tag2"] ); });
var q = require('q'); var _ = require('lodash'); var moment = require('moment'); var trello = require('../libs/trello_client'); var ORGANIZATIONS = [ { id: '4ffb85c372c8548a030144e5', name: 'HuaJiao' }, { id: '4ffb861572c8548a03015a66', name: 'Asimov' }, { id: '544765a39570e08b7e6aeccb', name: 'NextTao' }, ]; var NEXTTAO = { id: '544765a39570e08b7e6aeccb', name: 'NextTao' }; var SCRUM_NAMES = [ 'Features', 'Bugs', 'Upcoming', 'Today', 'Re-Open', 'Close', ]; function _mapListIds(lists) { return _.reduce(lists, function (memo, next) { memo[next.name] = next.id; return memo; }, {}); } function _summarizeBoard(brd) { var d = q.defer(); q .all([trello.getCardsOfBoard(brd.id), trello.getListsOfBoard(brd.id)]) .spread(function (cards, lists) { var aggregated = _.groupBy(cards, 'idList'); var mapping = _mapListIds(lists); var result = _.map(SCRUM_NAMES, function (name) { var listId = mapping[name]; var cards = aggregated[listId]; if (cards) { return name + ": " + cards.length; } else { return name + ": 0"; } }); d.resolve('# ' + brd.name + '\n' + result.join(', ')) }) .fail(function (error) { d.reject(error); }) .done(); return d.promise; } function _summarizeOrg(org, msg) { trello.getOpenBoardsOfOrg(org.id) .then(function (boards) { var results = _.map(boards, function (brd) { return _summarizeBoard(brd); }) return q.all(results); }) .then(function (results) { msg.send([ org.name, '----------------', results.join('\n'), ].join('\n')); }) .fail(function (error) { console.log(error); }) .done(); } function _weeklyBoard(board) { var d = q.defer(); trello.activeCards(board.id, -7) .then(function (cards) { var text = [ board.name, '----------------', _.map(cards, function (c) { return [ c.list.name, c.name, c.updated ].join(' '); }).join('\n') ].join('\n'); d.resolve(text); }) .fail() .done(); return d.promise; } function _weeklyOrg(org, msg) { trello.getOpenBoardsOfOrg(org.id) .then(function (boards) { var results = _.map(boards, function (brd) { return _weeklyBoard(brd); }) return q.all(results); }) .then(function (results) { _.each(results, function (r) { msg.send(r); }) }) .fail() .done(); } module.exports = { summary: function (msg) { _.each(ORGANIZATIONS, function (org) { _summarizeOrg(org, msg); }); }, weekly: function (msg) { msg.send('// working on the weekly report of ' + NEXTTAO.name); _weeklyOrg(NEXTTAO, msg); } };
// !LOCNS:live_game var model; var handlers = {}; $(document).ready(function () { function HeaderViewModel() { var self = this; self.active = ko.observable(true); self.setup = function () { $(window).focus(function() { self.active(true); }); $(window).blur(function() { self.active(false); }); }; } model = new HeaderViewModel(); // inject per scene mods if (scene_mod_list['live_game_header']) loadMods(scene_mod_list['live_game_header']); // setup send/recv messages and signals app.registerWithCoherent(model, handlers); // Activates knockout.js ko.applyBindings(model); // run start up logic model.setup(); });
alert("alert2.js")
/** * App Dispatcher * Extends Facebook's Flux Dispatcher */ 'use strict'; var Dispatcher = require('flux').Dispatcher; var AppDispatcher = new Dispatcher(); module.exports = AppDispatcher;
var Mesh = require('../../lib/mesh'); var config = { name: 'remoteMesh', dataLayer: { port: 3001, authTokenSecret: 'a256a2fd43bf441483c5177fc85fd9d3', systemSecret: 'mesh', secure: true, adminPassword: 'guessme', }, endpoints: {}, modules: { "remoteComponent": { path: __dirname + "/4-remote-component", constructor: { type: "sync", parameters: [] } } }, components: { "remoteComponent": { moduleName: "remoteComponent", schema: { "exclusive": false, "methods": { "remoteFunction": { parameters: [ {name: 'one', required: true}, {name: 'two', required: true}, {name: 'three', required: true}, {name: 'callback', type: 'callback', required: true} ] } , "causeError": { parameters: [ {name: 'callback', type: 'callback', required: true} ] } } } } } }; (new Mesh()).initialize(config, function (err) { if (err) { console.log(err); process.exit(err.code || 1); return; } console.log('READY'); });
var struct_h5_t_l_1_1adapt_3_01_t[_n]_4 = [ [ "allocate_return", "struct_h5_t_l_1_1adapt_3_01_t[_n]_4.html#a0b70e9265935053f7cd15dd9ae47b5e9", null ], [ "const_data_return", "struct_h5_t_l_1_1adapt_3_01_t[_n]_4.html#aa26ab555a2c6ae40181e9212b292e3df", null ], [ "data_return", "struct_h5_t_l_1_1adapt_3_01_t[_n]_4.html#a255473fbedaa64738ad99c1b2b4e9f33", null ], [ "data_t", "struct_h5_t_l_1_1adapt_3_01_t[_n]_4.html#af9933a1521aecd615759226aab22fc60", null ], [ "dtype_return", "struct_h5_t_l_1_1adapt_3_01_t[_n]_4.html#a796cb13cf8219e0bef087b366e33be18", null ] ];
import React, { Component } from 'react'; import { YsideBar, YrightBar } from 'yrui'; import { rightbarTabs, rightbarTabLists, projectList } from '../../models/models'; let userInfo = { logo: require('../../styles/images/usr.jpg'), name: 'test', email: 'test@test.com' }; export default class Yaside extends Component { constructor(props) { super(props); }; render() { return ( <aside> <YsideBar menu={this.props.sideBarMenu} projectList={true} userInfo={true} /> <YrightBar tabs={rightbarTabs} tabList={rightbarTabLists} /> </aside> ); } }
/* jshint browser: true */ /* global $ */ "use strict"; var formField = require("../ui/utils/form-field.js"); module.exports = function(core, config, store) { function addBanMenu(from, menu, next) { var room = store.get("nav", "room"), rel = store.getRelation(), senderRelation = store.getRelation(room, from), senderRole, senderTransitionRole; senderRelation = senderRelation ? senderRelation : {}; senderRole = senderRelation.role ? senderRelation.role : "none"; senderTransitionRole = senderRelation.transitionRole ? senderRelation.transitionRole : "none"; if (/^guest-/.test(from)) senderRole = "guest"; switch (senderRole) { case "follower": case "none": case "moderator": case "registered": if (senderRole === "moderator" && rel.role !== "owner") break; menu.items.banuser = { prio: 550, text: "Ban user", action: function() { core.emit("expel-up", { to: room, ref: from, role: "banned", transitionRole: senderRole, transitionType: null }); } }; break; case "banned": menu.items.unbanuser = { prio: 550, text: "unban user", action: function() { core.emit("admit-up", { to: room, ref: from, role: senderTransitionRole || "follower" }); } }; break; case "owner": case "guest": break; } next(); } core.on("conf-show", function(tabs, next) { var room = tabs.room, antiAbuse, $div; room.params = room.params || {}; antiAbuse = room.params.antiAbuse = room.params.antiAbuse || {}; antiAbuse.block = antiAbuse.block || { english: false }; antiAbuse.customPhrases = antiAbuse.customPhrases || []; if (typeof antiAbuse.spam !== "boolean") { antiAbuse.spam = true; } $div = $("<div>").append( formField("Spam control", "toggle", "spam-control", antiAbuse.spam), formField("Blocked words list", "check", "blocklists", [ ["list-en-strict", "English abusive words", antiAbuse.block.english] ]), formField("Custom blocked phrases/word", "area", "block-custom", antiAbuse.customPhrases.join("\n")), formField("", "info", "spam-control-helper-text", "One phrase/word each line") ); tabs.spam = { text: "Spam control", html: $div }; next(); }, 600); core.on("conf-save", function(room, next) { room.params = room.params || {}; room.params.antiAbuse = { spam: $("#spam-control").is(":checked"), block: { english: $("#list-en-strict").is(":checked") }, customPhrases: $("#block-custom").val().split("\n").map(function(item) { return (item.trim()).toLowerCase(); }) }; next(); }, 500); core.on("text-menu", function(menu, next) { var textObj = menu.textObj, room = store.get("nav", "room"), rel = store.getRelation(); if (!(rel && (/(owner|moderator|su)/).test(rel.role) && textObj)) { return next(); } if (textObj.tags && textObj.tags.indexOf("hidden") > -1) { menu.items.unhidemessage = { prio: 500, text: "Unhide message", action: function() { var tags = Array.isArray(textObj.tags) ? textObj.tags.slice(0) : []; core.emit("edit-up", { to: room, ref: textObj.id, tags: tags.filter(function(t) { return t !== "hidden"; }) }); } }; } else { menu.items.hidemessage = { prio: 500, text: "Hide message", action: function() { var tags = Array.isArray(textObj.tags) ? textObj.tags.slice(0) : []; tags.push("hidden"); core.emit("edit-up", { to: room, ref: textObj.id, tags: tags }); } }; } addBanMenu(textObj.from, menu, next); }, 500); core.on("people-menu", function(menu, next) { var rel = store.getRelation(); if (!(rel && (/(owner|moderator|su)/).test(rel.role))) { return next(); } addBanMenu(menu.user.id, menu, next); }, 500); core.on("thread-menu", function(menu, next) { var threadObj = menu.threadObj, room = store.get("nav", "room"), rel = store.getRelation(); if (!(rel && (/(owner|moderator)/).test(rel.role) && threadObj)) { return next(); } if (threadObj.tags && threadObj.tags.indexOf("thread-hidden") > -1) { menu.items.unhidethread = { prio: 500, text: "Unhide discussion", action: function() { var tags = Array.isArray(threadObj.tags) ? threadObj.tags.slice(0) : []; core.emit("edit-up", { to: room, ref: threadObj.id, tags: tags.filter(function(t) { return t !== "thread-hidden"; }), color: threadObj.color // Ugly hack around lack of color info on a discussion }); } }; } else { menu.items.hidethread = { prio: 500, text: "Hide discussion", action: function() { var tags = Array.isArray(threadObj.tags) ? threadObj.tags.slice(0) : []; tags.push("thread-hidden"); core.emit("edit-up", { to: room, ref: threadObj.id, tags: tags, color: threadObj.color }); } }; } next(); }, 500); };
import { App } from "./nwGui"; import Process from "./process"; App.removeAllListeners( "open" ); export default App; export const argv = App.argv; export const filteredArgv = App.filteredArgv; export const manifest = App.manifest; export function quit() { try { // manually emit the process's exit event Process.emit( "exit" ); } catch ( e ) {} App.quit(); }
"use strict"; var WrapperBuilder = require("thunkify-object").WrapperBuilder; var Db = require("./Db").Db; function wrapDb (db) { return new Db(db); } exports.MongoClient = new WrapperBuilder() .add("connect", {transformations: {1: wrapDb} }) .getWrapper();
/* jshint expr:true */ import { expect } from 'chai'; import { describeComponent, it } from 'ember-mocha'; import hbs from 'htmlbars-inline-precompile'; describeComponent( 'techno-date-cell', 'Integration: TechnoDateCellComponent', { integration: true }, function() { it('renders', function() { this.set('date', new Date("1/1/1925")); this.render(hbs`{{techno-date-cell value=date}}`); expect(this.$()).to.have.length(1); expect(this.$().find('td')).to.have.length(1); expect(this.$().find('td:contains("1/1/1925")')).to.have.length(1); }); } );
/*! * Cooki v1.0.0 * http://k-legrand.fr * * Copyright 2014 Contributors * Released under the MIT license * https://github.com/Manoz/Cooki/blob/master/LICENSE */ /*! * Your website scripts below */
/*jslint node: true */ /*global module, require*/ 'use strict'; var subjectType = require('./type'); var subjectValue = require('./value'); /** * Given the parts of speech, this returns an subjects type & value. * @param {Object} parts The parts of speech. * @return {Object} The parsed subjects type & value. */ module.exports = function subject(parts) { return { type: subjectType(parts), value: subjectValue(parts) }; };
/** * Sample content to test the concat and minify grunt plugins. */ function sampleA() { 'use strict'; window.console.log("Sample A"); } sampleA(); /** * Sample content to test the concat and minify grunt plugins. */ function sampleB() { 'use strict'; window.console.log("Sample B"); } sampleB();
'use strict'; describe('Service: header', function () { // load the service's module beforeEach(module('musicyaoBackendApp')); // instantiate service var header; beforeEach(inject(function (_header_) { header = _header_; })); it('should do something', function () { expect(!!header).toBe(true); }); });
var Q = require('q'); var uuid = require('uuid'); var crypto = require('../../../../crypto/crypto'); function Connect() { } var connect = new Connect(); module.exports = connect; Connect.prototype.init = function(letter, handler) { console.log(letter); var deferred = Q.defer(); var back_letter = { signature: letter.signature, directive: { connect: { init: null } } }; deferred.resolve(back_letter); return deferred.promise; }; Connect.prototype.crypto = function(letter, handler) { let deferred = Q.defer(); let public_str = letter.crypto.public_str; // 使用uuid 作为密码 // let secret = uuid.v4(); let secret = '12345678'; let encryptSecret = crypto.publicEncrypt(public_str, secret); let json = encryptSecret.toJSON(); console.log('密码为:'); console.log(secret); // console.log(encryptSecret.toString()); letter.crypto.encryptSecret = JSON.stringify(encryptSecret.toJSON()); deferred.resolve(letter); setTimeout(function() { handler.crypto = true; handler.encryptSecret = secret; let letter = { directive: { test: null } }; letter = JSON.stringify(letter); letter = crypto.cipher(letter, secret); handler.evenEmitter.emit('letter', letter); }, 5000); return deferred.promise; };
let EventEmitter = require('events').EventEmitter; let telecom; describe("Interface Unit Tests", function () { it('should create a new interface', function () { telecom = new Telecom(); expect(telecom).to.be.an.instanceOf(EventEmitter); expect(telecom).to.have.property('parallelize'); expect(telecom).to.have.property('pipeline'); expect(telecom).to.have.property('isMaster', true); }); it('should return bundled interfaces', function () { expect(telecom.interfaces).to.be.an.Object; expect(telecom.interfaces).to.have.property('TCP'); }); it('should create a new pipeline', function () { let intf = new telecom.interfaces.TCP(8000); expect(intf).to.be.an.instanceOf(Interface); let pipeline = telecom.pipeline(intf); expect(pipeline).to.be.an.instanceOf(Pipeline); }); });
// Copyright 2015-2018 FormBucket LLC // ISURL returns true when the value matches the regex for a uniform resource locator. export default function isurl(str) { // credit: http://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-an-url var pattern = new RegExp( "^(https?:\\/\\/)?" + // protocol "((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|" + // domain name "((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address "(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path "(\\?[;&a-z\\d%_.~+=-]*)?" + // query string "(\\#[-a-z\\d_]*)?$", "i" ); // fragment locator return pattern.test(str); }
/* MIT License Copyright (c) 2016 Christian Rafael JS Object to CSS String Parser christian@paradix.com.br */ function parseCSS( object_css ) { function parseClass( _class, properties ) { return String().concat( _class, " { ", parseProperties( properties ), " } " ); } function parseProperties( properties ) { var css_properties = String(); for (var prop in properties) { css_properties = css_properties.concat( typeof properties[ prop ] === "object" && parseClass( prop, properties[ prop ] ) || String().concat( prop, " : ", properties[ prop ] ), typeof properties[ prop ] !== "object" && ";" || "" ); } return css_properties; } var css_str = String(); for ( var _class in object_css ) { css_str = css_str.concat( parseClass( _class, object_css[ _class ] ) ); } return css_str; }
'use strict'; const fetchUrl = require('./fetchUrl'); /** * @param {Function} fetch - fetch API compatible function * @param {string} source * @param {Object} [fetchOptions={}] * @returns {Promise.<DefinitionProvider>} */ function urlProviderFactory (fetch, source, fetchOptions = {}) { let urlProvider = source; if (typeof source === 'string') { urlProvider = () => source; } /** * @param {Function} [callback] */ return (progressCallback) => { const deferredUrls = urlProvider(); return Promise.resolve(deferredUrls) .then((oneOrMoreUrls) => { if (typeof oneOrMoreUrls === 'object') { const result = { null: {} }; return Object.keys(oneOrMoreUrls).reduce((prev, key) => prev.then(() => { const url = oneOrMoreUrls[key]; return fetchUrl(fetch, url, fetchOptions).then((urlResult) => { result[key] = urlResult; if (progressCallback) { progressCallback(); } }); }), Promise.resolve()).then(() => result); } else if (typeof oneOrMoreUrls === 'string') { return fetchUrl(fetch, oneOrMoreUrls, fetchOptions) .then(urlResult => ({ null: urlResult })); } throw new Error('Unsupported url type'); }); }; } module.exports = urlProviderFactory;
'use strict'; /** * @ngdoc function * @name yeoprojectApp.controller:MiembrosCtrl * @description * # MiembrosCtrl * Controller of the yeoprojectApp */ angular.module('yeoprojectApp') .controller('MiembrosCtrl', function ($scope,$http,$modal) { $http.get('http://localhost:9000/miembros.json').success(function (data) { $scope.miembros= data; }); $scope.gridOptions={ data:'miembros', showGroupPanel: true, showFilter:true, enableCellSelection: true, enableRowSelection: false, enableCellEdit: true, columnDefs:[ {field:'no', displayName:'Nº.'}, {field:'nombre', displayName:'Nombre'}, {field:'fidelidad', displayName:'Puntos Fidelidad'}, {field:'fechaUnion', displayName:'Fecha de Unión'}, {field:'tipoMiembro', displayName:'Tipo de Miembro'}] }; $scope.showModal=function () { $scope.nuevoMiembro={}; //objeto vacio para almacenar var modalInstance= $modal.open({ templateUrl: 'views/add-miembros.html', controller:'AddNuevoMiembroCtrl', resolve:{ nuevoMiembro: function () { return $scope.nuevoMiembro; } } }); modalInstance.result.then(function(selectedItem){ $scope.miembros.push({ no: $scope.miembros.length + 1, nombre: $scope.nuevoMiembro.nombre, tipoMiembro: $scope.nuevoMiembro.tipoMiembro, fidelidad: $scope.nuevoMiembro.fidelidad, fechaUnion: $scope.nuevoMiembro.fechaUnion }); }); }; }) .controller('AddNuevoMiembroCtrl',function ($scope,$modalInstance,nuevoMiembro) { $scope.nuevoMiembro= nuevoMiembro; $scope.salvarNuevoMiembro=function () { $modalInstance.close(nuevoMiembro); }; $scope.cancel= function () { $modalInstance.dismiss('cancel'); }; });
/// <reference path="jquery-ui-1.10.3.js" /> /// <reference path="jquery-2.0.3.js" /> /// <reference path="jquery.validate.js" /> /// <reference path="jquery.validate.unobtrusive.js" /> /// <reference path="knockout-2.1.0.debug.js" /> /// <reference path="modernizr-2.5.3.js" /> /// <reference path="bootstrap.js"/>
/* 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( 'removeformat', 'sv', { toolbar: 'Radera formatering' } );
(function(DOM, COMPONENT_CLASS) { "use strict"; if ("orientation" in window) return; // skip mobile/tablet browsers // polyfill timeinput for desktop browsers var htmlEl = DOM.find("html"), timeparts = function(str) { str = str.split(":"); if (str.length === 2) { str[0] = parseFloat(str[0]); str[1] = parseFloat(str[1]); } else { str = []; } return str; }, zeropad = function(value) { return ("00" + value).slice(-2) }, ampm = function(pos, neg) { return htmlEl.get("lang") === "en-US" ? pos : neg }, formatISOTime = function(hours, minutes, ampm) { return zeropad(ampm === "PM" ? hours + 12 : hours) + ":" + zeropad(minutes); }; DOM.extend("input[type=time]", { constructor: function() { var timeinput = DOM.create("input[type=hidden name=${name}]", {name: this.get("name")}), ampmspan = DOM.create("span.${c}-meridian>(select>option>{AM}^option>{PM})+span>{AM}", {c: COMPONENT_CLASS}), ampmselect = ampmspan.child(0); this // drop native implementation and clear name attribute .set({type: "text", maxlength: 5, name: null}) .addClass(COMPONENT_CLASS) .on("change", this.onChange.bind(this, timeinput, ampmselect)) .on("keydown", this.onKeydown, ["which", "shiftKey"]) .after(ampmspan, timeinput); ampmselect.on("change", this.onMeridianChange.bind(this, timeinput, ampmselect)); // update value correctly on form reset this.parent("form").on("reset", this.onFormReset.bind(this, timeinput, ampmselect)); // patch set method to update visible input as well timeinput.set = this.onValueChanged.bind(this, timeinput.set, timeinput, ampmselect); // update hidden input value and refresh all visible controls timeinput.set(this.get()).data("defaultValue", timeinput.get()); // update default values to be formatted this.set("defaultValue", this.get()); ampmselect.next().data("defaultValue", ampmselect.get()); if (this.matches(":focus")) timeinput.fire("focus"); }, onValueChanged: function(setter, timeinput, ampmselect) { var parts, hours, minutes; setter.apply(timeinput, Array.prototype.slice.call(arguments, 3)); if (arguments.length === 4) { parts = timeparts(timeinput.get()); hours = parts[0]; minutes = parts[1]; // select appropriate AM/PM ampmselect.child((hours -= 12) > 0 ? 1 : Math.min(hours += 12, 0)).set("selected", true); // update displayed AM/PM ampmselect.next().set(ampmselect.get()); // update visible input value, need to add zero padding to minutes this.set(hours < ampm(13, 24) && minutes < 60 ? hours + ":" + zeropad(minutes) : ""); } return timeinput; }, onKeydown: function(which, shiftKey) { return which === 186 && shiftKey || which < 58; }, onChange: function(timeinput, ampmselect) { var parts = timeparts(this.get()), hours = parts[0], minutes = parts[1], value = ""; if (hours < ampm(13, 24) && minutes < 60) { // refresh hidden input with new value value = formatISOTime(hours, minutes, ampmselect.get()); } else if (parts.length === 2) { // restore previous valid value value = timeinput.get(); } timeinput.set(value); }, onMeridianChange: function(timeinput, ampmselect) { // update displayed AM/PM ampmselect.next().set(ampmselect.get()); // adjust time in hidden input timeinput.set(function(el) { var parts = timeparts(el.get()), hours = parts[0], minutes = parts[1]; if (ampmselect.get() === "AM") hours -= 12; return formatISOTime(hours, minutes, ampmselect.get()); }); }, onFormReset: function(timeinput, ampmselect) { timeinput.set(timeinput.data("defaultValue")); ampmselect.next().set(ampmselect.data("defaultValue")); } }); }(window.DOM, "better-timeinput"));
var app = require('app'); // Module to control application life. var BrowserWindow = require('browser-window'); // Module to create native browser window. // Report crashes to our server. // require('crash-reporter').start(); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is GCed. var mainWindow = null; // Quit when all windows are closed. app.on('window-all-closed', function() { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform != 'darwin') { app.quit(); } }); // Specify flash path. // On Windows, it might be /path/to/pepflashplayer.dll // On Mac, /path/to/PepperFlashPlayer.plugin // On Linux, /path/to/libpepflashplayer.so // app.commandLine.appendSwitch('ppapi-flash-path', '/path/to/libpepflashplayer.so'); app.commandLine.appendSwitch('ppapi-flash-path', '/Applications/Google Chrome.app/Contents/Versions/44.0.2403.125/Google Chrome Framework.framework/Internet Plug-Ins/PepperFlash/PepperFlashPlayer.plugin'); // Specify flash version, for example, v17.0.0.169 app.commandLine.appendSwitch('ppapi-flash-version', '18.0.0.209'); // This method will be called when Electron has finished // initialization and is ready to create browser windows. app.on('ready', function() { // Create the browser window. mainWindow = new BrowserWindow({ 'accept-first-mouse': true, 'always-on-top': true, 'auto-hide-menu-bar': true, 'dark-theme': true, 'frame': false, 'height': 600, 'resizable': true, 'show': false, 'title': 'StreamShell', 'width': 800, 'web-preferences': { 'plugins': true } }); // and load the index.html of the app. mainWindow.loadUrl('file://' + __dirname + '/index.html'); // Emitted when the window is closed. mainWindow.on('closed', function() { // Dereference the window object mainWindow = null; }); // Display the window only once the DOM is ready mainWindow.webContents.on('did-finish-load', function() { setTimeout(function() { mainWindow.show(); // mainWindow.openDevTools({detach: true}); }, 40); }); });
import React from 'react'; import {shallow} from 'enzyme'; import AboutPage from './AboutPage'; describe('<AboutPage />', () => { it('should have a header called \'About\'', () => { const wrapper = shallow(<AboutPage />); const actual = wrapper.find('h2').text(); const expected = 'About'; expect(actual).toEqual(expected); }); it('should have a header with \'alt-header\' class', () => { const wrapper = shallow(<AboutPage />); const actual = wrapper.find('h2').prop('className'); const expected = 'alt-header'; expect(actual).toEqual(expected); }); it('should link to an unknown route path', () => { const wrapper = shallow(<AboutPage />); const actual = wrapper.findWhere(n => n.prop('to') === '/badlink').length; const expected = 1; expect(actual).toEqual(expected); }); });
'use strict'; require('require-dir')('./tasks');
'use strict'; //Games service used for games REST endpoint angular.module('mean.games').factory('Games', ['$resource', function($resource) { return $resource('games/:gameid', { gameid: '@_id' }, { update: { method: 'PUT' } }); } ]);
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @providesModule Array.prototype.es6 * @polyfill * @nolint */ /* eslint-disable no-bitwise, no-extend-native, radix, no-self-compare */ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex function findIndex(predicate, context) { if (this == null) { throw new TypeError( 'Array.prototype.findIndex called on null or undefined' ); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } const list = Object(this); const length = list.length >>> 0; for (let i = 0; i < length; i++) { if (predicate.call(context, list[i], i, list)) { return i; } } return -1; } if (!Array.prototype.findIndex) { Object.defineProperty(Array.prototype, 'findIndex', { enumerable: false, writable: true, configurable: true, value: findIndex, }); } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find if (!Array.prototype.find) { Object.defineProperty(Array.prototype, 'find', { enumerable: false, writable: true, configurable: true, value(predicate, context) { if (this == null) { throw new TypeError('Array.prototype.find called on null or undefined'); } const index = findIndex.call(this, predicate, context); return index === -1 ? undefined : this[index]; }, }); } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes if (!Array.prototype.includes) { Object.defineProperty(Array.prototype, 'includes', { enumerable: false, writable: true, configurable: true, value(searchElement) { const O = Object(this); const len = parseInt(O.length) || 0; if (len === 0) { return false; } const n = parseInt(arguments[1]) || 0; let k; if (n >= 0) { k = n; } else { k = len + n; if (k < 0) { k = 0; } } let currentElement; while (k < len) { currentElement = O[k]; if ( searchElement === currentElement || (searchElement !== searchElement && currentElement !== currentElement) ) { return true; } k++; } return false; }, }); }
//var application = require("application"); //application.mainModule = "main-page"; //application.cssFile = "./app.css"; var map = new Map(); map.set("a", "b"); log(map); application.start(); //var application = new System.Windows.Application(); //application.Run(new System.Windows.Window());
const R = require('aws-response'); const f = require('../contactGetRequests/index'); exports.handler = R(f);
/* 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( 'fakeobjects', 'en-au', { anchor: 'Anchor', flash: 'Flash Animation', hiddenfield: 'Hidden Field', iframe: 'IFrame', unknown: 'Unknown Object' } );
import { domReady, transitionFromClass, transitionToClass, readFileAsText } from '../utils'; import Spinner from './spinner'; import { EventEmitter } from 'events'; export default class MainMenu extends EventEmitter { constructor() { super(); this.allowHide = false; this._spinner = new Spinner(); domReady.then(() => { this.container = document.querySelector('.main-menu'); this._loadFileInput = document.querySelector('.load-file-input'); this._pasteInput = document.querySelector('.paste-input'); this._loadDemoBtn = document.querySelector('.load-demo'); this._loadFileBtn = document.querySelector('.load-file'); this._pasteLabel = document.querySelector('.menu-input'); this._overlay = this.container.querySelector('.overlay'); this._menu = this.container.querySelector('.menu'); document.querySelector('.menu-btn') .addEventListener('click', e => this._onMenuButtonClick(e)); this._overlay.addEventListener('click', e => this._onOverlayClick(e)); this._loadFileBtn.addEventListener('click', e => this._onLoadFileClick(e)); this._loadDemoBtn.addEventListener('click', e => this._onLoadDemoClick(e)); this._loadFileInput.addEventListener('change', e => this._onFileInputChange(e)); this._pasteInput.addEventListener('input', e => this._onTextInputChange(e)); }); } show() { this.container.classList.remove('hidden'); transitionFromClass(this._overlay, 'hidden'); transitionFromClass(this._menu, 'hidden'); } hide() { if (!this.allowHide) return; this.stopSpinner(); this.container.classList.add('hidden'); transitionToClass(this._overlay, 'hidden'); transitionToClass(this._menu, 'hidden'); } stopSpinner() { this._spinner.hide(); } showFilePicker() { this._loadFileInput.click(); } _onOverlayClick(event) { event.preventDefault(); this.hide(); } _onMenuButtonClick(event) { event.preventDefault(); this.show(); } _onTextInputChange(event) { const val = this._pasteInput.value.trim(); if (val.includes('</svg>')) { this._pasteInput.value = ''; this._pasteInput.blur(); this._pasteLabel.appendChild(this._spinner.container); this._spinner.show(); this.emit('svgDataLoad', { data: val, filename: 'image.svg' }); } } _onLoadFileClick(event) { event.preventDefault(); event.target.blur(); this.showFilePicker(); } async _onFileInputChange(event) { const file = this._loadFileInput.files[0]; if (!file) return; this._loadFileBtn.appendChild(this._spinner.container); this._spinner.show(); this.emit('svgDataLoad', { data: await readFileAsText(file), filename: file.name }); } async _onLoadDemoClick(event) { event.preventDefault(); event.target.blur(); this._loadDemoBtn.appendChild(this._spinner.container); this._spinner.show(); try { this.emit('svgDataLoad', { data: await fetch('test-svgs/car-lite.svg').then(r => r.text()), filename: 'car-lite.svg' }); } catch (err) { // This extra scope is working around a babel-minify bug. // It's fixed in Babel 7. { this.stopSpinner(); let error; if ('serviceWorker' in navigator && navigator.serviceWorker.controller) { error = Error("Demo not available offline"); } else { error = Error("Couldn't fetch demo SVG"); } this.emit('error', { error }); } } } }
// Karma configuration // Generated on Fri May 29 2015 12:25:53 GMT-0500 (CDT) 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: ['mocha'], // list of files / patterns to load in the browser files: [ 'src/index.coffee', 'test/test.coffee' ], // 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: { '**/*.coffee': ['coffee'] }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'coverage'], // 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: true }); };
var _ = require('underscore'); var nolp = require('./lib/nolp/nolp.js'); var ups = require('./lib/ups/ups.js'); /** * available delivery services * * @var array of strings * @private */ var availableServices = [ "dhl", "ups" ]; /** * retrieves the status of a package sent with packet delivery service. * * A callback will be called with an tracking object: * * { * // contains the status of the tracking request * // is true on success, false otherwise * // use the issues array for human-readable error messages on failure. * "status": <boolean> * * // contains tracking data to the packet * "data": { * * // flag to sign wether packet has arrived ord not. * "arrived": <boolean>, * * // a string containing the current delivery state (delivery service dependent) * "status": <string>, * * // an array of objects explaining the progress in detail * // there can be zero to Math.Infinity entries here. * "steps": [ * { * "date": <string> // Unix Timestamp * "location": <string> // location of the step * "status": <string> // message * } * ] * }, * * // an array containing strings with problems and errors on failure. * "issues": [ * ] * } * * @param object packet {"service": <string>, "id": <string>} * @param function callback get called with a status object * @returns boolean true on succesful call, false otherwise * @access public * @final */ this.track = function track (packet, callback) { if (typeof packet == "undefined") { console.log("No packet definition given."); return false; } if (typeof packet.id == "undefined") { console.log("No packet id given."); return false; } if (typeof packet.service != "string") { console.log("No packet service given."); return false; } if (!this.isAvailableService(packet.service)) { console.log("Delivery service " + packet.service + " is not available."); return false; } if (typeof callback != "function") { console.log("No callback function given."); return false; } var deliveryService = getDeliveryService(packet.service); deliveryService.get(packet.id, function (error, page) { if (error !== null) { callback({ "status": false, "data": { // no data sadly :( }, "issues": [ "Could not retrieve status page." ] }); return; } deliveryService.parse(page, function (error, track) { if (error !== null) { callback({ "status": false, "data": { // no data sadly :( }, "issues": [ "Could not parse status page." ] }); return; } deliveryService.normalize(track, function (error, model) { if (error !== null) { callback({ "status": false, "data": { // no data sadly :( }, "issues": [ "Could not normalize parsed data." ] }); return; } callback({ "status": true, "data": model, "issues": [ // no issues \o/ ] }); }); }); }); return true; }; /** * checks if service is available. * * @param string service name of service * @return boolean * @access public * @final */ this.isAvailableService = function isAvailableService (service) { if (typeof service == "undefined") { return false; } if (_.indexOf(availableServices, service) === -1) { return false; } return true; } /** * gives the delivery service * * @param string serviceName name of delivery service * @return controller|null іf serviceName could not map * @access private * @final */ function getDeliveryService (serviceName) { switch (serviceName) { case "dhl": return nolp; case "ups": return ups; } return null; }
import './Text1';
var Shapes; (function (Shapes) { var Polygons; (function (Polygons) { var Triangle = (function () { function Triangle() { } return Triangle; })(); Polygons.Triangle = Triangle; var Square = (function () { function Square() { } return Square; })(); Polygons.Square = Square; })(Polygons = Shapes.Polygons || (Shapes.Polygons = {})); })(Shapes || (Shapes = {})); var polygons = Shapes.Polygons; var sq = new polygons.Square();
var assert = require('assert'), _ = require('underscore'), request = require('request'), config = require('../../config/'), apiHost = 'http://localhost:' + config.port + '/api'; describe('api', function () { describe('users', function () { // assuming that there are // 200+ testing records describe('finds list', function () { var url = apiHost + '/users'; it('with offset/limit', function (done) { request(url, { qs: { offset: 50, limit: 5 } }, function (err, res, json) { var users = JSON.parse(json); assert.equal(users.length, 5); done(); }); }); it('with page/limit', function (done) { request(url, { qs: { page: 3, limit: 7 } }, function (err, res, json) { var users = JSON.parse(json); assert.equal(users.length, 7); done(); }); }); }); describe('finds one', function () { it('that exists', function (done) { var url = apiHost + '/users/2'; request(url, function (err, res, json) { var user = JSON.parse(json); assert.equal(user.id, 2); done(); }); }); it('that does not exist', function (done) { var url = apiHost + '/users/-1'; request(url, function (err, res, json) { var error = JSON.parse(json) assert.ok(error.request); assert.ok(error.errCode); assert.ok(error.errMsg); done(); }); }); }); }); });
angular.module('gitphaser').controller('ProfileController', ProfileCtrl); /** * @ngdoc object * @module gitphaser * @name gitphaser.object:ProfileCtrl * @description Exposes GitHub.me profile object or account object to the profile template. * Governs the `/tab/profile` and `others/:username` routes. */ function ProfileCtrl ($scope, $stateParams, $state, $cordovaInAppBrowser, GitHub, account) { var self = this; self.browser = $cordovaInAppBrowser; /** * @ngdoc object * @propertyOf gitphaser.object:ProfileCtrl * @name gitphaser..object:ProfileCtrl.modalOpen * @description `Boolean`: Triggers appearance changes in the template when * a contact modal opens. See 'contact' directive. */ self.modalOpen = false; // Arbitrary profile if (account) { self.user = account.info; self.repos = account.repos; self.events = account.events; self.viewTitle = account.info.login; self.state = $state; self.nav = true; self.canFollow = GitHub.canFollow(account.info.login); // The user's own profile } else { self.user = GitHub.me; self.repos = GitHub.repos; self.events = GitHub.events; self.viewTitle = GitHub.me.login; self.canFollow = false; self.nav = false; } // Info logic: There are four optional profile fields // and two spaces to show them in. In order of importance: // 1. Company, 2. Blog, 3. Email, 4. Location self.company = self.user.company; self.email = self.user.email; self.blog = self.user.blog; self.location = self.user.location; // Case: both exist - no space if (self.company && self.email) { self.blog = false; self.location = false; // Case: One exists - one space, pick blog, or location } else if ((!self.company && self.email) || (self.company && !self.email)) { (self.blog) ? self.location = false : true; } /** * @ngdoc method * @methodOf gitphaser.object:ProfileCtrl * @name gitphaser.object:ProfileCtrl.back * @description Navigates back to `$stateParams.origin`. For nav back arrow visible in the `others` * route. */ self.back = function () { if ($stateParams.origin === 'nearby') $state.go('tab.nearby'); if ($stateParams.origin === 'notifications') $state.go('tab.notifications'); }; /** * @ngdoc method * @methodOf gitphaser.object:ProfileCtrl * @name gitphaser.object:ProfileCtrl.follow * @description Wraps `GitHub.follow` and hides the follow button when clicked. */ self.follow = function () { self.canFollow = false; GitHub.follow(self.user); }; }
if (typeof exports === 'object') { var assert = require('assert'); var alasql = require('..'); } /* Test for issue #379 */ var test = 428; describe('Test ' + test + ' UUID()', function () { before(function () { alasql('CREATE DATABASE test' + test + ';USE test' + test); }); after(function () { alasql('DROP DATABASE test' + test); }); it('1. Simple test GUID', function (done) { var res = alasql('=UUID()'); assert( !!res.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i) ); done(); }); it('2. DEFAULT GUID', function (done) { alasql('CREATE TABLE one (a INT, b STRING DEFAULT UUID())'); alasql('INSERT INTO one(a) VALUES (1)'); var res = alasql('SELECT * FROM one'); assert( !!res[0].b.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i) ); done(); }); });
/** AnalyzeController.js */ application.controller('AnalyzeController', ['$scope', '$stateParams', 'PathService', function ($scope, $stateParams, PathService) { $scope.path = {}; PathService.path({ Type: "SUBMISSION", EntityId: $stateParams.submissionId }) .success(function (data, status, headers, config) { $scope.path = data; }); }]);
/** * Extend Object works like Object.assign(...) but recurses into the nested properties * * @param {object} base - an object to extend * @param {...object} args - a series of objects to extend * @returns {object} extended object */ function extend(base, ...args) { args.forEach(current => { if (!Array.isArray(current) && base instanceof Object && current instanceof Object && base !== current) { for (const x in current) { base[x] = extend(base[x], current[x]); } } else { base = current; } }); return base; } module.exports = extend;
/* * * HomeItemPage constants * */ export const DEFAULT_ACTION = 'app/HomeItemPage/DEFAULT_ACTION';
'use strict'; var browserify = require('browserify'); var go = module.exports = function () { return browserify() .require(require.resolve('./main'), { entry: true }) .bundle({ debug: true }); }; // Test if (!module.parent) { go().pipe(process.stdout); }
// NOTE: This example uses the next generation Twilio helper library - for more // information on how to download and install this version, visit // https://www.twilio.com/docs/libraries/node const apiKeySid = 'SKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const apiKeySecret = 'your_api_key_secret'; const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const Twilio = require('twilio'); const client = new Twilio(apiKeySid, apiKeySecret, { accountSid: accountSid }); client.video.rooms('RMXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch().then(room => { console.log(room.uniqueName); });
import Ember from 'ember'; export default Ember.Controller.extend({ actions: { create() { this.get('model').save().then((user) => { this.transitionToRoute('admin.users.show', user); }) } } });
var Avenger = require('mongoose').model('Avenger'); exports.getAvengers = function (req, res) { Avenger.find({}).exec(function (err, collection) { res.send(collection); }); }; exports.getAvengerById = function (req, res) { Avenger.findOne({_id:req.params.id}).exec(function (err, avenger) { res.send(avenger); }); };
// # Templates // // Figure out which template should be used to render a request // based on the templates which are allowed, and what is available in the theme // TODO: consider where this should live as it deals with channels, singles, and errors var _ = require('lodash'), path = require('path'), config = require('../../config'), themes = require('../../themes'), _private = {}; /** * ## Get Error Template Hierarchy * * Fetch the ordered list of templates that can be used to render this error statusCode. * * The default is the * * @param {integer} statusCode * @returns {String[]} */ _private.getErrorTemplateHierarchy = function getErrorTemplateHierarchy(statusCode) { var errorCode = _.toString(statusCode), templateList = ['error']; // Add error class template: E.g. error-4xx.hbs or error-5xx.hbs templateList.unshift('error-' + errorCode[0] + 'xx'); // Add statusCode specific template: E.g. error-404.hbs templateList.unshift('error-' + errorCode); return templateList; }; /** * ## Get Channel Template Hierarchy * * Fetch the ordered list of templates that can be used to render this request. * 'index' is the default / fallback * For channels with slugs: [:channelName-:slug, :channelName, index] * For channels without slugs: [:channelName, index] * Channels can also have a front page template which is used if this is the first page of the channel, e.g. 'home.hbs' * * @param {Object} channelOpts * @returns {String[]} */ _private.getChannelTemplateHierarchy = function getChannelTemplateHierarchy(channelOpts) { var templateList = ['index']; if (channelOpts.name && channelOpts.name !== 'index') { templateList.unshift(channelOpts.name); if (channelOpts.slugTemplate && channelOpts.slugParam) { templateList.unshift(channelOpts.name + '-' + channelOpts.slugParam); } } if (channelOpts.frontPageTemplate && channelOpts.postOptions.page === 1) { templateList.unshift(channelOpts.frontPageTemplate); } return templateList; }; /** * ## Get Entry Template Hierarchy * * Fetch the ordered list of templates that can be used to render this request. * 'post' is the default / fallback * For posts: [post-:slug, custom-*, post] * For pages: [page-:slug, custom-*, page, post] * * @param {Object} postObject * @returns {String[]} */ _private.getEntryTemplateHierarchy = function getEntryTemplateHierarchy(postObject) { var templateList = ['post'], slugTemplate = 'post-' + postObject.slug; if (postObject.page) { templateList.unshift('page'); slugTemplate = 'page-' + postObject.slug; } if (postObject.custom_template) { templateList.unshift(postObject.custom_template); } templateList.unshift(slugTemplate); return templateList; }; /** * ## Pick Template * * Taking the ordered list of allowed templates for this request * Cycle through and find the first one which has a match in the theme * * @param {Array|String} templateList * @param {String} fallback - a fallback template */ _private.pickTemplate = function pickTemplate(templateList, fallback) { var template; if (!_.isArray(templateList)) { templateList = [templateList]; } if (!themes.getActive()) { template = fallback; } else { template = _.find(templateList, function (template) { return themes.getActive().hasTemplate(template); }); } if (!template) { template = fallback; } return template; }; _private.getTemplateForEntry = function getTemplateForEntry(postObject) { var templateList = _private.getEntryTemplateHierarchy(postObject), fallback = templateList[templateList.length - 1]; return _private.pickTemplate(templateList, fallback); }; _private.getTemplateForChannel = function getTemplateForChannel(channelOpts) { var templateList = _private.getChannelTemplateHierarchy(channelOpts), fallback = templateList[templateList.length - 1]; return _private.pickTemplate(templateList, fallback); }; _private.getTemplateForError = function getTemplateForError(statusCode) { var templateList = _private.getErrorTemplateHierarchy(statusCode), fallback = path.resolve(config.get('paths').defaultViews, 'error.hbs'); return _private.pickTemplate(templateList, fallback); }; module.exports.setTemplate = function setTemplate(req, res, data) { var routeConfig = res._route || {}; if (res._template && !req.err) { return; } if (req.err) { res._template = _private.getTemplateForError(res.statusCode); return; } switch (routeConfig.type) { case 'custom': res._template = _private.pickTemplate(routeConfig.templateName, routeConfig.defaultTemplate); break; case 'channel': res._template = _private.getTemplateForChannel(res.locals.channel); break; case 'entry': res._template = _private.getTemplateForEntry(data.post); break; default: res._template = 'index'; } };
var mongodb = require("mongodb"), config = require("./config"), connectArr = []; module.exports = function(server){ connectArr.push("mongodb://"); if(config.dbUser){ connectArr.push(config.dbUser); connectArr.push("@"); } if(config.dbPwd){ connectArr.push(config.dbPwd); } connectArr.push(config.db); mongodb.MongoClient.connect(connectArr.join(""), function(err, db){ if(err) { console.log("error connecting to mongo"); } else { console.log("connected to %s successfully", db.databaseName); require("./realtime")(server, db); } }); };
import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import * as actionCreators from '../actions/workspace'; import { setActiveComponent } from '../actions/FileSystemActions'; import Workspace from '../components/Workspace'; function mapStateToProps(state) { return { workspace: state.workspace }; } function mapDispatchToProps(dispatch) { return bindActionCreators({ ...actionCreators, setActiveComponent }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(Workspace);