code
stringlengths
2
1.05M
module.exports = function(grunt) { // required require('load-grunt-tasks')(grunt); require('time-grunt')(grunt); // grunt plugins grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-nodemon'); // Project configuration. grunt.initConfig({ //------------- concurrent: { options:{ limit: 10, logConcurrentOutput: true }, watch: [ 'shell:start', 'watch:reloads', 'nodemon:dev' ] }, //------------- //------------- watch: { //------------------ reloads: { files: [ 'views/*.*', 'public/app/**/*.*', ], options: { livereload: 35729, // https://github.com/gruntjs/grunt-contrib-watch#optionslivereload spawn: false }, }, //------------------ }, //------------- //-------------------------- /* WATCHES FOR CHANGES ON APP.JS FILE */ nodemon: { dev: { script: 'app.js' }, }, //-------------------------- //------------- shell: { options: { stderr: false, maxBuffer: Infinity }, start: { command: 'npm start' } } //------------- }); // ***** GRUNT COMMANDS *******// //*****************************// // ------------------- grunt.registerTask('default', ['concurrent:watch']); // ------------------- //*****************************// };
/** * Library tests focused on the processLimit option. * * Copyright (c) 2013 - 2021, Alex Grant, LocalNerve, contributors */ /* global it */ var assert = require("assert"); var rimraf = require("rimraf").sync; var utils = require("./utils"); var optHelp = require("../../helpers/options"); var ss = require("../../../lib/html-snapshots"); var robotsTests = require("./robots"); // missing destructuring, will write postcard... var timeout = utils.timeout; var outputDir = utils.outputDir; var cleanup = utils.cleanup; var killSpawnedProcesses = utils.killSpawnedProcesses; var countSpawnedProcesses = utils.countSpawnedProcesses; var unexpectedError = utils.unexpectedError; var multiError = utils.multiError; var checkActualFiles = utils.checkActualFiles; var urls = robotsTests.urlCount; var inputFile = robotsTests.inputFile; function processLimitTests (options) { var port = options.port; var pollInterval = 50; var phantomCount = 0; var timer; function completeTest (done, processLimit, e, files) { var countError = phantomCount ? new Error(phantomCount + " exceeded processLimit " + processLimit) : undefined; clearInterval(timer); if (files) { checkActualFiles(files).then(function () { cleanup(done, multiError(e, countError)); }); } else { cleanup(done, multiError(e, countError)); } } return function () { it("should limit as expected", function (done) { var processLimit = urls - 1; var complete = completeTest.bind(null, done, processLimit); if (process.platform === "win32") { assert.ok(true, "Skipping posix compliant tests for processLimit"); done(); } else { rimraf(outputDir); killSpawnedProcesses(function (err) { var options = { source: inputFile, hostname: "localhost", port: port, selector: "#dynamic-content", outputDir: outputDir, outputDirClean: true, timeout: timeout, processLimit: processLimit }; if (err) { return done(err); } ss.run(optHelp.decorate(options)) .then(function () { complete(); }) .catch(function (e) { complete(e || unexpectedError, e.notCompleted); }); timer = setInterval(function () { countSpawnedProcesses(function (count) { // console.log("@@@ DEBUG @@@ phantom count: "+count); if (count > processLimit) { phantomCount = count; clearInterval(timer); } }); }, pollInterval); }); } }); it("should limit to just one process", function (done) { var processLimit = 1; var complete = completeTest.bind(null, done, processLimit); if (process.platform === "win32") { assert.ok(true, "Skipping posix compliant tests for processLimit"); done(); } else { rimraf(outputDir); killSpawnedProcesses(function (err) { var options = { source: inputFile, hostname: "localhost", port: port, selector: "#dynamic-content", outputDir: outputDir, outputDirClean: true, timeout: timeout, processLimit: processLimit }; if (err) { return done(err); } ss.run(optHelp.decorate(options)) .then(function () { complete(); }) .catch(function (e) { complete(e || unexpectedError, e.notCompleted); }); timer = setInterval(function () { countSpawnedProcesses(function (count) { // console.log("@@@ DEBUG @@@ phantom count: "+count); if (count > processLimit) { phantomCount = count; clearInterval(timer); } }); }, pollInterval); }); } }); }; } module.exports = { testSuite: processLimitTests, inputFile: inputFile, urlCount: urls };
datab = [{},{"Attribute Name":{"colspan":"1","rowspan":"1","text":"Parametric Map Frame Type Sequence"},"Tag":{"colspan":"1","rowspan":"1","text":"(0040,9092)"},"Type":{"colspan":"1","rowspan":"1","text":"1"},"Attribute Description":{"colspan":"1","rowspan":"1","text":"Identifies the characteristics of this Parametric Map frame. Only a single Item shall be included in this Sequence."}},{"Attribute Name":{"colspan":"1","rowspan":"1","text":">Frame Type"},"Tag":{"colspan":"1","rowspan":"1","text":"(0008,9007)"},"Type":{"colspan":"1","rowspan":"1","text":"1"},"Attribute Description":{"colspan":"1","rowspan":"1","text":"Type of Frame. A multi-valued attribute analogous to Image Type (0008,0008). Enumerated Values and Defined Terms are the same as those for the four values of Image Type (0008,0008), except that the value MIXED is not allowed. See ."}}];
var exiler = require("exiler"); var options = { publicFolder: "src/public", templateFolder: "src/template", route: { index: { ex_data: function (resolve) { resolve({aaa: 1}); } }, nodata: { ex_template: "nodata.ejs" }, pageAction: { ex_data: { pageData: "I'm the page" }, ex_template: "page.ejs" }, paramTest: { ex_param_id: { ex_data: function (resolve, param) { resolve({ id: param.id }); }, ex_template: "id.ejs", ex_param_secondId: { ex_data: function (resolve, param) { resolve({ id: param.id, secondId: param.secondId }); }, ex_template: "id.ejs" } } } } }; exiler.server(options);
// declaration assignment var arr = ["one", "two", "three"]; // direct index assignment var arr2 = new Array(); arr2[0] = "one"; arr2[1] = "two"; arr2[2] = "three"; // object-oriented assignment var arr3 = new Array(); arr3.push("one"); arr3.push("two"); arr3.push("three"); var numOfItems = arr.length; var week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]; var first = week[0]; var last = week[week.length - 1]; // combining arrays var arr4 = [1,2,3]; var arr5 = ["three", "four", "five"] var arr6 = arr4 + arr5; var arr7 = arr4.concat(arr5); // iterating through arrays for (var i = 0; i < week.length; i++) { console.log("<li>" + week[i] + "</li>"); } for (var i in week) { console.log("<li>" + week[i] + "</li>"); } // converting an array into a string var timeArr = [12,10,36]; var timeStr = timeArr.join(":"); // checking whether an array contains an item function message(day) { if (week.indexOf(day) != -1) { console.log("Happy " + day); } } message("Monday"); message("Birthday");
/* * * INSPINIA - Responsive Admin Theme * version 2.6 * */ $(document).ready(function () { // Add body-small class if window less than 768px if ($(this).width() < 769) { $('body').addClass('body-small') } else { $('body').removeClass('body-small') } // MetsiMenu $('#side-menu').metisMenu(); // Collapse ibox function $('.collapse-link').on('click', function () { var ibox = $(this).closest('div.ibox'); var button = $(this).find('i'); var content = ibox.find('div.ibox-content'); content.slideToggle(200); button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down'); ibox.toggleClass('').toggleClass('border-bottom'); setTimeout(function () { ibox.resize(); ibox.find('[id^=map-]').resize(); }, 50); }); // Close ibox function $('.close-link').on('click', function () { var content = $(this).closest('div.ibox'); content.remove(); }); // Fullscreen ibox function $('.fullscreen-link').on('click', function () { var ibox = $(this).closest('div.ibox'); var button = $(this).find('i'); $('body').toggleClass('fullscreen-ibox-mode'); button.toggleClass('fa-expand').toggleClass('fa-compress'); ibox.toggleClass('fullscreen'); setTimeout(function () { $(window).trigger('resize'); }, 100); }); // Close menu in canvas mode $('.close-canvas-menu').on('click', function () { $("body").toggleClass("mini-navbar"); SmoothlyMenu(); }); // Run menu of canvas $('body.canvas-menu .sidebar-collapse').slimScroll({ height: '100%', railOpacity: 0.9 }); // Open close right sidebar $('.right-sidebar-toggle').on('click', function () { $('#right-sidebar').toggleClass('sidebar-open'); }); // Initialize slimscroll for right sidebar $('.sidebar-container').slimScroll({ height: '100%', railOpacity: 0.4, wheelStep: 10 }); // Open close small chat // $('.open-small-chat').on('click', function () { // $(this).children().toggleClass('fa-comments').toggleClass('fa-remove'); // $('.small-chat-box').toggleClass('active'); // }); // Initialize slimscroll for small chat $('.small-chat-box .content').slimScroll({ height: '234px', railOpacity: 0.4 }); // Small todo handler $('.check-link').on('click', function () { var button = $(this).find('i'); var label = $(this).next('span'); button.toggleClass('fa-check-square').toggleClass('fa-square-o'); label.toggleClass('todo-completed'); return false; }); // Append config box / Only for demo purpose // Uncomment on server mode to enable XHR calls //$.get("skin-config.html", function (data) { // if (!$('body').hasClass('no-skin-config')) // $('body').append(data); //}); // Minimalize menu $('.navbar-minimalize').on('click', function () { $("body").toggleClass("mini-navbar"); SmoothlyMenu(); }); // Tooltips demo $('.tooltip-demo').tooltip({ selector: "[data-toggle=tooltip]", container: "body" }); // Full height of sidebar function fix_height() { var heightWithoutNavbar = $("body > #wrapper").height() - 61; $(".sidebard-panel").css("min-height", heightWithoutNavbar + "px"); var navbarHeigh = $('nav.navbar-default').height(); var wrapperHeigh = $('#page-wrapper').height(); if (navbarHeigh > wrapperHeigh) { $('#page-wrapper').css("min-height", navbarHeigh + "px"); } if (navbarHeigh < wrapperHeigh) { $('#page-wrapper').css("min-height", $(window).height() + "px"); } if ($('body').hasClass('fixed-nav')) { if (navbarHeigh > wrapperHeigh) { $('#page-wrapper').css("min-height", navbarHeigh - 60 + "px"); } else { $('#page-wrapper').css("min-height", $(window).height() - 60 + "px"); } } } fix_height(); // Fixed Sidebar $(window).bind("load", function () { if ($("body").hasClass('fixed-sidebar')) { $('.sidebar-collapse').slimScroll({ height: '100%', railOpacity: 0.9 }); } }); // Move right sidebar top after scroll $(window).scroll(function () { if ($(window).scrollTop() > 0 && !$('body').hasClass('fixed-nav')) { $('#right-sidebar').addClass('sidebar-top'); } else { $('#right-sidebar').removeClass('sidebar-top'); } }); $(window).bind("load resize scroll", function () { if (!$("body").hasClass('body-small')) { fix_height(); } }); $("[data-toggle=popover]") .popover(); // Add slimscroll to element $('.full-height-scroll').slimscroll({ height: '100%' }) }); // Minimalize menu when screen is less than 768px $(window).bind("resize", function () { if ($(this).width() < 769) { $('body').addClass('body-small') } else { $('body').removeClass('body-small') } }); // Local Storage functions // Set proper body class and plugins based on user configuration $(document).ready(function () { if (localStorageSupport()) { var collapse = localStorage.getItem("collapse_menu"); var fixedsidebar = localStorage.getItem("fixedsidebar"); var fixednavbar = localStorage.getItem("fixednavbar"); var boxedlayout = localStorage.getItem("boxedlayout"); var fixedfooter = localStorage.getItem("fixedfooter"); var body = $('body'); if (fixedsidebar == 'on') { body.addClass('fixed-sidebar'); $('.sidebar-collapse').slimScroll({ height: '100%', railOpacity: 0.9 }); } if (collapse == 'on') { if (body.hasClass('fixed-sidebar')) { if (!body.hasClass('body-small')) { body.addClass('mini-navbar'); } } else { if (!body.hasClass('body-small')) { body.addClass('mini-navbar'); } } } if (fixednavbar == 'on') { $(".navbar-static-top").removeClass('navbar-static-top').addClass('navbar-fixed-top'); body.addClass('fixed-nav'); } if (boxedlayout == 'on') { body.addClass('boxed-layout'); } if (fixedfooter == 'on') { $(".footer").addClass('fixed'); } } }); // check if browser support HTML5 local storage function localStorageSupport() { return (('localStorage' in window) && window['localStorage'] !== null) } // For demo purpose - animation css script function animationHover(element, animation) { element = $(element); element.hover( function () { element.addClass('animated ' + animation); }, function () { //wait for animation to finish before removing classes window.setTimeout(function () { element.removeClass('animated ' + animation); }, 2000); }); } function SmoothlyMenu() { if (!$('body').hasClass('mini-navbar') || $('body').hasClass('body-small')) { // Hide menu in order to smoothly turn on when maximize menu $('#side-menu').hide(); // For smoothly turn on menu setTimeout( function () { $('#side-menu').fadeIn(400); }, 200); } else if ($('body').hasClass('fixed-sidebar')) { $('#side-menu').hide(); setTimeout( function () { $('#side-menu').fadeIn(400); }, 100); } else { // Remove all inline style from jquery fadeIn function to reset menu state $('#side-menu').removeAttr('style'); } } // Dragable panels function WinMove() { var element = "[class*=col]"; var handle = ".ibox-title"; var connect = "[class*=col]"; $(element).sortable( { handle: handle, connectWith: connect, tolerance: 'pointer', forcePlaceholderSize: true, opacity: 0.8 }) .disableSelection(); }
import assert from 'assert'; export default { cssClass(element, className) { const cn = element.className; assert(cn.split(' ').indexOf(className) >= 0, `"${className}" not found in "${cn}"`); }, noCssClass(element, className) { const cn = element.className; assert(cn.split(' ').indexOf(className) === -1, `Unexpected "${className}" in "${cn}"`); }, contains(haystack, needle) { assert(haystack.indexOf(needle) >= 0, `"${needle}" not found in "${haystack}"`); }, floatEqual(x, y) { assert(Math.abs(x - y) < 0.0000001, `${x} !≈ ${y}`); } };
(function() { 'use strict'; angular .module('app.core') .constant('FIREBASE_URL', 'https://waitandeat-demo.firebaseio.com/'); })();
beforeEach(function () { jasmine.addMatchers({ toContainText: function () { return { compare: function (actual, expectedText) { var actualText = actual.textContent; return { pass: actualText.indexOf(expectedText) > -1, get message() { return 'Expected ' + actualText + ' to contain ' + expectedText; } }; } }; } }); }); /* Copyright 2016 Google Inc. All Rights Reserved. Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at http://angular.io/license */ //# sourceMappingURL=matchers.js.map
git://github.com/evandroeisinger/uP.js.git
define(['games/resource', 'games/sprite'], function (Resource, Sprite) { function PlanesView (config) { var settings = $.extend(true, {}, config); var context; var shadow = [1, 3]; var templates = { terrain : { source : 'img/sea.png' }, plane0 : { source : 'img/fighters.png', x : 50, y : 37, w : 100, h : 100, size : [ settings.player.size, settings.player.size ] }, plane1 : { source : 'img/fighters.png', x : 50, y : 200, w : 100, h : 100, size : [ settings.player.size, settings.player.size ] }, plane2 : { source : 'img/fighters.png', x : 200, y : 37, w : 100, h : 100, size : [ settings.player.size, settings.player.size ] }, plane3 : { source : 'img/fighters.png', x : 200, y : 200, w : 100, h : 100, size : [ settings.player.size, settings.player.size ] }, rocket : { source : 'img/missile_2.png', w : 47, h : 12, size : [ settings.rocket.size * 2, settings.rocket.size / 2 ] }, explosion : { source : 'img/explosion.png', x : 0, y : 0, w : 33, h : 33, speed : 5 / settings.rocket.duration / 60, frames : [0, 1, 2, 3, 4, 5], size : [ settings.explosion.size, settings.explosion.size ] }, debris : { source : 'img/explosion2.png', x : 0, y : 0, w : 65, h : 65, speed : 6 / settings.debris.duration / 60, frames : [0, 1, 2, 3, 4, 5, 6], size : [ settings.debris.size, settings.debris.size ] } }; // rendering for each type of actor var renderHandlers = { player : function (actor) { if(!actor.sprite){ // random plane sprite var key = 'plane' + actor.spriteType; actor.sprite = new Sprite(templates[key]); } context.save(); context.translate(actor.position.x, actor.position.y); // shadow context.beginPath(); context.arc( // shadow[0], shadow[1], // 0,0, actor.heading.x * 5, actor.heading.y * 5, settings.player.size / 3, 0, 2 * Math.PI, false); context.strokeStyle = 'black'; // context.strokeStyle = actor.parent.color; // context.setLineDash([4, 4]); context.lineWidth = 1; // context.globalAlpha = 0.8; context.stroke(); context.fillStyle = actor.parent.color; context.globalAlpha = 0.5; context.fill(); context.globalAlpha = 1; // heading // context.beginPath(); // context.arc( // actor.heading.x * 30, actor.heading.y * 30, // settings.player.size / 10, // 0, 2 * Math.PI, false); // context.fillStyle = actor.parent.color; // context.globalAlpha = 0.7; // context.fill(); // context.globalAlpha = 1; // plane context.rotate(actor.velocity.angle()); actor.sprite.render(context); context.restore(); }, debris : function (actor) { if(!actor.sprite){ actor.sprite = new Sprite(templates[actor.type]); } context.save(); context.translate(actor.position.x, actor.position.y); actor.sprite.render(context); context.restore(); }, bullet : function (actor) { context.save(); context.translate(actor.position.x, actor.position.y); context.rotate(actor.velocity.angle()); context.beginPath(); context.arc( 0,0, settings.bullet.size, 0, 2 * Math.PI, false); context.strokeStyle = 'black'; // context.strokeStyle = actor.parent.color; // context.setLineDash([4, 4]); context.lineWidth = 1; // context.globalAlpha = 0.8; context.stroke(); context.fillStyle = actor.parent.parent.color; // context.globalAlpha = 0.5; context.fill(); // context.globalAlpha = 1; context.restore(); }, rocket : function (actor) { if(!actor.sprite){ actor.sprite = new Sprite(templates.rocket); } context.save(); context.translate(actor.position.x, actor.position.y); context.rotate(actor.velocity.angle()); actor.sprite.render(context); context.restore(); }, explosion : function (actor) { if(!actor.sprite){ actor.sprite = new Sprite(templates[actor.type]); } context.save(); context.translate(actor.position.x, actor.position.y); actor.sprite.render(context); context.restore(); } }; function initialize () { // create and place the canvas var $canvas = $('<canvas id="theCanvas"/>').appendTo('.gameboard'); context = $canvas[0].getContext('2d'); // set the canvas dimensions settings.canvas = { w : $canvas.width(), h : $canvas.height() }; context.canvas.width = settings.canvas.w; context.canvas.height = settings.canvas.h; // preload resources for(var key in templates){ Resource.load(templates[key].source); } Resource.onReady(function () { for(var key in templates){ var t = templates[key]; t.image = Resource.get(t.source); } // terrain templates.terrain.pattern = context.createPattern(templates.terrain.image, 'repeat'); }); } function onLoop (data) { context.clearRect(0, 0, settings.canvas.w, settings.canvas.h); // terrain context.fillStyle = templates.terrain.pattern; context.fillRect(0, 0, settings.canvas.w, settings.canvas.h); var renderOrder = [ 'debris', 'explosion', 'rocket', 'bullet', 'player' ]; for(var i = 0; i < renderOrder.length; i++){ var actors = data.viewModel.actors[renderOrder[i]]; for(var id in actors){ var a = actors[id]; renderHandlers[a.type](a); } } } initialize (); return { getDimensions : function () { return settings.canvas; }, onLoop : onLoop, onReady : Resource.onReady }; } return PlanesView; });
var cf = require('../'); var n = cf( function (n) { return (n - 2) % 3 ? 1 : 2 * ((n - 2) / 3) }, function (n) { return 1 } ); console.log(n);
/*eslint-env node*/ module.exports.buildIcon = (svg, color) => { const buildSvg = svg.replace('{{fill}}', color); return buildSvg.replace(/#g/, '%23'); };
/** * @author john */ $(document).ready(function() { $("input#search-objet").bind("keyup change webkitspeechchange",function() { $.ajax($(this).attr("actionSearch"), { type: "POST", data: { literalQuery : $(this).val() }, success: function(data) { $("ul.list-objets").html(data).listview('refresh');; } }); }); });
;(function() { "use strict"; // Provides management of goals. function GoalCtrl(GoalService, goalTool, currentGoals, studyEndDate, noticesEnabled, noticeUtility, SN_CONSTANTS) { this._goals = GoalService; this._goalTool = goalTool; this.goalModel = this._goalTool.getModel(); this.textMaxLength = SN_CONSTANTS.TEXT_MAX_LENGTH; this.participantGoals = currentGoals; this.studyEndDate = studyEndDate; this.noticesEnabled = noticesEnabled; this.noticeUtility = noticeUtility; this.resetForm(); this.resetTabs(); if (typeof $ !== 'undefined') { $("#help-pop").popover({ html: true }); } } // Is this only available for goal browsing? GoalCtrl.prototype.inBrowseMode = function() { return this._goalTool.getMode() === this._goalTool.MODES.BROWSE; }; // Is this available for goal entry? GoalCtrl.prototype.inEntryMode = function() { return this._goalTool.getMode() === this._goalTool.MODES.ENTRY; }; // Open a form. GoalCtrl.prototype.new = function() { this._goalTool.edit(); }; GoalCtrl.prototype.edit = function(goal) { this._goalTool.edit(goal); }; // Persist the isCompleted attribute to the server. GoalCtrl.prototype.toggleComplete = function(currentGoal) { if (window.confirm("Are you sure you would like to mark this goal as complete? This action cannot be undone.")) { currentGoal.isCompleted = !currentGoal.isCompleted; this._goals.update(currentGoal) .catch(function(goal) { currentGoal.isCompleted = goal.isCompleted; }); if(this.noticesEnabled && this.noticeUtility) { this.noticeUtility.actionNotice("SocialNetworking::Goal", "Complete a goal.", currentGoal.participantId); } } }; // Persist the isDeleted attribute to the server. GoalCtrl.prototype.toggleDeleted = function(currentGoal) { if (window.confirm("Are you sure you would like to delete this goal? This action cannot be undone.")) { currentGoal.isDeleted = !currentGoal.isDeleted; this._goals.update(currentGoal) .catch(function (goal) { currentGoal.isDeleted = goal.isDeleted; }); } }; // Persist a goal from the form. GoalCtrl.prototype.save = function() { var self = this; if (this._goalTool.getModel().id === null) { this._goals.create(this._goalTool.getModel()) .then(function(goal) { self.resetForm(); self.participantGoals.push(goal); self.resetTabs(); if(self.noticesEnabled && self.noticeUtility) { self.noticeUtility.actionNotice("SocialNetworking::Goal", "Create a goal.", goal.participantId); } }) .catch(function(message) { self.error = message.error; }); } else { this._goals.update(this._goalTool.getModel()) .then(function(goal) { // Update the model in the collection. self.participantGoals.some(function(g, i, array) { if (g.id === goal.id) { self._goalTool.copy(goal, g); return true; } return false; }); self.resetForm(); self.resetTabs(); }) .catch(function(message) { self.error = message.error; }); } }; // Undo any changes. GoalCtrl.prototype.resetForm = function() { this._goalTool.setModel(); this._goalTool.setMode(this._goalTool.MODES.BROWSE); }; GoalCtrl.prototype.resetTabs = function() { this._goalTool.setFilter('all'); this._goalTool.setTab('all'); }; GoalCtrl.prototype.setTab = function(name) { this._goalTool.setTab(name); }; GoalCtrl.prototype.getTab = function() { return this._goalTool.getTab(); }; GoalCtrl.prototype.dateInNWeeks = function(week_number) { if (week_number) { return moment().add(week_number, 'weeks').format('MMM DD YYYY'); } else { return null; } }; GoalCtrl.prototype.dateAtEndOfTrial = function() { if (this.studyEndDate && moment(this.studyEndDate) > moment()) { return moment(this.studyEndDate).format("MMM DD YYYY"); } else { return null; } }; GoalCtrl.prototype.atLeastNWeeksLeftInTrial = function(week_number) { week_number = week_number || 0; return moment().add(week_number, 'weeks') .isBefore(moment(this.studyEndDate)); }; GoalCtrl.prototype.setFilter = function(type) { this._goalTool.setFilter(type); }; GoalCtrl.prototype.showCharLimit = function(inputTag) { $(inputTag) .showCharLimit({ maxlength: this.textMaxLength }); }; GoalCtrl.prototype.getFilter = function() { return this._goalTool.getFilter(); }; // Create a module and register the controller. angular.module('socialNetworking.controllers') .controller('GoalCtrl', ['Goals', 'goalTool', 'currentGoals', 'participantStudyEndDate', 'noticesEnabled', 'noticeUtility', 'SN_CONSTANTS', GoalCtrl]); })();
/** *-------------------------------------------------------------------------*** *广告位管理-添加广告位-验证 *-------------------------------------------------------------------------*** **/ function validulate(){ $("#advertSiteForm").validate({ submitHandler:function(form){ saveAdvertSite(); }, rules:{ advertiseNo:{ required:true, maxlength:40, ocharval:true, remote:{ url:"advertSite.do?method=add&dot=1", type:"post", dataType:"json", data:{ siteNo:function(){ return $("#advertiseNo").val(); } } } }, advertiseName:{required:true,maxlength:50,nameval:true}, width:{required:true,maxlength:4,number:true}, height:{required:true,maxlength:4,number:true} }, messages:{ advertiseNo:{required:"不能为空!",maxlength:"最多40个字符!",ocharval:"不能输入特殊字符!",remote:"此编号已经存在!"}, advertiseName:{required:"不能为空!",maxlength:"最多50个字符!",nameval:"不能输入特殊字符!"}, width:{required:"不能为空!",maxlength:"最多4个字符!",number:"只能为数字!"}, height:{required:"不能为空!",maxlength:"最多4个字符!",number:"只能为数字!"} } }); } /** *-------------------------------------------------------------------------*** *广告位管理-添加广告位-提交 *-------------------------------------------------------------------------*** **/ function saveAdvertSite(){ var data = $("#advertSiteForm").serializeObject(); data.status = 0; data.companyId = GetCookie('companyId'); $.post("advertSite.do?method=add&random="+getRandom(10),{data:JSON.stringify(data),dot:'2'},function(json){ if(json.returnState == true){ jAlert("添加成功","提示信息",function(){ window.location = "advertSite.do?random="+getRandom(15); }); }else{ jAlert("添加失败","提示信息"); } },"json"); } /** *-------------------------------------------------------------------------*** *广告位管理-添加广告位-加载 *-------------------------------------------------------------------------*** **/ $(document).ready(function(){ validulate(); //声明提交事件 $("#saveBtn").click(function(){ $("#advertSiteForm").submit(); }); $("#backBtn").click(function(){ window.location = "advertSite.do?random="+getRandom(15); }); });
$(document).ready(function() { var submitIcon = $(".ExpIcon "); var submitInput = $(".ExpInput"); var searchBox = $(".Exp-search"); var isOpen = false; $(document).mouseup(function() { if (isOpen == true) { submitInput.val(""); $(".Expbtn").css("z-index", "-999"); submitIcon.click(); } }); searchBox.mouseup(function() { return false; }); submitIcon.click(function() { if (isOpen == false) { searchBox.addClass("Exp-search-open"); isOpen = true; } else { searchBox.removeClass("Exp-search-open"); isOpen = false; } }); }); $(document).ready(function() { console.log('hello'); $(".js-example-basic-single").select2(); }); $("#channelSelect").select2({ closeOnSelect:false, templateResult: function (data) { console.log('got in channel?') var $res = $('<span></span>'); var $check = $('<input type="checkbox" />'); $res.text(data.text); if (data.element) { $res.prepend($check); $check.prop('checked', data.element.selected); } return $res; } }); /* resizable table*/ $(function() { var thHeight = $("table#filesTable th:first").height(); $( "table#filesTable th:first-child, table#filesTable td:first-child" ).resizable({ handles: "e", minHeight: thHeight, maxHeight: thHeight, minWidth: 40, resize: function(event, ui) { var sizerID = "#" + $(event.target).attr("id") + "-sizer"; $(sizerID).width(ui.size.width); } }); }); $(document).ready(function() { jQuery(".scrollbar-dynamic").scrollbar(); //var calcHeight = FilePanelH(); $(".files-panel").css("height", FilePanelH); }); // Popup dHeight // capture click $("#fileExplorer").on("shown.bs.modal", function(event) { popUpH(); }); $(window).resize(function() { popUpH(); }); function popUpH() { function popUpHeight() { var popupMargins = 80, // 40 + 40 topand bottom margins mHeaderH = $(".modal-header").innerHeight(), mFooterH = $(".modal-footer").innerHeight(); //calc var calcHeight = window.innerHeight - (popupMargins + mHeaderH + mFooterH); return calcHeight; } $(".modal-body > .dheight") .find(".scroll-wrapper.scrollbar-dynamic") .css("max-height", popUpHeight); } function FilePanelH() { var pageMargins = 112, // 40 + 40 topand bottom margins ContentPH = $("#Content-Panel").innerHeight(), HeaderH = $(".custom-navbar").innerHeight(), FooterH = $(".btn-bar").innerHeight(); //calc var calcHeight = window.innerHeight - (pageMargins + ContentPH + HeaderH + FooterH); return calcHeight; } function FilePanelHNew() { var pageMargins = 130, // 40 + 40 topand bottom margins HeaderH = $(".custom-navbar").innerHeight(), FooterH = $(".btn-bar").innerHeight(); //calc var calcHeight = window.innerHeight - (pageMargins + HeaderH + FooterH); return calcHeight; } $("#Techattr").on("shown.bs.collapse", function() { $(".files-panel").css("height", FilePanelH); }); $(window).resize(function() { popUpH(), FilePanelH(); }); $("#ContentDetails").on("hide.bs.collapse", function() { $(".files-panel").css("height", FilePanelHNew); }); $(window).resize(function() { popUpH(), FilePanelH(); });
// -------------------- // co-series module // Tests // -------------------- // modules var chai = require('chai'), chaiAsPromised = require('chai-as-promised'), expect = chai.expect, Promise = global.Promise, Bluebird = require('bluebird'), Q = require('q'), series = require('../lib/'); // init chai.config.includeStack = true; chai.use(chaiAsPromised); // use Bluebird if no native Promise (e.g. Node v0.10) if (!Promise) { Promise = require('bluebird'); series = series.use(Promise); } // tests /* jshint expr: true */ /* global describe, it, beforeEach */ module.exports = function(order, fn1, fn2, fn3, fn4, fn5) { beforeEach(function() { order.length = 0; }); it('runs serially', function() { var fn = series(fn1); var res = [1, 2, 3].map(fn); order.push('sync'); return res[2].then(function(res) { expect(res).to.equal(30); expect(order).to.deep.equal(['start1', 'sync', 'end1', 'start2', 'end2', 'start3', 'end3']); }); }); it('delays first iteration with option {immediate: false}', function() { var fn = series(fn1, {immediate: false}); var res = [1, 2, 3].map(fn); order.push('sync'); return res[2].then(function(res) { expect(res).to.equal(30); expect(order).to.deep.equal(['sync', 'start1', 'end1', 'start2', 'end2', 'start3', 'end3']); }); }); it('passes this context', function() { var fn = series(fn2); var x = {fn: fn, j: 9}; return x.fn(3).then(function(res) { expect(res).to.equal('3-9'); }); }); describe('Error handling', function() { describe('sync error', function() { var fn; beforeEach(function() { fn = series(fn3); }); describe('on 1st iteration', function() { it('rejects', function() { var res = [2, 3, 4].map(fn); return Promise.all([ expect(res[0]).to.be.rejectedWith(Error, 'error2'), expect(res[1]).to.be.rejectedWith(Error, 'error2'), expect(res[2]).to.be.rejectedWith(Error, 'error2') ]); }); it('halts execution', function() { var res = [2, 3, 4].map(fn); return reflectAll(res).then(function() { expect(order).to.deep.equal(['start2']); }); }); }); describe('on 2nd iteration', function() { it('rejects', function() { var res = [1, 2, 3].map(fn); return Promise.all([ expect(res[0]).to.eventually.equal(10), expect(res[1]).to.be.rejectedWith(Error, 'error2'), expect(res[2]).to.be.rejectedWith(Error, 'error2') ]); }); it('halts execution', function() { var res = [1, 2, 3].map(fn); return reflectAll(res).then(function() { expect(order).to.deep.equal(['start1', 'end1', 'start2']); }); }); }); }); describe('async error', function() { var fn; beforeEach(function() { fn = series(fn4); }); describe('on 1st iteration', function() { it('rejects', function() { var res = [2, 3, 4].map(fn); return Promise.all([ expect(res[0]).to.be.rejectedWith(Error, 'error2'), expect(res[1]).to.be.rejectedWith(Error, 'error2'), expect(res[2]).to.be.rejectedWith(Error, 'error2') ]); }); it('halts execution', function() { var res = [2, 3, 4].map(fn); return reflectAll(res).then(function() { expect(order).to.deep.equal(['start2']); }); }); }); describe('on 2nd iteration', function() { it('rejects', function() { var res = [1, 2, 3].map(fn); return Promise.all([ expect(res[0]).to.eventually.equal(10), expect(res[1]).to.be.rejectedWith(Error, 'error2'), expect(res[2]).to.be.rejectedWith(Error, 'error2') ]); }); it('halts execution', function() { var res = [1, 2, 3].map(fn); return reflectAll(res).then(function() { expect(order).to.deep.equal(['start1', 'end1', 'start2']); }); }); }); }); }); it('use method uses supplied promise implementation', function() { var useSeries = series.use(Q); var fn = useSeries(fn5); var p = fn(); expect(isPromise(p)).to.be.true; expect(p).not.to.be.instanceof(Promise); }); }; function reflectAll(promises) { return Promise.all(promises.map(function(promise) { return Bluebird.resolve(promise).reflect(); })); } function isPromise(obj) { return !!obj && (typeof obj == 'object' || typeof obj == 'function') && typeof obj.then == 'function'; }
ScalaJS.impls.scala_sys_process_ProcessCreation$class__apply__Lscala_sys_process_ProcessCreation__T__Lscala_sys_process_ProcessBuilder = (function($$this, command$9) { return $$this.apply__T__Lscala_Option__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder(command$9, ScalaJS.modules.scala_None(), ScalaJS.modules.scala_Predef().wrapRefArray__AO__Lscala_collection_mutable_WrappedArray(ScalaJS.asArrayOf.java_lang_Object(ScalaJS.makeNativeArrayWrapper(ScalaJS.data.scala_Tuple2.getArrayOf(), []), 1))) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__apply__Lscala_sys_process_ProcessCreation__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder = (function($$this, command) { return $$this.apply__Lscala_collection_Seq__Lscala_Option__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder(command, ScalaJS.modules.scala_None(), ScalaJS.modules.scala_Predef().wrapRefArray__AO__Lscala_collection_mutable_WrappedArray(ScalaJS.asArrayOf.java_lang_Object(ScalaJS.makeNativeArrayWrapper(ScalaJS.data.scala_Tuple2.getArrayOf(), []), 1))) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__apply__Lscala_sys_process_ProcessCreation__T__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder = (function($$this, command, arguments$2) { var jsx$2 = $$this; var x$1 = command; var jsx$1 = ScalaJS.as.scala_collection_Seq(arguments$2.$$plus$colon__O__Lscala_collection_generic_CanBuildFrom__O(x$1, ScalaJS.modules.scala_collection_Seq().canBuildFrom__Lscala_collection_generic_CanBuildFrom())); return jsx$2.apply__Lscala_collection_Seq__Lscala_Option__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder(jsx$1, ScalaJS.modules.scala_None(), ScalaJS.modules.scala_Predef().wrapRefArray__AO__Lscala_collection_mutable_WrappedArray(ScalaJS.asArrayOf.java_lang_Object(ScalaJS.makeNativeArrayWrapper(ScalaJS.data.scala_Tuple2.getArrayOf(), []), 1))) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__apply__Lscala_sys_process_ProcessCreation__T__Ljava_io_File__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder = (function($$this, command, cwd, extraEnv) { return $$this.apply__T__Lscala_Option__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder(command, new ScalaJS.c.scala_Some().init___O(cwd), extraEnv) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__apply__Lscala_sys_process_ProcessCreation__Lscala_collection_Seq__Ljava_io_File__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder = (function($$this, command, cwd, extraEnv) { return $$this.apply__Lscala_collection_Seq__Lscala_Option__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder(command, new ScalaJS.c.scala_Some().init___O(cwd), extraEnv) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__apply__Lscala_sys_process_ProcessCreation__T__Lscala_Option__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder = (function($$this, command, cwd, extraEnv) { return $$this.apply__Lscala_collection_Seq__Lscala_Option__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder(ScalaJS.modules.scala_Predef().wrapRefArray__AO__Lscala_collection_mutable_WrappedArray(ScalaJS.asArrayOf.java_lang_Object(ScalaJS.impls.scala_scalajs_runtime_RuntimeString$class__split__Lscala_scalajs_runtime_RuntimeString__T__AT(command, "\\s+"), 1)), cwd, extraEnv) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__apply__Lscala_sys_process_ProcessCreation__Lscala_collection_Seq__Lscala_Option__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder = (function($$this, command, cwd, extraEnv) { var jpb = new ScalaJS.c.java_lang_ProcessBuilder().init___AT(ScalaJS.asArrayOf.java_lang_String(command.toArray__Lscala_reflect_ClassTag__O(ScalaJS.modules.scala_reflect_ClassTag().apply__Ljava_lang_Class__Lscala_reflect_ClassTag(ScalaJS.data.java_lang_String.getClassOf())), 1)); cwd.foreach__Lscala_Function1__V(new ScalaJS.c.scala_scalajs_runtime_AnonFunction1().init___Lscala_scalajs_js_Function1((function(jpb$1) { return (function(x$2) { return jpb$1.directory__Ljava_io_File__Ljava_lang_ProcessBuilder(x$2) }) })(jpb))); extraEnv.foreach__Lscala_Function1__V(new ScalaJS.c.scala_scalajs_runtime_AnonFunction1().init___Lscala_scalajs_js_Function1((function(jpb$1) { return (function(x0$1) { var x1 = x0$1; if ((x1 !== null)) { var k = ScalaJS.as.java_lang_String(x1.$$und1__O()); var v = ScalaJS.as.java_lang_String(x1.$$und2__O()); return ScalaJS.as.java_lang_String(jpb$1.environment__Ljava_util_Map().put__O__O__O(k, v)) }; throw new ScalaJS.c.scala_MatchError().init___O(x1) }) })(jpb))); return $$this.apply__Ljava_lang_ProcessBuilder__Lscala_sys_process_ProcessBuilder(jpb) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__apply__Lscala_sys_process_ProcessCreation__Ljava_lang_ProcessBuilder__Lscala_sys_process_ProcessBuilder = (function($$this, builder) { return new ScalaJS.c.scala_sys_process_ProcessBuilderImpl$Simple().init___Lscala_sys_process_ProcessBuilder$__Ljava_lang_ProcessBuilder(ScalaJS.modules.scala_sys_process_ProcessBuilder(), builder) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__apply__Lscala_sys_process_ProcessCreation__Ljava_io_File__Lscala_sys_process_ProcessBuilder$FileBuilder = (function($$this, file) { return new ScalaJS.c.scala_sys_process_ProcessBuilderImpl$FileImpl().init___Lscala_sys_process_ProcessBuilder$__Ljava_io_File(ScalaJS.modules.scala_sys_process_ProcessBuilder(), file) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__apply__Lscala_sys_process_ProcessCreation__Ljava_net_URL__Lscala_sys_process_ProcessBuilder$URLBuilder = (function($$this, url) { return new ScalaJS.c.scala_sys_process_ProcessBuilderImpl$URLImpl().init___Lscala_sys_process_ProcessBuilder$__Ljava_net_URL(ScalaJS.modules.scala_sys_process_ProcessBuilder(), url) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__apply__Lscala_sys_process_ProcessCreation__Lscala_xml_Elem__Lscala_sys_process_ProcessBuilder = (function($$this, command) { return $$this.apply__T__Lscala_sys_process_ProcessBuilder(ScalaJS.impls.scala_scalajs_runtime_RuntimeString$class__trim__Lscala_scalajs_runtime_RuntimeString__T(command.text__T())) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__apply__Lscala_sys_process_ProcessCreation__Z__Lscala_sys_process_ProcessBuilder = (function($$this, value) { return $$this.apply__T__Lscala_Function0__Lscala_sys_process_ProcessBuilder(ScalaJS.objectToString(ScalaJS.bZ(value)), new ScalaJS.c.scala_scalajs_runtime_AnonFunction0().init___Lscala_scalajs_js_Function0((function(value$1) { return (function() { if (value$1) { var jsx$3 = 0 } else { var jsx$3 = 1 }; return ScalaJS.bI(jsx$3) }) })(value))) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__apply__Lscala_sys_process_ProcessCreation__T__Lscala_Function0__Lscala_sys_process_ProcessBuilder = (function($$this, name, exitValue) { return new ScalaJS.c.scala_sys_process_ProcessBuilderImpl$Dummy().init___Lscala_sys_process_ProcessBuilder$__T__Lscala_Function0(ScalaJS.modules.scala_sys_process_ProcessBuilder(), name, exitValue) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__applySeq__Lscala_sys_process_ProcessCreation__Lscala_collection_Seq__Lscala_Function1__Lscala_collection_Seq = (function($$this, builders, convert) { return ScalaJS.as.scala_collection_Seq(builders.map__Lscala_Function1__Lscala_collection_generic_CanBuildFrom__O(convert, ScalaJS.modules.scala_collection_Seq().canBuildFrom__Lscala_collection_generic_CanBuildFrom())) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__cat__Lscala_sys_process_ProcessCreation__Lscala_sys_process_ProcessBuilder$Source__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder = (function($$this, file, files) { var jsx$5 = $$this; var x$3 = file; var jsx$4 = ScalaJS.as.scala_collection_Seq(files.$$plus$colon__O__Lscala_collection_generic_CanBuildFrom__O(x$3, ScalaJS.modules.scala_collection_Seq().canBuildFrom__Lscala_collection_generic_CanBuildFrom())); return jsx$5.cat__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder(jsx$4) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__cat__Lscala_sys_process_ProcessCreation__Lscala_collection_Seq__Lscala_sys_process_ProcessBuilder = (function($$this, files) { ScalaJS.modules.scala_Predef().require__Z__V(files.nonEmpty__Z()); return ScalaJS.as.scala_sys_process_ProcessBuilder(ScalaJS.as.scala_collection_TraversableOnce(files.map__Lscala_Function1__Lscala_collection_generic_CanBuildFrom__O(new ScalaJS.c.scala_scalajs_runtime_AnonFunction1().init___Lscala_scalajs_js_Function1((function() { return (function(x$4) { return x$4.cat__Lscala_sys_process_ProcessBuilder() }) })()), ScalaJS.modules.scala_collection_Seq().canBuildFrom__Lscala_collection_generic_CanBuildFrom())).reduceLeft__Lscala_Function2__O(new ScalaJS.c.scala_scalajs_runtime_AnonFunction2().init___Lscala_scalajs_js_Function2((function() { return (function(x$5, x$6) { return x$5.$$hash$amp$amp__Lscala_sys_process_ProcessBuilder__Lscala_sys_process_ProcessBuilder(x$6) }) })()))) }); ScalaJS.impls.scala_sys_process_ProcessCreation$class__$init$__Lscala_sys_process_ProcessCreation__V = (function($$this) { /*<skip>*/ }); //@ sourceMappingURL=ProcessCreation$class.js.map
/** * Created by antoinelucas on 12/05/2016. */ 'use strict'; var authorization = require('./../helpers/authorization.middleware'), user = require('./../controllers/user.server.controller'); module.exports = function (app) { app.route('/user/details').get(authorization.hasRole(['user', 'admin']), user.details); };
'use strict'; module.exports = function (targs, opts) { // takes targets and parses out f1 friendly values //defaults opts = { type: opts.type || 'simple', slotMachine: opts.slotMachine || false, iconPosition: opts.iconPosition || 'right', iconDirection: opts.iconDirection || 'left' }; /*offBgBackgroundColor: [46, 204, 114], offBorderBorderColor: [256, 256, 256], offIconPosition: [324, 27, 0], offIconColor: [256, 256, 256], offTextColor: [256, 256, 256], overBgBackgroundColor: [36, 182, 98], overIconPosition: [188, 27, 0], downBorderBorderColor: [23, 149, 76], downIconColor: [23, 149, 76], downTextColor: [23, 149, 76]*/ var getBgBackgroundColor = function(bg){ return window.getComputedStyle(bg, null).getPropertyValue("background-color"); }; var states = {}; states.off = {}; if(targs.bg){ states.off.bg = { backgroundColor: getBgBackgroundColor(targs.bg) } } return states; }; /* function getBtnTextPosition(txt){ return [txt.offsetLeft, txt.offsetTop, 0] } function getIconOverPosition(targs, opts){ if(!targs) console.warn('You need to supply "getIconOverPosition()", a target object.'); opts = opts || { position: 'right', direction: 'left' }; var edgeOfText = targs.text.offsetLeft + targs.text.offsetWidth; var availSpace = targs.bg.offsetWidth - edgeOfText - borderWidth; var left = edgeOfText + ((availSpace - targs.icon.offsetWidth) * .5); var top = (targs.bg.offsetHeight - targs.icon.offsetHeight) * .5; return [Math.floor(left), Math.floor(top), 0]; } function getIconOffPosition(targs, opts){ if(!targs) console.warn('You need to supply "getIconOverPosition()", a target object.'); opts = opts || { position: 'right', direction: 'left' }; var left = targs.bg.offsetWidth * 1.3; var top = (targs.bg.offsetHeight - targs.icon.offsetHeight) * .5; return [left, top, 0]; }*/
import API from 'src/util/api'; export class RangesManager { constructor(ranges, options = {}) { this.ranges = ranges; this.currentRange = undefined; this.ensureLabel = options.ensureLabel; } processAction(action) { if ( !action.value.event.altKey || action.value.event.shiftKey || action.value.event.ctrlKey ) { return; } let track; if (action.value && action.value.data) { let firstChart = Object.keys(action.value.data)[0]; if (firstChart) { track = action.value.data[firstChart]; } } if (!track) return; switch (action.name) { case 'trackClicked': this.updateRange(track); break; case 'trackMove': this.updateAnnotations(track); break; default: } } updateAnnotations(track) { if (!this.ranges || this.ranges.length === 0) { API.createData('rangeAnnotations', []); return; } let annotations = []; let updateHighlight = false; for (let range of this.ranges) { if (!range._highlight) { updateHighlight = true; Object.defineProperty(range, '_highlight', { enumerable: false, value: Math.random() }); } if (range.to) { let annotation = { position: [ { x: range.from, y: '15px' }, { x: range.to, y: '20px' } ], type: 'rect', fillColor: range.color || 'red', strokeColor: range.color || 'red', _highlight: [range._highlight], info: range }; if (range.label) { annotation.label = [ { text: range.label, size: '18px', anchor: 'middle', color: range.color || 'red', position: { x: (range.from + range.to) / 2, y: '10px' } } ]; } annotations.push(annotation); } if (updateHighlight) { API.getData('ranges').triggerChange(); } } if (track && this.currentRange && !this.currentRange.to) { annotations.push({ position: [ { x: this.currentRange.from, y: '15px' }, { x: track.xClosest, y: '20px' } ], type: 'rect', fillColor: 'green', strokeColor: 'green' }); } API.createData('rangeAnnotations', annotations); } setLabel(currentRange) { // look for the first letter not used let current = 65; label: while (current < 91) { for (let range of this.ranges) { if (range.label && range.label.charCodeAt(0) === current) { current++; continue label; } } currentRange.label = String.fromCharCode(current); return; } } updateRange(track) { if (this.currentRange) { this.currentRange.to = track.xClosest; checkFromTo(this.currentRange); this.currentRange = undefined; } else { let range = {}; this.ranges.push(range); this.currentRange = range; range.from = track.xClosest; } if (this.ensureLabel && this.currentRange && !this.currentRange.label) { this.setLabel(this.currentRange); } this.ranges.triggerChange(); this.updateAnnotations(); } addRanges(ranges) { for (let range of ranges) { checkFromTo(range); if (!range.label) { this.manager.setLabel(range); } this.ranges.push(range); } this.ranges.triggerChange(); this.updateAnnotations(); } } function checkFromTo(range) { if (range.to === undefined) return; if (range.from > range.to) [range.from, range.to] = [range.to, range.from]; } module.exports = RangesManager;
'use strict'; angular.module('teamDashboardApp') .controller('LoginCtrl', function ($scope, Auth, $location) { $scope.user = {}; $scope.errors = {}; $scope.login = function(form) { $scope.submitted = true; if(form.$valid) { Auth.login({ email: $scope.user.email, password: $scope.user.password }) .then( function() { // Logged in, redirect to home $location.path('/'); }) .catch( function(err) { err = err.data; $scope.errors.other = err.message; }); } }; });
(function() { 'use strict'; describe('loci.entry module', function() { beforeEach(module('loci.entry')); describe('entry controller', function(){ it('should be defined', inject(function($controller) { var entryCtrl = $controller('EntryCtrl'); expect(entryCtrl).toBeDefined(); })); }); }); }());
/* global module:false */ module.exports = function(grunt) { var port = grunt.option('port') || 8000; // Project configuration grunt.initConfig({ watch: { options: { livereload: true }, css: { files: [ 'style.css' ] }, html: { files: [ 'index.html'] } } }); // Dependencies grunt.loadNpmTasks( 'grunt-contrib-watch' ); };
({ baseUrl: './', //optimize: 'none', //uncomment this option if built source needs to be debugged paths: { almond: '../vendor/almond/almond' }, mainConfigFile: 'require-config.js', name: 'almond', include: ['main'], out: '../dist/scripts/mentalmodeler.js' })
/* * Video.js AB loop plugin * Adds function to allow looping for a section of a video in video.js player * https://github.com/phhu/videojs-abloop * MIT licence */ ; (function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory.bind(this, root, root.videojs)); } else if (typeof module !== 'undefined' && module.exports) { module.exports = factory(root, root.videojs); } else { factory(root, root.videojs); } })(window, function (window, videojs) { "use strict"; var version = "1.0.1"; var abLoopPlugin = function (initialOptions) { //default initial options if not specified. initialOptions = initialOptions || {}; //get reference to player var player = this; //utility functions var isNumber = function (n) { return !isNaN(parseFloat(n)) && isFinite(n); }; var isFunction = function (functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; }; var toBoolean = function (x) { return !!x; }; var cloneAndPluck = function (sourceObject, keys) { var newObject = {}; keys.forEach(function (key) { if (sourceObject[key] !== undefined) { newObject[key] = sourceObject[key]; } }); return newObject; }; //adds decimals to videojs's format time function var formatTimeWithMS = function (seconds, decimalPlaces) { decimalPlaces = decimalPlaces || 1; return videojs.formatTime(seconds) + '.' + Math.floor((seconds % 1) * Math.pow(10, decimalPlaces)); }; var roundFloat = function (n, decimalPlaces) { var f = Math.pow(10, decimalPlaces); return Math.floor(n * f) / f; }; //this converts a timestamp (1h23, 1:23:33, 1m30s etc) to a number of seconds var parseTimeStamp = function (timestamp) { if (timestamp === undefined) { return undefined; } //if a plain number ,assume seconds if (isNumber(timestamp)) { return timestamp; } if (/^([+\-])?([\d\.]+)$/i.test(timestamp)) { return parseFloat(timestamp); } //this assumes a plain whole number is minutes var res = /^([+\-])?((([\d]+)(h|:(?=.*:)))?(([\d]+)(m|:|$))?)?(([\d\.]+)s?)?$/i.exec(timestamp); if (!res) { return null; } var d = { match: res[0], sign: res[1], hours: res[4] || 0, mins: res[7] || 0, secs: res[10] || 0 }; var multiplier = (d.sign == '-') ? -1 : 1; var totSecs = parseFloat(d.hours) * 60 * 60 + parseFloat(d.mins) * 60 + parseFloat(d.secs); return isNumber(totSecs) ? multiplier * totSecs : null; }; //contains options, allowing them to be set at runtime var opts = {}; var optionSpecs = { 'start': { "default": 0, "validate": function (x) { if (x === false) { return x; } if (isNumber(x) && x >= 0) { return x; } return 0; } }, 'end': { "default": false, "validate": function (x) { if (x === false) { return x; } //allow false values to mean loop til end if (isNumber(x)) { var duration = player.duration(); if (duration === undefined || duration === 0) { //duration unknown if (x >= 0) { return x; } } else { //we know the duration if (x >= 0 && x <= duration) { return x; } else if (x > duration) { return duration; } } } return false; // by default, loop to end of video } }, 'enabled': { "default": false, "validate": toBoolean }, 'loopIfBeforeStart': { "default": true, "validate": toBoolean }, 'loopIfAfterEnd': { "default": true, "validate": toBoolean }, 'pauseBeforeLooping': { "default": false, "validate": toBoolean }, 'pauseAfterLooping': { "default": false, "validate": toBoolean } //it's easier not to treat this as an option, as can't remove buttons once created /*,'createButtons':{ "default":true ,"validate":toBoolean }*/ }; //callbacks can be included in initial options, but are not treated as options //check is used to check that the callbacks are valid, but not to replace their values var callBackSpecs = { 'onLoopCallBack': { "default": undefined, "check": isFunction }, 'onOptionsChange': { "default": undefined, "check": isFunction } }; //for convenience var optionNames = Object.keys(optionSpecs); var callBackNames = Object.keys(callBackSpecs); //set initial option values to defaults if they are not specified var defaultInitialOptions = function () { initialOptions = initialOptions || {}; var setToDefault = function (specs) { return function (name) { if (initialOptions[name] === undefined) { initialOptions[name] = specs[name].default; } }; }; optionNames.forEach(setToDefault(optionSpecs)); callBackNames.forEach(setToDefault(callBackSpecs)); }; //assign bound copies of the callbacks to the api var setCallBacksToInitialOptions = function () { callBackNames.forEach(function (callBackName) { if (callBackSpecs[callBackName].check(initialOptions[callBackName])) { api[callBackName] = initialOptions[callBackName]; // .bind(api) - better not to bind } }); }; //check that the options make sense. This is called on timeupdate, before the main logic. //so nonsense options will persist as long as time does not update var validateOptions = function () { optionNames.forEach(function (optName) { opts[optName] = optionSpecs[optName].validate(opts[optName]); }); return api; }; var setOptionsToInitialOptions = function () { return setOptions(initialOptions, true); }; var setOptions = function (newOptions, replaceAll) { optionNames.forEach(function (optName) { if (replaceAll || newOptions[optName] !== undefined) { opts[optName] = newOptions[optName]; } }); validateOptions(); return api; }; var alreadyPausedBeforeLoop = false; //if we pause before looping, need to know if it has already been done so that we can then loop //this sets the player to the start of the loop var goToStartOfLoop = function (checkPause) { if (checkPause) { if (opts.pauseBeforeLooping && alreadyPausedBeforeLoop === false) { player.pause(); alreadyPausedBeforeLoop = true; } else { alreadyPausedBeforeLoop = false; //do loop player.currentTime(opts.start); //invoke callback if set if (opts.pauseAfterLooping) { player.pause(); } if (callBackSpecs.onLoopCallBack.check(api.onLoopCallBack)) { api.onLoopCallBack(api, player); } } } else { alreadyPausedBeforeLoop = false; player.currentTime(opts.start); } return api; }; var goToEndOfLoop = function () { alreadyPausedBeforeLoop = false; player.currentTime(opts.end); return api; }; //makes a function to set a time option (start,end) var timeSetter = function (optName) { return function (time) { if (time === false) { opts[optName] = false; } else { if (time !== undefined) { time = parseTimeStamp(time); } if (time !== null) { time = (time === undefined) ? player.currentTime() : time; opts[optName] = time; } } return api; }; }; //makes a function to change a time option var timeAdjuster = function (optName) { return function (adjustment) { adjustment = parseTimeStamp(adjustment); if (isNumber(adjustment)) { opts[optName] += adjustment; } return api; }; }; var playLoop = function () { validateOptions(); goToStartOfLoop(false); enableLoop(); player.play(); return api; }; var enableLoop = function () { opts.enabled = true; return api; }; var disableLoop = function () { opts.enabled = false; return api; }; var cyclePauseOnLooping = function () { var after = opts.pauseAfterLooping, before = opts.pauseBeforeLooping; if (!after && !before) { setOptions({ pauseAfterLooping: true, pauseBeforeLooping: false }); } else if (after && !before) { setOptions({ pauseAfterLooping: false, pauseBeforeLooping: true }); } else if (!after && before) { setOptions({ pauseAfterLooping: true, pauseBeforeLooping: true }); } else { setOptions({ pauseAfterLooping: false, pauseBeforeLooping: false }); } return api; }; //return a function to toggle an option var toggler = function (optName) { return function () { opts[optName] = !opts[optName]; return api; }; }; //borrowed from videojs library (private method) var absoluteURL = function (url) { // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. if (window && window.document) { var div = window.document.createElement('div'); div.innerHTML = '<a href="' + url + '">x</a>'; url = div.firstChild.href; } } return url; }; var getAbsoluteUrlWithHash = function (spec) { return absoluteURL(getUrlWithHash(spec)); }; //return a URL hash / fragment describing the looped portion. //e.g. #t=10,12 - see https://www.w3.org/TR/media-frags/#standardisation-URI-fragments var getUrlHash = function (spec) { spec = spec || {}; spec.decimalPlaces = Math.floor(spec.decimalPlaces) || 3; //validateOptions(); var start = (opts.start !== false) ? parseFloat(opts.start) : 0; var hash = '#' + 't=' + roundFloat(start, spec.decimalPlaces); if (opts.end !== false) { var end = parseFloat(opts.end); hash += (',' + roundFloat(end, spec.decimalPlaces)); } return hash; }; //get a URL with a hash to identify the looping section var getUrlWithHash = function (spec) { spec = spec || {}; var src = player.currentSrc(); if (src.src) { src = src.src; } var url = src + getUrlHash(spec); return url; }; //apply just a hash, effectively setting start and end options var applyUrlHash = function (url) { //allow to pass in a string or an object with hash property if (typeof url === 'string') { url = videojs.parseUrl(url); } if (url.hash) { //extract out the start and end times var re = /^(#?t=)?([^,]*)(,(.*))?$/; var start = url.hash.replace(re, '$2'); var end = url.hash.replace(re, '$4'); //normally only seconds or hh:mm:ss are allowed, but allow 1m20s etc start = parseTimeStamp(start); end = parseTimeStamp(end); if (isNumber(start)) { opts.start = parseFloat(start); } if (isNumber(end)) { opts.end = parseFloat(end); } } return api; }; //apply a url, typically with a hash to identify a section to loop //this will load a new source if necessary var applyUrl = function (url) { //could use videojs.parseUrl, but regexping is less hassle var urlWithoutHash = url.replace(/^(.*?)(#.*)?$/, '$1'); var urlHash = url.replace(/^(.*?)(#.*)?$/, '$2'); //check if we need to update the source var curSrc = player.currentSrc(); if (!(curSrc == urlWithoutHash || curSrc == url || url == urlHash)) { player.src(urlWithoutHash); } //apply hash if there is one if (urlHash) { applyUrlHash(urlHash); } return api; }; var getOptions = function (optionsToReturn) { var retOpts = optionsToReturn; //coerce retOpts into an Array if (typeof optionsToReturn === 'string') { retOpts = [optionsToReturn]; } else if (optionsToReturn === undefined || !Array.isArray(optionsToReturn)) { if (optionsToReturn !== null && typeof optionsToReturn === 'object') { //allow specification with an object` retOpts = Object.keys(optionsToReturn); } else { //return all options if none are specified retOpts = Object.keys(optionSpecs); } } return cloneAndPluck(opts, retOpts); }; //used to add notification to a function call //changed is an object of properties which have changed //e.g. {'start':true, 'end':false} var notify = function (funcToRun, changed) { var defValue = changed ? false : true; //if changed not specified, assume they all have changed = changed || {}; //set defaults for changed optionNames.forEach(function (optName) { changed[optName] = !!changed[optName] || defValue; }); return function () { var args = arguments; var oldOpts = getOptions(); //copy options as were var ret = funcToRun.apply(null, args); var optionDetails = { 'changed': changed, 'oldOpts': oldOpts, 'newOpts': getOptions() }; if (api.onOptionsChange) { api.onOptionsChange(optionDetails, api, player); } updateButtonText(changed); //API might have changed settings, so update the buttons return ret; }; }; var loopAtEndOfVideoRequired = false; //flag set to true if looping around end of video is requierd (where start > end) var startMargin = 0.5; //sometimes the video will go to a point just before the loop (rounding), so allow a small margin on the start position check. var endMargin = 1; //sometimes the video will go to a point just before the loop (rounding), so allow a small margin on the start position check. //given the current player state and options, should we loop? var loopRequired = function () { var curTime, endTime, startTime; validateOptions(); curTime = player.currentTime(); endTime = getEndTime(); startTime = getStartTime(); if (startTime > endTime) { loopAtEndOfVideoRequired = true; //if the end is before the start, deal with it if (curTime < (startTime - startMargin) && curTime > endTime && ((curTime - endTime) < endMargin || opts.loopIfAfterEnd || opts.loopIfBeforeStart)) { return true; } } else { //startTime <= endTime loopAtEndOfVideoRequired = false; if (curTime < (startTime - startMargin) && opts.loopIfBeforeStart) { return true; } else if (curTime >= endTime) { //use a margin of one just in case time has skipped a bit past if ((curTime - endTime) < endMargin || opts.loopIfAfterEnd) { return true; } } } return false; }; var getStartTime = function () { return (opts.start === false) ? 0 : opts.start; }; var getEndTime = function () { return (opts.end === false) ? player.duration() : opts.end; }; var isLooping = false; var minLoopLength = (isNumber(initialOptions.minLoopLength) && initialOptions.minLoopLength > 0) ? initialOptions.minLoopLength : 200; //function run on time update by player var checkABLoop = function (e) { if (!isLooping && opts.enabled && !player.paused() && loopRequired()) { //prevents constant looping /*if (getStartTime() === getEndTime()){ player.pause(); }*/ //prevent looping happening to quickly in succession //this effectively sets a minimum loop time //if start time and end time are the same, we would get a loop of this length isLooping = true; setTimeout(function () { isLooping = false; }, minLoopLength); goToStartOfLoop(true); } }; // BUTTON THINGS var buttons = {}; //holds references to the button objects var buttonSpecs = [{ 'name': 'start', 'optionsUsed': ['start'], 'leftclick': function (api, event) { if (event.shiftKey) { api.adjustStart(-0.5); } else { api.setStart(); } }, 'rightclick': function (api, event) { if (event.shiftKey) { api.adjustStart(0.5); } else { api.goToStart(); } }, 'defaultText': 'Start', 'textFunction': function (opts) { return formatTimeWithMS(opts.start); } }, { 'name': 'end', 'optionsUsed': ['end'], 'leftclick': function (api, event) { if (event.shiftKey) { api.adjustEnd(-0.5); } else if (event.ctrlKey) { api.adjustEnd(-0.05); } else { api.setEnd(); } }, 'rightclick': function (api, event) { if (event.shiftKey) { api.adjustEnd(0.5); } else if (event.ctrlKey) { api.adjustEnd(0.05); } else { api.goToEnd(); } }, 'defaultText': 'End', 'textFunction': function (opts) { return formatTimeWithMS(opts.end); } }, { 'name': 'enabled', 'optionsUsed': ['enabled', 'pauseAfterLooping', 'pauseBeforeLooping'], 'leftclick': function (api, event) { var msg, url; if (window && window.prompt) { if (event.ctrlKey) { api.applyUrl(inputPrompt("Set new URL", api.getAbsoluteUrl())); } else if (event.altKey) { api.applyUrl(inputPrompt("Set new URL", api.getUrl())); } else if (event.shiftKey) { api.applyUrlFragment(inputPrompt("Set new URL fragment", api.getUrlFragment())); } else { api.toggle(); } } else { api.toggle(); } }, 'rightclick': function (api, event) { var msg; if (window && window.prompt) { if (event.ctrlKey) { msg = api.getAbsoluteUrl(); } else if (event.altKey) { msg = api.getUrl(); } else if (event.shiftKey) { msg = api.getUrlFragment(); } } if (msg) { clipboardPrompt(msg); } else { api.cyclePauseOnLooping(); } }, 'defaultText': 'Loop', 'textFunction': function (opts) { if (opts.enabled) { if (opts.pauseBeforeLooping && opts.pauseAfterLooping) { return 'PAUSE LOOP PAUSE'; } if (opts.pauseAfterLooping) { return 'LOOP& PAUSE'; } if (opts.pauseBeforeLooping) { return 'PAUSE &LOOP'; } return 'LOOP ON'; } else { return 'Loop off'; } } } ]; var clipboardPrompt = function (msg) { if (window && window.prompt) { window.prompt("Copy to clipboard: Ctrl+C, Enter", msg); } }; var inputPrompt = function (message, def) { if (window && window.prompt) { return window.prompt(message, def); } else { return false; } }; var createButton = function (spec, player) { //returns a function which handles button clicks, var clickFunction = function (abLoopCall, whichButton) { return function (event) { if (whichButton === undefined || (event.which && event.which == whichButton)) { abLoopCall(player.abLoopPlugin, event); this.updateText(); } }; }; //returns a function which handles button text updates var updateTextFunction = function (defaultText, textFunction) { return function () { var text = textFunction(opts) || defaultText; var el = this.el(); el.textContent = text; //el.innerText = text; //doesn't work in Firefox }; }; //create the button var b = player.controlBar.addChild('Button'); if (spec.leftclick) { b.on('click', clickFunction(spec.leftclick)); } if (spec.rightclick) { //event which //bind the function as it isn't bound by default b.el().onmousedown = clickFunction(spec.rightclick, 3).bind(b); //knock out the context menu b.on('contextmenu', function (event) { if (event.preventDefault) { event.preventDefault(); } if (event.preventDefault) { event.stopPropagation(); } return false; }); } //gets called when text on button needs updating b.updateText = updateTextFunction(spec.defaultText, spec.textFunction); b.optionsUsed = spec.optionsUsed; b.addClass('abLoopButton'); b.addClass(spec.name); b.updateText(); //set the initial text return b; }; //create the buttons based on the specs var createButtons = function (specs) { specs.forEach(function (spec) { //only create the button if it's not already there if (buttons[spec.name] === undefined) { buttons[spec.name] = createButton(spec, player); } }); }; //updates button displays if not already done var updateButtonText = function (changed) { var changedReducer = function (acc, optName) { return acc || changed[optName]; }; for (var buttonName in buttons) { var b = buttons[buttonName]; var needsUpdate = !(b.optionsUsed) || b.optionsUsed.reduce(changedReducer, false); if (needsUpdate) { b.updateText(); } } }; //functions etc to expose as API //those which change values can be passed through the notify function var api = { validateOptions: notify(validateOptions), resetToInitialOptions: notify(setOptionsToInitialOptions), setOptions: notify(setOptions), getOptions: getOptions, goToStart: goToStartOfLoop, goToEnd: goToEndOfLoop, setStart: notify(timeSetter('start'), { 'start': true }), setEnd: notify(timeSetter('end'), { 'end': true }), adjustStart: notify(timeAdjuster('start'), { 'start': true }), adjustEnd: notify(timeAdjuster('end'), { 'end': true }), enable: notify(enableLoop, { 'enabled': true }), disable: notify(disableLoop, { 'enabled': true }), toggle: notify(toggler('enabled'), { 'enabled': true }), togglePauseAfterLooping: notify(toggler('pauseAfterLooping'), { 'pauseAfterLooping': true }), togglePauseBeforeLooping: notify(toggler('pauseBeforeLooping'), { 'pauseBeforeLooping': true }), cyclePauseOnLooping: notify(cyclePauseOnLooping, { 'pauseBeforeLooping': true, 'pauseAfterLooping': true }), player: player, version: version, getAbsoluteUrl: getAbsoluteUrlWithHash, getUrl: getUrlWithHash, getUrlFragment: getUrlHash, applyUrl: notify(applyUrl, { 'start': true, 'end': true }), applyUrlFragment: notify(applyUrlHash, { 'start': true, 'end': true }), loopRequired: loopRequired //allows testing of conditions via API when player is paused , playLoop: notify(playLoop) }; //set up the plugin var setup = function () { defaultInitialOptions(); setCallBacksToInitialOptions(); //set options to initial options and notify of change notify(setOptionsToInitialOptions)(); player.ready(function () { //create buttons once the player is ready if (initialOptions.createButtons != false) { createButtons(buttonSpecs); } //if start time is greater than end, the video needs to loop on ending //this is indicated by the loopAtEndOfVideoRequired flag player.on('ended', function () { if (loopAtEndOfVideoRequired && opts.enabled && !player.loop()) { player.play(); } }); }); //this replaces the reference created to this function on each player object //with a reference to the api object (created once per invocation of this function) //The functions created in this function and referenced by api will still //be available via closure player.abLoopPlugin = api; //on timeupdate, check if we need to loop player.on('timeupdate', checkABLoop); api.loaded = true; }; setup(); return api; }; abLoopPlugin.loaded = false; abLoopPlugin.VERSION = version; var registerPlugin = videojs.registerPlugin || videojs.plugin; return registerPlugin('abLoopPlugin', abLoopPlugin); });
var spellingList = ["fit", "mad", "bus", "dots", "spy", "job", "row", "tree", "ship", "name", "ears", "room", "case", "meal", "rang", "tile", "lost", "aim", "nest", "tiny", "need", "darts", "straw", "maybe", "cried", "shell", "wash", "chew", "start", "first", "picky", "claws", "great", "stage", "open", "sadly", "brush", "cross", "hugged", "trail", "butter", "sharp", "digging", "soap", "bones", //problem "small", "center", //or "centre" "lava", "monster", //problem "bathtub", "ivy", "nose", "tusk", "road", "oven", "news", "food", "rules", "braid", "miles", "folds", "pages", "boring", "corner", //problem "ferns", "elbow", "taxi", "stuck", //problem "grain", "float", "awake", "bird", "snack", "wear", "mane", "hardly", "shirts", "moody", "lawn", "branch", "pantry", "sandbox", "posters", "spider", "coast", "bother", "mouse", "swift", "restless", "parents", "beehive", "shopping", "artwork", "chance", "lookout", "stroller", "anyone", "thumb", "backdrop", "fuddy-duddy" ]; var problemList = [ "bones", "monster", "corner", "stuck" ] var hasTTS = true; if ('speechSynthesis' in window) { //sweet. } else { hasTTS = false; alert("I'm sorry, your browser doesn't support a text-to-speech feature, so some words will be skipped. To access all the words, try Chrome v 33 or higher, Firefox v 49 or higher, Safari v 7 or higher, or Microsoft Edge v 38 or higher."); } var studyListArray = []; if (!window.localStorage) { alert("Sorry, we can't remember which word you're on when you leave this page. The next time you come back or reload the page it will start from the beginning."); } else if (localStorage.currentWordIndex === undefined) { localStorage.currentWordIndex = 0; localStorage.recordScore = 0; } if (window.localStorage) { if (!localStorage.studyListArray) { localStorage.studyListArray = ""; } else if (localStorage.studyListArray.length > 0) { studyListArray = localStorage.studyListArray.split(","); } } var currentWordIndex = localStorage.currentWordIndex; var word = ""; var tts; var usingTTS = false; var audio; var audioURL = ""; var hintLetter = 1; var loadaling; var chip = { tag: 'chip content', id: 1, //optional }; function preloader() { $("#play").addClass("disabled").html('<div class="preloader-wrapper small active valign-wrapper"><div class="spinner-layer spinner valign"><div class="circle-clipper left"><div class="circle"></div></div><div class="gap-patch"><div class="circle"></div></div><div class="circle-clipper right"><div class="circle"></div></div></div></div>'); loadaling = true; } function stopLoader() { $("#play").removeClass("disabled").html('<i class="large material-icons">play_arrow</i>'); loadaling = false; } var updateWord = function() { preloader(); word = spellingList[currentWordIndex]; localStorage.currentWordIndex = currentWordIndex; hintLetter = 1; } function getMerriamWebster() { updateWord(); usingTTS = false; var xhr = new XMLHttpRequest(); var url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/" + word + "?key=9ef9d420-7fba-449f-9167-bd807480798e"; xhr.onload = function(data) { var audioFilename = $(data).find("hw:contains(" + word + ") ~ sound wav").html(); console.log("wav =" + audioFilename); if (audioFilename === undefined || problemList.includes(word)) { if (hasTTS === false) { skipWord(); } else { usingTTS = true; console.log("using TTS"); tts = new SpeechSynthesisUtterance(word); } } else { var subdir = "" if (audioFilename.startsWith("bix")) { subdir = "bix/"; } else if (audioFilename.startsWith("gg")) { subdir = "gg/" } else if (parseInt(audioFilename.charAt(0)) === "number") { subdir = "number/" } else { subdir = audioFilename.charAt(0) + "/"; } audioURL = "http://media.merriam-webster.com/soundc11/" + subdir + audioFilename; console.log(audioURL); audio = new Audio(audioURL); } stopLoader(); } xhr.send(); // $.ajax({ // url: "http://crossorigin.me/http://www.dictionaryapi.com/api/v1/references/collegiate/xml/" + word + "?key=9ef9d420-7fba-449f-9167-bd807480798e", //maybe remove the crossorigin once I get this off Codepen // type: "GET", // contentType: "text/plain", // xhrFields: { // withCredentials: false // }, // dataType: "xml", // success: function(data) { // var audioFilename = $(data).find("hw:contains(" + word + ") ~ sound wav").html(); // console.log("wav =" + audioFilename); // if (audioFilename === undefined || problemList.includes(word)) { // if (hasTTS === false) { // skipWord(); // } else { // usingTTS = true; // console.log("using TTS"); // tts = new SpeechSynthesisUtterance(word); // } // } else { // var subdir = "" // if (audioFilename.startsWith("bix")) { // subdir = "bix/"; // } else if (audioFilename.startsWith("gg")) { // subdir = "gg/" // } else if (parseInt(audioFilename.charAt(0)) === "number") { // subdir = "number/" // } else { // subdir = audioFilename.charAt(0) + "/"; // } // audioURL = "http://media.merriam-webster.com/soundc11/" + subdir + audioFilename; // console.log(audioURL); // audio = new Audio(audioURL); // } // stopLoader(); // }, // error: function() { // alert("I'm sorry, there was an error. Try reloading?"); // } // }); // } } function updateRight() { var rightCount = $("#rightScore").html(); rightCount++; $("#rightScore").html(rightCount); } function updateWrong() { var wrongCount = $("#wrongScore").html(); wrongCount++; $("#wrongScore").html(wrongCount); if (studyListArray.includes(word)) { //do nuttin } else { studyListArray.push(word); localStorage.studyListArray = studyListArray; } } function updateRecord() { var recordCount = Number(localStorage.recordScore); recordCount++; $("#recordScore").html(recordCount); localStorage.recordScore = recordCount; } $("#play").click(function() { if (loadaling === false) { if (usingTTS === true) { window.speechSynthesis.speak(tts); } else { audio.play(); } $("#responseText").focus(); } else { //do nuttin } }); $("#response").submit(function(event) { event.preventDefault(); var response = $("#responseText").val(); if (word === spellingList[spellingList.length - 1]) { Materialize.toast("Yay!! You made it to the end of the list! Now you can click the 'restart' button to start again at the beginning.", 4000, "rounded"); updateRight(); updateRecord(); } else if (response === word) { Materialize.toast("That's right! You rock! Now click to hear the next word.", 4000, "rounded"); $("#responseText").val(""); updateRight(); updateRecord(); currentWordIndex++; getMerriamWebster(); } else { Materialize.toast("Sorry, that's not right. Try again!", 4000, "rounded"); updateWrong(); } }); $("#resetScore").click(function() { localStorage.recordScore = 0; $("#recordScore").html("0"); }); $("#hint").click(function() { Materialize.toast("It starts with: " + word.substring(0, hintLetter), 4000, "rounded"); hintLetter++; }); function skipWord() { currentWordIndex++; getMerriamWebster(); } $("#skip").click(function() { studyListArray.push(word); localStorage.studyListArray = studyListArray; skipWord(); }); $("#restart").click(function() { currentWordIndex = 0; getMerriamWebster(); }); $("#random").click(function() { currentWordIndex = Math.floor((Math.random() * 100) + 1); getMerriamWebster(); }); $("#study").click(function() { for (var i = 0; i < studyListArray.length; i++) { if (studyListArray[i] === "undefined" || studyListArray[i].length < 1 || $("#studyListWords").find("#" + studyListArray[i]).length) { continue; } else { $("#studyListWords").append('<div id="' + studyListArray[i] + '" class="chip">' + studyListArray[i] + '<i class="close material-icons">close</i></div>'); } } $('#studyList').openModal(); }); $("#studyListWords").on("click", ".chip", function() { studyListArray.splice(studyListArray.indexOf(this.id), 1); localStorage.studyListArray = studyListArray; }) $("#studyClear").click(function() { studyListArray = [] localStorage.studyListArray = ""; $("#studyListWords").html(""); }); $(document).ready(getMerriamWebster()); $(document).ready(function() { recordCount = Number(localStorage.recordScore); $("#recordScore").html(recordCount); localStorage.recordScore = recordCount; });
// Underscore.js 1.3.1 // (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc. // Underscore is freely distributable under the MIT license. // Portions of Underscore are inspired or borrowed from Prototype, // Oliver Steele's Functional, and John Resig's Micro-Templating. // For all details and documentation: // http://documentcloud.github.com/underscore (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `global` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Establish the object that gets returned to break out of a loop iteration. var breaker = {}; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var slice = ArrayProto.slice, unshift = ArrayProto.unshift, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeForEach = ArrayProto.forEach, nativeMap = ArrayProto.map, nativeReduce = ArrayProto.reduce, nativeReduceRight = ArrayProto.reduceRight, nativeFilter = ArrayProto.filter, nativeEvery = ArrayProto.every, nativeSome = ArrayProto.some, nativeIndexOf = ArrayProto.indexOf, nativeLastIndexOf = ArrayProto.lastIndexOf, nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { return new wrapper(obj); }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object via a string identifier, // for Closure Compiler "advanced" mode. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root['_'] = _; } // Current version. _.VERSION = '1.3.1'; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles objects with the built-in `forEach`, arrays, and raw objects. // Delegates to **ECMAScript 5**'s native `forEach` if available. var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return; } } else { for (var key in obj) { if (_.has(obj, key)) { if (iterator.call(context, obj[key], key, obj) === breaker) return; } } } }; // Return the results of applying the iterator to each element. // Delegates to **ECMAScript 5**'s native `map` if available. _.map = _.collect = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); each(obj, function(value, index, list) { results[results.length] = iterator.call(context, value, index, list); }); if (obj.length === +obj.length) results.length = obj.length; return results; }; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduce && obj.reduce === nativeReduce) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); } each(obj, function(value, index, list) { if (!initial) { memo = value; initial = true; } else { memo = iterator.call(context, memo, value, index, list); } }); if (!initial) throw new TypeError('Reduce of empty array with no initial value'); return memo; }; // The right-associative version of reduce, also known as `foldr`. // Delegates to **ECMAScript 5**'s native `reduceRight` if available. _.reduceRight = _.foldr = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); } var reversed = _.toArray(obj).reverse(); if (context && !initial) iterator = _.bind(iterator, context); return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator); }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, iterator, context) { var result; any(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Delegates to **ECMAScript 5**'s native `filter` if available. // Aliased as `select`. _.filter = _.select = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); each(obj, function(value, index, list) { if (iterator.call(context, value, index, list)) results[results.length] = value; }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, iterator, context) { var results = []; if (obj == null) return results; each(obj, function(value, index, list) { if (!iterator.call(context, value, index, list)) results[results.length] = value; }); return results; }; // Determine whether all of the elements match a truth test. // Delegates to **ECMAScript 5**'s native `every` if available. // Aliased as `all`. _.every = _.all = function(obj, iterator, context) { var result = true; if (obj == null) return result; if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); each(obj, function(value, index, list) { if (!(result = result && iterator.call(context, value, index, list))) return breaker; }); return result; }; // Determine if at least one element in the object matches a truth test. // Delegates to **ECMAScript 5**'s native `some` if available. // Aliased as `any`. var any = _.some = _.any = function(obj, iterator, context) { iterator || (iterator = _.identity); var result = false; if (obj == null) return result; if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); each(obj, function(value, index, list) { if (result || (result = iterator.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if a given value is included in the array or object using `===`. // Aliased as `contains`. _.include = _.contains = function(obj, target) { var found = false; if (obj == null) return found; if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; found = any(obj, function(value) { return value === target; }); return found; }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); return _.map(obj, function(value) { return (_.isFunction(method) ? method || value : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, function(value){ return value[key]; }); }; // Return the maximum element or (element-based computation). _.max = function(obj, iterator, context) { if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj); if (!iterator && _.isEmpty(obj)) return -Infinity; var result = {computed : -Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed >= result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Return the minimum element (or element-based computation). _.min = function(obj, iterator, context) { if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj); if (!iterator && _.isEmpty(obj)) return Infinity; var result = {computed : Infinity}; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; computed < result.computed && (result = {value : value, computed : computed}); }); return result.value; }; // Shuffle an array. _.shuffle = function(obj) { var shuffled = [], rand; each(obj, function(value, index, list) { if (index == 0) { shuffled[0] = value; } else { rand = Math.floor(Math.random() * (index + 1)); shuffled[index] = shuffled[rand]; shuffled[rand] = value; } }); return shuffled; }; // Sort the object's values by a criterion produced by an iterator. _.sortBy = function(obj, iterator, context) { return _.pluck(_.map(obj, function(value, index, list) { return { value : value, criteria : iterator.call(context, value, index, list) }; }).sort(function(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; }), 'value'); }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = function(obj, val) { var result = {}; var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; }; each(obj, function(value, index) { var key = iterator(value, index); (result[key] || (result[key] = [])).push(value); }); return result; }; // Use a comparator function to figure out at what index an object should // be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iterator) { iterator || (iterator = _.identity); var low = 0, high = array.length; while (low < high) { var mid = (low + high) >> 1; iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid; } return low; }; // Safely convert anything iterable into a real, live array. _.toArray = function(iterable) { if (!iterable) return []; if (iterable.toArray) return iterable.toArray(); if (_.isArray(iterable)) return slice.call(iterable); if (_.isArguments(iterable)) return slice.call(iterable); return _.values(iterable); }; // Return the number of elements in an object. _.size = function(obj) { return _.toArray(obj).length; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head`. The **guard** check allows it to work // with `_.map`. _.first = _.head = function(array, n, guard) { return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; }; // Returns everything but the last entry of the array. Especcialy useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if ((n != null) && !guard) { return slice.call(array, Math.max(array.length - n, 0)); } else { return array[array.length - 1]; } }; // Returns everything but the first entry of the array. Aliased as `tail`. // Especially useful on the arguments object. Passing an **index** will return // the rest of the values in the array from that index onward. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = function(array, index, guard) { return slice.call(array, (index == null) || guard ? 1 : index); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, function(value){ return !!value; }); }; // Return a completely flattened version of an array. _.flatten = function(array, shallow) { return _.reduce(array, function(memo, value) { if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value)); memo[memo.length] = value; return memo; }, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iterator) { var initial = iterator ? _.map(array, iterator) : array; var result = []; _.reduce(initial, function(memo, el, i) { if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) { memo[memo.length] = el; result[result.length] = array[i]; } return memo; }, []); return result; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(_.flatten(arguments, true)); }; // Produce an array that contains every item shared between all the // passed-in arrays. (Aliased as "intersect" for back-compat.) _.intersection = _.intersect = function(array) { var rest = slice.call(arguments, 1); return _.filter(_.uniq(array), function(item) { return _.every(rest, function(other) { return _.indexOf(other, item) >= 0; }); }); }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = _.flatten(slice.call(arguments, 1)); return _.filter(array, function(value){ return !_.include(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function() { var args = slice.call(arguments); var length = _.max(_.pluck(args, 'length')); var results = new Array(length); for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i); return results; }; // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), // we need this function. Return the position of the first occurrence of an // item in an array, or -1 if the item is not included in the array. // Delegates to **ECMAScript 5**'s native `indexOf` if available. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i, l; if (isSorted) { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item); for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i; return -1; }; // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. _.lastIndexOf = function(array, item) { if (array == null) return -1; if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item); var i = array.length; while (i--) if (i in array && array[i] === item) return i; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = arguments[2] || 1; var len = Math.max(Math.ceil((stop - start) / step), 0); var idx = 0; var range = new Array(len); while(idx < len) { range[idx++] = start; start += step; } return range; }; // Function (ahem) Functions // ------------------ // Reusable constructor function for prototype setting. var ctor = function(){}; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Binding with arguments is also known as `curry`. // Delegates to **ECMAScript 5**'s native `Function.bind` if available. // We check for `func.bind` first, to fail fast when `func` is undefined. _.bind = function bind(func, context) { var bound, args; if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError; args = slice.call(arguments, 2); return bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); ctor.prototype = func.prototype; var self = new ctor; var result = func.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) return result; return self; }; }; // Bind all of an object's methods to that object. Useful for ensuring that // all callbacks defined on an object belong to it. _.bindAll = function(obj) { var funcs = slice.call(arguments, 1); if (funcs.length == 0) funcs = _.functions(obj); each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memo = {}; hasher || (hasher = _.identity); return function() { var key = hasher.apply(this, arguments); return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); }; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(func, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. _.throttle = function(func, wait) { var context, args, timeout, throttling, more; var whenDone = _.debounce(function(){ more = throttling = false; }, wait); return function() { context = this; args = arguments; var later = function() { timeout = null; if (more) func.apply(context, args); whenDone(); }; if (!timeout) timeout = setTimeout(later, wait); if (throttling) { more = true; } else { func.apply(context, args); } whenDone(); throttling = true; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. _.debounce = function(func, wait) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; func.apply(context, args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = function(func) { var ran = false, memo; return function() { if (ran) return memo; ran = true; return memo = func.apply(this, arguments); }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return function() { var args = [func].concat(slice.call(arguments, 0)); return wrapper.apply(this, args); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var funcs = arguments; return function() { var args = arguments; for (var i = funcs.length - 1; i >= 0; i--) { args = [funcs[i].apply(this, args)]; } return args[0]; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { if (times <= 0) return func(); return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = nativeKeys || function(obj) { if (obj !== Object(obj)) throw new TypeError('Invalid object'); var keys = []; for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key; return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { return _.map(obj, _.identity); }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { each(slice.call(arguments, 1), function(source) { for (var prop in source) { obj[prop] = source[prop]; } }); return obj; }; // Fill in a given object with default properties. _.defaults = function(obj) { each(slice.call(arguments, 1), function(source) { for (var prop in source) { if (obj[prop] == null) obj[prop] = source[prop]; } }); return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function. function eq(a, b, stack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. if (a === b) return a !== 0 || 1 / a == 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a._chain) a = a._wrapped; if (b._chain) b = b._wrapped; // Invoke a custom `isEqual` method if one is provided. if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b); if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a); // Compare `[[Class]]` names. var className = toString.call(a); if (className != toString.call(b)) return false; switch (className) { // Strings, numbers, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return a == String(b); case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a == +b; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = stack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (stack[length] == a) return true; } // Add the first object to the stack of traversed objects. stack.push(a); var size = 0, result = true; // Recursively compare objects and arrays. if (className == '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size == b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { // Ensure commutative equality for sparse arrays. if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break; } } } else { // Objects with different constructors are not equivalent. if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false; // Deep compare objects. for (var key in a) { if (_.has(a, key)) { // Count the expected number of properties. size++; // Deep compare each member. if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break; } } // Ensure that both objects contain the same number of properties. if (result) { for (key in b) { if (_.has(b, key) && !(size--)) break; } result = !size; } } // Remove the first object from the stack of traversed objects. stack.pop(); return result; } // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType == 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) == '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { return obj === Object(obj); }; // Is a given variable an arguments object? _.isArguments = function(obj) { return toString.call(obj) == '[object Arguments]'; }; if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return !!(obj && _.has(obj, 'callee')); }; } // Is a given value a function? _.isFunction = function(obj) { return toString.call(obj) == '[object Function]'; }; // Is a given value a string? _.isString = function(obj) { return toString.call(obj) == '[object String]'; }; // Is a given value a number? _.isNumber = function(obj) { return toString.call(obj) == '[object Number]'; }; // Is the given value `NaN`? _.isNaN = function(obj) { // `NaN` is the only value for which `===` is not reflexive. return obj !== obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; }; // Is a given value a date? _.isDate = function(obj) { return toString.call(obj) == '[object Date]'; }; // Is the given value a regular expression? _.isRegExp = function(obj) { return toString.call(obj) == '[object RegExp]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Has own property? _.has = function(obj, key) { return hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iterators. _.identity = function(value) { return value; }; // Run a function **n** times. _.times = function (n, iterator, context) { for (var i = 0; i < n; i++) iterator.call(context, i); }; // Escape a string for HTML interpolation. _.escape = function(string) { return (''+string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;'); }; // Add your own custom functions to the Underscore object, ensuring that // they're correctly added to the OOP wrapper as well. _.mixin = function(obj) { each(_.functions(obj), function(name){ addToWrapper(name, _[name] = obj[name]); }); }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = idCounter++; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /.^/; // Within an interpolation, evaluation, or escaping, remove HTML escaping // that had been previously added. var unescape = function(code) { return code.replace(/\\\\/g, '\\').replace(/\\'/g, "'"); }; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. _.template = function(str, data) { var c = _.templateSettings; var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' + 'with(obj||{}){__p.push(\'' + str.replace(/\\/g, '\\\\') .replace(/'/g, "\\'") .replace(c.escape || noMatch, function(match, code) { return "',_.escape(" + unescape(code) + "),'"; }) .replace(c.interpolate || noMatch, function(match, code) { return "'," + unescape(code) + ",'"; }) .replace(c.evaluate || noMatch, function(match, code) { return "');" + unescape(code).replace(/[\r\n\t]/g, ' ') + ";__p.push('"; }) .replace(/\r/g, '\\r') .replace(/\n/g, '\\n') .replace(/\t/g, '\\t') + "');}return __p.join('');"; var func = new Function('obj', '_', tmpl); if (data) return func(data, _); return function(data) { return func.call(this, data, _); }; }; // Add a "chain" function, which will delegate to the wrapper. _.chain = function(obj) { return _(obj).chain(); }; // The OOP Wrapper // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. var wrapper = function(obj) { this._wrapped = obj; }; // Expose `wrapper.prototype` as `_.prototype` _.prototype = wrapper.prototype; // Helper function to continue chaining intermediate results. var result = function(obj, chain) { return chain ? _(obj).chain() : obj; }; // A method to easily add functions to the OOP wrapper. var addToWrapper = function(name, func) { wrapper.prototype[name] = function() { var args = slice.call(arguments); unshift.call(args, this._wrapped); return result(func.apply(_, args), this._chain); }; }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; wrapper.prototype[name] = function() { var wrapped = this._wrapped; method.apply(wrapped, arguments); var length = wrapped.length; if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0]; return result(wrapped, this._chain); }; }); // Add all accessor Array functions to the wrapper. each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; wrapper.prototype[name] = function() { return result(method.apply(this._wrapped, arguments), this._chain); }; }); // Start chaining a wrapped Underscore object. wrapper.prototype.chain = function() { this._chain = true; return this; }; // Extracts the result from a wrapped and chained object. wrapper.prototype.value = function() { return this._wrapped; }; module.exports = _; }).call(this);
/* * Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) * * openAUSIAS: The stunning micro-library that helps you to develop easily * AJAX web applications by using Java and jQuery * openAUSIAS is distributed under the MIT License (MIT) * Sources at https://github.com/rafaelaznar/ * * 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. * */ 'use strict'; moduloEmpleado.controller('EmpleadoEditController', ['$scope', '$routeParams', '$location', 'serverService', 'sharedSpaceService', '$filter', function ($scope, $routeParams, $location, serverService, sharedSpaceService, $filter) { $scope.obj = null; $scope.id = $routeParams.id; $scope.ob = 'empleado'; $scope.op = 'edit'; $scope.result = null; $scope.title = "Edición de empleado"; $scope.icon = "fa-users"; if (sharedSpaceService.getFase() == 0) { serverService.getDataFromPromise(serverService.promise_getOne($scope.ob, $scope.id)).then(function (data) { $scope.obj = data.message; //date conversion $scope.obj.fechaNa = serverService.date_toDate($scope.obj.fechaNa); }); } else { $scope.obj = sharedSpaceService.getObject(); sharedSpaceService.setFase(0); } $scope.chooseOne = function (foreignObjectName) { sharedSpaceService.setObject($scope.obj); sharedSpaceService.setReturnLink('/' + $scope.ob + '/' + $scope.op + '/' + $scope.id); sharedSpaceService.setFase(1); $location.path('/' + foreignObjectName + '/selection/1/10'); } $scope.save = function () { var dateFechaNaAsString = $filter('date')($scope.obj.fechaNa, "dd/MM/yyyy"); $scope.obj.fechaNa = dateFechaNaAsString; serverService.getDataFromPromise(serverService.promise_setOne($scope.ob, {json: JSON.stringify(serverService.array_identificarArray($scope.obj))})).then(function (data) { $scope.result = data; }); }; $scope.$watch('obj.obj_tipoempleado.id', function () { if ($scope.obj) { serverService.getDataFromPromise(serverService.promise_getOne('tipoempleado', $scope.obj.obj_tipoempleado.id)).then(function (data2) { $scope.obj.obj_tipoempleado = data2.message; }); } }); $scope.back = function () { window.history.back(); }; $scope.close = function () { $location.path('/home'); }; $scope.plist = function () { $location.path('/empleado/plist'); }; //datepicker $scope.open1 = function () { $scope.popup1.opened = true; }; $scope.popup1 = { opened: false }; $scope.disabled = function (date, mode) { return mode === 'day' && (date.getDay() === 0 || date.getDay() === 6); }; $scope.dateOptions = { formatYear: 'yyyy', startingDay: 1 }; $scope.open2 = function () { $scope.popup2.opened = true; }; $scope.popup2 = { opened: false }; }]);
var chai = require('chai'); var expect = chai.expect; describe('Server test', function(){ it('Pass everything is okay', function(){ expect(true).to.be.true; }); });
import React from "react"; import { Card } from 'material-ui/Card'; import { CardActions } from 'material-ui/Card'; import FlatButton from 'material-ui/FlatButton'; import { List, ListItem } from 'material-ui/List'; function UsersPage(props) { return ( <div> <Card className="usersList"> <CardActions> <List> <ListItem leftAvatar={props.image} style={{ width: '1000px', height: '80px' }} primaryText={props.firstName + " " + props.lastName} secondaryText={'email: ' + props.email + ' телефон: ' + props.phone + ' админ: ' + props.admin} /> </List> <FlatButton label="Подробнее" href={"admin/users/" + props.id} /> </CardActions> </Card> </div> ) } export default UsersPage;
var _; //globals describe("About Applying What We Have Learnt", function() { var products; beforeEach(function () { products = [ { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false }, { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false }, { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false }, { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true }, { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true } ]; }); /*********************************************************************************/ it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () { var i,j,hasMushrooms, productsICanEat = []; for (i = 0; i < products.length; i+=1) { if (products[i].containsNuts === false) { hasMushrooms = false; for (j = 0; j < products[i].ingredients.length; j+=1) { if (products[i].ingredients[j] === "mushrooms") { hasMushrooms = true; } } if (!hasMushrooms) productsICanEat.push(products[i]); } } expect(productsICanEat.length).toBe(1); }); it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () { var productsICanEat = _(products).filter(function (x) { return !(x.containsNuts) && _(x.ingredients).all(function (y) { return y !== "mushrooms"}) }); /* solve using filter() & all() / any() */ expect(productsICanEat.length).toBe(1); }); /*********************************************************************************/ it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () { var sum = 0; for(var i=1; i<1000; i+=1) { if (i % 3 === 0 || i % 5 === 0) { sum += i; } } expect(sum).toBe(233168); }); it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () { var sum = (_.range(1000)) .filter(function (num) { return num % 3 === 0 || num % 5 ===0 }) .reduce(function (sum, x) { return sum + x}); /* try chaining range() and reduce() */ expect(233168).toBe(sum); }); /*********************************************************************************/ it("should count the ingredient occurrence (imperative)", function () { var ingredientCount = { "{ingredient name}": 0 }; for (i = 0; i < products.length; i+=1) { for (j = 0; j < products[i].ingredients.length; j+=1) { ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1; } } expect(ingredientCount['mushrooms']).toBe(2); }); it("should count the ingredient occurrence (functional)", function () { var ingredientCount = { "{ingredient name}": 0 }; _(products).chain() .map(function (x) { return x.ingredients } ) .flatten() .reduce(function (count, name) { ingredientCount[name] = (ingredientCount[name] || 0 ) + 1; }); /* Not sure about this one :) */ /* chain() together map(), flatten() and reduce() */ expect(ingredientCount['mushrooms']).toBe(2); }); /*********************************************************************************/ /* UNCOMMENT FOR EXTRA CREDIT */ /* it("should find the largest prime factor of a composite number", function () { }); it("should find the largest palindrome made from the product of two 3 digit numbers", function () { }); it("should find the smallest number divisible by each of the numbers 1 to 20", function () { }); it("should find the difference between the sum of the squares and the square of the sums", function () { }); it("should find the 10001st prime", function () { }); */ });
/** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE_AFL.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category design * @package base_default * @copyright Copyright (c) 2006-2019 Magento, Inc. (http://www.magento.com) * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) */ /** * Controller of order review form that may select shipping method */ OrderReviewController = Class.create(); OrderReviewController.prototype = { _canSubmitOrder : false, _pleaseWait : false, shippingSelect : false, reloadByShippingSelect : false, _copyElement : false, onSubmitShippingSuccess : false, shippingMethodsUpdateUrl : false, _updateShippingMethods: false, _ubpdateOrderButton : false, shippingMethodsContainer: false, _submitUpdateOrderUrl : false, _itemsGrid : false, /** * Add listeners to provided objects, if any * @param orderForm - form of the order submission * @param orderFormSubmit - element for the order form submission (optional) * @param shippingSelect - dropdown with available shipping methods (optional) * @param shippingSubmitForm - form of shipping method submission (optional, requires shippingSelect) * @param shippingResultId - element where to update results of shipping ajax submission (optional, requires shippingSubmitForm) */ initialize : function(orderForm, orderFormSubmit, shippingSelect, shippingSubmitForm, shippingResultId, shippingSubmit) { if (!orderForm) { return; } this.form = orderForm; if (orderFormSubmit) { this.formSubmit = orderFormSubmit; Event.observe(orderFormSubmit, 'click', this._submitOrder.bind(this)); } if (shippingSubmitForm) { this.reloadByShippingSelect = true; if (shippingSubmitForm && shippingSelect) { this.shippingSelect = shippingSelect; Event.observe( shippingSelect, 'change', this._submitShipping.bindAsEventListener(this, shippingSubmitForm.action, shippingResultId) ); this._updateOrderSubmit(false); } else { this._canSubmitOrder = true; } } else { Form.getElements(this.form).each(this._bindElementChange, this); if (shippingSelect && $(shippingSelect)) { this.shippingSelect = $(shippingSelect).id; this.shippingMethodsContainer = $(this.shippingSelect).up(); } else { this.shippingSelect = shippingSelect; } this._updateOrderSubmit(false); } }, /** * Register element that should show up when ajax request is in progress * @param element */ addPleaseWait : function(element) { if (element) { this._pleaseWait = element; } }, /** * Dispatch an ajax request of shipping method submission * @param event * @param url - url where to submit shipping method * @param resultId - id of element to be updated */ _submitShipping : function(event, url, resultId) { if (this.shippingSelect && url && resultId) { this._updateOrderSubmit(true); if (this._pleaseWait) { this._pleaseWait.show(); } if ('' != this.shippingSelect.value) { new Ajax.Updater(resultId, url, { parameters: {isAjax:true, shipping_method:this.shippingSelect.value}, onComplete: function() { if (this._pleaseWait) { this._pleaseWait.hide(); } }.bind(this), onSuccess: this._onSubmitShippingSuccess.bind(this), evalScripts: true }); } } }, /** * Set event observer to Update Order button * @param element * @param url - url to submit on Update button * @param resultId - id of element to be updated */ setUpdateButton : function(element, url, resultId) { if (element) { this._ubpdateOrderButton = element; this._submitUpdateOrderUrl = url; this._itemsGrid = resultId; Event.observe(element, 'click', this._submitUpdateOrder.bindAsEventListener(this, url, resultId)); if(this.shippingSelect) { this._updateShipping(); } this._updateOrderSubmit(!this._validateForm()); this.formValidator.reset(); this._clearValidation(''); } }, /** * Set event observer to copy data from shipping address to billing * @param element */ setCopyElement : function(element) { if (element) { this._copyElement = element; Event.observe(element, 'click', this._copyShippingToBilling.bind(this)); this._copyShippingToBilling(); } }, /** * Set observers to Shipping Address elements * @param element Container of Shipping Address elements */ setShippingAddressContainer: function(element) { if (element) { Form.getElements(element).each(function(input) { if (input.type.toLowerCase() == 'radio' || input.type.toLowerCase() == 'checkbox') { Event.observe(input, 'click', this._onShippingChange.bindAsEventListener(this)); } else { Event.observe(input, 'change', this._onShippingChange.bindAsEventListener(this)); } }, this); } }, /** * Sets Container element of Shipping Method * @param element Container element of Shipping Method */ setShippingMethodContainer: function(element) { if (element) { this.shippingMethodsContainer = element; } }, /** * Copy element value from shipping to billing address * @param el */ _copyElementValue: function(el) { var newId = el.id.replace('shipping:','billing:'); if (newId && $(newId) && $(newId).type != 'hidden') { $(newId).value = el.value; $(newId).setAttribute('readOnly', 'readonly'); $(newId).addClassName('local-validation'); $(newId).setStyle({opacity:.5}); $(newId).disable(); } }, /** * Copy data from shipping address to billing */ _copyShippingToBilling : function (event) { if (!this._copyElement) { return; } if (this._copyElement.checked) { this._copyElementValue($('shipping:country_id')); billingRegionUpdater.update(); $$('[id^="shipping:"]').each(this._copyElementValue); this._clearValidation('billing'); } else { $$('[id^="billing:"]').invoke('enable'); $$('[id^="billing:"]').each(function(el){el.removeAttribute("readOnly");}); $$('[id^="billing:"]').invoke('removeClassName', 'local-validation'); $$('[id^="billing:"]').invoke('setStyle', {opacity:1}); } if (event) { this._updateOrderSubmit(true); } }, /** * Dispatch an ajax request of Update Order submission * @param url - url where to submit shipping method * @param resultId - id of element to be updated */ _submitUpdateOrder : function(event, url, resultId) { this._copyShippingToBilling(); if (url && resultId && this._validateForm()) { if (this._copyElement && this._copyElement.checked) { this._clearValidation('billing'); } this._updateOrderSubmit(true); if (this._pleaseWait) { this._pleaseWait.show(); } this._toggleButton(this._ubpdateOrderButton, true); arr = $$('[id^="billing:"]').invoke('enable'); var formData = this.form.serialize(true); if (this._copyElement.checked) { $$('[id^="billing:"]').invoke('disable'); this._copyElement.enable(); } formData.isAjax = true; new Ajax.Updater(resultId, url, { parameters: formData, onComplete: function() { if (this._pleaseWait && !this._updateShippingMethods) { this._pleaseWait.hide(); } this._toggleButton(this._ubpdateOrderButton, false); }.bind(this), onSuccess: this._updateShippingMethodsElement.bind(this), evalScripts: true }); } else { if (this._copyElement && this._copyElement.checked) { this._clearValidation('billing'); } } }, /** * Update Shipping Methods Element from server */ _updateShippingMethodsElement : function (){ if (this._updateShippingMethods ) { new Ajax.Updater($(this.shippingMethodsContainer).up(), this.shippingMethodsUpdateUrl, { onComplete: this._updateShipping.bind(this), onSuccess: this._onSubmitShippingSuccess.bind(this), evalScripts: false }); } else { this._onSubmitShippingSuccess(); } }, /** * Update Shipping Method select element and bind events */ _updateShipping : function () { if ($(this.shippingSelect)) { $(this.shippingSelect).enable(); Event.stopObserving($(this.shippingSelect), 'change'); this._bindElementChange($(this.shippingSelect)); Event.observe( $(this.shippingSelect), 'change', this._submitUpdateOrder.bindAsEventListener(this, this._submitUpdateOrderUrl, this._itemsGrid) ); $(this.shippingSelect + '_update').hide(); $(this.shippingSelect).show(); } this._updateShippingMethods = false; if (this._pleaseWait) { this._pleaseWait.hide(); } }, /** * Validate Order form */ _validateForm : function() { if (!this.form) { return false; } if (!this.formValidator) { this.formValidator = new Validation(this.form); } return this.formValidator.validate(); }, /** * Actions on change Shipping Address data * @param event */ _onShippingChange : function(event){ var element = Event.element(event); if (element != $(this.shippingSelect) && !($(this.shippingSelect) && $(this.shippingSelect).disabled)) { if ($(this.shippingSelect)) { $(this.shippingSelect).disable(); $(this.shippingSelect).hide(); if ($('advice-required-entry-' + this.shippingSelect)) { $('advice-required-entry-' + this.shippingSelect).hide(); } } if (this.shippingMethodsContainer && $(this.shippingMethodsContainer)) { $(this.shippingMethodsContainer).hide(); } if (this.shippingSelect && $(this.shippingSelect + '_update')) { $(this.shippingSelect + '_update').show(); } this._updateShippingMethods = true; } }, /** * Bind onChange event listener to elements for update Submit Order button state * @param input */ _bindElementChange : function(input){ Event.observe(input, 'change', this._onElementChange.bindAsEventListener(this)); }, /** * Disable Submit Order button */ _onElementChange : function(){ this._updateOrderSubmit(true); }, /** * Clear validation result for all form elements or for elements with id prefix * @param idprefix */ _clearValidation : function(idprefix) { var prefix = ''; if (idprefix) { prefix = '[id*="' + idprefix + ':"]'; $$(prefix).each(function(el){ el.up().removeClassName('validation-failed') .removeClassName('validation-passed') .removeClassName('validation-error'); }); } else { this.formValidator.reset(); } $$('.validation-advice' + prefix).invoke('remove'); $$('.validation-failed' + prefix).invoke('removeClassName', 'validation-failed'); $$('.validation-passed' + prefix).invoke('removeClassName', 'validation-passed'); $$('.validation-error' + prefix).invoke('removeClassName', 'validation-error'); }, /** * Attempt to submit order */ _submitOrder : function() { if (this._canSubmitOrder && (this.reloadByShippingSelect || this._validateForm())) { this.form.submit(); this._updateOrderSubmit(true); if (this._ubpdateOrderButton) { this._ubpdateOrderButton.addClassName('no-checkout'); this._ubpdateOrderButton.setStyle({opacity:.5}); } if (this._pleaseWait) { this._pleaseWait.show(); } return; } this._updateOrderSubmit(true); }, /** * Explicitly enable order submission */ _onSubmitShippingSuccess : function() { this._updateOrderSubmit(false); if (this.onSubmitShippingSuccess) { this.onSubmitShippingSuccess(); } }, /** * Check/Set whether order can be submitted * Also disables form submission element, if any * @param shouldDisable - whether should prevent order submission explicitly */ _updateOrderSubmit : function(shouldDisable) { var isDisabled = shouldDisable || ( this.reloadByShippingSelect && (!this.shippingSelect || '' == this.shippingSelect.value) ); this._canSubmitOrder = !isDisabled; if (this.formSubmit) { this._toggleButton(this.formSubmit, isDisabled); } }, /** * Enable/Disable button * * @param button * @param disable */ _toggleButton : function(button, disable) { button.disabled = disable; button.removeClassName('no-checkout'); button.setStyle({opacity:1}); if (disable) { button.addClassName('no-checkout'); button.setStyle({opacity:.5}); } } };
/** * This is a shorter version of Mathias Bynens' HTMLEntities map. * It is no longer compressed as of v0.4.1, * since it's no longer needed on the client side */ module.exports = { "Á": [ "Aacute" ], "á": [ "aacute" ], "Ă": [ "Abreve" ], "ă": [ "abreve" ], "∾": [ "ac", "mstpos" ], "∿": [ "acd" ], "∾̳": [ "acE" ], "Â": [ "Acirc" ], "â": [ "acirc" ], "´": [ "acute", "DiacriticalAcute" ], "А": [ "Acy" ], "а": [ "acy" ], "Æ": [ "AElig" ], "æ": [ "aelig" ], "⁡": [ "af", "ApplyFunction" ], "𝔄": [ "Afr" ], "𝔞": [ "afr" ], "À": [ "Agrave" ], "à": [ "agrave" ], "ℵ": [ "alefsym", "aleph" ], "Α": [ "Alpha" ], "α": [ "alpha" ], "Ā": [ "Amacr" ], "ā": [ "amacr" ], "⨿": [ "amalg" ], "&": [ false, "amp", "AMP" ], "⩕": [ "andand" ], "⩓": [ "And" ], "∧": [ "and", "wedge" ], "⩜": [ "andd" ], "⩘": [ "andslope" ], "⩚": [ "andv" ], "∠": [ "ang", "angle" ], "⦤": [ "ange" ], "⦨": [ "angmsdaa" ], "⦩": [ "angmsdab" ], "⦪": [ "angmsdac" ], "⦫": [ "angmsdad" ], "⦬": [ "angmsdae" ], "⦭": [ "angmsdaf" ], "⦮": [ "angmsdag" ], "⦯": [ "angmsdah" ], "∡": [ "angmsd", "measuredangle" ], "∟": [ "angrt" ], "⊾": [ "angrtvb" ], "⦝": [ "angrtvbd" ], "∢": [ "angsph" ], "Å": [ "angst", "Aring" ], "⍼": [ "angzarr" ], "Ą": [ "Aogon" ], "ą": [ "aogon" ], "𝔸": [ "Aopf" ], "𝕒": [ "aopf" ], "⩯": [ "apacir" ], "≈": [ "ap", "approx", "asymp", "thickapprox", "thkap", "TildeTilde" ], "⩰": [ "apE" ], "≊": [ "ape", "approxeq" ], "≋": [ "apid" ], "'": [ "apos" ], "å": [ "aring" ], "𝒜": [ "Ascr" ], "𝒶": [ "ascr" ], "≔": [ "Assign", "colone", "coloneq" ], "*": [ "ast", "midast" ], "≍": [ "asympeq", "CupCap" ], "Ã": [ "Atilde" ], "ã": [ "atilde" ], "Ä": [ "Auml" ], "ä": [ "auml" ], "∳": [ "awconint", "CounterClockwiseContourIntegral" ], "⨑": [ "awint" ], "≌": [ "backcong", "bcong" ], "϶": [ "backepsilon", "bepsi" ], "‵": [ "backprime", "bprime" ], "∽": [ "backsim", "bsim" ], "⋍": [ "backsimeq", "bsime" ], "∖": [ "Backslash", "setminus", "setmn", "smallsetminus", "ssetmn" ], "⫧": [ "Barv" ], "⊽": [ "barvee" ], "⌅": [ "barwed", "barwedge" ], "⌆": [ "Barwed", "doublebarwedge" ], "⎵": [ "bbrk", "UnderBracket" ], "⎶": [ "bbrktbrk" ], "Б": [ "Bcy" ], "б": [ "bcy" ], "„": [ "bdquo", "ldquor" ], "∵": [ "becaus", "because", "Because" ], "⦰": [ "bemptyv" ], "ℬ": [ "bernou", "Bernoullis", "Bscr" ], "Β": [ "Beta" ], "β": [ "beta" ], "ℶ": [ "beth" ], "≬": [ "between", "twixt" ], "𝔅": [ "Bfr" ], "𝔟": [ "bfr" ], "⋂": [ "bigcap", "Intersection", "xcap" ], "◯": [ "bigcirc", "xcirc" ], "⋃": [ "bigcup", "Union", "xcup" ], "⨀": [ "bigodot", "xodot" ], "⨁": [ "bigoplus", "xoplus" ], "⨂": [ "bigotimes", "xotime" ], "⨆": [ "bigsqcup", "xsqcup" ], "★": [ "bigstar", "starf" ], "▽": [ "bigtriangledown", "xdtri" ], "△": [ "bigtriangleup", "xutri" ], "⨄": [ "biguplus", "xuplus" ], "⋁": [ "bigvee", "Vee", "xvee" ], "⋀": [ "bigwedge", "Wedge", "xwedge" ], "⤍": [ "bkarow", "rbarr" ], "⧫": [ "blacklozenge", "lozf" ], "▪": [ "blacksquare", "FilledVerySmallSquare", "squarf", "squf" ], "▴": [ "blacktriangle", "utrif" ], "▾": [ "blacktriangledown", "dtrif" ], "◂": [ "blacktriangleleft", "ltrif" ], "▸": [ "blacktriangleright", "rtrif" ], "␣": [ "blank" ], "▒": [ "blk12" ], "░": [ "blk14" ], "▓": [ "blk34" ], "█": [ "block" ], "=⃥": [ "bne" ], "≡⃥": [ "bnequiv" ], "⫭": [ "bNot" ], "⌐": [ "bnot" ], "𝔹": [ "Bopf" ], "𝕓": [ "bopf" ], "⊥": [ "bot", "bottom", "perp", "UpTee" ], "⋈": [ "bowtie" ], "⧉": [ "boxbox" ], "┐": [ "boxdl" ], "╕": [ "boxdL" ], "╖": [ "boxDl" ], "╗": [ "boxDL" ], "┌": [ "boxdr" ], "╒": [ "boxdR" ], "╓": [ "boxDr" ], "╔": [ "boxDR" ], "─": [ "boxh", "HorizontalLine" ], "═": [ "boxH" ], "┬": [ "boxhd" ], "╤": [ "boxHd" ], "╥": [ "boxhD" ], "╦": [ "boxHD" ], "┴": [ "boxhu" ], "╧": [ "boxHu" ], "╨": [ "boxhU" ], "╩": [ "boxHU" ], "⊟": [ "boxminus", "minusb" ], "⊞": [ "boxplus", "plusb" ], "⊠": [ "boxtimes", "timesb" ], "┘": [ "boxul" ], "╛": [ "boxuL" ], "╜": [ "boxUl" ], "╝": [ "boxUL" ], "└": [ "boxur" ], "╘": [ "boxuR" ], "╙": [ "boxUr" ], "╚": [ "boxUR" ], "│": [ "boxv" ], "║": [ "boxV" ], "┼": [ "boxvh" ], "╪": [ "boxvH" ], "╫": [ "boxVh" ], "╬": [ "boxVH" ], "┤": [ "boxvl" ], "╡": [ "boxvL" ], "╢": [ "boxVl" ], "╣": [ "boxVL" ], "├": [ "boxvr" ], "╞": [ "boxvR" ], "╟": [ "boxVr" ], "╠": [ "boxVR" ], "˘": [ "breve", "Breve" ], "¦": [ "brvbar" ], "𝒷": [ "bscr" ], "⁏": [ "bsemi" ], "⧅": [ "bsolb" ], "\\": [ "bsol" ], "⟈": [ "bsolhsub" ], "•": [ "bull", "bullet" ], "≎": [ "bump", "Bumpeq", "HumpDownHump" ], "⪮": [ "bumpE" ], "≏": [ "bumpe", "bumpeq", "HumpEqual" ], "Ć": [ "Cacute" ], "ć": [ "cacute" ], "⩄": [ "capand" ], "⩉": [ "capbrcup" ], "⩋": [ "capcap" ], "∩": [ "cap" ], "⋒": [ "Cap" ], "⩇": [ "capcup" ], "⩀": [ "capdot" ], "ⅅ": [ "CapitalDifferentialD", "DD" ], "∩︀": [ "caps" ], "⁁": [ "caret" ], "ˇ": [ "caron", "Hacek" ], "ℭ": [ "Cayleys", "Cfr" ], "⩍": [ "ccaps" ], "Č": [ "Ccaron" ], "č": [ "ccaron" ], "Ç": [ "Ccedil" ], "ç": [ "ccedil" ], "Ĉ": [ "Ccirc" ], "ĉ": [ "ccirc" ], "∰": [ "Cconint" ], "⩌": [ "ccups" ], "⩐": [ "ccupssm" ], "Ċ": [ "Cdot" ], "ċ": [ "cdot" ], "¸": [ "cedil", "Cedilla" ], "⦲": [ "cemptyv" ], "¢": [ "cent" ], "·": [ "centerdot", "CenterDot", "middot" ], "𝔠": [ "cfr" ], "Ч": [ "CHcy" ], "ч": [ "chcy" ], "✓": [ "check", "checkmark" ], "Χ": [ "Chi" ], "χ": [ "chi" ], "ˆ": [ "circ" ], "≗": [ "circeq", "cire" ], "↺": [ "circlearrowleft", "olarr" ], "↻": [ "circlearrowright", "orarr" ], "⊛": [ "circledast", "oast" ], "⊚": [ "circledcirc", "ocir" ], "⊝": [ "circleddash", "odash" ], "⊙": [ "CircleDot", "odot" ], "®": [ "circledR", "reg", "REG" ], "Ⓢ": [ "circledS", "oS" ], "⊖": [ "CircleMinus", "ominus" ], "⊕": [ "CirclePlus", "oplus" ], "⊗": [ "CircleTimes", "otimes" ], "○": [ "cir" ], "⧃": [ "cirE" ], "⨐": [ "cirfnint" ], "⫯": [ "cirmid" ], "⧂": [ "cirscir" ], "∲": [ "ClockwiseContourIntegral", "cwconint" ], "”": [ "CloseCurlyDoubleQuote", "rdquo", "rdquor" ], "’": [ "CloseCurlyQuote", "rsquo", "rsquor" ], "♣": [ "clubs", "clubsuit" ], ":": [ false, "colon" ], "∷": [ "Colon", "Proportion" ], "⩴": [ "Colone" ], ",": [ "comma" ], "@": [ "commat" ], "∁": [ "comp", "complement" ], "∘": [ "compfn", "SmallCircle" ], "ℂ": [ "complexes", "Copf" ], "≅": [ "cong", "TildeFullEqual" ], "⩭": [ "congdot" ], "≡": [ "Congruent", "equiv" ], "∮": [ "conint", "ContourIntegral", "oint" ], "∯": [ "Conint", "DoubleContourIntegral" ], "𝕔": [ "copf" ], "∐": [ "coprod", "Coproduct" ], "©": [ "copy", "COPY" ], "℗": [ "copysr" ], "↵": [ "crarr" ], "✗": [ "cross" ], "⨯": [ "Cross" ], "𝒞": [ "Cscr" ], "𝒸": [ "cscr" ], "⫏": [ "csub" ], "⫑": [ "csube" ], "⫐": [ "csup" ], "⫒": [ "csupe" ], "⋯": [ "ctdot" ], "⤸": [ "cudarrl" ], "⤵": [ "cudarrr" ], "⋞": [ "cuepr", "curlyeqprec" ], "⋟": [ "cuesc", "curlyeqsucc" ], "↶": [ "cularr", "curvearrowleft" ], "⤽": [ "cularrp" ], "⩈": [ "cupbrcap" ], "⩆": [ "cupcap" ], "∪": [ "cup" ], "⋓": [ "Cup" ], "⩊": [ "cupcup" ], "⊍": [ "cupdot" ], "⩅": [ "cupor" ], "∪︀": [ "cups" ], "↷": [ "curarr", "curvearrowright" ], "⤼": [ "curarrm" ], "⋎": [ "curlyvee", "cuvee" ], "⋏": [ "curlywedge", "cuwed" ], "¤": [ "curren" ], "∱": [ "cwint" ], "⌭": [ "cylcty" ], "†": [ "dagger" ], "‡": [ "Dagger", "ddagger" ], "ℸ": [ "daleth" ], "↓": [ "darr", "downarrow", "DownArrow", "ShortDownArrow" ], "↡": [ "Darr" ], "⇓": [ "dArr", "DoubleDownArrow", "Downarrow" ], "‐": [ "dash", "hyphen" ], "⫤": [ "Dashv", "DoubleLeftTee" ], "⊣": [ "dashv", "LeftTee" ], "⤏": [ "dbkarow", "rBarr" ], "˝": [ "dblac", "DiacriticalDoubleAcute" ], "Ď": [ "Dcaron" ], "ď": [ "dcaron" ], "Д": [ "Dcy" ], "д": [ "dcy" ], "⇊": [ "ddarr", "downdownarrows" ], "ⅆ": [ "dd", "DifferentialD" ], "⤑": [ "DDotrahd" ], "⩷": [ "ddotseq", "eDDot" ], "°": [ "deg" ], "∇": [ "Del", "nabla" ], "Δ": [ "Delta" ], "δ": [ "delta" ], "⦱": [ "demptyv" ], "⥿": [ "dfisht" ], "𝔇": [ "Dfr" ], "𝔡": [ "dfr" ], "⥥": [ "dHar" ], "⇃": [ "dharl", "downharpoonleft", "LeftDownVector" ], "⇂": [ "dharr", "downharpoonright", "RightDownVector" ], "˙": [ "DiacriticalDot", "dot" ], "`": [ "DiacriticalGrave", "grave" ], "˜": [ "DiacriticalTilde", "tilde" ], "⋄": [ "diam", "diamond", "Diamond" ], "♦": [ "diamondsuit", "diams" ], "¨": [ "die", "Dot", "DoubleDot", "uml" ], "ϝ": [ "digamma", "gammad" ], "⋲": [ "disin" ], "÷": [ "div", "divide" ], "⋇": [ "divideontimes", "divonx" ], "Ђ": [ "DJcy" ], "ђ": [ "djcy" ], "⌞": [ "dlcorn", "llcorner" ], "⌍": [ "dlcrop" ], "$": [ "dollar" ], "𝔻": [ "Dopf" ], "𝕕": [ "dopf" ], "⃜": [ "DotDot" ], "≐": [ "doteq", "DotEqual", "esdot" ], "≑": [ "doteqdot", "eDot" ], "∸": [ "dotminus", "minusd" ], "∔": [ "dotplus", "plusdo" ], "⊡": [ "dotsquare", "sdotb" ], "⇐": [ "DoubleLeftArrow", "lArr", "Leftarrow" ], "⇔": [ "DoubleLeftRightArrow", "hArr", "iff", "Leftrightarrow" ], "⟸": [ "DoubleLongLeftArrow", "Longleftarrow", "xlArr" ], "⟺": [ "DoubleLongLeftRightArrow", "Longleftrightarrow", "xhArr" ], "⟹": [ "DoubleLongRightArrow", "Longrightarrow", "xrArr" ], "⇒": [ "DoubleRightArrow", "Implies", "rArr", "Rightarrow" ], "⊨": [ "DoubleRightTee", "vDash" ], "⇑": [ "DoubleUpArrow", "uArr", "Uparrow" ], "⇕": [ "DoubleUpDownArrow", "Updownarrow", "vArr" ], "∥": [ "DoubleVerticalBar", "parallel", "par", "shortparallel", "spar" ], "⤓": [ "DownArrowBar" ], "⇵": [ "DownArrowUpArrow", "duarr" ], "̑": [ "DownBreve" ], "⥐": [ "DownLeftRightVector" ], "⥞": [ "DownLeftTeeVector" ], "⥖": [ "DownLeftVectorBar" ], "↽": [ "DownLeftVector", "leftharpoondown", "lhard" ], "⥟": [ "DownRightTeeVector" ], "⥗": [ "DownRightVectorBar" ], "⇁": [ "DownRightVector", "rhard", "rightharpoondown" ], "↧": [ "DownTeeArrow", "mapstodown" ], "⊤": [ "DownTee", "top" ], "⤐": [ "drbkarow", "RBarr" ], "⌟": [ "drcorn", "lrcorner" ], "⌌": [ "drcrop" ], "𝒟": [ "Dscr" ], "𝒹": [ "dscr" ], "Ѕ": [ "DScy" ], "ѕ": [ "dscy" ], "⧶": [ "dsol" ], "Đ": [ "Dstrok" ], "đ": [ "dstrok" ], "⋱": [ "dtdot" ], "▿": [ "dtri", "triangledown" ], "⥯": [ "duhar", "ReverseUpEquilibrium" ], "⦦": [ "dwangle" ], "Џ": [ "DZcy" ], "џ": [ "dzcy" ], "⟿": [ "dzigrarr" ], "É": [ "Eacute" ], "é": [ "eacute" ], "⩮": [ "easter" ], "Ě": [ "Ecaron" ], "ě": [ "ecaron" ], "Ê": [ "Ecirc" ], "ê": [ "ecirc" ], "≖": [ "ecir", "eqcirc" ], "≕": [ "ecolon", "eqcolon" ], "Э": [ "Ecy" ], "э": [ "ecy" ], "Ė": [ "Edot" ], "ė": [ "edot" ], "ⅇ": [ "ee", "exponentiale", "ExponentialE" ], "≒": [ "efDot", "fallingdotseq" ], "𝔈": [ "Efr" ], "𝔢": [ "efr" ], "⪚": [ "eg" ], "È": [ "Egrave" ], "è": [ "egrave" ], "⪖": [ "egs", "eqslantgtr" ], "⪘": [ "egsdot" ], "⪙": [ "el" ], "∈": [ "Element", "in", "isin", "isinv" ], "⏧": [ "elinters" ], "ℓ": [ "ell" ], "⪕": [ "els", "eqslantless" ], "⪗": [ "elsdot" ], "Ē": [ "Emacr" ], "ē": [ "emacr" ], "∅": [ "empty", "emptyset", "emptyv", "varnothing" ], "◻": [ "EmptySmallSquare" ], "▫": [ "EmptyVerySmallSquare" ], " ": [ "emsp13" ], " ": [ "emsp14" ], " ": [ "emsp" ], "Ŋ": [ "ENG" ], "ŋ": [ "eng" ], " ": [ "ensp" ], "Ę": [ "Eogon" ], "ę": [ "eogon" ], "𝔼": [ "Eopf" ], "𝕖": [ "eopf" ], "⋕": [ "epar" ], "⧣": [ "eparsl" ], "⩱": [ "eplus" ], "ε": [ "epsi", "epsilon" ], "Ε": [ "Epsilon" ], "ϵ": [ "epsiv", "straightepsilon", "varepsilon" ], "≂": [ "eqsim", "EqualTilde", "esim" ], "⩵": [ "Equal" ], "=": [ "equals" ], "≟": [ "equest", "questeq" ], "⇌": [ "Equilibrium", "rightleftharpoons", "rlhar" ], "⩸": [ "equivDD" ], "⧥": [ "eqvparsl" ], "⥱": [ "erarr" ], "≓": [ "erDot", "risingdotseq" ], "ℯ": [ "escr" ], "ℰ": [ "Escr", "expectation" ], "⩳": [ "Esim" ], "Η": [ "Eta" ], "η": [ "eta" ], "Ð": [ "ETH" ], "ð": [ "eth" ], "Ë": [ "Euml" ], "ë": [ "euml" ], "€": [ "euro" ], "!": [ false, "excl" ], "∃": [ "exist", "Exists" ], "Ф": [ "Fcy" ], "ф": [ "fcy" ], "♀": [ "female" ], "ffi": [ "ffilig" ], "ff": [ "fflig" ], "ffl": [ "ffllig" ], "𝔉": [ "Ffr" ], "𝔣": [ "ffr" ], "fi": [ "filig" ], "◼": [ "FilledSmallSquare" ], "fj": [ "fjlig" ], "♭": [ "flat" ], "fl": [ "fllig" ], "▱": [ "fltns" ], "ƒ": [ "fnof" ], "𝔽": [ "Fopf" ], "𝕗": [ "fopf" ], "∀": [ "forall", "ForAll" ], "⋔": [ "fork", "pitchfork" ], "⫙": [ "forkv" ], "ℱ": [ "Fouriertrf", "Fscr" ], "⨍": [ "fpartint" ], "½": [ "frac12", "half" ], "⅓": [ "frac13" ], "¼": [ "frac14" ], "⅕": [ "frac15" ], "⅙": [ "frac16" ], "⅛": [ "frac18" ], "⅔": [ "frac23" ], "⅖": [ "frac25" ], "¾": [ "frac34" ], "⅗": [ "frac35" ], "⅜": [ "frac38" ], "⅘": [ "frac45" ], "⅚": [ "frac56" ], "⅝": [ "frac58" ], "⅞": [ "frac78" ], "⁄": [ "frasl" ], "⌢": [ "frown", "sfrown" ], "𝒻": [ "fscr" ], "ǵ": [ "gacute" ], "Γ": [ "Gamma" ], "γ": [ "gamma" ], "Ϝ": [ "Gammad" ], "⪆": [ "gap", "gtrapprox" ], "Ğ": [ "Gbreve" ], "ğ": [ "gbreve" ], "Ģ": [ "Gcedil" ], "Ĝ": [ "Gcirc" ], "ĝ": [ "gcirc" ], "Г": [ "Gcy" ], "г": [ "gcy" ], "Ġ": [ "Gdot" ], "ġ": [ "gdot" ], "≥": [ "ge", "geq", "GreaterEqual" ], "≧": [ "gE", "geqq", "GreaterFullEqual" ], "⪌": [ "gEl", "gtreqqless" ], "⋛": [ "gel", "GreaterEqualLess", "gtreqless" ], "⩾": [ "geqslant", "ges", "GreaterSlantEqual" ], "⪩": [ "gescc" ], "⪀": [ "gesdot" ], "⪂": [ "gesdoto" ], "⪄": [ "gesdotol" ], "⋛︀": [ "gesl" ], "⪔": [ "gesles" ], "𝔊": [ "Gfr" ], "𝔤": [ "gfr" ], "≫": [ "gg", "Gt", "NestedGreaterGreater" ], "⋙": [ "Gg", "ggg" ], "ℷ": [ "gimel" ], "Ѓ": [ "GJcy" ], "ѓ": [ "gjcy" ], "⪥": [ "gla" ], "≷": [ "gl", "GreaterLess", "gtrless" ], "⪒": [ "glE" ], "⪤": [ "glj" ], "⪊": [ "gnap", "gnapprox" ], "⪈": [ "gne", "gneq" ], "≩": [ "gnE", "gneqq" ], "⋧": [ "gnsim" ], "𝔾": [ "Gopf" ], "𝕘": [ "gopf" ], "⪢": [ "GreaterGreater" ], "≳": [ "GreaterTilde", "gsim", "gtrsim" ], "𝒢": [ "Gscr" ], "ℊ": [ "gscr" ], "⪎": [ "gsime" ], "⪐": [ "gsiml" ], "⪧": [ "gtcc" ], "⩺": [ "gtcir" ], ">": [ "gt", "GT" ], "⋗": [ "gtdot", "gtrdot" ], "⦕": [ "gtlPar" ], "⩼": [ "gtquest" ], "⥸": [ "gtrarr" ], "≩︀": [ "gvertneqq", "gvnE" ], " ": [ "hairsp", "VeryThinSpace" ], "ℋ": [ "hamilt", "HilbertSpace", "Hscr" ], "Ъ": [ "HARDcy" ], "ъ": [ "hardcy" ], "⥈": [ "harrcir" ], "↔": [ "harr", "leftrightarrow", "LeftRightArrow" ], "↭": [ "harrw", "leftrightsquigarrow" ], "^": [ "Hat" ], "ℏ": [ "hbar", "hslash", "planck", "plankv" ], "Ĥ": [ "Hcirc" ], "ĥ": [ "hcirc" ], "♥": [ "hearts", "heartsuit" ], "…": [ "hellip", "mldr" ], "⊹": [ "hercon" ], "𝔥": [ "hfr" ], "ℌ": [ "Hfr", "Poincareplane" ], "⤥": [ "hksearow", "searhk" ], "⤦": [ "hkswarow", "swarhk" ], "⇿": [ "hoarr" ], "∻": [ "homtht" ], "↩": [ "hookleftarrow", "larrhk" ], "↪": [ "hookrightarrow", "rarrhk" ], "𝕙": [ "hopf" ], "ℍ": [ "Hopf", "quaternions" ], "―": [ "horbar" ], "𝒽": [ "hscr" ], "Ħ": [ "Hstrok" ], "ħ": [ "hstrok" ], "⁃": [ "hybull" ], "Í": [ "Iacute" ], "í": [ "iacute" ], "⁣": [ "ic", "InvisibleComma" ], "Î": [ "Icirc" ], "î": [ "icirc" ], "И": [ "Icy" ], "и": [ "icy" ], "İ": [ "Idot" ], "Е": [ "IEcy" ], "е": [ "iecy" ], "¡": [ "iexcl" ], "𝔦": [ "ifr" ], "ℑ": [ "Ifr", "image", "imagpart", "Im" ], "Ì": [ "Igrave" ], "ì": [ "igrave" ], "ⅈ": [ "ii", "ImaginaryI" ], "⨌": [ "iiiint", "qint" ], "∭": [ "iiint", "tint" ], "⧜": [ "iinfin" ], "℩": [ "iiota" ], "IJ": [ "IJlig" ], "ij": [ "ijlig" ], "Ī": [ "Imacr" ], "ī": [ "imacr" ], "ℐ": [ "imagline", "Iscr" ], "ı": [ "imath", "inodot" ], "⊷": [ "imof" ], "Ƶ": [ "imped" ], "℅": [ "incare" ], "∞": [ "infin" ], "⧝": [ "infintie" ], "⊺": [ "intcal", "intercal" ], "∫": [ "int", "Integral" ], "∬": [ "Int" ], "ℤ": [ "integers", "Zopf" ], "⨗": [ "intlarhk" ], "⨼": [ "intprod", "iprod" ], "⁢": [ "InvisibleTimes", "it" ], "Ё": [ "IOcy" ], "ё": [ "iocy" ], "Į": [ "Iogon" ], "į": [ "iogon" ], "𝕀": [ "Iopf" ], "𝕚": [ "iopf" ], "Ι": [ "Iota" ], "ι": [ "iota" ], "¿": [ "iquest" ], "𝒾": [ "iscr" ], "⋵": [ "isindot" ], "⋹": [ "isinE" ], "⋴": [ "isins" ], "⋳": [ "isinsv" ], "Ĩ": [ "Itilde" ], "ĩ": [ "itilde" ], "І": [ "Iukcy" ], "і": [ "iukcy" ], "Ï": [ "Iuml" ], "ï": [ "iuml" ], "Ĵ": [ "Jcirc" ], "ĵ": [ "jcirc" ], "Й": [ "Jcy" ], "й": [ "jcy" ], "𝔍": [ "Jfr" ], "𝔧": [ "jfr" ], "ȷ": [ "jmath" ], "𝕁": [ "Jopf" ], "𝕛": [ "jopf" ], "𝒥": [ "Jscr" ], "𝒿": [ "jscr" ], "Ј": [ "Jsercy" ], "ј": [ "jsercy" ], "Є": [ "Jukcy" ], "є": [ "jukcy" ], "Κ": [ "Kappa" ], "κ": [ "kappa" ], "ϰ": [ "kappav", "varkappa" ], "Ķ": [ "Kcedil" ], "ķ": [ "kcedil" ], "К": [ "Kcy" ], "к": [ "kcy" ], "𝔎": [ "Kfr" ], "𝔨": [ "kfr" ], "ĸ": [ "kgreen" ], "Х": [ "KHcy" ], "х": [ "khcy" ], "Ќ": [ "KJcy" ], "ќ": [ "kjcy" ], "𝕂": [ "Kopf" ], "𝕜": [ "kopf" ], "𝒦": [ "Kscr" ], "𝓀": [ "kscr" ], "⇚": [ "lAarr", "Lleftarrow" ], "Ĺ": [ "Lacute" ], "ĺ": [ "lacute" ], "⦴": [ "laemptyv" ], "ℒ": [ "lagran", "Laplacetrf", "Lscr" ], "Λ": [ "Lambda" ], "λ": [ "lambda" ], "⟨": [ "lang", "langle", "LeftAngleBracket" ], "⟪": [ "Lang" ], "⦑": [ "langd" ], "⪅": [ "lap", "lessapprox" ], "«": [ "laquo" ], "⇤": [ "larrb", "LeftArrowBar" ], "⤟": [ "larrbfs" ], "←": [ "larr", "leftarrow", "LeftArrow", "ShortLeftArrow", "slarr" ], "↞": [ "Larr", "twoheadleftarrow" ], "⤝": [ "larrfs" ], "↫": [ "larrlp", "looparrowleft" ], "⤹": [ "larrpl" ], "⥳": [ "larrsim" ], "↢": [ "larrtl", "leftarrowtail" ], "⤙": [ "latail" ], "⤛": [ "lAtail" ], "⪫": [ "lat" ], "⪭": [ "late" ], "⪭︀": [ "lates" ], "⤌": [ "lbarr" ], "⤎": [ "lBarr" ], "❲": [ "lbbrk" ], "{": [ "lbrace", "lcub" ], "[": [ "lbrack", "lsqb" ], "⦋": [ "lbrke" ], "⦏": [ "lbrksld" ], "⦍": [ "lbrkslu" ], "Ľ": [ "Lcaron" ], "ľ": [ "lcaron" ], "Ļ": [ "Lcedil" ], "ļ": [ "lcedil" ], "⌈": [ "lceil", "LeftCeiling" ], "Л": [ "Lcy" ], "л": [ "lcy" ], "⤶": [ "ldca" ], "“": [ "ldquo", "OpenCurlyDoubleQuote" ], "⥧": [ "ldrdhar" ], "⥋": [ "ldrushar" ], "↲": [ "ldsh" ], "≤": [ "le", "leq" ], "≦": [ "lE", "leqq", "LessFullEqual" ], "⇆": [ "LeftArrowRightArrow", "leftrightarrows", "lrarr" ], "⟦": [ "LeftDoubleBracket", "lobrk" ], "⥡": [ "LeftDownTeeVector" ], "⥙": [ "LeftDownVectorBar" ], "⌊": [ "LeftFloor", "lfloor" ], "↼": [ "leftharpoonup", "LeftVector", "lharu" ], "⇇": [ "leftleftarrows", "llarr" ], "⇋": [ "leftrightharpoons", "lrhar", "ReverseEquilibrium" ], "⥎": [ "LeftRightVector" ], "↤": [ "LeftTeeArrow", "mapstoleft" ], "⥚": [ "LeftTeeVector" ], "⋋": [ "leftthreetimes", "lthree" ], "⧏": [ "LeftTriangleBar" ], "⊲": [ "LeftTriangle", "vartriangleleft", "vltri" ], "⊴": [ "LeftTriangleEqual", "ltrie", "trianglelefteq" ], "⥑": [ "LeftUpDownVector" ], "⥠": [ "LeftUpTeeVector" ], "⥘": [ "LeftUpVectorBar" ], "↿": [ "LeftUpVector", "uharl", "upharpoonleft" ], "⥒": [ "LeftVectorBar" ], "⪋": [ "lEg", "lesseqqgtr" ], "⋚": [ "leg", "lesseqgtr", "LessEqualGreater" ], "⩽": [ "leqslant", "les", "LessSlantEqual" ], "⪨": [ "lescc" ], "⩿": [ "lesdot" ], "⪁": [ "lesdoto" ], "⪃": [ "lesdotor" ], "⋚︀": [ "lesg" ], "⪓": [ "lesges" ], "⋖": [ "lessdot", "ltdot" ], "≶": [ "LessGreater", "lessgtr", "lg" ], "⪡": [ "LessLess" ], "≲": [ "lesssim", "LessTilde", "lsim" ], "⥼": [ "lfisht" ], "𝔏": [ "Lfr" ], "𝔩": [ "lfr" ], "⪑": [ "lgE" ], "⥢": [ "lHar" ], "⥪": [ "lharul" ], "▄": [ "lhblk" ], "Љ": [ "LJcy" ], "љ": [ "ljcy" ], "≪": [ "ll", "Lt", "NestedLessLess" ], "⋘": [ "Ll" ], "⥫": [ "llhard" ], "◺": [ "lltri" ], "Ŀ": [ "Lmidot" ], "ŀ": [ "lmidot" ], "⎰": [ "lmoustache", "lmoust" ], "⪉": [ "lnap", "lnapprox" ], "⪇": [ "lne", "lneq" ], "≨": [ "lnE", "lneqq" ], "⋦": [ "lnsim" ], "⟬": [ "loang" ], "⇽": [ "loarr" ], "⟵": [ "longleftarrow", "LongLeftArrow", "xlarr" ], "⟷": [ "longleftrightarrow", "LongLeftRightArrow", "xharr" ], "⟼": [ "longmapsto", "xmap" ], "⟶": [ "longrightarrow", "LongRightArrow", "xrarr" ], "↬": [ "looparrowright", "rarrlp" ], "⦅": [ "lopar" ], "𝕃": [ "Lopf" ], "𝕝": [ "lopf" ], "⨭": [ "loplus" ], "⨴": [ "lotimes" ], "∗": [ "lowast" ], "_": [ "lowbar", "UnderBar" ], "↙": [ "LowerLeftArrow", "swarr", "swarrow" ], "↘": [ "LowerRightArrow", "searr", "searrow" ], "◊": [ "loz", "lozenge" ], "(": [ "lpar" ], "⦓": [ "lparlt" ], "⥭": [ "lrhard" ], "‎": [ "lrm" ], "⊿": [ "lrtri" ], "‹": [ "lsaquo" ], "𝓁": [ "lscr" ], "↰": [ "lsh", "Lsh" ], "⪍": [ "lsime" ], "⪏": [ "lsimg" ], "‘": [ "lsquo", "OpenCurlyQuote" ], "‚": [ "lsquor", "sbquo" ], "Ł": [ "Lstrok" ], "ł": [ "lstrok" ], "⪦": [ "ltcc" ], "⩹": [ "ltcir" ], "<": [ "lt", "LT" ], "⋉": [ "ltimes" ], "⥶": [ "ltlarr" ], "⩻": [ "ltquest" ], "◃": [ "ltri", "triangleleft" ], "⦖": [ "ltrPar" ], "⥊": [ "lurdshar" ], "⥦": [ "luruhar" ], "≨︀": [ "lvertneqq", "lvnE" ], "¯": [ "macr", "strns" ], "♂": [ "male" ], "✠": [ "malt", "maltese" ], "⤅": [ "Map" ], "↦": [ "map", "mapsto", "RightTeeArrow" ], "↥": [ "mapstoup", "UpTeeArrow" ], "▮": [ "marker" ], "⨩": [ "mcomma" ], "М": [ "Mcy" ], "м": [ "mcy" ], "—": [ "mdash" ], "∺": [ "mDDot" ], " ": [ "MediumSpace" ], "ℳ": [ "Mellintrf", "Mscr", "phmmat" ], "𝔐": [ "Mfr" ], "𝔪": [ "mfr" ], "℧": [ "mho" ], "µ": [ "micro" ], "⫰": [ "midcir" ], "∣": [ "mid", "shortmid", "smid", "VerticalBar" ], "−": [ "minus" ], "⨪": [ "minusdu" ], "∓": [ "MinusPlus", "mnplus", "mp" ], "⫛": [ "mlcp" ], "⊧": [ "models" ], "𝕄": [ "Mopf" ], "𝕞": [ "mopf" ], "𝓂": [ "mscr" ], "Μ": [ "Mu" ], "μ": [ "mu" ], "⊸": [ "multimap", "mumap" ], "Ń": [ "Nacute" ], "ń": [ "nacute" ], "∠⃒": [ "nang" ], "≉": [ "nap", "napprox", "NotTildeTilde" ], "⩰̸": [ "napE" ], "≋̸": [ "napid" ], "ʼn": [ "napos" ], "♮": [ "natural", "natur" ], "ℕ": [ "naturals", "Nopf" ], " ": [ "nbsp", "NonBreakingSpace" ], "≎̸": [ "nbump", "NotHumpDownHump" ], "≏̸": [ "nbumpe", "NotHumpEqual" ], "⩃": [ "ncap" ], "Ň": [ "Ncaron" ], "ň": [ "ncaron" ], "Ņ": [ "Ncedil" ], "ņ": [ "ncedil" ], "≇": [ "ncong", "NotTildeFullEqual" ], "⩭̸": [ "ncongdot" ], "⩂": [ "ncup" ], "Н": [ "Ncy" ], "н": [ "ncy" ], "–": [ "ndash" ], "⤤": [ "nearhk" ], "↗": [ "nearr", "nearrow", "UpperRightArrow" ], "⇗": [ "neArr" ], "≠": [ "ne", "NotEqual" ], "≐̸": [ "nedot" ], "​": [ "NegativeMediumSpace", "NegativeThickSpace", "NegativeThinSpace", "NegativeVeryThinSpace", "ZeroWidthSpace" ], "≢": [ "nequiv", "NotCongruent" ], "⤨": [ "nesear", "toea" ], "≂̸": [ "nesim", "NotEqualTilde" ], "\n": [ false, "NewLine" ], "∄": [ "nexist", "nexists", "NotExists" ], "𝔑": [ "Nfr" ], "𝔫": [ "nfr" ], "≧̸": [ "ngE", "ngeqq", "NotGreaterFullEqual" ], "≱": [ "nge", "ngeq", "NotGreaterEqual" ], "⩾̸": [ "ngeqslant", "nges", "NotGreaterSlantEqual" ], "⋙̸": [ "nGg" ], "≵": [ "ngsim", "NotGreaterTilde" ], "≫⃒": [ "nGt" ], "≯": [ "ngt", "ngtr", "NotGreater" ], "≫̸": [ "nGtv", "NotGreaterGreater" ], "↮": [ "nharr", "nleftrightarrow" ], "⇎": [ "nhArr", "nLeftrightarrow" ], "⫲": [ "nhpar" ], "∋": [ "ni", "niv", "ReverseElement", "SuchThat" ], "⋼": [ "nis" ], "⋺": [ "nisd" ], "Њ": [ "NJcy" ], "њ": [ "njcy" ], "↚": [ "nlarr", "nleftarrow" ], "⇍": [ "nlArr", "nLeftarrow" ], "‥": [ "nldr" ], "≦̸": [ "nlE", "nleqq" ], "≰": [ "nle", "nleq", "NotLessEqual" ], "⩽̸": [ "nleqslant", "nles", "NotLessSlantEqual" ], "≮": [ "nless", "nlt", "NotLess" ], "⋘̸": [ "nLl" ], "≴": [ "nlsim", "NotLessTilde" ], "≪⃒": [ "nLt" ], "⋪": [ "nltri", "NotLeftTriangle", "ntriangleleft" ], "⋬": [ "nltrie", "NotLeftTriangleEqual", "ntrianglelefteq" ], "≪̸": [ "nLtv", "NotLessLess" ], "∤": [ "nmid", "NotVerticalBar", "nshortmid", "nsmid" ], "⁠": [ "NoBreak" ], "𝕟": [ "nopf" ], "⫬": [ "Not" ], "¬": [ "not" ], "≭": [ "NotCupCap" ], "∦": [ "NotDoubleVerticalBar", "nparallel", "npar", "nshortparallel", "nspar" ], "∉": [ "NotElement", "notin", "notinva" ], "≹": [ "NotGreaterLess", "ntgl" ], "⋵̸": [ "notindot" ], "⋹̸": [ "notinE" ], "⋷": [ "notinvb" ], "⋶": [ "notinvc" ], "⧏̸": [ "NotLeftTriangleBar" ], "≸": [ "NotLessGreater", "ntlg" ], "⪢̸": [ "NotNestedGreaterGreater" ], "⪡̸": [ "NotNestedLessLess" ], "∌": [ "notni", "notniva", "NotReverseElement" ], "⋾": [ "notnivb" ], "⋽": [ "notnivc" ], "⊀": [ "NotPrecedes", "npr", "nprec" ], "⪯̸": [ "NotPrecedesEqual", "npreceq", "npre" ], "⋠": [ "NotPrecedesSlantEqual", "nprcue" ], "⧐̸": [ "NotRightTriangleBar" ], "⋫": [ "NotRightTriangle", "nrtri", "ntriangleright" ], "⋭": [ "NotRightTriangleEqual", "nrtrie", "ntrianglerighteq" ], "⊏̸": [ "NotSquareSubset" ], "⋢": [ "NotSquareSubsetEqual", "nsqsube" ], "⊐̸": [ "NotSquareSuperset" ], "⋣": [ "NotSquareSupersetEqual", "nsqsupe" ], "⊂⃒": [ "NotSubset", "nsubset", "vnsub" ], "⊈": [ "NotSubsetEqual", "nsube", "nsubseteq" ], "⊁": [ "NotSucceeds", "nsc", "nsucc" ], "⪰̸": [ "NotSucceedsEqual", "nsce", "nsucceq" ], "⋡": [ "NotSucceedsSlantEqual", "nsccue" ], "≿̸": [ "NotSucceedsTilde" ], "⊃⃒": [ "NotSuperset", "nsupset", "vnsup" ], "⊉": [ "NotSupersetEqual", "nsupe", "nsupseteq" ], "≁": [ "NotTilde", "nsim" ], "≄": [ "NotTildeEqual", "nsime", "nsimeq" ], "⫽⃥": [ "nparsl" ], "∂̸": [ "npart" ], "⨔": [ "npolint" ], "⤳̸": [ "nrarrc" ], "↛": [ "nrarr", "nrightarrow" ], "⇏": [ "nrArr", "nRightarrow" ], "↝̸": [ "nrarrw" ], "𝒩": [ "Nscr" ], "𝓃": [ "nscr" ], "⊄": [ "nsub" ], "⫅̸": [ "nsubE", "nsubseteqq" ], "⊅": [ "nsup" ], "⫆̸": [ "nsupE", "nsupseteqq" ], "Ñ": [ "Ntilde" ], "ñ": [ "ntilde" ], "Ν": [ "Nu" ], "ν": [ "nu" ], "#": [ "num" ], "№": [ "numero" ], " ": [ "numsp" ], "≍⃒": [ "nvap" ], "⊬": [ "nvdash" ], "⊭": [ "nvDash" ], "⊮": [ "nVdash" ], "⊯": [ "nVDash" ], "≥⃒": [ "nvge" ], ">⃒": [ "nvgt" ], "⤄": [ "nvHarr" ], "⧞": [ "nvinfin" ], "⤂": [ "nvlArr" ], "≤⃒": [ "nvle" ], "<⃒": [ "nvlt" ], "⊴⃒": [ "nvltrie" ], "⤃": [ "nvrArr" ], "⊵⃒": [ "nvrtrie" ], "∼⃒": [ "nvsim" ], "⤣": [ "nwarhk" ], "↖": [ "nwarr", "nwarrow", "UpperLeftArrow" ], "⇖": [ "nwArr" ], "⤧": [ "nwnear" ], "Ó": [ "Oacute" ], "ó": [ "oacute" ], "Ô": [ "Ocirc" ], "ô": [ "ocirc" ], "О": [ "Ocy" ], "о": [ "ocy" ], "Ő": [ "Odblac" ], "ő": [ "odblac" ], "⨸": [ "odiv" ], "⦼": [ "odsold" ], "Œ": [ "OElig" ], "œ": [ "oelig" ], "⦿": [ "ofcir" ], "𝔒": [ "Ofr" ], "𝔬": [ "ofr" ], "˛": [ "ogon" ], "Ò": [ "Ograve" ], "ò": [ "ograve" ], "⧁": [ "ogt" ], "⦵": [ "ohbar" ], "Ω": [ "ohm", "Omega" ], "⦾": [ "olcir" ], "⦻": [ "olcross" ], "‾": [ "oline", "OverBar" ], "⧀": [ "olt" ], "Ō": [ "Omacr" ], "ō": [ "omacr" ], "ω": [ "omega" ], "Ο": [ "Omicron" ], "ο": [ "omicron" ], "⦶": [ "omid" ], "𝕆": [ "Oopf" ], "𝕠": [ "oopf" ], "⦷": [ "opar" ], "⦹": [ "operp" ], "⩔": [ "Or" ], "∨": [ "or", "vee" ], "⩝": [ "ord" ], "ℴ": [ "order", "orderof", "oscr" ], "ª": [ "ordf" ], "º": [ "ordm" ], "⊶": [ "origof" ], "⩖": [ "oror" ], "⩗": [ "orslope" ], "⩛": [ "orv" ], "𝒪": [ "Oscr" ], "Ø": [ "Oslash" ], "ø": [ "oslash" ], "⊘": [ "osol" ], "Õ": [ "Otilde" ], "õ": [ "otilde" ], "⨶": [ "otimesas" ], "⨷": [ "Otimes" ], "Ö": [ "Ouml" ], "ö": [ "ouml" ], "⌽": [ "ovbar" ], "⏞": [ "OverBrace" ], "⎴": [ "OverBracket", "tbrk" ], "⏜": [ "OverParenthesis" ], "¶": [ "para" ], "⫳": [ "parsim" ], "⫽": [ "parsl" ], "∂": [ "part", "PartialD" ], "П": [ "Pcy" ], "п": [ "pcy" ], "%": [ "percnt" ], ".": [ "period" ], "‰": [ "permil" ], "‱": [ "pertenk" ], "𝔓": [ "Pfr" ], "𝔭": [ "pfr" ], "Φ": [ "Phi" ], "φ": [ "phi" ], "ϕ": [ "phiv", "straightphi", "varphi" ], "☎": [ "phone" ], "Π": [ "Pi" ], "π": [ "pi" ], "ϖ": [ "piv", "varpi" ], "ℎ": [ "planckh" ], "⨣": [ "plusacir" ], "⨢": [ "pluscir" ], "+": [ "plus" ], "⨥": [ "plusdu" ], "⩲": [ "pluse" ], "±": [ "PlusMinus", "plusmn", "pm" ], "⨦": [ "plussim" ], "⨧": [ "plustwo" ], "⨕": [ "pointint" ], "𝕡": [ "popf" ], "ℙ": [ "Popf", "primes" ], "£": [ "pound" ], "⪷": [ "prap", "precapprox" ], "⪻": [ "Pr" ], "≺": [ "pr", "prec", "Precedes" ], "≼": [ "prcue", "preccurlyeq", "PrecedesSlantEqual" ], "⪯": [ "PrecedesEqual", "preceq", "pre" ], "≾": [ "PrecedesTilde", "precsim", "prsim" ], "⪹": [ "precnapprox", "prnap" ], "⪵": [ "precneqq", "prnE" ], "⋨": [ "precnsim", "prnsim" ], "⪳": [ "prE" ], "′": [ "prime" ], "″": [ "Prime" ], "∏": [ "prod", "Product" ], "⌮": [ "profalar" ], "⌒": [ "profline" ], "⌓": [ "profsurf" ], "∝": [ "prop", "Proportional", "propto", "varpropto", "vprop" ], "⊰": [ "prurel" ], "𝒫": [ "Pscr" ], "𝓅": [ "pscr" ], "Ψ": [ "Psi" ], "ψ": [ "psi" ], " ": [ "puncsp" ], "𝔔": [ "Qfr" ], "𝔮": [ "qfr" ], "𝕢": [ "qopf" ], "ℚ": [ "Qopf", "rationals" ], "⁗": [ "qprime" ], "𝒬": [ "Qscr" ], "𝓆": [ "qscr" ], "⨖": [ "quatint" ], "?": [ "quest" ], "\"": [ "quot", "QUOT" ], "⇛": [ "rAarr", "Rrightarrow" ], "∽̱": [ "race" ], "Ŕ": [ "Racute" ], "ŕ": [ "racute" ], "√": [ "radic", "Sqrt" ], "⦳": [ "raemptyv" ], "⟩": [ "rang", "rangle", "RightAngleBracket" ], "⟫": [ "Rang" ], "⦒": [ "rangd" ], "⦥": [ "range" ], "»": [ "raquo" ], "⥵": [ "rarrap" ], "⇥": [ "rarrb", "RightArrowBar" ], "⤠": [ "rarrbfs" ], "⤳": [ "rarrc" ], "→": [ "rarr", "rightarrow", "RightArrow", "ShortRightArrow", "srarr" ], "↠": [ "Rarr", "twoheadrightarrow" ], "⤞": [ "rarrfs" ], "⥅": [ "rarrpl" ], "⥴": [ "rarrsim" ], "⤖": [ "Rarrtl" ], "↣": [ "rarrtl", "rightarrowtail" ], "↝": [ "rarrw", "rightsquigarrow" ], "⤚": [ "ratail" ], "⤜": [ "rAtail" ], "∶": [ "ratio" ], "❳": [ "rbbrk" ], "}": [ "rbrace", "rcub" ], "]": [ "rbrack", "rsqb" ], "⦌": [ "rbrke" ], "⦎": [ "rbrksld" ], "⦐": [ "rbrkslu" ], "Ř": [ "Rcaron" ], "ř": [ "rcaron" ], "Ŗ": [ "Rcedil" ], "ŗ": [ "rcedil" ], "⌉": [ "rceil", "RightCeiling" ], "Р": [ "Rcy" ], "р": [ "rcy" ], "⤷": [ "rdca" ], "⥩": [ "rdldhar" ], "↳": [ "rdsh" ], "ℜ": [ "real", "realpart", "Re", "Rfr" ], "ℛ": [ "realine", "Rscr" ], "ℝ": [ "reals", "Ropf" ], "▭": [ "rect" ], "⥽": [ "rfisht" ], "⌋": [ "rfloor", "RightFloor" ], "𝔯": [ "rfr" ], "⥤": [ "rHar" ], "⇀": [ "rharu", "rightharpoonup", "RightVector" ], "⥬": [ "rharul" ], "Ρ": [ "Rho" ], "ρ": [ "rho" ], "ϱ": [ "rhov", "varrho" ], "⇄": [ "RightArrowLeftArrow", "rightleftarrows", "rlarr" ], "⟧": [ "RightDoubleBracket", "robrk" ], "⥝": [ "RightDownTeeVector" ], "⥕": [ "RightDownVectorBar" ], "⇉": [ "rightrightarrows", "rrarr" ], "⊢": [ "RightTee", "vdash" ], "⥛": [ "RightTeeVector" ], "⋌": [ "rightthreetimes", "rthree" ], "⧐": [ "RightTriangleBar" ], "⊳": [ "RightTriangle", "vartriangleright", "vrtri" ], "⊵": [ "RightTriangleEqual", "rtrie", "trianglerighteq" ], "⥏": [ "RightUpDownVector" ], "⥜": [ "RightUpTeeVector" ], "⥔": [ "RightUpVectorBar" ], "↾": [ "RightUpVector", "uharr", "upharpoonright" ], "⥓": [ "RightVectorBar" ], "˚": [ "ring" ], "‏": [ "rlm" ], "⎱": [ "rmoustache", "rmoust" ], "⫮": [ "rnmid" ], "⟭": [ "roang" ], "⇾": [ "roarr" ], "⦆": [ "ropar" ], "𝕣": [ "ropf" ], "⨮": [ "roplus" ], "⨵": [ "rotimes" ], "⥰": [ "RoundImplies" ], ")": [ "rpar" ], "⦔": [ "rpargt" ], "⨒": [ "rppolint" ], "›": [ "rsaquo" ], "𝓇": [ "rscr" ], "↱": [ "rsh", "Rsh" ], "⋊": [ "rtimes" ], "▹": [ "rtri", "triangleright" ], "⧎": [ "rtriltri" ], "⧴": [ "RuleDelayed" ], "⥨": [ "ruluhar" ], "℞": [ "rx" ], "Ś": [ "Sacute" ], "ś": [ "sacute" ], "⪸": [ "scap", "succapprox" ], "Š": [ "Scaron" ], "š": [ "scaron" ], "⪼": [ "Sc" ], "≻": [ "sc", "succ", "Succeeds" ], "≽": [ "sccue", "succcurlyeq", "SucceedsSlantEqual" ], "⪰": [ "sce", "SucceedsEqual", "succeq" ], "⪴": [ "scE" ], "Ş": [ "Scedil" ], "ş": [ "scedil" ], "Ŝ": [ "Scirc" ], "ŝ": [ "scirc" ], "⪺": [ "scnap", "succnapprox" ], "⪶": [ "scnE", "succneqq" ], "⋩": [ "scnsim", "succnsim" ], "⨓": [ "scpolint" ], "≿": [ "scsim", "SucceedsTilde", "succsim" ], "С": [ "Scy" ], "с": [ "scy" ], "⋅": [ "sdot" ], "⩦": [ "sdote" ], "⇘": [ "seArr" ], "§": [ "sect" ], ";": [ false, "semi" ], "⤩": [ "seswar", "tosa" ], "✶": [ "sext" ], "𝔖": [ "Sfr" ], "𝔰": [ "sfr" ], "♯": [ "sharp" ], "Щ": [ "SHCHcy" ], "щ": [ "shchcy" ], "Ш": [ "SHcy" ], "ш": [ "shcy" ], "↑": [ "ShortUpArrow", "uarr", "uparrow", "UpArrow" ], "­": [ "shy" ], "Σ": [ "Sigma" ], "σ": [ "sigma" ], "ς": [ "sigmaf", "sigmav", "varsigma" ], "∼": [ "sim", "thicksim", "thksim", "Tilde" ], "⩪": [ "simdot" ], "≃": [ "sime", "simeq", "TildeEqual" ], "⪞": [ "simg" ], "⪠": [ "simgE" ], "⪝": [ "siml" ], "⪟": [ "simlE" ], "≆": [ "simne" ], "⨤": [ "simplus" ], "⥲": [ "simrarr" ], "⨳": [ "smashp" ], "⧤": [ "smeparsl" ], "⌣": [ "smile", "ssmile" ], "⪪": [ "smt" ], "⪬": [ "smte" ], "⪬︀": [ "smtes" ], "Ь": [ "SOFTcy" ], "ь": [ "softcy" ], "⌿": [ "solbar" ], "⧄": [ "solb" ], "/": [ false, "sol" ], "𝕊": [ "Sopf" ], "𝕤": [ "sopf" ], "♠": [ "spades", "spadesuit" ], "⊓": [ "sqcap", "SquareIntersection" ], "⊓︀": [ "sqcaps" ], "⊔": [ "sqcup", "SquareUnion" ], "⊔︀": [ "sqcups" ], "⊏": [ "sqsub", "sqsubset", "SquareSubset" ], "⊑": [ "sqsube", "sqsubseteq", "SquareSubsetEqual" ], "⊐": [ "sqsup", "sqsupset", "SquareSuperset" ], "⊒": [ "sqsupe", "sqsupseteq", "SquareSupersetEqual" ], "□": [ "square", "Square", "squ" ], "𝒮": [ "Sscr" ], "𝓈": [ "sscr" ], "⋆": [ "sstarf", "Star" ], "☆": [ "star" ], "⊂": [ "sub", "subset" ], "⋐": [ "Sub", "Subset" ], "⪽": [ "subdot" ], "⫅": [ "subE", "subseteqq" ], "⊆": [ "sube", "subseteq", "SubsetEqual" ], "⫃": [ "subedot" ], "⫁": [ "submult" ], "⫋": [ "subnE", "subsetneqq" ], "⊊": [ "subne", "subsetneq" ], "⪿": [ "subplus" ], "⥹": [ "subrarr" ], "⫇": [ "subsim" ], "⫕": [ "subsub" ], "⫓": [ "subsup" ], "∑": [ "sum", "Sum" ], "♪": [ "sung" ], "¹": [ "sup1" ], "²": [ "sup2" ], "³": [ "sup3" ], "⊃": [ "sup", "Superset", "supset" ], "⋑": [ "Sup", "Supset" ], "⪾": [ "supdot" ], "⫘": [ "supdsub" ], "⫆": [ "supE", "supseteqq" ], "⊇": [ "supe", "SupersetEqual", "supseteq" ], "⫄": [ "supedot" ], "⟉": [ "suphsol" ], "⫗": [ "suphsub" ], "⥻": [ "suplarr" ], "⫂": [ "supmult" ], "⫌": [ "supnE", "supsetneqq" ], "⊋": [ "supne", "supsetneq" ], "⫀": [ "supplus" ], "⫈": [ "supsim" ], "⫔": [ "supsub" ], "⫖": [ "supsup" ], "⇙": [ "swArr" ], "⤪": [ "swnwar" ], "ß": [ "szlig" ], "\t": [ false, "Tab" ], "⌖": [ "target" ], "Τ": [ "Tau" ], "τ": [ "tau" ], "Ť": [ "Tcaron" ], "ť": [ "tcaron" ], "Ţ": [ "Tcedil" ], "ţ": [ "tcedil" ], "Т": [ "Tcy" ], "т": [ "tcy" ], "⃛": [ "tdot", "TripleDot" ], "⌕": [ "telrec" ], "𝔗": [ "Tfr" ], "𝔱": [ "tfr" ], "∴": [ "there4", "therefore", "Therefore" ], "Θ": [ "Theta" ], "θ": [ "theta" ], "ϑ": [ "thetasym", "thetav", "vartheta" ], "  ": [ "ThickSpace" ], " ": [ "ThinSpace", "thinsp" ], "Þ": [ "THORN" ], "þ": [ "thorn" ], "⨱": [ "timesbar" ], "×": [ "times" ], "⨰": [ "timesd" ], "⌶": [ "topbot" ], "⫱": [ "topcir" ], "𝕋": [ "Topf" ], "𝕥": [ "topf" ], "⫚": [ "topfork" ], "‴": [ "tprime" ], "™": [ "trade", "TRADE" ], "▵": [ "triangle", "utri" ], "≜": [ "triangleq", "trie" ], "◬": [ "tridot" ], "⨺": [ "triminus" ], "⨹": [ "triplus" ], "⧍": [ "trisb" ], "⨻": [ "tritime" ], "⏢": [ "trpezium" ], "𝒯": [ "Tscr" ], "𝓉": [ "tscr" ], "Ц": [ "TScy" ], "ц": [ "tscy" ], "Ћ": [ "TSHcy" ], "ћ": [ "tshcy" ], "Ŧ": [ "Tstrok" ], "ŧ": [ "tstrok" ], "Ú": [ "Uacute" ], "ú": [ "uacute" ], "↟": [ "Uarr" ], "⥉": [ "Uarrocir" ], "Ў": [ "Ubrcy" ], "ў": [ "ubrcy" ], "Ŭ": [ "Ubreve" ], "ŭ": [ "ubreve" ], "Û": [ "Ucirc" ], "û": [ "ucirc" ], "У": [ "Ucy" ], "у": [ "ucy" ], "⇅": [ "udarr", "UpArrowDownArrow" ], "Ű": [ "Udblac" ], "ű": [ "udblac" ], "⥮": [ "udhar", "UpEquilibrium" ], "⥾": [ "ufisht" ], "𝔘": [ "Ufr" ], "𝔲": [ "ufr" ], "Ù": [ "Ugrave" ], "ù": [ "ugrave" ], "⥣": [ "uHar" ], "▀": [ "uhblk" ], "⌜": [ "ulcorn", "ulcorner" ], "⌏": [ "ulcrop" ], "◸": [ "ultri" ], "Ū": [ "Umacr" ], "ū": [ "umacr" ], "⏟": [ "UnderBrace" ], "⏝": [ "UnderParenthesis" ], "⊎": [ "UnionPlus", "uplus" ], "Ų": [ "Uogon" ], "ų": [ "uogon" ], "𝕌": [ "Uopf" ], "𝕦": [ "uopf" ], "⤒": [ "UpArrowBar" ], "↕": [ "updownarrow", "UpDownArrow", "varr" ], "υ": [ "upsi", "upsilon" ], "ϒ": [ "Upsi", "upsih" ], "Υ": [ "Upsilon" ], "⇈": [ "upuparrows", "uuarr" ], "⌝": [ "urcorn", "urcorner" ], "⌎": [ "urcrop" ], "Ů": [ "Uring" ], "ů": [ "uring" ], "◹": [ "urtri" ], "𝒰": [ "Uscr" ], "𝓊": [ "uscr" ], "⋰": [ "utdot" ], "Ũ": [ "Utilde" ], "ũ": [ "utilde" ], "Ü": [ "Uuml" ], "ü": [ "uuml" ], "⦧": [ "uwangle" ], "⦜": [ "vangrt" ], "⊊︀": [ "varsubsetneq", "vsubne" ], "⫋︀": [ "varsubsetneqq", "vsubnE" ], "⊋︀": [ "varsupsetneq", "vsupne" ], "⫌︀": [ "varsupsetneqq", "vsupnE" ], "⫨": [ "vBar" ], "⫫": [ "Vbar" ], "⫩": [ "vBarv" ], "В": [ "Vcy" ], "в": [ "vcy" ], "⊩": [ "Vdash" ], "⊫": [ "VDash" ], "⫦": [ "Vdashl" ], "⊻": [ "veebar" ], "≚": [ "veeeq" ], "⋮": [ "vellip" ], "|": [ "verbar", "vert", "VerticalLine" ], "‖": [ "Verbar", "Vert" ], "❘": [ "VerticalSeparator" ], "≀": [ "VerticalTilde", "wr", "wreath" ], "𝔙": [ "Vfr" ], "𝔳": [ "vfr" ], "𝕍": [ "Vopf" ], "𝕧": [ "vopf" ], "𝒱": [ "Vscr" ], "𝓋": [ "vscr" ], "⊪": [ "Vvdash" ], "⦚": [ "vzigzag" ], "Ŵ": [ "Wcirc" ], "ŵ": [ "wcirc" ], "⩟": [ "wedbar" ], "≙": [ "wedgeq" ], "℘": [ "weierp", "wp" ], "𝔚": [ "Wfr" ], "𝔴": [ "wfr" ], "𝕎": [ "Wopf" ], "𝕨": [ "wopf" ], "𝒲": [ "Wscr" ], "𝓌": [ "wscr" ], "𝔛": [ "Xfr" ], "𝔵": [ "xfr" ], "Ξ": [ "Xi" ], "ξ": [ "xi" ], "⋻": [ "xnis" ], "𝕏": [ "Xopf" ], "𝕩": [ "xopf" ], "𝒳": [ "Xscr" ], "𝓍": [ "xscr" ], "Ý": [ "Yacute" ], "ý": [ "yacute" ], "Я": [ "YAcy" ], "я": [ "yacy" ], "Ŷ": [ "Ycirc" ], "ŷ": [ "ycirc" ], "Ы": [ "Ycy" ], "ы": [ "ycy" ], "¥": [ "yen" ], "𝔜": [ "Yfr" ], "𝔶": [ "yfr" ], "Ї": [ "YIcy" ], "ї": [ "yicy" ], "𝕐": [ "Yopf" ], "𝕪": [ "yopf" ], "𝒴": [ "Yscr" ], "𝓎": [ "yscr" ], "Ю": [ "YUcy" ], "ю": [ "yucy" ], "ÿ": [ "yuml" ], "Ÿ": [ "Yuml" ], "Ź": [ "Zacute" ], "ź": [ "zacute" ], "Ž": [ "Zcaron" ], "ž": [ "zcaron" ], "З": [ "Zcy" ], "з": [ "zcy" ], "Ż": [ "Zdot" ], "ż": [ "zdot" ], "ℨ": [ "zeetrf", "Zfr" ], "Ζ": [ "Zeta" ], "ζ": [ "zeta" ], "𝔷": [ "zfr" ], "Ж": [ "ZHcy" ], "ж": [ "zhcy" ], "⇝": [ "zigrarr" ], "𝕫": [ "zopf" ], "𝒵": [ "Zscr" ], "𝓏": [ "zscr" ], "‍": [ "zwj" ], "‌": [ "zwnj" ] };
import React from 'react' import {DeleteWrapper, DelButton} from 'rt/styles/Elements' const DeleteButton = props => { return ( <DeleteWrapper {...props}> <DelButton>&#10006;</DelButton> </DeleteWrapper> ) } export default DeleteButton
"use strict"; function Core(size) { var interactive = true; this._stats = new Stats(); this._stats.setMode(0); this._stats.domElement.style.position = 'absolute'; this._stats.domElement.style.left = '0px'; this._stats.domElement.style.top = '0px'; this._rectangles = []; this._stage = new PIXI.Stage(0x66FF99, interactive); this._renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight); this._collisionAlgo = new AABB(); document.body.appendChild(this._renderer.view); document.body.appendChild(this._stats.domElement); } Core.prototype = { constructor: Core, addRectangle: function () { var rect = new Rectangle(10, 10); rect.index = this._rectangles.length; this._rectangles.push(rect); this._stage.addChild(rect.getGraphics()); }, onResize: function () { this._rectangles.forEach(function (obj) { if (obj.getX() + obj.getWidth() >= window.innerWidth) { obj.setX(window.innerWidth - obj.getWidth()); } if (obj.getY() + obj.getWidth() >= window.innerHeight) { obj.setY(window.innerHeight - obj.getHeight()); } }); this._renderer.resize(window.innerWidth, window.innerHeight); }, algo: function () { }, management: function () { }, setAlgo: function (newAlgo) { this._collisionAlgo = newAlgo; }, getAlgo: function () { return this._collisionAlgo; }, _moveObjects: function () { this._rectangles.forEach(function (obj, index) { obj.updatePosition(); }); }, render: function () { this._stats.begin(); this._moveObjects(); this._collisionAlgo.getCollisions(this._rectangles).forEach(function (obj) { this._rectangles[obj.a].setColor(0xFF0000); this._rectangles[obj.b].setColor(0xFF0000); }.bind(this)); this._renderer.render(this._stage); this._stats.end(); requestAnimationFrame(function () { this.render(); }.bind(this)); } };
import React from 'react'; import translateName from '../util/translateName'; import TextInput from './TextInput'; import { learningHoursTemplate } from '../data/defaultData'; import CollapsiblePanel from './CollapsiblePanel'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as learningHoursActions from '../Actions/learningHoursActions'; import SaveButton from './saveButton'; class LearningHours extends React.Component { updateLearningHours = (learningHoursItem) => { var updatedItem = {}; updatedItem[learningHoursItem.name] = learningHoursItem.value; var newLearningHours = Object.assign({}, this.props.learningHours, updatedItem); this.props.actions.updateLearningHours(newLearningHours); } save = () => { this.props.actions.startSavingLearningHours(this.props.learningHours); } render() { var totalLearningHours = Object.keys(this.props.learningHours).map(a => { return { name: a, value: this.props.learningHours[a] } }); var render = totalLearningHours.map(a => { return ( <TextInput biglabels={true} inputsTemplate={learningHoursTemplate} name={translateName(a.name)} key={a.name} update={(e) => this.updateLearningHours({ name: a.name, value: e.target.value })} propertyname={a.name} value={a.value} /> ) }) return ( <CollapsiblePanel valid={this.props.valid} title="Study Hours"> {render} <div className="sv-form-group sv-col-md-12"> <div className="sv-col-md-3 sv-col-md-offset-9"> <SaveButton loading={this.props.loading} saved={this.props.saved} save={this.save} /> </div> </div> </CollapsiblePanel> ) } } const mapDispatchToProps = function (dispatch, ownProps) { return { actions: bindActionCreators(learningHoursActions, dispatch) } } const mapStateToProps = function (store, ownProps) { return { learningHours: store.learningHours, saved: store.learningHoursSaved, loading: store.learningHoursLoading } } export default connect(mapStateToProps, mapDispatchToProps)(LearningHours);
'use strict'; var $ = require('jquery'); require('jquery-ui'); $.widget('custom.adslide', { _create: function () { var self = this , a = self.element.find("a.slide") , len = a.length , current = 0 , container = a.parent() ; a.css({ display: 'none' }).eq(0).css({ display: 'block' }); function animation () { a.eq(current).animate({ left: -container.width(), opacity: 0 }, 500, function () { a.eq(current).css({ display: 'none' }); current = (current + 1) % len; a.eq(current).css({ display: 'block', opacity: 0, left: container.width() }).animate({ left: 0, opacity: 1 }, 500, function () { setTimeout(animation, 5000); }); }); } setTimeout(animation, 5000); } });
$(document).ready(function() { $('aside > ul > a').click(function() { console.log("link clicked"); var ind = $(this).index() + 2; $('html, body').animate({ scrollTop: $('.post:nth-child(' + ind + ')').offset().top}, 'slow'); return false; }); $("a[href='#top']").click(function() { console.log("going to top"); $("html, body").animate({scrollTop:0}, "slow"); return false; }); });
/* * Profile route */ 'use strict'; var User = require('../models/user'); var Auth = require('../middleware/authorization'); var UI = require("../util/ui_util"); module.exports = function (app, passport) { // View the user's profile app.get("/profile", Auth.isAuthenticated, function (req, res) { res.render("profile", { user: req.user }); }); app.post("/profile", Auth.isAuthenticated, function (req, res, next) { User.saveProfile(req.body, function (err, user) { // XXX If password changed, send email to the user that that happened if (err) { req.flash(err.type, err.message); } else { req.flash('info', "Profile successfully updated."); } res.render('profile', { user: user, flash: UI.bundleFlash(req) }); }); }); }
const fs = require('fs'); const path = require('path'); const { schema } = require('../data/schema'); const { graphql } = require('graphql'); const { introspectionQuery, printSchema } = require('graphql/utilities'); // Save JSON of full schema introspection for Babel Relay Plugin to use (async () => { const result = await (graphql(schema, introspectionQuery)); if (result.errors) { console.error( 'ERROR introspecting schema: ', JSON.stringify(result.errors, null, 2) ); } else { fs.writeFileSync( path.join(__dirname, '../data/schema.json'), JSON.stringify(result, null, 2) ); } })(); // Save user readable type system shorthand of schema fs.writeFileSync( path.join(__dirname, '../data/schema.graphql'), printSchema(schema) );
(function() { 'use strict'; angular .module('wearska') .config(function() { }); })();
'use strict'; //Coupons service used for articles REST endpoint angular.module('mean.admin').factory('Coupons', ['$resource', function($resource) { return $resource('coupons/:couponId', { couponId: '@_id' }, { update: { method: 'PUT' } }); } ]);
'use strict'; var path = require('path'); var assert = require('yeoman-assert'); var helpers = require('yeoman-test'); describe('generator-ng-voi:factory moduleA.someFactory', function () { before(function () { return helpers.run(path.join(__dirname, '../generators/factory')) .withArguments(['moduleA.someFactory']) .toPromise(); }); it('creates factory', function () { assert.file([ 'app/src/moduleA/someFactory.factory.js' ]); }); }); describe('generator-ng-voi:factory someFactory', function () { before(function () { return helpers.run(path.join(__dirname, '../generators/factory')) .withArguments(['someFactory']) .withPrompts({moduleName: 'moduleB'}) .toPromise(); }); it('creates module and factory', function () { assert.file([ 'app/src/moduleB/moduleB.module.js', 'app/src/moduleB/someFactory.factory.js' ]); }); }); describe('generator-ng-voi:factory', function () { before(function () { return helpers.run(path.join(__dirname, '../generators/factory')) .withPrompts({factoryName:'someFactory', moduleName: 'moduleC'}) .toPromise(); }); it('creates module and factory', function () { assert.file([ 'app/src/moduleC/moduleC.module.js', 'app/src/moduleC/someFactory.factory.js' ]); }); });
/* The MIT License (MIT) Copyright (c) 2017 Microsoft Corporation 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. */ "use strict"; var Base = require("../base") , QueryMetrics = require("../queryMetrics/queryMetrics.js") , ClientSideMetrics = require("../queryMetrics/clientSideMetrics.js") , DefaultQueryExecutionContext = require("./defaultQueryExecutionContext") , Constants = require("../constants") , HttpHeaders = require("../constants").HttpHeaders , HeaderUtils = require("./headerUtils") , StatusCodes = require("../statusCodes").StatusCodes , SubStatusCodes = require("../statusCodes").SubStatusCodes , assert = require("assert") //SCRIPT START var DocumentProducer = Base.defineClass( /** * Provides the Target Partition Range Query Execution Context. * @constructor DocumentProducer * @param {DocumentClient} documentclient - The service endpoint to use to create the client. * @param {String} collectionLink - Represents collection link * @param {SqlQuerySpec | string} query - A SQL query. * @param {object} targetPartitionKeyRange - Query Target Partition key Range * @ignore */ function (documentclient, collectionLink, query, targetPartitionKeyRange, options) { this.documentclient = documentclient; this.collectionLink = collectionLink; this.query = query; this.targetPartitionKeyRange = targetPartitionKeyRange; this.fetchResults = []; this.state = DocumentProducer.STATES.started; this.allFetched = false; this.err = undefined; this.previousContinuationToken = undefined; this.continuationToken = undefined; this._respHeaders = HeaderUtils.getInitialHeader(); var isNameBased = Base.isLinkNameBased(collectionLink); var path = this.documentclient.getPathFromLink(collectionLink, "docs", isNameBased); var id = this.documentclient.getIdFromLink(collectionLink, isNameBased); var that = this; var fetchFunction = function (options, callback) { that.documentclient.queryFeed.call(documentclient, documentclient, path, "docs", id, function (result) { return result.Documents; }, function (parent, body) { return body; }, query, options, callback, that.targetPartitionKeyRange["id"]); }; this.internalExecutionContext = new DefaultQueryExecutionContext(documentclient, query, options, fetchFunction); this.state = DocumentProducer.STATES.inProgress; }, { /** * Synchronously gives the contiguous buffered results (stops at the first non result) if any * @returns {Object} - buffered current items if any * @ignore */ peekBufferedItems: function () { var bufferedResults = []; for (var i = 0, done = false; i < this.fetchResults.length && !done; i++) { var fetchResult = this.fetchResults[i]; switch (fetchResult.fetchResultType) { case FetchResultType.Done: done = true; break; case FetchResultType.Exception: done = true; break; case FetchResultType.Result: bufferedResults.push(fetchResult.feedResponse); break; } } return bufferedResults; }, hasMoreResults: function () { return this.internalExecutionContext.hasMoreResults() || this.fetchResults.length != 0; }, gotSplit: function () { var fetchResult = this.fetchResults[0]; if (fetchResult.fetchResultType == FetchResultType.Exception) { if (this._needPartitionKeyRangeCacheRefresh(fetchResult.error)) { return true; } } return false; }, /** * Synchronously gives the buffered items if any and moves inner indices. * @returns {Object} - buffered current items if any * @ignore */ consumeBufferedItems: function () { var res = this._getBufferedResults(); this.fetchResults = []; this._updateStates(undefined, this.continuationToken === null || this.continuationToken === undefined); return res; }, _getAndResetActiveResponseHeaders: function () { var ret = this._respHeaders; this._respHeaders = HeaderUtils.getInitialHeader(); return ret; }, _updateStates: function (err, allFetched) { if (err) { this.state = DocumentProducer.STATES.ended; this.err = err return; } if (allFetched) { this.allFetched = true; } if (this.allFetched && this.peekBufferedItems().length === 0) { this.state = DocumentProducer.STATES.ended; } if (this.internalExecutionContext.continuation === this.continuationToken) { // nothing changed return; } this.previousContinuationToken = this.continuationToken; this.continuationToken = this.internalExecutionContext.continuation; }, _needPartitionKeyRangeCacheRefresh: function (error) { return (error.code === StatusCodes.Gone) && ('substatus' in error) && (error['substatus'] === SubStatusCodes.PartitionKeyRangeGone); }, /** * Fetches and bufferes the next page of results and executes the given callback * @memberof DocumentProducer * @instance * @param {callback} callback - Function to execute for next page of result. * the function takes three parameters error, resources, headerResponse. */ bufferMore: function (callback) { var that = this; if (that.err) { return callback(that.err); } this.internalExecutionContext.fetchMore(function (err, resources, headerResponse) { if (err) { if (that._needPartitionKeyRangeCacheRefresh(err)) { // Split just happend // Buffer the error so the execution context can still get the feedResponses in the itemBuffer var bufferedError = new FetchResult(undefined, err); that.fetchResults.push(bufferedError); // Putting a dummy result so that the rest of code flows return callback(undefined, [bufferedError], headerResponse); } else { that._updateStates(err, resources === undefined); return callback(err, undefined, headerResponse); } } that._updateStates(undefined, resources === undefined); if (resources != undefined) { // some more results resources.forEach(function (element) { that.fetchResults.push(new FetchResult(element, undefined)); }); } // need to modify the header response so that the query metrics are per partition if (headerResponse != null && Constants.HttpHeaders.QueryMetrics in headerResponse) { // "0" is the default partition before one is actually assigned. var queryMetrics = headerResponse[Constants.HttpHeaders.QueryMetrics]["0"]; // Wraping query metrics in a object where the keys are the partition key range. headerResponse[Constants.HttpHeaders.QueryMetrics] = {}; headerResponse[Constants.HttpHeaders.QueryMetrics][that.targetPartitionKeyRange.id] = queryMetrics; } return callback(undefined, resources, headerResponse); }); }, /** * Synchronously gives the bufferend current item if any * @returns {Object} - buffered current item if any * @ignore */ getTargetParitionKeyRange: function () { return this.targetPartitionKeyRange; }, /** * Execute a provided function on the next element in the DocumentProducer. * @memberof DocumentProducer * @instance * @param {callback} callback - Function to execute for each element. the function takes two parameters error, element. */ nextItem: function (callback) { var that = this; if (that.err) { that._updateStates(err, undefined); return callback(that.err); } this.current(function (err, item, headers) { if (err) { that._updateStates(err, item === undefined); return callback(err, undefined, headers); } var fetchResult = that.fetchResults.shift(); that._updateStates(undefined, item === undefined); assert.equal(fetchResult.feedResponse, item); switch (fetchResult.fetchResultType) { case FetchResultType.Done: return callback(undefined, undefined, headers); case FetchResultType.Exception: return callback(fetchResult.error, undefined, headers); case FetchResultType.Result: return callback(undefined, fetchResult.feedResponse, headers); } }); }, /** * Retrieve the current element on the DocumentProducer. * @memberof DocumentProducer * @instance * @param {callback} callback - Function to execute for the current element. the function takes two parameters error, element. */ current: function (callback) { // If something is buffered just give that if (this.fetchResults.length > 0) { var fetchResult = this.fetchResults[0]; //Need to unwrap fetch results switch (fetchResult.fetchResultType) { case FetchResultType.Done: return callback(undefined, undefined, this._getAndResetActiveResponseHeaders()); case FetchResultType.Exception: return callback(fetchResult.error, undefined, this._getAndResetActiveResponseHeaders()); case FetchResultType.Result: return callback(undefined, fetchResult.feedResponse, this._getAndResetActiveResponseHeaders()); } } // If there isn't anymore items left to fetch then let the user know. if (this.allFetched) { return callback(undefined, undefined, this._getAndResetActiveResponseHeaders()); } // If there are no more buffered items and there are still items to be fetched then buffer more var that = this; this.bufferMore(function (err, items, headers) { if (err) { return callback(err, undefined, headers); } if (items === undefined) { return callback(undefined, undefined, headers); } HeaderUtils.mergeHeaders(that._respHeaders, headers); that.current(callback); }); }, }, { // Static Members STATES: Object.freeze({ started: "started", inProgress: "inProgress", ended: "ended" }) } ); var FetchResultType = { "Done": 0, "Exception": 1, "Result": 2 }; var FetchResult = Base.defineClass( /** * Wraps fetch results for the document producer. * This allows the document producer to buffer exceptions so that actual results don't get flushed during splits. * @constructor DocumentProducer * @param {object} feedReponse - The response the document producer got back on a successful fetch * @param {object} error - The exception meant to be buffered on an unsuccessful fetch * @ignore */ function (feedResponse, error) { if (feedResponse) { this.feedResponse = feedResponse; this.fetchResultType = FetchResultType.Result; } else { this.error = error; this.fetchResultType = FetchResultType.Exception; } }, { }, { DoneResult : { fetchResultType: FetchResultType.Done } } ); //SCRIPT END if (typeof exports !== "undefined") { module.exports = DocumentProducer; }
var tswlairmgr = tswlairmgr || {}; tswlairmgr.core.data.addLocalizationData("English", "English", "enUS", { alphabets: { greek: { alpha: "Alpha", beta: "Beta", gamma: "Gamma", delta: "Delta", epsilon: "Epsilon", zeta: "Zeta", eta: "Eta", theta: "Theta", iota: "Iota", kappa: "Kappa", lambda: "Lambda", mu: "Mu", nu: "Nu", xi: "Xi", omicron: "Omicron", pi: "Pi", rho: "Rho", sigma: "Sigma", tau: "Tau", upsilon: "Upsilon", phi: "Phi", chi: "Chi", psi: "Psi", omega: "Omega" }, phoenician: { alaph: "Alaph", beth: "Beth", gamal: "Gamal", dalath: "Dalath", he: "He", waw: "Waw", zain: "Zain", heth: "Heth", teth: "Teth", yudh: "Yudh", kaph: "Kaph", lamadh: "Lamadh", mim: "Mim", nun: "Nun", semkath: "Semkath", // ayin: "", /* Unused so far */ pe: "Pe", sadhe: "Sadhe", qoph: "Qoph", resh: "Resh", shin: "Shin", // taw: "", /* Unused so far */ e: "E" } }, itemNamePatterns: { fragmentLair: "Summoning Ritual Fragment: {{0}}", fragmentRegional: "Cleansing Ritual Fragment: {{0}}", summonLair: "Summoning Ritual: {{0}}", summonRegional: "Cleansing Ritual: {{0}}" }, regions: { sol: { name: "Solomon Island", regionalName: "Aspect of the Long-Toothed", zones: { km: { name: "Kingsmouth", lairs: [ { name: "Duma Beach", bosses: [ { name: "Cta-Tha", missionName: "Unto the Beach" }, { name: "Wreathmother", missionName: "Coralations" }, { name: "Head of Glamr", missionName: "The Last Strand" } ] } ] }, sc: { name: "Savage Coast", lairs: [ { name: "The Overlooked", bosses: [ { name: "Lost Sarcoma", missionName: "Sinking Feelings" }, { name: "Filth.Vector", missionName: "Nobel Calling" }, { name: "Shadow of Depravity", missionName: "The Cover-up" } ] } ] }, bm: { name: "Blue Mountain", lairs: [ { name: "The Casino Pits", bosses: [ { name: "Polluted Effigy", missionName: "The House Always Win" }, { name: "Ferrous Dueller", missionName: "Picking Up the Pieces" }, { name: "Blue Harvester", missionName: "The Whole Truth" } ] } ] } } }, egy: { name: "Egypt", regionalName: "Aspect of the Many-Limbed", zones: { sd: { name: "Scorched Desert", lairs: [ { name: "The Summits", bosses: [ { name: "Eye of the Swarm", missionName: "Return of the Red Nights" }, { name: "Lives-on-Snakes", missionName: "Blood Garments" }, { name: "The Idolator", missionName: "Up In Smoke" } ] } ] }, cs: { name: "City of the Sun God", lairs: [ { name: "The Blighted Kingdom", bosses: [ { name: "Nyarlat, Royal Executioner", missionName: "Citadel of Pain" }, { name: "Hassan, the Ruiner", missionName: "The Trinket Trail" }, { name: "Duneback", missionName: "The Black Pharaoh's Guard" } ] } ] } } }, tra: { name: "Transylvania", regionalName: "Aspect of the Great-Winged", zones: { bf: { name: "Besieged Farmlands", lairs: [ { name: "The Dread Retreat", bosses: [ { name: "Red Revere", missionName: "Midnight Mass" }, { name: "The Plague", missionName: "Blessed Are The Makers" }, { name: "The Scythian", missionName: "Restoration" } ] } ] }, sf: { name: "Shadowy Forest", lairs: [ { name: "The Spoiled Gardens", bosses: [ { name: "She of Woe", missionName: "The Spoils of Cold War" }, { name: "Avatar of the Creep", missionName: "Seedy Underbelly" }, { name: "Dacian Pureblood", missionName: "Kreep Rush" } ] } ] }, cf: { name: "Carpathian Fangs", lairs: [ { name: "The Motherland", bosses: [ { name: "Devourer", missionName: "From Beyond the Iron Curtain" }, { name: "The Voivode", missionName: "The Mortal Coil" }, { name: "Vulkan", missionName: "The Shipping News" } ] } ] } } } } });
import Avatar from './avatar' import Date from './date' import CoverImage from './cover-image' import Link from 'next/link' export default function HeroPost({ title, coverImage, date, excerpt, author, slug, }) { return ( <section> <div className="mb-8 md:mb-16"> <CoverImage title={title} url={coverImage} slug={slug} /> </div> <div className="md:grid md:grid-cols-2 md:col-gap-16 lg:col-gap-8 mb-20 md:mb-28"> <div> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight"> <Link as={`/posts/${slug}`} href="/posts/[slug]"> <a className="hover:underline">{title}</a> </Link> </h3> <div className="mb-4 md:mb-0 text-lg"> <Date dateString={date} /> </div> </div> <div> <p className="text-lg leading-relaxed mb-4">{excerpt}</p> <Avatar name={author.name} picture={author.content.picture} /> </div> </div> </section> ) }
import { polyfill } from 'es6-promise'; import request from 'axios'; import { push } from 'react-router-redux'; import * as types from '../types'; polyfill(); const getMessage = res => res.response && res.response.data && res.response.data.message; function makeUserRequest(method, data, api = '/') { return request[method](api, data); } // Log In Action Creators export function beginLogin() { return { type: types.MANUAL_LOGIN_USER }; } export function loginSuccess(message) { return { type: types.LOGIN_SUCCESS_USER, message }; } export function loginError(message) { return { type: types.LOGIN_ERROR_USER, message }; } // Sign Up Action Creators export function signUpError(message) { return { type: types.SIGNUP_ERROR_USER, message }; } export function beginSignUp() { return { type: types.SIGNUP_USER }; } export function signUpSuccess(message) { return { type: types.SIGNUP_SUCCESS_USER, message }; } // Log Out Action Creators export function beginLogout() { return { type: types.LOGOUT_USER}; } export function logoutSuccess() { return { type: types.LOGOUT_SUCCESS_USER }; } export function logoutError() { return { type: types.LOGOUT_ERROR_USER }; } export function toggleLoginMode() { return { type: types.TOGGLE_LOGIN_MODE }; } export function manualLogin(data) { return dispatch => { dispatch(beginLogin()); return makeUserRequest('post', data, '/login') .then(response => { if (response.status === 200) { dispatch(loginSuccess(response.data.message)); dispatch(push('/dashboard')); } else { dispatch(loginError('Oops! Something went wrong!')); } }) .catch(err => { dispatch(loginError(getMessage(err))); }); }; } export function signUp(data) { return dispatch => { dispatch(beginSignUp()); return makeUserRequest('post', data, '/signup') .then(response => { if (response.status === 200) { dispatch(signUpSuccess(response.data.message)); dispatch(push('/')); } else { dispatch(signUpError('Oops! Something went wrong')); } }) .catch(err => { dispatch(signUpError(getMessage(err))); }); }; } export function logOut() { return dispatch => { dispatch(beginLogout()); return makeUserRequest('post', null, '/logout') .then(response => { if (response.status === 200) { dispatch(logoutSuccess()); } else { dispatch(logoutError()); } }); }; }
describe('Check if gulp is working', function () { it("should be able to calculate",function () { var openPlusOne = 1+1; expect(openPlusOne).toBe(2); }); });
const pkg = require('../package.json') module.exports = key => { return `<!doctype html> <html> <head> <meta charset="utf-8" /> <meta name="description" content="Fair Analytics"> <title>Home - Fair Analytics</title> <style type="text/css"> html, body { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; } a { color: #0366d6; text-decoration: none; } pre { border: 1px solid rgb(234, 234, 234); padding: 3px; margin: 40px 0px; white-space: pre; overflow: auto; } code { color: tomato; font-size: 13px; line-height: 20px; } #root { padding: 10px; } .tac { text-align: center; } </style> </head> <body> <div id='root'> <h1>Fair Analytics</h1> <h4>v${pkg.version}</h4> <ul> <li><a href="https://github.com/vesparny/fair-analytics">Fair Analytics source code</a></li> <li><a href="https://github.com/vesparny/fair-analytics/#readme">Fair Analytics complete documentation</a></li> </ul> <div><h3>The public key for accessing raw data tracked by this instance is:</h3></div> <hr> <div><b>${key}</b></div> <hr> <b>Example: </b> <pre> <code> // replicate the feed to another one // useful when you want to store raw data to another machine // or when you want to process it somehow (like storing it to another database) const hypercore = require('hypercore') const swarm = require('hyperdiscovery') const KEY = '${key}' const LOCALPATH = './replicated.dataset' const feed = hypercore(LOCALPATH, KEY, {valueEncoding: 'json'}) swarm(feed) feed.on('ready', () => { // this configuration will download all the feed // and process new incoming data // via the feed.on('data') callback // in case you want to process all the feed (old and new) // use only {tail: true, tail: true} feed.createReadStream({ tail: true, live: true, start: feed.length, snapshot: false }) .on('data', console.log) }) </code> </pre> <b>Then run it: </b> <pre> <code> node replicate.js </code> </pre> <hr> <div class='tac'>with ❤️ from <a href="https://twitter.com/vesparny">@vesparny</a></div> </div> </body> </html> ` }
/** * Created by leo on 3/26/15. */ var Sails = require('sails'); var Barrels = require('barrels'); var port = 8010; require('should'); // Global before hook before(function (done) { this.timeout(25000); // Lift Sails with test database Sails.lift({ port:port, globals:{ sails:true }, log: { level: 'error' }, models: { connection: 'localDiskDb', migrate: 'drop' } }, function(err, sails) { if (err) return done(err); // Load fixtures var barrels = new Barrels(); // Save original objects in `fixtures` variable fixtures = barrels.data; // Populate the DB barrels.populate(function(err) { done(err, sails); }); }); }); // Global after hook after(function (done) { sails.log.verbose(); // Skip a line before displaying Sails lowering logs sails.lower(function() { done(); }); });
// Source : https://leetcode.com/problems/climbing-stairs // Author : Dean Shi // Date : 2017-07-10 /*************************************************************************************** * * You are climbing a stair case. It takes n steps to reach to the top. * * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb * to the top? * * Note: Given n will be a positive integer. * * ***************************************************************************************/ /** * @param {number} n * @return {number} */ var climbStairs = function(n) { let [curr, next] = [1, 2] while (--n) { [curr, next] = [next, curr + next] } return curr }; /** * Solution in DP * * @param {number} n * @return {number} */ var climbStairs = function(n) { const dp = [0, 1, 2] for(let i = 3; i <= n; ++i) { dp[i] = dp[i-1] + dp[i-2] } return dp[n] };
// // This acts as the server from the front end React application // and is used for CRUD operations on the task and note models. // // TODO (Connor)
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import { PLATFORM } from 'aurelia-pal'; function isObject(val) { return val && (typeof val === 'function' || typeof val === 'object'); } export const metadata = { resource: 'aurelia:resource', paramTypes: 'design:paramtypes', propertyType: 'design:type', properties: 'design:properties', get(metadataKey, target, targetKey) { if (!isObject(target)) { return undefined; } let result = metadata.getOwn(metadataKey, target, targetKey); return result === undefined ? metadata.get(metadataKey, Object.getPrototypeOf(target), targetKey) : result; }, getOwn(metadataKey, target, targetKey) { if (!isObject(target)) { return undefined; } return Reflect.getOwnMetadata(metadataKey, target, targetKey); }, define(metadataKey, metadataValue, target, targetKey) { Reflect.defineMetadata(metadataKey, metadataValue, target, targetKey); }, getOrCreateOwn(metadataKey, Type, target, targetKey) { let result = metadata.getOwn(metadataKey, target, targetKey); if (result === undefined) { result = new Type(); Reflect.defineMetadata(metadataKey, result, target, targetKey); } return result; } }; const originStorage = new Map(); const unknownOrigin = Object.freeze({ moduleId: undefined, moduleMember: undefined }); export let Origin = class Origin { constructor(moduleId, moduleMember) { this.moduleId = moduleId; this.moduleMember = moduleMember; } static get(fn) { let origin = originStorage.get(fn); if (origin === undefined) { PLATFORM.eachModule((key, value) => { if (typeof value === 'object') { let isBrowserWindow = typeof window !== 'undefined' && value === window; for (let name in value) { if (isBrowserWindow && name === 'webkitStorageInfo') { continue; } try { let exp = value[name]; if (exp === fn) { originStorage.set(fn, origin = new Origin(key, name)); return true; } } catch (e) {} } } if (value === fn) { originStorage.set(fn, origin = new Origin(key, 'default')); return true; } return false; }); } return origin || unknownOrigin; } static set(fn, origin) { originStorage.set(fn, origin); } }; export function decorators(...rest) { let applicator = function (target, key, descriptor) { let i = rest.length; if (key) { descriptor = descriptor || { value: target[key], writable: true, configurable: true, enumerable: true }; while (i--) { descriptor = rest[i](target, key, descriptor) || descriptor; } Object.defineProperty(target, key, descriptor); } else { while (i--) { target = rest[i](target) || target; } } return target; }; applicator.on = applicator; return applicator; } export function deprecated(optionsOrTarget, maybeKey, maybeDescriptor) { function decorator(target, key, descriptor) { const methodSignature = `${target.constructor.name}#${key}`; let options = maybeKey ? {} : optionsOrTarget || {}; let message = `DEPRECATION - ${methodSignature}`; if (typeof descriptor.value !== 'function') { throw new SyntaxError('Only methods can be marked as deprecated.'); } if (options.message) { message += ` - ${options.message}`; } return _extends({}, descriptor, { value: function deprecationWrapper() { if (options.error) { throw new Error(message); } else { console.warn(message); } return descriptor.value.apply(this, arguments); } }); } return maybeKey ? decorator(optionsOrTarget, maybeKey, maybeDescriptor) : decorator; } export function mixin(behavior) { const instanceKeys = Object.keys(behavior); function _mixin(possible) { let decorator = function (target) { let resolvedTarget = typeof target === 'function' ? target.prototype : target; let i = instanceKeys.length; while (i--) { let property = instanceKeys[i]; Object.defineProperty(resolvedTarget, property, { value: behavior[property], writable: true }); } }; return possible ? decorator(possible) : decorator; } return _mixin; } function alwaysValid() { return true; } function noCompose() {} function ensureProtocolOptions(options) { if (options === undefined) { options = {}; } else if (typeof options === 'function') { options = { validate: options }; } if (!options.validate) { options.validate = alwaysValid; } if (!options.compose) { options.compose = noCompose; } return options; } function createProtocolValidator(validate) { return function (target) { let result = validate(target); return result === true; }; } function createProtocolAsserter(name, validate) { return function (target) { let result = validate(target); if (result !== true) { throw new Error(result || `${name} was not correctly implemented.`); } }; } export function protocol(name, options) { options = ensureProtocolOptions(options); let result = function (target) { let resolvedTarget = typeof target === 'function' ? target.prototype : target; options.compose(resolvedTarget); result.assert(resolvedTarget); Object.defineProperty(resolvedTarget, 'protocol:' + name, { enumerable: false, configurable: false, writable: false, value: true }); }; result.validate = createProtocolValidator(options.validate); result.assert = createProtocolAsserter(name, options.validate); return result; } protocol.create = function (name, options) { options = ensureProtocolOptions(options); let hidden = 'protocol:' + name; let result = function (target) { let decorator = protocol(name, options); return target ? decorator(target) : decorator; }; result.decorates = function (obj) { return obj[hidden] === true; }; result.validate = createProtocolValidator(options.validate); result.assert = createProtocolAsserter(name, options.validate); return result; };
import Helmet from 'react-helmet'; import PropTypes from 'prop-types'; import React from 'react'; import { StaticQuery, graphql } from 'gatsby'; const SEO = ({ description, lang, meta, path, title }) => ( <StaticQuery query={graphql` query DefaultSEOQuery { site { siteMetadata { author description siteUrl title } } } `} render={({ site: { siteMetadata } }) => { const metaDescription = description || siteMetadata.description; return ( <Helmet htmlAttributes={{ lang }} meta={[ { content: 'summary', name: 'twitter:card' }, { content: 'website', property: 'og:type' }, { content: metaDescription, name: 'description' }, { content: metaDescription, name: 'twitter:description' }, { content: metaDescription, property: 'og:description' }, { content: siteMetadata.author, name: 'twitter:creator' }, { content: title || siteMetadata.title, name: 'twitter:title' }, { content: title || siteMetadata.title, property: 'og:title' }, ].concat(meta)} title={title || siteMetadata.title} titleTemplate={ title && path !== '/' ? `%s | ${siteMetadata.title}` : '%s' } > <link href={`${siteMetadata.siteUrl}${path}`} rel="canonical" /> <script type="application/ld+json"> {JSON.stringify({ '@context': 'http://schema.org/', '@type': 'Person', description: siteMetadata.description, email: 'email@cade.me', familyName: 'Scroggins', givenName: 'Cade', jobTitle: 'Software Engineering Lead', mainEntityOfPage: siteMetadata.siteUrl, name: 'Cade Scroggins', sameAs: [ 'https://github.com/cadejscroggins', 'https://www.linkedin.com/in/cadejscroggins', 'https://www.instagram.com/cadejscroggins', 'https://twitter.com/cadejscroggins', ], worksFor: { '@type': 'Organization', description: 'An insurtech solutions provider with a focus on machine learning.', mainEntityOfPage: 'https://spraoi.ai', name: 'Spraoi', }, })} </script> </Helmet> ); }} /> ); SEO.propTypes = { description: PropTypes.string, lang: PropTypes.string, meta: PropTypes.arrayOf( PropTypes.shape({ content: PropTypes.string, name: PropTypes.string, property: PropTypes.string, }) ), path: PropTypes.string, title: PropTypes.string, }; SEO.defaultProps = { description: null, lang: 'en', meta: [], path: '/', title: null, }; export default SEO;
(function(b,r){b.widget("mobile.lazyloader",b.mobile.widget,{_defaultOptions:{threshold:b(window).height(),retrieve:20,retrieved:20,bubbles:!1,offset:0,limit:0},_defaultParameters:{retrieve:20,retrieved:20,offset:0},_defaultSettings:{pageId:"",templateType:"",templatePrecompiled:!1,templateId:"",template:"",mainId:"",progressDivId:"",moreUrl:"",clearUrl:"",JSONP:!1,JSONPCallback:""},_defaultSelectors:{main:"ul",single:"ul li",bottom:'[data-role="list-divider"]'},_handleScrollStartJustFired:!1,_handleScrollStopJustFired:!1, _mouseWheelEventJustFired:!1,_handleScrollStartTimeoutId:null,_handleScrollStopTimeoutId:null,_mouseWheelTimeoutId:null,_instances:{},_moreOutstandingPageId:null,_parameters:null,_settings:null,_selectors:null,timeoutOptions:{mousewheel:350,scrollstart:500,scrollstop:50,showprogress:200,scrolldown:400,immediately:0},_widgetName:"lazyloader",_widgetState:{busy:!1,done:!1,limit:!1},_create:function(){this._initialize(this._defaultOptions,this._defaultSettings,this._defaultParameters,this._defaultSelectors); this._bind()},_init:function(){},_initialize:function(a,d,c,e){if("undefined"!=typeof a&&""!=a&&(this._widgetState.busy=!1,this._widgetState.done=!1,this._widgetState.limit=!1,this._settings=b.extend(!0,this._settings,this._defaultSettings),this._settings=b.extend(!0,this._settings,d),"undefined"!==typeof this._settings.mainId&&""!==this._settings.mainId&&(this._defaultSelectors.main="#"+this._settings.mainId,this._defaultSelectors.single="#"+this._settings.mainId+" li",this._defaultSelectors.bottom= '[data-role="list-divider"]'),"undefined"!==typeof this._settings.pageId&&""!==this._settings.pageId&&(this._settings.totalHeight=b("#"+this._settings.pageId).height()),this._selectors=b.extend(!0,this._selectors,this._defaultSelectors),this._selectors=b.extend(!0,this._selectors,e),this._parameters=b.extend(!0,this._parameters,this._defaultParameters),this._parameters=b.extend(!0,this._parameters,c),this.options=b.extend(!0,this.options,this._defaultOptions),this.options=b.extend(!0,this.options, a),a=d.pageId,"undefined "!=typeof a&&""!=a&&!this._instances[a])){if(("undefined"==typeof this._settings.template||""==this._settings.template)&&"undefined"!=typeof this._settings.templateId&&""!=this._settings.templateId)d=b("#"+this._settings.templateId).html(),c="",e=this._settings.templatePrecompiled,"undefined"!=typeof this._settings.templateType&&""!=this._settings.templateType&&(c=this._settings.templateType),this._settings.template="dust"===c&&""!==d&&!e?dust.compile(d,this._settings.templateId): d;this._instances[a]=[];this._instances[a].options=b.extend(!0,{},this.options);this._instances[a].settings=b.extend(!0,{},this._settings);this._instances[a].selectors=b.extend(!0,{},this._selectors);0<this._instances[a].options.limit&&this._instances[a].options.limit<this._instances[a].options.retrieved&&(this._widgetState.done=!0,this._widgetState.limit=!0,message="Limit must be greater than the number of items listed by default (i.e. 'retrieved' by default)",this._triggerEvent("error","_load", message))}},_bind:function(){b("body").bind("scrollstart",b.proxy(this._handleScrollStart,this));b("body").bind("scrollstop",b.proxy(this._handleScrollStop,this));/Firefox/i.test(navigator.userAgent)?b(window).bind("DOMMouseScroll",b.proxy(this._handleMouseWheelEvent,this)):"undefined"!=typeof this._selectors&&null!=this._selectors&&""!=this._selectors&&"undefined"!=typeof this._selectors.main&&(b(this._selectors.main).attachEvent?b(window).bind("onmousewheel",b.proxy(this._handleMouseWheelEvent, this)):b(window).bind("mousewheel",b.proxy(this._handleMouseWheelEvent,this)))},_unbind:function(){b("body").unbind("scrollstart",this._handleScrollStart);b("body").unbind("scrollstop",this._handleScrollStop);/Firefox/i.test(navigator.userAgent)?b(window).unbind("DOMMouseScroll",this._handleMouseWheelEvent):"undefined"!=typeof this._selectors&&null!=this._selectors&&""!=this._selectors&&"undefined"!=typeof this._selectors.main&&(b(this._selectors.main).attachEvent?b(window).unbind("onmousewheel", this._handleMouseWheelEvent):b(window).unbind("mousewheel",this._handleMouseWheelEvent))},destroy:function(){this._unbind();this._defaultParameters=this._defaultSettings=this._defaultOptions=this._widgetState=this._mouseWheelTimeoutId=this._handleScrollStopTimeoutId=this._handleScrollStartTimeoutId=this._mouseWheelEventJustFired=this._handleScrollStopJustFired=this._handleScrollStartJustFired=this._instances=this._parameters=this._settings=this.timeoutOptions=this.options=null;b.Widget.prototype.destroy.apply(this)}, _check:function(a){a=this.options.threshold||a;var d,c,e;c=document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop;d=this._instances[this._settings.pageId]?this._instances[this._settings.pageId].settings.totalHeight:this._settings.totalHeight;e=b(window).height();return d-a<=c+e},_load:function(a){typeof this._settings.pageId!=r&&""!=this._settings.pageId&&(b(".ui-page-active").attr("id")==this._settings.pageId?(this._moreOutstandingPageId=this._settings.pageId, $that=this,setTimeout(function(){!$that._widgetState.busy&&!$that._widgetState.done&&!$that._widgetState.limit?$that._moreOutstandingPageId==$that._settings.pageId&&($that._check($that.options.threshold)||0===a)&&b("#"+$that._settings.progressDivId).show($that.timeoutOptions.showprogress,function(){moreUrl=$that._settings.moreUrl;var a="POST",c="json",e="",n=!1,p="",h=0;$that._instances[$that._settings.pageId]?($that._parameters.retrieve=$that._instances[$that._settings.pageId].options.retrieve,$that._parameters.retrieved= $that._instances[$that._settings.pageId].options.retrieved,$that._parameters.offset=$that._instances[$that._settings.pageId].options.offset,0<$that._instances[$that._settings.pageId].options.limit&&$that._instances[$that._settings.pageId].options.retrieved+$that._instances[$that._settings.pageId].options.retrieve>=$that._instances[$that._settings.pageId].options.limit&&($that._parameters.retrieve=$that._instances[$that._settings.pageId].options.limit>=$that._instances[$that._settings.pageId].options.retrieved? $that._instances[$that._settings.pageId].options.limit-$that._instances[$that._settings.pageId].options.retrieved:0),$that._instances[$that._settings.pageId].settings.JSONP&&(n=!0,p=$that._instances[$that._settings.pageId].settings.JSONPCallback)):($that._parameters.retrieve=$that.options.retrieve,$that._parameters.retrieved=$that.options.retrieved,$that._parameters.offset=$that.options.offset,0<$that.options.limit&&$that.options.retrieve+$that.options.retrieved>=$that.options.limit&&($that._parameters.retrieve= $that.options.limit>=$that.options.retrieve?$that.options.limit-$that.options.retrieve:0));if("undefined"!=typeof $that._settings.pageId&&""!=$that._settings.pageId){var q=b("#"+$that._settings.pageId).find('[type="hidden"]');for(i=0;i<q.length;i++){var k=b(q).get(i);"undefined"!=typeof b(k).attr("id")&&""!=b(k).attr("id")&&($that._parameters[b(k).attr("id")]=escape(b(k).val()))}}if(n){a="GET";c="jsonp";e="";for(f in $that._parameters)e=0==h?e+('"'+f+'": "'+$that._parameters[f]+'"'):e+(', "'+f+'": "'+ $that._parameters[f]+'"'),h+=1;e=b.parseJSON("{ "+e+" }")}else for(var f in $that._parameters)e=0==h?e+(f+"="+$that._parameters[f]):e+("&"+f+"="+$that._parameters[f]),h+=1;b.ajax({type:a,url:moreUrl,dataType:c,jsonpCallback:p,data:e,success:function(a){more=a;if("object"!==typeof a)try{more=b.parseJSON(a)}catch(c){return $that._triggerEvent("error","_load",c.message),b("#"+$that._settings.progressDivId).hide(250,function(){$that._widgetState.busy=!1}),!1}try{var d=more.data[0].count,e="",g="",j="", f="",h="",k=!1,m="",n=a="",l="";if(0<d){m=$that._selectors.main;a=$that._selectors.single;n=$that._selectors.bottom;l=$that._getBottomElement(m,n);if("undefined"!=typeof more.data[0].html&&""!=more.data[0].html)e=more.data[0].html,l?b(a).last().before(e):b(m).append(e);else if($that._instances[$that._settings.pageId]?("undefined"!=typeof $that._instances[$that._settings.pageId].settings.templateId&&""!=$that._instances[$that._settings.pageId].settings.templateId&&(f=$that._instances[$that._settings.pageId].settings.templateId, "undefined"!=typeof $that._instances[$that._settings.pageId].settings.templateType&&""!=$that._instances[$that._settings.pageId].settings.templateType&&(h=$that._instances[$that._settings.pageId].settings.templateType),"undefined"!=typeof $that._instances[$that._settings.pageId].settings.template&&""!=$that._instances[$that._settings.pageId].settings.template&&(j=$that._instances[$that._settings.pageId].settings.template)),k=$that._instances[$that._settings.pageId].settings.templatePrecompiled):("undefined"!= typeof $that._settings.templateId&&""!=$that._settings.templateId&&(f=$that._settings.templateId,"undefined"!=typeof $that._settings.templateType&&""!=$that._settings.templateType&&(h=$that._settings.templateType),"undefined"!=typeof $that._settings.template&&""!=$that._settings.template&&(j=$that._settings.template)),k=$that._settings.templatePrecompiled),""!==h&&""!==f&&""!==j)if("json2html"===h)g=more.data[0].json,l&&l.remove(),b(m).json2html(g,j),l&&b(a).last().append(l);else{g=more.data[0];switch(h){case "handlebars":j= k?Handlebars.templates[f+".tmpl"]:Handlebars.compile(j);e=j(g);break;case "icanhaz":ich.addTemplate("listitem",j);e=ich.listitem(g,!0);ich.clearAll();break;case "dust":k?dust.render(f,g,function(a,b){e=b}):(dust.loadSource(j),dust.render(f,g,function(a,b){e=b}));break;case "dot":j=doT.template(j),e=j(g)}l?b(a).last().before(e):b(m).append(e)}b(m).listview("refresh");g=0;d=parseInt(d);if($that._instances[$that._settings.pageId]){var p=$that._instances[$that._settings.pageId].settings.totalHeight;"undefined"!== typeof $that._instances[$that._settings.pageId].settings.singleItemHeight?g=$that._instances[$that._settings.pageId].settings.singleItemHeight:(g=b(a).first().next().height(),$that._instances[$that._settings.pageId].settings.singleItemHeight=g);$that._instances[$that._settings.pageId].settings.totalHeight=p+g*d}else"undefined"!==typeof $that._settings.singleItemHeight?g=$that._settings.singleItemHeight:(g=b(a).first().next().height(),$that._settings.singleItemHeight=g),$that._settings.totalHeight+= $that._settings.singleItemHeight*d;$that._instances[$that._settings.pageId].options.retrieved+=d;0<$that._instances[$that._settings.pageId].options.limit&&$that._instances[$that._settings.pageId].options.retrieved==$that._instances[$that._settings.pageId].options.limit&&($that._widgetState.limit=!0,$that._triggerEvent("limitreached","_load"));if(d<$that._instances[$that._settings.pageId].options.retrieve||"all"==$that._instances[$that._settings.pageId].options.retrieve)$that._widgetState.done=!0, $that._triggerEvent("alldone","_load")}else $that._widgetState.done=!0,$that._triggerEvent("alldone","_load");b("#"+$that._settings.progressDivId).hide(250,function(){$that._widgetState.busy=!1});$that._triggerEvent("doneloading","_load")}catch(q){return $that._triggerEvent("error","_load",q.message),b("#"+$that._settings.progressDivId).hide(250,function(){$that._widgetState.busy=!1}),!1}},error:function(a){$that._triggerEvent("error","_load",a);b("#"+$that._settings.progressDivId).hide(250,function(){$that._widgetState.busy= !1})},complete:function(){}})}):$that._widgetState.done?($that._triggerEvent("alldone","_load"),$that._widgetState.limit&&$that._triggerEvent("limited","_load")):$that._widgetState.busy&&$that._triggerEvent("busy","_load")},a)):b("#"+this._settings.progressDivId).hide(250,function(){"undefined"!=typeof this._widgetState&&(this._widgetState.busy=!1)}))},_getBottomElement:function(a,d){var c=b(a).last().find(d);switch(c.length){case 2:c=c.last();break;default:c=null}return"undefined"!=typeof c&&null!= c&&""!=c&&"null"!=c?c:!1},_handleMouseWheelEvent:function(){if(!this._mouseWheelEventJustFired&&!this._handleScrollStopJustFired&&!this._handleScrollStartJustFired){this._mouseWheelEventJustFired=!0;this._load(this.timeoutOptions.mousewheel);var a=this;this._mouseWheelTimeoutId=setTimeout(function(){a._mouseWheelEventJustFired=!1},1E3)}},_handleScrollStart:function(){if(!this._mouseWheelEventJustFired&&!this._handleScrollStopJustFired&&!this._handleScrollStartJustFired){this._handleScrollStartJustFired= !0;this._load(this.timeoutOptions.scrollstart);var a=this;this._handleScrollStartTimeoutId=setTimeout(function(){a._handleScrollStartJustFired=!1},1200)}},_handleScrollStop:function(){if(!this._mouseWheelEventJustFired&&!this._handleScrollStopJustFired&&!this._handleScrollStartJustFired){this._handleScrollStopJustFired=!0;this._load(this.timeoutOptions.scrollstop);var a=this;this._handleScrollStopTimeoutId=setTimeout(function(){a._handleScrollStopJustFired=!1},1200)}},loadMore:function(a){0===a?this._load(this.timeoutOptions.immediately): this._load(this.timeoutOptions.scrolldown)},_setOption:function(a,d){this._instances[this._settings.pageId]&&this._instances[this._settings.pageId].options[a]&&(this._instances[this._settings.pageId].options[a]=d);b.Widget.prototype._setOption.apply(this,arguments)},refresh:function(a,d){if("parameters"==a){if("undefined"!=typeof this.options)for(var c in this._parameters)"undefined"!=typeof this.options[c]&&(this._parameters[c]=this.options[c])}else"parameter"==a&&(c=d,"undefined"!=typeof this.options[c]&& (this._parameters[c]=this.options[c]));c=JSON.stringify(this._parameters);this._parameters=b.parseJSON(c)},reInitialize:function(a,b,c,e){this._initialize(a,b,c,e)},reset:function(a){var d=this;b.ajax({type:"POST",url:d._settings.clearUrl,async:!0,data:"section="+a,success:function(b){parseInt(b)&&(d.options.retrieved=d._defaultOptions.retrieved,d._widgetState.done=!1,d._widgetState.limit=!1,"undefined"!=typeof d._instances[a]&&delete d._instances[a],d._triggerEvent("reset","reset","All session variables for the '"+ a+"' page and the lazyloader instance variables have been cleared."))},error:function(a){d._triggerEvent("error","reset",a);b("#"+d._settings.progressDivId).hide(250,function(){d._widgetState.busy=!1})}})},resetAll:function(){var a=this;b.ajax({type:"POST",url:a._settings.clearUrl,async:!0,data:"",success:function(b){if(parseInt(b)){for(pageId in a._instances)delete a._instances[pageId];a.options.retrieved=a._defaultOptions.retrieved;a._widgetState.done=!1;a._widgetState.busy=!1;a._widgetState.limit= !1;a._triggerEvent("resetall","resetAll","All session variables for all pages currently being tracked by the lazyloader have been cleared.")}}})},_triggerEvent:function(a,b,c){c=c||"";switch(a){case "error":case "resetall":this._trigger(a,{type:"lazyloader"+a,"function":b,message:c,settings:this._settings,options:this.options,parameters:this._parameters});break;default:this._trigger(a,{type:"lazyloader"+a,"function":b,message:c,pageId:this._settings.pageId,mainId:this._settings.mainId,loaded:this.options.retrieved})}}}); b(document).bind("pagecreate create",function(a){b.mobile.lazyloader.prototype.enhanceWithin(a.target)})})(jQuery);
/* * Also import the necessary CSS into the app. * * Example: * import 'quasar-extras/animate/bounceInLeft.css' */ export default { name: 'q-transition', functional: true, props: { name: String, enter: String, leave: String, group: Boolean }, render (h, ctx) { const prop = ctx.props, data = ctx.data if (prop.name) { data.props = { name: prop.name } } else if (prop.enter && prop.leave) { data.props = { enterActiveClass: `animated ${prop.enter}`, leaveActiveClass: `animated ${prop.leave}` } } else { return ctx.children } return h(`transition${ctx.props.group ? '-group' : ''}`, data, ctx.children) } }
!function(e){function o(){e.simpleDB.open(r).then(function(o){o.forEach(function(t,n){var r=Date.now()-n,i=t+"&qt="+r;console.log("About to replay:",i),e.fetch(i).then(function(e){return e.status>=500?Response.error():(console.log("Replay succeeded:",i),void o["delete"](t))})["catch"](function(e){r>l?(console.error("Replay failed, but the original request is too old to retry any further. Error:",e),o["delete"](t)):console.error("Replay failed, and will be retried the next time the service worker starts. Error:",e)})})})}function t(o){console.log("Queueing failed request:",o),e.simpleDB.open(r).then(function(e){e.set(o.url,Date.now())})}function n(o){return e.fetch(o).then(function(e){return e.status>=500?Response.error():e})["catch"](function(){t(o)})}var r="offline-analytics",l=864e5,i=/https?:\/\/((www|ssl)\.)?google-analytics\.com/;e.toolbox.router.get("/collect",n,{origin:i}),e.toolbox.router.get("/analytics.js",e.toolbox.networkFirst,{origin:i}),o()}(self);
'use strict'; var assign = require('es5-ext/object/assign') , callable = require('es5-ext/object/valid-callable') , path = require('path') , readdir = require('fs').readdir , Mocha = require("mocha") , Promise = require('./') , Deferred = require('./deferred') , resolve = path.resolve, extname = path.extname , testsDir = resolve(__dirname, 'node_modules/promises-aplus-tests/lib/tests') , adapter, ignore; ignore = { '2.3.1': true, // Circular resolution '2.3.3': true // Thenables (support for foreign promises or promise-likes) }; adapter = { resolved: Promise.resolve, rejected: Promise.reject, deferred: function () { return new Deferred(); } }; module.exports = function (mochaOpts, cb) { if (typeof mochaOpts === "function") { cb = mochaOpts; mochaOpts = {}; } else { mochaOpts = Object(mochaOpts); } callable(cb); mochaOpts = assign({ timeout: 200, slow: Infinity, bail: true }, mochaOpts); readdir(testsDir, function (err, testFileNames) { if (err) { cb(err); return; } var mocha = new Mocha(mochaOpts); testFileNames.forEach(function (testFileName) { var testFilePath; if (extname(testFileName) !== ".js") return; if (ignore[testFileName.slice(0, -3)]) return; testFilePath = resolve(testsDir, testFileName); mocha.addFile(testFilePath); }); global.adapter = adapter; mocha.run(function (failures) { var err; delete global.adapter; if (failures > 0) { err = new Error("Test suite failed with " + failures + " failures."); err.failures = failures; cb(err); } else { cb(null); } }); }); };
var searchData= [ ['dataloggrammarbasevisitor_335',['DatalogGrammarBaseVisitor',['../classDatalogGrammarBaseVisitor.html',1,'']]], ['dataloggrammarbasevisitor_3c_20object_20_3e_336',['DatalogGrammarBaseVisitor&lt; object &gt;',['../classDatalogGrammarBaseVisitor.html',1,'']]], ['dataloggrammarparser_337',['DatalogGrammarParser',['../classDatalogGrammarParser.html',1,'']]], ['dataloginputprogram_338',['DatalogInputProgram',['../classit_1_1unical_1_1mat_1_1embasp_1_1languages_1_1datalog_1_1DatalogInputProgram.html',1,'it::unical::mat::embasp::languages::datalog']]], ['datalogmapper_339',['DatalogMapper',['../classit_1_1unical_1_1mat_1_1embasp_1_1languages_1_1datalog_1_1DatalogMapper.html',1,'it::unical::mat::embasp::languages::datalog']]], ['datalogparser_340',['DatalogParser',['../classit_1_1unical_1_1mat_1_1parsers_1_1datalog_1_1DatalogParser.html',1,'it::unical::mat::parsers::datalog']]], ['desktophandler_341',['DesktopHandler',['../classit_1_1unical_1_1mat_1_1embasp_1_1platforms_1_1desktop_1_1DesktopHandler.html',1,'it::unical::mat::embasp::platforms::desktop']]], ['desktopservice_342',['DesktopService',['../classit_1_1unical_1_1mat_1_1embasp_1_1platforms_1_1desktop_1_1DesktopService.html',1,'it::unical::mat::embasp::platforms::desktop']]], ['dlv2answersets_343',['DLV2AnswerSets',['../classit_1_1unical_1_1mat_1_1embasp_1_1specializations_1_1dlv2_1_1DLV2AnswerSets.html',1,'it::unical::mat::embasp::specializations::dlv2']]], ['dlv2desktopservice_344',['DLV2DesktopService',['../classit_1_1unical_1_1mat_1_1embasp_1_1specializations_1_1dlv2_1_1desktop_1_1DLV2DesktopService.html',1,'it::unical::mat::embasp::specializations::dlv2::desktop']]], ['dlv2parserbasevisitor_345',['DLV2ParserBaseVisitor',['../classDLV2ParserBaseVisitor.html',1,'']]], ['dlv2parserbasevisitor_3c_20object_20_3e_346',['DLV2ParserBaseVisitor&lt; object &gt;',['../classDLV2ParserBaseVisitor.html',1,'']]], ['dlv2parserbasevisitorimplementation_347',['DLV2ParserBaseVisitorImplementation',['../classit_1_1unical_1_1mat_1_1parsers_1_1asp_1_1dlv2_1_1DLV2ParserBaseVisitorImplementation.html',1,'it::unical::mat::parsers::asp::dlv2']]], ['dlvanswersets_348',['DLVAnswerSets',['../classit_1_1unical_1_1mat_1_1embasp_1_1specializations_1_1dlv_1_1DLVAnswerSets.html',1,'it::unical::mat::embasp::specializations::dlv']]], ['dlvdesktopservice_349',['DLVDesktopService',['../classit_1_1unical_1_1mat_1_1embasp_1_1specializations_1_1dlv_1_1desktop_1_1DLVDesktopService.html',1,'it::unical::mat::embasp::specializations::dlv::desktop']]], ['dlvfilteroption_350',['DLVFilterOption',['../classit_1_1unical_1_1mat_1_1embasp_1_1specializations_1_1dlv_1_1DLVFilterOption.html',1,'it::unical::mat::embasp::specializations::dlv']]], ['dlvhexanswersets_351',['DLVHEXAnswerSets',['../classit_1_1unical_1_1mat_1_1embasp_1_1specializations_1_1dlvhex_1_1DLVHEXAnswerSets.html',1,'it::unical::mat::embasp::specializations::dlvhex']]], ['dlvhexdesktopservice_352',['DLVHEXDesktopService',['../classit_1_1unical_1_1mat_1_1embasp_1_1specializations_1_1dlvhex_1_1desktop_1_1DLVHEXDesktopService.html',1,'it::unical::mat::embasp::specializations::dlvhex::desktop']]], ['dlvhexparserbasevisitor_353',['DLVHEXParserBaseVisitor',['../classDLVHEXParserBaseVisitor.html',1,'']]], ['dlvhexparserbasevisitor_3c_20object_20_3e_354',['DLVHEXParserBaseVisitor&lt; object &gt;',['../classDLVHEXParserBaseVisitor.html',1,'']]], ['dlvhexparserbasevisitorimplementation_355',['DLVHEXParserBaseVisitorImplementation',['../classit_1_1unical_1_1mat_1_1parsers_1_1asp_1_1dlvhex_1_1DLVHEXParserBaseVisitorImplementation.html',1,'it::unical::mat::parsers::asp::dlvhex']]], ['dlvparserbasevisitor_356',['DLVParserBaseVisitor',['../classDLVParserBaseVisitor.html',1,'']]], ['dlvparserbasevisitor_3c_20object_20_3e_357',['DLVParserBaseVisitor&lt; object &gt;',['../classDLVParserBaseVisitor.html',1,'']]], ['dlvparserbasevisitorimplementation_358',['DLVParserBaseVisitorImplementation',['../classit_1_1unical_1_1mat_1_1parsers_1_1asp_1_1dlv_1_1DLVParserBaseVisitorImplementation.html',1,'it::unical::mat::parsers::asp::dlv']]] ];
/* import React from 'react';*/ /* import { shallow } from 'enzyme';*/ /* import SingleStructureView from '../index';*/ describe('<SingleStructureView />', () => { it('Expect to render a nested div', () => { expect(true).toBe(true); }); });
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "pamilau", "pamunyi" ], "DAY": [ "pa mulungu", "pa shahuviluha", "pa hivili", "pa hidatu", "pa hitayi", "pa hihanu", "pa shahulembela" ], "MONTH": [ "pa mwedzi gwa hutala", "pa mwedzi gwa wuvili", "pa mwedzi gwa wudatu", "pa mwedzi gwa wutai", "pa mwedzi gwa wuhanu", "pa mwedzi gwa sita", "pa mwedzi gwa saba", "pa mwedzi gwa nane", "pa mwedzi gwa tisa", "pa mwedzi gwa kumi", "pa mwedzi gwa kumi na moja", "pa mwedzi gwa kumi na mbili" ], "SHORTDAY": [ "Mul", "Vil", "Hiv", "Hid", "Hit", "Hih", "Lem" ], "SHORTMONTH": [ "Hut", "Vil", "Dat", "Tai", "Han", "Sit", "Sab", "Nan", "Tis", "Kum", "Kmj", "Kmb" ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "dd/MM/y h:mm a", "shortDate": "dd/MM/y", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "TSh", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a4", "posPre": "", "posSuf": "\u00a4" } ] }, "id": "bez", "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
describe('Togashi Mitsu', function() { integration(function() { describe('Togashi Mitsu\'s constant ability', function() { beforeEach(function() { this.setupTest({ phase: 'conflict', player1: { inPlay: ['iuchi-shahai'] }, player2: { inPlay: ['togashi-mitsu-2', 'doji-whisperer', 'tengu-sensei', 'doji-challenger'], provinces: ['manicured-garden'] } }); this.shahai = this.player1.findCardByName('iuchi-shahai'); this.mitsu = this.player2.findCardByName('togashi-mitsu-2'); this.whisperer = this.player2.findCardByName('doji-whisperer'); this.tengu = this.player2.findCardByName('tengu-sensei'); this.challenger = this.player2.findCardByName('doji-challenger'); this.garden = this.player2.findCardByName('manicured-garden'); }); it('should not allow being chosen by covert', function() { this.noMoreActions(); this.player1.clickRing('air'); this.player1.clickCard(this.garden); this.player1.clickCard(this.shahai); this.player1.clickPrompt('Initiate Conflict'); expect(this.player1).toHavePrompt('Choose covert target for Iuchi Shahai'); expect(this.player1).not.toBeAbleToSelect(this.mitsu); expect(this.player1).toBeAbleToSelect(this.whisperer); expect(this.player1).not.toBeAbleToSelect(this.tengu); expect(this.player1).toBeAbleToSelect(this.challenger); }); }); describe('Togashi Mitsu\'s triggered ability', function() { beforeEach(function() { this.setupTest({ phase: 'conflict', player1: { inPlay: ['doji-challenger'] }, player2: { inPlay: ['togashi-mitsu-2', 'doji-whisperer', 'asako-azunami'], hand: ['a-new-name', 'a-new-name', 'a-new-name', 'a-new-name', 'a-new-name'] } }); this.challenger = this.player1.findCardByName('doji-challenger'); this.mitsu = this.player2.findCardByName('togashi-mitsu-2'); this.whisperer = this.player2.findCardByName('doji-whisperer'); this.azunami = this.player2.findCardByName('asako-azunami'); this.player1.claimRing('fire'); this.player2.claimRing('water'); }); it('should not allow triggering unless you have played 5 cards', function() { this.noMoreActions(); this.initiateConflict({ attackers: [this.challenger], defenders: [this.mitsu], type: 'military' }); let i = 0; for(i = 0; i < 5; i++) { expect(this.player2).toHavePrompt('Conflict Action Window'); this.player2.clickCard(this.mitsu); expect(this.player2).toHavePrompt('Conflict Action Window'); this.player2.playAttachment(this.player2.filterCardsByName('a-new-name')[i], this.mitsu); this.player1.pass(); } expect(this.player2).toHavePrompt('Conflict Action Window'); this.player2.clickCard(this.mitsu); expect(this.player2).toHavePrompt('Togashi Mitsu'); }); it('should not allow triggering if not participating', function() { this.noMoreActions(); this.initiateConflict({ attackers: [this.challenger], defenders: [this.whisperer], type: 'military' }); let i = 0; for(i = 0; i < 5; i++) { this.player2.playAttachment(this.player2.filterCardsByName('a-new-name')[i], this.mitsu); this.player1.pass(); } expect(this.player2).toHavePrompt('Conflict Action Window'); this.player2.clickCard(this.mitsu); expect(this.player2).toHavePrompt('Conflict Action Window'); }); it('should let you resolve a legal ring effect', function() { this.noMoreActions(); this.initiateConflict({ attackers: [this.challenger], defenders: [this.mitsu], type: 'military' }); let i = 0; for(i = 0; i < 5; i++) { this.player2.playAttachment(this.player2.filterCardsByName('a-new-name')[i], this.mitsu); this.player1.pass(); } expect(this.player2).toHavePrompt('Conflict Action Window'); this.player2.clickCard(this.mitsu); expect(this.player2).toHavePrompt('Choose a ring effect to resolve'); expect(this.player2).toBeAbleToSelectRing('air'); expect(this.player2).toBeAbleToSelectRing('earth'); expect(this.player2).toBeAbleToSelectRing('fire'); expect(this.player2).not.toBeAbleToSelectRing('void'); expect(this.player2).toBeAbleToSelectRing('water'); this.player2.clickRing('fire'); expect(this.player2).toHavePrompt('Fire Ring'); this.player2.clickCard(this.mitsu); this.player2.clickPrompt('Honor Togashi Mitsu'); expect(this.mitsu.isHonored).toBe(true); }); it('should allow ring replacement effects', function() { this.noMoreActions(); this.initiateConflict({ attackers: [this.challenger], defenders: [this.mitsu], type: 'military' }); let i = 0; for(i = 0; i < 5; i++) { this.player2.playAttachment(this.player2.filterCardsByName('a-new-name')[i], this.mitsu); this.player1.pass(); } this.player2.clickCard(this.mitsu); this.player2.clickRing('water'); expect(this.player2).toHavePrompt('Triggered Abilities'); expect(this.player2).toBeAbleToSelect(this.azunami); this.player2.clickCard(this.azunami); expect(this.player2).toHavePrompt('Asako Azunami'); }); }); }); });
'use strict' var is = require('unist-util-is') module.exports = findAllBefore /* Find nodes before `index` in `parent` which pass `test`. */ function findAllBefore(parent, index, test) { var results = [] var children var child if (!parent || !parent.type || !parent.children) { throw new Error('Expected parent node') } children = parent.children if (index && index.type) { index = children.indexOf(index) } if (isNaN(index) || index < 0 || index === Infinity) { throw new Error('Expected positive finite index or child node') } /* Performance. */ if (index > children.length) { index = children.length } while (index--) { child = children[index] if (is(test, child, index, parent)) { results.push(child) } } return results }
'use strict'; var toInteger = require('./_to-integer'), defined = require('./_defined'); // true -> String#at // false -> String#codePointAt module.exports = function (TO_STRING) { return function (that, pos) { var s = String(defined(that)), i = toInteger(pos), l = s.length, a, b; if (i < 0 || i >= l) return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; //# sourceMappingURL=_string-at.js.map
import { addHours } from 'date-fns'; import { getReviewStatusText } from 'features/dashboard/ReviewStatus'; const defaults = { isOnVacation: false, isLoading: false, reviewsCount: 0, vacationDate: false, nextReviewDate: false, freshUser: false, loadQuizCounts: () => {}, }; describe('getReviewStatusText()', () => { it('sane default', () => { expect(getReviewStatusText()).toMatchSnapshot(); }); it('no reviews unlocked', () => { expect(getReviewStatusText({ ...defaults, freshUser: true })).toMatchSnapshot(); }); it('on vacation', () => { expect( getReviewStatusText({ ...defaults, isOnVacation: true, reviewsCount: 40, vacationDate: new Date(2017, 11, 26), // Dec 26 2017 }) ).toMatchSnapshot(); }); it('has reviews ready', () => { expect( getReviewStatusText({ ...defaults, reviewsCount: 1, }) ).toMatchSnapshot(); }); it('review date is future', () => { expect( getReviewStatusText({ ...defaults, nextReviewDate: addHours(new Date(), 2), }) ).toMatchSnapshot(); }); it('review date is past', () => { expect( getReviewStatusText({ ...defaults, nextReviewDate: addHours(new Date(), -2), }) ).toMatchSnapshot(); }); it('user is loading', () => { expect( getReviewStatusText({ ...defaults, isLoading: true, }) ).toMatchSnapshot(); }); });
module.exports = { onPhantomPageCreate: function(phantom, req, res, next) { req.prerender.page.run(function(resolve) { var customHeaders = this.customHeaders; customHeaders['X-Prerender'] = 1; this.customHeaders = customHeaders; resolve(); }).then(function() { next(); }).catch(function() { next(); }); } }
// External const chalk = require('chalk'); module.exports = Object.assign(chalk, { bad: chalk.red, cmd: chalk.yellow, hvy: chalk.bold, ok: chalk.green, opt: chalk.cyan, req: chalk.magenta, sec: chalk.bold.underline });
import fs from 'fs'; import webpack from 'webpack'; import {devConfig, proConfig} from './webpack.config'; import gulp from 'gulp'; import {log, PluginError} from 'gulp-util'; gulp.task('js:dev', function (cb) { webpack(devConfig, function (e, stats) { if (e) { throw new PluginError('[webpack]', e); } else { log('[webpack]', stats.toString({ version: true, timings: true, assets: true, chunks: true, chunkModules: true, modules: true })); fs.writeFile('storage/app/webpack.json', JSON.stringify(stats.toJson('verbose'))); } cb(); }); }); gulp.task('js:production', function (cb) { webpack(proConfig, cb) }); gulp.task('js', ['js:dev', 'js:production']);
export default class NanoRouter { /** * Constructor * @param {Object} routes Object where key is the route, and value is the callback */ constructor (routes = {}) { this._routes = routes; window.addEventListener('hashchange', ()=> { this._route(); }); this._route(); } /** * Navigate to path * @param {String} path Path */ static navigate (path = '/') { window.location.hash = (path.substr(0, 1) !== '#' ? '#' : '') + path; } onBeforeRoute (callback) { this._onBeforeRoute = callback; } /** * Handle route change * @param {String} path Optionally provide a path */ _route (path = this._getCurrentPath()) { Object.keys(this._routes).forEach((route)=> { const match = this._match(route, path); if (match) { if (typeof this._onBeforeRoute === 'function') { this._onBeforeRoute(path); } this._routes[route].apply(route, match.args); } }); } /** * Match a route with a path * @param {String} route Route to match * @param {String} path Path to match * @return {bool|Object} False if no match, an Object with args if match */ _match (route, path) { let result = false; let routeParts = route.split('/'); let pathParts = path.split('/'); const argIndexes = this._getArgIndexes(routeParts); const matchableRoute = this._toMatchableString(routeParts, argIndexes); const matchablePath = this._toMatchableString(pathParts, argIndexes); if (matchableRoute === matchablePath) { result = { args: this._getArgs(pathParts, argIndexes) } } return result; } /** * Get the indexes of the route parts that are placeholders for arguments * @param {Array} parts Route parts * @return {Array} Indexes of the parts that are placeholders for arguments */ _getArgIndexes (parts = []) { let argIndexes = []; parts.forEach(function (part, index) { if (/:w*/.test(part)) { argIndexes.push(index); } }); return argIndexes; } /** * Join the parts and replace the arg with a contant, so we can match them later * @param {Array} parts Parts * @param {Array} argIndexes Indexes of the parts that should be replaced * @return {String} Matchable string */ _toMatchableString (parts = [], argIndexes = []) { // Don't modify the original array let _parts = parts.slice(0); _parts.forEach(function (part, index) { if (argIndexes.indexOf(index) !== -1) { _parts[index] = ':placeholder:'; } }); return _parts.join('/'); } /** * Get the args from an array of parts * @param {Array} pathParts Parts * @param {Array} argIndexes Indexes of the parts that are arguments * @return {Array} Arguments */ _getArgs (pathParts = [], argIndexes = []) { let args = []; pathParts.forEach((part, index)=> { if (argIndexes.indexOf(index) !== -1) { args.push(part); } }); return args; } /** * Get the current part, with leading slash * @return {[type]} [description] */ _getCurrentPath () { // Remove hash and leading / let page = window.location.hash.replace(/^[#]*[\/]*/, ''); // Now we add the / again to make sure we only have it once return '/' + page; } }
Template.TodosCount.events({ }); Template.TodosCount.helpers({ completedCount: function(){ return Todos.find({userId: Meteor.userId(), isDone: true}).count(); }, totalCount: function(){ return Todos.find({userId: Meteor.userId()}).count(); } });
/* @flow */ class Loader { /*:: _path: string; */ constructor(path/*: string */) { this._path = path; } getPath()/*: string */ { return this._path; } load()/*: Promise<Buffer> */ { return Promise.reject('Not Implemented!'); } } module.exports = Loader;
//This needs all kinds of testing... work on it more... again just for test... ivar.search = {}; /** * @param {boolean} [sorted=true] * @param {number|string} [field] * @todo TEST */ ivar.search.quickSearch = function(arr, key, sorted, field) { var found = []; if(!ivar.isSet(sorted)) sorted = true; if(!sorted) if(ivar.isSet(field)) { return ivar.sortObjectsBy(found, field); } else { arr.sort(); } var start = ivar.search.binaryKeySearch(arr, key, field); //TODO: wtf is this??? if(isSet(start)) { for(var i = start+1; i < arr.length; i++) { var elem = arr[i]; if(isSet(field)) elem = elem[field]; if(elem.startsWith(key)) { found.push(arr[i]); } else { break; } } for(var i = start; i >= 0; i--) { var elem = arr[i]; if(isSet(field)) elem = elem[field]; if(elem.startsWith(key)) { found.push(arr[i]); } else { break; } } } if(ivar.isSet(field)) { return ivar.sortObjectsBy(found, field); } else { return found.sort(); } }; ivar.search.binaryKeySearch = function(arr, key, field, caseSensitive) { var low = 0, high = arr.length - 1, i; while (low <= high) { i = Math.floor((low + high) / 2); var pre; if(isSet(field)) { pre = arr[i][field].substring(0, key.length); } else { pre = arr[i].substring(0, key.length); } if(!isSet(caseSensitive)) caseSensitive = false; if(!caseSensitive) pre = pre.toLowerCase(); if (pre < key) { low = i + 1; continue; }; if (pre > key) { high = i - 1; continue; }; return i; } return null; }; ivar.search.binarySearch = function(arr, find) { var low = 0, high = arr.length - 1, i; while (low <= high) { i = Math.floor((low + high) / 2); if (arr[i] < find) { low = i + 1; continue; }; if (arr[i] > find) { high = i - 1; continue; }; return i; } return null; };
/** * @file * @author zdying */ var path = require('path'); require('../src/global'); var webpackConfig = require('../src/webpackConfig/index'); var locConfig = require('../src/webpackConfig/loc/config'); var devConfig = require('../src/webpackConfig/dev/config'); var prdConfig = require('../src/webpackConfig/prd/config'); var assert = require('assert'); describe('mergeConfig: ',function(){ var userCofig = webpackConfig.getUserConfig(__dirname + '/webpackConfig/project', 'loc'); var userCofigDev = webpackConfig.getUserConfig(__dirname + '/webpackConfig/project', 'dev'); var userCofigPrd = webpackConfig.getUserConfig(__dirname + '/webpackConfig/project', 'prd'); // 删除 dll delete userCofig.library; delete userCofigDev.library; delete userCofigPrd.library; var locConf = locConfig(__dirname + '/webpackConfig/project', userCofig); var devConf = devConfig(__dirname + '/webpackConfig/project', userCofigDev); var prdConf = prdConfig(__dirname + '/webpackConfig/project', userCofigPrd); it('正确扩展plugins', function(){ var plugins = locConf.plugins; // loc 默认三个插件, 配置文件中有三个插件 assert(plugins.length === 6); //TODO 进一步验证插件内容是否正确 }); it('正确扩展loaders', function(){ var loaders = locConf.module.loaders; var exists = false; var testOk, loaderOk; for(var i = 0, len = loaders.length; i < len; i++){ /* 配置文件中增加了一个: * { * 'mustache mustache-loader': function(loader, path){ * return { test: /\.(mustache|html)$/, loader: 'mustache' } * } * } */ testOk = loaders[i].test.toString() === /\.(mustache|html)$/.toString(); loaderOk = loaders[i].loader === path.join(__hii__.packageTmpdir, 'node_modules/mustache-loader'); if(testOk && loaderOk){ exists = true; break; } } assert(exists); }); it('特殊配置不直接扩展', function(){ assert(locConf.autoTest === undefined) }); it('只有extend.module.loaders', function(){ assert.equal(devConf.module.loaders.length, 6); }); it('只有extend.plugins', function(){ assert.equal(prdConf.plugins.length, 8); }); });
import Modal from 'react-bootstrap/lib/Modal'; import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; export class AppModalPage extends React.Component { render() { return (<Modal onEnter={this.props.dialog.onEnter} onEntered={this.props.dialog.onEntered} onEntering={this.props.dialog.onEntering} onExit={this.props.dialog.onExit} onExited={this.props.dialog.onExited} onExiting={this.props.dialog.onExiting} onHide={this.props.dialog.onHide} show={this.props.dialog.show} dialogClassName="app-modal"> <Modal.Header onHide={this.props.dialog.onHide} closeButton={this.props.dialog.showCloseButton}> <Modal.Title>{this.props.dialog.title}</Modal.Title> <Modal.Body> {this.props.dialog.body} </Modal.Body> <Modal.Footer> {this.props.dialog.footer} </Modal.Footer> </Modal.Header> </Modal>); } } AppModalPage.propTypes = { dialog: PropTypes.object.isRequired }; function mapStateToProps(state) { return { dialog: state.dialog }; } export const ConnectAppModelPage = connect( mapStateToProps )(AppModalPage);
import React from 'react'; import ReactDOM from 'react-dom'; import Master from './components/Master' const App = () => ( <div> <Master /> </div> ) ReactDOM.render( <App />, document.getElementById('root') );
var app = app || {}; (function(){ app.TestButton = React.createClass({displayName: "TestButton", handleClick: function() { this.props.submitTestTask(this.props.btnType); }, render: function() { return ( React.createElement("button", {onClick: this.handleClick, className: "btn btn-test"}, " ", React.createElement("span", {className: "btn-test-text"}, " ", this.props.btn_name, " ")) ); } }); app.CodeEditor = React.createClass({displayName: "CodeEditor", handleType:function(){ this.props.updateCode(this.editor.session.getValue()); }, componentDidMount:function(){ this.editor = ace.edit("codeeditor"); this.editor.setTheme("ace/theme/clouds_midnight"); this.editor.setOptions({ fontSize: "1.2em" }); this.editor.session.setMode("ace/mode/"+this.props.language); }, render:function(){ return ( React.createElement("div", {id: "codeeditor", onKeyUp: this.handleType}) ); } }); app.UrlEditor = React.createClass({displayName: "UrlEditor", getInitialState: function(){ return { url_vaild:true } }, handleChange:function(){ //if url valid, update state, if not, warn var url_str = this.refs.urlInput.value; if (app.isUrl(url_str)){ this.setState({url_vaild:true}); //this.probs.updateUrl(url_str) }else{ this.setState({url_vaild:false}); } }, classNames:function(){ return 'input-url ' + ((this.state.url_vaild) ? 'input-right':'input-error'); }, render: function(){ return ( React.createElement("input", {className: this.classNames(), onChange: this.handleChange, ref: "urlInput", placeholder: "Type Server or App URL"}) ); } }); app.ResultDisplay = React.createClass({displayName: "ResultDisplay", render: function(){ return ( React.createElement("div", {className: "result-container bg-success"}, React.createElement("div", {className: "result-head"}, React.createElement("span", {className: "area-title area-title-black"}, "Test Type: "), " ", React.createElement("span", null, this.props.testType)), React.createElement("div", {className: "detail-result"}, React.createElement(StepDisplay, null) ) ) ) } }); var StepDisplay = app.StepDisplay = React.createClass({displayName: "StepDisplay", getInitialState: function(){ return { is_img_hide:true } }, handleTextClick:function(){ this.setState({is_img_hide:!this.state.is_img_hide}); }, handleShowFullImage:function(event){ event.stopPropagation(); alert('test'); }, render:function(){ return ( React.createElement("div", {className: "step-brief step-brief-failed", onClick: this.handleTextClick}, React.createElement("div", null, React.createElement("span", {className: "step-brief-text"}, "This is a step info")), React.createElement("div", {hidden: this.state.is_img_hide, className: "step-img-block"}, React.createElement("img", {className: "img-responsive img-rounded step-img", src: "../img/7.png"}), React.createElement("button", {onClick: this.handleShowFullImage, className: "btn btn-primary"}, "Full Image") ) ) ); } }); var modal = app.modal = React.createClass({displayName: "modal", componentDidMount(){ $(this.getDOMNode()).modal('show'); $(this.getDOMNode()).on('hidden.bs.modal', this.props.handleHideModal); }, }); })();
const ReadableStream = require('readable-stream') /* global URL */ module.exports = function (snapshot) { return inject.bind(null, snapshot.hash) } const docWrite = `\ <!doctype html> <html> <head> <meta charset="utf-8"> <script src="{{root}}/planktos/planktos.min.js"></script> <script> _planktos = new Planktos() _planktos.getAllSnapshots() .then(snapshots => { var snapshot = snapshots.find(function (s) { return s.hash === '{{snapshotHash}}' }) var fpath = (new URL('{{url}}')).pathname.replace('{{root}}', '') return snapshot.getFile(fpath).getBuffer() }) .then(buffer => { document.documentElement.innerHTML = buffer.toString() }) </script> </head> <body> </body> </html> ` const rendermedia = `\ <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> html {overflow: auto;} html, body, div, iframe {margin: 0px; padding: 0px; height: 100%; border: none;} iframe {display: block; width: 100%; border: none; overflow-y: auto; overflow-x: hidden;} </style> <script src="{{root}}/planktos/planktos.min.js"></script> <script> _planktos = new Planktos(); _planktos.getAllSnapshots().then(snapshots => { var snapshot = snapshots.find(function (s) { return s.hash === '{{snapshotHash}}' }) var fpath = (new URL('{{url}}')).pathname.replace('{{root}}', '') snapshot.getFile(fpath).appendTo('body') }) </script> </head> </html> ` function inject (snapshotHash, req, rsp) { // Inject only if it's the initial page load if (req.planktosInject !== true && (!req.fetchEvent || req.fetchEvent.clientId)) return const url = new URL(req.url) const fname = url.pathname.substr(url.pathname.lastIndexOf('/') + 1) const isHTML = fname.endsWith('.html') || fname.endsWith('.htm') || !fname.includes('.') const template = (isHTML ? docWrite : rendermedia) .replace(/{{url}}/g, url.toString()) .replace(/{{root}}/g, req.planktosRoot || '') .replace(/{{snapshotHash}}/g, snapshotHash) rsp.status = 200 rsp.statusText = 'OK' rsp.headers.set('Content-Length', template.length) rsp.headers.set('Content-Type', 'text/html') rsp.createReadStream = function () { const s = new ReadableStream() s._read = function noop () {} s.push(template) s.push(null) return s } }
"use strict"; var Rx = require("rx"); var _observablePool = {}; function _replicate(source, subject) { return source.subscribe(function onOnNext(x) { setTimeout(function () { subject.onNext(x); }, 0); }, function onError(err) { subject.onError(err); }, function onComplete() { subject.onCompleted(); }); } function _getObservable(name) { return (_observablePool[name] = _observablePool[name] || new Rx.Subject()); } function _replicatedSubject(source) { return RR.replicate(source); } function getArgumentsNames(fn) { return fn .toString() .replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s))/gm, '') .match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1] .split(/,/); } function argumentsAre(args, types) { return types .map(function (type, idx) { if (type == 'object') { return !!args[idx] && !('length' in args[idx]) && typeof args[idx] == 'object'; } else if (type == 'array') { return !!args[idx] && 'length' in args[idx]; } else if (type == 'function') { return !!args[idx] && typeof args[idx] == 'function'; } else { return !!args[idx]; } }) .reduce(function (sofar, curr) { return sofar && curr; }, true); } function defineMemorizedGetter(obj, name, getter) { var val; Object.defineProperty(obj, name, { get: function () { if (!val) { val = getter.call(obj); } return val; }, }); } function _assignReplicatedSubject(context) { return function (observable, prop) { return (context[prop] = _replicatedSubject(observable)); }; } var Observable = { createAction: function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var dependencies = [], register, extend; var action = {}; if (argumentsAre(args, ['object'])) { var config_1 = args[0]; action = Object.keys(config_1).reduce(function (ext, key) { defineMemorizedGetter(ext, key, function () { var deps = getArgumentsNames(config_1[key]).map(_getObservable); return _replicatedSubject(config_1[key].apply(ext, deps)); }); return ext; }, action); } else { if (argumentsAre(args, ['array', 'function'])) { dependencies = args[0]; register = args[1]; } else if (argumentsAre(args, ['function'])) { register = args[0]; dependencies = getArgumentsNames(register); } extend = register.apply(action, dependencies.map(_getObservable)); for (var prop in extend) { _assignReplicatedSubject(action)(extend[prop], prop); } } return action; }, bind: function (observableName, transform) { var subject = new Rx.Subject(), trans = transform || (function (x) { return x; }), context = null, disposable = null; return function (obj) { if (context !== this) { if (disposable) { disposable.dispose(); subject = new Rx.Subject(); } disposable = _replicate(trans.apply(this, [subject, this]), _getObservable(observableName)); context = this; } return subject.onNext(obj); }; }, }; var RR = { replicate: function (source, name) { if (name === void 0) { name = null; } var sub = name ? _getObservable(name) : new Rx.Subject(); var ret = Object.create(sub); Object.defineProperties(ret, { subject: { value: sub }, disposable: { value: _replicate(source, sub) }, }); return ret; }, getObservable: function (name) { return _getObservable(name); }, Observable: Observable, }; module.exports = RR;
import {expect} from 'chai'; import jsdom from 'jsdom'; import fs from 'fs'; describe('index.html', () => { it('should have h1 that says Users', (done) => { const index = fs.readFileSync('./src/index.html', 'utf-8'); jsdom.env(index, (err, window) => { const h1 = window.document.getElementsByTagName('h1')[0]; expect(h1.innerHTML).to.equal("Users"); done(); window.close(); }); }) })
angular.module('lampost_mud').service('lmComm', ['lpEvent', 'lpData', 'lpRemote', 'lpDialog', function (lpEvent, lpData, lpRemote, lpDialog) { var self = this; var allLogins = false; lpEvent.register('friend_login', friendLogin); lpEvent.register('any_login', anyLogin); lpEvent.register('login', checkAllLogins); lpEvent.register('logout', function() { checkAllLogins(); }); lpEvent.register('notifies_updated', checkAllLogins); function checkAllLogins() { if (lpData.notifies.indexOf('allDesktop') > -1 || lpData.notifies.indexOf('allSound') > -1) { if (!allLogins) { lpRemote.registerService('login_notify_service'); allLogins = true; } } else { if (allLogins) { allLogins = false; lpRemote.unregisterService('login_notify_service'); } } } function friendLogin(friend_info) { if (lpData.notifies.indexOf('friendDesktop') > -1 && lpData.notifies.indexOf('allDesktop') == -1) { self.notify({icon: 'image/friendNotify.png', title: "Your friend " + friend_info.name + " logged into " + lampost_config.title, content: ''}); } if (lpData.notifies.indexOf('friendSound') > -1 && lpData.notifies.indexOf('allSound') == -1) { jQuery('#sound_beep_ping')[0].play(); } lpEvent.dispatch('display_line', 'Your friend ' + friend_info.name + ' just logged in', 'system'); } function anyLogin(login) { if (lpData.notifies.indexOf('allDesktop') > -1) { self.notify({icon: 'image/friendNotify.png', title: "Player " + login.name + " logged into " + lampost_config.title, content: ''}); } if (lpData.notifies.indexOf('allSound') > -1) { jQuery('#sound_beep_ping')[0].play(); lpEvent.dispatch('display_line', login.name + ' just logged in', 'system'); } } function showNotification(notify_data) { var notification = window.webkitNotifications.createNotification(notify_data.icon, notify_data.title, notify_data.content); notification.show(); } this.requestNotificationPermission = function (notify_data) { lpDialog.showConfirm("Allow Notifications", "You must grant permission to allow notifications from " + lampost_config.title).then(function () { window.webkitNotifications.requestPermission(function () { self.notify(notify_data); }) }); }; this.notify = function (notify_data) { if (!window.webkitNotifications) { return; } var permLevel = window.webkitNotifications.checkPermission(); if (permLevel == 0) { showNotification(notify_data); } else if (permLevel == 1) { self.requestNotificationPermission(notify_data); } } }]);
import User from '../../models/User'; export default (req, res) => { User.find().select('name email logins').then((users) => { const processed = users.map(user => ({ email: user.email, name: user.name, // NOTE: In the future, we can assume user.logins is always sorted lastOnline: new Date(Math.max(...user.logins)), createdAt: new Date(Math.min(...user.logins)), visits: user.logins.length, })).sort((a, b) => new Date(b.lastOnline) - new Date(a.lastOnline)); res.json({ users: processed, success: true, }); }).catch((error) => { res.json({ error, success: false, }); }); };
/* global describe, it, expect, jest */ import newCharIndex from '../char_index'; describe('newCharIndex()', () => { it('returns an array', () => { let index = newCharIndex('foo', 'bar'); expect(index instanceof Array).toBe(true); }); }); describe('character index', () => { it('length equals number of matches in text', () => { let index = newCharIndex('1', 'a1 b1 c1'); expect(index.length).toBe(3); }); it('contains the string index where the character was found', () => { let index = newCharIndex('1', 'a1 b1 c1'); expect(index[0]).toBe(1); expect(index[1]).toBe(4); expect(index[2]).toBe(7); }); });
var should = require('should'), testUtils = require('../../utils'), rewire = require('rewire'), configUtils = require('../../utils/configUtils'), // Stuff we are testing ConfigurationAPI = rewire('../../../server/api/configuration'); describe('Configuration API', function () { // Keep the DB clean before(testUtils.teardown); beforeEach(testUtils.setup('clients')); afterEach(function () { configUtils.restore(); return testUtils.teardown(); }); should.exist(ConfigurationAPI); it('can read basic config and get all expected properties', function (done) { configUtils.set('auth:type', 'ghost'); configUtils.set('auth:url', 'https://auth.ghost.com'); ConfigurationAPI.read().then(function (response) { var props; should.exist(response); should.exist(response.configuration); response.configuration.should.be.an.Array().with.lengthOf(1); props = response.configuration[0]; props.blogUrl.should.eql('http://127.0.0.1:2369/'); props.routeKeywords.should.eql({ tag: 'tag', author: 'author', page: 'page', preview: 'p', primaryTagFallback: 'all', private: 'private', subscribe: 'subscribe', amp: 'amp' }); props.useGravatar.should.eql(false); props.publicAPI.should.eql(false); props.clientId.should.eql('ghost-admin'); props.clientSecret.should.eql('not_available'); props.ghostAuthUrl.should.eql('https://auth.ghost.com'); // value not available, because settings API was not called yet props.hasOwnProperty('blogTitle').should.eql(true); // uuid props.hasOwnProperty('ghostAuthId').should.eql(true); done(); }).catch(done); }); it('can read about config and get all expected properties', function (done) { ConfigurationAPI.read({key: 'about'}).then(function (response) { var props; should.exist(response); should.exist(response.configuration); response.configuration.should.be.an.Array().with.lengthOf(1); props = response.configuration[0]; // Check the structure props.should.have.property('version').which.is.a.String(); props.should.have.property('environment').which.is.a.String(); props.should.have.property('database').which.is.a.String(); props.should.have.property('mail').which.is.a.String(); // Check a few values props.environment.should.match(/^testing/); props.version.should.eql(require('../../../../package.json').version); done(); }).catch(done); }); it('can read private config and get all expected properties', function (done) { ConfigurationAPI.read({key: 'private'}).then(function (response) { var props; should.exist(response); should.exist(response.configuration); response.configuration.should.be.an.Array().with.lengthOf(1); props = response.configuration[0]; // property is set, but value not available, because settings API was not called yet props.should.have.property('unsplashAPI').which.is.an.Object(); props.unsplashAPI.should.be.empty(); done(); }).catch(done); }); });
'use strict'; var path = require('path'); var yeoman = require('yeoman-generator'); var util = require('util'); var ngUtil = require('../util'); var BaseGenerator = require('../base.js'); var Generator = module.exports = function Generator() { BaseGenerator.apply(this, arguments); }; util.inherits(Generator, BaseGenerator); Generator.prototype.askFor = function askFor() { var self = this; var done = this.async(); var prompts = [ { name: 'dir', message: 'Where would you like to create this factory?', default: self.config.get('serviceDirectory') } ]; this.prompt(prompts, function (props) { this.dir = path.join(props.dir, this.name); done(); }.bind(this)); }; Generator.prototype.createFiles = function createFiles() { ngUtil.copyTemplates(this, 'factory'); };
var server = require('./server.js'); var router = require('./router.js'); var requestHandlers = require('./postHandler.js'); var handle = {}; handle['/'] = requestHandlers.start; handle['/start'] = requestHandlers.start; handle['/upload'] = requestHandlers.upload; server.start(router.route, handle);
angular.module('webapp').controller('AdminPlacesCreateCtrl', AdminPlacesCreateCtrl) AdminPlacesCreateCtrl.$inject = ['PlacesService'] /** * @ngdoc controller * @name webapp.controller:AdminPlacesCreateCtrl * @description In charge of the admin places creation view. */ function AdminPlacesCreateCtrl(PlacesService) { var vm = this vm.titleName = "Add new place" vm.backName = "Places Dashboard" vm.backAction = function() { vm.$router.navigate(['AdminPlacesDashboard']) } vm.textAction = "Save the place" vm.iconAction = "save" vm.action = function() { PlacesService.addPlace(vm.place) .then(function() { vm.$router.navigate(['AdminPlacesDashboardData', { data: "creationOkay" }]) }) .catch(function() {}) } vm.place = PlacesService.Model vm.$routerOnActivate = function(next, prev) { PlacesService.Model.reset() } }
var mocha = require('mocha'); var assert = require('assert'); var config = require('./config'); var Clips = require('../lib/clips').Clips; describe('Testing Clips', function() { var clips = new Clips(config.auth); describe('#search()', function() { it('should return information about the query', function(done) { clips.search({ q: 'javascript', is_starred: false },function(err, data) { assert.ok(!err, 'No error'); assert.ok(data, 'Has data'); assert.ok(data.objects, 'Has clips array'); done(); }); }); }); describe('#all()', function() { it('should return JSON of full clips data', function(done) { clips.all(function(err, data) { assert.ok(!err, 'No error'); assert.ok(data, 'Has data'); assert.ok(data.objects, 'Has clips array'); done(); }); }); }); describe('#get()', function() { it('should return JSON associated with an id', function(done) { clips.get(config.clips.id, function(err, data) { assert.ok(!err, 'No error'); assert.ok(data, 'Has data'); assert.ok(data.title, 'Has title'); assert.ok(data.url, 'Has url'); assert.equal(data.id, config.clips.id, 'Return ID matches request ID'); done(); }); }); }); describe('#update()', function() { it('should be able to update a clip', function(done) { var opts = { id: config.clips.id, notes: 'Some random text ' +Math.random() }; clips.update(opts, function(err, data) { assert.ok(!err, 'No error'); assert.equal(data.notes, opts.notes, 'Saved data equals post data'); done(); }); }); }); describe('#add() and #remove()', function() { it('should be able to add and remove clips', function(done) { var url = 'https://github.com/EnotionZ/node-kippt'; clips.add({url: url}, function(err, data) { assert.ok(!err, 'No error'); assert.equal(data.url, url, 'Saved url equals post url'); clips.remove(data.id, function(err) { assert.ok(!err, 'No error'); done(); }); }); }); }); });
export const generateConfig = () => { return { server: 'http://localhost', port: 8080 } } export const generateConfig2 = () => { return { server: 'http://localhost', port: 8080, time: new Date() } }
const wizard = require('./wizard'); const spawn = require('cross-spawn-promise'); module.exports = async function (options = {}) { let command = await wizard(options); let spawnArgs = []; [command, ...spawnArgs] = command.split(' '); await spawn(command, spawnArgs, {stdio: 'inherit'}); };
import * as logUtil from '../utils/log' const REDIRECT_URL = browser.runtime.getURL("redirect/redirect.html"); function returnFirstNotNull() { return [...arguments].find(a => a !== null && a !== undefined); } export class Executor { constructor() { //template this.backgroundChildTabCount = 0; this.lastDownloadItemID = -1; this.lastDownloadObjectURL = ""; //prepare for revoke this.findFlag = false; this.bgConfig = null; this.sender = null; this.data = null; this.temporaryDataStorage = new Map(); this.downloadIdSetToRevoke = new Map(); browser.storage.onChanged.addListener((_, areaName) => { if (areaName === "local") { this.refreshBackgroundConfig(); } }); browser.downloads.onChanged.addListener(item => { if (this.downloadIdSetToRevoke.has(item.id)) { if (item.state.current === "interrupted" || item.state.current === "complete") { window.URL.revokeObjectURL(this.lastDownloadObjectURL); this.downloadIdSetToRevoke.delete(item.id); } } }); browser.tabs.onRemoved.addListener(() => { this.backgroundChildTabCount = 0; }); browser.tabs.onActivated.addListener(() => { this.backgroundChildTabCount = 0; }); this.refreshBackgroundConfig(); this.doFlag = false; } async refreshBackgroundConfig() { console.info("refresh background config"); browser.storage.local.get().then(a => { this.bgConfig = a; }); } async DO(actionWrapper, sender) { if (this.doFlag) { console.error("while one action is executing, another action want to execute. It is not allowed", actionWrapper); return; } console.time("do action"); this.data = actionWrapper; this.sender = sender; this.doFlag = true; try { await this.execute(); } finally { this.data = null; this.sender = null; this.doFlag = false; console.timeEnd("do action"); } } async execute(data) { logUtil.log("execute command: ", this.data.command); switch (this.data.command) { case "open": return this.openHandler(); case "copy": return this.copyHandler(); case "search": return this.searchHandler(); case "download": return this.downloadHandler(); case "query": return this.queryHandler(); case "find": return this.findText(this.data.selection.text); case "translate": return this.translateText(this.data.selection.text); case "runScript": // ignore result this.runScript(); return; case "": logUtil.warn("no operation"); browser.notifications.create("nooperation", { message: `No Operation`, title: "Glitter Drag Notification", type: "basic", }); return; default: console.error(`unexcepted commond: "${this.data.command}"`); } } async openHandler(data) { console.time("openHandler"); switch (this.data.actionType) { case "text": { await this.searchText(this.data.selection.text); break; } case "link": { if (this.data.commandTarget === "text") { await this.searchText(this.data.selection.text); } else { await this.openURL(this.data.selection.plainUrl); } break; } case "image": { if (this.data.selection.imageLink !== "") { await this.openURL(this.data.selection.imageLink); } else { await this.fetchImagePromise(this.data.extraImageInfo) .then(u8Array => { this.openImageViewer(u8Array); }); } break; } case "linkAndImage": { if (this.data.commandTarget === "link") { await this.openTab(this.data.selection.plainUrl); } else { await this.openTab(this.data.selection.imageLink); } break; } } console.timeEnd("openHandler"); } async copyHandler() { logUtil.log("copyHandler"); let p; switch (this.data.actionType) { case "link": { switch (this.data.commandTarget) { case "image": p = this.copyText( returnFirstNotNull( this.data.selection.imageLink, this.data.selection.link, )); break; case "text": p = this.copyText( returnFirstNotNull( this.data.selection.text, this.data.selection.link, )); break; case "link": p = this.copyText(this.data.selection.plainUrl); break; } break; } case "text": { p = this.copyText(this.data.selection.text); break; } case "image": { p = this.fetchImagePromise(this.data.extraImageInfo) .then(u8Array => { this.copyImage(u8Array); }); break; } case "linkAndImage": { if (this.data.commandTarget === "link") { p = this.copyText(this.data.selection.plainUrl) } else { p = this.fetchImagePromise(this.data.extraImageInfo) .then(u8Array => { this.copyImage(u8Array); }); } break; } } if (this.bgConfig.features.showNotificationAfterCopy) { p = p.then(this.showCopyNotificaion); } return p; } async searchHandler() { let p; switch (this.data.actionType) { case "link": { if (this.data.commandTarget === "text") { p = this.searchText(this.data.selection.text); } else { p = this.searchText(this.data.selection.plainUrl); } break; } case "image": { p = this.searchText(this.data.selection.imageLink); break; } case "text": { p = this.searchText(this.data.selection.text); break; } case "linkAndImage": { if (this.data.commandTarget === "link") { p = this.searchText(this.data.selection.plainUrl); } else { p = this.searchImage(this.data.selection.imageLink); } } } return p; } async downloadHandler() { if (this.data.selection.imageLink === null) { console.error("image link is null, could not start download") return; } switch (this.data.actionType) { case "image": { return this.download(this.data.selection.imageLink); } case "linkAndImage": { if (this.data.commandTarget === "image") { return this.download(this.data.selection.imageLink); } console.error("could not start download because commandTarget != image"); break; } default: { console.error("could not download image"); break; } } } async queryHandler() { logUtil.log("queryHandler"); if (this.data.actionType !== "text") { console.error(`unsuuport "query" command under ${this.data.actionType}`); return; } const tabId = this.sender.tab.id; logUtil.log(`send activeQueryWindow to tab ${tabId}`); return browser.tabs.sendMessage(tabId, { msgCmd: "activeQueryWindow", text: this.data.selection.text, }, { frameId: 0 }); } async searchText(keyword) { logUtil.log("search text: ", keyword); if (env.isFirefox && (this.data.searchEngine.url === "" || this.data.searchEngine.builtin === true)) { const tabHoldingSearch = await this.openTab("about:blank"); const option = { query: keyword, tabId: tabHoldingSearch.id, }; if (this.data.searchEngine.name !== "") { option.engine = this.data.searchEngine.name; } logUtil.log("call browser search api", ", engine name:", this.data.searchEngine.name, ", tab holds search page:", tabHoldingSearch, ", option: ", option); return browser.search.search(option); } if (!env.isFirefox && this.data.searchEngine.url === "") { browser.notifications.create({ type: "basic", title: "No Search Engine", message: "No search engine is speficied to performed search", }); return; } // TODO: check chromium logUtil.log(`search engine name: "${this.data.searchEngine.name}" , url: "${this.data.searchEngine.url}"`); return this.openURL(processURLPlaceholders(this.data.searchEngine.url, keyword, { site: this.data.site, })); } async searchImage(imageUrl) { //TODO return this.openTab(); } async searchImageByPostMethod(u8Array) { //TODO const key = randomString(10); this.temporaryDataStorage.set(key, { cmd: "search", data: u8Array, }); return this.openTab(REDIRECT_URL + "?key=" + key); } async findText(text = "") { logUtil.log("find text:", text); if (text.length === 0) { return; } const result = await browser.find.find(text); if (result.count > 0) { this.findFlag = true; browser.find.highlightResults(); } } async removeHighlighting() { logUtil.log("remove highlight"); if (this.findFlag) { this.findFlag = false; return browser.find.removeHighlighting(); } } async download(url) { const path = `${this.data.download.directory.trim()}${fileUtil.getFilename(url).trim()}`; logUtil.log("download: ", url, ", path: ", path, ", site: ", this.data.site); const headers = []; if (env.isFirefox) { headers.push({ name: "Referer", value: this.data.site }); } browser.downloads.download({ url, filename: path, saveAs: this.data.download.showSaveAsDialog, headers: headers, }); } async translateText(text) { const sended = { command: "translate", data: text, }; let portName = "sendToContentScript"; const tabs = await browser.tabs.query({ currentWindow: true, active: true, }); let port = browser.tabs.connect(tabs[0].id, { name: portName }); return port.postMessage(sended); } async copyText(data) { logUtil.log("copy text:", data); return navigator.clipboard.writeText(data); } async copyImage(u8Array) { logUtil.log("copy image, length:", u8Array); browser.clipboard.setImageData(u8Array, this.data.extraImageInfo.extension === ".png" ? "png" : "jpeg"); } //TODO remove this method async openURL(url) { if (typeof url !== "string") { console.error(`url is ${url} rather than string`); return; } await this.openTab(url); // return this.searchText(url); } async openTab(url) { if (typeof url !== "string") { console.error(`url is ${url} rather than string`); return; } console.trace("open tab: ", url, ", tabPosition: ", this.data.tabPosition, ", activeTab: ", this.data.activeTab); if (["newWindow", "privateWindow"].includes(this.data.tabPosition)) { let win; if ("newWindow" === this.data.tabPosition) { logUtil.log("create window"); win = await browser.windows.create(); } else { logUtil.log("attempt to reuse icongito window"); win = (await browser.windows.getAll({ windowTypes: ["normal"] })).find(w => w.incognito); if (!win) { logUtil.log("create new icongito window"); win = await browser.windows.create({ incognito: true }); } } const tab = await browser.tabs.create({ url: url, windowId: win.id, active: this.data.activeTab, }); if (true === this.data.activeTab) { browser.windows.update(win.id, { focused: true }); } return tab; } else { console.time("query tabs"); const tabs = await browser.tabs.query({ currentWindow: true }); console.timeEnd("query tabs"); const activatedTab = tabs.find(t => t.active); if (!activatedTab) { throw new Error("No actived tab is found"); } if (this.data.tabPosition === "current") { browser.tabs.update(activatedTab.id, { url }); } else { const option = { active: this.data.activeTab, url, openerTabId: activatedTab.id, }; if (this.data.tabPosition !== "") { option.index = this.getTabIndex(tabs.length, activatedTab.index); } // console.time("create tab") /*const newTab = */ return browser.tabs.create(option); // console.timeEnd("create tab") } } } getTabIndex(tabsLength = 0, currentTabIndex = 0) { logUtil.log("calc the index of new created tab", ", tabsLength:", tabsLength, ", currentTabIndex:", currentTabIndex, ", backgroundChildCount:", this.backgroundChildTabCount); if (this.data.activeTab) { this.backgroundChildTabCount = 0; } let index = 0; switch (this.data.tabPosition) { case "left": index = currentTabIndex; break; case "right": index = currentTabIndex + this.backgroundChildTabCount + 1; break; case "start": index = 0; break; case "end": index = tabsLength; break; default: break; } if (!this.data.activeTab && this.data.tabPosition === "right") { this.backgroundChildTabCount += 1; logUtil.log("increase backgroundChildTabCount: ", this.backgroundChildTabCount); } logUtil.log("the index of tab maybe: ", index); return index; } async fetchImagePromise(extraImageInfo) { logUtil.log("create fetch image promise"); return new Promise((resolve, reject) => { const port = browser.tabs.connect(this.sender.tab.id); if (port.error) { console.trace(port, port.error); reject(port.error); return; } port.onMessage.addListener(u8Array => { logUtil.log("got u8Array, call disconnect then resolve promise"); port.disconnect(); resolve(u8Array); }); port.postMessage(extraImageInfo.token); }); } async runScript() { return browser.tabs.executeScript({ code: `{ ${this.data.script}; ; }`, }); } async openImageViewer(u8Array) { } async showCopyNotificaion() { setTimeout(async() => { await browser.notifications.clear("copynotification"); }, 2000); return browser.notifications.create("copynotification", { message: `Copy Complete`, title: "Glitter Drag Notification", type: "basic", }); } }
//@ts-check "use strict"; require("dotenv").config(); const express = require("express") , session = require("express-session") , http = require("http") , socketIO = require("socket.io") , bodyParser = require("body-parser") , mongo = require("mongodb") , MongoStore = require("connect-mongo")(session) , path = require("path") , pug = require("pug") , morgan = require("morgan") , passport = require("passport") , TwitterStrategy = require("passport-twitter").Strategy , flash = require("connect-flash") , pictiles = require("./app/pictiles") ; const url = "mongodb://" + process.env.DBUSR + ":" + process.env.DBPW + "@" + process.env.DB_URI; const dbClient = mongo.MongoClient; dbClient.connect(url, (err, db) => { if (err) throw err; let app = express(); const server = http.Server(app); const io = socketIO(server); const sessionStore = session({ secret: "myDirtyLittleSecret" , resave: false , saveUninitialized: false , store: new MongoStore( { db: db , collection: "pictilesSessions" } ) , cookie: {maxAge: 24 * 60 * 60 * 1000} }); app.set("view engine", "pug"); app.set("views", path.join(__dirname, "views")); app.engine("pug", pug.__express); app.set("port", (process.env.PORT || 5000)); app.use( express.static(path.join(__dirname, "static")) , morgan("error") , bodyParser.json() , bodyParser.urlencoded({extended: true}) , flash() , sessionStore ); passport.use(new TwitterStrategy( { consumerKey: process.env.TWITTER_KEY, consumerSecret: process.env.TWITTER_SECRET, callbackURL: "/auth/twitter/callback" }, function(token, tokenSecret, profile, done) { db.collection("pictilesUsers").findOne({_id: profile.id}, function(err, user) { if (err) return done(err); if (user) { return done(null, user) } const newUser = { _id: profile.id, userName: profile.username, displayName: profile.displayName, pics: [] }; db.collection("pictilesUsers").insertOne(newUser, function(err, user) { if (err) return console.error(err); done(null, newUser); }); }); } )); passport.serializeUser((user, done) => { done(null, user) }) passport.deserializeUser((user, done) => { db.collection("pictilesUsers").findOne({_id: user._id}, function (err, user) { if (err) { return done(err); } return done(null, user); }); }); app.use(passport.initialize()); app.use(passport.session()); server.listen(app.get("port"), function() { console.log(app.name + " running on port " + app.get("port")) }) pictiles(app, db, passport); })
/*global SignaturePad: true*/ angular.module("ngSignaturePad").directive('signaturePad', function ($window) { "use strict"; var signaturePad, canvas, scope, element, EMPTY_IMAGE = "data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA="; function calculateHeight($element) { return parseInt($element.css("height"), 10) - 70; } function calculateWidth($element) { return parseInt($element.css("width"), 10) - 25; } function setCanvasHeightAndWidth() { var height = calculateHeight(element), width = calculateWidth(element); scope.signatureWidth = width; scope.signatureHeight = height; canvas.attr("height", height); canvas.attr("width", width); } $window.addEventListener("resize", function () { scope.$apply(function () { var img = signaturePad.toDataURL(); setCanvasHeightAndWidth(); signaturePad.fromDataURL(img); }); }, false); $window.addEventListener("orientationchange", function () { scope.$apply(function () { var img = signaturePad.toDataURL(); setCanvasHeightAndWidth(); signaturePad.fromDataURL(img); }); }, false); return { restrict: 'A', replace: true, template: '<div class="signature-background">' + '<div class="action">' + '<button ng-click="accept()">OK</button>' + '<button " ng-click="clear()">Empty</button>' + '</div>' + '<div class="signature" ng-style="{height: signatureHeight, width: signatureWidth}" >' + '<canvas></canvas>' + '</div>' + '</div>', scope: { signature: "=signature", close: "&" }, controller: function ($scope) { $scope.accept = function () { if (!signaturePad.isEmpty()) { $scope.signature.dataUrl = signaturePad.toDataURL(); $scope.signature.$isEmpty = false; } else { $scope.signature.dataUrl = EMPTY_IMAGE; $scope.signature.$isEmpty = true; } $scope.close(); }; $scope.clear = function () { signaturePad.clear(); setCanvasHeightAndWidth(); }; }, link: function ($scope, $element) { canvas = $element.find("canvas"); scope = $scope; element = $element; signaturePad = new SignaturePad(canvas.get(0)); setCanvasHeightAndWidth(); if ($scope.signature && !$scope.signature.$isEmpty && $scope.signature.dataUrl) { signaturePad.fromDataURL($scope.signature.dataUrl); } } }; });
var cluster = require('cluster'); var crypto = require('crypto'); var pearson = require('../'); if (cluster.isMaster){ var numCPUs = require('os').cpus().length; //Getting a random seed for pearson var theSeed = pearson.seed(); console.log('Generated seed:\n' + theSeed.toString('hex')); //Generating random data to be collisionned var d = randomData(); console.log('Attempting to collision: ' + d.toString('hex')); //Setting up cluster parameters cluster.setupMaster({ args: [theSeed.toString('hex'), d.toString('hex')] }); //Start time : var startTime = process.hrtime(); var workers = [] //Spawnning workers for (var i = 0; i < numCPUs; i++){ var newWorker = cluster.fork(); newWorker.once('message', msgHandler); workers.push(newWorker); } function msgHandler(m){ var msgParts = m.split(/\r\n/); var collision = msgParts[0]; var attempts = Number(msgParts[1]); console.log('Collision found: ' + collision); var endTime = process.hrtime(startTime); var elapsedTime = endTime[0] + endTime[1] / 1e9; console.log('Elapsed time: ' + elapsedTime + ' seconds'); //Getting number of attempts from each worker, and then killing them var count = attempts; var stopped = 1; while (workers.length > 0){ var currentWorker = workers[0]; try { currentWorker.removeAllListeners(); currentWorker.once('message', function(c){ console.log('cb: ' + c); c = Number(c); count += c; currentWorker.kill(); stopped++; }); currentWorker.send('stop'); console.log('Stop sent'); } catch (e){ console.error(e); process.exit(1); } workers.splice(0, 1); } setInterval(function(){ if (stopped == numCPUs){ console.log('Number of trials before collision: ' + count); process.exit(); } }, 50); } } else { var pid = cluster.worker.process.pid; function log(m){console.log('[' + pid + '] ' + m)}; var seed = new Buffer(cluster.worker.process.argv[2], 'hex'); var dataToCollision = new Buffer(cluster.worker.process.argv[3], 'hex'); var hashToCollision = pearson(dataToCollision, null, seed); var attempt; var count = 0; //Binding message events cluster.worker.on('message', function(msg){ if (msg == 'stop'){ log('Stopping'); log('Count: ' + count); cluster.worker.send(count.toString()); cluster.worker.process.exit(); } }); do { attempt = randomData(); count++; } while (!bufEquals(pearson(attempt, null, seed), hashToCollision)); cluster.worker.send(attempt.toString('hex') + '\r\n' + count.toString()); } function bufEquals(b1, b2){ if (!(Buffer.isBuffer(b1) && Buffer.isBuffer(b2))) return false; if (b1.length != b2.length) return false; for (var i = 0; i < b1.length; i++) if (b1[i] != b2[i]) return false; return true; } function randomData(){ var dLength = Math.ceil(16 * Math.random()); return crypto.pseudoRandomBytes(dLength); }
/*! * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ // jQuery to collapse the navbar on scroll $(window).scroll(function() { if ($(".navbar").offset().top > 50) { $(".navbar-fixed-top").addClass("top-nav-collapse"); } else { $(".navbar-fixed-top").removeClass("top-nav-collapse"); } }); // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); // Google Maps Scripts // When the window has finished loading create our google map below // google.maps.event.addDomListener(window, 'load', init); function init() { // Basic options for a simple Google Map // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions var mapOptions = { // How zoomed in you want the map to start at (always required) zoom: 15, // The latitude and longitude to center the map (always required) center: new google.maps.LatLng(40.6700, -73.9400), // New York // Disables the default Google Maps UI components disableDefaultUI: true, scrollwheel: false, draggable: false, // How you would like to style the map. // This is where you would paste any style found on Snazzy Maps. styles: [{ "featureType": "water", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 17 }] }, { "featureType": "landscape", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 20 }] }, { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [{ "color": "#000000" }, { "lightness": 17 }] }, { "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [{ "color": "#000000" }, { "lightness": 29 }, { "weight": 0.2 }] }, { "featureType": "road.arterial", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 18 }] }, { "featureType": "road.local", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 16 }] }, { "featureType": "poi", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 21 }] }, { "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#000000" }, { "lightness": 16 }] }, { "elementType": "labels.text.fill", "stylers": [{ "saturation": 36 }, { "color": "#000000" }, { "lightness": 40 }] }, { "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "transit", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 19 }] }, { "featureType": "administrative", "elementType": "geometry.fill", "stylers": [{ "color": "#000000" }, { "lightness": 20 }] }, { "featureType": "administrative", "elementType": "geometry.stroke", "stylers": [{ "color": "#000000" }, { "lightness": 17 }, { "weight": 1.2 }] }] }; // Get the HTML DOM element that will contain your map // We are using a div with id="map" seen below in the <body> var mapElement = document.getElementById('map'); // Create the Google Map using out element and options defined above var map = new google.maps.Map(mapElement, mapOptions); // Custom Map Marker Icon - Customize the map-marker.png file to customize your icon var image = 'img/map-marker.png'; var myLatLng = new google.maps.LatLng(40.6700, -73.9400); var beachMarker = new google.maps.Marker({ position: myLatLng, map: map, icon: image }); }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const os = require("os"); const path = require("path"); const fs_1 = require("@ionic/cli-framework/utils/fs"); exports.ERROR_SSH_MISSING_PRIVKEY = 'SSH_MISSING_PRIVKEY'; exports.ERROR_SSH_INVALID_PUBKEY = 'SSH_INVALID_PUBKEY'; exports.ERROR_SSH_INVALID_PRIVKEY = 'SSH_INVALID_PRIVKEY'; function getGeneratedPrivateKeyPath(env) { return tslib_1.__awaiter(this, void 0, void 0, function* () { const config = yield env.config.load(); const id = config.user.id ? config.user.id : 'anonymous'; return path.resolve(os.homedir(), '.ssh', 'ionic', id); }); } exports.getGeneratedPrivateKeyPath = getGeneratedPrivateKeyPath; function parsePublicKeyFile(pubkeyPath) { return tslib_1.__awaiter(this, void 0, void 0, function* () { try { yield fs_1.fsStat(pubkeyPath); } catch (e) { if (e.code === 'ENOENT') { throw fs_1.ERROR_FILE_NOT_FOUND; } throw e; } return parsePublicKey((yield fs_1.fsReadFile(pubkeyPath, { encoding: 'utf8' })).trim()); }); } exports.parsePublicKeyFile = parsePublicKeyFile; /** * @return Promise<[full pubkey, algorithm, public numbers, annotation]> */ function parsePublicKey(pubkey) { return tslib_1.__awaiter(this, void 0, void 0, function* () { const r = /^(ssh-[A-z0-9]+)\s([A-z0-9+\/=]+)\s?(.+)?$/.exec(pubkey); if (!r) { throw exports.ERROR_SSH_INVALID_PUBKEY; } if (!r[3]) { r[3] = ''; } r[1] = r[1].trim(); r[2] = r[2].trim(); r[3] = r[3].trim(); return [pubkey, r[1], r[2], r[3]]; }); } exports.parsePublicKey = parsePublicKey; function validatePrivateKey(keyPath) { return tslib_1.__awaiter(this, void 0, void 0, function* () { try { yield fs_1.fsStat(keyPath); } catch (e) { if (e.code === 'ENOENT') { throw exports.ERROR_SSH_MISSING_PRIVKEY; } throw e; } const f = yield fs_1.fsReadFile(keyPath, { encoding: 'utf8' }); const lines = f.split('\n'); if (!lines[0].match(/^\-{5}BEGIN [R|D]SA PRIVATE KEY\-{5}$/)) { throw exports.ERROR_SSH_INVALID_PRIVKEY; } }); } exports.validatePrivateKey = validatePrivateKey;
angular.module('student.attendance').service('StudentAttendanceService', [ '$rootScope', '$q', function( $rootScope, $q ){ var exports = {}; exports.getAttendances = function(){ var deferred = $q.defer(); var mAttendances = $rootScope.$meteorCollection(Attendances, false); $rootScope.$meteorSubscribe('ownerAttendances').then(function (handle) { var attendances = $rootScope.$meteorObject(Attendances, {}, true); if(!attendances.attendance){ attendances.attendance = []; } $rootScope.hasId = false; if(attendances._id){ $rootScope.hasId = true; } if(!$rootScope.hasId){ mAttendances.save({owner:$rootScope.currentUser._id, attendance:attendances.attendance}).then(function(){ attendances = $rootScope.$meteorObject(Attendances, {}, true); deferred.resolve(attendances); }); } if($rootScope.hasId){ deferred.resolve(attendances); } }); return deferred.promise; }; return exports; } ]);
"use strict"; module.exports = { modules: [], configure: function (names) { if (names) { names = names instanceof Array ? names : [names]; names.forEach(function (name) { var Module = require(name); this.modules.push(Module); }, this); } } };
var Ad = {}; Ad.edit = { init : function() { $('[name=type]').click(function(e) { var type = $(this).val(), nodes = []; switch (type) { case 'zl' : nodes = [ ['cpm_size', 0], ['size', 0], ['html_code', 0], ['img_url', 0], ['zl_item', 1] ]; break; case 'tw' : nodes = [ ['cpm_size', 0], ['size', 1], ['html_code', 1], ['img_url', 0], ['zl_item', 0] ]; break; case 'img' : nodes = [ ['cpm_size', 0], ['size', 1], ['html_code', 0], ['img_url', 1], ['zl_item', 0] ]; break; case 'zn' : nodes = [ ['cpm_size', 0], ['size', 0], ['html_code', 1], ['img_url', 0], ['zl_item', 0] ]; break; } $.each(nodes, function(k, v) { $('[g=' + v[0] + ']')[(v[1] ? 'show' : 'hide')](); }) }).trigger('click'); } }; /** * 充值 */ var Recharge = { win : {}, //窗口对象 add : function(userName, userType, dao) { dao = dao || {}; if (!dao.user_name) { dao.user_name = userName; } if (!dao.user_type) { dao.user_type = userType; } this.openAddDialog(dao); }, openAddDialog : function(dao) { var $h = $($('#t-recharge-form').html()), _this = this; this.win = dialog({ title : '手工充值', content : $h, width : 400, height : 180, okValue : '保存', ok : function () { var d = _this.getFormDao($h); _this.save(d); return false; }, cancelValue: '取消', cancel: function () {} }); this.win.showModal(); dao.user_type = parseInt(dao.user_type, 10); switch (dao.user_type) { case 1 : $h.find('[g=money_pre]').hide(); break; case 2 : $h.find('[g=money_type]').hide(); break; default : alert('会员类型有误'); return false; } this.fillForm($h, dao); }, getFormDao : function($f) { var dao = { id : $f.find('[name=id]').val(), user_name : $f.find('[name=user_name]').val(), money_type : $f.find('[name=money_type]:checked').val(), type : $f.find('[name=type]:checked').val(), money : $f.find('[name=money]').val(), comment : $f.find('[name=comment]').val() }; return dao; }, fillForm : function($f, dao) { if (dao.user_name) { $f.find('[name=user_name]').val(dao.user_name); } dao.money_type = dao.money_type || 1; $f.find('[name=money_type][value=' + dao.money_type + ']').attr({ checked : true}); if (dao.money) { $f.find('[name=money]').val(dao.money); } if (dao.comment) { $f.find('[name=comment]').val(dao.comment); } if (dao.type) { $f.find('[name=type][value='+dao.type+']').attr({checked : true}); } /** * 只有扣除预充值时才会有id */ if (dao.id) { $f.find('[name=id]').val(dao.id); var disabled = {disabled : true}; $f.find('input[type=text]').attr(disabled); $f.find('input[type=radio]').attr(disabled); $f.find('textarea').attr(disabled); } return true; }, save : function(dao) { var url = '?c=Recharge&a=', _this = this; url += (dao.id) ? 'doDeduct' : 'doSave'; $.post(url, dao, function(j) { if (!j.s) { alert(j.m); return false; } window.location.href = window.location.href; _this.win.close(); }, 'json'); }, deduct : function(id) { if (typeof(id) == 'undefined') { alert('参数不完整'); } var _this = this, d = dialog({ content : '正在载入数据,请稍等...' }); d.showModal(); $.getJSON('?c=Recharge&a=getById', {id : id}, function(j) { d.close(); if (!j.s) { alert(j.m); return false; } var dao = j.m; dao.type = 2; dao.money_type = 1; dao.user_type = 2; dao.comment = '扣除' + dao.finish_time + '预充的' + dao.money + '元'; _this.openAddDialog(dao); }) } };