code
stringlengths
2
1.05M
import React, { useState } from "react"; import Article from "../components/Article/Article"; import AddArticle from "../components/AddArticle/AddArticle"; const Articles = () => { const [articles, setArticles] = useState([ { id: 1, title: "post 1", body: "Quisque cursus, metus vitae pharetra" }, { id: 2, title: "post 2", body: "Quisque cursus, metus vitae pharetra" }, ]); const saveArticle = (e) => { e.preventDefault(); // 逻辑代码稍后更新 }; return ( <div> <AddArticle saveArticle={saveArticle} /> {articles.map((article) => ( <Article key={article.id} article={article} /> ))} </div> ); }; export default Articles;
define(function(require,exports,module){ var register = require("api/panel").registerFormat; //Separator register(function(msg){ var _class = ""; if(msg.indexOf("...")>-1){_class="dot";} else if(msg.indexOf("---")>-1){_class="line";} else if(msg.indexOf("+++")>-1){_class="plus";} else if(msg.indexOf("***")>-1){_class="asterisc";} else if(msg.indexOf(":::")>-1){_class="doubledot";} else if(msg.indexOf("···")>-1){_class="middledot";} if(_class!==""){ return '<div class="separator '+_class+'"/>'; } return msg; },'pre'); //LORM register(function(output){ var object = output.match(/ (.*){(\n[\w\W\r\n\t]*) }\n/); if( object){ var definition = object[1]; var content = object[2]; content = content.split('\n'); var name = '<span role="name">'; var opts = '<span role="opts">'; var header = '<header>'; var body = '<article>'; var data = definition.match(/(.*)\((.*)\).*/); object=$('<section role="object">').append( $(header).append($(name).html( data[1]), $(opts).html(data[2])), $(body) ); object.children('header').click(function(){ $(this).parent().children('article').toggle(); }); var current = object.find('article'); for( var i in content){ if(content[i].indexOf("{")>-1){ var subobject = $('<section role="subobject"/>'); var data = content[i].match(/.*?\[(.*)\] => (.*){/); subobject.append($(header).append( $(name).html( data[1]), $(opts).html(data[2]) ),$(body)); subobject.children('header').click(function(){ $(this).parent().children('article').toggle(); }); current.append( subobject ); current = subobject.find('article'); }else if(content[i].indexOf("}")>-1){ current = current.parent().parent(); }else{ var prop = content[i].match(/.*?\[(.*)\] => (.*)/); if( prop!==null){ prop = $('<div role="property"/>').append( $('<span role="name">').html(prop[1]), $('<span role="value">').html(prop[2]) ); current.prepend(prop); } } } object.find('article').hide(); return [object,/ (.*){(\n[\w\W\r\n\t]*) }\n/]; } //{([^{}]*)} },'after'); });
import React from 'react'; import ReactDOM from 'react-dom'; class ListOfWords extends React.PureComponent { render () { const { words } = this.props; return <div>{ words.join(',') }</div> } } class WordAdder extends React.Component { constructor (props) { super(props); this.state = { words: ['marklar'] } } handleClick = () => { // 这样取到了数组的引用,尽管数据内容发生了改变,但是都是同一对象,继承PureComponent // 会进行shouldUpdateComponent浅比较,不会发生重绘 // const words = this.state.words; const words = this.state.words.slice(); words.push('marklar'); this.setState({ words: words }); } render () { return ( <div> <button type="button" onClick={this.handleClick}>Click me!</button> <ListOfWords words={this.state.words}/> </div> ) } } ReactDOM.render(<WordAdder />, document.getElementById('root'));
// @flow import pify from "pify"; import nativeFs from "fs"; import path from "path"; import minimatch from "minimatch"; import reEscape from "escape-string-regexp"; const fs = pify(nativeFs); const isIgnored = (workdir, patterns) => { const re = new RegExp(`^${reEscape(workdir)}`); return async file => (await patterns).some(pattern => minimatch(file.replace(re, ""), pattern)); }; async function findFiles( filename: string, workdir: string, ignore: Array<string> = [] ): Promise<Array<string>> { const files = []; const shouldSkip = isIgnored(workdir, ignore); async function walk(dir) { try { const stats = await fs.stat(dir); if (stats.isFile() && path.basename(dir) === filename) { files.push(dir); } else if (stats.isDirectory()) { const visit = !await shouldSkip(dir); if (visit) { const dirs = await fs.readdir(dir); await Promise.all(dirs.map(child => walk(path.join(dir, child)))); } } } catch (e) { // TODO: What now? } } await walk(workdir); return files; } export default findFiles;
/** * Loader for your controllers. */ const fs = require('fs'); const path = require('path'); module.exports = function(parent) { fs.readdirSync(path.join(__dirname, '..', 'controllers')).forEach(function(name){ if (!fs.statSync(path.join(__dirname, '..', 'controllers', name)).isDirectory()) return; let ctrl = require('./../controllers/' + name); let autoload = ctrl.autoload; let prefix = ctrl.prefix || null; let app = ctrl.controller; if ('undefined' !== typeof autoload && !autoload) return; // allow specifying the view engine. // NOTE: The controller has to be an express application and not an express router if (ctrl.engine) { app.set('view engine', ctrl.engine); app.set('views', path.join(__dirname, '..', 'controllers', name, 'views')); } // mount the app with before middleware support if (prefix) { if (ctrl.before) { parent.use(prefix, ctrl.before, app); } else { parent.use(prefix, app); } } else { if (ctrl.before) { parent.use(ctrl.before, app); } else { parent.use(app); } } }) // forEach }
'use strict'; var portfolioModel = new (require('../models/PortfolioModel'))(), path = require('path'), fs = require('fs'), async = require('async'); function PortfoiloService() { if (!(this instanceof PortfoiloService)) { return new PortfoiloService(); } } PortfoiloService.prototype.getUserPortfolioData = function (params, callback) { var criteria = { USER_NAME: params.userName }; var options = {}; var result = {}; portfolioModel.selectByName(criteria, options, function (err, portfolio) { result = portfolio; callback(err, result); }); }; PortfoiloService.prototype.makeUserPortfolioData = function (params, callback) { var criteria = {}; var options = {}; var result = {}; async.waterfall([ function (callback) { criteria = { USER_ID: params.userId }; portfolioModel.selectById(criteria, options, function (err, portfolio) { // 유저 포트폴리오가 이미 존재할 때 true 전달 if (portfolio && portfolio.length > 0) { callback(null, true); return; } callback(err, false); }); }, function (hasPortfolio, callback) { criteria = { TEMPLATE_ID: params.templateId, USER_ID: params.userId, USER_NAME: params.userName }; if (hasPortfolio) { portfolioModel.update(criteria, options, function (err) { callback(err); }); } else { portfolioModel.insert(criteria, options, function (err) { callback(err); }); } }, function (callback) { criteria = { USER_ID: params.userId }; portfolioModel.selectById(criteria, options, function (err, portfolio) { callback(err, portfolio); }); }, function (portfolio, callback) { // templateFileName: 템플릿 이름.ejs // saveFileName: 포트폴리오 이름.ejs // srcPath: 템플릿 경로 // savPath: 포트폴리어 저장되는 경로 var templateFileName = 'template' + params.templateId + '.ejs'; var saveFileName = portfolio[0].PORTFOLIO_ID + '.ejs'; var srcPath = path.join(__dirname, '../views/template/', templateFileName); var savPath = path.join(__dirname, '../views/portfolio/', saveFileName); fs.readFile(srcPath, 'utf8', function (err, data) { if (err) { callback(err, null); return; } fs.writeFile (savPath, data, function(err) { callback(err, { code: 1, msg: "success" }); }); }); } ], function (err, state) { if (err && err.code === 0) { result = err; err = null; } else { result = state; } callback(err, result); }); }; PortfoiloService.prototype.saveUserPortfolioData = function (params, callback) { var portfolioFileName = params.portfolioId + '.ejs'; var savPath = path.join(__dirname, '../views/portfolio/', portfolioFileName); var data = params.html; fs.writeFile (savPath, data, function(err) { callback(err, { code: 1, msg: "success" }); }); }; module.exports = PortfoiloService;
var assert = require("assert"); var quartz = require("../lib/quartz.js"); var quartzSynchronizer = require("../lib/quartzSynchronizer.js"); describe('Quartz', function(){ it('should be an object', function(){ var quartzInstance = new quartz.Quartz(); assert.notDeepEqual(quartzInstance, undefined); }); it('should have an init method', function(){ var quartzInstance = new quartz.Quartz(); quartzInstance.init(); }); it('should have a schedule job method', function(){ var quartzInstance = new quartz.Quartz(); var jobId = quartzInstance.scheduleCronJob(); assert.notEqual(jobId, undefined, "valid JobId"); var jobId2 = quartzInstance.scheduleCronJob(); assert.notEqual(jobId2, jobId, "which is unique"); }); it('should provide a way to schedule a job using cron syntax', function(done){ var quartzInstance = new quartz.Quartz(); var Listener = function() { var counter = 0; this.jobFunction = function(){ counter++; if(counter == 1) done(); // call done only once. } } quartzInstance.init(new Listener()); quartzInstance.scheduleCronJob("* * * * *", "jobFunction"); }); it('should have provide a way to unschedule a job scheduled with a cron syntax', function(done){ var quartzInstance = new quartz.Quartz(); var jobExecuted = false; var Listener = function() { this.jobFunction = function(){ jobExecuted = true; } } quartzInstance.init(new Listener()); var jobId = quartzInstance.scheduleCronJob("* * * * *", "jobFunction"); setTimeout(function afterABitMoreThanAMinute(){ assert.equal(jobExecuted, false); done(); }, 61000); quartzInstance.unscheduleJob(jobId); }); it('should provide a way to execute a job after a delay', function(done){ var quartzInstance = new quartz.Quartz(); var Listener = function() { var counter = 0; this.jobFunction = function(){ counter++; if(counter == 1) done(); // call done only once. } } quartzInstance.init(new Listener()); quartzInstance.delayJob(2, "jobFunction"); }); it('should have provide a way to unschedule a delayed job', function(done){ var quartzInstance = new quartz.Quartz(); var jobExecuted = false; var Listener = function() { this.jobFunction = function(){ jobExecuted = true; } } quartzInstance.init(new Listener()); var jobId = quartzInstance.delayJob(2, "jobFunction"); setTimeout(function afterTheDelay(){ assert.equal(jobExecuted, false); done(); }, 3000); quartzInstance.unscheduleJob(jobId); }); it('should be possible to synchronize two quartz, when one is down the other one continue to work.', function(done) { var quartzInstance1 = new quartz.Quartz(); var quartzInstance2 = new quartz.Quartz(); var synchronizer = new quartzSynchronizer.QuartzSyncrhonizer(); var jobExecuted = false; var Listener = function() { this.jobFunction = function(){ jobExecuted = true; } } quartzInstance1.init(new Listener(), synchronizer); quartzInstance2.init(new Listener(), synchronizer); quartzInstance1.delayJob(2, "jobFunction"); setTimeout(function afterTheDelay(){ assert.equal(jobExecuted, true, "the job should have been executed even if the original quartz has been finalized"); done(); }, 3000); quartzInstance1.finalize(); }); it('should be possible to synchronize two quartz, only one runs the delayed job', function(done) { var quartzInstance1 = new quartz.Quartz(); var quartzInstance2 = new quartz.Quartz(); var synchronizer = new quartzSynchronizer.QuartzSyncrhonizer(); var jobExecutedCounter = 0; var Listener = function() { this.jobFunction = function(){ jobExecutedCounter++; } } quartzInstance1.init(new Listener(), synchronizer); quartzInstance2.init(new Listener(), synchronizer); quartzInstance1.delayJob(2, "jobFunction"); setTimeout(function afterTheDelay(){ assert.equal(jobExecutedCounter, 1, "the job should have been executed once"); done(); }, 3000); }); }); describe('Synchronizer', function() { it('should allow to connect a client', function () { var synchronizer = new quartzSynchronizer.QuartzSyncrhonizer(); synchronizer.connectClient(null); }); });
"use strict"; var core_1 = require('@angular/core'); var DashboardComponent = (function () { function DashboardComponent() { } DashboardComponent = __decorate([ core_1.Component({ selector: 'my-dashboard', encapsulation: core_1.ViewEncapsulation.None, styles: [require('./dashboard.scss')], template: require('./dashboard.html') }), __metadata('design:paramtypes', []) ], DashboardComponent); return DashboardComponent; }()); exports.DashboardComponent = DashboardComponent; //# sourceMappingURL=dashboard.component.js.map
function solve() { let arr = [10, 20, 30]; for(let index in arr){ console.log(index); } } solve();
var webpack = require('webpack'); var baseConfig = require('./webpack.config.base'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var config = Object.create(baseConfig); config.plugins = [ new ExtractTextPlugin('dist/style.css', { allChunks: true }) ]; module.exports = config;
version https://git-lfs.github.com/spec/v1 oid sha256:adaa3a4db6a03b3eee5b5f006f090495696a94e1173365bb14ace015d84e4ad3 size 8246
#!/usr/bin/env node var path = require('path'); var rollup = require('rollup'); var entry = path.resolve(__dirname, '../lib/simple-html-tokenizer.js'); var dest = path.resolve(__dirname, '../dist/simple-html-tokenizer.js'); rollup.rollup({ entry: entry }).then(function (bundle) { return bundle.write({ sourceMap: true, dest: dest, format: 'umd', moduleName: 'HTML5Tokenizer' }); }).catch(function (err) { console.error(err); console.error(err.stack); process.exit(1); });
var config = require('../config'), gulp = require('gulp'), del = require('del'); module.exports = function(taskName) { gulp.task(taskName, function(cb) { del.sync(config.clean); cb(); }); };
require.config({ baseUrl: "/static/js", paths: { "angular": "//ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min", "bootstrap": "//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min", "jquery": "//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min", "recaptcha": "//www.google.com/recaptcha/api", "tween-max": "//cdnjs.cloudflare.com/ajax/libs/gsap/1.15.1/TweenMax.min", }, shim: { 'angular': { exports: "angular", deps: ['bootstrap'] }, 'bootstrap': { deps: ["jquery"] } } }); require(['angular', 'app'], function (ng, app) { ng.bootstrap(document, [app.name]); });
function solve(args){ var a = +args[0]; var b = +args[1]; var c = +args[2]; if (a >= b && a >=c) { if (b >= c) { console.log(a,b,c); } else { console.log(a,c,b); } } else if(b >= a && b >= c){ if (a >= c) { console.log(b, a, c); } else { console.log(b, c, a); } } else { if (a >= b) { console.log(c,a,b); } else { console.log(c,b,a); } } } solve([5, 1, 2]);
/** * Created by tudecai on 2017/1/13. */ /** 签名需要用到的js */ ;var Signature = (function () { var signDataUrl = serverPath + 'signature/query'; //获取签名UI显示需要的数据的URL var signConfirmUrl = serverPath + 'signature/confirms'; //签名确认调用的后台地址 var owerSid = 0; //签名ID var comfirmCallBack = null; //签名成功回调函数 var signType = 0; //签名类型 1双人 0单人 var signSelf = 0; //签名类型 1本人签名 0可以不是本人 var remark = 0; //签名备注 1必填 0不必 //签名 function CallSign(signId, callBack) { comfirmCallBack = callBack; $.ajax({ url: signDataUrl, data: {"id": signId}, xhrFields: {withCredentials: true}, dataType: "json", success: function (result) { var errCode = result.errorCode; if (errCode == 0) { SignLoad(result); } }, error: function () { alert('未找到相关签名的定义:' + signId); } }); } /** * 弹出签名层时的 加载方法 * @param sid 功能对应得签名的ID * @param callback 功能对应签名后 数据操作的回调方法 * @constructor */ function SignLoad(sdata) { signType = sdata.type; signSelf = sdata.signself; remark = sdata.remark; var signTitle = sdata.sign.description; owerSid = sdata.sign.id; if (signType == 0) { var htmlUrl = getRootPath() + '/WebUI/Public/Signature2.html'; TuLayer.ShowDiv(htmlUrl, signTitle, '400px', '400px', function () { LoadSingleSignData(sdata); $("#sigBtn").on('click', function () { SignSave(); }); $("#cancelSigBtn").on('click', function () { CloseSign(); }) }); } else { var htmlUrl = 'DoubleSignature.html'; TuLayer.ShowDiv(htmlUrl, signTitle, '700px', '500px', function () { LoadDoubleSignData(sdata); }); } } //加载单人签名数据 function LoadSingleSignData(sigData) { $('#sDescription').val(sigData.sign.meaning); var ugInfo1 = sigData.user1; for (var i = 0; i < ugInfo1.length; i++) { var ugId = ugInfo1[i].id; var ugName = ugInfo1[i].name; var ss = ""; ss += "<option value='" + ugId + "'>" + ugName + "</option>" $("#sGroupName").append(ss); } var sigGroupId = $("#sGroupName").val(); var userSelect = $("#sUsers"); GetSigGroupMember(sigGroupId, userSelect); }; //加载双人签名的数据 function LoadDoubleSignData(signBaseInfo) { //用户组1的信息 LoadSingleSignData(signBaseInfo) //用户组2的信息 $('#sDescription1').val(signBaseInfo.meaning2); var ugInfo2 = sigData.user2; for (var i = 0; i < ugInfo2.length; i++) { var id = ugInfo2[i].id; var name = ugInfo2[i].name; var ss = ""; ss += "<option value='" + id + "'>" + name + "</option>" $("#sGroupName1").append(ss); } var sigGroupId = $("#sGroupName1").val(); var userSelect1 = $("#sUsers1"); GetSigGroupMember(sigGroupId, userSelect1); } //获取签名组成员 function GetSigGroupMember(sigGroupId, userSelect) { var getSigGroupMemberUrl = serverPath + 'userGroups/get/users'; $.ajax({ url: getSigGroupMemberUrl, data: {"id": sigGroupId}, dataType: "json", xhrFields: {withCredentials: true}, success: function (result) { if (result.errorCode == 0) { var data = result.data; FillSigGroupMember(data, userSelect); } }, error: function () { alert('获取签名组成员失败!'); } }); } //填充签名组成员 function FillSigGroupMember(member, userSelect) { userSelect.empty(); for (var i = 0; i < member.length; i++) { var account = member[i].account; var name = member[i].name; var ss = ""; ss += "<option value='" + account + "'>" + name + "(" + account + ")</option>"; userSelect.append(ss); } } //画面绑定的事件 $(function () { //单人签名,签名组改变事件 $("body").on("change", "#sGroupName", function () { var sigGroupId = $("#sGroupName").val(); var userSelect = $("#sUsers"); GetSigGroupMember(sigGroupId, userSelect); }); //双人签名,签名组改变事件 $("body").on("change", "#sGroupName1", function () { var sigGroupId = $("#sGroupName1").val(); var userSelect1 = $("#sUsers1"); GetSigGroupMember(sigGroupId, userSelect1); }); }) //签名 //确认签名 function SignSave() { //单人签名 var user1 = new Object; var user2 = new Object; var pwd = $("#sPassword").val(); var sUser = $("#sUsers").val(); var comment = $("#comment").val(); var ugId = $("#sGroupName").val(); user1.account = sUser; user1.password = pwd; user1.comment = comment; user1.ugId = ugId; if (signType == 0) { //密码 if (pwd.length <= 0) { //ShowTips("请输入密码", $("#userGroupCode")); return; } } else { var password2 = $("#sPassword1").val(); var account2 = $("#sUsers1").val(); var comment2 = $("#comment1").val(); var ugId = $("#sGroupName1").val(); user2.account = account2; user2.password = password2; user2.comment = comment2; user2.ugId = ugId; } $.ajax({ url: signConfirmUrl, data: {"sid": owerSid, "user1": user1, "user2": user2}, dataType: "json", xhrFields: {withCredentials: true}, success: function (result) { var errCode = result.errorCode; if (errCode == 0) { var rId = result.data; comfirmCallBack(rId); } else { TuLayer.ShowMsg(errCode); } }, error: function () { //alert('签名服务异常!'); TuLayer.ShowMsg("签名服务异常"); } }); }; //获取项目根目录 function getRootPath() { //获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jsp var curWwwPath = window.document.location.href; //获取主机地址之后的目录,如: uimcardprj/share/meun.jsp var pathName = window.document.location.pathname; var pos = curWwwPath.indexOf(pathName); //获取主机地址,如: http://localhost:8083 var localhostPaht = curWwwPath.substring(0, pos); //获取带"/"的项目名,如:/uimcardprj var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1); return (localhostPaht + projectName); } //取消签名 function CloseSign() { TuLayer.Close(); } var sig = { CallSign: CallSign, CloseSign: CloseSign } return sig; })();
import test from 'ava' import React from 'react' import {shallow, mount} from 'enzyme' import sinon from 'sinon'; import NumericStepper from './numericstepper' test('renders correct label', t => { const label = 'A label' const component = shallow(<NumericStepper label={label}/>) t.is( component.find('label').text(), label ) }); test('renders correct value', t => { const value = 4 const component = shallow(<NumericStepper value={value}/>) t.is( component.find({ value }).length, 1 ) }); test('responds to change events', t => { const onChange = sinon.spy() const component = mount(<NumericStepper value={4} onChange={onChange}/>) component.find('input').get(0).value = 5 component.find('input').simulate( 'change' ) t.is( onChange.called, true ) }); test('satisfies minimum constraint', t => { const value = 4 const min = 5 const component = mount(<NumericStepper value={value} min={min}/>) t.is( parseFloat( component.find('input').get(0).value ), min ) }); test('satisfies maximum constraint', t => { const value = 4 const max = 3 const component = mount(<NumericStepper value={value} max={max}/>) t.is( parseFloat( component.find('input').get(0).value ), max ) }); // test.todo( 'Validates input' ) // test.todo( 'Change even fires with correct value' ) // test('change event fires with correct value', t => { // const onChange = sinon.spy(); // const change = 'Change!' // const wrapper = shallow(<TextInput onChange={onChange}/>) // wrapper.find('input').simulate('change', { target:{ value: change}}); // t.is( onChange.calledWith( change ), true ) // });
/** * @typedef {object} Phaser.Curves.Types.JSONPath * @since 3.0.0 * * @property {string} type - The of the curve. * @property {number} x - The X coordinate of the curve's starting point. * @property {number} y - The Y coordinate of the path's starting point. * @property {boolean} autoClose - The path is auto closed. * @property {Phaser.Curves.Types.JSONCurve[]} curves - The list of the curves */
// The Tern server object // A server is a stateful object that manages the analysis for a // project, and defines an interface for querying the code in the // project. (function(root, mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS return mod(exports, require("./infer"), require("./signal"), require("acorn/acorn"), require("acorn/util/walk")); if (typeof define == "function" && define.amd) // AMD return define(["exports", "./infer", "./signal", "acorn/acorn", "acorn/util/walk"], mod); mod(root.tern || (root.tern = {}), tern, tern.signal, acorn, acorn.walk); // Plain browser env })(this, function(exports, infer, signal, acorn, walk) { "use strict"; var plugins = Object.create(null); exports.registerPlugin = function(name, init) { plugins[name] = init; }; var defaultOptions = exports.defaultOptions = { debug: false, async: false, getFile: function(_f, c) { if (this.async) c(null, null); }, defs: [], plugins: {}, fetchTimeout: 1000, dependencyBudget: 20000, reuseInstances: true }; var queryTypes = { completions: { takesFile: true, run: findCompletions }, properties: { run: findProperties }, type: { takesFile: true, run: findTypeAt }, documentation: { takesFile: true, run: findDocs }, definition: { takesFile: true, run: findDef }, refs: { takesFile: true, fullFile: true, run: findRefs }, rename: { takesFile: true, fullFile: true, run: buildRename }, files: { run: listFiles } }; exports.defineQueryType = function(name, desc) { queryTypes[name] = desc; }; function File(name, parent) { this.name = name; this.parent = parent; this.scope = this.text = this.ast = this.lineOffsets = null; } File.prototype.asLineChar = function(pos) { return asLineChar(this, pos); }; function updateText(file, text, srv) { file.text = text; infer.withContext(srv.cx, function() { file.ast = infer.parse(text, srv.passes, {directSourceFile: file, allowReturnOutsideFunction: true}); }); file.lineOffsets = null; } var Server = exports.Server = function(options) { this.cx = null; this.options = options || {}; for (var o in defaultOptions) if (!options.hasOwnProperty(o)) options[o] = defaultOptions[o]; this.handlers = Object.create(null); this.files = []; this.fileMap = Object.create(null); this.needsPurge = []; this.budgets = Object.create(null); this.uses = 0; this.pending = 0; this.asyncError = null; this.passes = Object.create(null); this.defs = options.defs.slice(0); for (var plugin in options.plugins) if (options.plugins.hasOwnProperty(plugin) && plugin in plugins) { var init = plugins[plugin](this, options.plugins[plugin]); if (init && init.defs) { if (init.loadFirst) this.defs.unshift(init.defs); else this.defs.push(init.defs); } if (init && init.passes) for (var type in init.passes) if (init.passes.hasOwnProperty(type)) (this.passes[type] || (this.passes[type] = [])).push(init.passes[type]); } this.reset(); }; Server.prototype = signal.mixin({ addFile: function(name, /*optional*/ text, parent) { // Don't crash when sloppy plugins pass non-existent parent ids if (parent && !(parent in this.fileMap)) parent = null; ensureFile(this, name, parent, text); }, delFile: function(name) { var file = this.findFile(name); if (file) { this.needsPurge.push(file.name); this.files.splice(this.files.indexOf(file), 1); delete this.fileMap[name]; } }, reset: function() { this.signal("reset"); this.cx = new infer.Context(this.defs, this); this.uses = 0; this.budgets = Object.create(null); for (var i = 0; i < this.files.length; ++i) { var file = this.files[i]; file.scope = null; } }, request: function(doc, c) { var inv = invalidDoc(doc); if (inv) return c(inv); var self = this; doRequest(this, doc, function(err, data) { c(err, data); if (self.uses > 40) { self.reset(); analyzeAll(self, null, function(){}); } }); }, findFile: function(name) { return this.fileMap[name]; }, flush: function(c) { var cx = this.cx; analyzeAll(this, null, function(err) { if (err) return c(err); infer.withContext(cx, c); }); }, startAsyncAction: function() { ++this.pending; }, finishAsyncAction: function(err) { if (err) this.asyncError = err; if (--this.pending === 0) this.signal("everythingFetched"); } }); function doRequest(srv, doc, c) { if (doc.query && !queryTypes.hasOwnProperty(doc.query.type)) return c("No query type '" + doc.query.type + "' defined"); var query = doc.query; // Respond as soon as possible when this just uploads files if (!query) c(null, {}); var files = doc.files || []; if (files.length) ++srv.uses; for (var i = 0; i < files.length; ++i) { var file = files[i]; if (file.type == "delete") srv.delFile(file.name); else ensureFile(srv, file.name, null, file.type == "full" ? file.text : null); } var timeBudget = typeof doc.timeout == "number" ? [doc.timeout] : null; if (!query) { analyzeAll(srv, timeBudget, function(){}); return; } var queryType = queryTypes[query.type]; if (queryType.takesFile) { if (typeof query.file != "string") return c(".query.file must be a string"); if (!/^#/.test(query.file)) ensureFile(srv, query.file, null); } analyzeAll(srv, timeBudget, function(err) { if (err) return c(err); var file = queryType.takesFile && resolveFile(srv, files, query.file); if (queryType.fullFile && file.type == "part") return c("Can't run a " + query.type + " query on a file fragment"); function run() { var result; try { result = queryType.run(srv, query, file); } catch (e) { if (srv.options.debug && e.name != "TernError") console.error(e.stack); return c(e); } c(null, result); } infer.withContext(srv.cx, timeBudget ? function() { infer.withTimeout(timeBudget[0], run); } : run); }); } function analyzeFile(srv, file) { infer.withContext(srv.cx, function() { file.scope = srv.cx.topScope; srv.signal("beforeLoad", file); infer.analyze(file.ast, file.name, file.scope, srv.passes); srv.signal("afterLoad", file); }); return file; } function ensureFile(srv, name, parent, text) { var known = srv.findFile(name); if (known) { if (text != null) { if (known.scope) { srv.needsPurge.push(name); known.scope = null; } updateText(known, text, srv); } if (parentDepth(srv, known.parent) > parentDepth(srv, parent)) { known.parent = parent; if (known.excluded) known.excluded = null; } return; } var file = new File(name, parent); srv.files.push(file); srv.fileMap[name] = file; if (text != null) { updateText(file, text, srv); } else if (srv.options.async) { srv.startAsyncAction(); srv.options.getFile(name, function(err, text) { updateText(file, text || "", srv); srv.finishAsyncAction(err); }); } else { updateText(file, srv.options.getFile(name) || "", srv); } } function fetchAll(srv, c) { var done = true, returned = false; srv.files.forEach(function(file) { if (file.text != null) return; if (srv.options.async) { done = false; srv.options.getFile(file.name, function(err, text) { if (err && !returned) { returned = true; return c(err); } updateText(file, text || "", srv); fetchAll(srv, c); }); } else { try { updateText(file, srv.options.getFile(file.name) || "", srv); } catch (e) { return c(e); } } }); if (done) c(); } function waitOnFetch(srv, timeBudget, c) { var done = function() { srv.off("everythingFetched", done); clearTimeout(timeout); analyzeAll(srv, timeBudget, c); }; srv.on("everythingFetched", done); var timeout = setTimeout(done, srv.options.fetchTimeout); } function analyzeAll(srv, timeBudget, c) { if (srv.pending) return waitOnFetch(srv, timeBudget, c); var e = srv.fetchError; if (e) { srv.fetchError = null; return c(e); } if (srv.needsPurge.length > 0) infer.withContext(srv.cx, function() { infer.purge(srv.needsPurge); srv.needsPurge.length = 0; }); var done = true; // The second inner loop might add new files. The outer loop keeps // repeating both inner loops until all files have been looked at. for (var i = 0; i < srv.files.length;) { var toAnalyze = []; for (; i < srv.files.length; ++i) { var file = srv.files[i]; if (file.text == null) done = false; else if (file.scope == null && !file.excluded) toAnalyze.push(file); } toAnalyze.sort(function(a, b) { return parentDepth(srv, a.parent) - parentDepth(srv, b.parent); }); for (var j = 0; j < toAnalyze.length; j++) { var file = toAnalyze[j]; if (file.parent && !chargeOnBudget(srv, file)) { file.excluded = true; } else if (timeBudget) { var startTime = +new Date; infer.withTimeout(timeBudget[0], function() { analyzeFile(srv, file); }); timeBudget[0] -= +new Date - startTime; } else { analyzeFile(srv, file); } } } if (done) c(); else waitOnFetch(srv, timeBudget, c); } function firstLine(str) { var end = str.indexOf("\n"); if (end < 0) return str; return str.slice(0, end); } function findMatchingPosition(line, file, near) { var pos = Math.max(0, near - 500), closest = null; if (!/^\s*$/.test(line)) for (;;) { var found = file.indexOf(line, pos); if (found < 0 || found > near + 500) break; if (closest == null || Math.abs(closest - near) > Math.abs(found - near)) closest = found; pos = found + line.length; } return closest; } function scopeDepth(s) { for (var i = 0; s; ++i, s = s.prev) {} return i; } function ternError(msg) { var err = new Error(msg); err.name = "TernError"; return err; } function resolveFile(srv, localFiles, name) { var isRef = name.match(/^#(\d+)$/); if (!isRef) return srv.findFile(name); var file = localFiles[isRef[1]]; if (!file || file.type == "delete") throw ternError("Reference to unknown file " + name); if (file.type == "full") return srv.findFile(file.name); // This is a partial file var realFile = file.backing = srv.findFile(file.name); var offset = file.offset; if (file.offsetLines) offset = {line: file.offsetLines, ch: 0}; file.offset = offset = resolvePos(realFile, file.offsetLines == null ? file.offset : {line: file.offsetLines, ch: 0}, true); var line = firstLine(file.text); var foundPos = findMatchingPosition(line, realFile.text, offset); var pos = foundPos == null ? Math.max(0, realFile.text.lastIndexOf("\n", offset)) : foundPos; var inObject, atFunction; infer.withContext(srv.cx, function() { infer.purge(file.name, pos, pos + file.text.length); var text = file.text, m; if (m = text.match(/(?:"([^"]*)"|([\w$]+))\s*:\s*function\b/)) { var objNode = walk.findNodeAround(file.backing.ast, pos, "ObjectExpression"); if (objNode && objNode.node.objType) inObject = {type: objNode.node.objType, prop: m[2] || m[1]}; } if (foundPos && (m = line.match(/^(.*?)\bfunction\b/))) { var cut = m[1].length, white = ""; for (var i = 0; i < cut; ++i) white += " "; text = white + text.slice(cut); atFunction = true; } var scopeStart = infer.scopeAt(realFile.ast, pos, realFile.scope); var scopeEnd = infer.scopeAt(realFile.ast, pos + text.length, realFile.scope); var scope = file.scope = scopeDepth(scopeStart) < scopeDepth(scopeEnd) ? scopeEnd : scopeStart; file.ast = infer.parse(file.text, srv.passes, {directSourceFile: file, allowReturnOutsideFunction: true}); infer.analyze(file.ast, file.name, scope, srv.passes); // This is a kludge to tie together the function types (if any) // outside and inside of the fragment, so that arguments and // return values have some information known about them. tieTogether: if (inObject || atFunction) { var newInner = infer.scopeAt(file.ast, line.length, scopeStart); if (!newInner.fnType) break tieTogether; if (inObject) { var prop = inObject.type.getProp(inObject.prop); prop.addType(newInner.fnType); } else if (atFunction) { var inner = infer.scopeAt(realFile.ast, pos + line.length, realFile.scope); if (inner == scopeStart || !inner.fnType) break tieTogether; var fOld = inner.fnType, fNew = newInner.fnType; if (!fNew || (fNew.name != fOld.name && fOld.name)) break tieTogether; for (var i = 0, e = Math.min(fOld.args.length, fNew.args.length); i < e; ++i) fOld.args[i].propagate(fNew.args[i]); fOld.self.propagate(fNew.self); fNew.retval.propagate(fOld.retval); } } }); return file; } // Budget management function astSize(node) { var size = 0; walk.simple(node, {Expression: function() { ++size; }}); return size; } function parentDepth(srv, parent) { var depth = 0; while (parent) { parent = srv.findFile(parent).parent; ++depth; } return depth; } function budgetName(srv, file) { for (;;) { var parent = srv.findFile(file.parent); if (!parent.parent) break; file = parent; } return file.name; } function chargeOnBudget(srv, file) { var bName = budgetName(srv, file); var size = astSize(file.ast); var known = srv.budgets[bName]; if (known == null) known = srv.budgets[bName] = srv.options.dependencyBudget; if (known < size) return false; srv.budgets[bName] = known - size; return true; } // Query helpers function isPosition(val) { return typeof val == "number" || typeof val == "object" && typeof val.line == "number" && typeof val.ch == "number"; } // Baseline query document validation function invalidDoc(doc) { if (doc.query) { if (typeof doc.query.type != "string") return ".query.type must be a string"; if (doc.query.start && !isPosition(doc.query.start)) return ".query.start must be a position"; if (doc.query.end && !isPosition(doc.query.end)) return ".query.end must be a position"; } if (doc.files) { if (!Array.isArray(doc.files)) return "Files property must be an array"; for (var i = 0; i < doc.files.length; ++i) { var file = doc.files[i]; if (typeof file != "object") return ".files[n] must be objects"; else if (typeof file.name != "string") return ".files[n].name must be a string"; else if (file.type == "delete") continue; else if (typeof file.text != "string") return ".files[n].text must be a string"; else if (file.type == "part") { if (!isPosition(file.offset) && typeof file.offsetLines != "number") return ".files[n].offset must be a position"; } else if (file.type != "full") return ".files[n].type must be \"full\" or \"part\""; } } } var offsetSkipLines = 25; function findLineStart(file, line) { var text = file.text, offsets = file.lineOffsets || (file.lineOffsets = [0]); var pos = 0, curLine = 0; var storePos = Math.min(Math.floor(line / offsetSkipLines), offsets.length - 1); var pos = offsets[storePos], curLine = storePos * offsetSkipLines; while (curLine < line) { ++curLine; pos = text.indexOf("\n", pos) + 1; if (pos === 0) return null; if (curLine % offsetSkipLines === 0) offsets.push(pos); } return pos; } var resolvePos = exports.resolvePos = function(file, pos, tolerant) { if (typeof pos != "number") { var lineStart = findLineStart(file, pos.line); if (lineStart == null) { if (tolerant) pos = file.text.length; else throw ternError("File doesn't contain a line " + pos.line); } else { pos = lineStart + pos.ch; } } if (pos > file.text.length) { if (tolerant) pos = file.text.length; else throw ternError("Position " + pos + " is outside of file."); } return pos; }; function asLineChar(file, pos) { if (!file) return {line: 0, ch: 0}; var offsets = file.lineOffsets || (file.lineOffsets = [0]); var text = file.text, line, lineStart; for (var i = offsets.length - 1; i >= 0; --i) if (offsets[i] <= pos) { line = i * offsetSkipLines; lineStart = offsets[i]; } for (;;) { var eol = text.indexOf("\n", lineStart); if (eol >= pos || eol < 0) break; lineStart = eol + 1; ++line; } return {line: line, ch: pos - lineStart}; } var outputPos = exports.outputPos = function(query, file, pos) { if (query.lineCharPositions) { var out = asLineChar(file, pos); if (file.type == "part") out.line += file.offsetLines != null ? file.offsetLines : asLineChar(file.backing, file.offset).line; return out; } else { return pos + (file.type == "part" ? file.offset : 0); } }; // Delete empty fields from result objects function clean(obj) { for (var prop in obj) if (obj[prop] == null) delete obj[prop]; return obj; } function maybeSet(obj, prop, val) { if (val != null) obj[prop] = val; } // Built-in query types function compareCompletions(a, b) { if (typeof a != "string") { a = a.name; b = b.name; } var aUp = /^[A-Z]/.test(a), bUp = /^[A-Z]/.test(b); if (aUp == bUp) return a < b ? -1 : a == b ? 0 : 1; else return aUp ? 1 : -1; } function isStringAround(node, start, end) { return node.type == "Literal" && typeof node.value == "string" && node.start == start - 1 && node.end <= end + 1; } function pointInProp(objNode, point) { for (var i = 0; i < objNode.properties.length; i++) { var curProp = objNode.properties[i]; if (curProp.key.start <= point && curProp.key.end >= point) return {type: 'key', node: curProp}; if (curProp.value.start <= point && curProp.value.end >= point) return {type: 'value', node: curProp}; } } var jsKeywords = ("break do instanceof typeof case else new var " + "catch finally return void continue for switch while debugger " + "function this with default if throw delete in try").split(" "); function findCompletions(srv, query, file) { if (query.end == null) throw ternError("missing .query.end field"); if (srv.passes.completion) for (var i = 0; i < srv.passes.completion.length; i++) { var result = srv.passes.completion[i](file, query); if (result) return result; } var wordStart = resolvePos(file, query.end), wordEnd = wordStart, text = file.text; while (wordStart && acorn.isIdentifierChar(text.charCodeAt(wordStart - 1))) --wordStart; if (query.expandWordForward !== false) while (wordEnd < text.length && acorn.isIdentifierChar(text.charCodeAt(wordEnd))) ++wordEnd; var word = text.slice(wordStart, wordEnd), completions = [], ignoreObj; if (query.caseInsensitive) word = word.toLowerCase(); var wrapAsObjs = query.types || query.depths || query.docs || query.urls || query.origins; function gather(prop, obj, depth, addInfo) { // 'hasOwnProperty' and such are usually just noise, leave them // out when no prefix is provided. if (query.omitObjectPrototype !== false && obj == srv.cx.protos.Object && !word) return; if (query.filter !== false && word && (query.caseInsensitive ? prop.toLowerCase() : prop).indexOf(word) !== 0) return; if (ignoreObj && ignoreObj.props[prop]) return; for (var i = 0; i < completions.length; ++i) { var c = completions[i]; if ((wrapAsObjs ? c.name : c) == prop) return; } var rec = wrapAsObjs ? {name: prop} : prop; completions.push(rec); if (obj && (query.types || query.docs || query.urls || query.origins)) { var val = obj.props[prop]; infer.resetGuessing(); var type = val.getType(); rec.guess = infer.didGuess(); if (query.types) rec.type = infer.toString(type); if (query.docs) maybeSet(rec, "doc", val.doc || type && type.doc); if (query.urls) maybeSet(rec, "url", val.url || type && type.url); if (query.origins) maybeSet(rec, "origin", val.origin || type && type.origin); } if (query.depths) rec.depth = depth; if (wrapAsObjs && addInfo) addInfo(rec); } var hookname, prop, objType, isKey, isValue; var exprAt = infer.findExpressionAround(file.ast, null, wordStart, file.scope); var memberExpr, objLit; // Decide whether this is an object property, either in a member // expression or an object literal. if (exprAt) { if (exprAt.node.type == "MemberExpression" && exprAt.node.object.end < wordStart) { memberExpr = exprAt; } else if (isStringAround(exprAt.node, wordStart, wordEnd)) { var parent = infer.parentNode(exprAt.node, file.ast); if (parent.type == "MemberExpression" && parent.property == exprAt.node) memberExpr = {node: parent, state: exprAt.state}; else if (parent.type == "Property") { var objNode = infer.parentNode(parent, file.ast); objLit = {node: objNode, state: exprAt.state}; prop = objProp.key.name ? objProp.key.name : objProp.key.value; isValue = true; } } else if (exprAt.node.type == "ObjectExpression") { var objProp = pointInProp(exprAt.node, wordEnd); if (objProp) { objLit = exprAt; prop = objProp.node[objProp.type].name ? objProp.node[objProp.type].name : objProp.node[objProp.type].value; isKey = objProp.type == 'key', isValue = !isKey; } else if (!word && !/:\s*$/.test(file.text.slice(0, wordStart))) { objLit = exprAt; prop = isKey = true; } else { objLit = exprAt; prop = isValue = true; } } } if (objLit) { // Since we can't use the type of the literal itself to complete // its properties (it doesn't contain the information we need), // we have to try asking the surrounding expression for type info. objType = infer.typeFromContext(file.ast, objLit); if (isValue) { prop = false; } else { ignoreObj = objLit.node.objType; } } else if (memberExpr) { prop = memberExpr.node.property; prop = prop.type == "Literal" ? prop.value.slice(1) : prop.name; memberExpr.node = memberExpr.node.object; objType = infer.expressionType(memberExpr); } else if (text.charAt(wordStart - 1) == ".") { var pathStart = wordStart - 1; while (pathStart && (text.charAt(pathStart - 1) == "." || acorn.isIdentifierChar(text.charCodeAt(pathStart - 1)))) pathStart--; var path = text.slice(pathStart, wordStart - 1); if (path) { objType = infer.def.parsePath(path, file.scope).getType(); prop = word; } } if (prop != null) { srv.cx.completingProperty = prop; if (objType) infer.forAllPropertiesOf(objType, gather); if (!completions.length && query.guess !== false && objType && objType.guessProperties) objType.guessProperties(function(p, o, d) {if (p != prop && p != "✖") gather(p, o, d);}); if (!completions.length && word.length >= 2 && query.guess !== false) for (var prop in srv.cx.props) gather(prop, srv.cx.props[prop][0], 0); hookname = "memberCompletion"; } else { infer.forAllLocalsAt(file.ast, wordStart, file.scope, gather); if (query.includeKeywords) jsKeywords.forEach(function(kw) { gather(kw, null, 0, function(rec) { rec.isKeyword = true; }); }); hookname = "variableCompletion"; } if (srv.passes[hookname]) srv.passes[hookname].forEach(function(hook) {hook(file, wordStart, wordEnd, gather);}); if (query.sort !== false) completions.sort(compareCompletions); srv.cx.completingProperty = null; return {start: outputPos(query, file, wordStart), end: outputPos(query, file, wordEnd), isProperty: !!prop, isObjectKey: isKey, completions: completions}; } function findProperties(srv, query) { var prefix = query.prefix, found = []; for (var prop in srv.cx.props) if (prop != "<i>" && (!prefix || prop.indexOf(prefix) === 0)) found.push(prop); if (query.sort !== false) found.sort(compareCompletions); return {completions: found}; } var findExpr = exports.findQueryExpr = function(file, query, wide) { if (query.end == null) throw ternError("missing .query.end field"); if (query.variable) { var scope = infer.scopeAt(file.ast, resolvePos(file, query.end), file.scope); return {node: {type: "Identifier", name: query.variable, start: query.end, end: query.end + 1}, state: scope}; } else { var start = query.start && resolvePos(file, query.start), end = resolvePos(file, query.end); var expr = infer.findExpressionAt(file.ast, start, end, file.scope); if (expr) return expr; expr = infer.findExpressionAround(file.ast, start, end, file.scope); if (expr && (expr.node.type == "ObjectExpression" || wide || (start == null ? end : start) - expr.node.start < 20 || expr.node.end - end < 20)) return expr; return null; } }; function findExprOrThrow(file, query, wide) { var expr = findExpr(file, query, wide); if (expr) return expr; throw ternError("No expression at the given position."); } function ensureObj(tp) { if (!tp || !(tp = tp.getType()) || !(tp instanceof infer.Obj)) return null; return tp; } function findExprType(srv, query, file, expr) { var type; if (expr) { infer.resetGuessing(); type = infer.expressionType(expr); } if (srv.passes["typeAt"]) { var pos = resolvePos(file, query.end); srv.passes["typeAt"].forEach(function(hook) { type = hook(file, pos, expr, type); }); } if (!type) throw ternError("No type found at the given position."); var objProp; if (expr.node.type == "ObjectExpression" && query.end != null && (objProp = pointInProp(expr.node, resolvePos(file, query.end)))) { var name = objProp.key.name; var fromCx = ensureObj(infer.typeFromContext(file.ast, expr)); if (fromCx && fromCx.hasProp(name)) { type = fromCx.props[name]; } else { var fromLocal = ensureObj(type); if (fromLocal && fromLocal.hasProp(name)) type = fromLocal.props[name]; } } return type; }; function findTypeAt(srv, query, file) { var expr = findExpr(file, query), exprName; var type = findExprType(srv, query, file, expr), exprType = type; if (query.preferFunction) type = type.getFunctionType() || type.getType(); else type = type.getType(); if (expr) { if (expr.node.type == "Identifier") exprName = expr.node.name; else if (expr.node.type == "MemberExpression" && !expr.node.computed) exprName = expr.node.property.name; } if (query.depth != null && typeof query.depth != "number") throw ternError(".query.depth must be a number"); var result = {guess: infer.didGuess(), type: infer.toString(type, query.depth), name: type && type.name, exprName: exprName}; if (type) storeTypeDocs(type, result); if (!result.doc && exprType.doc) result.doc = exprType.doc; return clean(result); } function findDocs(srv, query, file) { var expr = findExpr(file, query); var type = findExprType(srv, query, file, expr); var result = {url: type.url, doc: type.doc, type: infer.toString(type.getType())}; var inner = type.getType(); if (inner) storeTypeDocs(inner, result); return clean(result); } function storeTypeDocs(type, out) { if (!out.url) out.url = type.url; if (!out.doc) out.doc = type.doc; if (!out.origin) out.origin = type.origin; var ctor, boring = infer.cx().protos; if (!out.url && !out.doc && type.proto && (ctor = type.proto.hasCtor) && type.proto != boring.Object && type.proto != boring.Function && type.proto != boring.Array) { out.url = ctor.url; out.doc = ctor.doc; } } var getSpan = exports.getSpan = function(obj) { if (!obj.origin) return; if (obj.originNode) { var node = obj.originNode; if (/^Function/.test(node.type) && node.id) node = node.id; return {origin: obj.origin, node: node}; } if (obj.span) return {origin: obj.origin, span: obj.span}; }; var storeSpan = exports.storeSpan = function(srv, query, span, target) { target.origin = span.origin; if (span.span) { var m = /^(\d+)\[(\d+):(\d+)\]-(\d+)\[(\d+):(\d+)\]$/.exec(span.span); target.start = query.lineCharPositions ? {line: Number(m[2]), ch: Number(m[3])} : Number(m[1]); target.end = query.lineCharPositions ? {line: Number(m[5]), ch: Number(m[6])} : Number(m[4]); } else { var file = srv.findFile(span.origin); target.start = outputPos(query, file, span.node.start); target.end = outputPos(query, file, span.node.end); } }; function findDef(srv, query, file) { var expr = findExpr(file, query); var type = findExprType(srv, query, file, expr); if (infer.didGuess()) return {}; var span = getSpan(type); var result = {url: type.url, doc: type.doc, origin: type.origin}; if (type.types) for (var i = type.types.length - 1; i >= 0; --i) { var tp = type.types[i]; storeTypeDocs(tp, result); if (!span) span = getSpan(tp); } if (span && span.node) { // refers to a loaded file var spanFile = span.node.sourceFile || srv.findFile(span.origin); var start = outputPos(query, spanFile, span.node.start), end = outputPos(query, spanFile, span.node.end); result.start = start; result.end = end; result.file = span.origin; var cxStart = Math.max(0, span.node.start - 50); result.contextOffset = span.node.start - cxStart; result.context = spanFile.text.slice(cxStart, cxStart + 50); } else if (span) { // external result.file = span.origin; storeSpan(srv, query, span, result); } return clean(result); } function findRefsToVariable(srv, query, file, expr, checkShadowing) { var name = expr.node.name; for (var scope = expr.state; scope && !(name in scope.props); scope = scope.prev) {} if (!scope) throw ternError("Could not find a definition for " + name + " " + !!srv.cx.topScope.props.x); var type, refs = []; function storeRef(file) { return function(node, scopeHere) { if (checkShadowing) for (var s = scopeHere; s != scope; s = s.prev) { var exists = s.hasProp(checkShadowing); if (exists) throw ternError("Renaming `" + name + "` to `" + checkShadowing + "` would make a variable at line " + (asLineChar(file, node.start).line + 1) + " point to the definition at line " + (asLineChar(file, exists.name.start).line + 1)); } refs.push({file: file.name, start: outputPos(query, file, node.start), end: outputPos(query, file, node.end)}); }; } if (scope.originNode) { type = "local"; if (checkShadowing) { for (var prev = scope.prev; prev; prev = prev.prev) if (checkShadowing in prev.props) break; if (prev) infer.findRefs(scope.originNode, scope, checkShadowing, prev, function(node) { throw ternError("Renaming `" + name + "` to `" + checkShadowing + "` would shadow the definition used at line " + (asLineChar(file, node.start).line + 1)); }); } infer.findRefs(scope.originNode, scope, name, scope, storeRef(file)); } else { type = "global"; for (var i = 0; i < srv.files.length; ++i) { var cur = srv.files[i]; infer.findRefs(cur.ast, cur.scope, name, scope, storeRef(cur)); } } return {refs: refs, type: type, name: name}; } function findRefsToProperty(srv, query, expr, prop) { var objType = infer.expressionType(expr).getType(); if (!objType) throw ternError("Couldn't determine type of base object."); var refs = []; function storeRef(file) { return function(node) { refs.push({file: file.name, start: outputPos(query, file, node.start), end: outputPos(query, file, node.end)}); }; } for (var i = 0; i < srv.files.length; ++i) { var cur = srv.files[i]; infer.findPropRefs(cur.ast, cur.scope, objType, prop.name, storeRef(cur)); } return {refs: refs, name: prop.name}; } function findRefs(srv, query, file) { var expr = findExprOrThrow(file, query, true); if (expr && expr.node.type == "Identifier") { return findRefsToVariable(srv, query, file, expr); } else if (expr && expr.node.type == "MemberExpression" && !expr.node.computed) { var p = expr.node.property; expr.node = expr.node.object; return findRefsToProperty(srv, query, expr, p); } else if (expr && expr.node.type == "ObjectExpression") { var pos = resolvePos(file, query.end); for (var i = 0; i < expr.node.properties.length; ++i) { var k = expr.node.properties[i].key; if (k.start <= pos && k.end >= pos) return findRefsToProperty(srv, query, expr, k); } } throw ternError("Not at a variable or property name."); } function buildRename(srv, query, file) { if (typeof query.newName != "string") throw ternError(".query.newName should be a string"); var expr = findExprOrThrow(file, query); if (!expr || expr.node.type != "Identifier") throw ternError("Not at a variable."); var data = findRefsToVariable(srv, query, file, expr, query.newName), refs = data.refs; delete data.refs; data.files = srv.files.map(function(f){return f.name;}); var changes = data.changes = []; for (var i = 0; i < refs.length; ++i) { var use = refs[i]; use.text = query.newName; changes.push(use); } return data; } function listFiles(srv) { return {files: srv.files.map(function(f){return f.name;})}; } exports.version = "0.7.1"; });
'use strict'; export default { user: { username: { match: /^[a-zA-Z0-9_]{4,12}$/i, note: '' }, password: { match: /^[a-zA-Z0-9_-]{6,18}$/i, note: '' } } }
import React from 'react' import ReactDOM from 'react-dom/server' import { createResolveStore, ResolveReduxProvider } from '@resolve-js/redux' import { StaticRouter } from 'react-router' import { renderRoutes } from 'react-router-config' import { Helmet } from 'react-helmet' import { createMemoryHistory } from 'history' import jsonwebtoken from 'jsonwebtoken' import { getRoutes } from './get-routes' import { getRedux } from './get-redux' const ssrHandler = async (serverContext, req, res) => { try { const { constants, seedClientEnvs, utils, viewModels } = serverContext const { getRootBasedUrl, getStaticBasedPath, jsonUtfStringify } = utils const { rootPath, staticPath, jwtCookie } = constants const history = createMemoryHistory() const baseQueryUrl = getRootBasedUrl(rootPath, '/') const url = req.path.substring(baseQueryUrl.length) history.push(url) const redux = getRedux() const routes = getRoutes() const jwt = {} try { Object.assign(jwt, jsonwebtoken.decode(req.cookies[jwtCookie.name])) } catch (e) {} const resolveContext = { ...constants, viewModels, origin: '', } const store = createResolveStore( resolveContext, { initialState: { jwt }, redux, }, false ) const staticContext = {} const markup = ReactDOM.renderToStaticMarkup( <ResolveReduxProvider context={resolveContext} store={store}> <StaticRouter location={url} context={staticContext}> {renderRoutes(routes)} </StaticRouter> </ResolveReduxProvider> ) const initialState = store.getState() const bundleUrl = getStaticBasedPath(rootPath, staticPath, 'index.js') const faviconUrl = getStaticBasedPath(rootPath, staticPath, 'favicon.png') const helmet = Helmet.renderStatic() const markupHtml = `<!doctype html>` + `<html ${helmet.htmlAttributes.toString()}>` + '<head>' + `<link rel="icon" type="image/x-icon" href="${faviconUrl}" />` + `${helmet.title.toString()}` + `${helmet.meta.toString()}` + `${helmet.link.toString()}` + `${helmet.style.toString()}` + '<script>' + `window.__INITIAL_STATE__=${jsonUtfStringify(initialState)};` + `window.__RESOLVE_RUNTIME_ENV__=${jsonUtfStringify(seedClientEnvs)};` + '</script>' + `${helmet.script.toString()}` + '</head>' + `<body ${helmet.bodyAttributes.toString()}>` + `<div id="app-container">${markup}</div>` + `<script src="${bundleUrl}"></script>` + '</body>' + '</html>' await res.setHeader('Content-Type', 'text/html') await res.end(markupHtml) } catch (error) { // eslint-disable-next-line no-console console.warn('SSR error', error) res.status(500) res.end('SSR error') } } export default ssrHandler
//Modal View define(["jquery", "backbone"], function($, Backbone) { // Backbone.ModalDialog.js v0.3.2 // // Copyright (C)2012 Gareth Elms // Distributed under MIT License // // Documentation and full license availabe at: // https://github.com/GarethElms/BackboneJSModalView ModalView = Backbone.View.extend( { name: "ModalView", modalBlanket: null, modalContainer: null, defaultOptions: { fadeInDuration:150, fadeOutDuration:150, showCloseButton:true, bodyOverflowHidden:false, setFocusOnFirstFormControl:true, targetContainer: document.body, slideFromAbove: false, slideFromBelow: false, slideDistance: 150, closeImageUrl: "/img/close-modal.png", closeImageHoverUrl: "/img/close-modal-hover.png", showModalAtScrollPosition: true, permanentlyVisible: false, backgroundClickClosesModal: true, pressingEscapeClosesModal: true, css: { "border": "2px solid #111", "background-color": "#fff", "-webkit-box-shadow": "0px 0px 15px 4px rgba(0, 0, 0, 0.5)", "-moz-box-shadow": "0px 0px 15px 4px rgba(0, 0, 0, 0.5)", "box-shadow": "0px 0px 15px 4px rgba(0, 0, 0, 0.5)", "-webkit-border-radius": "10px", "-moz-border-radius": "10px", "border-radius": "10px" } }, initialize: function() { }, events: { }, showModalBlanket: function() { return this.ensureModalBlanket().fadeIn( this.options.fadeInDuration); }, hideModalBlanket: function() { return this.modalBlanket.fadeOut( this.options.fadeOutDuration); }, ensureModalContainer: function( target) { if( target != null) { // A target is passed in, we need to re-render the modal container into the target. if( this.modalContainer != null) { this.modalContainer.remove(); this.modalContainer = null; } } if( this.modalContainer == null) { this.modalContainer = $("<div id='modalContainer'>") .css({ "z-index":"99999", "position":"relative", "-webkit-border-radius": "6px", "-moz-border-radius": "6px", "border-radius": "6px" }) .appendTo( target); } return this.modalContainer; }, ensureModalBlanket: function() { this.modalBlanket = $("#modal-blanket"); if( this.modalBlanket.length == 0) { this.modalBlanket = $("<div id='modal-blanket'>") .css( { position: "absolute", top: 0, left: 0, height: $(document).height(), // Span the full document height... width: "100%", // ...and full width opacity: 0.5, // Make it slightly transparent backgroundColor: "#000", "z-index": 99900 }) .appendTo( document.body) .hide(); } else { // Ensure the blanket spans the whole document, screen may have been updated. this.modalBlanket.css( { height: $(document).height(), // Span the full document height... width: "100%" // ...and full width }); } return this.modalBlanket; }, keyup: function( event) { if( event.keyCode == 27 && this.options.pressingEscapeClosesModal) { this.hideModal(); } }, click: function( event) { if( event.target.id == "modal-blanket" && this.options.backgroundClickClosesModal) { this.hideModal(); } }, setFocusOnFirstFormControl: function() { var controls = $("input, select, email, url, number, range, date, month, week, time, datetime, datetime-local, search, color", $(this.el)); if( controls.length > 0) { $(controls[0]).focus(); } }, hideModal: function() { this.trigger( "closeModalWindow"); this.hideModalBlanket(); $(document.body).unbind( "keyup", this.keyup); this.modalBlanket.unbind( "click", this.click); if( this.options.bodyOverflowHidden === true) { $(document.body).css( "overflow", this.originalBodyOverflowValue); } var container = this.modalContainer; $(this.modalContainer) .fadeOut( this.options.fadeOutDuration, function() { container.remove(); }); }, getCoordinate: function( coordinate, css) { if( typeof( css[coordinate]) !== "undefined") { var value = css[coordinate]; delete css[coordinate]; // Don't apply positioning to the $el, we apply it to the modal container. Remove it from options.css return value; } }, recenter: function() { return this.recentre(); }, recentre: // Re-centre the modal dialog after it has been displayed. Useful if the height changes after initial rendering eg; jquery ui tabs will hide tab sections function() { var $el = $(this.el); var coords = { top: this.getCoordinate( "top", this.options.css), left: this.getCoordinate( "left", this.options.css), right: this.getCoordinate( "right", this.options.css), bottom: this.getCoordinate( "bottom", this.options.css), isEmpty: function(){return (this.top == null && this.left == null && this.right == null && this.bottom == null);} }; var offsets = this.getOffsets(); var centreY = $(window).height() / 2; var centreX = $(window).width() / 2; var modalContainer = this.modalContainer; var positionY = centreY - ($el.outerHeight() / 2); modalContainer.css({"top": (positionY + offsets.y) + "px"}); var positionX = centreX - ($el.outerWidth() / 2); modalContainer.css({"left": (positionX + offsets.x) + "px"}); return this; }, getOffsets: function() { var offsetY = 0, offsetX = 0; if( this.options.showModalAtScrollPosition) { offsetY = $(document).scrollTop(), offsetX = $(document).scrollLeft() } return {x:offsetX, y:offsetY}; }, showModal: function( options) { this.defaultOptions.targetContainer = document.body; this.options = $.extend( true, {}, this.defaultOptions, options, this.options); if( this.options.permanentlyVisible) { this.options.showCloseButton = false; this.options.backgroundClickClosesModal = false; this.options.pressingEscapeClosesModal = false; } //Set the center alignment padding + border see css style var $el = $(this.el); var centreY = $(window).height() / 2; var centreX = $(window).width() / 2; var modalContainer = this.ensureModalContainer( this.options.targetContainer).empty(); $el.addClass( "modal"); var coords = { top: this.getCoordinate( "top", this.options.css), left: this.getCoordinate( "left", this.options.css), right: this.getCoordinate( "right", this.options.css), bottom: this.getCoordinate( "bottom", this.options.css), isEmpty: function(){return (this.top == null && this.left == null && this.right == null && this.bottom == null);} }; $el.css( this.options.css); this.showModalBlanket(); this.keyup = _.bind( this.keyup, this); this.click = _.bind( this.click, this); $(document.body).keyup( this.keyup); // This handler is unbound in hideModal() this.modalBlanket.click( this.click); // This handler is unbound in hideModal() if( this.options.bodyOverflowHidden === true) { this.originalBodyOverflowValue = $(document.body).css( "overflow"); $(document.body).css( "overflow", "hidden"); } modalContainer .append( $el); modalContainer.css({ "opacity": 0, "position": "absolute", "z-index": 999999}); var offsets = this.getOffsets(); // Only apply default centre coordinates if no css positions have been supplied if( coords.isEmpty()) { var positionY = centreY - ($el.outerHeight() / 2); if( positionY < 10) positionY = 10; // Overriding the coordinates with explicit values if they are passed in if( typeof( this.options.y) !== "undefined") { positionY = this.options.y; } else { positionY += offsets.y; } modalContainer.css({"top": positionY + "px"}); var positionX = centreX - ($el.outerWidth() / 2); // Overriding the coordinates with explicit values if they are passed in if( typeof( this.options.x) !== "undefined") { positionX = this.options.x; } else { positionX += offsets.x; } modalContainer.css({"left": positionX + "px"}); } else { if( coords.top != null) modalContainer.css({"top": coords.top + offsets.y}); if( coords.left != null) modalContainer.css({"left": coords.left + offsets.x}); if( coords.right != null) modalContainer.css({"right": coords.right}); if( coords.bottom != null) modalContainer.css({"bottom": coords.bottom}); } if( this.options.setFocusOnFirstFormControl) { this.setFocusOnFirstFormControl(); } if( this.options.showCloseButton) { var view = this; var image = $("<a href='#' id='modalCloseButton'>&#160;</a>") .css({ "position":"absolute", "top":"-10px", "right":"-10px", "width":"32px", "height":"32px", "background":"transparent url(" + view.options.closeImageUrl + ") top left no-repeat", "text-decoration":"none"}) .appendTo( this.modalContainer) .hover( function() { $(this).css( "background-image", "url(" + view.options.closeImageHoverUrl + ") !important"); }, function() { $(this).css( "background-image", "url(" + view.options.closeImageUrl + ") !important"); }) .click( function( event) { event.preventDefault(); view.hideModal(); }); } var animateProperties = {opacity:1}; var modalOffset = modalContainer.offset(); if( this.options.slideFromAbove) { modalContainer.css({"top": (modalOffset.top - this.options.slideDistance) + "px"}); animateProperties.top = coords.top; } if( this.options.slideFromBelow) { modalContainer.css({"top": (modalOffset.top + this.options.slideDistance) + "px"}); animateProperties.top = coords.top; } this.modalContainer.animate( animateProperties, this.options.fadeInDuration); return this; } }); // Returns the View class return ModalView; } );
$(document).ready(function(){ var windowHeight = $(window).height(); var navbarHeight = $('nav').outerHeight(true); var footerHeight = $('footer').outerHeight(true); var frontLeft = $('.front-left').outerHeight(true); var vcenter = $('.vcenter').outerHeight(true); var contentHeight = windowHeight - (navbarHeight + footerHeight); $('.front-left').css('padding-top', (contentHeight - frontLeft) / 2.5); $('.vcenter').css('padding-top', (contentHeight - vcenter) / 2.5); });
/** * Created by diakabanab on 11/5/2016. */ define(["jquery", "wheel/Colors", "chord.sass", "chord/Positions", "tinycolor2"], function($, Colors, chordStyle, Positions, TinyColor) { /** * Draws chord wheel */ var Wheel = function(container) { this.canvas = $("<canvas>", { id : "Canvas" }).appendTo(container); // width and height of the wheel this.radius = this.canvas.width(); this.center = this.canvas.width(); this.innerRadius = 0.66 * this.radius; // notes and keys this.currentLetter = "C"; this.currentKey = "major"; // context this.context = this.canvas.get(0).getContext("2d"); this.resize(); $(window).on("resize", this.resize.bind(this)); }; var minorColors = {}; for (var key in Colors) { var color = TinyColor(Colors[key]); color.darken(10); minorColors[key] = color.toRgbString(); } Wheel.prototype.resize = function() { this.radius = Math.min(this.canvas.width(), this.canvas.height()); this.center = this.radius; this.context.canvas.width = this.canvas.width() * 2; this.context.canvas.height = this.canvas.height() * 2; this.innerRadius = 0.66 * this.radius; }; Wheel.prototype.draw = function(highlightLetter, major) { this.curentLetter = highlightLetter; this.currentKey = major; this.context.clearRect(0, 0, this.context.canvas.width, this.context.canvas.height); major = major === "major"; var centerX = this.canvas.width(); var centerY = this.canvas.height(); // draws the major notes first for (var majorChordLetter in positions.major) { var majorChord = Positions.major[majorChordLetter]; if (majorChordLetter == highlightLetter && major) { this.context.fillStyle = "black" } else { this.context.fillStyle = Colors[majorChordLetter]; } this.context.beginPath(); this.context.moveTo(centerX, centerY); this.context.arc(centerX, centerY, this.radius * majorChord.outerRadius, majorChord.startAngle, majorChord.endAngle, false); this.context.fill(); } // and now the minor notes for (var minorChordLetter in positions.minor) { var minorChord = Positions.minor[minorChordLetter]; if (minorChordLetter == highlightLetter && !major) { this.context.fillStyle = "black" } else { this.context.fillStyle = Colors[minorChordLetter]; } this.context.beginPath(); this.context.moveTo(centerX, centerY); this.context.arc(centerX, centerY, this.radius * minorChord.outerRadius, minorChord.startAngle, minorChord.endAngle, false); this.context.fill(); } }; return Wheel; });
/*global define */ /*jslint white:true */ define(["kb/thrift/core", "./assembly_types"], function (Thrift, assembly) { "use strict"; // // Autogenerated by Thrift Compiler (0.9.2) // // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING // //HELPER FUNCTIONS AND STRUCTURES assembly.thrift_service_get_assembly_id_args = function(args) { this.token = null; this.ref = null; if (args) { if (args.token !== undefined) { this.token = args.token; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field token is unset!'); } if (args.ref !== undefined) { this.ref = args.ref; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field ref is unset!'); } } }; assembly.thrift_service_get_assembly_id_args.prototype = {}; assembly.thrift_service_get_assembly_id_args.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype === Thrift.Type.STRING) { this.token = input.readString().value; } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRING) { this.ref = input.readString().value; } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_assembly_id_args.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_assembly_id_args'); if (this.token !== null && this.token !== undefined) { output.writeFieldBegin('token', Thrift.Type.STRING, 1); output.writeString(this.token); output.writeFieldEnd(); } if (this.ref !== null && this.ref !== undefined) { output.writeFieldBegin('ref', Thrift.Type.STRING, 2); output.writeString(this.ref); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_assembly_id_result = function(args) { this.success = null; this.generic_exception = null; this.authorization_exception = null; this.authentication_exception = null; this.reference_exception = null; this.attribute_exception = null; this.type_exception = null; if (args instanceof assembly.ServiceException) { this.generic_exception = args; return; } if (args instanceof assembly.AuthorizationException) { this.authorization_exception = args; return; } if (args instanceof assembly.AuthenticationException) { this.authentication_exception = args; return; } if (args instanceof assembly.ObjectReferenceException) { this.reference_exception = args; return; } if (args instanceof assembly.AttributeException) { this.attribute_exception = args; return; } if (args instanceof assembly.TypeException) { this.type_exception = args; return; } if (args) { if (args.success !== undefined) { this.success = args.success; } if (args.generic_exception !== undefined) { this.generic_exception = args.generic_exception; } if (args.authorization_exception !== undefined) { this.authorization_exception = args.authorization_exception; } if (args.authentication_exception !== undefined) { this.authentication_exception = args.authentication_exception; } if (args.reference_exception !== undefined) { this.reference_exception = args.reference_exception; } if (args.attribute_exception !== undefined) { this.attribute_exception = args.attribute_exception; } if (args.type_exception !== undefined) { this.type_exception = args.type_exception; } } }; assembly.thrift_service_get_assembly_id_result.prototype = {}; assembly.thrift_service_get_assembly_id_result.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 0: if (ftype === Thrift.Type.STRING) { this.success = input.readString().value; } else { input.skip(ftype); } break; case 1: if (ftype === Thrift.Type.STRUCT) { this.generic_exception = new assembly.ServiceException(); this.generic_exception.read(input); } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRUCT) { this.authorization_exception = new assembly.AuthorizationException(); this.authorization_exception.read(input); } else { input.skip(ftype); } break; case 3: if (ftype === Thrift.Type.STRUCT) { this.authentication_exception = new assembly.AuthenticationException(); this.authentication_exception.read(input); } else { input.skip(ftype); } break; case 4: if (ftype === Thrift.Type.STRUCT) { this.reference_exception = new assembly.ObjectReferenceException(); this.reference_exception.read(input); } else { input.skip(ftype); } break; case 5: if (ftype === Thrift.Type.STRUCT) { this.attribute_exception = new assembly.AttributeException(); this.attribute_exception.read(input); } else { input.skip(ftype); } break; case 6: if (ftype === Thrift.Type.STRUCT) { this.type_exception = new assembly.TypeException(); this.type_exception.read(input); } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_assembly_id_result.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_assembly_id_result'); if (this.success !== null && this.success !== undefined) { output.writeFieldBegin('success', Thrift.Type.STRING, 0); output.writeString(this.success); output.writeFieldEnd(); } if (this.generic_exception !== null && this.generic_exception !== undefined) { output.writeFieldBegin('generic_exception', Thrift.Type.STRUCT, 1); this.generic_exception.write(output); output.writeFieldEnd(); } if (this.authorization_exception !== null && this.authorization_exception !== undefined) { output.writeFieldBegin('authorization_exception', Thrift.Type.STRUCT, 2); this.authorization_exception.write(output); output.writeFieldEnd(); } if (this.authentication_exception !== null && this.authentication_exception !== undefined) { output.writeFieldBegin('authentication_exception', Thrift.Type.STRUCT, 3); this.authentication_exception.write(output); output.writeFieldEnd(); } if (this.reference_exception !== null && this.reference_exception !== undefined) { output.writeFieldBegin('reference_exception', Thrift.Type.STRUCT, 4); this.reference_exception.write(output); output.writeFieldEnd(); } if (this.attribute_exception !== null && this.attribute_exception !== undefined) { output.writeFieldBegin('attribute_exception', Thrift.Type.STRUCT, 5); this.attribute_exception.write(output); output.writeFieldEnd(); } if (this.type_exception !== null && this.type_exception !== undefined) { output.writeFieldBegin('type_exception', Thrift.Type.STRUCT, 6); this.type_exception.write(output); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_genome_annotations_args = function(args) { this.token = null; this.ref = null; if (args) { if (args.token !== undefined) { this.token = args.token; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field token is unset!'); } if (args.ref !== undefined) { this.ref = args.ref; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field ref is unset!'); } } }; assembly.thrift_service_get_genome_annotations_args.prototype = {}; assembly.thrift_service_get_genome_annotations_args.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype === Thrift.Type.STRING) { this.token = input.readString().value; } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRING) { this.ref = input.readString().value; } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_genome_annotations_args.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_genome_annotations_args'); if (this.token !== null && this.token !== undefined) { output.writeFieldBegin('token', Thrift.Type.STRING, 1); output.writeString(this.token); output.writeFieldEnd(); } if (this.ref !== null && this.ref !== undefined) { output.writeFieldBegin('ref', Thrift.Type.STRING, 2); output.writeString(this.ref); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_genome_annotations_result = function(args) { this.success = null; this.generic_exception = null; this.authorization_exception = null; this.authentication_exception = null; this.reference_exception = null; this.attribute_exception = null; this.type_exception = null; if (args instanceof assembly.ServiceException) { this.generic_exception = args; return; } if (args instanceof assembly.AuthorizationException) { this.authorization_exception = args; return; } if (args instanceof assembly.AuthenticationException) { this.authentication_exception = args; return; } if (args instanceof assembly.ObjectReferenceException) { this.reference_exception = args; return; } if (args instanceof assembly.AttributeException) { this.attribute_exception = args; return; } if (args instanceof assembly.TypeException) { this.type_exception = args; return; } if (args) { if (args.success !== undefined) { this.success = args.success; } if (args.generic_exception !== undefined) { this.generic_exception = args.generic_exception; } if (args.authorization_exception !== undefined) { this.authorization_exception = args.authorization_exception; } if (args.authentication_exception !== undefined) { this.authentication_exception = args.authentication_exception; } if (args.reference_exception !== undefined) { this.reference_exception = args.reference_exception; } if (args.attribute_exception !== undefined) { this.attribute_exception = args.attribute_exception; } if (args.type_exception !== undefined) { this.type_exception = args.type_exception; } } }; assembly.thrift_service_get_genome_annotations_result.prototype = {}; assembly.thrift_service_get_genome_annotations_result.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 0: if (ftype === Thrift.Type.LIST) { var _size18 = 0; var _rtmp322; this.success = []; var _etype21 = 0; _rtmp322 = input.readListBegin(); _etype21 = _rtmp322.etype; _size18 = _rtmp322.size; for (var _i23 = 0; _i23 < _size18; ++_i23) { var elem24 = null; elem24 = input.readString().value; this.success.push(elem24); } input.readListEnd(); } else { input.skip(ftype); } break; case 1: if (ftype === Thrift.Type.STRUCT) { this.generic_exception = new assembly.ServiceException(); this.generic_exception.read(input); } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRUCT) { this.authorization_exception = new assembly.AuthorizationException(); this.authorization_exception.read(input); } else { input.skip(ftype); } break; case 3: if (ftype === Thrift.Type.STRUCT) { this.authentication_exception = new assembly.AuthenticationException(); this.authentication_exception.read(input); } else { input.skip(ftype); } break; case 4: if (ftype === Thrift.Type.STRUCT) { this.reference_exception = new assembly.ObjectReferenceException(); this.reference_exception.read(input); } else { input.skip(ftype); } break; case 5: if (ftype === Thrift.Type.STRUCT) { this.attribute_exception = new assembly.AttributeException(); this.attribute_exception.read(input); } else { input.skip(ftype); } break; case 6: if (ftype === Thrift.Type.STRUCT) { this.type_exception = new assembly.TypeException(); this.type_exception.read(input); } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_genome_annotations_result.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_genome_annotations_result'); if (this.success !== null && this.success !== undefined) { output.writeFieldBegin('success', Thrift.Type.LIST, 0); output.writeListBegin(Thrift.Type.STRING, this.success.length); for (var iter25 in this.success) { if (this.success.hasOwnProperty(iter25)) { iter25 = this.success[iter25]; output.writeString(iter25); } } output.writeListEnd(); output.writeFieldEnd(); } if (this.generic_exception !== null && this.generic_exception !== undefined) { output.writeFieldBegin('generic_exception', Thrift.Type.STRUCT, 1); this.generic_exception.write(output); output.writeFieldEnd(); } if (this.authorization_exception !== null && this.authorization_exception !== undefined) { output.writeFieldBegin('authorization_exception', Thrift.Type.STRUCT, 2); this.authorization_exception.write(output); output.writeFieldEnd(); } if (this.authentication_exception !== null && this.authentication_exception !== undefined) { output.writeFieldBegin('authentication_exception', Thrift.Type.STRUCT, 3); this.authentication_exception.write(output); output.writeFieldEnd(); } if (this.reference_exception !== null && this.reference_exception !== undefined) { output.writeFieldBegin('reference_exception', Thrift.Type.STRUCT, 4); this.reference_exception.write(output); output.writeFieldEnd(); } if (this.attribute_exception !== null && this.attribute_exception !== undefined) { output.writeFieldBegin('attribute_exception', Thrift.Type.STRUCT, 5); this.attribute_exception.write(output); output.writeFieldEnd(); } if (this.type_exception !== null && this.type_exception !== undefined) { output.writeFieldBegin('type_exception', Thrift.Type.STRUCT, 6); this.type_exception.write(output); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_external_source_info_args = function(args) { this.token = null; this.ref = null; if (args) { if (args.token !== undefined) { this.token = args.token; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field token is unset!'); } if (args.ref !== undefined) { this.ref = args.ref; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field ref is unset!'); } } }; assembly.thrift_service_get_external_source_info_args.prototype = {}; assembly.thrift_service_get_external_source_info_args.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype === Thrift.Type.STRING) { this.token = input.readString().value; } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRING) { this.ref = input.readString().value; } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_external_source_info_args.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_external_source_info_args'); if (this.token !== null && this.token !== undefined) { output.writeFieldBegin('token', Thrift.Type.STRING, 1); output.writeString(this.token); output.writeFieldEnd(); } if (this.ref !== null && this.ref !== undefined) { output.writeFieldBegin('ref', Thrift.Type.STRING, 2); output.writeString(this.ref); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_external_source_info_result = function(args) { this.success = null; this.generic_exception = null; this.authorization_exception = null; this.authentication_exception = null; this.reference_exception = null; this.attribute_exception = null; this.type_exception = null; if (args instanceof assembly.ServiceException) { this.generic_exception = args; return; } if (args instanceof assembly.AuthorizationException) { this.authorization_exception = args; return; } if (args instanceof assembly.AuthenticationException) { this.authentication_exception = args; return; } if (args instanceof assembly.ObjectReferenceException) { this.reference_exception = args; return; } if (args instanceof assembly.AttributeException) { this.attribute_exception = args; return; } if (args instanceof assembly.TypeException) { this.type_exception = args; return; } if (args) { if (args.success !== undefined) { this.success = args.success; } if (args.generic_exception !== undefined) { this.generic_exception = args.generic_exception; } if (args.authorization_exception !== undefined) { this.authorization_exception = args.authorization_exception; } if (args.authentication_exception !== undefined) { this.authentication_exception = args.authentication_exception; } if (args.reference_exception !== undefined) { this.reference_exception = args.reference_exception; } if (args.attribute_exception !== undefined) { this.attribute_exception = args.attribute_exception; } if (args.type_exception !== undefined) { this.type_exception = args.type_exception; } } }; assembly.thrift_service_get_external_source_info_result.prototype = {}; assembly.thrift_service_get_external_source_info_result.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 0: if (ftype === Thrift.Type.STRUCT) { this.success = new assembly.AssemblyExternalSourceInfo(); this.success.read(input); } else { input.skip(ftype); } break; case 1: if (ftype === Thrift.Type.STRUCT) { this.generic_exception = new assembly.ServiceException(); this.generic_exception.read(input); } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRUCT) { this.authorization_exception = new assembly.AuthorizationException(); this.authorization_exception.read(input); } else { input.skip(ftype); } break; case 3: if (ftype === Thrift.Type.STRUCT) { this.authentication_exception = new assembly.AuthenticationException(); this.authentication_exception.read(input); } else { input.skip(ftype); } break; case 4: if (ftype === Thrift.Type.STRUCT) { this.reference_exception = new assembly.ObjectReferenceException(); this.reference_exception.read(input); } else { input.skip(ftype); } break; case 5: if (ftype === Thrift.Type.STRUCT) { this.attribute_exception = new assembly.AttributeException(); this.attribute_exception.read(input); } else { input.skip(ftype); } break; case 6: if (ftype === Thrift.Type.STRUCT) { this.type_exception = new assembly.TypeException(); this.type_exception.read(input); } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_external_source_info_result.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_external_source_info_result'); if (this.success !== null && this.success !== undefined) { output.writeFieldBegin('success', Thrift.Type.STRUCT, 0); this.success.write(output); output.writeFieldEnd(); } if (this.generic_exception !== null && this.generic_exception !== undefined) { output.writeFieldBegin('generic_exception', Thrift.Type.STRUCT, 1); this.generic_exception.write(output); output.writeFieldEnd(); } if (this.authorization_exception !== null && this.authorization_exception !== undefined) { output.writeFieldBegin('authorization_exception', Thrift.Type.STRUCT, 2); this.authorization_exception.write(output); output.writeFieldEnd(); } if (this.authentication_exception !== null && this.authentication_exception !== undefined) { output.writeFieldBegin('authentication_exception', Thrift.Type.STRUCT, 3); this.authentication_exception.write(output); output.writeFieldEnd(); } if (this.reference_exception !== null && this.reference_exception !== undefined) { output.writeFieldBegin('reference_exception', Thrift.Type.STRUCT, 4); this.reference_exception.write(output); output.writeFieldEnd(); } if (this.attribute_exception !== null && this.attribute_exception !== undefined) { output.writeFieldBegin('attribute_exception', Thrift.Type.STRUCT, 5); this.attribute_exception.write(output); output.writeFieldEnd(); } if (this.type_exception !== null && this.type_exception !== undefined) { output.writeFieldBegin('type_exception', Thrift.Type.STRUCT, 6); this.type_exception.write(output); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_stats_args = function(args) { this.token = null; this.ref = null; if (args) { if (args.token !== undefined) { this.token = args.token; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field token is unset!'); } if (args.ref !== undefined) { this.ref = args.ref; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field ref is unset!'); } } }; assembly.thrift_service_get_stats_args.prototype = {}; assembly.thrift_service_get_stats_args.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype === Thrift.Type.STRING) { this.token = input.readString().value; } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRING) { this.ref = input.readString().value; } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_stats_args.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_stats_args'); if (this.token !== null && this.token !== undefined) { output.writeFieldBegin('token', Thrift.Type.STRING, 1); output.writeString(this.token); output.writeFieldEnd(); } if (this.ref !== null && this.ref !== undefined) { output.writeFieldBegin('ref', Thrift.Type.STRING, 2); output.writeString(this.ref); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_stats_result = function(args) { this.success = null; this.generic_exception = null; this.authorization_exception = null; this.authentication_exception = null; this.reference_exception = null; this.attribute_exception = null; this.type_exception = null; if (args instanceof assembly.ServiceException) { this.generic_exception = args; return; } if (args instanceof assembly.AuthorizationException) { this.authorization_exception = args; return; } if (args instanceof assembly.AuthenticationException) { this.authentication_exception = args; return; } if (args instanceof assembly.ObjectReferenceException) { this.reference_exception = args; return; } if (args instanceof assembly.AttributeException) { this.attribute_exception = args; return; } if (args instanceof assembly.TypeException) { this.type_exception = args; return; } if (args) { if (args.success !== undefined) { this.success = args.success; } if (args.generic_exception !== undefined) { this.generic_exception = args.generic_exception; } if (args.authorization_exception !== undefined) { this.authorization_exception = args.authorization_exception; } if (args.authentication_exception !== undefined) { this.authentication_exception = args.authentication_exception; } if (args.reference_exception !== undefined) { this.reference_exception = args.reference_exception; } if (args.attribute_exception !== undefined) { this.attribute_exception = args.attribute_exception; } if (args.type_exception !== undefined) { this.type_exception = args.type_exception; } } }; assembly.thrift_service_get_stats_result.prototype = {}; assembly.thrift_service_get_stats_result.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 0: if (ftype === Thrift.Type.STRUCT) { this.success = new assembly.AssemblyStats(); this.success.read(input); } else { input.skip(ftype); } break; case 1: if (ftype === Thrift.Type.STRUCT) { this.generic_exception = new assembly.ServiceException(); this.generic_exception.read(input); } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRUCT) { this.authorization_exception = new assembly.AuthorizationException(); this.authorization_exception.read(input); } else { input.skip(ftype); } break; case 3: if (ftype === Thrift.Type.STRUCT) { this.authentication_exception = new assembly.AuthenticationException(); this.authentication_exception.read(input); } else { input.skip(ftype); } break; case 4: if (ftype === Thrift.Type.STRUCT) { this.reference_exception = new assembly.ObjectReferenceException(); this.reference_exception.read(input); } else { input.skip(ftype); } break; case 5: if (ftype === Thrift.Type.STRUCT) { this.attribute_exception = new assembly.AttributeException(); this.attribute_exception.read(input); } else { input.skip(ftype); } break; case 6: if (ftype === Thrift.Type.STRUCT) { this.type_exception = new assembly.TypeException(); this.type_exception.read(input); } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_stats_result.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_stats_result'); if (this.success !== null && this.success !== undefined) { output.writeFieldBegin('success', Thrift.Type.STRUCT, 0); this.success.write(output); output.writeFieldEnd(); } if (this.generic_exception !== null && this.generic_exception !== undefined) { output.writeFieldBegin('generic_exception', Thrift.Type.STRUCT, 1); this.generic_exception.write(output); output.writeFieldEnd(); } if (this.authorization_exception !== null && this.authorization_exception !== undefined) { output.writeFieldBegin('authorization_exception', Thrift.Type.STRUCT, 2); this.authorization_exception.write(output); output.writeFieldEnd(); } if (this.authentication_exception !== null && this.authentication_exception !== undefined) { output.writeFieldBegin('authentication_exception', Thrift.Type.STRUCT, 3); this.authentication_exception.write(output); output.writeFieldEnd(); } if (this.reference_exception !== null && this.reference_exception !== undefined) { output.writeFieldBegin('reference_exception', Thrift.Type.STRUCT, 4); this.reference_exception.write(output); output.writeFieldEnd(); } if (this.attribute_exception !== null && this.attribute_exception !== undefined) { output.writeFieldBegin('attribute_exception', Thrift.Type.STRUCT, 5); this.attribute_exception.write(output); output.writeFieldEnd(); } if (this.type_exception !== null && this.type_exception !== undefined) { output.writeFieldBegin('type_exception', Thrift.Type.STRUCT, 6); this.type_exception.write(output); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_number_contigs_args = function(args) { this.token = null; this.ref = null; if (args) { if (args.token !== undefined) { this.token = args.token; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field token is unset!'); } if (args.ref !== undefined) { this.ref = args.ref; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field ref is unset!'); } } }; assembly.thrift_service_get_number_contigs_args.prototype = {}; assembly.thrift_service_get_number_contigs_args.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype === Thrift.Type.STRING) { this.token = input.readString().value; } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRING) { this.ref = input.readString().value; } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_number_contigs_args.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_number_contigs_args'); if (this.token !== null && this.token !== undefined) { output.writeFieldBegin('token', Thrift.Type.STRING, 1); output.writeString(this.token); output.writeFieldEnd(); } if (this.ref !== null && this.ref !== undefined) { output.writeFieldBegin('ref', Thrift.Type.STRING, 2); output.writeString(this.ref); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_number_contigs_result = function(args) { this.success = null; this.generic_exception = null; this.authorization_exception = null; this.authentication_exception = null; this.reference_exception = null; this.attribute_exception = null; this.type_exception = null; if (args instanceof assembly.ServiceException) { this.generic_exception = args; return; } if (args instanceof assembly.AuthorizationException) { this.authorization_exception = args; return; } if (args instanceof assembly.AuthenticationException) { this.authentication_exception = args; return; } if (args instanceof assembly.ObjectReferenceException) { this.reference_exception = args; return; } if (args instanceof assembly.AttributeException) { this.attribute_exception = args; return; } if (args instanceof assembly.TypeException) { this.type_exception = args; return; } if (args) { if (args.success !== undefined) { this.success = args.success; } if (args.generic_exception !== undefined) { this.generic_exception = args.generic_exception; } if (args.authorization_exception !== undefined) { this.authorization_exception = args.authorization_exception; } if (args.authentication_exception !== undefined) { this.authentication_exception = args.authentication_exception; } if (args.reference_exception !== undefined) { this.reference_exception = args.reference_exception; } if (args.attribute_exception !== undefined) { this.attribute_exception = args.attribute_exception; } if (args.type_exception !== undefined) { this.type_exception = args.type_exception; } } }; assembly.thrift_service_get_number_contigs_result.prototype = {}; assembly.thrift_service_get_number_contigs_result.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 0: if (ftype === Thrift.Type.I64) { this.success = input.readI64().value; } else { input.skip(ftype); } break; case 1: if (ftype === Thrift.Type.STRUCT) { this.generic_exception = new assembly.ServiceException(); this.generic_exception.read(input); } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRUCT) { this.authorization_exception = new assembly.AuthorizationException(); this.authorization_exception.read(input); } else { input.skip(ftype); } break; case 3: if (ftype === Thrift.Type.STRUCT) { this.authentication_exception = new assembly.AuthenticationException(); this.authentication_exception.read(input); } else { input.skip(ftype); } break; case 4: if (ftype === Thrift.Type.STRUCT) { this.reference_exception = new assembly.ObjectReferenceException(); this.reference_exception.read(input); } else { input.skip(ftype); } break; case 5: if (ftype === Thrift.Type.STRUCT) { this.attribute_exception = new assembly.AttributeException(); this.attribute_exception.read(input); } else { input.skip(ftype); } break; case 6: if (ftype === Thrift.Type.STRUCT) { this.type_exception = new assembly.TypeException(); this.type_exception.read(input); } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_number_contigs_result.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_number_contigs_result'); if (this.success !== null && this.success !== undefined) { output.writeFieldBegin('success', Thrift.Type.I64, 0); output.writeI64(this.success); output.writeFieldEnd(); } if (this.generic_exception !== null && this.generic_exception !== undefined) { output.writeFieldBegin('generic_exception', Thrift.Type.STRUCT, 1); this.generic_exception.write(output); output.writeFieldEnd(); } if (this.authorization_exception !== null && this.authorization_exception !== undefined) { output.writeFieldBegin('authorization_exception', Thrift.Type.STRUCT, 2); this.authorization_exception.write(output); output.writeFieldEnd(); } if (this.authentication_exception !== null && this.authentication_exception !== undefined) { output.writeFieldBegin('authentication_exception', Thrift.Type.STRUCT, 3); this.authentication_exception.write(output); output.writeFieldEnd(); } if (this.reference_exception !== null && this.reference_exception !== undefined) { output.writeFieldBegin('reference_exception', Thrift.Type.STRUCT, 4); this.reference_exception.write(output); output.writeFieldEnd(); } if (this.attribute_exception !== null && this.attribute_exception !== undefined) { output.writeFieldBegin('attribute_exception', Thrift.Type.STRUCT, 5); this.attribute_exception.write(output); output.writeFieldEnd(); } if (this.type_exception !== null && this.type_exception !== undefined) { output.writeFieldBegin('type_exception', Thrift.Type.STRUCT, 6); this.type_exception.write(output); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_gc_content_args = function(args) { this.token = null; this.ref = null; if (args) { if (args.token !== undefined) { this.token = args.token; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field token is unset!'); } if (args.ref !== undefined) { this.ref = args.ref; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field ref is unset!'); } } }; assembly.thrift_service_get_gc_content_args.prototype = {}; assembly.thrift_service_get_gc_content_args.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype === Thrift.Type.STRING) { this.token = input.readString().value; } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRING) { this.ref = input.readString().value; } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_gc_content_args.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_gc_content_args'); if (this.token !== null && this.token !== undefined) { output.writeFieldBegin('token', Thrift.Type.STRING, 1); output.writeString(this.token); output.writeFieldEnd(); } if (this.ref !== null && this.ref !== undefined) { output.writeFieldBegin('ref', Thrift.Type.STRING, 2); output.writeString(this.ref); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_gc_content_result = function(args) { this.success = null; this.generic_exception = null; this.authorization_exception = null; this.authentication_exception = null; this.reference_exception = null; this.attribute_exception = null; this.type_exception = null; if (args instanceof assembly.ServiceException) { this.generic_exception = args; return; } if (args instanceof assembly.AuthorizationException) { this.authorization_exception = args; return; } if (args instanceof assembly.AuthenticationException) { this.authentication_exception = args; return; } if (args instanceof assembly.ObjectReferenceException) { this.reference_exception = args; return; } if (args instanceof assembly.AttributeException) { this.attribute_exception = args; return; } if (args instanceof assembly.TypeException) { this.type_exception = args; return; } if (args) { if (args.success !== undefined) { this.success = args.success; } if (args.generic_exception !== undefined) { this.generic_exception = args.generic_exception; } if (args.authorization_exception !== undefined) { this.authorization_exception = args.authorization_exception; } if (args.authentication_exception !== undefined) { this.authentication_exception = args.authentication_exception; } if (args.reference_exception !== undefined) { this.reference_exception = args.reference_exception; } if (args.attribute_exception !== undefined) { this.attribute_exception = args.attribute_exception; } if (args.type_exception !== undefined) { this.type_exception = args.type_exception; } } }; assembly.thrift_service_get_gc_content_result.prototype = {}; assembly.thrift_service_get_gc_content_result.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 0: if (ftype === Thrift.Type.DOUBLE) { this.success = input.readDouble().value; } else { input.skip(ftype); } break; case 1: if (ftype === Thrift.Type.STRUCT) { this.generic_exception = new assembly.ServiceException(); this.generic_exception.read(input); } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRUCT) { this.authorization_exception = new assembly.AuthorizationException(); this.authorization_exception.read(input); } else { input.skip(ftype); } break; case 3: if (ftype === Thrift.Type.STRUCT) { this.authentication_exception = new assembly.AuthenticationException(); this.authentication_exception.read(input); } else { input.skip(ftype); } break; case 4: if (ftype === Thrift.Type.STRUCT) { this.reference_exception = new assembly.ObjectReferenceException(); this.reference_exception.read(input); } else { input.skip(ftype); } break; case 5: if (ftype === Thrift.Type.STRUCT) { this.attribute_exception = new assembly.AttributeException(); this.attribute_exception.read(input); } else { input.skip(ftype); } break; case 6: if (ftype === Thrift.Type.STRUCT) { this.type_exception = new assembly.TypeException(); this.type_exception.read(input); } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_gc_content_result.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_gc_content_result'); if (this.success !== null && this.success !== undefined) { output.writeFieldBegin('success', Thrift.Type.DOUBLE, 0); output.writeDouble(this.success); output.writeFieldEnd(); } if (this.generic_exception !== null && this.generic_exception !== undefined) { output.writeFieldBegin('generic_exception', Thrift.Type.STRUCT, 1); this.generic_exception.write(output); output.writeFieldEnd(); } if (this.authorization_exception !== null && this.authorization_exception !== undefined) { output.writeFieldBegin('authorization_exception', Thrift.Type.STRUCT, 2); this.authorization_exception.write(output); output.writeFieldEnd(); } if (this.authentication_exception !== null && this.authentication_exception !== undefined) { output.writeFieldBegin('authentication_exception', Thrift.Type.STRUCT, 3); this.authentication_exception.write(output); output.writeFieldEnd(); } if (this.reference_exception !== null && this.reference_exception !== undefined) { output.writeFieldBegin('reference_exception', Thrift.Type.STRUCT, 4); this.reference_exception.write(output); output.writeFieldEnd(); } if (this.attribute_exception !== null && this.attribute_exception !== undefined) { output.writeFieldBegin('attribute_exception', Thrift.Type.STRUCT, 5); this.attribute_exception.write(output); output.writeFieldEnd(); } if (this.type_exception !== null && this.type_exception !== undefined) { output.writeFieldBegin('type_exception', Thrift.Type.STRUCT, 6); this.type_exception.write(output); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_dna_size_args = function(args) { this.token = null; this.ref = null; if (args) { if (args.token !== undefined) { this.token = args.token; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field token is unset!'); } if (args.ref !== undefined) { this.ref = args.ref; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field ref is unset!'); } } }; assembly.thrift_service_get_dna_size_args.prototype = {}; assembly.thrift_service_get_dna_size_args.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype === Thrift.Type.STRING) { this.token = input.readString().value; } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRING) { this.ref = input.readString().value; } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_dna_size_args.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_dna_size_args'); if (this.token !== null && this.token !== undefined) { output.writeFieldBegin('token', Thrift.Type.STRING, 1); output.writeString(this.token); output.writeFieldEnd(); } if (this.ref !== null && this.ref !== undefined) { output.writeFieldBegin('ref', Thrift.Type.STRING, 2); output.writeString(this.ref); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_dna_size_result = function(args) { this.success = null; this.generic_exception = null; this.authorization_exception = null; this.authentication_exception = null; this.reference_exception = null; this.attribute_exception = null; this.type_exception = null; if (args instanceof assembly.ServiceException) { this.generic_exception = args; return; } if (args instanceof assembly.AuthorizationException) { this.authorization_exception = args; return; } if (args instanceof assembly.AuthenticationException) { this.authentication_exception = args; return; } if (args instanceof assembly.ObjectReferenceException) { this.reference_exception = args; return; } if (args instanceof assembly.AttributeException) { this.attribute_exception = args; return; } if (args instanceof assembly.TypeException) { this.type_exception = args; return; } if (args) { if (args.success !== undefined) { this.success = args.success; } if (args.generic_exception !== undefined) { this.generic_exception = args.generic_exception; } if (args.authorization_exception !== undefined) { this.authorization_exception = args.authorization_exception; } if (args.authentication_exception !== undefined) { this.authentication_exception = args.authentication_exception; } if (args.reference_exception !== undefined) { this.reference_exception = args.reference_exception; } if (args.attribute_exception !== undefined) { this.attribute_exception = args.attribute_exception; } if (args.type_exception !== undefined) { this.type_exception = args.type_exception; } } }; assembly.thrift_service_get_dna_size_result.prototype = {}; assembly.thrift_service_get_dna_size_result.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 0: if (ftype === Thrift.Type.I64) { this.success = input.readI64().value; } else { input.skip(ftype); } break; case 1: if (ftype === Thrift.Type.STRUCT) { this.generic_exception = new assembly.ServiceException(); this.generic_exception.read(input); } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRUCT) { this.authorization_exception = new assembly.AuthorizationException(); this.authorization_exception.read(input); } else { input.skip(ftype); } break; case 3: if (ftype === Thrift.Type.STRUCT) { this.authentication_exception = new assembly.AuthenticationException(); this.authentication_exception.read(input); } else { input.skip(ftype); } break; case 4: if (ftype === Thrift.Type.STRUCT) { this.reference_exception = new assembly.ObjectReferenceException(); this.reference_exception.read(input); } else { input.skip(ftype); } break; case 5: if (ftype === Thrift.Type.STRUCT) { this.attribute_exception = new assembly.AttributeException(); this.attribute_exception.read(input); } else { input.skip(ftype); } break; case 6: if (ftype === Thrift.Type.STRUCT) { this.type_exception = new assembly.TypeException(); this.type_exception.read(input); } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_dna_size_result.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_dna_size_result'); if (this.success !== null && this.success !== undefined) { output.writeFieldBegin('success', Thrift.Type.I64, 0); output.writeI64(this.success); output.writeFieldEnd(); } if (this.generic_exception !== null && this.generic_exception !== undefined) { output.writeFieldBegin('generic_exception', Thrift.Type.STRUCT, 1); this.generic_exception.write(output); output.writeFieldEnd(); } if (this.authorization_exception !== null && this.authorization_exception !== undefined) { output.writeFieldBegin('authorization_exception', Thrift.Type.STRUCT, 2); this.authorization_exception.write(output); output.writeFieldEnd(); } if (this.authentication_exception !== null && this.authentication_exception !== undefined) { output.writeFieldBegin('authentication_exception', Thrift.Type.STRUCT, 3); this.authentication_exception.write(output); output.writeFieldEnd(); } if (this.reference_exception !== null && this.reference_exception !== undefined) { output.writeFieldBegin('reference_exception', Thrift.Type.STRUCT, 4); this.reference_exception.write(output); output.writeFieldEnd(); } if (this.attribute_exception !== null && this.attribute_exception !== undefined) { output.writeFieldBegin('attribute_exception', Thrift.Type.STRUCT, 5); this.attribute_exception.write(output); output.writeFieldEnd(); } if (this.type_exception !== null && this.type_exception !== undefined) { output.writeFieldBegin('type_exception', Thrift.Type.STRUCT, 6); this.type_exception.write(output); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_contig_ids_args = function(args) { this.token = null; this.ref = null; if (args) { if (args.token !== undefined) { this.token = args.token; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field token is unset!'); } if (args.ref !== undefined) { this.ref = args.ref; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field ref is unset!'); } } }; assembly.thrift_service_get_contig_ids_args.prototype = {}; assembly.thrift_service_get_contig_ids_args.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype === Thrift.Type.STRING) { this.token = input.readString().value; } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRING) { this.ref = input.readString().value; } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_contig_ids_args.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_contig_ids_args'); if (this.token !== null && this.token !== undefined) { output.writeFieldBegin('token', Thrift.Type.STRING, 1); output.writeString(this.token); output.writeFieldEnd(); } if (this.ref !== null && this.ref !== undefined) { output.writeFieldBegin('ref', Thrift.Type.STRING, 2); output.writeString(this.ref); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_contig_ids_result = function(args) { this.success = null; this.generic_exception = null; this.authorization_exception = null; this.authentication_exception = null; this.reference_exception = null; this.attribute_exception = null; this.type_exception = null; if (args instanceof assembly.ServiceException) { this.generic_exception = args; return; } if (args instanceof assembly.AuthorizationException) { this.authorization_exception = args; return; } if (args instanceof assembly.AuthenticationException) { this.authentication_exception = args; return; } if (args instanceof assembly.ObjectReferenceException) { this.reference_exception = args; return; } if (args instanceof assembly.AttributeException) { this.attribute_exception = args; return; } if (args instanceof assembly.TypeException) { this.type_exception = args; return; } if (args) { if (args.success !== undefined) { this.success = args.success; } if (args.generic_exception !== undefined) { this.generic_exception = args.generic_exception; } if (args.authorization_exception !== undefined) { this.authorization_exception = args.authorization_exception; } if (args.authentication_exception !== undefined) { this.authentication_exception = args.authentication_exception; } if (args.reference_exception !== undefined) { this.reference_exception = args.reference_exception; } if (args.attribute_exception !== undefined) { this.attribute_exception = args.attribute_exception; } if (args.type_exception !== undefined) { this.type_exception = args.type_exception; } } }; assembly.thrift_service_get_contig_ids_result.prototype = {}; assembly.thrift_service_get_contig_ids_result.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 0: if (ftype === Thrift.Type.LIST) { var _size26 = 0; var _rtmp330; this.success = []; var _etype29 = 0; _rtmp330 = input.readListBegin(); _etype29 = _rtmp330.etype; _size26 = _rtmp330.size; for (var _i31 = 0; _i31 < _size26; ++_i31) { var elem32 = null; elem32 = input.readString().value; this.success.push(elem32); } input.readListEnd(); } else { input.skip(ftype); } break; case 1: if (ftype === Thrift.Type.STRUCT) { this.generic_exception = new assembly.ServiceException(); this.generic_exception.read(input); } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRUCT) { this.authorization_exception = new assembly.AuthorizationException(); this.authorization_exception.read(input); } else { input.skip(ftype); } break; case 3: if (ftype === Thrift.Type.STRUCT) { this.authentication_exception = new assembly.AuthenticationException(); this.authentication_exception.read(input); } else { input.skip(ftype); } break; case 4: if (ftype === Thrift.Type.STRUCT) { this.reference_exception = new assembly.ObjectReferenceException(); this.reference_exception.read(input); } else { input.skip(ftype); } break; case 5: if (ftype === Thrift.Type.STRUCT) { this.attribute_exception = new assembly.AttributeException(); this.attribute_exception.read(input); } else { input.skip(ftype); } break; case 6: if (ftype === Thrift.Type.STRUCT) { this.type_exception = new assembly.TypeException(); this.type_exception.read(input); } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_contig_ids_result.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_contig_ids_result'); if (this.success !== null && this.success !== undefined) { output.writeFieldBegin('success', Thrift.Type.LIST, 0); output.writeListBegin(Thrift.Type.STRING, this.success.length); for (var iter33 in this.success) { if (this.success.hasOwnProperty(iter33)) { iter33 = this.success[iter33]; output.writeString(iter33); } } output.writeListEnd(); output.writeFieldEnd(); } if (this.generic_exception !== null && this.generic_exception !== undefined) { output.writeFieldBegin('generic_exception', Thrift.Type.STRUCT, 1); this.generic_exception.write(output); output.writeFieldEnd(); } if (this.authorization_exception !== null && this.authorization_exception !== undefined) { output.writeFieldBegin('authorization_exception', Thrift.Type.STRUCT, 2); this.authorization_exception.write(output); output.writeFieldEnd(); } if (this.authentication_exception !== null && this.authentication_exception !== undefined) { output.writeFieldBegin('authentication_exception', Thrift.Type.STRUCT, 3); this.authentication_exception.write(output); output.writeFieldEnd(); } if (this.reference_exception !== null && this.reference_exception !== undefined) { output.writeFieldBegin('reference_exception', Thrift.Type.STRUCT, 4); this.reference_exception.write(output); output.writeFieldEnd(); } if (this.attribute_exception !== null && this.attribute_exception !== undefined) { output.writeFieldBegin('attribute_exception', Thrift.Type.STRUCT, 5); this.attribute_exception.write(output); output.writeFieldEnd(); } if (this.type_exception !== null && this.type_exception !== undefined) { output.writeFieldBegin('type_exception', Thrift.Type.STRUCT, 6); this.type_exception.write(output); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_contig_lengths_args = function(args) { this.token = null; this.ref = null; this.contig_id_list = null; if (args) { if (args.token !== undefined) { this.token = args.token; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field token is unset!'); } if (args.ref !== undefined) { this.ref = args.ref; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field ref is unset!'); } if (args.contig_id_list !== undefined) { this.contig_id_list = args.contig_id_list; } } }; assembly.thrift_service_get_contig_lengths_args.prototype = {}; assembly.thrift_service_get_contig_lengths_args.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype === Thrift.Type.STRING) { this.token = input.readString().value; } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRING) { this.ref = input.readString().value; } else { input.skip(ftype); } break; case 3: if (ftype === Thrift.Type.LIST) { var _size34 = 0; var _rtmp338; this.contig_id_list = []; var _etype37 = 0; _rtmp338 = input.readListBegin(); _etype37 = _rtmp338.etype; _size34 = _rtmp338.size; for (var _i39 = 0; _i39 < _size34; ++_i39) { var elem40 = null; elem40 = input.readString().value; this.contig_id_list.push(elem40); } input.readListEnd(); } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_contig_lengths_args.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_contig_lengths_args'); if (this.token !== null && this.token !== undefined) { output.writeFieldBegin('token', Thrift.Type.STRING, 1); output.writeString(this.token); output.writeFieldEnd(); } if (this.ref !== null && this.ref !== undefined) { output.writeFieldBegin('ref', Thrift.Type.STRING, 2); output.writeString(this.ref); output.writeFieldEnd(); } if (this.contig_id_list !== null && this.contig_id_list !== undefined) { output.writeFieldBegin('contig_id_list', Thrift.Type.LIST, 3); output.writeListBegin(Thrift.Type.STRING, this.contig_id_list.length); for (var iter41 in this.contig_id_list) { if (this.contig_id_list.hasOwnProperty(iter41)) { iter41 = this.contig_id_list[iter41]; output.writeString(iter41); } } output.writeListEnd(); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_contig_lengths_result = function(args) { this.success = null; this.generic_exception = null; this.authorization_exception = null; this.authentication_exception = null; this.reference_exception = null; this.attribute_exception = null; this.type_exception = null; if (args instanceof assembly.ServiceException) { this.generic_exception = args; return; } if (args instanceof assembly.AuthorizationException) { this.authorization_exception = args; return; } if (args instanceof assembly.AuthenticationException) { this.authentication_exception = args; return; } if (args instanceof assembly.ObjectReferenceException) { this.reference_exception = args; return; } if (args instanceof assembly.AttributeException) { this.attribute_exception = args; return; } if (args instanceof assembly.TypeException) { this.type_exception = args; return; } if (args) { if (args.success !== undefined) { this.success = args.success; } if (args.generic_exception !== undefined) { this.generic_exception = args.generic_exception; } if (args.authorization_exception !== undefined) { this.authorization_exception = args.authorization_exception; } if (args.authentication_exception !== undefined) { this.authentication_exception = args.authentication_exception; } if (args.reference_exception !== undefined) { this.reference_exception = args.reference_exception; } if (args.attribute_exception !== undefined) { this.attribute_exception = args.attribute_exception; } if (args.type_exception !== undefined) { this.type_exception = args.type_exception; } } }; assembly.thrift_service_get_contig_lengths_result.prototype = {}; assembly.thrift_service_get_contig_lengths_result.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 0: if (ftype === Thrift.Type.MAP) { var _size42 = 0; var _rtmp346; this.success = {}; var _ktype43 = 0; var _vtype44 = 0; _rtmp346 = input.readMapBegin(); _ktype43 = _rtmp346.ktype; _vtype44 = _rtmp346.vtype; _size42 = _rtmp346.size; for (var _i47 = 0; _i47 < _size42; ++_i47) { // removed rpos bug var key48 = null; var val49 = null; key48 = input.readString().value; val49 = input.readI64().value; this.success[key48] = val49; } input.readMapEnd(); } else { input.skip(ftype); } break; case 1: if (ftype === Thrift.Type.STRUCT) { this.generic_exception = new assembly.ServiceException(); this.generic_exception.read(input); } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRUCT) { this.authorization_exception = new assembly.AuthorizationException(); this.authorization_exception.read(input); } else { input.skip(ftype); } break; case 3: if (ftype === Thrift.Type.STRUCT) { this.authentication_exception = new assembly.AuthenticationException(); this.authentication_exception.read(input); } else { input.skip(ftype); } break; case 4: if (ftype === Thrift.Type.STRUCT) { this.reference_exception = new assembly.ObjectReferenceException(); this.reference_exception.read(input); } else { input.skip(ftype); } break; case 5: if (ftype === Thrift.Type.STRUCT) { this.attribute_exception = new assembly.AttributeException(); this.attribute_exception.read(input); } else { input.skip(ftype); } break; case 6: if (ftype === Thrift.Type.STRUCT) { this.type_exception = new assembly.TypeException(); this.type_exception.read(input); } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_contig_lengths_result.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_contig_lengths_result'); if (this.success !== null && this.success !== undefined) { output.writeFieldBegin('success', Thrift.Type.MAP, 0); output.writeMapBegin(Thrift.Type.STRING, Thrift.Type.I64, Thrift.objectLength(this.success)); for (var kiter50 in this.success) { if (this.success.hasOwnProperty(kiter50)) { var viter51 = this.success[kiter50]; output.writeString(kiter50); output.writeI64(viter51); } } output.writeMapEnd(); output.writeFieldEnd(); } if (this.generic_exception !== null && this.generic_exception !== undefined) { output.writeFieldBegin('generic_exception', Thrift.Type.STRUCT, 1); this.generic_exception.write(output); output.writeFieldEnd(); } if (this.authorization_exception !== null && this.authorization_exception !== undefined) { output.writeFieldBegin('authorization_exception', Thrift.Type.STRUCT, 2); this.authorization_exception.write(output); output.writeFieldEnd(); } if (this.authentication_exception !== null && this.authentication_exception !== undefined) { output.writeFieldBegin('authentication_exception', Thrift.Type.STRUCT, 3); this.authentication_exception.write(output); output.writeFieldEnd(); } if (this.reference_exception !== null && this.reference_exception !== undefined) { output.writeFieldBegin('reference_exception', Thrift.Type.STRUCT, 4); this.reference_exception.write(output); output.writeFieldEnd(); } if (this.attribute_exception !== null && this.attribute_exception !== undefined) { output.writeFieldBegin('attribute_exception', Thrift.Type.STRUCT, 5); this.attribute_exception.write(output); output.writeFieldEnd(); } if (this.type_exception !== null && this.type_exception !== undefined) { output.writeFieldBegin('type_exception', Thrift.Type.STRUCT, 6); this.type_exception.write(output); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_contig_gc_content_args = function(args) { this.token = null; this.ref = null; this.contig_id_list = null; if (args) { if (args.token !== undefined) { this.token = args.token; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field token is unset!'); } if (args.ref !== undefined) { this.ref = args.ref; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field ref is unset!'); } if (args.contig_id_list !== undefined) { this.contig_id_list = args.contig_id_list; } } }; assembly.thrift_service_get_contig_gc_content_args.prototype = {}; assembly.thrift_service_get_contig_gc_content_args.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype === Thrift.Type.STRING) { this.token = input.readString().value; } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRING) { this.ref = input.readString().value; } else { input.skip(ftype); } break; case 3: if (ftype === Thrift.Type.LIST) { var _size52 = 0; var _rtmp356; this.contig_id_list = []; var _etype55 = 0; _rtmp356 = input.readListBegin(); _etype55 = _rtmp356.etype; _size52 = _rtmp356.size; for (var _i57 = 0; _i57 < _size52; ++_i57) { var elem58 = null; elem58 = input.readString().value; this.contig_id_list.push(elem58); } input.readListEnd(); } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_contig_gc_content_args.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_contig_gc_content_args'); if (this.token !== null && this.token !== undefined) { output.writeFieldBegin('token', Thrift.Type.STRING, 1); output.writeString(this.token); output.writeFieldEnd(); } if (this.ref !== null && this.ref !== undefined) { output.writeFieldBegin('ref', Thrift.Type.STRING, 2); output.writeString(this.ref); output.writeFieldEnd(); } if (this.contig_id_list !== null && this.contig_id_list !== undefined) { output.writeFieldBegin('contig_id_list', Thrift.Type.LIST, 3); output.writeListBegin(Thrift.Type.STRING, this.contig_id_list.length); for (var iter59 in this.contig_id_list) { if (this.contig_id_list.hasOwnProperty(iter59)) { iter59 = this.contig_id_list[iter59]; output.writeString(iter59); } } output.writeListEnd(); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_contig_gc_content_result = function(args) { this.success = null; this.generic_exception = null; this.authorization_exception = null; this.authentication_exception = null; this.reference_exception = null; this.attribute_exception = null; this.type_exception = null; if (args instanceof assembly.ServiceException) { this.generic_exception = args; return; } if (args instanceof assembly.AuthorizationException) { this.authorization_exception = args; return; } if (args instanceof assembly.AuthenticationException) { this.authentication_exception = args; return; } if (args instanceof assembly.ObjectReferenceException) { this.reference_exception = args; return; } if (args instanceof assembly.AttributeException) { this.attribute_exception = args; return; } if (args instanceof assembly.TypeException) { this.type_exception = args; return; } if (args) { if (args.success !== undefined) { this.success = args.success; } if (args.generic_exception !== undefined) { this.generic_exception = args.generic_exception; } if (args.authorization_exception !== undefined) { this.authorization_exception = args.authorization_exception; } if (args.authentication_exception !== undefined) { this.authentication_exception = args.authentication_exception; } if (args.reference_exception !== undefined) { this.reference_exception = args.reference_exception; } if (args.attribute_exception !== undefined) { this.attribute_exception = args.attribute_exception; } if (args.type_exception !== undefined) { this.type_exception = args.type_exception; } } }; assembly.thrift_service_get_contig_gc_content_result.prototype = {}; assembly.thrift_service_get_contig_gc_content_result.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 0: if (ftype === Thrift.Type.MAP) { var _size60 = 0; var _rtmp364; this.success = {}; var _ktype61 = 0; var _vtype62 = 0; _rtmp364 = input.readMapBegin(); _ktype61 = _rtmp364.ktype; _vtype62 = _rtmp364.vtype; _size60 = _rtmp364.size; for (var _i65 = 0; _i65 < _size60; ++_i65) { // removed rpos bug var key66 = null; var val67 = null; key66 = input.readString().value; val67 = input.readDouble().value; this.success[key66] = val67; } input.readMapEnd(); } else { input.skip(ftype); } break; case 1: if (ftype === Thrift.Type.STRUCT) { this.generic_exception = new assembly.ServiceException(); this.generic_exception.read(input); } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRUCT) { this.authorization_exception = new assembly.AuthorizationException(); this.authorization_exception.read(input); } else { input.skip(ftype); } break; case 3: if (ftype === Thrift.Type.STRUCT) { this.authentication_exception = new assembly.AuthenticationException(); this.authentication_exception.read(input); } else { input.skip(ftype); } break; case 4: if (ftype === Thrift.Type.STRUCT) { this.reference_exception = new assembly.ObjectReferenceException(); this.reference_exception.read(input); } else { input.skip(ftype); } break; case 5: if (ftype === Thrift.Type.STRUCT) { this.attribute_exception = new assembly.AttributeException(); this.attribute_exception.read(input); } else { input.skip(ftype); } break; case 6: if (ftype === Thrift.Type.STRUCT) { this.type_exception = new assembly.TypeException(); this.type_exception.read(input); } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_contig_gc_content_result.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_contig_gc_content_result'); if (this.success !== null && this.success !== undefined) { output.writeFieldBegin('success', Thrift.Type.MAP, 0); output.writeMapBegin(Thrift.Type.STRING, Thrift.Type.DOUBLE, Thrift.objectLength(this.success)); for (var kiter68 in this.success) { if (this.success.hasOwnProperty(kiter68)) { var viter69 = this.success[kiter68]; output.writeString(kiter68); output.writeDouble(viter69); } } output.writeMapEnd(); output.writeFieldEnd(); } if (this.generic_exception !== null && this.generic_exception !== undefined) { output.writeFieldBegin('generic_exception', Thrift.Type.STRUCT, 1); this.generic_exception.write(output); output.writeFieldEnd(); } if (this.authorization_exception !== null && this.authorization_exception !== undefined) { output.writeFieldBegin('authorization_exception', Thrift.Type.STRUCT, 2); this.authorization_exception.write(output); output.writeFieldEnd(); } if (this.authentication_exception !== null && this.authentication_exception !== undefined) { output.writeFieldBegin('authentication_exception', Thrift.Type.STRUCT, 3); this.authentication_exception.write(output); output.writeFieldEnd(); } if (this.reference_exception !== null && this.reference_exception !== undefined) { output.writeFieldBegin('reference_exception', Thrift.Type.STRUCT, 4); this.reference_exception.write(output); output.writeFieldEnd(); } if (this.attribute_exception !== null && this.attribute_exception !== undefined) { output.writeFieldBegin('attribute_exception', Thrift.Type.STRUCT, 5); this.attribute_exception.write(output); output.writeFieldEnd(); } if (this.type_exception !== null && this.type_exception !== undefined) { output.writeFieldBegin('type_exception', Thrift.Type.STRUCT, 6); this.type_exception.write(output); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_contigs_args = function(args) { this.token = null; this.ref = null; this.contig_id_list = null; if (args) { if (args.token !== undefined) { this.token = args.token; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field token is unset!'); } if (args.ref !== undefined) { this.ref = args.ref; } else { throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field ref is unset!'); } if (args.contig_id_list !== undefined) { this.contig_id_list = args.contig_id_list; } } }; assembly.thrift_service_get_contigs_args.prototype = {}; assembly.thrift_service_get_contigs_args.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 1: if (ftype === Thrift.Type.STRING) { this.token = input.readString().value; } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRING) { this.ref = input.readString().value; } else { input.skip(ftype); } break; case 3: if (ftype === Thrift.Type.LIST) { var _size70 = 0; var _rtmp374; this.contig_id_list = []; var _etype73 = 0; _rtmp374 = input.readListBegin(); _etype73 = _rtmp374.etype; _size70 = _rtmp374.size; for (var _i75 = 0; _i75 < _size70; ++_i75) { var elem76 = null; elem76 = input.readString().value; this.contig_id_list.push(elem76); } input.readListEnd(); } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_contigs_args.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_contigs_args'); if (this.token !== null && this.token !== undefined) { output.writeFieldBegin('token', Thrift.Type.STRING, 1); output.writeString(this.token); output.writeFieldEnd(); } if (this.ref !== null && this.ref !== undefined) { output.writeFieldBegin('ref', Thrift.Type.STRING, 2); output.writeString(this.ref); output.writeFieldEnd(); } if (this.contig_id_list !== null && this.contig_id_list !== undefined) { output.writeFieldBegin('contig_id_list', Thrift.Type.LIST, 3); output.writeListBegin(Thrift.Type.STRING, this.contig_id_list.length); for (var iter77 in this.contig_id_list) { if (this.contig_id_list.hasOwnProperty(iter77)) { iter77 = this.contig_id_list[iter77]; output.writeString(iter77); } } output.writeListEnd(); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_service_get_contigs_result = function(args) { this.success = null; this.generic_exception = null; this.authorization_exception = null; this.authentication_exception = null; this.reference_exception = null; this.attribute_exception = null; this.type_exception = null; if (args instanceof assembly.ServiceException) { this.generic_exception = args; return; } if (args instanceof assembly.AuthorizationException) { this.authorization_exception = args; return; } if (args instanceof assembly.AuthenticationException) { this.authentication_exception = args; return; } if (args instanceof assembly.ObjectReferenceException) { this.reference_exception = args; return; } if (args instanceof assembly.AttributeException) { this.attribute_exception = args; return; } if (args instanceof assembly.TypeException) { this.type_exception = args; return; } if (args) { if (args.success !== undefined) { this.success = args.success; } if (args.generic_exception !== undefined) { this.generic_exception = args.generic_exception; } if (args.authorization_exception !== undefined) { this.authorization_exception = args.authorization_exception; } if (args.authentication_exception !== undefined) { this.authentication_exception = args.authentication_exception; } if (args.reference_exception !== undefined) { this.reference_exception = args.reference_exception; } if (args.attribute_exception !== undefined) { this.attribute_exception = args.attribute_exception; } if (args.type_exception !== undefined) { this.type_exception = args.type_exception; } } }; assembly.thrift_service_get_contigs_result.prototype = {}; assembly.thrift_service_get_contigs_result.prototype.read = function(input) { input.readStructBegin(); while (true) { var ret = input.readFieldBegin(); var fname = ret.fname; var ftype = ret.ftype; var fid = ret.fid; if (ftype === Thrift.Type.STOP) { break; } switch (fid) { case 0: if (ftype === Thrift.Type.MAP) { var _size78 = 0; var _rtmp382; this.success = {}; var _ktype79 = 0; var _vtype80 = 0; _rtmp382 = input.readMapBegin(); _ktype79 = _rtmp382.ktype; _vtype80 = _rtmp382.vtype; _size78 = _rtmp382.size; for (var _i83 = 0; _i83 < _size78; ++_i83) { // removed rpos bug var key84 = null; var val85 = null; key84 = input.readString().value; val85 = new assembly.AssemblyContig(); val85.read(input); this.success[key84] = val85; } input.readMapEnd(); } else { input.skip(ftype); } break; case 1: if (ftype === Thrift.Type.STRUCT) { this.generic_exception = new assembly.ServiceException(); this.generic_exception.read(input); } else { input.skip(ftype); } break; case 2: if (ftype === Thrift.Type.STRUCT) { this.authorization_exception = new assembly.AuthorizationException(); this.authorization_exception.read(input); } else { input.skip(ftype); } break; case 3: if (ftype === Thrift.Type.STRUCT) { this.authentication_exception = new assembly.AuthenticationException(); this.authentication_exception.read(input); } else { input.skip(ftype); } break; case 4: if (ftype === Thrift.Type.STRUCT) { this.reference_exception = new assembly.ObjectReferenceException(); this.reference_exception.read(input); } else { input.skip(ftype); } break; case 5: if (ftype === Thrift.Type.STRUCT) { this.attribute_exception = new assembly.AttributeException(); this.attribute_exception.read(input); } else { input.skip(ftype); } break; case 6: if (ftype === Thrift.Type.STRUCT) { this.type_exception = new assembly.TypeException(); this.type_exception.read(input); } else { input.skip(ftype); } break; default: input.skip(ftype); } input.readFieldEnd(); } input.readStructEnd(); return; }; assembly.thrift_service_get_contigs_result.prototype.write = function(output) { output.writeStructBegin('thrift_service_get_contigs_result'); if (this.success !== null && this.success !== undefined) { output.writeFieldBegin('success', Thrift.Type.MAP, 0); output.writeMapBegin(Thrift.Type.STRING, Thrift.Type.STRUCT, Thrift.objectLength(this.success)); for (var kiter86 in this.success) { if (this.success.hasOwnProperty(kiter86)) { var viter87 = this.success[kiter86]; output.writeString(kiter86); viter87.write(output); } } output.writeMapEnd(); output.writeFieldEnd(); } if (this.generic_exception !== null && this.generic_exception !== undefined) { output.writeFieldBegin('generic_exception', Thrift.Type.STRUCT, 1); this.generic_exception.write(output); output.writeFieldEnd(); } if (this.authorization_exception !== null && this.authorization_exception !== undefined) { output.writeFieldBegin('authorization_exception', Thrift.Type.STRUCT, 2); this.authorization_exception.write(output); output.writeFieldEnd(); } if (this.authentication_exception !== null && this.authentication_exception !== undefined) { output.writeFieldBegin('authentication_exception', Thrift.Type.STRUCT, 3); this.authentication_exception.write(output); output.writeFieldEnd(); } if (this.reference_exception !== null && this.reference_exception !== undefined) { output.writeFieldBegin('reference_exception', Thrift.Type.STRUCT, 4); this.reference_exception.write(output); output.writeFieldEnd(); } if (this.attribute_exception !== null && this.attribute_exception !== undefined) { output.writeFieldBegin('attribute_exception', Thrift.Type.STRUCT, 5); this.attribute_exception.write(output); output.writeFieldEnd(); } if (this.type_exception !== null && this.type_exception !== undefined) { output.writeFieldBegin('type_exception', Thrift.Type.STRUCT, 6); this.type_exception.write(output); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; }; assembly.thrift_serviceClient = function(input, output) { this.input = input; this.output = (!output) ? input : output; this.seqid = 0; }; assembly.thrift_serviceClient.prototype = {}; assembly.thrift_serviceClient.prototype.get_assembly_id = function(token, ref, callback) { if (callback === undefined) { this.send_get_assembly_id(token, ref); return this.recv_get_assembly_id(); } else { var postData = this.send_get_assembly_id(token, ref, true); return this.output.getTransport() .jqRequest(this, postData, arguments, this.recv_get_assembly_id); } }; assembly.thrift_serviceClient.prototype.send_get_assembly_id = function(token, ref, callback) { this.output.writeMessageBegin('get_assembly_id', Thrift.MessageType.CALL, this.seqid); var args = new assembly.thrift_service_get_assembly_id_args(); args.token = token; args.ref = ref; args.write(this.output); this.output.writeMessageEnd(); return this.output.getTransport().flush(callback); }; assembly.thrift_serviceClient.prototype.recv_get_assembly_id = function() { var ret = this.input.readMessageBegin(); var fname = ret.fname; var mtype = ret.mtype; var rseqid = ret.rseqid; if (mtype === Thrift.MessageType.EXCEPTION) { var x = new Thrift.TApplicationException(); x.read(this.input); this.input.readMessageEnd(); throw x; } var result = new assembly.thrift_service_get_assembly_id_result(); result.read(this.input); this.input.readMessageEnd(); if (null !== result.generic_exception) { throw result.generic_exception; } if (null !== result.authorization_exception) { throw result.authorization_exception; } if (null !== result.authentication_exception) { throw result.authentication_exception; } if (null !== result.reference_exception) { throw result.reference_exception; } if (null !== result.attribute_exception) { throw result.attribute_exception; } if (null !== result.type_exception) { throw result.type_exception; } if (null !== result.success) { return result.success; } throw 'get_assembly_id failed: unknown result'; }; assembly.thrift_serviceClient.prototype.get_genome_annotations = function(token, ref, callback) { if (callback === undefined) { this.send_get_genome_annotations(token, ref); return this.recv_get_genome_annotations(); } else { var postData = this.send_get_genome_annotations(token, ref, true); return this.output.getTransport() .jqRequest(this, postData, arguments, this.recv_get_genome_annotations); } }; assembly.thrift_serviceClient.prototype.send_get_genome_annotations = function(token, ref, callback) { this.output.writeMessageBegin('get_genome_annotations', Thrift.MessageType.CALL, this.seqid); var args = new assembly.thrift_service_get_genome_annotations_args(); args.token = token; args.ref = ref; args.write(this.output); this.output.writeMessageEnd(); return this.output.getTransport().flush(callback); }; assembly.thrift_serviceClient.prototype.recv_get_genome_annotations = function() { var ret = this.input.readMessageBegin(); var fname = ret.fname; var mtype = ret.mtype; var rseqid = ret.rseqid; if (mtype === Thrift.MessageType.EXCEPTION) { var x = new Thrift.TApplicationException(); x.read(this.input); this.input.readMessageEnd(); throw x; } var result = new assembly.thrift_service_get_genome_annotations_result(); result.read(this.input); this.input.readMessageEnd(); if (null !== result.generic_exception) { throw result.generic_exception; } if (null !== result.authorization_exception) { throw result.authorization_exception; } if (null !== result.authentication_exception) { throw result.authentication_exception; } if (null !== result.reference_exception) { throw result.reference_exception; } if (null !== result.attribute_exception) { throw result.attribute_exception; } if (null !== result.type_exception) { throw result.type_exception; } if (null !== result.success) { return result.success; } throw 'get_genome_annotations failed: unknown result'; }; assembly.thrift_serviceClient.prototype.get_external_source_info = function(token, ref, callback) { if (callback === undefined) { this.send_get_external_source_info(token, ref); return this.recv_get_external_source_info(); } else { var postData = this.send_get_external_source_info(token, ref, true); return this.output.getTransport() .jqRequest(this, postData, arguments, this.recv_get_external_source_info); } }; assembly.thrift_serviceClient.prototype.send_get_external_source_info = function(token, ref, callback) { this.output.writeMessageBegin('get_external_source_info', Thrift.MessageType.CALL, this.seqid); var args = new assembly.thrift_service_get_external_source_info_args(); args.token = token; args.ref = ref; args.write(this.output); this.output.writeMessageEnd(); return this.output.getTransport().flush(callback); }; assembly.thrift_serviceClient.prototype.recv_get_external_source_info = function() { var ret = this.input.readMessageBegin(); var fname = ret.fname; var mtype = ret.mtype; var rseqid = ret.rseqid; if (mtype === Thrift.MessageType.EXCEPTION) { var x = new Thrift.TApplicationException(); x.read(this.input); this.input.readMessageEnd(); throw x; } var result = new assembly.thrift_service_get_external_source_info_result(); result.read(this.input); this.input.readMessageEnd(); if (null !== result.generic_exception) { throw result.generic_exception; } if (null !== result.authorization_exception) { throw result.authorization_exception; } if (null !== result.authentication_exception) { throw result.authentication_exception; } if (null !== result.reference_exception) { throw result.reference_exception; } if (null !== result.attribute_exception) { throw result.attribute_exception; } if (null !== result.type_exception) { throw result.type_exception; } if (null !== result.success) { return result.success; } throw 'get_external_source_info failed: unknown result'; }; assembly.thrift_serviceClient.prototype.get_stats = function(token, ref, callback) { if (callback === undefined) { this.send_get_stats(token, ref); return this.recv_get_stats(); } else { var postData = this.send_get_stats(token, ref, true); return this.output.getTransport() .jqRequest(this, postData, arguments, this.recv_get_stats); } }; assembly.thrift_serviceClient.prototype.send_get_stats = function(token, ref, callback) { this.output.writeMessageBegin('get_stats', Thrift.MessageType.CALL, this.seqid); var args = new assembly.thrift_service_get_stats_args(); args.token = token; args.ref = ref; args.write(this.output); this.output.writeMessageEnd(); return this.output.getTransport().flush(callback); }; assembly.thrift_serviceClient.prototype.recv_get_stats = function() { var ret = this.input.readMessageBegin(); var fname = ret.fname; var mtype = ret.mtype; var rseqid = ret.rseqid; if (mtype === Thrift.MessageType.EXCEPTION) { var x = new Thrift.TApplicationException(); x.read(this.input); this.input.readMessageEnd(); throw x; } var result = new assembly.thrift_service_get_stats_result(); result.read(this.input); this.input.readMessageEnd(); if (null !== result.generic_exception) { throw result.generic_exception; } if (null !== result.authorization_exception) { throw result.authorization_exception; } if (null !== result.authentication_exception) { throw result.authentication_exception; } if (null !== result.reference_exception) { throw result.reference_exception; } if (null !== result.attribute_exception) { throw result.attribute_exception; } if (null !== result.type_exception) { throw result.type_exception; } if (null !== result.success) { return result.success; } throw 'get_stats failed: unknown result'; }; assembly.thrift_serviceClient.prototype.get_number_contigs = function(token, ref, callback) { if (callback === undefined) { this.send_get_number_contigs(token, ref); return this.recv_get_number_contigs(); } else { var postData = this.send_get_number_contigs(token, ref, true); return this.output.getTransport() .jqRequest(this, postData, arguments, this.recv_get_number_contigs); } }; assembly.thrift_serviceClient.prototype.send_get_number_contigs = function(token, ref, callback) { this.output.writeMessageBegin('get_number_contigs', Thrift.MessageType.CALL, this.seqid); var args = new assembly.thrift_service_get_number_contigs_args(); args.token = token; args.ref = ref; args.write(this.output); this.output.writeMessageEnd(); return this.output.getTransport().flush(callback); }; assembly.thrift_serviceClient.prototype.recv_get_number_contigs = function() { var ret = this.input.readMessageBegin(); var fname = ret.fname; var mtype = ret.mtype; var rseqid = ret.rseqid; if (mtype === Thrift.MessageType.EXCEPTION) { var x = new Thrift.TApplicationException(); x.read(this.input); this.input.readMessageEnd(); throw x; } var result = new assembly.thrift_service_get_number_contigs_result(); result.read(this.input); this.input.readMessageEnd(); if (null !== result.generic_exception) { throw result.generic_exception; } if (null !== result.authorization_exception) { throw result.authorization_exception; } if (null !== result.authentication_exception) { throw result.authentication_exception; } if (null !== result.reference_exception) { throw result.reference_exception; } if (null !== result.attribute_exception) { throw result.attribute_exception; } if (null !== result.type_exception) { throw result.type_exception; } if (null !== result.success) { return result.success; } throw 'get_number_contigs failed: unknown result'; }; assembly.thrift_serviceClient.prototype.get_gc_content = function(token, ref, callback) { if (callback === undefined) { this.send_get_gc_content(token, ref); return this.recv_get_gc_content(); } else { var postData = this.send_get_gc_content(token, ref, true); return this.output.getTransport() .jqRequest(this, postData, arguments, this.recv_get_gc_content); } }; assembly.thrift_serviceClient.prototype.send_get_gc_content = function(token, ref, callback) { this.output.writeMessageBegin('get_gc_content', Thrift.MessageType.CALL, this.seqid); var args = new assembly.thrift_service_get_gc_content_args(); args.token = token; args.ref = ref; args.write(this.output); this.output.writeMessageEnd(); return this.output.getTransport().flush(callback); }; assembly.thrift_serviceClient.prototype.recv_get_gc_content = function() { var ret = this.input.readMessageBegin(); var fname = ret.fname; var mtype = ret.mtype; var rseqid = ret.rseqid; if (mtype === Thrift.MessageType.EXCEPTION) { var x = new Thrift.TApplicationException(); x.read(this.input); this.input.readMessageEnd(); throw x; } var result = new assembly.thrift_service_get_gc_content_result(); result.read(this.input); this.input.readMessageEnd(); if (null !== result.generic_exception) { throw result.generic_exception; } if (null !== result.authorization_exception) { throw result.authorization_exception; } if (null !== result.authentication_exception) { throw result.authentication_exception; } if (null !== result.reference_exception) { throw result.reference_exception; } if (null !== result.attribute_exception) { throw result.attribute_exception; } if (null !== result.type_exception) { throw result.type_exception; } if (null !== result.success) { return result.success; } throw 'get_gc_content failed: unknown result'; }; assembly.thrift_serviceClient.prototype.get_dna_size = function(token, ref, callback) { if (callback === undefined) { this.send_get_dna_size(token, ref); return this.recv_get_dna_size(); } else { var postData = this.send_get_dna_size(token, ref, true); return this.output.getTransport() .jqRequest(this, postData, arguments, this.recv_get_dna_size); } }; assembly.thrift_serviceClient.prototype.send_get_dna_size = function(token, ref, callback) { this.output.writeMessageBegin('get_dna_size', Thrift.MessageType.CALL, this.seqid); var args = new assembly.thrift_service_get_dna_size_args(); args.token = token; args.ref = ref; args.write(this.output); this.output.writeMessageEnd(); return this.output.getTransport().flush(callback); }; assembly.thrift_serviceClient.prototype.recv_get_dna_size = function() { var ret = this.input.readMessageBegin(); var fname = ret.fname; var mtype = ret.mtype; var rseqid = ret.rseqid; if (mtype === Thrift.MessageType.EXCEPTION) { var x = new Thrift.TApplicationException(); x.read(this.input); this.input.readMessageEnd(); throw x; } var result = new assembly.thrift_service_get_dna_size_result(); result.read(this.input); this.input.readMessageEnd(); if (null !== result.generic_exception) { throw result.generic_exception; } if (null !== result.authorization_exception) { throw result.authorization_exception; } if (null !== result.authentication_exception) { throw result.authentication_exception; } if (null !== result.reference_exception) { throw result.reference_exception; } if (null !== result.attribute_exception) { throw result.attribute_exception; } if (null !== result.type_exception) { throw result.type_exception; } if (null !== result.success) { return result.success; } throw 'get_dna_size failed: unknown result'; }; assembly.thrift_serviceClient.prototype.get_contig_ids = function(token, ref, callback) { if (callback === undefined) { this.send_get_contig_ids(token, ref); return this.recv_get_contig_ids(); } else { var postData = this.send_get_contig_ids(token, ref, true); return this.output.getTransport() .jqRequest(this, postData, arguments, this.recv_get_contig_ids); } }; assembly.thrift_serviceClient.prototype.send_get_contig_ids = function(token, ref, callback) { this.output.writeMessageBegin('get_contig_ids', Thrift.MessageType.CALL, this.seqid); var args = new assembly.thrift_service_get_contig_ids_args(); args.token = token; args.ref = ref; args.write(this.output); this.output.writeMessageEnd(); return this.output.getTransport().flush(callback); }; assembly.thrift_serviceClient.prototype.recv_get_contig_ids = function() { var ret = this.input.readMessageBegin(); var fname = ret.fname; var mtype = ret.mtype; var rseqid = ret.rseqid; if (mtype === Thrift.MessageType.EXCEPTION) { var x = new Thrift.TApplicationException(); x.read(this.input); this.input.readMessageEnd(); throw x; } var result = new assembly.thrift_service_get_contig_ids_result(); result.read(this.input); this.input.readMessageEnd(); if (null !== result.generic_exception) { throw result.generic_exception; } if (null !== result.authorization_exception) { throw result.authorization_exception; } if (null !== result.authentication_exception) { throw result.authentication_exception; } if (null !== result.reference_exception) { throw result.reference_exception; } if (null !== result.attribute_exception) { throw result.attribute_exception; } if (null !== result.type_exception) { throw result.type_exception; } if (null !== result.success) { return result.success; } throw 'get_contig_ids failed: unknown result'; }; assembly.thrift_serviceClient.prototype.get_contig_lengths = function(token, ref, contig_id_list, callback) { if (callback === undefined) { this.send_get_contig_lengths(token, ref, contig_id_list); return this.recv_get_contig_lengths(); } else { var postData = this.send_get_contig_lengths(token, ref, contig_id_list, true); return this.output.getTransport() .jqRequest(this, postData, arguments, this.recv_get_contig_lengths); } }; assembly.thrift_serviceClient.prototype.send_get_contig_lengths = function(token, ref, contig_id_list, callback) { this.output.writeMessageBegin('get_contig_lengths', Thrift.MessageType.CALL, this.seqid); var args = new assembly.thrift_service_get_contig_lengths_args(); args.token = token; args.ref = ref; args.contig_id_list = contig_id_list; args.write(this.output); this.output.writeMessageEnd(); return this.output.getTransport().flush(callback); }; assembly.thrift_serviceClient.prototype.recv_get_contig_lengths = function() { var ret = this.input.readMessageBegin(); var fname = ret.fname; var mtype = ret.mtype; var rseqid = ret.rseqid; if (mtype === Thrift.MessageType.EXCEPTION) { var x = new Thrift.TApplicationException(); x.read(this.input); this.input.readMessageEnd(); throw x; } var result = new assembly.thrift_service_get_contig_lengths_result(); result.read(this.input); this.input.readMessageEnd(); if (null !== result.generic_exception) { throw result.generic_exception; } if (null !== result.authorization_exception) { throw result.authorization_exception; } if (null !== result.authentication_exception) { throw result.authentication_exception; } if (null !== result.reference_exception) { throw result.reference_exception; } if (null !== result.attribute_exception) { throw result.attribute_exception; } if (null !== result.type_exception) { throw result.type_exception; } if (null !== result.success) { return result.success; } throw 'get_contig_lengths failed: unknown result'; }; assembly.thrift_serviceClient.prototype.get_contig_gc_content = function(token, ref, contig_id_list, callback) { if (callback === undefined) { this.send_get_contig_gc_content(token, ref, contig_id_list); return this.recv_get_contig_gc_content(); } else { var postData = this.send_get_contig_gc_content(token, ref, contig_id_list, true); return this.output.getTransport() .jqRequest(this, postData, arguments, this.recv_get_contig_gc_content); } }; assembly.thrift_serviceClient.prototype.send_get_contig_gc_content = function(token, ref, contig_id_list, callback) { this.output.writeMessageBegin('get_contig_gc_content', Thrift.MessageType.CALL, this.seqid); var args = new assembly.thrift_service_get_contig_gc_content_args(); args.token = token; args.ref = ref; args.contig_id_list = contig_id_list; args.write(this.output); this.output.writeMessageEnd(); return this.output.getTransport().flush(callback); }; assembly.thrift_serviceClient.prototype.recv_get_contig_gc_content = function() { var ret = this.input.readMessageBegin(); var fname = ret.fname; var mtype = ret.mtype; var rseqid = ret.rseqid; if (mtype === Thrift.MessageType.EXCEPTION) { var x = new Thrift.TApplicationException(); x.read(this.input); this.input.readMessageEnd(); throw x; } var result = new assembly.thrift_service_get_contig_gc_content_result(); result.read(this.input); this.input.readMessageEnd(); if (null !== result.generic_exception) { throw result.generic_exception; } if (null !== result.authorization_exception) { throw result.authorization_exception; } if (null !== result.authentication_exception) { throw result.authentication_exception; } if (null !== result.reference_exception) { throw result.reference_exception; } if (null !== result.attribute_exception) { throw result.attribute_exception; } if (null !== result.type_exception) { throw result.type_exception; } if (null !== result.success) { return result.success; } throw 'get_contig_gc_content failed: unknown result'; }; assembly.thrift_serviceClient.prototype.get_contigs = function(token, ref, contig_id_list, callback) { if (callback === undefined) { this.send_get_contigs(token, ref, contig_id_list); return this.recv_get_contigs(); } else { var postData = this.send_get_contigs(token, ref, contig_id_list, true); return this.output.getTransport() .jqRequest(this, postData, arguments, this.recv_get_contigs); } }; assembly.thrift_serviceClient.prototype.send_get_contigs = function(token, ref, contig_id_list, callback) { this.output.writeMessageBegin('get_contigs', Thrift.MessageType.CALL, this.seqid); var args = new assembly.thrift_service_get_contigs_args(); args.token = token; args.ref = ref; args.contig_id_list = contig_id_list; args.write(this.output); this.output.writeMessageEnd(); return this.output.getTransport().flush(callback); }; assembly.thrift_serviceClient.prototype.recv_get_contigs = function() { var ret = this.input.readMessageBegin(); var fname = ret.fname; var mtype = ret.mtype; var rseqid = ret.rseqid; if (mtype === Thrift.MessageType.EXCEPTION) { var x = new Thrift.TApplicationException(); x.read(this.input); this.input.readMessageEnd(); throw x; } var result = new assembly.thrift_service_get_contigs_result(); result.read(this.input); this.input.readMessageEnd(); if (null !== result.generic_exception) { throw result.generic_exception; } if (null !== result.authorization_exception) { throw result.authorization_exception; } if (null !== result.authentication_exception) { throw result.authentication_exception; } if (null !== result.reference_exception) { throw result.reference_exception; } if (null !== result.attribute_exception) { throw result.attribute_exception; } if (null !== result.type_exception) { throw result.type_exception; } if (null !== result.success) { return result.success; } throw 'get_contigs failed: unknown result'; }; return assembly; });
/* * Tests that the parse trees generated by nearley-lanauge-bootstrapped.ne * match those generated by the old scannerless-nearley.ne. */ const fs = require('fs'); const expect = require('expect'); const nearley = require('../lib/nearley'); const shared = require('./_shared'); const compile = shared.compile; const parse = shared.parse; function read(filename) { return fs.readFileSync(filename, 'utf-8'); } describe('bootstrapped lexer', () => { const lexer = compile(read("lib/nearley-language-bootstrapped.ne")).lexer; function lex(source) { return Array.from(lexer.reset(source)).map(tok => tok.type + " " + tok.value) } function lexTypes(source) { return Array.from(lexer.reset(source)).map(tok => tok.type) } it('lexes directives', () => { expect(lex('@builtin "quxx"')).toEqual([ "@builtin @builtin", "ws ", "string quxx", ]) expect(lex("@lexer moo")).toEqual([ "@ @", "word lexer", "ws ", "word moo", ]) }) it('lexes a simple rule', () => { expect(lex("foo -> bar")).toEqual([ "word foo", "ws ", "arrow ->", "ws ", "word bar", ]) }) it('lexes arrows', () => { expect(lex("->")).toEqual(["arrow ->"]) expect(lex("=>")).toEqual(["arrow =>"]) expect(lex("-=->")).toEqual(["arrow -=->"]) }) it('lexes js code', () => { expect(lexTypes("{% foo % %}")).toEqual(['js']) expect(lexTypes("{% function() %}")).toEqual(['js']) expect(lexTypes("{% %}")).toEqual(['js']) expect(lexTypes("{%%}")).toEqual(['js']) }) it('lexes charclasses', () => { expect(lex(".")).toEqual([ "charclass /./", ]) expect(lex("[^a-z\\s]")).toEqual([ "charclass /[^a-z\\s]/", ]) expect(lex("foo->[^a-z\\s]")).toEqual([ "word foo", "arrow ->", "charclass /[^a-z\\s]/", ]) }) it('rejects newline in charclass', () => { expect(() => lex("[foo\n]")).toThrow() }) it('lexes macros', () => { expect(lex("foo[X, Y]")).toEqual([ "word foo", "[ [", "word X", ", ,", "ws ", "word Y", "] ]", ]) expect(lex("foo[[0-9]]")).toEqual([ "word foo", "[ [", "charclass /[0-9]/", "] ]", ]) }) it('lexes strings', () => { expect(lex(`"bar"`)).toEqual(['string bar']) expect(lex('"I\\"m\\\\"')).toEqual(["string I\"m\\"]) expect(lex('"foo\\"b\\\\ar\\n"')).toEqual(['string foo"b\\ar\n']) expect(lex('"\\u1234"')).toEqual(['string \u1234']) }) it('lexes strings non-greedily ', () => { expect(lexTypes('"foo" "bar"')).toEqual(["string", "ws", "string"]) }) it('lexes a rule', () => { expect(lex('Tp4 -> "(" _ Tp _ ")"')).toEqual([ "word Tp4", "ws ", "arrow ->", "ws ", "string (", "ws ", "word _", "ws ", "word Tp", "ws ", "word _", "ws ", "string )", ]) }) }) describe('bootstrapped parser', () => { const scannerless = compile(read("test/grammars/scannerless-nearley.ne")); const current = compile(read("lib/nearley-language-bootstrapped.ne")); const check = source => expect(parse(current, source)).toEqual(parse(scannerless, source)) it('parses directives', () => { check("@lexer moo") check('@include "foo"') check('@builtin "bar"') }) it('parses simple rules', () => { check('foo -> "waffle"') check("foo -> bar") }) it('parses postprocessors', () => { check('foo -> "waffle" {% d => d[0] %}') check('foo -> "waffle" {%\nfunction(d) { return d[0]; }\n%}') }) it('parses js code', () => { check("@{%\nconst moo = require('moo');\n%}") }) it('parses options', () => { check("foo -> bar\n | quxx") }) it('parses tokens', () => { check("foo -> %foo") }) it('parses strings', () => { check('foo -> "potato"') check('foo -> "("') //check("foo -> 'p'") }) it('parses charclasses', () => { check('char -> .') check('y -> x:+\nx -> [a-z0-9] | "\\n"') check('m_key -> "any" {% id %} | [a-z0-9] {% id %}') }) it('parses macro definitions', () => { check('foo[X] -> X') check('foo[X, Y] -> X') }) it('parses macro use', () => { check('Y -> foo[Q]') check('Y -> foo[Q, P]') check('Y -> foo["string"]') check('Y -> foo[%tok]') check('Y -> foo[(baz quxx)]') }) it('parses macro use', () => { check('Y -> foo[Q]') check('Y -> foo[Q, P]') check('Y -> foo["string"]') check('Y -> foo[%tok]') check('Y -> foo[(baz quxx)]') }) it('parses a rule', () => { check('Tp4 -> "(" _ Tp _ ")"') }) })
/** * Created by lu on 2017/7/20. */ import React, { Component } from 'react'; import { Slider, Icon, InputNumber } from 'antd'; import styles from './SuperResolutionSlider.css'; class SRSlider extends Component { constructor(props) { super(props); this.state = { cHeight: this.props.pre_height, sliderValue: this.props.value, cWidth: this.props.pre_width, }; } handleChange = (v) => { this.setState({ cWidth: v * this.props.pre_width, sliderValue: v, cHeight: v * this.props.pre_height, }); this.props.handleSlider(v * this.props.pre_width, v * this.props.pre_height); } handleWidthChange=(v) => { this.setState({ cWidth: v, sliderValue: (v / this.props.pre_width), cHeight: ((v / this.props.pre_width) * this.props.pre_height), }); this.props.handleSlider(v, ((v / this.props.pre_width) * this.props.pre_height)); } handleHeightChange=(v) => { this.setState({ cHeight: v, sliderValue: (v / this.props.pre_height), cWidth: ((v / this.props.pre_height) * this.props.pre_width), }); this.props.handleSlider(((v / this.props.pre_height) * this.props.pre_width), v); } render() { return ( <div className={styles.SR_icon_wrapper}> <Icon className={styles.anticon1} type="minus-circle" /> <Slider {...this.props} className={styles.anticon} tipFormatter={formatter} value={this.state.sliderValue} onChange={this.handleChange} step={0.1} /> <Icon className={styles.anticon2} type="plus-circle" /> <InputNumber {...this.props} className={styles.inputWidth} min={this.props.pre_width} max={this.props.pre_width * 2} value={this.state.sliderValue * this.props.pre_width} onChange={this.handleWidthChange} /> <InputNumber {...this.props} className={styles.inputHeight} min={this.props.pre_height} max={this.props.pre_height * 2} value={this.state.sliderValue * this.props.pre_height} onChange={this.handleHeightChange} /> <label className={`${styles.note_label} ${styles.px1_label}`} htmlFor={`${styles.try}`} >px</label> <label className={`${styles.note_label} ${styles.px2_label}`} htmlFor={`${styles.try}`} >px</label> </div> ); } } function formatter(value) { return `x${value}`; } export default SRSlider; SRSlider.propTypes = { pre_width: React.PropTypes.number.isRequired, pre_height: React.PropTypes.number.isRequired, value: React.PropTypes.number.isRequired, handleSlider: React.PropTypes.func.isRequired, };
'use strict'; import angular from 'angular'; import CONFIG from '../../common/config'; let actions = () => { return { template: require('./templates/actions.html'), scope: { send: '=', } }; }; angular.module(CONFIG.APP).directive('actions', actions);
// OPCION 1: Para implementar agregar: onkeypress="return validaPatron(event, 'patron')" function validaPatron(event, patron) { // Patron de entrada, en este caso solo aceptaria numeros o numeros y punto. // patron =[0-9]; patron =[0-9-.]; tecla = (document.all) ? event.keyCode : event.which; // Teclas de retroceso para borrar(8), tab(9), enter(13), flecha izquierda(37) y derecha(39), siempre la permite if (tecla==8 || tecla==13) { return true; } else if (event.keyCode==9 || event.keyCode==37 || event.keyCode==39) { return true; } patron = new RegExp(patron); tecla_final = String.fromCharCode(tecla); return patron.test(tecla_final); } // OPCION 2: Utilizo JQuery para el control se debe poner como class: mwsValidaPatron // Para configurar el Patron agregar propiedad como ejemplos, mwspatron = [0-9]; mwspatron = [0-9-.]; returnGlobal = false; // EJECUTA PRIMERO $(".mwsValidaPatron").on("keydown", function(event) { returnGlobal = false; tecla = event.which; // Teclas de retroceso para borrar(8), tab(9), enter(13), flecha izquierda(37), derecha(39), // suprimir(46), siempre la permite if (tecla==8 || tecla==9 || tecla==13 || tecla==37 || tecla==39 || tecla==46) { returnGlobal = true; } }); // EJECUTA SEGUNDO $(".mwsValidaPatron").on("keypress", function(event) { if (returnGlobal) { return true; } else { patron = null; $.each(this.attributes, function(index, attr) { if(attr.name == "mwspatron") { patron = attr.value; } }); patron = new RegExp(patron); tecla = (document.all) ? event.keyCode : event.which; tecla_final = String.fromCharCode(tecla); return patron.test(tecla_final); } });
// Compiled by ClojureScript 1.10.339 {} goog.provide('example.demos.table.events'); goog.require('cljs.core'); goog.require('re_frame.core'); goog.require('clojure.string'); goog.require('example.utils.js'); goog.require('example.utils.http_fx'); re_frame.core.reg_event_fx.call(null,new cljs.core.Keyword(null,"get-people","get-people",726403750),new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [((goog.DEBUG)?re_frame.core.debug:null)], null),(function (p__28207,p__28208){ var map__28209 = p__28207; var map__28209__$1 = ((((!((map__28209 == null)))?(((((map__28209.cljs$lang$protocol_mask$partition0$ & (64))) || ((cljs.core.PROTOCOL_SENTINEL === map__28209.cljs$core$ISeq$))))?true:false):false))?cljs.core.apply.call(null,cljs.core.hash_map,map__28209):map__28209); var db = cljs.core.get.call(null,map__28209__$1,new cljs.core.Keyword(null,"db","db",993250759)); var vec__28210 = p__28208; var _ = cljs.core.nth.call(null,vec__28210,(0),null); var vals = cljs.core.nth.call(null,vec__28210,(1),null); var page = new cljs.core.Keyword(null,"page","page",849072397).cljs$core$IFn$_invoke$arity$1(vals); return new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"http-xhrio","http-xhrio",1846166714),example.utils.http_fx.GET.call(null,["https://swapi.co/api/people/?page=",cljs.core.str.cljs$core$IFn$_invoke$arity$1(page)].join(''),new cljs.core.Keyword(null,"get-people-success","get-people-success",1458367143),new cljs.core.Keyword(null,"get-people-failure","get-people-failure",-1197832865))], null); })); re_frame.core.reg_event_db.call(null,new cljs.core.Keyword(null,"get-people-success","get-people-success",1458367143),(function (db,p__28214){ var vec__28215 = p__28214; var _ = cljs.core.nth.call(null,vec__28215,(0),null); var response = cljs.core.nth.call(null,vec__28215,(1),null); var records = new cljs.core.Keyword(null,"results","results",-1134170113).cljs$core$IFn$_invoke$arity$1(response); return cljs.core.assoc_in.call(null,cljs.core.assoc_in.call(null,cljs.core.assoc_in.call(null,db,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"loading?","loading?",1905707049),new cljs.core.Keyword(null,"people","people",1443537404)], null),false),new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"people","people",1443537404),new cljs.core.Keyword(null,"total","total",1916810418)], null),new cljs.core.Keyword(null,"count","count",2139924085).cljs$core$IFn$_invoke$arity$1(response)),new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"people","people",1443537404),new cljs.core.Keyword(null,"records","records",1326822832)], null),records); })); re_frame.core.reg_event_db.call(null,new cljs.core.Keyword(null,"get-people-failure","get-people-failure",-1197832865),(function (db,p__28218){ var vec__28219 = p__28218; var _ = cljs.core.nth.call(null,vec__28219,(0),null); var response = cljs.core.nth.call(null,vec__28219,(1),null); return cljs.core.assoc.call(null,cljs.core.assoc_in.call(null,db,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"loading?","loading?",1905707049),new cljs.core.Keyword(null,"people","people",1443537404)], null),false),new cljs.core.Keyword(null,"current-user","current-user",-868792091),cljs.core.PersistentArrayMap.EMPTY,new cljs.core.Keyword(null,"error","error",-978969032),response); })); re_frame.core.reg_event_db.call(null,new cljs.core.Keyword(null,"set-current-file","set-current-file",2128397373),(function (db,p__28222){ var vec__28223 = p__28222; var _ = cljs.core.nth.call(null,vec__28223,(0),null); var current_file = cljs.core.nth.call(null,vec__28223,(1),null); return cljs.core.assoc.call(null,db,new cljs.core.Keyword(null,"current-file","current-file",56284307),current_file); })); //# sourceMappingURL=events.js.map?rel=1542405694851
require('ember-model/adapter'); require('ember-model/record_array'); var get = Ember.get, set = Ember.set, setProperties = Ember.setProperties, meta = Ember.meta, underscore = Ember.String.underscore; function contains(array, element) { for (var i = 0, l = array.length; i < l; i++) { if (array[i] === element) { return true; } } return false; } function concatUnique(toArray, fromArray) { var e; for (var i = 0, l = fromArray.length; i < l; i++) { e = fromArray[i]; if (!contains(toArray, e)) { toArray.push(e); } } return toArray; } function hasCachedValue(object, key) { var objectMeta = meta(object, false); if (objectMeta) { return key in objectMeta.cache; } } Ember.run.queues.push('data'); Ember.Model = Ember.Object.extend(Ember.Evented, { isLoaded: true, isLoading: Ember.computed.not('isLoaded'), isNew: true, isDeleted: false, _dirtyAttributes: null, /** Called when attribute is accessed. @method getAttr @param key {String} key which is being accessed @param value {Object} value, which will be returned from getter by default */ getAttr: function(key, value) { return value; }, isDirty: function() { var dirtyAttributes = get(this, '_dirtyAttributes'); return dirtyAttributes && dirtyAttributes.length !== 0 || false; }.property('_dirtyAttributes.length'), _relationshipBecameDirty: function(name) { var dirtyAttributes = get(this, '_dirtyAttributes'); if (!dirtyAttributes.contains(name)) { dirtyAttributes.pushObject(name); } }, _relationshipBecameClean: function(name) { var dirtyAttributes = get(this, '_dirtyAttributes'); dirtyAttributes.removeObject(name); }, dataKey: function(key) { var camelizeKeys = get(this.constructor, 'camelizeKeys'); var meta = this.constructor.metaForProperty(key); if (meta.options && meta.options.key) { return camelizeKeys ? underscore(meta.options.key) : meta.options.key; } return camelizeKeys ? underscore(key) : key; }, init: function() { this._createReference(); if (!this._dirtyAttributes) { set(this, '_dirtyAttributes', []); } this._super(); }, _createReference: function() { var reference = this._reference, id = this.getPrimaryKey(); if (!reference) { reference = this.constructor._getOrCreateReferenceForId(id); reference.record = this; this._reference = reference; } else if (reference.id !== id) { reference.id = id; this.constructor._cacheReference(reference); } if (!reference.id) { reference.id = id; } return reference; }, getPrimaryKey: function() { return get(this, get(this.constructor, 'primaryKey')); }, load: function(id, hash) { var data = {}; data[get(this.constructor, 'primaryKey')] = id; set(this, '_data', Ember.merge(data, hash)); this.getWithDefault('_dirtyAttributes', []).clear(); this._reloadHasManys(); // eagerly load embedded data var relationships = this.constructor._relationships || [], meta = Ember.meta(this), relationshipKey, relationship, relationshipMeta, relationshipData, relationshipType; for (var i = 0, l = relationships.length; i < l; i++) { relationshipKey = relationships[i]; relationship = meta.descs[relationshipKey]; relationshipMeta = relationship.meta(); if (relationshipMeta.options.embedded) { relationshipType = relationshipMeta.type; if (typeof relationshipType === "string") { relationshipType = Ember.get(Ember.lookup, relationshipType) || this.container.lookupFactory('model:'+ relationshipType); } relationshipData = data[relationshipKey]; if (relationshipData) { relationshipType.load(relationshipData); } } } set(this, 'isNew', false); set(this, 'isLoaded', true); this._createReference(); this.trigger('didLoad'); }, didDefineProperty: function(proto, key, value) { if (value instanceof Ember.Descriptor) { var meta = value.meta(); var klass = proto.constructor; if (meta.isAttribute) { if (!klass._attributes) { klass._attributes = []; } klass._attributes.push(key); } else if (meta.isRelationship) { if (!klass._relationships) { klass._relationships = []; } klass._relationships.push(key); meta.relationshipKey = key; } } }, serializeHasMany: function(key, meta) { return this.get(key).toJSON(); }, serializeBelongsTo: function(key, meta) { if (meta.options.embedded) { var record = this.get(key); return record ? record.toJSON() : null; } else { var primaryKey = get(meta.getType(), 'primaryKey'); return this.get(key + '.' + primaryKey); } }, toJSON: function() { var key, meta, json = {}, attributes = this.constructor.getAttributes(), relationships = this.constructor.getRelationships(), properties = attributes ? this.getProperties(attributes) : {}, rootKey = get(this.constructor, 'rootKey'); for (key in properties) { meta = this.constructor.metaForProperty(key); if (meta.type && meta.type.serialize) { json[this.dataKey(key)] = meta.type.serialize(properties[key]); } else if (meta.type && Ember.Model.dataTypes[meta.type]) { json[this.dataKey(key)] = Ember.Model.dataTypes[meta.type].serialize(properties[key]); } else { json[this.dataKey(key)] = properties[key]; } } if (relationships) { var data, relationshipKey; for(var i = 0; i < relationships.length; i++) { key = relationships[i]; meta = this.constructor.metaForProperty(key); relationshipKey = meta.options.key || key; if (meta.kind === 'belongsTo') { data = this.serializeBelongsTo(key, meta); } else { data = this.serializeHasMany(key, meta); } json[relationshipKey] = data; } } if (rootKey) { var jsonRoot = {}; jsonRoot[rootKey] = json; return jsonRoot; } else { return json; } }, save: function() { var adapter = this.constructor.adapter; set(this, 'isSaving', true); if (get(this, 'isNew')) { return adapter.createRecord(this); } else if (get(this, 'isDirty')) { return adapter.saveRecord(this); } else { // noop, return a resolved promise var self = this, promise = new Ember.RSVP.Promise(function(resolve, reject) { resolve(self); }); set(this, 'isSaving', false); return promise; } }, reload: function() { this.getWithDefault('_dirtyAttributes', []).clear(); return this.constructor.reload(this.get(get(this.constructor, 'primaryKey')), this.container); }, revert: function() { this.getWithDefault('_dirtyAttributes', []).clear(); this.notifyPropertyChange('_data'); this._reloadHasManys(true); }, didCreateRecord: function() { var primaryKey = get(this.constructor, 'primaryKey'), id = get(this, primaryKey); set(this, 'isNew', false); set(this, '_dirtyAttributes', []); this.constructor.addToRecordArrays(this); this.trigger('didCreateRecord'); this.didSaveRecord(); }, didSaveRecord: function() { set(this, 'isSaving', false); this.trigger('didSaveRecord'); if (this.get('isDirty')) { this._copyDirtyAttributesToData(); } }, deleteRecord: function() { return this.constructor.adapter.deleteRecord(this); }, didDeleteRecord: function() { this.constructor.removeFromRecordArrays(this); set(this, 'isDeleted', true); this.trigger('didDeleteRecord'); }, _copyDirtyAttributesToData: function() { if (!this._dirtyAttributes) { return; } var dirtyAttributes = this._dirtyAttributes, data = get(this, '_data'), key; if (!data) { data = {}; set(this, '_data', data); } for (var i = 0, l = dirtyAttributes.length; i < l; i++) { // TODO: merge Object.create'd object into prototype key = dirtyAttributes[i]; data[this.dataKey(key)] = this.cacheFor(key); } set(this, '_dirtyAttributes', []); this._resetDirtyStateInNestedObjects(this); // we need to reset isDirty state to all child objects in embedded relationships }, _resetDirtyStateInNestedObjects: function(object) { var i, obj; if (object._hasManyArrays) { for (i = 0; i < object._hasManyArrays.length; i++) { var array = object._hasManyArrays[i]; array.revert(); if (array.embedded) { for (var j = 0; j < array.get('length'); j++) { obj = array.objectAt(j); obj._copyDirtyAttributesToData(); } } } } if (object._belongsTo) { for (i = 0; i < object._belongsTo.length; i++) { var belongsTo = object._belongsTo[i]; if (belongsTo.options.embedded) { obj = this.get(belongsTo.relationshipKey); if (obj) { obj._copyDirtyAttributesToData(); } } } } }, _registerHasManyArray: function(array) { if (!this._hasManyArrays) { this._hasManyArrays = Ember.A([]); } this._hasManyArrays.pushObject(array); }, registerParentHasManyArray: function(array) { if (!this._parentHasManyArrays) { this._parentHasManyArrays = Ember.A([]); } this._parentHasManyArrays.pushObject(array); }, unregisterParentHasManyArray: function(array) { if (!this._parentHasManyArrays) { return; } this._parentHasManyArrays.removeObject(array); }, _reloadHasManys: function(reverting) { if (!this._hasManyArrays) { return; } var i, j; for (i = 0; i < this._hasManyArrays.length; i++) { var array = this._hasManyArrays[i], hasManyContent = this._getHasManyContent(get(array, 'key'), get(array, 'modelClass'), get(array, 'embedded')); if (!reverting) { for (j = 0; j < array.get('length'); j++) { if (array.objectAt(j).get('isNew') && !array.objectAt(j).get('isDeleted')) { hasManyContent.addObject(array.objectAt(j)._reference); } } } array.load(hasManyContent); } }, _getHasManyContent: function(key, type, embedded) { var content = get(this, '_data.' + key); if (content) { var mapFunction, primaryKey, reference; if (embedded) { primaryKey = get(type, 'primaryKey'); mapFunction = function(attrs) { reference = type._getOrCreateReferenceForId(attrs[primaryKey]); reference.data = attrs; return reference; }; } else { mapFunction = function(id) { return type._getOrCreateReferenceForId(id); }; } content = Ember.EnumerableUtils.map(content, mapFunction); } return Ember.A(content || []); }, _registerBelongsTo: function(key) { if (!this._belongsTo) { this._belongsTo = Ember.A([]); } this._belongsTo.pushObject(key); } }); Ember.Model.reopenClass({ primaryKey: 'id', adapter: Ember.Adapter.create(), _clientIdCounter: 1, getAttributes: function() { this.proto(); // force class "compilation" if it hasn't been done. var attributes = this._attributes || []; if (typeof this.superclass.getAttributes === 'function') { attributes = this.superclass.getAttributes().concat(attributes); } return attributes; }, getRelationships: function() { this.proto(); // force class "compilation" if it hasn't been done. var relationships = this._relationships || []; if (typeof this.superclass.getRelationships === 'function') { relationships = this.superclass.getRelationships().concat(relationships); } return relationships; }, fetch: function(id) { if (!arguments.length) { return this._findFetchAll(true); } else if (Ember.isArray(id)) { return this._findFetchMany(id, true); } else if (typeof id === 'object') { return this._findFetchQuery(id, true); } else { return this._findFetchById(id, true); } }, find: function(id) { if (!arguments.length) { return this._findFetchAll(false); } else if (Ember.isArray(id)) { return this._findFetchMany(id, false); } else if (typeof id === 'object') { return this._findFetchQuery(id, false); } else { return this._findFetchById(id, false); } }, findQuery: function(params) { return this._findFetchQuery(params, false); }, fetchQuery: function(params) { return this._findFetchQuery(params, true); }, _findFetchQuery: function(params, isFetch, container) { var records = Ember.RecordArray.create({modelClass: this, _query: params, container: container}); var promise = this.adapter.findQuery(this, records, params); return isFetch ? promise : records; }, findMany: function(ids) { return this._findFetchMany(ids, false); }, fetchMany: function(ids) { return this._findFetchMany(ids, true); }, _findFetchMany: function(ids, isFetch, container) { Ember.assert("findFetchMany requires an array", Ember.isArray(ids)); var records = Ember.RecordArray.create({_ids: ids, modelClass: this, container: container}), deferred; if (!this.recordArrays) { this.recordArrays = []; } this.recordArrays.push(records); if (this._currentBatchIds) { concatUnique(this._currentBatchIds, ids); this._currentBatchRecordArrays.push(records); } else { this._currentBatchIds = concatUnique([], ids); this._currentBatchRecordArrays = [records]; } if (isFetch) { deferred = Ember.Deferred.create(); Ember.set(deferred, 'resolveWith', records); if (!this._currentBatchDeferreds) { this._currentBatchDeferreds = []; } this._currentBatchDeferreds.push(deferred); } Ember.run.scheduleOnce('data', this, this._executeBatch, container); return isFetch ? deferred : records; }, findAll: function() { return this._findFetchAll(false); }, fetchAll: function() { return this._findFetchAll(true); }, _findFetchAll: function(isFetch, container) { var self = this; var currentFetchPromise = this._currentFindFetchAllPromise; if (isFetch && currentFetchPromise) { return currentFetchPromise; } else if (this._findAllRecordArray) { if (isFetch) { return new Ember.RSVP.Promise(function(resolve) { resolve(self._findAllRecordArray); }); } else { return this._findAllRecordArray; } } var records = this._findAllRecordArray = Ember.RecordArray.create({modelClass: this, container: container}); var promise = this._currentFindFetchAllPromise = this.adapter.findAll(this, records); promise.finally(function() { self._currentFindFetchAllPromise = null; }); // Remove the cached record array if the promise is rejected if (promise.then) { promise.then(null, function() { self._findAllRecordArray = null; return Ember.RSVP.reject.apply(null, arguments); }); } return isFetch ? promise : records; }, findById: function(id) { return this._findFetchById(id, false); }, fetchById: function(id) { return this._findFetchById(id, true); }, _findFetchById: function(id, isFetch, container) { var record = this.cachedRecordForId(id, container), isLoaded = get(record, 'isLoaded'), adapter = get(this, 'adapter'), deferredOrPromise; if (isLoaded) { if (isFetch) { return new Ember.RSVP.Promise(function(resolve, reject) { resolve(record); }); } else { return record; } } deferredOrPromise = this._fetchById(record, id); return isFetch ? deferredOrPromise : record; }, _currentBatchIds: null, _currentBatchRecordArrays: null, _currentBatchDeferreds: null, reload: function(id, container) { var record = this.cachedRecordForId(id, container); record.set('isLoaded', false); return this._fetchById(record, id); }, _fetchById: function(record, id) { var adapter = get(this, 'adapter'), deferred; if (adapter.findMany && !adapter.findMany.isUnimplemented) { if (this._currentBatchIds) { if (!contains(this._currentBatchIds, id)) { this._currentBatchIds.push(id); } } else { this._currentBatchIds = [id]; this._currentBatchRecordArrays = []; } deferred = Ember.Deferred.create(); //Attached the record to the deferred so we can resolve it later. Ember.set(deferred, 'resolveWith', record); if (!this._currentBatchDeferreds) { this._currentBatchDeferreds = []; } this._currentBatchDeferreds.push(deferred); Ember.run.scheduleOnce('data', this, this._executeBatch, record.container); return deferred; } else { return adapter.find(record, id); } }, _executeBatch: function(container) { var batchIds = this._currentBatchIds, batchRecordArrays = this._currentBatchRecordArrays, batchDeferreds = this._currentBatchDeferreds, self = this, requestIds = [], promise, i; this._currentBatchIds = null; this._currentBatchRecordArrays = null; this._currentBatchDeferreds = null; for (i = 0; i < batchIds.length; i++) { if (!this.cachedRecordForId(batchIds[i]).get('isLoaded')) { requestIds.push(batchIds[i]); } } if (requestIds.length === 1) { promise = get(this, 'adapter').find(this.cachedRecordForId(requestIds[0], container), requestIds[0]); } else { var recordArray = Ember.RecordArray.create({_ids: batchIds, container: container}); if (requestIds.length === 0) { promise = new Ember.RSVP.Promise(function(resolve, reject) { resolve(recordArray); }); recordArray.notifyLoaded(); } else { promise = get(this, 'adapter').findMany(this, recordArray, requestIds); } } promise.then(function() { for (var i = 0, l = batchRecordArrays.length; i < l; i++) { batchRecordArrays[i].loadForFindMany(self); } if (batchDeferreds) { for (i = 0, l = batchDeferreds.length; i < l; i++) { var resolveWith = Ember.get(batchDeferreds[i], 'resolveWith'); batchDeferreds[i].resolve(resolveWith); } } }).then(null, function(errorXHR) { if (batchDeferreds) { for (var i = 0, l = batchDeferreds.length; i < l; i++) { batchDeferreds[i].reject(errorXHR); } } }); }, getCachedReferenceRecord: function(id, container){ var ref = this._getReferenceById(id); if(ref && ref.record) { ref.record.container = container; return ref.record; } return undefined; }, cachedRecordForId: function(id, container) { var record; if (!this.transient) { record = this.getCachedReferenceRecord(id, container); } if (!record) { var primaryKey = get(this, 'primaryKey'), attrs = {isLoaded: false}; attrs[primaryKey] = id; attrs.container = container; record = this.create(attrs); if (!this.transient) { var sideloadedData = this.sideloadedData && this.sideloadedData[id]; if (sideloadedData) { record.load(id, sideloadedData); } } } return record; }, addToRecordArrays: function(record) { if (this._findAllRecordArray) { this._findAllRecordArray.addObject(record); } if (this.recordArrays) { this.recordArrays.forEach(function(recordArray) { if (recordArray instanceof Ember.FilteredRecordArray) { recordArray.registerObserversOnRecord(record); recordArray.updateFilter(); } else { recordArray.addObject(record); } }); } }, unload: function (record) { this.removeFromHasManyArrays(record); this.removeFromRecordArrays(record); var primaryKey = record.get(get(this, 'primaryKey')); this.removeFromCache(primaryKey); }, clearCache: function () { this.sideloadedData = undefined; this._referenceCache = undefined; this._findAllRecordArray = undefined; }, removeFromCache: function (key) { if (this.sideloadedData && this.sideloadedData[key]) { delete this.sideloadedData[key]; } if(this._referenceCache && this._referenceCache[key]) { delete this._referenceCache[key]; } }, removeFromHasManyArrays: function(record) { if (record._parentHasManyArrays) { record._parentHasManyArrays.forEach(function(hasManyArray) { hasManyArray.unloadObject(record); }); record._parentHasManyArrays = null; } }, removeFromRecordArrays: function(record) { if (this._findAllRecordArray) { this._findAllRecordArray.removeObject(record); } if (this.recordArrays) { this.recordArrays.forEach(function(recordArray) { recordArray.removeObject(record); }); } }, // FIXME findFromCacheOrLoad: function(data, container) { var record; if (!data[get(this, 'primaryKey')]) { record = this.create({isLoaded: false, container: container}); } else { record = this.cachedRecordForId(data[get(this, 'primaryKey')], container); } // set(record, 'data', data); record.load(data[get(this, 'primaryKey')], data); return record; }, registerRecordArray: function(recordArray) { if (!this.recordArrays) { this.recordArrays = []; } this.recordArrays.push(recordArray); }, unregisterRecordArray: function(recordArray) { if (!this.recordArrays) { return; } Ember.A(this.recordArrays).removeObject(recordArray); }, forEachCachedRecord: function(callback) { if (!this._referenceCache) { return; } var ids = Object.keys(this._referenceCache); ids.map(function(id) { return this._getReferenceById(id).record; }, this).forEach(callback); }, load: function(hashes) { if (Ember.typeOf(hashes) !== 'array') { hashes = [hashes]; } if (!this.sideloadedData) { this.sideloadedData = {}; } for (var i = 0, l = hashes.length; i < l; i++) { var hash = hashes[i], primaryKey = hash[get(this, 'primaryKey')], record = this.getCachedReferenceRecord(primaryKey); if (record) { record.load(primaryKey, hash); } else { this.sideloadedData[primaryKey] = hash; } } }, _getReferenceById: function(id) { if (!this._referenceCache) { this._referenceCache = {}; } return this._referenceCache[id]; }, _getOrCreateReferenceForId: function(id) { var reference = this._getReferenceById(id); if (!reference) { reference = this._createReference(id); } return reference; }, _createReference: function(id) { if (!this._referenceCache) { this._referenceCache = {}; } Ember.assert('The id ' + id + ' has already been used with another record of type ' + this.toString() + '.', !id || !this._referenceCache[id]); var reference = { id: id, clientId: this._clientIdCounter++ }; this._cacheReference(reference); return reference; }, _cacheReference: function(reference) { if (!this._referenceCache) { this._referenceCache = {}; } // if we're creating an item, this process will be done // later, once the object has been persisted. if (!Ember.isEmpty(reference.id)) { this._referenceCache[reference.id] = reference; } } });
'use strict' class BaseFactory { constructor () { if (this.constructor === BaseFactory) { throw new Error('BaseFactory cannot be instantiated directly') } } } module.exports = BaseFactory
const env = process.env.NODE_ENV || "development"; console.log("*****", env); if (env === "development" || env === "test") { let config = require("./config.json"); let envConfig = config[env]; Object.keys(envConfig).forEach((key) => { process.env[key] = envConfig[key]; }); }
/* @flow */ import type { CreateTemplate } from '../../types'; module.exports = (createTemplate: CreateTemplate) => createTemplate` export default []; `;
import Ember from "ember-metal/core"; // lookup, etc import run from "ember-metal/run_loop"; import Application from "ember-application/system/application"; import EmberObject from "ember-runtime/system/object"; import { DefaultResolver } from "ember-application/system/resolver"; import { guidFor } from "ember-metal/utils"; var originalLookup, App, originalModelInjections; module("Ember.Application Dependency Injection – toString",{ setup: function() { originalModelInjections = Ember.MODEL_FACTORY_INJECTIONS; Ember.MODEL_FACTORY_INJECTIONS = true; originalLookup = Ember.lookup; run(function(){ App = Application.create(); Ember.lookup = { App: App }; }); App.Post = EmberObject.extend(); }, teardown: function() { Ember.lookup = originalLookup; run(App, 'destroy'); Ember.MODEL_FACTORY_INJECTIONS = originalModelInjections; } }); test("factories", function() { var PostFactory = App.__container__.lookupFactory('model:post'); equal(PostFactory.toString(), 'App.Post', 'expecting the model to be post'); }); test("instances", function() { var post = App.__container__.lookup('model:post'); var guid = guidFor(post); equal(post.toString(), '<App.Post:' + guid + '>', 'expecting the model to be post'); }); test("with a custom resolver", function() { run(App,'destroy'); run(function(){ App = Application.create({ Resolver: DefaultResolver.extend({ makeToString: function(factory, fullName) { return fullName; } }) }); }); App.__container__.register('model:peter', EmberObject.extend()); var peter = App.__container__.lookup('model:peter'); var guid = guidFor(peter); equal(peter.toString(), '<model:peter:' + guid + '>', 'expecting the supermodel to be peter'); });
function addSassCss(props) { this.draft.loaders.css.loader.push('sass'); this.draft.devDependencies = this.draft.devDependencies.concat(['sass-loader']); return true; } module.exports = addSassCss;
/* * GET home page. */ exports.index = function(req, res){ res.render('index', { title: 'Magitek' }); };
#!/usr/bin/env node /** * this is a wrapper around the node app to allow it to be executed like a * shell script and keep the shebang from blowing things up. */ require('./lib/pnpm-replicate.js');
import styled from 'styled-components'; const A = styled.p` margin-bottom: 3%; font-size: 14px; width: 85%; display: block; margin: 0 auto; `; export default A;
/** * plugin to handle deviceOrientation API */ define(['threex/THREEx.DeviceOrientationState'], function(){ var instance = null; tQuery.register('deviceOrientation', function(){ if( !instance ) instance = new THREEx.DeviceOrientationState(); return instance; }); });
version https://git-lfs.github.com/spec/v1 oid sha256:d429a63e4b671011e053eda74fcba1306a4b4b3a6bd035a4b16cafd29e0264dc size 17545
import 'aurelia-polyfills'; import { PLATFORM } from 'aurelia-pal'; import { initialize } from 'aurelia-pal-browser'; let bootstrapQueue = []; let sharedLoader = null; let Aurelia = null; function onBootstrap(callback) { return new Promise((resolve, reject) => { if (sharedLoader) { resolve(callback(sharedLoader)); } else { bootstrapQueue.push(() => { try { resolve(callback(sharedLoader)); } catch (e) { reject(e); } }); } }); } function ready(global) { return new Promise((resolve, reject) => { if (global.document.readyState === 'complete') { resolve(global.document); } else { global.document.addEventListener('DOMContentLoaded', completed); global.addEventListener('load', completed); } function completed() { global.document.removeEventListener('DOMContentLoaded', completed); global.removeEventListener('load', completed); resolve(global.document); } }); } function createLoader() { if (PLATFORM.Loader) { return Promise.resolve(new PLATFORM.Loader()); } if (window.System && typeof window.System.import === 'function') { return System.normalize('aurelia-bootstrapper').then(bootstrapperName => { return System.normalize('aurelia-loader-default', bootstrapperName); }).then(loaderName => { return System.import(loaderName).then(m => new m.DefaultLoader()); }); } if (typeof window.require === 'function') { return new Promise((resolve, reject) => require(['aurelia-loader-default'], m => resolve(new m.DefaultLoader()), reject)); } return Promise.reject('No PLATFORM.Loader is defined and there is neither a System API (ES6) or a Require API (AMD) globally available to load your app.'); } function preparePlatform(loader) { return loader.normalize('aurelia-bootstrapper').then(bootstrapperName => { return loader.normalize('aurelia-framework', bootstrapperName).then(frameworkName => { loader.map('aurelia-framework', frameworkName); return Promise.all([loader.normalize('aurelia-dependency-injection', frameworkName).then(diName => loader.map('aurelia-dependency-injection', diName)), loader.normalize('aurelia-router', bootstrapperName).then(routerName => loader.map('aurelia-router', routerName)), loader.normalize('aurelia-logging-console', bootstrapperName).then(loggingConsoleName => loader.map('aurelia-logging-console', loggingConsoleName))]).then(() => { return loader.loadModule(frameworkName).then(m => Aurelia = m.Aurelia); }); }); }); } function handleApp(loader, appHost) { const moduleId = appHost.getAttribute('aurelia-app') || appHost.getAttribute('data-aurelia-app'); return config(loader, appHost, moduleId); } function config(loader, appHost, configModuleId) { const aurelia = new Aurelia(loader); aurelia.host = appHost; aurelia.configModuleId = configModuleId || null; if (configModuleId) { return loader.loadModule(configModuleId).then(customConfig => { if (!customConfig.configure) { throw new Error("Cannot initialize module '" + configModuleId + "' without a configure function."); } customConfig.configure(aurelia); }); } aurelia.use.standardConfiguration().developmentLogging(); return aurelia.start().then(() => aurelia.setRoot()); } function run() { return ready(window).then(doc => { initialize(); const appHost = doc.querySelectorAll('[aurelia-app],[data-aurelia-app]'); return createLoader().then(loader => { return preparePlatform(loader).then(() => { for (let i = 0, ii = appHost.length; i < ii; ++i) { handleApp(loader, appHost[i]).catch(console.error.bind(console)); } sharedLoader = loader; for (let i = 0, ii = bootstrapQueue.length; i < ii; ++i) { bootstrapQueue[i](); } bootstrapQueue = null; }); }); }); } export function bootstrap(configure) { return onBootstrap(loader => { const aurelia = new Aurelia(loader); return configure(aurelia); }); } run();
const path = require('path'); module.exports = { entry: './js/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'public') } };
'use strict'; module.exports = function(karma) { karma.set({ basePath: '', frameworks: [ 'browserify', 'mocha' ], files: [ 'test/**/*Spec.js' ], reporters: [ 'spec' ], preprocessors: { 'test/**/*.js': [ 'browserify' ], 'src/**/*.js': [ 'browserify' ] }, browsers: [ 'PhantomJS' ], // browserify configuration browserify: { debug: true, extensions: ['.js'], transform: [ 'babelify' ] } }); };
"use strict"; exports.__esModule = true; exports.resetListeners = resetListeners; exports.addResponseListener = addResponseListener; exports.getResponseListener = getResponseListener; exports.deleteResponseListener = deleteResponseListener; exports.cancelResponseListeners = cancelResponseListeners; exports.markResponseListenerErrored = markResponseListenerErrored; exports.isResponseListenerErrored = isResponseListenerErrored; exports.getRequestListener = getRequestListener; exports.addRequestListener = addRequestListener; var _src = require("cross-domain-utils/src"); var _src2 = require("belter/src"); var _global = require("../global"); var _conf = require("../conf"); function resetListeners() { const responseListeners = (0, _global.globalStore)('responseListeners'); const erroredResponseListeners = (0, _global.globalStore)('erroredResponseListeners'); responseListeners.reset(); erroredResponseListeners.reset(); } const __DOMAIN_REGEX__ = '__domain_regex__'; function addResponseListener(hash, listener) { const responseListeners = (0, _global.globalStore)('responseListeners'); responseListeners.set(hash, listener); } function getResponseListener(hash) { const responseListeners = (0, _global.globalStore)('responseListeners'); return responseListeners.get(hash); } function deleteResponseListener(hash) { const responseListeners = (0, _global.globalStore)('responseListeners'); responseListeners.del(hash); } function cancelResponseListeners() { const responseListeners = (0, _global.globalStore)('responseListeners'); for (const hash of responseListeners.keys()) { const listener = responseListeners.get(hash); if (listener) { listener.cancelled = true; } responseListeners.del(hash); } } function markResponseListenerErrored(hash) { const erroredResponseListeners = (0, _global.globalStore)('erroredResponseListeners'); erroredResponseListeners.set(hash, true); } function isResponseListenerErrored(hash) { const erroredResponseListeners = (0, _global.globalStore)('erroredResponseListeners'); return erroredResponseListeners.has(hash); } function getRequestListener({ name, win, domain }) { const requestListeners = (0, _global.windowStore)('requestListeners'); if (win === _conf.WILDCARD) { win = null; } if (domain === _conf.WILDCARD) { domain = null; } if (!name) { throw new Error(`Name required to get request listener`); } for (const winQualifier of [win, (0, _global.getWildcard)()]) { if (!winQualifier) { continue; } const nameListeners = requestListeners.get(winQualifier); if (!nameListeners) { continue; } const domainListeners = nameListeners[name]; if (!domainListeners) { continue; } if (domain && typeof domain === 'string') { if (domainListeners[domain]) { return domainListeners[domain]; } if (domainListeners[__DOMAIN_REGEX__]) { for (const _ref of domainListeners[__DOMAIN_REGEX__]) { const { regex, listener } = _ref; if ((0, _src.matchDomain)(regex, domain)) { return listener; } } } } if (domainListeners[_conf.WILDCARD]) { return domainListeners[_conf.WILDCARD]; } } } function addRequestListener({ name, win, domain }, listener) { const requestListeners = (0, _global.windowStore)('requestListeners'); if (!name || typeof name !== 'string') { throw new Error(`Name required to add request listener`); } if (Array.isArray(win)) { const listenersCollection = []; for (const item of win) { listenersCollection.push(addRequestListener({ name, domain, win: item }, listener)); } return { cancel() { for (const cancelListener of listenersCollection) { cancelListener.cancel(); } } }; } if (Array.isArray(domain)) { const listenersCollection = []; for (const item of domain) { listenersCollection.push(addRequestListener({ name, win, domain: item }, listener)); } return { cancel() { for (const cancelListener of listenersCollection) { cancelListener.cancel(); } } }; } const existingListener = getRequestListener({ name, win, domain }); if (!win || win === _conf.WILDCARD) { win = (0, _global.getWildcard)(); } domain = domain || _conf.WILDCARD; if (existingListener) { if (win && domain) { throw new Error(`Request listener already exists for ${name} on domain ${domain.toString()} for ${win === (0, _global.getWildcard)() ? 'wildcard' : 'specified'} window`); } else if (win) { throw new Error(`Request listener already exists for ${name} for ${win === (0, _global.getWildcard)() ? 'wildcard' : 'specified'} window`); } else if (domain) { throw new Error(`Request listener already exists for ${name} on domain ${domain.toString()}`); } else { throw new Error(`Request listener already exists for ${name}`); } } const nameListeners = requestListeners.getOrSet(win, () => ({})); const domainListeners = (0, _src2.getOrSet)(nameListeners, name, () => ({})); const strDomain = domain.toString(); let regexListeners; let regexListener; if ((0, _src2.isRegex)(domain)) { regexListeners = (0, _src2.getOrSet)(domainListeners, __DOMAIN_REGEX__, () => []); regexListener = { regex: domain, listener }; regexListeners.push(regexListener); } else { domainListeners[strDomain] = listener; } return { cancel() { delete domainListeners[strDomain]; if (regexListener) { regexListeners.splice(regexListeners.indexOf(regexListener, 1)); if (!regexListeners.length) { delete domainListeners[__DOMAIN_REGEX__]; } } if (!Object.keys(domainListeners).length) { delete nameListeners[name]; } if (win && !Object.keys(nameListeners).length) { requestListeners.del(win); } } }; }
// @flow import renderer from 'react-test-renderer' import React from 'react' import {mockFeed, mockModification, mockPattern} from '../../../utils/mock-data' import AdjustDwellTime from '../adjust-dwell-time' describe('Component > Modification > AdjustDwellTime', () => { const props = { addControl: jest.fn(), addLayer: jest.fn(), feeds: [], modification: mockModification, removeControl: jest.fn(), removeLayer: jest.fn(), routePatterns: [], routeStops: [], selectedFeed: undefined, selectedStops: [], setMapState: jest.fn(), update: jest.fn(), updateAndRetrieveFeedData: jest.fn() } const noCalls = [ 'addControl', 'addLayer', 'removeControl', 'removeLayer', 'setMapState', 'update' ] it('renders empty correctly', () => { const tree = renderer.create(<AdjustDwellTime {...props} />).toJSON() expect(tree).toMatchSnapshot() noCalls.forEach(fn => { expect(props[fn]).not.toBeCalled() }) }) it('renders with data correctly', () => { const tree = renderer .create( <AdjustDwellTime {...props} feed={[mockFeed]} routePatterns={[mockPattern]} /> ) .toJSON() expect(tree).toMatchSnapshot() noCalls.forEach(fn => { expect(props[fn]).not.toBeCalled() }) }) })
#!/usr/bin/env node var YAML = require('yamljs'); var program = require('commander'); var _ = require('lodash'); var path = require('path'); var fs = require('fs'); var endOfLine = require('os').EOL; var defaultConfig = YAML.load(path.join(__dirname, './config.yml')); var userConfig = path.join(process.cwd(), 'compscaf.yml'); if (fs.existsSync(userConfig)) { userConfig = YAML.load(userConfig); } var config = _.assign({}, defaultConfig, userConfig); var compRoot = config.cwd; var contentMap = config.contentTpl; var tpl = config.tpl; var regx = config.varRegx; var extension = config.extension; var defaultNames = config.defaultName; program .version('0.0.1') .option('-o, --comp [name]', 'init a compoment : required') .option('-t, --tpl [name]', 'init a tpl file, default is main ') .option('-s, --scss [name]', 'init a scss file, default is base ') .option('-j, --js [name]', 'init a entry file, default is index') .option('-a, --all', 'init all file[tpl/scss/js]') .option('-f, --force', 'init a compoment, remove the old one if extis') .option('-c, --clear', 'clear a component, remove all file in the component dir') .parse(process.argv); var initDeps = function (deps) { var deps = config.baseDeps || []; _.forEach(deps, function (dep, k) { deps[k] = "'" + dep + "'"; }); return deps; } var parseDepName = function (dep, regx) { if (regx && regx.length >= 2) { return dep.replace(new RegExp(regx[0], regx[2]), regx[1]); } return '$unknown'; } var initDepsVars = function (deps) { var depsVars = []; var baseRegx = regx.baseDep; _.forEach(deps, function (dep) { depsVars.push(parseDepName(dep, baseRegx)); }); return depsVars; } starter(); function starter() { var compName = program.comp; var force = program.force; var isClear = program.clear; var TYPE = Object.prototype.toString, STRING = TYPE.call(''), BOOL = TYPE.call(true); if (isClear) { clear(); return; } var deps = initDeps(); var depsVars = initDepsVars(deps); if (!initComponent(compName)) { initFiles('tpl') initFiles('scss') initFiles('js') } function initComponent(o) { var status = 0; if (TYPE.call(o) === STRING) { initDir(); } else { status = 2; makeError( 'option:comp is required'); return status; } function initDir() { var fullPath; fullPath = path.resolve(path.join(compRoot, compName)); try { fs.mkdirSync(fullPath); } catch(e) { if (force && e.code == 'EEXIST') { rmDir(fullPath); initDir(); } else { status = 1; makeError(e); } } } return status; } function clear() { var fullPath; fullPath = path.resolve(path.join(compRoot, compName)); rmDir(fullPath); } function initFiles(type) { var o = program[type] || program.all; var regxType = regx[type]; var extType = extension[type] || type; var defaultName = defaultNames[type]; if (!o) return; var targetName; var isError = false; var contentTpl = contentMap[type] || ''; var fullPath; switch (TYPE.call(o)) { case BOOL: targetName = defaultName; break; case STRING: targetName = o; break; default: if (required) { isError = 1; //label this a error } break; } if (isError === 1) { makeError(type + ' is required'); return isError; } targetName += '.' + extType; fullPath = path.resolve(path.join(compRoot, compName, targetName)); contentTpl = compiler(contentTpl, { comp: compName, EOL: endOfLine, deps: deps.join(', '), dep: targetName, depsVars: depsVars.join(', ') }); fs.writeFileSync(fullPath, contentTpl) deps.push(compiler(tpl.dep, { comp: compName, EOL: endOfLine, dep: targetName, })); if (regxType && regxType.length >= 2) { depsVars.push(parseDepName(targetName, regxType)); } } } function compiler(content, data) { var keys = Object.keys(data); keys.forEach(function (v) { content = content.replace(new RegExp('\{\{' + v + '\}\}', 'g'), data[v]) }); return content; } function makeError(msg) { console.error(msg); } function rmDir(dirPath, removeSelf) { removeSelf = removeSelf || removeSelf === undefined; try { var files = fs.readdirSync(dirPath); } catch(e) { return; } if (files.length > 0) for (var i = 0; i < files.length; i++) { var filePath = dirPath + '/' + files[i]; if (fs.statSync(filePath).isFile()) fs.unlinkSync(filePath); else rmDir(filePath); } if (removeSelf) { fs.rmdirSync(dirPath); } }
'use strict'; const request = require('./utils/request'); const cheerio = require('cheerio'); const PLAYSTORE_URL = 'https://play.google.com/store/apps'; const CATEGORY_URL_PREFIX = '/store/apps/category/'; function categories (opts) { opts = Object.assign({}, opts); return new Promise(function (resolve, reject) { const options = Object.assign( { url: PLAYSTORE_URL }, opts.requestOptions ); request(options, opts.throttle) .then(cheerio.load) .then(extractCategories) .then(resolve) .catch(reject); }); } function extractCategories ($) { const categoryIds = $('a') .toArray() .map((el) => $(el).attr('href')) .filter((url) => url.startsWith(CATEGORY_URL_PREFIX) && !url.includes('?age=')) .map((url) => url.substr(CATEGORY_URL_PREFIX.length)); categoryIds.push('APPLICATION'); return categoryIds; } module.exports = categories;
var arrayDiff = require('arraydiff-papandreou'); function extend(target) { for (var i = 1; i < arguments.length; i += 1) { var source = arguments[i]; Object.keys(source).forEach(function (key) { target[key] = source[key]; }); } return target; } module.exports = function arrayChanges(actual, expected, equal, similar, includeNonNumericalProperties) { var mutatedArray = new Array(actual.length); for (var k = 0; k < actual.length; k += 1) { mutatedArray[k] = { type: 'similar', value: actual[k], actualIndex: k }; } similar = similar || function (a, b) { return false; }; var itemsDiff = arrayDiff(Array.prototype.slice.call(actual), Array.prototype.slice.call(expected), function (a, b, aIndex, bIndex) { return equal(a, b, aIndex, bIndex) || similar(a, b, aIndex, bIndex); }); var removeTable = []; function offsetIndex(index) { return index + (removeTable[index - 1] || 0); } var removes = itemsDiff.filter(function (diffItem) { return diffItem.type === 'remove'; }); var removesByIndex = {}; var removedItems = 0; removes.forEach(function (diffItem) { var removeIndex = removedItems + diffItem.index; mutatedArray.slice(removeIndex, diffItem.howMany + removeIndex).forEach(function (v) { v.type = 'remove'; }); removedItems += diffItem.howMany; removesByIndex[diffItem.index] = removedItems; }); function updateRemoveTable() { removedItems = 0; Array.prototype.forEach.call(actual, function (_, index) { removedItems += removesByIndex[index] || 0; removeTable[index] = removedItems; }); } updateRemoveTable(); var moves = itemsDiff.filter(function (diffItem) { return diffItem.type === 'move'; }); var movedItems = 0; moves.forEach(function (diffItem) { var moveFromIndex = offsetIndex(diffItem.from); var removed = mutatedArray.slice(moveFromIndex, diffItem.howMany + moveFromIndex); var added = removed.map(function (v) { return extend({}, v, { last: false, type: 'insert' }); }); removed.forEach(function (v) { v.type = 'remove'; }); Array.prototype.splice.apply(mutatedArray, [offsetIndex(diffItem.to), 0].concat(added)); movedItems += diffItem.howMany; removesByIndex[diffItem.from] = movedItems; updateRemoveTable(); }); var inserts = itemsDiff.filter(function (diffItem) { return diffItem.type === 'insert'; }); inserts.forEach(function (diffItem) { var added = new Array(diffItem.values.length); for (var i = 0 ; i < diffItem.values.length ; i += 1) { added[i] = { type: 'insert', value: diffItem.values[i], expectedIndex: diffItem.index }; } Array.prototype.splice.apply(mutatedArray, [offsetIndex(diffItem.index), 0].concat(added)); }); var offset = 0; mutatedArray.forEach(function (diffItem, index) { var type = diffItem.type; if (type === 'remove') { offset -= 1; } else if (type === 'similar') { diffItem.expected = expected[offset + index]; diffItem.expectedIndex = offset + index; } }); var conflicts = mutatedArray.reduce(function (conflicts, item) { return item.type === 'similar' ? conflicts : conflicts + 1; }, 0); for (var i = 0, c = 0; i < Math.max(actual.length, expected.length) && c <= conflicts; i += 1) { if ( i >= actual.length || i >= expected.length || (!equal(actual[i], expected[i], i, i) && !similar(actual[i], expected[i], i, i)) ) { c += 1; } } if (c <= conflicts) { mutatedArray = []; var j; for (j = 0; j < Math.min(actual.length, expected.length); j += 1) { mutatedArray.push({ type: 'similar', value: actual[j], expected: expected[j], actualIndex: j, expectedIndex: j }); } if (actual.length < expected.length) { for (; j < Math.max(actual.length, expected.length); j += 1) { mutatedArray.push({ type: 'insert', value: expected[j], expectedIndex: j }); } } else { for (; j < Math.max(actual.length, expected.length); j += 1) { mutatedArray.push({ type: 'remove', value: actual[j], actualIndex: j }); } } } mutatedArray.forEach(function (diffItem) { if (diffItem.type === 'similar' && equal(diffItem.value, diffItem.expected, diffItem.actualIndex, diffItem.expectedIndex)) { diffItem.type = 'equal'; } }); if (includeNonNumericalProperties) { var nonNumericalKeys; if (Array.isArray(includeNonNumericalProperties)) { nonNumericalKeys = includeNonNumericalProperties; } else { var isSeenByNonNumericalKey = {}; nonNumericalKeys = []; [actual, expected].forEach(function (obj) { Object.keys(obj).forEach(function (key) { if (!/^(?:0|[1-9][0-9]*)$/.test(key) && !isSeenByNonNumericalKey[key]) { isSeenByNonNumericalKey[key] = true; nonNumericalKeys.push(key); } }); if (Object.getOwnPropertySymbols) { Object.getOwnPropertySymbols(obj).forEach(function (symbol) { if (!isSeenByNonNumericalKey[symbol]) { isSeenByNonNumericalKey[symbol] = true; nonNumericalKeys.push(symbol); } }); } }); } nonNumericalKeys.forEach(function (key) { if (key in actual) { if (key in expected) { mutatedArray.push({ type: equal(actual[key], expected[key], key, key) ? 'equal' : 'similar', expectedIndex: key, actualIndex: key, value: actual[key], expected: expected[key] }); } else { mutatedArray.push({ type: 'remove', actualIndex: key, value: actual[key] }); } } else { mutatedArray.push({ type: 'insert', expectedIndex: key, value: expected[key] }); } }); } if (mutatedArray.length > 0) { mutatedArray[mutatedArray.length - 1].last = true; } return mutatedArray; };
/** * Open Payments Cloud Application API * Open Payments Cloud API * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['ApiClient', 'model/CreatePayinSimulationParams'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient'), require('./CreatePayinSimulationParams')); } else { // Browser globals (root is window) if (!root.OpenPaymentsCloudApplicationApi) { root.OpenPaymentsCloudApplicationApi = {}; } root.OpenPaymentsCloudApplicationApi.PayinSimulationParams = factory(root.OpenPaymentsCloudApplicationApi.ApiClient, root.OpenPaymentsCloudApplicationApi.CreatePayinSimulationParams); } }(this, function(ApiClient, CreatePayinSimulationParams) { 'use strict'; /** * The PayinSimulationParams model module. * @module model/PayinSimulationParams * @version 1.1.0 */ /** * Constructs a new <code>PayinSimulationParams</code>. * @alias module:model/PayinSimulationParams * @class * @param providerKey {String} * @param details {module:model/CreatePayinSimulationParams} */ var exports = function(providerKey, details) { var _this = this; _this['providerKey'] = providerKey; _this['details'] = details; }; /** * Constructs a <code>PayinSimulationParams</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/PayinSimulationParams} obj Optional instance to populate. * @return {module:model/PayinSimulationParams} The populated <code>PayinSimulationParams</code> instance. */ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports(); if (data.hasOwnProperty('providerKey')) { obj['providerKey'] = ApiClient.convertToType(data['providerKey'], 'String'); } if (data.hasOwnProperty('details')) { obj['details'] = CreatePayinSimulationParams.constructFromObject(data['details']); } } return obj; } /** * @member {String} providerKey */ exports.prototype['providerKey'] = undefined; /** * @member {module:model/CreatePayinSimulationParams} details */ exports.prototype['details'] = undefined; return exports; }));
/* global it, describe, console, after */ var http = require('http'); var _ = require('underscore'); var expect = require('chai').expect; var EventEmitter = require('events').EventEmitter; var mock_server_data = require('./mock-server-data'); var jut_statsd_backend = require('../lib/jut'); var fake_logger = { log: function() { console.log(arguments); } }; var mock_receiver = { events: new EventEmitter(), current_test: '', port: null, srv: null, start: function(callback) { var self = this; var srv = http.createServer(function(req, res) { var expected_request = mock_server_data[self.current_test].request; var current_response = mock_server_data[self.current_test].response; var req_body = ''; req.on('data', function(chunk) { req_body += chunk; }); req.on('end', function() { try { expect(req.method).to.equal('POST'); expect(req.url).to.equal('/'); var json_body = JSON.parse(req_body); // both check that the time is ISO-8601 and // rewrite as ms-since-epoch so the deep compare // below succeeds json_body.forEach(function(item) { var d = new Date(item.time); expect(item.time).to.be.a('string'); expect(item.time).to.equal(d.toISOString()); item.time = d.getTime(); }); expect(json_body).to.deep.equal(expected_request.body); res.writeHead(current_response.status, {'Content-Type': 'application/json'}); if (typeof current_response.body !== 'string') { res.end(JSON.stringify(current_response.body, null, 2)); } else { res.end(current_response.body); } } catch(err) { res.end(); return self.events.emit('done', err); } self.events.emit('done'); }); }); srv.listen(0, function() { self.port = srv.address().port; callback(); }); this.srv = srv; }, stop: function(callback) { this.srv.close(callback); } }; describe('jut statsd backend basic init tests', function() { it('can initialize the module successfully', function() { var retval = jut_statsd_backend.init( Date.now() / 1000, { jut: { url: 'http://example.com' }, }, new EventEmitter(), fake_logger ); expect(retval).to.be.true; }); it('fails if receiver url is omitted', function(done) { try { jut_statsd_backend.init( Date.now(), { }, new EventEmitter(), fake_logger ); } catch(e) { return done(); } throw new Error('init() should have failed'); }); it('fails if a reserved tag is used', function(done) { try { jut_statsd_backend.init( Date.now(), { jut: { url: 'http://example.com', tags: { time: 42 } } }, new EventEmitter(), fake_logger ); } catch(e) { return done(); } throw new Error('init() should have failed'); }); }); describe('jut statsd backend custom sender test', function() { var events; it('initializes the module with a custom sender', function() { events = new EventEmitter(); var retval = jut_statsd_backend.init( Date.now() / 1000, { jut: { sender_module: __dirname + '/test-sender', events: events, }, debug: true, flushInterval: 10000, }, events, fake_logger ); expect(retval).to.be.true; }); it('calls the test sender correctly', function(done) { events.on('test', function(payload) { // quick and dirty test, stricter tests later on expect(payload).to.have.length(mock_server_data.basic_counter.request.body.length); expect(_.omit(payload[0], 'time')).to.deep.equal(_.omit(mock_server_data.basic_counter.request.body[0], 'time')); done(); }); events.emit( 'flush', mock_server_data.basic_counter.input.timestamp, mock_server_data.basic_counter.input.metrics ); }); }); describe('jut statsd backend mock receiver tests', function() { this.timeout(30000); var receiver_url; var events; function emit_event(test_name) { // send defaults so we don't have to set unnecessary stuff _.defaults(mock_server_data[test_name].input.metrics, { counters: {}, gauges: {}, timers: {}, sets: {}, counter_rates: {}, timer_data: {}, statsd_metrics: {}, pctThreshold: {} }); events.emit( 'flush', mock_server_data[test_name].input.timestamp, mock_server_data[test_name].input.metrics ); } it('starts the mock receiver', function(done) { mock_receiver.start(function() { receiver_url = 'http://localhost:' + mock_receiver.port; done(); }); }); it('initializes the backend with default settings', function() { events = new EventEmitter(); var retval = jut_statsd_backend.init( Date.now() / 1000, { jut: { url: receiver_url, }, debug: true, flushInterval: 10000, }, events, fake_logger ); expect(retval).to.be.true; }); it('imports a counter with no rate', function(done) { mock_receiver.current_test = 'basic_counter'; emit_event('basic_counter'); mock_receiver.events.once('done', done); }); it('imports a gauge', function(done) { mock_receiver.current_test = 'basic_gauge'; emit_event('basic_gauge'); mock_receiver.events.once('done', done); }); it('imports timer data', function(done) { mock_receiver.current_test = 'timer_with_stats'; emit_event('timer_with_stats'); mock_receiver.events.once('done', done); }); it('does not split keys by default', function(done) { mock_receiver.current_test = 'key_split_disabled'; emit_event('key_split_disabled'); mock_receiver.events.once('done', done); }); it('initializes the backend module with key splitting, counter rates, and extra tags', function() { events = new EventEmitter(); var retval = jut_statsd_backend.init( Date.now() / 1000, { jut: { url: receiver_url, split_keys: true, counter_rates: true, tags: { cats: 'cute', lives: 9 } }, debug: true, flushInterval: 10000, }, events, fake_logger ); expect(retval).to.be.true; }); it('imports a counter with a rate', function(done) { mock_receiver.current_test = 'counter_with_rate'; emit_event('counter_with_rate'); mock_receiver.events.once('done', done); }); it('tries out some tags', function(done) { mock_receiver.current_test = 'metric_with_tags'; emit_event('metric_with_tags'); mock_receiver.events.once('done', done); }); it('is able to override some internal tags', function(done) { mock_receiver.current_test = 'override_internal_tags'; emit_event('override_internal_tags'); mock_receiver.events.once('done', done); }); it('initializes the backend module with invalid extra tags', function() { events = new EventEmitter(); try { jut_statsd_backend.init( Date.now() / 1000, { jut: { url: receiver_url, split_keys: true, counter_rates: true, tags: { time: 1234, value: 5678 } }, debug: true, flushInterval: 10000, }, events, fake_logger ); } catch(e) { return; } throw new Error('this test should fail'); }); it('checks some stats', function(done) { var seen_flush = false; var seen_exception = false; function check_stats(key, value) { if (key === 'lastFlush') { seen_flush = true; expect(value * 1000).to.be.at.most(Date.now()); } else if (key === 'lastException') { seen_exception = true; expect(value * 1000).to.be.at.most(Date.now()); } if (seen_flush && seen_exception) { done(); } } jut_statsd_backend.status(function(a, backend, key, value) { check_stats(key, value); }); }); after(function(done) { mock_receiver.stop(done); }); });
/** * Copyright (c) 2017, Three Pawns, Inc. All rights reserved. */ 'use strict'; const fs = require('fs'); const path = require('path'); const defer = require('config/defer').deferConfig; const raw = require('config/raw').raw; const basicAuth = require('basic-auth'); const stringify = require('json-stringify-safe'); const rfs = require('rotating-file-stream'); const bunyan = require('bunyan'); module.exports = { servers: { open: { port: 8080, }, secure: { port: 8443, key: `config/local-${process.env.NODE_ENV ? process.env.NODE_ENV : 'development'}-key.pem`, cert: `config/local-${process.env.NODE_ENV ? process.env.NODE_ENV : 'development'}-cert.pem`, options: { key: defer(cfg => `${fs.readFileSync(cfg.servers.secure.key)}`), cert: defer(cfg => `${fs.readFileSync(cfg.servers.secure.cert)}`), }, }, auth: { token: { secret: 'OVERRIDE', ttl: 10800, }, }, logs: { directory: 'log', file: 'access.log', rotate: '1d', type: 'combined', options: defer((cfg) => { const dir = path.join(process.cwd(), cfg.servers.logs.directory); const rotate = { interval: cfg.servers.logs.rotate, path: fs.existsSync(dir) ? dir : fs.mkdirSync(dir) || dir, }; return raw({ type: cfg.servers.logs.type, options: { stream: rfs(cfg.servers.logs.file, rotate), }, }); }), }, }, ldapauth: { credentialsLookup: basicAuth, server: { url: 'OVERRIDE', bindDn: 'OVERRIDE', bindCredentials: 'OVERRIDE', searchBase: 'OVERRIDE', searchFilter: '(uid={{username}})', }, }, solos: { resource: {}, security: { groups: { 'reinier admin': '.*', 'reinier editor': ['GET /', '(GET|PUT|POST|DELETE) /edit/.*'], 'reinier blogger': ['GET /', '(GET|PUT|POST|DELETE) /blog/.*'], }, }, }, bunyan: { logger: { name: 'seneca', streams: [{ level: 'info', stream: 'process.stdout', }, { type: 'rotating-file', file: 'application.log', level: 'info', period: '1d', // daily rotation count: 7, // keep a week of back copies }], }, }, seneca: { log: { map: [{ level: 'all', handler: defer((cfg) => { const config = JSON.parse(JSON.stringify(cfg.bunyan.logger)); config.streams.forEach((stream) => { if (stream.stream === 'process.stdout') { stream.stream = process.stdout; } else if (stream.type === 'rotating-file' && stream.file) { const dir = cfg.servers.logs.directory; // cannot guarantee execution order stream.path = `${process.cwd()}/${fs.existsSync(dir) ? dir : fs.mkdirSync(dir) || dir}/${stream.file}`; } }); if (!config.serializers) { config.serializers = bunyan.stdSerializers; } const logger = bunyan.createLogger(config); return function log(...args) { args.shift(); // remove timestamp - bunyan has one const level = args.splice(1, 1)[0]; // remove log level const msg = stringify(args, (key, value) => (['req', 'res'].indexOf(key) >= 0 ? '[FILTERED]' : value)); logger[level](msg.replace(/["]/g, '\'')); // make pretty and log }; }), }], }, }, };
version https://git-lfs.github.com/spec/v1 oid sha256:8e3ccbcbe4f1b467f77062a935cb95a4eb54abfcc33d8207a26853105acdb6d5 size 91721
// flow-typed signature: f516d807fc98953d25da7f70504240e5 // flow-typed version: <<STUB>>/rambda_v^1.0.12/flow_v0.66.0 /** * This is an autogenerated libdef stub for: * * 'rambda' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'rambda' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'rambda/__tests__/addIndex' { declare module.exports: any; } declare module 'rambda/__tests__/array/adjust' { declare module.exports: any; } declare module 'rambda/__tests__/array/any' { declare module.exports: any; } declare module 'rambda/__tests__/array/append' { declare module.exports: any; } declare module 'rambda/__tests__/array/filter' { declare module.exports: any; } declare module 'rambda/__tests__/array/find' { declare module.exports: any; } declare module 'rambda/__tests__/array/findIndex' { declare module.exports: any; } declare module 'rambda/__tests__/array/flatten' { declare module.exports: any; } declare module 'rambda/__tests__/array/forEach' { declare module.exports: any; } declare module 'rambda/__tests__/array/indexOf' { declare module.exports: any; } declare module 'rambda/__tests__/array/join' { declare module.exports: any; } declare module 'rambda/__tests__/array/map' { declare module.exports: any; } declare module 'rambda/__tests__/array/prepend' { declare module.exports: any; } declare module 'rambda/__tests__/array/reduce' { declare module.exports: any; } declare module 'rambda/__tests__/array/reverse' { declare module.exports: any; } declare module 'rambda/__tests__/array/update' { declare module.exports: any; } declare module 'rambda/__tests__/contains' { declare module.exports: any; } declare module 'rambda/__tests__/drop' { declare module.exports: any; } declare module 'rambda/__tests__/dropLast' { declare module.exports: any; } declare module 'rambda/__tests__/general' { declare module.exports: any; } declare module 'rambda/__tests__/head' { declare module.exports: any; } declare module 'rambda/__tests__/includes' { declare module.exports: any; } declare module 'rambda/__tests__/init' { declare module.exports: any; } declare module 'rambda/__tests__/is' { declare module.exports: any; } declare module 'rambda/__tests__/last' { declare module.exports: any; } declare module 'rambda/__tests__/lazy/concat' { declare module.exports: any; } declare module 'rambda/__tests__/lazy/endsWith' { declare module.exports: any; } declare module 'rambda/__tests__/lazy/lastIndexOf' { declare module.exports: any; } declare module 'rambda/__tests__/lazy/length' { declare module.exports: any; } declare module 'rambda/__tests__/lazy/not' { declare module.exports: any; } declare module 'rambda/__tests__/lazy/startsWith' { declare module.exports: any; } declare module 'rambda/__tests__/lazy/toLower' { declare module.exports: any; } declare module 'rambda/__tests__/lazy/toString' { declare module.exports: any; } declare module 'rambda/__tests__/lazy/toUpper' { declare module.exports: any; } declare module 'rambda/__tests__/lazy/trim' { declare module.exports: any; } declare module 'rambda/__tests__/logic/all' { declare module.exports: any; } declare module 'rambda/__tests__/logic/allPass' { declare module.exports: any; } declare module 'rambda/__tests__/logic/always' { declare module.exports: any; } declare module 'rambda/__tests__/logic/anyPass' { declare module.exports: any; } declare module 'rambda/__tests__/logic/both' { declare module.exports: any; } declare module 'rambda/__tests__/logic/complement' { declare module.exports: any; } declare module 'rambda/__tests__/logic/compose' { declare module.exports: any; } declare module 'rambda/__tests__/logic/curry' { declare module.exports: any; } declare module 'rambda/__tests__/logic/defaultTo' { declare module.exports: any; } declare module 'rambda/__tests__/logic/either' { declare module.exports: any; } declare module 'rambda/__tests__/logic/equals' { declare module.exports: any; } declare module 'rambda/__tests__/logic/flip' { declare module.exports: any; } declare module 'rambda/__tests__/logic/identity' { declare module.exports: any; } declare module 'rambda/__tests__/logic/ifElse' { declare module.exports: any; } declare module 'rambda/__tests__/logic/isNil' { declare module.exports: any; } declare module 'rambda/__tests__/logic/partialCurry' { declare module.exports: any; } declare module 'rambda/__tests__/logic/pipe' { declare module.exports: any; } declare module 'rambda/__tests__/match' { declare module.exports: any; } declare module 'rambda/__tests__/math/add' { declare module.exports: any; } declare module 'rambda/__tests__/math/divide' { declare module.exports: any; } declare module 'rambda/__tests__/math/modulo' { declare module.exports: any; } declare module 'rambda/__tests__/math/multiply' { declare module.exports: any; } declare module 'rambda/__tests__/math/subtract' { declare module.exports: any; } declare module 'rambda/__tests__/none' { declare module.exports: any; } declare module 'rambda/__tests__/object/dissoc' { declare module.exports: any; } declare module 'rambda/__tests__/object/has' { declare module.exports: any; } declare module 'rambda/__tests__/object/merge' { declare module.exports: any; } declare module 'rambda/__tests__/object/omit' { declare module.exports: any; } declare module 'rambda/__tests__/object/path' { declare module.exports: any; } declare module 'rambda/__tests__/object/pathOr' { declare module.exports: any; } declare module 'rambda/__tests__/object/pick' { declare module.exports: any; } declare module 'rambda/__tests__/object/pickAll' { declare module.exports: any; } declare module 'rambda/__tests__/object/pluck' { declare module.exports: any; } declare module 'rambda/__tests__/object/prop' { declare module.exports: any; } declare module 'rambda/__tests__/object/values' { declare module.exports: any; } declare module 'rambda/__tests__/propEq' { declare module.exports: any; } declare module 'rambda/__tests__/range' { declare module.exports: any; } declare module 'rambda/__tests__/reject' { declare module.exports: any; } declare module 'rambda/__tests__/repeat' { declare module.exports: any; } declare module 'rambda/__tests__/replace' { declare module.exports: any; } declare module 'rambda/__tests__/sort' { declare module.exports: any; } declare module 'rambda/__tests__/sortBy' { declare module.exports: any; } declare module 'rambda/__tests__/split' { declare module.exports: any; } declare module 'rambda/__tests__/splitEvery' { declare module.exports: any; } declare module 'rambda/__tests__/tail' { declare module.exports: any; } declare module 'rambda/__tests__/take' { declare module.exports: any; } declare module 'rambda/__tests__/takeLast' { declare module.exports: any; } declare module 'rambda/__tests__/tap' { declare module.exports: any; } declare module 'rambda/__tests__/test' { declare module.exports: any; } declare module 'rambda/__tests__/times' { declare module.exports: any; } declare module 'rambda/__tests__/type' { declare module.exports: any; } declare module 'rambda/__tests__/uniq' { declare module.exports: any; } declare module 'rambda/__tests__/uniqWith' { declare module.exports: any; } declare module 'rambda/__tests__/without' { declare module.exports: any; } declare module 'rambda/benchmarks/add' { declare module.exports: any; } declare module 'rambda/benchmarks/adjust' { declare module.exports: any; } declare module 'rambda/benchmarks/any' { declare module.exports: any; } declare module 'rambda/benchmarks/append' { declare module.exports: any; } declare module 'rambda/benchmarks/compose' { declare module.exports: any; } declare module 'rambda/benchmarks/contains' { declare module.exports: any; } declare module 'rambda/benchmarks/drop' { declare module.exports: any; } declare module 'rambda/benchmarks/dropLast' { declare module.exports: any; } declare module 'rambda/benchmarks/equals' { declare module.exports: any; } declare module 'rambda/benchmarks/filter' { declare module.exports: any; } declare module 'rambda/benchmarks/find' { declare module.exports: any; } declare module 'rambda/benchmarks/findIndex' { declare module.exports: any; } declare module 'rambda/benchmarks/flatten' { declare module.exports: any; } declare module 'rambda/benchmarks/head' { declare module.exports: any; } declare module 'rambda/benchmarks/headString' { declare module.exports: any; } declare module 'rambda/benchmarks/index' { declare module.exports: any; } declare module 'rambda/benchmarks/indexOf' { declare module.exports: any; } declare module 'rambda/benchmarks/init' { declare module.exports: any; } declare module 'rambda/benchmarks/initString' { declare module.exports: any; } declare module 'rambda/benchmarks/last' { declare module.exports: any; } declare module 'rambda/benchmarks/map' { declare module.exports: any; } declare module 'rambda/benchmarks/match' { declare module.exports: any; } declare module 'rambda/benchmarks/merge' { declare module.exports: any; } declare module 'rambda/benchmarks/omit' { declare module.exports: any; } declare module 'rambda/benchmarks/path' { declare module.exports: any; } declare module 'rambda/benchmarks/pick' { declare module.exports: any; } declare module 'rambda/benchmarks/pipe' { declare module.exports: any; } declare module 'rambda/benchmarks/prop' { declare module.exports: any; } declare module 'rambda/benchmarks/propEq' { declare module.exports: any; } declare module 'rambda/benchmarks/range' { declare module.exports: any; } declare module 'rambda/benchmarks/reduce' { declare module.exports: any; } declare module 'rambda/dist/rambda.cjs' { declare module.exports: any; } declare module 'rambda/dist/rambda.esm' { declare module.exports: any; } declare module 'rambda/dist/rambda.umd' { declare module.exports: any; } declare module 'rambda/files/benchmark' { declare module.exports: any; } declare module 'rambda/files/browseByTag' { declare module.exports: any; } declare module 'rambda/files/createReadme' { declare module.exports: any; } declare module 'rambda/files/debug' { declare module.exports: any; } declare module 'rambda/files/lint' { declare module.exports: any; } declare module 'rambda/files/minify' { declare module.exports: any; } declare module 'rambda/files/rollup.config' { declare module.exports: any; } declare module 'rambda/lib/add' { declare module.exports: any; } declare module 'rambda/lib/addIndex' { declare module.exports: any; } declare module 'rambda/lib/adjust' { declare module.exports: any; } declare module 'rambda/lib/all' { declare module.exports: any; } declare module 'rambda/lib/allPass' { declare module.exports: any; } declare module 'rambda/lib/always' { declare module.exports: any; } declare module 'rambda/lib/any' { declare module.exports: any; } declare module 'rambda/lib/anyPass' { declare module.exports: any; } declare module 'rambda/lib/append' { declare module.exports: any; } declare module 'rambda/lib/both' { declare module.exports: any; } declare module 'rambda/lib/complement' { declare module.exports: any; } declare module 'rambda/lib/compose' { declare module.exports: any; } declare module 'rambda/lib/concat' { declare module.exports: any; } declare module 'rambda/lib/contains' { declare module.exports: any; } declare module 'rambda/lib/curry' { declare module.exports: any; } declare module 'rambda/lib/dec' { declare module.exports: any; } declare module 'rambda/lib/defaultTo' { declare module.exports: any; } declare module 'rambda/lib/dissoc' { declare module.exports: any; } declare module 'rambda/lib/divide' { declare module.exports: any; } declare module 'rambda/lib/drop' { declare module.exports: any; } declare module 'rambda/lib/dropLast' { declare module.exports: any; } declare module 'rambda/lib/either' { declare module.exports: any; } declare module 'rambda/lib/endsWith' { declare module.exports: any; } declare module 'rambda/lib/equals' { declare module.exports: any; } declare module 'rambda/lib/F' { declare module.exports: any; } declare module 'rambda/lib/filter' { declare module.exports: any; } declare module 'rambda/lib/find' { declare module.exports: any; } declare module 'rambda/lib/findIndex' { declare module.exports: any; } declare module 'rambda/lib/flatten' { declare module.exports: any; } declare module 'rambda/lib/flip' { declare module.exports: any; } declare module 'rambda/lib/forEach' { declare module.exports: any; } declare module 'rambda/lib/has' { declare module.exports: any; } declare module 'rambda/lib/head' { declare module.exports: any; } declare module 'rambda/lib/identity' { declare module.exports: any; } declare module 'rambda/lib/ifElse' { declare module.exports: any; } declare module 'rambda/lib/inc' { declare module.exports: any; } declare module 'rambda/lib/includes' { declare module.exports: any; } declare module 'rambda/lib/indexOf' { declare module.exports: any; } declare module 'rambda/lib/init' { declare module.exports: any; } declare module 'rambda/lib/internal/baseSlice' { declare module.exports: any; } declare module 'rambda/lib/is' { declare module.exports: any; } declare module 'rambda/lib/isNil' { declare module.exports: any; } declare module 'rambda/lib/join' { declare module.exports: any; } declare module 'rambda/lib/last' { declare module.exports: any; } declare module 'rambda/lib/lastIndexOf' { declare module.exports: any; } declare module 'rambda/lib/length' { declare module.exports: any; } declare module 'rambda/lib/map' { declare module.exports: any; } declare module 'rambda/lib/match' { declare module.exports: any; } declare module 'rambda/lib/merge' { declare module.exports: any; } declare module 'rambda/lib/modulo' { declare module.exports: any; } declare module 'rambda/lib/multiply' { declare module.exports: any; } declare module 'rambda/lib/none' { declare module.exports: any; } declare module 'rambda/lib/not' { declare module.exports: any; } declare module 'rambda/lib/omit' { declare module.exports: any; } declare module 'rambda/lib/partialCurry' { declare module.exports: any; } declare module 'rambda/lib/path' { declare module.exports: any; } declare module 'rambda/lib/pathOr' { declare module.exports: any; } declare module 'rambda/lib/pick' { declare module.exports: any; } declare module 'rambda/lib/pickAll' { declare module.exports: any; } declare module 'rambda/lib/pipe' { declare module.exports: any; } declare module 'rambda/lib/pluck' { declare module.exports: any; } declare module 'rambda/lib/prepend' { declare module.exports: any; } declare module 'rambda/lib/prop' { declare module.exports: any; } declare module 'rambda/lib/propEq' { declare module.exports: any; } declare module 'rambda/lib/range' { declare module.exports: any; } declare module 'rambda/lib/reduce' { declare module.exports: any; } declare module 'rambda/lib/reject' { declare module.exports: any; } declare module 'rambda/lib/repeat' { declare module.exports: any; } declare module 'rambda/lib/replace' { declare module.exports: any; } declare module 'rambda/lib/reverse' { declare module.exports: any; } declare module 'rambda/lib/sort' { declare module.exports: any; } declare module 'rambda/lib/sortBy' { declare module.exports: any; } declare module 'rambda/lib/split' { declare module.exports: any; } declare module 'rambda/lib/splitEvery' { declare module.exports: any; } declare module 'rambda/lib/startsWith' { declare module.exports: any; } declare module 'rambda/lib/subtract' { declare module.exports: any; } declare module 'rambda/lib/T' { declare module.exports: any; } declare module 'rambda/lib/tail' { declare module.exports: any; } declare module 'rambda/lib/take' { declare module.exports: any; } declare module 'rambda/lib/takeLast' { declare module.exports: any; } declare module 'rambda/lib/tap' { declare module.exports: any; } declare module 'rambda/lib/test' { declare module.exports: any; } declare module 'rambda/lib/times' { declare module.exports: any; } declare module 'rambda/lib/toLower' { declare module.exports: any; } declare module 'rambda/lib/toString' { declare module.exports: any; } declare module 'rambda/lib/toUpper' { declare module.exports: any; } declare module 'rambda/lib/trim' { declare module.exports: any; } declare module 'rambda/lib/type' { declare module.exports: any; } declare module 'rambda/lib/uniq' { declare module.exports: any; } declare module 'rambda/lib/uniqWith' { declare module.exports: any; } declare module 'rambda/lib/update' { declare module.exports: any; } declare module 'rambda/lib/values' { declare module.exports: any; } declare module 'rambda/lib/without' { declare module.exports: any; } declare module 'rambda/modules/add' { declare module.exports: any; } declare module 'rambda/modules/addIndex' { declare module.exports: any; } declare module 'rambda/modules/adjust' { declare module.exports: any; } declare module 'rambda/modules/all' { declare module.exports: any; } declare module 'rambda/modules/allPass' { declare module.exports: any; } declare module 'rambda/modules/always' { declare module.exports: any; } declare module 'rambda/modules/any' { declare module.exports: any; } declare module 'rambda/modules/anyPass' { declare module.exports: any; } declare module 'rambda/modules/append' { declare module.exports: any; } declare module 'rambda/modules/both' { declare module.exports: any; } declare module 'rambda/modules/complement' { declare module.exports: any; } declare module 'rambda/modules/compose' { declare module.exports: any; } declare module 'rambda/modules/concat' { declare module.exports: any; } declare module 'rambda/modules/contains' { declare module.exports: any; } declare module 'rambda/modules/curry' { declare module.exports: any; } declare module 'rambda/modules/dec' { declare module.exports: any; } declare module 'rambda/modules/defaultTo' { declare module.exports: any; } declare module 'rambda/modules/dissoc' { declare module.exports: any; } declare module 'rambda/modules/divide' { declare module.exports: any; } declare module 'rambda/modules/drop' { declare module.exports: any; } declare module 'rambda/modules/dropLast' { declare module.exports: any; } declare module 'rambda/modules/either' { declare module.exports: any; } declare module 'rambda/modules/endsWith' { declare module.exports: any; } declare module 'rambda/modules/equals' { declare module.exports: any; } declare module 'rambda/modules/F' { declare module.exports: any; } declare module 'rambda/modules/filter' { declare module.exports: any; } declare module 'rambda/modules/find' { declare module.exports: any; } declare module 'rambda/modules/findIndex' { declare module.exports: any; } declare module 'rambda/modules/flatten' { declare module.exports: any; } declare module 'rambda/modules/flip' { declare module.exports: any; } declare module 'rambda/modules/forEach' { declare module.exports: any; } declare module 'rambda/modules/has' { declare module.exports: any; } declare module 'rambda/modules/head' { declare module.exports: any; } declare module 'rambda/modules/identity' { declare module.exports: any; } declare module 'rambda/modules/ifElse' { declare module.exports: any; } declare module 'rambda/modules/inc' { declare module.exports: any; } declare module 'rambda/modules/includes' { declare module.exports: any; } declare module 'rambda/modules/indexOf' { declare module.exports: any; } declare module 'rambda/modules/init' { declare module.exports: any; } declare module 'rambda/modules/internal/baseSlice' { declare module.exports: any; } declare module 'rambda/modules/is' { declare module.exports: any; } declare module 'rambda/modules/isNil' { declare module.exports: any; } declare module 'rambda/modules/join' { declare module.exports: any; } declare module 'rambda/modules/last' { declare module.exports: any; } declare module 'rambda/modules/lastIndexOf' { declare module.exports: any; } declare module 'rambda/modules/length' { declare module.exports: any; } declare module 'rambda/modules/map' { declare module.exports: any; } declare module 'rambda/modules/match' { declare module.exports: any; } declare module 'rambda/modules/merge' { declare module.exports: any; } declare module 'rambda/modules/modulo' { declare module.exports: any; } declare module 'rambda/modules/multiply' { declare module.exports: any; } declare module 'rambda/modules/none' { declare module.exports: any; } declare module 'rambda/modules/not' { declare module.exports: any; } declare module 'rambda/modules/omit' { declare module.exports: any; } declare module 'rambda/modules/partialCurry' { declare module.exports: any; } declare module 'rambda/modules/path' { declare module.exports: any; } declare module 'rambda/modules/pathOr' { declare module.exports: any; } declare module 'rambda/modules/pick' { declare module.exports: any; } declare module 'rambda/modules/pickAll' { declare module.exports: any; } declare module 'rambda/modules/pipe' { declare module.exports: any; } declare module 'rambda/modules/pluck' { declare module.exports: any; } declare module 'rambda/modules/prepend' { declare module.exports: any; } declare module 'rambda/modules/prop' { declare module.exports: any; } declare module 'rambda/modules/propEq' { declare module.exports: any; } declare module 'rambda/modules/range' { declare module.exports: any; } declare module 'rambda/modules/reduce' { declare module.exports: any; } declare module 'rambda/modules/reject' { declare module.exports: any; } declare module 'rambda/modules/repeat' { declare module.exports: any; } declare module 'rambda/modules/replace' { declare module.exports: any; } declare module 'rambda/modules/reverse' { declare module.exports: any; } declare module 'rambda/modules/sort' { declare module.exports: any; } declare module 'rambda/modules/sortBy' { declare module.exports: any; } declare module 'rambda/modules/split' { declare module.exports: any; } declare module 'rambda/modules/splitEvery' { declare module.exports: any; } declare module 'rambda/modules/startsWith' { declare module.exports: any; } declare module 'rambda/modules/subtract' { declare module.exports: any; } declare module 'rambda/modules/T' { declare module.exports: any; } declare module 'rambda/modules/tail' { declare module.exports: any; } declare module 'rambda/modules/take' { declare module.exports: any; } declare module 'rambda/modules/takeLast' { declare module.exports: any; } declare module 'rambda/modules/tap' { declare module.exports: any; } declare module 'rambda/modules/test' { declare module.exports: any; } declare module 'rambda/modules/times' { declare module.exports: any; } declare module 'rambda/modules/toLower' { declare module.exports: any; } declare module 'rambda/modules/toString' { declare module.exports: any; } declare module 'rambda/modules/toUpper' { declare module.exports: any; } declare module 'rambda/modules/trim' { declare module.exports: any; } declare module 'rambda/modules/type' { declare module.exports: any; } declare module 'rambda/modules/uniq' { declare module.exports: any; } declare module 'rambda/modules/uniqWith' { declare module.exports: any; } declare module 'rambda/modules/update' { declare module.exports: any; } declare module 'rambda/modules/values' { declare module.exports: any; } declare module 'rambda/modules/without' { declare module.exports: any; } declare module 'rambda/rambda' { declare module.exports: any; } declare module 'rambda/webVersion' { declare module.exports: any; } // Filename aliases declare module 'rambda/__tests__/addIndex.js' { declare module.exports: $Exports<'rambda/__tests__/addIndex'>; } declare module 'rambda/__tests__/array/adjust.js' { declare module.exports: $Exports<'rambda/__tests__/array/adjust'>; } declare module 'rambda/__tests__/array/any.js' { declare module.exports: $Exports<'rambda/__tests__/array/any'>; } declare module 'rambda/__tests__/array/append.js' { declare module.exports: $Exports<'rambda/__tests__/array/append'>; } declare module 'rambda/__tests__/array/filter.js' { declare module.exports: $Exports<'rambda/__tests__/array/filter'>; } declare module 'rambda/__tests__/array/find.js' { declare module.exports: $Exports<'rambda/__tests__/array/find'>; } declare module 'rambda/__tests__/array/findIndex.js' { declare module.exports: $Exports<'rambda/__tests__/array/findIndex'>; } declare module 'rambda/__tests__/array/flatten.js' { declare module.exports: $Exports<'rambda/__tests__/array/flatten'>; } declare module 'rambda/__tests__/array/forEach.js' { declare module.exports: $Exports<'rambda/__tests__/array/forEach'>; } declare module 'rambda/__tests__/array/indexOf.js' { declare module.exports: $Exports<'rambda/__tests__/array/indexOf'>; } declare module 'rambda/__tests__/array/join.js' { declare module.exports: $Exports<'rambda/__tests__/array/join'>; } declare module 'rambda/__tests__/array/map.js' { declare module.exports: $Exports<'rambda/__tests__/array/map'>; } declare module 'rambda/__tests__/array/prepend.js' { declare module.exports: $Exports<'rambda/__tests__/array/prepend'>; } declare module 'rambda/__tests__/array/reduce.js' { declare module.exports: $Exports<'rambda/__tests__/array/reduce'>; } declare module 'rambda/__tests__/array/reverse.js' { declare module.exports: $Exports<'rambda/__tests__/array/reverse'>; } declare module 'rambda/__tests__/array/update.js' { declare module.exports: $Exports<'rambda/__tests__/array/update'>; } declare module 'rambda/__tests__/contains.js' { declare module.exports: $Exports<'rambda/__tests__/contains'>; } declare module 'rambda/__tests__/drop.js' { declare module.exports: $Exports<'rambda/__tests__/drop'>; } declare module 'rambda/__tests__/dropLast.js' { declare module.exports: $Exports<'rambda/__tests__/dropLast'>; } declare module 'rambda/__tests__/general.js' { declare module.exports: $Exports<'rambda/__tests__/general'>; } declare module 'rambda/__tests__/head.js' { declare module.exports: $Exports<'rambda/__tests__/head'>; } declare module 'rambda/__tests__/includes.js' { declare module.exports: $Exports<'rambda/__tests__/includes'>; } declare module 'rambda/__tests__/init.js' { declare module.exports: $Exports<'rambda/__tests__/init'>; } declare module 'rambda/__tests__/is.js' { declare module.exports: $Exports<'rambda/__tests__/is'>; } declare module 'rambda/__tests__/last.js' { declare module.exports: $Exports<'rambda/__tests__/last'>; } declare module 'rambda/__tests__/lazy/concat.js' { declare module.exports: $Exports<'rambda/__tests__/lazy/concat'>; } declare module 'rambda/__tests__/lazy/endsWith.js' { declare module.exports: $Exports<'rambda/__tests__/lazy/endsWith'>; } declare module 'rambda/__tests__/lazy/lastIndexOf.js' { declare module.exports: $Exports<'rambda/__tests__/lazy/lastIndexOf'>; } declare module 'rambda/__tests__/lazy/length.js' { declare module.exports: $Exports<'rambda/__tests__/lazy/length'>; } declare module 'rambda/__tests__/lazy/not.js' { declare module.exports: $Exports<'rambda/__tests__/lazy/not'>; } declare module 'rambda/__tests__/lazy/startsWith.js' { declare module.exports: $Exports<'rambda/__tests__/lazy/startsWith'>; } declare module 'rambda/__tests__/lazy/toLower.js' { declare module.exports: $Exports<'rambda/__tests__/lazy/toLower'>; } declare module 'rambda/__tests__/lazy/toString.js' { declare module.exports: $Exports<'rambda/__tests__/lazy/toString'>; } declare module 'rambda/__tests__/lazy/toUpper.js' { declare module.exports: $Exports<'rambda/__tests__/lazy/toUpper'>; } declare module 'rambda/__tests__/lazy/trim.js' { declare module.exports: $Exports<'rambda/__tests__/lazy/trim'>; } declare module 'rambda/__tests__/logic/all.js' { declare module.exports: $Exports<'rambda/__tests__/logic/all'>; } declare module 'rambda/__tests__/logic/allPass.js' { declare module.exports: $Exports<'rambda/__tests__/logic/allPass'>; } declare module 'rambda/__tests__/logic/always.js' { declare module.exports: $Exports<'rambda/__tests__/logic/always'>; } declare module 'rambda/__tests__/logic/anyPass.js' { declare module.exports: $Exports<'rambda/__tests__/logic/anyPass'>; } declare module 'rambda/__tests__/logic/both.js' { declare module.exports: $Exports<'rambda/__tests__/logic/both'>; } declare module 'rambda/__tests__/logic/complement.js' { declare module.exports: $Exports<'rambda/__tests__/logic/complement'>; } declare module 'rambda/__tests__/logic/compose.js' { declare module.exports: $Exports<'rambda/__tests__/logic/compose'>; } declare module 'rambda/__tests__/logic/curry.js' { declare module.exports: $Exports<'rambda/__tests__/logic/curry'>; } declare module 'rambda/__tests__/logic/defaultTo.js' { declare module.exports: $Exports<'rambda/__tests__/logic/defaultTo'>; } declare module 'rambda/__tests__/logic/either.js' { declare module.exports: $Exports<'rambda/__tests__/logic/either'>; } declare module 'rambda/__tests__/logic/equals.js' { declare module.exports: $Exports<'rambda/__tests__/logic/equals'>; } declare module 'rambda/__tests__/logic/flip.js' { declare module.exports: $Exports<'rambda/__tests__/logic/flip'>; } declare module 'rambda/__tests__/logic/identity.js' { declare module.exports: $Exports<'rambda/__tests__/logic/identity'>; } declare module 'rambda/__tests__/logic/ifElse.js' { declare module.exports: $Exports<'rambda/__tests__/logic/ifElse'>; } declare module 'rambda/__tests__/logic/isNil.js' { declare module.exports: $Exports<'rambda/__tests__/logic/isNil'>; } declare module 'rambda/__tests__/logic/partialCurry.js' { declare module.exports: $Exports<'rambda/__tests__/logic/partialCurry'>; } declare module 'rambda/__tests__/logic/pipe.js' { declare module.exports: $Exports<'rambda/__tests__/logic/pipe'>; } declare module 'rambda/__tests__/match.js' { declare module.exports: $Exports<'rambda/__tests__/match'>; } declare module 'rambda/__tests__/math/add.js' { declare module.exports: $Exports<'rambda/__tests__/math/add'>; } declare module 'rambda/__tests__/math/divide.js' { declare module.exports: $Exports<'rambda/__tests__/math/divide'>; } declare module 'rambda/__tests__/math/modulo.js' { declare module.exports: $Exports<'rambda/__tests__/math/modulo'>; } declare module 'rambda/__tests__/math/multiply.js' { declare module.exports: $Exports<'rambda/__tests__/math/multiply'>; } declare module 'rambda/__tests__/math/subtract.js' { declare module.exports: $Exports<'rambda/__tests__/math/subtract'>; } declare module 'rambda/__tests__/none.js' { declare module.exports: $Exports<'rambda/__tests__/none'>; } declare module 'rambda/__tests__/object/dissoc.js' { declare module.exports: $Exports<'rambda/__tests__/object/dissoc'>; } declare module 'rambda/__tests__/object/has.js' { declare module.exports: $Exports<'rambda/__tests__/object/has'>; } declare module 'rambda/__tests__/object/merge.js' { declare module.exports: $Exports<'rambda/__tests__/object/merge'>; } declare module 'rambda/__tests__/object/omit.js' { declare module.exports: $Exports<'rambda/__tests__/object/omit'>; } declare module 'rambda/__tests__/object/path.js' { declare module.exports: $Exports<'rambda/__tests__/object/path'>; } declare module 'rambda/__tests__/object/pathOr.js' { declare module.exports: $Exports<'rambda/__tests__/object/pathOr'>; } declare module 'rambda/__tests__/object/pick.js' { declare module.exports: $Exports<'rambda/__tests__/object/pick'>; } declare module 'rambda/__tests__/object/pickAll.js' { declare module.exports: $Exports<'rambda/__tests__/object/pickAll'>; } declare module 'rambda/__tests__/object/pluck.js' { declare module.exports: $Exports<'rambda/__tests__/object/pluck'>; } declare module 'rambda/__tests__/object/prop.js' { declare module.exports: $Exports<'rambda/__tests__/object/prop'>; } declare module 'rambda/__tests__/object/values.js' { declare module.exports: $Exports<'rambda/__tests__/object/values'>; } declare module 'rambda/__tests__/propEq.js' { declare module.exports: $Exports<'rambda/__tests__/propEq'>; } declare module 'rambda/__tests__/range.js' { declare module.exports: $Exports<'rambda/__tests__/range'>; } declare module 'rambda/__tests__/reject.js' { declare module.exports: $Exports<'rambda/__tests__/reject'>; } declare module 'rambda/__tests__/repeat.js' { declare module.exports: $Exports<'rambda/__tests__/repeat'>; } declare module 'rambda/__tests__/replace.js' { declare module.exports: $Exports<'rambda/__tests__/replace'>; } declare module 'rambda/__tests__/sort.js' { declare module.exports: $Exports<'rambda/__tests__/sort'>; } declare module 'rambda/__tests__/sortBy.js' { declare module.exports: $Exports<'rambda/__tests__/sortBy'>; } declare module 'rambda/__tests__/split.js' { declare module.exports: $Exports<'rambda/__tests__/split'>; } declare module 'rambda/__tests__/splitEvery.js' { declare module.exports: $Exports<'rambda/__tests__/splitEvery'>; } declare module 'rambda/__tests__/tail.js' { declare module.exports: $Exports<'rambda/__tests__/tail'>; } declare module 'rambda/__tests__/take.js' { declare module.exports: $Exports<'rambda/__tests__/take'>; } declare module 'rambda/__tests__/takeLast.js' { declare module.exports: $Exports<'rambda/__tests__/takeLast'>; } declare module 'rambda/__tests__/tap.js' { declare module.exports: $Exports<'rambda/__tests__/tap'>; } declare module 'rambda/__tests__/test.js' { declare module.exports: $Exports<'rambda/__tests__/test'>; } declare module 'rambda/__tests__/times.js' { declare module.exports: $Exports<'rambda/__tests__/times'>; } declare module 'rambda/__tests__/type.js' { declare module.exports: $Exports<'rambda/__tests__/type'>; } declare module 'rambda/__tests__/uniq.js' { declare module.exports: $Exports<'rambda/__tests__/uniq'>; } declare module 'rambda/__tests__/uniqWith.js' { declare module.exports: $Exports<'rambda/__tests__/uniqWith'>; } declare module 'rambda/__tests__/without.js' { declare module.exports: $Exports<'rambda/__tests__/without'>; } declare module 'rambda/benchmarks/add.js' { declare module.exports: $Exports<'rambda/benchmarks/add'>; } declare module 'rambda/benchmarks/adjust.js' { declare module.exports: $Exports<'rambda/benchmarks/adjust'>; } declare module 'rambda/benchmarks/any.js' { declare module.exports: $Exports<'rambda/benchmarks/any'>; } declare module 'rambda/benchmarks/append.js' { declare module.exports: $Exports<'rambda/benchmarks/append'>; } declare module 'rambda/benchmarks/compose.js' { declare module.exports: $Exports<'rambda/benchmarks/compose'>; } declare module 'rambda/benchmarks/contains.js' { declare module.exports: $Exports<'rambda/benchmarks/contains'>; } declare module 'rambda/benchmarks/drop.js' { declare module.exports: $Exports<'rambda/benchmarks/drop'>; } declare module 'rambda/benchmarks/dropLast.js' { declare module.exports: $Exports<'rambda/benchmarks/dropLast'>; } declare module 'rambda/benchmarks/equals.js' { declare module.exports: $Exports<'rambda/benchmarks/equals'>; } declare module 'rambda/benchmarks/filter.js' { declare module.exports: $Exports<'rambda/benchmarks/filter'>; } declare module 'rambda/benchmarks/find.js' { declare module.exports: $Exports<'rambda/benchmarks/find'>; } declare module 'rambda/benchmarks/findIndex.js' { declare module.exports: $Exports<'rambda/benchmarks/findIndex'>; } declare module 'rambda/benchmarks/flatten.js' { declare module.exports: $Exports<'rambda/benchmarks/flatten'>; } declare module 'rambda/benchmarks/head.js' { declare module.exports: $Exports<'rambda/benchmarks/head'>; } declare module 'rambda/benchmarks/headString.js' { declare module.exports: $Exports<'rambda/benchmarks/headString'>; } declare module 'rambda/benchmarks/index.js' { declare module.exports: $Exports<'rambda/benchmarks/index'>; } declare module 'rambda/benchmarks/indexOf.js' { declare module.exports: $Exports<'rambda/benchmarks/indexOf'>; } declare module 'rambda/benchmarks/init.js' { declare module.exports: $Exports<'rambda/benchmarks/init'>; } declare module 'rambda/benchmarks/initString.js' { declare module.exports: $Exports<'rambda/benchmarks/initString'>; } declare module 'rambda/benchmarks/last.js' { declare module.exports: $Exports<'rambda/benchmarks/last'>; } declare module 'rambda/benchmarks/map.js' { declare module.exports: $Exports<'rambda/benchmarks/map'>; } declare module 'rambda/benchmarks/match.js' { declare module.exports: $Exports<'rambda/benchmarks/match'>; } declare module 'rambda/benchmarks/merge.js' { declare module.exports: $Exports<'rambda/benchmarks/merge'>; } declare module 'rambda/benchmarks/omit.js' { declare module.exports: $Exports<'rambda/benchmarks/omit'>; } declare module 'rambda/benchmarks/path.js' { declare module.exports: $Exports<'rambda/benchmarks/path'>; } declare module 'rambda/benchmarks/pick.js' { declare module.exports: $Exports<'rambda/benchmarks/pick'>; } declare module 'rambda/benchmarks/pipe.js' { declare module.exports: $Exports<'rambda/benchmarks/pipe'>; } declare module 'rambda/benchmarks/prop.js' { declare module.exports: $Exports<'rambda/benchmarks/prop'>; } declare module 'rambda/benchmarks/propEq.js' { declare module.exports: $Exports<'rambda/benchmarks/propEq'>; } declare module 'rambda/benchmarks/range.js' { declare module.exports: $Exports<'rambda/benchmarks/range'>; } declare module 'rambda/benchmarks/reduce.js' { declare module.exports: $Exports<'rambda/benchmarks/reduce'>; } declare module 'rambda/dist/rambda.cjs.js' { declare module.exports: $Exports<'rambda/dist/rambda.cjs'>; } declare module 'rambda/dist/rambda.esm.js' { declare module.exports: $Exports<'rambda/dist/rambda.esm'>; } declare module 'rambda/dist/rambda.umd.js' { declare module.exports: $Exports<'rambda/dist/rambda.umd'>; } declare module 'rambda/files/benchmark.js' { declare module.exports: $Exports<'rambda/files/benchmark'>; } declare module 'rambda/files/browseByTag.js' { declare module.exports: $Exports<'rambda/files/browseByTag'>; } declare module 'rambda/files/createReadme.js' { declare module.exports: $Exports<'rambda/files/createReadme'>; } declare module 'rambda/files/debug.js' { declare module.exports: $Exports<'rambda/files/debug'>; } declare module 'rambda/files/lint.js' { declare module.exports: $Exports<'rambda/files/lint'>; } declare module 'rambda/files/minify.js' { declare module.exports: $Exports<'rambda/files/minify'>; } declare module 'rambda/files/rollup.config.js' { declare module.exports: $Exports<'rambda/files/rollup.config'>; } declare module 'rambda/lib/add.js' { declare module.exports: $Exports<'rambda/lib/add'>; } declare module 'rambda/lib/addIndex.js' { declare module.exports: $Exports<'rambda/lib/addIndex'>; } declare module 'rambda/lib/adjust.js' { declare module.exports: $Exports<'rambda/lib/adjust'>; } declare module 'rambda/lib/all.js' { declare module.exports: $Exports<'rambda/lib/all'>; } declare module 'rambda/lib/allPass.js' { declare module.exports: $Exports<'rambda/lib/allPass'>; } declare module 'rambda/lib/always.js' { declare module.exports: $Exports<'rambda/lib/always'>; } declare module 'rambda/lib/any.js' { declare module.exports: $Exports<'rambda/lib/any'>; } declare module 'rambda/lib/anyPass.js' { declare module.exports: $Exports<'rambda/lib/anyPass'>; } declare module 'rambda/lib/append.js' { declare module.exports: $Exports<'rambda/lib/append'>; } declare module 'rambda/lib/both.js' { declare module.exports: $Exports<'rambda/lib/both'>; } declare module 'rambda/lib/complement.js' { declare module.exports: $Exports<'rambda/lib/complement'>; } declare module 'rambda/lib/compose.js' { declare module.exports: $Exports<'rambda/lib/compose'>; } declare module 'rambda/lib/concat.js' { declare module.exports: $Exports<'rambda/lib/concat'>; } declare module 'rambda/lib/contains.js' { declare module.exports: $Exports<'rambda/lib/contains'>; } declare module 'rambda/lib/curry.js' { declare module.exports: $Exports<'rambda/lib/curry'>; } declare module 'rambda/lib/dec.js' { declare module.exports: $Exports<'rambda/lib/dec'>; } declare module 'rambda/lib/defaultTo.js' { declare module.exports: $Exports<'rambda/lib/defaultTo'>; } declare module 'rambda/lib/dissoc.js' { declare module.exports: $Exports<'rambda/lib/dissoc'>; } declare module 'rambda/lib/divide.js' { declare module.exports: $Exports<'rambda/lib/divide'>; } declare module 'rambda/lib/drop.js' { declare module.exports: $Exports<'rambda/lib/drop'>; } declare module 'rambda/lib/dropLast.js' { declare module.exports: $Exports<'rambda/lib/dropLast'>; } declare module 'rambda/lib/either.js' { declare module.exports: $Exports<'rambda/lib/either'>; } declare module 'rambda/lib/endsWith.js' { declare module.exports: $Exports<'rambda/lib/endsWith'>; } declare module 'rambda/lib/equals.js' { declare module.exports: $Exports<'rambda/lib/equals'>; } declare module 'rambda/lib/F.js' { declare module.exports: $Exports<'rambda/lib/F'>; } declare module 'rambda/lib/filter.js' { declare module.exports: $Exports<'rambda/lib/filter'>; } declare module 'rambda/lib/find.js' { declare module.exports: $Exports<'rambda/lib/find'>; } declare module 'rambda/lib/findIndex.js' { declare module.exports: $Exports<'rambda/lib/findIndex'>; } declare module 'rambda/lib/flatten.js' { declare module.exports: $Exports<'rambda/lib/flatten'>; } declare module 'rambda/lib/flip.js' { declare module.exports: $Exports<'rambda/lib/flip'>; } declare module 'rambda/lib/forEach.js' { declare module.exports: $Exports<'rambda/lib/forEach'>; } declare module 'rambda/lib/has.js' { declare module.exports: $Exports<'rambda/lib/has'>; } declare module 'rambda/lib/head.js' { declare module.exports: $Exports<'rambda/lib/head'>; } declare module 'rambda/lib/identity.js' { declare module.exports: $Exports<'rambda/lib/identity'>; } declare module 'rambda/lib/ifElse.js' { declare module.exports: $Exports<'rambda/lib/ifElse'>; } declare module 'rambda/lib/inc.js' { declare module.exports: $Exports<'rambda/lib/inc'>; } declare module 'rambda/lib/includes.js' { declare module.exports: $Exports<'rambda/lib/includes'>; } declare module 'rambda/lib/indexOf.js' { declare module.exports: $Exports<'rambda/lib/indexOf'>; } declare module 'rambda/lib/init.js' { declare module.exports: $Exports<'rambda/lib/init'>; } declare module 'rambda/lib/internal/baseSlice.js' { declare module.exports: $Exports<'rambda/lib/internal/baseSlice'>; } declare module 'rambda/lib/is.js' { declare module.exports: $Exports<'rambda/lib/is'>; } declare module 'rambda/lib/isNil.js' { declare module.exports: $Exports<'rambda/lib/isNil'>; } declare module 'rambda/lib/join.js' { declare module.exports: $Exports<'rambda/lib/join'>; } declare module 'rambda/lib/last.js' { declare module.exports: $Exports<'rambda/lib/last'>; } declare module 'rambda/lib/lastIndexOf.js' { declare module.exports: $Exports<'rambda/lib/lastIndexOf'>; } declare module 'rambda/lib/length.js' { declare module.exports: $Exports<'rambda/lib/length'>; } declare module 'rambda/lib/map.js' { declare module.exports: $Exports<'rambda/lib/map'>; } declare module 'rambda/lib/match.js' { declare module.exports: $Exports<'rambda/lib/match'>; } declare module 'rambda/lib/merge.js' { declare module.exports: $Exports<'rambda/lib/merge'>; } declare module 'rambda/lib/modulo.js' { declare module.exports: $Exports<'rambda/lib/modulo'>; } declare module 'rambda/lib/multiply.js' { declare module.exports: $Exports<'rambda/lib/multiply'>; } declare module 'rambda/lib/none.js' { declare module.exports: $Exports<'rambda/lib/none'>; } declare module 'rambda/lib/not.js' { declare module.exports: $Exports<'rambda/lib/not'>; } declare module 'rambda/lib/omit.js' { declare module.exports: $Exports<'rambda/lib/omit'>; } declare module 'rambda/lib/partialCurry.js' { declare module.exports: $Exports<'rambda/lib/partialCurry'>; } declare module 'rambda/lib/path.js' { declare module.exports: $Exports<'rambda/lib/path'>; } declare module 'rambda/lib/pathOr.js' { declare module.exports: $Exports<'rambda/lib/pathOr'>; } declare module 'rambda/lib/pick.js' { declare module.exports: $Exports<'rambda/lib/pick'>; } declare module 'rambda/lib/pickAll.js' { declare module.exports: $Exports<'rambda/lib/pickAll'>; } declare module 'rambda/lib/pipe.js' { declare module.exports: $Exports<'rambda/lib/pipe'>; } declare module 'rambda/lib/pluck.js' { declare module.exports: $Exports<'rambda/lib/pluck'>; } declare module 'rambda/lib/prepend.js' { declare module.exports: $Exports<'rambda/lib/prepend'>; } declare module 'rambda/lib/prop.js' { declare module.exports: $Exports<'rambda/lib/prop'>; } declare module 'rambda/lib/propEq.js' { declare module.exports: $Exports<'rambda/lib/propEq'>; } declare module 'rambda/lib/range.js' { declare module.exports: $Exports<'rambda/lib/range'>; } declare module 'rambda/lib/reduce.js' { declare module.exports: $Exports<'rambda/lib/reduce'>; } declare module 'rambda/lib/reject.js' { declare module.exports: $Exports<'rambda/lib/reject'>; } declare module 'rambda/lib/repeat.js' { declare module.exports: $Exports<'rambda/lib/repeat'>; } declare module 'rambda/lib/replace.js' { declare module.exports: $Exports<'rambda/lib/replace'>; } declare module 'rambda/lib/reverse.js' { declare module.exports: $Exports<'rambda/lib/reverse'>; } declare module 'rambda/lib/sort.js' { declare module.exports: $Exports<'rambda/lib/sort'>; } declare module 'rambda/lib/sortBy.js' { declare module.exports: $Exports<'rambda/lib/sortBy'>; } declare module 'rambda/lib/split.js' { declare module.exports: $Exports<'rambda/lib/split'>; } declare module 'rambda/lib/splitEvery.js' { declare module.exports: $Exports<'rambda/lib/splitEvery'>; } declare module 'rambda/lib/startsWith.js' { declare module.exports: $Exports<'rambda/lib/startsWith'>; } declare module 'rambda/lib/subtract.js' { declare module.exports: $Exports<'rambda/lib/subtract'>; } declare module 'rambda/lib/T.js' { declare module.exports: $Exports<'rambda/lib/T'>; } declare module 'rambda/lib/tail.js' { declare module.exports: $Exports<'rambda/lib/tail'>; } declare module 'rambda/lib/take.js' { declare module.exports: $Exports<'rambda/lib/take'>; } declare module 'rambda/lib/takeLast.js' { declare module.exports: $Exports<'rambda/lib/takeLast'>; } declare module 'rambda/lib/tap.js' { declare module.exports: $Exports<'rambda/lib/tap'>; } declare module 'rambda/lib/test.js' { declare module.exports: $Exports<'rambda/lib/test'>; } declare module 'rambda/lib/times.js' { declare module.exports: $Exports<'rambda/lib/times'>; } declare module 'rambda/lib/toLower.js' { declare module.exports: $Exports<'rambda/lib/toLower'>; } declare module 'rambda/lib/toString.js' { declare module.exports: $Exports<'rambda/lib/toString'>; } declare module 'rambda/lib/toUpper.js' { declare module.exports: $Exports<'rambda/lib/toUpper'>; } declare module 'rambda/lib/trim.js' { declare module.exports: $Exports<'rambda/lib/trim'>; } declare module 'rambda/lib/type.js' { declare module.exports: $Exports<'rambda/lib/type'>; } declare module 'rambda/lib/uniq.js' { declare module.exports: $Exports<'rambda/lib/uniq'>; } declare module 'rambda/lib/uniqWith.js' { declare module.exports: $Exports<'rambda/lib/uniqWith'>; } declare module 'rambda/lib/update.js' { declare module.exports: $Exports<'rambda/lib/update'>; } declare module 'rambda/lib/values.js' { declare module.exports: $Exports<'rambda/lib/values'>; } declare module 'rambda/lib/without.js' { declare module.exports: $Exports<'rambda/lib/without'>; } declare module 'rambda/modules/add.js' { declare module.exports: $Exports<'rambda/modules/add'>; } declare module 'rambda/modules/addIndex.js' { declare module.exports: $Exports<'rambda/modules/addIndex'>; } declare module 'rambda/modules/adjust.js' { declare module.exports: $Exports<'rambda/modules/adjust'>; } declare module 'rambda/modules/all.js' { declare module.exports: $Exports<'rambda/modules/all'>; } declare module 'rambda/modules/allPass.js' { declare module.exports: $Exports<'rambda/modules/allPass'>; } declare module 'rambda/modules/always.js' { declare module.exports: $Exports<'rambda/modules/always'>; } declare module 'rambda/modules/any.js' { declare module.exports: $Exports<'rambda/modules/any'>; } declare module 'rambda/modules/anyPass.js' { declare module.exports: $Exports<'rambda/modules/anyPass'>; } declare module 'rambda/modules/append.js' { declare module.exports: $Exports<'rambda/modules/append'>; } declare module 'rambda/modules/both.js' { declare module.exports: $Exports<'rambda/modules/both'>; } declare module 'rambda/modules/complement.js' { declare module.exports: $Exports<'rambda/modules/complement'>; } declare module 'rambda/modules/compose.js' { declare module.exports: $Exports<'rambda/modules/compose'>; } declare module 'rambda/modules/concat.js' { declare module.exports: $Exports<'rambda/modules/concat'>; } declare module 'rambda/modules/contains.js' { declare module.exports: $Exports<'rambda/modules/contains'>; } declare module 'rambda/modules/curry.js' { declare module.exports: $Exports<'rambda/modules/curry'>; } declare module 'rambda/modules/dec.js' { declare module.exports: $Exports<'rambda/modules/dec'>; } declare module 'rambda/modules/defaultTo.js' { declare module.exports: $Exports<'rambda/modules/defaultTo'>; } declare module 'rambda/modules/dissoc.js' { declare module.exports: $Exports<'rambda/modules/dissoc'>; } declare module 'rambda/modules/divide.js' { declare module.exports: $Exports<'rambda/modules/divide'>; } declare module 'rambda/modules/drop.js' { declare module.exports: $Exports<'rambda/modules/drop'>; } declare module 'rambda/modules/dropLast.js' { declare module.exports: $Exports<'rambda/modules/dropLast'>; } declare module 'rambda/modules/either.js' { declare module.exports: $Exports<'rambda/modules/either'>; } declare module 'rambda/modules/endsWith.js' { declare module.exports: $Exports<'rambda/modules/endsWith'>; } declare module 'rambda/modules/equals.js' { declare module.exports: $Exports<'rambda/modules/equals'>; } declare module 'rambda/modules/F.js' { declare module.exports: $Exports<'rambda/modules/F'>; } declare module 'rambda/modules/filter.js' { declare module.exports: $Exports<'rambda/modules/filter'>; } declare module 'rambda/modules/find.js' { declare module.exports: $Exports<'rambda/modules/find'>; } declare module 'rambda/modules/findIndex.js' { declare module.exports: $Exports<'rambda/modules/findIndex'>; } declare module 'rambda/modules/flatten.js' { declare module.exports: $Exports<'rambda/modules/flatten'>; } declare module 'rambda/modules/flip.js' { declare module.exports: $Exports<'rambda/modules/flip'>; } declare module 'rambda/modules/forEach.js' { declare module.exports: $Exports<'rambda/modules/forEach'>; } declare module 'rambda/modules/has.js' { declare module.exports: $Exports<'rambda/modules/has'>; } declare module 'rambda/modules/head.js' { declare module.exports: $Exports<'rambda/modules/head'>; } declare module 'rambda/modules/identity.js' { declare module.exports: $Exports<'rambda/modules/identity'>; } declare module 'rambda/modules/ifElse.js' { declare module.exports: $Exports<'rambda/modules/ifElse'>; } declare module 'rambda/modules/inc.js' { declare module.exports: $Exports<'rambda/modules/inc'>; } declare module 'rambda/modules/includes.js' { declare module.exports: $Exports<'rambda/modules/includes'>; } declare module 'rambda/modules/indexOf.js' { declare module.exports: $Exports<'rambda/modules/indexOf'>; } declare module 'rambda/modules/init.js' { declare module.exports: $Exports<'rambda/modules/init'>; } declare module 'rambda/modules/internal/baseSlice.js' { declare module.exports: $Exports<'rambda/modules/internal/baseSlice'>; } declare module 'rambda/modules/is.js' { declare module.exports: $Exports<'rambda/modules/is'>; } declare module 'rambda/modules/isNil.js' { declare module.exports: $Exports<'rambda/modules/isNil'>; } declare module 'rambda/modules/join.js' { declare module.exports: $Exports<'rambda/modules/join'>; } declare module 'rambda/modules/last.js' { declare module.exports: $Exports<'rambda/modules/last'>; } declare module 'rambda/modules/lastIndexOf.js' { declare module.exports: $Exports<'rambda/modules/lastIndexOf'>; } declare module 'rambda/modules/length.js' { declare module.exports: $Exports<'rambda/modules/length'>; } declare module 'rambda/modules/map.js' { declare module.exports: $Exports<'rambda/modules/map'>; } declare module 'rambda/modules/match.js' { declare module.exports: $Exports<'rambda/modules/match'>; } declare module 'rambda/modules/merge.js' { declare module.exports: $Exports<'rambda/modules/merge'>; } declare module 'rambda/modules/modulo.js' { declare module.exports: $Exports<'rambda/modules/modulo'>; } declare module 'rambda/modules/multiply.js' { declare module.exports: $Exports<'rambda/modules/multiply'>; } declare module 'rambda/modules/none.js' { declare module.exports: $Exports<'rambda/modules/none'>; } declare module 'rambda/modules/not.js' { declare module.exports: $Exports<'rambda/modules/not'>; } declare module 'rambda/modules/omit.js' { declare module.exports: $Exports<'rambda/modules/omit'>; } declare module 'rambda/modules/partialCurry.js' { declare module.exports: $Exports<'rambda/modules/partialCurry'>; } declare module 'rambda/modules/path.js' { declare module.exports: $Exports<'rambda/modules/path'>; } declare module 'rambda/modules/pathOr.js' { declare module.exports: $Exports<'rambda/modules/pathOr'>; } declare module 'rambda/modules/pick.js' { declare module.exports: $Exports<'rambda/modules/pick'>; } declare module 'rambda/modules/pickAll.js' { declare module.exports: $Exports<'rambda/modules/pickAll'>; } declare module 'rambda/modules/pipe.js' { declare module.exports: $Exports<'rambda/modules/pipe'>; } declare module 'rambda/modules/pluck.js' { declare module.exports: $Exports<'rambda/modules/pluck'>; } declare module 'rambda/modules/prepend.js' { declare module.exports: $Exports<'rambda/modules/prepend'>; } declare module 'rambda/modules/prop.js' { declare module.exports: $Exports<'rambda/modules/prop'>; } declare module 'rambda/modules/propEq.js' { declare module.exports: $Exports<'rambda/modules/propEq'>; } declare module 'rambda/modules/range.js' { declare module.exports: $Exports<'rambda/modules/range'>; } declare module 'rambda/modules/reduce.js' { declare module.exports: $Exports<'rambda/modules/reduce'>; } declare module 'rambda/modules/reject.js' { declare module.exports: $Exports<'rambda/modules/reject'>; } declare module 'rambda/modules/repeat.js' { declare module.exports: $Exports<'rambda/modules/repeat'>; } declare module 'rambda/modules/replace.js' { declare module.exports: $Exports<'rambda/modules/replace'>; } declare module 'rambda/modules/reverse.js' { declare module.exports: $Exports<'rambda/modules/reverse'>; } declare module 'rambda/modules/sort.js' { declare module.exports: $Exports<'rambda/modules/sort'>; } declare module 'rambda/modules/sortBy.js' { declare module.exports: $Exports<'rambda/modules/sortBy'>; } declare module 'rambda/modules/split.js' { declare module.exports: $Exports<'rambda/modules/split'>; } declare module 'rambda/modules/splitEvery.js' { declare module.exports: $Exports<'rambda/modules/splitEvery'>; } declare module 'rambda/modules/startsWith.js' { declare module.exports: $Exports<'rambda/modules/startsWith'>; } declare module 'rambda/modules/subtract.js' { declare module.exports: $Exports<'rambda/modules/subtract'>; } declare module 'rambda/modules/T.js' { declare module.exports: $Exports<'rambda/modules/T'>; } declare module 'rambda/modules/tail.js' { declare module.exports: $Exports<'rambda/modules/tail'>; } declare module 'rambda/modules/take.js' { declare module.exports: $Exports<'rambda/modules/take'>; } declare module 'rambda/modules/takeLast.js' { declare module.exports: $Exports<'rambda/modules/takeLast'>; } declare module 'rambda/modules/tap.js' { declare module.exports: $Exports<'rambda/modules/tap'>; } declare module 'rambda/modules/test.js' { declare module.exports: $Exports<'rambda/modules/test'>; } declare module 'rambda/modules/times.js' { declare module.exports: $Exports<'rambda/modules/times'>; } declare module 'rambda/modules/toLower.js' { declare module.exports: $Exports<'rambda/modules/toLower'>; } declare module 'rambda/modules/toString.js' { declare module.exports: $Exports<'rambda/modules/toString'>; } declare module 'rambda/modules/toUpper.js' { declare module.exports: $Exports<'rambda/modules/toUpper'>; } declare module 'rambda/modules/trim.js' { declare module.exports: $Exports<'rambda/modules/trim'>; } declare module 'rambda/modules/type.js' { declare module.exports: $Exports<'rambda/modules/type'>; } declare module 'rambda/modules/uniq.js' { declare module.exports: $Exports<'rambda/modules/uniq'>; } declare module 'rambda/modules/uniqWith.js' { declare module.exports: $Exports<'rambda/modules/uniqWith'>; } declare module 'rambda/modules/update.js' { declare module.exports: $Exports<'rambda/modules/update'>; } declare module 'rambda/modules/values.js' { declare module.exports: $Exports<'rambda/modules/values'>; } declare module 'rambda/modules/without.js' { declare module.exports: $Exports<'rambda/modules/without'>; } declare module 'rambda/rambda.js' { declare module.exports: $Exports<'rambda/rambda'>; } declare module 'rambda/webVersion.js' { declare module.exports: $Exports<'rambda/webVersion'>; }
import gravity from "lib/loaders/gravity" import OrderedSet from "./ordered_set" import { GraphQLString, GraphQLNonNull, GraphQLList, GraphQLBoolean } from "graphql" const OrderedSets = { type: new GraphQLList(OrderedSet.type), description: "A collection of OrderedSets", args: { key: { type: new GraphQLNonNull(GraphQLString), description: "Key to the OrderedSet or group of OrderedSets", }, public: { type: GraphQLBoolean, defaultValue: true, }, }, resolve: (root, options) => gravity("sets", options), } export default OrderedSets
import React from 'react'; import {connect} from 'react-redux'; import { changeHash } from 'actions/pageActions'; import 'styles/layout.scss'; // Page Styles: import 'styles/pages/home.scss'; export const Page = class Footer extends React.Component { componentDidMount(){ const { dispatch } = this.props; if (!location.hash) { location.hash = "home"; } else { dispatch(changeHash(location.hash.slice(1))); } window.onhashchange = ()=>{ dispatch(changeHash(location.hash.slice(1))); } } render() { return ( <section className={this.props.className} dangerouslySetInnerHTML={{__html: this.props.currentPage}}> </section> ) } }; function mapStateToProps(state){ return { currentPage: state.page.currentPage }; } export const PageContainer = connect(mapStateToProps)(Page);
/** * test * @author: SimonHao * @date: 2016-01-12 10:29:26 */ 'use strict'; var pack = require('../index.js'); console.log(pack({ basedir: __dirname, require: ['base', 'qq'] }));
import { commitMutation, graphql } from 'react-relay'; import { ConnectionHandler } from 'relay-runtime'; const mutation = graphql` mutation deleteWidgetMutation($input: DeleteWidgetInput!) { deleteWidget(input: $input) { viewer { id widgets { totalCount } } widget { id name description color size quantity } } } `; const sharedUpdater = (source, viewerId, widgetId, totalCount) => { const viewerProxy = source.get(viewerId); const conn = ConnectionHandler.getConnection(viewerProxy, 'WidgetTable_widgets'); ConnectionHandler.deleteNode(conn, widgetId); // update the total count if (!totalCount) { totalCount = conn.getValue('totalCount') - 1; } conn.setValue(totalCount, 'totalCount'); }; let clientMutationId = 0; export const deleteWidget = (environment, viewerId, widgetId) => { return new Promise((resolve, reject) => { commitMutation( environment, { mutation, variables: { input: { widgetId, clientMutationId: String(clientMutationId++), }, }, updater: source => { const payload = source.getRootField('deleteWidget'); if (!payload) { return; } const deletedWidget = payload.getLinkedRecord('widget'); const totalCount = payload.getLinkedRecord('viewer') .getLinkedRecord('widgets').getValue('totalCount'); sharedUpdater(source, viewerId, deletedWidget.getValue('id'), totalCount); }, optimisticUpdater: source => { sharedUpdater(source, viewerId, widgetId); }, onCompleted: (results, errors) => { if (errors) { reject(errors); return; } resolve(results); }, onError: errors => reject(errors), } ); }); };
// imports var fs = require('fs'); var jsonfile = require('jsonfile'); // function fileExists function fileExists(filePath) { try { return fs.statSync(filePath).isFile(); } catch (err) { return false; } } // load file var filename = 'data.json'; var allTweets = {}; if (fileExists(filename)) { allTweets = jsonfile.readFileSync(filename); } else { allTweets = { meta: { max_id: Number.MAX_VALUE, since_id: undefined, topics_max_id: Number.MAX_VALUE, topics_since_id: undefined }, tweets: [], topics: [] }; } // static class definition var jsonService = { getTweetsMaxId: function () { return Promise.resolve(allTweets.meta.max_id); }, getTweetsSinceId: function () { return Promise.resolve(allTweets.meta.since_id); }, getTopicsMaxId: function () { return Promise.resolve(allTweets.meta.topics_max_id); }, getTopicsSinceId: function () { return Promise.resolve(allTweets.meta.topics_since_id); }, setTweetsMaxId: function (newValue) { return new Promise((res) => { allTweets.meta.max_id = newValue; jsonfile.writeFileSync(filename, allTweets); res(newValue); }); }, setTweetsSinceId: function (newValue) { return new Promise((res) => { allTweets.meta.since_id = newValue; jsonfile.writeFileSync(filename, allTweets); res(newValue); }); }, setTopicsMaxId: function (newValue) { return new Promise((res) => { allTweets.meta.topics_max_id = newValue; jsonfile.writeFileSync(filename, allTweets); res(newValue); }); }, setTopicsSinceId: function (newValue) { return new Promise((res) => { allTweets.meta.topics_since_id = newValue; jsonfile.writeFileSync(filename, allTweets); res(newValue); }); }, getTweets: function () { return Promise.resolve(allTweets.tweets); }, setTweets: function (newTweets) { return new Promise((res) => { allTweets.tweets = newTweets; jsonfile.writeFileSync(filename, allTweets); res(newTweets); }); }, getTopics: function () { return Promise.resolve(allTweets.topics); }, setTopics: function (newTopics) { return new Promise((res) => { allTweets.topics = newTopics; jsonfile.writeFileSync(filename, allTweets); res(newTopics); }); } }; // export module.exports = jsonService;
window.addEventListener("load", init); function init() { var stage = new createjs.Stage("myCanvas"); setInterval(snowBegin, 200); function snowBegin() { var snowflake = new createjs.Bitmap("snowflakeS.png"); var container = new createjs.Container(); container.x = Math.random() * window.innerWidth; container.addChild(snowflake); stage.addChild(container); var duration = Math.random() * 1000 + 1000; createjs.Tween.get(snowflake, {loop:true}) .to({x:0, alpha:1}, createjs.Ease.quadInOut) .wait(15) .to({x:25, alpha:1}, duration, createjs.Ease.quadInOut) .wait(15) .to({x:0, alpha:1}, duration, createjs.Ease.quadInOut); createjs.Tween.get(container, {loop:true}) .to({y:window.innerHeight}, 10000, createjs.Ease.BackOut) .call(removeContainer); function removeContainer(e) { stage.removeChild(e.target); } } createjs.Ticker.on("tick", stage); }
console.log('moduleA'); require('./moduleA'); require('./moduleB'); // "moduleA" require('./moduleA');
/* @flow */ const BASE = 'nip.io' import type {Service} from '../service' function isValidIpv4Addr(ip) { return /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g.test(ip) } export async function getNIPSubdomain(externalIP: string) { if (!isValidIpv4Addr(externalIP)) { // invalid IP address, fallback to local return `127.0.0.1.${BASE}` } return `${externalIP}.${BASE}` } export async function createHostForService(service: string, navyNormalisedName: string, externalIP: string) { return `${service}.${navyNormalisedName}.${process.env.NAVY_EXTERNAL_SUBDOMAIN || await getNIPSubdomain(externalIP)}` } export async function createUrlForService(service: string, navyNormalisedName: string, externalIP: string) { return `http://${await createHostForService(service, navyNormalisedName, externalIP)}` } export function getUrlFromService(service: Service) { if (!service || !service.raw || !service.raw.Config || !service.raw.Config.Env) { return null } const env = service.raw.Config.Env for (const envVar of env) { if (envVar.indexOf('VIRTUAL_HOST=') === 0) { return 'http://' + envVar.substring('VIRTUAL_HOST='.length) } } return null }
/*! UIkit 3.5.16 | https://www.getuikit.com | (c) 2014 - 2020 YOOtheme | MIT License */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('uikit-util')) : typeof define === 'function' && define.amd ? define('uikittooltip', ['uikit-util'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.UIkitTooltip = factory(global.UIkit.util)); }(this, (function (uikitUtil) { 'use strict'; var Container = { props: { container: Boolean }, data: { container: true }, computed: { container: function(ref) { var container = ref.container; return container === true && this.$container || container && uikitUtil.$(container); } } }; var Togglable = { props: { cls: Boolean, animation: 'list', duration: Number, origin: String, transition: String }, data: { cls: false, animation: [false], duration: 200, origin: false, transition: 'linear', initProps: { overflow: '', height: '', paddingTop: '', paddingBottom: '', marginTop: '', marginBottom: '' }, hideProps: { overflow: 'hidden', height: 0, paddingTop: 0, paddingBottom: 0, marginTop: 0, marginBottom: 0 } }, computed: { hasAnimation: function(ref) { var animation = ref.animation; return !!animation[0]; }, hasTransition: function(ref) { var animation = ref.animation; return this.hasAnimation && animation[0] === true; } }, methods: { toggleElement: function(targets, show, animate) { var this$1 = this; return uikitUtil.Promise.all(uikitUtil.toNodes(targets).map(function (el) { return new uikitUtil.Promise(function (resolve) { return this$1._toggleElement(el, show, animate).then(resolve, uikitUtil.noop); } ); } )); }, isToggled: function(el) { var nodes = uikitUtil.toNodes(el || this.$el); return this.cls ? uikitUtil.hasClass(nodes, this.cls.split(' ')[0]) : !uikitUtil.hasAttr(nodes, 'hidden'); }, updateAria: function(el) { if (this.cls === false) { uikitUtil.attr(el, 'aria-hidden', !this.isToggled(el)); } }, _toggleElement: function(el, show, animate) { var this$1 = this; show = uikitUtil.isBoolean(show) ? show : uikitUtil.Animation.inProgress(el) ? uikitUtil.hasClass(el, 'uk-animation-leave') : uikitUtil.Transition.inProgress(el) ? el.style.height === '0px' : !this.isToggled(el); if (!uikitUtil.trigger(el, ("before" + (show ? 'show' : 'hide')), [this])) { return uikitUtil.Promise.reject(); } var promise = ( uikitUtil.isFunction(animate) ? animate : animate === false || !this.hasAnimation ? this._toggle : this.hasTransition ? toggleHeight(this) : toggleAnimation(this) )(el, show); uikitUtil.trigger(el, show ? 'show' : 'hide', [this]); var final = function () { uikitUtil.trigger(el, show ? 'shown' : 'hidden', [this$1]); this$1.$update(el); }; return (promise || uikitUtil.Promise.resolve()).then(final); }, _toggle: function(el, toggled) { if (!el) { return; } toggled = Boolean(toggled); var changed; if (this.cls) { changed = uikitUtil.includes(this.cls, ' ') || toggled !== uikitUtil.hasClass(el, this.cls); changed && uikitUtil.toggleClass(el, this.cls, uikitUtil.includes(this.cls, ' ') ? undefined : toggled); } else { changed = toggled === el.hidden; changed && (el.hidden = !toggled); } uikitUtil.$$('[autofocus]', el).some(function (el) { return uikitUtil.isVisible(el) ? el.focus() || true : el.blur(); }); this.updateAria(el); if (changed) { uikitUtil.trigger(el, 'toggled', [this]); this.$update(el); } } } }; function toggleHeight(ref) { var isToggled = ref.isToggled; var duration = ref.duration; var initProps = ref.initProps; var hideProps = ref.hideProps; var transition = ref.transition; var _toggle = ref._toggle; return function (el, show) { var inProgress = uikitUtil.Transition.inProgress(el); var inner = el.hasChildNodes ? uikitUtil.toFloat(uikitUtil.css(el.firstElementChild, 'marginTop')) + uikitUtil.toFloat(uikitUtil.css(el.lastElementChild, 'marginBottom')) : 0; var currentHeight = uikitUtil.isVisible(el) ? uikitUtil.height(el) + (inProgress ? 0 : inner) : 0; uikitUtil.Transition.cancel(el); if (!isToggled(el)) { _toggle(el, true); } uikitUtil.height(el, ''); // Update child components first uikitUtil.fastdom.flush(); var endHeight = uikitUtil.height(el) + (inProgress ? 0 : inner); uikitUtil.height(el, currentHeight); return (show ? uikitUtil.Transition.start(el, uikitUtil.assign({}, initProps, {overflow: 'hidden', height: endHeight}), Math.round(duration * (1 - currentHeight / endHeight)), transition) : uikitUtil.Transition.start(el, hideProps, Math.round(duration * (currentHeight / endHeight)), transition).then(function () { return _toggle(el, false); }) ).then(function () { return uikitUtil.css(el, initProps); }); }; } function toggleAnimation(cmp) { return function (el, show) { uikitUtil.Animation.cancel(el); var animation = cmp.animation; var duration = cmp.duration; var _toggle = cmp._toggle; if (show) { _toggle(el, true); return uikitUtil.Animation.in(el, animation[0], duration, cmp.origin); } return uikitUtil.Animation.out(el, animation[1] || animation[0], duration, cmp.origin).then(function () { return _toggle(el, false); }); }; } var Position = { props: { pos: String, offset: null, flip: Boolean, clsPos: String }, data: { pos: ("bottom-" + (!uikitUtil.isRtl ? 'left' : 'right')), flip: true, offset: false, clsPos: '' }, computed: { pos: function(ref) { var pos = ref.pos; return (pos + (!uikitUtil.includes(pos, '-') ? '-center' : '')).split('-'); }, dir: function() { return this.pos[0]; }, align: function() { return this.pos[1]; } }, methods: { positionAt: function(element, target, boundary) { uikitUtil.removeClasses(element, ((this.clsPos) + "-(top|bottom|left|right)(-[a-z]+)?")); var node; var ref = this; var offset = ref.offset; var axis = this.getAxis(); if (!uikitUtil.isNumeric(offset)) { node = uikitUtil.$(offset); offset = node ? uikitUtil.offset(node)[axis === 'x' ? 'left' : 'top'] - uikitUtil.offset(target)[axis === 'x' ? 'right' : 'bottom'] : 0; } var ref$1 = uikitUtil.positionAt( element, target, axis === 'x' ? ((uikitUtil.flipPosition(this.dir)) + " " + (this.align)) : ((this.align) + " " + (uikitUtil.flipPosition(this.dir))), axis === 'x' ? ((this.dir) + " " + (this.align)) : ((this.align) + " " + (this.dir)), axis === 'x' ? ("" + (this.dir === 'left' ? -offset : offset)) : (" " + (this.dir === 'top' ? -offset : offset)), null, this.flip, boundary ).target; var x = ref$1.x; var y = ref$1.y; this.dir = axis === 'x' ? x : y; this.align = axis === 'x' ? y : x; uikitUtil.toggleClass(element, ((this.clsPos) + "-" + (this.dir) + "-" + (this.align)), this.offset === false); }, getAxis: function() { return this.dir === 'top' || this.dir === 'bottom' ? 'y' : 'x'; } } }; var obj; var actives = []; var Component = { mixins: [Container, Togglable, Position], args: 'title', props: { delay: Number, title: String }, data: { pos: 'top', title: '', delay: 0, animation: ['uk-animation-scale-up'], duration: 100, cls: 'uk-active', clsPos: 'uk-tooltip' }, beforeConnect: function() { this._hasTitle = uikitUtil.hasAttr(this.$el, 'title'); uikitUtil.attr(this.$el, {title: '', 'aria-expanded': false}); }, disconnected: function() { this.hide(); uikitUtil.attr(this.$el, {title: this._hasTitle ? this.title : null, 'aria-expanded': null}); }, methods: { show: function() { var this$1 = this; if (this.isActive() || !this.title) { return; } actives.forEach(function (active) { return active.hide(); }); actives.push(this); this._unbind = uikitUtil.on(document, uikitUtil.pointerUp, function (e) { return !uikitUtil.within(e.target, this$1.$el) && this$1.hide(); }); clearTimeout(this.showTimer); this.showTimer = setTimeout(this._show, this.delay); }, hide: function() { var this$1 = this; if (!this.isActive() || uikitUtil.matches(this.$el, 'input:focus')) { return; } this.toggleElement(this.tooltip, false, false).then(function () { actives.splice(actives.indexOf(this$1), 1); clearTimeout(this$1.showTimer); this$1.tooltip = uikitUtil.remove(this$1.tooltip); this$1._unbind(); }); }, _show: function() { var this$1 = this; this.tooltip = uikitUtil.append(this.container, ("<div class=\"" + (this.clsPos) + "\"> <div class=\"" + (this.clsPos) + "-inner\">" + (this.title) + "</div> </div>") ); uikitUtil.on(this.tooltip, 'toggled', function () { var toggled = this$1.isToggled(this$1.tooltip); uikitUtil.attr(this$1.$el, 'aria-expanded', toggled); if (!toggled) { return; } this$1.positionAt(this$1.tooltip, this$1.$el); this$1.origin = this$1.getAxis() === 'y' ? ((uikitUtil.flipPosition(this$1.dir)) + "-" + (this$1.align)) : ((this$1.align) + "-" + (uikitUtil.flipPosition(this$1.dir))); }); this.toggleElement(this.tooltip, true); }, isActive: function() { return uikitUtil.includes(actives, this); } }, events: ( obj = { focus: 'show', blur: 'hide' }, obj[(uikitUtil.pointerEnter + " " + uikitUtil.pointerLeave)] = function (e) { if (uikitUtil.isTouch(e)) { return; } e.type === uikitUtil.pointerEnter ? this.show() : this.hide(); }, obj[uikitUtil.pointerDown] = function (e) { if (!uikitUtil.isTouch(e)) { return; } this.isActive() ? this.hide() : this.show(); }, obj ) }; if (typeof window !== 'undefined' && window.UIkit) { window.UIkit.component('tooltip', Component); } return Component; })));
/* * Webpack distribution configuration * * This file is set up for serving the distribution version. It will be compiled to dist/ by default */ 'use strict'; var webpack = require('webpack'); module.exports = { output: { publicPath: '/assets/', path: 'dist/assets/', filename: 'main.js' }, debug: false, devtool: false, entry: './src/components/GalleryByReactApp.js', stats: { colors: true, reasons: false }, plugins: [ new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.AggressiveMergingPlugin(), new webpack.NoErrorsPlugin() ], resolve: { extensions: ['', '.js', '.jsx'], alias: { 'styles': __dirname + '/src/styles', 'mixins': __dirname + '/src/mixins', 'components': __dirname + '/src/components/' } }, module: { preLoaders: [{ test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'eslint-loader' }], loaders: [{ test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.css$/, loader: 'style-loader!css-loader!autoprefixer-loader?{browsers:["last 2 version"]}' }, { test: /\.scss/, loader: 'style-loader!css-loader!autoprefixer-loader?{browsers:["last 2 version"]}!sass-loader?outputStyle=expanded' }, { test: /\.json$/, loader: 'json-loader' }, { test: /\.(png|jpg|woff|woff2)$/, loader: 'url-loader?limit=8192' }] } };
// see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: '', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }, dev: { env: require('./dev.env'), port: 8785, autoOpenBrowser: true, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
/** Database schema creation functions */ var NoPg = require('nor-nopg'); module.exports = [ /* * plv8 environment initialization function * - defines require (loads libs from libs table) * http://pgxn.org/dist/plv8/doc/plv8.html#Start-up.procedure * Don't forget to set plv8.start_proc = 'plv8_init' in postgresql.conf */ function(db) { function plv8_init(plv8, LOG, INFO, WARNING, ERROR) { plv8._modules = {}; // Require function for loading libs this.require = function(name) { // Is the module already loaded? if (plv8._modules[name]) { return plv8._modules[name]; } // Load the module var module = {'exports':{}}; var code = plv8.execute("SELECT content FROM public.libs WHERE name = $1", [name])[0].content; (new Function("module", "exports", code))(module, module.exports); // Store the module plv8._modules[name] = module.exports; return plv8._modules[name]; }; // this.require // Console logging for the libraries this.console = { "log": plv8.elog.bind(plv8, LOG), "info": plv8.elog.bind(plv8, INFO), "warn": plv8.elog.bind(plv8, WARNING), "error": plv8.elog.bind(plv8, ERROR) }; return true; } // plv8_init return db.query('CREATE OR REPLACE FUNCTION plv8_init() RETURNS boolean LANGUAGE plv8 VOLATILE AS ' + NoPg._escapeFunction(plv8_init, ["plv8", "LOG", "INFO", "WARNING", "ERROR"])); }, /** #2 - Namespace and sql function wrapper for tv4 */ function(db) { function tv4_validateResult(data, schema) { var tv4 = require('tv4'); return tv4.validateResult(data, schema); } return db.query('CREATE SCHEMA IF NOT EXISTS tv4') .query('CREATE OR REPLACE FUNCTION tv4.validateResult(data json, schema json) RETURNS json LANGUAGE plv8 VOLATILE AS ' + NoPg._escapeFunction(tv4_validateResult, ["data", "schema"]) ); } ]; /* EOF */
define(function() { return { device: 'oven', bake: function(pizza) { return 'Baking a ' + pizza.size + ', ' + pizza.doughType + ' pizza with ' + pizza.ingredients.join(', ') + 'in a(n) ' + this.device + '... Gimme like 5 minutes!'; } }; });
/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */ var S$ = require('S$'); var x = S$.symbol("X", ''); var b = /^([a-z])$/.exec(x); if (b) { if (b[1] == 'a') throw 'Reachable'; throw 'Reachable'; }
var searchData= [ ['f_5fgroup',['F_GROUP',['../_list-_faction___group_8h.html#a1b2f26f03e2bcb0a7d4ccd1f0d371bf1',1,'List-Faction_Group.h']]], ['faction',['FACTION',['../_list-_faction_8h.html#ab3f9a36608d530db0300b6d9a1047971',1,'List-Faction.h']]] ];
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Glove = mongoose.model('Glove'), _ = require('lodash'); /** * Get the error message from error object */ var getErrorMessage = function(err) { var message = ''; if (err.code) { switch (err.code) { case 11000: case 11001: message = 'Glove already exists'; break; default: message = 'Something went wrong'; } } else { for (var errName in err.errors) { if (err.errors[errName].message) message = err.errors[errName].message; } } return message; }; /** * Create a Glove */ exports.create = function(req, res) { var glove = new Glove(req.body); glove.user = req.user; glove.save(function(err) { if (err) { return res.send(400, { message: getErrorMessage(err) }); } else { res.jsonp(glove); } }); }; /** * Show the current Glove */ exports.read = function(req, res) { res.jsonp(req.glove); }; /** * Update a Glove */ exports.update = function(req, res) { var glove = req.glove ; glove = _.extend(glove , req.body); glove.save(function(err) { if (err) { return res.send(400, { message: getErrorMessage(err) }); } else { res.jsonp(glove); } }); }; /** * Delete an Glove */ exports.delete = function(req, res) { var glove = req.glove ; glove.remove(function(err) { if (err) { return res.send(400, { message: getErrorMessage(err) }); } else { res.jsonp(glove); } }); }; /** * List of Gloves */ exports.list = function(req, res) { Glove.find().sort('-created').populate('user', 'displayName').exec(function(err, gloves) { if (err) { return res.send(400, { message: getErrorMessage(err) }); } else { res.jsonp(gloves); } }); }; /** * Glove middleware */ exports.gloveByID = function(req, res, next, id) { Glove.findById(id).populate('user', 'displayName').exec(function(err, glove) { if (err) return next(err); if (! glove) return next(new Error('Failed to load Glove ' + id)); req.glove = glove ; next(); }); }; /** * Glove authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.glove.user.id !== req.user.id) { return res.send(403, 'User is not authorized'); } next(); };
import React, {Component} from 'react'; import {View, StyleSheet, TouchableOpacity, Text, InteractionManager, Dimensions} from 'react-native'; import {Theme} from '../components/common/Themes'; import ContactList from '../components/contacts/ContactList'; import ContactsDao from '../dao/ContactsDao'; import LoadingSpinner from '../components/common/LoadingSpinner'; class ContactsPage extends Component{ constructor(props, context) { super(props, context); this.state = {contacts: [], isLoading: true}; } componentDidMount(){ this.loadRegisteredContacts(); } loadRegisteredContacts(){ let showRegistered = false; let contacts = ContactsDao.getContacts(showRegistered); this.setState({contacts: contacts, isLoading: false}); } onClickInvite(router){ router.toInviteContactsView(); } render() { const { router } = this.props; const { contacts, isLoading } = this.state; if(isLoading){ return( <View style={styles.loadingContainer}> <LoadingSpinner size="large"/> </View> ); }else{ return ( <View style={styles.container}> <ContactList router={router} showInviteButton={false} contacts={contacts}/> {this.renderNoContactsMessage(contacts)} <View style={styles.inviteButtonContainer}> <TouchableOpacity onPress={() => {this.onClickInvite(router)}} style={styles.inviteButton}> <Text style={styles.inviteButtonText}> Invite Friends! </Text> </TouchableOpacity> </View> </View> ); } } renderNoContactsMessage(contacts){ if(contacts.length <= 3){ return( <View style={styles.inviteFriendsMessageContainer}> <Text style={styles.inviteFriendsMessageText}> :( It's no fun without friends. Click below to invite your friends! </Text> </View> ); }else{ return null; } } } const styles = StyleSheet.create({ container: { flex: 1, borderRadius: 4, borderWidth: 0.5, borderColor: '#d6d7da', backgroundColor: '#FAFAFA', }, loadingContainer:{ flex: 1, justifyContent: 'center', alignItems: 'center', height: Dimensions.get('window').height, width: Dimensions.get('window').width, }, inviteFriendsMessageContainer:{ flex: 1, justifyContent: 'center', }, inviteFriendsMessageText:{ textAlign: 'center' }, inviteButtonContainer:{ flexDirection: 'row', justifyContent: 'center' }, inviteButton:{ borderColor: Theme.primaryColor, backgroundColor: Theme.primaryColor, borderRadius: 5, height: 40, width: 200, margin: 20, justifyContent: 'center', }, inviteButtonText:{ color: Theme.defaultTextColor, fontSize: Theme.fontSize, fontWeight: 'bold', textAlign: 'center', }, }); export default ContactsPage;
exports = function(modules) { if (modules.length > 0) { var module = modules.shift(); console.log("MODULE ["+module+"] is loading"); var beforeTs = new Date().getTime(); System.import(module).then(function (m) { var afterTs = new Date().getTime(); console.log("MODULE ["+module+"] loaded after ["+(afterTs - beforeTs)+" ms]"); exports(modules); }) .catch( function (err) { console.error(err); }); } }
/* [MS-OLEPS] 2.2 PropertyType */ { var VT_EMPTY = 0x0000; var VT_NULL = 0x0001; var VT_I2 = 0x0002; var VT_I4 = 0x0003; var VT_R4 = 0x0004; var VT_R8 = 0x0005; var VT_CY = 0x0006; var VT_DATE = 0x0007; var VT_BSTR = 0x0008; var VT_ERROR = 0x000A; var VT_BOOL = 0x000B; var VT_VARIANT = 0x000C; var VT_DECIMAL = 0x000E; var VT_I1 = 0x0010; var VT_UI1 = 0x0011; var VT_UI2 = 0x0012; var VT_UI4 = 0x0013; var VT_I8 = 0x0014; var VT_UI8 = 0x0015; var VT_INT = 0x0016; var VT_UINT = 0x0017; var VT_LPSTR = 0x001E; var VT_LPWSTR = 0x001F; var VT_FILETIME = 0x0040; var VT_BLOB = 0x0041; var VT_STREAM = 0x0042; var VT_STORAGE = 0x0043; var VT_STREAMED_Object = 0x0044; var VT_STORED_Object = 0x0045; var VT_BLOB_Object = 0x0046; var VT_CF = 0x0047; var VT_CLSID = 0x0048; var VT_VERSIONED_STREAM = 0x0049; var VT_VECTOR = 0x1000; var VT_ARRAY = 0x2000; var VT_STRING = 0x0050; // 2.3.3.1.11 VtString var VT_USTR = 0x0051; // 2.3.3.1.12 VtUnalignedString var VT_CUSTOM = [VT_STRING, VT_USTR]; } /* [MS-OSHARED] 2.3.3.2.2.1 Document Summary Information PIDDSI */ var DocSummaryPIDDSI = { /*::[*/0x01/*::]*/: { n: 'CodePage', t: VT_I2 }, /*::[*/0x02/*::]*/: { n: 'Category', t: VT_STRING }, /*::[*/0x03/*::]*/: { n: 'PresentationFormat', t: VT_STRING }, /*::[*/0x04/*::]*/: { n: 'ByteCount', t: VT_I4 }, /*::[*/0x05/*::]*/: { n: 'LineCount', t: VT_I4 }, /*::[*/0x06/*::]*/: { n: 'ParagraphCount', t: VT_I4 }, /*::[*/0x07/*::]*/: { n: 'SlideCount', t: VT_I4 }, /*::[*/0x08/*::]*/: { n: 'NoteCount', t: VT_I4 }, /*::[*/0x09/*::]*/: { n: 'HiddenCount', t: VT_I4 }, /*::[*/0x0a/*::]*/: { n: 'MultimediaClipCount', t: VT_I4 }, /*::[*/0x0b/*::]*/: { n: 'Scale', t: VT_BOOL }, /*::[*/0x0c/*::]*/: { n: 'HeadingPair', t: VT_VECTOR | VT_VARIANT }, /*::[*/0x0d/*::]*/: { n: 'DocParts', t: VT_VECTOR | VT_LPSTR }, /*::[*/0x0e/*::]*/: { n: 'Manager', t: VT_STRING }, /*::[*/0x0f/*::]*/: { n: 'Company', t: VT_STRING }, /*::[*/0x10/*::]*/: { n: 'LinksDirty', t: VT_BOOL }, /*::[*/0x11/*::]*/: { n: 'CharacterCount', t: VT_I4 }, /*::[*/0x13/*::]*/: { n: 'SharedDoc', t: VT_BOOL }, /*::[*/0x16/*::]*/: { n: 'HLinksChanged', t: VT_BOOL }, /*::[*/0x17/*::]*/: { n: 'AppVersion', t: VT_I4, p: 'version' }, /*::[*/0x1A/*::]*/: { n: 'ContentType', t: VT_STRING }, /*::[*/0x1B/*::]*/: { n: 'ContentStatus', t: VT_STRING }, /*::[*/0x1C/*::]*/: { n: 'Language', t: VT_STRING }, /*::[*/0x1D/*::]*/: { n: 'Version', t: VT_STRING }, /*::[*/0xFF/*::]*/: {} }; /* [MS-OSHARED] 2.3.3.2.1.1 Summary Information Property Set PIDSI */ var SummaryPIDSI = { /*::[*/0x01/*::]*/: { n: 'CodePage', t: VT_I2 }, /*::[*/0x02/*::]*/: { n: 'Title', t: VT_STRING }, /*::[*/0x03/*::]*/: { n: 'Subject', t: VT_STRING }, /*::[*/0x04/*::]*/: { n: 'Author', t: VT_STRING }, /*::[*/0x05/*::]*/: { n: 'Keywords', t: VT_STRING }, /*::[*/0x06/*::]*/: { n: 'Comments', t: VT_STRING }, /*::[*/0x07/*::]*/: { n: 'Template', t: VT_STRING }, /*::[*/0x08/*::]*/: { n: 'LastAuthor', t: VT_STRING }, /*::[*/0x09/*::]*/: { n: 'RevNumber', t: VT_STRING }, /*::[*/0x0A/*::]*/: { n: 'EditTime', t: VT_FILETIME }, /*::[*/0x0B/*::]*/: { n: 'LastPrinted', t: VT_FILETIME }, /*::[*/0x0C/*::]*/: { n: 'CreatedDate', t: VT_FILETIME }, /*::[*/0x0D/*::]*/: { n: 'ModifiedDate', t: VT_FILETIME }, /*::[*/0x0E/*::]*/: { n: 'PageCount', t: VT_I4 }, /*::[*/0x0F/*::]*/: { n: 'WordCount', t: VT_I4 }, /*::[*/0x10/*::]*/: { n: 'CharCount', t: VT_I4 }, /*::[*/0x11/*::]*/: { n: 'Thumbnail', t: VT_CF }, /*::[*/0x12/*::]*/: { n: 'ApplicationName', t: VT_LPSTR }, /*::[*/0x13/*::]*/: { n: 'DocumentSecurity', t: VT_I4 }, /*::[*/0xFF/*::]*/: {} }; /* [MS-OLEPS] 2.18 */ var SpecialProperties = { /*::[*/0x80000000/*::]*/: { n: 'Locale', t: VT_UI4 }, /*::[*/0x80000003/*::]*/: { n: 'Behavior', t: VT_UI4 }, /*::[*/0x72627262/*::]*/: {} }; (function() { for(var y in SpecialProperties) if(SpecialProperties.hasOwnProperty(y)) DocSummaryPIDDSI[y] = SummaryPIDSI[y] = SpecialProperties[y]; })(); /* [MS-XLS] 2.4.63 Country/Region codes */ var CountryEnum = { /*::[*/0x0001/*::]*/: "US", // United States /*::[*/0x0002/*::]*/: "CA", // Canada /*::[*/0x0003/*::]*/: "", // Latin America (except Brazil) /*::[*/0x0007/*::]*/: "RU", // Russia /*::[*/0x0014/*::]*/: "EG", // Egypt /*::[*/0x001E/*::]*/: "GR", // Greece /*::[*/0x001F/*::]*/: "NL", // Netherlands /*::[*/0x0020/*::]*/: "BE", // Belgium /*::[*/0x0021/*::]*/: "FR", // France /*::[*/0x0022/*::]*/: "ES", // Spain /*::[*/0x0024/*::]*/: "HU", // Hungary /*::[*/0x0027/*::]*/: "IT", // Italy /*::[*/0x0029/*::]*/: "CH", // Switzerland /*::[*/0x002B/*::]*/: "AT", // Austria /*::[*/0x002C/*::]*/: "GB", // United Kingdom /*::[*/0x002D/*::]*/: "DK", // Denmark /*::[*/0x002E/*::]*/: "SE", // Sweden /*::[*/0x002F/*::]*/: "NO", // Norway /*::[*/0x0030/*::]*/: "PL", // Poland /*::[*/0x0031/*::]*/: "DE", // Germany /*::[*/0x0034/*::]*/: "MX", // Mexico /*::[*/0x0037/*::]*/: "BR", // Brazil /*::[*/0x003d/*::]*/: "AU", // Australia /*::[*/0x0040/*::]*/: "NZ", // New Zealand /*::[*/0x0042/*::]*/: "TH", // Thailand /*::[*/0x0051/*::]*/: "JP", // Japan /*::[*/0x0052/*::]*/: "KR", // Korea /*::[*/0x0054/*::]*/: "VN", // Viet Nam /*::[*/0x0056/*::]*/: "CN", // China /*::[*/0x005A/*::]*/: "TR", // Turkey /*::[*/0x0069/*::]*/: "JS", // Ramastan /*::[*/0x00D5/*::]*/: "DZ", // Algeria /*::[*/0x00D8/*::]*/: "MA", // Morocco /*::[*/0x00DA/*::]*/: "LY", // Libya /*::[*/0x015F/*::]*/: "PT", // Portugal /*::[*/0x0162/*::]*/: "IS", // Iceland /*::[*/0x0166/*::]*/: "FI", // Finland /*::[*/0x01A4/*::]*/: "CZ", // Czech Republic /*::[*/0x0376/*::]*/: "TW", // Taiwan /*::[*/0x03C1/*::]*/: "LB", // Lebanon /*::[*/0x03C2/*::]*/: "JO", // Jordan /*::[*/0x03C3/*::]*/: "SY", // Syria /*::[*/0x03C4/*::]*/: "IQ", // Iraq /*::[*/0x03C5/*::]*/: "KW", // Kuwait /*::[*/0x03C6/*::]*/: "SA", // Saudi Arabia /*::[*/0x03CB/*::]*/: "AE", // United Arab Emirates /*::[*/0x03CC/*::]*/: "IL", // Israel /*::[*/0x03CE/*::]*/: "QA", // Qatar /*::[*/0x03D5/*::]*/: "IR", // Iran /*::[*/0xFFFF/*::]*/: "US" // United States }; /* [MS-XLS] 2.5.127 */ var XLSFillPattern = [ null, 'solid', 'mediumGray', 'darkGray', 'lightGray', 'darkHorizontal', 'darkVertical', 'darkDown', 'darkUp', 'darkGrid', 'darkTrellis', 'lightHorizontal', 'lightVertical', 'lightDown', 'lightUp', 'lightGrid', 'lightTrellis', 'gray125', 'gray0625' ]; function rgbify(arr) { return arr.map(function(x) { return [(x>>16)&255,(x>>8)&255,x&255]; }); } /* [MS-XLS] 2.5.161 */ var XLSIcv = rgbify([ /* Color Constants */ 0x000000, 0xFFFFFF, 0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF, /* Defaults */ 0x000000, 0xFFFFFF, 0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF, 0x800000, 0x008000, 0x000080, 0x808000, 0x800080, 0x008080, 0xC0C0C0, 0x808080, 0x9999FF, 0x993366, 0xFFFFCC, 0xCCFFFF, 0x660066, 0xFF8080, 0x0066CC, 0xCCCCFF, 0x000080, 0xFF00FF, 0xFFFF00, 0x00FFFF, 0x800080, 0x800000, 0x008080, 0x0000FF, 0x00CCFF, 0xCCFFFF, 0xCCFFCC, 0xFFFF99, 0x99CCFF, 0xFF99CC, 0xCC99FF, 0xFFCC99, 0x3366FF, 0x33CCCC, 0x99CC00, 0xFFCC00, 0xFF9900, 0xFF6600, 0x666699, 0x969696, 0x003366, 0x339966, 0x003300, 0x333300, 0x993300, 0x993366, 0x333399, 0x333333, /* Sheet */ 0xFFFFFF, 0x000000 ]);
/* eslint-disable prefer-destructuring, babel/new-cap */ import http from 'http'; import app from './app'; import { logger, initializeDb, disconnect, destroyRedis } from './services'; import config from './config'; const debug = require('debug')('boldrAPI:engine'); const PORT = config.server.port; const HOST = config.server.host; const server = http.createServer(app); initializeDb() .then(() => { logger.info('Database connected successfully'); server.listen(PORT, HOST); server.on('listening', () => { const address = server.address(); logger.info( '🚀 Starting server on %s:%s', address.address, address.port, ); }); server.on('error', err => { logger.error(`⚠️ ${err}`); throw err; }); }) .catch(err => { logger.error(err); process.exit(1); }); process.on('SIGINT', () => { logger.info('shutting down!'); disconnect(); destroyRedis(); server.close(); process.exit(); }); process.on('uncaughtException', error => { logger.error(`uncaughtException: ${error.message}`); logger.error(error.stack); debug(error.stack); process.exit(1); });
import React, { PropTypes, Component } from 'react'; import { Motion, spring } from 'react-motion'; import SnackBarContainer from './SnackBarContainer'; export default class SnackBar extends Component { static propTypes = { message: PropTypes.string, time: PropTypes.number, timeout: PropTypes.number, onRequestNext: PropTypes.func, }; static defaultProps = { timeout: 2500 }; state = { open: false }; handleRequestNext = () => { if (this.props.onRequestNext) { this.props.onRequestNext(); } }; componentWillReceiveProps(nextProps) { if (this.props.time != nextProps.time && nextProps.time) { this.show(); } } hide = () => { this.setState({ open: false }); }; show = () => { const { timeout } = this.props; this.setState({ open: true }); this._timer = setTimeout(() => { this._timer = null; this.hide(); }, timeout); }; componentWillUnmount() { if (this._timer) { clearTimeout(this._timer); } } componentDidMount() { if (this.props.message) { this.show(); } } render() { const { open } = this.state; return ( <Motion style={{ position: spring(open ? 1 : 0, { stiffness: 300, damping: 25 }) }}> {interpolated => { if (interpolated.position > 0) { return <SnackBarContainer {...this.props} {...interpolated} onRequestNext={this.handleRequestNext} />; } return null; }} </Motion> ); } }
/* Dependencies (A-Z) */ var _ = require('lodash-node'); var autoprefixer = require('gulp-autoprefixer'); var browserSync = require('browser-sync'); var cached = require('gulp-cached'); var del = require('del'); var gulpif = require('gulp-if'); var filter = require('gulp-filter'); var imagemin = require('gulp-imagemin'); var jscs = require('gulp-jscs'); var jshint = require('gulp-jshint'); var fs = require('fs'); var gulp = require('gulp'); var karma = require('gulp-karma'); var less = require('gulp-less'); var moduleUtility = require('./lib/module-utility'); var newer = require('gulp-newer'); var nunjucksRender = require('./lib/nunjucks-render'); var path = require('path'); var plumber = require('gulp-plumber'); var pngquant = require('imagemin-pngquant'); var prism = require('./lib/prism'); var recess = require('gulp-recess'); var rename = require('gulp-rename'); var replace = require('gulp-replace'); var rjs = require('requirejs'); var runSequence = require('run-sequence'); var sourcemaps = require('gulp-sourcemaps'); var zip = require('gulp-zip'); /* Shared configuration (A-Z) */ var config = require('./config.js'); var paths = config.paths; var pkg = require('./package.json'); /* Register default & custom tasks (A-Z) */ gulp.task('default', ['build_guide']); gulp.task('build', ['build_html', 'build_js', 'build_less', 'copy_assets']); gulp.task('build_assets', function(cb) { runSequence('imagemin', 'copy_assets', cb);}); gulp.task('build_clean', function(cb) { runSequence('clean_dist', 'build', cb); }); gulp.task('build_guide', function(cb) { runSequence('build_clean', 'build_previews', 'build_module_info', cb); }); gulp.task('build_html', buildHtmlTask); gulp.task('build_js',['jshint_src'], buildJsTask); gulp.task('build_less', buildLessTask); gulp.task('build_module_info', buildModuleInfoTask); gulp.task('build_previews', buildPreviewsTask); gulp.task('clean_dist', function (cb) { del([paths.dist], cb); }); gulp.task('copy_assets', copyAssetsTask); gulp.task('create_module', createModule); gulp.task('edit_module', editModule); gulp.task('jshint', ['jshint_src', 'jshint_node']); gulp.task('jshint_node', jshintNodeTask); gulp.task('jshint_src', jshintSrcTask); gulp.task('imagemin', imageminTask); gulp.task('process_images', imageminTask); gulp.task('remove_module', removeModule); gulp.task('serve', serveTask); gulp.task('test_run', testTask('run')); gulp.task('test_watch', testTask('watch')); gulp.task('watch', function(/*cb*/) { runSequence(['build_guide', 'serve'], watchTask); }); gulp.task('zip_dist', zipDistTask); /* Tasks and utils (A-Z) */ function buildHtmlTask() { configureNunjucks(); var moduleIndex = moduleUtility.getModuleIndex(); return srcFiles('html') .pipe(plumber()) // prevent pipe break on nunjucks render error .pipe(nunjucksRender(function(file){ return _.extend( htmlModuleData(file), { moduleIndex: moduleIndex } ); })) .pipe(plumber.stop()) .pipe(gulp.dest(paths.dist)) .pipe(reloadBrowser({ stream:true })); } function buildModuleInfoTask() { var MarkdownIt = require('markdown-it'); var md = new MarkdownIt(); ['Components', 'Views'].forEach(function(moduleType){ listDirectories(paths['src' + moduleType]) .filter(function(name){ return (name.substr(0,1) !== '_'); }) .map(function(name){ var srcBasename = paths['src' + moduleType] + name + '/' + name; var distBasename = paths['dist' + moduleType] + name + '/' + name; var moduleInfo = { name: name, readme : md.render(getFileContents(paths['src' + moduleType] + name + '/README.md')), html : highlightCode(getFileContents(distBasename + '.html'), 'markup'), css : highlightCode(getFileContents(distBasename + '.css'), 'css'), template: highlightCode(getFileContents(srcBasename + '.html'), 'twig'), less : highlightCode(getFileContents(srcBasename + '.less'), 'css'), js : highlightCode(getFileContents(srcBasename + '.js'), 'javascript') }; fs.writeFileSync(distBasename + '-info.json', JSON.stringify(moduleInfo, null, 4)); }); }); } function buildPreviewsTask() { configureNunjucks(); var templateHtml = fs.readFileSync(paths.srcViews + '_component-preview/component-preview.html', 'utf8'); return gulp.src(paths.srcComponents + '*/*.html', { base: paths.src }) .pipe(plumber()) // prevent pipe break on nunjucks render error .pipe(nunjucksRender(htmlModuleData)) .pipe(nunjucksRender(htmlModuleData, templateHtml)) .pipe(plumber.stop()) .pipe(rename(function(p){ p.basename += '-preview'; })) .pipe(gulp.dest(paths.dist)); } function buildJsTask(cb) { var amdConfig = _.extend( require('./src/amd-config.json'), { baseUrl: paths.src, generateSourceMaps: true, // http://requirejs.org/docs/optimization.html#sourcemaps include: ['index'], name: 'vendor/almond/almond', optimize: 'uglify2', out: paths.distAssets + 'index.js', preserveLicenseComments: false } ); rjs.optimize(amdConfig); if(browserSync.active){ browserSync.reload(); } cb(); } function buildLessTask() { return srcFiles('less') .pipe(plumber()) // prevent pipe break on less parsing .pipe(sourcemaps.init()) .pipe(less({ globalVars: { pathToAssets: '"assets/"' } })) .pipe(recess()) .pipe(recess.reporter()) .pipe(autoprefixer({ browsers: config.autoprefixBrowsers })) .pipe(sourcemaps.write('.', {includeContent: true, sourceRoot: '' })) .pipe(plumber.stop()) .pipe(rename(function(p){ if(p.dirname === '.'){ p.dirname = 'assets'; } // output root src files to assets dir })) .pipe(gulp.dest(paths.dist)) // write the css and source maps .pipe(filter('**/*.css')) // filtering stream to only css files .pipe(reloadBrowser({ stream:true })); } function configureNunjucks() { var env = nunjucksRender.nunjucks.configure(paths.src, {watch: false }); env.addFilter('match', require('./lib/nunjucks-filter-match')); env.addFilter('prettyJson', require('./lib/nunjucks-filter-pretty-json')); } /** * Copy all files from `assets/` directories in source root & modules. Only copies file when newer. * The `assets/` string is removed from the original path as the destination is an `assets/` dir itself. */ function copyAssetsTask() { paths.assetFiles.map(function(path){ return gulp.src(path, { base: paths.src }) //.pipe(newer(paths.distAssets)) .pipe(rename(function(p){ p.dirname = p.dirname .split('/') .filter(function(dir){ return (dir !== 'assets'); }) .join('/'); })) .pipe(gulp.dest(paths.distAssets)); }); } function createModule() { return moduleUtility.create(); } function editModule() { return moduleUtility.edit(); } function getFileContents(path){ if(fs.existsSync(path)){ return fs.readFileSync(path, 'utf8'); } else { return ''; } } /** * Use PrismJS in Node: https://github.com/LeaVerou/prism/pull/179 * @param {string} code * @param {string} lang * @returns {string} */ function highlightCode(code, lang){ if(!code.length){ return code; } code = prism.highlight(code, prism.languages[lang]); code = '<pre class="language-' + lang + '"><code>' + code + '</code></pre>'; return code; } function htmlModuleData(file) { var pathToRoot = path.relative(file.relative, '.'); pathToRoot = pathToRoot.substring(0, pathToRoot.length - 2); return { module: { id: path.dirname(file.relative), name: parsePath(file.relative).basename, html: file.contents.toString() }, paths: { assets: pathToRoot + 'assets/', root: pathToRoot }, pkg: pkg }; } /** * All images placed in a `assets-raw/images/` folder will be optimised (if newer) and placed in `assets/images/`. * Examples: * src/assets-raw/images/img.png >> src/assets/images/img.png * src/components/my-component/assets-raw/images/img.png >> src/components/my-component/assets/images/img.png * src/views/my-view/assets-raw/images/img.png >> src/views/my-view/assets/images/img.png * If you don't want an image to be processed place it directly into `assets` instead of `assets-raw`. */ function imageminTask () { var relRawImageDirPath = 'assets-raw/images'; var relRawImageFilePath = relRawImageDirPath + '/**/*.{gif,jpg,jpeg,png,svg}'; function renameImageDir(path){ return path.replace(relRawImageDirPath,'assets/images'); } return gulp.src([ paths.src + relRawImageFilePath, paths.srcComponents + '*/' + relRawImageFilePath, paths.srcViews + '*/' + relRawImageFilePath ], { base: paths.src }) // only process image if the raw image is newer (need to check against renamed output file) .pipe(newer({ dest: paths.src, map: function(relativePath){ return renameImageDir(relativePath); } })) .pipe(imagemin({ progressive: true, svgoPlugins: [], use: [pngquant()] })) // output the processed image in the assets output dir .pipe(rename(function(path){ path.dirname = renameImageDir(path.dirname); })) .pipe(gulp.dest(paths.src)); } function jshintNodeTask() { return gulp.src(['*.js']) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter(require('jshint-stylish'))); } function jshintSrcTask() { return srcFiles('js') .pipe(cached('hinting')) // filter down to changed files only .pipe(jscs()) .pipe(jshint(paths.src + '.jshintrc')) .pipe(jshint.reporter(require('jshint-stylish'))); } function listDirectories(cwd) { return fs.readdirSync(cwd) .filter(function(file){ return fs.statSync(cwd + file).isDirectory(); }); } function parsePath(filepath) { var extname = path.extname(filepath); return { dirname: path.dirname(filepath), basename: path.basename(filepath, extname), extname: extname }; } function reloadBrowser(options){ // only reload browserSync if active, otherwise causes an error. return gulpif(browserSync.active, browserSync.reload(options)); } function removeModule() { return moduleUtility.remove(); } function testTask(action) { return function () { return gulp.src([ // files you put in this array override the files array in karma.conf.js ]) .pipe(karma({ configFile: paths.karmaConfig, action: action })) .on('error', function (err) { throw err; }); }; } function serveTask() { // http://www.browsersync.io/docs/gulp/ browserSync({ server: { baseDir: paths.dist } }); } function srcFiles(filetype) { return gulp.src(paths.srcFiles, { base: paths.src }) .pipe(filter('**/*.' + filetype)); } function watchTask () { gulp.watch(paths.assetFiles, ['copy_assets']); gulp.watch(paths.htmlFiles, ['build_html', 'build_previews']); gulp.watch(paths.jsFiles, ['build_js']); gulp.watch(paths.lessFiles, ['build_less']); } function zipDistTask () { return gulp.src(paths.dist + '**/*') .pipe(zip(pkg.name + '.zip')) .pipe(gulp.dest(paths.dist)); }
let twinkleStar = "Twinkle, twinkle, little star"; let starRegex = /Twinkle/gi; // Change this line let result = twinkleStar.match(starRegex); // Change this line
angular.module('fui-ang').directive('fuifile', function(){ return { restrict: 'E', templateUrl: 'templates/file_template.html', replace: true, scope: { text: '@', changeText: '@', deleteText: '@', name: '@' }, link: function($scope, element, attrs){ $scope.text = attrs.text; $scope.changeText = attrs.changeText; $scope.deleteText = attrs.deleteText; $scope.name = attrs.name; element.fileinput(); } } });
System.register(["aurelia-framework", "../util"], function (exports_1, context_1) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __moduleName = context_1 && context_1.id; var aurelia_framework_1, util, MdcGrid; return { setters: [ function (aurelia_framework_1_1) { aurelia_framework_1 = aurelia_framework_1_1; }, function (util_1) { util = util_1; } ], execute: function () { MdcGrid = (function () { function MdcGrid() { this.fixedWidth = false; } MdcGrid.prototype.attached = function () { if (util.getBoolean(this.fixedWidth)) { this.elementDiv.classList.add('mdc-layout-grid--fixed-column-width'); } }; __decorate([ aurelia_framework_1.bindable(), __metadata("design:type", String) ], MdcGrid.prototype, "class", void 0); __decorate([ aurelia_framework_1.bindable({ defaultBindingMode: aurelia_framework_1.bindingMode.oneTime }), __metadata("design:type", Boolean) ], MdcGrid.prototype, "fixedWidth", void 0); MdcGrid = __decorate([ aurelia_framework_1.customElement('mdc-grid') ], MdcGrid); return MdcGrid; }()); exports_1("MdcGrid", MdcGrid); } }; });
require(`./data-resolution`) require(`./filtered-type-defs`) require(`./gatsby-image`) require(`./integrity`) require(`./plugin-options`) require(`./query-generation`)
const Console = console; { const init = () => { I.apl_font.hidden = true; if (D.el) { document.onmousewheel = (e) => { const d = e.wheelDelta; if (d && (e.ctrlKey || e.metaKey) && !e.shiftKey && !e.altKey) D.commands[d > 0 ? 'ZMI' : 'ZMO'](); }; document.body.className += ` zoom${D.prf.zoom()}`; } D.createContextMenu = (el, win) => { if (!D.el) return; el.oncontextmenu = (e) => { e.preventDefault(); e.stopPropagation(); const hasSelection = win ? !win.me.getSelection().isEmpty() : el.getSelection().type === 'Range'; const isReadOnly = !!win && win.isReadOnly; const tc = !!win && !!win.tc; const fx = !!win && !tc && win.isCode && !win.isReadOnlyEntity; const cmitems = [ { label: 'Cut', role: 'cut', enabled: hasSelection && !isReadOnly }, { label: 'Copy', role: 'copy', enabled: hasSelection }, { label: 'Paste', role: 'paste', enabled: !isReadOnly }, { type: 'separator' }, { label: 'Undo', role: 'undo', enabled: !tc }, { label: 'Redo', role: 'redo', enabled: !tc }, ]; if (win && !win.session.get()) { const { me } = win; if (tc) { cmitems.unshift(...[ { label: 'Skip to line', click: () => { win.STL(me); }, visible: tc, }, { type: 'separator' }, ]); } } const cmenu = D.el.Menu.buildFromTemplate(cmitems); cmenu.popup(); }; }; D.createContextMenu(window); D.open = D.open || ((url, o) => { const { height, width, x, y, } = o; let spec = 'resizable=1'; if (width != null && height != null) spec += `,width=${width},height=${height}`; if (x != null && y != null) spec += `,left=${x},top=${y},screenX=${x},screenY=${y}`; return !!window.open(url, '_blank', spec); }); D.openExternal = D.el ? D.el.shell.openExternal : (x) => { window.open(x, '_blank'); }; if (D.el) { window.electronOpen = window.open; window.open = (url) => { !!url && D.openExternal(url); return { location: { set href(u) { D.openExternal(u); } } }; }; } const loc = window.location; if (D.el) { const qp = nodeRequire('querystring').parse(loc.search.slice(1)); if (qp.type === 'prf') { D.ipc.config.appspace = qp.appid; document.body.className += ' floating-window'; D.IPC_Prf(); I.splash.hidden = 1; } else if (qp.type === 'editor') { D.ipc.config.appspace = qp.appid; document.body.className += ' floating-window'; D.IPC_Client(+qp.winId); I.splash.hidden = 1; } else { const winsLoaded = D.IPC_Server(); const appid = D.ipc.config.appspace; let bw = new D.el.BrowserWindow({ show: false, parent: D.elw, alwaysOnTop: false, fullscreen: false, fullscreenable: false, minWidth: 790, minHeight: 600, webPreferences: { contextIsolation: false, enableRemoteModule: true, nodeIntegration: true, }, }); bw.loadURL(`${loc}?type=prf&appid=${appid}`); D.prf_bw = { id: bw.id }; bw = new D.el.BrowserWindow({ show: false, parent: D.elw, alwaysOnTop: false, fullscreen: false, fullscreenable: false, modal: true, width: 400, height: 350, resizable: false, minimizable: false, maximizable: false, webPreferences: { contextIsolation: false, enableRemoteModule: true, nodeIntegration: true, }, }); bw.loadURL(`file://${__dirname}/dialog.html?appid=${appid}`); D.dlg_bw = { id: bw.id }; bw = new D.el.BrowserWindow({ show: false, parent: D.elw, alwaysOnTop: false, fullscreen: false, fullscreenable: false, modal: false, width: 600, height: 400, resizable: true, minimizable: true, maximizable: true, webPreferences: { contextIsolation: false, enableRemoteModule: true, nodeIntegration: true, }, }); bw.loadURL(`file://${__dirname}/status.html?appid=${appid}`); D.stw_bw = { id: bw.id }; D.elw.focus(); Promise.all(winsLoaded).then(() => { I.splash.hidden = 1; nodeRequire(`${__dirname}/src/cn`)(); }); } } else { const ws = new WebSocket((loc.protocol === 'https:' ? 'wss://' : 'ws://') + loc.host); const q = []; // q:send queue const flush = () => { while (ws.readyState === 1 && q.length) ws.send(q.shift()); }; D.send = (x, y) => { q.push(JSON.stringify([x, y])); flush(); }; ws.onopen = () => { ws.send('SupportedProtocols=2'); ws.send('UsingProtocol=2'); ws.send('["Identify",{"identity":1}]'); ws.send('["Connect",{"remoteId":2}]'); ws.send('["GetWindowLayout",{}]'); }; ws.onmessage = (x) => { if (x.data[0] === '[') { const [c, h] = JSON.parse(x.data); D.recv(c, h); } }; ws.onerror = (x) => { Console.info('ws error:', x); }; D.ide2 = new D.IDE(); I.splash.hidden = 1; } if (!D.quit) D.quit = window.close; window.onbeforeunload = (e) => { if (D.ide && D.ide.connected) { e.returnValue = false; setTimeout(() => { let q = true; if (D.prf.sqp() && !(D.el && process.env.NODE_ENV === 'test')) { const msg = D.spawned ? 'Quit Dyalog APL.' : 'Disconnect from interpreter.'; $.confirm(`${msg} Are you sure?`, document.title, (x) => { q = x; }); } if (q) { if (D.spawned) { D.send('Exit', { code: 0 }); // Wait for the disconnect message } else { D.send('Disconnect', { message: 'User shutdown request' }); D.ide.connected = 0; window.close(); } } }, 10); } else { D.ipc && D.ipc.server.stop(); D.ide && D.prf.connectOnQuit() && D.commands.CNC(); } if (D.ide && !D.ide.connected && D.el) D.wins[0].histWrite(); }; let platform = ''; if (D.mac) platform = ' platform-mac'; else if (D.win) platform = ' platform-windows'; if (D.el) document.body.className += platform; window.focused = true; window.onblur = (x) => { window.focused = x.type === 'focus'; }; window.onfocus = window.onblur; // Implement access keys (Alt-X) using <u></u>. // HTML's accesskey=X doesn't handle duplicates well - // - it doesn't always favour a visible input over a hidden one. // Also, browsers like Firefox and Opera use different shortcuts - // - (such as Alt-Shift-X or Ctrl-X) for accesskey-s. if (!D.mac) { $(document).on('keydown', (e) => { // Alt-A...Alt-Z or Alt-Shift-A...Alt-Shift-Z if (!e.altKey || e.ctrlKey || e.metaKey || e.which < 65 || e.which > 90) return undefined; const c = String.fromCharCode(e.which).toLowerCase(); const C = c.toUpperCase(); const $ctx = $('.ui-widget-overlay').length ? $('.ui-dialog:visible').last() : $('body'); // modal dialogs take priority const $a = $('u:visible', $ctx).map((i, n) => { const h = n.innerHTML; if (h !== c && h !== C) return undefined; let $i = $(n).closest(':input,label,a').eq(0); if ($i.is('label')) $i = $(`#${$i.attr('for')}`).add($i.find(':input')).eq(0); return $i[0]; }); if ($a.length > 1) { $a.eq(($a.index(':focus') + 1) % $a.length).focus(); } else if ($a.is(':checkbox')) { $a.focus().prop('checked', !$a.prop('checked')).change(); } else if ($a.is(':text,:password,textarea,select')) { $a.focus(); } else { $a.click(); } return !$a.length; }); } if (D.el) { // drag and drop window.ondrop = (e) => { e.preventDefault(); return !1; }; window.ondragover = window.ondrop; window.ondrop = (e) => { const { files } = e.dataTransfer; const { path } = (files[0] || {}); if (!D.ide || !path) { // no session or no file dragged } else if (!/\.dws$/i.test(path)) { toastr.error('RIDE supports drag and drop only for .dws files.'); } else if (files.length !== 1) { toastr.error('RIDE does not support dropping of multiple files.'); } else { if (!D.lastSpawnedExe) { toastr.warning( 'Drag and drop of workspaces works only for locally started interpreters.', 'Load may fail', ); } $.confirm( `Are you sure you want to )load ${path.replace(/^.*[\\/]/, '')}?`, 'Load workspace', (x) => { if (x) D.ide.exec([` )load ${path}\n`], 0); }, ); } e.preventDefault(); return !1; }; // extra css and js const path = nodeRequire('path'); const { env } = process; if (env.RIDE_JS) { env.RIDE_JS .split(path.delimiter) .forEach((x) => { if (x) $.getScript(`file://${path.resolve(process.cwd(), x)}`); }); } if (env.RIDE_CSS) { $('<style>') .text(env.RIDE_CSS.split(path.delimiter).map(x => `@import url("${x}");`)) .appendTo('head'); } } }; D.mop.then(() => init()); }
import { computed } from '@ember/object'; import { oneWay } from '@ember/object/computed'; import computedMoment from 'ember-calendar/macros/computed-moment'; import computedDuration from 'ember-calendar/macros/computed-duration'; import Calendar from './calendar'; import OccurrenceProxy from './occurrence-proxy'; export default Calendar.extend({ component: null, startingTime: computedMoment('component.startingDate'), dayStartingTime: computedDuration('component.dayStartingTime'), dayEndingTime: computedDuration('component.dayEndingTime'), timeSlotDuration: computedDuration('component.timeSlotDuration'), defaultOccurrenceTitle: oneWay( 'component.defaultOccurrenceTitle' ), defaultOccurrenceDuration: computedDuration( 'component.defaultOccurrenceDuration' ), occurrences: computed('component.occurrences.[]', function() { return this.get('component.occurrences').map((occurrence) => { return OccurrenceProxy.create({ calendar: this, content: occurrence }); }); }) });
var YI = require('../core'); YI.fn.flip = function(dir) { return this.process(workerBuilder, { width: this.width, height: this.height, dir:dir }); }; function workerBuilder(){ self.onmessage = function(evt){ var data = evt.data.data, dir = evt.data.dir, width = evt.data.width, height = evt.data.height; data.width = width; data.height = height; var xDir = false, yDir = false; dir = dir.toLowerCase(); if (dir.indexOf('x') != -1) { xDir = true; } if (dir.indexOf('y') != -1) { yDir = true; } var x, y, xlen, ylen; if (xDir && yDir) { for (y = 0, ylen = height / 2; y < ylen; y++){ for (x = 0; x < width; x++) { var leftTop = YI.value(data, x ,y); var rightBottom = YI.value(data, width - x -1, height - y -1); YI.value(data, x, y, rightBottom); YI.value(data, width - x -1, height - y -1, leftTop); } } } else if (xDir) { for (x = 0, xlen = width / 2; x < xlen; x++) { for (y = 0; y < height; y++) { var left = YI.value(data, x, y); var right = YI.value(data, width - x - 1, y); YI.value(data, x, y, right); YI.value(data, width - x - 1, y, left); } } } else if (yDir) { for (y = 0, ylen = height / 2; y < ylen; y++) { for (x = 0; x < width; x++) { var up = YI.value(data, x, y); var down = YI.value(data, x, height - y - 1); YI.value(data, x, y, down); YI.value(data, x, height - y - 1, up); } } } YI.progress(100, 100); self.postMessage({data:data, type:'data'}); }; }
/** * Module for password crypt, compare, and create check token. * Why use bcrypt instead of crypto from nodejs itself: * http://stackoverflow.com/a/14015883/1015046 */ var bcrypt = require('bcrypt'); module.exports.crypt = function (password, callback) { bcrypt.genSalt(10, function (err, salt) { if (err) return callback(err); bcrypt.hash(password, salt, function (err, hash) { return callback(err, hash); }); }); }; module.exports.compare = function (password, userPassword, callback) { bcrypt.compare(password, userPassword, function (err, isPasswordMatch) { if (err) return callback(err); return callback(null, isPasswordMatch); }); };
'use strict'; describe('Controller: ModeloCtrl', function () { // load the controller's module beforeEach(module('cgcomApp')); var ModeloCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); ModeloCtrl = $controller('ModeloCtrl', { $scope: scope // place here mocked dependencies }); })); it('should attach a list of awesomeThings to the scope', function () { expect(ModeloCtrl.awesomeThings.length).toBe(3); }); });
//Nuestra url base en desarrollo var baseUrl='http://localhost/appSOL/'; $(document).ready(function() { //Con esta funcion añadimos el evento onclick al boton abrir del imc /* $(".abrirCell").click(function(event) { //Leemos el mes y el año de la fila de la casilla donde se ha hecho click var month=$(event.target).parent().children('.imcYearCell').html(); var year=$(event.target).parent().children('.imcMonthCell').html(); //Y reenviamos a un nuevo controlador que nos muestra el IMC de ese mes location.href=baseUrl+"general/Imc/mostrarImcMes/"+month+"/"+year; }); */ var condicion=$('#condicion').val(); if(condicion==1) { $('#enviadosImc').css('font-weight','bold'); $('#enviadosImc').css('color','black'); $('#enviadosImc').css('background-color','#0f7c77'); //background: rgb(15,124,119)==#0f7c77; } if(condicion==2) { $('#noEnviadosImc').css('font-weight','bold'); $('#noEnviadosImc').css('color','black'); $('#noEnviadosImc').css('background-color','#0f7c77'); } if(condicion==3) { $('#todosImc').css('font-weight','bold'); $('#todosImc').css('color','black'); $('#todosImc').css('background-color','#0f7c77'); } });
import React, { Component } from 'react'; import Section from 'shared/components/section/section'; import QuoteBanner from 'shared/components/quoteBanner/quoteBanner'; import TeamCard from 'shared/components/teamCard/teamCard'; import StaffCard from 'shared/components/staffCard/staffCard'; import BoardCard from 'shared/components/boardCard/boardCard'; import styles from './team.css'; class Team extends Component { constructor(props) { super(props); this.state = { members: [] }; } componentWillMount() { return fetch('https://api.operationcode.org/api/v1/team_members.json').then(response => response.json().then((data) => { this.setState({ members: data }); })); } render() { const team = this.state.members.map(member => ( <TeamCard key={`${Math.random()} + ${member.name}`} name={member.name} role={member.role} /> )); const ceo = { name: 'David Molina', role: 'Founder / CEO', src: './images/DavidMolina.jpg', alt: 'David Molina', twitter: '@davidcmolina', email: 'david@operationcode.org' }; const coo = { name: 'Conrad Hollomon', role: 'COO', src: './images/ConradHollomon.jpg', alt: 'Conrad Hollomon', twitter: '@hollomancer', email: 'conrad@operationcode.org' }; const cto = { name: 'Rick Rein', role: 'CTO', src: './images/RickRein.jpg', alt: 'Rick Rein', twitter: '@rickrrrrrr', email: 'rick@operationcode.org' }; const chair = { name: 'Dr. James Davis', role: 'Chair', src: './images/james.jpg', alt: 'Dr. James Davis' }; const vicechair = { name: 'Dr. Tyrone Grandison', role: 'Vice Chair', src: './images/tyrone.png', alt: 'Dr. Tyrone Grandison' }; const treasurer = { name: 'Elmer Thomas', role: 'Treasurer', src: './images/elmer.png', alt: 'Elmer Thomas' }; const secretary = { name: 'Thomas Ciszec', role: 'Secretary', src: './images/thomas.jpg', alt: 'Thomas Ciszec' }; return ( <div> <QuoteBanner author="Abraham Lincoln" quote="To care for him who shall have borne the battle and for his widow, and his orphan." /> <Section title="Our Staff" theme="white"> <p> Our all volunteer staff are dedicated individuals who come from a wide variety of backgrounds, including members of both the civilian and military community. </p> <div className={styles.team}> { team } </div> </Section> <Section title="Our Team" theme="gray"> <div className={styles.board}> <StaffCard name={ceo.name} role={ceo.role} src={ceo.src} twitter={ceo.twitter} email={ceo.email} alt={ceo.alt} /> <StaffCard name={coo.name} role={coo.role} src={coo.src} twitter={coo.twitter} email={coo.email} alt={coo.alt} /> <StaffCard name={cto.name} role={cto.role} src={cto.src} twitter={cto.twitter} email={cto.email} alt={cto.alt} /> </div> </Section> <Section title="Our Board" theme="white"> <div className={styles.board}> <BoardCard name={chair.name} role={chair.role} src={chair.src} alt={chair.alt} /> <BoardCard name={vicechair.name} role={vicechair.role} src={vicechair.src} alt={vicechair.alt} /> <BoardCard name={treasurer.name} role={treasurer.role} src={treasurer.src} alt={treasurer.alt} /> <BoardCard name={secretary.name} role={secretary.role} src={secretary.src} alt={secretary.alt} /> </div> </Section> </div> ); } } export default Team;
define(['KBasePhenotypes.PhenotypeSet', 'KBModeling', 'testUtil'], (Widget, kbm, TestUtil) => { 'use strict'; describe('Test the KBasePhenotypes.PhenotypeSet widget', () => { afterAll(() => TestUtil.clearRuntime()); it('Should load the module', () => { const api = new KBModeling('token'); expect(api.KBasePhenotypes_PhenotypeSet).toEqual(jasmine.any(Function)); }); }); });
import React from 'react' import Link from 'react-router-dom/Link' export default function NotFound({ resource = 'Page' }) { return ( <div> <header className="header"> <h1 className="text-display container"> {resource} Not Found </h1> </header> <main role="main" className="container"> <p className="spacious"> It is possible this {resource.toLowerCase()} was removed or never existed. </p> <p className="spacious"> <Link to="/">Try starting over from the beginning</Link> </p> </main> </div> ) }
import Ember from 'ember'; export default Ember.Component.extend({ title: '', // name: '', buttonClasses: '', buttonText: '', showModal: false });
"use strict"; const dgram = require('dgram'); const EventEmitter = require('events'); const { encrypt, decrypt } = require('tplink-smarthome-crypto'); const Device = require('./device'); const Plug = require('./plug'); const Bulb = require('./bulb'); const createLogger = require('./logger'); const TcpConnection = require('./network/tcp-connection'); const UdpConnection = require('./network/udp-connection'); const { compareMac } = require('./utils'); const discoveryMsgBuf = encrypt('{"system":{"get_sysinfo":{}},"emeter":{"get_realtime":{}},"smartlife.iot.common.emeter":{"get_realtime":{}}}'); /** * @private */ function parseEmeter(response) { try { if (response.emeter.get_realtime.err_code === 0) { return response.emeter.get_realtime; } } catch (err) {// do nothing } try { if (response['smartlife.iot.common.emeter'].get_realtime.err_code === 0) { return response['smartlife.iot.common.emeter'].get_realtime; } } catch (err) {// do nothing } return null; } /** * Send Options. * * @typedef {Object} SendOptions * @property {number} timeout (ms) * @property {string} transport 'tcp','udp' * @property {boolean} useSharedSocket attempt to reuse a shared socket if available, UDP only * @property {boolean} sharedSocketTimeout (ms) how long to wait for another send before closing a shared socket. 0 = never automatically close socket */ /** * Client that sends commands to specified devices or discover devices on the local subnet. * - Contains factory methods to create devices. * - Events are emitted after {@link #startDiscovery} is called. * @extends EventEmitter */ class Client extends EventEmitter { /** * @param {Object} options * @param {SendOptions} [options.defaultSendOptions] * @param {number} [options.defaultSendOptions.timeout=10000] * @param {string} [options.defaultSendOptions.transport='tcp'] * @param {boolean} [options.defaultSendOptions.useSharedSocket=false] * @param {number} [options.defaultSendOptions.sharedSocketTimeout=20000] * @param {string} [options.logLevel] level for built in logger ['error','warn','info','debug','trace'] */ constructor({ defaultSendOptions, logLevel, logger } = {}) { super(); this.defaultSendOptions = { timeout: 10000, transport: 'tcp', useSharedSocket: false, sharedSocketTimeout: 20000, ...defaultSendOptions }; this.log = createLogger({ level: logLevel, logger }); this.devices = new Map(); this.discoveryTimer = null; this.discoveryPacketSequence = 0; this.maxSocketId = 0; } /** * @private */ getNextSocketId() { this.maxSocketId += 1; return this.maxSocketId; } /** * {@link https://github.com/plasticrake/tplink-smarthome-crypto Encrypts} `payload` and sends to device. * - If `payload` is not a string, it is `JSON.stringify`'d. * - Promise fulfills with parsed JSON response. * * Devices use JSON to communicate.\ * For Example: * - If a device receives: * - `{"system":{"get_sysinfo":{}}}` * - It responds with: * - `{"system":{"get_sysinfo":{ * err_code: 0, * sw_ver: "1.0.8 Build 151113 Rel.24658", * hw_ver: "1.0", * ... * }}}` * * All responses from device contain an `err_code` (`0` is success). * * @param {Object|string} payload * @param {string} host * @param {number} [port=9999] * @param {SendOptions} [sendOptions] * @return {Promise<Object, Error>} */ async send(payload, host, port = 9999, sendOptions) { const thisSendOptions = { ...this.defaultSendOptions, ...sendOptions, useSharedSocket: false }; const payloadString = !(typeof payload === 'string' || payload instanceof String) ? JSON.stringify(payload) : payload; let connection; if (thisSendOptions.transport === 'udp') { connection = new UdpConnection({ host, port, log: this.log, client: this }); } else { connection = new TcpConnection({ host, port, log: this.log, client: this }); } const response = await connection.send(payloadString, thisSendOptions); connection.close(); return response; } /** * Requests `{system:{get_sysinfo:{}}}` from device. * * @param {string} host * @param {number} [port=9999] * @param {SendOptions} [sendOptions] * @return {Promise<Object, Error>} parsed JSON response */ async getSysInfo(host, port = 9999, sendOptions) { this.log.debug('client.getSysInfo(%j)', { host, port, sendOptions }); const data = await this.send('{"system":{"get_sysinfo":{}}}', host, port, sendOptions); return data.system.get_sysinfo; } /** * @private */ emit(eventName, ...args) { // Add device- / plug- / bulb- to eventName if (args[0] instanceof Device) { super.emit(`device-${eventName}`, ...args); if (args[0].deviceType !== 'device') { super.emit(`${args[0].deviceType}-${eventName}`, ...args); } } else { super.emit(eventName, ...args); } } /** * Creates Bulb object. * * See [Device constructor]{@link Device} and [Bulb constructor]{@link Bulb} for valid options. * @param {Object} deviceOptions passed to [Bulb constructor]{@link Bulb} * @return {Bulb} */ getBulb(deviceOptions) { return new Bulb({ defaultSendOptions: this.defaultSendOptions, ...deviceOptions, client: this }); } /** * Creates {@link Plug} object. * * See [Device constructor]{@link Device} and [Plug constructor]{@link Plug} for valid options. * @param {Object} deviceOptions passed to [Plug constructor]{@link Plug} * @return {Plug} */ getPlug(deviceOptions) { return new Plug({ defaultSendOptions: this.defaultSendOptions, ...deviceOptions, client: this }); } /** * Creates a {@link Plug} or {@link Bulb} after querying device to determine type. * * See [Device constructor]{@link Device}, [Bulb constructor]{@link Bulb}, [Plug constructor]{@link Plug} for valid options. * @param {Object} deviceOptions passed to [Device constructor]{@link Device} * @param {SendOptions} [sendOptions] * @return {Promise<Plug|Bulb, Error>} */ async getDevice(deviceOptions, sendOptions) { this.log.debug('client.getDevice(%j)', { deviceOptions, sendOptions }); const sysInfo = await this.getSysInfo(deviceOptions.host, deviceOptions.port, sendOptions); return this.getDeviceFromSysInfo(sysInfo, { ...deviceOptions, client: this }); } /** * Create {@link Device} object. * - Device object only supports common Device methods. * - See [Device constructor]{@link Device} for valid options. * - Instead use {@link #getDevice} to create a fully featured object. * @param {Object} deviceOptions passed to [Device constructor]{@link Device} * @return {Device} */ getCommonDevice(deviceOptions) { return new Device({ client: this, defaultSendOptions: this.defaultSendOptions, ...deviceOptions }); } /** * @private */ getDeviceFromType(typeName, deviceOptions) { let name; if (typeof typeName === 'function') { name = typeName.name; } else { name = typeName; } switch (name.toLowerCase()) { case 'plug': return this.getPlug(deviceOptions); case 'bulb': return this.getBulb(deviceOptions); default: return this.getPlug(deviceOptions); } } /** * Creates device corresponding to the provided `sysInfo`. * * See [Device constructor]{@link Device}, [Bulb constructor]{@link Bulb}, [Plug constructor]{@link Plug} for valid options * @param {Object} sysInfo * @param {Object} deviceOptions passed to device constructor * @return {Plug|Bulb} */ getDeviceFromSysInfo(sysInfo, deviceOptions) { const thisDeviceOptions = { ...deviceOptions, sysInfo }; switch (this.getTypeFromSysInfo(sysInfo)) { case 'plug': return this.getPlug(thisDeviceOptions); case 'bulb': return this.getBulb(thisDeviceOptions); default: return this.getPlug(thisDeviceOptions); } } /** * Guess the device type from provided `sysInfo`. * * Based on sys_info.[type|mic_type] * @param {Object} sysInfo * @return {string} 'plug','bulb','device' */ // eslint-disable-next-line class-methods-use-this getTypeFromSysInfo(sysInfo) { const type = sysInfo.type || sysInfo.mic_type || ''; switch (true) { case /plug/i.test(type): return 'plug'; case /bulb/i.test(type): return 'bulb'; default: return 'device'; } } /** * First response from device. * @event Client#device-new * @property {Device|Bulb|Plug} */ /** * Follow up response from device. * @event Client#device-online * @property {Device|Bulb|Plug} */ /** * No response from device. * @event Client#device-offline * @property {Device|Bulb|Plug} */ /** * First response from Bulb. * @event Client#bulb-new * @property {Bulb} */ /** * Follow up response from Bulb. * @event Client#bulb-online * @property {Bulb} */ /** * No response from Bulb. * @event Client#bulb-offline * @property {Bulb} */ /** * First response from Plug. * @event Client#plug-new * @property {Plug} */ /** * Follow up response from Plug. * @event Client#plug-online * @property {Plug} */ /** * No response from Plug. * @event Client#plug-offline * @property {Plug} */ /** * Invalid/Unknown response from device. * @event Client#discovery-invalid * @property {Object} rinfo * @property {Buffer} response * @property {Buffer} decryptedResponse */ /** * Error during discovery. * @event Client#error * @type {Object} * @property {Error} */ /** * Discover TP-Link Smarthome devices on the network. * * - Sends a discovery packet (via UDP) to the `broadcast` address every `discoveryInterval`(ms). * - Stops discovery after `discoveryTimeout`(ms) (if `0`, runs until {@link #stopDiscovery} is called). * - If a device does not respond after `offlineTolerance` number of attempts, {@link event:Client#device-offline} is emitted. * - If `deviceTypes` are specified only matching devices are found. * - If `macAddresses` are specified only devices with matching MAC addresses are found. * - If `excludeMacAddresses` are specified devices with matching MAC addresses are excluded. * - if `filterCallback` is specified only devices where the callback returns a truthy value are found. * - If `devices` are specified it will attempt to contact them directly in addition to sending to the broadcast address. * - `devices` are specified as an array of `[{host, [port: 9999]}]`. * @param {Object} options * @param {string} [options.address] address to bind udp socket * @param {number} [options.port] port to bind udp socket * @param {string} [options.broadcast=255.255.255.255] broadcast address * @param {number} [options.discoveryInterval=10000] (ms) * @param {number} [options.discoveryTimeout=0] (ms) * @param {number} [options.offlineTolerance=3] # of consecutive missed replies to consider offline * @param {string[]} [options.deviceTypes] 'plug','bulb' * @param {string[]} [options.macAddresses] MAC will be normalized, comparison will be done after removing special characters (`:`,`-`, etc.) and case insensitive, glob style *, and ? in pattern are supported * @param {string[]} [options.excludeMacAddresses] MAC will be normalized, comparison will be done after removing special characters (`:`,`-`, etc.) and case insensitive, glob style *, and ? in pattern are supported * @param {function} [options.filterCallback] called with fn(sysInfo), return truthy value to include device * @param {boolean} [options.breakoutChildren=true] if device has multiple outlets, create a separate plug for each outlet, otherwise create a plug for the main device * @param {Object} [options.deviceOptions={}] passed to device constructors * @param {Object[]} [options.devices] known devices to query instead of relying on broadcast * @return {Client} this * @emits Client#error * @emits Client#device-new * @emits Client#device-online * @emits Client#device-offline * @emits Client#bulb-new * @emits Client#bulb-online * @emits Client#bulb-offline * @emits Client#plug-new * @emits Client#plug-online * @emits Client#plug-offline * @emits Client#discovery-invalid */ startDiscovery({ address, port, broadcast = '255.255.255.255', discoveryInterval = 10000, discoveryTimeout = 0, offlineTolerance = 3, deviceTypes, macAddresses = [], excludeMacAddresses = [], filterCallback, breakoutChildren = true, deviceOptions = {}, devices } = {}) { // eslint-disable-next-line prefer-rest-params this.log.debug('client.startDiscovery(%j)', arguments[0]); try { this.socket = dgram.createSocket('udp4'); this.socket.on('message', (msg, rinfo) => { const decryptedMsg = decrypt(msg).toString('utf8'); this.log.debug(`client.startDiscovery(): socket:message From: ${rinfo.address} ${rinfo.port} Message: ${decryptedMsg}`); let response; let sysInfo; let emeterRealtime; try { response = JSON.parse(decryptedMsg); sysInfo = response.system.get_sysinfo; emeterRealtime = parseEmeter(response); } catch (err) { this.log.debug(`client.startDiscovery(): Error parsing JSON: %s\nFrom: ${rinfo.address} ${rinfo.port} Original: [%s] Decrypted: [${decryptedMsg}]`, err, msg); this.emit('discovery-invalid', { rinfo, response: msg, decryptedResponse: decrypt(msg) }); return; } if (deviceTypes && deviceTypes.length > 0) { const deviceType = this.getTypeFromSysInfo(sysInfo); if (deviceTypes.indexOf(deviceType) === -1) { this.log.debug(`client.startDiscovery(): Filtered out: ${sysInfo.alias} [${sysInfo.deviceId}] (${deviceType}), allowed device types: (%j)`, deviceTypes); return; } } if (macAddresses && macAddresses.length > 0) { const mac = sysInfo.mac || sysInfo.mic_mac || sysInfo.ethernet_mac || ''; if (!compareMac(mac, macAddresses)) { this.log.debug(`client.startDiscovery(): Filtered out: ${sysInfo.alias} [${sysInfo.deviceId}] (${mac}), allowed macs: (%j)`, macAddresses); return; } } if (excludeMacAddresses && excludeMacAddresses.length > 0) { const mac = sysInfo.mac || sysInfo.mic_mac || sysInfo.ethernet_mac || ''; if (compareMac(mac, excludeMacAddresses)) { this.log.debug(`client.startDiscovery(): Filtered out: ${sysInfo.alias} [${sysInfo.deviceId}] (${mac}), excluded mac`); return; } } if (typeof filterCallback === 'function') { if (!filterCallback(sysInfo)) { this.log.debug(`client.startDiscovery(): Filtered out: ${sysInfo.alias} [${sysInfo.deviceId}], callback`); return; } } this.createOrUpdateDeviceFromSysInfo({ sysInfo, emeterRealtime, host: rinfo.address, port: rinfo.port, breakoutChildren, options: deviceOptions }); }); this.socket.on('error', err => { this.log.error('client.startDiscovery: UDP Error: %s', err); this.stopDiscovery(); this.emit('error', err); // TODO }); this.socket.bind(port, address, () => { this.isSocketBound = true; const sockAddress = this.socket.address(); this.log.debug(`client.socket: UDP ${sockAddress.family} listening on ${sockAddress.address}:${sockAddress.port}`); this.socket.setBroadcast(true); this.discoveryTimer = setInterval(() => { this.sendDiscovery(broadcast, devices, offlineTolerance); }, discoveryInterval); this.sendDiscovery(broadcast, devices, offlineTolerance); if (discoveryTimeout > 0) { setTimeout(() => { this.log.debug('client.startDiscovery: discoveryTimeout reached, stopping discovery'); this.stopDiscovery(); }, discoveryTimeout); } }); } catch (err) { this.log.error('client.startDiscovery: %s', err); this.emit('error', err); } return this; } /** * @private */ createOrUpdateDeviceFromSysInfo({ sysInfo, emeterRealtime, host, port, options, breakoutChildren }) { const process = (id, childId) => { let device; if (this.devices.has(id)) { device = this.devices.get(id); device.host = host; device.port = port; device.sysInfo = sysInfo; device.status = 'online'; device.seenOnDiscovery = this.discoveryPacketSequence; if (device.emeter) device.emeter.realtime = emeterRealtime; this.emit('online', device); } else { const deviceOptions = { ...options, client: this, host, port, childId }; device = this.getDeviceFromSysInfo(sysInfo, deviceOptions); device.status = 'online'; device.seenOnDiscovery = this.discoveryPacketSequence; if (device.emeter) device.emeter.realtime = emeterRealtime; this.devices.set(id, device); this.emit('new', device); } }; if (breakoutChildren && sysInfo.children && sysInfo.children.length > 0) { sysInfo.children.forEach(child => { const childId = child.id.length === 2 ? sysInfo.deviceId + child.id : child.id; process(childId, childId); }); } else { process(sysInfo.deviceId); } } /** * Stops discovery and closes UDP socket. */ stopDiscovery() { this.log.debug('client.stopDiscovery()'); clearInterval(this.discoveryTimer); this.discoveryTimer = null; if (this.isSocketBound) { this.isSocketBound = false; this.socket.close(); } } /** * @private */ sendDiscovery(address, devices = [], offlineTolerance) { this.log.debug('client.sendDiscovery(%s, %j, %s)', address, devices, offlineTolerance); try { this.devices.forEach(device => { if (device.status !== 'offline') { const diff = this.discoveryPacketSequence - device.seenOnDiscovery; if (diff >= offlineTolerance) { // eslint-disable-next-line no-param-reassign device.status = 'offline'; this.emit('offline', device); } } }); // sometimes there is a race condition with setInterval where this is called after it was cleared // check and exit if (!this.isSocketBound) { return; } this.socket.send(discoveryMsgBuf, 0, discoveryMsgBuf.length, 9999, address); devices.forEach(d => { this.log.debug('client.sendDiscovery() direct device:', d); this.socket.send(discoveryMsgBuf, 0, discoveryMsgBuf.length, d.port || 9999, d.host); }); if (this.discoveryPacketSequence >= Number.MAX_VALUE) { this.discoveryPacketSequence = 0; } else { this.discoveryPacketSequence += 1; } } catch (err) { this.log.error('client.sendDiscovery: %s', err); this.emit('error', err); } } } module.exports = Client;
/** * Session Configuration * (sails.config.session) * * Sails session integration leans heavily on the great work already done by * Express, but also unifies Socket.io with the Connect session store. It uses * Connect's cookie parser to normalize configuration differences between Express * and Socket.io and hooks into Sails' middleware interpreter to allow you to access * and auto-save to `req.session` with Socket.io the same way you would with Express. * * For more information on configuring the session, check out: * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.session.html */ module.exports.session = { /*************************************************************************** * * * Session secret is automatically generated when your new app is created * * Replace at your own risk in production-- you will invalidate the cookies * * of your users, forcing them to log in again. * * * ***************************************************************************/ secret: '085cd4a17e1d9e5aff5d7978f09db0a3', /*************************************************************************** * * * Set the session cookie expire time The maxAge is set by milliseconds, * * the example below is for 24 hours * * * ***************************************************************************/ // cookie: { // maxAge: 24 * 60 * 60 * 1000 // }, /*************************************************************************** * * * In production, uncomment the following lines to set up a shared redis * * session store that can be shared across multiple Sails.js servers * ***************************************************************************/ // adapter: 'redis', /*************************************************************************** * * * The following values are optional, if no options are set a redis * * instance running on localhost is expected. Read more about options at: * * https://github.com/visionmedia/connect-redis * * * * * ***************************************************************************/ // host: 'localhost', // port: 6379, // ttl: <redis session TTL in seconds>, // db: 0, // pass: <redis auth password>, // prefix: 'sess:', /*************************************************************************** * * * Uncomment the following lines to use your Mongo adapter as a session * * store * * * ***************************************************************************/ // adapter: 'mongo', // host: 'localhost', // port: 27017, // db: 'sails', // collection: 'sessions', /*************************************************************************** * * * Optional Values: * * * * # Note: url will override other connection settings url: * * 'mongodb://user:pass@host:port/database/collection', * * * ***************************************************************************/ // username: '', // password: '', // auto_reconnect: false, // ssl: false, // stringify: true };
import { combineReducers } from 'redux'; import { podcastReducer } from './podcasts'; import { screenReducer } from './screen'; import { eventReducer } from './events'; import { newsReducer } from './news'; export default combineReducers({ eventReducer, newsReducer, podcastReducer, screenReducer, });
// Improtamos el modelo de BD var models = require('../models/models'); // Autoload: Permite realizar una factorización del código si en alguna de las acciones llega // un parámetro de nombre commentId exports.load = function(req, res, next, commentId){ models.Comment .findById(commentId) .then(function(comment){ if(comment) { // Creamos nueva propiedad en req asignándole el valor de comment obtenido en la lectura req.comment = comment; next(); // Pasamos el control a la siguiente acción que corresponda } else { // Si no existe el comment con id commentId creamos mensaje de error next(new Error("No existe el comentario con id: "+comment)); } }) .catch(function(error){ // Añadimos controlador de errores para findById next(error); }); }; // Petición GET /quizes/:quizId/comments/new exports.new = function(req, res) { // Simplemente renderizamos la vista new enviando el quizId asociado res.render('comments/new',{quiz: req.quiz, quizId:req.params.quizId, errors: [] }); }; // Petición POST /quizes/:quizId/comments exports.create = function (req, res, next) { var comment = models.Comment.build({ texto: req.body.comment.texto, QuizId: req.params.quizId }); // Guardamos en la BD los campos pregunta y respusta del formulario comment .validate() .then(function(err){ if(err) { res.render('comments/new',{quiz: req.quiz, quizId:req.params.quizId, errors: err.errors}); } else { comment .save() .then(function(){res.redirect('/quizes/'+req.params.quizId);}) // Redirección HTTP a la página del listado de preguntas .catch(function(error){ // Añadimos controlador de errores para findAll next(error); }); } }); }; // Petición PUT /quizes/:quizId/comments/:commentId/publish exports.publish = function(req, res) { // Actualizamos el campo publicado del objeto comment obtenido en el Autoload req.comment.publicado = true; req.comment .save({fields:["publicado"]}) .then(function(){res.redirect('/quizes/'+req.params.quizId);}) // Redirección HTTP a la página de responder pregunta .catch(function(error){ // Añadimos controlador de errores para save next(error); }); };
'use strict'; // Init the application configuration module for AngularJS application var ApplicationConfiguration = (function() { // Init module configuration options var applicationModuleName = 'projectfit'; var applicationModuleVendorDependencies = ['ngResource', 'ui.router', 'ui.bootstrap', 'ui.utils']; // Add a new vertical module var registerModule = function(moduleName, dependencies) { // Create angular module angular.module(moduleName, dependencies || []); // Add the module to the AngularJS configuration file angular.module(applicationModuleName).requires.push(moduleName); }; return { applicationModuleName: applicationModuleName, applicationModuleVendorDependencies: applicationModuleVendorDependencies, registerModule: registerModule }; })();
var fs = require("fs"); var Fuse = require("../lib/fuse.js"); var isInitializingSearchIndex = false; var searchIndices = null; function initSearchIndex() { if (isInitializingSearchIndex) { return; } isInitializingSearchIndex = true; searchIndices = {}; var atcTree = JSON.parse(fs.readFileSync(__dirname + "/../../../npl/atcTree.json", "utf8")); //Medicine search var options = { keys: ["title", "titlePath", "id", "indications", "substance"], threshold: 0.3, distance: 3000, boost: [2, 1, 1, 1, 1] }; var medicineSearchTree = atcTree.filter(function(element) { return ((element.type === "atc" && element.hasChildren) || element.type === "product"); }); //sort with the longest title first // medicineSearchTree.sort(function(a, b) { // return (b.title.length - a.title.length) // }); var slices = []; //Create 16 slices var nrOfSlices = 16; for (var i = 0; i < nrOfSlices; i++) { slices.push([]); } //Iterate and distribute evenly in 8 slices for (var i = 0; i < medicineSearchTree.length; i++) { //Get first slice var slice = slices.shift(); //Add to slice slice.push(medicineSearchTree[i]); //Send slice to back of slices array slices.push(slice); } //Distribute slices to search indices for (var i = 0; i < slices.length; i++) { searchIndices[i] = new Fuse(slices[i], options); } isInitializingSearchIndex = false; } initSearchIndex(); module.exports = function(input, callback) { var index = searchIndices[input.index]; var results = index.search(input.term); //Create copy of array var trimmed = JSON.parse(JSON.stringify(results)); //Remove indications blob before returning or saving for (var i = trimmed.length - 1; i >= 0; i--){ if (trimmed[i].type === "product") { trimmed[i].indications = ""; } } results = trimmed; callback(null, results); }
var bcrypt = require("bcrypt"); var passport = require("passport"); var passportLocal = require("passport-local"); var salt = bcrypt.genSaltSync(10); module.exports = function(sequelize, DataTypes) { var Admin = sequelize.define("Admin", { username: { type: DataTypes.STRING, unique: true, allowNull: false, validate: { len: [5, 30] } }, password: DataTypes.STRING }, { classMethods: { encryptPass: function(password) { var hash = bcrypt.hashSync(password, salt); return hash; }, comparePass: function(userpass, dbpass) { // don't salt twice when you compare....watch out for this return bcrypt.compareSync(userpass, dbpass); }, createNewAdmin:function(username, password, err, success ) { if(password.length < 5) { err({message: "Password should be more than six characters"}); } else{ Admin.create({ username: username, password: this.encryptPass(password) }).done(function(error,admin) { if(error) { console.log(error) if(error.name === 'SequelizeValidationError'){ err({message: 'Your username should be at least 6 characters long', username: username}); } else if(error.name === 'SequelizeUniqueConstraintError') { err({message: 'An account with that username already exists', username: username}); } } else{ success({message: 'Account created, please log in now'}); } }); } }, } // close classMethods } //close classMethods outer ); // close define user passport.use(new passportLocal.Strategy({ usernameField: 'username', passwordField: 'password', passReqToCallback : true }, function(req, username, password, done) { // find a user in the DB Admin.find({ where: { username: username } }) // when that's done, .done(function(error,admin){ if(error){ console.log(error); return done (err, req.flash('loginMessage', 'Oops! Something went wrong.')); } if (admin === null){ return done (null, false, req.flash('loginMessage', 'username does not exist.')); } if ((Admin.comparePass(password, admin.password)) !== true){ return done (null, false, req.flash('loginMessage', 'Invalid Password')); } done(null, admin); }); })); return Admin; }; // close User function
'use strict'; // Include Gulp and other build automation tools and utilities // See: https://github.com/gulpjs/gulp/blob/master/docs/API.md var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var del = require('del'); var path = require('path'); var runSequence = require('run-sequence'); var webpack = require('webpack'); var argv = require('minimist')(process.argv.slice(2)); // Settings var DEST = './build'; // The build output folder var RELEASE = !!argv.release; // Minimize and optimize during a build? var AUTOPREFIXER_BROWSERS = [ // https://github.com/ai/autoprefixer 'ie >= 10', 'ie_mob >= 10', 'ff >= 30', 'chrome >= 34', 'safari >= 7', 'opera >= 23', 'ios >= 7', 'android >= 4.4', 'bb >= 10' ]; var src = {}; var watch = false; var browserSync; // The default task gulp.task('default', ['sync']); // Clean up gulp.task('clean', del.bind(null, [DEST])); // 3rd party libraries gulp.task('vendor', function() { return gulp.src('./node_modules/bootstrap/dist/fonts/**') .pipe(gulp.dest(DEST + '/fonts')); }); // Static files gulp.task('assets', function() { src.assets = [ 'src/assets/**' ]; return gulp.src(src.assets) .pipe($.changed(DEST)) .pipe(gulp.dest(DEST)) .pipe($.size({title: 'assets'})); }); // CSS style sheets gulp.task('styles', function() { src.styles = [ 'src/styles/bootstrap.less', 'src/components/**/*.{css,less}' ]; return gulp.src(src.styles) .pipe($.plumber()) .pipe($.less({ sourceMap: !RELEASE, sourceMapBasepath: __dirname })) .on('error', console.error.bind(console)) .pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS})) .pipe($.csscomb()) .pipe($.if(RELEASE, $.minifyCss())) .pipe($.concat('styles.css')) .pipe(gulp.dest(DEST + '/css')) .pipe($.size({title: 'styles'})); }); // Bundle gulp.task('bundle', function(cb) { var started = false; var config = require('./webpack.config.js'); var bundler = webpack(config); function bundle(err, stats) { if (err) { throw new $.util.PluginError('webpack', err); } if (argv.verbose) { $.util.log('[webpack]', stats.toString({colors: true})); } if (!started) { started = true; return cb(); } } if (watch) { bundler.watch(200, bundle); } else { bundler.run(bundle); } }); // Build the app from source code gulp.task('build', ['clean'], function(cb) { runSequence(['vendor', 'assets', 'styles', 'bundle'], cb); }); // Build and start watching for modifications gulp.task('build:watch', function(cb) { watch = true; runSequence('build', function() { gulp.watch(src.assets, ['assets']); gulp.watch(src.styles, ['styles']); cb(); }); }); // Launch a Node.js/Express server gulp.task('serve', ['build:watch'], function(cb) { src.server = [ DEST + '/server.js', DEST + '/content/**/*', DEST + '/templates/**/*' ]; var started = false; var cp = require('child_process'); var assign = require('react/lib/Object.assign'); var server = (function startup() { var child = cp.fork(DEST + '/server.js', { env: assign({ NODE_ENV: 'development' }, process.env) }); child.once('message', function(message) { if (message.match(/^online$/)) { if (browserSync) { browserSync.reload(); } if (!started) { started = true; gulp.watch(src.server, function(file) { $.util.log('Restarting development server.'); server.kill('SIGTERM'); server = startup(); }); cb(); } } }); return child; })(); process.on('exit', function() { server.kill('SIGTERM'); }); }); // Launch BrowserSync development server gulp.task('sync', ['serve'], function(cb) { browserSync = require('browser-sync'); browserSync({ notify: false, // Run as an https by setting 'https: true' // Note: this uses an unsigned certificate which on first access // will present a certificate warning in the browser. https: false, // Informs browser-sync to proxy our Express app which would run // at the following location proxy: 'localhost:5000' }, cb); process.on('exit', function () { browserSync.exit(); }); gulp.watch([DEST + '/**/*.*'].concat( src.server.map(function(file) {return '!' + file;}) ), function(file) { browserSync.reload(path.relative(__dirname, file.path)); }); });
// Generated by CoffeeScript 1.8.0 define(function(require, exports, module) { "use strict"; var Utils; Utils = require("core/utils"); return describe("Utils", function() { it("isType", function() { expect(Utils.isType(new Object(), "object")).toBe(true); return expect(Utils.isType(new String("abc"), "object")).toBe(false); }); it("isObject", function() { expect(Utils.isObject(new Object())).toBe(true); expect(Utils.isObject({})).toBe(true); expect(Utils.isObject(new String("abc"))).toBe(false); expect(Utils.isObject("abc")).toBe(false); expect(Utils.isObject(new Number(123))).toBe(false); expect(Utils.isObject(123)).toBe(false); expect(Utils.isObject(new Array())).toBe(false); expect(Utils.isObject([])).toBe(false); expect(Utils.isObject(function() {})).toBe(false); expect(Utils.isObject(new RegExp("abc"))).toBe(false); return expect(Utils.isObject(/abc/)).toBe(false); }); it("isString", function() { expect(Utils.isString(new Object())).toBe(false); expect(Utils.isString({})).toBe(false); expect(Utils.isString(new String("abc"))).toBe(true); expect(Utils.isString("abc")).toBe(true); expect(Utils.isString(new Number(123))).toBe(false); expect(Utils.isString(123)).toBe(false); expect(Utils.isString(new Array())).toBe(false); expect(Utils.isString([])).toBe(false); expect(Utils.isString(function() {})).toBe(false); expect(Utils.isString(new RegExp("abc"))).toBe(false); return expect(Utils.isString(/abc/)).toBe(false); }); it("isNumber", function() { expect(Utils.isNumber(new Object())).toBe(false); expect(Utils.isNumber({})).toBe(false); expect(Utils.isNumber(new String("abc"))).toBe(false); expect(Utils.isNumber("abc")).toBe(false); expect(Utils.isNumber(new Number(123))).toBe(true); expect(Utils.isNumber(123)).toBe(true); expect(Utils.isNumber(new Array())).toBe(false); expect(Utils.isNumber([])).toBe(false); expect(Utils.isNumber(function() {})).toBe(false); expect(Utils.isNumber(new RegExp("abc"))).toBe(false); return expect(Utils.isNumber(/abc/)).toBe(false); }); it("isArray", function() { expect(Utils.isArray(new Object())).toBe(false); expect(Utils.isArray({})).toBe(false); expect(Utils.isArray(new String("abc"))).toBe(false); expect(Utils.isArray("abc")).toBe(false); expect(Utils.isArray(new Number(123))).toBe(false); expect(Utils.isArray(123)).toBe(false); expect(Utils.isArray(new Array())).toBe(true); expect(Utils.isArray([])).toBe(true); expect(Utils.isArray(function() {})).toBe(false); expect(Utils.isArray(new RegExp("abc"))).toBe(false); return expect(Utils.isArray(/abc/)).toBe(false); }); it("isFunction", function() { expect(Utils.isFunction(new Object())).toBe(false); expect(Utils.isFunction({})).toBe(false); expect(Utils.isFunction(new String("abc"))).toBe(false); expect(Utils.isFunction("abc")).toBe(false); expect(Utils.isFunction(new Number(123))).toBe(false); expect(Utils.isFunction(123)).toBe(false); expect(Utils.isFunction(new Array())).toBe(false); expect(Utils.isFunction([])).toBe(false); expect(Utils.isFunction(function() {})).toBe(true); expect(Utils.isFunction(new RegExp("abc"))).toBe(false); return expect(Utils.isFunction(/abc/)).toBe(false); }); it("isRegex", function() { expect(Utils.isRegex(new Object())).toBe(false); expect(Utils.isRegex({})).toBe(false); expect(Utils.isRegex(new String("abc"))).toBe(false); expect(Utils.isRegex("abc")).toBe(false); expect(Utils.isRegex(new Number(123))).toBe(false); expect(Utils.isRegex(123)).toBe(false); expect(Utils.isRegex(new Array())).toBe(false); expect(Utils.isRegex([])).toBe(false); expect(Utils.isRegex(function() {})).toBe(false); expect(Utils.isRegex(new RegExp("abc"))).toBe(true); return expect(Utils.isRegex(/abc/)).toBe(true); }); it("parse", function() { expect(Utils.parse()).toEqual([]); expect(Utils.parse("[{\"a\":1}]")).toEqual([ { a: 1 } ]); return expect(Utils.parse("[1,2,3]")).toEqual([1, 2, 3]); }); it("stringify", function() { expect(Utils.stringify()).toEqual("[]"); expect(Utils.stringify([ { a: 1 } ])).toEqual("[{\"a\":1}]"); return expect(Utils.stringify([1, 2, 3])).toEqual("[1,2,3]"); }); it("isEqual", function() { expect(Utils.isEqual("aaa", "bbb")).toBe(false); expect(Utils.isEqual("aaa", "aaa")).toBe(true); expect(Utils.isEqual(1, 2)).toBe(false); expect(Utils.isEqual(1, 1)).toBe(true); expect(Utils.isEqual(0, 1)).toBe(false); expect(Utils.isEqual(new Date(2014, 9, 26), new Date(2014, 9, 26))).toBe(true); expect(Utils.isEqual(new Date(2014, 9, 27), new Date(2014, 9, 26))).toBe(false); expect(Utils.isEqual(true, true)).toBe(true); expect(Utils.isEqual(true, false)).toBe(false); expect(Utils.isEqual(null, void 0)).toBe(false); expect(Utils.isEqual(void 0, null)).toBe(false); return expect(Utils.isEqual(NaN, 1)).toBe(false); }); it("keys", function() { return expect(Utils.keys([])).toEqual([]); }); it("toUnicode&fromUnicode", function() { var fromUnicode, string, toUnicode; string = " 京东买奶茶——=+~!@#¥%……&*()"; toUnicode = Utils.toUnicode(string); fromUnicode = Utils.fromUnicode(toUnicode); return expect(fromUnicode).toEqual(string); }); return it("Domain", function() { var url; url = "http://www.taobao.com:8080/test.html"; expect(Utils.getDomain(url)).toEqual("www.taobao.com"); return expect(Utils.getOrigin(url)).toEqual("http://www.taobao.com:8080"); }); }); });
var Note = React.createClass({ componentDidMount: function() { this.attrs = this.props; this.syntaxHighlight(); this.change(); }, componentDidUpdate: function() { this.syntaxHighlight(); this.change(); }, getInitialState: function() { return { cssClass: 'note' }; }, setAttrs: function(updatedAttrs) { Object.keys(updatedAttrs).forEach(function(key) { this.attrs[key] = updatedAttrs[key]; }.bind(this)); }, mouseDown: function(event) { event.stopPropagation(); this.isDragging = true; this.hasDragged = false; this.clickX = event.pageX; this.clickY = event.pageY; this.updateCssState(); }, mouseUp: function(event) { event.stopPropagation(); this.isDragging = false; this.updateCssState(); if (!this.hasDragged) { EventBus.emitEvent('stop-editing-note'); this.setAttrs({ isEditing: true }); EventBus.emitEvent('update-note', [this.attrs]); this.change(); } }, mouseMove: function(event) { event.stopPropagation(); if (this.isDragging) { this.hasDragged = true; var dx = this.clickX - event.pageX; var dy = this.clickY - event.pageY; this.setAttrs({ x: this.props.x - dx, y: this.props.y - dy }); this.updateMatrixState(); this.clickX = event.pageX; this.clickY = event.pageY; this.updateCssState(); } }, syntaxHighlight: function() { var blocks = this.getDOMNode().querySelectorAll('pre code'); for (var index = 0; index < blocks.length; index++) { var block = blocks[index]; hljs.highlightBlock(block); }; }, updateCssState: function() { if (this.isDragging) { this.setState({ cssClass: 'note dragging' }); } else { this.setState({ cssClass: 'note' }); } }, updateMatrixState: function() { var matrix = 'translate(' + this.attrs.x.toFixed() + 'px, ' + this.attrs.y.toFixed() + 'px)'; this.setAttrs({ matrix: matrix }); EventBus.emitEvent('update-note', [this.attrs]); }, blur: function() { var content = this.getDOMNode().value; if (content === '') { EventBus.emitEvent('delete-note', [this.props.id]); } else { var attrs = { isEditing: false, content: content }; this.setAttrs(attrs); EventBus.emitEvent('update-note', [this.attrs]); } }, change: function() { if (this.attrs.isEditing) { var node = this.getDOMNode(); node.style.height = 'auto'; node.style.height = node.scrollHeight + 'px'; } }, keyUp: function(event) { if (event.keyCode === 27) { this.blur(); } }, render: function() { if (this.props.isEditing) { return ( <textarea className="note" style={{transform: this.props.matrix, '-webkit-transform': this.props.matrix}} onMouseDown={this.mouseDown} onMouseUp={this.mouseUp} onBlur={this.blur} onChange={this.change} onKeyUp={this.keyUp}> {this.props.content} </textarea> ); } else { var val = this.props.content; return ( <div className={this.state.cssClass} style={{transform: this.props.matrix, '-webkit-transform': this.props.matrix}} onMouseDown={this.mouseDown} onMouseMove={this.mouseMove} onMouseUp={this.mouseUp} dangerouslySetInnerHTML={{__html: marked(val, { sanitize: true })}}> </div> ); } } });