code
stringlengths
2
1.05M
const ws = new global.WebSocket('ws://') ws.onopen = (event) => { console.log(event) this.onmessage = (msg) => { console.log(msg) } } ws.onclose = (event) => { console.log(event) }
/////////////////////////////////////////////////////////////////////////////// // WebkitJs Objects - Copyright (c) 2013 Niclas Norgren - niclas@n3g.net // Released under the MIT license. // http://opensource.org/licenses/MIT /////////////////////////////////////////////////////////////////////////////// // requires goog.require('webkitjs.Component'); // provide goog.provide('webkitjs.Pane'); /** * The base Pane class. A pane is a component that has sub-content, ie adding to * the pane adds to an element inside the pane. * * @constructor * @extends {webkitjs.Component} * * @param {webkitjs.dom|Element|string|undefined=} el An optional element to * use for this pane */ webkitjs.Pane = function(el) { this.callSuper(webkitjs.Component, el); this.addListener('create', function() { this.rendered_ = true; }, this); }; webkitjs.Pane.prototype = new webkitjs.Component; webkitjs.extend(webkitjs.Pane, webkitjs.Component, 'webkitjs-pane'); /** * Identifier for the content area * * @type {string} */ webkitjs.Pane.prototype.contentSelector_ = '.content-area'; /** * Default html for the class * * @type {string} */ webkitjs.Pane.prototype.element_ = '<div><div class="content-area"></div></div>'; /** * Add a child to the content area. * * @param {webkitjs.Component} o A component to add as child * @override */ webkitjs.Pane.prototype.add = function(o) { this.getElement().find(this.contentSelector_).first() .append(o.getElement()); o.parent_ = this; }; /** * Remove a child from the content area. * * @param {webkitjs.Component} o The component to remove as child * @override */ webkitjs.Pane.prototype.remove = function(o) { this.getElement().find(this.contentSelector_).remove(o.getElement()); }; // / Proxy functionality for Widgets that might be children of this pane: /** * update children */ webkitjs.Pane.prototype.update = function() { var els = /** @type {webkitjs.dom} */ this.getElement().find(this.contentSelector_).first().children(); var comp = 'component_'; // release the thread setTimeout(function() { els.each(function(i, o) { if (o[comp] && o[comp].update && o[comp].rendered_) { o[comp].update(); } }); }, 2); };
'use strict'; exports.__esModule = true; var _trackHelper = require('./trackHelper'); var _helpers = require('./helpers'); var _helpers2 = _interopRequireDefault(_helpers); var _objectAssign = require('object-assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _reactDom = require('react-dom'); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EventHandlers = { // Event handler for previous and next changeSlide: function changeSlide(options) { var indexOffset, previousInt, slideOffset, unevenOffset, targetSlide; var _props = this.props; var slidesToScroll = _props.slidesToScroll; var slidesToShow = _props.slidesToShow; var _state = this.state; var slideCount = _state.slideCount; var currentSlide = _state.currentSlide; unevenOffset = slideCount % slidesToScroll !== 0; indexOffset = unevenOffset ? 0 : (slideCount - currentSlide) % slidesToScroll; if (options.message === 'previous') { slideOffset = indexOffset === 0 ? slidesToScroll : slidesToShow - indexOffset; targetSlide = currentSlide - slideOffset; if (this.props.lazyLoad) { previousInt = currentSlide - slideOffset; targetSlide = previousInt === -1 ? slideCount - 1 : previousInt; } } else if (options.message === 'next') { slideOffset = indexOffset === 0 ? slidesToScroll : indexOffset; targetSlide = currentSlide + slideOffset; if (this.props.lazyLoad) { targetSlide = (currentSlide + slidesToScroll) % slideCount + indexOffset; } } else if (options.message === 'dots' || options.message === 'children') { // Click on dots targetSlide = options.index * options.slidesToScroll; if (targetSlide === options.currentSlide) { return; } } else if (options.message === 'index') { targetSlide = parseInt(options.index); if (targetSlide === options.currentSlide) { return; } } this.slideHandler(targetSlide); }, // Accessiblity handler for previous and next keyHandler: function keyHandler(e) { //Dont slide if the cursor is inside the form fields and arrow keys are pressed if (!e.target.tagName.match('TEXTAREA|INPUT|SELECT')) { if (e.keyCode === 37 && this.props.accessibility === true) { this.changeSlide({ message: this.props.rtl === true ? 'next' : 'previous' }); } else if (e.keyCode === 39 && this.props.accessibility === true) { this.changeSlide({ message: this.props.rtl === true ? 'previous' : 'next' }); } } }, // Focus on selecting a slide (click handler on track) selectHandler: function selectHandler(options) { this.changeSlide(options); }, swipeStart: function swipeStart(e) { if (this.props.swipeDisabled) { this.setState({ dragging: false }); return; } var touches, posX, posY; if (this.props.swipe === false || 'ontouchend' in document && this.props.swipe === false) { return; } else if (this.props.draggable === false && e.type.indexOf('mouse') !== -1) { return; } posX = e.touches !== undefined ? e.touches[0].pageX : e.clientX; posY = e.touches !== undefined ? e.touches[0].pageY : e.clientY; this.setState({ dragging: true, touchObject: { startX: posX, startY: posY, curX: posX, curY: posY } }); }, swipeMove: function swipeMove(e) { if (this.props.swipeDisabled) { this.setState({ dragging: false }); return; } if (!this.state.dragging) { e.preventDefault(); return; } if (this.state.animating) { return; } var swipeLeft; var curLeft, positionOffset; var touchObject = this.state.touchObject; curLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2.default)({ slideIndex: this.state.currentSlide, trackRef: this.track }, this.props, this.state)); touchObject.curX = e.touches ? e.touches[0].pageX : e.clientX; touchObject.curY = e.touches ? e.touches[0].pageY : e.clientY; touchObject.swipeLength = Math.round(Math.sqrt(Math.pow(touchObject.curX - touchObject.startX, 2))); if (this.props.verticalSwiping) { touchObject.swipeLength = Math.round(Math.sqrt(Math.pow(touchObject.curY - touchObject.startY, 2))); } positionOffset = (this.props.rtl === false ? 1 : -1) * (touchObject.curX > touchObject.startX ? 1 : -1); if (this.props.verticalSwiping) { positionOffset = touchObject.curY > touchObject.startY ? 1 : -1; } var currentSlide = this.state.currentSlide; var dotCount = Math.ceil(this.state.slideCount / this.props.slidesToScroll); var swipeDirection = this.swipeDirection(this.state.touchObject); var touchSwipeLength = touchObject.swipeLength; if (this.props.infinite === false) { if (currentSlide === 0 && swipeDirection === 'right' || currentSlide + 1 >= dotCount && swipeDirection === 'left') { touchSwipeLength = touchObject.swipeLength * this.props.edgeFriction; if (this.state.edgeDragged === false && this.props.edgeEvent) { this.props.edgeEvent(swipeDirection); this.setState({ edgeDragged: true }); } } } if (this.state.swiped === false && this.props.swipeEvent) { this.props.swipeEvent(swipeDirection); this.setState({ swiped: true }); } if (!this.props.vertical) { swipeLeft = curLeft + touchSwipeLength * positionOffset; } else { swipeLeft = curLeft + touchSwipeLength * (this.state.listHeight / this.state.listWidth) * positionOffset; } if (this.props.verticalSwiping) { swipeLeft = curLeft + touchSwipeLength * positionOffset; } this.setState({ touchObject: touchObject, swipeLeft: swipeLeft, trackStyle: (0, _trackHelper.getTrackCSS)((0, _objectAssign2.default)({ left: swipeLeft }, this.props, this.state)) }); if (Math.abs(touchObject.curX - touchObject.startX) < Math.abs(touchObject.curY - touchObject.startY) * 0.8) { return; } if (touchObject.swipeLength > 4) { e.preventDefault(); } }, getNavigableIndexes: function getNavigableIndexes() { var max = void 0; var breakPoint = 0; var counter = 0; var indexes = []; if (!this.props.infinite) { max = this.state.slideCount; } else { breakPoint = this.props.slidesToShow * -1; counter = this.props.slidesToShow * -1; max = this.state.slideCount * 2; } while (breakPoint < max) { indexes.push(breakPoint); breakPoint = counter + this.props.slidesToScroll; counter += this.props.slidesToScroll <= this.props.slidesToShow ? this.props.slidesToScroll : this.props.slidesToShow; } return indexes; }, checkNavigable: function checkNavigable(index) { var navigables = this.getNavigableIndexes(); var prevNavigable = 0; if (index > navigables[navigables.length - 1]) { index = navigables[navigables.length - 1]; } else { for (var n in navigables) { if (index < navigables[n]) { index = prevNavigable; break; } prevNavigable = navigables[n]; } } return index; }, getSlideCount: function getSlideCount() { var _this = this; var centerOffset = this.props.centerMode ? this.state.slideWidth * Math.floor(this.props.slidesToShow / 2) : 0; if (this.props.swipeToSlide) { var swipedSlide = void 0; var slickList = _reactDom2.default.findDOMNode(this.list); var slides = slickList.querySelectorAll('.slick-slide'); Array.from(slides).every(function (slide) { if (!_this.props.vertical) { if (slide.offsetLeft - centerOffset + _this.getWidth(slide) / 2 > _this.state.swipeLeft * -1) { swipedSlide = slide; return false; } } else { if (slide.offsetTop + _this.getHeight(slide) / 2 > _this.state.swipeLeft * -1) { swipedSlide = slide; return false; } } return true; }); var slidesTraversed = Math.abs(swipedSlide.dataset.index - this.state.currentSlide) || 1; return slidesTraversed; } else { return this.props.slidesToScroll; } }, swipeEnd: function swipeEnd(e) { if (this.props.swipeDisabled) { this.setState({ dragging: false }); return; } if (!this.state.dragging) { e.preventDefault(); return; } var touchObject = this.state.touchObject; var minSwipe = this.state.listWidth / this.props.touchThreshold; var swipeDirection = this.swipeDirection(touchObject); if (this.props.verticalSwiping) { minSwipe = this.state.listHeight / this.props.touchThreshold; } // reset the state of touch related state variables. this.setState({ dragging: false, edgeDragged: false, swiped: false, swipeLeft: null, touchObject: {} }); // Fix for #13 if (!touchObject.swipeLength) { return; } if (touchObject.swipeLength > minSwipe) { e.preventDefault(); var slideCount = void 0, newSlide = void 0; switch (swipeDirection) { case 'left': case 'down': newSlide = this.state.currentSlide + this.getSlideCount(); slideCount = this.props.swipeToSlide ? this.checkNavigable(newSlide) : newSlide; this.state.currentDirection = 0; break; case 'right': case 'up': newSlide = this.state.currentSlide - this.getSlideCount(); slideCount = this.props.swipeToSlide ? this.checkNavigable(newSlide) : newSlide; this.state.currentDirection = 1; break; default: slideCount = this.state.currentSlide; } this.slideHandler(slideCount); } else { // Adjust the track back to it's original position. var currentLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2.default)({ slideIndex: this.state.currentSlide, trackRef: this.track }, this.props, this.state)); this.setState({ trackStyle: (0, _trackHelper.getTrackAnimateCSS)((0, _objectAssign2.default)({ left: currentLeft }, this.props, this.state)) }); } }, onInnerSliderEnter: function onInnerSliderEnter(e) { if (this.props.autoplay && this.props.pauseOnHover) { this.pause(); } }, onInnerSliderLeave: function onInnerSliderLeave(e) { if (this.props.autoplay && this.props.pauseOnHover) { this.autoPlay(); } } }; exports.default = EventHandlers;
$(document).ready(function(){ $('.page-body-right #content').css({color:'gray'}); $('.page-body-right #content').one('focus',function(){ $(this).val(''); }); //类型选择 $('.page-body-right #ques-type').on('change',function(){ var type_id = $(this).find("option:selected").attr('value'); if( type_id == 1 ){ $('.page-body-right #ques-course-category').show(); $('.page-body-right #ques-category').hide(); }else{ $('.page-body-right #ques-category').show(); $('.page-body-right #ques-course-category').hide(); } }); var type_id = ''; var ques_category_id = ''; var ques_course_category_id = ''; var is_open = ''; var title = ''; var content = ''; var questionSubmit = function(){ var check_info = $('.page-body-right #check-info'); $('.page-body-right #question-form').on('keyup',function(e){ e.stopPropagation(); var self =$(this); self.on('keyup','#title',function(){ title = $(this).val(); //console.log(title.length); if( title.length >= 50 || title.length <2 ){ $(this).addClass('border-red'); check_info.show(); check_info.html('请输入2-50个长度的标题!'); }else{ $(this).removeClass('border-red'); check_info.hide(); }; }); self.on('keyup','#content',function(){ content = $(this).val(); //console.log(content.length); if(content.length < 4 || content.length >=300 ){ $(this).addClass('border-red'); check_info.show(); check_info.html('请输入4-300个长度的内容!'); }else{ $(this).removeClass('border-red'); check_info.hide(); } }); }); $('.page-body-right #question-form').on({ 'click':function(){ var self = $(this); self.on('change','#ques-type',function(){ type_id = $(this).find("option:selected").attr('value'); if(type_id) check_info.hide(); }); self.on('change','#ques-category',function(){ ques_category_id = $(this).find("option:selected").attr('value'); ques_course_category_id = ''; if(ques_category_id) check_info.hide(); }); self.on('change','#ques-course-category',function(){ ques_course_category_id = $(this).find("option:selected").attr('value'); ques_category_id = ''; if(ques_course_category_id) check_info.hide(); }); self.on('change','#is_open',function(){ is_open = $(this).find("option:selected").attr('value'); if(is_open) check_info.hide(); }); } }); $('.page-body-right ').on('mouseover','#ques-submit',function(){ var self = $(this); var ques_form = $(this).parent().parent().parent(); title = ques_form.find('#title').val(); type_id = ques_form.find("#ques-type").find("option:selected").attr('value'); ques_course_category_id = ques_form.find("#ques-course-category").find("option:selected").attr('value'); content = ques_form.find('#content').val(); }); $('.page-body-right ').on('click','#ques-submit',function(e){ //console.log(type_id); //console.log(ques_category_id); //console.log(ques_course_category_id); //console.log(is_open); //console.log(title); //console.log(content); if(!type_id){ // $(this).attr('disabled','disabled'); check_info.show(); check_info.html('请选择问题的类型!'); $('body ,html').animate({ scrollTop : 0 },300); return ; } if(type_id == 0){ if(!ques_category_id){ check_info.show(); check_info.html('请选择问题的分类!'); $('body ,html').animate({ scrollTop : 0 },300); return ; } }else{ if(!ques_course_category_id){ check_info.show(); check_info.html('请选择课程!'); $('body ,html').animate({ scrollTop : 0 },300); return ; } } if(!is_open){ check_info.show(); check_info.html('请选择是否公开!'); $('body ,html').animate({ scrollTop : 0 },300); return ; }else if(!title.length){ check_info.show(); check_info.html('请输入标题!'); $('body ,html').animate({ scrollTop : 0 },300); return ; }else if( title.length >= 50 || title.length <2 ){ check_info.show(); check_info.html('请输入2-50个长度的标题!'); $('body ,html').animate({ scrollTop : 0 },300); return ; }else if(content.length < 4 || content.length >=300){ check_info.show(); check_info.html('请输入4-300个长度的内容!'); $('body ,html').animate({ scrollTop : 0 },300); return ; } var self = $(this); var btn = self.button('loading'); $.post($.U('Question/ajax_add_question'),{ type_id:type_id, ques_category_id:ques_category_id, ques_course_category_id:ques_course_category_id, is_open:is_open, title:title, content:content },function(data,status){ console.log(data); if( status == 'success' && data.status){ $('.page-body-right #question-form').find('#myModal').find('.modal-body').html(data.info); $('#myModal').modal('toggle'); $('#myModal').on('click',function(){ $('.page-body-right #question-form').find(":input").not(":button,:submit,:reset,:hidden").val("").removeAttr("checked").removeAttr("selected"); btn.button('reset'); }); }else { $('.page-body-right #question-form').find('#myModal').find('.modal-body').html('数据请求失败!'); $('#myModal').modal('toggle'); btn.button('reset'); } },'json'); }); } questionSubmit(); });
require('./main.css'); let component = require('./component'); document.body.appendChild(component());
const Hapi = require('hapi'); const Inert = require('inert'); const Request = require('request'); const Querystring = require('querystring'); const Env = require('env2')('./config.env'); const cookieAuth = require('hapi-auth-cookie'); const server = new Hapi.Server(); const port = process.env.PORT || 3000; // separate function so that it's easier to test functionality later const getUserDetails = (accessToken, cb) => { Request.get({ url: 'https://api.github.com/user', headers: { // Required header keys can be found in the API documentation // Name of the application 'User-Agent': 'OAuth workshop', // Common signature that is used for web tokens Authorization: `token ${accessToken}` } }, cb); } server.connection({ port: port }); const options = { password: process.env.ENCRYPTION_CODE, cookie: 'activeUserCookie', isSecure: false, ttl: 24 * 60 * 60 * 1000 }; server.register([cookieAuth, Inert], (err) => { if (err) {throw err}; server.auth.strategy('session', 'cookie', options); // when registering the cookie auth plugin, routes should be inside the callback // inert plugin is activated immediately though server.route([{ method: 'GET', path: '/{file*}', handler: { directory: { path: 'public' } } },{ method: 'GET', path: '/login', handler: (req, reply) => { const githubLink = 'https://github.com/login/oauth/authorize'; const queryParams = Querystring.stringify({'client_id':process.env.CLIENT_ID, 'redirect_uri':process.env.BASE_URL + '/welcome'}); reply.redirect(`${githubLink}?${queryParams}`); } },{ method: 'GET', path: '/welcome', config: { handler: (req, reply) => { const accessTokenUrl = 'https://github.com/login/oauth/access_token'; Request({ headers: { accept: 'application/json', }, url: accessTokenUrl, method: 'POST', form: { client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, code: req.query.code } },(err,res,body) => { if (err) throw err; const json = JSON.parse(body) console.log(json.access_token); const userDetails = { access_token: json.access_token }; req.cookieAuth.set(userDetails); reply.redirect('/profile'); }) } } }, { method: 'GET', path: '/profile', config: { auth: { mode: 'try', // try to go to page even if the strategy is not loaded strategy: 'session' }, handler: (req, reply) => { // First attempt to test if the cookie works // console.log(req.auth.credentials.access_token); // reply('Welcome to your profile!'); // Make an API call to the Github API to get user details getUserDetails(req.auth.credentials.access_token, (err, res, body) => { if (err) throw err; reply(JSON.parse(body)); }) } } } ]); }); server.start((err) => { if(err) throw err; console.log('Server is up and running at ', server.info.uri); })
import React from 'react'; import { shallow } from 'enzyme'; import expect from 'expect'; import { GroupButton } from '../../../components/dashboard/GroupButton.jsx'; import mockData from '../../mockData'; describe('GroupButton Component', () => { it('should render GroupButton component', () => { const wrapper = shallow(<GroupButton {...mockData.GroupButton.props }/>); expect(wrapper.node.props.className) .toEqual('btn waves-effect waves-light groupBut'); expect(wrapper.node.props.name).toEqual('action'); }); it('should call onClick', () => { const wrapper = shallow(<GroupButton {...mockData.GroupButton.props}/>); const span = wrapper.find('button'); span.simulate('click', { target: { id: 'VIEW MEMBERS' } }); }); });
'use strict'; const router = require('express').Router(); const auth = require('./authentication'); router.post('/', auth.authenticate); module.exports = router;
define([ 'jquery', '../utils' ], function ($, Utils) { function AttachBody (decorated, $element, options) { this.$dropdownParent = options.get('dropdownParent') || document.body; decorated.call(this, $element, options); } AttachBody.prototype.bind = function (decorated, container, $container) { var self = this; var setupResultsEvents = false; decorated.call(this, container, $container); container.on('open', function () { self._showDropdown(); self._attachPositioningHandler(container); if (!setupResultsEvents) { setupResultsEvents = true; container.on('results:all', function () { self._positionDropdown(); self._resizeDropdown(); }); container.on('results:append', function () { self._positionDropdown(); self._resizeDropdown(); }); } }); container.on('close', function () { self._hideDropdown(); self._detachPositioningHandler(container); }); this.$dropdownContainer.on('mousedown', function (evt) { evt.stopPropagation(); }); }; AttachBody.prototype.position = function (decorated, $dropdown, $container) { // Clone all of the container classes $dropdown.attr('class', $container.attr('class')); $dropdown.removeClass('select2'); $dropdown.addClass('select2-container--open'); $dropdown.css({ position: 'absolute', top: -999999 }); this.$container = $container; }; AttachBody.prototype.render = function (decorated) { var $container = $('<span></span>'); var $dropdown = decorated.call(this); $container.append($dropdown); this.$dropdownContainer = $container; return $container; }; AttachBody.prototype._hideDropdown = function (decorated) { this.$dropdownContainer.detach(); }; AttachBody.prototype._attachPositioningHandler = function (container) { var self = this; var scrollEvent = 'scroll.select2.' + container.id; var resizeEvent = 'resize.select2.' + container.id; var orientationEvent = 'orientationchange.select2.' + container.id; var $watchers = this.$container.parents().filter(Utils.hasScroll); $watchers.each(function () { $(this).data('select2-scroll-position', { x: $(this).scrollLeft(), y: $(this).scrollTop() }); }); $watchers.on(scrollEvent, function (ev) { var position = $(this).data('select2-scroll-position'); $(this).scrollTop(position.y); }); $(window).on(scrollEvent + ' ' + resizeEvent + ' ' + orientationEvent, function (e) { self._positionDropdown(); self._resizeDropdown(); }); }; AttachBody.prototype._detachPositioningHandler = function (container) { var scrollEvent = 'scroll.select2.' + container.id; var resizeEvent = 'resize.select2.' + container.id; var orientationEvent = 'orientationchange.select2.' + container.id; var $watchers = this.$container.parents().filter(Utils.hasScroll); $watchers.off(scrollEvent); $(window).off(scrollEvent + ' ' + resizeEvent + ' ' + orientationEvent); }; AttachBody.prototype._positionDropdown = function () { var $window = $(window); var isCurrentlyAbove = this.$dropdown.hasClass('select2-dropdown--above'); var isCurrentlyBelow = this.$dropdown.hasClass('select2-dropdown--below'); var newDirection = null; var position = this.$container.position(); var offset = this.$container.offset(); offset.bottom = offset.top + this.$container.outerHeight(false); var container = { height: this.$container.outerHeight(false) }; container.top = offset.top; container.bottom = offset.top + container.height; var dropdown = { height: this.$dropdown.outerHeight(false) }; var viewport = { top: $window.scrollTop(), bottom: $window.scrollTop() + $window.height() }; var enoughRoomAbove = viewport.top < (offset.top - dropdown.height); var enoughRoomBelow = viewport.bottom > (offset.bottom + dropdown.height); var css = { left: offset.left, top: container.bottom }; if (!isCurrentlyAbove && !isCurrentlyBelow) { newDirection = 'below'; } if (!enoughRoomBelow && enoughRoomAbove && !isCurrentlyAbove) { newDirection = 'above'; } else if (!enoughRoomAbove && enoughRoomBelow && isCurrentlyAbove) { newDirection = 'below'; } if (newDirection == 'above' || (isCurrentlyAbove && newDirection !== 'below')) { css.top = container.top - dropdown.height; } if (newDirection != null) { this.$dropdown .removeClass('select2-dropdown--below select2-dropdown--above') .addClass('select2-dropdown--' + newDirection); this.$container .removeClass('select2-container--below select2-container--above') .addClass('select2-container--' + newDirection); } this.$dropdownContainer.css(css); }; AttachBody.prototype._resizeDropdown = function () { var css = { width: this.$container.outerWidth(false) + 'px' }; if (this.options.get('dropdownAutoWidth')) { css.minWidth = css.width; css.width = 'auto'; } this.$dropdown.css(css); }; AttachBody.prototype._showDropdown = function (decorated) { this.$dropdownContainer.appendTo(this.$dropdownParent); this._positionDropdown(); this._resizeDropdown(); }; return AttachBody; });
/*! * ezLife AutoIn - The most easiest Anime i.ntere.st bot ever made * https://github.com/KazeFlame/ezLife-AutoIn/ * * Copyright 2015 by KazeFlame and contributors * Released under the MIT license * https://github.com/KazeFlame/ezLife-AutoIn/blob/master/LICENSE * */ KangoAPI.onReady(function(){ kango.browser.tabs.getCurrent(function(tab){ // Current url in the tab var currentUrl = tab.getUrl(); // Check if the current tab is Anime i.ntere.st and if the user is logged in kango.invokeAsync('kango.storage.getItem', 'isLoggedIn', function(d_isLoggedIn){ if(currentUrl.match(/(http|https):\/\/i.ntere.st/gi) == null || d_isLoggedIn == false) { $('#autoInAlbum').prop('disabled', true); $('#autoInNewArrivals').prop('disabled', true); $('#autoCreateAlbum').prop('disabled', true); $('#dumpImages').prop('disabled', true); } }); $('#autoInAlbum').click(function(event){ // Set the action to be AutoIn Album kango.invokeAsync('kango.storage.setItem', 'action', 'autoInAlbum'); // Set the url for the action kango.invokeAsync('kango.storage.setItem', 'urlForAction', currentUrl); // Reload the current page to activate the action tab.navigate(currentUrl); }); }); });
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.12.3-6-a-2 description: > JSON.stringify truccates non-integer numeric space arguments to their integer part. includes: [runTestCase.js] ---*/ function testcase() { var obj = {a1: {b1: [1,2,3,4], b2: {c1: 1, c2: 2}},a2: 'a2'}; return JSON.stringify(obj,null, 5.99999)=== JSON.stringify(obj,null, 5); } runTestCase(testcase);
// Script: jQuery hashchange event // // *Version: 1.3, Last updated: 7/21/2010* // // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/ // GitHub - http://github.com/cowboy/jquery-hashchange/ // Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js // (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // These working examples, complete with fully commented code, illustrate a few // ways in which this plugin can be used. // // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/ // document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5, // Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5. // Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/ // // About: Known issues // // While this jQuery hashchange event implementation is quite stable and // robust, there are a few unfortunate browser bugs surrounding expected // hashchange event-based behaviors, independent of any JavaScript // window.onhashchange abstraction. See the following examples for more // information: // // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/ // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/ // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/ // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/ // // Also note that should a browser natively support the window.onhashchange // event, but not report that it does, the fallback polling loop will be used. // // About: Release History // // 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more // "removable" for mobile-only development. Added IE6/7 document.title // support. Attempted to make Iframe as hidden as possible by using // techniques from http://www.paciellogroup.com/blog/?p=604. Added // support for the "shortcut" format $(window).hashchange( fn ) and // $(window).hashchange() like jQuery provides for built-in events. // Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and // lowered its default value to 50. Added <jQuery.fn.hashchange.domain> // and <jQuery.fn.hashchange.src> properties plus document-domain.html // file to address access denied issues when setting document.domain in // IE6/7. // 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin // from a page on another domain would cause an error in Safari 4. Also, // IE6/7 Iframe is now inserted after the body (this actually works), // which prevents the page from scrolling when the event is first bound. // Event can also now be bound before DOM ready, but it won't be usable // before then in IE6/7. // 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug // where browser version is incorrectly reported as 8.0, despite // inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag. // 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special // window.onhashchange functionality into a separate plugin for users // who want just the basic event & back button support, without all the // extra awesomeness that BBQ provides. This plugin will be included as // part of jQuery BBQ, but also be available separately. (function($,window,undefined){ // Reused string. var str_hashchange = 'hashchange', // Method / object references. doc = document, fake_onhashchange, special = $.event.special, // Does the browser support window.onhashchange? Note that IE8 running in // IE7 compatibility mode reports true for 'onhashchange' in window, even // though the event isn't supported, so also test document.documentMode. doc_mode = doc.documentMode, supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 ); // Get location.hash (or what you'd expect location.hash to be) sans any // leading #. Thanks for making this necessary, Firefox! function get_fragment( url ) { url = url || location.href; return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' ); }; // Method: jQuery.fn.hashchange // // Bind a handler to the window.onhashchange event or trigger all bound // window.onhashchange event handlers. This behavior is consistent with // jQuery's built-in event handlers. // // Usage: // // > jQuery(window).hashchange( [ handler ] ); // // Arguments: // // handler - (Function) Optional handler to be bound to the hashchange // event. This is a "shortcut" for the more verbose form: // jQuery(window).bind( 'hashchange', handler ). If handler is omitted, // all bound window.onhashchange event handlers will be triggered. This // is a shortcut for the more verbose // jQuery(window).trigger( 'hashchange' ). These forms are described in // the <hashchange event> section. // // Returns: // // (jQuery) The initial jQuery collection of elements. // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and // $(elem).hashchange() for triggering, like jQuery does for built-in events. $.fn[ str_hashchange ] = function( fn ) { return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange ); }; // Property: jQuery.fn.hashchange.delay // // The numeric interval (in milliseconds) at which the <hashchange event> // polling loop executes. Defaults to 50. // Property: jQuery.fn.hashchange.domain // // If you're setting document.domain in your JavaScript, and you want hash // history to work in IE6/7, not only must this property be set, but you must // also set document.domain BEFORE jQuery is loaded into the page. This // property is only applicable if you are supporting IE6/7 (or IE8 operating // in "IE7 compatibility" mode). // // In addition, the <jQuery.fn.hashchange.src> property must be set to the // path of the included "document-domain.html" file, which can be renamed or // modified if necessary (note that the document.domain specified must be the // same in both your main JavaScript as well as in this file). // // Usage: // // jQuery.fn.hashchange.domain = document.domain; // Property: jQuery.fn.hashchange.src // // If, for some reason, you need to specify an Iframe src file (for example, // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can // do so using this property. Note that when using this property, history // won't be recorded in IE6/7 until the Iframe src file loads. This property // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7 // compatibility" mode). // // Usage: // // jQuery.fn.hashchange.src = 'path/to/file.html'; $.fn[ str_hashchange ].delay = 50; /* $.fn[ str_hashchange ].domain = null; $.fn[ str_hashchange ].src = null; */ // Event: hashchange event // // Fired when location.hash changes. In browsers that support it, the native // HTML5 window.onhashchange event is used, otherwise a polling loop is // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7 // compatibility" mode), a hidden Iframe is created to allow the back button // and hash-based history to work. // // Usage as described in <jQuery.fn.hashchange>: // // > // Bind an event handler. // > jQuery(window).hashchange( function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).hashchange(); // // A more verbose usage that allows for event namespacing: // // > // Bind an event handler. // > jQuery(window).bind( 'hashchange', function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).trigger( 'hashchange' ); // // Additional Notes: // // * The polling loop and Iframe are not created until at least one handler // is actually bound to the 'hashchange' event. // * If you need the bound handler(s) to execute immediately, in cases where // a location.hash exists on page load, via bookmark or page refresh for // example, use jQuery(window).hashchange() or the more verbose // jQuery(window).trigger( 'hashchange' ). // * The event can be bound before DOM ready, but since it won't be usable // before then in IE6/7 (due to the necessary Iframe), recommended usage is // to bind it inside a DOM ready handler. // Override existing $.event.special.hashchange methods (allowing this plugin // to be defined after jQuery BBQ in BBQ's source code). special[ str_hashchange ] = $.extend( special[ str_hashchange ], { // Called only when the first 'hashchange' event is bound to window. setup: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to create our own. And we don't want to call this // until the user binds to the event, just in case they never do, since it // will create a polling loop and possibly even a hidden Iframe. $( fake_onhashchange.start ); }, // Called only when the last 'hashchange' event is unbound from window. teardown: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to stop ours (if possible). $( fake_onhashchange.stop ); } }); // fake_onhashchange does all the work of triggering the window.onhashchange // event for browsers that don't natively support it, including creating a // polling loop to watch for hash changes and in IE 6/7 creating a hidden // Iframe to enable back and forward. fake_onhashchange = (function(){ var self = {}, timeout_id, // Remember the initial hash so it doesn't get triggered immediately. last_hash = get_fragment(), fn_retval = function(val){ return val; }, history_set = fn_retval, history_get = fn_retval; // Start the polling loop. self.start = function() { timeout_id || poll(); }; // Stop the polling loop. self.stop = function() { timeout_id && clearTimeout( timeout_id ); timeout_id = undefined; }; // This polling loop checks every $.fn.hashchange.delay milliseconds to see // if location.hash has changed, and triggers the 'hashchange' event on // window when necessary. function poll() { var hash = get_fragment(), history_hash = history_get( last_hash ); if ( hash !== last_hash ) { history_set( last_hash = hash, history_hash ); $(window).trigger( str_hashchange ); } else if ( history_hash !== last_hash ) { location.href = location.href.replace( /#.*/, '' ) + history_hash; } timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay ); }; // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv $.browser.msie && !supports_onhashchange && (function(){ // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8 // when running in "IE7 compatibility" mode. var iframe, iframe_src; // When the event is bound and polling starts in IE 6/7, create a hidden // Iframe for history handling. self.start = function(){ if ( !iframe ) { iframe_src = $.fn[ str_hashchange ].src; iframe_src = iframe_src && iframe_src + get_fragment(); // Create hidden Iframe. Attempt to make Iframe as hidden as possible // by using techniques from http://www.paciellogroup.com/blog/?p=604. iframe = $('<iframe tabindex="-1" title="empty"/>').hide() // When Iframe has completely loaded, initialize the history and // start polling. .one( 'load', function(){ iframe_src || history_set( get_fragment() ); poll(); }) // Load Iframe src if specified, otherwise nothing. .attr( 'src', iframe_src || 'javascript:0' ) // Append Iframe after the end of the body to prevent unnecessary // initial page scrolling (yes, this works). .insertAfter( 'body' )[0].contentWindow; // Whenever `document.title` changes, update the Iframe's title to // prettify the back/next history menu entries. Since IE sometimes // errors with "Unspecified error" the very first time this is set // (yes, very useful) wrap this with a try/catch block. doc.onpropertychange = function(){ try { if ( event.propertyName === 'title' ) { iframe.document.title = doc.title; } } catch(e) {} }; } }; // Override the "stop" method since an IE6/7 Iframe was created. Even // if there are no longer any bound event handlers, the polling loop // is still necessary for back/next to work at all! self.stop = fn_retval; // Get history by looking at the hidden Iframe's location.hash. history_get = function() { return get_fragment( iframe.location.href ); }; // Set a new history item by opening and then closing the Iframe // document, *then* setting its location.hash. If document.domain has // been set, update that as well. history_set = function( hash, history_hash ) { var iframe_doc = iframe.document, domain = $.fn[ str_hashchange ].domain; if ( hash !== history_hash ) { // Update Iframe with any initial `document.title` that might be set. iframe_doc.title = doc.title; // Opening the Iframe's document after it has been closed is what // actually adds a history entry. iframe_doc.open(); // Set document.domain for the Iframe document as well, if necessary. domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' ); iframe_doc.close(); // Update the Iframe's hash, for great justice. iframe.location.hash = hash; } }; })(); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return self; })(); })(jQuery,this);
/* * grunt-assetic-dump * https://github.com/adam187/grunt-assetic-dump * * Copyright (c) 2013 Adam Misiorny * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>', ], options: { jshintrc: '.jshintrc', }, }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'], }, // Configuration to be run (and then tested). assetic_dump: { options: { configFile: 'test/app/config/config.yml', assetsBaseDir: 'test/fixtures/', webDir: 'tmp/' }, default_options: { }, custom_options: { webDir: 'tmp/custom_options/', options: { separator: '/* sep */\n', banner: '/* banner */\n', footer: '/* footer */\n' } } }, // Unit tests. nodeunit: { tests: ['test/*_test.js'], }, }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'assetic_dump', 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };
'use strict'; var yeoman = require('yeoman-generator'); module.exports = yeoman.generators.Base.extend({ initializing: function () {}, prompting: function() { var done = this.async(); var prompts = []; this.prompt(prompts, function(answers) { this.props = answers; done(); }.bind(this)); }, configuring: function() {}, default: {}, writing: function () { this.template('_gitignore', '.gitignore', this.props); }, conflicts: function() {}, install: function() {}, end: function() {} });
var should = require('should'); var EventEmitter = require('events').EventEmitter; var Midi = require('../../midi'); describe('midi.Input', function() { var input; beforeEach(()=>{ input = new Midi.Input();; }) afterEach(()=>{ input.closePort(); }) it('should raise when not called with new', function() { (function() { Midi.Input(); }).should.throw('Use the new operator to create instances of this object.'); }); it('should be an emitter', function() { input.should.be.an.instanceOf(EventEmitter); }); describe('.getPortCount', function() { it('.getPortCoun should return an integer', function() { // I feel like having more than 255 ports indicates a problem. input.getPortCount().should.be.within(0, 255); }); }); describe('.getPortName', function() { it('requires an argument', function() { (function() { input.getPortName(); }).should.throw('First argument must be an integer'); }); it('requires an integer', function() { (function() { input.getPortName('asdf'); }).should.throw('First argument must be an integer'); }); it('returns an empty string for unknown port', function() { input.getPortName(999).should.eql(''); }); }); describe('.openPort', function() { it('requires an argument', function() { (function() { input.openPort(); }).should.throw('First argument must be an integer'); }); it('requires an integer', function() { (function() { input.openPort('asdf'); }).should.throw('First argument must be an integer'); }); it('requires a valid port', function() { (function() { input.openPort(999); }).should.throw('Invalid MIDI port number'); }); }); describe('.openVirtualPort', function() { it('requires an argument', function() { (function() { input.openVirtualPort(); }).should.throw('First argument must be a string'); }); it('requires a string', function() { (function() { input.openVirtualPort(999); }).should.throw('First argument must be a string'); }); }); });
import buble from 'rollup-plugin-buble' import resolve from 'rollup-plugin-node-resolve' export default { entry: 'src/index.js', moduleName: 'WASD_Tetris', plugins: [ buble(), resolve() ], banner: '/*!\n' + ' * (c) 2016-' + new Date().getFullYear() + ' WASD-ORG\n' + ' * Released under the MIT License.\n' + ' */', targets: [ { dest: 'dist/tetris.js', format: 'umd' }, { dest: 'dist/tetris.common.js', format: 'cjs' }, { dest: 'dist/tetris.esm.js', format: 'es' } ] }
const assert = require("assert"); const path = require("path"); const _ = require("underscore"); module.exports = function (opcua) { opcua.ISA95.utils = {}; const BrowseDirection = opcua.browse_service.BrowseDirection; function _coerceISA95ReferenceType(addressSpace,obj) { const _coerced = typeof obj === "string" ? addressSpace.findISA95ReferenceType(obj) : obj; assert(_coerced,obj + " should exists in ISA95 addressSpace"); return _coerced; } function _coerceISA95ObjectType(addressSpace,obj) { const _coerced = typeof obj === "string" ? addressSpace.findISA95ObjectType(obj) : obj; assert(_coerced,obj.toString() + " should exists in ISA95 addressSpace"); return _coerced; } /** * * @param instance * @param FooClassReference * @param FooClassType * @param type must be a subtype Of FooClassType * @private * * * _addDefinedByFooClassReference(instance,"DefinedByEquipmentClass","EquipmentClassType",type); * will: * verify that type is a EquipmentClassType * add to instance, a DefinedByEquipmentClass reference pointing to type * update instance.definedByEquipmentClass by adding type to it. * */ function _addDefinedByFooClassReference(instance,FooClassReference,FooClassType,type) { assert(type," expecting a type"); assert(FooClassReference, "expecting a ClassReference"); assert(FooClassType, "expecting a FooClassType"); const addressSpace = instance.addressSpace; const definedByEquipmentClass = _coerceISA95ReferenceType(addressSpace,FooClassReference); const equipmentClassType = _coerceISA95ObjectType(addressSpace,FooClassType); // istanbul ignore next if(!type.isSupertypeOf(equipmentClassType)) { throw new Error(type.browseName.toString() + " must be of type "+ equipmentClassType.browseName.toString() ); } instance.addReference({ referenceType: definedByEquipmentClass.nodeId, nodeId: type }); // TODO : Add a __Getter__ property and use cache instead ... // set definedByEquipmentClass const attribute = opcua.utils.lowerFirstLetter(FooClassReference); if (!instance[attribute]) { instance[attribute] = []; } instance[attribute].push(type); } function addDefinedByFooClass(node,definedByFooClass,isa95PropertyType,options) { const addressSpace = node.addressSpace; const name = opcua.utils.capitalizeFirstLetter(definedByFooClass); const attribute = opcua.utils.lowerFirstLetter(definedByFooClass); const definedByFooClassReference = addressSpace.findISA95ReferenceType(name); if (!definedByFooClassReference) { throw new Error(" Cannot find ISA Reference Type " + name); } options[attribute] = options[attribute] || []; if (!_.isArray(options[attribute])) { options[attribute] = [options[attribute]]; } function addDefinedByFooClassReference(classType) { node.addReference({ referenceType: definedByFooClassReference.nodeId, nodeId: classType }); // also duplicate all hasIsa95ClassProperty of classType into HasIsa95Property on type const hasISA95ClassProperty = addressSpace.findISA95ReferenceType("HasISA95ClassProperty"); const hasISA95Property = addressSpace.findISA95ReferenceType("HasISA95ClassProperty"); const refs = classType.findReferencesExAsObject(hasISA95ClassProperty,BrowseDirection.Forward); function constructIsa95PropertyFromISA95ClassProperty(reference) { const srcProperty = addressSpace.findNode(reference.nodeId); // clone property const property = addressSpace.addISA95Property({ ISA95PropertyOf: node, browseName: srcProperty.browseName, dataType: srcProperty.dataType, value: srcProperty.readValue().value, typeDefinition: isa95PropertyType }); } refs.forEach(constructIsa95PropertyFromISA95ClassProperty); //xx console.log("[==>", refs.map(f => f.toString()).join("\n")); } options[attribute].forEach(addDefinedByFooClassReference); } opcua.ISA95.utils.addDefinedByFooClass = addDefinedByFooClass; /** * * @param params * @param params.node {UAObject} the node to add the DefinedBy...ClassType reference * @param params.definedByFooClass {String|UAObjectType|[]} * @param params.fooClassType * @param params.fooType * @param params.definedByFooClassRef = the r i.e "DefinedByEquipmentClass" * * example : * */ opcua.ISA95.utils.installDefinedByFooClassReferences = function(params) { assert(params.node); const addressSpace = params.node.addressSpace; // ------------------------------------------------------------------------------------------------------------- // Duplicate features defined in definedBy(Equipment|PhysicalAsset)Class // // My(Equipment|PhysicalAsset)ClassType (Equipment|PhysicalAsset)Type // | | // | \ +---definedBy(Equipment|PhysicalAsset)Class-->My(Equipment|PhysicalAsset)ClassType // | -------\ | // +-HasISA95ClassProperty-> "Property1" > +-HasISA95Property-->"Property1" // | -------/ // +- hasSubtypeOf -> / // (Equipment|PhysicalAsset)ClassType // ------------------------------------------------------------------------------------------------------------- // The Object identified by the SourceNode has the same features as that defined by the Object specified by TargetNode. if (typeof params.definedByFooClass === "string") { const node = addressSpace.findISA95ObjectType(params.definedByFooClass); if (!node) { throw Error(params.definedByFooClass +" must be a valid ISA95 Class Type"); } params.definedByFooClass = node; } if (!_.isArray(params.definedByFooClass)) { params.definedByFooClass =[params.definedByFooClass]; } if (typeof params.fooClassType === "string") { params.fooClassType = addressSpace.findISA95ObjectType(params.fooClassType); } for (const xxxxClass of params.definedByFooClass){ // we need to exclude OptionalPlaceHolder if (xxxxClass.modellingRule === "OptionalPlaceholder") { return; } assert(xxxxClass.isSupertypeOf(params.fooClassType),"expecting "); _addDefinedByFooClassReference( params.node, params.definedByFooClassRef, // "DefinedByEquipmentClass" params.fooClassType, // "EquipmentClassType", xxxxClass); } }; opcua.ISA95.utils._transferISA95Attributes = function (instance,classType) { // we need to exclude OptionalPlaceHolder if (classType.modellingRule === "OptionalPlaceholder") { return; } assert(classType.constructor.name == "UAObjectType"); const addressSpace = instance.addressSpace; const hasISA95Attribute = addressSpace.findISA95ReferenceType("HasISA95Attribute"); assert(hasISA95Attribute); const refs = classType.findReferencesEx(hasISA95Attribute); function constructIsa95AttributeFromISA95Attribute(reference) { const attribute = addressSpace.findNode(reference.nodeId); const _clone = attribute.clone(); instance.addReference({ referenceType: reference.referenceType, nodeId: _clone }); } refs.forEach(constructIsa95AttributeFromISA95Attribute); }; opcua.ISA95.utils._addContainedByFooReference = function (node,foo,fooType,madeUpOfFoo) { const addressSpace = node.addressSpace; assert(foo.nodeId instanceof opcua.NodeId); assert(typeof fooType === "string"); fooType = addressSpace.findISA95ObjectType(fooType); assert(typeof madeUpOfFoo === "string"); madeUpOfFoo = addressSpace.findISA95ReferenceType(madeUpOfFoo); // verify that containedByEquipment is really a equipment ! const t = foo.typeDefinitionObj; //xx console.log(t.toString()); //xx assert(equipmentType.isSupertypeOf(t),"options.containedByEquipment object must be of EquipmentType"); node.addReference({ referenceType: madeUpOfFoo.nodeId, isForward: false, nodeId: foo.nodeId }); let inverseName = madeUpOfFoo.inverseName.text.toString(); inverseName = opcua.utils.lowerFirstLetter(inverseName); // for inestance containedByEquipment node[inverseName] = foo; } };
var Model = require('../lib/Model'); var Properties = require('../lib/Properties'); describe('Model', function() { it('should assign properties to the object', function () { var aModel = new Model('test', { a: Properties.string }, {a: 'test'}); expect(aModel.a).toEqual('test'); }); it('should rename properties with specified attribute', function () { var aModel = new Model('test', { a: Properties.string('b') }, {b: 'test'}); expect(aModel.a).toEqual('test'); expect(aModel.b).toBeUndefined(); }); it('should have a method toString that returns the model name', function () { var aModel = new Model('test', { a: Properties.string }, {a: 'test'}); expect(aModel.toString()).toEqual('[test]'); }); it('should have a method toJSON that returns a JSON representation of model', function () { var aModel = new Model('test', { a: Properties.string }, {a: 'test'}); expect(aModel.toJSON()).toEqual({a: 'test'}); }); });
/*#if PROD*/ includeCore('browser/vendors/jquery-migrate-1.2.1-prod'); /*#else*/ includeCore('browser/vendors/jquery-migrate-1.2.1-dev'); /*#/if*/
a >>= 1
var API_v2_0 = require('./API_v2_0'); var util = require('util'); // Public Functions var API_v2_1 = function (v, storeT, storeL) { API_v2_0.apply(this, arguments); this.baseUrl = "https://api.mysportsfeeds.com/v2.1/pull"; }; util.inherits(API_v2_1, API_v2_0); exports = module.exports = API_v2_1;
import triangularSequence from '../src/triangularSequence/triangularSequence'; test('triangularSequence', () => { expect(triangularSequence(0)).toEqual([]); expect(triangularSequence(1)).toEqual([1]); expect(triangularSequence(2)).toEqual([1, 2]); expect(triangularSequence(3)).toEqual([1, 2, 2]); expect(triangularSequence(4)).toEqual([1, 2, 2, 3]); expect(triangularSequence(5)).toEqual([1, 2, 2, 3, 3]); });
/* * freakLoad - v0.1.0 * Preloader JS library * https://github.com/nofreakz/freakLoad * * Copyright (c) 2014 * MIT License */ ;(function($, win, doc) { 'use strict'; /* * DEFAULTS */ var _plugin = 'freakLoad', itemTpl = { node: undefined, url: '', data: {}, priority: 0.5, tags: [], async: true, progress: 0, onStart: $.noop, onComplete: $.noop, xhr: null }, groupTpl = { items: [], loaded: 0 }, defaults = { async: true, groupOrder: [], onStart: $.noop, onComplete: $.noop, item: { onStart: $.noop, onComplete: $.noop }, group: { onStart: $.noop, onComplete: $.noop } }; /* * CONSTRUCTOR */ function Plugin(items, options) { this.opt = $.extend(true, {}, defaults, options); this.init(items); } Plugin.prototype = { /* * DATA */ data: { // use queue as object to possibility multiple queues queue: { loaded: 0, items: [], groups: {} // @groupTpl }, requested: { items: [], groups: [] }, progress: 0 }, /* * PUBLIC */ init: function(items) { this._addItems(items); this.opt.onStart(); this.load(); }, load: function() { var group; // if has a groupOrder it'll load group by group listed // groups that weren't listed will load as regular item if (this.opt.groupOrder.length) { for (group in this.opt.groupOrder) { this.loadGroup(this.opt.groupOrder[group]); } } this._request(); }, loadGroup: function(groupName) { if (this._isGroup(groupName)) { this._request(groupName); } else { console.warn('No items was found to be loaded on the group "' + groupName + '".'); } }, // new items and a flag to indicate if have to load the new items add: function(items, load) { this._addItems(items); // load by default if (load === false ? load : true) { this.load(); } }, abort: function(item) { if (item) { _abortItem(item); return; } for (var l = this.queue.loaded; l < this.queue.length; l++) { _abortItem(this.queue.items[l]); } }, getData: function() { return this.data; }, /* * PRIVATE */ // add items to general and specific queue _addItems: function(items) { var queue = this.data.queue, item = {}, tag = '', i = 0, t = 0; items = this._normalizeItems(items); this._setPriority(items); for (i in items) { item = items[i]; queue.items[queue.items.length] = item; // create the new queues based on tags if (item.tags.length) { for (t in item.tags) { tag = item.tags[t]; this._createGroup(tag); // add item to specific queue queue.groups[tag].items[queue.groups[tag].items.length] = item; } } } }, _abortItem: function(item) { item.xhr.abort(); item.progress = 0; }, _normalizeItems: function(items) { var item = {}, i = 0; // if argument 'items' isn't a Array set as if (!(items instanceof Array)) { items = [items]; } // normalize with the template setted up previously for (i in items) { item = items[i]; if (typeof item !== 'object') { item = { url: item }; } items[i] = item = $.extend({}, itemTpl, item); item.priority = parseFloat(item.priority) || 0.1; } return items; }, _setPriority: function(items) { // organize items by priority items.sort(function(a, b) { return b.priority - a.priority; }); return items; }, _createGroup: function(tag) { // if the new tag still doesn't have a queue create one if (!this._isGroup(tag)) { // create a new group on groups this.data.queue.groups[tag] = $.extend(true, {}, groupTpl); } }, _isGroup: function(groupName) { return this.data.queue.groups.hasOwnProperty(groupName) ? true : false; }, // the _request will organize the queues that will be send to _load _request: function(groupName) { // group only will be setted if the function recive a groupName // otherwise group is going to the default queue of items var data = this.data, group = data.queue, i = 0, len = 0; // set group as lodaing and load the specific queue if (groupName) { group = data.queue.groups[groupName]; } // load items // stop loops when the number of loaded items is equal the size of the general queue for (len = group.items.length; i < len && data.requested.items.length < data.queue.items.length; i++) { this._load(group.items[i], group, groupName); } }, _load: function(item, group, groupName) { var self = this, data = this.data; // check if the item has been loaded // avoid multiple ajax calls for loaded items if (data.requested.items.indexOf(item.url) === -1) { // add to array of loaded items data.requested.items[data.requested.items.length] = item.url + ($.isPlainObject(item.data) ? '' : '?' + $.param(item.data)); // flag as loading and fire the starting callback (item.onStart !== $.noop ? item.onStart : this.opt.item.onStart)(item.node); if (groupName && data.requested.groups.indexOf(groupName) === -1) { data.requested.groups[data.requested.groups.length] = groupName; this.opt.group.onStart(groupName); } // set xhr item.xhr = $.ajax({ xhr: function() { var _xhr = new win.XMLHttpRequest(); _xhr.addEventListener('progress', function(evt) { if (evt.lengthComputable) { item.progress = evt.loaded / evt.total; } }, false); return _xhr; }, url: item.url, data: item.data, async: item.async ? item.async : self.opt.async }) .success(function(response) { if (groupName) { group.loaded++; } data.queue.loaded++; // the data will only be passed to callback if the item is a text file (item.onComplete !== $.noop ? item.onComplete : self.opt.item.onComplete)((/\.(xml|json|script|html|text)$/).test(item.url) ? response : '', item.node); // runs group callabck when complete all items if (groupName && (group.loaded === group.items.length || data.queue.loaded === data.queue.items.length)) { self.opt.group.onComplete(groupName); } // runs the final complete callabck when complete all items if (data.queue.loaded === data.queue.items.length) { self.opt.onComplete(); } // clean the xhr item.xhr = 'complete'; }) .fail(function(jqXHR) { item.xhr = 'fail'; throw jqXHR.responseText; }); } }, _updateProgress: function() {} }; /* * GLOBOL API */ $[_plugin] = function(fn, options) { var args = arguments, data = $.data(doc, _plugin), method = data && data[fn] ? data[fn] : false; // force to pass a method or items to plugin load if (!args.length) { throw 'The jquery plugin ' + _plugin + ' is not able to run whitout arguments or array of items to load.'; // if it still doesn't have been instanced, do that } else if (!data) { // fn here is the new items $.data(doc, _plugin, new Plugin(fn, options)); // check if data is a instance of the Plugin and fire the specific method // or simply add the new items to the loading } else if (data instanceof Plugin) { if (typeof method === 'function') { return method.apply(data, Array.prototype.slice.call(args, 1)); } else { $[_plugin]('add', fn); } // finally if the method doesn't exist or is a private method show a console error } else if (!method || (typeof fn === 'string' && fn.charAt(0) === '_')) { throw 'Method ' + fn + ' does not exist on jQuery.' + _plugin; } }; $.fn[_plugin] = function(itemOptions, generalOptions) { var items = $.map(this, function(item) { var dataset = JSON.parse(JSON.stringify(item.dataset)), tags = dataset.tags; dataset.tags = tags ? tags.replace(/\s+/g, '').split(',') : []; return $.extend({node: item}, dataset, itemOptions); }); $[_plugin](items, generalOptions); }; })(jQuery, window, document);
import setupStore from 'dummy/tests/helpers/store'; import Ember from 'ember'; import { isEnabled } from 'ember-data/-private'; import testInDebug from 'dummy/tests/helpers/test-in-debug'; import {module, test} from 'qunit'; import DS from 'ember-data'; var Post, post, Comment, comment, Favorite, favorite, env, serializer; var run = Ember.run; module("integration/serializer/json - JSONSerializer", { beforeEach() { Post = DS.Model.extend({ title: DS.attr('string'), comments: DS.hasMany('comment', { inverse: null, async: false }) }); Comment = DS.Model.extend({ body: DS.attr('string'), post: DS.belongsTo('post', { async: false }) }); Favorite = DS.Model.extend({ post: DS.belongsTo('post', { async: true, polymorphic: true }) }); env = setupStore({ post: Post, comment: Comment, favorite: Favorite }); env.store.modelFor('post'); env.store.modelFor('comment'); env.store.modelFor('favorite'); serializer = env.store.serializerFor('-json'); }, afterEach() { run(env.store, 'destroy'); } }); test("serialize doesn't include ID when includeId is false", function(assert) { run(() => { post = env.store.createRecord('post', { title: 'Rails is omakase', comments: [] }); }); let json = serializer.serialize(post._createSnapshot(), { includeId: false }); assert.deepEqual(json, { title: "Rails is omakase", comments: [] }); }); test("serialize doesn't include relationship if not aware of one", function(assert) { run(() => { post = env.store.createRecord('post', { title: 'Rails is omakase' }); }); let json = serializer.serialize(post._createSnapshot()); assert.deepEqual(json, { title: "Rails is omakase" }); }); test("serialize includes id when includeId is true", function(assert) { run(() => { post = env.store.createRecord('post', { title: 'Rails is omakase', comments: [] }); post.set('id', 'test'); }); let json = serializer.serialize(post._createSnapshot(), { includeId: true }); assert.deepEqual(json, { id: 'test', title: 'Rails is omakase', comments: [] }); }); if (isEnabled("ds-serialize-id")) { test("serializeId", function(assert) { run(() => { post = env.store.createRecord('post'); post.set('id', 'test'); }); let json = {}; serializer.serializeId(post._createSnapshot(), json, 'id'); assert.deepEqual(json, { id: 'test' }); }); test("modified serializeId is called from serialize", function(assert) { env.registry.register('serializer:post', DS.JSONSerializer.extend({ serializeId(snapshot, json, primaryKey) { var id = snapshot.id; json[primaryKey] = id.toUpperCase(); } })); run(function() { post = env.store.createRecord('post', { title: 'Rails is omakase' }); post.set('id', 'test'); }); var json = {}; json = env.store.serializerFor("post").serialize(post._createSnapshot(), { includeId: true }); assert.deepEqual(json, { id: 'TEST', title: 'Rails is omakase' }); }); test("serializeId respects `primaryKey` serializer property", function(assert) { env.registry.register('serializer:post', DS.JSONSerializer.extend({ primaryKey: '_ID_' })); run(function() { post = env.store.createRecord('post', { title: 'Rails is omakase' }); post.set('id', 'test'); }); var json = {}; json = env.store.serializerFor("post").serialize(post._createSnapshot(), { includeId: true }); assert.deepEqual(json, { _ID_: 'test', title: 'Rails is omakase' }); }); } test("serializeAttribute", function(assert) { run(function() { post = env.store.createRecord('post', { title: "Rails is omakase" }); }); var json = {}; serializer.serializeAttribute(post._createSnapshot(), json, "title", { type: "string" }); assert.deepEqual(json, { title: "Rails is omakase" }); }); test("serializeAttribute respects keyForAttribute", function(assert) { env.registry.register('serializer:post', DS.JSONSerializer.extend({ keyForAttribute(key) { return key.toUpperCase(); } })); run(function() { post = env.store.createRecord('post', { title: "Rails is omakase" }); }); var json = {}; env.store.serializerFor("post").serializeAttribute(post._createSnapshot(), json, "title", { type: "string" }); assert.deepEqual(json, { TITLE: "Rails is omakase" }); }); test("serializeBelongsTo", function(assert) { run(function() { post = env.store.createRecord('post', { title: "Rails is omakase", id: "1" }); comment = env.store.createRecord('comment', { body: "Omakase is delicious", post: post }); }); var json = {}; serializer.serializeBelongsTo(comment._createSnapshot(), json, { key: "post", options: {} }); assert.deepEqual(json, { post: "1" }); }); test("serializeBelongsTo with null", function(assert) { run(function() { comment = env.store.createRecord('comment', { body: "Omakase is delicious", post: null }); }); var json = {}; serializer.serializeBelongsTo(comment._createSnapshot(), json, { key: "post", options: {} }); assert.deepEqual(json, { post: null }, "Can set a belongsTo to a null value"); }); test("async serializeBelongsTo with null", function(assert) { Comment.reopen({ post: DS.belongsTo('post', { async: true }) }); run(function() { comment = env.store.createRecord('comment', { body: "Omakase is delicious", post: null }); }); var json = {}; serializer.serializeBelongsTo(comment._createSnapshot(), json, { key: "post", options: {} }); assert.deepEqual(json, { post: null }, "Can set a belongsTo to a null value"); }); test("serializeBelongsTo respects keyForRelationship", function(assert) { env.registry.register('serializer:post', DS.JSONSerializer.extend({ keyForRelationship(key, type) { return key.toUpperCase(); } })); run(function() { post = env.store.createRecord('post', { title: "Rails is omakase", id: "1" }); comment = env.store.createRecord('comment', { body: "Omakase is delicious", post: post }); }); var json = {}; env.store.serializerFor("post").serializeBelongsTo(comment._createSnapshot(), json, { key: "post", options: {} }); assert.deepEqual(json, { POST: "1" }); }); test("serializeHasMany respects keyForRelationship", function(assert) { env.registry.register('serializer:post', DS.JSONSerializer.extend({ keyForRelationship(key, type) { return key.toUpperCase(); } })); run(function() { post = env.store.createRecord('post', { title: "Rails is omakase", id: "1" }); comment = env.store.createRecord('comment', { body: "Omakase is delicious", post: post, id: "1" }); }); var json = {}; env.store.serializerFor("post").serializeHasMany(post._createSnapshot(), json, { key: "comments", options: {} }); assert.deepEqual(json, { COMMENTS: ["1"] }); }); test("serializeHasMany omits unknown relationships on pushed record", function(assert) { run(function() { post = env.store.push({ data: { id: "1", type: "post", attributes: { title: "Rails is omakase" } } }); }); var json = {}; env.store.serializerFor("post").serializeHasMany(post._createSnapshot(), json, { key: "comments", options: {} }); assert.ok(!json.hasOwnProperty("comments"), "Does not add the relationship key to json"); }); test("shouldSerializeHasMany", function(assert) { run(function() { post = env.store.createRecord('post', { title: "Rails is omakase", id: "1" }); comment = env.store.createRecord('comment', { body: "Omakase is delicious", post: post, id: "1" }); }); var snapshot = post._createSnapshot(); var relationship = snapshot.record.relationshipFor('comments'); var key = relationship.key; var shouldSerialize = env.store.serializerFor("post").shouldSerializeHasMany(snapshot, relationship, key); assert.ok(shouldSerialize, 'shouldSerializeHasMany correctly identifies with hasMany relationship'); }); if (isEnabled("ds-check-should-serialize-relationships")) { testInDebug("_shouldSerializeHasMany deprecation", function(assert) { env.store.serializerFor("post")._shouldSerializeHasMany = function() {}; assert.expectDeprecation(function() { env.store.serializerFor("post").shouldSerializeHasMany(); }, /_shouldSerializeHasMany has been promoted to the public API/); }); } test("serializeIntoHash", function(assert) { run(() => { post = env.store.createRecord('post', { title: "Rails is omakase", comments: [] }); }); let json = {}; serializer.serializeIntoHash(json, Post, post._createSnapshot()); assert.deepEqual(json, { title: "Rails is omakase", comments: [] }); }); test("serializePolymorphicType sync", function(assert) { assert.expect(1); env.registry.register('serializer:comment', DS.JSONSerializer.extend({ serializePolymorphicType(record, json, relationship) { let key = relationship.key; let belongsTo = record.belongsTo(key); json[relationship.key + "TYPE"] = belongsTo.modelName; assert.ok(true, 'serializePolymorphicType is called when serialize a polymorphic belongsTo'); } })); run(function() { post = env.store.createRecord('post', { title: 'Rails is omakase', id: 1 }); comment = env.store.createRecord('comment', { body: 'Omakase is delicious', post: post }); }); env.store.serializerFor('comment').serializeBelongsTo(comment._createSnapshot(), {}, { key: 'post', options: { polymorphic: true } }); }); test("serializePolymorphicType async", function(assert) { assert.expect(1); Comment.reopen({ post: DS.belongsTo('post', { async: true }) }); env.registry.register('serializer:comment', DS.JSONSerializer.extend({ serializePolymorphicType(record, json, relationship) { assert.ok(true, 'serializePolymorphicType is called when serialize a polymorphic belongsTo'); } })); run(function() { post = env.store.createRecord('post', { title: 'Rails is omakase', id: 1 }); comment = env.store.createRecord('comment', { body: 'Omakase is delicious', post: post }); }); env.store.serializerFor('comment').serializeBelongsTo(comment._createSnapshot(), {}, { key: 'post', options: { async: true, polymorphic: true } }); }); test("normalizeResponse normalizes each record in the array", function(assert) { var postNormalizeCount = 0; var posts = [ { id: "1", title: "Rails is omakase" }, { id: "2", title: "Another Post" } ]; env.registry.register('serializer:post', DS.JSONSerializer.extend({ normalize() { postNormalizeCount++; return this._super.apply(this, arguments); } })); run(function() { env.store.serializerFor("post").normalizeResponse(env.store, Post, posts, null, 'findAll'); }); assert.equal(postNormalizeCount, 2, "two posts are normalized"); }); test('Serializer should respect the attrs hash when extracting records', function(assert) { env.registry.register("serializer:post", DS.JSONSerializer.extend({ attrs: { title: "title_payload_key", comments: { key: 'my_comments' } } })); var jsonHash = { id: "1", title_payload_key: "Rails is omakase", my_comments: [1, 2] }; var post = env.store.serializerFor("post").normalizeResponse(env.store, Post, jsonHash, '1', 'findRecord'); assert.equal(post.data.attributes.title, "Rails is omakase"); assert.deepEqual(post.data.relationships.comments.data, [{ id: "1", type: "comment" }, { id: "2", type: "comment" }]); }); test('Serializer should map `attrs` attributes directly when keyForAttribute also has a transform', function(assert) { Post = DS.Model.extend({ authorName: DS.attr('string') }); env = setupStore({ post: Post }); env.registry.register("serializer:post", DS.JSONSerializer.extend({ keyForAttribute: Ember.String.underscore, attrs: { authorName: 'author_name_key' } })); var jsonHash = { id: "1", author_name_key: "DHH" }; var post = env.store.serializerFor("post").normalizeResponse(env.store, Post, jsonHash, '1', 'findRecord'); assert.equal(post.data.attributes.authorName, "DHH"); }); test('Serializer should respect the attrs hash when serializing records', function(assert) { Post.reopen({ parentPost: DS.belongsTo('post', { inverse: null, async: true }) }); env.registry.register("serializer:post", DS.JSONSerializer.extend({ attrs: { title: "title_payload_key", parentPost: { key: "my_parent" } } })); var parentPost; run(function() { env.store.push({ data: { type: 'post', id: '2', attributes: { title: "Rails is omakase" } } }); parentPost = env.store.peekRecord('post', 2); post = env.store.createRecord('post', { title: "Rails is omakase", parentPost: parentPost }); }); var payload = env.store.serializerFor("post").serialize(post._createSnapshot()); assert.equal(payload.title_payload_key, "Rails is omakase"); assert.equal(payload.my_parent, '2'); }); test('Serializer respects if embedded model has an attribute named "type" - #3726', function(assert) { env.registry.register("serializer:child", DS.JSONSerializer); env.registry.register("serializer:parent", DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { child: { embedded: 'always' } } })); env.registry.register("model:parent", DS.Model.extend({ child: DS.belongsTo('child') })); env.registry.register("model:child", DS.Model.extend({ type: DS.attr() })); var jsonHash = { id: 1, child: { id: 1, type: 'first_type' } }; var Parent = env.store.modelFor('parent'); var payload = env.store.serializerFor('parent').normalizeResponse(env.store, Parent, jsonHash, '1', 'findRecord'); assert.deepEqual(payload.included, [ { id: '1', type: 'child', attributes: { type: 'first_type' }, relationships: {} } ]); }); test('Serializer respects if embedded model has a relationship named "type" - #3726', function(assert) { env.registry.register("serializer:child", DS.JSONSerializer); env.registry.register("serializer:parent", DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { child: { embedded: 'always' } } })); env.registry.register("model:parent", DS.Model.extend({ child: DS.belongsTo('child') })); env.registry.register("model:child", DS.Model.extend({ type: DS.belongsTo('le-type') })); env.registry.register("model:le-type", DS.Model.extend()); var jsonHash = { id: 1, child: { id: 1, type: "my_type_id" } }; var Parent = env.store.modelFor('parent'); var payload = env.store.serializerFor('parent').normalizeResponse(env.store, Parent, jsonHash, '1', 'findRecord'); assert.deepEqual(payload.included, [ { id: '1', type: 'child', attributes: {}, relationships: { type: { data: { id: 'my_type_id', type: 'le-type' } } } } ]); }); test('Serializer respects `serialize: false` on the attrs hash', function(assert) { assert.expect(2); env.registry.register("serializer:post", DS.JSONSerializer.extend({ attrs: { title: { serialize: false } } })); run(function() { post = env.store.createRecord('post', { title: "Rails is omakase" }); }); var payload = env.store.serializerFor("post").serialize(post._createSnapshot()); assert.ok(!payload.hasOwnProperty('title'), "Does not add the key to instance"); assert.ok(!payload.hasOwnProperty('[object Object]'), "Does not add some random key like [object Object]"); }); test('Serializer respects `serialize: false` on the attrs hash for a `hasMany` property', function(assert) { assert.expect(1); env.registry.register("serializer:post", DS.JSONSerializer.extend({ attrs: { comments: { serialize: false } } })); run(function() { post = env.store.createRecord('post', { title: "Rails is omakase" }); comment = env.store.createRecord('comment', { body: "Omakase is delicious", post: post }); }); var serializer = env.store.serializerFor("post"); var serializedProperty = serializer.keyForRelationship('comments', 'hasMany'); var payload = serializer.serialize(post._createSnapshot()); assert.ok(!payload.hasOwnProperty(serializedProperty), "Does not add the key to instance"); }); test('Serializer respects `serialize: false` on the attrs hash for a `belongsTo` property', function(assert) { assert.expect(1); env.registry.register("serializer:comment", DS.JSONSerializer.extend({ attrs: { post: { serialize: false } } })); run(function() { post = env.store.createRecord('post', { title: "Rails is omakase" }); comment = env.store.createRecord('comment', { body: "Omakase is delicious", post: post }); }); var serializer = env.store.serializerFor("comment"); var serializedProperty = serializer.keyForRelationship('post', 'belongsTo'); var payload = serializer.serialize(comment._createSnapshot()); assert.ok(!payload.hasOwnProperty(serializedProperty), "Does not add the key to instance"); }); test('Serializer respects `serialize: false` on the attrs hash for a `hasMany` property', function(assert) { assert.expect(1); env.registry.register("serializer:post", DS.JSONSerializer.extend({ attrs: { comments: { serialize: false } } })); run(function() { post = env.store.createRecord('post', { title: "Rails is omakase" }); comment = env.store.createRecord('comment', { body: "Omakase is delicious", post: post }); }); var serializer = env.store.serializerFor("post"); var serializedProperty = serializer.keyForRelationship('comments', 'hasMany'); var payload = serializer.serialize(post._createSnapshot()); assert.ok(!payload.hasOwnProperty(serializedProperty), "Does not add the key to instance"); }); test('Serializer respects `serialize: false` on the attrs hash for a `belongsTo` property', function(assert) { assert.expect(1); env.registry.register("serializer:comment", DS.JSONSerializer.extend({ attrs: { post: { serialize: false } } })); run(function() { post = env.store.createRecord('post', { title: "Rails is omakase" }); comment = env.store.createRecord('comment', { body: "Omakase is delicious", post: post }); }); var serializer = env.store.serializerFor("comment"); var serializedProperty = serializer.keyForRelationship('post', 'belongsTo'); var payload = serializer.serialize(comment._createSnapshot()); assert.ok(!payload.hasOwnProperty(serializedProperty), "Does not add the key to instance"); }); test('Serializer respects `serialize: true` on the attrs hash for a `hasMany` property', function(assert) { assert.expect(1); env.registry.register("serializer:post", DS.JSONSerializer.extend({ attrs: { comments: { serialize: true } } })); run(function() { post = env.store.createRecord('post', { title: "Rails is omakase" }); comment = env.store.createRecord('comment', { body: "Omakase is delicious", post: post }); }); var serializer = env.store.serializerFor("post"); var serializedProperty = serializer.keyForRelationship('comments', 'hasMany'); var payload = serializer.serialize(post._createSnapshot()); assert.ok(payload.hasOwnProperty(serializedProperty), "Add the key to instance"); }); test('Serializer respects `serialize: true` on the attrs hash for a `belongsTo` property', function(assert) { assert.expect(1); env.registry.register("serializer:comment", DS.JSONSerializer.extend({ attrs: { post: { serialize: true } } })); run(function() { post = env.store.createRecord('post', { title: "Rails is omakase" }); comment = env.store.createRecord('comment', { body: "Omakase is delicious", post: post }); }); var serializer = env.store.serializerFor("comment"); var serializedProperty = serializer.keyForRelationship('post', 'belongsTo'); var payload = serializer.serialize(comment._createSnapshot()); assert.ok(payload.hasOwnProperty(serializedProperty), "Add the key to instance"); }); test("Serializer should merge attrs from superclasses", function(assert) { assert.expect(4); Post.reopen({ description: DS.attr('string'), anotherString: DS.attr('string') }); var BaseSerializer = DS.JSONSerializer.extend({ attrs: { title: "title_payload_key", anotherString: "base_another_string_key" } }); env.registry.register("serializer:post", BaseSerializer.extend({ attrs: { description: "description_payload_key", anotherString: "overwritten_another_string_key" } })); run(function() { post = env.store.createRecord("post", { title: "Rails is omakase", description: "Omakase is delicious", anotherString: "yet another string" }); }); var payload = env.store.serializerFor("post").serialize(post._createSnapshot()); assert.equal(payload.title_payload_key, "Rails is omakase"); assert.equal(payload.description_payload_key, "Omakase is delicious"); assert.equal(payload.overwritten_another_string_key, "yet another string"); assert.ok(!payload.base_another_string_key, "overwritten key is not added"); }); test("Serializer should respect the primaryKey attribute when extracting records", function(assert) { env.registry.register('serializer:post', DS.JSONSerializer.extend({ primaryKey: '_ID_' })); var jsonHash = { "_ID_": 1, title: "Rails is omakase" }; run(function() { post = env.store.serializerFor("post").normalizeResponse(env.store, Post, jsonHash, '1', 'findRecord'); }); assert.equal(post.data.id, "1"); assert.equal(post.data.attributes.title, "Rails is omakase"); }); test("Serializer should respect the primaryKey attribute when serializing records", function(assert) { env.registry.register('serializer:post', DS.JSONSerializer.extend({ primaryKey: '_ID_' })); run(function() { post = env.store.createRecord('post', { id: "1", title: "Rails is omakase" }); }); var payload = env.store.serializerFor("post").serialize(post._createSnapshot(), { includeId: true }); assert.equal(payload._ID_, "1"); }); test("Serializer should respect keyForAttribute when extracting records", function(assert) { env.registry.register('serializer:post', DS.JSONSerializer.extend({ keyForAttribute(key) { return key.toUpperCase(); } })); var jsonHash = { id: 1, TITLE: 'Rails is omakase' }; post = env.store.serializerFor("post").normalize(Post, jsonHash); assert.equal(post.data.id, "1"); assert.equal(post.data.attributes.title, "Rails is omakase"); }); test("Serializer should respect keyForRelationship when extracting records", function(assert) { env.registry.register('serializer:post', DS.JSONSerializer.extend({ keyForRelationship(key, type) { return key.toUpperCase(); } })); var jsonHash = { id: 1, title: 'Rails is omakase', COMMENTS: ['1'] }; post = env.store.serializerFor("post").normalize(Post, jsonHash); assert.deepEqual(post.data.relationships.comments.data, [{ id: "1", type: "comment" }]); }); test("Calling normalize should normalize the payload (only the passed keys)", function(assert) { assert.expect(1); var Person = DS.Model.extend({ posts: DS.hasMany('post', { async: false }) }); env.registry.register('serializer:post', DS.JSONSerializer.extend({ attrs: { notInHash: 'aCustomAttrNotInHash', inHash: 'aCustomAttrInHash' } })); env.registry.register('model:person', Person); Post.reopen({ content: DS.attr('string'), author: DS.belongsTo('person', { async: false }), notInHash: DS.attr('string'), inHash: DS.attr('string') }); var normalizedPayload = env.store.serializerFor("post").normalize(Post, { id: '1', title: 'Ember rocks', author: 1, aCustomAttrInHash: 'blah' }); assert.deepEqual(normalizedPayload, { "data": { "id": "1", "type": "post", "attributes": { "inHash": "blah", "title": "Ember rocks" }, "relationships": { "author": { "data": { "id": "1", "type": "person" } } } } }); }); test('serializeBelongsTo with async polymorphic', function(assert) { var json = {}; var expected = { post: '1', postTYPE: 'post' }; env.registry.register('serializer:favorite', DS.JSONSerializer.extend({ serializePolymorphicType(snapshot, json, relationship) { var key = relationship.key; json[key + 'TYPE'] = snapshot.belongsTo(key).modelName; } })); run(function() { post = env.store.createRecord('post', { title: 'Kitties are omakase', id: '1' }); favorite = env.store.createRecord('favorite', { post: post, id: '3' }); }); env.store.serializerFor('favorite').serializeBelongsTo(favorite._createSnapshot(), json, { key: 'post', options: { polymorphic: true, async: true } }); assert.deepEqual(json, expected, 'returned JSON is correct'); }); test('extractErrors respects custom key mappings', function(assert) { env.registry.register('serializer:post', DS.JSONSerializer.extend({ attrs: { title: 'le_title', comments: { key: 'my_comments' } } })); var payload = { errors: [ { source: { pointer: 'data/attributes/le_title' }, detail: "title errors" }, { source: { pointer: 'data/attributes/my_comments' }, detail: "comments errors" } ] }; var errors = env.store.serializerFor('post').extractErrors(env.store, Post, payload); assert.deepEqual(errors, { title: ["title errors"], comments: ["comments errors"] }); }); test('extractErrors expects error information located on the errors property of payload', function(assert) { env.registry.register('serializer:post', DS.JSONSerializer.extend()); var payload = { attributeWhichWillBeRemovedinExtractErrors: ["true"], errors: [ { source: { pointer: 'data/attributes/title' }, detail: "title errors" } ] }; var errors = env.store.serializerFor('post').extractErrors(env.store, Post, payload); assert.deepEqual(errors, { title: ["title errors"] }); }); test('extractErrors leaves payload untouched if it has no errors property', function(assert) { env.registry.register('serializer:post', DS.JSONSerializer.extend()); var payload = { untouchedSinceNoErrorsSiblingPresent: ["true"] }; var errors = env.store.serializerFor('post').extractErrors(env.store, Post, payload); assert.deepEqual(errors, { untouchedSinceNoErrorsSiblingPresent: ["true"] }); }); test('normalizeResponse should extract meta using extractMeta', function(assert) { env.registry.register("serializer:post", DS.JSONSerializer.extend({ extractMeta(store, modelClass, payload) { let meta = this._super(...arguments); meta.authors.push('Tomhuda'); return meta; } })); var jsonHash = { id: "1", title_payload_key: "Rails is omakase", my_comments: [1, 2], meta: { authors: ['Tomster'] } }; var post = env.store.serializerFor("post").normalizeResponse(env.store, Post, jsonHash, '1', 'findRecord'); assert.deepEqual(post.meta.authors, ['Tomster', 'Tomhuda']); }); test('normalizeResponse returns empty `included` payload by default', function(assert) { env.registry.register("serializer:post", DS.JSONSerializer.extend()); var jsonHash = { id: "1", title: "Rails is omakase" }; var post = env.store.serializerFor("post").normalizeResponse(env.store, Post, jsonHash, '1', 'findRecord'); assert.deepEqual(post.included, []); }); test('normalizeResponse returns empty `included` payload when relationship is undefined', function(assert) { env.registry.register("serializer:post", DS.JSONSerializer.extend()); var jsonHash = { id: "1", title: "Rails is omakase", comments: null }; var post = env.store.serializerFor("post").normalizeResponse(env.store, Post, jsonHash, '1', 'findRecord'); assert.deepEqual(post.included, []); }); test('normalizeResponse respects `included` items (single response)', function(assert) { env.registry.register("serializer:comment", DS.JSONSerializer); env.registry.register("serializer:post", DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: { embedded: 'always' } } })); var jsonHash = { id: "1", title: "Rails is omakase", comments: [ { id: "1", body: "comment 1" }, { id: "2", body: "comment 2" } ] }; var post = env.store.serializerFor("post").normalizeResponse(env.store, Post, jsonHash, '1', 'findRecord'); assert.deepEqual(post.included, [ { id: "1", type: "comment", attributes: { body: "comment 1" }, relationships: {} }, { id: "2", type: "comment", attributes: { body: "comment 2" }, relationships: {} } ]); }); test('normalizeResponse respects `included` items (array response)', function(assert) { env.registry.register("serializer:comment", DS.JSONSerializer); env.registry.register("serializer:post", DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: { embedded: 'always' } } })); var payload = [{ id: "1", title: "Rails is omakase", comments: [ { id: "1", body: "comment 1" } ] }, { id: "2", title: "Post 2", comments: [ { id: "2", body: "comment 2" }, { id: "3", body: "comment 3" } ] }]; var post = env.store.serializerFor("post").normalizeResponse(env.store, Post, payload, '1', 'findAll'); assert.deepEqual(post.included, [ { id: "1", type: "comment", attributes: { body: "comment 1" }, relationships: {} }, { id: "2", type: "comment", attributes: { body: "comment 2" }, relationships: {} }, { id: "3", type: "comment", attributes: { body: "comment 3" }, relationships: {} } ]); }); testInDebug('normalizeResponse ignores unmapped attributes', function(assert) { env.registry.register("serializer:post", DS.JSONSerializer.extend({ attrs: { title: { serialize: false }, notInMapping: { serialize: false } } })); var jsonHash = { id: "1", notInMapping: 'I should be ignored', title: "Rails is omakase" }; assert.expectWarning(function() { var post = env.store.serializerFor("post").normalizeResponse(env.store, Post, jsonHash, '1', 'findRecord'); assert.equal(post.data.attributes.title, "Rails is omakase"); }, /There is no attribute or relationship with the name/); }); test('options are passed to transform for serialization', function(assert) { assert.expect(1); env.registry.register('transform:custom', DS.Transform.extend({ serialize: function(deserialized, options) { assert.deepEqual(options, { custom: 'config' }); } })); Post.reopen({ custom: DS.attr('custom', { custom: 'config' }) }); var post; run(function() { post = env.store.createRecord('post', { custom: 'value' }); }); serializer.serialize(post._createSnapshot()); }); test('options are passed to transform for normalization', function(assert) { assert.expect(1); env.registry.register('transform:custom', DS.Transform.extend({ deserialize: function(serialized, options) { assert.deepEqual(options, { custom: 'config' }); } })); Post.reopen({ custom: DS.attr('custom', { custom: 'config' }) }); serializer.normalize(Post, { custom: 'value' }); }); test('Serializer should respect the attrs hash in links', function(assert) { env.registry.register("serializer:post", DS.JSONSerializer.extend({ attrs: { title: "title_payload_key", comments: { key: 'my_comments' } } })); var jsonHash = { title_payload_key: "Rails is omakase", links: { my_comments: 'posts/1/comments' } }; var post = env.container.lookup("serializer:post").normalizeSingleResponse(env.store, Post, jsonHash); assert.equal(post.data.attributes.title, "Rails is omakase"); assert.equal(post.data.relationships.comments.links.related, 'posts/1/comments'); }); if (isEnabled("ds-payload-type-hooks")) { test("mapping of model name can be customized via modelNameFromPayloadType", function(assert) { serializer.modelNameFromPayloadType = function(payloadType) { return payloadType.replace("api::v1::", ""); }; let jsonHash = { id: '1', post: { id: '1', type: "api::v1::post" } }; assert.expectNoDeprecation(); let normalized = serializer.normalizeSingleResponse(env.store, Favorite, jsonHash); assert.deepEqual(normalized, { data: { id: '1', type: 'favorite', attributes: {}, relationships: { post: { data: { id: '1', type: 'post' } } } }, included: [] }); }); testInDebug("DEPRECATED - mapping of model name can be customized via modelNameFromPayloadKey", function(assert) { serializer.modelNameFromPayloadKey = function(payloadType) { return payloadType.replace("api::v1::", ""); }; let jsonHash = { id: '1', post: { id: '1', type: "api::v1::post" } }; assert.expectDeprecation("You used modelNameFromPayloadKey to customize how a type is normalized. Use modelNameFromPayloadType instead"); let normalized = serializer.normalizeSingleResponse(env.store, Favorite, jsonHash); assert.deepEqual(normalized, { data: { id: '1', type: 'favorite', attributes: {}, relationships: { post: { data: { id: '1', type: 'post' } } } }, included: [] }); }); }
const { compile, not } = require('../index') test('not', () => { expect(compile(not.str)).toEqual({ not: { type: 'string' } }) })
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users'); var nutritions = require('../../app/controllers/nutritions'); // Nutritions Routes app.route('/nutritions') .get(users.requiresLogin, nutritions.list) .post(users.requiresLogin, nutritions.create); app.route('/nutritions/:nutritionId') .get(nutritions.read) .put(users.requiresLogin, nutritions.hasAuthorization, nutritions.update) .delete(users.requiresLogin, nutritions.hasAuthorization, nutritions.delete); // Finish by binding the Nutrition middleware app.param('nutritionId', nutritions.nutritionByID); };
describe("Utils", function() { var Utils = require('../lib/Utils'); var utils; beforeEach(function() { utils = new Utils(); }); it("should be able to validate that an empty string does not pass", function() { var result = utils.validatePassedString(""); expect(result).toBe(false); }); it("should be able to validate that non empty string does pass", function() { var result = utils.validatePassedString("test"); expect(result).toBe(true); }); });
/* @flow */ export default class ModelHelper { /* static toGlobalId(model: Model): string { invariant(model, 'Argument \'model\' is null'); if (model.type.endsWith('Edge')) { return toGlobalId( model.type, this._getGlobalIdParam(model.outID) + '___' + this._getGlobalIdParam(model.inID)); } return toGlobalId(model.type, this._getGlobalIdParam(model.id)); } */ }
import { __decorate } from "tslib"; import * as au from "../aurelia"; let ClickCounter = class ClickCounter { constructor() { this.count = 0; } increment() { this.count++; } }; ClickCounter = __decorate([ au.customElement("click-counter") ], ClickCounter); export { ClickCounter }; //# sourceMappingURL=click-counter.js.map
#!/usr/bin/env node "use strict"; var fs = require("fs"); var path = require("path"); var SnakeParser = require("../src/snakeParser.js"); // Helper function exitSuccess() { process.exit(0); } function exitFailure() { process.exit(1); } function abort(message) { console.error(message); exitFailure(); } function readStream(inputStream, callback) { var input = ""; inputStream.on("data", function(data) { input += data; }); inputStream.on("end", function() { callback(input); }); } // Arguments var rawArgs = process.argv.slice(2); var args = []; var exportVar = "module.exports"; while (rawArgs.length !== 0) { switch (rawArgs[0]) { case "-e": case "--export-var": rawArgs.shift(); if (rawArgs.length === 0) { abort("Missing parameter of the -e/--export-var option."); } exportVar = rawArgs[0]; break; case "-v": case "--version": console.log(SnakeParser.VERSION || "?"); exitSuccess(); case "-h": case "--help": console.log("Not implemented yet."); exitSuccess(); case "--": rawArgs.shift(); // Skip one argument. break; default: if (rawArgs[0].charAt(0) === "-") { abort("Unknown option: " + rawArgs[0] + "."); } args.push(rawArgs[0]); } rawArgs.shift(); } switch (args.length) { case 0: process.stdin.resume(); var inputStream = process.stdin; break; case 1: case 2: var inputFile = args[0]; var inputStream = fs.createReadStream(inputFile); inputStream.on("error", function() { abort("Can't read from file \"" + inputFile + "\"."); }); var outputFile = args.length === 1 ? args[0].replace(/\.[^.]*$/, ".js") : args[1]; break; default: abort("Too many arguments."); } readStream(inputStream, function(input) { // Build parser try { var source = SnakeParser.buildParser(input, { exportVariable: exportVar, }); } catch (e) { abort(e.message); } // Output if (outputFile) { var outputStream = fs.createWriteStream(outputFile); outputStream.on("error", function() { abort("Can't write to file \"" + outputFile + "\"."); }); } else { var outputStream = process.stdout; } outputStream.write(source); if (outputStream !== process.stdout) { outputStream.end(); } });
/** * Module dependencies. */ var express = require('express') , http = require('http') , path = require('path') , fs = require('fs') , qs = require('querystring') , persist = require("persist") , morgan = require('morgan') , cookieParser = require('cookie-parser') , methodOverride = require('method-override') , errorHandler = require('errorhandler') , hbs = require('hbs'); var CorsaHelper = require('./lib/Corsa/helper'); var app = express(); GLOBAL.hash = "dsfsd$@@Wdsafasd23e8"; GLOBAL.cookieHash = "dsf*jasda9#@#(@dsd"; GLOBAL.cookieName = "mimoData"; GLOBAL.app = app; // Due to some XML stuff, we need to override the default bodyParser app.use(function (req, res, next) { var data = ''; req.on('data', function (chunk) { data += chunk; }); req.on('end', function () { if (req.get('content-type') == 'application/x-www-form-urlencoded') { req.postData = req.body = qs.parse(data); } if (req.is('json')) { req.body = JSON.parse(data); } req.rawBody = data; next(); }); }); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, '/views')); app.use(morgan('dev')); app.use(cookieParser()); app.use(methodOverride()); app.use(express.static(path.join(__dirname, 'public'))); // overide jade with Handlebars app.set('view engine', 'html'); app.engine('html', require('hbs').__express); hbs.registerPartials(path.join(__dirname, '/views/partials')); // development only if ('development' == app.get('env')) { app.use(errorHandler()); } persist.connect({ driver: 'sqlite3', filename: './data/mimo.sqlite', trace: false }, function (err, connection) { if (err) { throw new Error("unable to connect to db"); } GLOBAL.persist = persist; GLOBAL.connection = connection; }); // bring in router require('./router')(app); if (app.get('env') == 'development') { http.createServer(app).listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); }); } else { var cluster = require('cluster'); var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', function (worker, code, signal) { console.log('worker ' + worker.process.pid + ' died'); }); } else { http.createServer(app).listen(8000,function () { console.log('Express server listening on port 8000'); }).listen(app.get('port')); } }
"use strict" const logger = require('../config/logger').mainLogger module.exports.floodFill = function (map) { const cells = [] for (let i = 0; i < map.cells.length; i++) { const cell = map.cells[i] cells[cell.x + ',' + cell.y + ',' + cell.z] = cell } const startTile = cells[map.startTile.x + ',' + map.startTile.y + ',' + map.startTile.z] floodFill( startTile, cells, { width : map.width, height: map.height, length: map.length } ) map.cells = [] for (let i in cells) { if (cells.hasOwnProperty(i)) { let cell = cells[i] map.cells.push(cell) } } } function floodFill(tile, cells, dim) { if (tile.tile.reachable) { return } else { tile.tile.reachable = true } if (cells[tile.x + ',' + (tile.y - 1) + ',' + tile.z] == null && tile.y - 2 > 0) { //top let top = cells[tile.x + ',' + (tile.y - 2) + ',' + tile.z] if (top == null) { top = { x : tile.x, y : tile.y - 2, z : tile.z, isTile: true, isWall: false, tile : {} } cells[tile.x + ',' + (tile.y - 2) + ',' + tile.z] = top } floodFill(top, cells, dim) } if (cells[(tile.x + 1) + ',' + tile.y + ',' + tile.z] == null && tile.x / 2 < dim.width) { //right let right = cells[(tile.x + 2) + ',' + tile.y + ',' + tile.z] if (right == null) { right = { x : tile.x + 2, y : tile.y, z : tile.z, isTile: true, isWall: false, tile : {} } cells[(tile.x + 2) + ',' + tile.y + ',' + tile.z] = right } floodFill(right, cells, dim) } if (cells[tile.x + ',' + (tile.y + 1) + ',' + tile.z] == null && tile.y / 2 < dim.length) { //bottom let bottom = cells[tile.x + ',' + (tile.y + 2) + ',' + tile.z] if (bottom == null) { bottom = { x : tile.x, y : tile.y + 2, z : tile.z, isTile: true, isWall: false, tile : {} } cells[tile.x + ',' + tile.y + 2 + ',' + tile.z] = bottom } floodFill(bottom, cells, dim) } if (cells[(tile.x - 1) + ',' + tile.y + ',' + tile.z] == null && tile.x - 2 > 0) { //left let left = cells[(tile.x - 2) + ',' + tile.y + ',' + tile.z] if (left == null) { left = { x : tile.x - 2, y : tile.y, z : tile.z, isTile: true, isWall: false, tile : {} } cells[(tile.x - 2) + ',' + tile.y + ',' + tile.z] = left } floodFill(left, cells, dim) } if (tile.tile.changeFloorTo != null && tile.tile.changeFloorTo != tile.z) { // Up/down let elev = cells[tile.x + ',' + tile.y + ',' + tile.tile.changeFloorTo] if (elev == null) { elev = { x : tile.x, y : tile.y, z : tile.tile.changeFloorTo, isTile: true, isWall: false, tile : { changeFloorTo: tile.z } } cells[tile.x + ',' + tile.y + ',' + tile.tile.changeFloorTo] = elev } floodFill(elev, cells, dim) } } module.exports.linearFill = function (map) { const cells = [] for (let i = 0; i < map.cells.length; i++) { const cell = map.cells[i] cell.isLinear = false cells[cell.x + ',' + cell.y + ',' + cell.z] = cell } cells[map.startTile.x + ',' + map.startTile.y + ',' + map.startTile.z].isLinear = true setAllSurroundingLinear(cells[(map.startTile.x - 1) + ',' + map.startTile.y + ',' + map.startTile.z], cells) setAllSurroundingLinear(cells[(map.startTile.x + 1) + ',' + map.startTile.y + ',' + map.startTile.z], cells) setAllSurroundingLinear(cells[map.startTile.x + ',' + (map.startTile.y - 1) + ',' + map.startTile.z], cells) setAllSurroundingLinear(cells[map.startTile.x + ',' + (map.startTile.y + 1) + ',' + map.startTile.z], cells) } function isOdd(n) { return n & 1 // Bitcheck LSB } function isEven(n) { return !isOdd(n) } function isHorizontal(wall) { return isOdd(wall.x) && isEven(wall.y) } function isVertical(wall) { return isEven(wall.x) && isOdd(wall.y) } function setAllSurroundingLinear(wall, cells) { if (wall == null) { return } if (wall.isLinear) { return } wall.isLinear = true //logger.debug("Linear at (" + wall.x + "," + wall.y + "," + wall.z + ")") for (let i = -(isHorizontal(wall) ? 2 : 1); i <= (isHorizontal(wall) ? 2 : 1); i++) { for (let j = -(isVertical(wall) ? 2 : 1); j <= (isVertical(wall) ? 2 : 1); j++) { let cell = cells[(wall.x + i) + ',' + (wall.y + j) + ',' + wall.z] if (cell != null) { if (cell.isWall) { setAllSurroundingLinear(cell, cells) } else if (cell.isTile) { cell.isLinear = true //logger.debug("Linear at (" + cell.x + "," + cell.y + "," + cell.z +")") if (cell.tile.changeFloorTo != cell.z) { setAllSurroundingLinear(cells[(cell.x - 1) + ',' + cell.y + ',' + cell.tile.changeFloorTo], cells) setAllSurroundingLinear(cells[(cell.x + 1) + ',' + cell.y + ',' + cell.tile.changeFloorTo], cells) setAllSurroundingLinear(cells[cell.x + ',' + (cell.y - 1) + ',' + cell.tile.changeFloorTo], cells) setAllSurroundingLinear(cells[cell.x + ',' + (cell.y + 1) + ',' + cell.tile.changeFloorTo], cells) } } } } } }
var postcss = require('postcss'); // Default properties for all layouts. var defaults = {}; defaults.container = { "box-sizing": "border-box", "margin-left": "0", "margin-right": "0", "text-align": "initial", "font-size": "initial" } defaults.item = { "box-sizing": "border-box", "display": "initial", "text-align": "initial", "vertical-align": "initial", "white-space": "initial", "font-size": "initial" } defaults.pseudo = { "position": "relative", "display": "none", "content": "normal", "clear": "none" } module.exports = postcss.plugin('postcss-layout', function (opts) { opts = opts || {}; // Attach the grids to the opts object if passed in, // mostly so it can be readout by tests. opts._grids = {}; var grids = opts._grids; return function (css, result) { // css.prepend({selector:'a', nodes: [{prop:'display', value:'none'}]}); // css.prepend(objToRule(defaults.item)); css .walkAtRules('grid', function(rule) { // Collect grid definitions. processGridDef(css, result, rule, grids); }); css .walkRules(function(rule) { var layout = {}; rule.walkDecls(function(decl) { // Collect layout info. processLayoutConf(css, result, rule, decl, grids, layout); }); if(layout.isSet) { // Make sure layouts use 'box-sizing: border-box;' for best results. // rule.insertAfter(layout.decl, {prop: 'box-sizing', value: 'border-box', source: layout.decl.source}); // layout.childrenRule.append({prop: 'box-sizing', value: 'border-box'}); // Stack layout. if(layout.values.indexOf('stack') + 1) { stackLayout(css, rule, layout.decl, layout); } // Line layout. else if(layout.values.indexOf('lines') + 1) { lineLayout(css, rule, layout.decl, layout); // if(layout.isGridContainer) { // gridContainer(css, rule, layout.gridContainerDecl, layout.grid); // } } else if(layout.values.indexOf('flow') + 1) { flowLayout(css, rule, layout.decl, layout); } // Columns layout. else if(layout.values.indexOf('columns') + 1) { columnLayout(css, rule, layout.decl, layout); } // Rows layout. else if(layout.values.indexOf('rows') + 1) { rowLayout(css, rule, layout.decl, layout); } else { throw layout.decl.error('Unknown \'layout\' property value: ' + layout.decl.value, { plugin: 'postcss-layout' }); } } if(layout.isGridContainer) { gridContainer(css, rule, layout.gridContainerDecl, layout.grid); } else if(layout.isGridItem) { gridItem(css, rule, layout.gridItemDecl, layout.grid); } }); }; }); function processGridDef(css, result, rule, grids) { var params = rule.params.split(/\s*,\s*|\s/); // String.split always returns an array with at least one element, // even if the source string is empty. // But the value of the first elm is an empty string, // so we check the length of the first elm, // if it is 0, there is no name for the grid and we return early. if(!params[0].length) return; // Create an entry in the grids obj with the name in params[0]. grids[params[0]] = {}; rule.walkDecls(function(decl) { // Add the props from the rule to the grids obj with key from params[0]. grids[params[0]][decl.prop] = decl.value; // Split gutter val into horizontal and vertical. if(decl.prop == 'gutter') { var gutter = decl.value.split(/\s*,\s*|\s/); grids[params[0]]['gutterH'] = gutter[0]; grids[params[0]]['gutterV'] = gutter[1] || null; } }); // If the grid is missing count, delete it. if(!grids[params[0]].count) delete(grids[params[0]]); // Remove the @rule from the result CSS, it is not needed in the result. rule.remove(); } function processLayoutConf(css, result, rule, decl, grids, layout) { // Look for layout prop in rule. if(decl.prop == 'layout') { var sels = []; layout.childrenRule = null; layout.pseudoRule = null; layout.values = decl.value.split(/\s*,\s*|\s/); layout.container = clone(defaults.container); layout.item = clone(defaults.item); layout.pseudo = clone(defaults.pseudo); for (var i = 0; i < rule.selectors.length; i++) { sels.push(rule.selectors[i] + ' > *'); }; layout.childrenRule = postcss.rule({selector: sels.join(', '), source: decl.source}); layout.item.selector = sels.join(', '); layout.item.source = decl.source; sels = []; for (var i = 0; i < rule.selectors.length; i++) { sels.push(rule.selectors[i] + ':after'); }; layout.pseudoRule = postcss.rule({selector: sels.join(', '), source: decl.source}); layout.pseudo.selector = sels.join(', '); layout.pseudo.source = decl.source; layout.isSet = true; layout.decl = decl; } // Look for grid prop in rule. else if(decl.prop == 'grid') { var grid = null; var gridName = decl.value; grid = gridName ? grids[gridName] : null; if(!grid) { throw decl.error('Undefined grid: ' + decl.value, { plugin: 'postcss-layout' }); } layout.isGridContainer = true; layout.gridContainerDecl = decl; layout.grid = grid; } // Look for grid control props like span. else if(decl.prop.indexOf('span') + 1 || decl.prop.indexOf('buffer') + 1 || decl.prop.indexOf('shift') + 1) { // console.log(decl.prop, decl.value); var grid = null; // DONE: Do a suffix check on '-span' instead of just a split on '-', // in case the gridName has a '-' in it. // var gridName = decl.prop.split('-'); // gridName = gridName.length == 2 ? gridName[0] : null; var gridName = decl.prop.match(/(.*)-(span|action)/); var gridAction = gridName.length == 3 ? gridName[2] : null; gridName = gridName.length == 3 ? gridName[1] : null; grid = gridName ? grids[gridName] : null; if(!grid) { throw decl.error('Unknown grid name in span/action property: ' + decl.prop, { plugin: 'postcss-layout' }); } layout.isGridItem = true; layout.gridItemDecl = decl; layout.grid = grid; layout.gridAction = gridAction; } } function stackLayout(css, rule, decl, layout) { // css.insertAfter(rule, layout.childrenRule); var parent = rule.parent; // Sizing, expand-to-fill container or shrink-to-fit content (horizontally). if(layout.values.indexOf('shrink') + 1) { // layout.childrenRule.append({prop: 'display', value: 'table'}); layout.item['display'] = 'table'; } else { // layout.childrenRule.append({prop: 'display', value: 'block'}); layout.item['display'] = 'block'; } // Alignment. if(layout.values.indexOf('left') + 1) { // layout.childrenRule.append({prop: 'margin', value: '0 auto 0 0'}); // layout.childrenRule.append({prop: 'margin-right', value: 'auto'}); layout.item['margin-right'] = 'auto'; } else if(layout.values.indexOf('right') + 1) { // layout.childrenRule.append({prop: 'margin', value: '0 0 0 auto'}); // layout.childrenRule.append({prop: 'margin-left', value: 'auto'}); layout.item['margin-left'] = 'auto'; } // else if(layout.values.indexOf('center') + 1) { else { // layout.childrenRule.append({prop: 'margin', value: '0 auto'}); // layout.childrenRule.append({prop: 'margin-left', value: 'auto'}); // layout.childrenRule.append({prop: 'margin-right', value: 'auto'}); layout.item['margin-left'] = 'auto'; layout.item['margin-right'] = 'auto'; } objToRule(layout.container, rule); parent.insertAfter(rule, objToRule(layout.item)); // Remove 'layout' property from result. decl.remove(); return; } function lineLayout(css, rule, decl, layout) { var i = null; var parent = rule.parent; layout.container['font-size'] = '0'; // rule.insertAfter(decl, {prop: 'font-size', value: '0', source: decl.source}); // layout.pseudoRule.append({prop: 'position', value: 'relative'}); // layout.pseudoRule.append({prop: 'content', value: '""'}); // layout.pseudoRule.append({prop: 'display', value: 'inline-block'}); // layout.pseudoRule.append({prop: 'width', value: '0'}); // layout.pseudoRule.append({prop: 'height', value: '100%'}); // layout.pseudoRule.append({prop: 'vertical-align', value: 'middle'}); // layout.childrenRule.append({prop: 'display', value: 'inline-block'}); // layout.childrenRule.append({prop:'text-align', value: 'initial'}); // layout.childrenRule.append({prop: 'vertical-align', value: 'top'}); // layout.childrenRule.append({prop: 'white-space', value: 'initial'}); // layout.childrenRule.append({prop:'font-size', value: 'initial'}); // css.insertAfter(rule, layout.pseudoRule); // css.insertAfter(rule, layout.childrenRule); layout.item.source = decl.source; layout.item['display'] = 'inline-block'; layout.item['vertical-align'] = 'top'; // Horizontal alignment. i = layout.values.indexOf('left') + 1 || layout.values.indexOf('right') + 1 || layout.values.indexOf('center') + 1; if(i) { // rule.insertAfter(decl, {prop: 'text-align', value: layout.values[i - 1], source: decl.source}); layout.container['text-align'] = layout.values[i - 1]; } // Vertical alignment. i = layout.values.indexOf('top') + 1 || layout.values.indexOf('bottom') + 1 || layout.values.indexOf('middle') + 1; if(i) { // layout.childrenRule.append({prop: 'vertical-align', value: layout.values[i - 1], source: decl.source}); // rule.insertAfter(decl, {prop: 'white-space', value: 'nowrap', source: decl.source}); layout.container['white-space'] = 'nowrap'; layout.item['vertical-align'] = layout.values[i - 1]; layout.pseudo['content'] = '""'; layout.pseudo['display'] = 'inline-block'; layout.pseudo['vertical-align'] = 'middle'; layout.pseudo['width'] = '0'; layout.pseudo['height'] = '100%'; } i = layout.values.indexOf('nowrap') + 1; if(i) { layout.container['white-space'] = 'nowrap'; } objToRule(layout.container, rule); parent.insertAfter(rule, objToRule(layout.pseudo)); parent.insertAfter(rule, objToRule(layout.item)); // Remove the 'layout' property from the result. decl.remove(); return; } function flowLayout(css, rule, decl, layout) { var i = null; var parent = rule.parent; layout.item.source = decl.source; layout.item['float'] = 'left'; layout.pseudo['content'] ='""'; layout.pseudo['display'] = 'table'; layout.pseudo['clear'] = 'both'; // Horizontal alignment. i = layout.values.indexOf('left') + 1 || layout.values.indexOf('right') + 1; if(i) { layout.item['float'] = layout.values[i - 1]; } objToRule(layout.container, rule); parent.insertAfter(rule, objToRule(layout.pseudo)); parent.insertAfter(rule, objToRule(layout.item)); // Remove the 'layout' property from the result. decl.remove(); return; } function columnLayout(css, rule, decl, layout) { // css.insertAfter(rule, layout.childrenRule); var parent = rule.parent; objToRule(layout.container, rule); rule.insertAfter(decl, {prop: 'display', value: 'table', source: decl.source}); rule.insertAfter(decl, {prop: 'table-layout', value: 'fixed', source: decl.source}); rule.insertAfter(decl, {prop: 'width', value: '100%', source: decl.source}); // layout.childrenRule.append({prop: 'display', value: 'table-cell'}); layout.item['display'] = 'table-cell'; parent.insertAfter(rule, objToRule(layout.item)); // Remove the 'layout' property from the result. decl.remove(); return; } function rowLayout(css, rule, decl, layout) { // css.insertAfter(rule, layout.childrenRule); var parent = rule.parent; objToRule(layout.container, rule); rule.insertAfter(decl, {prop: 'display', value: 'table', source: decl.source}); rule.insertAfter(decl, {prop: 'table-layout', value: 'fixed', source: decl.source}); rule.insertAfter(decl, {prop: 'width', value: '100%', source: decl.source}); // layout.childrenRule.append({prop: 'display', value: 'table-row'}); layout.item['display'] = 'table-row'; parent.insertAfter(rule, objToRule(layout.item)); // Remove the 'layout' property from the result. decl.remove(); return; } function gridContainer(css, rule, decl, grid) { var gutterH = grid.gutterH ? grid.gutterH.match(/(\d+\.?\d*)(\D*)/) : [0, 0]; var gutterHUnits = gutterH[2] || ''; var marginH = Number(gutterH[1]) ? '-' + gutterH[1]/2 + gutterHUnits : 0; var gutterV = grid.gutterV ? grid.gutterV.match(/(\d+\.?\d*)(\D*)/) : [0, 0]; var gutterVUnits = gutterV[2] || ''; var marginV = Number(gutterV[1]) ? '-' + gutterV[1]/2 + gutterVUnits : 0; if(marginH) { rule.insertAfter(decl, {prop:'margin-left', value: marginH + ' !important', source: decl.source}); rule.insertAfter(decl, {prop:'margin-right', value: marginH + ' !important', source: decl.source}); } if(marginV) { rule.insertAfter(decl, {prop:'margin-top', value: marginV + ' !important', source: decl.source}); rule.insertAfter(decl, {prop:'margin-bottom', value: marginV + ' !important', source: decl.source}); } // Remove 'grid' property. decl.remove(); } function gridItem(css, rule, decl, grid) { // Get the grid ratio value for later span and buffer calculations. var gridRatio = grid.count ? 100/grid.count : null; if(!gridRatio) { throw decl.error('Improperly defined grid, check your @grid rule. ' + decl.prop, { plugin: 'postcss-layout', grid: grid }); } // Break up the property value into it's span, buffer, shift values. var propValue = postcss.list.comma(decl.value); if(propValue.length == 0) { throw decl.error('Span/action must have at least one value. ' + decl.prop, { plugin: 'postcss-layout' }); } if(propValue.length > 1) { propValue[1] = postcss.list.space(propValue[1]); } // Get margin values for items from grid gutter setting. var gutterH = grid.gutterH ? grid.gutterH.match(/(\d+\.?\d*)(\D*)/) : [0, 0]; var gutterHUnits = gutterH[2] || ''; var marginH = Number(gutterH[1]) ? gutterH[1]/2 + gutterHUnits : 0; var gutterV = grid.gutterV ? grid.gutterV.match(/(\d+\.?\d*)(\D*)/) : [0, 0]; var gutterVUnits = gutterV[2] || ''; var marginV = Number(gutterV[1]) ? gutterV[1]/2 + gutterVUnits : 0; // Get the margin values for any buffer values for the item (compounded with marginH if gutter was set). if(propValue[1] && propValue[1][0] != 0) { var buffer = gridRatio * propValue[1][0] + '%'; if(marginH) buffer = 'calc(' + buffer + ' + ' + marginH + ')'; } if(propValue[1] && propValue[1][1]) { var bufferL = buffer; buffer = null; if(propValue[1][1] != 0) { var bufferR = gridRatio * propValue[1][1] + '%'; if(marginH) bufferR = 'calc(' + bufferR + ' + ' + marginH + ')'; } } // console.log(propValue); // console.log(buffer, bufferL, bufferR); // Get shift value for left property of item. if(propValue[2]){ var shift = gridRatio * propValue[2] + '%'; } // Get the width value for the item. var width = grid.count ? gridRatio * propValue[0] + '%' : 'auto'; var calc = marginH ? 'calc(' + width + ' - ' + grid.gutterH + ')' : width; // console.log(marginV); if(width != 'auto') rule.insertAfter(decl, {prop:'width', value: calc, source: decl.source}); if(buffer || bufferL || bufferR || marginH) { rule.insertAfter(decl, {prop:'margin-left', value: buffer || bufferL || marginH || '0' + ' !important', source: decl.source}); rule.insertAfter(decl, {prop:'margin-right', value: buffer || bufferR || marginH || '0' + ' !important', source: decl.source}); } if(marginV) { rule.insertAfter(decl, {prop:'margin-top', value: marginV, source: decl.source}); rule.insertAfter(decl, {prop:'margin-bottom', value: marginV, source: decl.source}); } if(shift) { rule.insertAfter(decl, {prop:'left', value: shift, source: decl.source}); } // Remove the 'span' property from the result. decl.remove(); return; } // Convert a js obj to a postcss rule, extending clonedRule if it is passed in. function objToRule(obj, clonedRule) { var rule = clonedRule || postcss.rule(); var skipKeys = ['selector', 'selectors', 'source']; if(obj.selector) rule.selector = obj.selector; else if(obj.selectors) rule.selectors = obj.selectors; if(obj.source) rule.source = obj.source; for(var k in obj) { if(obj.hasOwnProperty(k) && !(skipKeys.indexOf(k) + 1)) { var v = obj[k]; var found = false; // If clonedRule was passed in, check for an existing property. if(clonedRule) { rule.each(function(decl) { if(decl.prop == k) { decl.value = v; found = true; return false; } }); } // If no clonedRule or there was no existing prop. if(!clonedRule || !found) rule.append({prop: k, value: v}); } } return rule; } function clone(obj) { return JSON.parse(JSON.stringify(obj)); }
// es6 shim (function() { if( !String.prototype.startsWith ) { String.prototype.startsWith = function(s) { return this.indexOf(s) === 0; }; } if( !String.prototype.endsWith ) { String.prototype.endsWith = function(s) { var t = String(s); var index = this.lastIndexOf(t); return index >= 0 && index === this.length - t.length; }; } var global = window; // ES6 Map shim if( !global.Map ) { var Map = function Map() { this.k = []; this.v = []; this.size = 0; }; Map.prototype = { get: function(k) { return this.v[this.k.indexOf(k)]; }, set: function(k, v) { var i = this.k.indexOf(k); if( i >= 0 ) { this.k[i] = v; } else { this.k.push(k); this.v.push(v); } this.size = this.k.length; }, "delete": function(k) { var i = this.k.indexOf(k); if( i >= 0 ) { this.k.remove(i); this.v.remove(i); this.size = this.k.length; return true; } return false; }, has: function(k) { return (this.k.indexOf(k) >= 0); }, keys: function() { return this.k; }, values: function() { return this.v; }, items: function() { }, iterator: function() { return this.items(); }, clear: function() { this.k = []; this.v = []; this.size = 0; } }; // custom method Map.prototype.getKeyByValue = function(v) { var argk = this.keys(); var argv = this.values(); return argk[argv.indexOf(v)]; }; Map.prototype.toObject = function() { var keys = this.keys(); var o = {}; for(var i=0; i < keys.length; i++) { var k = keys[i]; o[k] = this.get(k); } return o; }; global.Map = global.WeakMap = Map; } })();
var mongoose = require('mongoose'); var fs = require('fs'); var chance = new (require('chance'))(); var express = require('express') , passport = require('passport') , ws = require('ws').Server; // Setup all var app = express(); // Prepare Schemas var models_path = __dirname + '/app/schemas' fs.readdirSync(models_path).forEach(function (file) { if (~file.indexOf('.js')) require(models_path + '/' + file); }); // Prepare All using configs var config_path = __dirname + '/app/config' fs.readdirSync(config_path).forEach(function (file) { if (~file.indexOf('.js')) require(config_path + '/' + file)(app, mongoose, passport, ws); }) app.listen(3000);
// including plugins var gulp = require('gulp'), uglify = require("gulp-uglify"), minifyCss = require("gulp-minify-css"), sass = require("gulp-sass"), rename = require("gulp-rename"); // task gulp.task('dist', function() { gulp.src('./src/scripts/*.js') // path to your files .pipe(uglify()) .pipe(rename({ extname: '.min.js' })) .pipe(gulp.dest('dist/scripts/')); gulp.src('./src/styles/*.scss') // path to your file .pipe(sass()) .pipe(gulp.dest('dist/styles')); gulp.src('./dist/styles/*.css') // path to your file .pipe(minifyCss()) .pipe(rename({ extname: '.min.css' })) .pipe(gulp.dest('dist/styles.min')); });
function foo() { debugger; console.log('foo'); }
//main.js /** * The Google Earth Plugin Instance Object * All functionality is provided by interacting with the GE Instance * @type {GEPlugin} */ var ge; /** * Load the required API Libraries from the Google API Loader * @param {string} The library to load * @param {string} The library version number * @param {Object?} Optional parameters */ google.load("earth", "1"); google.load("maps", "3", {other_params: "sensor=false"}); //Google Maps v3 requires you explicitly state whether or not you will be using a location sensor enabled device /* Wait until the entire page/APIs have been loaded, and the DOM has been completely built up before initializing the Google Earth Plugin Instance */ google.setOnLoadCallback(init); /** * Initialize an instance of the Google Earth Plugin */ function init() { /** * @param {string} googleEarthPlugin a HTML div element with a unique ID * @callback initCB the callback function to run if instance creation is successful * @callback failureCB the callback function to run if instance creation is unsuccessful */ google.earth.createInstance("googleEarthPlugin", initCB, failureCB); } /** * The callback function run if GEPlugin Instance creation is successful * @param {GEPlugin} instance The Google Earth Instance Object, returned when * google.earth.createInstance() calls the initCB * callback function */ function initCB(instance) { ge = instance; //Assign the GEPlugin object to our global variable preGEInitializationTasks(); ge.getWindow().setVisibility(true); //Make the Google Earth Plugin visible inside its div /* Draw the various Layers relevant to the Simulation application */ ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true); //Country/Area Borders, City/State/Country/Ocean/etc Labels ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true); //Roads and Road Names ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, true); //3D Buildings (where available) ge.getLayerRoot().enableLayerById(ge.LAYER_TERRAIN, true); //3D Terrain (where available) ge.getLayerRoot().enableLayerById(ge.LAYER_TREES, true); //3D Tree Models (where available) postGEInitializationTasks(); } /** * The callback function run if GEPlugin Instance creation was unsuccessful */ function failureCB() { } /** * Tasks that must be performed before the Google Earth Plugin is initialized */ function preGEInitializationTasks() { /* Create an event handler for the window resizing, and set the initial GEPlugin div size */ resizeTracker(); setGEDivSize(); //Set the initial position of the Progress Overlay setProgressOverlayPosition(); //Add an event handler for changing the Menu Icon on mouse over/off changeMenuIcon(); //Create Menu jQuery UI Sliders createSliders(); } /** * Tasks that are performed after the Google Earth Plugin is initialized */ function postGEInitializationTasks() { //An object with helpful methods for calculating various values and modifying properties of placemarks ModelSimulator.geHelper = new GEHelpers(ge); //Save the initial Fly To Speed so it can be restored (if desired) after a simulation has completed initialFlyToSpeed = ge.getOptions().getFlyToSpeed(); populateMenuLists(); enableMenu(); } /** * Create an event handler to be bound to the JavaScript resize event. * Whenever the window is resized, the GEPlugin div will be resized too */ function resizeTracker() { $(window).resize(function() { setGEDivSize(); setProgressOverlayPosition(); }); } /** * Set the height and width of the GEPlugin div to be the current size * of the window's viewpoort (the area in which HTML content can be placed) */ function setGEDivSize() { $("#googleEarthPlugin").height(verge.viewportH()); $("#googleEarthPlugin").width(verge.viewportW()); } /** * Center the "Processing in Progress" Overlay on the page */ function setProgressOverlayPosition() { var overlayWidth = $("#progressWrapper").width(); var overlayHeight = $("#progressWrapper").height(); var windowWidth = verge.viewportW(); var windowHeight = verge.viewportH(); var sideDistance = (windowWidth - overlayWidth) / 2; var topDistance = (windowHeight - overlayHeight) / 2; $("#progressOverlay").css("left", sideDistance + "px"); $("#progressOverlay").css("top", topDistance + "px"); } /** * Bind functions to the the on mouse over ("mouseenter") and on mouse off ("mouseleave") jQuery event handlers */ function changeMenuIcon() { //.hover() quickly and easily binds the handlers for both mouseenter and mouseleave $("#menuURL").hover(function () { $("#menuIcon").css("background-image", "url('img/menuhover.png')"); }, function () { $("#menuIcon").css("background-image", "url('img/menu.png')"); }); } /** * Create a new KmlLookAt - a position for the camera to be facing in Google Earth * @param {number} latitude The latitude for the LookAt to be pointing at * @param {number} longitude The longitude for the LookAt to be pointing at * @param {number} altitude The distance from the earth's surface, in meters * @param {KmlAltitudeModeEnum} altitudeMode How the altitude is to be interpreted; e.g. relative to the ground, relative to the sea floor, etc * @param {number} heading The direction for the LookAt to be facing - i.e. North South East or West. Value is in degrees (0 - 360) * @param {number} tilt The angle the LookAt is facing up or down; 0 - 90 degrees * @param {number} range The distance in meters (from the point specified by the latitude, longitude and altitude) for the LookAt to be situated at */ function createAndSetNewLookAt(latitude, longitude, altitude, altitudeMode, heading, tilt, range) { var lookAt = ge.createLookAt(''); lookAt.set(latitude, longitude, altitude, altitudeMode, heading, tilt, range); ge.getView().setAbstractView(lookAt); } /** * Add a function to the String Object to capitalize the first letter of every word in a string * Originally written by disfated, September 29, 2011 * Retrieved on 5/10/13 from http://stackoverflow.com/questions/2332811/capitalize-words-in-string */ String.prototype.capitalize = function() { return this.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); } ); }
'use strict'; export { default as default } from './admin-page';
// @flow import React, { useEffect, useState } from 'react'; import cx from 'classnames'; import CollapsibleRow from '../CollapsibleRow/CollapsibleRow'; import css from './CollapsibleProgressSteps.css'; type Props = { data: Array<Object> } const CollapsibleProgressSteps = ({ data }: Props) => { const [steps, setSteps] = useState(data); useEffect(() => { setSteps(data); }, [data]); const handleClick = (index) => { const newSteps = [...steps]; steps[index].opened = !steps[index].opened; setSteps(newSteps); }; return ( <div className={css.progressSteps}> {steps.map((item, index) => ( <CollapsibleRow className={cx(css.step, {[css.opened]: item.opened})} key={index} onClick={() => handleClick(index)} opened={item.opened} body={item.body} title={item.title} marginBottom={false} border={false} /> ))} </div> ); }; export default CollapsibleProgressSteps;
/** * Created by dhruti on 26-07-2014. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; var DeptEmployeeSchema = new Schema({ name: { type: String, default: '', required: 'Please fill Employee name', trim: true }, created: { type: Date, default: Date.now }, department_id: { type: Schema.ObjectId, ref: 'Department' } }); mongoose.model('DeptEmployee', DeptEmployeeSchema);
var EXPORT = ['Delegator']; /* * メソッドの委譲を行う */ let Delegator = function(obj, propertyDelegate) { this.__target__obj = obj; if (typeof propertyDelegate == 'undefined') propertyDelegate = true; if (propertyDelegate) { this.__propertyDelegate__(); } }; Delegator.prototype = { get __getTarget__() this.__target__obj, __noSuchMethod__: function (method, args) { let target = this.__getTarget__; return target[method].apply(target, args); }, __propertyDelegate__: function() { // XXX: prototype チェインのプロパティはどうする? let target = this.__getTarget__; let addedKeys = []; for (let key in target) { if (typeof this[key] == 'undefined') { this[key] = target[key]; addedKeys.push(key); } } return addedKeys; } };
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Mozilla Foundation. * Portions created by the Initial Developer are Copyright (C) 2007 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ //----------------------------------------------------------------------------- var BUGNUMBER = 382509; var summary = 'Disallow non-global indirect eval'; var actual = ''; var expect = ''; var global = typeof window == 'undefined' ? this : window; var object = {}; //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function test() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); if (options().match(/strict/)) { options('strict'); } if (options().match(/werror/)) { options('werror'); } global.foo = eval; global.a = 'global'; expect = 'global indirect'; actual = global.foo('a+" indirect"'); reportCompare(expect, actual, summary + ': global indirect'); object.foo = eval; object.a = 'local'; expect = 'EvalError: function eval must be called directly, and not by way of a function of another name'; try { actual = object.foo('a+" indirect"'); } catch(ex) { actual = ex + ''; } reportCompare(expect, actual, summary + ': local indirect'); options('strict'); options('werror'); try { var foo = eval; print("foo(1+1)" + foo('1+1')); actual = 'No Error'; } catch(ex) { actual = ex + ''; } reportCompare(expect, actual, summary + ': strict, rename warning'); options('strict'); options('werror'); expect = 'No Error'; try { var foo = eval; foo('1+1'); actual = 'No Error'; } catch(ex) { actual = ex + ''; } reportCompare(expect, actual, summary + ': not strict, no rename warning'); exitFunc ('test'); }
/* @flow */ export const input = ` type Demo = number; declare var demo: Demo; `; export const expected = ` const Demo = "number"; __assumeDataProperty(global, "demo", __abstract(Demo)); `;
// https://www.concurrencylabs.com/blog/configure-your-lambda-function-like-a-champ-sail-smoothly/ var AWS = require('aws-sdk'); var s3 = new AWS.S3({"signatureVersion":"v4"}); /* PRE-REQUISITES: - Become familiar with AWS Lambda function aliases and versions: http://docs.aws.amazon.com/lambda/latest/dg/aliases-intro.html - Create one or more aliases for your Lambda function (i.e. DEV, TEST, PROD) - Create an S3 bucket and create one folder per stage (i.e. mybucket/DEV, mybucket/TEST, mybucket/PROD) - Create one config file in each folder (i.e. env-config.json) and create relevant entries. For example: { "s3bucket": "mydevbucket", "snstopic": "mydevtopic" } This function loads config values from a JSON file (env-config.json) stored in S3. It fetches a config file based on the Lambda function alias you are executing. For example, if you are running the function's "DEV" alias, the function will fetch config file stored in the "/DEV" folder of your config bucket. The function knows which configuration to grab based on the function alias we are running, which is available in the invoked function ARN. For example, in function ARN arn:aws:lambda:us-east-1:123456789012:function:helloStagedWorld:DEV, "DEV" indicates the function alias we are running. */ function loadConfig(s3bucket, configFile, context, callback){ functionName = context.functionName; functionArn = context.invokedFunctionArn; alias = functionArn.split(":").pop(); //the ARN doesn't include an alias token, therefore we must be executing $LATEST if (alias == functionName) alias = "$LATEST"; obj_key = alias + "/" + configFile; console.log('S3 object key:['+obj_key+']'); var params = { Bucket: s3bucket, Key: obj_key }; s3.getObject(params, function(err, data) { if (err) { console.log(err); var message = "Error getting object from S3"; console.log(message); context.fail(message); } else { env_config = JSON.parse(String(data.Body)); callback(env_config); } }); } exports.load = function(event, context, callback) { var configBucket = "CONFIG BUCKET NAME"; var configFile = "env-config.json"; loadConfig(configBucket, configFile, context, callback); }; /*THIS SINGLE FILE is protected under the MIT License, explained below: Copyright (c) 2016 Concurrency Labs Changes Copyright (c) 2017 Robert Sherling Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --------------- The original file: https://github.com/ConcurrenyLabs/lambda-env-config/blob/master/s3-config/index.js */
/* jshint jquery: true, strict: false */ /* global klass: false, jQuery: false */ var VatNumberCheckObject = { /** * A css class selector to trigger `check` logic. * * @type {string} */ elementSelector: '', /** * An url to use for checking. * * @type {string} */ checkUrl: '', /** * An object with (status) images to use as background after checking. * * @type {Object} */ checkImages: {}, /** * Constructor. * * Initializes instance variables and attaches a blur event. * * Possible keys: * - ok * - failure * - serviceUnavailable * * @param {Object} options An options object */ initialize: function (options) { this.elementSelector = options.elementSelector || this.elementSelector; this.checkUrl = options.checkUrl || this.checkUrl; this.checkImages = options.checkImages || this.checkImages; jQuery(this.elementSelector).blur(jQuery.proxy(this._check, this)); }, /** * A blur event handler. * * Requests the check url and displays it's status. * * @access protected * @param {Object} event */ _check: function (event) { var element = jQuery(event.target); jQuery.ajax({ type: 'POST', url: this.checkUrl, beforeSend: jQuery.proxy(this._beforeSend, this, element), data: { vatNumber: element.val() } }).done( jQuery.proxy(this._done, this, element) ).fail( jQuery.proxy(this._fail, this, element) ); }, /** * A request handler for `done`. * * @access protected * @param {Object} element A DOM element * @param {Object} result Request data */ _done: function (element, result) { if (result.status === 'ok') { this._setBackground(element, this.checkImages.ok); } else { if (result.vatNumber.length === 0) { this._setBackground(element); } else { this._setBackground(element, this.checkImages.failure); } } element.val(result.vatNumber); }, /** * A request handler for `fail`. * * @access protected * @param {Object} element A DOM element */ _fail: function (element) { this._setBackground(element, this.checkImages.serviceUnavailable); }, /** * A request handler for `beforeSend`. * * @access protected * @param {Object} element A DOM element */ _beforeSend: function (element) { this._setBackground(element, ''); }, /** * Changes the background image of a given element. * * @access protected * @param {Object} element A DOM element * @param {string} image An image (url) */ _setBackground: function (element, image) { var backgroundImage; if (image) { backgroundImage = 'url("' + image + '")'; } else { backgroundImage = 'none'; } element.css({ backgroundImage: backgroundImage, backgroundRepeat: 'no-repeat', backgroundPosition: 'right' }); } }; var VatNumberCheck = klass(VatNumberCheckObject);
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: '<json:package.json>', meta: { banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' + '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' + ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */' }, concat: { dist: { src: ['<banner:meta.banner>', '<file_strip_banner:lib/CSSelector.js>'], dest: 'dist/CSSelector.js' } }, min: { dist: { src: ['<banner:meta.banner>', '<config:concat.dist.dest>'], dest: 'dist/CSSelector.min.js' } }, lint: { files: ['grunt.js', 'lib/**/*.js'] }, watch: { files: '<config:lint.files>', tasks: 'lint' }, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, smarttabs: true }, globals: { module: true, define: false } }, uglify: {} }); // Default task. grunt.registerTask('default', 'lint concat min'); };
"use strict"; var cluster = require("cluster"), os = require("os"); if (cluster.isMaster) { for (var i = 0; i < os.cpus().length; i++) { cluster.fork(); } } else { // TODO refactor to return an app object require("./index"); }
import Samay from '@/Samay'; describe("Addition Subtraction", () => { let samay, clone; beforeEach(() => { samay = new Samay(2015,9,5,9,30,14,500); clone = samay.clone(); }) it("can add and subtract years", () => { expect(clone._year).toBe(2015) clone.addYears(4); expect(clone._year).toBe(2019) clone.subtractYears(2); expect(clone._year).toBe(2017) }) it("can add and subtract quarters", () => { expect(clone._month).toBe(9) clone.addQuarters(2); expect(clone._month).toBe(3) expect(clone._year).toBe(2016) clone.subtractQuarters(3); expect(clone._month).toBe(6) expect(clone._year).toBe(2015) }) it("can add and subtract months", () => { expect(clone._month).toBe(9) clone.addMonths(4); expect(clone._month).toBe(1) expect(clone._year).toBe(2016) clone.subtractMonths(2); expect(clone._month).toBe(11) expect(clone._year).toBe(2015) }) it("can add and subtract weeks", () => { expect(clone._date).toBe(5) clone.addWeeks(3); expect(clone._date).toBe(26) clone.subtractWeeks(1); expect(clone._date).toBe(samay._date+14) }) it("can add and subtract days", () => { expect(clone._date).toBe(5) clone.addDays(21); expect(clone._date).toBe(26) clone.subtractDays(9); expect(clone._date).toBe(17) }) it("can add and subtract hours", () => { expect(clone._hours).toBe(9) clone.addHours(6); expect(clone._hours).toBe(15) clone.subtractHours(5); expect(clone._hours).toBe(10) }) it("can add and subtract minutes", () => { expect(clone._minutes).toBe(30) clone.addMinutes(15); expect(clone._minutes).toBe(45) clone.subtractMinutes(37); expect(clone._minutes).toBe(8) }) it("can add and subtract seconds", () => { expect(clone._seconds).toBe(14) clone.addSeconds(30); expect(clone._seconds).toBe(44) clone.subtractSeconds(40); expect(clone._seconds).toBe(4) }) it("can add and subtract milliseconds", () => { expect(clone._milliseconds).toBe(500) clone.addMilliseconds(50); expect(clone._milliseconds).toBe(550) clone.subtractMilliseconds(25); expect(clone._milliseconds).toBe(525) }) })
const EJS = require('ejs2'); module.exports = new EJS({ cache: true });
/** * Pico's Default Theme - JavaScript helper * * Pico is a stupidly simple, blazing fast, flat file CMS. * * @author Daniel Rudolf * @link http://picocms.org * @license http://opensource.org/licenses/MIT The MIT License * @version 1.1 */ function main() { // capability CSS classes document.documentElement.className = 'js'; // wrap tables var tables = document.querySelectorAll('#main > .container > table'); for (var i = 0; i < tables.length; i++) { if (!/\btable-responsive\b/.test(tables[i].parentElement.className)) { var tableWrapper = document.createElement('div'); tableWrapper.className = 'table-responsive'; tables[i].parentElement.insertBefore(tableWrapper, tables[i]); tableWrapper.appendChild(tables[i]); } } // responsive menu var menu = document.getElementById('nav'), menuToggle = document.getElementById('nav-toggle'), toggleMenuEvent = function (event) { if (event.type === 'keydown') { if ((event.keyCode != 13) && (event.keyCode != 32)) { return; } } event.preventDefault(); if (menuToggle.getAttribute('aria-expanded') === 'false') { menuToggle.setAttribute('aria-expanded', 'true'); utils.slideDown(menu, null, function () { if (event.type === 'keydown') { menu.focus(); } }); } else { menuToggle.setAttribute('aria-expanded', 'false'); utils.slideUp(menu); } }, onResizeEvent = function () { if (utils.isElementVisible(menuToggle)) { menu.className = 'hidden'; menuToggle.addEventListener('click', toggleMenuEvent); menuToggle.addEventListener('keydown', toggleMenuEvent); } else { menu.className = ''; menu.removeAttribute('data-slide-id'); menuToggle.removeEventListener('click', toggleMenuEvent); menuToggle.removeEventListener('keydown', toggleMenuEvent); } }; window.addEventListener('resize', onResizeEvent); onResizeEvent(); } main();
$(function() { // 共通の変数は`NS`名前空間をスコープにします。 var NS = NS || {}; // ブレイクポイントを定数で管理します。 NS.BREAK_POINT_SM = 400; NS.BREAK_POINT_MD = 768; NS.BREAK_POINT_LG = 1000; NS.BREAK_POINT_XL = 1200; // `NS.viewportWidth`に現在のviewportの横幅を格納する。 NS.viewportWidth = window.innerWidth; $(window).on('resize', debounce(function() { NS.viewportWidth = window.innerWidth; }, 200)); // 変数`scrollPosition`に現在のスクロール量(位置)を格納する。 NS.scrollPosition = window.pageYOffset; $(window).on('scroll', throttle(function() { NS.scrollPosition = window.pageYOffset; }, 200)); /** * 表示しているページと同じか、共通の親ディレクトリを持つリンクにクラスを追加します。 * パスは(`/`で始める)ルート相対パスで記述します。 * `current`と`$targetLink`は任意のクラス名を指定してください。 * ナビゲーションにトップページが含まれていない場合は`else`以降を削除します。 */ function navCurrentLink() { var current = 'is-current'; var $targetLink = $('.js-nav-current'); if(location.pathname != '/') { $targetLink.find('a[href^="/' + location.pathname.split("/")[1] + '"]').addClass(current); } else { $targetLink.find('a:eq(0)').addClass(current); } } navCurrentLink(); /** * ページトップへ戻るリンクをアニメーションさせます。。 */ function navScrollTop() { var $targetClass = $('.js-scroll-top'); var speed = 500; // アニメーションスピード(ms) var animation = 'linear'; // 'linear' or 'swing' $targetClass.on('click', function(e) { e.preventDefault(); $('html, body').animate({ scrollTop: 0}, speed, animation); }); } navScrollTop(); });
import "../core/array"; import "selection"; d3_selectionPrototype.call = function(callback) { var args = d3_array(arguments); callback.apply(args[0] = this, args); return this; };
/** * # plugins.js * * Plugins are like middleware, they get used 'automagically' * */ 'use strict'; /** * ## plugins * * when a route is config'd with auth, the hapi-auth-jwt will be invoked * * the good module prints out messages */ module.exports = [ { register: require('hapi-auth-jwt'), options: {} }, { register: require('good'), options: { opsInterval: 1000, reporters: [{ reporter: require('good-console'), events: { log: '*', response: '*', request: '*' } }] } } ];
import React, { Component, PropTypes } from 'react'; import Input from 'react-toolbox/lib/input'; import InstString from '../instrument-string/instrument-string'; import './chord-chart.scss'; export default class ChordChart extends Component { static propTypes = { chord: PropTypes.object, numFrets: PropTypes.number, }; static contextTypes = { isEditable: PropTypes.bool, onMinFretChange: PropTypes.func, }; renderMinFret = minFret => { const { isEditable, onMinFretChange } = this.context; let minFretEl; if (isEditable && onMinFretChange) { minFretEl = (<Input className='chord__min-fret-input' value={minFret || ''} onChange={onMinFretChange} >fr</Input>); } else { minFretEl = ( <span className='chord__min-fret'> {minFret ? minFret + 'fr' : ''} </span> ); } return minFretEl; }; render() { const { chord, numFrets } = this.props; const { minFret } = chord; return ( <div className='chord-chart'> {this.renderMinFret(minFret)} <div className='chord-chart__strings'> {chord.fingerings.map((string, i) => { return (<InstString key={i} stringIndex={i} string={string} numFrets={numFrets} minFret={minFret} />); })} </div> </div> ); } }
var game = new Phaser.Game(640, 480, Phaser.CANVAS, 'Ilegal'); //INITIALIZE HERE THE CANVAS AND OTHER STUFFS LIKE DEVICE TYPE AND RESOLUTION var Boot = function(game){}; Boot.prototype = { preload: function() { this.load.image('preloaderBg', 'assets/preload/loading-bg.png'); this.load.image('preloaderBar', 'assets/preload/loading-bar.png'); }, create: function() { console.log("Arranco Boot"); this.input.maxPointers = 1; this.scale.scaleMode = Phaser.ScaleManager.NO_SCALE; this.scale.pageAlignHorizontally = true; this.scale.pageAlignVertically = true; this.scale.setScreenSize(true); this.stage.backgroundColor = '#000000'; this.state.start('Preloader'); }, update: function() { } }; //PRELOAD HERE ASSETS var Preloader = function(game){}; Preloader.prototype = { preload: function() { this.preloadBg = this.add.sprite(this.world.centerX, this.world.centerY, 'preloaderBg'); this.preloadBg.anchor.setTo(0.5,0.5); this.preloadBar = this.add.sprite(this.world.centerX, this.world.centerY, 'preloaderBar'); this.preloadBar.anchor.setTo(0.5,0.5); this.load.setPreloadSprite(this.preloadBar); this.load.atlas('timon', 'assets/data/timon.png?v=1', 'assets/data/timon.json?v=1'); this.load.atlas('game', 'assets/data/game.png?v=1', 'assets/data/game.json?v=1'); this.load.atlas('player', 'assets/data/player.png?v=2', 'assets/data/player.json?v=2'); this.load.atlas('car', 'assets/data/car.png?v=1', 'assets/data/car.json?v=1'); this.load.image('street', 'assets/data/street.png'); this.load.image('cruce', 'assets/data/cruce.png'); this.load.image('semaforo', 'assets/data/semaforo.png') }, create: function() { console.log("Arranco Preloader"); this.state.start('Game'); } }; //PUT HERE THE GAME! var Game = function(game){}; Game.prototype = { preload: function() {}, create: function() { this.world.setBounds(0, 0, 2560, 480); this.physics.startSystem(Phaser.Physics.ARCADE); gameObjects = this.add.group(); street = this.add.tileSprite(0,0,1280,480,'street'); cruce = this.add.sprite(1280, 0, 'cruce'); street2 = this.add.tileSprite(1920,0,640,480,'street'); semaforo = this.add.sprite(1130, 330, 'semaforo'); semaforo.anchor.setTo(0,1); player = this.add.sprite(100,470,'player'); player.anchor.setTo(0,1); player.animations.add('playerMoving', Phaser.Animation.generateFrameNames('playerMovement', 0, 5, '.png', 2), 4, true); player.animations.add('playerFallin', Phaser.Animation.generateFrameNames('playerFallin', 0, 3, '.png', 2), 2, false).onComplete.add(this.onPlayerDie, this); player.animations.play('playerMoving'); car = this.add.sprite(1280, 460, 'car'); car.anchor.setTo(0,1); car.scale.setTo(1.3,1.3); car.animations.add('openDoor', Phaser.Animation.generateFrameNames('carDoor', 0, 1,'.png', 2), 1, false); this.physics.arcade.enable([player, car, semaforo]); player.body.setSize(70, 90, 40, -30); semaforo.body.setSize(50,90, 0, 60); car.body.setSize(50, 100, 150, -50); gameObjects.add(street); gameObjects.add(street2); gameObjects.add(cruce); gameObjects.add(semaforo); gameObjects.add(car); gameObjects.add(player); car.body.immovable = true; semaforo.body.immovable = true; this.camera.follow(player); this.camera.deadzone = new Phaser.Rectangle(this.width/2, 0, 1, 480); playerSpeed = 6; spaceButton = this.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); playerSpeed = 300; currentState = States.GAME; //this.state.start("SceneGameOver"); }, onPlayerDie: function() { console.log('la palmo'); player.body.velocity.x = 0; currentState = States.FINISH; game.time.events.add(Phaser.Timer.SECOND * 2, this.finishGame, this); }, render: function() { //game.debug.body(player); //game.debug.body(car); game.debug.body(semaforo); }, update: function() { if (currentState == States.GAME) { this.physics.arcade.collide(player, semaforo, this.onTrigger, null, player); this.physics.arcade.collide(player, car, this.onDoorHitted, null, player); player.body.velocity.x = 0; velocity.setTo(0); if (game.input.keyboard.isDown(Phaser.Keyboard.D)) { velocity.x = 1; } velocity = Phaser.Point.normalize(velocity); velocity.x *= playerSpeed; player.body.velocity.x = velocity.x; } if (currentState == States.END) { console.log('acelerando'); player.body.velocity.x = 0; velocity.setTo(0); velocity.x = 1; velocity = Phaser.Point.normalize(velocity); velocity.x *= playerSpeed; player.body.velocity.x = velocity.x; } }, onTrigger: function(player) { console.log('trigger'); semaforo.body.enable = false; car.animations.play('openDoor'); }, onDoorHitted: function(player) { console.log('se la puso'); car.body.enable = false; playerSpeed = 400; player.animations.play('playerFallin'); currentState = States.END; }, finishGame: function() { this.state.start('SceneGameOver'); } }; var States = { LOAD:0, START:1, GAME:2, WIN:3, END:4, FINISH:5, RESTART:6 }; var currentState; var playerSpeed = 150; var velocity = new Phaser.Point(); var SceneGameOver = function(game){}; SceneGameOver.prototype = { preload: function() {}, create: function() { this.world.setBounds(0, 0, 640, 480); title = game.add.sprite(game.world.centerX, 130, 'game'); title.animations.add('show', [2,3,4], 10, true); title.animations.play('show'); title.anchor.setTo(0.5, 0.5); title.scale.setTo(2); console.log('game over!?='); timon = game.add.sprite(game.world.centerX, 450, 'timon'); timon.anchor.setTo(0.5, 1); timon.animations.add('show'); timon.animations.play('show', 12, false); timon.scale.setTo(2); }, update: function() {}, }; game.state.add("Boot", Boot); game.state.add("Preloader", Preloader); game.state.add("Game", Game); game.state.add("SceneGameOver", SceneGameOver); game.state.start("Boot");
'use strict'; var pg = require('pg'); var Promise = require('promise'); var Mapper = function() { this.connectionString = 'postgres://postgres:synapse1@localhost/example_vm'; }; Mapper.prototype.query = function(query) { var mapper = this; return new Promise(function (resolve, reject) { pg.connect(mapper.connectionString, function(err, client, done) { if(err) { reject(err); } else { client.query(query, function(err, result) { done(); if(err) { reject(err); } else { resolve(result); } }); } }); }); }; module.exports = new Mapper();
export { default } from './MediaCard.container'
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaGetPocket extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m35.9 2.9q1.5 0 2.5 1t1 2.4v11.6q0 4-1.5 7.5t-4.1 6.2-6.1 4-7.5 1.5q-3.9 0-7.5-1.5t-6.1-4-4.1-6.2-1.5-7.5v-11.6q0-1.4 1-2.4t2.5-1h31.4z m-15.7 23.7q1.1 0 1.8-0.7l9.1-8.7q0.8-0.8 0.8-1.9 0-1.1-0.8-1.9t-1.8-0.7q-1.1 0-1.9 0.7l-7.2 6.9-7.2-6.9q-0.8-0.7-1.8-0.7-1.1 0-1.9 0.7t-0.7 1.9q0 1.2 0.8 1.9l9 8.7q0.7 0.7 1.8 0.7z"/></g> </IconBase> ); } }
// DOM Ready $(function() { // PNG Fallback for SVG if(!Modernizr.svg) { $('img[src*="svg"]').attr('src', function() { return $(this).attr('src').replace('.svg', '.png'); }); } // Basic FitVids $(".container").fitVids(); $(".videoWrapper").fitVids(); // Placeholder $('input, textarea').placeholder(); $('.btn-group > .btn').click(function (e) { $('.btn-group > .btn').removeClass('tb-active') $(this).addClass('tb-active') }); $('#large-thumb').click(function (e) { e.preventDefault(); $(".thumbnail-options").removeAttr('class'); $(".video-wrap").parent().addClass("col-xs-12 col-sm-12 col-md-12 thumbnail-options"); }); $('#medium-thumb').click(function (e) { e.preventDefault(); $(".thumbnail-options").removeAttr('class'); $(".video-wrap").parent().addClass("col-xs-12 col-sm-6 col-md-6 thumbnail-options"); }); $('#small-thumb').click(function (e) { e.preventDefault(); $(".thumbnail-options").removeAttr('class'); $(".video-wrap").parent().addClass("col-xs-12 col-sm-6 col-md-4 thumbnail-options"); }); $('.dropdown-menu li a').click(function (e) { $(".downloaded").fadeIn("slow").delay(2000).fadeOut("slow"); }); $('#show-download-btn').click(function (e) { e.preventDefault(); $("#dl-info").fadeIn("fast"); $("#show-download").fadeIn("slow"); }); // Phone menu visible $("#phone_visible").click(function(e){ e.preventDefault(); $(".phone-menu").fadeToggle("fast"); }); });
import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import { fade } from '../styles/colorManipulator'; export const styles = theme => ({ /* Styles applied to the root element. */ root: { height: 1, margin: 0, // Reset browser default style. border: 'none', flexShrink: 0, backgroundColor: theme.palette.divider, }, /* Styles applied to the root element if `absolute={true}`. */ absolute: { position: 'absolute', bottom: 0, left: 0, width: '100%', }, /* Styles applied to the root element if `variant="inset"`. */ inset: { marginLeft: 72, }, /* Styles applied to the root element if `light={true}`. */ light: { backgroundColor: fade(theme.palette.divider, 0.08), }, /* Styles applied to the root element if `variant="middle"`. */ middle: { marginLeft: theme.spacing(2), marginRight: theme.spacing(2), }, /* Styles applied to the root element if `orientation="vertical"`. */ vertical: { height: '100%', width: 1, }, }); const Divider = React.forwardRef(function Divider(props, ref) { const { absolute = false, classes, className, component: Component = 'hr', light = false, orientation = 'horizontal', role = Component !== 'hr' ? 'separator' : undefined, variant = 'fullWidth', ...other } = props; return ( <Component className={clsx( classes.root, { [classes[variant]]: variant !== 'fullWidth', [classes.absolute]: absolute, [classes.light]: light, [classes.vertical]: orientation === 'vertical', }, className, )} role={role} ref={ref} {...other} /> ); }); Divider.propTypes = { /** * Absolutely position the element. */ absolute: PropTypes.bool, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, /** * If `true`, the divider will have a lighter color. */ light: PropTypes.bool, /** * The divider orientation. */ orientation: PropTypes.oneOf(['horizontal', 'vertical']), /** * @ignore */ role: PropTypes.string, /** * The variant to use. */ variant: PropTypes.oneOf(['fullWidth', 'inset', 'middle']), }; export default withStyles(styles, { name: 'MuiDivider' })(Divider);
/*! nut 0.4.2 (https://github.com/pyrsmk/nut) */ !function(a,b,c){"undefined"!=typeof module&&module.exports?module.exports=c:"function"==typeof define&&define.amd?define(c):a[b]=c}(this,"nut",function(){var a=function(a){var b=document.getElementById(a);return b?[b]:[]},b=function(a,c){var d,e=c.firstChild,f=[];if(e)do 1==e.nodeType&&(e.className&&e.className.match("\\b"+a+"\\b")&&f.push(e),(d=b(a,e)).length&&(f=f.concat(d)));while(e=e.nextSibling);return f},c=function(a,c){return c.getElementsByClassName?c.getElementsByClassName(a):b(a,c)},d=function(a,b){return b.getElementsByTagName(a)};return function(b,e){e||(e=document);var f,g,h,i,j,k,l,m,n,o,p,q=[];for(b=b.split(","),n=-1;h=b[++n];)b[n]=h.split(/\s+/);for(j=b.length;j;){for(f=[e],k=-1,l=b[--j].length;++k<l;)if(h=b[j][k]){for("#"==h.charAt(0)?(h=h.substr(1),p=a):"."==h.charAt(0)?(h=h.substr(1),p=c):p=d,g=[],m=-1;f[++m];)for(i=p(h,f[m]),n=-1,o=i.length;++n<o;)g.push(i[n]);f=g}q=q.concat(f)}return q}}());
'use strict'; /** * Module dependencies. */ var fs = require('fs'), http = require('http'), https = require('https'), socketio = require('socket.io'), express = require('express'), morgan = require('morgan'), bodyParser = require('body-parser'), session = require('express-session'), compress = require('compression'), methodOverride = require('method-override'), helmet = require('helmet'), mongoStore = require('connect-mongo')({ session: session }), flash = require('connect-flash'), config = require('./config'), consolidate = require('consolidate'), path = require('path'); module.exports = function(db) { // Initialize express app var app = express(); // Globbing model files config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) { require(path.resolve(modelPath)); }); // Setting application local variables app.locals.title = config.app.title; app.locals.description = config.app.description; app.locals.keywords = config.app.keywords; app.locals.jsFiles = config.getJavaScriptAssets(); app.locals.cssFiles = config.getCSSAssets(); // Passing the request url to environment locals app.use(function(req, res, next) { res.locals.url = req.protocol + '://' + req.headers.host + req.url; next(); }); // Should be placed before express.static app.use(compress({ filter: function(req, res) { return (/json|text|javascript|css/).test(res.getHeader('Content-Type')); }, level: 9 })); // Showing stack errors app.set('showStackError', true); // Set swig as the template engine app.engine('server.view.html', consolidate[config.templateEngine]); // Set views path and view engine app.set('view engine', 'server.view.html'); app.set('views', './app/views'); // Environment dependent middleware if (process.env.NODE_ENV === 'development') { // Enable logger (morgan) app.use(morgan('dev')); // Disable views cache app.set('view cache', false); } else if (process.env.NODE_ENV === 'production') { app.locals.cache = 'memory'; } // Request body parsing middleware should be above methodOverride app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride()); // Express MongoDB session storage app.use(session({ saveUninitialized: true, resave: true, secret: config.sessionSecret, store: new mongoStore({ db: db.connection.db, collection: config.sessionCollection }) })); // connect flash for flash messages app.use(flash()); // Use helmet to secure Express headers app.use(helmet.xframe()); app.use(helmet.xssFilter()); app.use(helmet.nosniff()); app.use(helmet.ienoopen()); app.disable('x-powered-by'); // Attach Socket.io var server = http.createServer(app); var io = socketio.listen(server); app.set('socketio', io); app.set('server', server); // Setting the app router and static folder app.use(express.static(path.resolve('./public'))); // Globbing routing files config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) { require(path.resolve(routePath))(app); }); // Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc. app.use(function(err, req, res, next) { // If the error object doesn't exists if (!err) return next(); // Log it console.error(err.stack); // Error page res.status(500).render('500', { error: err.stack }); }); // Assume 404 since no middleware responded app.use(function(req, res) { res.status(404).render('404', { url: req.originalUrl, error: 'Not Found' }); }); if (process.env.NODE_ENV === 'secure') { // Log SSL usage console.log('Securely using https protocol'); // Load SSL key and certificate var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8'); var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8'); // Create HTTPS Server var httpsServer = https.createServer({ key: privateKey, cert: certificate }, app); // Return HTTPS server instance return httpsServer; } // Return Express server instance return app; };
#! /usr/bin/env node var tools = require('../api/tools'); var mainCommands = require('./main-commands'); var commands = { runUserCommand : function (userCommand) { var cliCommand = commands.formatUserCommand(userCommand); var mainCommand = cliCommand.commands[0]; //if no main command found show help file unless --version present if (!mainCommand) { mainCommand = cliCommand.vFlags[0] == '--version' ? 'version' : 'help'; } var restOfCommands = cliCommand.commands.slice(1); mainCommands.run(mainCommand, restOfCommands, cliCommand.vFlags); }, formatUserCommand : function (userCommand) { var cliCommand = commands.initCLICommand(); userCommand.forEach(function (command) { if (tools.isVFlag(command)) { cliCommand.vFlags.push(command); } else if (tools.isFlag(command)) { var convertedvFlag = tools.convertTovFlag(command); if (tools.isVFlag(convertedvFlag)) { cliCommand.vFlags.push(convertedvFlag); } } else { cliCommand.commands.push(command); } }); return cliCommand; }, initCLICommand : function () { return { commands : [], vFlags : [], }; } } module.exports = commands;
$(document).ready(function() { 'use strict'; if (applicationStatusCode == 1) $('.ui.basic.modal').modal('show'); $('.ui.dropdown').dropdown({ on: 'hover' }); $('.masthead .information').transition('scale in', 1000); var animateIcons = function() { $('.ui.feature .icon .icon').transition({ animation: 'horizontal flip', duration: 600, }) .transition({ animation: 'horizontal flip', duration: 600, }); }; setInterval(animateIcons, 3200); $('.menu .item').tab(); $('.ui.checkbox').checkbox(); $('.ui.form input[name="birth"]').datetimepicker({ timepicker: false, format: 'Y/m/d', lang: 'zh-TW' }); var printAmount = function() { var items = '', total; $('.ui.form input:checked').each(function() { items += $(this).val(); }); if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')==-1 && items.indexOf('加購紀念 T 恤')==-1) total = 500; else if (items.indexOf('學術課程')==-1 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')==-1) total = 2100; else if (items.indexOf('學術課程')==-1 && items.indexOf('活動課程')==-1 && items.indexOf('加購紀念 T 恤')>=0) total = 250; else if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')==-1) total = 2500; else if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')==-1 && items.indexOf('加購紀念 T 恤')>=0) total = 650; else if (items.indexOf('學術課程')==-1 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')>=0) total = 2250; else if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')>=0) total = 2650; else total = 0; $('.ui.form .green.label').text('費用總計:NT$ ' + total); }; $('.ui.form .ui.checkbox:not(.radio)').on('click', printAmount); var validationRules = { name: { identifier: 'name', rules: [ { type: 'empty', prompt: '請輸入姓名' } ] }, birth: { identifier: 'birth', rules: [ { type: 'empty', prompt: '請輸入生日' } ] }, phone: { identifier: 'phone', rules: [ { type: 'empty', prompt: '請輸入行動電話' }, { type: 'maxLength[10]', prompt: '行動電話的長度超過 10 個字元' }, { type: 'length[10]', prompt: '行動電話的長度小於 10 個字元' }, { type: 'integer', prompt: '行動電話無效' } ] }, idnum: { identifier: 'idnum', rules: [ { type: 'empty', prompt: '請輸入身份證字號' }, { type: 'maxLength[10]', prompt: '身份證字號的長度超過 10 個字元' }, { type: 'length[10]', prompt: '身份證字號的長度小於 10 個字元' } ] }, email: { identifier: 'email', rules: [ { type: 'empty', prompt: '請輸入電子郵件信箱' }, { type: 'email', prompt: '電子郵件信箱無效' } ] } }; $('.ui.form').form(validationRules, { on: 'blur' }); }); function goToApply() { 'use strict'; var destination = document.getElementsByTagName('section')[2]; $('html, body').animate({ scrollTop: $(destination).offset().top }, 800); }
export default [ "Puolet viljantilan päästöistä syntyvät lannotteiden käytöstä" ]
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { PropTypes } from 'react'; import styles from './contentPressMention.css'; import withStyles from '../../../decorators/withStyles'; @withStyles(styles) //ContentPressMention Component class ContentPressMention extends React.Component { constructor (props) { super(props) } render() { return ( <div className="ContentItem"> <p>This is a Press Mention</p> <p>{this.props.item.contentType}</p> </div> ); } } export default ContentPressMention;
define(['global/session', 'services/errorhandler', 'services/config', 'plugins/router', 'services/logger'], function (session, errorhandler, config, router, logger) { var unitofwork = session.unitofwork(); var vm = { activate: activate, attached: attached, audienceTypes: ko.observableArray(), reportTypes: ko.observableArray(), selectedAudienceType: ko.observable(), selectedDepartmentId: ko.observable(), selectedReportType: ko.observable(), selectedUnitId: ko.observable(), units: ko.observableArray(), generateReport: generateReport, }; errorhandler.includeIn(vm); return vm; function activate() { ga('send', 'pageview', { 'page': window.location.href, 'title': document.title }); return true; } function attached() { var self = this, audienceTypes = [ 'Department', 'Unit' ], reportTypes = [ { route: 'fo-export', text: 'Fiscal officer export' }, { route: 'meeting', text: 'Meeting' }, { route: 'base-salary-adjustment', text: 'Faculty with base salary adjustments' }, { route: 'multiple-employments', text: 'Faculty with multiple departments' }, { route: 'merit-summary-report', text: 'Merit summary' }, { route: 'salaries-by-faculty-type', text: 'Salaries by faculty type' }, { route: 'unreviewed', text: 'Unreviewed faculty' } ], units = unitofwork.units.all() .then(function (response) { vm.units(response); vm.selectedDepartmentId(response[0].departments()[0].id()) }); if (session.userIsInRole('manage-all')) { reportTypes.push({ route: 'role-assignment', text: 'User roles' }); } Q.all([units]).fail(self.handleError); vm.audienceTypes(audienceTypes); vm.reportTypes(reportTypes); return true; } function generateReport() { var route; switch (vm.selectedAudienceType()) { case 'Department': if (vm.selectedDepartmentId() && vm.selectedDepartmentId() !== 'Choose...') { route = 'reports/' + vm.selectedReportType() + '/' + vm.selectedDepartmentId(); router.navigate(route); } else { logger.logError('Choose a department to continue.', null, null, true); } break; case 'Unit': if (vm.selectedUnitId()) { route = 'reports/' + vm.selectedReportType() + '/' + vm.selectedUnitId(); router.navigate(route); } else { logger.logError('Choose a unit to continue.', null, null, true); } break; } } });
'use strict'; const assert = require('assert'); const { inspect } = require('util'); const { mustCall, mustCallAtLeast, setupSimple, } = require('./common.js'); const DEBUG = false; const setup = setupSimple.bind(undefined, DEBUG); { const { client, server } = setup('Simple exec()'); const COMMAND = 'foo --bar'; const STDOUT_DATA = 'stdout data!\n'; const STDERR_DATA = 'stderr data!\n'; server.on('connection', mustCall((conn) => { conn.on('ready', mustCall(() => { conn.on('session', mustCall((accept, reject) => { accept().on('exec', mustCall((accept, reject, info) => { assert(info.command === COMMAND, `Wrong exec command: ${info.command}`); const stream = accept(); stream.stderr.write(STDERR_DATA); stream.write(STDOUT_DATA); stream.exit(100); stream.end(); conn.end(); })); })); })); })); client.on('ready', mustCall(() => { let out = ''; let outErr = ''; const events = []; const EXPECTED_EVENTS = [ 'exit', 'close' ]; const EXPECTED_EXIT_CLOSE_ARGS = [ 100 ]; client.on('close', mustCall(() => { assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); assert.deepStrictEqual( events, EXPECTED_EVENTS, `Wrong command event order: ${events}` ); })).exec(COMMAND, mustCall((err, stream) => { assert(!err, `Unexpected exec error: ${err}`); stream.on('data', mustCallAtLeast((d) => { out += d; })).on('exit', mustCall((...args) => { assert.deepStrictEqual(args, EXPECTED_EXIT_CLOSE_ARGS, `Wrong exit args: ${inspect(args)}`); events.push('exit'); })).on('close', mustCall((...args) => { assert.deepStrictEqual(args, EXPECTED_EXIT_CLOSE_ARGS, `Wrong close args: ${inspect(args)}`); events.push('close'); })).stderr.on('data', mustCallAtLeast((d) => { outErr += d; })); })); })); } { const { client, server } = setup('Simple exec() (exit signal)'); const COMMAND = 'foo --bar'; const STDOUT_DATA = 'stdout data!\n'; const STDERR_DATA = 'stderr data!\n'; server.on('connection', mustCall((conn) => { conn.on('ready', mustCall(() => { conn.on('session', mustCall((accept, reject) => { accept().on('exec', mustCall((accept, reject, info) => { assert(info.command === COMMAND, `Wrong exec command: ${info.command}`); const stream = accept(); stream.stderr.write(STDERR_DATA); stream.write(STDOUT_DATA); assert.throws(() => stream.exit('SIGFAKE')); stream.exit('SIGKILL'); stream.end(); conn.end(); })); })); })); })); client.on('ready', mustCall(() => { let out = ''; let outErr = ''; const events = []; const EXPECTED_EVENTS = [ 'exit', 'close' ]; const EXPECTED_EXIT_CLOSE_ARGS = [ null, 'SIGKILL', false, '' ]; client.on('close', mustCall(() => { assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); assert.deepStrictEqual( events, EXPECTED_EVENTS, `Wrong command event order: ${events}` ); })).exec(COMMAND, mustCall((err, stream) => { assert(!err, `Unexpected exec error: ${err}`); stream.on('data', mustCallAtLeast((d) => { out += d; })).on('exit', mustCall((...args) => { assert.deepStrictEqual(args, EXPECTED_EXIT_CLOSE_ARGS, `Wrong exit args: ${inspect(args)}`); events.push('exit'); })).on('close', mustCall((...args) => { assert.deepStrictEqual(args, EXPECTED_EXIT_CLOSE_ARGS, `Wrong close args: ${inspect(args)}`); events.push('close'); })).stderr.on('data', mustCallAtLeast((d) => { outErr += d; })); })); })); } { const { client, server } = setup('Simple exec() (exit signal -- no "SIG")'); const COMMAND = 'foo --bar'; const STDOUT_DATA = 'stdout data!\n'; const STDERR_DATA = 'stderr data!\n'; server.on('connection', mustCall((conn) => { conn.on('ready', mustCall(() => { conn.on('session', mustCall((accept, reject) => { accept().on('exec', mustCall((accept, reject, info) => { assert(info.command === COMMAND, `Wrong exec command: ${info.command}`); const stream = accept(); stream.stderr.write(STDERR_DATA); stream.write(STDOUT_DATA); assert.throws(() => stream.exit('FAKE')); stream.exit('KILL'); stream.end(); conn.end(); })); })); })); })); client.on('ready', mustCall(() => { let out = ''; let outErr = ''; const events = []; const EXPECTED_EVENTS = [ 'exit', 'close' ]; const EXPECTED_EXIT_CLOSE_ARGS = [ null, 'SIGKILL', false, '' ]; client.on('close', mustCall(() => { assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); assert.deepStrictEqual( events, EXPECTED_EVENTS, `Wrong command event order: ${events}` ); })).exec(COMMAND, mustCall((err, stream) => { assert(!err, `Unexpected exec error: ${err}`); stream.on('data', mustCallAtLeast((d) => { out += d; })).on('exit', mustCall((...args) => { assert.deepStrictEqual(args, EXPECTED_EXIT_CLOSE_ARGS, `Wrong exit args: ${inspect(args)}`); events.push('exit'); })).on('close', mustCall((...args) => { assert.deepStrictEqual(args, EXPECTED_EXIT_CLOSE_ARGS, `Wrong close args: ${inspect(args)}`); events.push('close'); })).stderr.on('data', mustCallAtLeast((d) => { outErr += d; })); })); })); } { const { client, server } = setup('Exec with signal()'); const COMMAND = 'foo --bar'; const STDOUT_DATA = 'stdout data!\n'; const STDERR_DATA = 'stderr data!\n'; server.on('connection', mustCall((conn) => { conn.on('ready', mustCall(() => { conn.on('session', mustCall((accept, reject) => { let stream; accept().on('exec', mustCall((accept, reject, info) => { assert(info.command === COMMAND, `Wrong exec command: ${info.command}`); stream = accept(); stream.stderr.write(STDERR_DATA); stream.write(STDOUT_DATA); })).on('signal', mustCall((accept, reject, info) => { assert(info.name === 'INT', `Wrong client signal name: ${info.name}`); stream.exit(100); stream.end(); conn.end(); })); })); })); })); client.on('ready', mustCall(() => { let out = ''; let outErr = ''; const events = []; const EXPECTED_EVENTS = [ 'exit', 'close' ]; const EXPECTED_EXIT_CLOSE_ARGS = [ 100 ]; client.on('close', mustCall(() => { assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); assert.deepStrictEqual( events, EXPECTED_EVENTS, `Wrong command event order: ${events}` ); })).exec(COMMAND, mustCall((err, stream) => { assert(!err, `Unexpected exec error: ${err}`); const sendSignal = (() => { let sent = false; return () => { if (sent) return; sent = true; assert.throws(() => stream.signal('FAKE')); assert.throws(() => stream.signal('SIGFAKE')); stream.signal('SIGINT'); }; })(); stream.on('data', mustCallAtLeast((d) => { out += d; sendSignal(); })).on('exit', mustCall((...args) => { assert.deepStrictEqual(args, EXPECTED_EXIT_CLOSE_ARGS, `Wrong exit args: ${inspect(args)}`); events.push('exit'); })).on('close', mustCall((...args) => { assert.deepStrictEqual(args, EXPECTED_EXIT_CLOSE_ARGS, `Wrong close args: ${inspect(args)}`); events.push('close'); })).stderr.on('data', mustCallAtLeast((d) => { outErr += d; })); })); })); } { const { client, server } = setup('Exec with signal() -- no "SIG"'); const COMMAND = 'foo --bar'; const STDOUT_DATA = 'stdout data!\n'; const STDERR_DATA = 'stderr data!\n'; server.on('connection', mustCall((conn) => { conn.on('ready', mustCall(() => { conn.on('session', mustCall((accept, reject) => { let stream; accept().on('exec', mustCall((accept, reject, info) => { assert(info.command === COMMAND, `Wrong exec command: ${info.command}`); stream = accept(); stream.stderr.write(STDERR_DATA); stream.write(STDOUT_DATA); })).on('signal', mustCall((accept, reject, info) => { assert(info.name === 'INT', `Wrong client signal name: ${info.name}`); stream.exit(100); stream.end(); conn.end(); })); })); })); })); client.on('ready', mustCall(() => { let out = ''; let outErr = ''; const events = []; const EXPECTED_EVENTS = [ 'exit', 'close' ]; const EXPECTED_EXIT_CLOSE_ARGS = [ 100 ]; client.on('close', mustCall(() => { assert(out === STDOUT_DATA, `Wrong stdout data: ${inspect(out)}`); assert(outErr === STDERR_DATA, `Wrong stderr data: ${inspect(outErr)}`); assert.deepStrictEqual( events, EXPECTED_EVENTS, `Wrong command event order: ${events}` ); })).exec(COMMAND, mustCall((err, stream) => { assert(!err, `Unexpected exec error: ${err}`); const sendSignal = (() => { let sent = false; return () => { if (sent) return; sent = true; stream.signal('INT'); }; })(); stream.on('data', mustCallAtLeast((d) => { out += d; sendSignal(); })).on('exit', mustCall((...args) => { assert.deepStrictEqual(args, EXPECTED_EXIT_CLOSE_ARGS, `Wrong exit args: ${inspect(args)}`); events.push('exit'); })).on('close', mustCall((...args) => { assert.deepStrictEqual(args, EXPECTED_EXIT_CLOSE_ARGS, `Wrong close args: ${inspect(args)}`); events.push('close'); })).stderr.on('data', mustCallAtLeast((d) => { outErr += d; })); })); })); } { const { client, server } = setup('Exec with environment set'); const env = { SSH2NODETEST: 'foo' }; server.on('connection', mustCall((conn) => { conn.on('ready', mustCall(() => { conn.on('session', mustCall((accept, reject) => { accept().on('env', mustCall((accept, reject, info) => { accept && accept(); assert(info.key === Object.keys(env)[0], 'Wrong env key'); assert(info.val === Object.values(env)[0], 'Wrong env value'); })).on('exec', mustCall((accept, reject, info) => { assert(info.command === 'foo --bar', `Wrong exec command: ${info.command}`); const stream = accept(); stream.exit(100); stream.end(); conn.end(); })); })); })); })); client.on('ready', mustCall(() => { client.exec('foo --bar', { env }, mustCall((err, stream) => { assert(!err, `Unexpected exec error: ${err}`); stream.resume(); })); })); } { const { client, server } = setup('Exec with setWindow()'); const dimensions = { rows: 60, cols: 115, height: 480, width: 640, }; server.on('connection', mustCall((conn) => { conn.on('ready', mustCall(() => { conn.on('session', mustCall((accept, reject) => { accept().on('window-change', mustCall((accept, reject, info) => { accept && accept(); assert.deepStrictEqual(info, dimensions, 'Wrong dimensions'); })).on('exec', mustCall((accept, reject, info) => { assert(info.command === 'foo --bar', `Wrong exec command: ${info.command}`); const stream = accept(); stream.exit(100); stream.end(); conn.end(); })); })); })); })); client.on('ready', mustCall(() => { client.exec('foo --bar', mustCall((err, stream) => { assert(!err, `Unexpected exec error: ${err}`); stream.setWindow(...Object.values(dimensions)); stream.resume(); })); })); } { const { client, server } = setup('Exec with pty set'); const pty = { rows: 2, cols: 4, width: 0, height: 0, term: 'vt220', modes: {}, }; server.on('connection', mustCall((conn) => { conn.on('ready', mustCall(() => { conn.on('session', mustCall((accept, reject) => { let sawPty = false; accept().on('pty', mustCall((accept, reject, info) => { assert.deepStrictEqual(info, pty, 'Wrong pty info'); sawPty = true; accept && accept(); })).on('exec', mustCall((accept, reject, info) => { assert(sawPty, 'Expected pty to be set up'); assert(info.command === 'foo --bar', `Wrong exec command: ${info.command}`); const stream = accept(); stream.exit(100); stream.end(); conn.end(); })); })); })); })); client.on('ready', mustCall(() => { client.exec('foo --bar', { pty }, mustCall((err, stream) => { assert(!err, `Unexpected exec error: ${err}`); stream.resume(); })); })); } { const { client, server } = setup('Exec with X11 forwarding'); server.on('connection', mustCall((conn) => { conn.on('ready', mustCall(() => { conn.on('session', mustCall((accept, reject) => { let sawX11 = false; accept().on('x11', mustCall((accept, reject, info) => { assert.strictEqual(info.single, false, `Wrong x11 single: ${info.single}`); assert.strictEqual(info.screen, 0, `Wrong x11 screen: ${info.screen}`); assert.strictEqual(info.protocol, 'MIT-MAGIC-COOKIE-1', `Wrong x11 protocol: ${info.protocol}`); assert(Buffer.isBuffer(info.cookie), 'Expected cookie Buffer'); assert.strictEqual( info.cookie.length, 32, `Invalid x11 cookie length: ${info.cookie.length}` ); sawX11 = true; accept && accept(); })).on('exec', mustCall((accept, reject, info) => { assert(sawX11, 'Expected x11 before exec'); assert(info.command === 'foo --bar', `Wrong exec command: ${info.command}`); const stream = accept(); conn.x11('127.0.0.1', 4321, mustCall((err, xstream) => { assert(!err, `Unexpected x11() error: ${err}`); xstream.resume(); xstream.on('end', mustCall(() => { stream.exit(100); stream.end(); conn.end(); })).end(); })); })); })); })); })); client.on('ready', mustCall(() => { client.on('x11', mustCall((info, accept, reject) => { assert.strictEqual(info.srcIP, '127.0.0.1', `Invalid x11 srcIP: ${info.srcIP}`); assert.strictEqual(info.srcPort, 4321, `Invalid x11 srcPort: ${info.srcPort}`); accept(); })).exec('foo --bar', { x11: true }, mustCall((err, stream) => { assert(!err, `Unexpected exec error: ${err}`); stream.resume(); })); })); } { const { client, server } = setup( 'Exec with X11 forwarding (custom X11 settings)' ); const x11 = { single: true, screen: 1234, protocol: 'YUMMY-MAGIC-COOKIE-1', cookie: '00112233445566778899001122334455', }; server.on('connection', mustCall((conn) => { conn.on('ready', mustCall(() => { conn.on('session', mustCall((accept, reject) => { let sawX11 = false; accept().on('x11', mustCall((accept, reject, info) => { assert.strictEqual(info.single, x11.single, `Wrong x11 single: ${info.single}`); assert.strictEqual(info.screen, x11.screen, `Wrong x11 screen: ${info.screen}`); assert.strictEqual(info.protocol, x11.protocol, `Wrong x11 protocol: ${info.protocol}`); assert(Buffer.isBuffer(info.cookie), 'Expected cookie Buffer'); assert.strictEqual(info.cookie.toString(), x11.cookie, `Wrong x11 cookie: ${info.cookie}`); sawX11 = true; accept && accept(); })).on('exec', mustCall((accept, reject, info) => { assert(sawX11, 'Expected x11 before exec'); assert(info.command === 'foo --bar', `Wrong exec command: ${info.command}`); const stream = accept(); conn.x11('127.0.0.1', 4321, mustCall((err, xstream) => { assert(!err, `Unexpected x11() error: ${err}`); xstream.resume(); xstream.on('end', mustCall(() => { stream.exit(100); stream.end(); conn.end(); })).end(); })); })); })); })); })); client.on('ready', mustCall(() => { client.on('x11', mustCall((info, accept, reject) => { assert.strictEqual(info.srcIP, '127.0.0.1', `Invalid x11 srcIP: ${info.srcIP}`); assert.strictEqual(info.srcPort, 4321, `Invalid x11 srcPort: ${info.srcPort}`); accept(); })).exec('foo --bar', { x11 }, mustCall((err, stream) => { assert(!err, `Unexpected exec error: ${err}`); stream.resume(); })); })); }
export * from './client-exports' // TODO: add exports all test case in pages /** import * as all from '../components/client-exports-all' import * as allClient from '../components/client-exports-all.client' export default function Page() { const { a, b, c, d, e } = all const { a: ac, b: bc, c: cc, d: dc, e: ec } = allClient return ( <div> <div id='server'>{a}{b}{c}{d}{e[0]}</div> <div id='client'>{ac}{bc}{cc}{dc}{ec[0]}</div> </div> ) } */
'use strict'; var ejs = { renderFile: require('ejs-locals') }; var phantomjs = require('phantomjs'); var nodePhantom = require('node-phantom-simple'); var phantom; var debug = require('./debug'); var log = debug.getLogger({ prefix: '[pdfgen]- ' }); var paperSize = { format: 'Letter', orientation: 'portrait', margin: '1cm' }; var phantomErrorMsg = 'Error creating PhantomJS instance:\n\n\t%s\n'; var renderMsg = 'Successfully rendered PDF \'%s\''; var initMsg = 'Successfully initialized'; var templatePath = 'server/views/pdf/'; function generate (html, path, onError, onSuccess) { if (typeof html !== 'string' || typeof path !== 'string') { log('Error: expects parameters (html, path, callback)', onError); return; } phantom.createPage(function (err, page) { if (err) { log('Error creating page:\n\n\t%s\n', err, onError); return; } page.onLoadFinished = function (status) { if (status !== 'success') { log('Error rendering PDF \'%s\': %s', path, status, onError); return; } page.render(path, function (err) { if (err) { log('Error rendering PDF \'%s\': %s', path, err, onError); return; } log(renderMsg, path, function (renderMsg) { if (typeof onSuccess === 'function') { onSuccess(renderMsg); } }); page.close(); }); }; page.set('paperSize', paperSize); page.set('content', html); }); } module.exports = { init: function (callback) { if (typeof phantom === 'undefined' || typeof page === 'undefined') { nodePhantom.create(onPhantomCreated, { phantomPath: phantomjs.path }); } function onPhantomCreated (err, ph) { if (err) { log(phantomErrorMsg, err, callback); return; } phantom = ph; log(initMsg, function (initMsg) { if (typeof callback === 'function') { callback(null, initMsg); } }); } }, render: function (options) { var html = options.html; var path = options.path; var template = options.template; var locals = options.locals; var onError = options.onError; var onSuccess = options.onSuccess; if (typeof template === 'string' && typeof locals === 'object') { if (!/\.\/.+/.test(template)) template = templatePath + template; template += '.html'; ejs.renderFile(template, locals, function (err, html) { if (err) { log('Error reading template file:\n\n\t%s\n', err, onError); return; } generate(html, path, onError, onSuccess); }); } else { generate(html, path, onError, onSuccess); } } };
'use strict' const fs = require('fs') const path = require('path') const stripeComments = require('strip-css-comments') module.exports = function getLessVariables(theme) { return getContent(theme) } function trim (str) { if (!str) { return '' } else { return str.replace(/^\s+|\s+$/g, '') } } function getContent (file) { let themeContent = fs.readFileSync(file, 'utf-8') themeContent = stripeComments(themeContent) var variables = {} themeContent.split('\n').forEach(function (item) { if (trim(item).indexOf('//') === 0 || trim(item).indexOf('/*') === 0) { return } // has comments if (item.indexOf('//') > 0) { item = trim(item.slice(0, item.indexOf('//'))) } if (item.indexOf('/*') > 0) { item = trim(item.slice(0, item.indexOf('/*'))) } var _pair = item.split(':') if (_pair.length < 2) { if (!/@import/.test(_pair[0])) { return } let partFile = _pair[0] .replace(/;/g, '') .replace('@import', '') .replace(/'/g, '') .replace(/"/g, '') .replace(/\s+/g, '').trim() const partPath = path.resolve(path.dirname(file), partFile) let partVariables = getContent(partPath) for (let i in partVariables) { variables[i] = partVariables[i] } } else { let key = _pair[0].replace('\r', '').replace('@', '') if (!key) return; key = key.trim() if (!/^[A-Za-z0-9_-]*$/.test(key)) { console.log(`[vux-loader] 疑似不合法命名,将被忽略:${key}`) return } var value = _pair[1].replace(';', '').replace('\r', '').replace(/^\s+|\s+$/g, '') variables[key] = value } }) return variables }
import './lottery/base.js' import './lottery/timer.js' import './lottery/calculate.js' import './lottery/interface.js'
'use strict'; // Modules require('should'); // Subject var error_not_found = require('../../../app/errors/not_found.error.js'); describe('Error - ErrorNotFound', function () { it('should have a name of "ErrorNotFound"', function () { new error_not_found().should.have.property('name').and.equal('ErrorNotFound'); }); it('should have a type of "client"', function () { new error_not_found().should.have.property('type').and.equal('client'); }); it('should have a status of 404', function () { new error_not_found().should.have.property('status').and.equal(404); }); it('should have a message only when one is provided', function () { new error_not_found().should.not.have.property('message'); new error_not_found('My Message').should.have.property('message').and.equal('My Message'); }); it('should not have a data property by default', function () { new error_not_found().should.not.have.property('data'); }); it('should have a data property when sent an object with method', function () { var error = new error_not_found('message', { method : 'crystal' }); error.should.have.property('data').and.be.type('object'); error.data.should.have.property('method').and.equal('crystal'); }); it('should have a data property when sent an object with path', function () { var error = new error_not_found('message', { path : 'dirt' }); error.should.have.property('data').and.be.type('object'); error.data.should.have.property('path').and.equal('dirt'); }); });
class Rocket { constructor( context, canvasWidth, canvasHeight, width, height, orientationDirection, rotationRate, xVector, yVector, x, y, color) { // "this" refers to the instance of Rocket that I'm currently working with // Add properties to "this" when each instance of the class should have that property this.context = context; this.canvasWidth = canvasWidth; this.canvasHeight = canvasHeight; this.width = width; this.height = height; this.orientationDirection = orientationDirection; this.rotationRate = rotationRate; this.xVector = xVector; this.yVector = yVector; this.movementRate = 0; this.x = x; this.y = y; this.color = color; this.movementDirection = this.orientationDirection; window.addEventListener('keydown', event => this.handleKeydown(event)); } handleKeydown(event){ var orientationDirection = this.orientationDirection; var rotationRate = this.rotationRate; var movementRate = this.movementRate; var xVector = this.xVector; var yVector = this.yVector; switch(event.which){ case 37: // left this.orientationDirection = orientationDirection - rotationRate; break; case 38: // up this.movementRate = this.movementRate + 1; this.movementDirection = this.orientationDirection; break; case 39: // right this.orientationDirection = orientationDirection + rotationRate; break; case 40: // down this.movementRate = this.movementRate - 1; break; default: } } update(){ // var x = this.x; // x = 2; // this.x did not get changed to 2. Only the variable x got updated. // To change this.x, I have to say this.x = 2; // Variable x only lets me refer to the value of this.x from the time // I did the variable assignment. if (this.movementRate < 0){ this.movementRate = 0; } this.xVector = this.movementRate * Math.cos(this.movementDirection * Math.PI / 180); this.yVector = this.movementRate * Math.sin(this.movementDirection * Math.PI / 180); this.x = this.x + this.xVector; this.y = this.y + this.yVector; // console.log('update(), this.orientationDirection', this.orientationDirection); if (this.orientationDirection > 360){ this.orientationDirection = 0; } if (this.isRocketAtBoundary()){ this.stopRocket(); } } isRocketAtBoundary(){ var result = false; // At right boundary if (this.x >= (this.canvasWidth - this.width)){ result = true; } // At bottom boundary if (this.y >= (this.canvasHeight - this.height)){ result = true; } // At left boundary if (this.x < 0){ result = true; } // At top boundary if (this.y < 0){ result = true; } return result; } stopRocket(){ this.xVector = 0; this.yVector = 0; } draw(){ this.update(); var context = this.context; var x = this.x; var y = this.y; var width = this.width; var height = this.height; var orientationDirection = this.orientationDirection; context.save(); var centerX = x + width/2; var centerY = y + height/2; context.translate(centerX, centerY); // Translate to center of rectangle // Convert degrees to radians, because context.rotate needs radians var radians = orientationDirection * (Math.PI/180); context.rotate(radians); // Draw a triangle with paths context.strokeStyle = this.color; // Start a new path context.beginPath(); // Now define the path with .moveTo() and .lineTo() methods var triangleOriginX = -width/2; var triangleOriginY = -height/2; context.moveTo(triangleOriginX, triangleOriginY); context.lineTo(triangleOriginX + width, triangleOriginY + height/2); context.lineTo(triangleOriginX, triangleOriginY + height); context.closePath(); // The path is only made visible when we call .stroke() context.stroke(); context.restore(); } }
"use strict"; const getFirstIndex = require("./getFirstIndex"); const TimeUtils = require("./TimeUtils"); const dateToSeconds = TimeUtils.dateToSeconds; const hoursToSeconds = TimeUtils.hoursToSeconds; // get the current salat index from a list of times const getCurrent = (times, date) => { const now = date || new Date(); const total = times.length; // round to seconds because it is possible that fajr == isha // and float comparisation is not so great const currentSecond = dateToSeconds(now); const timesInSec = times.map(hoursToSeconds); // get the earliest time (isha can be before or after 0:00) const first = getFirstIndex(timesInSec); for (let i = 0; i < total; i++) { // adjusted counter starts at lowest value const j = (first + i) % total; // loop over the times until we find an upcoming item if (currentSecond >= timesInSec[j]) continue; // current salat was the previous item return (j + total - 1) % total; } // otherwise the current salat is the last item return (first + total - 1) % total; }; module.exports = getCurrent;
/** Universe.js Classes */ var UNIVERSE = UNIVERSE || {}; /** A simple Universe for drawing 3D modeling and simulation using WebGL @constructor @param {Date} time - The current universe time @param {double} refreshRate - The refresh rate for the universe in milliseconds @param {DOMElement} container - the container where the Universe will be drawn */ UNIVERSE.Universe = function (time, refreshRate, container) { var controller = new UNIVERSE.UniverseController(refreshRate), core = new UNIVERSE.Core3D(container), objectLibrary = new UNIVERSE.ObjectLibrary(), currentUniverseTime = time, // options playbackSpeed = 1, stateChangedCallback = function () {}, //function to call when we have a new state object timeBetweenStateUpdatesMs = 1000, // milliseconds between updating our state object that we broadcast to any listeners updateStateTimeout, // timeout for updating state universe = this; // OBJECT LIBRARY DEFAULTS objectLibrary.setObject("default_geometry", new THREE.Geometry()); objectLibrary.setObject("default_material", new THREE.MeshBasicMaterial()); // PRIVATE METHODS /** fires a state changed event to the callback @private */ function fireStateChanged(state) { if (stateChangedCallback !== null) { stateChangedCallback(state); } } /** adds an object that updates the currentUniverseTime using the playback speed @private */ function addSimStateObject() { controller.addGraphicsObject({ id : "simState", objectName : "simState", update : function (elapsedTime) { if (elapsedTime !== null) { currentUniverseTime.setTime(currentUniverseTime.getTime() + playbackSpeed * elapsedTime); } }, draw : function () { } }); } /** gets called at our state update interval and fires the state change callback @private */ function updateState() { //create our state object and notify our listener var state = { currentUniverseTime: new Date(currentUniverseTime) }; fireStateChanged(state); // call update() again in a certain number of milliseconds updateStateTimeout = setTimeout(function () { updateState(); }, timeBetweenStateUpdatesMs); } // PROTECTED METHODS (API METHODS) /** Start playback for the universe @public @param {date} startTime @param {double} newPlaybackSpeed @param {function} newStateChangedCallback */ this.play = function (startTime, newPlaybackSpeed, newStateChangedCallback) { clearTimeout(updateStateTimeout); if (startTime) { currentUniverseTime = new Date(startTime); } if (newPlaybackSpeed) { playbackSpeed = newPlaybackSpeed; } if (newStateChangedCallback) { stateChangedCallback = newStateChangedCallback; } // update state our first time updateState(); controller.play(); }; this.getMinZoomDistance = function () { return core.minZoom; }; this.getMaxZoomDistance = function () { return core.maxZoom; }; this.setCurrentZoomDistance = function (newDistanceTarget) { core.distanceTarget = newDistanceTarget; }; this.getCurrentZoomDistance = function () { return core.distanceTarget; }; /** Pause playback for the universe @public */ this.pause = function () { clearTimeout(updateStateTimeout); controller.pause(); }; /** Set the playback speed for the Universe @public @param {Double} speed */ this.setPlaybackSpeed = function (speed) { playbackSpeed = speed; }; /** Set the current time of the Universe @public @param {Date} newUniverseTime */ this.setCurrentUniverseTime = function (newUniverseTime) { currentUniverseTime = new Date(newUniverseTime); controller.updateOnce(); }; /** Get the current time of the Universe @public */ this.getCurrentUniverseTime = function () { return currentUniverseTime; }; /** Add a geometry to the universe with an ID and url to retrieve the model's geometry @public @param {string} modelId @param {string} modelUrl - URL for the THREE.js format geometry model @param {function} callback - callback function that gets called when the geometry is done loading */ this.addJsonGeometryModel = function (modelId, modelUrl, callback) { if (modelId) { objectLibrary.addGeometryObjectFromUrl(modelId, modelUrl, callback); } else { callback(); } }; /** Add an object to the universe @public @param {UNIVERSE.GraphicsObject} object */ this.addObject = function (object) { controller.addGraphicsObject(object); }; /** Draws an object in the Universe @public @param {string} id - identifier for the object @param {THREE.Mesh} mesh - THREE.js mesh for the object @param {boolean} isScale - specifies whether the object should be scaled to always be the same as the camera moves */ this.draw = function (id, mesh, isScale) { core.draw(id, mesh, isScale); }; /** Removes an object from the Universe @public @param {string} id - identifier for the object */ this.unDraw = function (id) { core.removeObject(id); }; /** Add an object to the Universe.js object pipeline. This is useful for storing things that take up GPU memory like geometries so you can reuse them. @public @param {string} id - identifier for the object @param {Object} object - any object you want to store for later retrieval */ this.setObjectInLibrary = function (id, object) { objectLibrary.setObject(id, object); }; /** Retrieves an object from the Universe.js object pipeline @public @param {string} id - identifier for the object @param {function} callback - method to be called with the retrieved object */ this.getObjectFromLibraryById = function (id, callback) { objectLibrary.getObjectById(id, callback); }; /** Remove an object completely from the Universe @public @param {string} id - identifier for the object */ this.removeObject = function (id) { controller.removeGraphicsObject(id); core.removeObject(id); }; /** Snap the Universe's camera to be directly behind an object @public @param {string} id - identifier for the object */ this.snapToObject = function (id) { // get the object's position and copy it into a vector var position = core.getObjectPosition(id), vector; if (position) { vector = new THREE.Vector3(); vector.copy(position); // move the point the camera will be at out a bit so we are behind the object vector.multiplyScalar(1.4); // tell the core to move to the vector core.moveCameraTo(vector); } // else Object is not added to the core so don't do anything }; this.addRotationToCamera = function (xRotation, yRotation) { core.addRotationToCameraTarget(xRotation, yRotation); }; /** Remove all objects from the Universe @public */ this.removeAll = function () { core.removeAllObjects(); controller.removeAllGraphicsObjects(); }; /** Get all of the objects currently in the Universe @public */ this.getGraphicsObjects = function () { return controller.getGraphicsObjects(); }; /** Get a graphics object by its id @public @param {string} id */ this.getGraphicsObjectById = function (id) { return controller.getGraphicsObjectById(id); }; /** @ignore */ // this.updateObject = function (id, propertyName, propertyValue) { // TODO: Implement or delete // }; this.updateOnce = function () { controller.updateOnce(); }; /** Toggle whether an object is visible in the Universe @public @param {string} id - identifier for the object @param {boolean} isEnabled - whether the object is visible or not */ this.showObject = function (id, isEnabled) { core.showObject(id, isEnabled); }; this.updateLight = function (x, y, z, intensity) { core.updateLight(new THREE.Vector3(x, y, z), intensity); }; this.addIntersectionListener = function(callback) { core.addIntersectionListener(callback); } /** Basic setup method, needs to be called after all objects are removed from the Universe @public */ this.setup = function () { addSimStateObject(); }; this.setup(); };
// We want to use this to test the user service // TODO: Add ability to create/use a separate test DB var assert = require("assert"), async = require('async'), _ = require('lodash'), Sequelize = require('sequelize'), // Grab the models using our connection models = require('../models')(new Sequelize( 'care', 'postgres', 'postgres', { dialect: "postgres", // 'mysql', 'sqlite', 'postgres', 'mariadb' port: 5432, // 3306 = mysql, 5432 = postgres omitNull: true // Needed to get sequelize to NOT insert nulls for postgres keys } )), user = require("../services/user.service")(models), userIDs = []; // User test describe('User', function(){ describe('#create()', function(){ it('should create a user with no tasks', function(done){ user.create({ username: 'Barry Test', userpassword: 'password', email: 'barry' + (new Date()).getTime() + '@example.com' }, null, // The callback returns error or null, user or null function(err, user){ assert.equal(user.username, 'Barry Test'); userIDs.push(user.id); done(); }); }); }); describe('#create()', function(){ it('should throw an error when we try to create a user with an invalid email address', function(done){ user.create({ username: 'Barry Test', userpassword: 'password', email: '@' }, null, // The callback returns error or null, user or null function(err, user){ assert.equal(err.email[0], 'Email address must be between 7 and 128 characters in length'); assert.equal(err.email[1], 'Email address must be valid'); assert.equal(err.email.length, 2); done(); }); }); }); describe('#create()', function(){ it('should create a user with a set of tasks', function(done){ user.create({ username: 'Barry Test', userpassword: 'password', email: 'barry' + (new Date()).getTime() + '@example.com' }, [{ title: 'blah', complete: false }, { title: 'deblah', complete: true }], // The callback returns error or null, user or null function(err, user){ assert.equal(user.username, 'Barry Test'); userIDs.push(user.id); done(); }); }); }); describe('#get()', function(){ it('should get a user by id', function(done){ // Grab the newly created user user.get(userIDs[1], function(err, user){ assert.equal(user.username, 'Barry Test'); assert.equal(user.tasks[1].title, 'deblah'); assert.equal(user.tasks[1].complete, true); done(); }); }); }); describe('#update()', function(){ it('should update a user\'s password', function(done){ user.update({ id: userIDs[0], userpassword: 'password2' }, // null won't change the tasks, [] will empty the tasks null, // The callback returns error or null, user or null function(err, user){ assert.equal(user.userpassword, 'password2'); done(); }); }); }); describe('#update()', function(){ it('should throw an error when we try to set an invalid email', function(done){ user.update({ id: userIDs[0], email: 'notanemailaddress' }, // null won't change the tasks, [] will empty the tasks null, // The callback returns error or null, user or null function(err, user){ assert.equal(err.email[0], 'Email address must be valid'); assert.equal(err.email.length, 1); done(); }); }); }); describe('#update()', function(){ it('should update a user\'s tasks', function(done){ user.update({ id: userIDs[0] }, // null won't change the tasks, [] will empty the tasks [{ title: 'Get milk', complete: false }], // The callback returns error or null, user or null function(err, user){ assert.equal(user.userpassword, 'password2'); done(); }); }); }); describe('#create()', function(){ it('should throw error when trying to create a user with a password length less than 6', function(done){ user.create({ username: 'Barry Test', userpassword: '123', email: 'barry' + (new Date()).getTime() + '@example.com' }, [{ title: 'blah', complete: false }, { title: 'deblah', complete: true }], // The callback returns error or null, user or null function(err, user){ assert.equal(typeof user, 'undefined'); assert.equal(err.userpassword, 'Password must be at least 6 characters'); done(); }); }); }); describe('#delete()', function(){ it('should delete all test users and associated tasks', function(done){ var endAt = userIDs.length - 1; _.forOwn(userIDs, function(id, k){ user.delete(id, function(err){ assert.equal(typeof err, 'undefined'); // Try to get the user - we expect use to be null user.get(userIDs[1], function(err, user){ assert.equal(user, null); if(endAt == k) { done(); } }); }); }); }); }); });
'use strict'; exports.keys = '123456'; exports.nohm = { };
'use strict'; const Cashy = require('../../index.js'); const Table = require('../lib/table.js'); const format = require('../lib/format.js'); // Output table const out = new Table(process.stdout); module.exports = (program) => program .command('balance') .option('-d, --date <date>', 'balances at this date') .option('--csv', 'output comma-separated account list') .description('list all accounts including their balances') .action(balance); function balance (opts) { const filter = {}; if (typeof opts.date === 'string') { filter.date = (opts.date === 'now') ? new Date() : new Date(opts.date); } const cashy = Cashy({ create: false, file: opts.parent.file, invert: opts.parent.invert }); cashy.getAccounts(filter).then((accounts) => { const jobs = []; for (let a of accounts) jobs.push(a.balance(filter)); return Promise.all(jobs).then((balances) => [accounts, balances]); }).then((args) => { const accounts = args[0]; const balances = args[1]; if (opts.csv) { for (let a in accounts) { console.log(`${accounts[a].id},${balances[a]}`); } } else { // Heading out.write('Account', { pos: 1 }); out.write('Balance', { pos: -1, align: 'right' }); out.nl(); out.line('blackBright'); // Body for (let a in accounts) { const path = accounts[a].id.split('/'); const pos = 1 + 2 * (path.length - 1); const caption = path.pop(); out.write(caption, { pos: pos }); out.write(format(balances[a], cashy.accuracy), { pos: -1, align: 'right', color: (accounts[a].dateClosed) ? 'blackBright' : (balances[a] >= 0) ? 'green' : 'red' }); out.nl(); } } }).catch((e) => { console.error(e.message); process.exit(1); }); }
export * from './links/state'; import './settings';
export default { version: '1.0.44', apiUrl: 'wss://ws.binaryws.com/websockets/v3', brand: 'Binary', logo: '/img/binary-symbol-logo.svg', affiliateToken: '', colors: { brandColor: '#123123', }, };
define("ace/mode/xml_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; this.$rules = { start: [ { token: "string.cdata.xml", regex: "<\\!\\[CDATA\\[", next: "cdata" }, { token: ["punctuation.instruction.xml", "keyword.instruction.xml"], regex: "(<\\?)(" + tagRegex + ")", next: "processing_instruction" }, { token: "comment.start.xml", regex: "<\\!--", next: "comment" }, { token: ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex: "(<\\!)(DOCTYPE)(?=[\\s])", next: "doctype", caseInsensitive: true }, { include: "tag" }, { token: "text.end-tag-open.xml", regex: "</" }, { token: "text.tag-open.xml", regex: "<" }, { include: "reference" }, { defaultToken: "text.xml" } ], processing_instruction: [{ token: "entity.other.attribute-name.decl-attribute-name.xml", regex: tagRegex }, { token: "keyword.operator.decl-attribute-equals.xml", regex: "=" }, { include: "whitespace" }, { include: "string" }, { token: "punctuation.xml-decl.xml", regex: "\\?>", next: "start" }], doctype: [ { include: "whitespace" }, { include: "string" }, { token: "xml-pe.doctype.xml", regex: ">", next: "start" }, { token: "xml-pe.xml", regex: "[-_a-zA-Z0-9:]+" }, { token: "punctuation.int-subset", regex: "\\[", push: "int_subset" } ], int_subset: [{ token: "text.xml", regex: "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token: ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex: "(<\\!)(" + tagRegex + ")", push: [{ token: "text", regex: "\\s+" }, { token: "punctuation.markup-decl.xml", regex: ">", next: "pop" }, { include: "string" }] }], cdata: [ { token: "string.cdata.xml", regex: "\\]\\]>", next: "start" }, { token: "text.xml", regex: "\\s+" }, { token: "text.xml", regex: "(?:[^\\]]|\\](?!\\]>))+" } ], comment: [ { token: "comment.end.xml", regex: "-->", next: "start" }, { defaultToken: "comment.xml" } ], reference: [{ token: "constant.language.escape.reference.xml", regex: "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference: [{ token: "constant.language.escape.reference.attribute-value.xml", regex: "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag: [{ token: ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex: "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ { include: "attributes" }, { token: "meta.tag.punctuation.tag-close.xml", regex: "/?>", next: "start" } ] }], tag_whitespace: [ { token: "text.tag-whitespace.xml", regex: "\\s+" } ], whitespace: [ { token: "text.whitespace.xml", regex: "\\s+" } ], string: [{ token: "string.xml", regex: "'", push: [ { token: "string.xml", regex: "'", next: "pop" }, { defaultToken: "string.xml" } ] }, { token: "string.xml", regex: '"', push: [ { token: "string.xml", regex: '"', next: "pop" }, { defaultToken: "string.xml" } ] }], attributes: [{ token: "entity.other.attribute-name.xml", regex: tagRegex }, { token: "keyword.operator.attribute-equals.xml", regex: "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token: "string.attribute-value.xml", regex: "'", push: [ { token: "string.attribute-value.xml", regex: "'", next: "pop" }, { include: "attr_reference" }, { defaultToken: "string.attribute-value.xml" } ] }, { token: "string.attribute-value.xml", regex: '"', push: [ { token: "string.attribute-value.xml", regex: '"', next: "pop" }, { include: "attr_reference" }, { defaultToken: "string.attribute-value.xml" } ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag) { this.$rules.tag.unshift({ token: ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex: "(<)(" + tag + "(?=\\s|>|$))", next: [ { include: "attributes" }, { token: "meta.tag.punctuation.tag-close.xml", regex: "/?>", next: prefix + "start" } ] }); this.$rules[tag + "-end"] = [ { include: "attributes" }, { token: "meta.tag.punctuation.tag-close.xml", regex: "/?>", next: "start", onMatch: function(value, currentState, stack) { stack.splice(0); return this.token; } } ]; this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex: "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex: "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex: "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); define("ace/mode/behaviour/xml", ["require", "exports", "module", "ace/lib/oop", "ace/mode/behaviour", "ace/token_iterator", "ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token && token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function() { this.add("string_dquotes", "insertion", function(state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function(state, action, editor, session, text) { if (text == '>') { var position = editor.getSelectionRange().start; var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var tokenEndColumn = iterator.getCurrentTokenColumn() + token.value.length; if (position.column < tokenEndColumn) return; if (position.column == tokenEndColumn) { var nextToken = iterator.stepForward(); if (nextToken && is(nextToken, "attribute-value")) return; iterator.stepBackward(); } } if (/^\s*>/.test(session.getLine(position.row).slice(position.column))) return; while (!is(token, "tag-name")) { token = iterator.stepBackward(); if (token.value == "<") { token = iterator.stepForward(); break; } } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function(state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column + 1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); define("ace/mode/folding/xml", ["require", "exports", "module", "ace/lib/oop", "ace/lib/lang", "ace/range", "ace/mode/folding/fold_mode", "ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; this.optionalEndTags = oop.mixin({}, this.voidElements); if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags); }; oop.inherits(FoldMode, BaseFoldMode); var Tag = function() { this.tagName = ""; this.closing = false; this.selfClosing = false; this.start = { row: 0, column: 0 }; this.end = { row: 0, column: 0 }; }; function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (!tag) return this.getCommentFoldWidget(session, row); if (tag.closing || (!tag.tagName && tag.selfClosing)) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) return ""; if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) return ""; return "start"; }; this.getCommentFoldWidget = function(session, row) { if (/comment/.test(session.getState(row)) && /<!-/.test(session.getLine(row))) return "start"; return ""; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var tag = new Tag(); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (is(token, "tag-open")) { tag.end.column = tag.start.column + token.value.length; tag.closing = is(token, "end-tag-open"); token = tokens[++i]; if (!token) return null; tag.tagName = token.value; tag.end.column += token.value.length; for (i++; i < tokens.length; i++) { token = tokens[i]; tag.end.column += token.value.length; if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; break; } } return tag; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; return tag; } tag.start.column += token.value.length; } return null; }; this._findEndTagInLine = function(session, row, tagName, startColumn) { var tokens = session.getTokens(row); var column = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; column += token.value.length; if (column < startColumn) continue; if (is(token, "end-tag-open")) { token = tokens[i + 1]; if (token && token.value == tagName) return true; } } return false; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; iterator.stepForward(); return tag; } } while (token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); iterator.stepBackward(); return tag; } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; } } while (token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length - 1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag) { return this.getCommentFoldWidget(session, row) && session.getCommentFoldRange(row, session.getLine(row).length); } var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.start.column); var start = { row: row, column: firstTag.start.column + firstTag.tagName.length + 2 }; if (firstTag.start.row == firstTag.end.row) start.column = firstTag.end.column; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag); } } } else { var iterator = new TokenIterator(session, row, firstTag.end.column); var end = { row: row, column: firstTag.start.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) tag.start.column = tag.end.column; return Range.fromPoints(tag.start, end); } } else { stack.push(tag); } } } }; }).call(FoldMode.prototype); }); define("ace/mode/xml", ["require", "exports", "module", "ace/lib/oop", "ace/lib/lang", "ace/mode/text", "ace/mode/xml_highlight_rules", "ace/mode/behaviour/xml", "ace/mode/folding/xml", "ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var XmlFoldMode = require("./folding/xml").FoldMode; var WorkerClient = require("../worker/worker_client").WorkerClient; var Mode = function() { this.HighlightRules = XmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.foldingRules = new XmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.voidElements = lang.arrayToMap([]); this.blockComment = { start: "<!--", end: "-->" }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/xml_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/xml"; }).call(Mode.prototype); exports.Mode = Mode; }); (function() { window.require(["ace/mode/xml"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
var passport = require('passport') , LocalStrategy = require('passport-local').Strategy; passport.use(new LocalStrategy( function(username, password, done) { User.findOne({ username: username }, function(err, user) { if (err) { return done(err); } if (!user) { return done(null, false, { message: 'Incorrect username.' }); } if (!user.validPassword(password)) { return done(null, false, { message: 'Incorrect password.' }); } return done(null, user); }); } ));
/* * Command to inline push ( Push to channel remotely) */ var inlinePushPassword = Ape.config("inlinepush.conf", "password"); var inlinePushAllowedIps = Ape.config("inlinepush.conf", "ips"); Ape.registerCmd("inlinepush", false, function(params, info) { if( inlinePushAllowedIps !== "" && inlinePushAllowedIps.indexOf(info.ip) < 0 ) return ["402", "IP_BANNED"]; if (params.password === inlinePushPassword) { var chan = Ape.getChannelByName(params.channel); if (!chan) { return ["401", "UNKNOWN_CHANNEL"]; } //Make data optional if (!params.data) { params.data = Array(); } chan.sendEvent(params.raw, params.data); return {"name":"pushed","data":{"value":"ok"}}; } else { return ["400", "BAD_PASSWORD"]; } });
var mentor = mentor || {}; // Single Droplet View mentor.DropletView = Backbone.View.extend({ tagName: 'div', // Re–render the item render: function() { var templateSource = $('#droplet-template').html(); var template = Handlebars.compile(templateSource); var compiled = template(this.model.toJSON()); this.$el.html(compiled); return this; }, });
import Ember from 'ember'; import {test, moduleForComponent} from 'ember-qunit'; const {run} = Ember; moduleForComponent('gh-find-in-webview', 'Unit | Component | gh find in webview', { unit: true, // specify the other units that are required for this test needs: ['service:window-menu', 'util:find-visible-webview'] } ); test('it renders', function(assert) { // creates the component instance const component = this.subject(); assert.equal(component._state, 'preRender'); // renders the component on the page this.render(); assert.equal(component._state, 'inDOM'); }); test('handleFind() toggles the find ui', function(assert) { const component = this.subject({isActive: false}); run(() => { this.render(); component.handleFind(); assert.ok(component.get('isActive')); }); }); test('handleFind() stops an active search if a webview is found', function(assert) { const component = this.subject({isActive: true}); const docQuerySelector = document.querySelectorAll; document.querySelectorAll = function(selector) { if (selector === 'webview') { return [{ stopFindInPage: (action) => assert.equal(action, 'clearSelection') }]; } else { return docQuerySelector(selector); } }; run(() => { this.render(); component.handleFind(); document.querySelectorAll = docQuerySelector; }); }); test('_insertMenuItem() injects an item', function(assert) { assert.expect(6); const component = this.subject({ windowMenu: new Object({ injectMenuItem(params) { assert.equal(params.menuName, 'Edit'); assert.equal(params.name, 'find-in-webview'); assert.equal(params.label, '&Find'); assert.equal(params.accelerator, 'CmdOrCtrl+F'); assert.equal(params.addSeperator, true); assert.equal(params.position, 3); } }) }); run(() => { this.render(); }); });
module.exports = { build_dll: function() { return new Promise(function (resolve, reject) { console.log("_postinstall > NPM: DLL build started. Please wait.."); require('child_process').execSync('npm run build:dll', {stdio:[0,1,2]}); console.log("_postinstall > NPM: DLL build completed"); resolve(); }); }, compile_aot: function() { return new Promise(function (resolve, reject) { console.log("_postinstall > NPM: AOT compilation has started. Please wait.."); require('child_process').execSync('npm run compile', {stdio:[0,1,2]}); console.log("_postinstall > NPM: AOT compilation completed"); resolve(); }); }, build_web: function() { return new Promise(function (resolve, reject) { console.log("_postinstall > NPM: Building web (heroku) distro. Please wait.."); require('child_process').execSync('npm run build:aot -- heroku', {stdio:[0,1,2]}); console.log("_postinstall > NPM: Web distro build completed. Ready to serve"); resolve(); }); }, build_ionic_resources: function() { return new Promise(function (resolve, reject) { console.log("_postinstall > NPM: Building Ionic resources. Please wait.."); require('child_process').execSync('npm run utils:ionic:resources', {stdio:[0,1,2]}); console.log("_postinstall > NPM: Ionic resources built."); resolve(); }); }, set_timezone: function() { return new Promise(function (resolve, reject) { console.log("_postinstall > NPM: Set timezone to UTC"); exec(`export TZ=UTC`, (error, stdout, stderr) => { if (error) reject(error); console.log(`_postinstall > NPM: Timezone has been set to UTC`); resolve(); }); }); }, };
module.exports = function(db) { var viewers = db.collection('viewers'); return { updateViewers: function(req, res, next) { var viewerList = req.body.viewers; var savedViewers = []; var i = 0; function saveViewer(viewerName) { viewers.findOne({name: viewerName}, function(e, record){ if (e) return next(e); if (record) { record.points++; var _id = record._id; delete record._id; viewers.updateById(_id, record, function(e, result){ if (e) return next(e); saveCallback(viewerName); }); } else { viewers.insert({name: viewerName, points: 1}, function(e, result){ if (e) return next(e); saveCallback(viewerName); }); } }); } function saveCallback(viewerName) { savedViewers.push(viewerName); i++; if (i >= viewerList.length) { res.send({message: 'saved ' + savedViewers.length + ' viewers', viewers: savedViewers}); } else { saveViewer(viewerList[i]); } } saveViewer(viewerList[i]); }, getViewerPoints: function(req, res, next) { viewers.findOne({name: req.params.name}, function(e, viewer){ if (e) return next(e); if (viewer) { res.send(viewer); } else { res.send({ name: req.params.name, points: 0 }); } }); } } }
import React from 'react'; import { Container, Content, Button, Text, List, ListItem, SwipeRow, Icon, Fab } from 'native-base'; import { FlatList } from 'react-native'; import I18n from 'yasav/locales/i18n' import { GenericHeader } from 'yasav/src/viewElements/shared/Header'; import Style from '../styles/style.js'; import StyleList from 'yasav/src/styles/List' import SearchContainer from 'yasav/src/components/search/screens/Search/containers/SearchContainer' import { SearchType } from 'yasav/src/const'; import ListView from 'yasav/src/viewElements/shared/listView/ListView' import Colors from 'yasav/src/styles/Colors'; export default class ActivityListView extends React.Component { constructor(props) { super(props); this.navigateToActivityDisplayScreen = this.navigateToActivityDisplayScreen.bind(this); this.navigateToActivityAddMeeting = this.navigateToActivityAddMeeting.bind(this); this.navigateToActivityAddContent = this.navigateToActivityAddContent.bind(this); this.navigateToActivityAddEvent = this.navigateToActivityAddEvent.bind(this); this.state = { active: false }; } navigateToActivityDisplayScreen(item) { this.props.navigateToActivityDisplayScreen(item); } navigateToActivityAddMeeting() { this.setState({ active: !this.state.active }); this.props.navigateToActivityAddMeeting(); } navigateToActivityAddEvent() { this.setState({ active: !this.state.active }); this.props.navigateToActivityAddEvent(); } navigateToActivityAddContent() { this.setState({ active: !this.state.active }); this.props.navigateToActivityAddContent(); } // BUG: need to put the style inline for the 3 buttons of the FAB. The Style.addMeetingButton doesn't work for no reason render() { return ( <Container style={StyleList.container}> <SearchContainer requestType={SearchType.ACTIVITY} modifySearchActivity={this.props.modifySearchActivity} /> <ListView displayList={this.props.displayActivityList} navigateToDisplayScreen={this.navigateToActivityDisplayScreen} /> <Fab active={this.state.active} direction="up" style={Style.addButton} position="bottomRight" onPress={() => this.setState({ active: !this.state.active })}> <Icon name="add"/> <Button onPress={this.navigateToActivityAddMeeting} style={{ backgroundColor: Colors.meet }} > <Icon name="person" /> </Button> <Button onPress={this.navigateToActivityAddEvent} style={{ backgroundColor: Colors.event }} > <Icon name="calendar" /> </Button> <Button onPress={this.navigateToActivityAddContent} style={{ backgroundColor: Colors.content }} > <Icon name="book" /> </Button> </Fab> </Container> ); } }
var multipleChoice = require('./multiple_choice/module'); var numeric = require('./numeric/module'); var freeResponse = require('./free_response/module'); var imageUpload = require('./image_upload/module'); module.exports = angular.module('app.components.quiz', [ multipleChoice.name, numeric.name, freeResponse.name, imageUpload.name ])
(function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports"], factory); } })(function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // export default IPrincipal; var IPrincipal = /** @class */ (function () { function IPrincipal() { } return IPrincipal; }()); exports.IPrincipal = IPrincipal; }); //# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9JZGVudGl0aWVzL0lQcmluY2lwYWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7SUFFQSw2QkFBNkI7SUFFN0I7UUFBQTtRQU1BLENBQUM7UUFBRCxpQkFBQztJQUFELENBTkEsQUFNQyxJQUFBO0lBTlksZ0NBQVUiLCJmaWxlIjoic3JjL0lkZW50aXRpZXMvSVByaW5jaXBhbC5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7SUlkZW50aXR5fSBmcm9tICcuL0lJZGVudGl0eSc7XHJcblxyXG4vLyBleHBvcnQgZGVmYXVsdCBJUHJpbmNpcGFsO1xyXG5cclxuZXhwb3J0IGNsYXNzIElQcmluY2lwYWwge1xyXG5cclxuICBJZGVudGl0eTogSUlkZW50aXR5O1xyXG5cclxuICBJc0F1dGhlbnRpY2F0ZWQ6IGJvb2xlYW47XHJcbiAgQXV0aGVudGljYXRpb25UeXBlOiBzdHJpbmc7XHJcbn1cclxuIl19
const { OPCUAClient, ClientSubscription, AttributeIds, ClientMonitoredItemGroup, StatusCodes, ClientSidePublishEngine, Subscription } = require("node-opcua"); const { perform_operation_on_session_async } = require("../../test_helpers/perform_operation_on_client_session"); const sinon = require("sinon"); const itemsToMonitor1 = [ { nodeId: "ns=2;s=Static_Scalar_Boolean", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_Byte", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_ByteString", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_DateTime", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_SByte", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_Int16", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_UInt16", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_Int32", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_UInt32", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_Int64", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_UInt64", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_Float", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_Double", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_Duration", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_Guid", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_LocaleId", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_LocalizedText", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_NodeId", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_Number", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_UInteger", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_Integer", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_UtcTime", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_XmlElement", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_ImageBMP", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_ImageGIF", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Scalar_ImagePNG", attributeId: AttributeIds.Value }, ]; const itemsToMonitor2 = [ { nodeId: "ns=2;s=Static_Array_Boolean", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_Byte", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_ByteString", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_DateTime", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_SByte", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_Int16", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_UInt16", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_Int32", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_UInt32", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_Int64", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_UInt64", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_Float", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_Double", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_Duration", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_Guid", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_LocaleId", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_LocalizedText", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_NodeId", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_Number", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_UInteger", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_Integer", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_UtcTime", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_XmlElement", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_ImageBMP", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_ImageGIF", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Static_Array_ImagePNG", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=ByteDataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=DoubleDataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Int16DataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Int32DataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Int64DataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=UInt16DataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=UInt32DataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=UInt64DataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=SByteDataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=StringDataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=DateTimeDataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=FloatDataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=DoubleArrayAnalogDataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Int16ArrayAnalogDataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=UInt16ArrayAnalogDataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=UInt16ArrayAnalogDataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=UInt32ArrayAnalogDataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=FloatArrayAnalogDataItem", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=MultiStateDiscrete001", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=MultiStateDiscrete002", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=MultiStateDiscrete003", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=MultiStateDiscrete004", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=MultiStateDiscrete005", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=TwoStateDiscrete001", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=TwoStateDiscrete002", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=TwoStateDiscrete003", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=TwoStateDiscrete004", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=TwoStateDiscrete005", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=ByteMultiStateValueDiscrete", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=SByteMultiStateValueDiscrete", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Int16MultiStateValueDiscrete", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Int32MultiStateValueDiscrete", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=Int64MultiStateValueDiscrete", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=UInt16MultiStateValueDiscrete", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=UInt32MultiStateValueDiscrete", attributeId: AttributeIds.Value }, { nodeId: "ns=2;s=UInt64MultiStateValueDiscrete", attributeId: AttributeIds.Value }, ]; const describe = require("node-opcua-leak-detector").describeWithLeakDetector; module.exports = function(test) { describe("Testing ctt 010 - Modify the samplingInterval of multiple nodes, where the first half are set to 1000 msec and the latter half 3000 msec", function() { let old_publishRequestCountInPipeline = 0; beforeEach(() => { old_publishRequestCountInPipeline = ClientSidePublishEngine.publishRequestCountInPipeline; ClientSidePublishEngine.publishRequestCountInPipeline = 1; }); afterEach(() => { ClientSidePublishEngine.publishRequestCountInPipeline = old_publishRequestCountInPipeline; }); it("should create a large number of monitored item and alter samplingInterval for half of them", async () => { const client = OPCUAClient.create(); const endpointUrl = test.endpointUrl; await client.withSessionAsync(endpointUrl, async (session) => { session.getPublishEngine().suspend(true); const subscription = ClientSubscription.create(session, { requestedPublishingInterval: 200, requestedLifetimeCount: 10 * 60 * 1000, requestedMaxKeepAliveCount: 60, maxNotificationsPerPublish: 0, publishingEnabled: true, priority: 6 }); const subscription_raw_notification_event = sinon.spy(); subscription.on("raw_notification", subscription_raw_notification_event); subscription.on("received_notifications", () => { console.log("..."); }); const options = { samplingInterval: 10, discardOldest: true, queueSize: 1 }; const itemsToMonitorX = [].concat(itemsToMonitor1, itemsToMonitor1, itemsToMonitor1, itemsToMonitor1, itemsToMonitor1, itemsToMonitor1, itemsToMonitor1, itemsToMonitor1); const itemsToMonitorY = [].concat(itemsToMonitorX, itemsToMonitorX, itemsToMonitorX, itemsToMonitorX, itemsToMonitorX, itemsToMonitorX, itemsToMonitorX, itemsToMonitorX); const itemsToMonitor = [].concat(itemsToMonitorY, itemsToMonitorY, itemsToMonitorY, itemsToMonitorY); const monitoredItemGroup = ClientMonitoredItemGroup.create(subscription, itemsToMonitor, options); await new Promise((resolve, reject) => { // subscription.on("item_added",function(monitoredItem){ monitoredItemGroup.on("initialized", function() { const allGood = monitoredItemGroup.monitoredItems.filter((item, index) => item.statusCode !== StatusCodes.Good); if (allGood.length > 0) { console.log(" Initialized Failed!", monitoredItemGroup.monitoredItems.map((item, index) => itemsToMonitor[index].nodeId.toString().padEnd(20) + " " + item.statusCode.toString()).join("\n")); return reject(new Error("Initialization failed , some nodeId are ")); } monitoredItemGroup.monitoredItems.length.should.eql(itemsToMonitor.length); resolve(); }); }); console.log("Sending Publish request"); session.getPublishEngine().internalSendPublishRequest(); // session.getPublishEngine().suspend(true); async function wait_notification() { if (subscription_raw_notification_event.callCount > 0) { return; } await new Promise((resolve) => setTimeout(resolve, 3000)); await wait_notification(); } await wait_notification(); function dumpNotificationResult() { console.log("notification received = ", subscription_raw_notification_event.callCount); for (const c of subscription_raw_notification_event.getCalls()) { // console.log("Initial l=", c.args[0].notificationData.length.toString()); for (const n of c.args[0].notificationData) { console.log(" monitoredItem changes = ", n.monitoredItems.length); } } } dumpNotificationResult(); subscription_raw_notification_event .getCall(0) .args[0].notificationData[0].monitoredItems.length.should.eql( Math.min(itemsToMonitor.length, Subscription.maxNotificationPerPublishHighLimit) ); subscription_raw_notification_event.resetHistory(); subscription_raw_notification_event.callCount.should.eql(0); // -------------------------------------------------------------------------------------------------- const itemsToModify = itemsToMonitor.map((item, index) => { return { monitoredItemId: monitoredItemGroup.monitoredItems[index].monitoredItemId, requestedParameters: { samplingInterval: (index % 2) ? 3000 : 1000 } } }) await session.modifyMonitoredItems({ subscriptionId: subscription.subscriptionId, itemsToModify }); session.getPublishEngine().internalSendPublishRequest(); session.getPublishEngine().internalSendPublishRequest(); session.getPublishEngine().internalSendPublishRequest(); await new Promise((resolve) => setTimeout(resolve, 6000)); dumpNotificationResult(); await new Promise(resolve => { monitoredItemGroup.terminate(function() { console.log(" terminated !"); resolve(); }); }); await subscription.terminate(); }); }); }); }
import React from 'react' import { connect } from 'react-redux' import { addTodo } from '../../actions' let AddTodo = ({ dispatch }) => { let input; return ( <div> <form onSubmit={ e => { e.preventDefault(); if (!input.value.trim()) { return; } dispatch(addTodo(input.value)); input.value = ''; }}> <input ref={ node => { input = node }} /> <button type='submit'> Add todo </button> </form> </div> ) } AddTodo = connect()(AddTodo) export default AddTodo
// Karma configuration // Generated on Fri Dec 05 2014 16:49:29 GMT-0500 (EST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jspm', 'jasmine'], jspm: { // Edit this to your needs loadFiles: [ 'src/**/*.js', 'test/data/**/*.js', 'test/unit/**/*.js' ], paths: { '*': '*.js' } }, // list of files / patterns to load in the browser files: [], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'test/**/*.js': ['babel'], 'src/**/*.js': ['babel'] }, 'babelPreprocessor': { options: { sourceMap: 'inline', modules: 'system', moduleIds: false, optional: [ "es7.decorators", "es7.classProperties" ] } }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['spec'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
google.maps.__gjsload__('stats', function(_){var ZZ=function(a,b,c){var d=[];_.Mb(a,function(a,c){d.push(c+b+a)});return d.join(c)},$Z=function(a,b,c,d){var e={};e.host=window.document.location&&window.document.location.host||window.location.host;e.v=a;e.r=Math.round(1/b);c&&(e.client=c);d&&(e.key=d);return e},a_=function(a){var b={};_.Mb(a,function(a,d){b[(0,window.encodeURIComponent)(d)]=(0,window.encodeURIComponent)(a).replace(/%7C/g,"|")});return ZZ(b,":",",")},c_=function(a,b,c,d){var e;e=_.M(_.Q,23,500);var f;f=_.M(_.Q,22,2);this.C=a; this.D=b;this.F=e;this.l=f;this.B=c;this.m=d;this.f=new _.Xj;this.b=0;this.j=_.Qa();b_(this)},b_=function(a){window.setTimeout(function(){d_(a);b_(a)},Math.min(a.F*Math.pow(a.l,a.b),2147483647))},e_=function(a,b,c){a.f.set(b,c)},d_=function(a){var b=$Z(a.D,a.B,a.m,void 0);b.t=a.b+"-"+(_.Qa()-a.j);a.f.forEach(function(a,d){a=a();0<a&&(b[d]=Number(a.toFixed(2))+(_.xm()?"-if":""))});a.C.b({ev:"api_snap"},b);++a.b},f_=function(a,b,c,d,e){this.m=a;this.C=b;this.l=c;this.f=d;this.j=e;this.b=new _.Xj;this.B= _.Qa()},g_=function(a,b,c){this.l=b;this.f=a+"/maps/gen_204";this.j=c},h_=function(){this.b=new _.Xj},i_=function(a){var b=0,c=0;a.b.forEach(function(a){b+=a.jo;c+=a.In});return c?b/c:0},j_=function(a,b,c,d,e){this.B=a;this.C=b;this.m=c;this.j=d;this.l=e;this.f={};this.b=[]},k_=function(a,b,c,d){this.j=a;_.y.bind(this.j,"set_at",this,this.l);_.y.bind(this.j,"insert_at",this,this.l);this.B=b;this.C=c;this.m=d;this.f=0;this.b={};this.l()},l_=function(){this.j=_.N(_.Q,6);this.b=new g_(_.xg[35]?_.N(_.Qf(_.Q), 11):_.ew,_.fj,window.document);new k_(_.Vi,(0,_.p)(this.b.b,this.b),_.Vf,!!this.j);var a=_.N(new _.Cf(_.Q.data[3]),1);this.C=a.split(".")[1]||a;this.D={};this.B={};this.m={};this.F={};this.G=_.M(_.Q,0,1);_.ej&&(this.l=new c_(this.b,this.C,this.G,this.j))}; f_.prototype.D=function(a){var b=void 0,b=_.m(b)?b:1;this.b.isEmpty()&&window.setTimeout((0,_.p)(function(){var a=$Z(this.C,this.l,this.f,this.j);a.t=_.Qa()-this.B;var b=this.b;_.Yj(b);for(var e={},f=0;f<b.b.length;f++){var g=b.b[f];e[g]=b.H[g]}_.mz(a,e);this.b.clear();this.m.b({ev:"api_maprft"},a)},this),500);b=this.b.get(a,0)+b;this.b.set(a,b)}; g_.prototype.b=function(a,b){b=b||{};var c=_.Kk().toString(36);b.src="apiv3";b.token=this.l;b.ts=c.substr(c.length-6);a.cad=a_(b);a=ZZ(a,"=","&");a=this.f+"?target=api&"+a;this.j.createElement("img").src=a;(b=_.Ub.__gm_captureCSI)&&b(a)};h_.prototype.f=function(a,b,c){this.b.set(_.Fb(a),{jo:b,In:c})};j_.prototype.D=function(a){this.f[a]||(this.f[a]=!0,this.b.push(a),2>this.b.length&&_.zz(this,this.F,500))}; j_.prototype.F=function(){for(var a=$Z(this.C,this.m,this.j,this.l),b=0,c;c=this.b[b];++b)a[c]="1";a.hybrid=+_.$l();this.b.length=0;this.B.b({ev:"api_mapft"},a)};k_.prototype.l=function(){for(var a;a=this.j.removeAt(0);){var b=a.nn;a=a.timestamp-this.C;++this.f;this.b[b]||(this.b[b]=0);++this.b[b];if(20<=this.f&&!(this.f%5)){var c={};c.s=b;c.sr=this.b[b];c.tr=this.f;c.te=a;c.hc=this.m?"1":"0";this.B({ev:"api_services"},c)}}};l_.prototype.S=function(a){a=_.Fb(a);this.D[a]||(this.D[a]=new j_(this.b,this.C,this.G,this.j));return this.D[a]};l_.prototype.O=function(a){a=_.Fb(a);this.B[a]||(this.B[a]=new f_(this.b,this.C,1,this.j));return this.B[a]};l_.prototype.f=function(a){if(this.l){this.m[a]||(this.m[a]=new _.KA,e_(this.l,a,function(){return b.nb()}));var b=this.m[a];return b}};l_.prototype.ea=function(a){if(this.l){this.F[a]||(this.F[a]=new h_,e_(this.l,a,function(){return i_(b)}));var b=this.F[a];return b}};var m_=new l_;_.Wc("stats",m_);});
exports.ansibleVariable = require('./ansibleVariable'); exports.folderize = require('./folderize');
'use strict'; var React = require('react'); var SvgIcon = require('../../svg-icon'); var ActionShoppingCart = React.createClass({ displayName: 'ActionShoppingCart', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: "M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z" }) ); } }); module.exports = ActionShoppingCart;
exports = module.exports = function(app, models) { var _ = require('underscore'); var add = function(req, res) { var doc = req.body; var grant = req.body.grant; var keys = _.keys(grant); var grant_new = {}; _.each(keys,function(key){ var feature = grant[key]; if(feature.getOne || feature.getMore || feature.add || feature.remove || feature.update){ grant_new[key] = grant[key]; } }); doc.grant = grant_new; doc.creator = { id: req.session.accountId, }; models.PlatformRole.create(doc,function(err) { if (err) return res.send(err); res.send({}); }); }; var remove = function(req,res){ var id = req.params.id; models.PlatformRole.findByIdAndRemove(id,function(err,doc){ if(err) return res.send(err); res.send(doc); }); }; var update = function(req, res) { var id = req.params.id; var set = req.body; var grant = req.body.grant; var keys = _.keys(grant); var grant_new = {}; _.each(keys,function(key){ var feature = grant[key]; if(feature.getOne || feature.getMore || feature.add || feature.remove || feature.update){ grant_new[key] = grant[key]; } }); set.grant = grant_new; models.PlatformRole.findByIdAndUpdate(id, { $set: set }, { 'upsert': false, 'new': true, }, function(err, doc) { if (err) return res.send(err); res.send(doc); } ); }; var getOne = function(req, res) { var id = req.params.id; models.PlatformRole .findById(id) .exec(function(err, doc) { if (err) return res.send(err); res.send(doc); }); }; var getMore = function(req, res) { var per = 20; var page = (!req.query.page || req.query.page < 0) ? 0 : req.query.page; page = (!page || page < 0) ? 0 : page; models.PlatformRole .find({}) .skip(per * page) .limit(per) .exec(function(err, docs) { if (err) return res.send(err); res.send(docs); }); }; /** * router outline */ /** * add protect/roles * type: * */ app.post('/protect/roles', app.grant, add); /** * update protect/roles * type: * */ app.put('/protect/roles/:id', app.grant, update); /** * delete protect/roles * type: * */ app.delete('/protect/roles/:id', app.grant, remove); /** * get protect/roles */ app.get('/protect/roles/:id', app.grant, getOne); /** * get protect/roles * type: */ app.get('/protect/roles', app.grant, getMore); };
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define({widgetLabel:"\u0102_Attachments____________\u0219",attachmentDetails:"\u0102_Attachment details___________________\u0219",add:"\u0102_Add_______\u0219",update:"\u0102_Update_____________\u0219",cancel:"\u0102_Cancel_____________\u0219",noTitle:"\u0102_Untitled_________________\u0219","delete":"\u0102_Delete_____________\u0219",selectFile:"\u0102_Select file____________\u0219",changeFile:"\u0102_Change file____________\u0219",noAttachments:"\u0102_No attachments_______________\u0219",addErrorMessage:"\u0102_Error adding the attachment. Please try again________________________\u0219.", deleteErrorMessage:"\u0102_Error deleting the attachment. Please try again_________________________\u0219.",updateErrorMessage:"\u0102_Error updating the attachment. Please try again_________________________\u0219."});