text
stringlengths
2
6.14k
// As a user, I want to have 3 different operations. // 1. Calculate the sum of arbitrary amount of numbers // 2. Calculate the mean of arbitrary amount of numbers // 3. Calculate the median of arbitrary amount of numbers // Turns out the code doesn't work properly, but just some minor mistakes. // 1. The name for the sum function is actually "sum" instead of "combine". // 2. It is better if there is no global variable being used for this function. So the variable "sum", which would be conflicting the function name, needs to be inside the function "sum". // 3. The function name need to be unique to other identifiers. In function "mean" both the function name and the return variable is called "mean". This will cause conflict on the compiler. // Nice job on the median! // So far the group has been doing a decent job on the work flow. We simulate the scenario and has found out about the problems that can happen in each step and each iteration. // Eventually if we goes through the process a couple more times, it would be more accurate. For example, person 1 will have a clearer (more detailed) description of the story, so person 2 will have more accurate pseudocode for person 3 and 4 to translate to actual code. // We need more practice to get use to this work flow. // ---------------- Code ----------------------- // Sum function function sum(numbers){ var total = 0; for (var index in numbers){ total=numbers[index] +total }; return total }; //Mean Function// function mean(numbers){ var m_num = sum(numbers); return m_num / numbers.length; }; //Median Function // This is where variable x was renamed and Math.floor was refactored, as well as 2 comments to make action slightly more explicit function median(numbers){ var sorter= numbers.sort(function (a,b){return a-b}); if (sorter.length %2===1){ //if odd var median= Math.floor(sorter.length/2); return(sorter[median]);} else if(sorter.length % 2 ===0) // if even {var median=sorter.length/2; return (sorter[median] +sorter[median-1])/2} else return "Please enter an array of integers"; };
var keystone = require('keystone'), async = require('async'), hat = require('hat'), Types = keystone.Field.Types, snowcoins = require('wallets'); /** * Posts Model * =========== */ var ClientConnect = new keystone.List(snowcoins.get('model clients'), { map: { name: 'name' }, autokey: { path: 'key', from: '_id', unique: true }, singular:'D2C/D3C API Key', plural:'D2C/D3C API Keys', label:'D2C/D3C API Keys', defaultSort:'-status', nodelete:true, track: true }); ClientConnect.add({ name: { type: String, required: true,index:true, unique: true }, owner: { type: Types.Relationship, ref: snowcoins.get('model user'), index: true, initial: true }, createdDate: { type: Types.Date, default: Date.now, index: true }, apikey: { label:'API Key', type: Types.Key, initial: true, unique: true }, apikeyused: { type: Types.Key }, type: { type: Types.Select, options: 'client, master', default: 'client', initial: true }, status: { type: Types.Select, options: 'valid, deleted', default: 'valid' }, clients: { type: Types.Relationship, ref: snowcoins.get('model clients'), many:true }, authlevel: { type: Types.Number , default:10 }, ip: { type: String } }); /** * Virtuals * ======== */ /** * Methods * ============= */ /** * Notifications * ============= */ /** * Registration * ============ */ //ClientConnect.addPattern('standard meta'); ClientConnect.defaultColumns = 'name,type,apikey,status,owner'; ClientConnect.register();
window.VariableEvents = function(a, c, d, e, g, h, k) { var b = "_" + c.toString(); a[b] = {a:d, b:e, e:g, c:h, d:k}; Object.defineProperty(a, c, {get:function() { "function" === typeof a[b].b && a[b].b(a[b].a); return "function" === typeof a[b].c ? a[b].c(a[b].a) : a[b].a; }, set:function(c) { a[b].a = "function" === typeof a[b].d ? a[b].d(c) : c; "function" === typeof a[b].e && a[b].e(a[b].a); }, enumerable:!0, configurable:!0}); };
/* Input Mask plugin dependencyLib http://github.com/RobinHerbots/jquery.inputmask Copyright (c) Robin Herbots Licensed under the MIT license */ import jQuery from "jquery"; if (jQuery === undefined) { throw "jQuery not loaded!"; } export default jQuery;
/************************* デバッグ変数コンストラクタ *************************/ /* var p = console.log; var print = console.log; var var_dump = console.dir; var trace = console.trace; var time = console.time; var count = console.count; */ /*********** http切り替え ***********/ if (location.host == 'localhost') { var http = 'http://localhost/sharetube/'; } else if (location.host == 'sharetube.jp') { var http = 'http://sharetube.jp/'; } else if (location.host == 'www.sharetube.jp') { var http = 'http://sharetube.jp/'; } //---------------- //読み込み後の処理 //---------------- $(function() { //---------------------------- //記事のバックに画像を表示する //---------------------------- // 表示する場所の大きさを取得 var article_list_contents_height = $('.article_list_contents').height(); // p(article_list_contents_height); // ズレる余白を取得 var main_padding_top = $('.main').css('padding-top').replace('px', ''); var article_list_contents_margin_bottom = $('.article_list_contents').css('margin-bottom').replace('px', ''); // intにキャストする main_padding_top = eval(main_padding_top); article_list_contents_margin_bottom = eval(article_list_contents_margin_bottom); // p('main_padding_top:'+main_padding_top); // p('article_list_contents_margin_bottom:'+article_list_contents_margin_bottom); // 微調整 var adjust = -15; // ブラウザのサイズによって調整していく if($(window).width() <= 768) { var adjust = 8; main_padding_top = 8; } else if($(window).width() <= 480) { var adjust = 8; main_padding_top = 8; } else if($(window).width() <= 320) { var adjust = 8; main_padding_top = 8; } // 余白を合計する var shift = main_padding_top + article_list_contents_margin_bottom; // p(shift); // 記事のナンバーを取得 article_number = $('.main_contents .article_list').attr('data-article_number'); // 記事のアップされた年を取得 article_year = $('.main_contents .article_list').attr('data-article_year'); // デフォルト設定 $('.article_list_contents_background').css( { background: 'url("'+ http +'/assets/img/article/'+article_year+'/facebook_ogp/'+article_number+'.jpg") no-repeat scroll center center / cover rgba(0, 0, 0, 0)', height: adjust + shift + article_list_contents_height + "px", width: $(window).width()+"px", }); // 2秒待機して数値を取得する setTimeout(function() { var article_list_contents_height = $('.article_list_contents').height(); // p(article_list_contents_height); // 再設定 $('.article_list_contents_background').css( { background: 'url("'+ http +'/assets/img/article/'+article_year+'/facebook_ogp/'+article_number+'.jpg") no-repeat scroll center center / cover rgba(0, 0, 0, 0)', height: adjust + shift + article_list_contents_height + "px", width: $(window).width()+"px", }); }, 2000); //-------------------------- //正しい数値を取得するテスト //-------------------------- $('#header').click(function() { var article_list_contents_height = $('.article_list_contents').height(); // p(article_list_contents_height); }); //-------------------------------------- //記事のバックに画像を表示する(リサイズ) //-------------------------------------- $(window).resize(function() { // 表示する場所の大きさを取得 var article_list_contents_height = $('.article_list_contents').height(); // p(article_list_contents_height); // ズレる余白を取得 var main_padding_top = $('.main').css('padding-top').replace('px', ''); var article_list_contents_margin_bottom = $('.article_list_contents').css('margin-bottom').replace('px', ''); // intにキャストする main_padding_top = eval(main_padding_top); article_list_contents_margin_bottom = eval(article_list_contents_margin_bottom); // p('main_padding_top:'+main_padding_top); // p('article_list_contents_margin_bottom:'+article_list_contents_margin_bottom); // 微調整 var adjust = -15; // ブラウザのサイズによって調整していく if($(window).width() <= 768) { var adjust = 8; main_padding_top = 8; } else if($(window).width() <= 480) { var adjust = 8; main_padding_top = 8; } else if($(window).width() <= 320) { var adjust = 8; main_padding_top = 8; } // 余白を合計する var shift = main_padding_top + article_list_contents_margin_bottom; // p(shift); // 記事のナンバーを取得 article_number = $('.main_contents .article_list').attr('data-article_number'); // 記事のアップされた年を取得 article_year = $('.main_contents .article_list').attr('data-article_year'); // デフォルト設定 $('.article_list_contents_background').css( { background: 'url("'+ http +'/assets/img/article/'+article_year+'/facebook_ogp/'+article_number+'.jpg") no-repeat scroll center center / cover rgba(0, 0, 0, 0)', height: adjust + shift + article_list_contents_height + "px", width: $(window).width()+"px", }); }); });
export {default as BevelFilter} from './BevelFilter';
function sendCharacters(client, worldId, characters) { var packet = new PacketWriter(0x0008); packet.writeUInt8(0); packet.writeUInt8(worldId); packet.writeUInt8(characters.length); for (var i = 0; i < characters.length; i++) { var character = characters[i]; character.addStats(packet); character.addAvatar(packet); packet.writeUInt8(false); } client.sendPacket(packet); } PacketHandler.setHandler(0x000D, function (client, reader) { // View all characters (clicked VAC button) if (!client.account) { client.disconnect('Trying to view all characters while not loggedin'); return; } var worldInConfig = ServerConfig.worlds; var worlds = {}; var worldId; for (var worldName in worldInConfig) { worldId = worldInConfig[worldName].id; worlds[worldId] = client.account.getCharacters(worldId); } var packet = new PacketWriter(0x0008); packet.writeUInt8(1); var totalCharacters = 0; for (worldId in worlds) { totalCharacters += worlds[worldId].length; } packet.writeUInt32(totalCharacters); packet.writeUInt32(totalCharacters + (3 - totalCharacters % 3)); client.sendPacket(packet); for (worldId in worlds) { if (worlds[worldId].length === 0) continue; sendCharacters(client, worldId, worlds[worldId]); } }); function enterChannel(client, characterId, worldId) { var world = getWorldInfoById(worldId); var channel = (world.channels * Math.random()) >>> 0; // Remote-hack vulnerable var packet = new PacketWriter(0x000C); packet.writeUInt16(0); packet.writeBytes(ipStringToBytes(world.publicIP)); packet.writeUInt16(world.portStart + channel); packet.writeUInt32(characterId); packet.writeUInt8(0); // Flag bit 1 set = korean popup? packet.writeUInt32(0); // Minutes left on Internet Cafe? client.sendPacket(packet); } PacketHandler.setHandler(0x0020, function (client, reader) { // Select VAC character with PIC if (!client.account) { client.disconnect('Trying to select character in VAC window (PIC) while not loggedin'); return; } var pic = reader.readString(); var characterId = reader.readUInt32(); var worldId = reader.readUInt32(); var macAddresses = reader.readString(); var deviceUID = reader.readString(); enterChannel(client, characterId, worldId); // Todo: Add check if the character is in this world AND from the same account }); PacketHandler.setHandler(0x000E, function (client, reader) { // Select VAC character without PIC if (!client.account) { client.disconnect('Trying to select character in VAC window while not loggedin'); return; } var characterId = reader.readUInt32(); var worldId = reader.readUInt32(); var macAddresses = reader.readString(); var deviceUID = reader.readString(); enterChannel(client, characterId, worldId); // Todo: Add check if the character is in this world AND from the same account });
//~ name c407 alert(c407); //~ component c408.js
const _ = require('lodash'); const profileData = { itemID: 284858585, title: 'Cologne Name', imagePath: 'https://picsum.photos/250/250', rating: 7.8, likesCount: 217, userID: 585858522, brand: { name: 'fake brand', internalURL: 'brand/brand-name', externalURL: 'http://www.brandwebsite.com', }, cost: [ { size: 8, units: 'ml', price: 20, }, { size: 100, units: 'ml', price: 100, } ], cost100ml: 100, buyLink: { path: 'path/to/buy', affID: '58595hghg', }, sampleLink: { path: 'path/to/sample', affID: '58595hghg', }, description: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum', discussionItems: [ { userId: 1234, first_name: 'first', last_name: 'last', voteCount: 10, itemId: 12421, text: 'Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum' }, { userId: 1234, first_name: 'first', last_name: 'last', voteCount: 10, itemId: 12421, text: 'Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum' }, { userId: 1234, first_name: 'first', last_name: 'last', voteCount: 10, itemId: 12421, text: 'Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum' }, ], accords: [ { id: 5757575, votes: 123, title: 'hey title yo', }, ], notes: { top: [ { id: 5757575, votes: 123, title: 'hey title yo', }, { id: 5757575, votes: 123, title: 'hey title yo', }, { id: 5757575, votes: 123, title: 'hey title yo', } ], middle: [ { id: 5757575, votes: 123, title: 'hey title yo', }, { id: 5757575, votes: 123, title: 'hey title yo', }, ], base: [ { id: 5757575, votes: 123, title: 'hey title yo', }, { id: 5757575, votes: 123, title: 'hey title yo', }, { id: 5757575, votes: 123, title: 'hey title yo', }, { id: 5757575, votes: 123, title: 'hey title yo', }, ], }, categories: [ { id: 157585, title: 'blah blah category', prefix: '', suffix: '', path: '/categories/blah-blah-category', }, { id: 157585, title: 'blah blah category', prefix: '', suffix: '', path: '/categories/blah-blah-category', }, { id: 157585, title: 'blah blah category', prefix: '', suffix: '', path: '/categories/blah-blah-category', }, ], }; /** * GET / * Home page. */ exports.index = (req, res) => { res.render('profile', { title: 'Profile', navigation: true, profileData: profileData, }); };
'use strict'; var mongoose = require('mongoose'), passport = require('passport'), Agent = mongoose.model('Agent'); exports.list = function(req, res) { var obj = {}; // set up //Agent.find() res.json(obj); }; exports.findOne = function(req, res) { var agentId = req.params.agentId; Agent.find(agentId, function(err, agent){ if(err) { console.log(err); } if(!agent) { console.log('No record'); } res.json(agent); }); };
const html = require('choo/html') const section = require('./section') const h1 = require('./h1') const list = require('./list') const a = require('./a') const choo = () => a({ href: 'https://github.com/yoshuawuyts/choo', content: 'choo' }) const electron = () => a({ href: 'https://electron.atom.io/', content: 'electron' }) const lens = () => a({ href: 'http://lens.elifesciences.org/about/', content: 'lens' }) const hyperdrive = () => a({ href: 'https://github.com/mafintosh/hyperdrive', content: 'hyperdrive' }) const searchindex = () => a({ href: 'https://github.com/fergiemcdowall/search-index', content: 'searchindex' }) const entries = [ html`<span>Science-focused JATS XML reader provided by ${lens()}.</span>`, html`<span>Distributed data sharing using Dat's ${hyperdrive()}.</span>`, html`<span>Fast local search index built on ${searchindex()}.</span>`, html`<span>Created using web technologies with ${choo()} and ${electron()}.</span>` ] const content = () => [ h1({ content: 'Technology', dark: true }), list({ entries: entries, dark: false }) ] module.exports = opts => section({ section: 'technology', dark: false, content: content() })
(function () { namespace("YE").Animate = YYC.Class({ Init: function (animation) { this.ye_anim = animation; this.ye_frames = YE.Collection.create(); }, Private: { ye_anim: null, ye_frames: null, ye_frameCount: 0, ye_duration: 0, ye_currentFrame: null, ye_currentFrameIndex: 0, ye_currentFramePlayed: 0 }, Public: { /** * 更新当前帧 * @param deltaTime 主循环的持续时间 */ update: function (deltaTime) { //判断当前帧是否播放完成, if (this.ye_currentFramePlayed >= this.ye_duration) { if (this.ye_currentFrameIndex >= this.ye_frameCount - 1) { //当前是最后一帧,则播放第0帧 this.ye_currentFrameIndex = 0; } else { //播放下一帧 this.ye_currentFrameIndex++; } //设置当前帧 this.setCurrentFrame(this.ye_currentFrameIndex); } else { //增加当前帧的已播放时间. this.ye_currentFramePlayed += deltaTime; } }, getCurrentFrame: function () { return this.ye_currentFrame; }, init: function () { this.ye_frames.addChilds(this.ye_anim.getFrames()); this.ye_duration = this.ye_anim.getDurationPerFrame(); this.ye_frameCount = this.ye_frames.getCount(); this.setCurrentFrame(0); }, setCurrentFrame: function (index) { this.ye_currentFrameIndex = index; this.ye_currentFrame = this.ye_frames.getChildAt(index); this.ye_currentFramePlayed = 0; } }, Static: { create: function (animationFrame) { return new this(animationFrame); } } }); }());
export default ngModule => { ngModule.run(addAddonsManipulator); function addAddonsManipulator(formlyConfig, formlyFoundationApiCheck) { var addonTemplate = require('./addons.html'); const addonChecker = formlyFoundationApiCheck.shape({ class: formlyFoundationApiCheck.string.optional, text: formlyFoundationApiCheck.string.optional }).strict.optional; const api = formlyFoundationApiCheck.shape({ templateOptions: formlyFoundationApiCheck.shape({ addonLeft: addonChecker, addonRight: addonChecker }) }); formlyConfig.templateManipulators.preWrapper.push(function(template, options) { if (options.type !== 'input' || (!options.templateOptions.addonLeft && !options.templateOptions.addonRight)) { return template; } formlyFoundationApiCheck.warn([api], [options]); return addonTemplate.replace('<formly-transclude></formly-transclude>', template); }); } };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _Preloader = require('./Preloader'); var _Preloader2 = _interopRequireDefault(_Preloader); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var System = function (_Component) { _inherits(System, _Component); function System(props) { _classCallCheck(this, System); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(System).call(this, props)); _this.state = { visible: false }; return _this; } _createClass(System, [{ key: 'showPreloader', value: function showPreloader() { this.setState({ visible: true }); } }, { key: 'hidePreloader', value: function hidePreloader() { this.setState({ visible: false }); } }, { key: 'render', value: function render() { var visible = this.state.visible; return _react2.default.createElement( 'div', { className: 'modal-wrapper', style: { display: visible ? 'block' : 'none' } }, _react2.default.createElement('div', { className: 'preloader-indicator-overlay' }), _react2.default.createElement( 'div', { className: 'preloader-indicator-modal' }, _react2.default.createElement(_Preloader2.default, { revert: true }) ) ); } }]); return System; }(_react.Component); exports.default = System;
//==================FLUX========================= var Reactor = require("client/js/reactor.js"); var Store = require("client/js/store"); //=============================================== var Form = require("client/js/views/form"); var Page = React.createClass({ displayName: "DriverRecoverPassword", propTypes: { device: React.PropTypes.string, children: React.PropTypes.node, route: React.PropTypes.object, history: React.PropTypes.object, params: React.PropTypes.object }, mixins: [Reactor.ReactMixin], getDataBindings() { //The order matter - the list need to be uptop , before the meta state return { formResetPWD: Store.getters.formResetPWD } }, getDefaultProps() { return { form: Immutable.fromJS({ POST: "/api/drivers/driver/reset_password", field: [ { id: "newPassword", type: "mirrorfield", subType: "text", title: ["New Password", "Confirm new Password"], required: true, htmlType: "password", getValidation:(fieldProps,validation,isValid)=> { console.log(fieldProps, validation, isValid); return mdx(validation.type,{ "mirrormatch": ()=> { return isValid ? null : { type: "error", message: "The confirm password does not match with the password" } } }); } } ] }) } }, onSubmit(isValid, formData, postURL,alrt) { if (isValid) { Store.actions.postForm({ target: "formResetPWD", URL: postURL, data: formData, onSuccess: ()=> { window.location.href = "/"; } }); } else { if (alrt) { Store.actions.alertStatus("formResetPWD", alrt.get("newPassword")); } else { let messageKey = (formData.newPassword === '') ? 'requiredField' : 'invalidPasswordField'; Store.actions.alertStatus("formResetPWD", { type: "error", message: initData.alert[messageKey] }); } } }, buildPage(props, state) { let _id = props.params.token; let _meta = state.formResetPWD.get("meta"); var className = cx({ "p-drivers-resetPWD": true }); return ( <div className={className}> <div className="v-block-title"> <h2 className="title"> Reset Password </h2> </div> <Form ref="form" alert={_meta.get("alert")} isLoading={_meta.get("isLoading")} device={props.device} form={props.form} onSubmit={this.onSubmit} id={_id}></Form> </div> ) }, render() { return this.buildPage(this.props, this.state) } }); module.exports = Page;
var mongoose = require('mongoose'), Schema = mongoose.Schema; var ThreadSchema = new Schema({ column: Number, color: String, }, {versionKey: false}); module.exports = mongoose.model('Thread', ThreadSchema);
var searchData= [ ['endin',['ENDIN',['../csoundCore_8h.html#aa97d83d75577cad84f8e2a4892207f72',1,'csoundCore.h']]], ['endop',['ENDOP',['../csoundCore_8h.html#a5d5fb12db6e5977c3ee6f70b93faaed2',1,'csoundCore.h']]] ];
'use strict'; require('should'); var sinon = require('sinon'); var workers = require('../lib/workers.js'); module.exports.addition = function(job, cb) { var spyPost = sinon.spy(job.anyfetchClient, "postDocument"); try { job.task.should.have.property('url'); job.task.should.have.property('identifier'); } catch(e) { return cb(e); } workers.addition(job, function(err) { try { spyPost.callCount.should.eql(1); spyPost.restore(); } catch(e) { return cb(e); } cb(err); }); }; module.exports.deletion = function(job, cb) { var spyPost = sinon.spy(job.anyfetchClient, "deleteDocumentByIdentifier"); try { job.task.should.be.type('string'); } catch(e) { return cb(e); } workers.deletion(job, function(err) { try { spyPost.callCount.should.eql(1); spyPost.restore(); } catch(e) { return cb(e); } cb(err); }); };
"use strict;" require("crisp-base"); require("crisp-create"); require("../src/EventJS"); module.exports = require("../test_/EventJS-utilPicker_test.js");
UTIL = { fire: function( func,funcname, args ) { var namespace = APP; // indicate your obj literal namespace here funcname = ( funcname === undefined ) ? 'init' : funcname; if ( func !== '' && namespace[ func ] && typeof namespace[ func ][ funcname ] == 'function' ) { namespace[ func ][ funcname ]( args ); } }, loadEvents: function() { var bodyId = document.body.id; // hit up common first. UTIL.fire( 'common' ); // do all the classes too. $.each( document.body.className.split( /\s+/ ), function( i, classnm ) { UTIL.fire( classnm ); UTIL.fire( classnm, bodyId ); }); UTIL.fire( 'common', 'finalize' ); } };
import Ember from 'ember'; import layout from '../templates/components/sticky-item'; let { computed, $, inject } = Ember; export default Ember.Component.extend({ layout, scrollWatcher: inject.service(), classNameBindings: ['isFixed:__ember-sticky-wrapper--sticky-item'], // when true, will insert a placeholder div before this component to // ensure that the flow does not change when the sticky item is absolutely // position. addPlaceholder: false, wrapperElement: computed('wrapper', function() { return $(this.get('wrapper')); }), // when there is no 'viewport' property, the window is used as the viewport viewportElement: computed('viewport', function() { let viewport = this.get('viewport'); return viewport && $(viewport); }), viewportTop: computed('viewportElement', function() { let element = this.get('viewportElement'); let top = 0; if (element) { top = element.offset().top; } return top; }), _startViewportWatcher() { let scrollWatcher = this.get('scrollWatcher'); let element = this.get('viewportElement'); let watcher; if (element) { watcher = scrollWatcher.startWatcher(element); } else { watcher = scrollWatcher.startWatcher(window); } this.set('viewportWatcher', watcher); }, _stopViewportWatcher() { let viewportWatcher = this.get('viewportWatcher'); let scrollWatcher = this.get('scrollWatcher'); scrollWatcher.stopWatcher(viewportWatcher); this.set('viewportWatcher', null); }, didInsertElement() { this._super(...arguments); this._startViewportWatcher(); let element = this.$(); let wrapperElement = this.get('wrapperElement'); let viewportTop = this.get('viewportTop'); let initialTop = element.offset().top - viewportTop; let initialBottom = wrapperElement.offset().top + wrapperElement[0].offsetHeight - viewportTop; this.set('initialTop', initialTop); this.set('initialBottom', initialBottom); }, willDestroyElement() { this._super(...arguments); this._stopViewportWatcher(); this.removePlaceholder(); }, isFixed: Ember.observer('viewportWatcher.scrollTop', function() { if (!this.$()) { return false; } let initialTop = this.get('initialTop'); let initialBottom = this.get('initialBottom'); let scrollTop = this.get('viewportWatcher.scrollTop'); if (scrollTop >= initialTop && scrollTop < initialBottom) { let element = this.$(); let height = element[0].offsetHeight; let elementTop = initialBottom-height; scrollTop = Math.min(scrollTop, elementTop); this.$().css({ width: '100%', position: 'absolute', top: scrollTop }); this.updatePlaceholder(); } else { this.$().css({ width: 'auto', position: 'initial', top: 'auto' }); this.removePlaceholder(); } }), updatePlaceholder() { if (!this.get('addPlaceholder')) { return; } if (this._placeholder) { return; } this._placeholder = `__ember-sticky-wicket__placeholder-${Ember.uuid()}`; let height = this.$().height(); let placeholderDiv = `<div id="${this._placeholder}" style="height:${height}px;"></div>`; this.$().before(placeholderDiv); }, removePlaceholder() { if (!this._placeholder) { return; } Ember.$(`#${this._placeholder}`).remove(); this._placeholder = false; } });
function validateData(){ if(document.getElementById("inputUsername").value.length<5){ var error = "Note: Username must be at least 5 characters long"; var errorStr = error.fontcolor("red"); document.getElementById("usernameDirections").innerHTML=errorStr; } } function switchInToUp(x){ var x = document.getElementById('page1'); var y = document.getElementById("page2"); x.style.display = 'block'; y.style.display = 'none'; } function switchUpToIn(x){ var x = document.getElementById('page1'); var y = document.getElementById("page2"); /*y.style.-webkit-transition = 'width 2s';*/ y.style.display = 'block'; x.style.display = 'none'; } function switchButton(){ var z = document.getElementById("signInSwitchButton"); var t = document.getElementById("b2"); z.style.display=''; t.style.display=''; }
var vow = require('vow'), path = require('path'), chai = require('chai'), Mocha = require('mocha'), async = require('async'), fs = require('fs'), istanbul = require('istanbul'), collector = new istanbul.Collector(), report = istanbul.Report.create('text-summary'), logger = new (require('enb/lib/logger'))(); /** * @exports */ exports.run = function(targets, root, coverageFile) { var defer = vow.defer(), withCoverage = !!coverageFile, coverageVar = '__coverage__'; // Setup global context for tests global.chai = chai; global.expect = chai.expect; global.assert = chai.assert; chai.should(); if (withCoverage) { global[coverageVar] = {}; if (fs.existsSync(coverageFile)) { collector.add(JSON.parse(fs.readFileSync(coverageFile, 'utf-8'))); } } // For every test async.mapSeries(Object.keys(targets), function(spec, next) { var basename = path.basename(spec), target = path.join(spec, basename + '.spec.js'), // path to bundled spec.js mocha = new Mocha({ ui : 'bdd' }), // new Mocha context suite = mocha.suite, source = path.relative(root, targets[spec]), // path to original source self = this; global.modules = require('ym').create(); suite.emit('pre-require', global, target, mocha); try { require(path.join(root, target)); } catch (e) { console.error(e); } modules.require('spec', function() { mocha.run(function(failures) { if (failures) { logger.logErrorAction('spec', target); defer.reject(); } else { logger.logAction('spec', target); defer.resolve(); } suite.emit('post-require', global, target, mocha); withCoverage && collector.add(global[coverageVar]); next(); }); }); }, function(){ if (withCoverage) { fs.writeFileSync( coverageFile, JSON.stringify(collector.getFinalCoverage()), 'utf-8' ); } }); };
const urls = require('../../../../../../lib/urls') function renderProjects(req, res) { const { company, returnUrl, dnbRelatedCompaniesCount } = res.locals res.locals.title = `Investments - ${company.name} - Companies` res.render('companies/apps/investments/projects/views/list', { props: { company, breadcrumbs: [ { link: urls.dashboard(), text: 'Home' }, { link: urls.companies.index(), text: 'Companies', }, { link: urls.companies.detail(company.id), text: company.name }, { text: 'Investment' }, ], returnUrl, dnbRelatedCompaniesCount, }, }) } module.exports = renderProjects
/** * Created by 斌 on 2017/4/15. */ const api = require('express').Router() const Product = require('../models/product') /** * type 1-7 * flag 1:date, 2:sales, 3:price * sort 1:asc, 2:desc */ function query ({flag = 1, sort = 1} = {}) { let s1, s2 switch (+flag) { case 1: s1 = 'date' break case 2: s1 = 'sales' break case 3: s1 = 'discounted' break default: s1 = 'date' } s2 = +sort === 1 ? '' : '-' return s2 + s1 } api.get('/query', (req, res, next) => { let params = req.query let limit = +params.limit || 0 if (!+params.flag || !+params.sort) { return res.json({code: -1, msg: 'invalid params'}) } let s = query(params) if (!params.type || +params.type <= 0 || +params.type > 7) { Product .find() .select('-introduce -sales -stock') .sort(s) .limit(limit) .exec(handler) return } Product .find({_type: +params.type}) .select('-introduce -sales -stock') .sort(s) .limit(limit) .exec(handler) function handler (err, docs) { if (err) { return res.json({code: 2, msg: '数据库出错', detail: err}) } return res.json({code: 1, msg: 'success', result: docs}) } }) api.get('/query/discount', (req, res, next) => { let limit = +req.query.limit || 0 Product .find() .select('-introduce -sales -stock') .$where(function () { return this.discounted <= this.price }) .limit(limit) .exec((err, docs) => { if (err) { return res.json({code: 2, msg: '数据库出错', detail: err}) } if (!docs || !docs.length) { return res.json({code: 1, msg: 'success', result: []}) } res.json({code: 1, msg: 'success', result: docs}) }) }) /** * 查询某个商品 */ api.get('/:sku', (req, res, next) => { let sku = req.params.sku if (!sku) { return res.json({code: -1, msg: 'need sku'}) } Product.findOne({sku: sku}) .select('-sales -stock') .exec((err, doc) => { if (err) { return res.json({code: 2, msg: '数据库出错', detail: err}) } if (!doc) { return res.json({code: -1, msg: `invalid sku, there is no pro with sku =${sku}`}) } return res.json({code: 1, msg: 'success', result: doc}) }) }) module.exports = api
angular.module('starter') .directive('pickProfile', function ($state, $ionicActionSheet, $rootScope) { return { templateUrl: 'app/main/choose-a-profile.html', link: function (scope) { var filepath; scope.setEmployee = function () { scope.setEmployeeDetails(); scope.profilePopup.close(); } scope.setEmployer = function () { scope.setEmployerDetails(); scope.profilePopup.close(); } } }; })
this["TydelLogger"] = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports) { module.exports = function tydelLogger(model) { var cacheByMethod = {}; model.on('method:call', function (event) { cacheByMethod[event.path.join('.')] = model.toJS(); }); model.on('method:change', function (event) { var p = event.path.join('.'); var prev = cacheByMethod[p]; var next = model.toJS(); if (typeof console.group === 'function') { console.group(p); } console.log('%cprevious state', 'color: #9e9e9e; font-weight: bold;', prev); console.log('%c↳current state', 'color: #4cAf50; font-weight: bold;', next); if (typeof console.groupEnd === 'function') { console.groupEnd(); } }); } /***/ } /******/ ]);
var dict = require('./dict.js'); module.exports.translate = function (arubedo) { 'use strict'; var value = ''; if (!arubedo) { return ''; } else { return arubedo.split('').map(function (element, index, array) { value = dict[element]; return value ? value : element; }).join(''); } };
const co = require('co'); const fs = require('fs'); function logic(data) { return new Promise((resolve, reject) => { try { fs.writeFile('./output.json', JSON.stringify(data), function (err) { if (err) { reject(err); } else { resolve('File generated as output.json'); } }); } catch (e) { reject(e); } }); } module.exports = { saveDataToFile: logic };
import React from 'react'; import LanguageIcon from './LanguageIcon'; export const symbols = { 'LanguageIcon': <LanguageIcon /> };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ErrorCategory_1 = require("./ErrorCategory"); var UnknownException_1 = require("./UnknownException"); var InternalException_1 = require("./InternalException"); var ConfigException_1 = require("./ConfigException"); var ConnectionException_1 = require("./ConnectionException"); var InvocationException_1 = require("./InvocationException"); var FileException_1 = require("./FileException"); var BadRequestException_1 = require("./BadRequestException"); var UnauthorizedException_1 = require("./UnauthorizedException"); var ConflictException_1 = require("./ConflictException"); var NotFoundException_1 = require("./NotFoundException"); var UnsupportedException_1 = require("./UnsupportedException"); var InvalidStateException_1 = require("./InvalidStateException"); var ApplicationExceptionFactory = /** @class */ (function () { function ApplicationExceptionFactory() { } ApplicationExceptionFactory.create = function (description) { if (description == null) throw new Error("Description cannot be null"); var error = null; var category = description.category; var code = description.code; var message = description.message; var correlationId = description.correlation_id; // Create well-known exception type based on error category if (ErrorCategory_1.ErrorCategory.Unknown == category) error = new UnknownException_1.UnknownException(correlationId, code, message); else if (ErrorCategory_1.ErrorCategory.Internal == category) error = new InternalException_1.InternalException(correlationId, code, message); else if (ErrorCategory_1.ErrorCategory.Misconfiguration == category) error = new ConfigException_1.ConfigException(correlationId, code, message); else if (ErrorCategory_1.ErrorCategory.NoResponse == category) error = new ConnectionException_1.ConnectionException(correlationId, code, message); else if (ErrorCategory_1.ErrorCategory.FailedInvocation == category) error = new InvocationException_1.InvocationException(correlationId, code, message); else if (ErrorCategory_1.ErrorCategory.FileError == category) error = new FileException_1.FileException(correlationId, code, message); else if (ErrorCategory_1.ErrorCategory.BadRequest == category) error = new BadRequestException_1.BadRequestException(correlationId, code, message); else if (ErrorCategory_1.ErrorCategory.Unauthorized == category) error = new UnauthorizedException_1.UnauthorizedException(correlationId, code, message); else if (ErrorCategory_1.ErrorCategory.Conflict == category) error = new ConflictException_1.ConflictException(correlationId, code, message); else if (ErrorCategory_1.ErrorCategory.NotFound == category) error = new NotFoundException_1.NotFoundException(correlationId, code, message); else if (ErrorCategory_1.ErrorCategory.InvalidState == category) error = new InvalidStateException_1.InvalidStateException(correlationId, code, message); else if (ErrorCategory_1.ErrorCategory.Unsupported == category) error = new UnsupportedException_1.UnsupportedException(correlationId, code, message); else { error = new UnknownException_1.UnknownException(); error.category = category; error.status = description.status; } // Fill error with details error.details = description.details; error.setCauseString(description.cause); error.setStackTraceString(description.stack_trace); return error; }; return ApplicationExceptionFactory; }()); exports.ApplicationExceptionFactory = ApplicationExceptionFactory; //# sourceMappingURL=ApplicationExceptionFactory.js.map
Array.prototype.mapAsync = require('./mapAsync'); /** * 遍歷 dict * [{ * pcode: string, * chinese: string, * english: string, * history[]: { * lnndate: string, * lser: string, * data: any * } * }] */ module.exports = async (asyncFunc, dict) => await dict.mapAsync(async (dictItem, counter) => { if(!(counter % 100)) process.stdout.write('.'); if(counter === dict.length - 1) process.stdout.write('\n'); const pcode = dictItem.pcode; const result = { pcode: dictItem.pcode, chinese: await asyncFunc(dictItem.chinese, pcode, 'chinese') }; if(dictItem.english) result.english = await asyncFunc(dictItem.english, pcode, 'english'); result.history = await dictItem.history.mapAsync(async hisItem => { const data = await asyncFunc(hisItem.data, pcode, 'history', hisItem.lnndate, hisItem.lser); const result = Object.assign({}, hisItem, {data}); return result; }); return result; }) ;
if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null || this === undefined) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { var kValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; }
'use strict'; // ------- Imports ------------------------------------------------------------- const changeCase = require('change-case'); const logger = require('../../config/logger'); // ------- Internal imports ---------------------------------------------------- // Blink Libs. const RabbitMQBroker = require('../lib/brokers/RabbitMQ/RabbitMQBroker'); const RedisConnectionManager = require('../lib/RedisConnectionManager'); // Queues. const CustomerIoGambitBroadcastQ = require('../queues/CustomerIoGambitBroadcastQ'); const CustomerIoSmsStatusActiveQ = require('../queues/CustomerIoSmsStatusActiveQ'); const QuasarCustomerIoEmailActivityQ = require('../queues/QuasarCustomerIoEmailActivityQ'); const QuasarCustomerIoEmailUnsubscribedQ = require('../queues/QuasarCustomerIoEmailUnsubscribedQ'); const TwilioSmsInboundGambitRelayQ = require('../queues/TwilioSmsInboundGambitRelayQ'); const TwilioSmsOutboundErrorRelayQ = require('../queues/TwilioSmsOutboundErrorRelayQ'); const TwilioSmsOutboundStatusRelayQ = require('../queues/TwilioSmsOutboundStatusRelayQ'); // ------- Class --------------------------------------------------------------- class BlinkApp { constructor(config) { this.config = config; this.queues = []; this.broker = false; // Attach Public API functions to object context. this.start = this.start.bind(this); this.stop = this.stop.bind(this); } // ------- Public API ------------------------------------------------------- async start() { // Setup connection to message broker server. this.broker = await this.setupBroker(); // Setup connection to redis. this.redis = await this.setupRedis(); // Assert queues and add them to queue registry. // IMPORTANT: if the broker goes away and returns with no queues, // we will be able to recover the connection automatically, // but queues will not be created. // Full topology is only asserted on app bootstrap. this.queues = await this.setupQueues(BlinkApp.discoverQueueClasses()); // Log success. logger.info('Blink app is loaded.', { meta: { code: 'success_blink_app_loaded', }, }); // TODO: Error handling? return true; } async stop() { // TODO: log. // Flush queues. this.queues = []; await this.broker.disconnect(); await this.redis.disconnect(); return true; } // ------- Internal machinery ----------------------------------------------- async setupBroker() { // Optional: tag connection for easier debug. const clientDescription = { // TODO: add dyno name. name: this.config.app.name, version: this.config.app.version, env: this.config.app.env, }; // Now only RabbitMQ is supported. const broker = new RabbitMQBroker(this.config.amqp, clientDescription); // Establish connection or perform authorization. const result = await broker.connect(); if (!result) { // Do what? } // Return connected broker. return broker; } async setupRedis() { // Now only RabbitMQ is supported. const redis = new RedisConnectionManager(this.config.redis); // Establish connection or perform authorization. const result = await redis.connect(); if (!result) { // TODO: Handle case when redis doesn't connect. } // Return connected redis. return redis; } async setupQueues(queueClasses) { // TODO: This is too confusing. KISS. const queueMappingPromises = queueClasses.map(async (queueClass, i) => { // It's not possible to just say `new queueClass()`, JS would think // we're trying to construct class called 'queueClass'. // To construct a class dynamically, it's possible `new` its reference // stored as an array element: `new queueClasses[i]`. const queue = new queueClasses[i](this.broker); // Ensure the queue is present with expected settings. // Todo: parse result. await queue.create(); // Registry key makes it more convenient to get queues from the // registry using Node's object destructing: // const { fetchQ } = this.blink.queues; const registryKey = BlinkApp.generateQueueRegistryKey(queueClass); // Return an item of 2D array for further transformation. return [registryKey, queue]; }); // Wait for all queues to be asserted. const queueRegistryArray = await Promise.all(queueMappingPromises); // Transform resolved promises array to an object. // TODO: Again, too confusing, KISS. const queueRegistry = {}; queueRegistryArray.forEach((mapping) => { const [key, value] = mapping; queueRegistry[key] = value; }); return queueRegistry; } /** * Returns a queue with a given name from queue registry. * * This method perform search on all queues. * It shouldn't be used in most cases, you can get the queue * from the registry by its mapping key, example * * ``` * const { fetchQ } = blink.queues; * ``` * @param {String} name The name of the queue to search * @return {Queue|undefined} The queue found or undefined */ getQueueByName(name) { return Object.values(this.queues).find(queue => queue.name === name); } // ------- Static helpers --------------------------------------------------- static discoverQueueClasses() { // TODO: register them from workers, bottom-up approach. return [ CustomerIoGambitBroadcastQ, CustomerIoSmsStatusActiveQ, QuasarCustomerIoEmailActivityQ, QuasarCustomerIoEmailUnsubscribedQ, TwilioSmsInboundGambitRelayQ, TwilioSmsOutboundErrorRelayQ, TwilioSmsOutboundStatusRelayQ, ]; } static generateQueueRegistryKey(queueClass) { return this.getQueueRegistryKey(queueClass.name); } static getQueueRegistryKey(queueName) { return changeCase.camelCase(queueName); } } // ------- Exports ------------------------------------------------------------- module.exports = BlinkApp; // ------- End -----------------------------------------------------------------
// import 'babel-core/polyfill'; import path from 'path'; import express from 'express'; import mongoose from 'mongoose'; import routes from './routes'; import seed from './seed'; const port = process.env.PORT || 8080; const server = express(); // server.use(express.static(path.join(__dirname, 'public'))); server.set('appPath', path.join(__dirname, 'public')); routes(server); server.get('/api/*', function(req, res) { res.status(404).end(); }); // error handler server.use((err, req, res, next) => { if (err.status && Array.isArray(err.errors)) { return res.status(err.status).json(err.errors.map((e) => e.message)); } else if(err instanceof Error){ return res.status(500).send(err); } next(err); }); mongoose.connection.open('mongodb://localhost/jsremoteconf-2016'); seed(); server.listen(port, () => { /* eslint-disable no-console */ console.log(`The server is running at http://localhost:${port}/`); });
import React, { Component, PropTypes } from 'react' import axios from 'axios' import { connect } from 'react-redux'; import store from './store' class Item extends Component { constructor(props) { super(props); this.state = { items: [] }; } componentDidMount() { axios.post('https://colppy.local/lib/frontera2/service.php', { "auth": { "usuario": "?", "password": "?" }, "service": { "provision": "inventario", "operacion": "?" }, "options": { }, "parameters": { } }, { headers: { "Content-Type": "application/x-www-form-urlencoded" } } ) .then(res => { const items = res.data.data.children.map(obj => obj.data); this.setState({ items }); console.log(items); }); } render() { return ( <div className="App"> <h1>Items</h1> </div> ); } } export default Item; Item.PropTypes = { }
/* class-Module ------------------------------------------------------------------------------*/ var WAITING = 0; var LOADING = 1; var LOADED = 2; var READY = 3; var modules = {}; var moduleData; function Module (uri) { Event.apply(this, arguments); this.uri = uri || ''; this.id = uri2Id(uri); this.dependencies = null; this.exports = null; this.status = WAITING; modules[this.id] = this; } // inherit prototype from Event inherit(Event, Module); Module.modules = modules; Module.prototype.set = function (dataToset) { for (toSetName in dataToset) { var toSetValue = dataToset[toSetName]; if (toSetValue) { this[toSetName] = toSetValue; } } }; Module.prototype.load = function () { var dependencies = this.dependencies; var uri = this.uri; var id = this.id; var module = this; this.status = LOADING; loadScript(uri, saveAfterLoad); // When `define` has run, then script containing `define` // will immediately fire the event `onload`, which will call // the function below. The `define` will set the `moduleData` // at the end of execution. when `onload` accurs, we can use // the function below to get moduleData and get information // such as `uri` by using closure, then we can composite with those // information and moduleData together. function saveAfterLoad () { if (moduleData) { module.set(moduleData); moduleData = null; module._remains_ = module.dependencies.length; module.status = LOADED; module.emit('loaded', this); module.loadDependencies(); } } }; Module.prototype.loadDependencies = function () { var dependencies = this.dependencies; var cwd = path.dirname(this.uri); var module = this; if (dependencies.length === 0) { tryToExecuteCurrentModule(); return; } for (var i = dependencies.length -1; i >= 0; i--) { var dependency = dependencies[i]; var dependencyUri = path2Uri(cwd, dependency); var dependencyId = uri2Id(dependencyUri); var depenModule = modules[dependencyId]; // replace the dependency's path in array with its real id dependencies[i] = dependencyId; // If dependency has been already created if(depenModule) { if (depenModule.status === READY) { tryToExecuteCurrentModule(); } else { // try to execute current module while dependendy has ready depenModule.on('ready', tryToExecuteCurrentModule); } continue; } // Dependency has not been not loaded, then create it. depenModule = new Module(dependencyUri); depenModule.load(); depenModule.on('ready', tryToExecuteCurrentModule); } function tryToExecuteCurrentModule(depenModule) { if (module._remains_ > 0) module._remains_--; module.tryToExecute(); if (depenModule) { depenModule.off('ready', tryToExecuteCurrentModule); } } }; Module.prototype.tryToExecute = function () { var _remains_ = this._remains_; var factory = this.factory; var cwd = path.dirname(this.uri); var module = this; if (_remains_ === 0 && factory) { var exports; exports = factory(require, module.exports = {}, module); module.exports = exports ? exports : module.exports; module.status = READY; module.emit('ready', module); delete module.factory; } function require (pathName) { var uri = path2Uri(cwd, pathName); return modules[uri2Id(uri)].exports; } }; Module.init = function () { var cobiaScript = getCobiaScriptNode(); var mainScriptPath = cobiaScript.getAttribute('data-main'); var mainUri = path2Uri(cwd, mainScriptPath); var mainModule = new Module(mainUri); mainModule.load(); };
// // drive/notebook functions - assumes gapi is loaded in window, user is logged in, and library is initialized // // callback is passed 'response', notebook is in 'response.result' export function downloadNotebook(notebookId, callback) { const path = 'https://www.googleapis.com/drive/v3/files/' + notebookId + '?alt=media'; const method = 'GET'; window.gapi.client.request({'path': path, 'method': method}).then(callback); } export function uploadNotebook(notebook, notebookId, callback) { const params = { "uploadType": "media" } const method = 'PATCH' const path = 'https://www.googleapis.com/upload/drive/v3/files/' + notebookId window.gapi.client.request({'path': path, 'method': method, 'body': notebook, 'params': params}).then(callback) } // callback is passed 'response', new notebook id is in 'response.result.id' export function createNotebook(name, callback) { // need to check that files with name doesn't alread exist, or should that be done someplace else??? const metaData = { "name": name, "mimeType": "application/json" } const method = 'POST' const path = 'https://www.googleapis.com/drive/v3/files' window.gapi.client.request({'path': path, 'method': method, 'body': metaData}).then(callback) } // callback is passed 'response', non trashed json files metaData are stored in 'response.result.files' export function getFiles(query, callback) { const method = 'GET' const path = 'https://www.googleapis.com/drive/v3/files' const params = { q: query } window.gapi.client.request({'path': path, 'method': method, 'params': params}).then(callback) }
import React from 'react'; import {Link} from 'react-router'; class Navbar extends React.Component { render() { return <div className="app-navbar"> {this.props.links.map((link, idx) => { let props = { to: link.path, className: 'app-navbar-item-link' }; if (document.location.pathname == link.path) { props.className += ' app-navbar-item-link__active'; } return <div key={idx} className="app-navbar-item"> <Link {...props}>{link.label}</Link> </div>; })} </div>; } } Navbar.propTypes = { links: React.PropTypes.array.isRequired }; export default Navbar;
const debounce = require('lodash/debounce'); const queue = []; function insertScriptTags($) { while (queue.length) { const src = queue.shift(); if (!$(`script[src="${src}"]`).length) { const script = document.createElement('script'); script.type = 'text/javascript'; script.src = src; document.head.appendChild(script); } } } module.exports = ($) => { const debouncedScriptTagsInsert = debounce(insertScriptTags, 500); $(document).on('warpjs-add-action-plugin', function(e) { queue.push(e.detail.href); debouncedScriptTagsInsert($); }); };
/** * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> * Build: `lodash modularize exports="amd" -o ./compat/` * Copyright 2012-2014 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.6.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ define(['../strings/escapeRegExp'], function(escapeRegExp) { /** Used for native method references */ var objectProto = Object.prototype; /** Used to resolve the internal `[[Class]]` of values */ var toString = objectProto.toString; /** Used to detect if a method is native */ var reNative = RegExp('^' + escapeRegExp(toString) .replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Native method shortcuts */ var fnToString = Function.prototype.toString; /** * Checks if `value` is a native function. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. */ function isNative(value) { return typeof value == 'function' && reNative.test(fnToString.call(value)); } return isNative; });
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2018 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Returns a Random element from the array. * * @function Phaser.Utils.Array.GetRandom * @since 3.0.0 * * @param {array} array - The array to select the random entry from. * @param {integer} [startIndex=0] - An optional start index. * @param {integer} [length=array.length] - An optional length, the total number of elements (from the startIndex) to choose from. * * @return {*} A random element from the array, or `null` if no element could be found in the range given. */ var GetRandom = function (array, startIndex, length) { if (startIndex === undefined) { startIndex = 0; } if (length === undefined) { length = array.length; } var randomIndex = startIndex + Math.floor(Math.random() * length); return (array[randomIndex] === undefined) ? null : array[randomIndex]; }; module.exports = GetRandom;
"use strict"; /** * Physics rigid body. */ function Body(geometry) { /** * Random ID to identify body */ this.id = -1; /** * Geometry of this physics body. */ this.geometry = geometry; /** * Indicates other bodies can collide with this one. */ this.collidable = true; /** * Static bodies do not move, can be used to create walls. */ this.isStatic = true; /** * Acceleration of the body. */ this.acceleration = new Vector3(0, 0, 0); /** * Position of the body, affected by speed. */ this.position = new Vector3(0, 0, 0); /** * Speed of the body, affected by acceleration. */ this.speed = new Vector3(0, 0, 0); /** * Indicates collision directions. */ this.isColliding = new Vector3(0, 0, 0); } /** * Set indentifier of the body. */ Body.prototype.setId = function(value) { this.id = value; }; /** * Get indentifier of the body. */ Body.prototype.getId = function() { return this.id; }; /** * Updates body state, updates the position, speed and acceleration of the body. * * Checks for collisions with other bodies, and applies world global effects to the body. */ Body.prototype.update = function(world) { if(world === undefined) { return; } if(!this.isStatic) { this.speed.add(world.acceleration); this.speed.add(this.acceleration); this.acceleration.mul(world.friction); this.speed.mul(world.friction); this.speed.roundCloseToZero(); this.isColliding.set(0, 0, 0); //Collision on X axis for(var i = 0; i < world.body.length; i++) { if(this.getId() !== world.body[i].getId()) { if(this.geometry.willCollide(new Vector3(this.speed.x, 0, 0), world.body[i].getGeometry())) { this.isColliding.x = 1; if(this.speed.x < 0) { this.geometry.position.x = (world.body[i].getGeometry().position.x - world.body[i].getGeometry().ori.x + world.body[i].getGeometry().size.x) + this.geometry.ori.x; } else { this.geometry.position.x = (world.body[i].getGeometry().position.x - world.body[i].getGeometry().ori.x) - this.geometry.size.x + this.geometry.ori.x; } this.speed.x = 0; } } } //Collision on Y axis for(var i = 0; i < world.body.length; i++) { if(this.getId() !== world.body[i].getId()) { if(this.geometry.willCollide(new Vector3(0, this.speed.y, 0), world.body[i].getGeometry())) { this.isColliding.y = 1; if(this.speed.y < 0) { this.geometry.position.y = (world.body[i].getGeometry().position.y - world.body[i].getGeometry().ori.y + world.body[i].getGeometry().size.y) + this.geometry.ori.y; } else { this.geometry.position.y = (world.body[i].getGeometry().position.y - world.body[i].getGeometry().ori.y) - this.geometry.size.y + this.geometry.ori.y; } this.speed.y = 0; } } } //Collision on Z axis for(var i = 0; i < world.body.length; i++) { if(this.getId() !== world.body[i].getId()) { if(this.geometry.willCollide(new Vector3(0, 0, this.speed.z), world.body[i].getGeometry())) { this.isColliding.z = 1; if(this.speed.z < 0) { this.geometry.position.z = (world.body[i].getGeometry().position.z - world.body[i].getGeometry().ori.z + world.body[i].getGeometry().size.z) + this.geometry.ori.z; } else { this.geometry.position.z = (world.body[i].getGeometry().position.z - world.body[i].getGeometry().ori.z) - this.geometry.size.z + this.geometry.ori.z; } this.speed.z = 0; } } } } this.geometry.position.add(this.speed); this.position = this.geometry.position; }; /** * Set as static body. */ Body.prototype.setStatic = function(value) { this.isStatic = value; }; /** * Get body geometry. */ Body.prototype.getGeometry = function() { return this.geometry; }; /** * Set if body is collidable. */ Body.prototype.setCollidable = function(collidable) { this.collidable = collidable; }; Body.prototype.toString = function() { return "Body (Position:" + this.position.toString() + ", Speed:" + this.speed.toString() + ", Acceleration:"+this.acceleration.toString() +")"; };
module.exports = function(gulp) { var colors = require('chalk'); var desc = require('./desc'); desc('help', 'List the available tasks'); var fn = function(done) { var filter = function(inc) { return function(n) { var hasDash = n.search(/[-_:]/) !== -1; return inc && hasDash || !inc && !hasDash; }; }, header = function(text) { console.log(''); console.log(colors.gray(text)); console.log('------------------------------'); }; var k = Object.keys(gulp.tasks).sort(); if (k.length > 0) { header('Main Tasks'); k.filter(filter(false)).forEach(function(name) { var d = desc(name); if (d) d = ' - ' + d; console.log(' ' + colors.cyan(name) + d); }); header('Sub Tasks'); k.filter(filter(true)).forEach(function(name) { var d = desc(name); if (d) d = ' - ' + d; console.log(' ' + name + d); }); } else { console.log('No tasks defined. Add one to your gulpfile.js'); } console.log(''); done(); }; gulp.task('help', fn); };
angular.module('Aggie') .controller('VisualizationController', [ '$scope', function($scope) { $scope.testing = "Controller Test"; } ]);
'use strict'; angular.module('admin').factory('Concepts', ['$resource', function ($resource) { return $resource('concepts/:projectId', { projectId: '@_id' }, { update: { method: 'PUT' } }); } ]);
services.factory('UploadService', function($q, $http){ var service = { uri: null, sendURI: function(uri){ service.uri = uri; var d = $q.defer(); $http.post('/uri', { uri: uri }, { withCredentials: true }).success(function(data){ d.resolve(data); }).error(function(data){ d.reject(data); console.log('error parsing article', data); }); return d.promise; } }; return service; });
/*! * Moajs Middle * Copyright(c) 2015-2019 Alfred Sang <shiren1118@126.com> * MIT Licensed */ module.exports = function (req, res, next) { if(req.method.toLowerCase() == 'head'){ console.log('[ALIYUN.COM LOG]: SLB health checking....OK...'); return res.sendStatus(200); } next(); };
import ImageFallback from '@/common/directives/cd-img-fallback'; describe('Image fallback', () => { afterEach(() => { sinon.restore(); }); it('should set the src to fallback on error', () => { // ARRANGE const bindingMock = { value: { src: 'https://s3-eu-west-1.amazonaws.com/zen-dojo-images/foo.png', fallback: '../assets/avatars/bar.png', }, }; const elMock = { addEventListener: sinon.stub(), style: {}, }; let errorCb = () => {}; let loadCb = () => {}; elMock.addEventListener.withArgs('error').callsFake((eventName, cb) => { errorCb = cb; }); elMock.addEventListener.withArgs('load').callsFake((eventName, cb) => { loadCb = cb; }); // ACT ImageFallback.bind(elMock, bindingMock); // ASSERT expect(elMock.style.visibility).to.equal('hidden'); expect(elMock.src).to.equal(bindingMock.value.src); errorCb(); expect(elMock.src).to.equal(bindingMock.value.fallback); loadCb(); expect(elMock.style.visibility).to.equal('visible'); }); it('should only try set fallback src once', () => { // ARRANGE const bindingMock = { value: { src: 'https://s3-eu-west-1.amazonaws.com/zen-dojo-images/foo.png', fallback: '../assets/avatars/bar.png', }, }; let srcSetCallCount = 0; let srcValue; const elMock = { addEventListener: sinon.stub(), style: {}, get src() { return srcValue; }, set src(val) { srcSetCallCount += 1; srcValue = val; }, }; let errorCb = () => {}; elMock.addEventListener.withArgs('error').callsFake((eventName, cb) => { errorCb = cb; }); // ACT ImageFallback.bind(elMock, bindingMock); // ASSERT expect(srcSetCallCount).to.equal(1); errorCb(); expect(srcSetCallCount).to.equal(2); expect(elMock.src).to.equal(bindingMock.value.fallback); errorCb(); expect(srcSetCallCount).to.equal(2); expect(elMock.src).to.equal(bindingMock.value.fallback); }); });
'use strict' var Renderer = function () { if (!(this instanceof Renderer)) { return new Renderer() } this.reset() } Renderer.prototype.reset = function () { this.flow = { connections: [], processes: {}, exports: [] } } /** * * Called from the fbpParser * */ Renderer.prototype.parseComponentString = function (component, node) { var m = component.split(':') if (m.length === 1) { node.component = component } else { node.component = m.shift() node.metadata = m } return node } Renderer.prototype.touchNode = function (/* processName */) { } Renderer.prototype.addNode = function (c) { this.flow.processes[c.process] = { component: c.component } if (c.metadata) { this.flow.processes[c.process].metadata = { routes: c.metadata } } } Renderer.prototype.addContext = function (/* process, in_port, context */) { } Renderer.prototype.addProvider = function (/* provider */) { /* if (!this.flow.providers) this.flow.providers = []; this.flow.providers.push(provider); */ } Renderer.prototype.addMeta = function (/* name, value */) { // this.flow[name] = value; } Renderer.prototype.addExport = function (e) { this.flow.exports.push({ 'private': [ e.process, e.port ].join('.').toLowerCase(), 'public': e.name.toLowerCase() }) } Renderer.prototype.addLink = function (link) { var connection = {} connection.tgt = { process: link.target, port: link.in.toLowerCase() } if (undefined !== link.targetIndex) { connection.tgt.index = link.targetIndex } if (link.source) { connection.src = { process: link.source, port: link.out.toLowerCase() } if (undefined !== link.sourceIndex) { connection.src.index = link.sourceIndex } } if (typeof link.data !== 'undefined') { connection.data = link.data } this.flow.connections.push(connection) } Renderer.prototype.fbpdoc = function (/* params */) { } Renderer.prototype.getFlow = function () { return JSON.parse(JSON.stringify(this.flow)) } Renderer.prototype.toJSON = function () { return JSON.stringify(this.flow, null, 2) } module.exports = Renderer
describe("Player", function() { var player; var song; beforeEach(function() { player = new Player(); song = new Song(); }); it("should be able to play a Song", function() { player.play(song); expect(player.currentlyPlayingSong).toEqual(song); //demonstrates use of custom matcher expect(player).toBePlaying(song); }); describe("when song has been paused", function() { beforeEach(function() { player.play(song); player.pause(); }); it("should indicate that the song is currently paused", function() { expect(player.isPlaying).toBeFalsy(); // demonstrates use of 'not' with a custom matcher expect(player).not.toBePlaying(song); }); it("should be possible to resume", function() { player.resume(); expect(player.isPlaying).toBeTruthy(); expect(player.currentlyPlayingSong).toEqual(song); }); }); // demonstrates use of spies to intercept and test method calls it("tells the current song if the user has made it a favorite", function() { spyOn(song, 'persistFavoriteStatus'); player.play(song); player.makeFavorite(); expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true); }); //demonstrates use of expected exceptions describe("#resume", function() { it("should throw an exception if song is already playing", function() { player.play(song); expect(function() { player.resume(); }).toThrowError("song is already playing"); }); }); });
/*! * Print button for Buttons and DataTables. * 2015 SpryMedia Ltd - datatables.net/license */ (function( factory ){ if ( typeof define === 'function' && define.amd ) { // AMD define( ['jquery', 'datatables.net', 'datatables.net-buttons'], function ( $ ) { return factory( $, window, document ); } ); } else if ( typeof exports === 'object' ) { // CommonJS module.exports = function (root, $) { if ( ! root ) { root = window; } if ( ! $ || ! $.fn.dataTable ) { $ = require('datatables.net')(root, $).$; } if ( ! $.fn.dataTable.Buttons ) { require('datatables.net-buttons')(root, $); } return factory( $, root, root.document ); }; } else { // Browser factory( jQuery, window, document ); } }(function( $, window, document, undefined ) { 'use strict'; var DataTable = $.fn.dataTable; var _link = document.createElement( 'a' ); /** * Convert a `link` tag's URL from a relative to an absolute address so it will * work correctly in the popup window which has no base URL. * * @param {node} el Element to convert */ var _relToAbs = function( el ) { var url; var clone = $(el).clone()[0]; var linkHost; if ( clone.nodeName.toLowerCase() === 'link' ) { _link.href = clone.href; linkHost = _link.host; // IE doesn't have a trailing slash on the host // Chrome has it on the pathname if ( linkHost.indexOf('/') === -1 && _link.pathname.indexOf('/') !== 0) { linkHost += '/'; } clone.href = _link.protocol+"//"+linkHost+_link.pathname+_link.search; } return clone.outerHTML; }; DataTable.ext.buttons.print = { className: 'buttons-print', text: function ( dt ) { return dt.i18n( 'buttons.print', 'Print' ); }, action: function ( e, dt, button, config ) { var data = dt.buttons.exportData( config.exportOptions ); var addRow = function ( d, tag ) { var str = '<tr>'; for ( var i=0, ien=d.length ; i<ien ; i++ ) { str += '<'+tag+'>'+d[i]+'</'+tag+'>'; } return str + '</tr>'; }; // Construct a table for printing var html = '<table class="'+dt.table().node().className+'">'; if ( config.header ) { html += '<thead>'+ addRow( data.header, 'th' ) +'</thead>'; } html += '<tbody>'; for ( var i=0, ien=data.body.length ; i<ien ; i++ ) { html += addRow( data.body[i], 'td' ); } html += '</tbody>'; if ( config.footer ) { html += '<thead>'+ addRow( data.footer, 'th' ) +'</thead>'; } // Open a new window for the printable table var win = window.open( '', '' ); var title = config.title.replace( '*', $('title').text() ); win.document.close(); // Inject the title and also a copy of the style and link tags from this // document so the table can retain its base styling. Note that we have // to use string manipulation as IE won't allow elements to be created // in the host document and then appended to the new window. var head = '<title>'+title+'</title>'; $('style, link').each( function () { head += _relToAbs( this ); } ); $(win.document.head).html( head ); // Inject the table and other surrounding information $(win.document.body).html( '<h1>'+title+'</h1>'+ '<div>'+config.message+'</div>'+ html ); if ( config.customize ) { config.customize( win ); } setTimeout( function () { if ( config.autoPrint ) { win.print(); // blocking - so close will not win.close(); // execute until this is done } }, 250 ); }, title: '*', message: '', exportOptions: {}, header: true, footer: false, autoPrint: true, customize: null }; return DataTable.Buttons; }));
/** * A spatial function that emits the geometry plus the value of the * properties field of the document (or null if not defined). */ function(doc){ if(doc.geometry){ emit(doc.geometry, doc.properties || null); } }
angular.module('hsgc').directive('footballTeamStats', function() { return { restrict: 'EA', templateUrl: 'templates/footballTeamStats.html', link: function(scope /*, element, attrs*/) { scope.timeOfPossessionRegex = /^00:/; } }; });
exports.decorator = function(coffee) { var originalCost = coffee.getCost; var originalIngredients = coffee.getIngredients; coffee.getCost = function() { return originalCost.apply(this, arguments) + 2; } coffee.getIngredients = function() { return originalIngredients.apply(this, arguments) + " Whip"; } return coffee; }
'use strict'; describe('Controller: AboutCtrl', function () { // load the controller's module beforeEach(module('stadiumsApp')); var AboutCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); AboutCtrl = $controller('AboutCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
var jsonApi = require("jsonapi-server"); jsonApi.define({ namespace: "json:api", resource: "tags", description: "Used to group resources together, useful for finding related resources.", handlers: jsonApi.mongoHandlers, searchParams: { }, attributes: { name: jsonApi.Joi.string() .description("The tag name") .example("Summer"), articles: jsonApi.Joi.belongsToMany({ resource: "articles", as: "tags" }) }, examples: [ { id: "7541a4de-4986-4597-81b9-cf31b6762486", type: "tags", name: "live" }, { id: "2a3bdea4-a889-480d-b886-104498c86f69", type: "tags", name: "staging" }, { id: "6ec62f6d-9f82-40c5-b4f4-279ed1765492", type: "tags", name: "needs-work" } ] });
var path = require('path'); var expect = require('chai').expect; var fs = require('fs-extra'); var swagger = require('./swagger.json'); var unsupportedTypeSwagger = require('./swaggerUnsupportedType.json'); var swaggerModel = require('./../generator'); var root = path.resolve(__dirname); var outPath = path.join(root, 'out'); describe('Swagger generator', function () { beforeEach(function () { fs.removeSync(outPath); fs.mkdirpSync(outPath); }); it('should generate', function () { // Generate swaggerModel.generate(swagger, outPath); // Should generate a file for each class in definiitions plus a ModelBase.js expect(fs.readdirSync(path.join(outPath, 'base'))).to.have.length(Object.keys(swagger.definitions).length + 1); }); it('should filter output', function () { var option = { outPath: outPath, filters: [ '^portal\\.suite\\.dto' ] }; // Generate swaggerModel.generate(swagger, option); expect(fs.readdirSync(path.join(outPath, 'base'))).to.be.deep.equal([ 'ModelBase.js', 'ReferenceDataDrivingHistoryEventPattern_ExtBase.js', 'ReferenceDataFinanceCompany_ExtBase.js' ]); }); it('should filter multiple', function () { var option = { outPath: outPath, filters: [ '^portal\\.suite\\.dto', 'QPMVehicleDTO' ] }; // Generate swaggerModel.generate(swagger, option); expect(fs.readdirSync(path.join(outPath, 'base'))).to.be.deep.equal([ 'ModelBase.js', 'QPMVehicleBase.js', 'ReferenceDataDrivingHistoryEventPattern_ExtBase.js', 'ReferenceDataFinanceCompany_ExtBase.js' ]); }); it('should filter exclude', function () { var option = { outPath: outPath, filters: [ '^portal\\.suite\\.dto', 'QPMVehicleDTO', '!QPMVehicleDTO', '!FinanceCompany' ] }; // Generate swaggerModel.generate(swagger, option); expect(fs.readdirSync(path.join(outPath, 'base'))).to.be.deep.equal([ 'ModelBase.js', 'ReferenceDataDrivingHistoryEventPattern_ExtBase.js' ]); }); it('should report unsupported type when generate', function () { var func = function () { swaggerModel.generate(unsupportedTypeSwagger, outPath); }; expect(func).to.throw(/unsupported/i) }); });
import Vue from 'vue'; import SentryErrorStackTrace from './components/sentry_error_stack_trace.vue'; import store from '~/error_tracking/store'; export default function initSentryErrorStacktrace() { const sentryErrorStackTraceEl = document.querySelector('#js-sentry-error-stack-trace'); if (sentryErrorStackTraceEl) { const { issueStackTracePath } = sentryErrorStackTraceEl.dataset; // eslint-disable-next-line no-new new Vue({ el: sentryErrorStackTraceEl, components: { SentryErrorStackTrace, }, store, render: createElement => createElement('sentry-error-stack-trace', { props: { issueStackTracePath }, }), }); } }
/* @flow */ import { isEqual } from 'lodash'; import { languageLookup, type LanguageType } from '../consts'; import { ROUTE_CHANGE } from '../actions/types'; import handleReducers, { type Handlers } from './handler'; import type { Action, RouteParamsType } from '../flows'; const INITIAL_VALUE = null; const handlers: Handlers<?LanguageType> = { [ROUTE_CHANGE]: (state, { payload }: { payload: RouteParamsType }) => { if (payload.lang) { // language has been chosen or cleared const language = languageLookup(payload.lang); return isEqual(state, language) ? state : (language || INITIAL_VALUE); } return state; }, }; export default (state: ?LanguageType = INITIAL_VALUE, action: Action) => handleReducers(handlers, state, action);
export { default } from 'ember-flexberry-designer/controllers/fd-interface-edit-form';
import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './Why.css'; export default class Why extends Component { render() { return ( <div className={styles.container}> <Link to="/" className={styles.home}></Link> <Link to="/ThankYou" className={styles.powerAhead}><div /></Link> <Link to="/ProductInfo" className={styles.productInformation}></Link> <Link to="/" className={styles.logo}></Link> <Link to="/Why/References" className={styles.references}></Link> </div> ); } }
module.exports = function(gulp, speck) { return gulp.task('css:main', function() { var sass = require('gulp-ruby-sass'), plumber = require('gulp-plumber'), postcss = require('gulp-postcss'), autoprefixer = require('autoprefixer-core'), minifyCSS = require('gulp-minify-css'), streamify = require('gulp-streamify'), gulpif = require('gulp-if'), insert = require('gulp-insert'), size = require('gulp-size'), merge = require('merge-stream'), _ = require('lodash'), notify = require('gulp-notify'); function sassPipeline(entry) { return sass(speck.assets.src.css + '/' + entry + '.scss', { sourcemap: speck.build.env.sourcemaps, style: 'expanded', precision: 10, container: 'gulp-ruby-sass-' + entry }) .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')})) .pipe(postcss([autoprefixer({browsers: ['> 1%', 'last 6 versions', 'Safari 5', 'Firefox ESR', 'Opera 12.1']})])) .pipe(gulpif(speck.build.env.optimise, minifyCSS({}))) .pipe(gulpif(speck.build.env.optimise, insert.prepend( '/*\n' + '* ' + speck.config.name + ', ' + speck.config.version + ' (' + speck.config.currentRevision + ')\n' + '* ' + entry + '.css built ' + new Date().toISOString().substring(0, 10) + '\n' + '* Don\'t edit this file directly.\n' + '*/\n' ))) .pipe(streamify(size({gzip: true, title: entry + '.css'}))) .pipe(gulp.dest(speck.assets.build.css)); } return merge(_.map(speck.entries.css, sassPipeline)); }); };
// All symbols in the `Inscriptional_Parthian` script as per Unicode v6.0.0: [ '\uD802\uDF40', '\uD802\uDF41', '\uD802\uDF42', '\uD802\uDF43', '\uD802\uDF44', '\uD802\uDF45', '\uD802\uDF46', '\uD802\uDF47', '\uD802\uDF48', '\uD802\uDF49', '\uD802\uDF4A', '\uD802\uDF4B', '\uD802\uDF4C', '\uD802\uDF4D', '\uD802\uDF4E', '\uD802\uDF4F', '\uD802\uDF50', '\uD802\uDF51', '\uD802\uDF52', '\uD802\uDF53', '\uD802\uDF54', '\uD802\uDF55', '\uD802\uDF58', '\uD802\uDF59', '\uD802\uDF5A', '\uD802\uDF5B', '\uD802\uDF5C', '\uD802\uDF5D', '\uD802\uDF5E', '\uD802\uDF5F' ];
"use strict"; /* global test */ var assert = require("proclaim"); var expect = assert.strictEqual; var lib = "../../lib" + (process.env.TEST_COV && "-cov" || "") + "/"; var dateUtils = require(lib + "date"); test("isLeapYear", function () { assert.isFalse(dateUtils.isLeapYear(2010)); assert.isFalse(dateUtils.isLeapYear(2011)); assert.isTrue(dateUtils.isLeapYear(2012)); assert.isFalse(dateUtils.isLeapYear(2013)); assert.isFalse(dateUtils.isLeapYear(2014)); }); test("daysInMonth", function () { expect(dateUtils.daysInMonth(0, 2014), 31); expect(dateUtils.daysInMonth(1, 2014), 28); expect(dateUtils.daysInMonth(1, 2012), 29); expect(dateUtils.daysInMonth(2, 2014), 31); expect(dateUtils.daysInMonth(3, 2014), 30); expect(dateUtils.daysInMonth(4, 2014), 31); expect(dateUtils.daysInMonth(5, 2014), 30); expect(dateUtils.daysInMonth(6, 2014), 31); expect(dateUtils.daysInMonth(7, 2014), 31); expect(dateUtils.daysInMonth(8, 2014), 30); expect(dateUtils.daysInMonth(9, 2014), 31); expect(dateUtils.daysInMonth(10, 2014), 30); expect(dateUtils.daysInMonth(11, 2014), 31); }); test("toSqlDate", function () { var date = new Date(2014, 0, 1, 8, 1, 1, 100); expect(dateUtils.toSqlDate(date), "2014-01-01 08:01:01"); expect(dateUtils.toSqlDate(date, false), "2014-01-01"); date = new Date(2014, 10, 22, 15, 54, 34, 100); expect(dateUtils.toSqlDate(date), "2014-11-22 15:54:34"); expect(dateUtils.toSqlDate(date, false), "2014-11-22"); }); test("parseSqlDate", function () { var parsedDate = dateUtils.parseSqlDate("2014-01-01 08:01:01"); expect(parsedDate.getFullYear(), 2014); expect(parsedDate.getMonth(), 0); expect(parsedDate.getDate(), 1); expect(parsedDate.getHours(), 8); expect(parsedDate.getMinutes(), 1); expect(parsedDate.getSeconds(), 1); parsedDate = dateUtils.parseSqlDate("2014-01-01"); expect(parsedDate.getFullYear(), 2014); expect(parsedDate.getMonth(), 0); expect(parsedDate.getDate(), 1); expect(parsedDate.getHours(), 0); expect(parsedDate.getMinutes(), 0); expect(parsedDate.getSeconds(), 0); parsedDate = dateUtils.parseSqlDate("2014-11-22 15:54:34"); expect(parsedDate.getFullYear(), 2014); expect(parsedDate.getMonth(), 10); expect(parsedDate.getDate(), 22); expect(parsedDate.getHours(), 15); expect(parsedDate.getMinutes(), 54); expect(parsedDate.getSeconds(), 34); parsedDate = dateUtils.parseSqlDate("2014-11-22"); expect(parsedDate.getFullYear(), 2014); expect(parsedDate.getMonth(), 10); expect(parsedDate.getDate(), 22); expect(parsedDate.getHours(), 0); expect(parsedDate.getMinutes(), 0); expect(parsedDate.getSeconds(), 0); }); //# sourceMappingURL=date.js.map
const fs = require('fs') const { promisify } = require('util') const readFile = promisify(fs.readFile) async function readFromList (list) { let content = {} for (let file of list) { content[file] = await readFile(file, { encoding: 'utf8' }) } return content } module.exports = readFromList
/** * Created by Andrew Rapo on 12/23/15. */ "use strict"; class MimDbPrompt { constructor() { this.id = ''; this.mimId = ''; this.promptCategory = ''; this.promptSubCategory = ''; this.index = ''; this.condition = ''; this.prompt = ''; this.media = ''; this.extra = ''; this.promptId = ''; } initWithJSON(data) { this.id = data.id; this.mimId = data.mim_id; this.promptCategory = data.prompt_category; this.promptSubCategory = data.prompt_sub_category; this.index = data.index; this.condition = data.condition; this.prompt = data.prompt; this.media = data.media; this.extra = data.extra; this.promptId = data.prompt_id; } getPromptText() { let result = this.prompt; return result; } toString() { let result = 'Prompt: '; result += this.mimId + ', '; result += this.promptCategory + ', '; result += this.promptSubCategory + ', '; result += this.index + ', '; result += this.condition + ', '; result += this.media + ': '; result += this.extra + ': '; result += '\'' + this.prompt + '\''; return result; } toHtml() { let html = '<p>Prompt:</br>'; html += `mimId: ${this.mimId}</br>`; html += `promptCategory: ${this.promptCategory}</br>`; html += `promptSubCategory: ${this.promptSubCategory}</br>`; html += `index: ${this.index}</br>`; html += `condition: ${this.condition}</br>`; html += `prompt: ${this.prompt}</br>`; html += `extra: ${this.extra}</br>`; html += `media: ${this.media}</br>`; html += '</p>'; return html; } toJSON() { let result = {}; result.mim_id = this.mimId; result.prompt_category = this.promptCategory; result.prompt_sub_category = this.promptSubCategory result.index = this.index;; result.condition = this.condition; result.prompt = this.prompt; result.media = this.media; result.extra = this.extra; result.prompt_id = this.promptId; return result; } } module.exports = MimDbPrompt;
module.exports = { font: { size: 21 } }
#!/usr/bin/env node var Nightwatch = require("nightwatch"); var browserstack = require("browserstack-local"); var bs_local; try { process.mainModule.filename = "./node_modules/.bin/nightwatch"; // Code to start browserstack local before start of test console.log("Connecting local"); Nightwatch.bs_local = bs_local = new browserstack.Local(); bs_local.start({ key: process.env.BROWSERSTACK_ACCESS_KEY }, function( error ) { if (error) { console.log(error); throw error; } console.log("Connected. Now testing..."); Nightwatch.cli(function(argv) { Nightwatch.CliRunner(argv) .setup(null, function() { // Code to stop browserstack local after end of parallel test bs_local.stop(function() {}); }) .runTests(function() { // Code to stop browserstack local after end of single test bs_local.stop(function() {}); }); }); }); } catch (ex) { console.log("There was an error while starting the test runner:\n\n"); process.stderr.write(ex.stack + "\n"); process.exit(2); }
const ClassTime = (() => { const timeTick = new Tracker.Dependency() // Reactive moment changes Meteor.setInterval(() => timeTick.changed(), 1000) moment.locale('en') return { fromNowReactive(mmt) { timeTick.depend() return mmt.fromNow() } } })() export default ClassTime
var documentData = { "trails": [ { "name": "Basic Tutorials", "documents": [ "first", "sub-seeds", "parameters", "domains", "details" ] }, { "name": "Advanced Tutorials", "documents": [ "custom-song-structure", "custom-harmony", "coupled-songs", "custom-song-part-indices" ] }, { "name": "In-depth Tutorials", "documents": [ "render-and-play-songs" ] } ], "documents": { "first": { "name": "Introduction", "page": "introduction" }, "sub-seeds": { "name": "Sub Seeds", "page": "sub_seeds" }, "parameters": { "name": "Parameters", "page": "parameters" }, "domains": { "name": "Domains", "page": "domains" }, "details": { "name": "Details", "page": "details" }, "custom-song-structure": { "name": "Custom Song Structure", "page": "custom_song_structure" }, "custom-harmony": { "name": "Custom Harmony", "page": "custom_harmony" }, "coupled-songs": { "name": "Connected Songs", "page": "connected_songs" }, "custom-song-part-indices": { "name": "Custom Song Part Indices" // "page": "coupled_songs" }, "render-and-play-songs": { "name": "Render and Play Songs", "page": "render_and_play_songs" } } }; function getTrailInfo(docId) { var trails = documentData.trails; for (var i = 0; i<trails.length; i++) { var trail = trails[i]; var index = trail.documents.indexOf(docId); if (index >= 0) { return {index: index, trail: trail}; } } return null; } function generate(docData) { } function createLargeToc() { var $largeTocDiv = $(".large-toc-div"); if ($largeTocDiv.size() > 0) { var tocHtmlArr = []; var trails = documentData.trails; for (var i = 0; i<trails.length; i++) { var trail = trails[i]; tocHtmlArr.push('<h2>' + trail.name + '</h2>'); for (var j=0; j<trail.documents.length; j++) { var docId = trail.documents[j]; var doc = documentData.documents[docId]; if (doc) { var page = doc.page; tocHtmlArr.push('<p>' + (page ? '<a href="' + page + '.html">' : "") + doc.name + (page ? '</a>' : "") + '</p>'); } else { console.log("Could not find document " + docId); } } } $largeTocDiv.append($(tocHtmlArr.join(""))); } } function createTrailToc($trailTocDiv) { var $trailTocDiv = $(".trail-toc-div"); if ($trailTocDiv.size() > 0) { var tocHtmlArr = ['<p>testing index</p>']; documentData.trails; $trailTocDiv.append($(tocHtmlArr.join(""))); } } function createHeader() { } function createFooter() { } $( document ).ready( function() { var $mainDiv = $(".main-div"); var mainId = $mainDiv.attr("id"); createLargeToc(); createTrailToc(); createHeader(); createFooter(); if (mainId == "index") { console.log("Found index"); } else if (mainId) { var docData = documentData.documents[mainId]; if (docData) { var trailInfo = getTrailInfo(mainId); if (trailInfo) { console.log(trailInfo); } else { console.log("Could not find trail for document " + mainId); } } else { console.log("Could not find doc data for id " + mainId); } } else { console.log("Could not find the id for this document"); } });
describe( require('../../__fixtures/utils/test_helper') .create() .testName(__filename, 3), function() { this.timeout(120000); var Mesh = require('../../..'); var test_id = Date.now() + '_' + require('shortid').generate(); var fs = require('fs-extra'); var dbFileName = './temp/' + test_id + '.nedb'; var expect = require('expect.js'); global.TESTING_7 = true; var config = { secure: true, happn: { persist: true, filename: dbFileName, adminPassword: 'TEST7' }, components: { data: {} } }; var unpersistedConfig = { port: 8888, secure: true, happn: { persist: false } }; after(function(done) { var _this = this; fs.unlink(dbFileName, function(e) { if (e) return callback(e); _this.mesh .stop({ reconnect: false }) .then(function() { _this.unpersistedMesh.stop({ reconnect: false }, done); }) .catch(done); }); }); var meshName; var meshPublicKey; var unpersistedMeshName; var unpersistedMeshPublicKey; before(function(done) { var _this = this; Mesh.create(config) .then(function(mesh) { _this.mesh = mesh; meshName = mesh._mesh.config.name; meshPublicKey = mesh._mesh.happn.server.services.security._keyPair.publicKey; Mesh.create(unpersistedConfig) .then(function(unpersistedMesh) { _this.unpersistedMesh = unpersistedMesh; unpersistedMeshName = unpersistedMesh._mesh.config.name; unpersistedMeshPublicKey = unpersistedMesh._mesh.happn.server.services.security._keyPair.publicKey; // console.log('names:::', meshName, unpersistedMeshName); done(); }) .catch(done); }) .catch(done); }); it('restarts the mesh, ensures the keypair', function(done) { var _this = this; _this.mesh.stop({ reconnect: false }, function(e) { if (e) return done(e); Mesh.create(config) .then(function(mesh) { _this.mesh = mesh; expect(mesh._mesh.happn.server.services.security._keyPair.publicKey.toString()).to.be( meshPublicKey.toString() ); expect(mesh._mesh.happn.server.services.security._keyPair.publicKey).to.not.be(null); expect(mesh._mesh.happn.server.services.security._keyPair.publicKey).to.not.be( undefined ); done(); }) .catch(done); }); }); it('restarts the unpersisted mesh, ensures the keypair is different', function(done) { var _this = this; _this.unpersistedMesh.stop({ reconnect: false }, function(e) { if (e) return done(e); Mesh.create(unpersistedConfig) .then(function(unpersistedMesh) { _this.unpersistedMesh = unpersistedMesh; expect( unpersistedMesh._mesh.happn.server.services.security._keyPair.publicKey.toString() ).to.not.be(unpersistedMeshPublicKey.toString()); expect( unpersistedMesh._mesh.happn.server.services.security._keyPair.publicKey ).to.not.be(null); expect( unpersistedMesh._mesh.happn.server.services.security._keyPair.publicKey ).to.not.be(undefined); expect(unpersistedMeshPublicKey).to.not.be(null); expect(unpersistedMeshPublicKey).to.not.be(undefined); done(); }) .catch(done); }); }); it('restarts the mesh, ensures the name', function(done) { var _this = this; _this.mesh.stop({ reconnect: false }, function(e) { if (e) return done(e); //so we need to check that we are getting the name from the file config.name = undefined; Mesh.create(config) .then(function(mesh) { _this.mesh = mesh; expect(mesh._mesh.config.name).to.be(meshName); expect(mesh._mesh.config.name).to.not.be(null); expect(mesh._mesh.config.name).to.not.be(undefined); done(); }) .catch(done); }); }); it('restarts the unpersisted mesh, ensures the name is different', function(done) { var _this = this; _this.unpersistedMesh.stop({ reconnect: false }, function(e) { if (e) return done(e); unpersistedConfig.name = undefined; unpersistedConfig.happn.name = undefined; Mesh.create(unpersistedConfig) .then(function(unpersistedMesh) { _this.unpersistedMesh = unpersistedMesh; expect(unpersistedMesh._mesh.config.name).to.not.be(unpersistedMeshName); expect(unpersistedMesh._mesh.config.name).to.not.be(null); expect(unpersistedMesh._mesh.config.name).to.not.be(undefined); expect(unpersistedMeshName).to.not.be(null); expect(unpersistedMeshName).to.not.be(undefined); done(); }) .catch(done); }); }); } );
'use strict'; const { isFunction } = require('../helpers/is'); module.exports = function get(key, defaultValue = null) { if (this.items[key] !== undefined) { return this.items[key]; } if (isFunction(defaultValue)) { return defaultValue(); } if (defaultValue !== null) { return defaultValue; } return null; };
import Smooth from '../../index' import css from 'dom-css' class Split extends Smooth { constructor(opt) { super(opt) this.createExtraBound() this.sections = null this.dom.sections = Array.prototype.slice.call(opt.sections, 0) } createExtraBound() { ['getCache', 'inViewport'] .forEach((fn) => this[fn] = this[fn].bind(this)) } resize() { this.dom.sections.forEach((el, index) => css(el, { 'display': 'block', 'position': 'relative', 'top': 0, 'transform': 'none' })) this.vars.bounding = this.dom.sections[this.dom.sections.length - 1].getBoundingClientRect().bottom - (this.vars.native ? 0 : this.vars.height) css(this.dom.section, 'height', this.vars.bounding) this.getCache() this.dom.sections.forEach((el, index) => css(el, { 'position': 'fixed', 'width': '100%', 'top': this.sections[index].top })) super.resize() } getCache() { this.sections = [] this.dom.sections.forEach((el, index) => { const bounding = el.getBoundingClientRect(); const bounds = { el: el, state: true, top: bounding.top, bottom: bounding.bottom, speed: '-1' } this.sections.push(bounds) }) } run() { this.dom.sections.forEach(this.inViewport) super.run() } inViewport(el, index) { if(!this.sections) return const cache = this.sections[index] const current = this.vars.current const transform = current * cache.speed const top = Math.round(cache.top + transform) const bottom = Math.round(cache.bottom + transform) const inview = bottom > 0 && top < this.vars.height if(inview) { // !cache.state && (this.dom.section.appendChild(cache.el), cache.state = true); el.style.display = 'block' el.style[this.prefix] = this.getTransform(transform) } else { el.style.display = 'none' el.style[this.prefix] = 'none' // cache.state && cache.el.parentNode && (cache.el.parentNode.removeChild(cache.el), cache.state = false); } } } export default Split
/* eslint-disable global-require */ const express = require('express'); const path = require('path'); const compression = require('compression'); const pkg = require(path.resolve(process.cwd(), 'package.json')); // Dev middleware const addDevMiddlewares = (app, webpackConfig) => { const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware'); const webpackHotMiddleware = require('webpack-hot-middleware'); const compiler = webpack(webpackConfig); const middleware = webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath, silent: true, stats: 'errors-only', }); app.use(middleware); app.use(webpackHotMiddleware(compiler)); // Since webpackDevMiddleware uses memory-fs internally to store build // artifacts, we use it instead const fs = middleware.fileSystem; if (pkg.dllPlugin) { app.get(/\.dll\.js$/, (req, res) => { const filename = req.path.replace(/^\//, ''); res.sendFile(path.join(process.cwd(), pkg.dllPlugin.path, filename)); }); } app.get('*', (req, res) => { fs.readFile(path.join(compiler.outputPath, 'index.html'), (err, file) => { if (err) { res.sendStatus(404); } else { res.send(file.toString()); } }); }); }; // Production middlewares const addProdMiddlewares = (app, options) => { const publicPath = options.publicPath || '/'; const outputPath = options.outputPath || path.resolve(process.cwd(), 'build'); // compression middleware compresses your server responses which makes them // smaller (applies also to assets). You can read more about that technique // and other good practices on official Express.js docs http://mxs.is/googmy app.use(compression()); app.use(publicPath, express.static(outputPath)); app.get('*', (req, res) => res.sendFile(path.resolve(outputPath, 'index.html'))); }; /** * Front-end middleware */ module.exports = (app, options) => { const isProd = process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging'; if (isProd) { addProdMiddlewares(app, options); } else { const webpackConfig = require('../../internals/webpack/webpack.dev.babel'); addDevMiddlewares(app, webpackConfig); } return app; };
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('story', 'Unit | Model | story', { // Specify the other units that are required for this test. needs: [] }); test('it exists', function(assert) { var model = this.subject(); // var store = this.store(); assert.ok(!!model); });
/* Stylesheet swappin */ $(document).ready(function(){ $('input.alternate-css').change(function() { if($(this).get(0).checked) { $("link[href*='prism-okaida.css']").attr('disabled', 'disabled'); $("link[href*='prism-default.css']").removeAttr('disabled'); } else { $("link[href*='prism-okaida.css']").removeAttr('disabled'); $("link[href*='prism-default.css']").attr('disabled', 'disabled'); } }); }); /* Adjust scrollTop when navigating to a subsection on the current page */ $(document).ready(function() { $('a.styleguide-subsection, .section-nav a').click(function(e) { var $target = $(e.target.hash); var desiredScrollPosition = $target.offset().top; window.history.pushState('', '', e.target.hash); $('body, html').animate({ scrollTop: desiredScrollPosition }, 500, function () { $target.focus(); }); return false; }); }); /* Make all links inside codeExamples open in a new window */ $(document).ready(function() { $('.codeExample a').attr('target', '_blank'); }); /* Navbar hamburger functionality */ $(document).ready(function() { $('#navbar-hamburger').click(function() { $('ul#styleguide-first-level-nav').slideToggle(300); }); $('.styleguide-second-level-nav-link').click(function(e) { e.preventDefault(); var $targetCategory = $('#' + $(e.currentTarget).data('target')); var targetCategoryClosed = !$targetCategory.hasClass('active'); $('li.styleguide-category').removeClass('active'); $('ul.styleguide-second-level-nav').slideUp(); if (targetCategoryClosed) { $targetCategory.addClass('active'); $targetCategory.find('ul.styleguide-second-level-nav').slideDown(); } else { setTimeout(function() { $('ul.styleguide-second-level-nav').removeAttr('style'); }, 500); } }); }); /* Copy button */ $(document).ready(function() { ZeroClipboard.config({ swfPath: "zeroclipboard/ZeroClipboard.swf" }); var zc = new ZeroClipboard( $('[data-btn-copy]') ); $('[data-btn-copy]') .attr('title', 'Copy to clipboard'); $('[data-btn-copy]').tooltip(); zc.on('ready', function() { zc.on('copy', function(e) { var copyText = $(e.target).parent().find('[data-code-to-copy]').text(); e.clipboardData.setData('text/plain', copyText); }); zc.on('aftercopy', function(e) { $(e.target).attr('title', 'Copied!') .tooltip('fixTitle') .tooltip('show') .attr('title', 'Copy to clipboard') .tooltip('fixTitle'); }); }); zc.on('error', function(err) { console.error('Zero clipboard error', err); ZeroClipboard.destroy(); }); });
import '../both/lib/actionLinks'; import './actionLinkHandler';
// Developed by Joseph Blau - josephblau@gmail.com // // ** Requires ** // NodeJS - http://nodejs.org/ // node-twitter - https://github.com/gasi/node-twitter // Node-Hashish - https://github.com/substack/node-hashish // // ** Instructions ** // # node topten.js // // ** Sample Output ** // Top Ten Trending Topics In Past 30 Seconds // 1 - woofuckinghoo // 1 - yum // 1 - yune // 1 - zaynmeetzaynmalikarmy // 1 - ÓTIMO // 1 - 頭にエアをつけるとションボリする // 2 - replacesongnameswithcurry // 2 - tienerthings // 2 - こうないしゃせいを変換させる事で自分が変態かそうじゃないかが分かるらしい // 2 - 同じ声優の台詞を混ぜる var sys = require('util'); var Twitter = require('twitter'); var Hash = require('hashish'); var debug = false; var secondsBetweenPrinting = 30; var trendingHash = Hash(); var twitter = new Twitter({ consumer_key: '', consumer_secret: '', access_token_key: '', access_token_secret: '' }); twitter.stream('statuses/sample', function(stream) { stream.on('data', function (tweet) { // sys.puts(sys.inspect(tweet)); try { if (tweet.entities.hashtags.length > 0){ for (hashtagobj in tweet.entities.hashtags){ if (debug) console.log("stream::Hashtag "+tweet.entities.hashtags[hashtagobj].text); var hahstag = tweet.entities.hashtags[hashtagobj].text.toLowerCase(); // If key is already in hashtag list, remove it from the hashtag list and increment it's count in the dictionary if (trendingHash.has(hahstag)){ if (debug) console.log("stream::HashtagExists - "+hahstag); var tally = trendingHash.valuesAt(hahstag) + 1; var obj = {}; obj[hahstag] = tally; trendingHash.update(obj); } else { var obj = {}; obj[hahstag] = 1; trendingHash.update(obj); } } } } catch (err){} }); }); // Loop for printing out tweets and clearing hashtable setInterval(function() { if (trendingHash.size > 0){ var frequencyList = new Array(trendingHash.size); var startIndex = (frequencyList.length < 10)?0:frequencyList.length-10; var counter = 0; // Assign each hash key/value to a location in an array trendingHash.forEach(function(x, key) { frequencyList[counter] = {freq:x, ht:key}; counter++; }); // Sort the array based on frequency frequencyList.sort(function(a, b) {return a.freq - b.freq;}); sys.puts('Top Ten Trending Topics In Past '+secondsBetweenPrinting+' Seconds'); if (debug) console.log('setInterval::CheckStartIndex - '+startIndex +' == ' + frequencyList.length); for (idx=startIndex; idx<frequencyList.length;idx++){ sys.puts(frequencyList[idx].freq + '\t - ' + frequencyList[idx].ht); } trendingHash = Hash(); } else { sys.puts('No Trending Topics Added in Past '+secondsBetweenPrinting+' Seconds') } }, secondsBetweenPrinting*1000);
/** * Action types */ export const SET_FB_STATUS = 'SET_FB_STATUS' export const FB_STATUSES = { LOADING: 'loading', DONE: 'done', } /** * Action creators */ export const setFacebookStatus = (text) => { return { type: SET_FB_STATUS, status: text, } }
require('es6-shim'); var restify = require('restify'); var GitHubGist = require('strkio-storage-githubgist'); var bunyan = require('bunyan'); var server = restify.createServer({name: 'strkio-api'}); server.use(restify.queryParser()); server.use(restify.jsonBodyParser()); if (process.env.NODE_ENV === 'development') { server.on('after', restify.auditLogger({ log: bunyan.createLogger({name: 'audit', stream: process.stdout}) })); } server.use(function (req, res, next) { var authorization = req.header('authorization'); if (authorization && ~authorization.toLowerCase().indexOf('token ')) { req.accessToken = authorization.substr(6); } next(); }); function requireAccessToken (req, res, next) { if (!req.accessToken) { return next(new restify.UnauthorizedError()); } next(); } function notImplemented(req, res, next) { next(new restify.NotImplementedError()); } server.post('/v1/gists', notImplemented); server.post('/v1/gists/:gist_id/streaks', notImplemented); server.get('/v1/gists/:gist_id', notImplemented); function findStreak(gist, streakName, cb) { var streaks = gist.data.streaks; var index = streaks.findIndex(function (streak) { return streak.name === streakName; }); if (~index) { cb(null, streaks[index], index); } else { var validStreakNames = streaks.map(function (streak) { return streak.name; }); cb(new restify.NotFoundError( 'GitHub Gist ' + gist.data.id + ' does not contain streak ' + '\'' + streakName + '\' ' + '(available: ' + validStreakNames + ')')); } } server.get('/v1/gists/:gist_id/streaks/:streak_name', function respond(req, res, next) { var gistId = req.params['gist_id']; var streakName = req.params['streak_name']; new GitHubGist({id: gistId}, {oauthToken: req.accessToken}) .fetch(function (err, gist) { if (err) { return next(err); } findStreak(gist, streakName, function (err, streak) { if (err) { return next(err); } res.json(200, streak); }); }); }); function asTimestamp(date) { return typeof date === 'string' ? Date.parse(date) : (typeof date === 'number' ? date : NaN); } function parseDataChanges(data) { var result = []; var keys = Object.keys(data); for (var i = 0, end = keys.length, key, timestamp, value; i < end; i++) { key = keys[i]; timestamp = asTimestamp(key); value = '' + data[key]; if (!timestamp || !/[+-]?\d+/.test(value)) { throw new restify.BadRequestError(); } result.push({ key: new Date(timestamp).toISOString().substr(0, 10), value: value }); } return result; } function applyDataChanges(data, changes) { changes.forEach(function (change) { var key = change.key; data[key] || (data[key] = 0); var prefix = change.value.charAt(0); if (prefix === '+') { data[key] += parseInt(change.value.substr(1), 10); } else if (prefix === '-') { data[key] -= parseInt(change.value.substr(1), 10); } else { data[key] = parseInt(change.value, 10); } }); } server.patch('/v1/gists/:gist_id/streaks/:streak_name', requireAccessToken, function respond(req, res, next) { if (!req.accessToken) { return next(new restify.UnauthorizedError()); } var gistId = req.params['gist_id']; var streakName = req.params['streak_name']; new GitHubGist({id: gistId}, {oauthToken: req.accessToken}) .fetch(function (err, gist) { if (err) { return next(err); } findStreak(gist, streakName, function (err, streak) { if (err) { return next(err); } var body = req.body; Object.keys(body) .filter(function (key) { return key !== 'data'; }) .forEach(function (key) { streak[key] = body[key]; }); if (body.data) { var changes; try { changes = parseDataChanges(body.data); } catch (e) { return next(e); } streak.data || (streak.data = {}); applyDataChanges(streak.data, changes); } gist.save(function (err) { if (err) { return next(err); } res.send(200); }); }); }); }); server.del('/v1/gists/:gist_id', notImplemented); server.del('/v1/gists/:gist_id/streaks/:streak_name', notImplemented); server.listen(process.env.PORT || 3000, function () { console.log('%s listening at %s', server.name, server.url); });
var NodeAhoCorasick = require('node-aho-corasick'); module.exports = function (content) { const ac = content.reduce((current, phrase) => { current.add(phrase); return current; }, new NodeAhoCorasick()); ac.build(); return (str) => { return ac.exec(str) }; }
import TwitterClientConstants from '../constants/twitter-client-constants'; class UserStreamActionFactory { constructor() { } getInitial(tweets) { return { actionType: TwitterClientConstants.INITIAL_TWEET, tweets: tweets } } getData(data) { if (data.friend) { } else if (data.event) { } else if (data.delete) { } else if (data.created_at) { return { actionType: TwitterClientConstants.USER_STREAM_TWEET, tweet: data }; } return {}; } } export default new UserStreamActionFactory();
/* jshint camelcase: false */ module.exports = function(grunt) { var chalk = require('grunt-attention/node_modules/chalk') grunt.initConfig({ install_at: (process.env.HOME || process.evn.HOMEPATH || process.env.USERPROFILE) + '/.mongorc.js', bower_concat: { dist: { dest: '.work/bower_components.js' } }, concat: { dist: { src: ['.work/*.js', 'src/**/*.js'], dest: '.dist/mongorc.js', options: { process: function (content, srcpath) { return content.replace( '###version###', grunt.file.readJSON('package.json')['version'] ) } } } }, copy: { release: { src: '<%= concat.dist.dest %>', dest: '<%= copy.released.src %>' }, builded: { src: '<%= concat.dist.dest %>', dest: '<%= install_at %>', }, released: { src: './released/mongorc.js', dest: '<%= install_at %>', } }, attention: { installed: { options: { borderColor: 'bgGreen', message: chalk.green.bold('MongoDB shell extensions installed in your home directory\n') + chalk.green('(see <%= install_at %>) \n\n') + chalk.green('Next time you\'ll open your mongo shell you\'ll have all the extensions automatically loaded') } } }, jshint: { options: grunt.file.readJSON('.jshintrc'), all: ['Gruntfile.js', 'spec/**/*.js', 'src/**/*.js'] }, release: { options: { add: false, bump: false, commit: false, tag: true, tagName: '<%= version %>', tagMessage: 'Release <%= version %>', push: true, pushTags: true, npm: true } }, clean: ['.work', '.dist'] }); grunt.loadNpmTasks('grunt-bower-concat') grunt.loadNpmTasks('grunt-contrib-concat') grunt.loadNpmTasks('grunt-contrib-clean') grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-contrib-copy') grunt.loadNpmTasks('grunt-attention') grunt.loadNpmTasks('grunt-release') grunt.registerTask('build', ['clean', 'jshint', 'bower_concat', 'concat']) grunt.registerTask('install-head', ['build', 'copy:builded', 'attention:installed']) grunt.registerTask('install-released', ['copy:released', 'attention:installed']) grunt.registerTask('spec', ['spec-on-head']) grunt.registerTask('spec-on-head', ['build', 'run-all-specs:head']) grunt.registerTask('spec-on-installed', ['run-all-specs:installed']) // To do a release you need to: // * change the version in package.json // * execute `grunt prepare-release` // * execute `git add --all && git commit -m "Release <version>"` // * execute `grunt release-and-publish` grunt.registerTask('prepare-release', ['build', 'copy:release']) grunt.registerTask('release-and-publish', ['release']) grunt.registerTask('default', ['spec']) // !!! I need to automate this, but it's not easy // How to run tests on a different MongoDB // * start mongod on a different port with a command like // `~/opt/mongodb-2.2.7/bin/mongod --port 3100 // --dbpath .tmp/db --logpath .tmp/log --fork // --quiet --nojournal --noprealloc --smallfiles // ` // * change the definition 'spec-on-head' spec to `['build', 'run-all-specs:head:3100']` // * [optional] to use the shell shipped with the server, change the spawn to use the full path of shell executable // * run `grunt spec` grunt.registerTask('run-all-specs', 'Run all specs in MongoDB Shell', function(onWhat, onPort) { var done = this.async(), path = require('path'), spawn = require('child_process').spawn, fileToLoad = (onWhat || 'head') === 'head' ? path.join(__dirname, './.dist/mongorc.js') : grunt.config('install_at'), portToConnectTo = (onPort ? onPort : '27017'), commandArguments = ['--quiet', '--port', portToConnectTo, fileToLoad, '_runner.js'], runner = spawn('mongo', commandArguments, {cwd: path.join(__dirname, 'spec')}) runner.stdout.on('data', function(data) { grunt.log.write(data.toString()) }) runner.stderr.on('data', function(data) { grunt.log.error(data.toString()) }) runner.on('close', function(code) { if (code !== 0) { grunt.util.exit(code) } done() }) }) }
{ if (this.props.x === 155) { return React.createElement(AdsPopoverLink62, { x: 154 }); } if (this.props.x === 239) { return React.createElement(AdsPopoverLink62, { x: 238 }); } }
/** * @fileOverview A jQuery UI Widget to jump to positions in the page * @author Joel Mitchell * @name $.cx.jump_to * @dependencies: jQuery, jQuery UI widget factory */ (function($) { 'use strict'; $.widget('cx.jump_to', { options: { 'speed': 300 }, // Add an underscore to the event prefix widgetEventPrefix: 'jump_to_', /** * Constructor */ _create: function() { var self = this; self._on({ 'change': function() { self._scrollTo(self.element.val()); } }); }, _scrollTo: function(element) { var self = this, options = self.options, $elem = $('#'+ element); if(typeof $elem === 'undefined'){ return; } // include both html and body for some browsers, but use a promise to not duplicate calls $('html,body') .animate({ scrollTop: $elem.offset().top }, options.speed) .promise() .done(function() { }); }, /** * Destroy */ _destroy: function() { var self = this; self._off('change'); } }); })(jQuery);
/* eslint max-nested-callbacks: ["error", 8] */ /* eslint-env mocha */ 'use strict' const chai = require('chai') const dirtyChai = require('dirty-chai') const expect = chai.expect chai.use(dirtyChai) const path = require('path') const parallel = require('async/parallel') const IPFSFactory = require('ipfsd-ctl') const f = IPFSFactory.create({ type: 'js' }) const config = { Bootstrap: [], Discovery: { MDNS: { Enabled: false }, webRTCStar: { Enabled: false } } } function createNode (callback) { f.spawn({ exec: path.resolve(`${__dirname}/../../src/cli/bin.js`), config, initOptions: { bits: 512 }, args: ['--preload-enabled=false'] }, callback) } describe.skip('kad-dht is routing content and peers correctly', () => { let nodeA let nodeB let nodeC let addrB let addrC let nodes before(function (done) { this.timeout(30 * 1000) parallel([ (cb) => createNode(cb), (cb) => createNode(cb), (cb) => createNode(cb) ], (err, _nodes) => { expect(err).to.not.exist() nodes = _nodes nodeA = _nodes[0].api nodeB = _nodes[1].api nodeC = _nodes[2].api parallel([ (cb) => nodeA.id(cb), (cb) => nodeB.id(cb), (cb) => nodeC.id(cb) ], (err, ids) => { expect(err).to.not.exist() addrB = ids[1].addresses[0] addrC = ids[2].addresses[0] parallel([ (cb) => nodeA.swarm.connect(addrB, cb), (cb) => nodeB.swarm.connect(addrC, cb) ], done) }) }) }) after((done) => parallel(nodes.map((node) => (cb) => node.stop(cb)), done)) it('add a file in B, fetch in A', function (done) { this.timeout(30 * 1000) const file = { path: 'testfile1.txt', content: Buffer.from('hello kad 1') } nodeB.add(file, (err, filesAdded) => { expect(err).to.not.exist() nodeA.cat(filesAdded[0].hash, (err, data) => { expect(err).to.not.exist() expect(data).to.eql(file.content) done() }) }) }) it('add a file in C, fetch through B in A', function (done) { this.timeout(30 * 1000) const file = { path: 'testfile2.txt', content: Buffer.from('hello kad 2') } nodeC.add(file, (err, filesAdded) => { expect(err).to.not.exist() nodeA.cat(filesAdded[0].hash, (err, data) => { expect(err).to.not.exist() expect(data).to.eql(file.content) done() }) }) }) })
// import React, {Component, PropTypes} from 'react'; import React, {Component} from 'react'; export default class Footer extends Component { render() { const styles = require('./footer.scss'); const logoFooter = require('./full-logo-kingpower.png'); return ( <footer className={ styles.footer }> <img src={ logoFooter } className={ styles['footer-image'] }/> </footer> ); } }
import React from 'react'; import { makeStyles, useTheme } from '@material-ui/core/styles'; import MobileStepper from '@material-ui/core/MobileStepper'; import Paper from '@material-ui/core/Paper'; import Typography from '@material-ui/core/Typography'; import Button from '@material-ui/core/Button'; import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft'; import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight'; import SwipeableViews from 'react-swipeable-views'; import { autoPlay } from 'react-swipeable-views-utils'; const AutoPlaySwipeableViews = autoPlay(SwipeableViews); const tutorialSteps = [ { label: 'San Francisco – Oakland Bay Bridge, United States', imgPath: 'https://images.unsplash.com/photo-1537944434965-cf4679d1a598?auto=format&fit=crop&w=400&h=250&q=60', }, { label: 'Bird', imgPath: 'https://images.unsplash.com/photo-1538032746644-0212e812a9e7?auto=format&fit=crop&w=400&h=250&q=60', }, { label: 'Bali, Indonesia', imgPath: 'https://images.unsplash.com/photo-1537996194471-e657df975ab4?auto=format&fit=crop&w=400&h=250&q=80', }, { label: 'NeONBRAND Digital Marketing, Las Vegas, United States', imgPath: 'https://images.unsplash.com/photo-1518732714860-b62714ce0c59?auto=format&fit=crop&w=400&h=250&q=60', }, { label: 'Goč, Serbia', imgPath: 'https://images.unsplash.com/photo-1512341689857-198e7e2f3ca8?auto=format&fit=crop&w=400&h=250&q=60', }, ]; const useStyles = makeStyles((theme) => ({ root: { maxWidth: 400, flexGrow: 1, }, header: { display: 'flex', alignItems: 'center', height: 50, paddingLeft: theme.spacing(4), backgroundColor: theme.palette.background.default, }, img: { height: 255, display: 'block', maxWidth: 400, overflow: 'hidden', width: '100%', }, })); function SwipeableTextMobileStepper() { const classes = useStyles(); const theme = useTheme(); const [activeStep, setActiveStep] = React.useState(0); const maxSteps = tutorialSteps.length; const handleNext = () => { setActiveStep((prevActiveStep) => prevActiveStep + 1); }; const handleBack = () => { setActiveStep((prevActiveStep) => prevActiveStep - 1); }; const handleStepChange = (step) => { setActiveStep(step); }; return ( <div className={classes.root}> <Paper square elevation={0} className={classes.header}> <Typography>{tutorialSteps[activeStep].label}</Typography> </Paper> <AutoPlaySwipeableViews axis={theme.direction === 'rtl' ? 'x-reverse' : 'x'} index={activeStep} onChangeIndex={handleStepChange} enableMouseEvents > {tutorialSteps.map((step, index) => ( <div key={step.label}> {Math.abs(activeStep - index) <= 2 ? ( <img className={classes.img} src={step.imgPath} alt={step.label} /> ) : null} </div> ))} </AutoPlaySwipeableViews> <MobileStepper steps={maxSteps} position="static" variant="text" activeStep={activeStep} nextButton={ <Button size="small" onClick={handleNext} disabled={activeStep === maxSteps - 1}> Next {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />} </Button> } backButton={ <Button size="small" onClick={handleBack} disabled={activeStep === 0}> {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />} Back </Button> } /> </div> ); } export default SwipeableTextMobileStepper;
var should = require('should'); module.exports = runner = function (later, constraint) { function convertToUTC(d) { return new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds())); } function runSingleTest(fn, data, utc) { var date = utc ? convertToUTC(data.date) : data.date, dateString = utc ? date.toUTCString() : date, ex = utc && (data[fn] instanceof Date) ? convertToUTC(data[fn]) : data[fn], exString = utc && (ex instanceof Date) ? ex.toUTCString() : ex; it('should return ' + exString + ' for ' + dateString, function() { if(utc) later.date.UTC(); else later.date.localTime(); constraint[fn](date).should.eql(ex); }); } function runSweepTest(fn, data, utc) { var min = data.extent[0] === 1 ? 0 : data.extent[0], max = data.extent[1] + 1, inc = Math.ceil((max-min)/200); // max 200 tests per constraint for(var i = min; i <= max; i = i + inc) { // test for overbounds if(fn === 'next') { testNext(data, i, utc); // test all values for amt } else { testPrev(data, i, utc); // test all values for amt } } } function testNext(data, amt, utc) { var date = utc ? convertToUTC(data.date) : data.date, dateString = utc ? date.toUTCString() : date; it('should return first date after ' + dateString + ' with val ' + amt, function() { if(utc) later.date.UTC(); else later.date.localTime(); var next = constraint.next(date, amt), ex = amt, outOfBounds = ex > constraint.extent(date)[1] || ex > constraint.extent(next)[1]; // if amt is outside of extent, the constraint should rollover to the // first value of the following time period if (outOfBounds) ex = constraint.extent(next)[0]; // hack to pass hour test that crosses DST if (ex === 2 && constraint.val(next) === 3 && next.getTimezoneOffset() !== date.getTimezoneOffset()) { ex = 3; } // result should match ex, should be greater than date, and should // be at the start of the time period // if check is hack to support year constraints which can return undefined if(constraint.name === 'year' && (amt <= constraint.val(date) || amt > later.Y.extent()[1])) { next.should.eql(later.NEVER); } else { constraint.isValid(next, ex).should.eql(true); next.getTime().should.be.above(date.getTime()); // need to special case day of week count since the last nth day may // not fall on a week boundary if(constraint.name !== 'day of week count' || amt !== 0) { constraint.start(next).getTime().should.eql(next.getTime()); } } }); } function testPrev(data, amt, utc) { var date = utc ? convertToUTC(data.date) : data.date, dateString = utc ? date.toUTCString() : date; it('should return first date before ' + dateString + ' with val ' + amt, function() { if(utc) later.date.UTC(); else later.date.localTime(); var prev = constraint.prev(date, amt), ex = amt, outOfBounds = ex > constraint.extent(prev)[1]; // if amt is outside of extent, the constraint should rollover to the // first value of the following time period if (outOfBounds) ex = constraint.extent(prev)[1]; // result should match ex, should be greater than date, and should // be at the start of the time period // if check is hack to support year constraints which can return undefined if(constraint.name === 'year' && (amt >= constraint.val(date) || amt < later.Y.extent()[0])) { prev.should.eql(later.NEVER); } else { constraint.isValid(prev, ex).should.eql(true); prev.getTime().should.be.below(date.getTime()); constraint.end(prev).getTime().should.eql(prev.getTime()); } }); } return { run: function (data, isYear) { var i = 0, len = data.length; // test both UTC and local times for all functions [true, false].forEach(function (utc) { // simple tests have the expected value passed in as data ['val', 'extent', 'start', 'end'].forEach(function (fn) { describe(fn, function() { for(i = 0; i < len; i++) { runSingleTest(fn, data[i], utc); } }); }); // complex tests do a sweep across all values and validate results // using checks verified by the simple tests ['next', 'prev'].forEach(function (fn) { describe(fn, function() { for(i = 0; i < len; i++) { runSweepTest(fn, data[i], utc); } }); }); }); } }; };
const hash = "#", space = " ", height = prompt("Set pyramid height"); (function buildPyramid(){ if (between(height, 2, 24)) drawStructure(height); else console.log('Please enter smaller height!') })(); function drawStructure(length){ if ( length == 0 ) return; drawStructure(length - 1); console.log(drawRow(length)); } function between(x, min, max) { return x >= min && x <= max } function drawRow(length){ return space.repeat(height-length) + hash.repeat(length) + space.repeat(2) + hash.repeat(length) }
var restify = require('restify'); var cheerio = require('cheerio'); var knex = require('knex')({ client: 'mysql', connection: { host: '127.0.0.1', user: 'root', password: null, database: 'ctksound' } }); //var client = restify.createClient({ // url: 'https://news.ycombinator.com/news' //}); // //client.get('/news', function(err, req) { // //assert.ifError(err); // connection error // // req.on('result', function(err, res) { // //assert.ifError(err); // HTTP status >= 400 // // res.body = ''; // res.setEncoding('utf8'); // res.on('data', function(chunk) { // res.body += chunk; // }); // // res.on('end', function() { // //console.log(res.body); // var $ = cheerio.load(res.body); // // console.log($('td.title a').text()+"\n"); // //console.log($('tr td.title + tr td.subtext a').text()+"\n"); // }); // }); //}); knex.select().from('sermons') .then(function(rows) { console.log(rows); }) .catch(function(err) { console.error(error); }); // BEGIN SERVER function respond(req, res, next) { res.send('hello ' + req.params.name); next(); } var server = restify.createServer(); server.get('/hello/:name', respond); server.head('/hello/:name', respond); server.get( '/foo/:id', function(req, res, next) { console.log('Authenticate'); return next(); }, function(req, res, next) { res.send(200); return next(); } ); server.get( { path: '/user/:name', version: '1.1.3' }, function(req, res, next) { res.send('hello ' + req.params.name); } ); server.get( { path: '/user/:name', version: '2.0.0' }, function(req, res, next) { res.send('hello: ' + req.params.name); } ); server.listen(8080, function() { console.log('%s listening at %s', server.name, server.url); });
import React from 'react'; import {Button, Modal, FormGroup, FormControl, Checkbox} from 'react-bootstrap'; import ReactDOM from 'react-dom'; class NewClass extends React.Component { static propTypes() { return { create: this.propTypes.func.required, error: this.propTypes.string, showModal: this.propTypes.bool.required, openModal: this.propTypes.func.required, closeModal: this.propTypes.func.required }; } constructor(props) { super(props); this.createClass = this.createClass.bind(this); this.create = props.create; this.error = props.error; this.showModal = false; this.openModal = props.openModal; this.closeModal = props.closeModal; } getValue(node) { // convert HTMLCollection to Array let children = Array.prototype.slice.call(node.querySelectorAll('input[type=checkbox]')); // find if was checked return children[0].checked; } createClass(e) { e.preventDefault(); const {name, durationQuestion, isPublic} = this.refs; const find = ReactDOM.findDOMNode; this.create( find(name).value, parseInt(find(durationQuestion).value, 10), this.getValue(find(isPublic)) ); } render() { const {showModal, error} = this.props; return ( <div> <Button bsStyle="primary" bsSize="small" onClick={this.openModal} > New Class </Button> <Modal show={showModal} onHide={this.closeModal}> <Modal.Header closeButton> <Modal.Title>Create new Class</Modal.Title> </Modal.Header> <Modal.Body> <form> <FormGroup> {error ? <p style={{color: 'red'}}>{error}</p> : null} <FormControl ref="name" type="text" placeholder="Class name" /> </FormGroup> <FormGroup> <FormControl componentClass="select" placeholder="Duration by question" defaultValue="" ref="durationQuestion" > <option value="" disabled>Duración por pregunta</option> <option value="30">30 segundos</option> <option value="60">1 minuto</option> <option value="90">1.5 minutos</option> <option value="120">2 minutos</option> <option value="180">3 minutos</option> <option value="300">5 minutos</option> <option value="600">10 minutos</option> </FormControl> </FormGroup> <FormGroup> <Checkbox ref="isPublic"> Público </Checkbox> </FormGroup> <Button type="submit" onClick={this.createClass}>Create</Button> </form> </Modal.Body> </Modal> </div> ); } } export default NewClass;
(function (constants) { constants = { 'CLIENT': { 'CONNECTION_STATE': { 'CONNECTED': 0, 'DISCONNECTED': 1, }, 'STATE': { 'HOST': 0, 'NONE': 1, 'PLAYER': 2, }, }, 'GAME_STATE': { 'ENTRY': 0, 'PLAYER_JOIN': 1, 'INTRO': 2, 'ROUND': 3, 'SCORE': 4, 'FINAL_SCORE': 5, }, 'OBJECTIVES': [ { 'name': 'Tiger Entrails', 'color': 'red', 'shape': 'tangle', 'filename': 'TigerEntrails.png' }, { 'name': 'Adder Fork', 'color': 'red', 'shape': 'branch', 'filename': 'AdderFork.png' }, { 'name': 'Goat Gall', 'color': 'red', 'shape': 'sphere', 'filename': 'GoatGall.png' }, { 'name': 'Baby Finger', 'color': 'red', 'shape': 'straight', 'filename': 'BabyFinger.png' }, { 'name': 'Baboon Blood', 'color': 'red', 'shape': 'vial', 'filename': 'BaboonBlood.png' }, { 'name': 'Poisoned Entrails', 'color': 'green', 'shape': 'tangle', 'filename': 'PoisonEntrails.png' }, { 'name': 'Lizard Leg', 'color': 'green', 'shape': 'branch', 'filename': 'LizardLeg.png' }, { 'name': 'Drop of Mucus', 'color': 'green', 'shape': 'sphere', 'filename': 'DropOfMucus.png' }, { 'name': 'Frog Toe', 'color': 'green', 'shape': 'straight', 'filename': 'FrogToe.png' }, { 'name': 'Toad Venom', 'color': 'green', 'shape': 'vial', 'filename': 'ToadVenom.png' }, { 'name': 'Snake Fillet', 'color': 'brown', 'shape': 'tangle', 'filename': 'SnakeFillet.png' }, { 'name': 'Hemlock Root', 'color': 'brown', 'shape': 'branch', 'filename': 'HemlockRoot.png' }, { 'name': 'Bat Wool', 'color': 'brown', 'shape': 'sphere', 'filename': 'BatsWool.png' }, { 'name': 'Wolf Tooth', 'color': 'brown', 'shape': 'straight', 'filename': 'WolfsTooth.png' }, { 'name': 'Sands of Time', 'color': 'brown', 'shape': 'vial', 'filename': 'SandsOfTime.png' }, { 'name': 'Silvered Yew', 'color': 'white', 'shape': 'branch', 'filename': 'SilveredYew.png' }, { 'name': 'Eye of Newt', 'color': 'white', 'shape': 'sphere', 'filename': 'EyeOfNewt.png' }, { 'name': 'Dragon Scale', 'color': 'white', 'shape': 'straight', 'filename': 'DragonScale.png' }, { 'name': 'Bone Dust', 'color': 'white', 'shape': 'vial', 'filename': 'BoneDust.png' } ], 'SCORE_STATUS': [ ' turned into a newt', ' turned into a frog', ' turned into a bat', ' turned into a mouse', ' grew a third arm', ' grew a third eye', ' grew a second head', '\'s bones turned into jelly', '\'s skin is now covered in scales', '\'s skin turned green', '\'s skin turned blue', '\'s skin turned purple', '\'s hair fell out', ' became blind', ' became deaf', ' became mute', ' became drunk', ' became deathly afraid of clowns', ' became invisible', ' became a vampire', ' became a werewolf', ' became incredibly muscular', ' craves human flesh', ' got the munchies', ' fell asleep', ' broke the fourth wall', ' let one rip', ' began having regrets', ' got struck by lightning', ' heard disembodied voices' ], 'FORTUNE': [ [ 'definitely', 'probably', 'not' ], [ 'find', 'lose', 'create', 'destroy', 'understand' ], [ 'love', 'money', 'power', 'fame', 'answers' ], [ 'all the right places', 'all the wrong places', 'the big city', 'the woods', 'a foreign country', 'an airplane', 'a taxi', 'a fever dream' ], ], 'INTRO_LENGTH': 15 * 1000, 'OBJECTIVE_SELECTION': 4, 'OBJECTIVE_ADD_INTERVAL': 1000, 'SCORE_LENGTH': 10 * 1000, 'ROUND_LENGTH_TARGET': 30 * 1000, 'ROUND_LENGTH_MINIMUM': 10 * 1000, 'ROUNDS_PER_GAME': 5, 'UPDATE_INTERVAL': 16, }; if (typeof window === 'undefined') { module.exports = constants; } else { window.app.constants = constants; } })({});
var http = require('http'); var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var responseSender = require('./middlewares/responseSender'); var cors = require('./middlewares/cors'); //处理跨域 var routers = { user: require('./routes/user'), msg: require('./routes/msg'), timeline: require('./routes/timeline'), joke: require('./routes/joke') }; var app = express(); var Promise = require('bluebird'); //数据库连接 var db = require('./db'); db.connect(); // //redisClient // var redisClient = require('./redis-client'); //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); // app.use('/wap', express.static(path.join(__dirname, 'wap/www'))); app.use('/public', express.static(path.join(__dirname, 'public'))); app.use(responseSender()); app.use(cors()); // 挂载路由 Object.keys(routers).forEach(function (name) { app.use('/api/' + name, routers[name]); }); // // catch 404 and forward to error handler // app.use(function (req, res, next) { // var err = new Error('Not Found'); // next(err); // }); // // error handler // app.use(function (err, req, res, next) { // // set locals, only providing error in development // res.send({ // code: -1,y // msg: err.message, // }); // }); module.exports = app;
const UserKinds = { ADMIN: 'admin', COACH: 'coach', LEARNER: 'learner', SUPERUSER: 'superuser', ANONYMOUS: 'anonymous', }; const ContentNodeKinds = { AUDIO: 'audio', DOCUMENT: 'document', VIDEO: 'video', EXERCISE: 'exercise', TOPIC: 'topic', HTML5: 'html5', }; // used internally on the client as a hack to allow content-icons to display users const USER = 'user'; const MasteryLoggingMap = { id: 'id', summarylog: 'summarylog', start_timestamp: 'start_timestamp', completion_timestamp: 'completion_timestamp', end_timestamp: 'end_timestamp', mastery_level: 'mastery_level', mastery_criterion: 'mastery_criterion', complete: 'complete', responsehistory: 'responsehistory', pastattempts: 'pastattempts', totalattempts: 'totalattempts', }; const AttemptLoggingMap = { id: 'id', sessionlog: 'sessionlog', item: 'item', start_timestamp: 'start_timestamp', completion_timestamp: 'completion_timestamp', end_timestamp: 'end_timestamp', time_spent: 'time_spent', complete: 'complete', correct: 'correct', answer: 'answer', simple_answer: 'simple_answer', interaction_history: 'interaction_history', masterylog: 'masterylog', hinted: 'hinted', }; const InteractionTypes = { hint: 'hint', }; /* HACK HACK The core application should not have this knowledge about the available plugins. However, until we have a way for plugins to properly indicate what nav bar widgets they supply to core and in what order, this is a work-around. */ const TopLevelPageNames = { LEARN: 'LEARN', COACH: 'COACH', MANAGE: 'MANAGE', USER: 'USER', ABOUT: 'ABOUT', PROFILE: 'PROFILE', }; module.exports = { UserKinds, ContentNodeKinds, MasteryLoggingMap, AttemptLoggingMap, InteractionTypes, USER, TopLevelPageNames, };
import Sequelize from 'sequelize'; import definedSequelizeDb from './define-sequelize-db.js'; const CompanyModel = definedSequelizeDb ? definedSequelizeDb.define( 'companies', { id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true, }, company_token: { type: Sequelize.TEXT }, created_at: { type: Sequelize.DATE }, updated_at: { type: Sequelize.DATE }, }, { timestamps: false }, ) : {}; CompanyModel.associate = models => { models.Company.hasMany(models.Device, { foreignKey: 'company_id' }); models.Company.hasMany(models.Location, { foreignKey: 'company_id' }); }; export default CompanyModel;
//= require_tree ./components window.App = require('./components/App');
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Entity_1 = require("./Entity"); var Aliases_1 = require("./Aliases"); var NumberField_1 = require("../field/NumberField"); var BooleanField_1 = require("../field/BooleanField"); var DateField_1 = require("../field/DateField"); var StringField_1 = require("../field/StringField"); var SubSelectEntity = (function () { function SubSelectEntity() { } return SubSelectEntity; }()); exports.SubSelectEntity = SubSelectEntity; exports.SUB_SELECT_ENTITY_NAME = "SubSelectEntity"; var SubSelectQEntity = (function (_super) { __extends(SubSelectQEntity, _super); function SubSelectQEntity(rootEntityPrefix, fromClausePosition, relationPropertyName, joinType) { if (rootEntityPrefix === void 0) { rootEntityPrefix = Aliases_1.getNextRootEntityName(); } if (fromClausePosition === void 0) { fromClausePosition = []; } if (relationPropertyName === void 0) { relationPropertyName = null; } if (joinType === void 0) { joinType = null; } _super.call(this, SubSelectQEntity, SubSelectEntity, exports.SUB_SELECT_ENTITY_NAME, rootEntityPrefix, fromClausePosition, relationPropertyName, joinType); this.rootEntityPrefix = rootEntityPrefix; this.fromClausePosition = fromClausePosition; this.relationPropertyName = relationPropertyName; this.joinType = joinType; } SubSelectQEntity.prototype.numberField = function (fieldName) { var field = this.__entityFieldMap__[fieldName]; if (!field) { field = new NumberField_1.QNumberField(this, SubSelectQEntity, exports.SUB_SELECT_ENTITY_NAME, fieldName); } return field; }; SubSelectQEntity.prototype.booleanField = function (fieldName) { var field = this.__entityFieldMap__[fieldName]; if (!field) { field = new BooleanField_1.QBooleanField(this, SubSelectQEntity, exports.SUB_SELECT_ENTITY_NAME, fieldName); } return field; }; SubSelectQEntity.prototype.dateField = function (fieldName) { var field = this.__entityFieldMap__[fieldName]; if (!field) { field = new DateField_1.QDateField(this, SubSelectQEntity, exports.SUB_SELECT_ENTITY_NAME, fieldName); } return field; }; SubSelectQEntity.prototype.stringField = function (fieldName) { var field = this.__entityFieldMap__[fieldName]; if (!field) { field = new StringField_1.QStringField(this, SubSelectQEntity, exports.SUB_SELECT_ENTITY_NAME, fieldName); } return field; }; SubSelectQEntity.prototype.toJSON = function () { throw 'Not Implemented'; }; return SubSelectQEntity; }(Entity_1.QEntity)); exports.SubSelectQEntity = SubSelectQEntity; //# sourceMappingURL=SubSelectEntity.js.map
(function () { 'use strict'; /** * usage: <div ng-model="article.body" quill="{ theme: 'mytheme' }"></div> * * extra options: * quill: pass as a string * */ var scripts = document.getElementsByTagName("script"), currentScriptPath = scripts[scripts.length - 1].src; angular.module('angular-quill', []) .directive("quill", ['$timeout', function ($timeout) { return { restrict: 'A', require: "ngModel", replace: true, scope: { annotationZoneAction: '&', hideAnnZoneButton: '=' }, templateUrl: function (elem, attrs) { var tmplt = currentScriptPath.replace('.js', '.html'); if (attrs['type']) { tmplt = tmplt.replace('.html', '-' + attrs['type'] + '.html'); } return tmplt; }, link: function (scope, element, attrs, ngModel) { var inputId = ''; if (attrs.id) inputId = '#' + attrs.id; var updateModel = function updateModel(value) { scope.$apply(function () { ngModel.$setViewValue(value); }); }; var options = { modules: { 'toolbar': {container: inputId + ' .toolbar'}, 'image-tooltip': true, 'link-tooltip': true }, theme: 'snow' }; scope.extraOptions = attrs.quill ? scope.$eval(attrs.quill) : {}; angular.extend(options, scope.extraOptions); $timeout(function () { scope.editor = new Quill(element.children()[1], options); scope.editor.quillId = inputId; $(inputId + ' .editor').click(function () { var isToolTipOpened = false; $(this).find('.ql-tooltip').each(function () { var toolTipPos = $(this).position(); if (typeof(toolTipPos.left) != 'undefined' && toolTipPos.left >= 0) { isToolTipOpened = true; return; } }); if (isToolTipOpened) return; if (scope.editor.getLength() > 0) { var range = scope.editor.getSelection(); if (!range) { scope.editor.setSelection(scope.editor.getLength() - 1, scope.editor.getLength()); } } else { scope.editor.focus(); } }); ngModel.$render(); scope.editor.on('text-change', function (delta, source) { updateModel(scope.editor.getHTML()); }); scope.editor.once('selection-change', function (hasFocus) { var editId = scope.editor.id; $('#' + editId).toggleClass('focus', hasFocus); // Hack for inability to scroll on mobile if (/mobile/i.test(navigator.userAgent)) { $(scope.editor).css('height', scope.editor.root.scrollHeight + 30); // 30 for padding } }); }); ngModel.$render = function () { if (angular.isDefined(scope.editor)) { $timeout(function () { scope.editor.setHTML(ngModel.$viewValue || ''); }); } }; } }; }]); })();