code
stringlengths
2
1.05M
/* * * MassiveMap constants * */ export const DEFAULT_ACTION = 'app/MassiveMap/DEFAULT_ACTION'; export const LOAD_HINTS = 'app/MassiveMap/LOAD_HINTS'; export const LOAD_HINTS_ERROR = 'app/MassiveMap/LOAD_HINTS_ERROR'; export const LOAD_HINTS_SUCCESS = 'app/MassiveMap/LOAD_HINTS_SUCCESS'; export const LOAD_STATUS = 'app/MassiveMap/LOAD_STATUS'; export const LOAD_STATUS_ERROR = 'app/MassiveMap/LOAD_STATUS_ERROR'; export const LOAD_STATUS_SUCCESS = 'app/MassiveMap/LOAD_STATUS_SUCCESS'; export const LOAD_CARS = 'app/MassiveMap/LOAD_CARS'; export const LOAD_CARS_ERROR = 'app/MassiveMap/LOAD_CARS_ERROR'; export const LOAD_CARS_SUCCESS = 'app/MassiveMap/LOAD_CARS_SUCCESS'; export const TOGGLE_HISTORY = 'app/MassiveMap/TOGGLE_HISTORY'; export const RIGHT_CLICK_EVENT = 'app/MassiveMap/RIGHT_CLICK_EVENT'; export const RIGHT_CLICK_EVENT_SUCCESS = 'app/MassiveMap/RIGHT_CLICK_EVENT_SUCCESS'; export const CLEAR_LOCATION = 'app/MassiveMap/CLEAR_LOCATION'; export const SET_LATLNG = 'app/MassiveMap/SET_LATLNG'; export const LOAD_PREDICTIONS = 'app/MassiveMap/LOAD_PREDICTIONS'; export const LOAD_PREDICTIONS_SUCCES = 'app/MassiveMap/LOAD_PREDICTIONS_SUCCES'; export const LOAD_PREDICTIONS_ERROR = 'app/MassiveMap/LOAD_PREDICTIONS_ERROR ';
var initializeDOM = function () { // Clean the DOM document.body.innerHTML = ''; var input = document.createElement('input'); input.value = 'TestValue'; input.id = '__REQUESTDIGEST'; document.body.appendChild(input); }; initializeDOM();
/** * Generics Support for Javascript * Can be included in any class to enforce dynamic strong typing **/ var Generics = (function() { var privateData = new WeakMap(); function Generics(T){ var privateMembers = {}; if(T !== undefined && typeof T.constructor === 'function'){ privateMembers.type = T; }else if(typeof T === 'string' || typeof T === 'number' || typeof T === 'boolean'){ privateMembers.type = typeof T; }else{ privateMembers.type = undefined; } privateData.set(this, privateMembers); } Generics.prototype.constructor = Generics; /** * Internal method that emulates Generics behaviour * @return {boolean} True if the element is of the Generics type or if Generics * are disabled. * @throws {IllegalArgumentException} If the element does not match the Generics type **/ Generics.prototype.checkType = function(t){ var T = privateData.get(this).type; if(T !== undefined && typeof T.constructor === 'function'){ if(t instanceof T){ return true; }else{ console.error(t); throw new IllegalArgumentException("Parameter does not match the Generic Type " + T.name); } }else if(typeof T === 'string'){ if(typeof t === 'string') return true; else throw new IllegalArgumentException("Parameter does not match the Generic Type string"); }else if(typeof T === 'number'){ if(typeof t === 'number') return true; else throw new IllegalArgumentException("Parameter does not match the Generic Type number"); }else if(typeof T === 'boolean'){ if(typeof t === 'boolean') return true; else throw new IllegalArgumentException("Parameter does not match the Generic Type boolean"); }else{ return true; } }; Generics.prototype.getType = function(){ return privateData.get(this).type; }; Generics.prototype.isPrimitive = function(){ var T = private.Data.get(this).type; return (typeof T !== 'function' && typeof T !== undefined); }; return Generics; }());
// Generated by CoffeeScript 1.7.1 var addCommas, boundingBox, canvasHeight, canvasWidth, colorbrewerGreen, generateLineGraph, labelPadding, line, lowerErrorBand, margin, orgs, svg, tooltipOffset, upperErrorBand, xAxis, xScale, yAxis, yScale, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; margin = { top: 20, bottom: 20, left: 20, right: 20 }; canvasWidth = 1100 - margin.left - margin.right; canvasHeight = 600 - margin.top - margin.bottom; svg = d3.select("#vis").append("svg").attr("width", canvasWidth + margin.left + margin.right).attr("height", canvasHeight + margin.top + margin.top).append("g").attr("transform", "translate(" + margin.left + ", " + margin.top + ")"); boundingBox = { x: 50, y: 0, width: canvasWidth - 100, height: canvasHeight - 50 }; orgs = ["us_census", "pop_reference", "un_desa", "hyde", "maddison"]; labelPadding = 7; colorbrewerGreen = "#4daf4a"; tooltipOffset = 5; addCommas = function(number) { return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); }; xScale = d3.scale.linear().range([0, boundingBox.width]); yScale = d3.scale.log().range([boundingBox.height, 0]); xAxis = d3.svg.axis().scale(xScale).orient("bottom"); yAxis = d3.svg.axis().scale(yScale).orient("left"); line = d3.svg.line().interpolate("linear").x(function(d) { return xScale(d.year); }).y(function(d) { return yScale(d.consensusValue); }); upperErrorBand = d3.svg.area().x(function(d) { return xScale(d.year); }).y0(function(d) { return yScale(d.consensusValue); }).y1(function(d) { return yScale(d.maxEstimate); }); lowerErrorBand = d3.svg.area().x(function(d) { return xScale(d.year); }).y0(function(d) { return yScale(d.minEstimate); }).y1(function(d) { return yScale(d.consensusValue); }); generateLineGraph = function(dataset) { var absoluteLowerDivergence, absoluteUpperDivergence, chartArea, combinedData, consensusValue, frame, maxEstimate, minEstimate, org, point, points, relativeLowerDivergence, relativeUpperDivergence, relevantEstimates, year, zoom, zoomed, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2; xScale.domain(d3.extent(dataset.allYears)); yScale.domain(d3.extent(dataset.allEstimates)); zoomed = function() { svg.select(".x.axis").call(xAxis); svg.select(".y.axis").call(yAxis); svg.select(".error-band.upper").attr("d", upperErrorBand); svg.select(".error-band.lower").attr("d", lowerErrorBand); svg.select(".line").attr("d", line); return svg.selectAll(".point").attr("transform", function(d) { return "translate(" + (xScale(d.year)) + ", " + (yScale(d.consensusValue)) + ")"; }); }; zoom = d3.behavior.zoom().x(xScale).y(yScale).on("zoom", zoomed); frame = svg.append("g").attr("transform", "translate(" + boundingBox.x + ", " + boundingBox.y + ")").call(zoom); frame.append("clipPath").attr("id", "clip").append("rect").attr("width", boundingBox.width).attr("height", boundingBox.height); frame.append("g").attr("class", "x axis").attr("transform", "translate(0, " + boundingBox.height + ")").call(xAxis); frame.append("g").attr("class", "y axis").call(yAxis); frame.append("text").attr("class", "x label").attr("text-anchor", "end").attr("x", boundingBox.width).attr("y", boundingBox.height - labelPadding).text("Year"); frame.append("text").attr("class", "y label").attr("text-anchor", "end").attr("y", labelPadding).attr("dy", ".75em").attr("transform", "rotate(-90)").text("log₁₀(Population)"); combinedData = []; _ref = dataset.allYears; for (_i = 0, _len = _ref.length; _i < _len; _i++) { year = _ref[_i]; relevantEstimates = []; for (_j = 0, _len1 = orgs.length; _j < _len1; _j++) { org = orgs[_j]; _ref1 = dataset[org]; for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) { point = _ref1[_k]; if (point.year === year) { relevantEstimates.push(point.estimate); break; } } } consensusValue = d3.mean(relevantEstimates); _ref2 = d3.extent(relevantEstimates), minEstimate = _ref2[0], maxEstimate = _ref2[1]; absoluteUpperDivergence = maxEstimate - consensusValue; absoluteLowerDivergence = consensusValue - minEstimate; relativeUpperDivergence = (maxEstimate / consensusValue) * 100 - 100; relativeLowerDivergence = 100 - (minEstimate / consensusValue) * 100; combinedData.push({ year: year, consensusValue: consensusValue, maxEstimate: maxEstimate, minEstimate: minEstimate, absoluteUpperDivergence: absoluteUpperDivergence, absoluteLowerDivergence: absoluteLowerDivergence, relativeUpperDivergence: relativeUpperDivergence, relativeLowerDivergence: relativeLowerDivergence }); } chartArea = frame.append("g").attr("clip-path", "url(#clip)"); chartArea.append("rect").attr("class", "overlay").attr("width", boundingBox.width).attr("height", boundingBox.height); chartArea.append("path").datum(combinedData).attr("class", "error-band upper").attr("d", upperErrorBand); chartArea.append("path").datum(combinedData).attr("class", "error-band lower").attr("d", lowerErrorBand); chartArea.append("path").datum(combinedData).attr("class", "line").attr("d", line); points = chartArea.selectAll(".point").data(combinedData).enter().append("circle").attr("class", "point").attr("transform", function(d) { return "translate(" + (xScale(d.year)) + ", " + (yScale(d.consensusValue)) + ")"; }).attr("r", 4); points.on("mouseover", function(d) { d3.select(this).style("fill", colorbrewerGreen); d3.select("#tooltip").style("left", "" + (d3.event.pageX + tooltipOffset) + "px").style("top", "" + (d3.event.pageY + tooltipOffset) + "px"); d3.select("#consensus-value").text("" + (addCommas(Math.round(d.consensusValue))) + " individuals"); d3.select("#upper-divergence").text("" + (addCommas(Math.round(d.absoluteUpperDivergence))) + " individuals (" + (d.relativeUpperDivergence.toFixed(2)) + "%)"); d3.select("#lower-divergence").text("" + (addCommas(Math.round(d.absoluteLowerDivergence))) + " individuals (" + (d.relativeLowerDivergence.toFixed(2)) + "%)"); return d3.select("#tooltip").classed("hidden", false); }); return points.on("mouseout", function() { d3.select(this).transition().duration(500).style("fill", "white"); return d3.select("#tooltip").classed("hidden", true); }); }; d3.csv("populationEstimates.csv", function(data) { var allEstimates, allYears, dataset, estimate, estimates, interpolatedData, interpolator, org, point, relevantYears, row, year, years, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _len6, _m, _n, _o, _ref; dataset = {}; for (_i = 0, _len = orgs.length; _i < _len; _i++) { org = orgs[_i]; dataset[org] = []; } for (_j = 0, _len1 = data.length; _j < _len1; _j++) { row = data[_j]; year = row.year; for (_k = 0, _len2 = orgs.length; _k < _len2; _k++) { org = orgs[_k]; estimate = row[org]; if (estimate !== "") { dataset[org].push({ year: +year, estimate: +estimate }); } } } allYears = []; allEstimates = []; for (org in dataset) { data = dataset[org]; for (_l = 0, _len3 = data.length; _l < _len3; _l++) { point = data[_l]; year = point.year; if (__indexOf.call(allYears, year) < 0) { allYears.push(year); } estimate = point.estimate; if (__indexOf.call(allEstimates, estimate) < 0) { allEstimates.push(estimate); } } } dataset.allYears = allYears.sort(); dataset.allEstimates = allEstimates; for (_m = 0, _len4 = orgs.length; _m < _len4; _m++) { org = orgs[_m]; years = []; estimates = []; _ref = dataset[org]; for (_n = 0, _len5 = _ref.length; _n < _len5; _n++) { point = _ref[_n]; years.push(point.year); estimates.push(point.estimate); } interpolator = d3.scale.linear().domain(years).range(estimates); interpolatedData = []; relevantYears = allYears.slice(allYears.indexOf(years[0]), +allYears.indexOf(years[years.length - 1]) + 1 || 9e9); for (_o = 0, _len6 = relevantYears.length; _o < _len6; _o++) { year = relevantYears[_o]; estimate = interpolator(year); interpolatedData.push({ year: year, estimate: estimate }); } dataset[org] = interpolatedData; } return generateLineGraph(dataset); });
/*global describe, it */ 'use strict'; var assert = require('assert'); var PriorityQueue = require('../src/priority-queue-adt.js'); var pq = new PriorityQueue(); describe('PriorityQueue operations test', function () { it('should create an empty priority-queue in the beginning', function(){ assert.equal(pq.isEmpty(), true); assert.equal(pq.size(), 0); }); });
import {fromJS} from "immutable"; import {MESSAGE_SENT} from "../App/actions/responses"; import {CHANGE_MESSAGE} from "./actions"; import {INSERT_EMOJI} from "../EmojiList/actions"; import {INPUT_ID} from "./constants"; const initState = fromJS({}); export default function(state = initState, action, threadID) { switch (action.type) { case MESSAGE_SENT: return state .set(action.threadID, ""); case CHANGE_MESSAGE: return state .set(threadID, action.message); case INSERT_EMOJI: if (!action.emoji) return state; /* Add an emoji on the cursor position inside the message input. Should potentially be moved to the component to keep the reducer free from UI logic. */ const input = document.getElementById(INPUT_ID); const selectStart = input.selectionStart; const selectEnd = input.selectionEnd; input.focus(); /* Put the cursor at the end of the newly inserted emoji. Must be delayed because taking focus takes a short while and resets the selection. */ setTimeout(() => { input.setSelectionRange(selectStart+2, selectEnd+2) }, 200); /* Update the cached message. */ return state .update(threadID, message => message ? message.substring(0,selectStart) + action.emoji + message.substring(selectEnd) : action.emoji); } }
'use strict' // initialize global listing data object const dev = '1oDO9zkpaK1wUSynqYgpQzIs3BJVZN9H19DtwQXBjNfw' const staging = '1nz4bJDJdKXyGvMbzfAYol6TpwfsVyoeKWKLFFjYa1Hw' const prod = '1oG10rZemC5R6-EcE8bLUofAMoJaqnsS-lgKxGUCuW2c' let listingsObj // // Template Rendering Functions // // render template and return html content function renderTemplate(source, data) { const template = Handlebars.compile(source) const content = template({data:data}) return content } // render template and insert in target element function replaceTemplate(target, source, data) { const template = Handlebars.compile(source) const content = template({data:data}) $(target).html(content) } // render template and append to target element function appendTemplate(target, source, data) { const template = Handlebars.compile(source) const content = template({data:data}) $(target).append(content) } // clear element from DOM function removeTemplate(target) { $(target).remove() } // display modal function showModal(content) { // if there's already a modal if ($('.modal').length) { // replace the existing modal replaceTemplate($('.modal')[0], content) } else { // append a new modal to the body $('body').append(content) } // display modal $('.modal').modal('show') } // // AJAX calls // // make AJAX call to JSON feed and return promise function getListingData(path) { return $.ajax({ url: path, cache: true }) } // make AJAX call to Handlebars template file and return promise function getTemplate (path) { return $.ajax({ url: path, cache: true }) } // Submit Contact Form function submitContact (data) { return $.ajax({ url: './cgi/submit.php', type: 'POST', data: data, cache: false }) } // // Listing Detail Functions // // get data from listingData array from mls number function getDetailData (mls) { for (let i = 0; i < listingsObj.data.length; i++) { if (listingsObj.data[i].mls == mls) { return listingsObj.data[i] } } } // render and display listing detail in a full screen modal function showDetails (mls) { getTemplate('js/templates/modal-detail.hbs') .then((template) => { const data = getDetailData(mls) const content = renderTemplate(template, data) showModal(content) }) .fail((err) => console.log('listing template is not available', err)) } // jQuery Gallery Setup function setUpGallery() { // Galleria.loadTheme('https://cdnjs.cloudflare.com/ajax/libs/galleria/1.5.7/themes/classic/galleria.classic.min.js'); Galleria.loadTheme('vendor/galleria/classic/galleria.classic.js') Galleria.configure({ idleMode:false, showImagenav: true }) Galleria.run('.galleria') } // // Contact Form Modal Functions // function showContactForm (event) { event.preventDefault() debugger; getTemplate('js/templates/modal-contact.hbs') .then((template) => { const content = renderTemplate(template) showModal(content) // auto-format phone number on input $('#phone').mask('(999) 999-9999',{placeholder:' '}) }) .fail((err) => console.log('contact template is not available')) } function showSubmitError () { getTemplate('js/templates/modal-submit-error.hbs') .then((template) => { const content = renderTemplate(template) showModal(content) }) .fail((err) => console.log('submit errror template is not available')) } function showSubmitSuccess () { getTemplate('js/templates/modal-submit-success.hbs') .then((template) => { const content = renderTemplate(template) showModal(content) }) .fail((err) => console.log('submit success template is not available')) } // // Event Handlers // function handleEvents () { // jQuery for page scrolling feature using jQuery Easing plugin $('a.page-scroll').bind('click', function(event) { const $anchor = $(this) $('html, body').stop().animate({ scrollTop: ($($anchor.attr('href')).offset().top - 100) }, 800, 'easeInOutExpo') event.preventDefault() }) // Highlight the top nav as page scrolls $('body').scrollspy({ target: '.navbar-fixed-top', offset: 100 }) // Close the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function(){ $('.navbar-toggle:visible').click() }) // Offset for Main Navigation $('#mainNav').affix({ offset: { top: 92 } }) // show listing detail modal when 'see more' is clicked $('.listings').on('click', '.see-more', (e) => { showDetails($(e.target).data('mls')) }) // show contact form modal when button is clicked $('.contact-btn').click((event) => { showContactForm(event) }) $('.how-it-works').on('click', '.contact-link', (e) => { debugger; showContactForm(e) }) // submit contact form $('body').on('submit', 'form#contact-form', event => { event.preventDefault() const name = $('input#firstName').val() + ' ' + $('input#lastName').val() const email = $('input#email').val() const phone = $('input#phone').val() const data = { name: name, email: email, phone: phone } submitContact(data) .then(showSubmitSuccess) .fail(showSubmitError) // reset form fields $('form#contact-form input').val('') }) // initialize jquery gallery in detail modal $('body').on('show.bs.modal', '#detail-modal', () => { setUpGallery() }) // clear modal from DOM when closed $('body').on('hidden.bs.modal', '.modal', () => { removeTemplate('.modal') }) } // // Document Ready // $(function() { // set event handlers handleEvents() // get data from JSON feed and wait for promise to be returned listingsObj = new ListingData(prod, dev, staging) getListingData(listingsObj.url) .then((data) => { // set global listing object to JSON feed data listingsObj.setData(data.feed.entry) // get template and render getTemplate('js/templates/listings.hbs') .then((template) => { replaceTemplate('#listings', template, listingsObj.data) }) .fail((err) => console.log('listing template is not available')) }) .fail((err) => console.log('data feed is not available')) })
// DATA_TEMPLATE: empty_table oTest.fnStart("aoColumns.bSeachable"); $(document).ready(function () { /* Check the default */ var oTable = $('#example').dataTable({ "sAjaxSource": "../../../examples/ajax/sources/objects.txt", "aoColumns": [ { "mData": "engine" }, { "mData": "browser" }, { "mData": "platform" }, { "mData": "version" }, { "mData": "grade" } ] }); var oSettings = oTable.fnSettings(); oTest.fnWaitTest( "Columns are searchable by default", function () { oTable.fnFilter("Camino"); }, function () { if ($('#example tbody tr:eq(0) td:eq(1)')[0]) return $('#example tbody tr:eq(0) td:eq(1)').html().match(/Camino/); else return null; } ); oTest.fnWaitTest( "Disabling sorting on a column removes it from the global filter", function () { oSession.fnRestore(); oTable = $('#example').dataTable({ "sAjaxSource": "../../../examples/ajax/sources/objects.txt", "aoColumns": [ { "mData": "engine" }, { "mData": "browser", "bSearchable": false }, { "mData": "platform" }, { "mData": "version" }, { "mData": "grade" } ] }); oSettings = oTable.fnSettings(); oTable.fnFilter("Camino"); }, function () { return $('#example tbody tr:eq(0) td:eq(0)').html() == "No matching records found"; } ); oTest.fnWaitTest( "Disabled on one column has no effect on other columns", function () { oTable.fnFilter("Webkit"); }, function () { return $('#example tbody tr:eq(0) td:eq(0)').html() == "Webkit"; } ); oTest.fnWaitTest( "Disable filtering on multiple columns", function () { oSession.fnRestore(); oTable = $('#example').dataTable({ "sAjaxSource": "../../../examples/ajax/sources/objects.txt", "aoColumns": [ { "mData": "engine", "bSearchable": false }, { "mData": "browser", "bSearchable": false }, { "mData": "platform" }, { "mData": "version" }, { "mData": "grade" } ] }); oSettings = oTable.fnSettings(); oTable.fnFilter("Webkit"); }, function () { return $('#example tbody tr:eq(0) td:eq(0)').html() == "No matching records found"; } ); oTest.fnWaitTest( "Filter on second disabled column", function () { oTable.fnFilter("Camino"); }, function () { return $('#example tbody tr:eq(0) td:eq(0)').html() == "No matching records found"; } ); oTest.fnComplete(); });
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = doris; var _object = _interopRequireDefault(require("./object")); var _utils = _interopRequireDefault(require("./utils")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } /** * * Instantiates a DorisObject based on the selector input. * * @param {(string|Array|Node|NodeList|Window|document|DorisObject)} nodes A CSS selector, a * DOM node, one of the root elements (window, document) or nother instance * of a DorisObject (the nodes will be the same). * @return {DorisObject} */ function doris(nodes) { var nodesObject; if (nodes instanceof Node) { // Standard DOM node. nodesObject = [nodes]; } else if (_typeof(nodes) === 'object' && nodes.elements) { // Another DorisObject being passed nodesObject = nodes.elements; } else if (nodes === document || nodes === document.documentElement) { nodesObject = [document.documentElement]; } else if (nodes === window) { nodesObject = [window]; } else if (typeof nodes === 'string') { try { nodesObject = document.querySelectorAll(nodes); } catch (e) { if (e instanceof DOMException) { nodesObject = _utils.default.stringToDOM(nodes); } else { throw new Error('Invalid Doris argument!'); } } } return new _object.default(nodesObject); } if (typeof window !== 'undefined') { window.doris = doris; } else { throw new Error('Doris is meant to be run in a browser!'); } },{"./object":4,"./utils":5}],2:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * * DorisEvent is a minimal wrapper around DOM events for the purpose of event * delegation handling inside Doris. You shouldn't really use this for * anything. * * @type {DorisEvent} */ var DorisEvent = /*#__PURE__*/ function () { /** * * Wraps a normal event with the purpose of assisting the event delegation * in Doris. * * @param {Event} event */ function DorisEvent(event) { _classCallCheck(this, DorisEvent); /** @member {bool} */ this.preventedDefault = false; /** @member {bool} */ this.propagationStopped = false; /** @member {bool} */ this.immediatePropagationStopped = false; /** @member {Event} */ this.originalEvent = event; /** @member {Node} */ this.target = event.target; /** @member {string} */ this.type = event.type; } /** * * Wrapper for preventDefault() */ _createClass(DorisEvent, [{ key: "preventDefault", value: function preventDefault() { this.originalEvent.preventDefault(); this.preventedDefault = true; } /** * * Wrapper for stopPropagation() */ }, { key: "stopPropagation", value: function stopPropagation() { this.originalEvent.stopPropagation(); this.propagationStopped = true; } /** * * Wrapper for stopImmediatePropagation() */ }, { key: "stopImmediatePropagation", value: function stopImmediatePropagation() { this.originalEvent.stopImmediatePropagation(); this.immediatePropagationStopped = true; } }]); return DorisEvent; }(); exports.default = DorisEvent; },{}],3:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; /** * * A collection of feature detections required by Doris. */ var _default = { classListAddMultiple: function () { var p = document.createElement('p'); p.classList.add('x1', 'x2'); return p.classList.contains('x2'); }() }; exports.default = _default; },{}],4:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _event = _interopRequireDefault(require("./event")); var _features = _interopRequireDefault(require("./features")); var _utils = _interopRequireDefault(require("./utils")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var EventList = {}; var elementCount = 0; /** * DorisObject is (as the name suggest) a wrapper for all the functionality. * * @type {DorisObject} */ var DorisObject = /*#__PURE__*/ function () { /** * This class should not be instantiated manually but rather by using the * doris() helper. * * @example * let body = doris('body') // A DorisObject with <body> as the only element. * @example * let p = doris('p') // A DorisObject with every <p>-tag in the DOM. * * @param {Array} nodes A list of DOM-nodes to work with. */ function DorisObject(nodes) { var _this = this; _classCallCheck(this, DorisObject); this.elements = Array.from(nodes); this.doris = true; Object.keys(this.elements).forEach(function (i) { if (_this.elements[i].dorisId === undefined) { elementCount += 1; _this.elements[i].dorisId = elementCount; } _this[i] = _this.elements[i]; }); this.length = this.elements.length; } /** * Returns the matched DOM element (zero based index) * * @param {number} index The index for which element should be returned. * @param {boolean} doris If the node should be a DorisObject or a normal Node * @return {(Node|DorisObject|undefined)} */ _createClass(DorisObject, [{ key: "get", value: function get(index) { var doris = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return doris ? new DorisObject([this.elements[index]]) : this.elements[index]; } /** * For each element call callback where this is a new DorisObject of the * matching element. * * @param {function(node: DorisObject, index: number)} callback * @return {DorisObject} */ }, { key: "each", value: function each(callback) { var _this2 = this; Object.keys(this.elements).forEach(function (i) { callback.apply(null, [new DorisObject([_this2.elements[i]]), parseInt(i, 10)]); }); return this; } /** * Check if the first element matches the selector. * * @param {string} selector CSS Selector * @return {boolean} */ }, { key: "matches", value: function matches(selector) { return DorisObject.matchSelector(this.elements[0], selector); } /** * Find matching parent nodes. * If two children has the same parent the parent node will only appear * once in the return value. * If no selector is given the first parent node of each element will be * returned. * * @param {string} [selector] CSS Selector to match, will traverse up the * tree until it's matched. */ }, { key: "parent", value: function parent(selector) { var list = []; Object.values(this.elements).forEach(function (element) { if (selector) { var t = element.parentNode; var match = false; while (t && t.tagName !== 'HTML' && t.tagName !== undefined) { match = DorisObject.matchSelector(t, selector); if (match) { break; } t = t.parentNode; } if (match && list.indexOf(t) < 0) { list.push(t); } } else if (element && element.parentNode && element.parentNode.tagName !== 'HTML' && list.indexOf(element.parentNode) < 0) { list.push(element.parentNode); } }); return new DorisObject(list); } /** * Find matching child nodes. * * @param {string} selector CSS Selector to match. * @return {DorisObject} The matching nodes in a DorisObject. */ }, { key: "find", value: function find(selector) { var list = []; if (selector) { Object.values(this.elements).forEach(function (element) { if (!element.querySelectorAll) { return; } var elements = Array.from(element.querySelectorAll(selector)); Object.keys(elements).forEach(function (e) { if (list.indexOf(elements[e]) === -1) { list.push(elements[e]); } }); }); } return new DorisObject(list); } /** * Prepends nodes in the DOM. * * @param {(Node|string)} dom A Node or string representation of the DOM nodes to * insert. If a Node is used, only a single top level element can be specified! * @return {DorisObject} */ }, { key: "prepend", value: function prepend(dom) { Object.values(this.elements).forEach(function (element) { var nodes = typeof dom === 'string' ? _utils.default.stringToDOM(dom) : [dom]; Object.values(nodes.reverse()).forEach(function (node) { if (element.firstChild) { element.insertBefore(node, element.firstChild); } else { element.appendChild(node); } }); }); return this; } /** * Appends nodes in the DOM. * * @param {(DorisObject|Node|string)} dom A Node or string representation of the DOM nodes to * insert. If a Node is used, only a single top level element can be specified! * @return {DorisObject} */ }, { key: "append", value: function append(dom) { Object.values(this.elements).forEach(function (element) { var nodes; if (typeof dom === 'string') { nodes = _utils.default.stringToDOM(dom); } else if (dom.doris === true) { nodes = dom.elements; } else { // Assume this is a created node nodes = [dom]; } Object.values(nodes).forEach(function (node) { element.appendChild(node); }); }); return this; } /** * Insert DOM element(s) before the elements. * * @param {(Node|string)} dom A Node or string representation of the DOM nodes to * insert. If a Node is used, only a single top level element can be specified! * @return {DorisObject} */ }, { key: "before", value: function before(dom) { Object.values(this.elements).forEach(function (element) { var nodes = typeof dom === 'string' ? _utils.default.stringToDOM(dom) : [dom]; Object.values(nodes).forEach(function (node) { element.parentNode.insertBefore(node, element); }); }); return this; } /** * Insert DOM element(s) after the elements. * * @param {(Node|string)} dom A Node or string representation of the DOM nodes to * insert. If a Node is used, only a single top level element can be specified! * @return {DorisObject} */ }, { key: "after", value: function after(dom) { Object.values(this.elements).forEach(function (element) { var nodes = typeof dom === 'string' ? _utils.default.stringToDOM(dom) : [dom]; Object.values(nodes.reverse()).forEach(function (node) { if (element.nextSibling) { element.parentNode.insertBefore(node, element.nextSibling); } else { element.parentNode.appendChild(node); } }); }); return this; } /** * Returns the next element based on the last element in the collection * * @return {DorisObject|boolean} A DorisObject containing next node or false if there isn't one. */ }, { key: "next", value: function next() { var empty = new DorisObject([]); if (this.elements.length > 0) { var nextSibling = this.elements[this.elements.length - 1].nextElementSibling; return nextSibling ? new DorisObject([nextSibling]) : empty; } return empty; } /** * Returns the previous element based on the first element in the collection * * @return {DorisObject|boolean} A DorisObject containing previous node or * false if there isn't one. */ }, { key: "previous", value: function previous() { var empty = new DorisObject([]); if (this.elements.length > 0) { var previousSibling = this.elements[0].previousElementSibling; return previousSibling ? new DorisObject([previousSibling]) : empty; } return empty; } /** * Removes every element in elements from the DOM and removes the references. * * @return {DorisObject} A DorisObject containing the parent nodes as returned by {@link parent} */ }, { key: "remove", value: function remove() { var _this3 = this; var parent = this.parent(); if (parent.length > 0) { Object.keys(this.elements).forEach(function (i) { _this3.elements[i].parentNode.removeChild(_this3.elements[i]); delete _this3.elements[i]; delete _this3[i]; }); this.length = this.elements.length; return parent; } return new DorisObject([]); } /** * Replaces every element, depending on how many elements are in the collection * the supplied nodes will be cloned. The elements in the original Object * aren't updated, after replacing content you probably want to create a new * doris object that matches on the new content. * * @param {(string|DorisObject)} replacement A string representation of the DOM you want to * use as the replacement or a Doris instance. * @return {DorisObject} A new instance with the replacement elements. */ }, { key: "replace", value: function replace(replacement) { var _this4 = this; var replacementValue = replacement; if (typeof replacementValue === 'string') { replacementValue = window.doris(replacementValue); } var newCollection = []; var m = this.elements.length > 1; Object.keys(this.elements).forEach(function (e) { if (replacementValue.elements.length === 1) { var s = m ? replacementValue.elements[0].cloneNode(true) : replacementValue.elements[0]; _this4.elements[e].parentNode.replaceChild(s, _this4.elements[e]); newCollection.push(s); } else { var previousNode = new DorisObject([_this4.get(e)]); replacementValue.each(function (n) { var s = m ? n.get(0).cloneNode(true) : n.get(0); newCollection.push(s); previousNode.after(s); previousNode = window.doris(s); }); new DorisObject([_this4.get(e)]).remove(); } }); return new DorisObject(newCollection); } /** * Returns a new DorisObject containing a cloned copy of the previous one. * * @param {(boolean)} [deep] If the cloning should be deep or not (shallow) * @return {(DorisObject)} */ }, { key: "clone", value: function clone(deep) { var elements = []; Object.values(this.elements).forEach(function (element) { elements.push(element.cloneNode(deep)); }); Object.keys(elements).forEach(function (i) { elementCount += 1; elements[i].dorisId = elementCount; }); return new DorisObject(elements); } /** * Returns the HTML content of the first element or sets the innerHTML * of every matched element. * * @param {(string|Node)} [html] A string representation of the DOM to use as replacement * or a Node representation that will to converted to markup. * @return {(string|DorisObject)} */ }, { key: "html", value: function html(_html) { var _this5 = this; if (_html === undefined || _html === null) { return this.elements[0].innerHTML; } var newHTML = _html; if (typeof newHTML !== 'string') { newHTML = new DorisObject([newHTML]).toHTML(); } Object.keys(this.elements).forEach(function (e) { _this5.elements[e].innerHTML = newHTML; }); return this; } /** * Returns the textContent of the matching elements or sets the textContent * of the first matching element. * * @param {(string|Node)} [text] Text to set in all matching elements. * @return {(string|DorisObject)} */ }, { key: "text", value: function text(_text) { var _this6 = this; if (_text === undefined) { var content = ''; Object.values(this.elements).forEach(function (element) { content += element.textContent; }); return content; } Object.keys(this.elements).forEach(function (i) { _this6.elements[i].textContent = _text; }); return this; } /** * Adds class(es) to every element. This is using the native classList * implementation. * * @param {...string} classes Names of class(es) * @return {DorisObject} */ }, { key: "addClass", value: function addClass() { var _this7 = this; for (var _len = arguments.length, classes = new Array(_len), _key = 0; _key < _len; _key++) { classes[_key] = arguments[_key]; } Object.keys(this.elements).forEach(function (key) { if (_features.default.classListAddMultiple) { var _this7$elements$key$c; (_this7$elements$key$c = _this7.elements[key].classList).add.apply(_this7$elements$key$c, classes); } else { Object.values(classes).forEach(function (value) { _this7.elements[key].classList.add(classes[value]); }); } }); return this; } /** * Removes class(es) from every element. This is using the native * classList implementation. * * @param {...string} classes Names of class(es) * @return {DorisObject} */ }, { key: "removeClass", value: function removeClass() { for (var _len2 = arguments.length, classes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { classes[_key2] = arguments[_key2]; } Object.values(this.elements).forEach(function (element) { if (_features.default.classListAddMultiple) { var _element$classList; (_element$classList = element.classList).remove.apply(_element$classList, classes); } else { Object.values(classes).forEach(function (c) { element.classList.remove(classes[c]); }); } }); return this; } /** * Checks if class is set on the first element. This is using the native * classList implementation. * * @param {string} klass Name of class * @return {boolean} */ }, { key: "hasClass", value: function hasClass(klass) { if (this.elements[0]) { return this.elements[0].classList.contains(klass); } return false; } /** * Toggles class of every element. This is using the native classList * implementation. * * @param {string} classname Name of class * @return {DorisObject} */ }, { key: "toggleClass", value: function toggleClass(classname) { Object.values(this.elements).forEach(function (element) { element.classList.toggle(classname); }); return this; } /** * Sets attribute to all elements and reads from the first. * * @param {string} name * @param {(string|boolean)} [value] Value to set, if false the attribute will * be deleted, if not specified the key will be read. * @return {(DorisObject|string)} Returns self if value is given, returns the value * of the first element if value isn't given. */ }, { key: "attribute", value: function attribute(name, value) { if (value === undefined) { return this.elements[0].getAttribute(name); } if (value === false) { Object.values(this.elements).forEach(function (element) { element.removeAttribute(name); }); return this; } Object.values(this.elements).forEach(function (element) { element.setAttribute(name, value); }); return this; } /** * Removes attribute from all elements. * * @param {string} attribute */ }, { key: "removeAttribute", value: function removeAttribute(attribute) { Object.values(this.elements).forEach(function (element) { element.removeAttribute(attribute); }); return this; } /** * Set CSS styles, returns the CSS property value of the first element if * no value is specified. * * @param {(string|Object.<string, string>)} style CSS property or a key value * object containing multiple style names and their values. * @param {string} [value] * @return {(DorisObject|string)} */ }, { key: "css", value: function css(style, value) { var _this8 = this; if (value !== undefined && value !== null || _typeof(style) === 'object') { Object.keys(this.elements).forEach(function (i) { if (typeof style === 'string') { _this8.elements[i].style[style] = value; } else { Object.keys(style).forEach(function (s) { _this8.elements[i].style[s] = style[s]; }); } }); return this; } return getComputedStyle(this.elements[0]).getPropertyValue(style); } /** * Width of the first element (the inner height if the first element is * window). * * @return {number} */ }, { key: "width", value: function width() { if (this.elements[0] === window) { return window.innerWidth; } var d = this.elements[0].getBoundingClientRect(); return d.width; } /** * Height of the first element (the inner height if the first element is * window). * * @return {number} */ }, { key: "height", value: function height() { if (this.elements[0] === window) { return window.innerHeight; } var d = this.elements[0].getBoundingClientRect(); return d.height; } /** * Size of the first element via getBoundingClientRect(). * * @return {Object.<string, number>} */ }, { key: "size", value: function size() { return this.elements[0].getBoundingClientRect(); } /** * Returns the offset (from top left) of the first element. * * @property {number} top * @property {number} left * @return {Object} */ }, { key: "offset", value: function offset() { if (this.elements[0] === window) { return { left: 0, top: 0 }; } var e = this.elements[0]; var left = 0; var top = 0; while (e !== null && e.tagName !== 'BODY') { left += e.offsetLeft; top += e.offsetTop; e = e.offsetParent; } return { left: left, top: top }; } /** * Sets data to all elements and reads from the first. * * @param {string} key Key to store or read from (will be automatically * coverted to standards). * @param {string} [value] Value to set, if not specified the key will be * read. * @return {(DorisObject|string)} Returns self if value is given, returns the value * of the first element if value isn't given. */ }, { key: "data", value: function data(key, value) { var _this9 = this; var keyName = key.replace('data-', ''); var dataKey = keyName.replace(/-([a-z])/g, function (match, p1) { if (p1) { return p1.toUpperCase(); } return match; }); if (value) { Object.keys(this.elements).forEach(function (i) { _this9.elements[i].dataset[dataKey] = value; }); return this; } return this.elements[0].dataset[dataKey]; } /** * Binds events on elements, can match on selectors. Callback will receive a DorisEvent * and the target of the bound element, not the element that triggered the event, it will * be available on DorisEvent.nativeEvent.target as usual. * * @param {string} event Name of event. * @param {...(string|function|object)} [args] Selector, Callback and Options arguments * @example * // Bind a click event on all <div> elements * doris('div').on('click', (e, target) => e.preventDefault()) * @example * // Bind a click event on document with a selector (delegation) * doris(document).on('click', '.click-element', (e, target) => { * // target will be the .click-element * }) * @example * // Bind a callback for scrolling but make it passive * doris(document).on('scroll', callback, { passive: true }) * @return {DorisObject} */ }, { key: "on", value: function on(event) { var _this10 = this; for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } var _DorisObject$parseEve = DorisObject.parseEventArguments([event].concat(args)), _DorisObject$parseEve2 = _slicedToArray(_DorisObject$parseEve, 4), parsedEvent = _DorisObject$parseEve2[0], parsedSelector = _DorisObject$parseEve2[1], parsedCallback = _DorisObject$parseEve2[2], parsedOptions = _DorisObject$parseEve2[3]; var options = parsedOptions === undefined ? false : parsedOptions; var caller = function caller(id, e) { var dorisEvent = new _event.default(e); if (!EventList[id].events[dorisEvent.type]) { return; } var parser = function parser(target) { if (dorisEvent.propagationStopped) { return; } Object.keys(EventList[id].events[dorisEvent.type]).forEach(function (i) { if (!dorisEvent.immediatePropagationStopped) { var eventData = EventList[id].events[dorisEvent.type][i]; if (eventData.selector === '*' && target.dorisId === id || eventData.selector !== '*' && DorisObject.matchSelector(target, eventData.selector)) { eventData.callback.call(null, dorisEvent, new DorisObject([target])); if (eventData.callback.one) { _this10.off(dorisEvent.type, eventData.callback.selector, eventData.callback.one, id); } } } }); if (target.dorisId === id || target.parentNode === null) { return; } parser(target.parentNode); }; parser(dorisEvent.target); }; Object.values(this.elements).forEach(function (element) { var id = element.dorisId; if (!EventList[id]) { EventList[id] = { events: {}, call: caller.bind(_this10, id), counts: {} }; } if (!EventList[id].events[parsedEvent]) { EventList[id].events[parsedEvent] = []; EventList[id].counts[parsedEvent] = 0; } EventList[id].events[parsedEvent].push({ selector: parsedSelector, callback: parsedCallback }); EventList[id].counts[parsedEvent] += 1; element.addEventListener(parsedEvent, EventList[id].call, options); }); return this; } /** * Binds an event that will only happen once. * * @see {@link on} * @param {string} event Name of event. * @param {...(string|function|object)} [args] Selector and Callback arguments * @return {DorisObject} */ }, { key: "once", value: function once(event) { for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { args[_key4 - 1] = arguments[_key4]; } var _DorisObject$parseEve3 = DorisObject.parseEventArguments([event].concat(args)), _DorisObject$parseEve4 = _slicedToArray(_DorisObject$parseEve3, 5), parsedEvent = _DorisObject$parseEve4[0], parsedSelector = _DorisObject$parseEve4[1], parsedCallback = _DorisObject$parseEve4[2], parsedOptions = _DorisObject$parseEve4[4]; var options = parsedOptions === undefined ? {} : parsedOptions; var wrappedCallback = function wrappedCallback(e, n) { parsedCallback.call(null, e, n); }; wrappedCallback.one = parsedCallback; wrappedCallback.selector = parsedSelector; this.on(parsedEvent, parsedSelector, wrappedCallback, options); return this; } /** * Unbind events * * @param {string} event name of event. * @param {...(string|function|object)} [args] Selector and Callback arguments * @example * // Removes all click events on body * off('click', 'body') * @example * // Removes all click events with the same callback * off('click', callback) * @example * // Removes all click events for li matching the callback * off('click', 'li', callback) * @return {DorisObject} */ }, { key: "off", value: function off(event) { for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { args[_key5 - 1] = arguments[_key5]; } var _DorisObject$parseEve5 = DorisObject.parseEventArguments([event].concat(args)), _DorisObject$parseEve6 = _slicedToArray(_DorisObject$parseEve5, 5), parsedEvent = _DorisObject$parseEve6[0], parsedSelector = _DorisObject$parseEve6[1], parsedCallback = _DorisObject$parseEve6[2], parsedNode = _DorisObject$parseEve6[4]; Object.values(this.elements).forEach(function (element) { var id = element.dorisId; if (parsedNode === undefined || id === parsedNode) { if (EventList[id].events[parsedEvent]) { var boundEvents = EventList[id].counts[parsedEvent]; Object.keys(EventList[id].events[parsedEvent]).forEach(function (e) { var evt = EventList[id].events[parsedEvent][e]; var selectorMatches = evt.selector === parsedSelector || parsedSelector === '*'; var callbackMatches = false; if (!parsedCallback) { callbackMatches = true; } else if (evt.callback.one && evt.callback.one === parsedCallback) { callbackMatches = true; } else if (parsedCallback === evt.callback) { callbackMatches = true; } if (selectorMatches && callbackMatches) { delete EventList[id].events[parsedEvent][e]; EventList[id].counts[parsedEvent] -= 1; boundEvents -= 1; } }); if (boundEvents === 0) { element.removeEventListener(parsedEvent, EventList[id].call, false); } } } }); return this; } /** * Fires an event * * @param {(string|Event)} event * @return {DorisObject} */ }, { key: "trigger", value: function trigger(event) { var e; if (event === 'click') { // From https://developer.mozilla.org/samples/domref/dispatchEvent.html e = document.createEvent('MouseEvents'); e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); } else { e = document.createEvent('Event'); e.initEvent(event, true, true); } Object.values(this.elements).forEach(function (element) { return element.dispatchEvent(e); }); return this; } /** * Returns a string representation of the elements. * @return {string} */ }, { key: "toHTML", value: function toHTML() { var fragment = document.createDocumentFragment(); fragment.appendChild(document.createElement('body')); Object.values(this.elements).forEach(function (element) { fragment.childNodes[0].appendChild(element); }); return fragment.childNodes[0].innerHTML; } /** * Matches a selector on an element. * @private */ }], [{ key: "matchSelector", value: function matchSelector(element, selector) { if (element === document) { return false; } var f = Element.prototype.matches || Element.prototype.msMatchesSelector; return f ? f.call(element, selector) : false; } /** * Argument parsing for event handling. * @private */ }, { key: "parseEventArguments", value: function parseEventArguments(args) { var event; var callback; var selector = '*'; var node; var options; if (typeof args[1] === 'function') { var _args = _slicedToArray(args, 3); event = _args[0]; callback = _args[1]; options = _args[2]; } else if (typeof args[1] === 'string' && !args[2]) { var _args2 = _slicedToArray(args, 2); event = _args2[0]; selector = _args2[1]; } else if (args[3] || typeof args[2] === 'function') { var _args3 = _slicedToArray(args, 3); event = _args3[0]; selector = _args3[1]; callback = _args3[2]; if (args[3] !== null && _typeof(args[3]) === 'object') { var _args4 = _slicedToArray(args, 5); event = _args4[0]; selector = _args4[1]; callback = _args4[2]; options = _args4[3]; node = _args4[4]; } else if (typeof args[3] === 'number') { var _args5 = _slicedToArray(args, 4); event = _args5[0]; selector = _args5[1]; callback = _args5[2]; node = _args5[3]; } } else { var _args6 = _slicedToArray(args, 1); event = _args6[0]; } selector = !selector ? '*' : selector; return [event, selector, callback, options, node]; } }]); return DorisObject; }(); exports.default = DorisObject; },{"./event":2,"./features":3,"./utils":5}],5:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; /** * * Converts a string to DOM nodes. * @param {string} string A string representation of the DOM. * @return {Array<Node>} */ var _default = { stringToDOM: function stringToDOM(string) { var fragment = document.createDocumentFragment(); fragment.appendChild(document.createElement('body')); fragment.childNodes[0].innerHTML = string; return Array.from(fragment.childNodes[0].childNodes); } }; exports.default = _default; },{}]},{},[1]);
/** * Created by Vahid on 09/06/15. */ /* * * A class holding a small list of unisex names (so they can fit any avatar) * * */ services.factory('nameGenerator', function () { // Keeping 20 unisex names to suite the avatars var nameGenerator = function () { this.names = ['Addison', 'Ash', 'Bailey', 'Bobbie', 'Brett', 'Brook', 'Charlie', 'Daryl', 'Frankie', 'Gray', 'Hayden', 'Morgan', 'Rudy', 'Taylor', 'Alex', 'West', 'Shannon', 'Ashley', 'Billy', 'Robin']; }; //Giving a new name each time. nameGenerator.prototype.generateName = function () { var self = this; if (self.names.length) { var index = Math.floor(Math.random() * self.names.length); var item = self.names[index]; self.names.splice(index, 1); return item; } return 'Dude' }; return nameGenerator; });
/* * Copyright (C) 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ WebInspector.HoverMenu = function (delegate) { WebInspector.Object.call(this); this.delegate = delegate; this._element = document.createElement("div"); this._element.className = WebInspector.HoverMenu.StyleClassName; this._element.addEventListener("transitionend", this, true); this._outlineElement = this._element.appendChild(document.createElementNS("http://www.w3.org/2000/svg", "svg")); this._button = this._element.appendChild(document.createElement("img")); this._button.addEventListener("click", this); }; WebInspector.HoverMenu.StyleClassName = "hover-menu"; WebInspector.HoverMenu.VisibleClassName = "visible"; WebInspector.HoverMenu.prototype = Object.defineProperties({ constructor: WebInspector.HoverMenu, __proto__: WebInspector.Object.prototype, present: function present(rects) { this._outlineElement.textContent = ""; document.body.appendChild(this._element); this._drawOutline(rects); this._element.classList.add(WebInspector.HoverMenu.VisibleClassName); window.addEventListener("scroll", this, true); }, dismiss: function dismiss(discrete) { if (this._element.parentNode !== document.body) return; if (discrete) this._element.remove(); this._element.classList.remove(WebInspector.HoverMenu.VisibleClassName); window.removeEventListener("scroll", this, true); }, // Protected handleEvent: function handleEvent(event) { switch (event.type) { case "scroll": if (!this._element.contains(event.target)) this.dismiss(true); break; case "click": this._handleClickEvent(event); break; case "transitionend": if (!this._element.classList.contains(WebInspector.HoverMenu.VisibleClassName)) this._element.remove(); break; } }, // Private _handleClickEvent: function _handleClickEvent(event) { if (this.delegate && typeof this.delegate.hoverMenuButtonWasPressed === "function") this.delegate.hoverMenuButtonWasPressed(this); }, _drawOutline: function _drawOutline(rects) { var buttonWidth = this._button.width; var buttonHeight = this._button.height; // Add room for the button on the last line. var lastRect = rects.pop(); lastRect.size.width += buttonWidth; rects.push(lastRect); if (rects.length === 1) this._drawSingleLine(rects[0]);else if (rects.length === 2 && rects[0].minX() >= rects[1].maxX()) this._drawTwoNonOverlappingLines(rects);else this._drawOverlappingLines(rects); var bounds = WebInspector.Rect.unionOfRects(rects).pad(3); // padding + 1/2 stroke-width var style = this._element.style; style.left = bounds.minX() + "px"; style.top = bounds.minY() + "px"; style.width = bounds.size.width + "px"; style.height = bounds.size.height + "px"; this._outlineElement.style.width = bounds.size.width + "px"; this._outlineElement.style.height = bounds.size.height + "px"; this._button.style.left = lastRect.maxX() - bounds.minX() - buttonWidth + "px"; this._button.style.top = lastRect.maxY() - bounds.minY() - buttonHeight + "px"; }, _addRect: function _addRect(rect) { var r = 4; var svgRect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); svgRect.setAttribute("x", 1); svgRect.setAttribute("y", 1); svgRect.setAttribute("width", rect.size.width); svgRect.setAttribute("height", rect.size.height); svgRect.setAttribute("rx", r); svgRect.setAttribute("ry", r); return this._outlineElement.appendChild(svgRect); }, _addPath: function _addPath(commands, tx, ty) { var path = document.createElementNS("http://www.w3.org/2000/svg", "path"); path.setAttribute("d", commands.join(" ")); path.setAttribute("transform", "translate(" + (tx + 1) + "," + (ty + 1) + ")"); return this._outlineElement.appendChild(path); }, _drawSingleLine: function _drawSingleLine(rect) { this._addRect(rect.pad(2)); }, _drawTwoNonOverlappingLines: function _drawTwoNonOverlappingLines(rects) { var r = 4; var firstRect = rects[0].pad(2); var secondRect = rects[1].pad(2); var tx = -secondRect.minX(); var ty = -firstRect.minY(); var rect = firstRect; this._addPath(["M", rect.maxX(), rect.minY(), "H", rect.minX() + r, "q", -r, 0, -r, r, "V", rect.maxY() - r, "q", 0, r, r, r, "H", rect.maxX()], tx, ty); rect = secondRect; this._addPath(["M", rect.minX(), rect.minY(), "H", rect.maxX() - r, "q", r, 0, r, r, "V", rect.maxY() - r, "q", 0, r, -r, r, "H", rect.minX()], tx, ty); }, _drawOverlappingLines: function _drawOverlappingLines(rects) { var PADDING = 2; var r = 4; var minX = Number.MAX_VALUE; var maxX = -Number.MAX_VALUE; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = rects[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var rect = _step.value; var minX = Math.min(rect.minX(), minX); var maxX = Math.max(rect.maxX(), maxX); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"]) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } minX -= PADDING; maxX += PADDING; var minY = rects[0].minY() - PADDING; var maxY = rects.lastValue.maxY() + PADDING; var firstLineMinX = rects[0].minX() - PADDING; var lastLineMaxX = rects.lastValue.maxX() + PADDING; if (firstLineMinX === minX && lastLineMaxX === maxX) return this._addRect(new WebInspector.Rect(minX, minY, maxX - minX, maxY - minY)); var lastLineMinY = rects.lastValue.minY() + PADDING; if (rects[0].minX() === minX + PADDING) return this._addPath(["M", minX + r, minY, "H", maxX - r, "q", r, 0, r, r, "V", lastLineMinY - r, "q", 0, r, -r, r, "H", lastLineMaxX + r, "q", -r, 0, -r, r, "V", maxY - r, "q", 0, r, -r, r, "H", minX + r, "q", -r, 0, -r, -r, "V", minY + r, "q", 0, -r, r, -r], -minX, -minY); var firstLineMaxY = rects[0].maxY() - PADDING; if (rects.lastValue.maxX() === maxX - PADDING) return this._addPath(["M", firstLineMinX + r, minY, "H", maxX - r, "q", r, 0, r, r, "V", maxY - r, "q", 0, r, -r, r, "H", minX + r, "q", -r, 0, -r, -r, "V", firstLineMaxY + r, "q", 0, -r, r, -r, "H", firstLineMinX - r, "q", r, 0, r, -r, "V", minY + r, "q", 0, -r, r, -r], -minX, -minY); return this._addPath(["M", firstLineMinX + r, minY, "H", maxX - r, "q", r, 0, r, r, "V", lastLineMinY - r, "q", 0, r, -r, r, "H", lastLineMaxX + r, "q", -r, 0, -r, r, "V", maxY - r, "q", 0, r, -r, r, "H", minX + r, "q", -r, 0, -r, -r, "V", firstLineMaxY + r, "q", 0, -r, r, -r, "H", firstLineMinX - r, "q", r, 0, r, -r, "V", minY + r, "q", 0, -r, r, -r], -minX, -minY); } }, { element: { // Public get: function get() { return this._element; }, configurable: true, enumerable: true } });
version https://git-lfs.github.com/spec/v1 oid sha256:06e5791ea6422573abd377d4d24d3aae58d3cec1e81a860458938ceddbd7a982 size 408272
define(["amber/boot", "amber_core/Kernel-Objects", "amber_core/SUnit"], function($boot){"use strict"; if(!$boot.nilAsReceiver)$boot.nilAsReceiver=$boot.nil; if(!("nilAsValue" in $boot))$boot.nilAsValue=$boot.nilAsReceiver; var $core=$boot.api,nil=$boot.nilAsValue,$nil=$boot.nilAsReceiver,$recv=$boot.asReceiver,$globals=$boot.globals; if(!$boot.nilAsClass)$boot.nilAsClass=$boot.dnu; $core.addPackage("OndafSimulator-Core-Tests"); $core.packages["OndafSimulator-Core-Tests"].innerEval = function (expr) { return eval(expr); }; $core.packages["OndafSimulator-Core-Tests"].transport = {"type":"amd","amdNamespace":"amber-ondafsimulator"}; $core.addClass("ExamCreator", $globals.Object, [], "OndafSimulator-Core-Tests"); $core.addMethod( $core.method({ selector: "examWithText:", protocol: "as yet unclassified", fn: function (text1){ var self=this,$self=this; var examDesigner; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); examDesigner=$recv($globals.ExamDesigner)._new(); $recv(examDesigner)._considerText_(text1); return $recv(examDesigner)._designExam(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"examWithText:",{text1:text1,examDesigner:examDesigner},$globals.ExamCreator)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["text1"], source: "examWithText: text1\x0a\x09| examDesigner |\x0a\x09examDesigner := ExamDesigner new.\x0a\x09examDesigner considerText: text1.\x0a\x09^ examDesigner designExam.", referencedClasses: ["ExamDesigner"], //>>excludeEnd("ide"); messageSends: ["new", "considerText:", "designExam"] }), $globals.ExamCreator); $core.addMethod( $core.method({ selector: "examWithText:and:", protocol: "as yet unclassified", fn: function (text1,text2){ var self=this,$self=this; var examDesigner; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); examDesigner=$recv($globals.ExamDesigner)._new(); $recv(examDesigner)._considerText_(text1); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["considerText:"]=1; //>>excludeEnd("ctx"); $recv(examDesigner)._considerText_(text2); return $recv(examDesigner)._designExam(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"examWithText:and:",{text1:text1,text2:text2,examDesigner:examDesigner},$globals.ExamCreator)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["text1", "text2"], source: "examWithText: text1 and: text2 \x0a\x09| examDesigner |\x0a\x09examDesigner := ExamDesigner new.\x0a\x09examDesigner considerText: text1.\x0a\x09examDesigner considerText: text2.\x0a\x09^ examDesigner designExam.", referencedClasses: ["ExamDesigner"], //>>excludeEnd("ide"); messageSends: ["new", "considerText:", "designExam"] }), $globals.ExamCreator); $core.addClass("ExamDesignerTest", $globals.TestCase, ["theExamDesigner"], "OndafSimulator-Core-Tests"); $core.addMethod( $core.method({ selector: "setUp", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self["@theExamDesigner"]=$recv($globals.ExamDesigner)._new(); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"setUp",{},$globals.ExamDesignerTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "setUp\x0a\x09theExamDesigner := ExamDesigner new.", referencedClasses: ["ExamDesigner"], //>>excludeEnd("ide"); messageSends: ["new"] }), $globals.ExamDesignerTest); $core.addMethod( $core.method({ selector: "test01DesignExamWithOneText", protocol: "tests", fn: function (){ var self=this,$self=this; var anExam; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$2; $1=$self["@theExamDesigner"]; $2=$recv("Title".__comma($recv($globals.String)._lf())).__comma("Content"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $recv($1)._considerText_($2); anExam=$recv($self["@theExamDesigner"])._designExam(); $self._assert_equals_($recv(anExam)._numberOfTexts(),(1)); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test01DesignExamWithOneText",{anExam:anExam},$globals.ExamDesignerTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test01DesignExamWithOneText\x0a\x09| anExam |\x0a\x09theExamDesigner considerText: 'Title', String lf, 'Content'.\x0a\x09anExam := theExamDesigner designExam.\x0a\x09self assert: anExam numberOfTexts equals: 1.", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["considerText:", ",", "lf", "designExam", "assert:equals:", "numberOfTexts"] }), $globals.ExamDesignerTest); $core.addMethod( $core.method({ selector: "test02DesignExamWithMultipleTexts", protocol: "tests", fn: function (){ var self=this,$self=this; var anExam; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$4,$3,$2,$5,$6; $1=$self["@theExamDesigner"]; $4=$recv($globals.String)._lf(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["lf"]=1; //>>excludeEnd("ctx"); $3="Title A".__comma($4); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=2; //>>excludeEnd("ctx"); $2=$recv($3).__comma("Content 1"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $recv($1)._considerText_($2); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["considerText:"]=1; //>>excludeEnd("ctx"); $5=$self["@theExamDesigner"]; $6=$recv("Title B".__comma($recv($globals.String)._lf())).__comma("Content 2"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=3; //>>excludeEnd("ctx"); $recv($5)._considerText_($6); anExam=$recv($self["@theExamDesigner"])._designExam(); $self._assert_equals_($recv(anExam)._numberOfTexts(),(2)); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test02DesignExamWithMultipleTexts",{anExam:anExam},$globals.ExamDesignerTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test02DesignExamWithMultipleTexts\x0a\x09| anExam |\x0a\x09theExamDesigner considerText: 'Title A', String lf, 'Content 1'.\x0a\x09theExamDesigner considerText: 'Title B', String lf, 'Content 2'.\x0a\x09anExam := theExamDesigner designExam.\x0a\x09self assert: anExam numberOfTexts equals: 2.", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["considerText:", ",", "lf", "designExam", "assert:equals:", "numberOfTexts"] }), $globals.ExamDesignerTest); $core.addMethod( $core.method({ selector: "test03InformTheTextTitlesAsTheyAreConsidered", protocol: "tests", fn: function (){ var self=this,$self=this; var titles; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$4,$3,$2,$5,$6; titles=$recv($globals.OrderedCollection)._new(); $recv($self["@theExamDesigner"])._informProgressTo_((function(title){ //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx2) { //>>excludeEnd("ctx"); return $recv(titles)._add_(title); //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx2) {$ctx2.fillBlock({title:title},$ctx1,1)}); //>>excludeEnd("ctx"); })); $1=$self["@theExamDesigner"]; $4=$recv($globals.String)._lf(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["lf"]=1; //>>excludeEnd("ctx"); $3="Title A".__comma($4); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=2; //>>excludeEnd("ctx"); $2=$recv($3).__comma("Content 1"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $recv($1)._considerText_($2); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["considerText:"]=1; //>>excludeEnd("ctx"); $5=$self["@theExamDesigner"]; $6=$recv("Title B".__comma($recv($globals.String)._lf())).__comma("Content 2"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=3; //>>excludeEnd("ctx"); $recv($5)._considerText_($6); $self._assert_equals_($recv(titles)._asArray(),["Title A", "Title B"]); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test03InformTheTextTitlesAsTheyAreConsidered",{titles:titles},$globals.ExamDesignerTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test03InformTheTextTitlesAsTheyAreConsidered\x0a\x09| titles |\x0a\x09titles := OrderedCollection new.\x0a\x09\x0a\x09theExamDesigner informProgressTo: [ :title | titles add: title ].\x0a\x09theExamDesigner considerText: 'Title A', String lf, 'Content 1'.\x0a\x09theExamDesigner considerText: 'Title B', String lf, 'Content 2'.\x0a\x09\x0a\x09self assert: titles asArray equals: #('Title A' 'Title B').", referencedClasses: ["OrderedCollection", "String"], //>>excludeEnd("ide"); messageSends: ["new", "informProgressTo:", "add:", "considerText:", ",", "lf", "assert:equals:", "asArray"] }), $globals.ExamDesignerTest); $core.addClass("ExamPrinterTest", $globals.TestCase, ["examCreator", "theExam", "printer", "copies"], "OndafSimulator-Core-Tests"); $core.addMethod( $core.method({ selector: "givenExamWithText:", protocol: "given", fn: function (text1){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self["@theExam"]=$recv($self["@examCreator"])._examWithText_(text1); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"givenExamWithText:",{text1:text1},$globals.ExamPrinterTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["text1"], source: "givenExamWithText: text1\x0a\x09theExam := examCreator examWithText: text1", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["examWithText:"] }), $globals.ExamPrinterTest); $core.addMethod( $core.method({ selector: "givenExamWithText:and:", protocol: "given", fn: function (text1,text2){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self["@theExam"]=$recv($self["@examCreator"])._examWithText_and_(text1,text2); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"givenExamWithText:and:",{text1:text1,text2:text2},$globals.ExamPrinterTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["text1", "text2"], source: "givenExamWithText: text1 and: text2 \x0a\x09theExam := examCreator examWithText: text1 and: text2", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["examWithText:and:"] }), $globals.ExamPrinterTest); $core.addMethod( $core.method({ selector: "printedText", protocol: "private", fn: function (){ var self=this,$self=this; var allText; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $2,$1; allText=$recv($recv($self["@copies"])._collect_("printedText"))._reduce_((function(a,b){ //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx2) { //>>excludeEnd("ctx"); return $recv(a).__comma(b); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx2.sendIdx[","]=1; //>>excludeEnd("ctx"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx2) {$ctx2.fillBlock({a:a,b:b},$ctx1,1)}); //>>excludeEnd("ctx"); })); $2=$recv("Texts: ".__comma($recv($recv($self["@copies"])._size())._asString())).__comma(" "); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=3; //>>excludeEnd("ctx"); $1=$recv($2).__comma(allText); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=2; //>>excludeEnd("ctx"); return $1; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"printedText",{allText:allText},$globals.ExamPrinterTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "printedText\x0a\x09| allText |\x0a\x09allText := (copies collect: #printedText) reduce: [ :a :b | a, b ].\x0a\x09^ 'Texts: ', copies size asString, ' ', allText.", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["reduce:", "collect:", ",", "asString", "size"] }), $globals.ExamPrinterTest); $core.addMethod( $core.method({ selector: "setUp", protocol: "running", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self["@examCreator"]=$recv($globals.ExamCreator)._new(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["new"]=1; //>>excludeEnd("ctx"); $self["@printer"]=$recv($globals.CTestPrinter)._newWithTray_($recv($globals.TestTray)._new()); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"setUp",{},$globals.ExamPrinterTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "setUp\x0a\x09examCreator := ExamCreator new.\x0a\x09printer := CTestPrinter newWithTray: TestTray new", referencedClasses: ["ExamCreator", "CTestPrinter", "TestTray"], //>>excludeEnd("ide"); messageSends: ["new", "newWithTray:"] }), $globals.ExamPrinterTest); $core.addMethod( $core.method({ selector: "test01CopyExamOnPrinter", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$recv("Title A".__comma($recv($globals.String)._lf())).__comma("And the text said: he{llo} wor{ld}."); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $self._givenExamWithText_($1); $self["@copies"]=$recv($self["@printer"])._print_($self["@theExam"]); $self._assert_equals_($recv($self["@copies"])._size(),(1)); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($self._printedText(),"Texts: 1 |Title A (30s)| And the text said: he_ wor_ . "); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test01CopyExamOnPrinter",{},$globals.ExamPrinterTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test01CopyExamOnPrinter\x0a\x09self givenExamWithText: 'Title A', String lf, 'And the text said: he{llo} wor{ld}.'.\x0a\x09\x0a\x09copies := printer print: theExam.\x0a\x09\x0a\x09self assert: copies size equals: 1.\x0a\x09self assert: self printedText equals: 'Texts: 1 |Title A (30s)| And the text said: he_ wor_ . '.", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["givenExamWithText:", ",", "lf", "print:", "assert:equals:", "size", "printedText"] }), $globals.ExamPrinterTest); $core.addMethod( $core.method({ selector: "test02CopyExamWithMultipleTexts", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $3,$2,$1,$4; $3=$recv($globals.String)._lf(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["lf"]=1; //>>excludeEnd("ctx"); $2="Title A".__comma($3); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=2; //>>excludeEnd("ctx"); $1=$recv($2).__comma("he{llo} wor{ld}"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $4=$recv("Title B".__comma($recv($globals.String)._lf())).__comma("loca{tion}"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=3; //>>excludeEnd("ctx"); $self._givenExamWithText_and_($1,$4); $self["@copies"]=$recv($self["@printer"])._print_($self["@theExam"]); $self._assert_equals_($self._printedText(),"Texts: 2 |Title A (30s)| he_ wor_ |Title B (15s)| loca_ "); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test02CopyExamWithMultipleTexts",{},$globals.ExamPrinterTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test02CopyExamWithMultipleTexts\x0a\x09self givenExamWithText: 'Title A', String lf, 'he{llo} wor{ld}'\x0a\x09 and: 'Title B', String lf, 'loca{tion}'.\x0a\x09\x0a\x09copies := printer print: theExam.\x0a\x09\x0a\x09self assert: self printedText equals: 'Texts: 2 |Title A (30s)| he_ wor_ |Title B (15s)| loca_ '.", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["givenExamWithText:and:", ",", "lf", "print:", "assert:equals:", "printedText"] }), $globals.ExamPrinterTest); $core.addClass("ExamTest", $globals.TestCase, ["theExam", "examCreator"], "OndafSimulator-Core-Tests"); $core.addMethod( $core.method({ selector: "givenExamWithText:", protocol: "given", fn: function (text1){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self["@theExam"]=$recv($self["@examCreator"])._examWithText_(text1); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"givenExamWithText:",{text1:text1},$globals.ExamTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["text1"], source: "givenExamWithText: text1\x0a\x09theExam := examCreator examWithText: text1", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["examWithText:"] }), $globals.ExamTest); $core.addMethod( $core.method({ selector: "givenExamWithText:and:", protocol: "given", fn: function (text1,text2){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self["@theExam"]=$recv($self["@examCreator"])._examWithText_and_(text1,text2); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"givenExamWithText:and:",{text1:text1,text2:text2},$globals.ExamTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["text1", "text2"], source: "givenExamWithText: text1 and: text2 \x0a\x09theExam := examCreator examWithText: text1 and: text2", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["examWithText:and:"] }), $globals.ExamTest); $core.addMethod( $core.method({ selector: "setUp", protocol: "running", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self["@examCreator"]=$recv($globals.ExamCreator)._new(); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"setUp",{},$globals.ExamTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "setUp\x0a\x09examCreator := ExamCreator new.", referencedClasses: ["ExamCreator"], //>>excludeEnd("ide"); messageSends: ["new"] }), $globals.ExamTest); $core.addMethod( $core.method({ selector: "test01EvaluateACorrectSubmission", protocol: "tests", fn: function (){ var self=this,$self=this; var aSubmission,aResult; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$recv("Title A".__comma($recv($globals.String)._lf())).__comma("And the text said: he{llo} wor{ld}."); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $self._givenExamWithText_($1); aSubmission=["llo", "ld"]; aResult=$recv($self["@theExam"])._evaluate_(aSubmission); $self._assert_equals_($recv(aResult)._individualResults(),[true, true]); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test01EvaluateACorrectSubmission",{aSubmission:aSubmission,aResult:aResult},$globals.ExamTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test01EvaluateACorrectSubmission\x0a\x09| aSubmission aResult |\x0a\x09self givenExamWithText: 'Title A', String lf, 'And the text said: he{llo} wor{ld}.'.\x0a\x09\x0a\x09aSubmission := #('llo' 'ld').\x0a\x09aResult := theExam evaluate: aSubmission.\x0a\x09\x0a\x09self assert: aResult individualResults equals: #(true true).", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["givenExamWithText:", ",", "lf", "evaluate:", "assert:equals:", "individualResults"] }), $globals.ExamTest); $core.addMethod( $core.method({ selector: "test02EvaluateAnIncorrectSubmission", protocol: "tests", fn: function (){ var self=this,$self=this; var aSubmission,aResult; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$recv("Title A".__comma($recv($globals.String)._lf())).__comma("And the text said: he{llo} wor{ld}."); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $self._givenExamWithText_($1); aSubmission=["wrong", "answer"]; aResult=$recv($self["@theExam"])._evaluate_(aSubmission); $self._assert_equals_($recv(aResult)._individualResults(),[false, false]); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test02EvaluateAnIncorrectSubmission",{aSubmission:aSubmission,aResult:aResult},$globals.ExamTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test02EvaluateAnIncorrectSubmission\x0a\x09| aSubmission aResult |\x0a\x09self givenExamWithText: 'Title A', String lf, 'And the text said: he{llo} wor{ld}.'.\x0a\x09\x0a\x09aSubmission := #('wrong' 'answer').\x0a\x09aResult := theExam evaluate: aSubmission.\x0a\x09\x0a\x09self assert: aResult individualResults equals: #(false false).", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["givenExamWithText:", ",", "lf", "evaluate:", "assert:equals:", "individualResults"] }), $globals.ExamTest); $core.addMethod( $core.method({ selector: "test03EvaluateAMixedSubmission1", protocol: "tests", fn: function (){ var self=this,$self=this; var aSubmission,aResult; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$recv("Title A".__comma($recv($globals.String)._lf())).__comma("And the text said: he{llo} wor{ld}."); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $self._givenExamWithText_($1); aSubmission=["llo"]; aResult=$recv($self["@theExam"])._evaluate_(aSubmission); $self._assert_equals_($recv(aResult)._individualResults(),[true, false]); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test03EvaluateAMixedSubmission1",{aSubmission:aSubmission,aResult:aResult},$globals.ExamTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test03EvaluateAMixedSubmission1\x0a\x09| aSubmission aResult |\x0a\x09self givenExamWithText: 'Title A', String lf, 'And the text said: he{llo} wor{ld}.'.\x0a\x09\x0a\x09aSubmission := #('llo').\x0a\x09aResult := theExam evaluate: aSubmission.\x0a\x09\x0a\x09self assert: aResult individualResults equals: #(true false).", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["givenExamWithText:", ",", "lf", "evaluate:", "assert:equals:", "individualResults"] }), $globals.ExamTest); $core.addMethod( $core.method({ selector: "test04EvaluateAMixedSubmission2", protocol: "tests", fn: function (){ var self=this,$self=this; var aSubmission,aResult; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$recv("Title A".__comma($recv($globals.String)._lf())).__comma("And the text said: he{llo} wor{ld}."); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $self._givenExamWithText_($1); aSubmission=["wrong", "ld"]; aResult=$recv($self["@theExam"])._evaluate_(aSubmission); $self._assert_equals_($recv(aResult)._individualResults(),[false, true]); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test04EvaluateAMixedSubmission2",{aSubmission:aSubmission,aResult:aResult},$globals.ExamTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test04EvaluateAMixedSubmission2\x0a\x09| aSubmission aResult |\x0a\x09self givenExamWithText: 'Title A', String lf, 'And the text said: he{llo} wor{ld}.'.\x0a\x09\x0a\x09aSubmission := #('wrong' 'ld').\x0a\x09aResult := theExam evaluate: aSubmission.\x0a\x09\x0a\x09self assert: aResult individualResults equals: #(false true).", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["givenExamWithText:", ",", "lf", "evaluate:", "assert:equals:", "individualResults"] }), $globals.ExamTest); $core.addMethod( $core.method({ selector: "test05EvaluateTheSubmissionOfMultipleTexts", protocol: "tests", fn: function (){ var self=this,$self=this; var aSubmission,aResult; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $3,$2,$1,$4; $3=$recv($globals.String)._lf(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["lf"]=1; //>>excludeEnd("ctx"); $2="Title A".__comma($3); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=2; //>>excludeEnd("ctx"); $1=$recv($2).__comma("he{llo} wor{ld}"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $4=$recv("Title B".__comma($recv($globals.String)._lf())).__comma("loca{tion}"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=3; //>>excludeEnd("ctx"); $self._givenExamWithText_and_($1,$4); aSubmission=["llo", "ld", "tion"]; aResult=$recv($self["@theExam"])._evaluate_(aSubmission); $self._assert_equals_($recv(aResult)._individualResults(),[true, true, true]); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test05EvaluateTheSubmissionOfMultipleTexts",{aSubmission:aSubmission,aResult:aResult},$globals.ExamTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test05EvaluateTheSubmissionOfMultipleTexts\x0a\x09| aSubmission aResult |\x0a\x09self givenExamWithText: 'Title A', String lf, 'he{llo} wor{ld}'\x0a\x09 and: 'Title B', String lf, 'loca{tion}'.\x0a\x09\x0a\x09aSubmission := #('llo' 'ld' 'tion').\x0a\x09aResult := theExam evaluate: aSubmission.\x0a\x09\x0a\x09self assert: aResult individualResults equals: #(true true true).", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["givenExamWithText:and:", ",", "lf", "evaluate:", "assert:equals:", "individualResults"] }), $globals.ExamTest); $core.addMethod( $core.method({ selector: "test06CalculatePercentage", protocol: "tests", fn: function (){ var self=this,$self=this; var aSubmission,aResult; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$recv("Title A".__comma($recv($globals.String)._lf())).__comma("And the text said: he{llo} wor{ld}."); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $self._givenExamWithText_($1); aSubmission=["wrong", "ld"]; aResult=$recv($self["@theExam"])._evaluate_(aSubmission); $self._assert_equals_($recv(aResult)._percentage(),(50)); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test06CalculatePercentage",{aSubmission:aSubmission,aResult:aResult},$globals.ExamTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test06CalculatePercentage\x0a\x09| aSubmission aResult |\x0a\x09self givenExamWithText: 'Title A', String lf, 'And the text said: he{llo} wor{ld}.'.\x0a\x09\x0a\x09aSubmission := #('wrong' 'ld').\x0a\x09aResult := theExam evaluate: aSubmission.\x0a\x09\x0a\x09self assert: aResult percentage equals: 50.", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["givenExamWithText:", ",", "lf", "evaluate:", "assert:equals:", "percentage"] }), $globals.ExamTest); $core.addMethod( $core.method({ selector: "test07RoundPercentageToTwoDecimals", protocol: "tests", fn: function (){ var self=this,$self=this; var aSubmission,aResult; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$recv("Title A".__comma($recv($globals.String)._lf())).__comma("And the text said: he{llo} wor{ld}. Cor{rect}"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $self._givenExamWithText_($1); aSubmission=["wrong", "ld", "rect"]; aResult=$recv($self["@theExam"])._evaluate_(aSubmission); $self._assert_equals_($recv(aResult)._percentage(),(66.67)); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test07RoundPercentageToTwoDecimals",{aSubmission:aSubmission,aResult:aResult},$globals.ExamTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test07RoundPercentageToTwoDecimals\x0a\x09| aSubmission aResult |\x0a\x09self givenExamWithText: 'Title A', String lf, 'And the text said: he{llo} wor{ld}. Cor{rect}'.\x0a\x09\x0a\x09aSubmission := #('wrong' 'ld' 'rect').\x0a\x09aResult := theExam evaluate: aSubmission.\x0a\x09\x0a\x09self assert: aResult percentage equals: 66.67.", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["givenExamWithText:", ",", "lf", "evaluate:", "assert:equals:", "percentage"] }), $globals.ExamTest); $core.addMethod( $core.method({ selector: "test08DetermineLevelForSubmission", protocol: "tests", fn: function (){ var self=this,$self=this; var aSubmission,aResult; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$recv("Title A".__comma($recv($globals.String)._lf())).__comma("And the text said: he{llo} wor{ld}. Cor{rect}"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $self._givenExamWithText_($1); aSubmission=["wrong", "ld", "rect"]; aResult=$recv($self["@theExam"])._evaluate_(aSubmission); $self._assert_equals_($recv(aResult)._level(),"B1"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test08DetermineLevelForSubmission",{aSubmission:aSubmission,aResult:aResult},$globals.ExamTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test08DetermineLevelForSubmission\x0a\x09| aSubmission aResult |\x0a\x09self givenExamWithText: 'Title A', String lf, 'And the text said: he{llo} wor{ld}. Cor{rect}'.\x0a\x09\x0a\x09aSubmission := #('wrong' 'ld' 'rect').\x0a\x09aResult := theExam evaluate: aSubmission.\x0a\x09\x0a\x09self assert: aResult level equals: 'B1'.", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["givenExamWithText:", ",", "lf", "evaluate:", "assert:equals:", "level"] }), $globals.ExamTest); $core.addMethod( $core.method({ selector: "test09DetermineScore", protocol: "tests", fn: function (){ var self=this,$self=this; var aSubmission,aResult; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$recv("Title A".__comma($recv($globals.String)._lf())).__comma("And the text said: he{llo} wor{ld}. Cor{rect}"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $self._givenExamWithText_($1); aSubmission=["wrong", "ld", "rect"]; aResult=$recv($self["@theExam"])._evaluate_(aSubmission); $self._assert_equals_($recv(aResult)._score(),(2)); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test09DetermineScore",{aSubmission:aSubmission,aResult:aResult},$globals.ExamTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test09DetermineScore\x0a\x09| aSubmission aResult |\x0a\x09self givenExamWithText: 'Title A', String lf, 'And the text said: he{llo} wor{ld}. Cor{rect}'.\x0a\x09\x0a\x09aSubmission := #('wrong' 'ld' 'rect').\x0a\x09aResult := theExam evaluate: aSubmission.\x0a\x09\x0a\x09self assert: aResult score equals: 2.", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["givenExamWithText:", ",", "lf", "evaluate:", "assert:equals:", "score"] }), $globals.ExamTest); $core.addMethod( $core.method({ selector: "test10DetermineMaximumScore", protocol: "tests", fn: function (){ var self=this,$self=this; var aSubmission,aResult; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$recv("Title A".__comma($recv($globals.String)._lf())).__comma("And the text said: he{llo} wor{ld}. Cor{rect}"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $self._givenExamWithText_($1); aSubmission=["wrong", "ld", "rect"]; aResult=$recv($self["@theExam"])._evaluate_(aSubmission); $self._assert_equals_($recv(aResult)._maxScore(),(3)); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test10DetermineMaximumScore",{aSubmission:aSubmission,aResult:aResult},$globals.ExamTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test10DetermineMaximumScore\x0a\x09| aSubmission aResult |\x0a\x09self givenExamWithText: 'Title A', String lf, 'And the text said: he{llo} wor{ld}. Cor{rect}'.\x0a\x09\x0a\x09aSubmission := #('wrong' 'ld' 'rect').\x0a\x09aResult := theExam evaluate: aSubmission.\x0a\x09\x0a\x09self assert: aResult maxScore equals: 3.", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["givenExamWithText:", ",", "lf", "evaluate:", "assert:equals:", "maxScore"] }), $globals.ExamTest); $core.addMethod( $core.method({ selector: "test11", protocol: "tests", fn: function (){ var self=this,$self=this; var spySubmissions,spyView,aResult; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$recv("Title A".__comma($recv($globals.String)._lf())).__comma("And the text said: he{llo} wor{ld}. Cor{rect}"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $self._givenExamWithText_($1); spySubmissions=$recv($globals.Array)._with_($recv($globals.SpySubmission)._newWith_(["wrong", "ld", "rect"])); spyView=$recv($globals.SpyResultsView)._new(); aResult=$recv($self["@theExam"])._evaluate_on_(spySubmissions,spyView); $recv(aResult)._giveToStudent(); $self._assert_equals_($recv(spyView)._score(),(2)); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv(spyView)._totalScore(),(3)); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=2; //>>excludeEnd("ctx"); $self._assert_equals_($recv(spyView)._percentage(),(66.67)); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=3; //>>excludeEnd("ctx"); $self._assert_equals_($recv(spyView)._level(),"B1"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=4; //>>excludeEnd("ctx"); $self._assert_equals_($recv($recv(spySubmissions)._first())._results(),[false, true, true]); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test11",{spySubmissions:spySubmissions,spyView:spyView,aResult:aResult},$globals.ExamTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test11\x0a\x09| spySubmissions spyView aResult |\x0a\x09self givenExamWithText: 'Title A', String lf, 'And the text said: he{llo} wor{ld}. Cor{rect}'.\x0a\x09\x0a\x09spySubmissions := Array with: (SpySubmission newWith: #('wrong' 'ld' 'rect')).\x0a\x09spyView := SpyResultsView new.\x0a\x09\x0a\x09aResult := theExam evaluate: spySubmissions on: spyView.\x0a\x09aResult giveToStudent.\x0a\x09\x0a\x09self assert: spyView score equals: 2.\x0a\x09self assert: spyView totalScore equals: 3.\x0a\x09self assert: spyView percentage equals: 66.67.\x0a\x09self assert: spyView level equals: 'B1'.\x0a\x09self assert: (spySubmissions first) results equals: #(false true true).", referencedClasses: ["String", "Array", "SpySubmission", "SpyResultsView"], //>>excludeEnd("ide"); messageSends: ["givenExamWithText:", ",", "lf", "with:", "newWith:", "new", "evaluate:on:", "giveToStudent", "assert:equals:", "score", "totalScore", "percentage", "level", "results", "first"] }), $globals.ExamTest); $core.addClass("InterpreterText", $globals.TestCase, [], "OndafSimulator-Core-Tests"); $core.addMethod( $core.method({ selector: "test01InterpretEmptyText", protocol: "tests", fn: function (){ var self=this,$self=this; var anInterpreter,aText; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); anInterpreter=$recv($globals.CTestInterpreter)._new(); aText=$recv(anInterpreter)._interpretText_(""); $self._assert_equals_($recv(aText)._title(),""); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test01InterpretEmptyText",{anInterpreter:anInterpreter,aText:aText},$globals.InterpreterText)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test01InterpretEmptyText\x0a\x09| anInterpreter aText |\x0a\x09anInterpreter := CTestInterpreter new.\x0a\x09aText := anInterpreter interpretText: ''.\x0a\x09self assert: aText title equals: ''.", referencedClasses: ["CTestInterpreter"], //>>excludeEnd("ide"); messageSends: ["new", "interpretText:", "assert:equals:", "title"] }), $globals.InterpreterText); $core.addMethod( $core.method({ selector: "test02InterpretTextTitle", protocol: "tests", fn: function (){ var self=this,$self=this; var anInterpreter,aText; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); anInterpreter=$recv($globals.CTestInterpreter)._new(); aText=$recv(anInterpreter)._interpretText_("The Title"); $self._assert_equals_($recv(aText)._title(),"The Title"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test02InterpretTextTitle",{anInterpreter:anInterpreter,aText:aText},$globals.InterpreterText)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test02InterpretTextTitle\x0a\x09| anInterpreter aText |\x0a\x09anInterpreter := CTestInterpreter new.\x0a\x09aText := anInterpreter interpretText: 'The Title'.\x0a\x09self assert: aText title equals: 'The Title'.", referencedClasses: ["CTestInterpreter"], //>>excludeEnd("ide"); messageSends: ["new", "interpretText:", "assert:equals:", "title"] }), $globals.InterpreterText); $core.addMethod( $core.method({ selector: "test03TrimSpacesOfTextTitle", protocol: "tests", fn: function (){ var self=this,$self=this; var anInterpreter,aText; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); anInterpreter=$recv($globals.CTestInterpreter)._new(); aText=$recv(anInterpreter)._interpretText_(" The Title "); $self._assert_equals_($recv(aText)._title(),"The Title"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test03TrimSpacesOfTextTitle",{anInterpreter:anInterpreter,aText:aText},$globals.InterpreterText)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test03TrimSpacesOfTextTitle\x0a\x09| anInterpreter aText |\x0a\x09anInterpreter := CTestInterpreter new.\x0a\x09aText := anInterpreter interpretText: ' The Title '.\x0a\x09self assert: aText title equals: 'The Title'.", referencedClasses: ["CTestInterpreter"], //>>excludeEnd("ide"); messageSends: ["new", "interpretText:", "assert:equals:", "title"] }), $globals.InterpreterText); $core.addMethod( $core.method({ selector: "test04IgnoreLineBreaksBeforeAndAfterTitle", protocol: "tests", fn: function (){ var self=this,$self=this; var anInterpreter,aText; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$4,$3,$2; anInterpreter=$recv($globals.CTestInterpreter)._new(); $1=anInterpreter; $4=$recv($globals.String)._lf(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["lf"]=1; //>>excludeEnd("ctx"); $3=$recv($4).__comma(" The Title "); $2=$recv($3).__comma($recv($globals.String)._lf()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); aText=$recv($1)._interpretText_($2); $self._assert_equals_($recv(aText)._title(),"The Title"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test04IgnoreLineBreaksBeforeAndAfterTitle",{anInterpreter:anInterpreter,aText:aText},$globals.InterpreterText)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test04IgnoreLineBreaksBeforeAndAfterTitle\x0a\x09| anInterpreter aText |\x0a\x09anInterpreter := CTestInterpreter new.\x0a\x09aText := anInterpreter interpretText: String lf, ' The Title ', String lf.\x0a\x09self assert: aText title equals: 'The Title'.", referencedClasses: ["CTestInterpreter", "String"], //>>excludeEnd("ide"); messageSends: ["new", "interpretText:", ",", "lf", "assert:equals:", "title"] }), $globals.InterpreterText); $core.addMethod( $core.method({ selector: "test05InterpretTextContentWithOneLine", protocol: "tests", fn: function (){ var self=this,$self=this; var anInterpreter,aText; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$2; anInterpreter=$recv($globals.CTestInterpreter)._new(); $1=anInterpreter; $2=$recv("The Title".__comma($recv($globals.String)._lf())).__comma("The content"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); aText=$recv($1)._interpretText_($2); $self._assert_equals_($recv(aText)._title(),"The Title"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv(aText)._contentAsString(),"The content"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test05InterpretTextContentWithOneLine",{anInterpreter:anInterpreter,aText:aText},$globals.InterpreterText)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test05InterpretTextContentWithOneLine\x0a\x09| anInterpreter aText |\x0a\x09anInterpreter := CTestInterpreter new.\x0a\x09aText := anInterpreter interpretText: 'The Title', String lf, 'The content'.\x0a\x09self assert: aText title equals: 'The Title'.\x0a\x09self assert: aText contentAsString equals: 'The content'", referencedClasses: ["CTestInterpreter", "String"], //>>excludeEnd("ide"); messageSends: ["new", "interpretText:", ",", "lf", "assert:equals:", "title", "contentAsString"] }), $globals.InterpreterText); $core.addMethod( $core.method({ selector: "test06TrimTextContent", protocol: "tests", fn: function (){ var self=this,$self=this; var anInterpreter,aText; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$2; anInterpreter=$recv($globals.CTestInterpreter)._new(); $1=anInterpreter; $2=$recv("The Title".__comma($recv($globals.String)._lf())).__comma(" The content "); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); aText=$recv($1)._interpretText_($2); $self._assert_equals_($recv(aText)._title(),"The Title"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv(aText)._contentAsString(),"The content"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test06TrimTextContent",{anInterpreter:anInterpreter,aText:aText},$globals.InterpreterText)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test06TrimTextContent\x0a\x09| anInterpreter aText |\x0a\x09anInterpreter := CTestInterpreter new.\x0a\x09aText := anInterpreter interpretText: 'The Title', String lf, ' The content '.\x0a\x09self assert: aText title equals: 'The Title'.\x0a\x09self assert: aText contentAsString equals: 'The content'", referencedClasses: ["CTestInterpreter", "String"], //>>excludeEnd("ide"); messageSends: ["new", "interpretText:", ",", "lf", "assert:equals:", "title", "contentAsString"] }), $globals.InterpreterText); $core.addMethod( $core.method({ selector: "test07InterpretTextContentWithMultipleLines", protocol: "tests", fn: function (){ var self=this,$self=this; var anInterpreter,aText,stringText; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $4,$3,$2,$1; anInterpreter=$recv($globals.CTestInterpreter)._new(); $4=$recv($globals.String)._lf(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["lf"]=1; //>>excludeEnd("ctx"); $3="The Title".__comma($4); $2=$recv($3).__comma("The content"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=3; //>>excludeEnd("ctx"); $1=$recv($2).__comma($recv($globals.String)._lf()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=2; //>>excludeEnd("ctx"); stringText=$recv($1).__comma("More content"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); aText=$recv(anInterpreter)._interpretText_(stringText); $self._assert_equals_($recv(aText)._title(),"The Title"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv(aText)._contentAsString(),"The content More content"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test07InterpretTextContentWithMultipleLines",{anInterpreter:anInterpreter,aText:aText,stringText:stringText},$globals.InterpreterText)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test07InterpretTextContentWithMultipleLines\x0a\x09| anInterpreter aText stringText |\x0a\x09anInterpreter := CTestInterpreter new.\x0a\x09stringText := 'The Title' , String lf , 'The content' , String lf, 'More content'.\x0a\x09aText := anInterpreter interpretText: stringText.\x0a\x09self assert: aText title equals: 'The Title'.\x0a\x09self assert: aText contentAsString equals: \x09'The content More content'", referencedClasses: ["CTestInterpreter", "String"], //>>excludeEnd("ide"); messageSends: ["new", ",", "lf", "interpretText:", "assert:equals:", "title", "contentAsString"] }), $globals.InterpreterText); $core.addMethod( $core.method({ selector: "test08InterpretTextContentWithWordsToComplete", protocol: "tests", fn: function (){ var self=this,$self=this; var anInterpreter,aText,stringText; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $4,$3,$2,$1; anInterpreter=$recv($globals.CTestInterpreter)._new(); $4=$recv($globals.String)._lf(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["lf"]=1; //>>excludeEnd("ctx"); $3="The Title".__comma($4); $2=$recv($3).__comma("The cont{ent}"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=3; //>>excludeEnd("ctx"); $1=$recv($2).__comma($recv($globals.String)._lf()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=2; //>>excludeEnd("ctx"); stringText=$recv($1).__comma("More content"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); aText=$recv(anInterpreter)._interpretText_(stringText); $self._assert_equals_($recv(aText)._title(),"The Title"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv(aText)._contentAsString(),"The cont{ent} More content"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test08InterpretTextContentWithWordsToComplete",{anInterpreter:anInterpreter,aText:aText,stringText:stringText},$globals.InterpreterText)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test08InterpretTextContentWithWordsToComplete\x0a\x09| anInterpreter aText stringText |\x0a\x09anInterpreter := CTestInterpreter new.\x0a\x09stringText := 'The Title' , String lf , 'The cont{ent}' , String lf, 'More content'.\x0a\x09aText := anInterpreter interpretText: stringText.\x0a\x09self assert: aText title equals: 'The Title'.\x0a\x09self assert: aText contentAsString equals: 'The cont{ent} More content'", referencedClasses: ["CTestInterpreter", "String"], //>>excludeEnd("ide"); messageSends: ["new", ",", "lf", "interpretText:", "assert:equals:", "title", "contentAsString"] }), $globals.InterpreterText); $core.addMethod( $core.method({ selector: "test09TitleCanBeSeparatedWithMultipleReturns", protocol: "tests", fn: function (){ var self=this,$self=this; var anInterpreter,aText,stringText; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $5,$4,$6,$3,$2,$1; anInterpreter=$recv($globals.CTestInterpreter)._new(); $5=$recv($globals.String)._lf(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["lf"]=1; //>>excludeEnd("ctx"); $4="The Title".__comma($5); $6=$recv($globals.String)._lf(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["lf"]=2; //>>excludeEnd("ctx"); $3=$recv($4).__comma($6); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=4; //>>excludeEnd("ctx"); $2=$recv($3).__comma("The cont{ent}"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=3; //>>excludeEnd("ctx"); $1=$recv($2).__comma($recv($globals.String)._lf()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=2; //>>excludeEnd("ctx"); stringText=$recv($1).__comma("More content"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); aText=$recv(anInterpreter)._interpretText_(stringText); $self._assert_equals_($recv(aText)._title(),"The Title"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv(aText)._contentAsString(),"The cont{ent} More content"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test09TitleCanBeSeparatedWithMultipleReturns",{anInterpreter:anInterpreter,aText:aText,stringText:stringText},$globals.InterpreterText)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test09TitleCanBeSeparatedWithMultipleReturns\x0a\x09| anInterpreter aText stringText |\x0a\x09anInterpreter := CTestInterpreter new.\x0a\x09stringText := 'The Title' , String lf, String lf , 'The cont{ent}' , String lf, 'More content'.\x0a\x09aText := anInterpreter interpretText: stringText.\x0a\x09self assert: aText title equals: 'The Title'.\x0a\x09self assert: aText contentAsString equals: 'The cont{ent} More content'", referencedClasses: ["CTestInterpreter", "String"], //>>excludeEnd("ide"); messageSends: ["new", ",", "lf", "interpretText:", "assert:equals:", "title", "contentAsString"] }), $globals.InterpreterText); $core.addClass("ParserForContentTest", $globals.TestCase, ["aParser"], "OndafSimulator-Core-Tests"); $core.addMethod( $core.method({ selector: "assertState:", protocol: "assertions", fn: function (stateName){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self._assert_equals_($recv($self["@aParser"])._state(),stateName); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"assertState:",{stateName:stateName},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["stateName"], source: "assertState: stateName\x0a\x09self assert: aParser state equals: stateName", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["assert:equals:", "state"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "setUp", protocol: "running", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $self["@aParser"]=$recv($globals.CTestParser)._forContent(); $1=$self["@aParser"]; return $1; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"setUp",{},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "setUp\x0a\x09^ aParser := CTestParser forContent", referencedClasses: ["CTestParser"], //>>excludeEnd("ide"); messageSends: ["forContent"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "test01AParserStartsEmtpyAndWaiting", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self._assert_equals_($recv($self["@aParser"])._contents(),$recv($globals.OrderedCollection)._new()); $self._assertState_("Waiting"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test01AParserStartsEmtpyAndWaiting",{},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test01AParserStartsEmtpyAndWaiting\x0a\x09self assert: aParser contents equals: OrderedCollection new.\x0a\x09self assertState: 'Waiting'", referencedClasses: ["OrderedCollection"], //>>excludeEnd("ide"); messageSends: ["assert:equals:", "contents", "new", "assertState:"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "test02ReadLetterWhenWaiting", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$2; $recv($self["@aParser"])._consumeAllIn_("a"._readStream()); $1=$recv($self["@aParser"])._contents(); $2=$recv($globals.OrderedCollection)._with_($recv($globals.CompletedText)._with_("a")); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["with:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($1,$2); $self._assertState_("ReadingWord"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test02ReadLetterWhenWaiting",{},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test02ReadLetterWhenWaiting\x0a\x09aParser consumeAllIn: 'a' readStream.\x0a\x09self assert: aParser contents equals: (OrderedCollection\x0a\x09\x09with: (CompletedText with: 'a')\x0a\x09).\x0a\x09self assertState: 'ReadingWord'", referencedClasses: ["OrderedCollection", "CompletedText"], //>>excludeEnd("ide"); messageSends: ["consumeAllIn:", "readStream", "assert:equals:", "contents", "with:", "assertState:"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "test03ReadBlankWhenWaiting", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $recv($self["@aParser"])._consumeAllIn_($recv(" ".__comma($recv($globals.String)._lf()))._readStream()); $self._assert_equals_($recv($self["@aParser"])._contents(),$recv($globals.OrderedCollection)._new()); $self._assertState_("Waiting"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test03ReadBlankWhenWaiting",{},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test03ReadBlankWhenWaiting\x0a\x09aParser consumeAllIn: (' ', String lf) readStream.\x0a\x09self assert: aParser contents equals: OrderedCollection new.\x0a\x09self assertState: 'Waiting'", referencedClasses: ["String", "OrderedCollection"], //>>excludeEnd("ide"); messageSends: ["consumeAllIn:", "readStream", ",", "lf", "assert:equals:", "contents", "new", "assertState:"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "test04ReadBlankWhenReading", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$2; $recv($self["@aParser"])._consumeAllIn_("a "._readStream()); $1=$recv($self["@aParser"])._contents(); $2=$recv($globals.OrderedCollection)._with_($recv($globals.CompletedText)._with_("a")); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["with:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($1,$2); $self._assertState_("WaitingForWord"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test04ReadBlankWhenReading",{},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test04ReadBlankWhenReading\x0a\x09aParser consumeAllIn: 'a ' readStream.\x0a\x09self assert: aParser contents equals: (OrderedCollection\x0a\x09\x09with: (CompletedText with: 'a')\x0a\x09).\x0a\x09self assertState: 'WaitingForWord'", referencedClasses: ["OrderedCollection", "CompletedText"], //>>excludeEnd("ide"); messageSends: ["consumeAllIn:", "readStream", "assert:equals:", "contents", "with:", "assertState:"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "test05ReadBlankWhenWaitingForWord", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$2; $recv($self["@aParser"])._consumeAllIn_("a b"._readStream()); $1=$recv($self["@aParser"])._contents(); $2=$recv($globals.OrderedCollection)._with_($recv($globals.CompletedText)._with_("a b")); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["with:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($1,$2); $self._assertState_("ReadingWord"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test05ReadBlankWhenWaitingForWord",{},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test05ReadBlankWhenWaitingForWord\x0a\x09aParser consumeAllIn: 'a b' readStream.\x0a\x09self assert: aParser contents equals: (OrderedCollection\x0a\x09\x09with: (CompletedText with: 'a b')\x0a\x09).\x0a\x09self assertState: 'ReadingWord'", referencedClasses: ["OrderedCollection", "CompletedText"], //>>excludeEnd("ide"); messageSends: ["consumeAllIn:", "readStream", "assert:equals:", "contents", "with:", "assertState:"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "test06ParseTextWithSpaces", protocol: "tests", fn: function (){ var self=this,$self=this; var text; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$2; text=$recv($recv($recv($globals.String)._lf()).__comma(" asd qwerty ")).__comma($recv($globals.String)._tab()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $recv($self["@aParser"])._consumeAllIn_($recv(text)._readStream()); $1=$recv($self["@aParser"])._contents(); $2=$recv($globals.OrderedCollection)._with_($recv($globals.CompletedText)._with_("asd qwerty")); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["with:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($1,$2); $self._assertState_("WaitingForWord"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test06ParseTextWithSpaces",{text:text},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test06ParseTextWithSpaces\x0a\x09| text |\x0a\x09text := String lf, ' asd qwerty ', String tab.\x0a\x09aParser consumeAllIn: text readStream.\x0a\x09self assert: aParser contents equals: (OrderedCollection\x0a\x09\x09with: (CompletedText with: 'asd qwerty')\x0a\x09).\x0a\x09self assertState: 'WaitingForWord'", referencedClasses: ["String", "OrderedCollection", "CompletedText"], //>>excludeEnd("ide"); messageSends: [",", "lf", "tab", "consumeAllIn:", "readStream", "assert:equals:", "contents", "with:", "assertState:"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "test07InitWordToComplete", protocol: "tests", fn: function (){ var self=this,$self=this; var text; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); text="he{"; $recv(text)._do_((function(c){ //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx2) { //>>excludeEnd("ctx"); return $recv($self["@aParser"])._consume_($recv(c)._asString()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx2) {$ctx2.fillBlock({c:c},$ctx1,1)}); //>>excludeEnd("ctx"); })); $self._assertState_("ReadingSuffixes"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test07InitWordToComplete",{text:text},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test07InitWordToComplete\x0a\x09| text |\x0a\x09text := 'he{'.\x0a\x09text do: [ :c | aParser consume: c asString ].\x0a\x09self assertState: 'ReadingSuffixes'.", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["do:", "consume:", "asString", "assertState:"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "test08ParseTextWithWordsToComplete", protocol: "tests", fn: function (){ var self=this,$self=this; var text; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); text="he{llo}"; $recv($self["@aParser"])._consumeAllIn_($recv(text)._readStream()); $self._assert_equals_($recv($self["@aParser"])._contents(),$recv($globals.OrderedCollection)._with_($recv($globals.WordToComplete)._withPrefix_options_("he",["llo"]))); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test08ParseTextWithWordsToComplete",{text:text},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test08ParseTextWithWordsToComplete\x0a\x09| text |\x0a\x09text := 'he{llo}'.\x0a\x09aParser consumeAllIn: text readStream.\x0a\x09self assert: aParser contents equals: (OrderedCollection\x0a\x09\x09with: (WordToComplete withPrefix: 'he' options: #('llo'))\x0a\x09).", referencedClasses: ["OrderedCollection", "WordToComplete"], //>>excludeEnd("ide"); messageSends: ["consumeAllIn:", "readStream", "assert:equals:", "contents", "with:", "withPrefix:options:"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "test09ParseTextWithWordsToCompleteBetweenText", protocol: "tests", fn: function (){ var self=this,$self=this; var text; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$3,$2; text="pre text he{llo} post text"; $recv($self["@aParser"])._consumeAllIn_($recv(text)._readStream()); $1=$recv($self["@aParser"])._contents(); $3=$recv($globals.CompletedText)._with_("pre text"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["with:"]=1; //>>excludeEnd("ctx"); $2=$recv($globals.OrderedCollection)._with_with_with_($3,$recv($globals.WordToComplete)._withPrefix_options_("he",["llo"]),$recv($globals.CompletedText)._with_("post text")); $self._assert_equals_($1,$2); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test09ParseTextWithWordsToCompleteBetweenText",{text:text},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test09ParseTextWithWordsToCompleteBetweenText\x0a\x09| text |\x0a\x09text := 'pre text he{llo} post text'.\x0a\x09aParser consumeAllIn: text readStream.\x0a\x09self assert: aParser contents equals: (OrderedCollection\x0a\x09\x09with: (CompletedText with: 'pre text')\x0a\x09\x09with: (WordToComplete withPrefix: 'he' options: #('llo'))\x0a\x09\x09with: (CompletedText with: 'post text')).", referencedClasses: ["OrderedCollection", "CompletedText", "WordToComplete"], //>>excludeEnd("ide"); messageSends: ["consumeAllIn:", "readStream", "assert:equals:", "contents", "with:with:with:", "with:", "withPrefix:options:"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "test10ParseTextWithOneOptionWordsToComplete", protocol: "tests", fn: function (){ var self=this,$self=this; var text; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $5,$4,$3,$2,$1,$6,$8,$9,$7; $5=$recv($globals.String)._lf(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["lf"]=1; //>>excludeEnd("ctx"); $4=$recv($5).__comma(" pre text 1 "); $3=$recv($4).__comma($recv($globals.String)._tab()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=4; //>>excludeEnd("ctx"); $2=$recv($3).__comma(" and he{llo} post. "); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=3; //>>excludeEnd("ctx"); $1=$recv($2).__comma($recv($globals.String)._lf()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=2; //>>excludeEnd("ctx"); text=$recv($1).__comma(" text anot{her} "); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $recv($self["@aParser"])._consumeAllIn_($recv(text)._readStream()); $6=$recv($self["@aParser"])._contents(); $8=$recv($globals.CompletedText)._with_("pre text 1 and"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["with:"]=1; //>>excludeEnd("ctx"); $9=$recv($globals.WordToComplete)._withPrefix_options_("he",["llo"]); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["withPrefix:options:"]=1; //>>excludeEnd("ctx"); $7=$recv($globals.OrderedCollection)._with_with_with_with_($8,$9,$recv($globals.CompletedText)._with_("post. text"),$recv($globals.WordToComplete)._withPrefix_options_("anot",["her"])); $self._assert_equals_($6,$7); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test10ParseTextWithOneOptionWordsToComplete",{text:text},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test10ParseTextWithOneOptionWordsToComplete\x0a\x09| text |\x0a\x09text := String lf, ' pre text 1 ', String tab, ' and he{llo} post. ', String lf, ' text anot{her} '.\x0a\x09aParser consumeAllIn: text readStream.\x0a\x09self assert: aParser contents equals: (OrderedCollection\x0a\x09\x09with: (CompletedText with: 'pre text 1 and')\x0a\x09\x09with: (WordToComplete withPrefix: 'he' options: #('llo'))\x0a\x09\x09with: (CompletedText with: 'post. text')\x0a\x09\x09with: (WordToComplete withPrefix: 'anot' options: #('her'))\x0a\x09).", referencedClasses: ["String", "OrderedCollection", "CompletedText", "WordToComplete"], //>>excludeEnd("ide"); messageSends: [",", "lf", "tab", "consumeAllIn:", "readStream", "assert:equals:", "contents", "with:with:with:with:", "with:", "withPrefix:options:"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "test11ParseTextWithMoreThenOneOptionWordToComplete", protocol: "tests", fn: function (){ var self=this,$self=this; var text; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$3,$2; text="pre text he{llo,art} post."; $recv($self["@aParser"])._consumeAllIn_($recv(text)._readStream()); $1=$recv($self["@aParser"])._contents(); $3=$recv($globals.CompletedText)._with_("pre text"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["with:"]=1; //>>excludeEnd("ctx"); $2=$recv($globals.OrderedCollection)._with_with_with_($3,$recv($globals.WordToComplete)._withPrefix_options_("he",["llo", "art"]),$recv($globals.CompletedText)._with_("post.")); $self._assert_equals_($1,$2); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test11ParseTextWithMoreThenOneOptionWordToComplete",{text:text},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test11ParseTextWithMoreThenOneOptionWordToComplete\x0a\x09| text |\x0a\x09text := 'pre text he{llo,art} post.'.\x0a\x09aParser consumeAllIn: text readStream.\x0a\x09self assert: aParser contents equals: (OrderedCollection\x0a\x09\x09with: (CompletedText with: 'pre text')\x0a\x09\x09with: (WordToComplete withPrefix: 'he' options: #('llo' 'art'))\x0a\x09\x09with: (CompletedText with: 'post.')\x0a\x09).", referencedClasses: ["OrderedCollection", "CompletedText", "WordToComplete"], //>>excludeEnd("ide"); messageSends: ["consumeAllIn:", "readStream", "assert:equals:", "contents", "with:with:with:", "with:", "withPrefix:options:"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "test12ParseTextWithSpaceInOptions", protocol: "tests", fn: function (){ var self=this,$self=this; var text; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$3,$2; text="pre text he{ llo , art } post."; $recv($self["@aParser"])._consumeAllIn_($recv(text)._readStream()); $1=$recv($self["@aParser"])._contents(); $3=$recv($globals.CompletedText)._with_("pre text"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["with:"]=1; //>>excludeEnd("ctx"); $2=$recv($globals.OrderedCollection)._with_with_with_($3,$recv($globals.WordToComplete)._withPrefix_options_("he",["llo", "art"]),$recv($globals.CompletedText)._with_("post.")); $self._assert_equals_($1,$2); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test12ParseTextWithSpaceInOptions",{text:text},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test12ParseTextWithSpaceInOptions\x0a\x09| text |\x0a\x09text := 'pre text he{ llo , art } post.'.\x0a\x09aParser consumeAllIn: text readStream.\x0a\x09self assert: aParser contents equals: (OrderedCollection\x0a\x09\x09with: (CompletedText with: 'pre text')\x0a\x09\x09with: (WordToComplete withPrefix: 'he' options: #('llo' 'art'))\x0a\x09\x09with: (CompletedText with: 'post.')\x0a\x09).", referencedClasses: ["OrderedCollection", "CompletedText", "WordToComplete"], //>>excludeEnd("ide"); messageSends: ["consumeAllIn:", "readStream", "assert:equals:", "contents", "with:with:with:", "with:", "withPrefix:options:"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "test13ParseTextWithManyOptions", protocol: "tests", fn: function (){ var self=this,$self=this; var text; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$3,$2; text="pre text he{llo, art, r} post."; $recv($self["@aParser"])._consumeAllIn_($recv(text)._readStream()); $1=$recv($self["@aParser"])._contents(); $3=$recv($globals.CompletedText)._with_("pre text"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["with:"]=1; //>>excludeEnd("ctx"); $2=$recv($globals.OrderedCollection)._with_with_with_($3,$recv($globals.WordToComplete)._withPrefix_options_("he",["llo", "art", "r"]),$recv($globals.CompletedText)._with_("post.")); $self._assert_equals_($1,$2); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test13ParseTextWithManyOptions",{text:text},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test13ParseTextWithManyOptions\x0a\x09| text |\x0a\x09text := 'pre text he{llo, art, r} post.'.\x0a\x09aParser consumeAllIn: text readStream.\x0a\x09self assert: aParser contents equals: (OrderedCollection\x0a\x09\x09with: (CompletedText with: 'pre text')\x0a\x09\x09with: (WordToComplete withPrefix: 'he' options: #('llo' 'art' 'r'))\x0a\x09\x09with: (CompletedText with: 'post.')\x0a\x09).", referencedClasses: ["OrderedCollection", "CompletedText", "WordToComplete"], //>>excludeEnd("ide"); messageSends: ["consumeAllIn:", "readStream", "assert:equals:", "contents", "with:with:with:", "with:", "withPrefix:options:"] }), $globals.ParserForContentTest); $core.addMethod( $core.method({ selector: "test14ParseTextWithLineBreaks", protocol: "tests", fn: function (){ var self=this,$self=this; var text; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1,$2; text=$recv("some text.".__comma($recv($globals.String)._lf())).__comma("more text"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $recv($self["@aParser"])._consumeAllIn_($recv(text)._readStream()); $1=$recv($self["@aParser"])._contents(); $2=$recv($globals.OrderedCollection)._with_($recv($globals.CompletedText)._with_("some text. more text")); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["with:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($1,$2); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test14ParseTextWithLineBreaks",{text:text},$globals.ParserForContentTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test14ParseTextWithLineBreaks\x0a\x09| text |\x0a\x09text := 'some text.', String lf, 'more text'.\x0a\x09aParser consumeAllIn: text readStream.\x0a\x09self assert: aParser contents equals: (OrderedCollection\x0a\x09\x09with: (CompletedText with: 'some text. more text')\x0a\x09).", referencedClasses: ["String", "OrderedCollection", "CompletedText"], //>>excludeEnd("ide"); messageSends: [",", "lf", "consumeAllIn:", "readStream", "assert:equals:", "contents", "with:"] }), $globals.ParserForContentTest); $core.addClass("ParserForTitleTest", $globals.TestCase, ["aParser"], "OndafSimulator-Core-Tests"); $core.addMethod( $core.method({ selector: "setUp", protocol: "running", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $self["@aParser"]=$recv($globals.CTestParser)._forTitle(); $1=$self["@aParser"]; return $1; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"setUp",{},$globals.ParserForTitleTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "setUp\x0a\x09^ aParser := CTestParser forTitle", referencedClasses: ["CTestParser"], //>>excludeEnd("ide"); messageSends: ["forTitle"] }), $globals.ParserForTitleTest); $core.addMethod( $core.method({ selector: "test01AParserStartsEmtpyAndWaiting", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self._assert_equals_($recv($self["@aParser"])._contents(),""); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv($self["@aParser"])._state(),"Waiting"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test01AParserStartsEmtpyAndWaiting",{},$globals.ParserForTitleTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test01AParserStartsEmtpyAndWaiting\x0a\x09self assert: aParser contents equals: ''.\x0a\x09self assert: aParser state equals: 'Waiting'", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["assert:equals:", "contents", "state"] }), $globals.ParserForTitleTest); $core.addMethod( $core.method({ selector: "test02ReadLetterWhenWaiting", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $recv($self["@aParser"])._consume_("a"); $self._assert_equals_($recv($self["@aParser"])._contents(),"a"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv($self["@aParser"])._state(),"ReadingWord"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test02ReadLetterWhenWaiting",{},$globals.ParserForTitleTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test02ReadLetterWhenWaiting\x0a\x09aParser consume: 'a'.\x0a\x09self assert: aParser contents equals: 'a'.\x0a\x09self assert: aParser state equals: 'ReadingWord'", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["consume:", "assert:equals:", "contents", "state"] }), $globals.ParserForTitleTest); $core.addMethod( $core.method({ selector: "test03ReadBlankWhenWaiting", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $recv($self["@aParser"])._consume_(" "); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["consume:"]=1; //>>excludeEnd("ctx"); $recv($self["@aParser"])._consume_($recv($globals.String)._lf()); $self._assert_equals_($recv($self["@aParser"])._contents(),""); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv($self["@aParser"])._state(),"Waiting"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test03ReadBlankWhenWaiting",{},$globals.ParserForTitleTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test03ReadBlankWhenWaiting\x0a\x09aParser consume: ' '.\x0a\x09aParser consume: String lf.\x0a\x09self assert: aParser contents equals: ''.\x0a\x09self assert: aParser state equals: 'Waiting'", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: ["consume:", "lf", "assert:equals:", "contents", "state"] }), $globals.ParserForTitleTest); $core.addMethod( $core.method({ selector: "test04ReadBlankWhenReading", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$self["@aParser"]; $recv($1)._consume_("a"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["consume:"]=1; //>>excludeEnd("ctx"); $recv($1)._consume_(" "); $self._assert_equals_($recv($self["@aParser"])._contents(),"a"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv($self["@aParser"])._state(),"WaitingForWord"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test04ReadBlankWhenReading",{},$globals.ParserForTitleTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test04ReadBlankWhenReading\x0a\x09aParser\x0a\x09\x09consume: 'a';\x0a\x09\x09consume: ' '.\x0a\x09self assert: aParser contents equals: 'a'.\x0a\x09self assert: aParser state equals: 'WaitingForWord'", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["consume:", "assert:equals:", "contents", "state"] }), $globals.ParserForTitleTest); $core.addMethod( $core.method({ selector: "test05ReadBlankWhenWaitingForWord", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$self["@aParser"]; $recv($1)._consume_("a"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["consume:"]=1; //>>excludeEnd("ctx"); $recv($1)._consume_(" "); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["consume:"]=2; //>>excludeEnd("ctx"); $recv($1)._consume_("b"); $self._assert_equals_($recv($self["@aParser"])._contents(),"a b"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv($self["@aParser"])._state(),"ReadingWord"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test05ReadBlankWhenWaitingForWord",{},$globals.ParserForTitleTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test05ReadBlankWhenWaitingForWord\x0a\x09aParser consume: 'a';\x0a\x09 consume: ' ';\x0a\x09 consume: 'b'.\x0a\x09self assert: aParser contents equals: 'a b'.\x0a\x09self assert: aParser state equals: 'ReadingWord'", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["consume:", "assert:equals:", "contents", "state"] }), $globals.ParserForTitleTest); $core.addMethod( $core.method({ selector: "test06ParseTextWithSpaces", protocol: "tests", fn: function (){ var self=this,$self=this; var text; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); text=$recv($recv($recv($globals.String)._lf()).__comma(" asd qwerty ")).__comma($recv($globals.String)._tab()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $recv(text)._do_((function(c){ //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx2) { //>>excludeEnd("ctx"); return $recv($self["@aParser"])._consume_($recv(c)._asString()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx2) {$ctx2.fillBlock({c:c},$ctx1,1)}); //>>excludeEnd("ctx"); })); $self._assert_equals_($recv($self["@aParser"])._contents(),"asd qwerty"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv($self["@aParser"])._state(),"WaitingForWord"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test06ParseTextWithSpaces",{text:text},$globals.ParserForTitleTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test06ParseTextWithSpaces\x0a\x09| text |\x0a\x09text := String lf, ' asd qwerty ', String tab.\x0a\x09text do: [ :c | aParser consume: c asString ].\x0a\x09self assert: aParser contents equals: 'asd qwerty'.\x0a\x09self assert: aParser state equals: 'WaitingForWord'", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: [",", "lf", "tab", "do:", "consume:", "asString", "assert:equals:", "contents", "state"] }), $globals.ParserForTitleTest); $core.addMethod( $core.method({ selector: "test07EndInNewLineWhenWaitingForWord", protocol: "tests", fn: function (){ var self=this,$self=this; var text; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $4,$3,$2,$1; $4=$recv($globals.String)._lf(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["lf"]=1; //>>excludeEnd("ctx"); $3=$recv($4).__comma(" asd qwerty "); $2=$recv($3).__comma($recv($globals.String)._tab()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=3; //>>excludeEnd("ctx"); $1=$recv($2).__comma($recv($globals.String)._lf()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=2; //>>excludeEnd("ctx"); text=$recv($1).__comma("more content"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $recv(text)._do_((function(c){ //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx2) { //>>excludeEnd("ctx"); return $recv($self["@aParser"])._consume_($recv(c)._asString()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx2) {$ctx2.fillBlock({c:c},$ctx1,1)}); //>>excludeEnd("ctx"); })); $self._assert_equals_($recv($self["@aParser"])._contents(),"asd qwerty"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv($self["@aParser"])._state(),"End"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test07EndInNewLineWhenWaitingForWord",{text:text},$globals.ParserForTitleTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test07EndInNewLineWhenWaitingForWord\x0a\x09| text |\x0a\x09text := String lf, ' asd qwerty ', String tab, String lf, 'more content'.\x0a\x09text do: [ :c | aParser consume: c asString ].\x0a\x09self assert: aParser contents equals: 'asd qwerty'.\x0a\x09self assert: aParser state equals: 'End'", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: [",", "lf", "tab", "do:", "consume:", "asString", "assert:equals:", "contents", "state"] }), $globals.ParserForTitleTest); $core.addMethod( $core.method({ selector: "test08EndInNewLineWhenReading", protocol: "tests", fn: function (){ var self=this,$self=this; var text; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $3,$2,$1; $3=$recv($globals.String)._lf(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["lf"]=1; //>>excludeEnd("ctx"); $2=$recv($3).__comma(" asd qwerty"); $1=$recv($2).__comma($recv($globals.String)._lf()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=2; //>>excludeEnd("ctx"); text=$recv($1).__comma("more content"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $recv(text)._do_((function(c){ //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx2) { //>>excludeEnd("ctx"); return $recv($self["@aParser"])._consume_($recv(c)._asString()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx2) {$ctx2.fillBlock({c:c},$ctx1,1)}); //>>excludeEnd("ctx"); })); $self._assert_equals_($recv($self["@aParser"])._contents(),"asd qwerty"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv($self["@aParser"])._state(),"End"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test08EndInNewLineWhenReading",{text:text},$globals.ParserForTitleTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test08EndInNewLineWhenReading\x0a\x09| text |\x0a\x09text := String lf, ' asd qwerty', String lf, 'more content'.\x0a\x09text do: [ :c | aParser consume: c asString ].\x0a\x09self assert: aParser contents equals: 'asd qwerty'.\x0a\x09self assert: aParser state equals: 'End'", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: [",", "lf", "do:", "consume:", "asString", "assert:equals:", "contents", "state"] }), $globals.ParserForTitleTest); $core.addMethod( $core.method({ selector: "test09DontKeepReadingIfAtEnd", protocol: "tests", fn: function (){ var self=this,$self=this; var text,textStream; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); text=$recv("123".__comma($recv($globals.String)._lf())).__comma("more content"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); textStream=$recv(text)._readStream(); $recv($self["@aParser"])._consumeAllIn_(textStream); $self._assert_equals_($recv($self["@aParser"])._contents(),"123"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=1; //>>excludeEnd("ctx"); $self._assert_equals_($recv($self["@aParser"])._state(),"End"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assert:equals:"]=2; //>>excludeEnd("ctx"); $self._assert_equals_($recv(textStream)._position(),(4)); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test09DontKeepReadingIfAtEnd",{text:text,textStream:textStream},$globals.ParserForTitleTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test09DontKeepReadingIfAtEnd\x0a\x09| text textStream |\x0a\x09text := '123', String lf, 'more content'.\x0a\x09textStream := text readStream.\x0a\x09aParser consumeAllIn: textStream.\x0a\x09self assert: aParser contents equals: '123'.\x0a\x09self assert: aParser state equals: 'End'.\x0a\x09self assert: textStream position equals: 4", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: [",", "lf", "readStream", "consumeAllIn:", "assert:equals:", "contents", "state", "position"] }), $globals.ParserForTitleTest); $core.addMethod( $core.method({ selector: "test10ReturnWhenStreamEnds", protocol: "tests", fn: function (){ var self=this,$self=this; var text,textStream; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); text="123"; textStream=$recv(text)._readStream(); $recv($self["@aParser"])._consumeAllIn_(textStream); $self._assert_equals_($recv($self["@aParser"])._contents(),"123"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test10ReturnWhenStreamEnds",{text:text,textStream:textStream},$globals.ParserForTitleTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test10ReturnWhenStreamEnds\x0a\x09| text textStream |\x0a\x09text := '123'.\x0a\x09textStream := text readStream.\x0a\x09aParser consumeAllIn: textStream.\x0a\x09self assert: aParser contents equals: '123'.", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["readStream", "consumeAllIn:", "assert:equals:", "contents"] }), $globals.ParserForTitleTest); $core.addMethod( $core.method({ selector: "test11ParseTitle", protocol: "tests", fn: function (){ var self=this,$self=this; var text,textStream; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); text=$recv(" This is a 3 ".__comma($recv($globals.String)._lf())).__comma(" more content"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); textStream=$recv(text)._readStream(); $recv($self["@aParser"])._consumeAllIn_(textStream); $self._assert_equals_($recv($self["@aParser"])._contents(),"This is a 3"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test11ParseTitle",{text:text,textStream:textStream},$globals.ParserForTitleTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test11ParseTitle\x0a\x09| text textStream |\x0a\x09text := ' This is a 3 ', String lf, ' more content'.\x0a\x09textStream := text readStream.\x0a\x09aParser consumeAllIn: textStream.\x0a\x09self assert: aParser contents equals: 'This is a 3'.", referencedClasses: ["String"], //>>excludeEnd("ide"); messageSends: [",", "lf", "readStream", "consumeAllIn:", "assert:equals:", "contents"] }), $globals.ParserForTitleTest); $core.addClass("ResultTableTest", $globals.TestCase, [], "OndafSimulator-Core-Tests"); $core.addMethod( $core.method({ selector: "assertPercentage:isLevel:", protocol: "assertions", fn: function (percentage,expectedLevel){ var self=this,$self=this; var aLevel; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); aLevel=$recv($globals.CTestResultTable)._levelForPercentage_(percentage); $self._assert_equals_(aLevel,expectedLevel); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"assertPercentage:isLevel:",{percentage:percentage,expectedLevel:expectedLevel,aLevel:aLevel},$globals.ResultTableTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["percentage", "expectedLevel"], source: "assertPercentage: percentage isLevel: expectedLevel\x0a\x09| aLevel |\x0a\x09aLevel := CTestResultTable levelForPercentage: percentage.\x0a\x09self assert: aLevel equals: expectedLevel", referencedClasses: ["CTestResultTable"], //>>excludeEnd("ide"); messageSends: ["levelForPercentage:", "assert:equals:"] }), $globals.ResultTableTest); $core.addMethod( $core.method({ selector: "test01DetermineLevelFromPercentage", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self._assertPercentage_isLevel_((60),"A2 (oder unter)"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assertPercentage:isLevel:"]=1; //>>excludeEnd("ctx"); $self._assertPercentage_isLevel_((61),"B1"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assertPercentage:isLevel:"]=2; //>>excludeEnd("ctx"); $self._assertPercentage_isLevel_((87),"B1"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx["assertPercentage:isLevel:"]=3; //>>excludeEnd("ctx"); $self._assertPercentage_isLevel_((88),"B2 (oder höher)"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test01DetermineLevelFromPercentage",{},$globals.ResultTableTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test01DetermineLevelFromPercentage\x0a\x09self assertPercentage: 60 isLevel: 'A2 (oder unter)'.\x0a\x09self assertPercentage: 61 isLevel: 'B1'.\x0a\x09self assertPercentage: 87 isLevel: 'B1'.\x0a\x09self assertPercentage: 88 isLevel: 'B2 (oder höher)'", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["assertPercentage:isLevel:"] }), $globals.ResultTableTest); $core.addClass("SpyResultsView", $globals.Object, ["score", "totalScore", "percentage", "level"], "OndafSimulator-Core-Tests"); $core.addMethod( $core.method({ selector: "level", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; return $self["@level"]; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "level\x0a\x09^ level", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.SpyResultsView); $core.addMethod( $core.method({ selector: "percentage", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; return $self["@percentage"]; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "percentage\x0a\x09^ percentage", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.SpyResultsView); $core.addMethod( $core.method({ selector: "renderScore:of:percentage:level:", protocol: "as yet unclassified", fn: function (aScore,aTotalScore,aPercentage,aLevel){ var self=this,$self=this; $self["@score"]=aScore; $self["@totalScore"]=aTotalScore; $self["@percentage"]=aPercentage; $self["@level"]=aLevel; return self; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["aScore", "aTotalScore", "aPercentage", "aLevel"], source: "renderScore: aScore of: aTotalScore percentage: aPercentage level: aLevel \x0a\x09score := aScore.\x0a\x09totalScore := aTotalScore.\x0a\x09percentage := aPercentage.\x0a\x09level := aLevel", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.SpyResultsView); $core.addMethod( $core.method({ selector: "score", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; return $self["@score"]; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "score\x0a\x09^ score", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.SpyResultsView); $core.addMethod( $core.method({ selector: "totalScore", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; return $self["@totalScore"]; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "totalScore\x0a\x09^ totalScore", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.SpyResultsView); $core.addClass("SpySubmission", $globals.Object, ["answers", "results", "shown"], "OndafSimulator-Core-Tests"); $core.addMethod( $core.method({ selector: "answers", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; return $self["@answers"]; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "answers\x0a\x09^ answers", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.SpySubmission); $core.addMethod( $core.method({ selector: "answers:", protocol: "as yet unclassified", fn: function (aCollection){ var self=this,$self=this; $self["@answers"]=aCollection; return self; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["aCollection"], source: "answers: aCollection \x0a\x09answers := aCollection", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.SpySubmission); $core.addMethod( $core.method({ selector: "consumeResults:", protocol: "as yet unclassified", fn: function (aReadStream){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self["@results"]=$recv(aReadStream)._next_($recv($self["@answers"])._size()); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"consumeResults:",{aReadStream:aReadStream},$globals.SpySubmission)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["aReadStream"], source: "consumeResults: aReadStream \x0a\x09results := aReadStream next: answers size.", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["next:", "size"] }), $globals.SpySubmission); $core.addMethod( $core.method({ selector: "giveBackToStudent", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; $self["@shown"]=true; return self; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "giveBackToStudent\x0a\x09shown := true", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.SpySubmission); $core.addMethod( $core.method({ selector: "results", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; return $self["@results"]; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "results\x0a\x09^ results", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.SpySubmission); $core.addMethod( $core.method({ selector: "newWith:", protocol: "as yet unclassified", fn: function (aCollection){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$self._new(); $recv($1)._answers_(aCollection); return $recv($1)._yourself(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"newWith:",{aCollection:aCollection},$globals.SpySubmission.a$cls)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["aCollection"], source: "newWith: aCollection \x0a\x09^ self new\x0a\x09\x09answers: aCollection;\x0a\x09\x09yourself", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["answers:", "new", "yourself"] }), $globals.SpySubmission.a$cls); $core.addClass("TestTray", $globals.Object, [], "OndafSimulator-Core-Tests"); $core.addMethod( $core.method({ selector: "newCopy:of:titled:withTime:", protocol: "as yet unclassified", fn: function (textNumber,totalTexts,aString,aTimeInSeconds){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; $1=$recv($globals.TextCopySpy)._new(); $recv($1)._time_(aTimeInSeconds); $recv($1)._title_(aString); return $recv($1)._yourself(); //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"newCopy:of:titled:withTime:",{textNumber:textNumber,totalTexts:totalTexts,aString:aString,aTimeInSeconds:aTimeInSeconds},$globals.TestTray)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["textNumber", "totalTexts", "aString", "aTimeInSeconds"], source: "newCopy: textNumber of: totalTexts titled: aString withTime: aTimeInSeconds \x0a\x09^ TextCopySpy new\x0a\x09\x09time: aTimeInSeconds;\x0a\x09\x09title: aString;\x0a\x09\x09yourself", referencedClasses: ["TextCopySpy"], //>>excludeEnd("ide"); messageSends: ["time:", "new", "title:", "yourself"] }), $globals.TestTray); $core.addClass("TextCopySpy", $globals.Object, ["printedText", "time"], "OndafSimulator-Core-Tests"); $core.addMethod( $core.method({ selector: "addText:", protocol: "as yet unclassified", fn: function (aString){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self["@printedText"]=$recv($recv($self["@printedText"]).__comma(aString)).__comma(" "); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"addText:",{aString:aString},$globals.TextCopySpy)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["aString"], source: "addText: aString \x0a\x09printedText := printedText, aString, ' '", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [","] }), $globals.TextCopySpy); $core.addMethod( $core.method({ selector: "addWordToComplete:", protocol: "as yet unclassified", fn: function (aString){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self._addText_($recv(aString).__comma("_")); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"addWordToComplete:",{aString:aString},$globals.TextCopySpy)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["aString"], source: "addWordToComplete: aString \x0a\x09self addText: aString, '_'", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["addText:", ","] }), $globals.TextCopySpy); $core.addMethod( $core.method({ selector: "initialize", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); ( //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.supercall = true, //>>excludeEnd("ctx"); ($globals.TextCopySpy.superclass||$boot.nilAsClass).fn.prototype._initialize.apply($self, [])); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.supercall = false; //>>excludeEnd("ctx");; $self["@printedText"]=""; return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"initialize",{},$globals.TextCopySpy)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "initialize\x0a\x09super initialize.\x0a\x09printedText := ''", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["initialize"] }), $globals.TextCopySpy); $core.addMethod( $core.method({ selector: "printedText", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; return $self["@printedText"]; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "printedText\x0a\x09^ printedText", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.TextCopySpy); $core.addMethod( $core.method({ selector: "time:", protocol: "as yet unclassified", fn: function (anInteger){ var self=this,$self=this; $self["@time"]=anInteger; return self; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["anInteger"], source: "time: anInteger \x0a\x09time := anInteger", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.TextCopySpy); $core.addMethod( $core.method({ selector: "title:", protocol: "as yet unclassified", fn: function (aString){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $3,$2,$1; $3=$recv("|".__comma(aString)).__comma(" ("); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=3; //>>excludeEnd("ctx"); $2=$recv($3).__comma($recv($self["@time"])._asString()); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=2; //>>excludeEnd("ctx"); $1=$recv($2).__comma("s)|"); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.sendIdx[","]=1; //>>excludeEnd("ctx"); $self._addText_($1); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"title:",{aString:aString},$globals.TextCopySpy)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["aString"], source: "title: aString \x0a\x09self addText: '|', aString, ' (', time asString, 's)|'", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["addText:", ",", "asString"] }), $globals.TextCopySpy); $core.addClass("TextViewSpy", $globals.TextCopySpy, ["rendered", "answers", "results", "onContinue", "wasShown"], "OndafSimulator-Core-Tests"); $core.addMethod( $core.method({ selector: "answers", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; return $self["@answers"]; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "answers\x0a\x09^ answers", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.TextViewSpy); $core.addMethod( $core.method({ selector: "answers:", protocol: "as yet unclassified", fn: function (anObject){ var self=this,$self=this; $self["@answers"]=anObject; return self; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["anObject"], source: "answers: anObject \x0a\x09answers := anObject", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.TextViewSpy); $core.addMethod( $core.method({ selector: "continue", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $recv($self["@onContinue"])._value(); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"continue",{},$globals.TextViewSpy)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "continue\x0a\x09onContinue value", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["value"] }), $globals.TextViewSpy); $core.addMethod( $core.method({ selector: "hide", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; $self["@rendered"]=false; return self; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "hide\x0a\x09rendered := false", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.TextViewSpy); $core.addMethod( $core.method({ selector: "isRendered", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; return $self["@rendered"]; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "isRendered\x0a\x09^ rendered", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.TextViewSpy); $core.addMethod( $core.method({ selector: "render", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; $self["@rendered"]=true; return self; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "render\x0a\x09rendered := true", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.TextViewSpy); $core.addMethod( $core.method({ selector: "results", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; return $self["@results"]; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "results\x0a\x09^ results", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.TextViewSpy); $core.addMethod( $core.method({ selector: "show", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; $self["@wasShown"]=true; return self; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "show\x0a\x09wasShown := true", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.TextViewSpy); $core.addMethod( $core.method({ selector: "showResults:", protocol: "as yet unclassified", fn: function (aCollection){ var self=this,$self=this; $self["@results"]=aCollection; return self; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["aCollection"], source: "showResults: aCollection \x0a\x09results := aCollection", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.TextViewSpy); $core.addMethod( $core.method({ selector: "wasShown", protocol: "as yet unclassified", fn: function (){ var self=this,$self=this; return $self["@wasShown"]; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "wasShown\x0a\x09^ wasShown", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.TextViewSpy); $core.addMethod( $core.method({ selector: "whenContinueDo:", protocol: "as yet unclassified", fn: function (aBlock){ var self=this,$self=this; $self["@onContinue"]=aBlock; return self; }, //>>excludeStart("ide", pragmas.excludeIdeData); args: ["aBlock"], source: "whenContinueDo: aBlock\x0a\x09onContinue := aBlock", referencedClasses: [], //>>excludeEnd("ide"); messageSends: [] }), $globals.TextViewSpy); $core.addClass("TextCopyTest", $globals.TestCase, ["spyView", "copy"], "OndafSimulator-Core-Tests"); $core.addMethod( $core.method({ selector: "setUp", protocol: "running", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); var $1; ( //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.supercall = true, //>>excludeEnd("ctx"); ($globals.TextCopyTest.superclass||$boot.nilAsClass).fn.prototype._setUp.apply($self, [])); //>>excludeStart("ctx", pragmas.excludeDebugContexts); $ctx1.supercall = false; //>>excludeEnd("ctx");; $self["@spyView"]=$recv($globals.TextViewSpy)._new(); $self["@copy"]=$recv($globals.CTestTextCopy)._newWithView_($self["@spyView"]); $1=$self["@copy"]; $recv($1)._time_((59)); $recv($1)._title_("The title"); $recv($1)._addText_("Some Text."); $recv($1)._addWordToComplete_("Plan ahea"); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"setUp",{},$globals.TextCopyTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "setUp\x0a\x09super setUp.\x0a\x09spyView := TextViewSpy new.\x0a\x09copy := CTestTextCopy newWithView: spyView.\x0a\x09copy\x0a\x09\x09time: 59;\x0a\x09\x09title: 'The title';\x0a\x09\x09addText: 'Some Text.';\x0a\x09\x09addWordToComplete: 'Plan ahea'.", referencedClasses: ["TextViewSpy", "CTestTextCopy"], //>>excludeEnd("ide"); messageSends: ["setUp", "new", "newWithView:", "time:", "title:", "addText:", "addWordToComplete:"] }), $globals.TextCopyTest); $core.addMethod( $core.method({ selector: "test01", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self._assert_equals_($recv($self["@spyView"])._printedText(),"|The title (59s)| Some Text. Plan ahea_ "); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test01",{},$globals.TextCopyTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test01\x09\x0a\x09self assert: spyView printedText equals: '|The title (59s)| Some Text. Plan ahea_ '", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["assert:equals:", "printedText"] }), $globals.TextCopyTest); $core.addMethod( $core.method({ selector: "test02", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $recv($self["@copy"])._giveToStudent(); $self._assert_($recv($self["@spyView"])._isRendered()); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test02",{},$globals.TextCopyTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test02\x0a\x09copy giveToStudent.\x0a\x09\x09\x0a\x09self assert: spyView isRendered", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["giveToStudent", "assert:", "isRendered"] }), $globals.TextCopyTest); $core.addMethod( $core.method({ selector: "test03", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $recv($self["@copy"])._giveToStudent(); $recv($self["@copy"])._finish(); $self._assert_($recv($recv($self["@spyView"])._isRendered())._not()); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test03",{},$globals.TextCopyTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test03\x09\x09\x0a\x09copy giveToStudent.\x0a\x09\x0a\x09copy finish.\x0a\x09\x09\x0a\x09self assert: spyView isRendered not", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["giveToStudent", "finish", "assert:", "not", "isRendered"] }), $globals.TextCopyTest); $core.addMethod( $core.method({ selector: "test04", protocol: "tests", fn: function (){ var self=this,$self=this; var executed; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); executed=false; $recv($self["@copy"])._whenFinishDo_((function(){ executed=true; return executed; })); $recv($self["@copy"])._giveToStudent(); $recv($self["@copy"])._finish(); $self._assert_(executed); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test04",{executed:executed},$globals.TextCopyTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test04\x0a\x09| executed |\x0a\x09executed := false.\x0a\x09\x0a\x09copy whenFinishDo: [ executed := true ].\x0a\x09copy giveToStudent.\x0a\x09copy finish.\x0a\x09\x09\x0a\x09self assert: executed", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["whenFinishDo:", "giveToStudent", "finish", "assert:"] }), $globals.TextCopyTest); $core.addMethod( $core.method({ selector: "test05", protocol: "tests", fn: function (){ var self=this,$self=this; var expectedAnswers; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); expectedAnswers=$recv($globals.Object)._new(); $recv($self["@spyView"])._answers_(expectedAnswers); $recv($self["@copy"])._giveToStudent(); $recv($self["@copy"])._finish(); $self._assert_equals_($recv($self["@copy"])._answers(),expectedAnswers); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test05",{expectedAnswers:expectedAnswers},$globals.TextCopyTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test05\x0a\x09| expectedAnswers |\x0a\x09expectedAnswers := Object new.\x0a\x09spyView answers: expectedAnswers.\x0a\x09\x0a\x09copy giveToStudent.\x0a\x09copy finish.\x0a\x09\x09\x0a\x09self assert: copy answers equals: expectedAnswers.", referencedClasses: ["Object"], //>>excludeEnd("ide"); messageSends: ["new", "answers:", "giveToStudent", "finish", "assert:equals:", "answers"] }), $globals.TextCopyTest); $core.addMethod( $core.method({ selector: "test06", protocol: "tests", fn: function (){ var self=this,$self=this; var resultStream; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); resultStream=[(1), (2), (3), (4)]._readStream(); $recv($self["@copy"])._addWordToComplete_("A second word to complete"); $recv($self["@copy"])._giveToStudent(); $recv($self["@copy"])._finish(); $recv($self["@copy"])._consumeResults_(resultStream); $self._assert_equals_($recv($self["@spyView"])._results(),[(1), (2)]); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test06",{resultStream:resultStream},$globals.TextCopyTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test06\x0a\x09| resultStream |\x0a\x09resultStream := #(1 2 3 4) readStream.\x0a\x09copy addWordToComplete: 'A second word to complete'.\x0a\x09copy giveToStudent.\x0a\x09copy finish.\x0a\x09copy consumeResults: resultStream.\x0a\x09\x09\x0a\x09self assert: spyView results equals: #(1 2).", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["readStream", "addWordToComplete:", "giveToStudent", "finish", "consumeResults:", "assert:equals:", "results"] }), $globals.TextCopyTest); $core.addMethod( $core.method({ selector: "test07", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $recv($self["@copy"])._giveToStudent(); $recv($self["@spyView"])._continue(); $self._assert_($recv($recv($self["@spyView"])._isRendered())._not()); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test07",{},$globals.TextCopyTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test07\x0a\x09copy giveToStudent.\x0a\x09spyView continue.\x0a\x09\x09\x0a\x09self assert: spyView isRendered not", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["giveToStudent", "continue", "assert:", "not", "isRendered"] }), $globals.TextCopyTest); $core.addMethod( $core.method({ selector: "test08", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $recv($self["@copy"])._giveToStudent(); $recv($self["@copy"])._finish(); $recv($self["@copy"])._giveBackToStudent(); $self._assert_($recv($self["@spyView"])._wasShown()); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test08",{},$globals.TextCopyTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test08\x09\x0a\x09copy giveToStudent.\x0a\x09copy finish.\x0a\x09\x0a\x09copy giveBackToStudent.\x0a\x09\x09\x0a\x09self assert: spyView wasShown", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["giveToStudent", "finish", "giveBackToStudent", "assert:", "wasShown"] }), $globals.TextCopyTest); $core.addMethod( $core.method({ selector: "test09", protocol: "tests", fn: function (){ var self=this,$self=this; //>>excludeStart("ctx", pragmas.excludeDebugContexts); return $core.withContext(function($ctx1) { //>>excludeEnd("ctx"); $self._assert_equals_($recv($self["@copy"])._timeInSeconds(),(59)); return self; //>>excludeStart("ctx", pragmas.excludeDebugContexts); }, function($ctx1) {$ctx1.fill(self,"test09",{},$globals.TextCopyTest)}); //>>excludeEnd("ctx"); }, //>>excludeStart("ide", pragmas.excludeIdeData); args: [], source: "test09\x0a\x09self assert: copy timeInSeconds equals: 59", referencedClasses: [], //>>excludeEnd("ide"); messageSends: ["assert:equals:", "timeInSeconds"] }), $globals.TextCopyTest); });
/** * Created by jaifar on 29/10/15. */ angular.module("otchi", []).controller("RecipeController", function ($scope, RecipeService) { $scope.recipesList = RecipeService.fetchAllRecipes(); $scope.addRecipe = function () { RecipeService.createRecipe($scope.recipe); $scope.recipe = {}; } }).service("RecipeService", function () { var db = [{description:"pastilla"},{description:"couscous"}, {description:"soupe"}]; this.createRecipe = function (recipe) { db.push(recipe); }; this.fetchAllRecipes = function () { return db; }; });
import React from 'react'; import { Well, Grid, Row, Col, Button } from 'react-bootstrap'; import ThemeSwitcher from './ThemeSwitcher'; import NewGameModal from './newGame/NewGameModal'; import SaveLoadGameModal from './saveLoadGame/SaveLoadGameModal'; export default class Header extends React.Component { constructor() { super(); this.state = { newGame: false, saveLoadGame: false }; } render() { return ( <Well bsSize='small'> <Grid> <div className='clearfix'> <h1 className='pull-left'> Nuzlog <small><small>v.{this.props.version}</small></small> </h1> <div className='pull-right'><ThemeSwitcher/></div> </div> <Row> <Col sm={6}> <Button bsStyle='primary' bsSize='large' block onClick={() => this.setState({newGame: true})}> New Game </Button> <NewGameModal show={this.state.newGame} onHide={() => this.setState({newGame: false})} /> </Col> <Col sm={6}> <Button bsStyle='primary' bsSize='large' block onClick={() => this.setState({saveLoadGame: true})}> Save/Load Game </Button> <SaveLoadGameModal show={this.state.saveLoadGame} onHide={() => this.setState({saveLoadGame: false})} /> </Col> </Row> </Grid> </Well> ); } }
define('pages.rooms', function () { var listRooms = require('pages.rooms.listRoomslistRooms'); });
import NodeController from '../controllers/node.server.controller'; module.exports = function(app){ app.route('/node/list').post(NodeController.nodeList); };
(function (exports) { 'use strict'; /** * Module : Sparrow extend enum * Author : Kvkens(yueming@yonyou.com) * Date : 2016-07-27 21:46:50 */ var U_LOCALE = "u_locale"; var enumerables = true; var enumerablesTest = { toString: 1 }; for(var i in enumerablesTest) { enumerables = null; } if(enumerables) { enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'constructor' ]; } /** * Module : Sparrow extend * Author : Kvkens(yueming@yonyou.com) * Date : 2016-07-27 21:46:50 */ /** * 复制对象属性 * * @param {Object} 目标对象 * @param {config} 源对象 */ var extend = function(object, config) { var args = arguments, options; if(args.length > 1) { for(var len = 1; len < args.length; len++) { options = args[len]; if(object && options && typeof options === 'object') { var i, j, k; for(i in options) { object[i] = options[i]; } if(enumerables) { for(j = enumerables.length; j--;) { k = enumerables[j]; if(options.hasOwnProperty && options.hasOwnProperty(k)) { object[k] = options[k]; } } } } } } return object; }; if(!Object.assign){ Object.assign = extend; } /** * Module : Sparrow touch event * Author : Kvkens(yueming@yonyou.com) * Date : 2016-07-28 14:41:17 */ var on = function(element, eventName, child, listener) { if(!element) return; if(arguments.length < 4) { listener = child; child = undefined; } else { var childlistener = function(e) { if(!e) { return; } var tmpchildren = element.querySelectorAll(child); tmpchildren.forEach(function(node) { if(node == e.target) { listener.call(e.target, e); } }); }; } //capture = capture || false; if(!element["uEvent"]) { //在dom上添加记录区 element["uEvent"] = {}; } //判断是否元素上是否用通过on方法填加进去的事件 if(!element["uEvent"][eventName]) { element["uEvent"][eventName] = [child ? childlistener : listener]; if(u.event && u.event[eventName] && u.event[eventName].setup) { u.event[eventName].setup.call(element); } element["uEvent"][eventName + 'fn'] = function(e) { //火狐下有问题修改判断 if(!e) e = typeof event != 'undefined' && event ? event : window.event; element["uEvent"][eventName].forEach(function(fn) { try { e.target = e.target || e.srcElement; //兼容IE8 } catch(ee) {} if(fn) fn.call(element, e); }); }; if(element.addEventListener) { // 用于支持DOM的浏览器 element.addEventListener(eventName, element["uEvent"][eventName + 'fn']); } else if(element.attachEvent) { // 用于IE浏览器 element.attachEvent("on" + eventName, element["uEvent"][eventName + 'fn']); } else { // 用于其它浏览器 element["on" + eventName] = element["uEvent"][eventName + 'fn']; } } else { //如果有就直接往元素的记录区添加事件 var lis = child ? childlistener : listener; var hasLis = false; element["uEvent"][eventName].forEach(function(fn) { if(fn == lis) { hasLis = true; } }); if(!hasLis) { element["uEvent"][eventName].push(child ? childlistener : listener); } } }; /** * Module : Sparrow dom * Author : Kvkens(yueming@yonyou.com) * Date : 2016-08-16 13:59:17 */ /** * 元素上是否存在该类 * @param {Object} element * @param {Object} value */ var hasClass = function(element, value) { if(!element) return false; if(element.nodeName && (element.nodeName === '#text' || element.nodeName === '#comment')) return false; if(typeof element.classList === 'undefined') { if(u._hasClass){ return u._hasClass(element, value); }else{ return $(element).hasClass(value); } return false; } else { return element.classList.contains(value); } }; /** * Module : Sparrow util tools * Author : Kvkens(yueming@yonyou.com) * Date : 2016-07-27 21:46:50 */ /** * 创建一个带壳的对象,防止外部修改 * @param {Object} proto */ var getFunction = function(target, val) { if(!val || typeof val == 'function') return val if(typeof target[val] == 'function') return target[val] else if(typeof window[val] == 'function') return window[val] else if(val.indexOf('.') != -1) { var func = getJSObject(target, val); if(typeof func == 'function') return func func = getJSObject(window, val); if(typeof func == 'function') return func } return val }; var getJSObject = function(target, names) { if(!names) { return; } if(typeof names == 'object') return names var nameArr = names.split('.'); var obj = target; for(var i = 0; i < nameArr.length; i++) { obj = obj[nameArr[i]]; if(!obj) return null } return obj }; var each = function(obj, callback) { if(obj.forEach) { obj.forEach(function(v, k) { callback(k, v); }); } else if(obj instanceof Object) { for(var k in obj) { callback(k, obj[k]); } } else { return; } }; try{ NodeList.prototype.forEach = Array.prototype.forEach; }catch(e){ } /** * 获得字符串的字节长度 */ String.prototype.lengthb = function() { // var str = this.replace(/[^\x800-\x10000]/g, "***"); var str = this.replace(/[^\x00-\xff]/g, "**"); return str.length; }; /** * 将AFindText全部替换为ARepText */ String.prototype.replaceAll = function(AFindText, ARepText) { //自定义String对象的方法 var raRegExp = new RegExp(AFindText, "g"); return this.replace(raRegExp, ARepText); }; /** * Module : Sparrow cookies * Author : Kvkens(yueming@yonyou.com) * Date : 2016-07-27 21:46:50 */ var getCookie = function(sName) { var sRE = "(?:; )?" + sName + "=([^;]*);?"; var oRE = new RegExp(sRE); if(oRE.test(document.cookie)) { return decodeURIComponent(RegExp["$1"]); } else return null; }; /** * Module : Sparrow i18n * Author : Kvkens(yueming@yonyou.com) * Date : 2016-07-29 10:16:54 */ //import {uuii18n} from '?';//缺失故修改为default值 // 从datatable/src/compatiable/u/JsExtension.js抽取 window.getCurrentJsPath = function() { var doc = document, a = {}, expose = +new Date(), rExtractUri = /((?:http|https|file):\/\/.*?\/[^:]+)(?::\d+)?:\d+/, isLtIE8 = ('' + doc.querySelector).indexOf('[native code]') === -1; // FF,Chrome if (doc.currentScript){ return doc.currentScript.src; } var stack; try{ a.b(); } catch(e){ stack = e.stack || e.fileName || e.sourceURL || e.stacktrace; } // IE10 if (stack){ var absPath = rExtractUri.exec(stack)[1]; if (absPath){ return absPath; } } // IE5-9 for(var scripts = doc.scripts, i = scripts.length - 1, script; script = scripts[i--];){ if (script.className !== expose && script.readyState === 'interactive'){ script.className = expose; // if less than ie 8, must get abs path by getAttribute(src, 4) return isLtIE8 ? script.getAttribute('src', 4) : script.src; } } }; if (window.i18n) { window.u = window.u || {}; var scriptPath = getCurrentJsPath(), _temp = scriptPath.substr(0, scriptPath.lastIndexOf('/')), __FOLDER__ = _temp.substr(0, _temp.lastIndexOf('/')), resGetPath = u.i18nPath || __FOLDER__ + '/locales/__lng__/__ns__.json'; i18n.init({ postAsync: false, getAsync: false, fallbackLng: false, ns: {namespaces: ['uui-trans']}, lng:getCookie(U_LOCALE) || 'zh', resGetPath: resGetPath }); } var trans = function (key, dftValue) { return window.i18n ? i18n.t('uui-trans:' + key) : dftValue }; /** * Module : neoui-pagination * Author : Kvkens(yueming@yonyou.com) * Date : 2016-08-03 08:45:49 */ var pagination = u.BaseComponent.extend({ }); var PageProxy = function(options, page) { this.isCurrent = function() { return page == options.currentPage; }; this.isFirst = function() { return page == 1; }; this.isLast = function() { return page == options.totalPages; }; this.isPrev = function() { return page == (options.currentPage - 1); }; this.isNext = function() { return page == (options.currentPage + 1); }; this.isLeftOuter = function() { return page <= options.outerWindow; }; this.isRightOuter = function() { return (options.totalPages - page) < options.outerWindow; }; this.isInsideWindow = function() { if (options.currentPage < options.innerWindow + 1) { return page <= ((options.innerWindow * 2) + 1); } else if (options.currentPage > (options.totalPages - options.innerWindow)) { return (options.totalPages - page) <= (options.innerWindow * 2); } else { return Math.abs(options.currentPage - page) <= options.innerWindow; } }; this.number = function() { return page; }; this.pageSize = function() { return options.pageSize; }; }; var View = { firstPage: function(pagin, options, currentPageProxy) { return '<li role="first"' + (currentPageProxy.isFirst() ? 'class="disabled"' : '') + '><a >' + options.first + '</a></li>'; }, prevPage: function(pagin, options, currentPageProxy) { return '<li role="prev"' + (currentPageProxy.isFirst() ? 'class="disabled"' : '') + '><a rel="prev">' + options.prev + '</a></li>'; }, nextPage: function(pagin, options, currentPageProxy) { return '<li role="next"' + (currentPageProxy.isLast() ? 'class="disabled"' : '') + '><a rel="next">' + options.next + '</a></li>'; }, lastPage: function(pagin, options, currentPageProxy) { return '<li role="last"' + (currentPageProxy.isLast() ? 'class="disabled"' : '') + '><a >' + options.last + '</a></li>'; }, gap: function(pagin, options) { return '<li role="gap" class="disabled"><a >' + options.gap + '</a></li>'; }, page: function(pagin, options, pageProxy) { return '<li role="page"' + (pageProxy.isCurrent() ? 'class="active"' : '') + '><a ' + (pageProxy.isNext() ? ' rel="next"' : '') + (pageProxy.isPrev() ? 'rel="prev"' : '') + '>' + pageProxy.number() + '</a></li>'; } }; //pagination.prototype.compType = 'pagination'; pagination.prototype.init = function(element, options) { var self = this; var element = this.element; this.$element = element; this.options = extend({}, this.DEFAULTS, this.options); this.$ul = this.$element; //.find("ul"); this.render(); }; pagination.prototype.DEFAULTS = { currentPage: 1, totalPages: 1, pageSize: 10, pageList: [5, 10, 20, 50, 100], innerWindow: 2, outerWindow: 0, first: '&laquo;', prev: '<i class="uf uf-anglepointingtoleft"></i>', next: '<i class="uf uf-anglearrowpointingtoright"></i>', last: '&raquo;', gap: '···', //totalText: '合计:', totalText: trans('pagination.totalText', '共'), listText: trans('pagination.listText', '条'), showText: trans('pagination.showText', '显示'), pageText: trans('pagination.pageText', '页'), toText: trans('pagination.toText', '到'), okText: trans('public.ok', '确定'), truncate: false, showState: true, showTotal: true, //初始默认显示总条数 “共xxx条” showColumn: true, //初始默认显示每页条数 “显示xx条” showJump: true, //初始默认显示跳转信息 “到xx页 确定”, showBtnOk: true, //初始默认显示确定按钮 page: function(page) { return true; } }; pagination.prototype.update = function(options) { this.$ul.innerHTML = ""; this.options = extend({}, this.options, options); this.render(); }; pagination.prototype.render = function() { var a = (new Date()).valueOf(); var options = this.options; if (!options.totalPages) { this.$element.style.display = "none"; return; } else { this.$element.style.display = "block"; } var htmlArr = []; var currentPageProxy = new PageProxy(options, options.currentPage); //update pagination by pengyic@yonyou.com //预设显示页码数 var windows = 2; var total = options.totalPages - 0; var current = options.currentPage - 0; //预设显示页码数截断修正 var fix = 0; var pageProxy; if (current - 2 <= windows + 1) { for (var i = 1; i <= current; i++) { pageProxy = new PageProxy(options, i); htmlArr.push(View.page(this, options, pageProxy)); } fix = windows - (current - 1) < 0 ? 0 : windows - (current - 1); if (total - current - fix <= windows + 1) { for (var i = current + 1; i <= total; i++) { pageProxy = new PageProxy(options, i); htmlArr.push(View.page(this, options, pageProxy)); } } else { for (var i = current + 1; i <= current + windows + fix; i++) { pageProxy = new PageProxy(options, i); htmlArr.push(View.page(this, options, pageProxy)); } //添加分割'...' htmlArr.push(View.gap(this, options)); pageProxy = new PageProxy(options, total); htmlArr.push(View.page(this, options, pageProxy)); } } else { if (total - current <= windows + 1) { fix = windows - (total - current) < 0 ? 0 : windows - (total - current); for (var i = current - windows - fix; i <= total; i++) { pageProxy = new PageProxy(options, i); htmlArr.push(View.page(this, options, pageProxy)); } if (i >= 2) { //添加分割'...' htmlArr.unshift(View.gap(this, options)); pageProxy = new PageProxy(options, 1); htmlArr.unshift(View.page(this, options, pageProxy)); } } else { for (var i = current - windows; i <= current + windows; i++) { pageProxy = new PageProxy(options, i); htmlArr.push(View.page(this, options, pageProxy)); } //添加分割'...' htmlArr.push(View.gap(this, options)); pageProxy = new PageProxy(options, total); htmlArr.push(View.page(this, options, pageProxy)); //添加分割'...' htmlArr.unshift(View.gap(this, options)); pageProxy = new PageProxy(options, 1); htmlArr.unshift(View.page(this, options, pageProxy)); } } htmlArr.unshift(View.prevPage(this, options, currentPageProxy)); htmlArr.push(View.nextPage(this, options, currentPageProxy)); if (options.totalCount === undefined || options.totalCount <= 0) { options.totalCount = 0; } if (options.showState) { // 处理pageOption字符串 var pageOption = ''; options.pageList.forEach(function(item) { if (options.pageSize - 0 == item) { pageOption += '<option selected>' + item + '</option>'; } else { pageOption += '<option>' + item + '</option>'; } }); var htmlTmp = ''; //分别得到分页条后“共xxx条”、“显示xx条”、“到xx页 确定”三个html片段 if (options.showTotal) { htmlTmp += '<div class="pagination-state">' + options.totalText + '&nbsp;' + options.totalCount + '&nbsp;' + options.listText + '</div>'; } if (options.showColumn) { if (hasClass(this.$ul, 'pagination-sm')) { htmlTmp += '<div class="pagination-state">' + options.showText + '<select class="page_z page_z_sm">' + pageOption + '</select>' + options.listText + '</div>'; } else if (hasClass(this.$ul, 'pagination-lg')) { htmlTmp += '<div class="pagination-state">' + options.showText + '<select class="page_z page_z_lg">' + pageOption + '</select>' + options.listText + '</div>'; } else { htmlTmp += '<div class="pagination-state">' + options.showText + '<select class="page_z">' + pageOption + '</select>' + options.listText + '</div>'; } } if (options.showJump) { if (options.showBtnOk) { if (hasClass(this.$ul, 'pagination-sm')) { htmlTmp += '<div class="pagination-state"><span>' + options.toText + '</span><input class="page_j text-center page_j_sm padding-left-0" value=' + options.currentPage + '><span>' + options.pageText + '</span><input class="pagination-jump pagination-jump-sm" type="button" value="' + options.okText + '"/></div>'; } else if (hasClass(this.$ul, 'pagination-lg')) { htmlTmp += '<div class="pagination-state"><span>' + options.toText + '</span><input class="page_j text-center page_j_lg padding-left-0" value=' + options.currentPage + '><span>' + options.pageText + '</span><input class="pagination-jump pagination-jump-lg" type="button" value="' + options.okText + '"/></div>'; } else { htmlTmp += '<div class="pagination-state"><span>' + options.toText + '</span><input class="page_j text-center padding-left-0" value=' + options.currentPage + '><span>' + options.pageText + '</span><input class="pagination-jump" type="button" value="' + options.okText + '"/></div>'; } } else { if (hasClass(this.$ul, 'pagination-sm')) { htmlTmp += '<div class="pagination-state"><span>' + options.toText + '</span><input class="page_j text-center padding-left-0" value=' + options.currentPage + '><span>' + options.pageText + '</span></div>'; } else if (hasClass(this.$ul, 'pagination-lg')) { htmlTmp += '<div class="pagination-state"><span>' + options.toText + '</span><input class="page_j text-center padding-left-0" value=' + options.currentPage + '><span>' + options.pageText + '</span></div>'; } else { htmlTmp += '<div class="pagination-state"><span>' + options.toText + '</span><input class="page_j text-center padding-left-0" value=' + options.currentPage + '><span>' + options.pageText + '</span></div>'; } } } htmlArr.push(htmlTmp); } //在将htmlArr插入到页面之前,对htmlArr进行处理 this.$ul.innerHTML = ""; this.$ul.insertAdjacentHTML('beforeEnd', htmlArr.join('')); var me = this; //对分页控件中的确定按钮和输入页码按回车键添加的统一调用方法 function paginationAddEventListen() { var jp, pz; jp = me.$ul.querySelector(".page_j").value || options.currentPage; pz = me.$ul.querySelector(".page_z").value || options.pageSize; if (isNaN(jp)) return; //if (pz != options.pageSize){ // me.$element.trigger('sizeChange', [pz, jp - 1]) //}else{ // me.$element.trigger('pageChange', jp - 1) //} me.page(jp, options.totalPages, pz); //me.$element.trigger('pageChange', jp - 1) //me.$element.trigger('sizeChange', pz) return false; } on(this.$ul.querySelector(".pagination-jump"), "click", function() { paginationAddEventListen(); }); on(this.$ul.querySelector(".page_j"), "keydown", function(event) { if (event.keyCode == '13') { paginationAddEventListen(); } }); on(this.$ul.querySelector('[role="first"] a'), 'click', function() { if (options.currentPage <= 1) return; me.firstPage(); //me.$element.trigger('pageChange', 0) return false; }); on(this.$ul.querySelector('[role="prev"] a'), 'click', function() { if (options.currentPage <= 1) return; me.prevPage(); //me.$element.trigger('pageChange', options.currentPage - 1) return false; }); on(this.$ul.querySelector('[role="next"] a'), 'click', function() { if (parseInt(options.currentPage) + 1 > options.totalPages) return; me.nextPage(); //me.$element.trigger('pageChange', parseInt(options.currentPage) + 1) return false; }); on(this.$ul.querySelector('[role="last"] a'), 'click', function() { if (options.currentPage == options.totalPages) return; me.lastPage(); //me.$element.trigger('pageChange', options.totalPages - 1) return false; }); each(this.$ul.querySelectorAll('[role="page"] a'), function(i, node) { on(node, 'click', function() { var pz = (me.$element.querySelector(".page_z") && $(this).val()) || options.pageSize; me.page(parseInt(this.innerHTML), options.totalPages, pz); //me.$element.trigger('pageChange', parseInt($(this).html()) - 1) return false; }); }); on(this.$ul.querySelector('.page_z'), 'change', function() { var pz = (me.$element.querySelector(".page_z") && $(this).val()) || options.pageSize; me.trigger('sizeChange', pz); }); }; pagination.prototype.page = function(pageIndex, totalPages, pageSize) { var options = this.options; if (totalPages === undefined) { totalPages = options.totalPages; } if (pageSize === undefined) { pageSize = options.pageSize; } var oldPageSize = options.pageSize; // if (pageIndex > 0 && pageIndex <= totalPages) { // if (options.page(pageIndex)) { // this.$ul.innerHTML=""; // options.pageSize = pageSize; // options.currentPage = pageIndex; // options.totalPages = totalPages; // this.render(); // } // }else{ // return false; // } if (options.page(pageIndex)) { if (pageIndex <= 0) { pageIndex = 1; } if (pageIndex > totalPages) { pageIndex = totalPages; } this.$ul.innerHTML = ""; options.pageSize = pageSize; options.currentPage = pageIndex; options.totalPages = totalPages; this.render(); } var temppageIndex = (pageIndex - 1) < 0 ? 0 : (pageIndex - 1); if (pageSize != oldPageSize) { this.trigger('sizeChange', [pageSize, temppageIndex]); } else { this.trigger('pageChange', temppageIndex); } //this.$element.trigger('pageChange', pageIndex) return false; }; pagination.prototype.firstPage = function() { return this.page(1); }; pagination.prototype.lastPage = function() { return this.page(this.options.totalPages); }; pagination.prototype.nextPage = function() { return this.page(parseInt(this.options.currentPage) + 1); }; pagination.prototype.prevPage = function() { return this.page(this.options.currentPage - 1); }; pagination.prototype.disableChangeSize = function() { this.$element.querySelector('.page_z').setAttribute('readonly', true); }; pagination.prototype.enableChangeSize = function() { this.$element.querySelector('.page_z').removeAttribute('readonly'); }; // var old = $.fn.pagination; // $.fn.pagination = Plugin // $.fn.pagination.Constructor = Pagination if (u.compMgr) u.compMgr.regComp({ comp: pagination, compAsString: 'u.pagination', css: 'u-pagination' }); /** * Module : Kero pagination * Author : Kvkens(yueming@yonyou.com) * Date : 2016-08-09 19:09:39 */ var PaginationAdapter = u.BaseAdapter.extend({ mixins: [], init: function() { var self = this; if (!this.dataModel.pageSize() && this.options.pageSize) this.dataModel.pageSize(this.options.pageSize); this.options.pageSize = this.dataModel.pageSize() || this.options.pageSize; var options = extend({}, { el: this.element }, this.options); this.comp = new pagination(options); this.element['u.pagination'] = this.comp; this.comp.dataModel = this.dataModel; this.pageChange = getFunction(this.viewModel, this.options['pageChange']); this.sizeChange = getFunction(this.viewModel, this.options['sizeChange']); this.comp.on('pageChange', function(pageIndex) { self.defaultPageChange(pageIndex); if (typeof self.pageChange == 'function') { self.pageChange(pageIndex); } }); this.comp.on('sizeChange', function(size, pageIndex) { self.defaultSizeChange(size, pageIndex); if (typeof self.sizeChange == 'function') { self.sizeChange(size, pageIndex); } }); this.dataModel.totalPages.subscribe(function(value) { self.comp.update({ totalPages: value }); }); this.dataModel.pageSize.subscribe(function(value) { self.comp.update({ pageSize: value }); }); this.dataModel.pageIndex.subscribe(function(value) { self.comp.update({ currentPage: value + 1 }); }); this.dataModel.totalRow.subscribe(function(value) { self.comp.update({ totalCount: value }); }); if (this.comp.options.pageList.length > 0) { this.comp.options.pageSize = this.comp.options.pageList[0]; ///this.comp.trigger('sizeChange', options.pageList[0]) var checkIndex = 0; var defalutPageSize = this.comp.dataModel.pageSize(); if (defalutPageSize > 0) { checkIndex = this.comp.options.pageList.indexOf(defalutPageSize); } checkIndex = checkIndex < 0 ? 0 : checkIndex; this.dataModel.pageSize(this.comp.options.pageList[checkIndex]); } // 如果datatable已经创建则根据datatable设置分页组件 // self.comp.update({totalPages: this.dataModel.totalPages()}) // self.comp.update({pageSize: this.dataModel.pageSize()}) // self.comp.update({currentPage: this.dataModel.pageIndex() + 1}) // self.comp.update({totalCount: this.dataModel.totalRow()}) self.comp.update({ totalPages: this.dataModel.totalPages(), pageSize: this.dataModel.pageSize(), currentPage: this.dataModel.pageIndex() + 1, totalCount: this.dataModel.totalRow() }); }, defaultPageChange: function(pageIndex) { this.dataModel.pageIndex(pageIndex); if (this.dataModel.hasPage(pageIndex)) { this.dataModel.setCurrentPage(pageIndex); } else {} }, defaultSizeChange: function(size, pageIndex) { this.dataModel.pageSize(size); }, disableChangeSize: function() { this.comp.disableChangeSize(); }, enableChangeSize: function() { this.comp.enableChangeSize(); } }); if (u.compMgr) u.compMgr.addDataAdapter({ adapter: PaginationAdapter, name: 'pagination' }); exports.PaginationAdapter = PaginationAdapter; }((this.bar = this.bar || {})));
var seneca = require('../seneca-client') var sequelize = require('../sequelize').default var Vendor = sequelize.model('Vendor') var services = require('../openprices-services') var Products = services.products var Vendors = services.vendors export function getVendors(req, res, next) { Vendor.all().then(vendors => { return vendors.map(VendorModelInterface) }).then(data => { res.json({ data }) }).catch(err => { next(err) }) } export function getVendor(req, res, next) { var { id } = req.params Vendor.findById(id).then(VendorModelInterface).then(data => { return res.json({ data }) return require('../lib/Vendors').getVendorInfo(data.code).catch(err => { res.json({ errors : [err], data }) throw err }).then(persona => { res.json({ afip : persona, data }) }) }) } function VendorModelInterface(v) { return VendorInterface(v.get()) } function VendorInterface(v) { var obj = { id: v.id, code: v.code, name: v.name, address: v.address } return obj } function PriceModelInterface(pr) { return PriceInterface(pr.get()) } function PriceInterface(pr) { var obj = { price: pr.price, date: pr.date, vendor: pr.VendorId, user: pr.UserId } return obj }
API = { authentication: function(apiKey){ return apiKey === Meteor.settings.PNCTSRC_ACCESS_KEY; }, connection: function(request){ var getRequestContents = API.utility.getRequestContents(request), apiKey = getRequestContents.api_key, validUser = API.authentication(apiKey); if(validUser){ delete getRequestContents.api_key; return { data: getRequestContents } } else { return { error: 401, message: "Invalid access key." } } }, handleRequest: function(context, resource, method){ var connection = API.connection(context.request); if(!connection.error){ API.methods[resource][method](context, connection); } else { API.utility.response(context, 401, connection); } }, methods: { search: { GET: function(context, connection){ const keyword = connection.data.keyword.replace(/[^a-z0-9]/gi, "\\$&"); if(keyword.match(/^ *$/gi)){ API.utility.sendError(context, 400, "Invalid keyword"); return; } const search_regex = new RegExp(keyword, "gi"); const post_title_array = Posts.find({title: {$regex: search_regex}}, {fields: {title: 1, description: 1}}).fetch(); const work_title_array = Works.find({title: {$regex: search_regex}}, {fields: {title: 1, description: 1}}).fetch(); const result = { post_result: post_title_array, work_result: work_title_array }; API.utility.response(context, 200, result); }, POST: function(context, connection){}, PUT: function(context, connection){}, DELETE: function(context, connection){} }, images: { GET: function(context, connection){ const fileName = connection.data.fileName; //validate type const fileType = fileName.substring(fileName.lastIndexOf(".") + 1); if(!fileName.match(/\./)){ API.utility.responseIMG(context, 400, { error: 400, message: "Invalid file name." }, true) } else if (_.indexOf(Meteor.settings.ALLOWED_IMAGE_TYPE, fileType) === -1){ API.utility.responseIMG(context, 400, { error: 400, message: "Invalid file type." }, true) } else { //check if the image exists const fs = require("fs"); if(fs.existsSync(Meteor.settings.IMAGE_PATH + fileName)){ const data = fs.readFileSync(Meteor.settings.IMAGE_PATH + fileName); API.utility.responseIMG(context, 200, data, false, fileType); } else { API.utility.responseIMG(context, 404, { error: 404, message: "No such image." }, true) } } }, POST: function(context, connection){ var Busboy = require('busboy'); var path = require('path'); var fs = require('fs'); var busboy = new Busboy({headers: context.request.headers}); var final_filename; var ifError = false;//true if any error happens later busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { const fileExtension = mimetype.substring(6).replace("e", ""); //validate the file var file_size = 0; file.on('data', function(data){ file_size += data.length; if(ifError) return; if(file_size > 10485760){ API.utility.sendError(context, 400, "Image size larger than 10MB."); ifError = true; } }) if(_.indexOf(Meteor.settings.ALLOWED_IMAGE_TYPE, fileExtension) === -1){ API.utility.sendError(context, 400, "Image type not allowed."); ifError = true; } final_filename = (new Date()).getTime() + "." + fileExtension; var saveTo = Meteor.settings.IMAGE_PATH + final_filename; if(ifError) { if(fs.existsSync(saveTo)){ fs.unlinkSync(saveTo); } return; } file.pipe(fs.createWriteStream(saveTo)); }); busboy.on('finish', function() { if(ifError) return; API.utility.response(context, 200, {link: "/resources/images/" + final_filename}); }); context.request.pipe(busboy); }, PUT: function(context, connection){}, DELETE: function(context, connection){ var fs = require('fs'); const fileName = connection.data.src.substring(connection.data.src.lastIndexOf('/') + 1); const path = Meteor.settings.IMAGE_PATH + fileName; //check if the file exists if(fs.existsSync(path)){ fs.unlinkSync(path); API.utility.response(context, 200, {message: "Success."}); } else { API.utility.sendError(context, 404, "No such Image"); } } }, files: { GET: function(context, connection){ const fileName = connection.data.fileName; //validate type const fileType = fileName.substring(fileName.lastIndexOf(".") + 1); if(!fileName.match(/\./)){ API.utility.responseFILE(context, 400, { error: 400, message: "Invalid file name." }, true) } else if (_.indexOf(Meteor.settings.ALLOWED_FILE_TYPE, fileType) === -1){ API.utility.responseFILE(context, 400, { error: 400, message: "Invalid file type." }, true) } else { //check if the image exists const fs = require("fs"); if(fs.existsSync(Meteor.settings.FILE_PATH + fileName)){ const data = fs.readFileSync(Meteor.settings.FILE_PATH + fileName); if(fileType === "pdf"){ API.utility.responsePDF(context, 200, data); } else if(fileType === "mp3" || fileType === "mp4"){ var stat = fs.statSync(Meteor.settings.FILE_PATH + fileName); API.utility.responseMEDIA(context, 200, data, fileType, stat.size); } else { API.utility.responseFILE(context, 200, data, false); } } else { API.utility.responseFILE(context, 404, { error: 404, message: "No such file." }, true) } } }, POST: function(context, connection){ var Busboy = require('busboy'); var path = require('path'); var fs = require('fs'); var busboy = new Busboy({headers: context.request.headers}); var final_filename; var ifError = false;//true if any error happens later busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { //validate the file if(!filename.match(/\./)){ API.utility.sendError(context, 400, "Invalid file name."); ifError = true; } else { var regex_string = "("; for(var type of Meteor.settings.ALLOWED_FILE_TYPE){ regex_string += type + "|"; } regex_string = regex_string.substring(0, regex_string.length - 1) + ")"; var type_regex = new RegExp(regex_string); if(!filename.substring(filename.lastIndexOf(".") + 1).match(type_regex)){ API.utility.sendError(context, 400, "File type not allowed."); ifError = true; } } var saveTo = Meteor.settings.FILE_PATH + filename; if(fs.existsSync(saveTo)){ API.utility.sendError(context, 400, "File already exists."); ifError = true; } var file_size = 0; file.on('data', function(data){ file_size += data.length; if(file_size > 10485760){ API.utility.sendError(context, 400, "File size larger than 10MB."); ifError = true; } }) if(ifError) return; file.pipe(fs.createWriteStream(saveTo)); final_filename = filename; }); busboy.on('finish', function() { if(ifError) return; API.utility.response(context, 200, {link: "/resources/files/" + final_filename}); }); context.request.pipe(busboy); }, PUT: function(context, connection){}, DELETE: function(context, connection){ var fs = require('fs'); const fileName = connection.data.filename; const path = Meteor.settings.FILE_PATH + fileName; //check if the file exists if(fs.existsSync(path)){ fs.unlinkSync(path); API.utility.response(context, 200, {message: "Success."}); } else { API.utility.sendError(context, 404, "No such file."); } } } }, resources: {}, utility: { getRequestContents: function(request){ switch (request.method){ case "GET": case "POST": return request.query; case "PUT": case "DELETE": return request.body; } }, hasData: function(data){ return Object.keys(data).length > 0 ? true : false; }, response: function(context, statusCode, data){ context.response.setHeader('Content-Type', 'application/json'); context.response.statusCode = statusCode; context.response.end(JSON.stringify(data)); }, validate: function(data, pattern){ return Match.test(data, pattern); }, sendError: function(context, statusCode, message){ API.utility.response(context, statusCode, { error: 400, message: message }); }, responseIMG: function(context, statusCode, data, hasErr, fileType){ context.response.statusCode = statusCode; if(hasErr){ context.response.setHeader('Content-Type', 'application/json'); context.response.end(JSON.stringify(data)); } else { context.response.setHeader('Content-Type', 'image/' + fileType.replace("e", "")); context.response.end(data); } }, responseFILE: function(context, statusCode, data, hasErr){ context.response.statusCode = statusCode; if(hasErr){ context.response.setHeader('Content-Type', 'application/json'); context.response.end(JSON.stringify(data)); } else { context.response.setHeader('Content-Type', 'application/octet-stream'); context.response.end(data); } }, responsePDF: function(context, statusCode, data){ context.response.statusCode = statusCode; context.response.setHeader('Content-Type', 'application/pdf'); context.response.end(data); }, responseMEDIA: function(context, statusCode, data, fileType, size){ context.response.statusCode = statusCode; context.response.setHeader('Content-Length', size); context.response.setHeader('Accept-Ranges', 'bytes'); if(fileType === "mp4"){ context.response.setHeader('Content-Type', 'video/mp4'); } else if(fileType === "mp3"){ context.response.setHeader('Content-Type', 'audio/mp3'); } context.response.end(data); }, } };
Package.describe({ summary: "Intercom package" }); Package.on_use(function (api) { api.add_files('intercom.js', 'client'); if(api.export) api.export('Intercom'); });
function AngularParser(fileContents) { this.fileContents = fileContents; this.result = null; } AngularParser.prototype.PATTERNS = { name: function function_name(type) { return new RegExp(type + '\\s*\\([\'"](\\w+)[\'"]\\s*,\\s*(.*?)|[(\'")]', 'g'); }, dependencies: { array: function (name, type) { return new RegExp(type + '[\\r\\n\\s]*?\\([\\r\\n\\s]*?[\'"]' + name + '[\'"][\\r\\n\\s]*?,[\\r\\n\\s]*?\\[([\'"$_a-zA-Z,\\n\\s]*?)function', 'g'); }, inline: function (name, type) { return new RegExp(type + '[\\r\\n\\s]*?\\([\\r\\n\\s]*?[\'"]' + name + '[\'"][\\r\\n\\s]*?,[\\r\\n\\s]*?function[\\r\\n\\s\\w]*?\\(([\'"$_a-zA-Z,\\n\\s]*?)\\)', 'g'); }, inject: function (name) { return new RegExp(name + '\\$inject[\\s\\S]*?=[\\s\\S]*?\\[([\\s\\S]*?)\\]', 'gm'); } } }; AngularParser.prototype.COMPONENTS = { directive: { typeRegExp: 'directive', type: 'directive' }, controller: { typeRegExp: 'controller', type: 'controller' }, filter: { typeRegExp: 'filter', type: 'filter' }, service: { typeRegExp: '(?:factory|service)', type: 'service' } }; AngularParser.prototype.parse = function () { var content = this.fileContents, components = this.COMPONENTS, self = this, result = []; Object.keys(components).forEach(function (component) { result = result.concat(self.parseComponent(content, component)); }); this.result = result; }; AngularParser.prototype.parseComponent = function (file, componentType) { function getDependencyArray(dependenciesString) { var parts = dependenciesString.split(','), result = []; parts.forEach(function (d) { d = d.replace(/['"\s]/g, ''); if (d) result.push(d); }); return result; } var component = this.COMPONENTS[componentType], componentPattern = component.typeRegExp, patterns = this.PATTERNS, namePattern = patterns.name(componentPattern), paramRegExps = 'array inject inline', result = [], currentDependenciesPattern, dependencyString, matches, name, componentName, dependencyArray; while (matches = namePattern.exec(file)) { dependencyString = null; name = matches[1]; if (!name) continue; // Starting with the once with hightest priority: // Array // $inject // function paramRegExps.split(' ').forEach(function (rName) { componentName = name; if (rName === 'inject') { componentName = matches[2]; //the name of the object } currentDependenciesPattern = patterns.dependencies[rName](componentName, componentPattern); dependencyArray = currentDependenciesPattern.exec(file); if (dependencyArray && dependencyArray[1]) { dependencyString = dependencyArray[1]; return; } }); if (!dependencyString) { console.warn('Cannot find the dependencies for', name); } else { dependencyArray = getDependencyArray(dependencyString); result.push({ name: name, type: component.type, dependencies: dependencyArray }); } } return result; }; module.exports = AngularParser;
/** * Bootstrap Table Indonesian translation * Author: Andre Gardiner<andre@sirdre.com> */ (function ($) { 'use strict'; $.fn.bootstrapTable.locales['id-ID'] = { formatLoadingMessage: function () { return 'Memuat, mohon tunggu...'; }, formatRecordsPerPage: function (pageNumber) { return pageNumber + ' baris per halaman'; }, formatShowingRows: function (pageFrom, pageTo, totalRows) { return 'Menampilkan ' + pageFrom + ' sampai ' + pageTo + ' dari ' + totalRows + ' baris'; }, formatSearch: function () { return 'Pencarian'; }, formatNoMatches: function () { return 'Tidak ditemukan data yang cocok'; }, formatPaginationSwitch: function () { return 'Sembunyikan/Tampilkan halaman'; }, formatRefresh: function () { return 'Muat ulang'; }, formatToggle: function () { return 'Beralih'; }, formatColumns: function () { return 'kolom'; }, formatAllRows: function () { return 'Semua'; }, formatExport: function () { return 'Ekspor data'; }, formatClearFilters: function () { return 'Bersihkan filter'; } }; $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['id-ID']); })(jQuery);
import express from 'express'; import bodyParser from 'body-parser'; import http from 'http'; export default function setupApi(customPort, database, callback) { const app = express(); const httpServer = http.createServer(app); app.use(bodyParser.json()); app.get('/snapshots', (req, res)=> { let query = {}; if (req.query.key) { query = { name: new RegExp(req.query.key), }; } database.find(query).sort({ createdAt: -1 }).exec((err, docs) => { res.json(docs); }); }); app.post('/snapshots', (req, res)=> { const name = req.body.name; const data = req.body.data; const createdAt = new Date(); database.insert({ name: name, data: data, createdAt: createdAt, }, (err, doc) => { res.status(201).json(doc); }); }); return httpServer.listen(customPort, callback); }
$(document).ready(function(){ $('.person:first').trigger('click'); var personName = $('.person:first').find('.name').text(); $('.right .top .name').html(personName); var userImage = $('.person:first').find('.userimage').html(); $('.right .top .userimage').html(userImage); var hideContent = $('.person:first').find('.hidecontent').html(); $('.right .hidecontent').html(hideContent); }); $('.left .person').mousedown(function(){ if ($(this).hasClass('.active')) { return false; } else { var findChat = $(this).attr('data-chat'); var personName = $(this).find('.name').text(); $('.right .top .name').html(personName); var userImage = $(this).find('.userimage').html(); $('.right .top .userimage').html(userImage); var hideContent = $(this).find('.hidecontent').html(); $('.right .hidecontent').html(hideContent); $('.chat').removeClass('active-chat'); $('.left .person').removeClass('active'); $(this).addClass('active'); $('.chat[data-chat = '+findChat+']').addClass('active-chat'); } });
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2015-2016 Rick Wargo. All Rights Reserved. // // Licensed under the MIT License (the "License"). You may not use this file // except in compliance with the License. A copy of the License is located at // http://opensource.org/licenses/MIT or in the "LICENSE" file accompanying // this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES // OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. //////////////////////////////////////////////////////////////////////////////// /*jslint node: true */ /*jslint todo: true */ 'use strict'; var DynamoDB = require('./dynamodb'), Config = require('../../config/lambda-config'), promise = require('bluebird'), Text = require('./text'); if (!process.env.SERVER || process.env.SERVER !== 'Local') { // Provide long stack traces when running locally (in active development mode) promise.longStackTraces(); } var intentFuncs = { handleAppIntent: function (request, response) { var slotThing = request.slot('SlotName', 'default'), failed = false; function log() { DynamoDB.log(slotThing, request.userId); } // Failure path for intent if (failed) { response .say(Text.failedResponse) .card('Problem', Text.failedResponse) .shouldEndSession(true) .send(); return promise.reject(); } response .say(Text.defaultResponse) .card(Config.applicationName, Text.defaultResponse) .shouldEndSession(true); if (!process.env.SERVER || process.env.SERVER !== 'Local') { // Don't log in active development mode log(); } return promise.resolve(); } }; // Allow this module to be reloaded by hotswap when changed module.change_code = 1; module.exports = intentFuncs;
class tvratings_evalrat_1 { constructor() { // int BlockedRatingAttributes (EnTvRat_System, EnTvRat_GenericLevel) {ge... this.Parameterized = undefined; // int BlockUnRated () {get} {set} this.BlockUnRated = undefined; } // void MostRestrictiveRating (EnTvRat_System, EnTvRat_GenericLevel, int,... MostRestrictiveRating() { } // void TestRating (EnTvRat_System, EnTvRat_GenericLevel, int) TestRating(EnTvRat_System, EnTvRat_GenericLevel, int) { } } module.exports = tvratings_evalrat_1;
var pix = []; var myCanvas; var glob; var glob2; var glob3; var makeCanvas = function (elem) { var retObj= {}, context = elem.getContext('2d'), canvasArr = context.getImageData(0,0,elem.width,elem.height).data, greenDist = {}; retObj.getRBG = function (x,y) { pos1 = (x + elem.width*y)*4; return [ canvasArr[pos1], canvasArr[pos1 + 1], canvasArr[pos1 + 2] ]; }; retObj.getLAB = function (x,y) { return rgb2lab(myCanvas.getRBG(x,y)); }; retObj.getGreenDist = function (x,y) { //temp, test dist from green var ret = 10000, tempLab, dist, col1 = [76.28056296, -35.52371953, 23.79405389]; //baseLab = [70.14204798, -38.19923716, 28.43955885]; //baseLab = [74.65687694, -38.39793167, 25.95259955]; //baseLab = [79.2967, -31.7154, 20.3356]; if(greenDist.hasOwnProperty(x + '_' + y)) { return greenDist[x + '_' + y]; } //Delta E from http://www.brucelindbloom.com/index.html?ColorDifferenceCalcHelp.html // 0 - L; 1 - a; 2 - b col2 = retObj.getLAB(x,y); var L1 = col1[0], L2 = col2[0], a1 = col1[1], a2 = col2[1], b1 = col1[2], b2 = col2[2], LbarP = (L1 + L2) / 2, c1 = Math.sqrt(Math.pow(a1,2) + Math.pow(b1,2)), c2 = Math.sqrt(Math.pow(a2,2) + Math.pow(b2,2)), Cbar = (c1 + c2) / 2, Cbar7 = Math.sqrt((Math.pow(Cbar,7) / (Math.pow(Cbar,7) + Math.pow(25,7)))), G = (1 - Cbar7) / 2, a1p = a1 * (1 + G), a2p = a2 * (1 + G), C1p = Math.sqrt(Math.pow(a1p,2) + Math.pow(b1,2)), C2p = Math.sqrt(Math.pow(a2p,2) + Math.pow(b2,2)), CbarP = (C1p + C2p) / 2, h1p = Math.atan2(b1, a1p) < 0 ? Math.atan2(b1, a1p) + 2 * Math.PI : Math.atan2(b1, a1p), h2p = Math.atan2(b2, a2p) < 0 ? Math.atan2(b2, a2p) + 2 * Math.PI : Math.atan2(b2, a2p), //Below, if C1p or C2p are 0 then HbarP is 0 HbarP = !C1p || !C2p ? 0 : Math.abs(h1p - h2p) > Math.PI ? (h1p + h2p) / 2 + Math.PI : (h1p + h2p) / 2, T = 1 - 0.17 * Math.cos(HbarP - Math.PI / 6) + 0.24 * Math.cos(2 * HbarP) + 0.32 * Math.cos(3 * HbarP + Math.PI / 30) - 0.20 * Math.cos(HbarP * 4 - 63 * Math.PI / 180), //Below, if C1p or C2p are 0 then dhP is 0 dhP = !C1p || !C2p ? 0 : h2p - h1p < -Math.PI / 2 ? h2p-h1p + 2 * Math.PI : h2p - h1p > Math.PI / 2 ? h2p - h1p - 2 * Math.PI : h2p - h1p, dLp = L2-L1, dCp = C2p - C1p, dHp = 2 * Math.sqrt(C1p * C2p) * Math.sin(dhP / 2), L50 = Math.pow(LbarP - 50, 2), S_L = 1 + (0.015 * L50)/Math.sqrt(20 + L50), S_C = 1 + 0.045 * CbarP, S_H = 1 + 0.015 * CbarP * T, dTheta = 30 * Math.exp(-1 * Math.pow((HbarP * 180 / Math.PI - 275) / 25, 2)), R_C = 2 * Cbar7, R_T = -R_C * Math.sin(2 * dTheta); dist = Math.sqrt(Math.pow(dLp / S_L, 2) + Math.pow(dCp / S_C, 2) + Math.pow(dHp / S_H, 2) + R_T * (dCp / S_C) * (dHp / S_H)); //var col = retObj.getRBG(x,y); //return col[0]*0.2989 + col[1]*0.5870 + col[2]*0.1140; // Distance is between 0 and 1 = 'green', 1 and 2 is other var normDist = dist / 16 < 1 ? dist / 16 : 2 - 16 / dist; normDist = Math.round(normDist*1000)/1000; greenDist[x + '_' + y] = normDist; return normDist; }; retObj.getGreenDistGaus = function (x,y) { return 1 / 115 * ( retObj.getGreenDist(x,y) * 15 + 12 * (retObj.getGreenDist(x-1,y)+retObj.getGreenDist(x+1,y)+retObj.getGreenDist(x,y-1)+retObj.getGreenDist(x,y+1)) + 9 * (retObj.getGreenDist(x-1,y-1)+retObj.getGreenDist(x+1,y-1)+retObj.getGreenDist(x+1,y+1)+retObj.getGreenDist(x-1,y+1)) + 5 * (retObj.getGreenDist(x,y-2)+retObj.getGreenDist(x,y+2)+retObj.getGreenDist(x+2,y)+retObj.getGreenDist(x-2,y)) + 4 * (retObj.getGreenDist(x-1,y-2)+retObj.getGreenDist(x+1,y-2)+retObj.getGreenDist(x+1,y+2)+retObj.getGreenDist(x-1,y+2)) + 4 * (retObj.getGreenDist(x-2,y-1)+retObj.getGreenDist(x+2,y-1)+retObj.getGreenDist(x+2,y+1)+retObj.getGreenDist(x-2,y+1)) + 2 * (retObj.getGreenDist(x-2,y-2)+retObj.getGreenDist(x+2,y-2)+retObj.getGreenDist(x+2,y+2)+retObj.getGreenDist(x-2,y+2))); }; retObj.getGrey = function (x,y) { var col = retObj.getRBG(x,y); // return 255* ((1-col[0]/255)*0.2989 + (1-col[1]/255)*0.5870 + (1-col[2]/255)*0.1140); return 255* ((1-col[0]/255)*0.21 + (1-col[1]/255)*0.72 + (1-col[2]/255)*0.07); } retObj.getGreyGaus = function(x,y) { return 1 / 115 * ( retObj.getGrey(x,y) * 15 + 12 * (retObj.getGrey(x-1,y)+retObj.getGrey(x+1,y)+retObj.getGrey(x,y-1)+retObj.getGrey(x,y+1)) + 9 * (retObj.getGrey(x-1,y-1)+retObj.getGrey(x+1,y-1)+retObj.getGrey(x+1,y+1)+retObj.getGrey(x-1,y+1)) + 5 * (retObj.getGrey(x,y-2)+retObj.getGrey(x,y+2)+retObj.getGrey(x+2,y)+retObj.getGrey(x-2,y)) + 4 * (retObj.getGrey(x-1,y-2)+retObj.getGrey(x+1,y-2)+retObj.getGrey(x+1,y+2)+retObj.getGrey(x-1,y+2)) + 4 * (retObj.getGrey(x-2,y-1)+retObj.getGrey(x+2,y-1)+retObj.getGrey(x+2,y+1)+retObj.getGrey(x-2,y+1)) + 2 * (retObj.getGrey(x-2,y-2)+retObj.getGrey(x+2,y-2)+retObj.getGrey(x+2,y+2)+retObj.getGrey(x-2,y+2))); } retObj.height = elem.height; retObj.width = elem.width; retObj.fillStyle = function (x) { context.fillStyle = x; }; retObj.fillRect = function (x,y,w,h) { //console.log(x,y); context.fillRect(x,y,w,h); }; return retObj; }; var rgb2xyz = function(rgb) { //https://github.com/MoOx/color-convert/blob/master/conversions.js var r = rgb[0] / 255, g = rgb[1] / 255, b = rgb[2] / 255; // assume sRGB r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); return [x * 100, y *100, z * 100]; }; var rgb2lab = function(rgb) { //https://github.com/MoOx/color-convert/blob/master/conversions.js var xyz = rgb2xyz(rgb), x = xyz[0], y = xyz[1], z = xyz[2], l, a, b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116); l = (116 * y) - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; var findGreen = function(canvas, minX, maxX, minY, maxY) { //var colorNorm = {X:[], Y:[]}; var colorRegion = [[maxX, maxY], [minX, minY]], yn, xn; //Really only need to find approximate max/min for these // So I skip every 2 for (yn = minY; yn < maxY; yn += 2 ) { for(xn = minX; xn < maxX; xn +=2 ){ if(canvas.getGreenDist(xn,yn) < 1) { colorRegion[0][0] = Math.min(colorRegion[0][0], xn); //x min colorRegion[1][0] = Math.max(colorRegion[1][0], xn); //x max colorRegion[0][1] = Math.min(colorRegion[0][1], yn); //y min colorRegion[1][1] = Math.max(colorRegion[1][1], yn); //y max } } } colorRegion[0][0] -= 5; colorRegion[0][1] -= 5; colorRegion[1][0] += 5; colorRegion[1][1] += 5; colorRegion[0][0] = Math.max(colorRegion[0][0], minX); colorRegion[0][1] = Math.max(colorRegion[0][1], minY); colorRegion[1][0] = Math.min(colorRegion[1][0], maxX); colorRegion[1][1] = Math.min(colorRegion[1][1], maxY); return colorRegion; }; var findEdges = function (colorFunction, minEdge, minX, maxX, minY, maxY, verbose) { var greyArr = [], direcArr = [], trueDirecArr = [], gy, gx, eStren, eDirec, c225 = (90 - 22.5) * Math.PI / 180, c675 = (90 - 67.5) * Math.PI / 180, j, i, greyEdgeArr = []; var direcObj = {"0": {}, "45": {}, "90": {}, "135": {}}; var em = [[0,0,0],[0,0,0],[0,0,0]] // if(verbose) {console.log("starting edge detection")} //get grey map for (j = minY; j < maxY; j += 1) { greyArr[j-minY] = []; greyEdgeArr[j-minY] = []; direcArr[j-minY] = []; trueDirecArr[j-minY] = []; for (i = minX; i < maxX; i += 1) { if(verbose) {console.log("EM array i, j", i, j)} //greyArr[j-minY][i-minX] = canvas.getGrey(i,j); em[0][0] = colorFunction(i-1,j-1); em[1][0] = colorFunction(i-0,j-1); em[2][0] = colorFunction(i+1,j-1); em[0][1] = colorFunction(i-1,j+0); //em[1][1] = canvas.getGrey(i-0,j+0); em[2][1] = colorFunction(i+1,j+0); em[0][2] = colorFunction(i-1,j+1); em[1][2] = colorFunction(i+0,j+1); em[2][2] = colorFunction(i+1,j+1); // if(verbose) {console.log("EM array", em)} gx = em[0][0]*-1 + em[2][0] + -2 * em[0][1] + 2 * em[2][1] + -1 * em[2][0] + em[2][0]; gy = em[0][0]*-1 - 2 * em[1][0] - em[2][0] + em[0][2] + 2 * em[1][2] + em[2][2]; // if(verbose) {console.log("(gx, gy) -> (", gx, gy, ")")} eStren = Math.sqrt(gx * gx + gy * gy); eStren = Math.round(eStren * 1000) / 1000; eDirec = Math.atan(gy / gx); if (eDirec < -c225 || eDirec > c225) { eDirec = 0; } else if (eDirec > -c675 && eDirec < c675 ) { eDirec = 90; } else if (eDirec > c675 && eDirec < c225) { eDirec = 45; } else { eDirec = 135; } // direcObj[eDirec][i] = direcObj[eDirec][i] || {}; // direcObj[eDirec][i][j] = [eStren, eDirec]; direcArr[j-minY][i-minX] = eDirec; greyArr[j-minY][i-minX] = eStren; trueDirecArr[j-minY][i-minX] = Math.atan2(gy, gx);; } } //Nonmax Suppression var fieldSize = 1, direc, cmpArr, posArr, xp, yp, k, maxGrey; for (j = minY; j < maxY; j += 1) { for (i = minX; i < maxX; i += 1) { //Get direction direc = direcArr[j-minY][i-minX]; cmpArr = []; posArr = []; switch (direc) { case 0 : for (k = -fieldSize; k <= fieldSize; k += 1) { //This looks above and below on y axis xp = i-minX; yp = j-minY+k; if ((xp >= 0 && xp < greyArr[0].length && yp >= 0 && yp < greyArr.length) && (direcArr[yp][xp] === direc)) { cmpArr.push(greyArr[yp][xp]); posArr.push([yp, xp]); } } break; case 45 : for (k = -fieldSize; k <= fieldSize; k += 1) { //This looks on the 45* axis xp = i-minX+k; yp = j-minY+k; if ((xp >= 0 && xp < greyArr[0].length && yp >= 0 && yp < greyArr.length) && direcArr[yp][xp] === direc) { cmpArr.push(greyArr[yp][xp]); posArr.push([yp, xp]); } } break; case 90 : for (k = -fieldSize; k <= fieldSize; k += 1) { //This looks on the left to right xp = i-minX+k; yp = j-minY; if ((xp >= 0 && xp < greyArr[0].length && yp >= 0 && yp < greyArr.length) && direcArr[yp][xp] === direc) { cmpArr.push(greyArr[yp][xp]); posArr.push([yp, xp]); } } break; default : for (k = -fieldSize; k <= fieldSize; k += 1) { //This looks on the 135* axis xp = i-minX-k; yp = j-minY+k; if ((xp >= 0 && xp < greyArr[0].length && yp >= 0 && yp < greyArr.length) && direcArr[yp][xp] === direc) { cmpArr.push(greyArr[yp][xp]); posArr.push([yp, xp]); } } } maxGrey = Math.max.apply(null,cmpArr); for (k = 0; k < posArr.length; k += 1) { xp = posArr[k][1]; yp = posArr[k][0]; //console.log(posArr,xp,yp); if (greyArr[yp][xp] < maxGrey - 0.001) { //Rounding error greyArr[yp][xp] = 0; greyEdgeArr[yp][xp] = 0; } else if (greyArr[yp][xp] > minEdge){ greyEdgeArr[yp][xp] = [greyArr[yp][xp], direcArr[yp][xp]] } else { greyEdgeArr[yp][xp] = 0; } } } } return greyEdgeArr; }; var findRectangles = function (colorMat, edgeMat, regionOfInterest) { // Note: ColorMat should be designed so < 1 is the color of interest // and greater than 1 is not of interest (Distance Proxy) // EdgeMat should be 0 if no edge, and a value for edge strength if there is //First we find contigous shapes within a 2px circle var myShapes = [], y, x, myRects = [], avgH = 0, avgW = 0; var shapeMat = grabGreenMatrix(regionOfInterest); var area, areas = [], medianArea, sortAreas = []; //myShapes= [findPositiveNeighbors(shapeMat, 10, 30)]; //Find groups of green pixels for(y = 0; y < shapeMat.length; y += 1) { for(x = 0; x < shapeMat[y].length; x += 1) { if (shapeMat[y][x] < 1) { //Note this sets all shapeMat Values to 10 once id'd as a neighbor myShapes.push(findPositiveNeighbors(shapeMat, y, x)); // return myShapes; } } } //calculate median region area to exclude really small accidental regions. for (x = 0; x < myShapes.length; x += 1) { area = (Math.max.apply(null,myShapes[x].xs) - Math.min.apply(null,myShapes[x].xs)) * (Math.max.apply(null,myShapes[x].ys) - Math.min.apply(null,myShapes[x].ys)); areas.push(area); sortAreas.push(area); } sortAreas = sortAreas.sort(function(a,b) { return a < b ? -1 : a > b ? 1 : 0; }); medianArea = 0.5 * (sortAreas[Math.floor(sortAreas.length/2)] + sortAreas[Math.ceil(sortAreas.length/2)]); console.log('areas', medianArea, areas, sortAreas); //Utilize a hough transform to determine rectangle coordinates for (x = 0; x < myShapes.length; x += 1) { if (areas[x] > medianArea * 0.25) { myRects.push(minimizeRectangle(myShapes[x], edgeMat, regionOfInterest)); } //return; } //Find average width and height for (x = 0; x < myRects.length; x += 1) { avgW += myRects[x][2]; avgH += myRects[x][3]; } avgW /= myRects.length; avgH /= myRects.length; glob = JSON.parse(JSON.stringify(myRects)); //Draw green rectangles for (x = 0; x < myRects.length; x += 1) { myRects[x][2] = avgW; myRects[x][3] = avgH; myRects[x][0] += regionOfInterest[0][0]; myRects[x][1] += regionOfInterest[0][1]; drawRectangle(myRects[x], "#52BE80"); } glob2 = JSON.parse(JSON.stringify(myRects)); console.log(myRects, regionOfInterest, shapeMat, myShapes); return myRects; }; var minimizeRectangle = function (rect, edges, regionOfInterest) { var rectP, maxX, minX, maxY, minY, rect; maxX = Math.max.apply(null,rect.xs); minX = Math.min.apply(null,rect.xs); maxY = Math.max.apply(null,rect.ys); minY = Math.min.apply(null,rect.ys); //starting point: // rectS = [ // (maxX - minX) / 2 + minX, //center x // (maxY - minY) / 2 + minY, //center y // (maxX - minX) / 2, //width / 2 // (maxY - minY) / 2, //height / 2 // 0 // angle // ]; rectP = [ minX-2, minY-2, maxX+2, maxY+2, (maxX - minX) / 2 + minX, (maxY - minY) / 2 + minY ] // console.log("rectScore", houghTrans(rect, edges, rectP)); rect = houghTrans(rect, edges, rectP, false, regionOfInterest[0][0], regionOfInterest[0][1]); return rect; //drawRectangle(rectS); }; var findPositiveNeighbors = function (shapeMat, yi, xi) { var wind, mwind=2, i, xp, yp, res = {ys:[yi], xs:[xi]}, edges, found, xm, yB ={}, xB = {}, yStart, xStart, yFin, xFin, x_min_bound, y_min_bound, x_max_bound, y_max_bound; shapeMat[yi][xi] = 10; yB[yi]=[xi,xi]; xB[xi]=[yi,yi]; // console.log(JSON.stringify(yB)); //for (i = 0; i < res.ys.length; i += 1) { for (i = 0; i < res.ys.length; i += 1) { //Get x,y point y = res.ys[i]; x = res.xs[i]; //console.log('test point',x,y, JSON.parse(JSON.stringify(xB)), JSON.parse(JSON.stringify(yB))); x_min_bound = yB[y][0] === x ? 1 : 0; y_min_bound = xB[x][0] === y ? 1 : 0; x_max_bound = yB[y][1] === x ? 1 : 0; y_max_bound = xB[x][1] === y ? 1 : 0; wind = mwind; while(wind > 0 && (x_min_bound + y_min_bound + x_max_bound + y_max_bound )) { //Based on the point's edge status determine the // start/finish points for the search window xStart = x - wind * x_min_bound; xFin = x + wind * x_max_bound; yStart = y - wind * y_min_bound; yFin = y + wind * y_max_bound; // console.log(y,x, 'is a boundry:', yStart, yFin, xStart, xFin); for(yp = yStart; yp < yFin + 1; yp += 1) { //So we only search the outer box ring if(yp === y - wind || yp === y + wind) { xm = 1; } else { //TODO: test if this actually helps with efficiency if (xStart === x || xFin === x) { xm = wind; } else { xm = wind * 2; } } for(xp = xStart; xp < xFin + 1; xp += xm) { if (yp>0 && xp>0 && yp < shapeMat.length && xp < shapeMat[yp].length) { if (shapeMat[yp][xp] < 1) { // console.log('green', yp, xp); res.ys.push(yp); res.xs.push(xp); shapeMat[yp][xp] = 10; xB[xp] = xB[xp] || [yp, yp]; yB[yp] = yB[yp] || [xp, xp]; xB[xp][0] = yp < xB[xp][0] ? yp : xB[xp][0]; xB[xp][1] = yp > xB[xp][1] ? yp : xB[xp][1]; yB[yp][0] = xp < yB[yp][0] ? xp : yB[yp][0]; yB[yp][1] = xp > yB[yp][1] ? xp : yB[yp][1]; } else { // console.log('not green', yp, xp, xm); } } } } wind -= 1; } } // console.log(JSON.parse(JSON.stringify(yB))); // console.log(JSON.parse(JSON.stringify(xB))); return res; }; var houghTrans = function (rect, edges, params, testing, shiftX, shiftY) { var x, y, x0, y0, d0, theta0, lines, ind, theta, mtheta, mdist, maxDist, peaks, peakParams, thetaMid, findRhoBin, findXBin, addCount, maxes, thetaBin, calculatedRho, calculatedTheta, ninetyStart; x0 = params[4]; y0 = params[5]; peakParams = { rho: [], theta: [] }; peaks = {vert: {distPos: [0,0,0], distNeg: [0,0,0]}, horz: {distPos: [0,0,0], distNeg: [0,0,0]} }; maxes = {}; shiftX = shiftX || 0; shiftY = shiftY || 0; maxDist = Math.sqrt(Math.pow(params[3] - params[1],2) + Math.pow(params[2] - params[0],2))/2; bins = Math.ceil(8 * maxDist / 3); radBins = Math.ceil(10 * Math.PI * maxDist / 4); addCount = function (theta, rho, edgeStrength, partition) { if (rho >= 0) { peaks[partition].distPos[0] += theta * edgeStrength; peaks[partition].distPos[1] += rho * edgeStrength; peaks[partition].distPos[2] += edgeStrength; } if (rho <= 0) { peaks[partition].distNeg[0] += theta * edgeStrength; peaks[partition].distNeg[1] += rho * edgeStrength; peaks[partition].distNeg[2] += edgeStrength; } } // console.log(peaks); // //perform a hough transform //For each edge point (non-zero) draw lines // and calculate the distance from the center to that line. var lines = []; for(y = params[1]; y <= params[3]; y += 1) { for(x = params[0]; x <= params[2]; x += 1) { if(edges[y] && edges[y][x]) { //If we find an edge vary the angle and //compute hough transform curve of angle //by mid distance // console.log(edges[y][x]); // d0 = Math.sqrt(Math.pow(x-x0,2)+Math.pow(y-y0,2)); // theta0 = Math.atan2(y-y0,x-x0); lines.push([]); ind = lines.length - 1; // thetaBin = 0; // thetaMid = edges[y][x][1] > 90 ? edges[y][x][1] - 180 : edges[y][x][1]; // thetaMid *= Math.PI / 180; // for(theta = thetaMid - Math.PI/8; theta < thetaMid + Math.PI/8; theta += Math.PI / 24 ) { if( edges[y][x][1] === 0 || edges[y][x][1] === 45 || edges[y][x][1] === 135 ) { // if( edges[y][x][1] === 0 ) { // Since these lines are stronger and longer we will use only the 0* //Look at the 90* region //Note to start and stop at the right place we calculate a strange starting location // Start around 5 PI / 6, caclulate the bin # -> // BIN = floor((5 PI / 12 + PI / 12) / (5 PI / 6) * bins) = floor(3 / 5 * bins) // BIN * (5 PI / 6) / bins - PI / 12 = PI /6 (5 * BIN / bins -1/2) //ninetyStart = Math.PI / 6 * (5 * Math.floor(3/5 * bins) / bins - 0.5); for(theta = 5 * Math.PI / 12; theta < 7 * Math.PI / 12; theta += (5 * Math.PI/6) / radBins ) { mdist = (x-x0) * Math.cos(theta) + (y-y0) * Math.sin(theta); lines[ind].push([theta, mdist]); addCount(theta, mdist, edges[y][x][0], 'horz'); } } if (edges[y][x][1] === 90 || edges[y][x][1] === 45 || edges[y][x][1] === 135) { //Look at the 0* region for(theta = -Math.PI / 12; theta < Math.PI / 12; theta += (5 * Math.PI/6) / radBins ) { mdist = (x-x0) * Math.cos(theta) + (y-y0) * Math.sin(theta); lines[ind].push([theta, mdist]); addCount(theta, mdist, edges[y][x][0], 'vert'); } } } } } glob2 = peaks; // peaks.vert.distPos[0] /= peaks.vert.distPos[2]; // theta // peaks.vert.distPos[1] /= peaks.vert.distPos[2]; // rho // peaks.vert.distNeg[0] /= peaks.vert.distNeg[2]; // theta // peaks.vert.distNeg[1] /= peaks.vert.distNeg[2]; // rho // peaks.horz.distPos[0] /= peaks.horz.distPos[2]; // theta // peaks.horz.distPos[1] /= peaks.horz.distPos[2]; // rho // peaks.horz.distNeg[0] /= peaks.horz.distNeg[2]; // theta // peaks.horz.distNeg[1] /= peaks.horz.distNeg[2]; // rho //To ensure nothing is /0 or weighted way too high... // This says assume our original guess was correct // If there is no evidence to suggest otherwise // if (!peaks.horz.distPos[2] || ! peaks.horz.distNeg[2]) { // peaks.horz.distPos[2] = Math.max(peaks.horz.distNeg[2], peaks.horz.distPos[2]); // peaks.horz.distPos[1] = Math.max(peaks.horz.distNeg[1], peaks.horz.distPos[1]); // peaks.horz.distPos[0] = Math.max(peaks.horz.distNeg[0], peaks.horz.distPos[0]); // peaks.horz.distNeg[0] = peaks.horz.distPos[0]; // peaks.horz.distNeg[1] = peaks.horz.distPos[1]; // peaks.horz.distNeg[2] = peaks.horz.distPos[2]; // } // peaks.horz.distPos[2] = peaks.horz.distPos[2] || 1; // peaks.horz.distNeg[2] = peaks.horz.distNeg[2] || 1; // peaks.vert.distPos[2] = peaks.vert.distPos[2] || 1; // peaks.vert.distNeg[2] = peaks.vert.distNeg[2] || 1; var finalTheta = (peaks.vert.distPos[0] + peaks.vert.distNeg[0] - Math.PI / 2 * (peaks.horz.distPos[2] + peaks.horz.distNeg[2]) + peaks.horz.distPos[0] + peaks.horz.distNeg[0]) / (peaks.vert.distPos[2] + peaks.vert.distNeg[2] + peaks.horz.distPos[2] + peaks.horz.distNeg[2]); var finalYi = y0 + peaks.horz.distPos[1] / peaks.horz.distPos[2] + peaks.horz.distNeg[1] / peaks.horz.distNeg[2]; var finalXi = x0 + peaks.vert.distPos[1] / peaks.vert.distPos[2] + peaks.vert.distNeg[1] / peaks.vert.distNeg[2]; var finalH = peaks.horz.distPos[1] / peaks.horz.distPos[2] - peaks.horz.distNeg[1] / peaks.horz.distNeg[2]; var finalL = peaks.vert.distPos[1] / peaks.vert.distPos[2] - peaks.vert.distNeg[1] / peaks.vert.distNeg[2]; //Below is just so I can understand the angles determined when console.logged peaks.vert.distPos[0] /= peaks.vert.distPos[2] / 180 * Math.PI; // theta peaks.vert.distPos[1] /= peaks.vert.distPos[2]; // rho peaks.vert.distNeg[0] /= peaks.vert.distNeg[2] / 180 * Math.PI; // theta peaks.vert.distNeg[1] /= peaks.vert.distNeg[2]; // rho peaks.horz.distPos[0] /= peaks.horz.distPos[2] / 180 * Math.PI; // theta peaks.horz.distPos[1] /= peaks.horz.distPos[2]; // rho peaks.horz.distNeg[0] /= peaks.horz.distNeg[2] / 180 * Math.PI; // theta peaks.horz.distNeg[1] /= peaks.horz.distNeg[2]; // rho if(testing) {console.log( // 'lines', // lines.map(function(x,i){return x.map(function(y) {return i + "\t" + y.map(function(z){return Math.round(z*1000)/1000;}).join('\t')}).join('\n')}).join('\n'), '\nparameters', params, '\ndenDiffX', Math.abs(peaks.vert.distPos[2] - peaks.vert.distNeg[2]), '\ndenDiffY', Math.abs(peaks.horz.distPos[2] - peaks.horz.distNeg[2]) );}; // // var maxKeys = Object.keys(maxes); // maxKeys = maxKeys.sort(function(a,b) { // if (maxes[a][0] < maxes[b][0]) { // return 1; // } else if (maxes[a][0] > maxes[b][0]) { // return -1; // } // return 0; // }) // for(x = 0; x < maxKeys.length; x += 1) { // console.log(maxKeys[x], maxes[maxKeys[x]]); // } // console.log(maxes, peaks) // console.log(finalTheta * 180 / Math.PI, finalXi, finalYi, finalL, finalH); //Draw rectange for region investigated drawRectangle([x0 + shiftX,y0+shiftY,params[2] - params[0], params[3] - params[1], 0], "#FF3300"); //pale yellow: FFFFCC return [finalXi, finalYi, finalL, finalH, finalTheta]; }; var grabGreenMatrix = function (regionOfInterest) { var ret = [], xp, yp; for(yp = regionOfInterest[0][1]; yp < regionOfInterest[1][1]; yp += 1) { ret.push([]); for(xp = regionOfInterest[0][0]; xp < regionOfInterest[1][0]; xp += 1) { ret[ret.length - 1].push(myCanvas.getGreenDist(xp,yp)); } } return ret; }; var drawRectangle = function (rectParams, color) { var phi, thetaA, r, inc = 0, cosPhi, sinPhi, tempPhi, aShift, x0 = rectParams[0], y0 = rectParams[1], w = rectParams[2], h = rectParams[3], theta0 = rectParams[4]; thetaA = Math.atan2(h, w); //theta0 = 0; thetaS = thetaA + theta0; // console.log('thetas for drawing', theta0, thetaA, thetaS); //It is easier to draw this as a parametric equation myCanvas.fillStyle(color); for(phi = 0; phi < 2* Math.PI; phi += inc) { // for(phi = 0; phi < 2 * Math.PI; phi += Math.PI/(w+h)/4) { cosPhi = Math.cos(phi); sinPhi = Math.sin(phi); //Calculate R, this is a simple parametric equation if ((phi > thetaS && phi <= Math.PI - thetaS) || (phi > Math.PI + thetaS && phi <= 2* Math.PI - thetaS)) { r = Math.abs(h / (2 * sinPhi)); // inc = (Math.PI - 2 * thetaA) / w / 2; tempPhi = phi < Math.PI ? phi : phi - Math.PI; aShift = phi < Math.PI ? 0 : Math.PI; inc = Math.abs(Math.acos(Math.cos(tempPhi + .3/r)) + aShift - phi); //inc = Math.abs(Math.acos(cosPhi - 0.1/r) - phi); // console.log('here top/bottom next inc', inc, Math.round(r * Math.cos(phi)+ x0), Math.round(r*Math.sin(phi)+ y0)); } else { r = Math.abs(w / (2 * cosPhi)); if (phi < Math.PI / 2) { tempPhi = phi; aShift = 0; } else if( phi < Math.PI) { tempPhi = phi - Math.PI / 2; aShift = Math.PI / 2; } else if ( phi < 1.5 * Math.PI ) { tempPhi = phi - Math.PI; aShift = Math.PI; } else { tempPhi = phi - 1.5 * Math.PI; aShift = 1.5 * Math.PI; } inc = Math.abs(Math.asin(Math.sin(tempPhi + .3/r)) + aShift - phi); // console.log('here left/right next inc', inc, Math.round(r * Math.cos(phi)+ x0), Math.round(r*Math.sin(phi)+ y0)); } // console.log(Math.round(r * Math.cos(phi)+ x0), Math.round(r*Math.sin(phi)+ y0)); // console.log(r, phi); //Using x = r cos phi and y = r sin(phi) plot a point myCanvas.fillRect(Math.floor(r * Math.cos(phi)+ x0 + 0.1), Math.floor(r*Math.sin(phi)+ y0 + 0.1), 1, 1); } //plot center as cross myCanvas.fillRect(Math.round(x0),Math.round(y0)-1,1,3); myCanvas.fillRect(Math.round(x0)-1,Math.round(y0),3,1); }; var findBandLocations = function (rectangles) { //Cycle through each main band location var i, j, edges, height, theta, x0, y0, width, center, rectagleCount, divisor, rightEdge, topEdge, leftEdge, bottomEdge = 0, testX, testY, xBuffer, testing = false, distances = [], distanceMeasure, roundedHypot, bandNumber; for (i = 0; i < rectangles.length; i += 1) { // for (i = 10; i < 11; i += 1) { console.log('Testing lane ' + (i + 1) + "."); rectagleCount = 1; distances[i] = []; //Remeber rectange is stored as: // [x0, y0, width, height, theta] theta = rectangles[i][4]; x0 = rectangles[i][0]; y0 = rectangles[i][1]; width = rectangles[i][2]; height = rectangles[i][3]; roundedHypot = Math.ceil(0.63 * 27 * width * 100) / 100; topEdge = Math.floor(height + y0); //To be sure that the height clears bottomEdge = Math.ceil(roundedHypot * Math.cos(Math.min(Math.abs(theta), Math.abs(Math.abs(theta) - Math.PI/180))) + y0 + 2); xBuffer = Math.sin(Math.PI/180 + Math.abs(theta)) * roundedHypot; rightEdge = Math.ceil(x0 + width / 2 + xBuffer) + 2; leftEdge = Math.ceil(x0 - width / 2 - xBuffer) - 2; rightEdge = Math.min(rightEdge, myCanvas.width); leftEdge = Math.max(leftEdge, 0); edges = findEdges(myCanvas.getGreyGaus, 5, leftEdge, rightEdge, topEdge, bottomEdge, false); console.log(width, height, leftEdge, rightEdge, topEdge, bottomEdge); for(j = 1; j < edges.length; j += 1) { testX = Math.round((j+topEdge-y0) * Math.tan(theta) + (x0-leftEdge)); testY = j; //Show the path traced myCanvas.fillStyle('#BE5A52'); myCanvas.fillRect(Math.round(testX+leftEdge), Math.round(testY+topEdge), 1, 1); //Test for edge if( edges[testY][testX] && edges[testY][testX][1] === 0 && edges[testY][testX][0] > 25) { //hough Transform params: minX, minY, maxX, maxY, centerX, centerY; //redefine testX, testY as the new center testY = j + .5 * height; testX = testY * Math.tan(theta) + (x0-leftEdge); rect = houghTrans([], edges, [ Math.max(Math.floor(testX - width * .7),0), Math.max(Math.floor(j-(.25*height)),0), Math.min(Math.ceil(testX + width * .7), rightEdge - leftEdge), Math.min(Math.ceil(j+(1.5*height)), edges.length), testX, testY] , false, leftEdge, topEdge); // console.log('band?', rect); rect[0] += leftEdge; // [x0, y0, width, height, theta] rect[1] += topEdge; //While weighting the previous height/width much higher calculate a new ref // height/width. The higher weight for a previous rectangle is due to // trusting the green rectangle detection substantially more than the grey rect[2] = (width * (4+rectagleCount+rectangles.length) + rect[2]) / (5 + rectagleCount+rectangles.length); rect[3] = (height * (4+rectagleCount+rectangles.length) + rect[3]) / (5 + rectagleCount+rectangles.length); //Recalculate theta var centerTheta = Math.atan2(rect[0]-x0, rect[1]-y0); rect[4] = rectagleCount * theta / (rectagleCount + 1) + (4 * rect[4] + centerTheta)/(rectagleCount+1) / 5; //While centerTheta is not that useful for actual theta calc due to a lack of granularity, // If the signs are different it can be used to decrease the theta of the actual line if(theta * centerTheta < 0) { rect[4] /= 2; } //Calculate median greyness to determine if a rectange is actually present if(isGrey(rect, testing)) { //adjust the old theta, width and height width = rect[2]; height = rect[3]; theta = rect[4]; //Adjust the center reference, this keeps shifts in location by 1-2 pixels // from making a large effect on the downstream centering x0 = (rectagleCount * rect[0] + x0) / (rectagleCount + 1); //Draw the rectange so it is visible drawRectangle(rect, "#4DCBCA"); //Save distance between start point and this rectangle //Note we use the original rectangle center here distanceMeasure = Math.sqrt(0.95 * Math.pow(rectangles[i][0] - rect[0], 2) + 1.05 * Math.pow(y0 - rect[1], 2)); distances[i].push(distanceMeasure); //Move down on j enough to not have the same rectangle found twice j += Math.ceil(height * 1.5); //Increment the rectangle count for avg calcs rectagleCount += 1; } } } divisor = 0.634; for(j = 0; j < distances[i].length; j+= 1) { bandNumber = Math.round(distances[i][j] / width / divisor * 10) / 10; if (bandNumber > 26.5) { distances[i].splice(j,1); j -= 1; } else { // divisor = (divisor * (j + 5) + distances[i][j] / bandNumber / width ) / (j + 6); // if(bandNumber > 20 && bandNumber < 24) { // distances[i][j] = [width, height, distances[i][j]].join(',') + '\t'; // } else { distances[i][j] = bandNumber; // } //distances[i][j] = [width, height, distances[i][j]].join(',') + '\t'; } } // console.log(edges, edges.map(function(x){return x.map(function(y){return y[0] || 0}).join('\t')}).join('\n')); } console.log(distances); glob3 = distances; return distances; }; var isGrey = function (rectParams, testing) { var phi, thetaA, r, inc = 0, cosPhi, sinPhi, tempPhi, aShift, x0 = rectParams[0], y0 = rectParams[1], w = rectParams[2], h = rectParams[3], theta0 = rectParams[4], x, y, xs, ys, xf, yf, medianGrey, count, greys = []; thetaA = Math.atan2(h, w); //theta0 = 0; thetaS = thetaA + theta0; r = Math.sqrt(w * w + h * h)/2; //Top left xs = Math.ceil(r * Math.cos(Math.PI+thetaS) + x0); ys = Math.ceil(r * Math.sin(Math.PI+thetaS) + y0); //Bottom right xf = Math.floor(r * Math.cos(thetaS) + x0); yf = Math.floor(r * Math.sin(thetaS) + y0); if(testing) { myCanvas.fillStyle("#FFCCFF"); myCanvas.fillRect(xs,ys-1,1,3); myCanvas.fillRect(xs-1,ys,3,1); myCanvas.fillStyle("#CCFFCC"); myCanvas.fillRect(xf,yf-1,1,3); myCanvas.fillRect(xf-1,yf,3,1); } medianGrey = 0; for(x = xs; x <= xf; x += 1) { for(y = ys; y <= yf; y += 1) { greys.push(myCanvas.getGrey(x,y)); } } greys = greys.sort(function(a,b) { return a < b ? -1 : a > b ? 1 : 0; }); medianGrey = greys[Math.floor(greys.length/2)]/2 + greys[Math.ceil(greys.length/2)]/2; if(testing) { console.log('median grey', medianGrey); } return medianGrey < 5 ? false : true; }; //Main function **** var processCanvas = function (canvas) { myCanvas = makeCanvas(canvas); var minY = 0, minX = 0, maxY = myCanvas.height, maxX = myCanvas.width; // var minY = 0, minX = 0, maxY = 60, maxX = 680; console.log('Finding Green'); myGreen = findGreen(myCanvas, minX, maxX, minY, maxY); console.log('Finding Green Edges'); myGreenEdges = findEdges(myCanvas.getGreenDistGaus, 1.5, myGreen[0][0], myGreen[1][0], myGreen[0][1], myGreen[1][1]); console.log('Finding Green Rectangles'); rects = findRectangles(myGreen, myGreenEdges, myGreen); rects = rects.sort(function(a,b) { return a[0] < b[0] ? -1 : b[0] < a[0] ? 1 : 0; }); console.log('finding experiments'); var distances = findBandLocations(rects); return distances; }; var convertPDF2Canvas = function (startObj) { return function(pdf) { return pdf.getPage(startObj.image.pageNumber).then(function (page) { var scale = 2, viewport, canvas, context, renderContext; //Get page image object viewport = page.getViewport(scale); // Prepare canvas using PDF page dimensions canvas = document.getElementById(startObj.canvas); context = canvas.getContext('2d'); canvas.height = viewport.height; canvas.width = viewport.width; // Render PDF page into canvas context renderContext = { canvasContext: context, viewport: viewport }; return page.render(renderContext).then(function () { return canvas; }); }); }; }; var hcvGenie = {}; hcvGenie.findBands = function (startObj) { var canvas, context, img; //Things we need on startObj: // File type // If pdf, page number // File URL if applicable // File Blob if applicable // Canvas object id canvas = document.getElementById(startObj.canvas); context = canvas.getContext('2d'); if(startObj.image.type !== 'pdf') { var promise = new Promise(function(resolve, reject) { img = new Image(); img.onload = function () { canvas.width = img.width; canvas.height = img.height; context.drawImage(img, 0, 0, img.width, img.height) resolve(processCanvas(canvas)); }; img.src = startObj.image.url; }); } else { return PDFJS.getDocument(startObj.image.url).then(convertPDF2Canvas(startObj)).then(processCanvas); } };
var wss = { ws: window.WebSocket || window.MozWebSocket, socket: "", config: { msgType: "registe", body: {} }, sendMsg: function(msg) { if(!this.ws) return; if(this.socket.readyState == WebSocket.OPEN){ this.socket.send(msg); }else{ alert("WebSocket 连接没有建立成功!"); } }, sendOper: function(from, target, msg) { if(!this.socket) return; if(this.socket.readyState == WebSocket.OPEN){ this.config.msgType = "operate"; this.config.body.command = msg; this.config.body.from = from; this.config.body.target = target; var str = JSON.stringify(this.config); this.socket.send(str); }else{ alert("WebSocket 连接没有建立成功!"); } }, init: function(url, productType) { var _this = this; if(_this.ws) { _this.socket = new _this.ws(url) // 建立连接 _this.socket.onopen = function(event){ _this.config.body.productType = productType; var str = JSON.stringify(_this.config); _this.sendMsg(str); } } else { alert("您的浏览器不支持WebSocket协议!"); } } }
/** * Babel Starter Kit (https://www.kriasoft.com/babel-starter-kit) * * Copyright © 2015-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ class Greeting { constructor(name) { this.name = name || 'Guest'; } hello() { return `Welcome, ${this.name}!`; } } export default Greeting;
/* jshint node:true, esnext:true */ "use strict"; var _ = require('lodash'); /** @module Parcela @submodule parcel */ /** Represents a section of real state in the HTML page. All Parcela apps should inherit from this class. Several properties might be configured on instantiation: * [containerType](#property_containerType) * [className](#property_className) * [attributes](#property_attributes) * [text](#property_text) @class Parcel @param [config] {Object} Initial configuration. @constructor */ export default class Parcel { constructor (config) { config = config || {}; /** Type of DOM element that will be created to serve as a container for this Parcel. Defaults to a `DIV` @property containerType @type String @default DIV */ this.containerType = config.containerType || 'DIV'; /** CSS className to add to the container for this parcel. This is in addition to the className of `parcel` which is automatically added to all Parcel containers. @property className @type String @default '' */ this.className= config.className || ''; /** Hash map of attributes for the container element @property attributes @type Object @default:null */ this.attributes=config.attributes || null; /** String to be shown within the container. This is used, mostly, for initial testing of layouts, to have something to show within the parcel. It is rarely used in the final product. @property text @type String */ if (config.text) this._text = config.text; } /** Destructor. The existing implementation does nothing. @method destructor */ destructor () {} /** Called by the renderer before this Parcel is shown for the first time. It is a good place to activate resources that are only usefull while the parcel is visible such as animations. The provided method is empty, it can be overriden by each Parcela app. @method preView */ preView () {} /** Called by the renderer after this Parcel is hidden. It is a good place to deactivate resources that are only usefull while the parcel is visible such as animations. The provided method is empty, it can be overriden by each Parcela app. @method postView */ postView () {} /** Returns the virtual DOM for this parcel. Must be overriden by each Parcela app. By default, it returns the value of the [text](#property_text) property. A virtual DOM node is composed of the following elements: * `tag` {String}: Name of the HTML tag for the node to be created. * `attrs` {Object}: Collection of HTML attributes to be added to the node. * `children` {Array}: Array of virtual DOM nodes that will become children of the created node. As a convenience, this method receives a reference to the [`vDOM.vNode`](vDOM.html#method_vNode) helper function to produce the virtual DOM node, however it may be ignored as long as a virtual DOM node is somehow returned. @example view: function (v) { return v('div', [ v('p.joyful','Hello Workd!'), v('hr'), v('p','(Not very original, really)') ]); } // Equivalent to: view: function (v) { return {tag:'div', attrs:{},children: [ {tag:'p', attrs:{className:'joyful'}, children:['Hellow World!']}, {tag:'hr', attrs: {}, children: []}, {tag:'p', attrs:{}, children:['(Not very original, really)']} ]}; } @method view @param v {function} Reference to the [`vDOM.vNode`](vDOM.html#method_vNode) helper function. @return {vNode} The expected virtual DOM node for this parcel. */ view (v) { return this._text || ''; } /** Returns a value representative of the state of this parcel. The system will compare it with the previous state and if they match, it will assume the view has not changed. The default function returns `NaN` which is always different than itself. It may be overriden for optimization purposes. @method stamp @return {value} any simple value (no objects or such) that reflects the state of this view */ stamp () { return NaN; } }
'use strict'; const path = require('path'); const electron = require('electron'); const {Application} = require('spectron'); const assert = require('assert'); // DISABLE: tap failed with spectron // issue reported: https://github.com/electron/spectron/issues/155 // const tap = require('tap'); // tap.test('electron', {autoend: false, timeout: 0}, t => { // let app = null; // t.beforeEach(() => { // app = new Application({ // path: electron, // args: [path.join(__dirname, 'fixtures', 'app')] // }); // return app.start(); // }); // t.afterEach(() => { // if (app && app.isRunning()) { // return app.stop(); // } // }); // t.test('should be ok in main process', () => { // t.equal('foo', 'foo'); // t.end(); // }); // }); describe('electron', function () { this.timeout(0); let app = null; before(function () { app = new Application({ path: electron, args: [path.join(__dirname, 'fixtures', 'app')] }); return app.start(); }); after(function () { if (app && app.isRunning()) { return app.stop(); } }); it('should be ok in main process', function () { return app.electron.remote.getGlobal('platform') .then(function (platform) { assert.equal(platform.isNode, true); assert.equal(platform.isElectron, true); assert.equal(platform.isNative, true); assert.equal(platform.isPureWeb, false); assert.equal(platform.isRendererProcess, false); assert.equal(platform.isMainProcess, true); assert.equal(platform.isDarwin, process.platform === 'darwin'); assert.equal(platform.isWin32, process.platform === 'win32'); assert.equal(platform.isDev, true); }); }); it('should be ok in renderer process', function () { return app.client .waitUntilWindowLoaded() .getRenderProcessLogs() .then(function (logs) { assert.equal(logs.length, 9); assert.ok(logs[0].message.indexOf('isNode: true') !== -1); assert.ok(logs[1].message.indexOf('isElectron: true') !== -1); assert.ok(logs[2].message.indexOf('isNative: true') !== -1); assert.ok(logs[3].message.indexOf('isPureWeb: false') !== -1); assert.ok(logs[4].message.indexOf('isRendererProcess: true') !== -1); assert.ok(logs[5].message.indexOf('isMainProcess: false') !== -1); assert.ok(logs[6].message.indexOf('isDarwin: ' + (process.platform === 'darwin').toString()) !== -1); assert.ok(logs[7].message.indexOf('isWin32: ' + (process.platform === 'win32').toString()) !== -1); assert.ok(logs[8].message.indexOf('isDev: true') !== -1); }); }); }); describe('electron without node-integration', function () { this.timeout(0); let app = null; before(function () { app = new Application({ path: electron, args: [path.join(__dirname, 'fixtures', 'app-no-node-integration')], requireName: 'electronRequire' }); return app.start(); }); after(function () { if (app && app.isRunning()) { return app.stop(); } }); it('should be ok in renderer process', function () { return app.client .waitUntilWindowLoaded() .getRenderProcessLogs() .then(function (logs) { assert.equal(logs.length, 9); assert.ok(logs[0].message.indexOf('isNode: false') !== -1); assert.ok(logs[1].message.indexOf('isElectron: true') !== -1); assert.ok(logs[2].message.indexOf('isNative: true') !== -1); assert.ok(logs[3].message.indexOf('isPureWeb: false') !== -1); assert.ok(logs[4].message.indexOf('isRendererProcess: true') !== -1); assert.ok(logs[5].message.indexOf('isMainProcess: false') !== -1); assert.ok(logs[6].message.indexOf('isDarwin: ' + (process.platform === 'darwin').toString()) !== -1); assert.ok(logs[7].message.indexOf('isWin32: ' + (process.platform === 'win32').toString()) !== -1); assert.ok(logs[8].message.indexOf('isDev: undefined') !== -1); }); }); });
const uuid = require('node-uuid'); const crypto = require('crypto'); const { GraphQLString, GraphQLNonNull, } = require('graphql'); const TokenResultType = require('../types/TokenResultType'); const AddProfileType = require('../inputTypes/AddProfileType'); const { profileModel } = require('models'); const { getProfile } = require('core/profile'); const { defineEntryAs } = require('core/permission'); const { MUTATION_PROJECT_PROFILE } = require('constants/permissions/values'); const { PRIVATE } = require('constants/permissions/pieces'); const mutation = { type: TokenResultType, args: { token: { type: new GraphQLNonNull(GraphQLString) }, profile: { type: new GraphQLNonNull(AddProfileType) }, }, resolve(_, { token, profile }) { return new Promise(function (resolve, reject) { getProfile({ token, permission: MUTATION_PROJECT_PROFILE }).then(sso => { profile.ssoId = sso.id; profile.secret = crypto.randomBytes(32).toString('hex'); profile.session = new Date().getTime().toString(); if (!profile.id) { profile.id = uuid.v1(); } profileModel.insert(profile) .then(() => resolve(profile)) .catch(reject); }).catch(reject); }).then(defineEntryAs(PRIVATE)); } }; module.exports = mutation;
var React = require('react'); var classes = require('classnames'); var Option = React.createClass({ propTypes: { addLabelText: React.PropTypes.string, // string rendered in case of allowCreate option passed to ReactSelect className: React.PropTypes.string, // className (based on mouse position) mouseDown: React.PropTypes.func, // method to handle click on option element mouseEnter: React.PropTypes.func, // method to handle mouseEnter on option element mouseLeave: React.PropTypes.func, // method to handle mouseLeave on option element option: React.PropTypes.object.isRequired, // object that is base for that option renderFunc: React.PropTypes.func // method passed to ReactSelect component to render label text }, render: function() { var obj = this.props.option; var renderedLabel = this.props.renderFunc(obj); var optionClasses = classes(this.props.className, obj.className); return obj.disabled ? ( <div className={optionClasses}>{renderedLabel}</div> ) : ( <div className={optionClasses} style={obj.style} onMouseEnter={this.props.mouseEnter} onMouseLeave={this.props.mouseLeave} onMouseDown={this.props.mouseDown} onClick={this.props.mouseDown} title={obj.title}> { obj.create ? this.props.addLabelText.replace('{label}', obj.label) : renderedLabel } </div> ); } }); module.exports = Option;
/** * Wraps the tests into a async try-catch * * @param {Function} An anonymous function that wraps the tests * @param {Function} jasmine's done */ export default async (tests, done) => { try { await tests(); } catch (e) { console.error(e); } finally { done(); } };
import { CALCULATE_COLOR_PALETTE, LOAD_INITIAL_APPLICATION_STATE, LOAD_MORE_IMAGES } from '../constants/actionTypes'; import mathHelper from '../utils/mathHelper'; import * as images from '../data/urls'; import * as appConfig from '../constants/appConfig'; import objectAssign from 'object-assign'; import initialState from './initialState'; // IMPORTANT: Note that with Redux, state should NEVER be changed. // State is considered immutable. Instead, // create a copy of the state passed and set new values on the copy. // Note that I'm using Object.assign to create a copy of current state // and update values on the copy. const randomizedImageUrls = mathHelper.shuffle(images.imageUrls.urls); const setGalleryImagesPage = (state) => { let newState = objectAssign({}, state); newState.imagePage += 1; newState.images = newState.images.concat(randomizedImageUrls.slice(appConfig.GALLERY_PAGE_IMAGES_PER_PAGE * (newState.imagePage - 1), appConfig.GALLERY_PAGE_IMAGES_PER_PAGE * newState.imagePage).map(x => { return { url: x, id: x, palette: [] }; })); // Determine if there are more pages available newState.morePages = randomizedImageUrls.length - newState.images.length > 0; return newState; }; const calculateColorPalette = (state, action) => { let newState = objectAssign({}, state); // Find object let newImages = newState.images.map(x => { if (x.id === action.id) { return objectAssign({}, x, { palette: action.palette }); } return x; }); newState.images = newImages; return newState; }; export default function galleryImages(state = initialState.galleryImages, action) { switch (action.type) { case LOAD_INITIAL_APPLICATION_STATE: // Could have other flag info here or could refactor to // get rid of this action and just have everything use page action return setGalleryImagesPage(state, action); case LOAD_MORE_IMAGES: return setGalleryImagesPage(state, action); case CALCULATE_COLOR_PALETTE: return calculateColorPalette(state, action); default: return state; } }
var actionTypes = require('../constants/actionTypes/modelActionTypes'); const VEHICLES = require('../constants/models').VEHICLES; const CONSUMERS = require('../constants/models').CONSUMERS; const SETTINGS = require('../constants/models').SETTINGS; var commonCRUD = require('../commons/commonReducerFunctions'); var mapActions = require('../constants/actionTypes/mapActionTypes.js'); var vehicleRouteActions = require('../constants/actionTypes/vehicleRouteActionTypes.js'); var _ = require('lodash'); var wptATypes = require('../constants/actionTypes/waypointsActionTypes.js') function updateConsumersArray(state, v_id, cArray) { var data = Object.assign({}, state.data); var vehicle = Object.assign({}, state.data[v_id]); vehicle.consumers = cArray.slice(); vehicle.optimized = undefined; vehicle.maxPassengerDuration = undefined; data[v_id] = vehicle; return Object.assign({}, state, { data: data, }); }; function removeConsumerFromVehicle(state, consumerId) { var vehicleId = state.consumersToVehiclesMap[consumerId]; if (!vehicleId) { return state; } var newState = _.cloneDeep(state); var consumers = newState.data[vehicleId].consumers; var consumerIndexToRemove = consumers.indexOf(consumerId); consumers.splice(consumerIndexToRemove, 1); return newState; } var mapConsumersToVehicles = function(state) { var consumersToVehiclesMap = {}; state.ids.forEach(function(v_id) { var vehicle = state.data[v_id]; vehicle.consumers.forEach(function(c_id){ if(consumersToVehiclesMap[c_id]) { console.err(`Consumer ${c_id} is assigned to ${consumersToVehiclesMap[c_id]} and ${v_id}`); } else { consumersToVehiclesMap[c_id] = v_id; } }) }) return Object.assign({}, state, { consumersToVehiclesMap: consumersToVehiclesMap }) } var setAmMaxPassDuration = function(state, directions) { var vehicle = Object.assign({}, state.data[directions.v_id]); var data = Object.assign({}, state.data); vehicle.maxPassengerDuration = Math.ceil(directions.morningRoute.maxPassengerDuration/60); data[directions.v_id] = vehicle; return Object.assign({}, state, {data: data}); } var resetVehicleOptimizationStatus = function(state){ var data = Object.assign({}, state.data); state.ids.forEach(function(v_id) { data[v_id] = Object.assign({}, data[v_id], {optimized: undefined, maxPassengerDuration: undefined}); }) return Object.assign({}, state, {data: data}); } var vehiclesReducer = function(state, action) { state = state || { ids: [], data: {}, consumersToVehiclesMap: {}, needToBeFetched: true }; switch (action.type) { case (wptATypes.WPT_ADD_SUCCESS): case (wptATypes.WPT_EDIT_SUCCESS): return commonCRUD.update(state, action.vehicle) case mapActions.MAP_REMOVE_FROM_ACTIVE_BUS_SUCCESS: case mapActions.MAP_ADD_TO_ACTIVE_BUS_SUCCESS: var newState = updateConsumersArray(state, action.v_id, action.consumersArray); return mapConsumersToVehicles(newState); case vehicleRouteActions.OPTIMIZE_ROUTE_SUCCESS: return commonCRUD.update(state, action.vehicle); case vehicleRouteActions.DIRECTIONS_LOAD_SUCCESS: return setAmMaxPassDuration(state, action.response); case actionTypes.DELETE: if(action.model === CONSUMERS && action.status === actionTypes.SUCCESS) { var newState = removeConsumerFromVehicle(state, action.id); return mapConsumersToVehicles(newState); } case actionTypes.UPDATE: if(action.model === SETTINGS && action.status === actionTypes.SUCCESS) { return resetVehicleOptimizationStatus(state); } } if (action.model != VEHICLES) { return state } switch (action.type) { case actionTypes.FETCH: if (action.status == actionTypes.LOADING) return commonCRUD.setRequested(state); if (action.status == actionTypes.SUCCESS){ var newState = commonCRUD.load(state, action.response); return mapConsumersToVehicles(newState); } if (action.status == actionTypes.ERROR) return commonCRUD.fetchError(state, action.error); case actionTypes.CREATE: if (action.status == actionTypes.SUCCESS) return commonCRUD.add(state, action.response); case actionTypes.UPDATE: if (action.status == actionTypes.SUCCESS) return commonCRUD.update(state, action.response); case actionTypes.DELETE: if (action.status == actionTypes.SUCCESS){ var newState = commonCRUD.destroy(state, action.id); return mapConsumersToVehicles(newState); } default: return state; } }; module.exports = vehiclesReducer;
/** * @fileOverview Comparison operation computations. * * Unlike `atum/value/compare`, these also handle object values. */ define(['exports', 'atum/compute', 'atum/fun', 'atum/operations/boolean', 'atum/operations/type_conversion', 'atum/operations/value_reference', 'atum/value/compare', 'atum/value/value'], function(exports, compute, fun, boolean, type_conversion, value_reference, compare, value) { "use strict"; /* Operations ******************************************************************************/ /** * Regular equality comparison of `left` and `right`. * * Will attempt type conversions. */ var equal = function(left, right) { return compute.binary( value_reference.getValue(left), value_reference.getValue(right), function(l, r) { if (value.isObject(l) && value.isObject(r)) return boolean.create(l === r); else if (value.isObject(l)) return compute.bind( type_conversion.toPrimitive(undefined, left), fun.curry(equal, right)); else if (value.isObject(r)) return compute.bind( type_conversion.toPrimitive(undefined, right), fun.curry(equal, left)); return boolean.create(compare.equal(l, r)); }); }; /** * Strict equality comparison of `left` and `right`. * * Does not attempt type conversion. */ var strictEqual = function(left, right) { return compute.binary( value_reference.getValue(left), value_reference.getValue(right), function(l, r) { return boolean.create(value.isObject(l) && value.isObject(r) ? (l === r) : compare.strictEqual(l, r)); }); }; /* Export ******************************************************************************/ exports.equal = equal; exports.strictEqual = strictEqual; });
module.exports = function() { var mongoose = require('mongoose'), config = require('./config'); // Connect to mongodb var options = { db: { native_parser: true }, server: { poolSize: 5 }, user: appConfig.database['USER_NAME'], pass: appConfig.database['PASSWORD'] }; mongoose.connect(config.db, options); connect(); mongoose.connection.on('error', console.log); mongoose.connection.on('disconnected', connect); }
const fluentify = require('../fluentify'); const expect = require('chai').expect; const sinon = require('sinon'); describe('Fluentify API', () => { it('does not decorate underscore properties', () => { const obj = { _one: 1, _two: '2', _three: [3], _four() { }, _five: {} }; const fluentObj = fluentify(obj); expect(fluentObj._one).to.equal(1); expect(fluentObj._two).to.equal('2') expect(fluentObj._three).to.eql([3]); expect(fluentObj._four.toString()).to.equal(obj._four.toString()); expect(fluentObj._five).to.eql({}); }); it('does not decorate non-function properties', () => { const obj = { one: 1, two: '2', three: [3], four: {} }; const sixBefore = obj.six; const fluentObj = fluentify(obj); expect(fluentObj.one).to.equal(1); expect(fluentObj.two).to.equal('2'); expect(fluentObj.three).to.eql([3]); expect(fluentObj.four).to.eql({}); }); it('decorates non-underscore function properties', () => { const obj = { one: 1, two() { }, three: [3], four() { }, five: {} }; const twoBefore = obj.two; const fourBefore = obj.four; const fluentObj = fluentify(obj); expect(fluentObj.one).to.equal(1); expect(fluentObj.two.toString()).to.not.equal(twoBefore.toString()); expect(fluentObj.two).to.be.a('function'); expect(fluentObj.three).to.eql([3]); expect(fluentObj.four.toString()).to.not.equal(fourBefore.toString()); expect(fluentObj.four).to.be.a('function'); expect(fluentObj.five).to.eql({}); }); it('returns wrapped instance', () => { const obj = { one() { } }; const fluentObj = fluentify(obj); expect(obj).to.equal(fluentObj); }) it('overrides "done" property', () => { const obj = { done: 1 }; const mock = sinon.mock(console); mock.expects('warn').withExactArgs('[Fluentify] "done" property will be overridden'); fluentify(obj); expect(obj.done).to.be.a('function'); mock.verify(); }); it('overrides "results" property', () => { const obj = { results: {} }; const mock = sinon.mock(console); mock.expects('warn').withExactArgs('[Fluentify] "results" property will be overridden'); fluentify(obj); expect(obj.results).to.be.a('function'); mock.verify(); }); it('attaches "done" function to instance', () => { const obj = {}; fluentify(obj); expect(obj.done).to.be.a('function'); }); it('attaches "results" function to instance', () => { const obj = {}; fluentify(obj); expect(obj.results).to.be.a('function'); }); describe('#done', () => { const obj = fluentify({ fooCalls: 0, foo(delay, cb) { ++this.fooCalls; return delay ? setTimeout(() => cb(null, this.fooCalls), delay) : cb(null, this.fooCalls); } }); beforeEach(() => { obj.fooCalls = 0; }); it('returns undefined when callback defined', () => { expect(obj.done(() => {})).to.not.exist; }) it('triggers callback when final call in the chain completes', done => { obj.foo(0).foo(500).foo(1000).foo(0).done(err => { expect(err, err).to.not.exist; expect(obj.fooCalls).to.equal(4); done(); }); }); it('binds results as callback parameters', done => { obj.foo(0).foo(500).foo(1000).done((err, ...results) => { expect(err, err).to.not.exist; expect(results).to.eql([[1], [2], [3]]); done(); }); }); it('returns Promise when no callback defined', () => { expect(obj.done()).to.be.a('Promise'); }); it('resolves when final call in chain completes', async () => { await obj.foo(0).foo(1000).foo(500).foo(0).done(); expect(obj.fooCalls).to.equal(4); }); it('resolves with results', async () => { const results = await obj.foo(0).foo(1000).foo(500).done(); expect(results).to.eql([[1], [2], [3]]); }); }); describe('FQL', () => { it('binds full result to parameter', async () => { const obj = fluentify({ inc(value, cb) { return cb(null, value + 1); } }); const results = await obj .inc(9) .inc('$1') .inc('$2') .inc('$3') .done(); expect(results).to.eql([[10], [11], [12], [13]]) }); it('binds result property to parameter', async () => { const api = fluentify({ init(cb) { return cb(null, { path: '0', child: { path: '0.0', child: { path: '0.0.0' } } }); }, foo(val, cb) { return cb(null, val); } }); const results = await api .init() .foo('$1.path') .foo('$1.child.path') .foo('$1.child.child.path') .done(); expect(results[1][0]).to.equal('0'); expect(results[2][0]).to.equal('0.0'); expect(results[3][0]).to.equal('0.0.0'); }); it('binds result array property to parameter', async () => { const api = fluentify({ init(cb) { return cb(null, { children: ['0', { children: ['0.0', { children: ['0.0.0'] }] }] }); }, foo(val, cb) { return cb(null, val); } }); const results = await api .init() .foo('$1.children.0') .foo('$1.children.1.children.0') .foo('$1.children.1.children.1.children.0') .done(); expect(results[1][0]).to.equal('0'); expect(results[2][0]).to.equal('0.0'); expect(results[3][0]).to.equal('0.0.0'); }); }) });
module.exports = (function () { var _ = require('lodash'); 'use strict'; /** route() - Create a middleware * * @method ExpressRedisCache.route * @return {Function} middleware */ function route () { /** The middleware to return * * @type Function */ var middleware; /** A reference to this * * @type ExpressRedisCache */ var self = this; /** The route options * * @type List */ var options = arguments; /** The domain handler * * @type Domain */ var domain = require('domain').create(); /** The domain error handler * * @type Domain */ domain.on('error', function (error) { self.emit('error', error); }); domain.run(function () { // Build the middleware function /** * @function * @arg {IncomingMessage} req * @arg {HttpResponse} res * @arg {Function} next */ middleware = function expressRedisCache_Middleware (req, res, next) { // If the cache isn't connected, call next() if ( self.connected === false || self.client.connected === false || req.query.bypassCache ) { return next(); } /** Cache entry name * * @type String * @description The name the cache entry will be saved under * @default req.originalUrl */ var name = req.originalUrl; // Bridg specific keys if(req.account_id) { name += '{' + req.account_id + '}'; } /** * @deprecated `res.expressRedisCacheName` is deprecated starting on v0.1.1, `use res.express_redis_cache_name` instead */ if ( res.expressRedisCacheName ) { self.emit('deprecated', { deprecated: 'expressRedisCacheName', substitute: 'express_redis_cache_name', file: __fileName, line: __line }); res.express_redis_cache_name = res.expressRedisCacheName; } // If a cache has been explicitly attached to `res` then use it as name if ( res.express_redis_cache_name ) { name = res.express_redis_cache_name; } // If route() was called with a string as its first argument, use this string as name if ( typeof options[0] === 'string' ) { name = options[0]; } if ( typeof options[0] === 'object' && typeof options[0].name === 'string' ) { name = options[0].name; } /** Name cannot have wildcards in them */ if ( /\*/.test(name) ) { return next(new Error('Name can not have wildcards')); } /** The seconds entry lives * * @type Number * @default this.expire */ var expire = self.expire; if ( typeof options[0] === 'object' ) { if ( typeof options[0].expire === 'number' || typeof options[0].expire === 'object' ) { expire = options[0].expire; } } if ( typeof options[0] === 'number' ) { expire = options[0]; } else if ( typeof options[1] === 'number' || typeof options[1] === 'object') { expire = options[1]; } var expirationPolicy = require('./expire')(expire); /** attempt to get cache **/ self.get(name, domain.bind(function (error, cache) { /** If there was an error with cache then call next **/ if ( error ) { return next(); } /** if it's cached, display cache **/ if ( cache.length ) { res.contentType(cache[0].type || "application/json"); res.send(cache[0].body); } /** otherwise, cache request **/ else { /** wrap res.send **/ var send = res.send.bind(res); if ( typeof res.use_express_redis_cache === 'undefined' ) { res.use_express_redis_cache = true; } res.send = function (body) { /** send output to HTTP client **/ send(body); if ( this.expressRedisCache ) { self.emit('deprecated', { deprecated: 'expressRedisCache', substitute: 'use_express_redis_cache', file: __fileName, line: __line }); this.use_express_redis_cache = this.expressRedisCache; } if ( this.use_express_redis_cache ) { /** Create the new cache **/ self.add(name, body, { type: res.get('Content-Type'), expire: expirationPolicy(res.statusCode) }, domain.intercept(function (name, cache) {})); } }; next(); } })); }; }); return middleware; } return route; }) ();
#!/usr/bin/env node require('./modules/config.js').loadConfig(); require('./db'); var version = process.versions.node.split('.'); if (version[0] === 0 && version[1] < 10) { console.error('Error: Cannot run in Node.js version < 0.10'); process.exit(1); } var optimist = require('optimist'); var args = process.argv; var arg0 = args.shift(); args.shift(); var command = args.shift(); var commands = require('./commands'); if (! command) { console.error('Usage: tckr <command>\n' + 'List of available commands:\n' + commands.list().map(bullet).join('\n')); process.exit(-1); } if (! ~commands.list().indexOf(command)) { console.error('Unknown command:', command); process.exit(-1); } var args = optimist(args); var module = commands.module(command); if (module.usage) { module.usage(command, args); } module(args.argv); function bullet(s) { return '\t' + s; }
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var Show = mongoose.model('Show'); router.get('/api/v1/shows', function(req, res, next) { Show.find(function(err, shows){ if(err){ return next(err); } res.json(shows); }); }); router.get('*', function(req, res) { res.sendfile('./public/index.html'); }); module.exports = router;
'use strict'; var fs = require('fs'); setTimeout(function(){ fs.writeFile('./test.txt', 'I ran!', function(err){ if(err){ throw err; } }); }, 3000);
module.exports = (sequelize, DataTypes) => { const UserGroups = sequelize.define('UserGroups', { userId: { allowNull: false, type: DataTypes.INTEGER }, groupId: { allowNull: false, type: DataTypes.INTEGER } }, { classMethods: { associate(models) { }, } }); return UserGroups; };
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'liststyle', 'sr-latn', { bulletedTitle: 'Bulleted List Properties', circle: 'Circle', decimal: 'Decimal (1, 2, 3, etc.)', disc: 'Disc', lowerAlpha: 'Lower Alpha (a, b, c, d, e, etc.)', lowerRoman: 'Lower Roman (i, ii, iii, iv, v, etc.)', none: 'None', notset: '<not set>', numberedTitle: 'Numbered List Properties', square: 'Square', start: 'Start', type: 'Type', upperAlpha: 'Upper Alpha (A, B, C, D, E, etc.)', upperRoman: 'Upper Roman (I, II, III, IV, V, etc.)', validateStartNumber: 'List start number must be a whole number.' } );
import React from 'react'; import CustomLineDot from './CustomLineDot'; import { changeNumberOfData } from './utils'; import { ResponsiveContainer, LineChart, Line, XAxis, YAxis, ReferenceLine, ReferenceDot, Tooltip, CartesianGrid, Legend, Brush } from 'recharts'; const data = [ { name: 'Page A', uv: 400, pv: 2400, amt: 2400 }, { name: 'Page B', uv: 300, pv: 4567, amt: 2400 }, { name: 'Page C', uv: 280, pv: 1398, amt: 2400 }, { name: 'Page D', uv: 200, pv: 9800, amt: 2400 }, { name: 'Page E', uv: 278, pv: 3908, amt: 2400 }, { name: 'Page F', uv: 189, pv: 4800, amt: 2400 }, ]; const data01 = [ { day: '05-01', wether: 'sunny' }, { day: '05-02', wether: 'sunny' }, { day: '05-03', wether: 'cloudy' }, { day: '05-04', wether: 'rain' }, { day: '05-05', wether: 'rain' }, { day: '05-06', wether: 'cloudy' }, { day: '05-07', wether: 'cloudy' }, { day: '05-08', wether: 'sunny' }, { day: '05-09', wether: 'sunny' }, ]; const data02 = [ { name: 'Page A', uv: 300, pv: 2600, amt: 3400 }, { name: 'Page B', uv: 400, pv: 4367, amt: 6400 }, { name: 'Page C', uv: 300, pv: 1398, amt: 2400 }, { name: 'Page D', uv: 200, pv: 9800, amt: 2400 }, { name: 'Page E', uv: 278, pv: 3908, amt: 2400 }, { name: 'Page F', uv: 189, pv: 4800, amt: 2400 }, { name: 'Page G', uv: 189, pv: 4800, amt: 2400 }, ]; const initilaState = { data, data01, data02, }; const renderSpecialDot = (props) => { const { cx, cy, stroke, key } = props; if (cx === +cx && cy === +cy) { return <path d={`M${cx - 2},${cy - 2}h4v4h-4Z`} fill={stroke} key={key}/>; } return null; }; const renderLabel = (props) => { const { x, y, textAnchor, key, value } = props; if (x === +x && y === +y) { return <text x={x} y={y} dy={-10} textAnchor={textAnchor} key={key}>{value}</text> } return null; }; export default React.createClass({ displayName: 'LineChartDemo', getInitialState() { return initilaState; }, handleChangeData() { this.setState(() => _.mapValues(initilaState, changeNumberOfData)); }, render() { const { data, data01, data02 } = this.state; return ( <div className='line-charts'> <a href="javascript: void(0);" className="btn update" onClick={this.handleChangeData} > change data </a> <br/> <p>A simple LineChart with fixed domain y-axis</p> <div className='line-chart-wrapper'> <LineChart width={400} height={400} data={data02} margin={{ top: 20, right: 40, bottom: 20, left: 20 }} syncId="test"> <CartesianGrid stroke='#f5f5f5'/> <Legend/> <XAxis/> <YAxis domain={[0, 350]} allowDataOverflow={true} /> <Tooltip /> <Line type='monotone' dataKey='uv' stroke='#ff7300' dot={renderSpecialDot} label={renderLabel}/> <Brush dataKey="name" height={30} /> </LineChart> </div> <p>A simple LineChart with customized line dot</p> <div className='line-chart-wrapper'> <LineChart width={400} height={400} data={data} margin={{ top: 20, right: 20, bottom: 20, left: 20 }} syncId="test"> <CartesianGrid stroke='#f5f5f5'/> <Legend /> <XAxis /> <YAxis domain={[0, 500]}/> <Tooltip /> <Line type='monotone' dataKey='uv' dot={<CustomLineDot/>} stroke='#ff7300'/> </LineChart> </div> <p>LineChart with two y-axes</p> <div className='line-chart-wrapper' style={{ padding: 40 }}> <LineChart width={400} height={400} data={data} margin={{top: 10, bottom: 10, left: 30, right: 30}}> <XAxis dataKey='name'/> <Tooltip/> <CartesianGrid stroke='#f5f5f5'/> <Line type='monotone' dataKey='uv' stroke='#ff7300' yAxisId={0} activeDot={{fill: '#ff7300', stroke: 'none'}}/> <Line type='monotone' dataKey='pv' stroke='#387908' yAxisId={1} activeDot={{fill: '#387908', stroke: 'none', r: 6}}/> </LineChart> </div> <p>LineChart with three y-axes</p> <div className='line-chart-wrapper' style={{ margin: 40 }}> <LineChart width={600} height={400} data={data}> <YAxis type='number' yAxisId={0} ticks={[0, 250]}/> <YAxis type='number' orientation='right' yAxisId={1}/> <YAxis type='number' orientation='right' yAxisId={2}/> <XAxis dataKey='name'/> <Tooltip/> <CartesianGrid stroke='#f5f5f5'/> <Line dataKey='uv' stroke='#ff7300' strokeWidth={2} yAxisId={0}/> <Line dataKey='pv' stroke='#387908' strokeWidth={2} yAxisId={1}/> <Line dataKey='amt' stroke='#38abc8' strokeWidth={2} yAxisId={2}/> </LineChart> </div> <p>LineChart when data change</p> <a href="javascript:void(0)" className="btn" onClick={() => { this.setState({ data: this.state.data === data ? data02 : data }); }} > change data </a> <div className="line-chart-wrapper"> <LineChart width={400} height={400} data={this.state.data} margin={{ top: 20, right: 20, bottom: 20, left: 20 }} > <CartesianGrid stroke="#f5f5f5" /> <Legend /> <XAxis /> <YAxis domain={[0, 500]} /> <Line type="monotone" dataKey="uv" dot={<CustomLineDot/>} stroke="#ff7300" /> </LineChart> </div> <p>LineChart of vertical layout</p> <div className='line-chart-wrapper' style={{ margin: 40 }}> <LineChart width={400} height={400} data={data} layout='vertical' margin={{top: 5, right: 20, left: 20, bottom: 5}}> <YAxis type='category' dataKey='name'/> <XAxis type='number' xAxisId={0} orientation='top'/> <XAxis type='number' xAxisId={1} orientation='bottom'/> <CartesianGrid stroke='#f5f5f5'/> <Line dataKey='uv' type="monotone" stroke='#ff7300' strokeWidth={2} xAxisId={0} /> <Line dataKey='pv' type="monotone" stroke='#387908' strokeWidth={2} xAxisId={1} /> </LineChart> </div> <p>LineChart of discrete values</p> <div className='line-chart-wrapper'> <LineChart width={400} height={400} data={data01} margin={{ top: 20, right: 20, bottom: 20, left: 20 }}> <XAxis dataKey="day"/> <YAxis type="category"/> <Tooltip/> <Line type="stepAfter" dataKey='wether' stroke='#ff7300'/> </LineChart> </div> </div> ); } });
export { default } from "./../../_gen/openfl/events/TextEvent";
$(document).ready(function(){ var $btn_renew = $('#btn_renew'); var $btn_change = $('#btn_change'); var $btn_delete = $('#btn_delete'); var $table = $('#table'); //设置bootstrap-table插件 function setBSTable() { $table.bootstrapTable({ toolbar : '#toolbar', showColumns : true, showToggle : true, pagination : true, showPaginationSwitch : false, clickToSelect : true, columns: [ { field: 'check', checkbox: true, align: 'center', valign: 'middle' }, { field: 'id', title: '序号', sortable: true, halign: 'center', align: 'right', width: 30 }, { field: 'type', title: '合同种类', halign: 'center' }, { field: 'number', title: '合同编号', halign: 'center' }, { field: 'category', title: '合同类型', halign: 'center' }, { field: 'title', title: '合同名称', halign: 'center' }, { field: 'version', title: '版本号', halign: 'center' }, { field: 'date', title: '上传时间', halign: 'center', sortable: true, align: 'center' } ], data: [ { id: 1, type: '新增', number: 'HT201923', category: '采购合同', title: '合同名称1', version: '1.0.1', date: '2017.06.23' }, { id: 2, type: '变更', number: 'HT1302923', category: '劳动合同', title: '合同名称2', version: '1.0.0', date: '2017.02.19' } ] }); setToolBtnDisableState(); $table.on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function () { setToolBtnDisableState(); }); //续签 $btn_renew.click(function () { if(!$(this).attr('disabled')) { //取表格的选中行数据 var arrselections = $table.bootstrapTable('getSelections'); if (arrselections.length <= 0) { toastr.warning('请选择有效数据'); return; } console.log(JSON.stringify(arrselections)); //根据选定的数据信息跳转到对应的页面 window.location.href='oa-contract-renew.html'; } }); //变更 $btn_change.click(function () { if(!$(this).attr('disabled')) { //取表格的选中行数据 var arrselections = $table.bootstrapTable('getSelections'); if (arrselections.length <= 0) { toastr.warning('请选择有效数据'); return; } console.log(JSON.stringify(arrselections)); //根据选定的数据信息跳转到对应的页面 window.location.href='oa-contract-change.html'; } }); //删除 $btn_delete.click(function () { //按钮如果不是disabled状态,则可进行操作 if(!$(this).attr('disabled')) { //取表格的选中行数据 var arrselections = $table.bootstrapTable('getSelections'); if (arrselections.length <= 0) { toastr.warning('请选择有效数据'); return; } BSModal.confirm({ content: "确认要删除选择的数据吗?" }).on(function (e) { if (!e) { return; } //此处仅是前端演示删除后的效果:删除表格条目,重置工具栏状态,显示删除成功的提示 var ids = getIdSelections(); $table.bootstrapTable('remove', { field: 'id', values: ids }); setToolBtnDisableState(); toastr.success('删除的数据已提交成功!'); }); } }); } function getIdSelections() { return $.map($table.bootstrapTable('getSelections'), function (row) { return row.id }); } function setToolBtnDisableState() { var tableSelections = $table.bootstrapTable('getSelections'); $btn_renew.attr('disabled', tableSelections.length != 1); $btn_change.attr('disabled', tableSelections.length != 1); $btn_delete.attr('disabled', !tableSelections.length); } setBSTable(); });
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 13c0 .55-.45 1-1 1H5c-.55 0-1-.45-1-1V7c0-.55.45-1 1-1h14c.55 0 1 .45 1 1v10zm-6-7c.55 0 1-.45 1-1s-.45-1-1-1h-1v-.01c0-.55-.45-1-1-1s-1 .45-1 1V8h-1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1h3v1h-3c-.55 0-1 .45-1 1s.45 1 1 1h1c0 .55.45 1 1 1s1-.45 1-1h1c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1h-3v-1h3z" /> , 'LocalAtmRounded');
// This is the webpack config used for unit tests. const path = require('path'); // var utils = require('./utils') const webpack = require('webpack'); const merge = require('webpack-merge'); const baseConfig = require('../webpack.config'); const webpackConfig = merge(baseConfig, { devtool: 'inline-source-map', resolve: { alias: { 'src': path.resolve('src'), }, }, plugins: [ new webpack.DefinePlugin({ 'process.env': '"test"', }), ] }); webpackConfig.module.loaders.push({ enforce: 'post', test: /\.js$/, use: { loader: 'istanbul-instrumenter-loader', options: { esModules: true } }, include: path.resolve('src'), exclude: [ /\.spec\.js$/, /node_modules/ ] }) // no need for app entry during tests delete webpackConfig.entry; module.exports = webpackConfig;
var through = require("through2"), gutil = require("gulp-util"), _ = require("lodash"); module.exports = function (options) { "use strict"; // if necessary check for required options(s), e.g. options hash, etc. if (!options) { throw new gutil.PluginError("gulp-translate-html", "No options supplied"); } // delimiters setting if(options.templateSettings) { _.assign(_.templateSettings, options.templateSettings); } /** * compile html file with object * @param {Object} file input file * @return {Object} compiled Template Object */ function compiler(file) { var compiled = _.template(file.contents); return compiled(options.messages); } // see "Writing a plugin" // https://github.com/gulpjs/gulp/blob/master/docs/writing-a-plugin/README.md function translateHtml(file, enc, callback) { /*jshint validthis:true*/ // Do nothing if no contents if (file.isNull()) { this.push(file); return callback(); } if (file.isStream()) { // http://nodejs.org/api/stream.html // http://nodejs.org/api/child_process.html // https://github.com/dominictarr/event-stream // accepting streams is optional this.emit("error", new gutil.PluginError("gulp-translate-html", "Stream content is not supported")); return callback(); } try { var compiled = compiler(file); // manipulate buffer in some way // http://nodejs.org/api/buffer.html file.contents = new Buffer(compiled); this.push(file); } catch(err) { this.emit('error', new gutil.PluginError('gulp-translate-html', err, {fileName: file.path})); } return callback(); } return through.obj(translateHtml); };
//= require graph/sigmajs.loadData //= require graph/sigmajs.searchNode //= require graph/sigmajs.fisheye //= require graph/sigmajs.circularLayout //= require graph/sigmajs.changeColors //= require graph/sigmajs.selectNodes //= require graph/sigmajs.buttonFilters //= require graph/sigmajs.nodesInfo //= require graph/sigmajs.layoutButtons //= require graph/sigmajs.events function init() { /*** VARIABLES ***/ zoom_min = 0.9; zoom_max = 4; init_x = -24; init_y = 42; cerebro = document.getElementById('js-graph'); if (cerebro == null) return; /*** CEREBRO INSTANTIATION ***/ //var defaultColor = 'rgb(119,221,119)'; $cerebro = $(cerebro); $cerebro_offset = $cerebro.offset(); var sigInst = sigma.init(cerebro).drawingProperties({ defaultLabelColor: '#fff', defaultLabelSize: 14, defaultLabelBGColor: '#fff', defaultLabelHoverColor: '#000', labelColor: "node", labelThreshold: 3, defaultEdgeType: 'curve' }).graphProperties({ minNodeSize: 1, maxNodeSize: $cerebro.attr('max_node_size') || 10, minEdgeSize: 1, maxEdgeSize: $cerebro.attr('max_edge_size') || 2, }).mouseProperties({ maxRatio: zoom_max, // Max zoom minRatio: zoom_min // Max dezoom }); sigInst.deselectColor = '#000'; sigInst.focusedNode = null; sigInst.delayForceAtlas = 5; sigInst.defaultColor = '#fff'; /*** END : CEREBRO INSTANTIATION ***/ /*** LAUNCH MODULES ***/ sigInst.loadData($cerebro); sigInst.deactivateFishEye(); sigInst.circularLayout(); sigInst.startForceAtlas2(); sigInst.searchNode(); sigInst.typeNodeFilter(); sigInst.typeLinkFilter(); sigInst.layoutButtons(); sigInst.bindEvents($cerebro); sigInst.nodeInfoLinksInit(); /*** END : LAUNCH MODULES ***/ /*setInterval(function() { console.log(sigInst.position()); }, 100);*/ } if (document.addEventListener) { document.addEventListener('DOMContentLoaded', init, false); } else { window.onload = init; }
/** * Created by M08180 on 21/10/2015. */ import Reflux from "reflux"; import Actions from "../../actions/actions.js"; import MyCartStore from '../MyCart/MyCart.store.js'; import _ from 'lodash'; import http from '../../core/HttpClient'; let CommercialOffers = Reflux.createStore({ listenables: [Actions], init: function(){ this.offers = []; this.listenTo(MyCartStore, this.onMyCartChange); this.getCommercialOffers(MyCartStore.list); }, onMyCartChange: function(items){ this.getCommercialOffers(items); }, getCommercialOffers: function(items) { var urlToCall = 'http://henri-potier.xebia.fr/books/'; if(!items || !items.length || items.length === 0){ return []; }else { for (var i = 0; i < items.length; i++) { for(var j = 0; j < items[i].qqt; j++) { urlToCall += items[i].isbn; if (i < items.length - 1) { urlToCall += ','; } } } urlToCall += '/commercialOffers'; http.get(urlToCall) .then(data => { this.offers = data.offers; this.trigger(this.offers); }) .catch(err => { console.error(err); }); } } }); export default CommercialOffers;
var should = require('chai').should() , sinon = require('sinon') , BusterGlob = require('buster-glob') , fs = require('fs') , JSHint = require('jshint') , Lint = require('./../lib/lint'); var jshintSettings = { "predef": [ ], "node" : true, "camelcase" : true, "indent" : 2, "boss" : false, "curly": false, "debug": false, "devel": false, "eqeqeq": true, "eqnull": false, "evil": true, "expr": true, "forin": false, "immed": false, "laxbreak": false, "laxcomma": true, "newcap": true, "noarg": true, "noempty": false, "nonew": false, "nomen": false, "onevar": false, "plusplus": false, "regexp": false, "strict": false, "sub": true, "undef": true, "white": true }; describe("Lint", function () { var readFileStub; before(function () { sinon.stub(BusterGlob, "glob").yields(null, ["file1.js", "file2.js"]); sinon.stub(fs, "lstatSync", function () { return { isFile: function () { return true; } }; }); readFileStub = sinon.stub(fs, "readFileSync"); }); after(function () { readFileStub.restore(); }); it("should lint successfully", function (done) { readFileStub.withArgs("file1.js").returns('var a = 0;'); readFileStub.withArgs("file2.js").returns('var b = 0;'); var lint = new Lint(); lint.on('done', function () { lint.report().should.have.length(1); done(); }); lint.globs(["test/index.js"], jshintSettings); }); it("should lint with failures", function (done) { readFileStub.withArgs("file1.js").returns('var a = 5\nvar b = (a == 5);'); readFileStub.withArgs("file2.js").returns('var b = 5;'); var lint = new Lint(); lint.on('done', function () { lint.report().should.have.length(3); lint.hasErrors().should.be.true; done(); }); lint.globs(["test/index.js"], jshintSettings); }); });
export default (entityData = []) => (_, { id }) => entityData.find((d) => d.id == id);
const Joi = require('joi'); module.exports = { schema: Joi.object().keys({ meta: Joi.object().keys({ id: Joi.string().required(), description: Joi.string().required(), name: Joi.string().required(), repository: Joi.string().required(), version: Joi.string().required(), }).required(), computation: Joi.object().keys({ command: Joi.array() .items(Joi.string().required()) .min(1) .required(), display: Joi.any().required(), dockerImage: Joi.string().required(), input: Joi.any().required(), output: Joi.any().required(), type: Joi.string().required(), remote: Joi.object().keys({ command: Joi.array() .items(Joi.string().required()) .min(1) .required(), dockerImage: Joi.string().required(), type: Joi.string().required(), }), }).required(), }), };
import { setData } from '@progress/kendo-angular-intl'; setData({ name: "fr-CD", likelySubtags: { fr: "fr-Latn-FR" }, identity: { language: "fr", territory: "CD" }, territory: "CD", calendar: { patterns: { d: "dd/MM/y", D: "EEEE d MMMM y", m: "d MMM", M: "d MMMM", y: "MMM y", Y: "MMMM y", F: "EEEE d MMMM y HH:mm:ss", g: "dd/MM/y HH:mm", G: "dd/MM/y HH:mm:ss", t: "HH:mm", T: "HH:mm:ss", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" }, dateTimeFormats: { full: "{1} 'à' {0}", long: "{1} 'à' {0}", medium: "{1} 'à' {0}", short: "{1} {0}", availableFormats: { d: "d", E: "E", Ed: "E d", Ehm: "E h:mm a", EHm: "E HH:mm", Ehms: "E h:mm:ss a", EHms: "E HH:mm:ss", Gy: "y G", GyMMM: "MMM y G", GyMMMd: "d MMM y G", GyMMMEd: "E d MMM y G", h: "h a", H: "HH 'h'", hm: "h:mm a", Hm: "HH:mm", hms: "h:mm:ss a", Hms: "HH:mm:ss", hmsv: "h:mm:ss a v", Hmsv: "HH:mm:ss v", hmv: "h:mm a v", Hmv: "HH:mm v", M: "L", Md: "dd/MM", MEd: "E dd/MM", MMM: "LLL", MMMd: "d MMM", MMMEd: "E d MMM", MMMMd: "d MMMM", "MMMMW-count-one": "'semaine' W 'de' MMM", "MMMMW-count-other": "'semaine' W 'de' MMM", ms: "mm:ss", y: "y", yM: "MM/y", yMd: "dd/MM/y", yMEd: "E dd/MM/y", yMMM: "MMM y", yMMMd: "d MMM y", yMMMEd: "E d MMM y", yMMMM: "MMMM y", yQQQ: "QQQ y", yQQQQ: "QQQQ y", "yw-count-one": "'semaine' w 'de' y", "yw-count-other": "'semaine' w 'de' y" } }, timeFormats: { full: "HH:mm:ss zzzz", long: "HH:mm:ss z", medium: "HH:mm:ss", short: "HH:mm" }, dateFormats: { full: "EEEE d MMMM y", long: "d MMMM y", medium: "d MMM y", short: "dd/MM/y" }, days: { format: { abbreviated: [ "dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam." ], narrow: [ "D", "L", "M", "M", "J", "V", "S" ], short: [ "di", "lu", "ma", "me", "je", "ve", "sa" ], wide: [ "dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi" ] }, "stand-alone": { abbreviated: [ "dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam." ], narrow: [ "D", "L", "M", "M", "J", "V", "S" ], short: [ "di", "lu", "ma", "me", "je", "ve", "sa" ], wide: [ "dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi" ] } }, months: { format: { abbreviated: [ "janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc." ], narrow: [ "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" ], wide: [ "janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre" ] }, "stand-alone": { abbreviated: [ "janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc." ], narrow: [ "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D" ], wide: [ "janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre" ] } }, quarters: { format: { abbreviated: [ "T1", "T2", "T3", "T4" ], narrow: [ "1", "2", "3", "4" ], wide: [ "1er trimestre", "2e trimestre", "3e trimestre", "4e trimestre" ] }, "stand-alone": { abbreviated: [ "T1", "T2", "T3", "T4" ], narrow: [ "1", "2", "3", "4" ], wide: [ "1er trimestre", "2e trimestre", "3e trimestre", "4e trimestre" ] } }, dayPeriods: { format: { abbreviated: { midnight: "minuit", am: "AM", noon: "midi", pm: "PM", morning1: "mat.", afternoon1: "ap.m.", evening1: "soir", night1: "nuit" }, narrow: { midnight: "min.", am: "AM", noon: "midi", pm: "PM", morning1: "mat.", afternoon1: "ap.m.", evening1: "soir", night1: "nuit" }, wide: { midnight: "minuit", am: "AM", noon: "midi", pm: "PM", morning1: "du matin", afternoon1: "de l’après-midi", evening1: "du soir", night1: "de nuit" } }, "stand-alone": { abbreviated: { midnight: "minuit", am: "AM", noon: "midi", pm: "PM", morning1: "mat.", afternoon1: "ap.m.", evening1: "soir", night1: "nuit" }, narrow: { midnight: "min.", am: "AM", noon: "midi", pm: "PM", morning1: "mat.", afternoon1: "ap.m.", evening1: "soir", night1: "nuit" }, wide: { midnight: "minuit", am: "AM", noon: "midi", pm: "PM", morning1: "matin", afternoon1: "après-midi", evening1: "soir", night1: "nuit" } } }, eras: { format: { wide: { 0: "avant Jésus-Christ", 1: "après Jésus-Christ", "0-alt-variant": "avant l’ère commune", "1-alt-variant": "de l’ère commune" }, abbreviated: { 0: "av. J.-C.", 1: "ap. J.-C.", "0-alt-variant": "AEC", "1-alt-variant": "EC" }, narrow: { 0: "av. J.-C.", 1: "ap. J.-C.", "0-alt-variant": "AEC", "1-alt-variant": "EC" } } }, gmtFormat: "UTC{0}", gmtZeroFormat: "UTC", dateFields: { era: { wide: "ère", short: "ère", narrow: "ère" }, year: { wide: "année", short: "an", narrow: "a" }, quarter: { wide: "trimestre", short: "trim.", narrow: "trim." }, month: { wide: "mois", short: "m.", narrow: "m." }, week: { wide: "semaine", short: "sem.", narrow: "sem." }, weekOfMonth: { wide: "Week Of Month", short: "Week Of Month", narrow: "Week Of Month" }, day: { wide: "jour", short: "j", narrow: "j" }, dayOfYear: { wide: "Day Of Year", short: "Day Of Year", narrow: "Day Of Year" }, weekday: { wide: "jour de la semaine", short: "jour de la semaine", narrow: "jour de la semaine" }, weekdayOfMonth: { wide: "Weekday Of Month", short: "Weekday Of Month", narrow: "Weekday Of Month" }, dayperiod: { short: "cadran", wide: "cadran", narrow: "cadran" }, hour: { wide: "heure", short: "h", narrow: "h" }, minute: { wide: "minute", short: "min", narrow: "min" }, second: { wide: "seconde", short: "s", narrow: "s" }, zone: { wide: "fuseau horaire", short: "fuseau horaire", narrow: "fuseau horaire" } } }, firstDay: 1 });
module.exports = function(grunt) { grunt.initConfig ({ sass: { dist: { files: { 'public/css/style.css' : 'src/scss/application.scss' } } }, watch: { options: { livereload: true }, source: { files: ['gruntfile.js','src/scss/**/*.scss','src/js/**/*.js'], tasks: ['rebuild'], options: { livereload: false, // needed to run LiveReload } }, express: { files: ['views/**/*.ejs'], tasks: [ 'express:dev' ], options: { spawn: false // for grunt-contrib-watch v0.5.0+, "nospawn: true" for lower versions. Without this option specified express won't be reloaded } } }, concat: { main: { src: ['src/js/*.js'], dest: 'public/scripts/main.js', }, vendor: { src: ['src/js/vendor/*.js'], dest: 'public/scripts/vendor.js', }, }, uglify: { dist: { files: { 'public/scripts/main.min.js': ['public/scripts/main.js'], 'public/scripts/vendor.min.js': ['public/scripts/vendor.js'], } } }, cssmin: { target: { files: [{ expand: true, cwd: 'public/css', src: ['style.css', '!*.min.css'], dest: 'public/css', ext: '.min.css' }] } }, express: { dev: { options: { script: 'app.js' } } }, copy: { main: { expand: true, cwd: 'src/fonts', src: '**', dest: 'public/css/fonts', }, loader: { expand: true, cwd: 'src/img', src: 'ajax-loader.gif', dest: 'public/css/' }, img: { expand: true, cwd: 'src/img', src: '**', dest: 'public/images/' }, }, }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-express-server'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.registerTask('rebuild', ['sass', 'concat', 'uglify', 'cssmin']); grunt.registerTask('dev', ['rebuild', 'express', 'watch']); grunt.registerTask('default', ['copy','sass', 'concat', 'uglify', 'cssmin']); };
'use strict'; var frisby = require('frisby'); var config = require('../../test-config.json'); var args = config[process.env.test || 'local']; var host = args.host, clientId = args.clientId, usr = args.user1, pwd = args.password1; //Testing the happy path for user-course CRUD frisby.create('Log in') .post(host + '/token', { grant_type: 'password', username: usr, password: pwd, client_id: clientId }) .afterJSON(function (json) { frisby.globalSetup({ request: { headers: { 'Authorization': 'Bearer ' + json.access_token } } }); var course = { courseDescription: 'Gopher Hills - White Tees' }; frisby.create('Create course') .post(host + '/api/users/courses', course, { json: true }) .expectHeaderContains('content-type', 'json') .expectStatus(201) .afterJSON(function (myCourse) { var key = myCourse.key; myCourse.courseDescription = 'Gopher Hills - White Tees - Front 9'; frisby.create('Get courses') .get(host + '/api/users/courses') .expectStatus(200) .expectHeaderContains('content-type', 'application/json') .expectJSONTypes('*', { //weird array checking syntax: http://frisbyjs.com/docs/api/ key: Number, userId: String, courseDescription: String }) .toss(); frisby.create('Get course by id') .get(host + '/api/users/courses/' + key) .expectStatus(200) .expectHeaderContains('content-type', 'application/json') .expectJSONTypes({ key: Number, userId: String, courseDescription: String }) .toss(); frisby.create('Update a course') .put(host + '/api/users/courses/' + key, myCourse, {json: true}) .expectStatus(204) .after(function () { frisby.create('Delete a course') .delete(host + '/api/users/courses/' + key) .expectStatus(200) .toss(); }) .toss(); }) .toss(); }) .toss();
import type { Config } from './../../types/Redis.type'; import type { Environment } from './../../types/Environment.type'; function config(environment: Environment = process.env): Config { const isProd = environment.NODE_ENV === 'production'; return { host: isProd ? environment.REDISHOST : '127.0.0.1', port: isProd ? environment.REDISPORT : '6379', password: isProd ? environment.REDISAUTH : '', }; } export default config;
'use strict' module.exports = concatRows var extend = require('util-extend') var ops = require('ndarray-ops') var pool = require('ndarray-scratch') var defaults = { dtype: 'double' } function concatRows () { var output, input, inputs, options, d, i, shape, idx, l, slice options = extend({}, defaults) if (arguments.length === 0) { throw new Error('Array of ndarrays to concatenate must not be empty') } if (Array.isArray(arguments[0])) { // If the first argument is an array, then assume it's the list // of arrays to concatenate: inputs = arguments[0] extend(options, arguments[1] || {}) } else if (arguments.length === 2) { // Otherwise assume the first argument is the output array: inputs = arguments[1] output = arguments[0] extend(options, arguments[2] || {}) } if (inputs.length === 0) { throw new Error('Array of ndarrays to concatenate must not be empty') } for (d = 0; d < inputs.length; d++) { // Verify the other dimensions: if (!shape) { // If no shape is set, set it: shape = inputs[d].shape.slice(0) } else { // At the very least, all arrays must share teh same dimensionality: if (inputs[d].dimension !== shape.length) { throw new Error('all arrays must have the same dimensionality') } // If shape is set, then this shape must match: for (i = 1; i < inputs[d].shape.length; i++) { if (inputs[d].shape[i] !== shape[i]) { throw new Error('last n-1 dimensions of concatenated rows must have the same size') } } // Add to the size of the concatenated dimension: shape[0] += inputs[d].shape[0] } } if (output) { if (shape[0] !== output.shape[0]) { throw new Error('first dimension of output array must match the total number of concatenated rows') } } else { // NB: Nothing after this can fail, otherwise we leak memory. So all // assertions MUST happen before this. output = pool.zeros(shape, options.dtype) } for (i = 0, idx = 0; i < inputs.length; i++) { input = inputs[i] l = input.shape[0] slice = output.lo(idx).hi(l) ops.assign(slice, input) idx += l } return output }
// // Copyright (c) 2015 by Mattermind Labs. All Rights Reserved. // var React = require('react'); var SchemeStore = require('../stores/SchemeStore'); var PaletteStore = require('../stores/PaletteStore'); var SchemeVar = require('./SchemeVar.react'); var _ = require('lodash'); function getState() { return { schemeVars: SchemeStore.getAll(), path: SchemeStore.path() }; } module.exports = React.createClass({ getInitialState: function() { return getState(); }, componentDidMount: function() { SchemeStore.addChangeListener(this._onChange); PaletteStore.addChangeListener(this._onChange); }, componentWillUnmount: function() { SchemeStore.removeChangeListener(this._onChange); PaletteStore.removeChangeListener(this._onChange); }, _onChange: function() { this.setState(getState()); }, render: function() { var svs = _.map(this.state.schemeVars, function(value, key) { return ( <SchemeVar key={key} name={key} value={value} /> ); }); return ( <div> <h1>{this.state.path}</h1> {svs} </div> ); } });
import { action, computed, observable } from 'mobx' import api from './_api' export default class ExamStore { @observable words @observable test @observable done @observable selectedWord @observable hintLevel @observable lastAnswer @observable testPhase @observable leitnerCats constructor() { this.reset() } reset() { this.words = [] this.done = [] this.test = undefined this.selectedWord = undefined this.hintLevel = 0 this.testPhase = 0 this.lastAnswer = undefined } startTest(words, test) { this.test = test this.words = words this.checkAdaptiveDifficulty() this.sortWordsToMotivate() this.selectWord(this.words[0]) } selectWord(word) { if (!word.answers) word.answers = [] if (!word.repeat) word.repeat = undefined this.selectedWord = word } checkAdaptiveDifficulty() { this.words.forEach(w => { if (w.word_users && w.word_users.length === 1) { w.difficulty = w.word_users[0].adaptive_difficulty } }) } sortWordsToMotivate() { // sorts words the easiest, the most difficult, // second easiest, second most difficult... var tmp = this.words.slice() var i this.words = [] var easiest = true while (tmp.length > 0) { if (easiest) { i = this.findMinDifficulty(tmp) easiest = false } else { i = this.findMaxDifficulty(tmp) easiest = true } this.words.push(tmp[i]) tmp.splice(i, 1) } } findMaxDifficulty(words) { var difficulties = [] words.forEach(w => difficulties.push(w.difficulty)) return difficulties.indexOf(difficulties.max()) } findMinDifficulty(words) { var difficulties = [] words.forEach(w => difficulties.push(w.difficulty)) return difficulties.indexOf(difficulties.min()) } @action answer(text, isRecall) { var rightAnswer = isRecall ? this.selectedWord.value : this.selectedWord.meaning var dist = rightAnswer.levenshtein(text) var answerType = this.answeredWithHint(this.answerType(dist, rightAnswer.length), this.hintLevel) if (!this.selectedWord.repeat) { this.selectedWord.repeat = this.repeat(answerType, this.selectedWord.difficulty) } let answ = { isRecall: isRecall, answer: answerType, hintLevel: this.hintLevel } this.lastAnswer = answ this.selectedWord.answers.push(answ) if (this.isDone(this.selectedWord)) { this.selectedWord.done = true this.done.push(this.selectedWord) this.words = this.words.filter(w => w != this.selectedWord) console.log('Word is done!') this.saveWord(this.selectedWord) if (this.words.length === 0) { console.log('Test is done!') return this.reset() } } } @action nextWord() { this.lastAnswer = undefined this.hintLevel = 0 if (this.testPhase === 0) { var currentI = this.words.indexOf(this.selectedWord) if (currentI + 1 === this.words.length) { this.testPhase = 1 this.splitToLeitnerCats() this.selectWord(this.words[0]) return true } else { this.selectWord(this.words[currentI + 1]) return true } } if (!this.done.includes(this.selectedWord)) { this.selectedWord.leitnerCat = this.newLeitnerCat() } if (!this.done.includes(this.selectedWord)) { this.placeCurrentQuestion() } this.selectedWord.flag = true this.selectedWord = this.words.find(w => w.leitnerCat <= this.testPhase && !w.flag) if (!this.selectedWord) { this.words.forEach(w => w.flag = false) this.selectedWord = this.words[0] this.testPhase = (this.testPhase + 1) % 4 } } placeCurrentQuestion() { const questionsLeitnerCat = this.words.filter(w => w.leitnerCat === this.selectedWord.leitnerCat && !w.done) const lastInLeitnerCat = questionsLeitnerCat[questionsLeitnerCat.length - 1] const iCurrent = this.words.indexOf(this.selectedWord) const iLastInLeitnerCat = this.words.indexOf(lastInLeitnerCat) for (let i = iCurrent; i < iLastInLeitnerCat; i++) { this.words[i] = this.words[i + 1] } this.words[iLastInLeitnerCat] = this.selectedWord } newLeitnerCat() { var cat = this.selectedWord.leitnerCat const a = this.selectedWord.answers[this.selectedWord.answers.length - 1].answer !== 'W' if (this.testPhase === 1 || this.testPhase === 2) { return a ? 2 : 1 } else if (this.testPhase === 3) { return !a ? 1 : (cat === 3 ? 3 : cat + 1) } return cat } isDone(word) { // checks last anwers of passed word // returns true if last n answers are A or R and last answer is not A // otherwise returns false let answers = word.answers.concat() answers = answers.slice(1) if (answers.length < word.repeat) { return false } answers = answers.slice(-1 * word.repeat) for (var i = 0; i < answers.length; i++) { if (answers[i].answer === 'W') { return false } } if (answers[answers.length - 1].answer === 'A') { return false } return true } splitToLeitnerCats() { this.words = this.words.sort(this.sortByLastAnswerDifficulty) const int = Math.floor(this.words.length / 3) let setLeitnerCat = (i) => { return (q) => { q.leitnerCat = i } } for (var i = 1; i < 3; i++) { this.words.slice((i - 1) * int, i * int).forEach(setLeitnerCat(i)) } this.words.slice(2 * int).forEach(setLeitnerCat(3)) } sortByLastAnswerDifficulty(a, b) { let answers = { 'W': 1, 'A': 2, 'R': 3 } let numA = answers[a.answers.slice(-1)[0]['answer']] let numB = answers[b.answers.slice(-1)[0]['answer']] if (numA > numB) return 1 if (numB > numA) return -1 if (a.difficulty > b.difficulty) return -1 if (a.difficulty < b.difficulty) return 1 return 0 } repeat(answer, difficulty) { // returns number of required successful answers // based on answer and global difficulty if (answer === 'W' && difficulty >= 3) { return 3 } if (answer !== 'W' && difficulty <= 2) { return 1 } if (difficulty <= 3) { return 2 } return 3 } answeredWithHint(answer, hintLevel) { // if student used more than one hint, // answer level is lowered if (hintLevel >= 1 && answer === 'R') { return 'A' } return answer } answerType(levenDist, answerLength) { // 1/6 wrong letter == spelling mistake var l = Math.floor(answerLength / 6) if (levenDist === 0) { return 'R' } if (levenDist <= l) { return 'A' } return 'W' } fetchTestWords(test, success = () => {}, failure = () => {}) { let store = this api.get(`/tests/${test.id}/words/exam/`).then(response => { store.startTest(response.data, test) console.log('Words were successfuly fetched.') success() }, errors => { console.log(errors, errors.response) failure() }) } saveWord(word, success = () => {}, failure = () => {}) { let data = { words: [{ id: word.id, difficulty: this.getLeitnerDifficulty(word.leitnerCat), done: word.done ? 'True' : '', test: this.test.id }] } this.saveUserWords(data, success, failure) } getLeitnerDifficulty(leitnerCat) { if (leitnerCat === 1) return 3 else if (leitnerCat === 3) return 1 return 2 } saveWords(success = () => {}, failure = () => {}) { if (this.testPhase === 0) { return success() } let data = { words: [] } this.words.forEach(w => { data.words.push({ id: w.id, difficulty: this.getLeitnerDifficulty(w.leitnerCat), done: w.done ? 'True' : '', test: this.test.id }) }) this.done.forEach(w => { data.words.push({ id: w.id, difficulty: this.getLeitnerDifficulty(w.leitnerCat), done: w.done ? 'True' : '', test: this.test.id }) }) this.saveUserWords(data, success, failure) } saveUserWords(data, success = () => {}, failure = () => {}) { let store = this api.post(`/words/user/`, data).then(response => { console.log('User\'s words are successfuly saved.') success() }, errors => { console.log(errors, errors.response) failure() }) } }
if ( 'Promise' in ( typeof window !== 'undefined' ? window : self ) ) { /*! localForage -- Offline Storage, Improved Version 1.3.1 https://mozilla.github.io/localForage (c) 2013-2015 Mozilla, Apache License 2.0 */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["localforage"] = factory(); else root["localforage"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { 'use strict'; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE]; var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function (self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function () { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function () { try { return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem; } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function () { var _args = arguments; return localForageInstance.ready().then(function () { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var LocalForage = (function () { function LocalForage(options) { _classCallCheck(this, LocalForage); this.INDEXEDDB = DriverType.INDEXEDDB; this.LOCALSTORAGE = DriverType.LOCALSTORAGE; this.WEBSQL = DriverType.WEBSQL; this._defaultConfig = extend({}, DefaultConfig); this._config = extend({}, this._defaultConfig, options); this._driverSet = null; this._initDriver = null; this._ready = false; this._dbInfo = null; this._wrapLibraryMethodsWithReady(); this.setDriver(this._config.driver); } // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function config(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof options === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof options === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { var promise = new Promise(function (resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); var namingError = new Error('Custom driver name already in use: ' + driverObject._driver); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function (supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); promise.then(callback, errorCallback); return promise; }; LocalForage.prototype.driver = function driver() { return this._driver || null; }; LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { var self = this; var getDriverPromise = (function () { if (isLibraryDriver(driverName)) { switch (driverName) { case self.INDEXEDDB: return new Promise(function (resolve, reject) { resolve(__webpack_require__(1)); }); case self.LOCALSTORAGE: return new Promise(function (resolve, reject) { resolve(__webpack_require__(2)); }); case self.WEBSQL: return new Promise(function (resolve, reject) { resolve(__webpack_require__(4)); }); } } else if (CustomDrivers[driverName]) { return Promise.resolve(CustomDrivers[driverName]); } return Promise.reject(new Error('Driver not found.')); })(); getDriverPromise.then(callback, errorCallback); return getDriverPromise; }; LocalForage.prototype.getSerializer = function getSerializer(callback) { var serializerPromise = new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }); if (callback && typeof callback === 'function') { serializerPromise.then(function (result) { callback(result); }); } return serializerPromise; }; LocalForage.prototype.ready = function ready(callback) { var self = this; var promise = self._driverSet.then(function () { if (self._ready === null) { self._ready = self._initDriver(); } return self._ready; }); promise.then(callback, callback); return promise; }; LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { var self = this; if (!isArray(drivers)) { drivers = [drivers]; } var supportedDrivers = this._getSupportedDrivers(drivers); function setDriverToConfig() { self._config.driver = self.driver(); } function initDriver(supportedDrivers) { return function () { var currentDriverIndex = 0; function driverPromiseLoop() { while (currentDriverIndex < supportedDrivers.length) { var driverName = supportedDrivers[currentDriverIndex]; currentDriverIndex++; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._extend(driver); setDriverToConfig(); self._ready = self._initStorage(self._config); return self._ready; })['catch'](driverPromiseLoop); } setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; } return driverPromiseLoop(); }; } // There might be a driver initialization in progress // so wait for it to finish in order to avoid a possible // race condition to set _dbInfo var oldDriverSetDone = this._driverSet !== null ? this._driverSet['catch'](function () { return Promise.resolve(); }) : Promise.resolve(); this._driverSet = oldDriverSetDone.then(function () { var driverName = supportedDrivers[0]; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._driver = driver._driver; setDriverToConfig(); self._wrapLibraryMethodsWithReady(); self._initDriver = initDriver(supportedDrivers); }); })['catch'](function () { setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; }); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function supports(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { var supportedDrivers = []; for (var i = 0, len = drivers.length; i < len; i++) { var driverName = drivers[i]; if (this.supports(driverName)) { supportedDrivers.push(driverName); } } return supportedDrivers; }; LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } }; LocalForage.prototype.createInstance = function createInstance(options) { return new LocalForage(options); }; return LocalForage; })(); var localForage = new LocalForage(); exports['default'] = localForage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 1 */ /***/ function(module, exports) { // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; var dbContexts; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // Fetch a blob using ajax. This reveals bugs in Chrome < 43. // For details on all this junk: // https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme function _blobAjax(url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = function () { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { return resolve({ response: xhr.response, type: xhr.getResponseHeader('Content-Type') }); } reject({ status: xhr.status, response: xhr.response }); }; xhr.send(); }); } // // Detect blob support. Chrome didn't support it until version 38. // In version 37 they had a broken version where PNGs (and possibly // other binary types) aren't stored correctly, because when you fetch // them, the content type is always null. // // Furthermore, they have some outstanding bugs where blobs occasionally // are read by FileReader as null, or by ajax as 404s. // // Sadly we use the 404 bug to detect the FileReader bug, so if they // get fixed independently and released in different versions of Chrome, // then the bug could come back. So it's worthwhile to watch these issues: // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // function _checkBlobSupportWithoutCaching(idb) { return new Promise(function (resolve, reject) { var blob = _createBlob([''], { type: 'image/png' }); var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.oncomplete = function () { // have to do it in a separate transaction, else the correct // content type is always returned var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key'); getBlobReq.onerror = reject; getBlobReq.onsuccess = function (e) { var storedBlob = e.target.result; var url = URL.createObjectURL(storedBlob); _blobAjax(url).then(function (res) { resolve(!!(res && res.type === 'image/png')); }, function () { resolve(false); }).then(function () { URL.revokeObjectURL(url); }); }; }; })['catch'](function () { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function (value) { supportsBlobs = value; return supportsBlobs; }); } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise(function (resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function (e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return _createBlob([arrayBuff], { type: encodedBlob.type }); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } // Initialize a singleton container for all running localForages. if (!dbContexts) { dbContexts = {}; } // Get the current context of the database; var dbContext = dbContexts[dbInfo.name]; // ...or create a new context. if (!dbContext) { dbContext = { // Running localForages sharing a database. forages: [], // Shared database. db: null }; // Register the new context in the global container. dbContexts[dbInfo.name] = dbContext; } // Register itself as a running localForage in the current context. dbContext.forages.push(this); // Create an array of readiness of the related localForages. var readyPromises = []; function ignoreErrors() { // Don't handle errors here, // just makes sure related localForages aren't pending. return Promise.resolve(); } for (var j = 0; j < dbContext.forages.length; j++) { var forage = dbContext.forages[j]; if (forage !== this) { // Don't wait for itself... readyPromises.push(forage.ready()['catch'](ignoreErrors)); } } // Take a snapshot of the related localForages. var forages = dbContext.forages.slice(0); // Initialize the connection process only when // all the related localForages aren't pending. return Promise.all(readyPromises).then(function () { dbInfo.db = dbContext.db; // Get the connection or open a new one without upgrade. return _getOriginalConnection(dbInfo); }).then(function (db) { dbInfo.db = db; if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } return db; }).then(function (db) { dbInfo.db = dbContext.db = db; self._dbInfo = dbInfo; // Share the final connection amongst related localForages. for (var k = 0; k < forages.length; k++) { var forage = forages[k]; if (forage !== self) { // Self is already up-to-date. forage._dbInfo.db = dbInfo.db; forage._dbInfo.version = dbInfo.version; } } }); } function _getOriginalConnection(dbInfo) { return _getConnection(dbInfo, false); } function _getUpgradedConnection(dbInfo) { return _getConnection(dbInfo, true); } function _getConnection(dbInfo, upgradeNeeded) { return new Promise(function (resolve, reject) { if (dbInfo.db) { if (upgradeNeeded) { dbInfo.db.close(); } else { return resolve(dbInfo.db); } } var dbArgs = [dbInfo.name]; if (upgradeNeeded) { dbArgs.push(dbInfo.version); } var openreq = indexedDB.open.apply(indexedDB, dbArgs); if (upgradeNeeded) { openreq.onupgradeneeded = function (e) { var db = openreq.result; try { db.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // Added when support for blob shims was added db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } } catch (ex) { if (ex.name === 'ConstraintError') { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); } else { throw ex; } } }; } openreq.onerror = function () { reject(openreq.error); }; openreq.onsuccess = function () { resolve(openreq.result); }; }); } function _isUpgradeNeeded(dbInfo, defaultVersion) { if (!dbInfo.db) { return true; } var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); var isDowngrade = dbInfo.version < dbInfo.db.version; var isUpgrade = dbInfo.version > dbInfo.db.version; if (isDowngrade) { // If the version is not the default one // then warn for impossible downgrade. if (dbInfo.version !== defaultVersion) { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); } // Align the versions to prevent errors. dbInfo.version = dbInfo.db.version; } if (isUpgrade || isNewStore) { // If the store is new then increment the version (if needed). // This will trigger an "upgradeneeded" event which is required // for creating a store. if (isNewStore) { var incVersion = dbInfo.db.version + 1; if (incVersion > dbInfo.version) { dbInfo.version = incVersion; } } return true; } return false; } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function () { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function () { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); if (result !== void 0) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { var dbInfo; self.ready().then(function () { dbInfo = self._dbInfo; if (value instanceof Blob) { return _checkBlobSupport(dbInfo.db).then(function (blobSupport) { if (blobSupport) { return value; } return _encodeBlob(value); }); } return value; }).then(function (value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function () { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `.delete()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function () { resolve(); }; transaction.onerror = function () { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function () { resolve(); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function () { resolve(req.result); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function () { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function () { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor['continue'](); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = asyncStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; if (dbInfo.storeName !== self._defaultConfig.storeName) { dbInfo.keyPrefix += dbInfo.storeName + '/'; } self._dbInfo = dbInfo; return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function () { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = dbInfo.serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var keyPrefix = dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = dbInfo.serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void 0) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function (keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function (resolve, reject) { var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { try { localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = localStorageWrapper; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; (function () { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Get out of our habit of using `window` inline, at least. var globalObject = this; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (err) { if (err.name !== 'TypeError') { throw err; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function () { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return _createBlob([buffer], { type: blobType }); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i += 4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); /*jslint bitwise: true */ bytes[p++] = encoded1 << 2 | encoded2 >> 4; bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if (bytes.length % 3 === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; exports['default'] = localforageSerializer; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; } } var dbInfoPromise = new Promise(function (resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return self.setDriver(self.LOCALSTORAGE).then(function () { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function (t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { self._dbInfo = dbInfo; resolve(); }, function (t, error) { reject(error); }); }); }); return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = dbInfo.serializer.deserialize(result); } resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = dbInfo.serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void 0) { resolve(result); return; } } resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { dbInfo.db.transaction(function (t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () { resolve(originalValue); }, function (t, error) { reject(error); }); }, function (sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { var result = results.rows.item(0).c; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = webSQLStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ } /******/ ]) }); ; }
(function () { 'use strict'; var Marionette = require('backbone.marionette'); var Behaviors = { /* your behaviors here */ }; Marionette.Behaviors.behaviorsLookup = function () { return Behaviors; }; })();
var MapProc = { voronoi: new Voronoi(), diagram: null, margin: 0.0, canvas: null, numberOfNodes: 1000, bbox: { xl: 0, xr: 800, yt: 0, yb: 600 }, numberOfPlates: 14, plateRootIds: [], sites: [], numberOfIterations: 2, showPlates: true, treemap: null, voronoiSiteColor: '#0000ff', voronoiEdgeColor: '#333', voronoiNotHoverColor:'#ffffff', voronoiHoverColor: '#f00000', voronoiEdgeRecolor: '#444', mouseButtonPressed: false, init: function() { this.canvas = document.getElementById('voronoiCanvas'); this.randomSites(this.numberOfNodes, true); for (var i = 0; i < this.numberOfIterations; i++) { this.relaxSites(); } this.treemap = this.buildTreemap(); this.plateRootIds = this.selectPlateStartingCellIds(); for(i in this.plateRootIds) { if(this.showPlates) { this.renderCell(this.plateRootIds[i], '#ff0000',this.voronoiEdgeColor); } } this.render(); }, clickMouse: function() { this.mouseButtonPressed = true; }, unClickMouse: function() { this.mouseButtonPressed = false; }, compute: function(sites) { this.sites = sites; this.voronoi.recycle(this.diagram); this.diagram = this.voronoi.compute(sites, this.bbox); this.treemap = this.buildTreemap(); }, inArray: function(array, value) { for (var i = 0; i < array.length; i++) { if (array[i] == value) return true; } return false; }, selectPlateStartingCellIds: function(numberToSelect) { var arr = []; var i=0; while(i < this.numberOfPlates) { var randomNumber = Math.floor(Math.random() * this.numberOfNodes); if(!this.inArray(arr, randomNumber)) { arr.push(randomNumber); i++; } } return arr; }, clearSites: function() { this.compute([]); }, randomSites: function(n, clear) { var sites = []; if (!clear) { sites = this.sites.slice(0); } // create vertices var xmargin = this.canvas.width * this.margin, ymargin = this.canvas.height * this.margin, xo = xmargin, dx = this.canvas.width - xmargin * 2, yo = ymargin, dy = this.canvas.height - ymargin * 2; for (var i = 0; i < n; i++) { sites.push({ x: self.Math.round((xo + self.Math.random() * dx) * 10) / 10, y: self.Math.round((yo + self.Math.random() * dy) * 10) / 10 }); } this.compute(sites); }, relaxSites: function() { if (!this.diagram) { return; } var cells = this.diagram.cells, iCell = cells.length, cell, site, sites = [], rn, dist; var p = 1 / iCell * 0.1; while (iCell--) { cell = cells[iCell]; rn = Math.random(); // probability of apoptosis if (rn < p) { continue; } site = this.cellCentroid(cell); dist = this.distance(site, cell.site); // don't relax too fast if (dist > 2) { site.x = (site.x + cell.site.x) / 2; site.y = (site.y + cell.site.y) / 2; } // probability of mytosis if (rn > (1 - p)) { dist /= 2; sites.push({ x: site.x + (site.x - cell.site.x) / dist, y: site.y + (site.y - cell.site.y) / dist, }); } sites.push(site); } this.compute(sites); }, distance: function(a, b) { var dx = a.x - b.x, dy = a.y - b.y; return Math.sqrt(dx * dx + dy * dy); }, cellArea: function(cell) { var area = 0, halfedges = cell.halfedges, iHalfedge = halfedges.length, halfedge, p1, p2; while (iHalfedge--) { halfedge = halfedges[iHalfedge]; p1 = halfedge.getStartpoint(); p2 = halfedge.getEndpoint(); area += p1.x * p2.y; area -= p1.y * p2.x; } area /= 2; return area; }, cellCentroid: function(cell) { var x = 0, y = 0, halfedges = cell.halfedges, iHalfedge = halfedges.length, halfedge, v, p1, p2; while (iHalfedge--) { halfedge = halfedges[iHalfedge]; p1 = halfedge.getStartpoint(); p2 = halfedge.getEndpoint(); v = p1.x * p2.y - p2.x * p1.y; x += (p1.x + p2.x) * v; y += (p1.y + p2.y) * v; } v = this.cellArea(cell) * 6; return { x: x / v, y: y / v }; }, buildTreemap: function() { var treemap = new QuadTree({ x: this.bbox.xl, y: this.bbox.yt, width: this.numberOfNodes * 5, height: this.numberOfNodes * 5 }); var cells = this.diagram.cells, iCell = cells.length; while (iCell--) { bbox = cells[iCell].getBbox(); bbox.cellid = iCell; treemap.insert(bbox); } return treemap; }, cellUnderMouse: function(ev) { if (!this.diagram) { return; } var canvas = document.getElementById('voronoiCanvas'); if (!canvas) { return; } var x = 0, y = 0; if (!ev) { ev = window.event; } console.log(ev); if (ev.pageX || ev.pageY) { x = ev.pageX; y = ev.pageY; } else if (e.clientX || e.clientY) { x = ev.clientX + document.body.scrollLeft + document.documentElement .scrollLeft; y = ev.clientY + document.body.scrollTop + document.documentElement .scrollTop; } x -= canvas.offsetLeft; y -= canvas.offsetTop; cellid = this.cellIdFromPoint(x, y); if(this.mouseButtonPressed) { if (this.lastCellId !== cellid) { if (this.lastCellId !== undefined) { this.renderCell(this.lastCellId, this.voronoiNotHoverColor, this.voronoiEdgeRecolor); } if (cellid !== undefined) { this.renderCell(cellid, this.voronoiHoverColor, this.voronoiEdgeColor); } this.lastCellId = cellid; } } document.getElementById('voronoiCellId').innerHTML = "(" + x + "," + y + ") = " + cellid; }, cellIdFromPoint: function(x, y) { // We build the treemap on-demand if (this.treemap === null) { return; } // Get the Voronoi cells from the tree map given x,y var items = this.treemap.retrieve({ x: x, y: y }), iItem = items.length, cells = this.diagram.cells, cell, cellid; while (iItem--) { cellid = items[iItem].cellid; cell = cells[cellid]; if (cell.pointIntersection(x, y) > 0) { return cellid; } } return undefined; }, renderCell: function(id, fillStyle, strokeStyle) { if (id === undefined) { return; } if (!this.diagram) { return; } var cell = this.diagram.cells[id]; if (!cell) { return; } var drawingContext = this.canvas.getContext('2d'); drawingContext.globalAlpha = 1; // edges drawingContext.beginPath(); var halfedges = cell.halfedges, nHalfedges = halfedges.length, v = halfedges[0].getStartpoint(); drawingContext.moveTo(v.x, v.y); for (var iHalfedge = 0; iHalfedge < nHalfedges; iHalfedge++) { v = halfedges[iHalfedge].getEndpoint(); drawingContext.lineTo(v.x, v.y); } drawingContext.fillStyle = fillStyle; drawingContext.strokeStyle = strokeStyle; drawingContext.fill(); drawingContext.stroke(); // site v = cell.site; drawingContext.fillStyle = this.voronoiSiteColor; drawingContext.beginPath(); drawingContext.rect(v.x - 2 / 3, v.y - 2 / 3, 2, 2); drawingContext.fill(); }, render: function() { var drawingContext = this.canvas.getContext('2d'); // background drawingContext.globalAlpha = 1; drawingContext.beginPath(); drawingContext.rect(0, 0, this.canvas.width, this.canvas.height); drawingContext.fillStyle = this.voronoiNotHoverColor; drawingContext.fill(); drawingContext.stokeStyle = this.voronoiEdgeColor; drawingContext.stroke(); // voronoi // if (!this.diagram) { // return; // } // // edges // drawingContext.beginPath(); // drawingContext.strokeStyle = this.voronoiEdgeColor; // var edges = this.diagram.edges, // iEdge = edges.length, // edge, v; // while (iEdge--) { // edge = edges[iEdge]; // v = edge.va; // drawingContext.moveTo(v.x, v.y); // v = edge.vb; // drawingContext.lineTo(v.x, v.y); // } // drawingContext.stroke(); // // sites // drawingContext.beginPath(); // drawingContext.fillStyle = this.voronoiSiteColor; // var sites = this.sites, // iSite = sites.length; // while (iSite--) { // v = sites[iSite]; // drawingContext.rect(v.x - 2 / 3, v.y - 2 / 3, 2, 2); // } // drawingContext.fill(); } };
// Allow a form to post without navigating to another page: postForm = function(oFormElement) { if (!oFormElement.action) { return; } var oReq = new XMLHttpRequest(); if (oFormElement.method.toLowerCase() === "post") { oReq.open("post", oFormElement.action); oReq.send(new FormData(oFormElement)); } else { console.error("Can only use post with this!"); } } // Make it so ctrl-Enter can send a message: onKeyDown = function(e) { var keynum; var keychar; var numcheck; keynum = e.keyCode; if (e.ctrlKey && (keynum == 13 || // ctrl-Enter keynum == 77)) // ctrl-M (ctrl-Enter on mac firefox does // this) { postForm(document.forms["messageForm"]); document.getElementById('content').value=''; return false; } return true; } // Called every time a new message shows up from the server: onMessage = function(m) { // Parse the message received from the server: var messages = JSON.parse(m.data); var posted_at_bottom = false; var height_before = document.body.clientHeight; for (var i = 0; i < messages.length; i++) { var message = messages[i]; var newDiv = document.createElement("div"); newDiv.setAttribute("class", "message"); newDiv.setAttribute("data-messageid", message.id); var newB = document.createElement("b"); newB.setAttribute("title", message.email); newB.textContent = message.name + " (" + message.topic + ") [" + message.date + "]"; var newBlockquote = document.createElement("blockquote"); newBlockquote.textContent = message.content; newDiv.appendChild(newB); newDiv.appendChild(newBlockquote); // Now we need to figure out where to add this message. var document_messages = document.getElementsByClassName("message"); var document_messages_length = document_messages.length|0; // Optimize for the common cases of it being inserted first or last: if (document_messages_length == 0 || parseInt(document_messages[document_messages.length-1].attributes["data-messageid"].value) < message.id) { var bottom = document.getElementsByClassName("bottom")[0]; document.body.insertBefore(newDiv, bottom); posted_at_bottom = true; } else { for (var j = 0; j < document_messages_length; j = j+1|0) { if (document_messages[j].attributes["data-messageid"].value == message.id) { // Discard duplicate message: break; } else if (document_messages[j].attributes["data-messageid"].value > message.id) { document.body.insertBefore(newDiv, document_messages[j]); break; } } } } var height_after = document.body.clientHeight; // Lame attempt at making the window not scroll as we insert new messages at // the top. This doesn't always work very well, feel free to improve this // if you are reading this. :-) var new_scroll_position = height_after - height_before; if (new_scroll_position > 0 && !posted_at_bottom) { window.scroll(0, new_scroll_position); } } onOpen = function() { console.log("Channel to server opened."); var document_messages = document.getElementsByClassName("message"); var document_messages_length = document_messages.length|0; if(document_messages_length == 0) { fetchMoreMessages(); } } onError = function(e) { console.log("Error taking to server: " + e.description + " [code: " + e.code + "]."); } onClose = function() { console.log("Channel to server closed"); // Just sleep 5s and retry: setTimeout(openChannel, 5000); } var websocket; // Initialization, called once upon page load: openChannel = function() { var loc = window.location, new_uri; if (loc.protocol === "https:") { new_uri = "wss:"; } else { new_uri = "ws:"; } new_uri += "//" + loc.host; new_uri += loc.pathname + "/websocket"; websocket = new WebSocket(new_uri); websocket.onopen = onOpen; websocket.onmessage = onMessage; websocket.onerror = onError; websocket.onclose = onClose; } fetchMoreMessages = function() { var document_messages = document.getElementsByClassName("message"); var document_messages_length = document_messages.length|0; var last_id = -1; if(document_messages_length > 0) { last_id = parseInt(document_messages[0].attributes["data-messageid"].value); } var request = { first_id: 0, // Ask for as many messages as we can get last_id: last_id } websocket.send(JSON.stringify(request)); } window.addEventListener('scroll', function() { // If the user scrolls up to the top of the window, load some older // messages to display for them and insert them into the top. if (window.scrollY == 0){ fetchMoreMessages(); } }) ; window.addEventListener('DOMContentLoaded', function() { // Scroll to bottom of document window.scrollTo(0, document.body.scrollHeight); // Open channel back to server to get new messages: openChannel(); }, false);
var assert = require('assert'); var Client = require('../'); var Put = require('put'); var zmq = require('zmq'); var testLiveCli = require('./util').testLiveCli; var config = {}; var port = config.blkport = config.txport = 'ipc:///tmp/ob-test-port'; var block0 = { height: 0, header: '0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c', tx: ['4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b'] }; var block1 = { height: 1, header: '010000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000982051fd1e4ba744bbbe680e1fee14677ba1a3c3540bf7b1cdb606e857233e0e61bc6649ffff001d01e36299', tx: ['0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098'] }; block0 = encodeBlock(block0); block1 = encodeBlock(block1); function encodeBlock(block) { var resp = [ Put().word32le(block.height).buffer(), Buffer(block.header, 'hex') ]; block.tx.forEach(function(tx) { resp.push(Buffer(tx, 'hex')); }); return resp; } describe('api liveBlocks()', function() { it('should receive blocks', function(done) { var socket = zmq.socket('pub'); socket.bindSync(port); var ob = new Client(config); var got = []; ob.on('block', function(block) { got.push(block); }).subscribeBlocks(); setTimeout(function() { socket.send(block0); socket.send(block1); }, 10); setTimeout(function() { ob.unsubscribeBlocks(); socket.send(block1); }, 20); setTimeout(function() { assert.equal(got.length, 2); done(); }, 30); }); });
(function() { //Templates used here. Makes it easy to update. var listBodyTemplate = '<input-list-body>' + '<button data-list-id="%n-item-list" class="input-list-add-button">+</button>' + '<span><input class="input-list-add-text" type="text" title="New Item" /></span>' + '<ul id="%n-item-list" data-form-input-id="%n-form-input"></ul>' + '<input id="%n-form-input" name="%n" class="input-list-form-input" value="[]" />' + '</input-list-body>'; var listItemTemplate = '<button data-list-id="%n" class="input-list-remove-button">-</button>' + '<p>%v</p>'; //Generates the HTML elements and structure for the lists. var generateInputList = function(listElement) { var name = listElement.getAttribute('name'); /* Other attributes possible... oh boy! var max = listElement.getAttribute('max'); var min = listElement.getAttribute('min'); */ listElement.innerHTML += listBodyTemplate.replace(new RegExp('%n', 'g'), name); listElement.getElementsByClassName('input-list-add-button')[0].addEventListener('click', addButtonClick); }; //Adds an item to the list var addButtonClick = function(e) { e.preventDefault(); var input = this.parentElement.getElementsByClassName('input-list-add-text')[0]; if (!(input.value.match(/^ *$/) !== null || input.value === null)) { var newItem = document.createElement('li'); newItem.innerHTML = listItemTemplate.replace('%v', input.value).replace('%n', this.dataset.listId); this.parentElement.getElementsByTagName('ul')[0].appendChild(newItem); newItem.getElementsByClassName('input-list-remove-button')[0].addEventListener('click', removeButtonClick); input.value = ''; resolveJSONList(this.dataset.listId); newItem.className += 'show'; } }; //Removes an item from the list var removeButtonClick = function(e) { e.preventDefault(); var btn = this; var li = this.parentElement; var ul = li.parentElement; li.className = ""; setTimeout(function() { ul.removeChild(li); resolveJSONList(btn.dataset.listId); }, 250); }; //Creates JSON object from items in list var resolveJSONList = function(listId) { var listElement = document.getElementById(listId); var listEntries = listElement.getElementsByTagName('li'); var entries = []; for (var i = 0; i < listEntries.length; i++) { entries.push(listEntries[i].getElementsByTagName('p')[0].innerText); } document.getElementById(listElement.dataset.formInputId).value = encodeURIComponent(JSON.stringify(entries)); }; //Generates our list structure for each input-list element window.onload = function() { var lists = document.getElementsByTagName('input-list'); for (var i = 0; i < lists.length; i++) { generateInputList(lists[i]); } }; })();
#!/usr/bin/env node /** * Zenvia SMS Callbacks Server - Usage Examples * * Functions: * startServer(port) - Set API Credentials * events - Promise to listen received data from Zenvia SMS Servers * * * Delivery status example: * { * "callbackMtRequest": { * "status": "03", * "statusMessage": "Delivered", * "statusDetail": "120", * "statusDetailMessage": "Message received by mobile", * "id": "hs765939216", * "received": "2014-08-26T12:55:48.593-03:00", * "mobileOperatorName": "any" * } * } * * Received SMS example: * { * "callbackMoRequest": { * "id": "20690090", * "mobile": "5551999999999", * "shortCode": "40001", * "account": "zenvia.account", * "body": "Message content", * "received": "2014-08-26T12:27:08.488-03:00", * "correlatedMessageSmsId": "hs765939061" * } * } * */ const zenviaCS = require('../index').callbacksServer; zenviaCS.startServer(81); zenviaCS.events.on('event', (data) => { console.log(data); });
(function($, undefined) { /** * Unobtrusive scripting adapter for jQuery * https://github.com/rails/jquery-ujs * * Requires jQuery 1.8.0 or later. * * Released under the MIT license * */ // Cut down on the number of issues from people inadvertently including jquery_ujs twice // by detecting and raising an error when it happens. 'use strict'; if ( $.rails !== undefined ) { $.error('jquery-ujs has already been loaded!'); } // Shorthand to make it a little easier to call public rails functions from within rails.js var rails; var $document = $(document); $.rails = rails = { // Link elements bound by jquery-ujs linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote]:not([disabled]), a[data-disable-with], a[data-disable]', // Button elements bound by jquery-ujs buttonClickSelector: 'button[data-remote]:not([form]):not(form button), button[data-confirm]:not([form]):not(form button)', // Select elements bound by jquery-ujs inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]', // Form elements bound by jquery-ujs formSubmitSelector: 'form', // Form input elements bound by jquery-ujs formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type]), input[type=submit][form], input[type=image][form], button[type=submit][form], button[form]:not([type])', // Form input elements disabled during form submission disableSelector: 'input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled, input[data-disable]:enabled, button[data-disable]:enabled, textarea[data-disable]:enabled', // Form input elements re-enabled after form submission enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled, input[data-disable]:disabled, button[data-disable]:disabled, textarea[data-disable]:disabled', // Form required input elements requiredInputSelector: 'input[name][required]:not([disabled]), textarea[name][required]:not([disabled])', // Form file input elements fileInputSelector: 'input[name][type=file]:not([disabled])', // Link onClick disable selector with possible reenable after remote submission linkDisableSelector: 'a[data-disable-with], a[data-disable]', // Button onClick disable selector with possible reenable after remote submission buttonDisableSelector: 'button[data-remote][data-disable-with], button[data-remote][data-disable]', // Up-to-date Cross-Site Request Forgery token csrfToken: function() { return $('meta[name=csrf-token]').attr('content'); }, // URL param that must contain the CSRF token csrfParam: function() { return $('meta[name=csrf-param]').attr('content'); }, // Make sure that every Ajax request sends the CSRF token CSRFProtection: function(xhr) { var token = rails.csrfToken(); if (token) xhr.setRequestHeader('X-CSRF-Token', token); }, // Make sure that all forms have actual up-to-date tokens (cached forms contain old ones) refreshCSRFTokens: function(){ $('form input[name="' + rails.csrfParam() + '"]').val(rails.csrfToken()); }, // Triggers an event on an element and returns false if the event result is false fire: function(obj, name, data) { var event = $.Event(name); obj.trigger(event, data); return event.result !== false; }, // Default confirm dialog, may be overridden with custom confirm dialog in $.rails.confirm confirm: function(message) { return confirm(message); }, // Default ajax function, may be overridden with custom function in $.rails.ajax ajax: function(options) { return $.ajax(options); }, // Default way to get an element's href. May be overridden at $.rails.href. href: function(element) { return element[0].href; }, // Checks "data-remote" if true to handle the request through a XHR request. isRemote: function(element) { return element.data('remote') !== undefined && element.data('remote') !== false; }, // Submits "remote" forms and links with ajax handleRemote: function(element) { var method, url, data, withCredentials, dataType, options; if (rails.fire(element, 'ajax:before')) { withCredentials = element.data('with-credentials') || null; dataType = element.data('type') || ($.ajaxSettings && $.ajaxSettings.dataType); if (element.is('form')) { method = element.data('ujs:submit-button-formmethod') || element.attr('method'); url = element.data('ujs:submit-button-formaction') || element.attr('action'); data = $(element[0]).serializeArray(); // memoized value from clicked submit button var button = element.data('ujs:submit-button'); if (button) { data.push(button); element.data('ujs:submit-button', null); } element.data('ujs:submit-button-formmethod', null); element.data('ujs:submit-button-formaction', null); } else if (element.is(rails.inputChangeSelector)) { method = element.data('method'); url = element.data('url'); data = element.serialize(); if (element.data('params')) data = data + '&' + element.data('params'); } else if (element.is(rails.buttonClickSelector)) { method = element.data('method') || 'get'; url = element.data('url'); data = element.serialize(); if (element.data('params')) data = data + '&' + element.data('params'); } else { method = element.data('method'); url = rails.href(element); data = element.data('params') || null; } options = { type: method || 'GET', data: data, dataType: dataType, // stopping the "ajax:beforeSend" event will cancel the ajax request beforeSend: function(xhr, settings) { if (settings.dataType === undefined) { xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script); } if (rails.fire(element, 'ajax:beforeSend', [xhr, settings])) { element.trigger('ajax:send', xhr); } else { return false; } }, success: function(data, status, xhr) { element.trigger('ajax:success', [data, status, xhr]); }, complete: function(xhr, status) { element.trigger('ajax:complete', [xhr, status]); }, error: function(xhr, status, error) { element.trigger('ajax:error', [xhr, status, error]); }, crossDomain: rails.isCrossDomain(url) }; // There is no withCredentials for IE6-8 when // "Enable native XMLHTTP support" is disabled if (withCredentials) { options.xhrFields = { withCredentials: withCredentials }; } // Only pass url to `ajax` options if not blank if (url) { options.url = url; } return rails.ajax(options); } else { return false; } }, // Determines if the request is a cross domain request. isCrossDomain: function(url) { var originAnchor = document.createElement('a'); originAnchor.href = location.href; var urlAnchor = document.createElement('a'); try { urlAnchor.href = url; // This is a workaround to a IE bug. urlAnchor.href = urlAnchor.href; // If URL protocol is false or is a string containing a single colon // *and* host are false, assume it is not a cross-domain request // (should only be the case for IE7 and IE compatibility mode). // Otherwise, evaluate protocol and host of the URL against the origin // protocol and host. return !(((!urlAnchor.protocol || urlAnchor.protocol === ':') && !urlAnchor.host) || (originAnchor.protocol + '//' + originAnchor.host === urlAnchor.protocol + '//' + urlAnchor.host)); } catch (e) { // If there is an error parsing the URL, assume it is crossDomain. return true; } }, // Handles "data-method" on links such as: // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a> handleMethod: function(link) { var href = rails.href(link), method = link.data('method'), target = link.attr('target'), csrfToken = rails.csrfToken(), csrfParam = rails.csrfParam(), form = $('<form method="post" action="' + href + '"></form>'), metadataInput = '<input name="_method" value="' + method + '" type="hidden" />'; if (csrfParam !== undefined && csrfToken !== undefined && !rails.isCrossDomain(href)) { metadataInput += '<input name="' + csrfParam + '" value="' + csrfToken + '" type="hidden" />'; } if (target) { form.attr('target', target); } form.hide().append(metadataInput).appendTo('body'); form.submit(); }, // Helper function that returns form elements that match the specified CSS selector // If form is actually a "form" element this will return associated elements outside the from that have // the html form attribute set formElements: function(form, selector) { return form.is('form') ? $(form[0].elements).filter(selector) : form.find(selector); }, /* Disables form elements: - Caches element value in 'ujs:enable-with' data store - Replaces element text with value of 'data-disable-with' attribute - Sets disabled property to true */ disableFormElements: function(form) { rails.formElements(form, rails.disableSelector).each(function() { rails.disableFormElement($(this)); }); }, disableFormElement: function(element) { var method, replacement; method = element.is('button') ? 'html' : 'val'; replacement = element.data('disable-with'); if (replacement !== undefined) { element.data('ujs:enable-with', element[method]()); element[method](replacement); } element.prop('disabled', true); element.data('ujs:disabled', true); }, /* Re-enables disabled form elements: - Replaces element text with cached value from 'ujs:enable-with' data store (created in `disableFormElements`) - Sets disabled property to false */ enableFormElements: function(form) { rails.formElements(form, rails.enableSelector).each(function() { rails.enableFormElement($(this)); }); }, enableFormElement: function(element) { var method = element.is('button') ? 'html' : 'val'; if (element.data('ujs:enable-with') !== undefined) { element[method](element.data('ujs:enable-with')); element.removeData('ujs:enable-with'); // clean up cache } element.prop('disabled', false); element.removeData('ujs:disabled'); }, /* For 'data-confirm' attribute: - Fires `confirm` event - Shows the confirmation dialog - Fires the `confirm:complete` event Returns `true` if no function stops the chain and user chose yes; `false` otherwise. Attaching a handler to the element's `confirm` event that returns a `falsy` value cancels the confirmation dialog. Attaching a handler to the element's `confirm:complete` event that returns a `falsy` value makes this function return false. The `confirm:complete` event is fired whether or not the user answered true or false to the dialog. */ allowAction: function(element) { var message = element.data('confirm'), answer = false, callback; if (!message) { return true; } if (rails.fire(element, 'confirm')) { try { answer = rails.confirm(message); } catch (e) { (console.error || console.log).call(console, e.stack || e); } callback = rails.fire(element, 'confirm:complete', [answer]); } return answer && callback; }, // Helper function which checks for blank inputs in a form that match the specified CSS selector blankInputs: function(form, specifiedSelector, nonBlank) { var foundInputs = $(), input, valueToCheck, radiosForNameWithNoneSelected, radioName, selector = specifiedSelector || 'input,textarea', requiredInputs = form.find(selector), checkedRadioButtonNames = {}; requiredInputs.each(function() { input = $(this); if (input.is('input[type=radio]')) { // Don't count unchecked required radio as blank if other radio with same name is checked, // regardless of whether same-name radio input has required attribute or not. The spec // states https://www.w3.org/TR/html5/forms.html#the-required-attribute radioName = input.attr('name'); // Skip if we've already seen the radio with this name. if (!checkedRadioButtonNames[radioName]) { // If none checked if (form.find('input[type=radio]:checked[name="' + radioName + '"]').length === 0) { radiosForNameWithNoneSelected = form.find( 'input[type=radio][name="' + radioName + '"]'); foundInputs = foundInputs.add(radiosForNameWithNoneSelected); } // We only need to check each name once. checkedRadioButtonNames[radioName] = radioName; } } else { valueToCheck = input.is('input[type=checkbox],input[type=radio]') ? input.is(':checked') : !!input.val(); if (valueToCheck === nonBlank) { foundInputs = foundInputs.add(input); } } }); return foundInputs.length ? foundInputs : false; }, // Helper function which checks for non-blank inputs in a form that match the specified CSS selector nonBlankInputs: function(form, specifiedSelector) { return rails.blankInputs(form, specifiedSelector, true); // true specifies nonBlank }, // Helper function, needed to provide consistent behavior in IE stopEverything: function(e) { $(e.target).trigger('ujs:everythingStopped'); e.stopImmediatePropagation(); return false; }, // Replace element's html with the 'data-disable-with' after storing original html // and prevent clicking on it disableElement: function(element) { var replacement = element.data('disable-with'); if (replacement !== undefined) { element.data('ujs:enable-with', element.html()); // store enabled state element.html(replacement); } element.bind('click.railsDisable', function(e) { // prevent further clicking return rails.stopEverything(e); }); element.data('ujs:disabled', true); }, // Restore element to its original state which was disabled by 'disableElement' above enableElement: function(element) { if (element.data('ujs:enable-with') !== undefined) { element.html(element.data('ujs:enable-with')); // set to old enabled state element.removeData('ujs:enable-with'); // clean up cache } element.unbind('click.railsDisable'); // enable element element.removeData('ujs:disabled'); } }; if (rails.fire($document, 'rails:attachBindings')) { $.ajaxPrefilter(function(options, originalOptions, xhr){ if ( !options.crossDomain ) { rails.CSRFProtection(xhr); }}); // This event works the same as the load event, except that it fires every // time the page is loaded. // // See https://github.com/rails/jquery-ujs/issues/357 // See https://developer.mozilla.org/en-US/docs/Using_Firefox_1.5_caching $(window).on('pageshow.rails', function () { $($.rails.enableSelector).each(function () { var element = $(this); if (element.data('ujs:disabled')) { $.rails.enableFormElement(element); } }); $($.rails.linkDisableSelector).each(function () { var element = $(this); if (element.data('ujs:disabled')) { $.rails.enableElement(element); } }); }); $document.on('ajax:complete', rails.linkDisableSelector, function() { rails.enableElement($(this)); }); $document.on('ajax:complete', rails.buttonDisableSelector, function() { rails.enableFormElement($(this)); }); $document.on('click.rails', rails.linkClickSelector, function(e) { var link = $(this), method = link.data('method'), data = link.data('params'), metaClick = e.metaKey || e.ctrlKey; if (!rails.allowAction(link)) return rails.stopEverything(e); if (!metaClick && link.is(rails.linkDisableSelector)) rails.disableElement(link); if (rails.isRemote(link)) { if (metaClick && (!method || method === 'GET') && !data) { return true; } var handleRemote = rails.handleRemote(link); // Response from rails.handleRemote() will either be false or a deferred object promise. if (handleRemote === false) { rails.enableElement(link); } else { handleRemote.fail( function() { rails.enableElement(link); } ); } return false; } else if (method) { rails.handleMethod(link); return false; } }); $document.on('click.rails', rails.buttonClickSelector, function(e) { var button = $(this); if (!rails.allowAction(button) || !rails.isRemote(button)) return rails.stopEverything(e); if (button.is(rails.buttonDisableSelector)) rails.disableFormElement(button); var handleRemote = rails.handleRemote(button); // Response from rails.handleRemote() will either be false or a deferred object promise. if (handleRemote === false) { rails.enableFormElement(button); } else { handleRemote.fail( function() { rails.enableFormElement(button); } ); } return false; }); $document.on('change.rails', rails.inputChangeSelector, function(e) { var link = $(this); if (!rails.allowAction(link) || !rails.isRemote(link)) return rails.stopEverything(e); rails.handleRemote(link); return false; }); $document.on('submit.rails', rails.formSubmitSelector, function(e) { var form = $(this), remote = rails.isRemote(form), blankRequiredInputs, nonBlankFileInputs; if (!rails.allowAction(form)) return rails.stopEverything(e); // Skip other logic when required values are missing or file upload is present if (form.attr('novalidate') === undefined) { if (form.data('ujs:formnovalidate-button') === undefined) { blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector, false); if (blankRequiredInputs && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) { return rails.stopEverything(e); } } else { // Clear the formnovalidate in case the next button click is not on a formnovalidate button // Not strictly necessary to do here, since it is also reset on each button click, but just to be certain form.data('ujs:formnovalidate-button', undefined); } } if (remote) { nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector); if (nonBlankFileInputs) { // Slight timeout so that the submit button gets properly serialized // (make it easy for event handler to serialize form without disabled values) setTimeout(function(){ rails.disableFormElements(form); }, 13); var aborted = rails.fire(form, 'ajax:aborted:file', [nonBlankFileInputs]); // Re-enable form elements if event bindings return false (canceling normal form submission) if (!aborted) { setTimeout(function(){ rails.enableFormElements(form); }, 13); } return aborted; } rails.handleRemote(form); return false; } else { // Slight timeout so that the submit button gets properly serialized setTimeout(function(){ rails.disableFormElements(form); }, 13); } }); $document.on('click.rails', rails.formInputClickSelector, function(event) { var button = $(this); if (!rails.allowAction(button)) return rails.stopEverything(event); // Register the pressed submit button var name = button.attr('name'), data = name ? {name:name, value:button.val()} : null; var form = button.closest('form'); if (form.length === 0) { form = $('#' + button.attr('form')); } form.data('ujs:submit-button', data); // Save attributes from button form.data('ujs:formnovalidate-button', button.attr('formnovalidate')); form.data('ujs:submit-button-formaction', button.attr('formaction')); form.data('ujs:submit-button-formmethod', button.attr('formmethod')); }); $document.on('ajax:send.rails', rails.formSubmitSelector, function(event) { if (this === event.target) rails.disableFormElements($(this)); }); $document.on('ajax:complete.rails', rails.formSubmitSelector, function(event) { if (this === event.target) rails.enableFormElements($(this)); }); $(function(){ rails.refreshCSRFTokens(); }); } })( jQuery );
!function($) { "use strict"; var SweetAlert = function() {}; //examples SweetAlert.prototype.init = function() { //Basic $('#sa-basic').click(function(){ swal("Here's a message!"); }); //A title with a text under $('#sa-title').click(function(){ swal("Here's a message!", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lorem erat eleifend ex semper, lobortis purus sed.") }); //Success Message $('#sa-success').click(function(){ swal("Good job!", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lorem erat eleifend ex semper, lobortis purus sed.", "success") }); //Warning Message $('#sa-warning').click(function(){ swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes, delete it!", closeOnConfirm: false }, function(){ swal("Deleted!", "Your imaginary file has been deleted.", "success"); }); }); //Parameter $('#sa-params').click(function(){ swal({ title: "Are you sure?", text: "You will not be able to recover this imaginary file!", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes, delete it!", cancelButtonText: "No, cancel plx!", closeOnConfirm: false, closeOnCancel: false }, function(isConfirm){ if (isConfirm) { swal("Deleted!", "Your imaginary file has been deleted.", "success"); } else { swal("Cancelled", "Your imaginary file is safe :)", "error"); } }); }); //Custom Image $('#sa-image').click(function(){ swal({ title: "Govinda!", text: "Recently joined twitter", imageUrl: "../../images/avatar.png" }); }); //Auto Close Timer $('#sa-close').click(function(){ swal({ title: "Auto close alert!", text: "I will close in 2 seconds.", timer: 2000, showConfirmButton: false }); }); }, //init $.SweetAlert = new SweetAlert, $.SweetAlert.Constructor = SweetAlert }(window.jQuery), //initializing function($) { "use strict"; $.SweetAlert.init() }(window.jQuery);
var MidiWriter = require('..'); var track = new MidiWriter.Track(); track.addEvent([ new MidiWriter.NoteEvent({ pitch: 'C4', duration: 'T50', startTick: 0 }), new MidiWriter.NoteEvent({ pitch: 'E4', duration: 'T50', startTick: 50 }), new MidiWriter.NoteEvent({ pitch: ['G4', 'B4'], duration: 'T50', startTick: 100 }), new MidiWriter.NoteEvent({ pitch: 'C5', duration: 'T50', startTick: 150 }), new MidiWriter.NoteEvent({ pitch: 'D5', duration: 'T50', startTick: 200 }), new MidiWriter.NoteEvent({ pitch: 'F5', duration: 'T50', startTick: 250 }), new MidiWriter.NoteEvent({ pitch: 'A5', duration: 'T50', startTick: 300 }), ] ); var write = new MidiWriter.Writer(track); console.log(write.dataUri()); module.exports = write;
module.exports = (() => function(value){ // Another parseFloat b/c null isn't NaN, but parseFloat(null) is NaN var isString = typeof value === "string"; var isNumeric = !isNaN(parseFloat(value)); if (isString) { isNumeric = isNumeric && /^[\d\.]+$/.test(value); var numberEndsOnDecimalPoint = /\.$/.test(value); isNumeric = isNumeric && !numberEndsOnDecimalPoint; } var response = { isValid: isNumeric } if (!response.isValid) { response.errorMessage = "Please enter a number."; } return response; })
'use strict'; const Path = require('upath'); const expect = require('unexpected').clone(); const helpers = require('../lib/helpers'); const babyTolk = require('@pingy/compile'); function getPath(path) { return Path.join(process.cwd(), 'examples', 'site', path); } describe('helpers', function() { describe('findSourceFile', function() { it('should find a source file if there is one (JS)', function() { return expect( helpers.findSourceFile(getPath('scripts/main.js'), babyTolk), 'to be fulfilled with', getPath('scripts/main.coffee') ); }); it('should find a source file if there is one (CSS)', function() { return expect( helpers.findSourceFile(getPath('styles/main.css'), babyTolk), 'to be fulfilled with', getPath('styles/main.styl') ); }); it("should reject with `null` when it can't find source file", function() { return expect( helpers.findSourceFile(getPath('scripts/404.js'), babyTolk), 'to be rejected with', null ); }); it("should reject with `null` when path doesn't exist", function() { return expect( helpers.findSourceFile(getPath('foo/bar'), babyTolk), 'to be rejected with', null ); }); }); });
import Minesweeper, { BlockRecord } from './minesweeper'; const mw = Minesweeper(); const iterate = 100; const counter = { win: 0, lose: 0 }; const now = new Date(); const testset = new Array(iterate).fill(0).map(() => { mw.blocks = mw.reset(16, 16, 40, true, false); counter[mw.solver( mw.clickOn(new BlockRecord({ row: 4, col: 4})) ) ? 'win' : 'lose'] += 1; }); const passtime = new Date() - now; console.log('---------------------------------'); console.log('time: ', passtime); console.log(counter); console.log('---------------------------------'); console.log('avg time: ', passtime / iterate); console.log(counter.win / iterate * 100 + '%'); console.log('---------------------------------'); console.log('waiting time: ', passtime / counter.win ); console.log('---------------------------------');
$( document ).ready(function() { console.log( "document loaded" ); }); $(document).on('click',"[id^=btn_mood] , .p_day", function (event) { // alert (var day=event.target.id;event.target.id); var day_clicked=event.target.id; $('#myModal').attr('data-id', day_clicked); // $(this).data('id')=event.target.id; $('#myModal').modal('show'); }); $(document).on('click', '[id^=choose_smiley]', function(event){ // alert ("Day "+day_clicked); var btn_day=$('#myModal').attr('data-id'); // alert ("btn_day"+$('#myModal').attr('data-id')); // alert ("btn_day "+btn_day); var day_clicked= parseInt(btn_day.match(/\d+$/)[0], 10); var smiley_chosen = parseInt(event.target.id.match(/\d+$/)[0], 10); // alert ("smiley_chosen".smiley_chosen); // alert ("day_clicked"+day_clicked); $("#smiley_"+day_clicked).attr('src','/images/smiley_'+smiley_chosen+'.png'); $("#value_smiley_"+day_clicked).attr('value',smiley_chosen); $('#myModal').modal('hide'); });
const _ = require('lodash') const crypto = require('crypto') const userRouter = require('../src/resource/user/user.router') /** * @param {object} supertest Supertest instance * @return {object} */ module.exports = function testHelperFactory (supertest) { return { request (options) { const method = options.method || 'get' const request = supertest[method.toLowerCase()](options.url || options.path) const expect = options.expect || options.status || options.assert if (options.user) { this.auth(options.user, request) } if (options.data) { request.send(options.data) } if (expect) { request.expect(expect) } if (options.headers) { _.each(options.headers, request.set) } return request }, auth (user, req) { return req.set('Authorization', `Bearer ${user.token}`) }, randomize (text) { return text + Date.now() + Math.floor(1000 * Math.random()) }, randomString (length) { length = length || 10 return crypto.randomBytes(parseInt(length / 2)).toString('hex') }, // ==== user ==== async createUser (attributes) { const randomUser = { first_name: `First ${Date.now()}${Math.floor(1000000 * Math.random())}`, last_name: `Last ${Date.now()}${Math.floor(1000000 * Math.random())}`, password: 'secretpassword', email: `${Math.floor(1000000 * Math.random())}${(new Date()).getTime()}@example.com` } Object.assign(randomUser, attributes) const resp = await this.request({ method: 'post', url: userRouter.url('createUser'), data: randomUser, expect: 201 }) Object.assign(randomUser, resp.body) return randomUser } } }
const {User} = require('../models') const jwt = require('jsonwebtoken') const config = require('../config/config') function jwtSignUser (user) { const ONE_WEEK = 60 * 60 * 24 * 7 return jwt.sign(user, config.authentication.jwtSecret, { expiresIn: ONE_WEEK }) } module.exports = { async register (req, res) { try { const user = await User.create(req.body) const userJson = user.toJSON() res.send({ user: userJson, token: jwtSignUser(userJson) }) res.send(user.toJSON()) } catch (err) { res.status(400).send({ error: 'This email account is already in used.' }) } }, async login (req, res) { try { const {email, password} = req.body const user = await User.findOne({ where: { email: email } }) if (!user) { return res.status(403).send({ error: 'The login information was incorrect' }) } const isPasswordValid = await user.comparePassword(password) if (!isPasswordValid) { return res.status(403).send({ error: 'The login information was incorrect' }) } const userJson = user.toJSON() res.send({ user: userJson, token: jwtSignUser(userJson) }) } catch (err) { res.status(500).send({ error: 'Internal error occur.' }) } } }
!function(){$(".mobile-menu__toggle").on("click",function(){$(".mobile-menu").slideToggle(),$(this).attr("src","img/cross.png")})}();
define([ 'config/types' ], function ( types ) { 'use strict'; return function ( tokens ) { var i, current, backOne, backTwo, leadingLinebreak, trailingLinebreak; leadingLinebreak = /^\s*\r?\n/; trailingLinebreak = /\r?\n\s*$/; for ( i=2; i<tokens.length; i+=1 ) { current = tokens[i]; backOne = tokens[i-1]; backTwo = tokens[i-2]; // if we're at the end of a [text][mustache][text] sequence, where [mustache] isn't a partial... if ( current.type === types.TEXT && ( backOne.type === types.MUSTACHE && backOne.mustacheType !== types.PARTIAL ) && backTwo.type === types.TEXT ) { // ... and the mustache is a standalone (i.e. line breaks either side)... if ( trailingLinebreak.test( backTwo.value ) && leadingLinebreak.test( current.value ) ) { // ... then we want to remove the whitespace after the first line break // if the mustache wasn't a triple or interpolator or partial if ( backOne.mustacheType !== types.INTERPOLATOR && backOne.mustacheType !== types.TRIPLE ) { backTwo.value = backTwo.value.replace( trailingLinebreak, '\n' ); } // and the leading line break of the second text token current.value = current.value.replace( leadingLinebreak, '' ); // if that means the current token is now empty, we should remove it if ( current.value === '' ) { tokens.splice( i--, 1 ); // splice and decrement } } } } return tokens; }; });
// app/models/assistanceRequest.js // load the things we need let mongoose = require('mongoose'); // define the schema for our user model let assistanceRequestSchema = mongoose.Schema({ requestTime: {type: Date, default: Date.now}, student: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, course: {type: mongoose.Schema.Types.ObjectId, ref: 'Course'}, resolved: Boolean, resolvedTime: {type: Date, default: null}, resolved_type: String, timestamp: {type: Date, default: Date.now} }); assistanceRequestSchema.pre('validate', function (next) { this.timestamp = new Date(); next(); }); // create the model for users and expose it to our app module.exports = { model: mongoose.model('AssistanceRequest', assistanceRequestSchema), };
var Hapi = require('hapi'); var server = new Hapi.Server(); server.route({ handler: function (request, reply){ request.response.header('X-Frame-Options', 'DENY') }});
// Medication page spec describe("medication-page", function () { //browser.get('#/'); it("should load", function () { // Login as an provider element(by.model("loginData.username")).sendKeys("doctor1"); element(by.model("loginData.password")).sendKeys("Password1?"); element(by.buttonText("Login to your account")).click(); element(by.linkText("Medications")).click(); expect(browser.getTitle()).toBe('Medications | CloudMedic Dashboard'); }); describe("add-form", function () { it("should open on selecting button", function () { element(by.buttonText("Add Medication")).click(); expect(element.all(by.cssContainingText(".modal-title", "Add New Medication")).count()).toEqual(1); }); describe("generic-name-input", function () { afterEach(function () { element(by.model("medicationsData.GenericName")).clear(); }); it("should display error messages for invalid name", function () { element(by.model("medicationsData.GenericName")).sendKeys("12345"); expect(element(by.id("generic-name-error")).isDisplayed()).toBeTruthy(); }); it("should accept a valid name", function () { element(by.model("medicationsData.GenericName")).sendKeys("Synthroid"); expect(element(by.id("generic-name-error")).isDisplayed()).toBeFalsy(); }); }); describe("medication-code-input", function () { afterEach(function () { element(by.model("medicationsData.Code")).clear(); }); it("should display error messages for invalid code", function () { element(by.model("medicationsData.Code")).sendKeys("abcdef"); expect(element(by.id("code-error")).isDisplayed()).toBeTruthy(); }); it("should accept a valid code", function () { element(by.model("medicationsData.Code")).sendKeys("50932"); expect(element(by.id("code-error")).isDisplayed()).toBeFalsy(); }); }); it("should prevent submitting until fields complete", function () { var createMed = element(by.buttonText("Create")); expect(createMed.isEnabled()).toBeFalsy(); element(by.model("medicationsData.GenericName")).sendKeys("Synthroid"); expect(createMed.isEnabled()).toBeFalsy(); element(by.model("medicationsData.Code")).sendKeys("50932"); expect(createMed.isEnabled()).toBeTruthy(); }); it("should close on creation", function () { element(by.buttonText("Create")).click(); expect(element.all(by.cssContainingText(".modal-title", "Add New Medication")).count()).toEqual(0); }); it("should successfully create a medication", function () { expect(element.all(by.cssContainingText("tbody tr", "Synthroid")).count()).toEqual(1); }); }); describe("table", function () { it("should be sortable by generic name", function () { element(by.id("medications-list")).element(by.linkText("Generic Name")).click(); var string1 = element(by.id("medications-list")).all(by.repeater("medication in medications")).get(0).getText(); var string2 = element(by.id("medications-list")).all(by.repeater("medication in medications")).get(1).getText(); protractor.promise.all([string1, string2]).then(function (data) { expect(data[0].toLowerCase() >= data[1].toLowerCase()).toBeTruthy(); }); element(by.id("medications-list")).element(by.linkText("Generic Name")).click(); var string3 = element(by.id("medications-list")).all(by.repeater("medication in medications")).get(0).getText(); var string4 = element(by.id("medications-list")).all(by.repeater("medication in medications")).get(1).getText(); protractor.promise.all([string3, string4]).then(function (data) { expect(data[0].toLowerCase() <= data[1].toLowerCase()).toBeTruthy(); }); }); it("should be sortable by id", function () { element(by.id("medications-list")).element(by.linkText("Medication ID")).click(); var r1 = element(by.id("medications-list")).all(by.repeater("medication in medications")).get(0); var string1 = r1.all(by.tagName('td')).get(1).getText(); var r2 = element(by.id("medications-list")).all(by.repeater("medication in medications")).get(1); var string2 = r2.all(by.tagName('td')).get(1).getText(); protractor.promise.all([string1, string2]).then(function (data) { expect(data[0]).toBeGreaterThan(data[1]); }); element(by.id("medications-list")).element(by.linkText("Medication ID")).click(); var r3 = element(by.id("medications-list")).all(by.repeater("medication in medications")).get(0); var string3 = r3.all(by.tagName('td')).get(1).getText(); var r4 = element(by.id("medications-list")).all(by.repeater("medication in medications")).get(1); var string4 = r4.all(by.tagName('td')).get(1).getText(); protractor.promise.all([string3, string4]).then(function (data) { expect(data[0]).toBeLessThan(data[1]); }); }); it("should be sortable by code", function () { element(by.id("medications-list")).element(by.linkText("Code")).click(); var r1 = element(by.id("medications-list")).all(by.repeater("medication in medications")).get(0); var string1 = r1.all(by.tagName('td')).get(2).getText(); var r2 = element(by.id("medications-list")).all(by.repeater("medication in medications")).get(1); var string2 = r2.all(by.tagName('td')).get(2).getText(); protractor.promise.all([string1, string2]).then(function (data) { expect(data[0]).toBeGreaterThan(data[1]); }); element(by.id("medications-list")).element(by.linkText("Code")).click(); var r3 = element(by.id("medications-list")).all(by.repeater("medication in medications")).get(0); var string3 = r3.all(by.tagName('td')).get(2).getText(); var r4 = element(by.id("medications-list")).all(by.repeater("medication in medications")).get(1); var string4 = r4.all(by.tagName('td')).get(2).getText(); protractor.promise.all([string3, string4]).then(function (data) { expect(data[0]).toBeLessThan(data[1]); }); }); describe("remove-button", function () { it("should ask for confirmation when clicked", function () { element(by.cssContainingText("tbody tr", "Synthroid")).element(by.id("remove-medication")).click(); expect(element.all(by.cssContainingText(".modal-title", "Are You Sure?")).count()).toEqual(1); }); it("should delete medication when confirmed", function () { element(by.buttonText("Yes, delete medication!")).click(); expect(element.all(by.cssContainingText("tbody tr", "Synthroid")).count()).toEqual(0); }); }); describe("prescribe-form", function () { it("should open on selecting prescribe button", function () { element.all(by.repeater("medication in medications")).get(0).element(by.id("prescribe-medication")).click(); expect(element.all(by.cssContainingText(".modal-title", "Add New Prescription")).count()).toEqual(1); }); describe("medication-name", function () { it("should not allow editing", function () { expect(element(by.id("medication-name")).isEnabled()).toBeFalsy(); }); }); describe("start-date", function () { it("should default to the current date", function () { var today = new Date(); var dateString = (today.getFullYear()) + "-" + ('0' + (today.getMonth() + 1)).slice(-2) + "-" + ('0' + today.getDate()).slice(-2); element(by.id("prescription-add-date")).getAttribute('value').then(function (data) { expect(data).toEqual(dateString); }); }); }); describe("patient-filter-results", function () { it("should change tabs", function () { element(by.id("patient-name-filter")).clear(); element(by.id("patient-name-filter")).sendKeys("z"); expect(element(by.id("rz-list")).isDisplayed()).toBeTruthy(); element(by.id("patient-name-filter")).clear(); element(by.id("patient-name-filter")).sendKeys("Patient"); expect(element(by.id("jq-list")).isDisplayed()).toBeTruthy(); }); }); it("should prevent submitting until all fields filled", function () { var prescribeBtn = element(by.buttonText("Create")); expect(prescribeBtn.isEnabled()).toBeFalsy(); element(by.id("prescription-frequency")).sendKeys("Twice a day"); expect(prescribeBtn.isEnabled()).toBeFalsy(); element(by.id("prescription-dosage")).sendKeys("Example Prescription"); expect(prescribeBtn.isEnabled()).toBeFalsy(); element(by.id("prescription-notes")).sendKeys("Report any symptoms"); expect(prescribeBtn.isEnabled()).toBeFalsy(); element(by.id("prescription-add-date")).clear(); element(by.id("prescription-add-date")).sendKeys("1990-01-01"); expect(prescribeBtn.isEnabled()).toBeFalsy(); element(by.cssContainingText("option", "100")).click(); expect(prescribeBtn.isEnabled()).toBeFalsy(); element(by.id("patient-name-filter")).clear(); element(by.id("patient-name-filter")).sendKeys("Patient"); element(by.cssContainingText("option", "Patient, Example")).click(); expect(prescribeBtn.isEnabled()).toBeTruthy(); }); it("should close upon successful prescription", function () { element(by.buttonText("Create")).click(); expect(element.all(by.cssContainingText(".modal-title", "Add New Prescription")).count()).toEqual(0); }); }); }); });
(function(){ var redirectKey = 'ir.loginRedirectRoute'; Session.set(redirectKey, null); _.extend(Router, { _route: Router.route, route: function(name, options){ function isLoggedIn() { if(options.isLoggedIn !== undefined) return options.isLoggedIn(); else return (Meteor.user() !== null); } if(options.redirectOnLogin && Session.get(redirectKey)){ var rname = Session.get(redirectKey); Session.set(redirectKey, null); return this.redirect(rname); } if(options.loginRequired || options.redirectOnLogin){ var onBeforeAction = null; if(options.onBeforeAction && _.isFunction(options.onBeforeAction)){ onBeforeAction = options.onBeforeAction; } options.onBeforeAction = function(pause){ if(Meteor.loggingIn()) return pause(); if(options.redirectOnLogin && Meteor.user()){ if(Session.get(redirectKey)){ var rname = Session.get(redirectKey); Session.set(redirectKey, null); return this.redirect(rname); } } if(options.loginRequired){ if(typeof options.loginRequired == 'string' || options.loginRequired instanceof String){ var routeName = options.loginRequired; options.loginRequired = { name: routeName, shouldRoute: true }; } if(!options.loginRequired.hasOwnProperty('shouldRoute')){ options.loginRequired.shouldRoute = true; } if(!isLoggedIn()){ Session.set(redirectKey, Router.current().path); if(options.loginRequired.layout){ this.layoutTemplate = options.loginRequired.layout; } if(options.loginRequired.shouldRoute){ return this.redirect(options.loginRequired.name); }else{ this.render(options.loginRequired.name); this.renderRegions(); return pause(); } } } if(onBeforeAction)onBeforeAction.call(this); }; } Router._route(name, options); } }); })();
// Generated on 2015-06-02 using // generator-webapp 0.5.1 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // If you want to recursively match all subfolders, use: // 'test/spec/**/*.js' module.exports = function (grunt) { // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Configurable paths var config = { app: 'app', dist: 'dist' }; // Define the configuration for all the tasks grunt.initConfig({ // Project settings config: config, // Watches files for changes and runs tasks based on the changed files watch: { bower: { files: ['bower.json'], tasks: ['wiredep'] }, coffee: { files: ['<%= config.app %>/scripts/{,*/}*.{coffee,litcoffee,coffee.md}'], tasks: ['coffee:dist'] }, coffeeTest: { files: ['test/spec/{,*/}*.{coffee,litcoffee,coffee.md}'], tasks: ['coffee:test', 'test:watch'] }, gruntfile: { files: ['Gruntfile.js'] }, styles: { files: ['<%= config.app %>/styles/{,*/}*.css'], tasks: ['newer:copy:styles', 'autoprefixer'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ '<%= config.app %>/{,*/}*.html', '.tmp/styles/{,*/}*.css', '.tmp/scripts/{,*/}*.js', '<%= config.app %>/images/{,*/}*' ] } }, // The actual grunt server settings connect: { options: { port: 9000, open: true, livereload: 35729, // Change this to '0.0.0.0' to access the server from outside hostname: 'localhost' }, livereload: { options: { middleware: function(connect) { return [ connect.static('.tmp'), connect().use('/bower_components', connect.static('./bower_components')), connect.static(config.app) ]; } } }, test: { options: { open: false, port: 9001, middleware: function(connect) { return [ connect.static('.tmp'), connect.static('test'), connect().use('/bower_components', connect.static('./bower_components')), connect.static(config.app) ]; } } }, dist: { options: { base: '<%= config.dist %>', livereload: false } } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= config.dist %>/*', '!<%= config.dist %>/.git*' ] }] }, server: '.tmp' }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: [ 'Gruntfile.js', '<%= config.app %>/scripts/{,*/}*.js', '!<%= config.app %>/scripts/vendor/*', 'test/spec/{,*/}*.js' ] }, // Mocha testing framework configuration options mocha: { all: { options: { run: true, urls: ['http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/index.html'] } } }, // Compiles CoffeeScript to JavaScript coffee: { dist: { files: [{ expand: true, cwd: '<%= config.app %>/scripts', src: '{,*/}*.{coffee,litcoffee,coffee.md}', dest: '.tmp/scripts', ext: '.js' }] }, test: { files: [{ expand: true, cwd: 'test/spec', src: '{,*/}*.{coffee,litcoffee,coffee.md}', dest: '.tmp/spec', ext: '.js' }] } }, // Add vendor prefixed styles autoprefixer: { options: { browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1'] }, dist: { files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] } }, // Automatically inject Bower components into the HTML file wiredep: { app: { ignorePath: /^\/|\.\.\//, src: ['<%= config.app %>/index.html'] } }, // Renames files for browser caching purposes rev: { dist: { files: { src: [ '<%= config.dist %>/scripts/{,*/}*.js', '<%= config.dist %>/styles/{,*/}*.css', '<%= config.dist %>/images/{,*/}*.*', '<%= config.dist %>/styles/fonts/{,*/}*.*', '<%= config.dist %>/*.{ico,png}' ] } } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { options: { dest: '<%= config.dist %>' }, html: '<%= config.app %>/index.html' }, // Performs rewrites based on rev and the useminPrepare configuration usemin: { options: { assetsDirs: [ '<%= config.dist %>', '<%= config.dist %>/images', '<%= config.dist %>/styles' ] }, html: ['<%= config.dist %>/{,*/}*.html'], css: ['<%= config.dist %>/styles/{,*/}*.css'] }, // The following *-min tasks produce minified files in the dist folder imagemin: { dist: { files: [{ expand: true, cwd: '<%= config.app %>/images', src: '{,*/}*.{gif,jpeg,jpg,png}', dest: '<%= config.dist %>/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= config.app %>/images', src: '{,*/}*.svg', dest: '<%= config.dist %>/images' }] } }, htmlmin: { dist: { options: { collapseBooleanAttributes: true, collapseWhitespace: true, conservativeCollapse: true, removeAttributeQuotes: true, removeCommentsFromCDATA: true, removeEmptyAttributes: true, removeOptionalTags: true, removeRedundantAttributes: true, useShortDoctype: true }, files: [{ expand: true, cwd: '<%= config.dist %>', src: '{,*/}*.html', dest: '<%= config.dist %>' }] } }, // By default, your `index.html`'s <!-- Usemin block --> will take care // of minification. These next options are pre-configured if you do not // wish to use the Usemin blocks. // cssmin: { // dist: { // files: { // '<%= config.dist %>/styles/main.css': [ // '.tmp/styles/{,*/}*.css', // '<%= config.app %>/styles/{,*/}*.css' // ] // } // } // }, // uglify: { // dist: { // files: { // '<%= config.dist %>/scripts/scripts.js': [ // '<%= config.dist %>/scripts/scripts.js' // ] // } // } // }, // concat: { // dist: {} // }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= config.app %>', dest: '<%= config.dist %>', src: [ '*.{ico,png,txt}', 'images/{,*/}*.webp', '{,*/}*.html', 'styles/fonts/{,*/}*.*' ] }, { src: 'node_modules/apache-server-configs/dist/.htaccess', dest: '<%= config.dist %>/.htaccess' }] }, styles: { expand: true, dot: true, cwd: '<%= config.app %>/styles', dest: '.tmp/styles/', src: '{,*/}*.css' } }, // Run some tasks in parallel to speed up build process concurrent: { server: [ 'coffee:dist', 'copy:styles' ], test: [ 'coffee', 'copy:styles' ], dist: [ 'coffee', 'copy:styles', 'imagemin', 'svgmin' ] } }); grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) { if (grunt.option('allow-remote')) { grunt.config.set('connect.options.hostname', '0.0.0.0'); } if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'wiredep', 'concurrent:server', 'autoprefixer', 'connect:livereload', 'watch' ]); }); grunt.registerTask('server', function (target) { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run([target ? ('serve:' + target) : 'serve']); }); grunt.registerTask('test', function (target) { if (target !== 'watch') { grunt.task.run([ 'clean:server', 'concurrent:test', 'autoprefixer' ]); } grunt.task.run([ 'connect:test', 'mocha' ]); }); grunt.registerTask('build', [ 'clean:dist', 'wiredep', 'useminPrepare', 'concurrent:dist', 'autoprefixer', 'concat', 'cssmin', 'uglify', 'copy:dist', 'rev', 'usemin', 'htmlmin' ]); grunt.registerTask('default', [ 'newer:jshint', 'test', 'build' ]); };
/** * Copyright 2012-2019, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var isNumeric = require('fast-isnumeric'); // used in the drawing step for 'scatter' and 'scattegeo' and // in the convert step for 'scatter3d' module.exports = function makeBubbleSizeFn(trace) { var marker = trace.marker; var sizeRef = marker.sizeref || 1; var sizeMin = marker.sizemin || 0; // for bubble charts, allow scaling the provided value linearly // and by area or diameter. // Note this only applies to the array-value sizes var baseFn = (marker.sizemode === 'area') ? function(v) { return Math.sqrt(v / sizeRef); } : function(v) { return v / sizeRef; }; // TODO add support for position/negative bubbles? // TODO add 'sizeoffset' attribute? return function(v) { var baseSize = baseFn(v / 2); // don't show non-numeric and negative sizes return (isNumeric(baseSize) && (baseSize > 0)) ? Math.max(baseSize, sizeMin) : 0; }; };
/** * File-based data storage */ const fs = require('fs'); const path = require('path'); const args = process.argv.splice(2); // splice out "node cli_tasks.js" to elave arguments const command = args.shift(); // pull out first argument (the command) const taskDescription = args.join(' '); const file = path.join(process.cwd(), '/.tasks'); // resolve database path relative to current working directory switch (command) { case 'list': // 'list' will list all tasks stored listTasks(file); break; case 'add': // 'add' will add new task addTask(file, taskDescription); break; default: // anything else will show usage help console.log('Usage: ' + process.argv[0] + ' list|add [taskDescription]'); } function loadOrInitializeTaskArray(file, cb) { fs.exists(file, (exists) => { // check if .tasks file already exists // let tasks = []; if (exists) { fs.readFile(file, 'utf8', (err, data) => { // read to-do data from .tasks file if (err) throw err; let newdata = data.toString(); let tasks = JSON.parse(newdata || '[]'); // parse JSON-encoded to-do data into array of tasks cb(tasks); }); } else { cb([]); // create empty array of tasks if tasks file doesn't exist } }); } function listTasks(file) { loadOrInitializeTaskArray(file, (tasks) => { for(var i in tasks) { console.log(tasks[i]); } }); } function storeTasks(file, tasks) { fs.writeFile(file, JSON.stringify(tasks), 'utf8', (err) => { if(err) throw err; console.log('Saved.'); }); } function addTask(file, taskDescription) { loadOrInitializeTaskArray(file, (tasks) => { tasks.push(taskDescription); storeTasks(file, tasks); }); }
var global = require("../global") , SimpleOrm = require("../../simpleorm") , Model = SimpleOrm.Model , DbHelper = SimpleOrm.DbHelper , Orms = require("./orms") , Q = require("q") , EventEmitter = require('events').EventEmitter; function Metric (info){ var me = this; EventEmitter.call(this); this.set = function (metric){ this.id = metric.id; this.name = metric.name; this.desc = metric.desc; this.ver = metric.ver; this.create_time = metric.create_time; this.modifiy_time = metric.modifiy_time; try { this.keys = JSON.parse(metric.keys); } catch (err){ // do nothing } } this.set(info); } require('util').inherits(Metric, EventEmitter); /* metric - { "name" : string, metric name, unique, "desc" : string, "keys" : [ { "name" : string, key name, "type" : string, data type, "default" : default value }, ... ... ] }, cb - function (err, metric_id) */ exports.create = function (metric, cb){ var metric_ = { "name" : metric.name, "desc" : metric.desc, "keys" : metric.keys ? JSON.stringify(metric.keys) : null } var dbhelper = new DbHelper(global.DbConnection); dbhelper.getConnection(function (err, connection){ var mdl = new Model(connection, Orms.metricsOrm, "id"); mdl.create(metric_, function (err, id){ if (err == "ER_OBJECT_EXIST") cb && cb("ER_METRIC_EXIST"); else cb && cb(err, id); }); }); } /* metric_id - number, metric id, required fields - { ["name"] : string, metric name, unique, ["desc"] : string, ["keys"] : [ { "name" : string, key name, "type" : string, data type, "default" : default value }, ... ... ] }, cb - function (err) */ exports.set = function (metric_id, fields, cb){ if (fields.keys) fields.keys = JSON.stringify(fields.keys); var dbhelper = new DbHelper(global.DbConnection); dbhelper.getConnection(function (err, connection){ var mdl = new Model(connection, Orms.metricsOrm, "id"); mdl.set(metric_id, fields, function (err){ if (err == "ER_OBJECT_NOT_EXIST") cb && cb("ER_METRIC_NOT_EXIST"); else if (err == "ER_DUP_ENTRY") cb && cb("ER_RENAME_METRIC_EXIST"); else cb && cb(err) }); }); } exports.setByName = function (metric_name, fields, cb){ if (fields.keys) fields.keys = JSON.stringify(fields.keys); var dbhelper = new DbHelper(global.DbConnection); dbhelper.getConnection(function (err, connection){ var mdl = new Model(connection, Orms.metricsOrm, "name"); mdl.set(metric_name, fields, function (err){ if (err == "ER_OBJECT_NOT_EXIST") cb && cb("ER_METRIC_NOT_EXIST"); else if (err == "ER_DUP_ENTRY") cb && cb("ER_RENAME_METRIC_EXIST"); else cb && cb(err) }); }); } /* metric_id - number, metric id, required cb - function (err, metric) metric - { "id" : number, metric id, "name" : string, metric name, unique, "desc" : string, "keys" : [ { "name" : string, key name, "type" : string, data type, "default" : default value }, ... ... ], "ver" : number, "create_time" : DateTime, "modifiy_time" : DateTime } */ exports.get = function (metric_id, cb){ var dbhelper = new DbHelper(global.DbConnection); dbhelper.getConnection(function (err, connection){ var mdl = new Model(connection, Orms.metricsOrm, "id"); mdl.get(metric_id, function (err, results){ if (err){ cb && cb("ER_OBJECT_NOT_EXIST" == err ? "ER_METRIC_NOT_EXIST" : err, null); } else { cb && cb(null, exports.createMetric(results)); } }); }); } exports.getByName = function (metric_name, cb){ var dbhelper = new DbHelper(global.DbConnection); dbhelper.getConnection(function (err, connection){ var mdl = new Model(connection, Orms.metricsOrm, "name"); mdl.get(metric_name, function (err, results){ if (err){ cb && cb("ER_OBJECT_NOT_EXIST" == err ? "ER_METRIC_NOT_EXIST" : err, null); } else { cb && cb(null, exports.createMetric(results)); } }); }); } exports.createMetric = function (results){ return new Metric(results); } /* metric_id - number, metric id, required cb - function (err) */ exports.drop = function (metric_id, cb){ var dbhelper = new DbHelper(global.DbConnection); dbhelper.execTransactionSeries(function (connection, commit, rollback){ var mdl = new Model(connection, Orms.metricsOrm, "id"); mdl.setTransactionFlag(); Q.fcall(function (){ return Q.Promise(function (resolve, reject, notify){ mdl.getForUpdate(metric_id, function (err, results){ if (err) reject("ER_OBJECT_NOT_EXIST" == err ? "ER_METRIC_NOT_EXIST" : err); else resolve(); }) }) }).then(function (){ return Q.Promise(function (resolve, reject, notify){ mdl.drop(metric_id, function (err, results){ if (err) reject(err); else { commit(function (err){ if (err) reject(err.code); else{ cb && cb(null); resolve(); } }); } }) }) }).catch(function (err){ rollback(); cb && cb(err); }) }); } exports.dropByName = function (metric_name, cb){ var dbhelper = new DbHelper(global.DbConnection); dbhelper.execTransactionSeries(function (connection, commit, rollback){ var mdl = new Model(connection, Orms.metricsOrm, "name"); mdl.setTransactionFlag(); Q.fcall(function (){ return Q.Promise(function (resolve, reject, notify){ mdl.getForUpdate(metric_name, function (err, results){ if (err) reject("ER_OBJECT_NOT_EXIST" == err ? "ER_METRIC_NOT_EXIST" : err); else resolve(); }) }) }).then(function (){ return Q.Promise(function (resolve, reject, notify){ mdl.drop(metric_name, function (err, results){ if (err) reject(err); else { commit(function (err){ if (err) reject(err.code); else{ cb && cb(null); resolve(); } }); } }) }) }).catch(function (err){ rollback(); cb && cb(err); }) }); } exports.find = function (conditions, options, cb){ switch (arguments.length){ case 1: return exports.find(null, {}, arguments[0]); case 2: return exports.find(arguments[0], {}, arguments[1]); case 3: default: var conditions = arguments[0]; var options = arguments[1]; var cb = arguments[2]; break; } var dbhelper = new DbHelper(global.DbConnection); dbhelper.getConnection(function (err, connection){ var mdl = new Model(connection, Orms.metricsOrm, "id"); var finder = mdl.Finder(); if (conditions) finder.addConditions(finder.parseQuery(conditions)); finder.find(options, function (err, results){ if (err) cb && cb(err); else{ var ret = []; results.forEach(function (result){ ret.push(exports.createMetric(result)) }); cb && cb(null, ret); } }); }); }
/*! jQuery UI - v1.9.2 - 2013-09-25 * http://jqueryui.com * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional.sv={closeText:"Stäng",prevText:"&#xAB;Förra",nextText:"Nästa&#xBB;",currentText:"Idag",monthNames:["Januari","Februari","Mars","April","Maj","Juni","Juli","Augusti","September","Oktober","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Aug","Sep","Okt","Nov","Dec"],dayNamesShort:["Sön","Mån","Tis","Ons","Tor","Fre","Lör"],dayNames:["Söndag","Måndag","Tisdag","Onsdag","Torsdag","Fredag","Lördag"],dayNamesMin:["Sö","Må","Ti","On","To","Fr","Lö"],weekHeader:"Ve",dateFormat:"yy-mm-dd",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.sv)});
// Regular expression that matches all symbols in the Vertical Forms block as per Unicode v8.0.0: /[\uFE10-\uFE1F]/;
module.exports = function abort(opts) { if (typeof opts === 'number') { opts = { delay: opts } } opts = opts || {} var delay = +opts.delay || 10 return function abort(req, res, next) { setTimeout(destroy, delay) function destroy() { if (req.socket.destroyed) { if (!opts.next) return next() } else { destroySocket(req, next) } } if (opts.next) next() } function destroySocket(req, next) { try { req.destroy(opts.error) } catch (err) { if (!opts.next) next(err) } } }
const fs = require('fs'); const path = require('path'); const babelcfg = JSON.parse(fs.readFileSync('./.babelrc')); babelcfg.plugins.push([ 'transform-es2015-modules-commonjs', { loose: true }, ]); require('babel-register')(babelcfg); setTimeout(() => { require(path.join(process.cwd(), '__manual__', `${process.argv[2]}.js`)); });
/* * Function utils `body()` tests */ var assert = require('assert') var isArray = require('util').isArray var fnutils = require('..') describe('#body', function () { describe('with an empty function', function () { it('should return an empty string', function (done) { function test () {} assert.equal( fnutils.body(test), '' ) done() }) }) describe('with a function', function () { it('should return the function body', function (done) { function test () {var a = {}} assert.equal( fnutils.body(test), 'var a = {}' ) done() }) }) })
export default { title: 'Core/Template', }; export const StringOnly = () => '<my-button :rounded="false">A Button with square edges</my-button>'; StringOnly.story = { name: 'string only', };
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; import './app.global.css'; const store = configureStore(); render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
const editorOptions = [ 'minLines', 'maxLines', 'readOnly', 'highlightActiveLine', 'tabSize', 'enableBasicAutocompletion', 'enableLiveAutocompletion', 'enableSnippets', ] export { editorOptions, }
// in this file create an express application - use the middle-ware built into express // to serve up static files from the public directory (index.html and client.js - you // can also serve up css files from the public directory this way if you want) // you need to support a '/trucks' endpoint, and a dynamic route for '/trucks/:name'
MeteorOS.FS.ContextMenus.Dir = { id: 'MeteorOS-FS-ContextMenus-Dir', data : [ { header: 'Main Actions' }, { icon: 'glyphicon-save-file', text: 'Download Directory (as .zip)', action: function(event, selector, context) { context.download(); } }, { icon: 'glyphicon-edit', text: 'Rename Directory', action: function(event, selector, context) { var fb_fileNameSpan = selector.find('.fb_fileName'); fb_fileNameSpan.attr('contentEditable', true); fb_fileNameSpan.attr('tabindex','0'); setTimeout(function() {fb_fileNameSpan.focus();fb_fileNameSpan.selectText();}); $(fb_fileNameSpan).off('keypress'); $(fb_fileNameSpan).on('keypress', function(event) { if (event.which === 13) { context.name(fb_fileNameSpan.text()); // The context is the FileSystem.File that was clicked fb_fileNameSpan.attr('contentEditable', false); fb_fileNameSpan.removeAttr('tabindex'); } }); } }, { icon: 'glyphicon-share-alt', text: 'Move Directory', action: function(event, selector) { MeteorOS.Alerts.NotImplemented(); } }, { icon: 'glyphicon-star', text: 'Make Favorite', action: function(event, selector, context) { MeteorOS.FS.current().addFavorite(context); } }, { divider : true }, { icon: 'glyphicon-trash', text: 'Delete Directory', action: function(event, selector, context) { if (context.files().length > 0) { MeteorOS.FS.Modals.DeleteFolder(function(result) { if (result) context.delete(); }).show(); } else { context.delete(); } } }, ] };