code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
import React, {Component, PropTypes} from 'react' import {Motion, spring} from 'react-motion' class Bars extends Component { constructor() { super() // setStates and rectStyle color change // included for example - remove if needed this.state = { activeBar: null, activeText: null, } } render() { const { values, xSpacing, ySpacing, yAxis, topPadding, } = this.props return ( <g transform={`translate(51, ${(topPadding)})`} > <text> {this.state.activeText} </text> { values.map((v, i) => { // negative adjustment to subtract the // positive bars position from the origin axis const negAdjust = v.yValue > 0 ? v.yValue * ySpacing : null const origin = ySpacing * yAxis.indexOf(0) let rectStyle = {fill: v.yValue > 0 ? '#091f2f' : '#4492b4'} if (this.state.activeBar === i) { rectStyle = {fill: '#f00'}; } return ( <Motion key={i} defaultStyle={{ barHeight: 0, y: origin, }} style={{ barHeight: spring(Math.abs(v.yValue) * ySpacing), y: spring(origin - negAdjust), }}> { ({barHeight, y}) => ( <rect x={i * xSpacing - 1} y={y} key={i} width="3" onClick={() => { this.setState({ activeText: `Bar number ${i} with value ${v.yValue}`, }) }} onMouseMove={() => this.setState({activeBar: i})} onMouseOut={() => this.setState({activeBar: null})} height={barHeight} style={rectStyle} rx="2" /> ) } </Motion> ) }) } </g> ) } } export default Bars
joe-vh/db-chart
charts/BarChart/Bars.js
JavaScript
mit
2,261
import React from 'react'; import { connect } from 'react-redux'; import { changeYear, changeMonth, changeDay } from '../actions/actionCreators'; import Modal from 'boron/DropModal'; import Results from './Results/Results'; import { giveMeMonths, daysInMonth } from '../utils/time'; class NthDaysOld extends React.Component { constructor() { // React ES6 classes do not autobind their methods :S // (the older React.createClass did it) // the following way is a tip from "eslint" super(); this.nextStep = this.nextStep.bind(this); this.clickHandler = this.clickHandler.bind(this); this.generateMonths = this.generateMonths.bind(this); this.generateDays = this.generateDays.bind(this); } nextStep(ev) { const className = ev.target.getAttribute('data-type'); switch (className) { case 'year': this.props.dispatch(changeYear(parseInt(this.refs.yearinput.value, 10))); this.refs.yearmodal.hide(); this.refs.monthmodal.show(); break; case 'month': this.props.dispatch(changeMonth(ev.target.getAttribute('value'))); this.refs.monthmodal.hide(); this.refs.daymodal.show(); break; case 'day': this.props.dispatch(changeDay(parseInt(ev.target.getAttribute('value'), 10))); this.refs.daymodal.hide(); break; default: } } clickHandler() { this.refs.yearmodal.show(); } generateMonths() { const months = giveMeMonths(this.props.locale); return months.reduce((accu, elem, index) => { accu.push( <button className="nthdaysold__modal__button nthdaysold__modal__button--month" data-type="month" onClick={this.nextStep} key={index} value={index} > {elem} </button> ); return accu; }, []); } generateDays() { const days = daysInMonth(this.props.data.year, this.props.data.month); const buttons = []; for (let i = 1; i <= days; i++) { buttons.push( <button data-type="day" className="nthdaysold__modal__button nthdaysold__modal__button--day" onClick={this.nextStep} key={i} value={i} > {i} </button> ); } return buttons; } render() { const birthdaySet = this.props.data.day !== 0; const backdropStyle = { backgroundColor: '#462E4D', opacity: 0.8 }; const contentStyle = { backgroundColor: 'white', padding: '2em' }; return ( <div className="nthDaysOld"> { birthdaySet ? null : <h2 className="nthdaysold__h2"> { this.props.messages.days_on_earth } </h2> } { birthdaySet ? null : <button className="nthdaysold__button--start fade" onClick={this.clickHandler} > {this.props.messages.calculate} </button> } <Modal className="modal" ref="yearmodal" backdropStyle={backdropStyle} contentStyle={contentStyle} > <h2 className="nthdaysold__modal__h2"> { this.props.messages.year_born } </h2> <div> <input ref="yearinput" className="nthdaysold__modal-input" type="tel" placeholder="1940" autoFocus /> <button data-type="year" className="nthdaysold__modal__button nthdaysold__modal__button--year" onClick={this.nextStep} > { this.props.messages.next } </button> </div> </Modal> <Modal className="modal" ref="monthmodal" backdropStyle={backdropStyle} contentStyle={contentStyle} > <h2 className="nthdaysold__modal__h2"> { this.props.messages.month_born } </h2> {this.generateMonths()} </Modal> <Modal className="modal" ref="daymodal" backdropStyle={backdropStyle} contentStyle={contentStyle} > <h2 className="nthdaysold__modal__h2"> { this.props.messages.day_born } </h2> {this.generateDays()} </Modal> { birthdaySet ? <div> <Results messages={ this.props.messages} locale={ this.props.locale } data={this.props.data} /> <button className="nthdaysold__button--start fade" onClick={this.clickHandler} > {this.props.messages.try_other} </button> </div> : null } </div> ); } } function select(state) { return { data: state }; } export default connect(select)(NthDaysOld);
jvalen/nth-days-old
js/components/NthDaysOld.js
JavaScript
mit
4,979
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides class sap.ui.dt.plugin.DragDrop. sap.ui.define([ 'sap/ui/dt/Plugin', 'sap/ui/dt/DOMUtil', 'sap/ui/dt/OverlayUtil', 'sap/ui/dt/ElementUtil' ], function(Plugin, DOMUtil, OverlayUtil, ElementUtil) { "use strict"; /** * Constructor for a new DragDrop. * * @param {string} [sId] id for the new object, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new object * * @class * The DragDrop plugin is an abstract plugin to enable drag and drop functionality of the Overlays * This Plugin should be overwritten by the D&D plugin implementations, the abstract functions should be used to perform actions * @extends sap.ui.dt.plugin.Plugin * * @author SAP SE * @version 1.38.4 * * @constructor * @private * @since 1.30 * @alias sap.ui.dt.plugin.DragDrop * @experimental Since 1.30. This class is experimental and provides only limited functionality. Also the API might be changed in future. */ var DragDrop = Plugin.extend("sap.ui.dt.plugin.DragDrop", /** @lends sap.ui.dt.plugin.DragDrop.prototype */ { metadata : { "abstract" : true, // ---- object ---- // ---- control specific ---- library : "sap.ui.dt", properties : { }, associations : { }, events : { } } }); /* * @private */ DragDrop.prototype.init = function() { Plugin.prototype.init.apply(this, arguments); this._mElementOverlayDelegate = { "onAfterRendering" : this._checkMovable }; this._mAggregationOverlayDelegate = { "onAfterRendering" : this._attachDragScrollHandler, "onBeforeRendering" : this._removeDragScrollHandler }; this._dragScrollHandler = this._dragScroll.bind(this); this._dragLeaveHandler = this._dragLeave.bind(this); this._mScrollIntervals = {}; }; /* * @private */ DragDrop.prototype.exit = function() { Plugin.prototype.exit.apply(this, arguments); delete this._mElementOverlayDelegate; delete this._mAggregationOverlayDelegate; delete this._dragScrollHandler; }; /** * @override * @param {sap.ui.dt.Overlay} an Overlay which should be registered */ DragDrop.prototype.registerElementOverlay = function(oOverlay) { oOverlay.addEventDelegate(this._mElementOverlayDelegate, this); oOverlay.attachEvent("movableChange", this._onMovableChange, this); if (oOverlay.isMovable()) { this._attachDragEvents(oOverlay); } oOverlay.attachBrowserEvent("dragover", this._onDragOver, this); oOverlay.attachBrowserEvent("dragenter", this._onDragEnter, this); }; /** * @override */ DragDrop.prototype.registerAggregationOverlay = function(oAggregationOverlay) { oAggregationOverlay.attachTargetZoneChange(this._onAggregationTargetZoneChange, this); if (!sap.ui.Device.browser.webkit) { this._attachDragScrollHandler(oAggregationOverlay); oAggregationOverlay.addEventDelegate(this._mAggregationOverlayDelegate, this); } }; /** * @override */ DragDrop.prototype.deregisterElementOverlay = function(oOverlay) { oOverlay.removeEventDelegate(this._mElementOverlayDelegate, this); oOverlay.detachEvent("movableChange", this._onMovableChange, this); this._detachDragEvents(oOverlay); oOverlay.detachBrowserEvent("dragover", this._onDragOver, this); oOverlay.detachBrowserEvent("dragenter", this._onDragEnter, this); }; /** * @override */ DragDrop.prototype.deregisterAggregationOverlay = function(oAggregationOverlay) { oAggregationOverlay.detachTargetZoneChange(this._onAggregationTargetZoneChange, this); if (!sap.ui.Device.browser.webkit) { oAggregationOverlay.removeEventDelegate(this._mAggregationOverlayDelegate, this); this._removeDragScrollHandler(oAggregationOverlay); this._clearScrollIntervalFor(oAggregationOverlay.$().attr("id")); } }; /** * @private * @param {sap.ui.dt.Overlay} an Overlay to attach events to */ DragDrop.prototype._attachDragEvents = function(oOverlay) { oOverlay.attachBrowserEvent("dragstart", this._onDragStart, this); oOverlay.attachBrowserEvent("drag", this._onDrag, this); oOverlay.attachBrowserEvent("dragend", this._onDragEnd, this); }; /** * @private * @param {sap.ui.dt.Overlay} an Overlay to detach events from */ DragDrop.prototype._detachDragEvents = function(oOverlay) { oOverlay.detachBrowserEvent("dragstart", this._onDragStart, this); oOverlay.detachBrowserEvent("dragend", this._onDragEnd, this); oOverlay.detachBrowserEvent("drag", this._onDrag, this); }; /** * @protected */ DragDrop.prototype.onMovableChange = function(oEvent) { }; /** * @protected */ DragDrop.prototype.onDragStart = function(oDraggedOverlay, oEvent) { }; /** * @protected */ DragDrop.prototype.onDragEnd = function(oDraggedOverlay, oEvent) { }; /** * @protected */ DragDrop.prototype.onDrag = function(oDraggedOverlay, oEvent) { }; /** * @return {boolean} return true to omit event.preventDefault * @protected */ DragDrop.prototype.onDragEnter = function(oOverlay, oEvent) { }; /** * @return {boolean} return true to omit event.preventDefault * @protected */ DragDrop.prototype.onDragOver = function(oOverlay, oEvent) { }; /** * @protected */ DragDrop.prototype.onAggregationDragEnter = function(oAggregationOverlay, oEvent) { }; /** * @protected */ DragDrop.prototype.onAggregationDragOver = function(oAggregationOverlay, oEvent) { }; /** * @protected */ DragDrop.prototype.onAggregationDragLeave = function(oAggregationOverlay, oEvent) { }; /** * @protected */ DragDrop.prototype.onAggregationDrop = function(oAggregationOverlay, oEvent) { }; /** * @private */ DragDrop.prototype._checkMovable = function(oEvent) { var oOverlay = oEvent.srcControl; if (oOverlay.isMovable()) { DOMUtil.setDraggable(oOverlay.$(), true); } }; /** * @private */ DragDrop.prototype._onMovableChange = function(oEvent) { var oOverlay = oEvent.getSource(); if (oOverlay.isMovable()) { this._attachDragEvents(oOverlay); } else { this._detachDragEvents(oOverlay); } this.onMovableChange(oOverlay, oEvent); }; /** * @private */ DragDrop.prototype._onDragStart = function(oEvent) { var oOverlay = sap.ui.getCore().byId(oEvent.currentTarget.id); oEvent.stopPropagation(); // Fix for Firfox - Firefox only fires drag events when data is set if (sap.ui.Device.browser.firefox && oEvent && oEvent.originalEvent && oEvent.originalEvent.dataTransfer && oEvent.originalEvent.dataTransfer.setData) { oEvent.originalEvent.dataTransfer.setData('text/plain', ''); } this.showGhost(oOverlay, oEvent); this.onDragStart(oOverlay, oEvent); }; /** * @protected */ DragDrop.prototype.showGhost = function(oOverlay, oEvent) { var that = this; // not supported in IE10+ if (oEvent && oEvent.originalEvent && oEvent.originalEvent.dataTransfer && oEvent.originalEvent.dataTransfer.setDragImage) { this._$ghost = this.createGhost(oOverlay, oEvent); // ghost should be visible to set it as dragImage this._$ghost.appendTo("#overlay-container"); // if ghost will be removed without timeout, setDragImage won't work setTimeout(function() { that._removeGhost(); }, 0); oEvent.originalEvent.dataTransfer.setDragImage( this._$ghost.get(0), oEvent.originalEvent.pageX - oOverlay.$().offset().left, oEvent.originalEvent.pageY - oOverlay.$().offset().top ); } }; /** * @private */ DragDrop.prototype._removeGhost = function() { this.removeGhost(); delete this._$ghost; }; /** * @protected */ DragDrop.prototype.removeGhost = function() { var $ghost = this.getGhost(); if ($ghost) { $ghost.remove(); } }; /** * @protected */ DragDrop.prototype.createGhost = function(oOverlay) { var oGhostDom = oOverlay.getAssociatedDomRef(); var $ghost; if (!oGhostDom) { oGhostDom = this._getAssociatedDomCopy(oOverlay); $ghost = jQuery(oGhostDom); } else { $ghost = jQuery("<div></div>"); DOMUtil.cloneDOMAndStyles(oGhostDom, $ghost); } var $ghostWrapper = jQuery("<div></div>").addClass("sapUiDtDragGhostWrapper"); return $ghostWrapper.append($ghost.addClass("sapUiDtDragGhost")); }; /** * @private */ DragDrop.prototype._getAssociatedDomCopy = function(oOverlay) { var that = this; var $DomCopy = jQuery("<div></div>"); oOverlay.getAggregationOverlays().forEach(function(oAggregationOverlay) { oAggregationOverlay.getChildren().forEach(function(oChildOverlay) { var oChildDom = oChildOverlay.getAssociatedDomRef(); if (oChildDom) { DOMUtil.cloneDOMAndStyles(oChildDom, $DomCopy); } else { DOMUtil.cloneDOMAndStyles(that._getAssociatedDomCopy(oChildOverlay), $DomCopy); } }); }); return $DomCopy.get(0); }; /** * @protected * @return {jQuery} jQuery object drag ghost */ DragDrop.prototype.getGhost = function() { return this._$ghost; }; /** * @private */ DragDrop.prototype._onDragEnd = function(oEvent) { var oOverlay = sap.ui.getCore().byId(oEvent.currentTarget.id); this._removeGhost(); this._clearAllScrollIntervals(); this.onDragEnd(oOverlay, oEvent); oEvent.stopPropagation(); }; /** * @private */ DragDrop.prototype._onDrag = function(oEvent) { var oOverlay = sap.ui.getCore().byId(oEvent.currentTarget.id); this.onDrag(oOverlay, oEvent); oEvent.stopPropagation(); }; /** * @private */ DragDrop.prototype._onDragEnter = function(oEvent) { var oOverlay = sap.ui.getCore().byId(oEvent.currentTarget.id); if (OverlayUtil.isInTargetZoneAggregation(oOverlay)) { //if "true" returned, propagation won't be canceled if (!this.onDragEnter(oOverlay, oEvent)) { oEvent.stopPropagation(); } } oEvent.preventDefault(); }; /** * @private */ DragDrop.prototype._onDragOver = function(oEvent) { var oOverlay = sap.ui.getCore().byId(oEvent.currentTarget.id); if (OverlayUtil.isInTargetZoneAggregation(oOverlay)) { //if "true" returned, propagation won't be canceled if (!this.onDragOver(oOverlay, oEvent)) { oEvent.stopPropagation(); } } oEvent.preventDefault(); }; /** * @private */ DragDrop.prototype._onAggregationTargetZoneChange = function(oEvent) { var oAggregationOverlay = oEvent.getSource(); var bTargetZone = oEvent.getParameter("targetZone"); if (bTargetZone) { this._attachAggregationOverlayEvents(oAggregationOverlay); } else { this._detachAggregationOverlayEvents(oAggregationOverlay); } }; /** * @private */ DragDrop.prototype._attachAggregationOverlayEvents = function(oAggregationOverlay) { oAggregationOverlay.attachBrowserEvent("dragenter", this._onAggregationDragEnter, this); oAggregationOverlay.attachBrowserEvent("dragover", this._onAggregationDragOver, this); oAggregationOverlay.attachBrowserEvent("dragleave", this._onAggregationDragLeave, this); oAggregationOverlay.attachBrowserEvent("drop", this._onAggregationDrop, this); }; /** * @private */ DragDrop.prototype._detachAggregationOverlayEvents = function(oAggregationOverlay) { oAggregationOverlay.detachBrowserEvent("dragenter", this._onAggregationDragEnter, this); oAggregationOverlay.detachBrowserEvent("dragover", this._onAggregationDragOver, this); oAggregationOverlay.detachBrowserEvent("dragleave", this._onAggregationDragLeave, this); oAggregationOverlay.detachBrowserEvent("drop", this._onAggregationDrop, this); }; /** * @private */ DragDrop.prototype._onAggregationDragEnter = function(oEvent) { var oAggregationOverlay = sap.ui.getCore().byId(oEvent.currentTarget.id); this.onAggregationDragEnter(oAggregationOverlay, oEvent); oEvent.preventDefault(); oEvent.stopPropagation(); }; /** * @private */ DragDrop.prototype._onAggregationDragOver = function(oEvent) { var oAggregationOverlay = sap.ui.getCore().byId(oEvent.currentTarget.id); this.onAggregationDragOver(oAggregationOverlay, oEvent); oEvent.preventDefault(); oEvent.stopPropagation(); }; /** * @private */ DragDrop.prototype._onAggregationDragLeave = function(oEvent) { var oAggregationOverlay = sap.ui.getCore().byId(oEvent.currentTarget.id); this.onAggregationDragLeave(oAggregationOverlay, oEvent); oEvent.preventDefault(); oEvent.stopPropagation(); }; /** * @private */ DragDrop.prototype._onAggregationDrop = function(oEvent) { var oAggregationOverlay = sap.ui.getCore().byId(oEvent.currentTarget.id); this.onAggregationDrop(oAggregationOverlay, oEvent); oEvent.stopPropagation(); }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Scroll ondrag enablement (only for non-webkit browsers) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ var I_SCROLL_TRAP_SIZE = 100; var I_SCROLL_STEP = 20; var I_SCROLL_INTERVAL = 50; /** * @private */ DragDrop.prototype._clearScrollInterval = function(sElementId, sDirection) { if (this._mScrollIntervals[sElementId]) { window.clearInterval(this._mScrollIntervals[sElementId][sDirection]); delete this._mScrollIntervals[sElementId][sDirection]; } }; /** * @private */ DragDrop.prototype._clearScrollIntervalFor = function(sElementId) { var that = this; if (this._mScrollIntervals[sElementId]) { Object.keys(this._mScrollIntervals[sElementId]).forEach(function(sDirection) { that._clearScrollInterval(sElementId, sDirection); }); } }; /** * @private */ DragDrop.prototype._clearAllScrollIntervals = function() { Object.keys(this._mScrollIntervals).forEach(this._clearScrollIntervalFor.bind(this)); }; /** * @private */ DragDrop.prototype._checkScroll = function($element, sDirection, iEventOffset) { var iSize; var fnScrollFunction; var iScrollMultiplier = 1; if (sDirection === "top" || sDirection === "bottom") { iSize = $element.height(); fnScrollFunction = $element.scrollTop.bind($element); } else { iSize = $element.width(); fnScrollFunction = $element.scrollLeft.bind($element); } if (sDirection === "top" || sDirection === "left") { iScrollMultiplier = -1; } // ensure scroll trap size isn't be bigger then ¼ of the container size var iSizeQuarter = Math.floor(iSize / 4); var iTrapSize = I_SCROLL_TRAP_SIZE; if (iSizeQuarter < I_SCROLL_TRAP_SIZE) { iTrapSize = iSizeQuarter; } if (iEventOffset < iTrapSize) { this._mScrollIntervals[$element.attr("id")] = this._mScrollIntervals[$element.attr("id")] || {}; if (!this._mScrollIntervals[$element.attr("id")][sDirection]) { this._mScrollIntervals[$element.attr("id")][sDirection] = window.setInterval(function() { var iInitialScrollOffset = fnScrollFunction(); fnScrollFunction(iInitialScrollOffset + iScrollMultiplier * I_SCROLL_STEP); }, I_SCROLL_INTERVAL); } } else { this._clearScrollInterval($element.attr("id"), sDirection); } }; /** * @private */ DragDrop.prototype._dragLeave = function(oEvent) { var oAggregationOverlay = sap.ui.getCore().byId(oEvent.currentTarget.id); this._clearScrollIntervalFor(oAggregationOverlay.$().attr("id")); }; /** * @private */ DragDrop.prototype._dragScroll = function(oEvent) { var oAggregationOverlay = sap.ui.getCore().byId(oEvent.currentTarget.id); var $aggregationOverlay = oAggregationOverlay.$(); var iDragX = oEvent.clientX; var iDragY = oEvent.clientY; var oOffset = $aggregationOverlay.offset(); var iHeight = $aggregationOverlay.height(); var iWidth = $aggregationOverlay.width(); var iTop = oOffset.top; var iLeft = oOffset.left; var iBottom = iTop + iHeight; var iRight = iLeft + iWidth; this._checkScroll($aggregationOverlay, "bottom", iBottom - iDragY); this._checkScroll($aggregationOverlay, "top", iDragY - iTop); this._checkScroll($aggregationOverlay, "right", iRight - iDragX); this._checkScroll($aggregationOverlay, "left", iDragX - iLeft); }; /** * @private */ DragDrop.prototype._attachDragScrollHandler = function(oEventOrAggregationOverlay) { var oAggregationOverlay; if (ElementUtil.isInstanceOf(oEventOrAggregationOverlay, "sap.ui.dt.AggregationOverlay")) { oAggregationOverlay = oEventOrAggregationOverlay; } else { oAggregationOverlay = oEventOrAggregationOverlay.srcControl; } if (DOMUtil.hasScrollBar(oAggregationOverlay.$())) { oAggregationOverlay.getDomRef().addEventListener("dragover", this._dragScrollHandler, true); oAggregationOverlay.getDomRef().addEventListener("dragleave", this._dragLeaveHandler, true); } }; /** * @private */ DragDrop.prototype._removeDragScrollHandler = function(oEventOrAggregationOverlay) { var oAggregationOverlay; if (ElementUtil.isInstanceOf(oEventOrAggregationOverlay, "sap.ui.dt.AggregationOverlay")) { oAggregationOverlay = oEventOrAggregationOverlay; } else { oAggregationOverlay = oEventOrAggregationOverlay.srcControl; } var oDomRef = oAggregationOverlay.getDomRef(); if (oDomRef) { oDomRef.removeEventListener("dragover", this._dragScrollHandler, true); } }; return DragDrop; }, /* bExport= */ true);
yomboprime/YomboServer
public/lib/openui5/resources/sap/ui/dt/plugin/DragDrop-dbg.js
JavaScript
mit
17,226
datab = [{},{"Tag":{"colspan":"1","rowspan":"1","text":"Group Number (16-bit unsigned integer)"},"Value Length":{"colspan":"1","rowspan":"1","text":"Element Number (16-bit unsigned integer)"},"Value":{"colspan":"1","rowspan":"1","text":"32-bit unsigned integer"},"undefined":{"colspan":"1","rowspan":"1","text":"Even number of bytes containing the Data Elements Value encoded according to the VR specified in and the negotiated Transfer Syntax. Delimited with Sequence Delimitation Item if of Undefined Length."}},{"Tag":{"colspan":"1","rowspan":"1","text":"2 bytes"},"Value Length":{"colspan":"1","rowspan":"1","text":"2 bytes"},"Value":{"colspan":"1","rowspan":"1","text":"4 bytes"},"undefined":{"colspan":"1","rowspan":"1","text":"'Value Length' bytes or Undefined Length"}}];
vupeter/posdaJS
lib/json/book/part05/table_7.1-3.js
JavaScript
mit
780
// Foundation JavaScript // Documentation can be found at: http://foundation.zurb.com/docs var anim; (function($) { function detectIE() { var ua = window.navigator.userAgent; var msie = ua.indexOf('MSIE '); if (msie > 0) { // IE 10 or older => return version number return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10); } var trident = ua.indexOf('Trident/'); if (trident > 0) { // IE 11 => return version number var rv = ua.indexOf('rv:'); return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10); } var edge = ua.indexOf('Edge/'); if (edge > 0) { // Edge (IE 12+) => return version number //return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10); } // other browser return false; } function detectEdge() { var ua = window.navigator.userAgent; var edge = ua.indexOf('Edge/'); if (edge > 0) { // Edge (IE 12+) => return version number return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10); } // other browser return false; } if( detectIE() ){ $('body').addClass('is-ie'); } if( detectEdge() ){ $('body').addClass('is-edge'); } var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1; function wowGrid(){ $('[data-wow-grid], .data-wow-grid').each(function(){ var columns; var $childrens; var $el = $(this); if( typeof( $el.attr('data-wow-selector') ) != 'undefined' ){ $childrens = $el.find( $el.attr('data-wow-selector') ); }else{ $childrens = $el.children(); } if( parseInt( $el.attr('data-wow') ) > 0){ columns = parseInt( $el.attr('data-wow') ); }else{ columns = Math.floor( $el.innerWidth() / $childrens.eq(1).outerWidth() ); } $childrens.each(function(index){ var delay = (index % columns *0.2) + ( Math.floor(index/columns) * 0.1); if( !$(this).hasClass('wow') ){ if(columns === 1){ $(this).addClass('wow fadeInUp'); }else{ $(this).addClass('wow fadeInRight'); } } $(this).attr('data-wow-delay',delay+"s"); }); }); } function rowExpandedPadding(){ var row = $('.row:not(.row .row):not(.expanded)').eq(0); if( typeof(row) != 'undefined' && row.outerWidth() <= $(window).width() ){ var offset = ( $(window).width() - row.outerWidth() ) /2; if(Foundation.MediaQuery.atLeast('medium') ){ offset += 15; }else{ offset += 10; } $('.row.expanded.autopadding > .columns:first-child').css('padding-left', offset); $('.row.expanded.autopadding > .columns:last-child').css('padding-right', offset); } } wowGrid(); $( window ).resize(function() { wowGrid(); }); function wowList(){ $('[data-wow-list], .data-wow-list').each(function(){ $(this).children().each(function(index){ var delay = 0.2; $(this).addClass('wow fadeInUp'); $(this).attr('data-wow-delay',delay+"s"); }); }); } wowList(); $('[data-disabled]').on('click',function(e){e.preventDefault();}); $('.ddl-full-width-row').addClass('expanded').addClass('collapse'); //inject special media queries for interchange on retina devices var retinaQueries = configShared.mediaqueries.retina.replace("'","").split(","); configShared.breakpoints = JSON.parse( configShared.breakpoints.replace(/\s?\(\s?/i, '{"').replace(/\s?\)\s?/i, '"}').replace(/\s?(\,|\:)\s?/ig,'"$1"')); var sizes = ['smallplus','medium','large','xlarge','xxlarge','xxxlarge']; for( var k in sizes ){ var mediaQuerySize = configShared.breakpoints[sizes[k]].match(/([0-9]{1,4})([a-z]{1,3})/i); Foundation.Interchange.SPECIAL_QUERIES[sizes[k]+'R'] = "";//"only screen and (min-width: "+configShared.breakpoints[sizes[k]]+")"; var i = 0; for(var k2 in retinaQueries){ if(i !== 0){ Foundation.Interchange.SPECIAL_QUERIES[sizes[k]+'R'] += ', '; } Foundation.Interchange.SPECIAL_QUERIES[sizes[k]+'R'] += retinaQueries[k2] + ' and (min-width: '+ parseInt(mediaQuerySize[1])/2 + mediaQuerySize[2] +')'; i++; } } $(document).foundation(); rowExpandedPadding(); $(window).on('resize', Foundation.util.throttle(function(e){ rowExpandedPadding(); }, 300)); if( typeof(map) != 'undefined' && typeof(google) != 'undefined' ){ $(document).ready(function() { $(window).resize(function() { google.maps.event.trigger(map, 'resize'); }); google.maps.event.trigger(map, 'resize'); }); } //make interchange work with equalizer $(document).on('replaced.zf.interchange', 'img', function(e) { $(e.target).trigger( 'resizeme.zf.trigger'); }); // Remove empty P tags created by WP inside of Accordion and Orbit jQuery('.accordion p:empty, .orbit p:empty').remove(); // Makes sure last grid item floats left jQuery( '.archive-grid > .columns' ).last().addClass( 'end' ); // Adds Flex Video to YouTube and Vimeo Embeds jQuery( 'iframe[src*="youtube.com"], iframe[src*="vimeo.com"]' ).wrap("<div class='flex-video'/>"); // sticky footer and padding for sticky header function stickyFooter(){ var topOffset = 0; if($('#main-header').css('position') != 'absolute' && $('#main-header').css('position') != 'fixed' ){ topOffset = $('#main-header').outerHeight(true); }else{ } var bottomOffset = $('#main-footer').outerHeight(true); var bodyOffset = $('body').outerHeight(true) - $('body').innerHeight(); if($('#main-header').hasClass('sticky')){ //topOffset = $('#main-header').outerHeight(true); $('.page-wrapper').css('margin-top',topOffset); } $('.page-wrapper').css('min-height',$(window).innerHeight() - topOffset - bottomOffset - bodyOffset); } stickyFooter(); $( window ).resize(function() { stickyFooter(); }); $('[data-slick]').slick(); /* featured posts slider */ $('.slider-for').slick({ slidesToShow: 1, slidesToScroll: 1, arrows: false, fade: true, asNavFor: '.slider-nav', autoplay: true, autoplaySpeed: 5000, }); $('.slider-for').on('init', function(){ }); $('.slider-for').on('afterChange', function(event, slick, currentSlide){ $('.slider-for article').removeClass('slick-timer'); $('.slider-for article').eq(currentSlide).addClass('slick-timer'); $('.slider-nav .article-wrapper').removeClass('slick-highlight'); $('.slider-nav .article-wrapper').eq(currentSlide).addClass('slick-highlight'); }); $('.slider-nav').slick({ slidesToShow: 3, slidesToScroll: 3, asNavFor: '.slider-for', dots: true, centerMode: false, focusOnSelect: true, }); $('.slider-nav').on('setPosition',function(){ $('.slider-nav [data-equalizer-watch]').trigger( 'resizeme.zf.trigger'); }); $('.slider-nav [data-equalizer-watch]').trigger( 'resizeme.zf.trigger'); $('.slider-for article').eq(0).addClass('slick-timer'); $('.slider-nav .article-wrapper').eq(0).addClass('slick-highlight'); /* end of featured posts slider */ function fullpageWow(){ $('body').find('[data-animation]').each(function(){ if( $(this)[0].getBoundingClientRect().top < $(window).height() && $(this)[0].getBoundingClientRect().bottom > 0){ //if($(this).visible( true )){ $(this).addClass('animated ' + $(this).data('animation')); } }); } function fullpageResetWow(){ $('body').find('[data-animation]').each(function(){ $(this).removeClass('animated').removeClass( $(this).data('animation') ).css('opacity',0); }); } var fullpageMultiScrollHandler = function(e, pos){ fullpageWow(); }; var preventWheel = function(e){ //console.log(e); e.stopPropagation(); e.preventDefault(); return false; }; $(document).on("click",'#fp-nav a',function(){ var index = $(this).parent().index(); $('.fp-section').eq(index).find('.fp-scrollable').slimScroll({ scrollTo: '0px' }); }); $(window).on('scroll',function(e){ if($(window).scrollTop() >= $('#main-header').outerHeight() ){ $('body').addClass('menu-scrolled'); }else{ $('body').removeClass('menu-scrolled'); } }); if($(".animsition").length){ $('.wow').css('visibility', 'hidden').css('animation-name', 'none'); var outTransitionTime = 800; if($('body').hasClass('home')){ outTransitionTime = 800; } $(".animsition").animsition({ inClass: 'animsition-fade-in', outClass: 'animsition-fade-out', inDuration: 1500, outDuration: outTransitionTime, linkElement: ':not(.flex-control-nav li) > a:not([target="_blank"]):not([href^="#"]):not(.no-animation):not([data-scroll-target])', // e.g. linkElement: 'a:not([target="_blank"]):not([href^="#"])' loading: true, loadingParentElement: 'body', //animsition wrapper element loadingClass: 'animsition-loading', //loadingInner: "loading", browser: [ 'animation-duration', '-webkit-animation-duration', '-o-animation-duration' ], //"unSupportCss" option allows you to disable the "animsition" in case the css property in the array is not supported by your browser. //The default setting is to disable the "animsition" in a browser that does not support "animation-duration". overlay : false, overlayClass : 'animsition-overlay-slide', overlayParentElement : 'body' }).one('animsition.inStart', function(){ if( $('#fullpage').length > 0 && typeof($.fn.fullpage) != 'undefined' ){ $('#fullpage').fullpage({ //Navigation //menu: '#menu', lockAnchors: false, //anchors:['firstPage', 'secondPage'], navigation: true, navigationPosition: 'right', //navigationTooltips: ['firstSlide', 'secondSlide'], showActiveTooltip: false, slidesNavigation: true, slidesNavPosition: 'bottom', //Scrolling css3: true, scrollingSpeed: 700, autoScrolling: true, fitToSection: true, fitToSectionDelay: 1000, scrollBar: false , easing: 'easeInOutCubic', easingcss3: 'ease', loopBottom: false, loopTop: false, loopHorizontal: true, continuousVertical: false, //normalScrollElements: '#element1, .element2', scrollOverflow: ($(window).width() > 512) , touchSensitivity: 15, normalScrollElementTouchThreshold: 5, //Accessibility keyboardScrolling: true, animateAnchor: true, recordHistory: true, //Design controlArrows: true, verticalCentered: true, resize : true, //sectionsColor : ['#ccc', '#fff'], paddingTop: $('#main-header').outerHeight(), paddingBottom: '0px', //fixedElements: '#main-header, .main-footer', responsiveWidth: 512, responsiveHeight: 0, //Custom selectors sectionSelector: '.section', slideSelector: '.slide', should_scroll_section: true, //events onLeave: function(index, nextIndex, direction){ //console.log(nextIndex); //console.log($('#fullpage > .section').eq(nextIndex-1).css('background-color')); $slide = $('#fullpage > .section').eq(nextIndex-1); //$slide.find('.fp-scrollable').slimScroll({ scrollTo: '0px' });//.isOverPanel = false; $('body').removeClass('dark-color-scheme').removeClass('light-color-scheme'); $('body').addClass($slide.data('color-scheme')); $slide.find('.fp-scrollable').bindFirst('DOMMouseScroll', preventWheel); $slide.find('.fp-scrollable').bindFirst('mousewheel', preventWheel); if( $slide.outerHeight() >= $(window).height()){ $('#main-header').css('background', $slide.css('background-color')); //$('#main-header').animate({ backgroundColor : $slide.css('background-color')}, 700); } }, onSlideLeave: function(anchorLink, index, slideIndex, direction, nextSlideIndex){ //console.log("onSlideLeave--" + "anchorLink: " + anchorLink + " index: " + index + " slideIndex: " + slideIndex + " direction: " + direction); }, afterRender: function(){ //new WOW().init(); fullpageResetWow(); $('.fp-scrollable').slimScroll().unbind('slimscrolling', fullpageMultiScrollHandler); $('.fp-scrollable').slimScroll().bind('slimscrolling', fullpageMultiScrollHandler); $(window).unbind('scroll',fullpageMultiScrollHandler); $(window).bind('scroll',fullpageMultiScrollHandler); $('body').removeClass('dark-color-scheme').removeClass('light-color-scheme'); $('body').addClass( $('.fp-section.active').data('color-scheme') ); fullpageWow(); //console.log("afterRender"); }, afterResize: function(){ //console.log("afterResize"); }, afterReBuild: function(){ //console.log("afterReBuild"); fullpageResetWow(); $('.fp-scrollable').slimScroll().unbind('slimscrolling', fullpageMultiScrollHandler); $('.fp-scrollable').slimScroll().bind('slimscrolling', fullpageMultiScrollHandler); $('body').removeClass('dark-color-scheme').removeClass('light-color-scheme'); $('body').addClass( $('.fp-section.active').data('color-scheme') ); fullpageWow(); }, afterSlideLoad: function(anchorLink, index, slideAnchor, slideIndex){ //console.log("afterSlideLoad--" + "anchorLink: " + anchorLink + " index: " + index + " slideAnchor: " + slideAnchor + " slideIndex: " + slideIndex); //console.log("----------------"); }, afterLoad: function(anchorLink, index){ if( $(this).outerHeight() >= $(window).height()){ //$('#main-header').animate({ backgroundColor : $(this).css('background-color')}, 0); } $(this).find('.fp-scrollable').unbind('DOMMouseScroll', preventWheel); $(this).find('.fp-scrollable').unbind('mousewheel', preventWheel); //$(this).find('.fp-scrollable').slimScroll().isOverPanel = true; fullpageWow(); //console.log('==============='); //console.log("afterLoad--" + "anchorLink: " + anchorLink + " index: " + index ); } }); } else { window.setTimeout(function(){ wow.init(); },500); } }); }else{ wow.init(); } // esempio di body movin come da sito cocacola if( $('#bodymovin').length > 0 && typeof(bodymovinParams) != 'undefined' ){ var firstAutoPlay = true; anim = bodymovin.loadAnimation(bodymovinParams); /* if($('#bodymovin').data('play-from') != null && $('#bodymovin').data('play-to') != null){ console.log('playsegments'); anim.playSegments([$('#bodymovin').data('play-from'),$('#bodymovin').data('play-to')],true); } */ anim.addEventListener('enterFrame',function(e){ //console.log( e); if( Math.ceil( e.currentTime) >= $('#bodymovin').data('play-to') && firstAutoPlay){ anim.pause(); firstAutoPlay = false; } }); anim.addEventListener('complete',function(e){ //console.log(this); //console.log(e); console.log('complete') }); if($('body').hasClass('home')){ console.log('home'); $(document).off( 'click.animsition' ); $(document).on('click.bodymovin' , ':not(.flex-control-nav li) > a:not([target="_blank"]):not([href^="#"]):not(.no-animation):not([data-scroll-target])', function(event) { event.preventDefault(); event.stopPropagation(); var $self = $(this); var url = $self.attr('href'); anim.play(); firstAutoPlay = false; var remainingTime =(anim.totalFrames - anim.currentFrame) / anim.frameRate; //console.log( remainingTime - 0.8); setTimeout(function(){ $('.animsition').animsition('out', $self, url); }, (remainingTime - 0.4) * 1000); // middle mouse button issue #24 // if(middle mouse button || command key || shift key || win control key) /* if (event.which === 2 || event.metaKey || event.shiftKey || navigator.platform.toUpperCase().indexOf('WIN') !== -1 && event.ctrlKey) { window.open(url, '_blank'); } else { __.out.call(_this, $self, url); } */ }); } } // just insert a div like this: // <div class="o-box" data-map data-map-id="yourmapid" data-map-key="yourapikey" data-map-lat="45.514719" data-map-lon="9.229454" data-map-zoom="16" data-map-marker-color="#1ECF92" data-map-marker-size="large" data-map-marker-symbol="circle" data-map-marker-title="Studio Up" data-map-marker-description="Via Esopo 8, Milano"></div> if($('[data-map]').length ){ $('head').append('<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox.js/v2.1.6/mapbox.css" type="text/css" />'); $.getScript("https://api.tiles.mapbox.com/mapbox.js/v2.1.6/mapbox.js", function(){ var lat = $(this).data('map-lat') || 45.514719, lon = $(this).data('map-lon') || 9.229454; $('[data-map]').each(function(){ L.mapbox.accessToken = $(this).data('map-key'); var map = L.mapbox.map($(this)[0], $(this).data('map-id') || 'examples.map-i86nkdio' ).setView([ lat , lon ], $(this).data('map-zoom') || 16); if (Modernizr.touch) { map.dragging.disable(); if (map.tap) map.tap.disable(); }else{ map.scrollWheelZoom.disable(); } L.mapbox.featureLayer({ type: 'Feature', geometry: { type: 'Point', coordinates: [ lon, lat ] }, properties: { title: $(this).data('map-marker-title') || false, description: $(this).data('map-marker-description') || false, 'marker-size': $(this).data('map-marker-size') || 'medium', 'marker-color': $(this).data('map-marker-color') || "#00a3d2", 'marker-symbol': $(this).data('map-marker-symbol') || "" } }).addTo(map); }); }); } outdatedBrowser({ bgColor: '#c6352b', color: '#ffffff', lowerThan: 'transform', languagePath: '' }); })(jQuery);
studioup/cerulean
js/sources/app.js
JavaScript
mit
19,774
import PropTypes from 'prop-types'; import React from 'react'; export default class NumberControl extends React.Component { handleChange = (e) => { const valueType = this.props.field.get('valueType'); const { onChange } = this.props; if(valueType === 'int') { onChange(parseInt(e.target.value, 10)); } else if(valueType === 'float') { onChange(parseFloat(e.target.value)); } else { onChange(e.target.value); } }; render() { const { field, value, forID } = this.props; const min = field.get('min', ''); const max = field.get('max', ''); const step = field.get('step', field.get('valueType') === 'int' ? 1 : ''); return <input type="number" id={forID} value={value || ''} step={step} min={min} max={max} onChange={this.handleChange} />; } } NumberControl.propTypes = { onChange: PropTypes.func.isRequired, value: PropTypes.node, forID: PropTypes.string, valueType: PropTypes.string, step: PropTypes.number, min: PropTypes.number, max: PropTypes.number, };
dopry/netlify-cms
src/components/Widgets/NumberControl.js
JavaScript
mit
1,087
import React from 'react' import BasicType from './BasicType' import { isNumber, toNumber } from 'lodash' class NumberType extends BasicType { constructor() { super() this.type = 'KeyValue' this.updateValue = (e) => { this.props.onChange(toNumber(e.target.value)) } } render() { return ( <div style={{ marginTop: 25 }}> <label style={{ marginBottom: 10 }} className={this.props.displayProps.labelClass}> {this.props.struct.label} </label> <div className="Select"> <input type="number" autoComplete="off" value={this.state.value} onChange={this.updateValue} className={'Select-control Input ' + this.props.displayProps.inputClass} /> </div> </div> ) } } NumberType.checkStruct = function (value) { return isNumber(value) } export default NumberType
jcgertig/react-struct-editor
src/components/Types/Number.js
JavaScript
mit
929
// Load in dependencies var fs = require('fs'); var path = require('path'); var _ = require('underscore'); var async = require('async'); var templater = require('spritesheet-templates'); var Spritesmith = require('spritesmith'); var url = require('url2'); // Define class to contain different extension handlers function ExtFormat() { this.formatObj = {}; } ExtFormat.prototype = { add: function (name, val) { this.formatObj[name] = val; }, get: function (filepath) { // Grab the extension from the filepath var ext = path.extname(filepath); var lowerExt = ext.toLowerCase(); // Look up the file extenion from our format object var formatObj = this.formatObj; var format = formatObj[lowerExt]; return format; } }; // Create img and css formats var imgFormats = new ExtFormat(); var cssFormats = new ExtFormat(); // Add our img formats imgFormats.add('.png', 'png'); imgFormats.add('.jpg', 'jpeg'); imgFormats.add('.jpeg', 'jpeg'); // Add our css formats cssFormats.add('.styl', 'stylus'); cssFormats.add('.stylus', 'stylus'); cssFormats.add('.sass', 'sass'); cssFormats.add('.scss', 'scss'); cssFormats.add('.less', 'less'); cssFormats.add('.json', 'json'); cssFormats.add('.css', 'css'); function getCoordinateName(filepath) { // Extract the image name (exlcuding extension) var fullname = path.basename(filepath); var nameParts = fullname.split('.'); // If there is are more than 2 parts, pop the last one if (nameParts.length >= 2) { nameParts.pop(); } // Return our modified filename return nameParts.join('.'); } module.exports = function gruntSpritesmith(grunt) { // Create a gruntSpritesmithFn function function gruntSpritesmithFn() { // Grab the raw configuration var data = this.data; // If we were invoked via `grunt-newer`, re-localize the info if (data.src === undefined && data.files) { data = data.files[0] || {}; } // Determine the origin and destinations var src = data.src; var destImg = data.dest; var destCss = data.destCss; var cssTemplate = data.cssTemplate; var that = this; // Verify all properties are here if (!src || !destImg || !destCss) { return grunt.fatal('grunt.sprite requires a src, dest (img), and destCss property'); } // Expand all filepaths (e.g. `*.png` -> `home.png`) var srcFiles = grunt.file.expand(src); // If there are settings for retina var retinaSrcFiles; var retinaSrcFilter = data.retinaSrcFilter; var retinaDestImg = data.retinaDest; if (retinaSrcFilter || retinaDestImg) { grunt.log.debug('Retina settings detected'); // Verify our required set is present if (!retinaSrcFilter || !retinaDestImg) { return grunt.fatal('Retina settings detected. We must have both `retinaSrcFilter` and `retinaDest` ' + 'provided for retina to work'); } // Filter out our retina files retinaSrcFiles = []; srcFiles = srcFiles.filter(function filterSrcFile(filepath) { // If we have a retina file, filter it out if (grunt.file.match(retinaSrcFilter, filepath).length) { retinaSrcFiles.push(filepath); return false; // Otherwise, keep it in the src files } else { return true; } }); grunt.verbose.writeln('Retina images found: ' + retinaSrcFiles.join(', ')); // If we have a different amount of normal and retina images, complain and leave if (srcFiles.length !== retinaSrcFiles.length) { return grunt.fatal('Retina settings detected but ' + retinaSrcFiles.length + ' retina images were found. ' + 'We have ' + srcFiles.length + ' normal images and expect these numbers to line up. ' + 'Please double check `retinaSrcFilter`.'); } } // Create an async callback var callback = this.async(); // Determine the format of the image var imgOpts = data.imgOpts || {}; var imgFormat = imgOpts.format || imgFormats.get(destImg) || 'png'; // Set up the defautls for imgOpts _.defaults(imgOpts, {format: imgFormat}); // Prepare spritesmith parameters var spritesmithParams = { engine: data.engine, algorithm: data.algorithm, padding: data.padding || 0, algorithmOpts: data.algorithmOpts || {}, engineOpts: data.engineOpts || {}, exportOpts: imgOpts }; // Construct our spritesmiths var spritesmith = new Spritesmith(spritesmithParams); var retinaSpritesmithParams; // eslint-disable-line var retinaSpritesmith; // eslint-disable-line if (retinaSrcFiles) { retinaSpritesmithParams = _.defaults({ padding: spritesmithParams.padding * 2 }, spritesmithParams); retinaSpritesmith = new Spritesmith(retinaSpritesmithParams); } // In parallel async.parallel([ // Load in our normal images function generateNormalImages(callback) { spritesmith.createImages(srcFiles, callback); }, // If we have retina images, load them in as well function generateRetinaImages(callback) { if (retinaSrcFiles) { return retinaSpritesmith.createImages(retinaSrcFiles, callback); } else { return process.nextTick(callback); } } ], function handleImages(err, resultArr) { // If an error occurred, callback with it if (err) { grunt.fatal(err); return callback(err); } // Otherwise, validate our images line up var normalSprites = resultArr[0]; var retinaSprites = resultArr[1]; // TODO: Validate error looks good if (retinaSprites) { normalSprites.forEach(function validateSprites(normalSprite, i) { var retinaSprite = retinaSprites[i]; if (retinaSprite.width !== normalSprite.width * 2 || retinaSprite.height !== normalSprite.height * 2) { grunt.log.warn('Normal sprite has inconsistent size with retina sprite. ' + '"' + srcFiles[i] + '" is ' + normalSprite.width + 'x' + normalSprite.height + ' while ' + '"' + retinaSrcFiles[i] + '" is ' + retinaSprite.width + 'x' + retinaSprite.height + '.'); } }); } // Process our sprites into spritesheets var result = spritesmith.processImages(normalSprites, spritesmithParams); var retinaResult; if (retinaSprites) { retinaResult = retinaSpritesmith.processImages(retinaSprites, retinaSpritesmithParams); } // Generate a listing of CSS variables var coordinates = result.coordinates; var properties = result.properties; var spritePath = data.imgPath || url.relative(destCss, destImg); var spritesheetInfo = { width: properties.width, height: properties.height, image: spritePath }; var cssVarMap = data.cssVarMap || function noop() {}; var cleanCoords = []; // Clean up the file name of the file Object.getOwnPropertyNames(coordinates).sort().forEach(function prepareTemplateData(file) { // Extract out our name var name = getCoordinateName(file); var coords = coordinates[file]; // Specify the image for the sprite coords.name = name; coords.source_image = file; // DEV: `image`, `total_width`, `total_height` are deprecated as they are overwritten in `spritesheet-templates` coords.image = spritePath; coords.total_width = properties.width; coords.total_height = properties.height; // Map the coordinates through cssVarMap coords = cssVarMap(coords) || coords; // Save the cleaned name and coordinates cleanCoords.push(coords); }); // If we have retina sprites var retinaCleanCoords; // eslint-disable-line var retinaGroups; // eslint-disable-line var retinaSpritesheetInfo; // eslint-disable-line if (retinaResult) { // Generate a listing of CSS variables var retinaCoordinates = retinaResult.coordinates; var retinaProperties = retinaResult.properties; var retinaSpritePath = data.retinaImgPath || url.relative(destCss, retinaDestImg); retinaSpritesheetInfo = { width: retinaProperties.width, height: retinaProperties.height, image: retinaSpritePath }; // DEV: We reuse cssVarMap retinaCleanCoords = []; // Clean up the file name of the file Object.getOwnPropertyNames(retinaCoordinates).sort().forEach(function prepareRetinaTemplateData(file) { var name = getCoordinateName(file); var coords = retinaCoordinates[file]; coords.name = name; coords.source_image = file; coords.image = retinaSpritePath; coords.total_width = retinaProperties.width; coords.total_height = retinaProperties.height; coords = cssVarMap(coords) || coords; retinaCleanCoords.push(coords); }); // Generate groups for our coordinates retinaGroups = cleanCoords.map(function getRetinaGroups(normalSprite, i) { // DEV: Name is inherited from `cssVarMap` on normal sprite return { name: normalSprite.name, index: i }; }); } // If we have handlebars helpers, register them var handlebarsHelpers = data.cssHandlebarsHelpers; if (handlebarsHelpers) { Object.keys(handlebarsHelpers).forEach(function registerHelper(helperKey) { templater.registerHandlebarsHelper(helperKey, handlebarsHelpers[helperKey]); }); } // If there is a custom template, use it var cssFormat = 'spritesmith-custom'; var cssOptions = data.cssOpts || {}; if (cssTemplate) { if (typeof cssTemplate === 'function') { templater.addTemplate(cssFormat, cssTemplate); } else { templater.addHandlebarsTemplate(cssFormat, fs.readFileSync(cssTemplate, 'utf8')); } // Otherwise, override the cssFormat and fallback to 'json' } else { cssFormat = data.cssFormat; if (!cssFormat) { cssFormat = cssFormats.get(destCss) || 'json'; // If we are dealing with retina items, move to retina flavor (e.g. `scss` -> `scss_retina`) if (retinaGroups) { cssFormat += '_retina'; } } } // Render the variables via `spritesheet-templates` var cssStr = templater({ sprites: cleanCoords, spritesheet: spritesheetInfo, spritesheet_info: { name: data.cssSpritesheetName }, retina_groups: retinaGroups, retina_sprites: retinaCleanCoords, retina_spritesheet: retinaSpritesheetInfo, retina_spritesheet_info: { name: data.cssRetinaSpritesheetName }, retina_groups_info: { name: data.cssRetinaGroupsName } }, { format: cssFormat, formatOpts: cssOptions }); // Write out the content async.parallel([ function outputNormalImage(cb) { // Create our directory var destImgDir = path.dirname(destImg); grunt.file.mkdir(destImgDir); // Generate our write stream and pipe the image to it var writeStream = fs.createWriteStream(destImg); writeStream.on('error', cb); writeStream.on('finish', cb); result.image.pipe(writeStream); }, function outputRetinaImage(cb) { if (retinaResult) { var retinaDestImgDir = path.dirname(retinaDestImg); grunt.file.mkdir(retinaDestImgDir); var retinaWriteStream = fs.createWriteStream(retinaDestImg); retinaWriteStream.on('error', cb); retinaWriteStream.on('finish', cb); retinaResult.image.pipe(retinaWriteStream); return; } else { return process.nextTick(cb); } }, function outputCss(cb) { var destCssDir = path.dirname(destCss); grunt.file.mkdir(destCssDir); fs.writeFile(destCss, cssStr, 'utf8', cb); } ], function handleError(err) { // If there was an error, fail with it if (err) { grunt.fatal(err); return callback(err); } // Fail task if errors were logged if (that.errorCount) { return callback(false); } // Otherwise, print a success message if (retinaDestImg) { grunt.log.writeln('Files "' + destCss + '", "' + destImg + '", "' + retinaDestImg + '" created.'); } else { grunt.log.writeln('Files "' + destCss + '", "' + destImg + '" created.'); } // Callback callback(true); }); }); } // Export the gruntSpritesmithFn function grunt.registerMultiTask('sprite', 'Spritesheet making utility', gruntSpritesmithFn); };
Ensighten/grunt-spritesmith
src/grunt-spritesmith.js
JavaScript
mit
13,043
/* jQTouch Calendar Extension based on jQTouch iCal alpha by Bruno Alexandre Use this markup: <div id="any_id"> <ul> <li><time datetime="2009-02-17T05:00Z">Task text here</time></li> </ul> </div> and this to initialise: <script type="text/javascript" charset="utf-8"> var jQT = new $.jQTouch({}); $(function() { $('#any_id').getCalendar(); }); </script> you can also call getCalendar with an options object $('#any_id').getCalendar({date:variable_x, weekstart:variable_y}); Options: date: Date around which to render the initial calendar. Shows this date as selected (default: new Date()) days: Array of titles for the columns (default: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']) months: Array of month names (default: ['January','February','March','April','May','June','July','August','September','October','November','December']) weekstart: index of the position in the days array the week is to start on (default: 1) */ (function($) { if ($.jQTouch) { $.jQTouch.addExtension(function Calendar(jQT){ // Load the calendar for the given date jQuery.fn.getCalendar = function(options) { var defaults = { date : new Date(), days : ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'], months: ['January','February','March','April','May','June','July','August','September','October','November','December'], weekstart: 1, noEvents: 'No Events' } var settings = $.extend({}, defaults, options); return this.each(function(){ var $el = $(this); //Add class for styling $el.addClass('jqt_calendar'); //Save settings $el.data('settings', settings); //Read events from markup $el.loadEvents(); // clear existing calendar $el.empty(); // append generated calendar markup $el.append($el.generateCalendar(settings.date.getMonth(),settings.date.getFullYear())); //Run through dates and add a class to those with events $el.attachEvents(); // set all clicks (don't use live or tap to avoid bugs) $el.setBindings(); // Highlight today if we're on this month $el.setToday(); // If the selected date has events, load them $el.setSelected(settings.date); }); }; //Markup Reading jQuery.fn.loadEvents = function() { $el = $(this); if($el.data('events')) { //We've already processed these. //might look into merging arrays later } else { var events = {}; $el.find('time').each(function(index) { var task_datetime = $(this).attr('datetime'); var time_marker_index = task_datetime.indexOf('T'); var task_day = task_datetime.substring(0, time_marker_index).replace(/-0/g,'-'); var task_time = task_datetime.substring(time_marker_index+1,task_datetime.length-1); var task_text = $(this).html(); if(!$.isArray(events[task_day])) { events[task_day] = [] } events[task_day].push({time:task_time, text:task_text}); }); $el.data('events', events); } } //Markup Generation jQuery.fn.dayMarkup = function(format,day,month,year,column) { var this_day = $('<td/>'); if ( format == 0 ) { this_day.addClass('prevmonth'); } else if ( format == 9 ) { this_day.addClass('nextmonth'); } if ( column==0 || column==6 ) { this_day.addClass('weekend'); } this_day.attr('datetime',year+'-'+(month+1)+'-'+day); this_day.html(day); return this_day; } jQuery.fn.monthLength = function(month, year) { var dd = new Date(year, month, 0); return dd.getDate(); } jQuery.fn.monthMarkup= function(month, year) { var $el = $(this); var settings = $el.data('settings'); var c = new Date(); c.setDate(1);c.setMonth(month);c.setFullYear(year); var x = parseInt(settings.weekstart,10); var s = (c.getDay()-x)%7; if (s<0) { s+=7; } var dm = $el.monthLength(month,year); var this_month = $('<table/>'); this_month.data('month',month+1); this_month.data('year',year); this_month.attr('cellspacing', 0); var table_head = $('<thead/>'); var table_row = $('<tr/>'); $('<th>' + settings.days[(0+x)%7]+'</th>').addClass('goto-prevmonth').appendTo(table_row); $('<th>' + settings.days[(1+x)%7]+'</th>').appendTo(table_row); $('<th>' + settings.days[(2+x)%7]+'</th>').appendTo(table_row); $('<th><span>' + settings.months[month] + ' ' + year + '</span>' + settings.days[(3+x)%7] + '</th>').appendTo(table_row); $('<th>' + settings.days[(4+x)%7]+'</th>').appendTo(table_row); $('<th>' + settings.days[(5+x)%7]+'</th>').appendTo(table_row); $('<th>' + settings.days[(6+x)%7]+'</th>').addClass('goto-nextmonth').appendTo(table_row); table_head.append(table_row); this_month.append(table_head); this_month.append('<tfoot><tr><th colspan="7">&nbsp;</th></tr></tfoot>'); var table_body = $('<tbody/>'); table_row = $('<tr/>'); //Add remaining days from previous month for ( var i=s; i>0; i-- ) { var this_y = (month-1)<0?year-1:year; table_row.append($el.dayMarkup(0, dm-i+1 , (month+11)%12, this_y, (s-i+x)%7)); } //Add this month dm = $el.monthLength(month+1,year); for(var i=1; i <= dm; i++) { if ( (s%7) == 0 ) { table_body.append(table_row.clone()); table_row.empty(); s = 0; } table_row.append($el.dayMarkup(1, i , month, year, (s+x)%7)); s++; } //Add start of next month var j=1; for ( var i=s; i<7; i++ ) { var this_y = (month+1)>11?year+1:year; table_row.append($el.dayMarkup(9, j , (month+1)%12, this_y, (i+x)%7)); j++; } table_body.append(table_row); this_month.append(table_body); return this_month; } jQuery.fn.generateCalendar = function(month, year) { var $el = $(this); var markup = $el.monthMarkup(month, year).after('<ul class="events"></ul>'); return markup; } //Tasks/Events jQuery.fn.attachEvents = function() { return this.each(function(){ var $el = $(this); $el.find('td').each( function(index) { clickedDate = $el.getCellDate($(this)); if($el.hasEvent(clickedDate)) { $(this).addClass('date_has_event'); } }); }); } jQuery.fn.hasEvent = function(date) { //Before doing anything here, we need to parse the events from the code var $el = $(this); var key = $el.dateToString(date); return $el.data('events') && $el.data('events')[key] && $el.data('events')[key].length; } jQuery.fn.getCellDate = function(dateCell) { var date = $(dateCell).attr('datetime'); return $(this).stringToDate(date); } jQuery.fn.stringToDate = function(dateString) { var a = dateString.split('-'); return new Date(a[0],(a[1]-1),a[2]); } jQuery.fn.dateToString = function(date) { return date.getFullYear()+"-"+(date.getMonth() + 1)+"-"+date.getDate(); } jQuery.fn.getEvents = function(date) { var $el = $(this); var d = date.getDate(); var m = date.getMonth() + 1; // zero index based var y = date.getFullYear(); $el.find('.events').empty().append($el.generateEvents(y, m, d)); } jQuery.fn.getNoEvents = function() { $(this).find('.events').empty(); $el.find('.events').empty().append("<li class='no-event'>"+$el.data('settings').noEvents+"</li>"); } jQuery.fn.generateEvents = function(year, month, day) { var $el = $(this); var returnable = ''; $.each($el.data('events')[""+year+"-"+month+"-"+day+""], function(index, value){ returnable += '<li><span>' + value.time + '</span>'+value.text+'</li>'; }); return returnable; } //DOM events & Calendar Manipulation jQuery.fn.setBindings = function() { var $el = $(this); // Days $el.find('td').bind("click", function() { $el.removeSelectedCell(); $(this).addClass('selected'); var clickedDate = $el.getCellDate($(this)); $el.setToday(); if( $(this).hasClass('date_has_event') ) { $el.getEvents(clickedDate); } else { $el.getNoEvents(); } if(jQT.bars) { jQT.setPageHeight(); } if( $(this).hasClass('prevmonth') || $(this).hasClass('nextmonth') ) { $el.getCalendar({date:clickedDate}); } }); // load previous Month $el.find(".goto-prevmonth").bind("click", function() { $el.loadMonthDelta(-1); }); // load next Month $el.find(".goto-nextmonth").bind("click", function() { $el.loadMonthDelta(1); }); } jQuery.fn.removeSelectedCell = function() { $(this).find('.selected').removeClass('selected'); } jQuery.fn.setToday = function() { var $el = $(this); // var date = $el.data('settings').date; var date = new Date(); $el.find('td[datetime='+date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+']').addClass('today'); } jQuery.fn.setSelected = function(date) { $el = $(this); $el.removeSelectedCell(); $el.find('td').each(function() { var clickedDate = $el.getCellDate($(this)); if( !$(this).hasClass("prevmonth") && !$(this).hasClass("nextmonth") && ($el.sameDay(date, clickedDate)) ) { $(this).addClass('selected'); if ( $(this).hasClass('date_has_event') ) { $el.getEvents(date); } else { $el.getNoEvents(); } } }); $el.setToday(); } jQuery.fn.sameDay = function(date1, date2) { return (date1.getDate && date2.getDate) && date1.getDate() == date2.getDate() && date1.getMonth() == date2.getMonth() && date1.getFullYear() == date2.getFullYear() } jQuery.fn.loadMonthDelta = function(delta) { $el = $(this); if($el.find('.selected').length>=1) { var day = $(this).stringToDate($el.find('.selected').attr('datetime')).getDate(); } else { var day = $(this).stringToDate($el.find('.today').attr('datetime')).getDate(); } var month = $el.find('table').data('month'); var year = $el.find('table').data('year'); var newDay = new Date(year, (month-1)+delta, day); $el.getCalendar( $.extend({}, $el.data('settings'), {date:newDay}) ); } }); } })(jQuery);
thingsinjars/jQTouch-Calendar
jqt.calendar.js
JavaScript
mit
10,733
var expect = require('chai').expect; var Column = require('../../lib/mysql/column'); var iface = require('../../lib/column').iface; describe('pg column', function () { it('should implement all the methods defined in the base column interface', function (done) { var c = new Column({ column_name: 'col', data_type: 'integer' }); iface.forEach(function (method) { c[method].call(c); }); done(); }); it('should create an internal meta property for constructor argument', function (done) { var t = new Column({ column_name: 'col' }); expect(t.meta).not.to.be.null; done(); }); it('should implement the getName method', function (done) { var c = new Column({ column_name: 'col' }); expect(c.getName()).to.equal('col'); done(); }); it('should implement the isNullable method', function (done) { var c = new Column({ column_name: 'col', is_nullable: 'YES' }); expect(c.isNullable()).to.be.true; c = new Column({ column_name: 'col', is_nullable: 'NO' }); expect(c.isNullable()).to.be.false; done(); }); it('should implement the getMaxLength method', function (done) { var c = new Column({ column_name: 'col', character_maximum_length: 255 }); expect(c.getMaxLength()).to.equal(255); done(); }); it('should implement the getDataType method', function(done) { var c = new Column({ column_name: 'col', data_type: 'integer' }); expect(c.getDataType()).to.equal('INTEGER'); done(); }); it('should implement the isPrimaryKey method', function(done) { var c = new Column({ column_name: 'col', column_key: 'PRI' }); expect(c.isPrimaryKey()).to.be.true; var c = new Column({ column_name: 'col', column_key: '' }); expect(c.isPrimaryKey()).to.be.false; done(); }); it('should implement the getDefaultValue method', function(done) { var c = new Column({ column_name: 'col', column_default: '30' }); expect(c.getDefaultValue()).to.equal('30'); done(); }); it('should implement the isUnique method', function(done) { var c = new Column({ column_name: 'col', column_key: 'UNI' }); expect(c.isUnique()).to.be.true; var c = new Column({ column_name: 'col', column_key: 'PRI' }); expect(c.isUnique()).to.be.true; var c = new Column({ column_name: 'col', column_key: '' }); expect(c.isUnique()).to.be.false; done(); }); it('should implement the isAutoIncrementing method', function(done) { var c = new Column({ column_name: 'col', extra: 'auto_increment' }); expect(c.isAutoIncrementing()).to.be.true; var c = new Column({ column_name: 'col', extra: '' }); expect(c.isAutoIncrementing()).to.be.false; done(); }); });
kunklejr/node-db-meta
test/mysql/column-test.js
JavaScript
mit
2,712
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {AnyNativeEvent} from '../events/PluginModuleType'; import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; import type {Container, SuspenseInstance} from '../client/ReactDOMHostConfig'; import type {DOMEventName} from '../events/DOMEventNames'; import { isReplayableDiscreteEvent, queueDiscreteEvent, hasQueuedDiscreteEvents, clearIfContinuousEvent, queueIfContinuousEvent, } from './ReactDOMEventReplaying'; import { getNearestMountedFiber, getContainerFromFiber, getSuspenseInstanceFromFiber, } from 'react-reconciler/src/ReactFiberTreeReflection'; import {HostRoot, SuspenseComponent} from 'react-reconciler/src/ReactWorkTags'; import {type EventSystemFlags, IS_CAPTURE_PHASE} from './EventSystemFlags'; import getEventTarget from './getEventTarget'; import {getClosestInstanceFromNode} from '../client/ReactDOMComponentTree'; import {dispatchEventForPluginEventSystem} from './DOMPluginEventSystem'; import {discreteUpdates} from './ReactDOMUpdateBatching'; import { getCurrentPriorityLevel as getCurrentSchedulerPriorityLevel, IdlePriority as IdleSchedulerPriority, ImmediatePriority as ImmediateSchedulerPriority, LowPriority as LowSchedulerPriority, NormalPriority as NormalSchedulerPriority, UserBlockingPriority as UserBlockingSchedulerPriority, } from 'react-reconciler/src/Scheduler'; import { DiscreteEventPriority, ContinuousEventPriority, DefaultEventPriority, IdleEventPriority, getCurrentUpdatePriority, setCurrentUpdatePriority, } from 'react-reconciler/src/ReactEventPriorities'; import ReactSharedInternals from 'shared/ReactSharedInternals'; const {ReactCurrentBatchConfig} = ReactSharedInternals; // TODO: can we stop exporting these? export let _enabled = true; // This is exported in FB builds for use by legacy FB layer infra. // We'd like to remove this but it's not clear if this is safe. export function setEnabled(enabled: ?boolean) { _enabled = !!enabled; } export function isEnabled() { return _enabled; } export function createEventListenerWrapper( targetContainer: EventTarget, domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, ): Function { return dispatchEvent.bind( null, domEventName, eventSystemFlags, targetContainer, ); } export function createEventListenerWrapperWithPriority( targetContainer: EventTarget, domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, ): Function { const eventPriority = getEventPriority(domEventName); let listenerWrapper; switch (eventPriority) { case DiscreteEventPriority: listenerWrapper = dispatchDiscreteEvent; break; case ContinuousEventPriority: listenerWrapper = dispatchContinuousEvent; break; case DefaultEventPriority: default: listenerWrapper = dispatchEvent; break; } return listenerWrapper.bind( null, domEventName, eventSystemFlags, targetContainer, ); } function dispatchDiscreteEvent( domEventName, eventSystemFlags, container, nativeEvent, ) { discreteUpdates( dispatchEvent, domEventName, eventSystemFlags, container, nativeEvent, ); } function dispatchContinuousEvent( domEventName, eventSystemFlags, container, nativeEvent, ) { const previousPriority = getCurrentUpdatePriority(); const prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = 0; try { setCurrentUpdatePriority(ContinuousEventPriority); dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent); } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig.transition = prevTransition; } } export function dispatchEvent( domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, targetContainer: EventTarget, nativeEvent: AnyNativeEvent, ): void { if (!_enabled) { return; } // TODO: replaying capture phase events is currently broken // because we used to do it during top-level native bubble handlers // but now we use different bubble and capture handlers. // In eager mode, we attach capture listeners early, so we need // to filter them out until we fix the logic to handle them correctly. const allowReplay = (eventSystemFlags & IS_CAPTURE_PHASE) === 0; if ( allowReplay && hasQueuedDiscreteEvents() && isReplayableDiscreteEvent(domEventName) ) { // If we already have a queue of discrete events, and this is another discrete // event, then we can't dispatch it regardless of its target, since they // need to dispatch in order. queueDiscreteEvent( null, // Flags that we're not actually blocked on anything as far as we know. domEventName, eventSystemFlags, targetContainer, nativeEvent, ); return; } const blockedOn = attemptToDispatchEvent( domEventName, eventSystemFlags, targetContainer, nativeEvent, ); if (blockedOn === null) { // We successfully dispatched this event. if (allowReplay) { clearIfContinuousEvent(domEventName, nativeEvent); } return; } if (allowReplay) { if (isReplayableDiscreteEvent(domEventName)) { // This this to be replayed later once the target is available. queueDiscreteEvent( blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent, ); return; } if ( queueIfContinuousEvent( blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent, ) ) { return; } // We need to clear only if we didn't queue because // queueing is accumulative. clearIfContinuousEvent(domEventName, nativeEvent); } // This is not replayable so we'll invoke it but without a target, // in case the event system needs to trace it. dispatchEventForPluginEventSystem( domEventName, eventSystemFlags, nativeEvent, null, targetContainer, ); } // Attempt dispatching an event. Returns a SuspenseInstance or Container if it's blocked. export function attemptToDispatchEvent( domEventName: DOMEventName, eventSystemFlags: EventSystemFlags, targetContainer: EventTarget, nativeEvent: AnyNativeEvent, ): null | Container | SuspenseInstance { // TODO: Warn if _enabled is false. const nativeEventTarget = getEventTarget(nativeEvent); let targetInst = getClosestInstanceFromNode(nativeEventTarget); if (targetInst !== null) { const nearestMounted = getNearestMountedFiber(targetInst); if (nearestMounted === null) { // This tree has been unmounted already. Dispatch without a target. targetInst = null; } else { const tag = nearestMounted.tag; if (tag === SuspenseComponent) { const instance = getSuspenseInstanceFromFiber(nearestMounted); if (instance !== null) { // Queue the event to be replayed later. Abort dispatching since we // don't want this event dispatched twice through the event system. // TODO: If this is the first discrete event in the queue. Schedule an increased // priority for this boundary. return instance; } // This shouldn't happen, something went wrong but to avoid blocking // the whole system, dispatch the event without a target. // TODO: Warn. targetInst = null; } else if (tag === HostRoot) { const root: FiberRoot = nearestMounted.stateNode; if (root.hydrate) { // If this happens during a replay something went wrong and it might block // the whole system. return getContainerFromFiber(nearestMounted); } targetInst = null; } else if (nearestMounted !== targetInst) { // If we get an event (ex: img onload) before committing that // component's mount, ignore it for now (that is, treat it as if it was an // event on a non-React tree). We might also consider queueing events and // dispatching them after the mount. targetInst = null; } } } dispatchEventForPluginEventSystem( domEventName, eventSystemFlags, nativeEvent, targetInst, targetContainer, ); // We're not blocked on anything. return null; } export function getEventPriority(domEventName: DOMEventName): * { switch (domEventName) { // Used by SimpleEventPlugin: case 'cancel': case 'click': case 'close': case 'contextmenu': case 'copy': case 'cut': case 'auxclick': case 'dblclick': case 'dragend': case 'dragstart': case 'drop': case 'focusin': case 'focusout': case 'input': case 'invalid': case 'keydown': case 'keypress': case 'keyup': case 'mousedown': case 'mouseup': case 'paste': case 'pause': case 'play': case 'pointercancel': case 'pointerdown': case 'pointerup': case 'ratechange': case 'reset': case 'seeked': case 'submit': case 'touchcancel': case 'touchend': case 'touchstart': case 'volumechange': // Used by polyfills: // eslint-disable-next-line no-fallthrough case 'change': case 'selectionchange': case 'textInput': case 'compositionstart': case 'compositionend': case 'compositionupdate': // Only enableCreateEventHandleAPI: // eslint-disable-next-line no-fallthrough case 'beforeblur': case 'afterblur': // Not used by React but could be by user code: // eslint-disable-next-line no-fallthrough case 'beforeinput': case 'blur': case 'fullscreenchange': case 'focus': case 'hashchange': case 'popstate': case 'select': case 'selectstart': return DiscreteEventPriority; case 'drag': case 'dragenter': case 'dragexit': case 'dragleave': case 'dragover': case 'mousemove': case 'mouseout': case 'mouseover': case 'pointermove': case 'pointerout': case 'pointerover': case 'scroll': case 'toggle': case 'touchmove': case 'wheel': // Not used by React but could be by user code: // eslint-disable-next-line no-fallthrough case 'mouseenter': case 'mouseleave': case 'pointerenter': case 'pointerleave': return ContinuousEventPriority; case 'message': { // We might be in the Scheduler callback. // Eventually this mechanism will be replaced by a check // of the current priority on the native scheduler. const schedulerPriority = getCurrentSchedulerPriorityLevel(); switch (schedulerPriority) { case ImmediateSchedulerPriority: return DiscreteEventPriority; case UserBlockingSchedulerPriority: return ContinuousEventPriority; case NormalSchedulerPriority: case LowSchedulerPriority: // TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration. return DefaultEventPriority; case IdleSchedulerPriority: return IdleEventPriority; default: return DefaultEventPriority; } } default: return DefaultEventPriority; } }
mosoft521/react
packages/react-dom/src/events/ReactDOMEventListener.js
JavaScript
mit
11,428
const axios = require('axios'); const Context = require('../context'); module.exports = async function (callback, ts) { try { if (this.isStopped) { return; } if (!this.longPollParams) { this.longPollParams = await this.getLongPollParams(); } if (callback && !callback.called) { callback.called = true; callback(); } const { data: body } = await axios.get(this.longPollParams.server, { params: { ...this.longPollParams, ts, act: 'a_check', wait: this.settings.polling_timeout, }, }); if (body.failed === 1) { return this.startPolling(callback, body.ts); } if (body.failed) { this.longPollParams = null; this.startPolling(callback); return; } this.ts = body.ts; this.startPolling(callback, body.ts); body.updates.forEach(update => this.next(new Context(update, this))); } catch (err) { if (callback) { callback(err); } this.longPollParams = null; this.startPolling(callback); } };
bifot/node-vk-bot-api
lib/methods/startPolling.js
JavaScript
mit
1,069
/*jslint node: true */ var async = require('async'), http = require('http'), querystring = require('querystring'), parse = require('url').parse; exports.widgets = require('./widgets'); exports.fields = require('./fields'); exports.render = require('./render'); exports.validators = require('./validators'); exports.create = function (fields) { var f = { fields: fields, bind: function (data) { var b = {}; b.toHTML = f.toHTML; b.toJSON = f.toJSON; b.clear = f.clear; b.fields = f.fields; Object.keys(b.fields).forEach(function (k) { b.fields[k] = f.fields[k].bind(data[k]); }); b.data = Object.keys(b.fields).reduce(function (a, k) { a[k] = b.fields[k].data; return a; }, {}); b.validate = function (callback) { async.forEach(Object.keys(b.fields), function (k, callback) { f.fields[k].validate(b, function (err, bound_field) { b.fields[k] = bound_field; callback(err); }); }, function (err) { callback(err, b); }); }; b.isValid = function () { var form = this; return Object.keys(form.fields).every(function (k) { return form.fields[k].error === null || typeof form.fields[k].error === 'undefined'; }); }; return b; }, clear: function () { var b = {}; b.toHTML = f.toHTML; b.toJSON = f.toJSON; b.fields = f.fields; Object.keys(f.fields).forEach(function (k) { f.fields[k].clear(); }); }, handle: function (obj, callbacks) { if (typeof obj === 'undefined' || obj === null) { (callbacks.empty || callbacks.other)(f); } else if (obj instanceof http.IncomingMessage) { if (obj.method === 'GET') { f.handle(parse(obj.url, 1).query, callbacks); } else if (obj.method === 'POST' || obj.method === 'PUT') { // If the app is using bodyDecoder for connect or express, // it has already put all the POST data into request.body. if (obj.body) { f.handle(obj.body, callbacks); } else { var buffer = ''; obj.addListener('data', function (chunk) { buffer += chunk; }); obj.addListener('end', function () { f.handle(querystring.parse(buffer), callbacks); }); } } else { throw new Error('Cannot handle request method: ' + obj.method); } } else if (typeof obj === 'object') { f.bind(obj).validate(function (err, f) { if (f.isValid()) { (callbacks.success || callbacks.other)(f); } else { (callbacks.error || callbacks.other)(f); } }); } else { throw new Error('Cannot handle type: ' + typeof obj); } }, toJSON: function () { var form = this; var r = {}; Object.keys(form.fields).forEach(function (k) { r[k] = form.fields[k].toJSON(k) ; }); return r; }, toHTML: function (iterator) { var form = this; return Object.keys(form.fields).reduce(function (html, k) { return html + form.fields[k].toHTML(k, iterator); }, ''); } }; return f; };
toulon/trestle
templates/app/public/vendor/forms-bootstrap/lib/forms.js
JavaScript
mit
4,027
"use strict"; var should = require('should'); var V4Validator = require('../../src/factory')(); describe('url', function() { it('should pass when the field under validation is a valid URL', function (done) { var data = { field_1: 'http://google.com' }; var rules = { field_1: 'url' }; var validator = V4Validator.make(data, rules); validator.validate(function(err) { if (err) { throw err; } done(); }); }); it('should not pass if the field under validation is not a valid URL', function (done) { var data = { field_1: 'http://google.com', field_2: 'http://musejs.io/fake-page', field_3: 'ksdjflk' }; var rules = { field_1: 'url', field_2: 'url', field_3: 'url' }; var validator = V4Validator.make(data, rules); validator.validate(function(err) { err.should.be.ok; err.should.have.property('meta'); err.meta.should.not.have.property('field_1'); err.meta.should.not.have.property('field_2'); err.meta.should.have.property('field_3'); done(); }); }); });
musejs/v4-validator
test/rules/url.js
JavaScript
mit
1,312
import React, {PropTypes, Component} from 'react'; import Paper from 'material-ui/Paper'; import Popover from 'material-ui/Popover'; import Menu from 'material-ui/Menu'; import MenuItem from 'material-ui/MenuItem'; import IconMenu from 'material-ui/IconMenu'; import IconButton from 'material-ui/IconButton'; import FlatButton from 'material-ui/FlatButton'; import FontIcon from 'material-ui/FontIcon'; import {ActionHome, NavigationMenu, ActionAccountBox, ActionPowerSettingsNew, NavigationMoreVert} from 'material-ui/svg-icons'; import {Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle} from 'material-ui/Toolbar'; import Drawer from 'material-ui/Drawer'; import {Confirm, Alert, SideMenu} from 'react-semi-theme/widgets'; import helper from 'react-semi-theme/libs/helper'; import 'flag-icon-css/css/flag-icon.min.css'; class SecondaryLayout extends Component { constructor(props, context) { super(props, context); this.linkTo = this.linkTo.bind(this); this.openConfirm = this.openConfirm.bind(this); this.openAlert = this.openAlert.bind(this); let {query} = props.location; let showMenu = (query['show-menu']=='true' || query['show-menu'] == '1'); let defaultLocale = props.locale; let currentLocale = query['locale'] || defaultLocale; this.state = { showMainMenu: showMenu, languages: { items: [ {icon: <FontIcon className="flag-icon flag-icon-th" />, name: 'ไทย', locale: 'th'}, {icon: <FontIcon className="flag-icon flag-icon-gb" />, name: 'English', locale: 'en'} ], defaultLocale, currentLocale, openMenu: false, anchorEl: null } }; } linkTo(pathname) { return this.context.router.push(pathname); } getChildContext() { return { dialog: { confirm: this.openConfirm, alert: this.openAlert } } } openConfirm(...params) { console.log('openConfirm'); this.refs.confirm.open(params); } openAlert(...params) { // console.log('description', title, description); this.refs.alert.open(params); } toggleMainMenu = () => { this.setState({showMainMenu: !this.state.showMainMenu}); }; render() { // console.log('render: layout', this.props.user); let showMainMenu = this.state.showMainMenu; let settings = this.props.settings; let {query} = this.props.location; let {setLocale} = this.props.actions; let toolsMenu = null; /* let languages = this.state.languages.items.map((lang, i)=>{ return ( <MenuItem key={i} primaryText={lang.name} onTouchTap={()=>{ let localeQuery = lang.locale==this.state.languages.defaultLocale ? undefined : lang.locale; let nextQuery = Object.assign({}, query, {'locale': localeQuery}); this.context.router.replace(Object.assign({}, this.props.location, {query: nextQuery})); this.setState({languages: Object.assign({}, this.state.languages, {currentLocale: lang.locale, openMenu: false, anchorEl: null})}); setLocale(lang.locale); }} /> ); }); let lang = this.state.languages.items.filter((l)=>l.locale==this.state.languages.currentLocale)[0]; */ let languages = this.state.languages.items.map((lang, i)=> { return ( <FlatButton key={i} className="icon-btn left-most" icon={lang.icon} backgroundColor={lang.locale==this.state.languages.currentLocale ? 'rgba(153, 153, 153, 0.2)' : ''} onTouchTap={()=>{ let localeQuery = lang.locale==this.state.languages.defaultLocale ? undefined : lang.locale; let nextQuery = Object.assign({}, query, {'locale': localeQuery}); this.context.router.replace(Object.assign({}, this.props.location, {query: nextQuery})); this.setState({languages: Object.assign({}, this.state.languages, {currentLocale: lang.locale, openMenu: false, anchorEl: null})}); setLocale(lang.locale) }} /> ) }); let showMenu = (query['show-menu']=='true' || query['show-menu'] == '1'); return ( <div id="layout" className={`${showMainMenu ? '' : 'no-menu'}`} onKeyPress={(e)=>{ if(e.charCode==76){ let nextLang = this.state.languages.items.filter((lang)=>lang.locale!=this.state.languages.currentLocale)[0]; let localeQuery = nextLang.locale==this.state.languages.defaultLocale ? undefined : nextLang.locale; let nextQuery = Object.assign({}, query, {'locale': localeQuery}); this.context.router.replace(Object.assign({}, this.props.location, {query: nextQuery})); this.setState({languages: Object.assign({}, this.state.languages, {currentLocale: nextLang.locale, openMenu: false, anchorEl: null})}); setLocale(nextLang.locale); } if(e.charCode==77){ let nextQuery = Object.assign({}, query, {'show-menu': !showMenu || undefined}); this.context.router.replace(Object.assign({}, this.props.location, {query: nextQuery})); this.setState({showMainMenu: !showMenu}); } }} tabIndex="1" > <Confirm ref="confirm" /> <Alert ref="alert" /> <Drawer open={showMainMenu} className={`menu-wrapper ${showMainMenu ? '' : 'minimize'}`}> <Toolbar className="side-nav-bar"><ToolbarTitle text="Navigation"/></Toolbar> <SideMenu location={this.props.location} menu={this.props.mainMenu} /> </Drawer> <Paper className="top-nav-wrap" zDepth={1}> <Toolbar className="top-nav-bar"> <ToolbarGroup firstChild={true}> {/*FlatButton className="icon-btn left-most" icon={<NavigationMenu />} onTouchTap={this.toggleMainMenu} /> <IconButton iconClassName="muidocs-icon-custom-github"/>*/} <FlatButton className="icon-btn left-most" icon={<ActionHome />} onTouchTap={()=>this.context.router.push('/')} /> </ToolbarGroup> <ToolbarGroup> {/* <FlatButton className="icon-btn left-most" icon={lang.icon} onTouchTap={(event)=>{event.preventDefault();this.setState({languages: Object.assign(this.state.languages, {openMenu: !this.state.languages.openMenu, anchorEl: event.currentTarget})})}}/> <Popover open={this.state.languages.openMenu} anchorEl={this.state.languages.anchorEl} anchorOrigin={{horizontal: 'left', vertical: 'top'}} targetOrigin={{horizontal: 'right', vertical: 'top'}} onRequestClose={()=>this.setState({languages: Object.assign(this.state.languages, {openMenu: false, anchorEl: null})})} > <Menu> {languages} </Menu> </Popover> */} {languages} <ToolbarTitle text={settings.toolbarTitle} /> {toolsMenu} </ToolbarGroup> </Toolbar> </Paper> <div className={`main-wrap`}> {React.cloneElement(this.props.children, {locale: this.props.locale, setLocale})} </div> </div> ); } } SecondaryLayout.propTypes = { location: PropTypes.object.isRequired, appBarTitle: PropTypes.string.isRequired, children: PropTypes.object.isRequired }; SecondaryLayout.contextTypes = { router: PropTypes.object }; SecondaryLayout.childContextTypes = { dialog: PropTypes.object }; export default SecondaryLayout;
tsupol/semi-starter
src/components/main/SecondaryLayout.js
JavaScript
mit
8,411
version https://git-lfs.github.com/spec/v1 oid sha256:3712c50fc5c0d8df7d48255abb240c06675994003ac1992d97d0e38e68ea8709 size 34487
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.17.2/app-transitions-native/app-transitions-native-coverage.js
JavaScript
mit
130
'use strict'; const path = require('path'); const coffee = require('coffee'); const mm = require('mm'); describe('test/my-cosmos-bin.test.js', () => { const cosmosBin = require.resolve('./fixtures/my-cosmos-bin/bin/my-cosmos-bin.js'); const cwd = path.join(__dirname, 'fixtures/test-files'); afterEach(mm.restore); it('should my-cosmos-bin test success', done => { mm(process.env, 'TESTS', 'test/**/*.test.js'); coffee.fork(cosmosBin, [ 'test' ], { cwd }) .debug() .expect('stdout', /should success/) .expect('stdout', /a.test.js/) .expect('stdout', /b\/b.test.js/) .notExpect('stdout', /a.js/) .expect('code', 0) .end(done); }); });
kinglion/cosmos-bin
test/my-cosmos-bin.test.js
JavaScript
mit
757
var De = { output: '', log: function() {}, errlog: null, startTime: '', init: function(output) { De.output = output; if (typeof(output) == 'string') { if (output == 'firebug') { De.log = function() { if (!window.DEV_MODE) return; Function.prototype.apply.apply(console.log, [console, arguments]); } } else if (output == 'alert') { De.log = function() { if (!window.DEV_MODE) return; var s = ''; for(var i=0;i<arguments.length;i++) { s+= ' '+arguments[i]+' '; } alert(s); } } else { var errlog; if (document.getElementById('errlog') != null) { errlog = document.getElementById('errlog'); } else { errlog = document.createElement('div'); errlog.id = 'errlog'; errlog.style.zIndex = 999999; errlog.style.color = 'red'; document.body.appendChild(errlog); } De.log = function () { if (!window.DEV_MODE) return; errlog.innerHTML += '<div>'; errlog.innerHTML += '<div><pre style="float:left">'; for(var i=0;i<arguments.length;i++) { errlog.innerHTML += ' '+arguments[i]+' '; } errlog.innerHTML += '</pre></div>'; errlog.innerHTML += '<div><font color=blue>'+(new Date).getTime()+'</font></div>'; errlog.innerHTML += '</div>'; } } } else { output(); } }, assert: function (condition, msg, para) { if (!condition) { console.error('ASSERTION FAILED: '+msg); if (defined(para)) { //De.listProp(para); De.log(para); } console.error('ASSERTION END'); return false; } return true; }, listProp: function (obj) { if (De.output == 'firebug') { for (var k in obj) { De.log("obj.",k," = ",obj[k]); } } else if (De.output == 'alert') { newline = '\n'; var s=''; for (var k in obj) { s+="obj."+i+" = "+obj[k]+newline; if (s.length > 300) { De.log(s); s = ''; } } De.log(s); } else { newline = '<br/>'; var s=''; for (var k in obj) { s+="obj."+i+" = "+obj[k]+newline; } De.log(s); } }, time: function (){ if (!window.DEV_MODE) return; var isReset = false; var extra = []; if (arguments.length > 0){ for (var i=0; i < arguments.length; i++) { if (arguments[i] === true) { isReset = true; } else { extra.push(arguments[i]); } } } if (isReset) { De.startTime = (new Date).getTime(); } var delta = ((new Date).getTime()) - De.startTime; delta = delta / 1000; var caller = arguments.callee.caller.name; caller = (caller) ? caller : '(func)'; // var caller = ''; var msg = delta+" "+caller+"."; if (extra.length !== 0) { De.log(msg, extra); } else { De.log(msg); } }, dummy: 0 } var ie = (function(){ var undef, v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while ( div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[0] ) {} return v > 4 ? v : undef; }()); if (ie) { De.init('ie'); } else { De.init('firebug'); } var de = De; //alias function defined(v) { var f = 1; if (typeof (v) === 'undefined') { f = 0; } else if (typeof (v) === 'number') { f = 1 } else if (typeof (v) === 'string') { f = 1 } else if (typeof (v) === 'function') { f = 1 } else if (!v) { f = 0; } return f; } function getKCode(event) { return event.which || event.keyCode } // implement JSON.stringify serialization var JSON = JSON || {}; JSON.stringify = JSON.stringify || function (obj) { var t = typeof (obj); if (t != "object" || obj === null) { // simple data type if (t == "string") obj = '"'+obj+'"'; return String(obj); } else { // recurse array or object var n, v, json = [], arr = (obj && obj.constructor == Array); for (n in obj) { v = obj[n]; t = typeof(v); if (t == "string") v = '"'+v+'"'; else if (t == "object" && v !== null) v = JSON.stringify(v); json.push((arr ? "" : '"' + n + '":') + String(v)); } return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}"); } }; // FUTURE maybe separated these as one file // http://stackoverflow.com/questions/4877326/how-can-i-tell-if-a-string-contains-multibyte-characters-in-javascript // use: None function containsSurrogatePair(str) { return /[\uD800-\uDFFF]/.test(str); } // http://stackoverflow.com/questions/11200451/extract-substring-by-utf-8-byte-positions // use: std.js function encode_utf8(str) { return unescape(encodeURIComponent(str)); } // use: std.js, [Manager.js] function length_utf8_length(str) { // by chintown return encode_utf8(str).length; } // use: std.js, [Manager.js] function substr_utf8_bytes(str, startInBytes, lengthInBytes) { /* this function scans a multibyte string and returns a substring. * arguments are start position and length, both defined in bytes. * * this is tricky, because javascript only allows character level * and not byte level access on strings. Also, all strings are stored * in utf-16 internally - so we need to convert characters to utf-8 * to detect their length in utf-8 encoding. * * the startInBytes and lengthInBytes parameters are based on byte * positions in a utf-8 encoded string. * in utf-8, for example: * "a" is 1 byte, "ü" is 2 byte, and "你" is 3 byte. * * NOTE: * according to ECMAScript 262 all strings are stored as a sequence * of 16-bit characters. so we need a encode_utf8() function to safely * detect the length our character would have in a utf8 representation. * * http://www.ecma-international.org/publications/files/ecma-st/ECMA-262.pdf * see "4.3.16 String Value": * > Although each value usually represents a single 16-bit unit of * > UTF-16 text, the language does not place any restrictions or * > requirements on the values except that they be 16-bit unsigned * > integers. */ var resultStr = ''; var startInChars = 0; // scan string forward to find index of first character // (convert start position in byte to start position in characters) for (bytePos = 0; bytePos < startInBytes; startInChars++) { // get numeric code of character (is >128 for multibyte character) // and increase "bytePos" for each byte of the character sequence ch = str.charCodeAt(startInChars); bytePos += (ch < 128) ? 1 : encode_utf8(str[startInChars]).length; } // now that we have the position of the starting character, // we can built the resulting substring // as we don't know the end position in chars yet, we start with a mix of // chars and bytes. we decrease "end" by the byte count of each selected // character to end up in the right position end = startInChars + lengthInBytes - 1; for (n = startInChars; startInChars <= end; n++) { // get numeric code of character (is >128 for multibyte character) // and decrease "end" for each byte of the character sequence ch = str.charCodeAt(n); end -= (ch < 128) ? 1 : encode_utf8(str[n]).length; resultStr += str[n]; } return resultStr; } var RE_NEWLINE_WINDOWS = new RegExp("\r\n", 'g'); var RE_NEWLINE_MAC = new RegExp("\r", 'g'); function normalizeNewline (text) { // http://darklaunch.com/2009/05/06/php-normalize-newlines-line-endings-crlf-cr-lf-unix-windows-mac text = text.replace(RE_NEWLINE_WINDOWS, "\n"); text = text.replace(RE_NEWLINE_MAC, "\n"); return text; } // (space) ~!@#$%^&*=\;'/()[]{}<>`+|:"? var RE_INVALID_FILE_CHARS = new RegExp('[ ~!@#$%\^&*=\\\\;\'\/(){}<>\\[\\]`+|:"]', 'g'); function normalizeFilename (text, prefixPreventEmpty) { prefixPreventEmpty = prefixPreventEmpty || 'fn_'+(new Date()).getTime(); text = text.replace(RE_INVALID_FILE_CHARS, "_"); if (text.replace(/_/g, '') === '') { text = prefixPreventEmpty + text; } return text; } //de.log(normalizeFilename('0~1!2@3#4$5%6^7&8*9=0')); //de.log(normalizeFilename('a\\b;c\'d/e(f)g[h]i{j}k<l>m`n+o|p:q"rstuvwxyx')); //de.log(normalizeFilename('!@#$@#%#^#$%^')); //de.log(normalizeFilename('5/5/5')); function setCookie(key, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toGMTString(); } document.cookie = key + "=" + value +expires + "; path=/"; } function getCookie(key) { var cookieStr = document.cookie; cookieStr = (cookieStr) ? cookieStr+";" : cookieStr; // make the pattern consistent var matchResult = cookieStr.match(key+'=(.*?);'); if (matchResult) { return matchResult[1]; } else { return null; } } function removeCookie(key) { setCookie(key, "", -1); }
chintown/PhpStake
htdoc/js/std.js
JavaScript
mit
10,154
export default class Node { constructor(board, id, containerSvg, x, y, numCol, numRow, unitW, unitH, w, h) { this.board = board; this.id = id; this.containerSvg = containerSvg; this.x = x; this.y = y; this.numCol = numCol; this.numRow = numRow; this.unitW = unitW; this.unitH = unitH; this.w = w; this.h = h; this.create(); this.board.nodeList.push(this); this.board.nodeMap[id] = this; //this.draw(); } create() { var self = this; this.svg = this.containerSvg.append("g").attr("height", this.h).attr("width", this.w).attr("transform", "translate("+this.getX()+", "+this.getY()+")") .on("click", function() { self.setSelected(); }) } draw() { } getX() { //debugger return this.x*this.unitW+this.board.x-this.unitW/2; } getY() { return this.y*this.unitH+this.board.y-this.unitH/2; } setSelected(notSet) { this.notSet = notSet; this.markButtonList = []; //clear existing button if (this.board.selected!==undefined && !notSet) { //do unselected UI here if(this.board.markList.length > 0){ for(var i = 0; i < this.board.markList.length; i++){ this.board.markList[i].elem.style("visibility", function() {return "hidden";}) } } } this.board.markList = []; this.board.selected = this; //do selected UI here this.handleButtons(); return this.markButtonList; } handleButtons() { //handle it in sub classes } illegalMove(x, y){ return false; }//movetoNode? getButton(x, y) { if (this.board.buttonList[x]===undefined) { return false; } if(this.illegalMove(x, y)){ return false; } var cell = this.board.cellState[x][y]; if (this.id=="blackCar1" && cell !==undefined) { //debugger } if (cell !== undefined && cell.isRed === this.isRed){ return false; } var b = this.board.buttonList[x][y] if (b===undefined) { return false; } this.doSetButton(b); return true; } doSetButton(b) { this.markButtonList.push(b); if (this.notSet) { return; } b.visibility = "visible" b.elem.style("visibility", function() {return "visible";}) console.log("==="+this.board.markList.length) this.board.markList.push(b); } }
cindyqian/BoardGames
src/common/Node.js
JavaScript
mit
2,218
var chai = require('chai'); var expect = chai.expect; require('../../src/utils/adjustDecimal'); describe('src/utils/math', function () { it('should be able to round10', function () { expect(Math.round10(120.002, 2)) .to.be.equal(100); expect(Math.round10(180.002, 2)) .to.be.equal(200); }); it('should be able to floor10', function () { expect(Math.floor10(120.002, 2)) .to.be.equal(100); expect(Math.floor10(120.684, -2)) .to.be.equal(120.68); }); it('should be able to ceil10', function () { expect(Math.ceil10(120.002, 2)) .to.be.equal(200); }); it('should be able to handle no arguments and return NaN', function () { expect(Math.round10()) .to.satisfy(function (re) { if (isNaN(re)) { return true; } return false; }); expect(Math.floor10()) .to.satisfy(function (re) { if (isNaN(re)) { return true; } return false; }); expect(Math.ceil10()) .to.satisfy(function (re) { if (isNaN(re)) { return true; } return false; }); }); it('should be able to handle and return the origin number', function () { expect(Math.round10(10)) .to.be.equal(10); expect(Math.floor10(10)) .to.be.equal(10); expect(Math.ceil10(10)) .to.be.equal(10); }); });
alfredkam/yakojs
test/utils/adjustDecimal-test.js
JavaScript
mit
1,642
/* // load the things we need var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); // define the schema for our user model var userSchema = mongoose.Schema({ local : { email : String, password : String }, facebook : { id : String, token : String, email : String, name : String, photos : String }, twitter : { id : String, token : String, displayName : String, username : String, photos : String }, google : { id : String, token : String, email : String, name : String, photos : String }, vk : { id : String, token : String, email : String, name : String, photos : String }, odnoklassniki : { id : String, token : String, email : String, name : String, photos : String } }); // generating a hash userSchema.methods.generateHash = function(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); }; // checking if password is valid userSchema.methods.validPassword = function(password) { return bcrypt.compareSync(password, this.local.password); }; // create the model for users and expose it to our app module.exports = mongoose.model('User', userSchema); */
zablon/BE-for-Gport
app/oldModels/user.js
JavaScript
mit
1,628
'use strict'; // return hex module.exports = function(buffer) { return buffer.toString('hex'); };
ynakajima/psd-image-resource-parser
lib/block-data-parser/hex.js
JavaScript
mit
101
/*globals define*/ /*jshint browser: true, bitwise: false*/ /** * @author brollb / https://github/brollb */ define([ 'js/logger', 'common/util/assert', './AutoRouter.Constants', './AutoRouter.Utils', './AutoRouter.Point', './AutoRouter.Rect', './AutoRouter.PointList' ], function (Logger, assert, CONSTANTS, Utils, ArPoint, ArRect, ArPointListPath) { 'use strict'; // AutoRouterPath var AutoRouterPath = function () { this.id = 'None'; this.owner = null; this.startpoint = null; this.endpoint = null; this.startports = null; this.endports = null; this.startport = null; this.endport = null; this.attributes = CONSTANTS.PathDefault; this.state = CONSTANTS.PathStateDefault; this.isAutoRoutingOn = true; this.customPathData = []; this.customizationType = 'Points'; this.pathDataToDelete = []; this.points = new ArPointListPath(); }; //----Points AutoRouterPath.prototype.hasOwner = function () { return this.owner !== null; }; AutoRouterPath.prototype.setStartPorts = function (newPorts) { this.startports = newPorts; if (this.startport) { this.calculateStartPorts(); } }; AutoRouterPath.prototype.setEndPorts = function (newPorts) { this.endports = newPorts; if (this.endport) { this.calculateEndPorts(); } }; AutoRouterPath.prototype.clearPorts = function () { // remove the start/endpoints from the given ports if (this.startpoint) { this.startport.removePoint(this.startpoint); this.startpoint = null; } if (this.endpoint) { this.endport.removePoint(this.endpoint); this.endpoint = null; } this.startport = null; this.endport = null; }; AutoRouterPath.prototype.getStartPort = function () { assert(this.startports.length, 'ARPort.getStartPort: Can\'t retrieve start port. from '+this.id); if (!this.startport) { this.calculateStartPorts(); } return this.startport; }; AutoRouterPath.prototype.getEndPort = function () { assert(this.endports.length, 'ARPort.getEndPort: Can\'t retrieve end port from '+this.id); if (!this.endport) { this.calculateEndPorts(); } return this.endport; }; /** * Remove port from start/end port lists. * * @param port * @return {undefined} */ AutoRouterPath.prototype.removePort = function (port) { var removed = Utils.removeFromArrays(port, this.startports, this.endports); assert(removed, 'Port was not removed from path start/end ports'); // If no more start/end ports, remove the path // assert(this.startports.length && this.endports.length, 'Removed all start/endports of path ' + this.id); this.owner.disconnect(this); }; AutoRouterPath.prototype.calculateStartEndPorts = function () { return {src: this.calculateStartPorts(), dst: this.calculateEndPorts()}; }; AutoRouterPath.prototype.calculateStartPorts = function () { var srcPorts = [], tgt, i; assert(this.startports.length > 0, 'ArPath.calculateStartEndPorts: this.startports cannot be empty!'); //Remove this.startpoint if (this.startport && this.startport.hasPoint(this.startpoint)) { this.startport.removePoint(this.startpoint); } //Get available ports for (i = this.startports.length; i--;) { assert(this.startports[i].owner, 'ARPath.calculateStartEndPorts: port ' + this.startports[i].id + ' has invalid this.owner!'); if (this.startports[i].isAvailable()) { srcPorts.push(this.startports[i]); } } if (srcPorts.length === 0) { srcPorts = this.startports; } //Preventing same start/endport if (this.endport && srcPorts.length > 1) { i = srcPorts.length; while (i--) { if (srcPorts[i] === this.endport) { srcPorts.splice(i, 1); } } } // Getting target if (this.isAutoRouted()) { var accumulatePortCenters = function (prev, current) { var center = current.rect.getCenter(); prev.x += center.x; prev.y += center.y; return prev; }; tgt = this.endports.reduce(accumulatePortCenters, new ArPoint(0, 0)); tgt.x /= this.endports.length; tgt.y /= this.endports.length; } else { tgt = this.customPathData[0]; } // Get the optimal port to the target this.startport = Utils.getOptimalPorts(srcPorts, tgt); // Create a this.startpoint at the port var startdir = this.getStartDir(), startportHasLimited = false, startportCanHave = true; if (startdir !== CONSTANTS.DirNone) { startportHasLimited = this.startport.hasLimitedDirs(); startportCanHave = this.startport.canHaveStartEndPointOn(startdir, true); } if (startdir === CONSTANTS.DirNone || // recalc startdir if empty startportHasLimited && !startportCanHave) { // or is limited and userpref is invalid startdir = this.startport.getStartEndDirTo(tgt, true); } this.startpoint = this.startport.createStartEndPointTo(tgt, startdir); this.startpoint.owner = this; return this.startport; }; AutoRouterPath.prototype.calculateEndPorts = function () { var dstPorts = [], tgt, i = this.endports.length; assert(this.endports.length > 0, 'ArPath.calculateStartEndPorts: this.endports cannot be empty!'); //Remove old this.endpoint if (this.endport && this.endport.hasPoint(this.endpoint)) { this.endport.removePoint(this.endpoint); } //Get available ports while (i--) { assert(this.endports[i].owner, 'ARPath.calculateStartEndPorts: this.endport has invalid this.owner!'); if (this.endports[i].isAvailable()) { dstPorts.push(this.endports[i]); } } if (dstPorts.length === 0) { dstPorts = this.endports; } //Preventing same start/this.endport if (this.startport && dstPorts.length > 1) { i = dstPorts.length; while (i--) { if (dstPorts[i] === this.startport) { dstPorts.splice(i, 1); } } } //Getting target if (this.isAutoRouted()) { var accumulatePortCenters = function (prev, current) { var center = current.rect.getCenter(); prev.x += center.x; prev.y += center.y; return prev; }; tgt = this.startports.reduce(accumulatePortCenters, new ArPoint(0, 0)); tgt.x /= this.startports.length; tgt.y /= this.startports.length; } else { tgt = this.customPathData[this.customPathData.length - 1]; } //Get the optimal port to the target this.endport = Utils.getOptimalPorts(dstPorts, tgt); //Create this.endpoint at the port var enddir = this.getEndDir(), startdir = this.getStartDir(), endportHasLimited = false, endportCanHave = true; if (enddir !== CONSTANTS.DirNone) { endportHasLimited = this.endport.hasLimitedDirs(); endportCanHave = this.endport.canHaveStartEndPointOn(enddir, false); } if (enddir === CONSTANTS.DirNone || // like above endportHasLimited && !endportCanHave) { enddir = this.endport.getStartEndDirTo(tgt, false, this.startport === this.endport ? startdir : CONSTANTS.DirNone); } this.endpoint = this.endport.createStartEndPointTo(tgt, enddir); this.endpoint.owner = this; return this.endport; }; AutoRouterPath.prototype.isConnected = function () { return (this.state & CONSTANTS.PathStateConnected) !== 0; }; AutoRouterPath.prototype.addTail = function (pt) { assert(!this.isConnected(), 'ARPath.addTail: !this.isConnected() FAILED'); this.points.push(pt); }; AutoRouterPath.prototype.deleteAll = function () { this.points = new ArPointListPath(); this.state = CONSTANTS.PathStateDefault; this.clearPorts(); }; AutoRouterPath.prototype.getStartBox = function () { var port = this.startport || this.startports[0]; return port.owner.getRootBox(); }; AutoRouterPath.prototype.getEndBox = function () { var port = this.endport || this.endports[0]; return port.owner.getRootBox(); }; AutoRouterPath.prototype.getOutOfBoxStartPoint = function (hintDir) { var startBoxRect = this.getStartBox(); assert(hintDir !== CONSTANTS.DirSkew, 'ARPath.getOutOfBoxStartPoint: hintDir !== CONSTANTS.DirSkew FAILED'); assert(this.points.length >= 2, 'ARPath.getOutOfBoxStartPoint: this.points.length >= 2 FAILED'); var pos = 0, p = new ArPoint(this.points[pos++]), d = Utils.getDir(this.points[pos].minus(p)); if (d === CONSTANTS.DirSkew) { d = hintDir; } assert(Utils.isRightAngle(d), 'ARPath.getOutOfBoxStartPoint: Utils.isRightAngle (d) FAILED'); if (Utils.isHorizontal(d)) { p.x = Utils.getRectOuterCoord(startBoxRect, d); } else { p.y = Utils.getRectOuterCoord(startBoxRect, d); } //assert(Utils.getDir (this.points[pos].minus(p)) === Utils.reverseDir ( d ) || // Utils.getDir (this.points[pos].minus(p)) === d, 'Utils.getDir (this.points[pos].minus(p)) === // Utils.reverseDir ( d ) || Utils.getDir (this.points[pos].minus(p)) === d FAILED'); return p; }; AutoRouterPath.prototype.getOutOfBoxEndPoint = function (hintDir) { var endBoxRect = this.getEndBox(); assert(hintDir !== CONSTANTS.DirSkew, 'ARPath.getOutOfBoxEndPoint: hintDir !== CONSTANTS.DirSkew FAILED'); assert(this.points.length >= 2, 'ARPath.getOutOfBoxEndPoint: this.points.length >= 2 FAILED'); var pos = this.points.length - 1, p = new ArPoint(this.points[pos--]), d = Utils.getDir(this.points[pos].minus(p)); if (d === CONSTANTS.DirSkew) { d = hintDir; } assert(Utils.isRightAngle(d), 'ARPath.getOutOfBoxEndPoint: Utils.isRightAngle (d) FAILED'); if (Utils.isHorizontal(d)) { p.x = Utils.getRectOuterCoord(endBoxRect, d); } else { p.y = Utils.getRectOuterCoord(endBoxRect, d); } //assert(Utils.getDir (this.points[pos].minus(p)) === Utils.reverseDir ( d ) || // Utils.getDir (this.points[pos].minus(p)) === d, 'ARPath.getOutOfBoxEndPoint: Utils.getDir // (this.points[pos].minus(p)) === d || Utils.getDir (this.points[pos].minus(p)) === d FAILED'); return p; }; AutoRouterPath.prototype.simplifyTrivially = function () { assert(!this.isConnected(), 'ARPath.simplifyTrivially: !isConnected() FAILED'); if (this.points.length <= 2) { return; } var pos = 0, pos1 = pos; assert(pos1 !== this.points.length, 'ARPath.simplifyTrivially: pos1 !== this.points.length FAILED'); var p1 = this.points[pos++], pos2 = pos; assert(pos2 !== this.points.length, 'ARPath.simplifyTrivially: pos2 !== this.points.length FAILED'); var p2 = this.points[pos++], dir12 = Utils.getDir(p2.minus(p1)), pos3 = pos; assert(pos3 !== this.points.length, 'ARPath.simplifyTrivially: pos3 !== this.points.length FAILED'); var p3 = this.points[pos++], dir23 = Utils.getDir(p3.minus(p2)); for (; ;) { if (dir12 === CONSTANTS.DirNone || dir23 === CONSTANTS.DirNone || (dir12 !== CONSTANTS.DirSkew && dir23 !== CONSTANTS.DirSkew && (dir12 === dir23 || dir12 === Utils.reverseDir(dir23)) )) { this.points.splice(pos2, 1); pos--; pos3--; dir12 = Utils.getDir(p3.minus(p1)); } else { pos1 = pos2; p1 = p2; dir12 = dir23; } if (pos === this.points.length) { return; } pos2 = pos3; p2 = p3; pos3 = pos; p3 = this.points[pos++]; dir23 = Utils.getDir(p3.minus(p2)); } if (CONSTANTS.DEBUG) { this.assertValidPoints(); } }; AutoRouterPath.prototype.getPointList = function () { return this.points; }; AutoRouterPath.prototype.isPathClip = function (r, isStartOrEndRect) { var tmp = this.points.getTailEdge(), a = tmp.start, b = tmp.end, pos = tmp.pos, i = 0, numEdges = this.points.length - 1; while (pos >= 0) { if (isStartOrEndRect && ( i === 0 || i === numEdges - 1 )) { if (Utils.isPointIn(a, r, 1) && Utils.isPointIn(b, r, 1)) { return true; } } else if (Utils.isLineClipRect(a, b, r)) { return true; } tmp = this.points.getPrevEdge(pos, a, b); a = tmp.start; b = tmp.end; pos = tmp.pos; i++; } return false; }; AutoRouterPath.prototype.isFixed = function () { return ((this.attributes & CONSTANTS.PathFixed) !== 0); }; AutoRouterPath.prototype.isMoveable = function () { return ((this.attributes & CONSTANTS.PathFixed) === 0); }; AutoRouterPath.prototype.setState = function (s) { assert(this.owner !== null, 'ARPath.setState: this.owner !== null FAILED'); this.state = s; if (CONSTANTS.DEBUG) { this.assertValid(); } }; AutoRouterPath.prototype.getEndDir = function () { var a = this.attributes & CONSTANTS.PathEndMask; return a & CONSTANTS.PathEndOnTop ? CONSTANTS.DirTop : a & CONSTANTS.PathEndOnRight ? CONSTANTS.DirRight : a & CONSTANTS.PathEndOnBottom ? CONSTANTS.DirBottom : a & CONSTANTS.PathEndOnLeft ? CONSTANTS.DirLeft : CONSTANTS.DirNone; }; AutoRouterPath.prototype.getStartDir = function () { var a = this.attributes & CONSTANTS.PathStartMask; return a & CONSTANTS.PathStartOnTop ? CONSTANTS.DirTop : a & CONSTANTS.PathStartOnRight ? CONSTANTS.DirRight : a & CONSTANTS.PathStartOnBottom ? CONSTANTS.DirBottom : a & CONSTANTS.PathStartOnLeft ? CONSTANTS.DirLeft : CONSTANTS.DirNone; }; AutoRouterPath.prototype.setEndDir = function (pathEnd) { this.attributes = (this.attributes & ~CONSTANTS.PathEndMask) + pathEnd; }; AutoRouterPath.prototype.setStartDir = function (pathStart) { this.attributes = (this.attributes & ~CONSTANTS.PathStartMask) + pathStart; }; /** * Set the custom points of the path and determine start/end points/ports. * * @param {Array<ArPoint>} points * @return {undefined} */ AutoRouterPath.prototype.setCustomPathPoints = function (points) { this.customPathData = points; // Find the start/endports this.calculateStartEndPorts(); this.points = new ArPointListPath().concat(points); // Add the start/end points to the list this.points.unshift(this.startpoint); this.points.push(this.endpoint); // Set as connected this.setState(CONSTANTS.PathStateConnected); }; AutoRouterPath.prototype.createCustomPath = function () { this.points.shift(); this.points.pop(); this.points.unshift(this.startpoint); this.points.push(this.endpoint); this.setState(CONSTANTS.PathStateConnected); }; AutoRouterPath.prototype.removePathCustomizations = function () { this.customPathData = []; }; AutoRouterPath.prototype.areTherePathCustomizations = function () { return this.customPathData.length !== 0; }; AutoRouterPath.prototype.isAutoRouted = function () { return this.isAutoRoutingOn; }; AutoRouterPath.prototype.setAutoRouting = function (arState) { this.isAutoRoutingOn = arState; }; AutoRouterPath.prototype.destroy = function () { if (this.isConnected()) { this.startport.removePoint(this.startpoint); this.endport.removePoint(this.endpoint); } }; AutoRouterPath.prototype.assertValid = function () { var i; assert(this.startports.length > 0, 'Path has no startports!'); assert(this.endports.length > 0, 'Path has no endports!'); for (i = this.startports.length; i--;) { this.startports[i].assertValid(); } for (i = this.endports.length; i--;) { this.endports[i].assertValid(); } if (this.isAutoRouted()) { if (this.isConnected()) { assert(this.points.length !== 0, 'ARPath.assertValid: this.points.length !== 0 FAILED'); var points = this.getPointList(); points.assertValid(); } } // If it has a startpoint, must also have a startport if (this.startpoint) { assert(this.startport, 'Path has a startpoint without a startport'); } if (this.endpoint) { assert(this.endport, 'Path has a endpoint without a endport'); } assert(this.owner, 'Path does not have owner!'); }; AutoRouterPath.prototype.assertValidPoints = function () { }; return AutoRouterPath; });
metamorph-inc/webgme
src/client/js/Widgets/DiagramDesigner/AutoRouter.Path.js
JavaScript
mit
18,572
var utils = require('../waz-storage/utils') , xml2js = require('xml2js') , _ = require('underscore') , CoreService = require('../waz-storage/core-service'); exports = module.exports = Service; function Service(options) { this.options = options; this.init(); } Service.prototype = new CoreService; Service.prototype.listContainers = function(args, callback){ var options = {comp: 'list'}; this.execute('get', null, options, null, null, function(err, response) { if (err != null && err.statusCode == 404) { callback({ message: 'container `' + name + '` not found' }, null); return; } new xml2js.Parser().on('end', function(result) { var containers = []; if (result.Containers.Container) containers = [result.Containers.Container].flatten().map(function(c){ return { name: c.Name, url: c.Url, lastModified: c.LastModified }; }); callback(null, containers); }).on('error', function(e){ // Don't know why but without this it throws an error // Non-whitespace before first tag.\nLine: 0\nColumn: 1\nChar }).parseString(response.body); }); }; Service.prototype.listBlobs = function(containerName, callback){ var options = {restype: 'container', comp: 'list'}; this.execute('get', containerName, options, {'x-ms-version': '2009-09-19'}, null, function(err, response) { new xml2js.Parser().on('end', function(result) { var blobs = []; if (result.Blobs.Blob) blobs = [result.Blobs.Blob].flatten().map(function(c){ return { name: c.Name, url: c.Url, contentType: c.Properties['Content-Type'] }; }); callback(null, blobs); }).on('error', function(e){ // Don't know why but without adding this callback it throws an error // Non-whitespace before first tag.\nLine: 0\nColumn: 1\nChar }).parseString(' '+response.body); }); }; Service.prototype.createContainer = function(name, callback){ this.execute('put', name, {restype: 'container'}, {'x-ms-version': '2009-09-19'}, null, function(err, response) { var error = null, data = null; if (err != null && err.statusCode == 409) error = { message: 'container `' + name + '` already exists' }; else data = { name: name }; callback(error, data); }); }; Service.prototype.deleteContainer = function(name, callback){ this.execute('delete', name, {restype: 'container'}, {'x-ms-version': '2009-09-19'}, null, function(err, response) { var error = null; if (err != null && err.statusCode == 404) error = { message: 'container `' + name + '` not found' }; callback(error); }); }; Service.prototype.getContainerProperties = function(name, callback){ this.execute('get', name, {restype: 'container'}, {'x-ms-version': '2009-09-19'}, null, function(err, response) { var error = null, data = null if (err != null && err.statusCode == 404) error = { message: 'container `' + name + '` not found' }; else data = response.headers; callback(error, data); }); }; Service.prototype.setContainerMetadata = function(name, metadata, callback){ this.execute('put', name, {restype: 'container', comp: 'metadata'}, {'x-ms-version': '2009-09-19'}.merge(metadata || {}), null, function(err, response) { var error = null; if (err != null && err.statusCode == 400) error = { message: 'container `' + name + '` not found' }; callback(error); }); }; Service.prototype.getContainerAcl = function(name, callback){ this.execute('get', name, {restype: 'container', comp: 'acl'}, {'x-ms-version': '2009-09-19'}, null, function(err, response) { var error = null, data = null; if (err != null) error = { message: err.statusCode }; else if (response.headers && response.headers['x-ms-blob-public-access']) data = response.headers['x-ms-blob-public-access']; callback(error, data); }); }; Service.prototype.setContainerAcl = function(name, level, callback){ var headers = {'x-ms-version': '2009-09-19'} if (level) headers.merge({'x-ms-blob-public-access': level}); var payload = '<?xml version="1.0" encoding="utf-8"?><SignedIdentifiers />' this.execute('put', name, {restype: 'container', comp: 'acl'}, headers, payload, function(err, response) { var error = null; if (err != null) error = { message: err.statusCode }; callback(error); }); }; Service.prototype.getBlobProperties = function(path, callback){ this.execute('head', path, null, {'x-ms-version': '2009-09-19'}, null, function(err, response) { var error = null, data = null; if (err != null && err.statusCode == 400) error = { message: 'blob `' + path + '` not found' }; else data = response.headers; callback(error, data); }); }; Service.prototype.getBlobMetadata = function(name, callback){ this.execute('head', name, {comp: 'metadata'}, {'x-ms-version': '2009-09-19'}, null, function(err, response) { var error = null, data = null; if (err != null && err.statusCode == 400) error = { message: 'blob `' + name + '` not found' }; else data = response.headers; callback(error, data); }); }; Service.prototype.setBlobProperties = function(path, properties, callback){ this.execute('put', path, {comp: 'properties'}, {'x-ms-version': '2009-09-19'}.merge(properties || {}), null, function(err, response) { var error = null; if (err != null && err.statusCode == 400) error = { message: 'blob `' + path + '` not found' }; callback(error); }); }; Service.prototype.setBlobMetadata = function(path, properties, callback){ this.execute('put', path, {comp: 'metadata'}, {'x-ms-version': '2009-09-19'}.merge(properties || {}), null, function(err, response) { var error = null; if (err != null && err.statusCode == 400) error = { message: 'blob `' + path + '` not found' }; callback(error); }); }; Service.prototype.putBlob = function(path, payload, contentType, metadata, callback){ contentType = contentType || "application/octet-stream"; headers = {'Content-Type': contentType, 'x-ms-blob-type': 'BlockBlob', 'x-ms-version': '2009-09-19', 'x-ms-blob-content-type': contentType}.merge(metadata); this.execute('put', path, null, headers, payload, function(err, response) { var error = null, data = null if (err != null && err.statusCode == 400) error = { message: 'blob `' + name + '` not found' }; else data = response.headers; callback(error, data); }); }; Service.prototype.getBlob = function(path, callback){ this.execute('get', path, null, {'x-ms-version': '2009-09-19'}, null, function(err, response) { var error = null, data = null if (err != null && err.statusCode == 404) error = { message: 'blob `' + path + '` not found' }; else data = response.body; callback(error, data); }); }; Service.prototype.deleteBlob = function(path, callback){ this.execute('delete', path, null, {'x-ms-version': '2009-09-19'}, null, function(err) { var error = null; if (err != null && err.statusCode == 404) error = { message: 'blob `' + path + '` not found' }; callback(error); }); } Service.prototype.copyBlob = function(source, destination, callback){ var headers = {'x-ms-version': '2009-09-19', 'x-ms-copy-source': this.canonicalizeMessage(source) }; this.execute('put', destination, null, headers, null, function(err, response) { var error = null, data = null if (err != null && err.statusCode == 404) error = { message: 'blob `' + source + '` not found' }; callback(error); }); } Service.prototype.snapshotBlob = function(path, callback){ var headers = {'x-ms-version': '2009-09-19'}; this.execute('put', path, {'comp': 'snapshot'}, headers, null, function(err, response) { var error = null, data = null if (err != null && err.statusCode == 404) error = { message: 'blob `' + path + '` not found' }; else data = response.headers; callback(error, data); }); } Service.prototype.putBlock = function(path, identifier, payload, callback){ var service = this; service.execute('put', path, { comp : 'block', blockid: identifier }, {'Content-Type': "application/octet-stream"}, payload, function(err, response) { if (service.parseError(response, callback)) return; callback(null, response.headers); }); } Service.prototype.putBlockList = function(path, blockList, contentType, metadata, callback){ var headers = {"Content-Type": contentType, 'x-ms-version': '2009-09-19'}.merge(metadata) var payload = '<?xml version="1.0" encoding="utf-8"?> \ <BlockList>' + _.map(blockList, function(id) { return "<Latest>" + id + "</Latest>"}).join('') + '</BlockList>'; var service = this; this.execute('put', path, { comp : 'blocklist' }, headers , payload, function(response) { if (service.parseError(response, callback)) return; callback(null, response.headers); }); };
jpgarcia/waz-storage-js
lib/waz-blobs/service.js
JavaScript
mit
8,785
import * as React from 'react'; import { experimentalStyled as styled } from '@material-ui/core/styles'; import Radio from '@material-ui/core/Radio'; import RadioGroup from '@material-ui/core/RadioGroup'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import FormControl from '@material-ui/core/FormControl'; import FormLabel from '@material-ui/core/FormLabel'; const Icon = styled('span')({ borderRadius: '50%', width: 16, height: 16, boxShadow: 'inset 0 0 0 1px rgba(16,22,26,.2), inset 0 -1px 0 rgba(16,22,26,.1)', backgroundColor: '#f5f8fa', backgroundImage: 'linear-gradient(180deg,hsla(0,0%,100%,.8),hsla(0,0%,100%,0))', '.Mui-focusVisible &': { outline: '2px auto rgba(19,124,189,.6)', outlineOffset: 2, }, 'input:hover ~ &': { backgroundColor: '#ebf1f5', }, 'input:disabled ~ &': { boxShadow: 'none', background: 'rgba(206,217,224,.5)', }, }); const CheckedIcon = styled(Icon)({ backgroundColor: '#137cbd', backgroundImage: 'linear-gradient(180deg,hsla(0,0%,100%,.1),hsla(0,0%,100%,0))', '&:before': { display: 'block', width: 16, height: 16, backgroundImage: 'radial-gradient(#fff,#fff 28%,transparent 32%)', content: '""', }, 'input:hover ~ &': { backgroundColor: '#106ba3', }, }); // Inspired by blueprintjs function StyledRadio(props) { return ( <Radio sx={{ '&:hover': { bgcolor: 'transparent', }, }} disableRipple color="default" checkedIcon={<CheckedIcon />} icon={<Icon />} {...props} /> ); } export default function CustomizedRadios() { return ( <FormControl component="fieldset"> <FormLabel component="legend">Gender</FormLabel> <RadioGroup defaultValue="female" aria-label="gender" name="customized-radios"> <FormControlLabel value="female" control={<StyledRadio />} label="Female" /> <FormControlLabel value="male" control={<StyledRadio />} label="Male" /> <FormControlLabel value="other" control={<StyledRadio />} label="Other" /> <FormControlLabel value="disabled" disabled control={<StyledRadio />} label="(Disabled option)" /> </RadioGroup> </FormControl> ); }
callemall/material-ui
docs/src/pages/components/radio-buttons/CustomizedRadios.js
JavaScript
mit
2,279
import path from 'path'; import { getManager, allManagers } from './managers'; import { separator } from './log'; /** * changed files to array * * @desc converts the output of the diff commands to an array * @param {string} files - string with all files * @return {array} */ export const changedFilesToArray = (files) => { let changedFiles = files; if (typeof changedFiles === 'string') { changedFiles = changedFiles.split('\n'); } return changedFiles; }; /** * check for updates * * @desc checks if a changed file should trigger an install * @param {array} files - all changed files */ export const checkForUpdates = (files) => { const changedFiles = changedFilesToArray(files); const managers = {}; // check if any file from a package manager got changed for (const file of changedFiles) { for (const manager of allManagers) { if (manager.isDependencyFile(file)) { if (!managers[manager.name]) { managers[manager.name] = []; } const base = path.dirname(file); if (managers[manager.name].indexOf(base) < 0) { managers[manager.name].push(base); } } } } // update all managers if (Object.keys(managers).length > 0) { separator(); for (const manager of Object.keys(managers)) { getManager(manager).update(managers[manager]); separator(); } } };
cyrilwanner/npm-autoinstaller
src/updatePackages.js
JavaScript
mit
1,403
import test from 'ava'; import 'babel-core/register'; import Rectangle from '../../../src/geom/rectangle/Rectangle.js' import Ceil from '../../../src/geom/rectangle/Ceil.js' test('Rectangle.Ceil', t => { let r = Rectangle(34.2, 39.8, 1, 1); Ceil(r); t.plan(2); t.is(r.x, 35); t.is(r.y, 40); });
photonstorm/lazer
tests/geom/rectangle/rectangle3-ceil.js
JavaScript
mit
325
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M17.73 12.02l3.98-3.98c.39-.39.39-1.02 0-1.41l-4.34-4.34a.9959.9959 0 00-1.41 0l-3.98 3.98L8 2.29C7.8 2.1 7.55 2 7.29 2c-.25 0-.51.1-.7.29L2.25 6.63c-.39.39-.39 1.02 0 1.41l3.98 3.98L2.25 16c-.39.39-.39 1.02 0 1.41l4.34 4.34c.39.39 1.02.39 1.41 0l3.98-3.98 3.98 3.98c.2.2.45.29.71.29.26 0 .51-.1.71-.29l4.34-4.34c.39-.39.39-1.02 0-1.41l-3.99-3.98zM12 9c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm-4.71 1.96L3.66 7.34l3.63-3.63 3.62 3.62-3.62 3.63zM10 13c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm2 2c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm2-4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2.66 9.34l-3.63-3.62 3.63-3.63 3.62 3.62-3.62 3.63z" /> , 'HealingOutlined');
kybarg/material-ui
packages/material-ui-icons/src/HealingOutlined.js
JavaScript
mit
809
describe('Right Hand of the Emperor', function() { integration(function() { describe('Right Hand of the Emperor\'s ability', function() { beforeEach(function() { this.setupTest({ phase: 'conflict', player1: { inPlay: ['brash-samurai', 'border-rider', 'doji-whisperer', 'daidoji-uji', 'doji-challenger', 'guest-of-honor', 'moto-youth', 'kakita-toshimoko'], hand: ['right-hand-of-the-emperor', 'sharpen-the-mind'] }, player2: { inPlay: ['naive-student','doji-kuwanan'], hand: ['voice-of-honor', 'way-of-the-crane'] } }); this.player1.fate = 30; this.brashSamurai = this.player1.findCardByName('brash-samurai'); this.brashSamurai.bowed = true; this.borderRider = this.player1.findCardByName('border-rider'); this.borderRider.fate = 1; this.borderRider.bowed = true; this.dojiWhisperer = this.player1.findCardByName('doji-whisperer'); this.daidojiUji = this.player1.findCardByName('daidoji-uji'); this.daidojiUji.bowed = true; this.dojiChallenger = this.player1.findCardByName('doji-challenger'); this.dojiChallenger.bowed = true; this.guestOfHonor = this.player1.findCardByName('guest-of-honor'); this.guestOfHonor.bowed = true; this.motoYouth = this.player1.findCardByName('moto-youth'); this.motoYouth.bowed = true; this.kakitaToshimoko = this.player1.findCardByName('kakita-toshimoko'); this.kakitaToshimoko.bowed = false; this.rightHandOfTheEmperor = this.player1.findCardByName('right-hand-of-the-emperor', 'hand'); this.sharpenTheMind = this.player1.findCardByName('sharpen-the-mind'); this.naiveStudent = this.player2.findCardByName('naive-student'); this.naiveStudent.bowed = true; this.dojiKuwanan = this.player2.findCardByName('doji-kuwanan'); this.dojiKuwanan.bowed = true; }); it('should be playable from hand if less honorable', function() { this.player1.player.honor = 5; this.player2.player.honor = 11; this.player1.playAttachment(this.sharpenTheMind, this.dojiChallenger); this.player2.pass(); this.player1.clickCard(this.rightHandOfTheEmperor); expect(this.player1).toHavePrompt('Choose characters'); }); it('should be playable from hand if equally honorable', function() { this.player1.player.honor = 11; this.player2.player.honor = 11; this.player1.playAttachment(this.sharpenTheMind, this.dojiChallenger); this.player2.pass(); this.player1.clickCard(this.rightHandOfTheEmperor); expect(this.player1).toHavePrompt('Choose characters'); }); it('should be playable from hand if more honorable', function() { this.player1.player.honor = 11; this.player2.player.honor = 5; this.player1.playAttachment(this.sharpenTheMind, this.dojiChallenger); this.player2.pass(); this.player1.clickCard(this.rightHandOfTheEmperor); expect(this.player1).toHavePrompt('Choose characters'); }); it('should prompt you to target bowed bushi characters you control', function() { this.player1.clickCard(this.rightHandOfTheEmperor); expect(this.player1).toHavePrompt('Choose characters'); expect(this.player1).toBeAbleToSelect(this.brashSamurai); expect(this.player1).toBeAbleToSelect(this.borderRider); expect(this.player1).not.toBeAbleToSelect(this.dojiWhisperer); expect(this.player1).toBeAbleToSelect(this.daidojiUji); expect(this.player1).toBeAbleToSelect(this.dojiChallenger); expect(this.player1).not.toBeAbleToSelect(this.guestOfHonor); expect(this.player1).not.toBeAbleToSelect(this.naiveStudent); expect(this.player1).toBeAbleToSelect(this.motoYouth); expect(this.player1).not.toBeAbleToSelect(this.dojiKuwanan); expect(this.player1).not.toBeAbleToSelect(this.kakitaToshimoko); }); it('should allow you to select zero characters', function() { this.player1.clickCard(this.rightHandOfTheEmperor); expect(this.player1).toHavePrompt('Choose characters'); expect(this.player1).toHavePromptButton('Done'); }); it('should allow you to select zero characters and go to the bottom of the deck', function() { this.player1.clickCard(this.rightHandOfTheEmperor); expect(this.player1).toHavePrompt('Choose characters'); expect(this.player1).toHavePromptButton('Done'); this.player1.clickPrompt('Done'); expect(this.getChatLogs(1)).toContain('player1 plays Right Hand of the Emperor to ready no one. Right Hand of the Emperor is placed on the bottom of player1\'s conflict deck'); expect(this.player1.player.conflictDeck.last()).toBe(this.rightHandOfTheEmperor); }); it('should not allow you to target characters greater than a total of 6 fate cost', function() { this.player1.clickCard(this.rightHandOfTheEmperor); this.player1.clickCard(this.daidojiUji); this.player1.clickCard(this.dojiChallenger); expect(this.player1.player.promptState.selectedCards).toContain(this.daidojiUji); expect(this.player1.player.promptState.selectedCards).not.toContain(this.dojiChallenger); }); it('should allow you to target characters with a total of 6 fate cost or fewer', function() { this.player1.clickCard(this.rightHandOfTheEmperor); this.player1.clickCard(this.dojiChallenger); expect(this.player1).toHavePromptButton('Done'); this.player1.clickCard(this.brashSamurai); expect(this.player1).toHavePromptButton('Done'); this.player1.clickCard(this.motoYouth); expect(this.player1).toHavePromptButton('Done'); }); it('should ready the chosen characters', function() { this.player1.clickCard(this.rightHandOfTheEmperor); this.player1.clickCard(this.dojiChallenger); this.player1.clickCard(this.brashSamurai); this.player1.clickCard(this.motoYouth); this.player1.clickPrompt('Done'); expect(this.dojiChallenger.bowed).toBe(false); expect(this.brashSamurai.bowed).toBe(false); expect(this.motoYouth.bowed).toBe(false); expect(this.getChatLogs(1)).toContain('player1 plays Right Hand of the Emperor to ready Doji Challenger, Brash Samurai and Moto Youth. Right Hand of the Emperor is placed on the bottom of player1\'s conflict deck'); }); it('should go to bottom of the deck rather than discard', function() { this.player1.clickCard(this.rightHandOfTheEmperor); this.player1.clickCard(this.dojiChallenger); this.player1.clickCard(this.brashSamurai); this.player1.clickCard(this.motoYouth); this.player1.clickPrompt('Done'); expect(this.dojiChallenger.bowed).toBe(false); expect(this.brashSamurai.bowed).toBe(false); expect(this.motoYouth.bowed).toBe(false); expect(this.getChatLogs(1)).toContain('player1 plays Right Hand of the Emperor to ready Doji Challenger, Brash Samurai and Moto Youth. Right Hand of the Emperor is placed on the bottom of player1\'s conflict deck'); expect(this.player1.player.conflictDeck.last()).toBe(this.rightHandOfTheEmperor); }); it('should go to the discard pile if cancelled', function() { this.player1.pass(); this.player2.clickCard('way-of-the-crane'); this.player2.clickCard(this.dojiKuwanan); expect(this.dojiKuwanan.isHonored).toBe(true); this.player1.clickCard(this.rightHandOfTheEmperor); expect(this.player1).toHavePrompt('Choose characters'); this.player1.clickCard(this.dojiChallenger); expect(this.player1).toHavePromptButton('Done'); this.player1.clickPrompt('Done'); expect(this.player2).toHavePrompt('Triggered Abilities'); expect(this.player2).toBeAbleToSelect('voice-of-honor'); this.player2.clickCard('voice-of-honor'); expect(this.player2).toHavePrompt('Action Window'); expect(this.dojiChallenger.bowed).toBe(true); expect(this.rightHandOfTheEmperor.location).toBe('conflict discard pile'); }); it('should be playable from discard if more honorable and go to bottom of deck', function() { this.player1.player.honor = 11; this.player2.player.honor = 5; this.player1.playAttachment(this.sharpenTheMind, this.dojiChallenger); this.noMoreActions(); this.dojiChallenger.bowed = false; this.initiateConflict({ type: 'military', attackers: [this.dojiChallenger], defenders: [] }); this.player2.pass(); this.player1.clickCard(this.sharpenTheMind); this.player1.clickCard(this.rightHandOfTheEmperor); this.player2.pass(); this.player1.clickCard(this.rightHandOfTheEmperor); expect(this.player1).toHavePrompt('Choose characters'); this.player1.clickCard(this.brashSamurai); expect(this.player1).toHavePromptButton('Done'); this.player1.clickPrompt('Done'); expect(this.player2).toHavePrompt('Conflict Action Window'); expect(this.brashSamurai.bowed).toBe(false); expect(this.player1.player.conflictDeck.last()).toBe(this.rightHandOfTheEmperor); }); it('should not be playable from discard if equally honorable', function() { this.player1.player.honor = 5; this.player2.player.honor = 5; this.player1.playAttachment(this.sharpenTheMind, this.dojiChallenger); this.noMoreActions(); this.dojiChallenger.bowed = false; this.initiateConflict({ type: 'military', attackers: [this.dojiChallenger], defenders: [] }); this.player2.pass(); this.player1.clickCard(this.sharpenTheMind); this.player1.clickCard(this.rightHandOfTheEmperor); this.player2.pass(); this.player1.clickCard(this.rightHandOfTheEmperor); expect(this.player1).toHavePrompt('Conflict Action Window'); }); it('should not be playable from discard if less honorable', function() { this.player1.player.honor = 5; this.player2.player.honor = 11; this.player1.playAttachment(this.sharpenTheMind, this.dojiChallenger); this.noMoreActions(); this.dojiChallenger.bowed = false; this.initiateConflict({ type: 'military', attackers: [this.dojiChallenger], defenders: [] }); this.player2.pass(); this.player1.clickCard(this.sharpenTheMind); this.player1.clickCard(this.rightHandOfTheEmperor); this.player2.pass(); this.player1.clickCard(this.rightHandOfTheEmperor); expect(this.player1).toHavePrompt('Conflict Action Window'); }); it('same copy should be playable from discard if cancelled from hand', function() { this.player1.player.honor = 11; this.player2.player.honor = 5; this.player1.playAttachment(this.sharpenTheMind, this.dojiChallenger); this.noMoreActions(); this.dojiChallenger.bowed = false; this.initiateConflict({ type: 'military', attackers: [this.dojiChallenger], defenders: [] }); this.player2.clickCard('way-of-the-crane'); this.player2.clickCard(this.dojiKuwanan); expect(this.dojiKuwanan.isHonored).toBe(true); this.player1.clickCard(this.rightHandOfTheEmperor); expect(this.player1).toHavePrompt('Choose characters'); this.player1.clickCard(this.brashSamurai); expect(this.player1).toHavePromptButton('Done'); this.player1.clickPrompt('Done'); expect(this.player2).toHavePrompt('Triggered Abilities'); expect(this.player2).toBeAbleToSelect('voice-of-honor'); this.player2.clickCard('voice-of-honor'); expect(this.player2).toHavePrompt('Conflict Action Window'); expect(this.brashSamurai.bowed).toBe(true); expect(this.rightHandOfTheEmperor.location).toBe('conflict discard pile'); this.player2.pass(); this.player1.clickCard(this.rightHandOfTheEmperor); expect(this.player1).toHavePrompt('Choose characters'); this.player1.clickCard(this.brashSamurai); expect(this.player1).toHavePromptButton('Done'); this.player1.clickPrompt('Done'); expect(this.brashSamurai.bowed).toBe(false); expect(this.player1.player.conflictDeck.last()).toBe(this.rightHandOfTheEmperor); }); it('same copy should be playable from discard if cancelled from discard', function() { this.player1.player.honor = 11; this.player2.player.honor = 5; this.player1.playAttachment(this.sharpenTheMind, this.dojiChallenger); this.noMoreActions(); this.dojiChallenger.bowed = false; this.initiateConflict({ type: 'military', attackers: [this.dojiChallenger], defenders: [] }); this.player2.pass(); this.player1.clickCard(this.sharpenTheMind); this.player1.clickCard(this.rightHandOfTheEmperor); this.player2.clickCard('way-of-the-crane'); this.player2.clickCard(this.dojiKuwanan); expect(this.dojiKuwanan.isHonored).toBe(true); this.player1.clickCard(this.rightHandOfTheEmperor); expect(this.player1).toHavePrompt('Choose characters'); this.player1.clickCard(this.brashSamurai); expect(this.player1).toHavePromptButton('Done'); this.player1.clickPrompt('Done'); expect(this.player2).toHavePrompt('Triggered Abilities'); expect(this.player2).toBeAbleToSelect('voice-of-honor'); this.player2.clickCard('voice-of-honor'); expect(this.player2).toHavePrompt('Conflict Action Window'); expect(this.brashSamurai.bowed).toBe(true); expect(this.rightHandOfTheEmperor.location).toBe('conflict discard pile'); this.player2.pass(); this.player1.clickCard(this.rightHandOfTheEmperor); expect(this.player1).toHavePrompt('Choose characters'); this.player1.clickCard(this.brashSamurai); expect(this.player1).toHavePromptButton('Done'); this.player1.clickPrompt('Done'); expect(this.brashSamurai.bowed).toBe(false); expect(this.player1.player.conflictDeck.last()).toBe(this.rightHandOfTheEmperor); }); }); describe('Right Hand of the Emperor played by non-owner interaction', function() { beforeEach(function() { this.setupTest({ phase: 'conflict', player1: { inPlay: ['border-rider', 'doji-challenger'], hand: ['voice-of-honor', 'way-of-the-crane', 'assassination', 'right-hand-of-the-emperor', 'censure', 'levy'] }, player2: { inPlay: ['brash-samurai','doji-kuwanan'], hand: ['stolen-secrets'] } }); this.player1.fate = 30; this.player2.fate = 30; this.borderRider = this.player1.findCardByName('border-rider'); this.dojiChallenger = this.player1.findCardByName('doji-challenger'); this.brashSamurai = this.player2.findCardByName('brash-samurai'); this.brashSamurai.fate = 2; this.dojiKuwanan = this.player2.findCardByName('doji-kuwanan'); this.dojiKuwanan.bowed = true; this.rightHandOfTheEmperor = this.player1.findCardByName('right-hand-of-the-emperor', 'hand'); this.assassination = this.player1.findCardByName('assassination', 'hand'); this.censure = this.player1.findCardByName('censure', 'hand'); this.levy = this.player1.findCardByName('levy', 'hand'); this.player1.player.moveCard(this.rightHandOfTheEmperor, 'conflict deck'); this.player1.player.moveCard(this.assassination, 'conflict deck'); this.player1.player.moveCard(this.censure, 'conflict deck'); this.player1.player.moveCard(this.levy, 'conflict deck'); this.noMoreActions(); this.initiateConflict({ type: 'political', attackers: [this.borderRider], defenders: [this.brashSamurai] }); this.player2.clickCard('stolen-secrets'); this.player2.clickCard(this.brashSamurai); this.player2.clickPrompt(this.rightHandOfTheEmperor.name); this.player2.clickPrompt(this.assassination.name); this.player2.clickPrompt(this.censure.name); }); it('should go to the bottom of owners deck if played by non-owner', function() { this.player1.pass(); this.player2.clickCard(this.rightHandOfTheEmperor); expect(this.player2).toHavePrompt('Choose characters'); this.player2.clickCard(this.dojiKuwanan); expect(this.player2).toHavePromptButton('Done'); this.player2.clickPrompt('Done'); expect(this.dojiKuwanan.bowed).toBe(false); expect(this.player1.player.conflictDeck.last()).toBe(this.rightHandOfTheEmperor); expect(this.getChatLogs(3)).toContain('player2 plays Right Hand of the Emperor to ready Doji Kuwanan. Right Hand of the Emperor is placed on the bottom of player1\'s conflict deck'); }); it('should go to the owners discard if played by non-owner and cancelled', function() { this.player1.clickCard('way-of-the-crane'); this.player1.clickCard(this.dojiChallenger); expect(this.dojiChallenger.isHonored).toBe(true); this.player2.clickCard(this.rightHandOfTheEmperor); expect(this.player2).toHavePrompt('Choose characters'); this.player2.clickCard(this.dojiKuwanan); expect(this.player2).toHavePromptButton('Done'); this.player2.clickPrompt('Done'); expect(this.player1).toHavePrompt('Triggered Abilities'); expect(this.player1).toBeAbleToSelect('voice-of-honor'); this.player1.clickCard('voice-of-honor'); expect(this.player1).toHavePrompt('Conflict Action Window'); expect(this.dojiKuwanan.bowed).toBe(true); expect(this.rightHandOfTheEmperor.location).toBe('conflict discard pile'); expect(this.player1.player.conflictDiscardPile.toArray()).toContain(this.rightHandOfTheEmperor); }); }); describe('Right Hand of the Emperor <-> Special Interactions (From Hand)', function() { beforeEach(function() { this.setupTest({ phase: 'draw', player1: { honor: 5, inPlay: ['guest-of-honor','master-of-gisei-toshi','utaku-tetsuko','akodo-toturi-2'] }, player2: { honor: 11, fate: 30, inPlay: ['brash-samurai', 'doji-challenger'], hand: ['right-hand-of-the-emperor'] } }); this.brashSamurai = this.player2.findCardByName('brash-samurai'); this.dojiChallenger = this.player2.findCardByName('doji-challenger'); this.rightHandOfTheEmperor = this.player2.findCardByName('right-hand-of-the-emperor'); this.brashSamurai.bowed = true; this.GoH = this.player1.findCardByName('guest-of-honor'); this.MoGT = this.player1.findCardByName('master-of-gisei-toshi'); this.tetsuko = this.player1.findCardByName('utaku-tetsuko'); this.toturi = this.player1.findCardByName('akodo-toturi-2'); this.player1.player.imperialFavor = 'political'; this.player1.clickPrompt('1'); this.player2.clickPrompt('1'); this.noMoreActions(); this.player1.clickCard(this.MoGT); this.player1.clickRing('fire'); this.noMoreActions(); }); it('GoH - should not be playable from hand', function() { this.initiateConflict({ type: 'military', attackers: [this.GoH], defenders: [this.dojiChallenger] }); this.player2.clickCard(this.rightHandOfTheEmperor); expect(this.player2).toHavePrompt('Conflict Action Window'); }); it('Tetsuko - should increase cost from hand', function() { this.initiateConflict({ type: 'military', attackers: [this.tetsuko], defenders: [this.dojiChallenger] }); this.player2.clickCard(this.rightHandOfTheEmperor); this.player2.clickCard(this.brashSamurai); this.player2.clickPrompt('Done'); expect(this.player1).toHavePrompt('Conflict Action Window'); expect(this.player2.fate).toBe(26); }); it('Toturi2 - should not be playable from hand', function() { this.initiateConflict({ type: 'military', attackers: [this.toturi], defenders: [this.dojiChallenger] }); this.player2.pass(); this.player1.clickCard(this.toturi); this.player2.clickCard(this.rightHandOfTheEmperor); expect(this.player2).toHavePrompt('Conflict Action Window'); }); it('MoGT - should not be playable from hand', function() { this.initiateConflict({ type: 'military', ring: 'fire', attackers: [this.MoGT], defenders: [this.dojiChallenger] }); this.player2.clickCard(this.rightHandOfTheEmperor); expect(this.player2).toHavePrompt('Conflict Action Window'); }); }); describe('Right Hand of the Emperor <-> Special Interactions (From Discard)', function() { beforeEach(function() { this.setupTest({ phase: 'draw', player1: { honor: 5, inPlay: ['guest-of-honor','master-of-gisei-toshi','utaku-tetsuko','akodo-toturi-2'] }, player2: { honor: 11, fate: 30, inPlay: ['brash-samurai', 'doji-challenger'], conflictDiscard: ['right-hand-of-the-emperor'] } }); this.brashSamurai = this.player2.findCardByName('brash-samurai'); this.dojiChallenger = this.player2.findCardByName('doji-challenger'); this.rightHandOfTheEmperor = this.player2.findCardByName('right-hand-of-the-emperor'); this.brashSamurai.bowed = true; this.GoH = this.player1.findCardByName('guest-of-honor'); this.MoGT = this.player1.findCardByName('master-of-gisei-toshi'); this.tetsuko = this.player1.findCardByName('utaku-tetsuko'); this.toturi = this.player1.findCardByName('akodo-toturi-2'); this.player1.player.imperialFavor = 'political'; this.player1.clickPrompt('1'); this.player2.clickPrompt('1'); this.noMoreActions(); this.player1.clickCard(this.MoGT); this.player1.clickRing('fire'); this.noMoreActions(); }); it('GoH - should not be playable from discard', function() { this.initiateConflict({ type: 'military', attackers: [this.GoH], defenders: [this.dojiChallenger] }); this.player2.clickCard(this.rightHandOfTheEmperor); expect(this.player2).toHavePrompt('Conflict Action Window'); }); it('Tetsuko - should not increase cost from discard', function() { this.initiateConflict({ type: 'military', attackers: [this.tetsuko], defenders: [this.dojiChallenger] }); this.player2.clickCard(this.rightHandOfTheEmperor); this.player2.clickCard(this.brashSamurai); this.player2.clickPrompt('Done'); expect(this.player1).toHavePrompt('Conflict Action Window'); expect(this.player2.fate).toBe(27); }); it('Toturi2 - should be playable from discard', function() { this.initiateConflict({ type: 'military', attackers: [this.toturi], defenders: [this.dojiChallenger] }); this.player2.pass(); this.player1.clickCard(this.toturi); this.player2.clickCard(this.rightHandOfTheEmperor); expect(this.player2).toHavePrompt('Choose characters'); }); it('MoGT - should not be playable from discard', function() { this.initiateConflict({ type: 'military', ring: 'fire', attackers: [this.MoGT], defenders: [this.dojiChallenger] }); this.player2.clickCard(this.rightHandOfTheEmperor); expect(this.player2).toHavePrompt('Conflict Action Window'); }); }); }); });
gryffon/ringteki
test/server/cards/10-TEL/RightHandOfTheEmperor.spec.js
JavaScript
mit
28,635
// external dependencies import debounceMethod from 'debounce'; import {deepEqual} from 'fast-equals'; import memoize from 'micro-memoize'; import PropTypes from 'prop-types'; import React, {Component} from 'react'; import {findDOMNode} from 'react-dom'; import raf from 'raf'; import ResizeObserver from 'resize-observer-polyfill'; // constants import { COMPONENT_WILL_MOUNT, COMPONENT_WILL_RECEIVE_PROPS, IS_PRODUCTION, KEY_NAMES, KEYS, SOURCES, } from './constants'; // utils import { getNaturalDimensionValue, getStateKeys, isElementVoidTag, } from './utils'; /** * @private * * @function getInitialState * * @description * get the initial state of the component instance * * @returns {Object} the initial state */ export const getInitialState = () => KEY_NAMES.reduce((state, key) => { state[key] = null; return state; }, {}); export const createComponentWillMount = (instance) => /** * @private * * @function componentWillMount * * @description * prior to mount, set the keys to watch for and the render method */ () => { instance.keys = getStateKeys(instance.props); instance.setRenderMethod(instance.props); }; export const createComponentDidMount = (instance) => /** * @private * * @function componentDidMount * * @description * on mount, get the element and set it's resize observer */ () => { instance._isMounted = true; instance.element = findDOMNode(instance); instance.setResizeObserver(); }; export const createComponentWillReceiveProps = (instance) => /** * @private * * @function componentWillReceiveProps * * @description * when the component receives new props, set the render method for future renders * * @param {Object} nextProps the next render's props */ (nextProps) => instance.setRenderMethod(nextProps); export const createSetValues = (instance, isDebounce) => { const {debounce} = instance.props; /** * @private * * @function delayedMethod * * @description * on a delay (either requestAnimationFrame or debounce), determine the calculated measurements and assign * them to state if changed */ const delayedMethod = (event) => { const clientRect = instance.element ? instance.element.getBoundingClientRect() : {}; const isResize = event && event.type === 'resize'; const newValues = KEYS.reduce((values, key) => { values[key.key] = ~instance.keys.indexOf(key) ? instance.element ? getNaturalDimensionValue(key.source === SOURCES.CLIENT_RECT ? clientRect : instance.element, key.key) : 0 : null; return values; }, {}); if (!instance._isMounted) { return; } if (isResize || !deepEqual(instance.state, newValues)) { instance.setState(() => newValues); } }; return isDebounce && typeof debounce === 'number' ? debounceMethod(delayedMethod, debounce) : (event) => raf(() => delayedMethod(event)); }; export const createComponentDidUpdate = (instance) => /** * @private * * @function componentDidUpdate * * @description * on update, assign the new properties if they have changed * * element * * debounce (assign new debounced render method) * * keys * * @param {number} [previousDebounce] the previous props' debounce value */ ({debounce: previousDebounce}) => { const {debounce} = instance.props; const element = findDOMNode(instance); const hasElementChanged = element !== instance.element; const hasDebounceChanged = debounce !== previousDebounce; const shouldSetResizeObserver = hasElementChanged || hasDebounceChanged; if (hasElementChanged) { instance.element = element; } if (hasDebounceChanged) { instance.setValuesViaDebounce = createSetValues(instance, true); } if (shouldSetResizeObserver) { instance.setResizeObserver(); } const newKeys = getStateKeys(instance.props); if (shouldSetResizeObserver || !deepEqual(instance.keys, newKeys)) { instance.keys = newKeys; instance.resizeMethod(); } }; export const createComponentWillUnmount = (instance) => /** * @private * * @function componentWillUnmount * * @description * prior to unmount, disconnect the resize observer and reset the instance properties */ () => { instance._isMounted = false; instance.disconnectObserver(); instance.element = null; instance.keys = []; instance.resizeMethod = null; }; export const createConnectObserver = (instance) => /** * @private * * @function connectObserver * * @description * if render on resize is requested, assign a resize observer to the element with the correct resize method */ () => { const {renderOnResize, renderOnWindowResize} = instance.props; if (renderOnWindowResize) { window.addEventListener('resize', instance.resizeMethod); } if (renderOnResize) { if (!IS_PRODUCTION && isElementVoidTag(instance.element)) { /* eslint-disable no-console */ console.warn( 'WARNING: You are attempting to listen to resizes on a void element, which is not supported. You should wrap this element in an element that supports children, such as a <div>, to ensure correct behavior.' ); /* eslint-enable */ } instance.resizeObserver = new ResizeObserver(instance.resizeMethod); instance.resizeObserver.observe(instance.element); } }; export const createDisconnectObserver = (instance) => /** * @private * * @function disconnectObserver * * @description * if a resize observer exists, disconnect it from the element */ () => { if (instance.resizeObserver) { instance.resizeObserver.disconnect(instance.element); instance.resizeObserver = null; } window.removeEventListener('resize', instance.resizeMethod); }; export const createGetPassedValues = (instance) => /** * @private * * @function getPassedValues * * @description * get the passed values as an object, namespaced if requested * * @param {Object} state the current state values * @param {string} [namespace] the possible namespace to assign the values to * @returns {Object} the values to pass */ memoize((state, namespace) => { const populatedState = instance.keys.reduce((values, {key}) => { values[key] = state[key] || 0; return values; }, {}); return namespace ? {[namespace]: populatedState} : populatedState; }); export const createSetRef = (instance, ref) => /** * @private * * @function setRef * * @description * set the DOM node to the ref passed * * @param {HTMLElement|ReactComponent} element the element to find the DOM node of */ (element) => { instance[ref] = findDOMNode(element); }; export const createSetRenderMethod = (instance) => /** * @private * * @function setRenderMethod * * @description * set the render method based on the possible props passed * * @param {function} [children] the child render function * @param {function} [component] the component prop function * @param {function} [render] the render prop function */ ({children, component, render}) => { const RenderComponent = children || component || render || null; if (!IS_PRODUCTION && typeof RenderComponent !== 'function') { /* eslint-disable no-console */ console.error( 'ERROR: You must provide a render function, or either a "render" or "component" prop that passes a functional component.' ); /* eslint-enable */ } if (RenderComponent !== instance.RenderComponent) { instance.RenderComponent = RenderComponent; } }; export const createSetResizeObserver = (instance) => /** * @private * * @function setResizeObserver * * @description * set the resize observer on the instance, based on the existence of a currrent resizeObserver and the new element */ () => { const {debounce} = instance.props; const resizeMethod = typeof debounce === 'number' ? instance.setValuesViaDebounce : instance.setValuesViaRaf; if (instance.resizeObserver) { instance.disconnectObserver(); } if (resizeMethod !== instance.resizeMethod) { instance.resizeMethod = resizeMethod; resizeMethod(); } if (instance.element) { instance.connectObserver(); } }; // eslint-disable-next-line react/no-deprecated class Measured extends Component { static displayName = 'Measured'; static propTypes = { children: PropTypes.func, component: PropTypes.func, debounce: PropTypes.number, namespace: PropTypes.string, render: PropTypes.func, renderOnResize: PropTypes.bool.isRequired, renderOnWindowResize: PropTypes.bool.isRequired, ...KEY_NAMES.reduce((keyPropTypes, key) => { keyPropTypes[key] = PropTypes.bool; return keyPropTypes; }, {}), }; static defaultProps = { renderOnResize: true, renderOnWindowResize: false, }; // state state = getInitialState(); // lifecycle methods componentDidMount = createComponentDidMount(this); componentDidUpdate = createComponentDidUpdate(this); componentWillUnmount = createComponentWillUnmount(this); [COMPONENT_WILL_MOUNT] = createComponentWillMount(this); [COMPONENT_WILL_RECEIVE_PROPS] = createComponentWillReceiveProps(this); // instance values _isMounted = false; element = null; keys = []; RenderComponent = null; resizeMethod = null; resizeObserver = null; // instance methods connectObserver = createConnectObserver(this); disconnectObserver = createDisconnectObserver(this); getPassedValues = createGetPassedValues(this); setElementRef = createSetRef(this, 'element'); setRenderMethod = createSetRenderMethod(this); setResizeObserver = createSetResizeObserver(this); setValuesViaDebounce = createSetValues(this, true); setValuesViaRaf = createSetValues(this, false); render() { if (!this.RenderComponent) { return null; } const { children: childrenIgnored, component: componentIgnored, debounce: debounceIgnored, keys: keysIgnored, namespace, render: renderIgnored, renderOnResize: renderOnResizeIgnored, renderOnWindowResize: renderOnWindowResizeIgnored, ...passThroughProps } = this.props; const RenderComponent = this.RenderComponent; return ( /* eslint-disable prettier */ <RenderComponent {...passThroughProps} {...this.getPassedValues(this.state, namespace)} /> /* eslint-enable */ ); } } export default Measured;
planttheidea/remeasure
src/Measured.js
JavaScript
mit
10,809
var config = require('./') module.exports = { autoprefixer: { browsers: ['last 2 version'] }, src: config.sourceAssets + "/css/**/*.{sass,scss}", dest: config.publicAssets + '/css', settings: { indentedSyntax: false, imagePath: 'assets/images' // Used by the image-url helper } }
ebessa/app-starter
gulpfile.js/config/sass.js
JavaScript
mit
299
/** * @fileOverview * An undefined state - the special case where a state engine is not * initialized, or where a flow of transitions comes to an end. */ var util = require("util"); var State = require("../state"); //----------------------------------------------------------- // Class Definition //----------------------------------------------------------- /** * @class * A state that is a string. * * @param {String} representation * A string. */ function UndefinedState() { UndefinedState.super_.call(this, undefined); this.isUndefined = true; } util.inherits(UndefinedState, State); var p = UndefinedState.prototype; //----------------------------------------------------------- // Methods //----------------------------------------------------------- p.key = function() { return ""; }; //----------------------------------------------------------- // Exports - Class constructor //----------------------------------------------------------- module.exports = UndefinedState;
exratione/state-engines
lib/states/undefinedState.js
JavaScript
mit
1,005
var config = require('./webpack.config.js'), path = require('path'), webpack = require('webpack'), BundleTracker = require('webpack-bundle-tracker'); config.output.path = path.resolve('./coc_war_planner/static/js/dist/'); config.output.publicPath = '/static/js/dist/'; config.plugins = [ new BundleTracker({filename: './webpack-stats-prod.json'}), // removes a lot of debugging code in React new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), // keeps hashes consistent between compilations new webpack.optimize.OccurenceOrderPlugin(), // minifies your code new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) ]; module.exports = config;
arthurio/coc_war_planner
webpack.prod.config.js
JavaScript
mit
809
var server = require('nodebootstrap-server'); server.setup(function(runningApp) { // runningApp.use(require('express-session')({secret: CONF.app.cookie_secret, resave: false, saveUninitialized: false})); // Choose your favorite view engine(s) runningApp.set('view engine', 'handlebars'); runningApp.engine('handlebars', require('hbs').__express); //// you could use two view engines in parallel (if you are brave): // runningApp.set('view engine', 'j2'); // runningApp.engine('j2', require('swig').renderFile); //---- Mounting well-encapsulated application modules //---- See: http://vimeo.com/56166857 runningApp.use('/hello', require('hello')); // attach to sub-route runningApp.use('/tasks', require('tasks')); runningApp.use(require('routes')); // attach to root route // If you need websockets: // var socketio = require('socket.io')(runningApp.http); // require('fauxchatapp')(socketio); });
qial/taskit
server.js
JavaScript
mit
948
'use strict'; // This tests the errors thrown from TLSSocket.prototype.setServername const common = require('../common'); const fixtures = require('../common/fixtures'); if (!common.hasCrypto) common.skip('missing crypto'); const { connect, TLSSocket } = require('tls'); const makeDuplexPair = require('../common/duplexpair'); const { clientSide, serverSide } = makeDuplexPair(); const key = fixtures.readKey('agent1-key.pem'); const cert = fixtures.readKey('agent1-cert.pem'); const ca = fixtures.readKey('ca1-cert.pem'); const client = connect({ socket: clientSide, ca, host: 'agent1' // Hostname from certificate }); [undefined, null, 1, true, {}].forEach((value) => { common.expectsError(() => { client.setServername(value); }, { code: 'ERR_INVALID_ARG_TYPE', message: 'The "name" argument must be of type string. ' + `Received type ${typeof value}` }); }); const server = new TLSSocket(serverSide, { isServer: true, key, cert, ca }); common.expectsError(() => { server.setServername('localhost'); }, { code: 'ERR_TLS_SNI_FROM_SERVER', message: 'Cannot issue SNI from a TLS server-side socket' });
MTASZTAKI/ApertusVR
plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/test/parallel/test-tls-error-servername.js
JavaScript
mit
1,165
'use strict'; // Setting up route angular.module('articles').config(['$stateProvider', function ($stateProvider) { // Articles state routing $stateProvider .state('articles', { abstract: true, url: '/articles', template: '<ui-view/>', data: { roles: ['admin'] } }) .state('articles.list', { url: '', templateUrl: 'modules/articles/views/list-articles.client.view.html' }) .state('articles.create', { url: '/create', templateUrl: 'modules/articles/views/create-article.client.view.html' }) .state('articles.view', { url: '/:articleId', templateUrl: 'modules/articles/views/view-article.client.view.html' }) .state('articles.edit', { url: '/:articleId/edit', templateUrl: 'modules/articles/views/edit-article.client.view.html' }); } ]);
ldlharper/bath-squash-league
modules/articles/client/config/articles.client.routes.js
JavaScript
mit
922
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ window.qs = require('qs'); },{"qs":5}],2:[function(require,module,exports){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT */ var base64 = require('base64-js') var ieee754 = require('ieee754') exports.Buffer = Buffer exports.SlowBuffer = Buffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 /** * If `TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Note: * * - Implementation must support adding new properties to `Uint8Array` instances. * Firefox 4-29 lacked support, fixed in Firefox 30+. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * * We detect these buggy browsers and set `TYPED_ARRAY_SUPPORT` to `false` so they will * get the Object implementation, which is slower but will work correctly. */ var TYPED_ARRAY_SUPPORT = (function () { try { var buf = new ArrayBuffer(0) var arr = new Uint8Array(buf) arr.foo = function () { return 42 } return 42 === arr.foo() && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } })() /** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */ function Buffer (subject, encoding, noZero) { if (!(this instanceof Buffer)) return new Buffer(subject, encoding, noZero) var type = typeof subject // Find the length var length if (type === 'number') length = subject > 0 ? subject >>> 0 : 0 else if (type === 'string') { if (encoding === 'base64') subject = base64clean(subject) length = Buffer.byteLength(subject, encoding) } else if (type === 'object' && subject !== null) { // assume object is array-like if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data length = +subject.length > 0 ? Math.floor(+subject.length) : 0 } else throw new Error('First argument needs to be a number, array or string.') var buf if (TYPED_ARRAY_SUPPORT) { // Preferred: Return an augmented `Uint8Array` instance for best performance buf = Buffer._augment(new Uint8Array(length)) } else { // Fallback: Return THIS instance of Buffer (created by `new`) buf = this buf.length = length buf._isBuffer = true } var i if (TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') { // Speed optimization -- use set if we're copying from a typed array buf._set(subject) } else if (isArrayish(subject)) { // Treat array-ish objects as a byte array if (Buffer.isBuffer(subject)) { for (i = 0; i < length; i++) buf[i] = subject.readUInt8(i) } else { for (i = 0; i < length; i++) buf[i] = ((subject[i] % 256) + 256) % 256 } } else if (type === 'string') { buf.write(subject, 0, encoding) } else if (type === 'number' && !TYPED_ARRAY_SUPPORT && !noZero) { for (i = 0; i < length; i++) { buf[i] = 0 } } return buf } // STATIC METHODS // ============== Buffer.isEncoding = function (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.isBuffer = function (b) { return !!(b != null && b._isBuffer) } Buffer.byteLength = function (str, encoding) { var ret str = str.toString() switch (encoding || 'utf8') { case 'hex': ret = str.length / 2 break case 'utf8': case 'utf-8': ret = utf8ToBytes(str).length break case 'ascii': case 'binary': case 'raw': ret = str.length break case 'base64': ret = base64ToBytes(str).length break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = str.length * 2 break default: throw new Error('Unknown encoding') } return ret } Buffer.concat = function (list, totalLength) { assert(isArray(list), 'Usage: Buffer.concat(list[, length])') if (list.length === 0) { return new Buffer(0) } else if (list.length === 1) { return list[0] } var i if (totalLength === undefined) { totalLength = 0 for (i = 0; i < list.length; i++) { totalLength += list[i].length } } var buf = new Buffer(totalLength) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } Buffer.compare = function (a, b) { assert(Buffer.isBuffer(a) && Buffer.isBuffer(b), 'Arguments must be Buffers') var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; i++) {} if (i !== len) { x = a[i] y = b[i] } if (x < y) { return -1 } if (y < x) { return 1 } return 0 } // BUFFER INSTANCE METHODS // ======================= function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length assert(strLen % 2 === 0, 'Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var byte = parseInt(string.substr(i * 2, 2), 16) assert(!isNaN(byte), 'Invalid hex string') buf[offset + i] = byte } return i } function utf8Write (buf, string, offset, length) { var charsWritten = blitBuffer(utf8ToBytes(string), buf, offset, length) return charsWritten } function asciiWrite (buf, string, offset, length) { var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length) return charsWritten } function binaryWrite (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length) return charsWritten } function utf16leWrite (buf, string, offset, length) { var charsWritten = blitBuffer(utf16leToBytes(string), buf, offset, length) return charsWritten } Buffer.prototype.write = function (string, offset, length, encoding) { // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length length = undefined } } else { // legacy var swap = encoding encoding = offset offset = length length = swap } offset = Number(offset) || 0 var remaining = this.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } encoding = String(encoding || 'utf8').toLowerCase() var ret switch (encoding) { case 'hex': ret = hexWrite(this, string, offset, length) break case 'utf8': case 'utf-8': ret = utf8Write(this, string, offset, length) break case 'ascii': ret = asciiWrite(this, string, offset, length) break case 'binary': ret = binaryWrite(this, string, offset, length) break case 'base64': ret = base64Write(this, string, offset, length) break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = utf16leWrite(this, string, offset, length) break default: throw new Error('Unknown encoding') } return ret } Buffer.prototype.toString = function (encoding, start, end) { var self = this encoding = String(encoding || 'utf8').toLowerCase() start = Number(start) || 0 end = (end === undefined) ? self.length : Number(end) // Fastpath empty strings if (end === start) return '' var ret switch (encoding) { case 'hex': ret = hexSlice(self, start, end) break case 'utf8': case 'utf-8': ret = utf8Slice(self, start, end) break case 'ascii': ret = asciiSlice(self, start, end) break case 'binary': ret = binarySlice(self, start, end) break case 'base64': ret = base64Slice(self, start, end) break case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': ret = utf16leSlice(self, start, end) break default: throw new Error('Unknown encoding') } return ret } Buffer.prototype.toJSON = function () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } Buffer.prototype.equals = function (b) { assert(Buffer.isBuffer(b), 'Argument must be a Buffer') return Buffer.compare(this, b) === 0 } Buffer.prototype.compare = function (b) { assert(Buffer.isBuffer(b), 'Argument must be a Buffer') return Buffer.compare(this, b) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function (target, target_start, start, end) { var source = this if (!start) start = 0 if (!end && end !== 0) end = this.length if (!target_start) target_start = 0 // Copy 0 bytes; we're done if (end === start) return if (target.length === 0 || source.length === 0) return // Fatal error conditions assert(end >= start, 'sourceEnd < sourceStart') assert(target_start >= 0 && target_start < target.length, 'targetStart out of bounds') assert(start >= 0 && start < source.length, 'sourceStart out of bounds') assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - target_start < end - start) end = target.length - target_start + start var len = end - start if (len < 100 || !TYPED_ARRAY_SUPPORT) { for (var i = 0; i < len; i++) { target[i + target_start] = this[i + start] } } else { target._set(this.subarray(start, start + len), target_start) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { var res = '' var tmp = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { if (buf[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) tmp = '' } else { tmp += '%' + buf[i].toString(16) } } return res + decodeUtf8Char(tmp) } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i]) } return ret } function binarySlice (buf, start, end) { return asciiSlice(buf, start, end) } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len; if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start if (TYPED_ARRAY_SUPPORT) { return Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start var newBuf = new Buffer(sliceLen, undefined, true) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } return newBuf } } // `get` will be removed in Node 0.13+ Buffer.prototype.get = function (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `set` will be removed in Node 0.13+ Buffer.prototype.set = function (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } Buffer.prototype.readUInt8 = function (offset, noAssert) { if (!noAssert) { assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to read beyond buffer length') } if (offset >= this.length) return return this[offset] } function readUInt16 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val if (littleEndian) { val = buf[offset] if (offset + 1 < len) val |= buf[offset + 1] << 8 } else { val = buf[offset] << 8 if (offset + 1 < len) val |= buf[offset + 1] } return val } Buffer.prototype.readUInt16LE = function (offset, noAssert) { return readUInt16(this, offset, true, noAssert) } Buffer.prototype.readUInt16BE = function (offset, noAssert) { return readUInt16(this, offset, false, noAssert) } function readUInt32 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val if (littleEndian) { if (offset + 2 < len) val = buf[offset + 2] << 16 if (offset + 1 < len) val |= buf[offset + 1] << 8 val |= buf[offset] if (offset + 3 < len) val = val + (buf[offset + 3] << 24 >>> 0) } else { if (offset + 1 < len) val = buf[offset + 1] << 16 if (offset + 2 < len) val |= buf[offset + 2] << 8 if (offset + 3 < len) val |= buf[offset + 3] val = val + (buf[offset] << 24 >>> 0) } return val } Buffer.prototype.readUInt32LE = function (offset, noAssert) { return readUInt32(this, offset, true, noAssert) } Buffer.prototype.readUInt32BE = function (offset, noAssert) { return readUInt32(this, offset, false, noAssert) } Buffer.prototype.readInt8 = function (offset, noAssert) { if (!noAssert) { assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to read beyond buffer length') } if (offset >= this.length) return var neg = this[offset] & 0x80 if (neg) return (0xff - this[offset] + 1) * -1 else return this[offset] } function readInt16 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val = readUInt16(buf, offset, littleEndian, true) var neg = val & 0x8000 if (neg) return (0xffff - val + 1) * -1 else return val } Buffer.prototype.readInt16LE = function (offset, noAssert) { return readInt16(this, offset, true, noAssert) } Buffer.prototype.readInt16BE = function (offset, noAssert) { return readInt16(this, offset, false, noAssert) } function readInt32 (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } var len = buf.length if (offset >= len) return var val = readUInt32(buf, offset, littleEndian, true) var neg = val & 0x80000000 if (neg) return (0xffffffff - val + 1) * -1 else return val } Buffer.prototype.readInt32LE = function (offset, noAssert) { return readInt32(this, offset, true, noAssert) } Buffer.prototype.readInt32BE = function (offset, noAssert) { return readInt32(this, offset, false, noAssert) } function readFloat (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } return ieee754.read(buf, offset, littleEndian, 23, 4) } Buffer.prototype.readFloatLE = function (offset, noAssert) { return readFloat(this, offset, true, noAssert) } Buffer.prototype.readFloatBE = function (offset, noAssert) { return readFloat(this, offset, false, noAssert) } function readDouble (buf, offset, littleEndian, noAssert) { if (!noAssert) { assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset + 7 < buf.length, 'Trying to read beyond buffer length') } return ieee754.read(buf, offset, littleEndian, 52, 8) } Buffer.prototype.readDoubleLE = function (offset, noAssert) { return readDouble(this, offset, true, noAssert) } Buffer.prototype.readDoubleBE = function (offset, noAssert) { return readDouble(this, offset, false, noAssert) } Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'trying to write beyond buffer length') verifuint(value, 0xff) } if (offset >= this.length) return this[offset] = value return offset + 1 } function writeUInt16 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'trying to write beyond buffer length') verifuint(value, 0xffff) } var len = buf.length if (offset >= len) return for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } return offset + 2 } Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { return writeUInt16(this, value, offset, true, noAssert) } Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { return writeUInt16(this, value, offset, false, noAssert) } function writeUInt32 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'trying to write beyond buffer length') verifuint(value, 0xffffffff) } var len = buf.length if (offset >= len) return for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } return offset + 4 } Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { return writeUInt32(this, value, offset, true, noAssert) } Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { return writeUInt32(this, value, offset, false, noAssert) } Buffer.prototype.writeInt8 = function (value, offset, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset < this.length, 'Trying to write beyond buffer length') verifsint(value, 0x7f, -0x80) } if (offset >= this.length) return if (value >= 0) this.writeUInt8(value, offset, noAssert) else this.writeUInt8(0xff + value + 1, offset, noAssert) return offset + 1 } function writeInt16 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 1 < buf.length, 'Trying to write beyond buffer length') verifsint(value, 0x7fff, -0x8000) } var len = buf.length if (offset >= len) return if (value >= 0) writeUInt16(buf, value, offset, littleEndian, noAssert) else writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert) return offset + 2 } Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { return writeInt16(this, value, offset, true, noAssert) } Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { return writeInt16(this, value, offset, false, noAssert) } function writeInt32 (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') verifsint(value, 0x7fffffff, -0x80000000) } var len = buf.length if (offset >= len) return if (value >= 0) writeUInt32(buf, value, offset, littleEndian, noAssert) else writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert) return offset + 4 } Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { return writeInt32(this, value, offset, true, noAssert) } Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { return writeInt32(this, value, offset, false, noAssert) } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38) } var len = buf.length if (offset >= len) return ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { assert(value !== undefined && value !== null, 'missing value') assert(typeof littleEndian === 'boolean', 'missing or invalid endian') assert(offset !== undefined && offset !== null, 'missing offset') assert(offset + 7 < buf.length, 'Trying to write beyond buffer length') verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308) } var len = buf.length if (offset >= len) return ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function (value, start, end) { if (!value) value = 0 if (!start) start = 0 if (!end) end = this.length assert(end >= start, 'end < start') // Fill 0 bytes; we're done if (end === start) return if (this.length === 0) return assert(start >= 0 && start < this.length, 'start out of bounds') assert(end >= 0 && end <= this.length, 'end out of bounds') var i if (typeof value === 'number') { for (i = start; i < end; i++) { this[i] = value } } else { var bytes = utf8ToBytes(value.toString()) var len = bytes.length for (i = start; i < end; i++) { this[i] = bytes[i % len] } } return this } Buffer.prototype.inspect = function () { var out = [] var len = this.length for (var i = 0; i < len; i++) { out[i] = toHex(this[i]) if (i === exports.INSPECT_MAX_BYTES) { out[i + 1] = '...' break } } return '<Buffer ' + out.join(' ') + '>' } /** * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. * Added in Node 0.12. Only available in browsers that support ArrayBuffer. */ Buffer.prototype.toArrayBuffer = function () { if (typeof Uint8Array !== 'undefined') { if (TYPED_ARRAY_SUPPORT) { return (new Buffer(this)).buffer } else { var buf = new Uint8Array(this.length) for (var i = 0, len = buf.length; i < len; i += 1) { buf[i] = this[i] } return buf.buffer } } else { throw new Error('Buffer.toArrayBuffer not supported in this browser') } } // HELPER FUNCTIONS // ================ var BP = Buffer.prototype /** * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods */ Buffer._augment = function (arr) { arr._isBuffer = true // save reference to original Uint8Array get/set methods before overwriting arr._get = arr.get arr._set = arr.set // deprecated, will be removed in node 0.13+ arr.get = BP.get arr.set = BP.set arr.write = BP.write arr.toString = BP.toString arr.toLocaleString = BP.toString arr.toJSON = BP.toJSON arr.equals = BP.equals arr.compare = BP.compare arr.copy = BP.copy arr.slice = BP.slice arr.readUInt8 = BP.readUInt8 arr.readUInt16LE = BP.readUInt16LE arr.readUInt16BE = BP.readUInt16BE arr.readUInt32LE = BP.readUInt32LE arr.readUInt32BE = BP.readUInt32BE arr.readInt8 = BP.readInt8 arr.readInt16LE = BP.readInt16LE arr.readInt16BE = BP.readInt16BE arr.readInt32LE = BP.readInt32LE arr.readInt32BE = BP.readInt32BE arr.readFloatLE = BP.readFloatLE arr.readFloatBE = BP.readFloatBE arr.readDoubleLE = BP.readDoubleLE arr.readDoubleBE = BP.readDoubleBE arr.writeUInt8 = BP.writeUInt8 arr.writeUInt16LE = BP.writeUInt16LE arr.writeUInt16BE = BP.writeUInt16BE arr.writeUInt32LE = BP.writeUInt32LE arr.writeUInt32BE = BP.writeUInt32BE arr.writeInt8 = BP.writeInt8 arr.writeInt16LE = BP.writeInt16LE arr.writeInt16BE = BP.writeInt16BE arr.writeInt32LE = BP.writeInt32LE arr.writeInt32BE = BP.writeInt32BE arr.writeFloatLE = BP.writeFloatLE arr.writeFloatBE = BP.writeFloatBE arr.writeDoubleLE = BP.writeDoubleLE arr.writeDoubleBE = BP.writeDoubleBE arr.fill = BP.fill arr.inspect = BP.inspect arr.toArrayBuffer = BP.toArrayBuffer return arr } var INVALID_BASE64_RE = /[^+\/0-9A-z]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function isArray (subject) { return (Array.isArray || function (subject) { return Object.prototype.toString.call(subject) === '[object Array]' })(subject) } function isArrayish (subject) { return isArray(subject) || Buffer.isBuffer(subject) || subject && typeof subject === 'object' && typeof subject.length === 'number' } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { var b = str.charCodeAt(i) if (b <= 0x7F) { byteArray.push(b) } else { var start = i if (b >= 0xD800 && b <= 0xDFFF) i++ var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') for (var j = 0; j < h.length; j++) { byteArray.push(parseInt(h[j], 16)) } } } return byteArray } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(str) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; i++) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function decodeUtf8Char (str) { try { return decodeURIComponent(str) } catch (err) { return String.fromCharCode(0xFFFD) // UTF 8 invalid char } } /* * We have to make sure that the value is a valid integer. This means that it * is non-negative. It has no fractional component and that it does not * exceed the maximum allowed value. */ function verifuint (value, max) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value >= 0, 'specified a negative value for writing an unsigned value') assert(value <= max, 'value is larger than maximum value for type') assert(Math.floor(value) === value, 'value has a fractional component') } function verifsint (value, max, min) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value <= max, 'value larger than maximum allowed value') assert(value >= min, 'value smaller than minimum allowed value') assert(Math.floor(value) === value, 'value has a fractional component') } function verifIEEE754 (value, max, min) { assert(typeof value === 'number', 'cannot write a non-number as a number') assert(value <= max, 'value larger than maximum allowed value') assert(value >= min, 'value smaller than minimum allowed value') } function assert (test, message) { if (!test) throw new Error(message || 'Failed assertion') } },{"base64-js":3,"ieee754":4}],3:[function(require,module,exports){ var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; ;(function (exports) { 'use strict'; var Arr = (typeof Uint8Array !== 'undefined') ? Uint8Array : Array var PLUS = '+'.charCodeAt(0) var SLASH = '/'.charCodeAt(0) var NUMBER = '0'.charCodeAt(0) var LOWER = 'a'.charCodeAt(0) var UPPER = 'A'.charCodeAt(0) function decode (elt) { var code = elt.charCodeAt(0) if (code === PLUS) return 62 // '+' if (code === SLASH) return 63 // '/' if (code < NUMBER) return -1 //no match if (code < NUMBER + 10) return code - NUMBER + 26 + 26 if (code < UPPER + 26) return code - UPPER if (code < LOWER + 26) return code - LOWER + 26 } function b64ToByteArray (b64) { var i, j, l, tmp, placeHolders, arr if (b64.length % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr(b64.length * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) push((tmp & 0xFF0000) >> 16) push((tmp & 0xFF00) >> 8) push(tmp & 0xFF) } if (placeHolders === 2) { tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) push(tmp & 0xFF) } else if (placeHolders === 1) { tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) push((tmp >> 8) & 0xFF) push(tmp & 0xFF) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 2) output += encode((temp << 4) & 0x3F) output += '==' break case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) output += encode(temp >> 10) output += encode((temp >> 4) & 0x3F) output += encode((temp << 2) & 0x3F) output += '=' break } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) },{}],4:[function(require,module,exports){ exports.read = function(buffer, offset, isLE, mLen, nBytes) { var e, m, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, nBits = -7, i = isLE ? (nBytes - 1) : 0, d = isLE ? -1 : 1, s = buffer[offset + i]; i += d; e = s & ((1 << (-nBits)) - 1); s >>= (-nBits); nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); m = e & ((1 << (-nBits)) - 1); e >>= (-nBits); nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity); } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { var e, m, c, eLen = nBytes * 8 - mLen - 1, eMax = (1 << eLen) - 1, eBias = eMax >> 1, rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), i = isLE ? 0 : (nBytes - 1), d = isLE ? 1 : -1, s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); e = (e << mLen) | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); buffer[offset + i - d] |= s * 128; }; },{}],5:[function(require,module,exports){ module.exports = require('./lib'); },{"./lib":6}],6:[function(require,module,exports){ // Load modules var Stringify = require('./stringify'); var Parse = require('./parse'); // Declare internals var internals = {}; module.exports = { stringify: Stringify, parse: Parse }; },{"./parse":7,"./stringify":8}],7:[function(require,module,exports){ // Load modules var Utils = require('./utils'); // Declare internals var internals = { delimiter: '&', depth: 5, arrayLimit: 20, parametersLimit: 1000 }; internals.parseValues = function (str, delimiter) { delimiter = typeof delimiter === 'string' ? delimiter : internals.delimiter; var obj = {}; var parts = str.split(delimiter, internals.parametersLimit); for (var i = 0, il = parts.length; i < il; ++i) { var part = parts[i]; var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; if (pos === -1) { obj[Utils.decode(part)] = ''; } else { var key = Utils.decode(part.slice(0, pos)); var val = Utils.decode(part.slice(pos + 1)); if (!obj[key]) { obj[key] = val; } else { obj[key] = [].concat(obj[key]).concat(val); } } } return obj; }; internals.parseObject = function (chain, val) { if (!chain.length) { return val; } var root = chain.shift(); var obj = {}; if (root === '[]') { obj = []; obj = obj.concat(internals.parseObject(chain, val)); } else { var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; var index = parseInt(cleanRoot, 10); if (!isNaN(index) && root !== cleanRoot && index <= internals.arrayLimit) { obj = []; obj[index] = internals.parseObject(chain, val); } else { obj[cleanRoot] = internals.parseObject(chain, val); } } return obj; }; internals.parseKeys = function (key, val, depth) { if (!key) { return; } // The regex chunks var parent = /^([^\[\]]*)/; var child = /(\[[^\[\]]*\])/g; // Get the parent var segment = parent.exec(key); // Don't allow them to overwrite object prototype properties if (Object.prototype.hasOwnProperty(segment[1])) { return; } // Stash the parent if it exists var keys = []; if (segment[1]) { keys.push(segment[1]); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < depth) { ++i; if (!Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) { keys.push(segment[1]); } } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return internals.parseObject(keys, val); }; module.exports = function (str, depth, delimiter) { if (str === '' || str === null || typeof str === 'undefined') { return {}; } if (typeof depth !== 'number') { delimiter = depth; depth = internals.depth; } var tempObj = typeof str === 'string' ? internals.parseValues(str, delimiter) : Utils.clone(str); var obj = {}; // Iterate over the keys and setup the new object // for (var key in tempObj) { if (tempObj.hasOwnProperty(key)) { var newObj = internals.parseKeys(key, tempObj[key], depth); obj = Utils.merge(obj, newObj); } } return Utils.compact(obj); }; },{"./utils":9}],8:[function(require,module,exports){ (function (Buffer){ // Load modules // Declare internals var internals = { delimiter: '&' }; internals.stringify = function (obj, prefix) { if (Buffer.isBuffer(obj)) { obj = obj.toString(); } else if (obj instanceof Date) { obj = obj.toISOString(); } else if (obj === null) { obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') { return [encodeURIComponent(prefix) + '=' + encodeURIComponent(obj)]; } var values = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']')); } } return values; }; module.exports = function (obj, delimiter) { delimiter = typeof delimiter === 'undefined' ? internals.delimiter : delimiter; var keys = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keys = keys.concat(internals.stringify(obj[key], key)); } } return keys.join(delimiter); }; }).call(this,require("buffer").Buffer) },{"buffer":2}],9:[function(require,module,exports){ (function (Buffer){ // Load modules // Declare internals var internals = {}; exports.arrayToObject = function (source) { var obj = {}; for (var i = 0, il = source.length; i < il; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; exports.clone = function (source) { if (typeof source !== 'object' || source === null) { return source; } if (Buffer.isBuffer(source)) { return source.toString(); } var obj = Array.isArray(source) ? [] : {}; for (var i in source) { if (source.hasOwnProperty(i)) { obj[i] = exports.clone(source[i]); } } return obj; }; exports.merge = function (target, source) { if (!source) { return target; } var obj = exports.clone(target); if (Array.isArray(source)) { for (var i = 0, il = source.length; i < il; ++i) { if (typeof source[i] !== 'undefined') { if (typeof obj[i] === 'object') { obj[i] = exports.merge(obj[i], source[i]); } else { obj[i] = source[i]; } } } return obj; } if (Array.isArray(obj)) { obj = exports.arrayToObject(obj); } var keys = Object.keys(source); for (var k = 0, kl = keys.length; k < kl; ++k) { var key = keys[k]; var value = source[key]; if (value && typeof value === 'object') { if (!obj[key]) { obj[key] = exports.clone(value); } else { obj[key] = exports.merge(obj[key], value); } } else { obj[key] = value; } } return obj; }; exports.decode = function (str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; exports.compact = function (obj) { if (typeof obj !== 'object') { return obj; } var compacted = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { if (Array.isArray(obj[key])) { compacted[key] = []; for (var i = 0, l = obj[key].length; i < l; i++) { if (typeof obj[key][i] !== 'undefined') { compacted[key].push(obj[key][i]); } } } else { compacted[key] = exports.compact(obj[key]); } } } return compacted; }; }).call(this,require("buffer").Buffer) },{"buffer":2}]},{},[1]); (function(undefined){ /** * Minimal Event interface implementation * * Original implementation by Sven Fuchs: https://gist.github.com/995028 * Modifications and tests by Christian Johansen. * * @author Sven Fuchs (svenfuchs@artweb-design.de) * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2011 Sven Fuchs, Christian Johansen */ var _Event = function Event(type, bubbles, cancelable, target) { this.type = type; this.bubbles = bubbles; this.cancelable = cancelable; this.target = target; }; _Event.prototype = { stopPropagation: function () {}, preventDefault: function () { this.defaultPrevented = true; } }; /* Used to set the statusText property of an xhr object */ var httpStatusCodes = { 100: "Continue", 101: "Switching Protocols", 200: "OK", 201: "Created", 202: "Accepted", 203: "Non-Authoritative Information", 204: "No Content", 205: "Reset Content", 206: "Partial Content", 300: "Multiple Choice", 301: "Moved Permanently", 302: "Found", 303: "See Other", 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 406: "Not Acceptable", 407: "Proxy Authentication Required", 408: "Request Timeout", 409: "Conflict", 410: "Gone", 411: "Length Required", 412: "Precondition Failed", 413: "Request Entity Too Large", 414: "Request-URI Too Long", 415: "Unsupported Media Type", 416: "Requested Range Not Satisfiable", 417: "Expectation Failed", 422: "Unprocessable Entity", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout", 505: "HTTP Version Not Supported" }; /* Cross-browser XML parsing. Used to turn XML responses into Document objects Borrowed from JSpec */ function parseXML(text) { var xmlDoc; if (typeof DOMParser != "undefined") { var parser = new DOMParser(); xmlDoc = parser.parseFromString(text, "text/xml"); } else { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(text); } return xmlDoc; } /* Without mocking, the native XMLHttpRequest object will throw an error when attempting to set these headers. We match this behavior. */ var unsafeHeaders = { "Accept-Charset": true, "Accept-Encoding": true, "Connection": true, "Content-Length": true, "Cookie": true, "Cookie2": true, "Content-Transfer-Encoding": true, "Date": true, "Expect": true, "Host": true, "Keep-Alive": true, "Referer": true, "TE": true, "Trailer": true, "Transfer-Encoding": true, "Upgrade": true, "User-Agent": true, "Via": true }; /* Adds an "event" onto the fake xhr object that just calls the same-named method. This is in case a library adds callbacks for these events. */ function _addEventListener(eventName, xhr){ xhr.addEventListener(eventName, function (event) { var listener = xhr["on" + eventName]; if (listener && typeof listener == "function") { listener(event); } }); } /* Constructor for a fake window.XMLHttpRequest */ function FakeXMLHttpRequest() { this.readyState = FakeXMLHttpRequest.UNSENT; this.requestHeaders = {}; this.requestBody = null; this.status = 0; this.statusText = ""; this._eventListeners = {}; var events = ["loadstart", "load", "abort", "loadend"]; for (var i = events.length - 1; i >= 0; i--) { _addEventListener(events[i], this); } } // These status codes are available on the native XMLHttpRequest // object, so we match that here in case a library is relying on them. FakeXMLHttpRequest.UNSENT = 0; FakeXMLHttpRequest.OPENED = 1; FakeXMLHttpRequest.HEADERS_RECEIVED = 2; FakeXMLHttpRequest.LOADING = 3; FakeXMLHttpRequest.DONE = 4; FakeXMLHttpRequest.prototype = { UNSENT: 0, OPENED: 1, HEADERS_RECEIVED: 2, LOADING: 3, DONE: 4, async: true, /* Duplicates the behavior of native XMLHttpRequest's open function */ open: function open(method, url, async, username, password) { this.method = method; this.url = url; this.async = typeof async == "boolean" ? async : true; this.username = username; this.password = password; this.responseText = null; this.responseXML = null; this.requestHeaders = {}; this.sendFlag = false; this._readyStateChange(FakeXMLHttpRequest.OPENED); }, /* Duplicates the behavior of native XMLHttpRequest's addEventListener function */ addEventListener: function addEventListener(event, listener) { this._eventListeners[event] = this._eventListeners[event] || []; this._eventListeners[event].push(listener); }, /* Duplicates the behavior of native XMLHttpRequest's removeEventListener function */ removeEventListener: function removeEventListener(event, listener) { var listeners = this._eventListeners[event] || []; for (var i = 0, l = listeners.length; i < l; ++i) { if (listeners[i] == listener) { return listeners.splice(i, 1); } } }, /* Duplicates the behavior of native XMLHttpRequest's dispatchEvent function */ dispatchEvent: function dispatchEvent(event) { var type = event.type; var listeners = this._eventListeners[type] || []; for (var i = 0; i < listeners.length; i++) { if (typeof listeners[i] == "function") { listeners[i].call(this, event); } else { listeners[i].handleEvent(event); } } return !!event.defaultPrevented; }, /* Duplicates the behavior of native XMLHttpRequest's setRequestHeader function */ setRequestHeader: function setRequestHeader(header, value) { verifyState(this); if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) { throw new Error("Refused to set unsafe header \"" + header + "\""); } if (this.requestHeaders[header]) { this.requestHeaders[header] += "," + value; } else { this.requestHeaders[header] = value; } }, /* Duplicates the behavior of native XMLHttpRequest's send function */ send: function send(data) { verifyState(this); if (!/^(get|head)$/i.test(this.method)) { if (this.requestHeaders["Content-Type"]) { var value = this.requestHeaders["Content-Type"].split(";"); this.requestHeaders["Content-Type"] = value[0] + ";charset=utf-8"; } else { this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; } this.requestBody = data; } this.errorFlag = false; this.sendFlag = this.async; this._readyStateChange(FakeXMLHttpRequest.OPENED); if (typeof this.onSend == "function") { this.onSend(this); } this.dispatchEvent(new _Event("loadstart", false, false, this)); }, /* Duplicates the behavior of native XMLHttpRequest's abort function */ abort: function abort() { this.aborted = true; this.responseText = null; this.errorFlag = true; this.requestHeaders = {}; if (this.readyState > FakeXMLHttpRequest.UNSENT && this.sendFlag) { this._readyStateChange(FakeXMLHttpRequest.DONE); this.sendFlag = false; } this.readyState = FakeXMLHttpRequest.UNSENT; this.dispatchEvent(new _Event("abort", false, false, this)); if (typeof this.onerror === "function") { this.onerror(); } }, /* Duplicates the behavior of native XMLHttpRequest's getResponseHeader function */ getResponseHeader: function getResponseHeader(header) { if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { return null; } if (/^Set-Cookie2?$/i.test(header)) { return null; } header = header.toLowerCase(); for (var h in this.responseHeaders) { if (h.toLowerCase() == header) { return this.responseHeaders[h]; } } return null; }, /* Duplicates the behavior of native XMLHttpRequest's getAllResponseHeaders function */ getAllResponseHeaders: function getAllResponseHeaders() { if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { return ""; } var headers = ""; for (var header in this.responseHeaders) { if (this.responseHeaders.hasOwnProperty(header) && !/^Set-Cookie2?$/i.test(header)) { headers += header + ": " + this.responseHeaders[header] + "\r\n"; } } return headers; }, /* Places a FakeXMLHttpRequest object into the passed state. */ _readyStateChange: function _readyStateChange(state) { this.readyState = state; if (typeof this.onreadystatechange == "function") { this.onreadystatechange(); } this.dispatchEvent(new _Event("readystatechange")); if (this.readyState == FakeXMLHttpRequest.DONE) { this.dispatchEvent(new _Event("load", false, false, this)); this.dispatchEvent(new _Event("loadend", false, false, this)); } }, /* Sets the FakeXMLHttpRequest object's response headers and places the object into readyState 2 */ _setResponseHeaders: function _setResponseHeaders(headers) { this.responseHeaders = {}; for (var header in headers) { if (headers.hasOwnProperty(header)) { this.responseHeaders[header] = headers[header]; } } if (this.async) { this._readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED); } else { this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED; } }, /* Sets the FakeXMLHttpRequest object's response body and if body text is XML, sets responseXML to parsed document object */ _setResponseBody: function _setResponseBody(body) { verifyRequestSent(this); verifyHeadersReceived(this); verifyResponseBodyType(body); var chunkSize = this.chunkSize || 10; var index = 0; this.responseText = ""; do { if (this.async) { this._readyStateChange(FakeXMLHttpRequest.LOADING); } this.responseText += body.substring(index, index + chunkSize); index += chunkSize; } while (index < body.length); var type = this.getResponseHeader("Content-Type"); if (this.responseText && (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) { try { this.responseXML = parseXML(this.responseText); } catch (e) { // Unable to parse XML - no biggie } } if (this.async) { this._readyStateChange(FakeXMLHttpRequest.DONE); } else { this.readyState = FakeXMLHttpRequest.DONE; } }, /* Forces a response on to the FakeXMLHttpRequest object. This is the public API for faking responses. This function takes a number status, headers object, and string body: ``` xhr.respond(404, {Content-Type: 'text/plain'}, "Sorry. This object was not found.") ``` */ respond: function respond(status, headers, body) { this._setResponseHeaders(headers || {}); this.status = typeof status == "number" ? status : 200; this.statusText = httpStatusCodes[this.status]; this._setResponseBody(body || ""); if (typeof this.onload === "function"){ this.onload(); } } }; function verifyState(xhr) { if (xhr.readyState !== FakeXMLHttpRequest.OPENED) { throw new Error("INVALID_STATE_ERR"); } if (xhr.sendFlag) { throw new Error("INVALID_STATE_ERR"); } } function verifyRequestSent(xhr) { if (xhr.readyState == FakeXMLHttpRequest.DONE) { throw new Error("Request done"); } } function verifyHeadersReceived(xhr) { if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) { throw new Error("No headers received"); } } function verifyResponseBodyType(body) { if (typeof body != "string") { var error = new Error("Attempted to respond to fake XMLHttpRequest with " + body + ", which is not a string."); error.name = "InvalidBodyException"; throw error; } } if (typeof module !== 'undefined' && module.exports) { module.exports = FakeXMLHttpRequest; } else if (typeof define === 'function' && define.amd) { define(function() { return FakeXMLHttpRequest; }); } else if (typeof window !== 'undefined') { window.FakeXMLHttpRequest = FakeXMLHttpRequest; } else if (this) { this.FakeXMLHttpRequest = FakeXMLHttpRequest; } })(); (function(__exports__) { "use strict"; var specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ]; var escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); function isArray(test) { return Object.prototype.toString.call(test) === "[object Array]"; } // A Segment represents a segment in the original route description. // Each Segment type provides an `eachChar` and `regex` method. // // The `eachChar` method invokes the callback with one or more character // specifications. A character specification consumes one or more input // characters. // // The `regex` method returns a regex fragment for the segment. If the // segment is a dynamic of star segment, the regex fragment also includes // a capture. // // A character specification contains: // // * `validChars`: a String with a list of all valid characters, or // * `invalidChars`: a String with a list of all invalid characters // * `repeat`: true if the character specification can repeat function StaticSegment(string) { this.string = string; } StaticSegment.prototype = { eachChar: function(callback) { var string = this.string, ch; for (var i=0, l=string.length; i<l; i++) { ch = string.charAt(i); callback({ validChars: ch }); } }, regex: function() { return this.string.replace(escapeRegex, '\\$1'); }, generate: function() { return this.string; } }; function DynamicSegment(name) { this.name = name; } DynamicSegment.prototype = { eachChar: function(callback) { callback({ invalidChars: "/", repeat: true }); }, regex: function() { return "([^/]+)"; }, generate: function(params) { return params[this.name]; } }; function StarSegment(name) { this.name = name; } StarSegment.prototype = { eachChar: function(callback) { callback({ invalidChars: "", repeat: true }); }, regex: function() { return "(.+)"; }, generate: function(params) { return params[this.name]; } }; function EpsilonSegment() {} EpsilonSegment.prototype = { eachChar: function() {}, regex: function() { return ""; }, generate: function() { return ""; } }; function parse(route, names, types) { // normalize route as not starting with a "/". Recognition will // also normalize. if (route.charAt(0) === "/") { route = route.substr(1); } var segments = route.split("/"), results = []; for (var i=0, l=segments.length; i<l; i++) { var segment = segments[i], match; if (match = segment.match(/^:([^\/]+)$/)) { results.push(new DynamicSegment(match[1])); names.push(match[1]); types.dynamics++; } else if (match = segment.match(/^\*([^\/]+)$/)) { results.push(new StarSegment(match[1])); names.push(match[1]); types.stars++; } else if(segment === "") { results.push(new EpsilonSegment()); } else { results.push(new StaticSegment(segment)); types.statics++; } } return results; } // A State has a character specification and (`charSpec`) and a list of possible // subsequent states (`nextStates`). // // If a State is an accepting state, it will also have several additional // properties: // // * `regex`: A regular expression that is used to extract parameters from paths // that reached this accepting state. // * `handlers`: Information on how to convert the list of captures into calls // to registered handlers with the specified parameters // * `types`: How many static, dynamic or star segments in this route. Used to // decide which route to use if multiple registered routes match a path. // // Currently, State is implemented naively by looping over `nextStates` and // comparing a character specification against a character. A more efficient // implementation would use a hash of keys pointing at one or more next states. function State(charSpec) { this.charSpec = charSpec; this.nextStates = []; } State.prototype = { get: function(charSpec) { var nextStates = this.nextStates; for (var i=0, l=nextStates.length; i<l; i++) { var child = nextStates[i]; var isEqual = child.charSpec.validChars === charSpec.validChars; isEqual = isEqual && child.charSpec.invalidChars === charSpec.invalidChars; if (isEqual) { return child; } } }, put: function(charSpec) { var state; // If the character specification already exists in a child of the current // state, just return that state. if (state = this.get(charSpec)) { return state; } // Make a new state for the character spec state = new State(charSpec); // Insert the new state as a child of the current state this.nextStates.push(state); // If this character specification repeats, insert the new state as a child // of itself. Note that this will not trigger an infinite loop because each // transition during recognition consumes a character. if (charSpec.repeat) { state.nextStates.push(state); } // Return the new state return state; }, // Find a list of child states matching the next character match: function(ch) { // DEBUG "Processing `" + ch + "`:" var nextStates = this.nextStates, child, charSpec, chars; // DEBUG " " + debugState(this) var returned = []; for (var i=0, l=nextStates.length; i<l; i++) { child = nextStates[i]; charSpec = child.charSpec; if (typeof (chars = charSpec.validChars) !== 'undefined') { if (chars.indexOf(ch) !== -1) { returned.push(child); } } else if (typeof (chars = charSpec.invalidChars) !== 'undefined') { if (chars.indexOf(ch) === -1) { returned.push(child); } } } return returned; } /** IF DEBUG , debug: function() { var charSpec = this.charSpec, debug = "[", chars = charSpec.validChars || charSpec.invalidChars; if (charSpec.invalidChars) { debug += "^"; } debug += chars; debug += "]"; if (charSpec.repeat) { debug += "+"; } return debug; } END IF **/ }; /** IF DEBUG function debug(log) { console.log(log); } function debugState(state) { return state.nextStates.map(function(n) { if (n.nextStates.length === 0) { return "( " + n.debug() + " [accepting] )"; } return "( " + n.debug() + " <then> " + n.nextStates.map(function(s) { return s.debug() }).join(" or ") + " )"; }).join(", ") } END IF **/ // This is a somewhat naive strategy, but should work in a lot of cases // A better strategy would properly resolve /posts/:id/new and /posts/edit/:id. // // This strategy generally prefers more static and less dynamic matching. // Specifically, it // // * prefers fewer stars to more, then // * prefers using stars for less of the match to more, then // * prefers fewer dynamic segments to more, then // * prefers more static segments to more function sortSolutions(states) { return states.sort(function(a, b) { if (a.types.stars !== b.types.stars) { return a.types.stars - b.types.stars; } if (a.types.stars) { if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; } if (a.types.dynamics !== b.types.dynamics) { return b.types.dynamics - a.types.dynamics; } } if (a.types.dynamics !== b.types.dynamics) { return a.types.dynamics - b.types.dynamics; } if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; } return 0; }); } function recognizeChar(states, ch) { var nextStates = []; for (var i=0, l=states.length; i<l; i++) { var state = states[i]; nextStates = nextStates.concat(state.match(ch)); } return nextStates; } var oCreate = Object.create || function(proto) { function F() {} F.prototype = proto; return new F(); }; function RecognizeResults(queryParams) { this.queryParams = queryParams || {}; } RecognizeResults.prototype = oCreate({ splice: Array.prototype.splice, slice: Array.prototype.slice, push: Array.prototype.push, length: 0, queryParams: null }); function findHandler(state, path, queryParams) { var handlers = state.handlers, regex = state.regex; var captures = path.match(regex), currentCapture = 1; var result = new RecognizeResults(queryParams); for (var i=0, l=handlers.length; i<l; i++) { var handler = handlers[i], names = handler.names, params = {}; for (var j=0, m=names.length; j<m; j++) { params[names[j]] = captures[currentCapture++]; } result.push({ handler: handler.handler, params: params, isDynamic: !!names.length }); } return result; } function addSegment(currentState, segment) { segment.eachChar(function(ch) { var state; currentState = currentState.put(ch); }); return currentState; } // The main interface var RouteRecognizer = function() { this.rootState = new State(); this.names = {}; }; RouteRecognizer.prototype = { add: function(routes, options) { var currentState = this.rootState, regex = "^", types = { statics: 0, dynamics: 0, stars: 0 }, handlers = [], allSegments = [], name; var isEmpty = true; for (var i=0, l=routes.length; i<l; i++) { var route = routes[i], names = []; var segments = parse(route.path, names, types); allSegments = allSegments.concat(segments); for (var j=0, m=segments.length; j<m; j++) { var segment = segments[j]; if (segment instanceof EpsilonSegment) { continue; } isEmpty = false; // Add a "/" for the new segment currentState = currentState.put({ validChars: "/" }); regex += "/"; // Add a representation of the segment to the NFA and regex currentState = addSegment(currentState, segment); regex += segment.regex(); } var handler = { handler: route.handler, names: names }; handlers.push(handler); } if (isEmpty) { currentState = currentState.put({ validChars: "/" }); regex += "/"; } currentState.handlers = handlers; currentState.regex = new RegExp(regex + "$"); currentState.types = types; if (name = options && options.as) { this.names[name] = { segments: allSegments, handlers: handlers }; } }, handlersFor: function(name) { var route = this.names[name], result = []; if (!route) { throw new Error("There is no route named " + name); } for (var i=0, l=route.handlers.length; i<l; i++) { result.push(route.handlers[i]); } return result; }, hasRoute: function(name) { return !!this.names[name]; }, generate: function(name, params) { var route = this.names[name], output = ""; if (!route) { throw new Error("There is no route named " + name); } var segments = route.segments; for (var i=0, l=segments.length; i<l; i++) { var segment = segments[i]; if (segment instanceof EpsilonSegment) { continue; } output += "/"; output += segment.generate(params); } if (output.charAt(0) !== '/') { output = '/' + output; } if (params && params.queryParams) { output += this.generateQueryString(params.queryParams, route.handlers); } return output; }, generateQueryString: function(params, handlers) { var pairs = []; var keys = []; for(var key in params) { if (params.hasOwnProperty(key)) { keys.push(key); } } keys.sort(); for (var i = 0, len = keys.length; i < len; i++) { key = keys[i]; var value = params[key]; if (value == null) { continue; } var pair = key; if (isArray(value)) { for (var j = 0, l = value.length; j < l; j++) { var arrayPair = key + '[]' + '=' + encodeURIComponent(value[j]); pairs.push(arrayPair); } } else { pair += "=" + encodeURIComponent(value); pairs.push(pair); } } if (pairs.length === 0) { return ''; } return "?" + pairs.join("&"); }, parseQueryString: function(queryString) { var pairs = queryString.split("&"), queryParams = {}; for(var i=0; i < pairs.length; i++) { var pair = pairs[i].split('='), key = decodeURIComponent(pair[0]), keyLength = key.length, isArray = false, value; if (pair.length === 1) { value = 'true'; } else { //Handle arrays if (keyLength > 2 && key.slice(keyLength -2) === '[]') { isArray = true; key = key.slice(0, keyLength - 2); if(!queryParams[key]) { queryParams[key] = []; } } value = pair[1] ? decodeURIComponent(pair[1]) : ''; } if (isArray) { queryParams[key].push(value); } else { queryParams[key] = decodeURIComponent(value); } } return queryParams; }, recognize: function(path) { var states = [ this.rootState ], pathLen, i, l, queryStart, queryParams = {}, isSlashDropped = false; path = decodeURI(path); queryStart = path.indexOf('?'); if (queryStart !== -1) { var queryString = path.substr(queryStart + 1, path.length); path = path.substr(0, queryStart); queryParams = this.parseQueryString(queryString); } // DEBUG GROUP path if (path.charAt(0) !== "/") { path = "/" + path; } pathLen = path.length; if (pathLen > 1 && path.charAt(pathLen - 1) === "/") { path = path.substr(0, pathLen - 1); isSlashDropped = true; } for (i=0, l=path.length; i<l; i++) { states = recognizeChar(states, path.charAt(i)); if (!states.length) { break; } } // END DEBUG GROUP var solutions = []; for (i=0, l=states.length; i<l; i++) { if (states[i].handlers) { solutions.push(states[i]); } } states = sortSolutions(solutions); var state = solutions[0]; if (state && state.handlers) { // if a trailing slash was dropped and a star segment is the last segment // specified, put the trailing slash back if (isSlashDropped && state.regex.source.slice(-5) === "(.+)$") { path = path + "/"; } return findHandler(state, path, queryParams); } } }; __exports__.RouteRecognizer = RouteRecognizer; function Target(path, matcher, delegate) { this.path = path; this.matcher = matcher; this.delegate = delegate; } Target.prototype = { to: function(target, callback) { var delegate = this.delegate; if (delegate && delegate.willAddRoute) { target = delegate.willAddRoute(this.matcher.target, target); } this.matcher.add(this.path, target); if (callback) { if (callback.length === 0) { throw new Error("You must have an argument in the function passed to `to`"); } this.matcher.addChild(this.path, target, callback, this.delegate); } return this; } }; function Matcher(target) { this.routes = {}; this.children = {}; this.target = target; } Matcher.prototype = { add: function(path, handler) { this.routes[path] = handler; }, addChild: function(path, target, callback, delegate) { var matcher = new Matcher(target); this.children[path] = matcher; var match = generateMatch(path, matcher, delegate); if (delegate && delegate.contextEntered) { delegate.contextEntered(target, match); } callback(match); } }; function generateMatch(startingPath, matcher, delegate) { return function(path, nestedCallback) { var fullPath = startingPath + path; if (nestedCallback) { nestedCallback(generateMatch(fullPath, matcher, delegate)); } else { return new Target(startingPath + path, matcher, delegate); } }; } function addRoute(routeArray, path, handler) { var len = 0; for (var i=0, l=routeArray.length; i<l; i++) { len += routeArray[i].path.length; } path = path.substr(len); var route = { path: path, handler: handler }; routeArray.push(route); } function eachRoute(baseRoute, matcher, callback, binding) { var routes = matcher.routes; for (var path in routes) { if (routes.hasOwnProperty(path)) { var routeArray = baseRoute.slice(); addRoute(routeArray, path, routes[path]); if (matcher.children[path]) { eachRoute(routeArray, matcher.children[path], callback, binding); } else { callback.call(binding, routeArray); } } } } RouteRecognizer.prototype.map = function(callback, addRouteCallback) { var matcher = new Matcher(); callback(generateMatch("", matcher, this.delegate)); eachRoute([], matcher, function(route) { if (addRouteCallback) { addRouteCallback(this, route); } else { this.add(route); } }, this); }; })(window); var isNode = typeof process !== 'undefined' && process.toString() === '[object process]'; var RouteRecognizer = isNode ? require('route-recognizer') : window.RouteRecognizer; var FakeXMLHttpRequest = isNode ? require('./bower_components/FakeXMLHttpRequest/fake_xml_http_request') : window.FakeXMLHttpRequest; var forEach = [].forEach; function Pretender(maps){ maps = maps || function(){}; // Herein we keep track of RouteRecognizer instances // keyed by HTTP method. Feel free to add more as needed. this.registry = { GET: new RouteRecognizer(), PUT: new RouteRecognizer(), POST: new RouteRecognizer(), DELETE: new RouteRecognizer(), PATCH: new RouteRecognizer(), HEAD: new RouteRecognizer() }; this.handlers = []; this.handledRequests = []; this.unhandledRequests = []; // reference the native XMLHttpRequest object so // it can be restored later this._nativeXMLHttpRequest = window.XMLHttpRequest; // capture xhr requests, channeling them into // the route map. window.XMLHttpRequest = interceptor(this); // trigger the route map DSL. maps.call(this); } function interceptor(pretender) { function FakeRequest(){ // super() FakeXMLHttpRequest.call(this); } // extend var proto = new FakeXMLHttpRequest(); proto.send = function send(){ FakeXMLHttpRequest.prototype.send.apply(this, arguments); pretender.handleRequest(this); }; FakeRequest.prototype = proto; return FakeRequest; } function verbify(verb){ return function(path, handler){ this.register(verb, path, handler); }; } Pretender.prototype = { get: verbify('GET'), post: verbify('POST'), put: verbify('PUT'), 'delete': verbify('DELETE'), patch: verbify('PATCH'), head: verbify('HEAD'), register: function register(verb, path, handler){ handler.numberOfCalls = 0; this.handlers.push(handler); var registry = this.registry[verb]; registry.add([{path: path, handler: handler}]); }, handleRequest: function handleRequest(request){ var verb = request.method.toUpperCase(); var path = request.url; var handler = this._handlerFor(verb, path, request); if (handler) { handler.handler.numberOfCalls++; this.handledRequests.push(request); this.handledRequest(verb, path, request); try { var statusHeadersAndBody = handler.handler(request), status = statusHeadersAndBody[0], headers = statusHeadersAndBody[1], body = this.prepareBody(statusHeadersAndBody[2]); request.respond(status, headers, body); } catch (error) { this.erroredRequest(verb, path, request, error); } } else { this.unhandledRequests.push(request); this.unhandledRequest(verb, path, request); } }, prepareBody: function(body){ return body; }, handledRequest: function(verb, path, request){/* no-op */}, unhandledRequest: function(verb, path, request) { throw new Error("Pretender intercepted "+verb+" "+path+" but no handler was defined for this type of request"); }, erroredRequest: function(verb, path, request, error){ error.message = "Pretender intercepted "+verb+" "+path+" but encountered an error: " + error.message; throw error; }, _handlerFor: function(verb, path, request){ var registry = this.registry[verb]; var matches = registry.recognize(path); var match = matches ? matches[0] : null; if (match) { request.params = match.params; request.queryParams = matches.queryParams; } return match; }, shutdown: function shutdown(){ window.XMLHttpRequest = this._nativeXMLHttpRequest; } }; if (isNode) { module.exports = Pretender; } /** * Agent * * Library for building fixture data to be returned by a * Pretender server running in the client. */ Agent = function(defaults) { var d = defaults || {}, storeConst, i; this.fixtureIds = {}; this.groups = []; this.useUUID = true; this.router = new Agent.Router(this); this._server = null; this.logger = console; if (d.store) { if (typeof d.store === 'function') { this.store = new d.store(); } else if (typeof d.store === 'string' && Agent[d.store]) { this.store = new Agent[d.store](); } else { this.store = new Agent.MemoryStore(); } delete d.store; } else { this.store = new Agent.MemoryStore(); } if (typeof d=== 'object') { for (i in d) { if (d.hasOwnProperty(i)) { this[i] = d[i]; } } } // Setting current instance to the global object so it can // be accessed globally to change values that the tests might // rely on. See examples. Agent.instance = this; }; Agent.instance = null; Agent.nk = function(key) { return ('' + key).toUpperCase(); }; Agent.create = function(defaults) { return new Agent(defaults); }; Agent.uuid = Agent.prototype.uuid = function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); }; Agent.prototype.server = function(cb) { var agent = this; if (!this._server) { if (typeof cb === 'function') { new Pretender(function() { agent._server = this; cb.call(this, agent); }); } else { this._server = new Pretender(); } } return this._server; }; Agent.prototype.makeIds = function(key, length) { var i, obj = {}, id; key = Agent.nk(key); if (this.fixtureIds[key] === undefined) { this.fixtureIds[key] = obj; } else { obj = this.fixtureIds[key]; } for (i = 0; i < length; i++) { id = i + 1; if (this.useUUID) { id = this.uuid(); } obj[i + 1] = id; } return obj; }; Agent.prototype.setIds = function(key, list) { var i, len, obj = {}; key = Agent.nk(key); for (i = 0, len = list.length; i < len; i++) { obj[i + 1] = list[i]; } this.fixtureIds[key] = obj; return this.fixtureIds[key]; }; Agent.prototype.getIds = function(key) { return this.fixtureIds[Agent.nk(key)] || {}; }; Agent.prototype.group = function(key, callback) { this.groups.push(new Agent.FixtureGroup(Agent.nk(key), callback)); return this; }; Agent.prototype.build = function() { var i, j, len, key, records; for (i = 0, len = this.groups.length; i < len; i++) { key = Agent.nk(this.groups[i].key); records = this.groups[i].records(); for (j in records) { if (records.hasOwnProperty(j)) { this.store.createRecord(key, j, records[j]); } } } return this; }; Agent.prototype.reset = function() { this.groups.forEach(function(g) { return g.reset(); }); this.store.reset(); }; Agent.prototype.rebuild = function() { this.reset(); this.build(); }; Agent.prototype.log = function() { if (this.logger && this.logger.log) { this.logger.log.apply(this.logger, arguments); } }; Agent.prototype.fixtures = Agent.prototype.get = function(key) { return this.store.get(Agent.nk(key)); }; Agent.prototype.getRecord = function(key, id) { return this.store.getRecord(key, id); }; Agent.prototype.createRecord = function(key, data) { var records = this.store.get(key), id; if (data.id) { id = data.id; } else { if (this.useUUID) { id = this.uuid(); } else { id = Object.keys(records).length; } } data.id = id; return this.store.createRecord(key, id, data); }; Agent.prototype.updateRecord = function(key, id, data) { return this.store.updateRecord(key, id, data); }; Agent.prototype.replaceRecord = function(key, id, data) { return this.store.replaceRecord(key, id, data); }; Agent.prototype.deleteRecord = function(key, id) { return this.store.deleteRecord(key, id); }; /** * Agent.FixtureGroup * * A fixture group is indentified by a key (typically the * resource type) holds the callback that will eventually * be called to generate fixture records. After building * (calling the callback) the records method will return * and object keyed by record id of all the fixtures. */ Agent.FixtureGroup = function(key, callback) { this.key = Agent.nk(key); this.callback = callback; this.isBuilt = false; this.fixtures = []; }; Agent.FixtureGroup.prototype.build = function() { var self = this, obj = { fixture: function(id, data) { self.fixtures.push(new Agent.Fixture(id, data)); } }; if (typeof this.callback === 'function') { this.callback.call(obj, this); } this.isBuilt = true; }; Agent.FixtureGroup.prototype.records = function() { if (!this.isBuilt) { this.build(); } return this.fixtures.reduce(function(accum, fixture) { accum[fixture.id] = fixture.record(); return accum; }, {}); }; Agent.FixtureGroup.prototype.reset = function() { this.isBuilt = false; this.fixtures = []; }; /** * Agent.Fixture * * An object of data identified by an id. When generating * the final object that represents the fixture, the id * is injected in if the data does not include the id key */ Agent.Fixture = function(id, data) { this.id = id; this.data = data; }; Agent.Fixture.prototype.record = function() { var data = this.data, id = this.id; if (data.id === undefined) { data.id = id; } return data; }; /** * Agent.Store * * Base of any store adapter. Stores hold the fixture data, and * should be capable of adding, editing, removing records and * also resetting to empty. */ Agent.Store = function() {}; Agent.Store.prototype._get = function() { throw new Error('Implement _get method'); }; Agent.Store.prototype._set = function() { throw new Error('Implement _set method'); }; Agent.Store.prototype.get = function(key) { throw new Error('Implement get method'); }; Agent.Store.prototype.getRecord = function(key, id) { throw new Error('Implement getRecord method'); }; Agent.Store.prototype.createRecord = function(key, id, record) { throw new Error('Implement createRecord method'); }; Agent.Store.prototype.updateRecord = function(key, id, data) { throw new Error('Implement updateRecord method'); }; Agent.Store.prototype.replaceRecord = function(key, id, record) { throw new Error('Implement replaceRecord method'); }; Agent.Store.prototype.deleteRecord = function(key, id) { throw new Error('Implement deleteRecord method'); }; Agent.Store.prototype.reset = function() { throw new Error('Implement reset method'); }; /** * Agent.MemoryStore * * A store adapter that saves data in memory. * Data is not saved between reloads */ Agent.MemoryStore = function() { this._data = {}; }; Agent.MemoryStore.prototype = Object.create(Agent.Store.prototype); Agent.MemoryStore.prototype.constructor = Agent.MemoryStore; Agent.MemoryStore.prototype._get = function() { return this._data; }; Agent.MemoryStore.prototype._set = function(data) { this._data = data; }; Agent.MemoryStore.prototype.get = function(key) { var k = Agent.nk(key), data = this._get(); return data[k] || false; }; Agent.MemoryStore.prototype.getRecord = function(key, id) { var data = this.get(key), ret = false; if (data) { ret = data['' + id] || false; } return ret; }; Agent.MemoryStore.prototype.createRecord = function(key, id, record) { if (this.getRecord(key, id)) { return false; } return this.replaceRecord(key, id, record); }; Agent.MemoryStore.prototype.updateRecord = function(key, id, record) { var data = this._get(), k = Agent.nk(key), i, r; if (!this.get(key)) { return false; } data[k] = data[k] || {}; if (!data[k]['' + id]) { return false; } r = data[k]['' + id]; for (i in record) { if (r.hasOwnProperty(i) && record.hasOwnProperty(i)) { r[i] = record[i]; } } this._set(data); return this.getRecord(key, id); }; Agent.MemoryStore.prototype.replaceRecord = function(key, id, record) { var data = this._get(), k = Agent.nk(key); data[k] = data[k] || {}; data[k]['' + id] = record; this._set(data); return this.getRecord(key, id); }; Agent.MemoryStore.prototype.deleteRecord = function(key, id) { var data = this._get(), k = Agent.nk(key); data[k] = data[k] || {}; if (data[k]['' + id]) { delete data[k]['' + id]; } else { return false; } this._set(data); return true; }; Agent.MemoryStore.prototype.reset = function() { this._set({}); }; /** * Agent.LocalStorageStore * * Store adapter that will save data to the browser's localStorage. * This data should persist between browser reloads. */ Agent.LocalStorageStore = function() { if (!window.localStorage) { throw new Error('This browser does not support localStorage'); } }; Agent.LocalStorageStore.prototype = Object.create(Agent.MemoryStore.prototype); Agent.LocalStorageStore.prototype.constructor = Agent.LocalStorageStore; Agent.LocalStorageStore.prototype._get = function() { return JSON.parse(localStorage.getItem('Agent.LocalStorageStore')) || {}; }; Agent.LocalStorageStore.prototype._set = function(data) { localStorage.setItem('Agent.LocalStorageStore', JSON.stringify(data)); }; /** * Agent.Router * * An instance of this will live on the agent instances. It exposes * convenience methods for making conventional rest endpoints with * Pretender and will use the agent.store to get and save records. */ Agent.Router = function(agent) { this.agent = agent; }; Agent.Router.prototype._parseKey = function(key, route) { var ret = [], bits, id; bits = route.split('/'); if (key) { ret.push(key); } key = bits[bits.length - 1]; if (key[0] === ':') { id = key.slice(1); key = bits[bits.length - 2]; if (!ret.length) { ret.push(key); } ret.push(id); } return ret; }; Agent.Router.prototype._toArray = function(obj) { var i, arr = []; for (i in obj) { if (obj.hasOwnProperty(i)) { arr.push(obj[i]); } } return arr; }; Agent.Router.prototype._parseParams = function(params) { var ret = false; try { ret = JSON.parse(params); } catch(e) { try { ret = qs.parse(params); } catch(er) { ret = false; } } return ret; }; /** * router.get * */ Agent.Router.prototype.get = function(route, options) { var agent = this.agent, server = agent.server(), router = this, segment = false, plural, singular, bits; if (typeof options === 'function') { server.get(route, function(request) { var response = options.call(this, request); agent.log('request: GET ' + request.url + ' response: ' + response[0]); return response; }); return; } options = options || {}; plural = options.plural; singular = options.singular || false; bits = this._parseKey(plural, route); plural = bits[0]; segment = bits[1]; if (!singular) { throw new Error('The singular key must be set in the options for Agent.instance.router.get()'); } server.get(route, function(request) { var code = 200, headers = { "Content-Type": "application/json" }, body = {}, data = agent.get(plural), id = false; if (segment) { id = request.params[segment]; } if (!data) { code = 404; } else { if (id !== false) { data = agent.getRecord(plural, id); if (!data) { code = 404; } else { body[singular] = data; } } else { body[plural] = router._toArray(data); } } agent.log('request: GET ' + request.url + ' response: ' + code); return [code, headers, JSON.stringify(body)]; }); }; /** * router.post * */ Agent.Router.prototype.post = function(route, options) { var agent = this.agent, server = agent.server(), router = this, segment = false, plural, singular, bits; if (typeof options === 'function') { server.post(route, function(request) { var response = options.call(this, request); agent.log('request: POST ' + request.url + ' response: ' + response[0] + ' data: ' + request.requestBody); return response; }); return; } options = options || {}; plural = options.plural; singular = options.singular || false; bits = this._parseKey(plural, route); plural = bits[0]; segment = bits[1]; if (!singular) { throw new Error('The singular key must be set in the options for Agent.instance.router.post()'); } server.post(route, function(request) { var code = 200, headers = { "Content-Type": "application/json" }, body = {}, data = agent.get(plural), id = false, params = {}, hasSingular, responseKey; if (segment) { id = request.params[segment]; } params = router._parseParams(request.requestBody); if (!params || (!params[singular] && !params[plural])) { code = 400; } hasSingular = params[singular]; if (hasSingular) { params = params[singular]; responseKey = singular; } else { params = params[plural]; responseKey = plural; } if (data && id) { if (agent.getRecord(plural, id)) { body[responseKey] = agent.updateRecord(plural, id, params); code = 201; } else { code = 404; } } else { body[responseKey] = agent.createRecord(plural, params); code = 201; } agent.log('request: POST ' + request.url + ' response: ' + code + ' data: ' + request.requestBody); return [code, headers, JSON.stringify(body)]; }); }; /** * router.put * */ Agent.Router.prototype.put = function(route, options) { var agent = this.agent, server = agent.server(), router = this, segment = false, plural, singular, bits; if (typeof options === 'function') { server.put(route, function(request) { var response = options.call(this, request); agent.log('request: PUT ' + request.url + ' response: ' + response[0] + ' data: ' + request.requestBody); return response; }); return; } options = options || {}; plural = options.plural; singular = options.singular || false; bits = this._parseKey(plural, route); plural = bits[0]; segment = bits[1]; if (!singular) { throw new Error('The singular key must be set in the options for Agent.instance.router.post()'); } server.put(route, function(request) { var code = 200, headers = { "Content-Type": "application/json" }, body = {}, id = false, params = {}, data, hasSingular, responseKey; if (segment) { id = request.params[segment]; } params = router._parseParams(request.requestBody); if (!params || (!params[singular] && !params[plural])) { code = 400; } hasSingular = params[singular]; if (hasSingular) { params = params[singular]; responseKey = singular; } else { params = params[plural]; responseKey = plural; } data = agent.getRecord(plural, id); if (!data) { code = 404; } if (data && id && params) { body[responseKey] = agent.updateRecord(plural, id, params); } agent.log('request: PUT ' + request.url + ' response: ' + code + ' data: ' + request.requestBody); return [code, headers, JSON.stringify(body)]; }); }; /** * router.delete * */ Agent.Router.prototype['delete'] = function(route, key) { var agent = this.agent, server = agent.server(), router = this, segment = false, bits; if (typeof options === 'function') { server.delete(route, function(request) { var response = options.call(this, request); agent.log('request: DELETE ' + request.url + ' response: ' + response[0]); return response; }); return; } bits = this._parseKey(key, route); key = bits[0]; segment = bits[1]; server.delete(route, function(request) { var code = 200, headers = { "Content-Type": "application/json" }, id = false, data; if (segment) { id = request.params[segment]; } data = agent.getRecord(key, id); if (!data) { code = 404; } else { agent.deleteRecord(key, id); } agent.log('request: DELETE ' + request.url + ' response: ' + code); return [code, headers, '{}']; }); }; /** * router.resource * */ Agent.Router.prototype.resource = function(key, options) { var only, router, routes, plural, singular; router = this; only = ['index', 'view', 'add', 'edit', 'delete']; if (!options) { options = {}; } if (options.only) { only = options.only; } plural = key; if (options.plural) { plural = options.plural; } singular = options.singular; if (!singular) { throw new Error('Must give the singular option in the resource options'); } routes = function(type) { switch (type) { case 'index': router.get('/' + key, { singular: singular, plural: plural }); break; case 'view': router.get('/' + key + '/:id', { singular: singular, plural: plural }); break; case 'add': router.post('/' + key, { singular: singular, plural: plural }); break; case 'edit': router.put('/' + key + '/:id', { singular: singular, plural: plural }); break; case 'delete': router.delete('/' + key + '/:id', plural); break; } }; only.forEach(function(o) { routes(o); }); };
joeytrapp/pretender-fixtures
dist/agent.js
JavaScript
mit
96,951
(function(app) { // Transitions: scale, fade, flip, drop, fly, swing, browse, slide, jiggle, flash, shake, pulse, tada, bounce app .factory('SemanticTransitionLink', ['SemanticUI', SemanticTransitionLink]) .directive('smTransition', ['SemanticTransitionLink', SemanticTransition]) ; function SemanticTransition(SemanticTransitionLink) { return { restrict: 'A', scope: { smTransition: '@', smTransitionEvents: '@', smTransitionOther: '@' }, link: SemanticTransitionLink }; } function SemanticTransitionLink(SemanticUI) { return function(scope, element, attributes) { scope.smTransitionEvents = scope.smTransitionEvents || 'click'; element.on( scope.smTransitionEvents, function() { ( scope.smTransitionOther ? $( scope.smTransitionOther ) : element ).transition( scope.smTransition ); }); }; } })( angular.module('semantic-ui-transition', ['semantic-ui-core']) );
ClickerMonkey/SemanticUI-Angular
src/transition/sm-transition.js
JavaScript
mit
998
var LocalDb = (function() { "use strict"; // Debug messages for Dexie (otherwise it swallows our messages) Dexie.Promise.on('error', function(err) { console.log("Uncaught error: " + err); }); var db = new Dexie("lastFM"); db.version(1).stores({ tracks: "timePlayed, username" }); db.version(2).stores({ users: "name, _page, _pages, _last", // responses from the api responses: "[name+to], name, to", // requestQueue: "++,name" // note: timePlayed can clash (even with single user) tracks: "timePlayed, username" }); db.version(3).stores({ /* { priority: int, state: int, user: string, request: {parameters}, response: {response_data}, } */ requests: '++, priority, state, user, [user+state]' }); db.open(); function saveRequest(request){ return db.requests.put(request) } function requestsFor(user){ return db.requests .where('user').equals(user) } // for hacks function requests(){ return db.requests } // export our API to window. return { saveRequest: saveRequest, requestsFor: requestsFor, requests: requests } })();
benfoxall/lastfm-to-csv-next
js/ds_lastfm_local.js
JavaScript
mit
1,203
$('#nav-toggle').click(function(e) { e.preventDefault(); $('#navbarSide').addClass('reveal'); $('.overlay').show(); }); $('.overlay').on('click', function() { $('#navbarSide').removeClass('reveal'); $('.overlay').hide(); }); // Reveal gallery as they scroll if (!(document.getElementById('gallery') == null)) { var galleryReveal = { delay : 0, duration : 500, reset: false, }; window.sr = ScrollReveal(); sr.reveal('.reveal', galleryReveal); } // Gallery PopUp $(function() { $('.gallery > .row div').magnificPopup({ delegate: 'a', // child items selector, by clicking on it popup will open type: 'image', mainClass: 'mfp-fade', gallery: { enabled: true }, closeOnContentClick: true, overflowY: 'scroll', callbacks: { open: function() { }, close: function() { } } }); }); // HELPSCOUT ! function(e, o, n) { window.HSCW = o, window.HS = n, n.beacon = n.beacon || {}; var t = n.beacon; t.userConfig = {}, t.readyQueue = [], t.config = function(e) { this.userConfig = e }, t.ready = function(e) { this.readyQueue.push(e) }, o.config = { docs: { enabled: !1, baseUrl: "" }, contact: { enabled: !0, formId: "4cf5a890-79da-11e6-91aa-0a5fecc78a4d" } }; var r = e.getElementsByTagName("script")[0], c = e.createElement("script"); c.type = "text/javascript", c.async = !0, c.src = "https://djtflbt20bdde.cloudfront.net/", r.parentNode.insertBefore(c, r) }(document, window.HSCW || {}, window.HS || {}); HS.beacon.config({ modal: true, }); $('.contact-us').click(function(e) { e.preventDefault(); // $('#projectSubmit > i').hide(); HS.beacon.open(); });
saturnonearth/gulp-boilerplate
src/scripts/app.js
JavaScript
mit
1,987
exports.info = { FormatID: '899', FormatName: 'Microsoft Works Database for DOS', FormatVersion: '2.0', FormatAliases: '', FormatFamilies: '', FormatTypes: 'Database', FormatDisclosure: '', FormatDescription: 'This is an outline record only, and requires further details, research or authentication to provide information that will enable users to further understand the format and to assess digital preservation risks associated with it if appropriate. If you are able to help by supplying any additional information concerning this entry, please return to the main PRONOM page and select ‘Add an Entry’.', BinaryFileFormat: 'Text', ByteOrders: '', ReleaseDate: '', WithdrawnDate: '', ProvenanceSourceID: '1', ProvenanceName: 'Digital Preservation Department / The National Archives', ProvenanceSourceDate: '28 Sep 2009', ProvenanceDescription: '', LastUpdatedDate: '28 Sep 2009', FormatNote: '', FormatRisk: '', TechnicalEnvironment: '', FileFormatIdentifier: { Identifier: 'fmt/171', IdentifierType: 'PUID' }, Developers: { DeveloperID: '93', DeveloperName: '', OrganisationName: 'Microsoft Corporation', DeveloperCompoundName: 'Microsoft Corporation' }, ExternalSignature: { ExternalSignatureID: '887', Signature: 'wdb', SignatureType: 'File extension' } }
redaktor/exiftool.js
src/exiftool/filetypes/171.js
JavaScript
mit
1,341
const html = require('../template/html'); const { getAssets, getHtml } = require('../utils'); const props = { 'initialState': { 'products': [ { 'image': 'http://localhost:3001/test-redux/assets/comic-book.jpg', 'title': 'Superhero Comic Book', 'price': { 'currency': 'GBP', 'amount': 1699 }, 'code': 393327, 'removed': false } ], 'listId': '1' } }; module.exports = function one(req, res) { let assets; return Promise.resolve() .then(() => getAssets(['test-redux'])) .then(({ scripts, styles }) => { assets = { scripts, styles }; return getHtml([`test-redux.raw.html?props=${JSON.stringify(props)}`]); }) .then((htmlStrings) => { res.send(html({ id: 'test-redux', body: htmlStrings.join('<hr/>'), scripts: assets.scripts, styles: assets.styles })); }) .catch(function(err) { res.send(err); }); };
notonthehighstreet/toga
example/routes/redux-component.js
JavaScript
mit
989
/** * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com * * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/ * * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License: * http://www.opensource.org/licenses/mit-license.php * * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License: * http://www.opensource.org/licenses/mit-license.php * */ /* ******************* */ /* Constructor & Init */ /* ******************* */ var SWFUpload; if (SWFUpload == undefined) { SWFUpload = function (settings) { this.initSWFUpload(settings); }; } SWFUpload.prototype.initSWFUpload = function (settings) { try { this.customSettings = {}; // A container where developers can place their own settings associated with this instance. this.settings = settings; this.eventQueue = []; this.movieName = "SWFUpload_" + SWFUpload.movieCount++; this.movieElement = null; // Setup global control tracking SWFUpload.instances[this.movieName] = this; // Load the settings. Load the Flash movie. this.initSettings(); this.loadFlash(); this.displayDebugInfo(); } catch (ex) { delete SWFUpload.instances[this.movieName]; throw ex; } }; /* *************** */ /* Static Members */ /* *************** */ SWFUpload.instances = {}; SWFUpload.movieCount = 0; SWFUpload.version = "2.2.0 Beta 3"; SWFUpload.QUEUE_ERROR = { QUEUE_LIMIT_EXCEEDED : -100, FILE_EXCEEDS_SIZE_LIMIT : -110, ZERO_BYTE_FILE : -120, INVALID_FILETYPE : -130 }; SWFUpload.UPLOAD_ERROR = { HTTP_ERROR : -200, MISSING_UPLOAD_URL : -210, IO_ERROR : -220, SECURITY_ERROR : -230, UPLOAD_LIMIT_EXCEEDED : -240, UPLOAD_FAILED : -250, SPECIFIED_FILE_ID_NOT_FOUND : -260, FILE_VALIDATION_FAILED : -270, FILE_CANCELLED : -280, UPLOAD_STOPPED : -290 }; SWFUpload.FILE_STATUS = { QUEUED : -1, IN_PROGRESS : -2, ERROR : -3, COMPLETE : -4, CANCELLED : -5 }; SWFUpload.BUTTON_ACTION = { SELECT_FILE : -100, SELECT_FILES : -110, START_UPLOAD : -120 }; SWFUpload.CURSOR = { ARROW : -1, HAND : -2 }; SWFUpload.WINDOW_MODE = { WINDOW : "window", TRANSPARENT : "transparent", OPAQUE : "opaque" }; /* ******************** */ /* Instance Members */ /* ******************** */ // Private: initSettings ensures that all the // settings are set, getting a default value if one was not assigned. SWFUpload.prototype.initSettings = function () { this.ensureDefault = function (settingName, defaultValue) { this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName]; }; // Upload backend settings this.ensureDefault("upload_url", ""); this.ensureDefault("file_post_name", "Filedata"); this.ensureDefault("post_params", {}); this.ensureDefault("use_query_string", false); this.ensureDefault("requeue_on_error", false); this.ensureDefault("http_success", []); // File Settings this.ensureDefault("file_types", "*.*"); this.ensureDefault("file_types_description", "All Files"); this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited" this.ensureDefault("file_upload_limit", 0); this.ensureDefault("file_queue_limit", 0); // Flash Settings this.ensureDefault("flash_url", "swfupload.swf"); this.ensureDefault("prevent_swf_caching", true); // Button Settings this.ensureDefault("button_image_url", ""); this.ensureDefault("button_width", 1); this.ensureDefault("button_height", 1); this.ensureDefault("button_text", ""); this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;"); this.ensureDefault("button_text_top_padding", 0); this.ensureDefault("button_text_left_padding", 0); this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES); this.ensureDefault("button_disabled", false); this.ensureDefault("button_placeholder_id", null); this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW); this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.TRANSPARENT);//SWFUpload.WINDOW_MODE.WINDOW // Debug Settings this.ensureDefault("debug", false); this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API // Event Handlers this.settings.return_upload_start_handler = this.returnUploadStart; this.ensureDefault("swfupload_loaded_handler", null); this.ensureDefault("file_dialog_start_handler", null); this.ensureDefault("file_queued_handler", null); this.ensureDefault("file_queue_error_handler", null); this.ensureDefault("file_dialog_complete_handler", null); this.ensureDefault("upload_start_handler", null); this.ensureDefault("upload_progress_handler", null); this.ensureDefault("upload_error_handler", null); this.ensureDefault("upload_success_handler", null); this.ensureDefault("upload_complete_handler", null); this.ensureDefault("debug_handler", this.debugMessage); this.ensureDefault("custom_settings", {}); // Other settings this.customSettings = this.settings.custom_settings; // Update the flash url if needed if (this.settings.prevent_swf_caching) { this.settings.flash_url = this.settings.flash_url + "?swfuploadrnd=" + Math.floor(Math.random() * 999999999); } delete this.ensureDefault; }; SWFUpload.prototype.loadFlash = function () { if (this.settings.button_placeholder_id !== "") { this.replaceWithFlash(); } else { this.appendFlash(); } }; // Private: appendFlash gets the HTML tag for the Flash // It then appends the flash to the body SWFUpload.prototype.appendFlash = function () { var targetElement, container; // Make sure an element with the ID we are going to use doesn't already exist if (document.getElementById(this.movieName) !== null) { throw "ID " + this.movieName + " is already in use. The Flash Object could not be added"; } // Get the body tag where we will be adding the flash movie targetElement = document.getElementsByTagName("body")[0]; if (targetElement == undefined) { throw "Could not find the 'body' element."; } // Append the container and load the flash container = document.createElement("div"); container.style.width = "1px"; container.style.height = "1px"; container.style.overflow = "hidden"; targetElement.appendChild(container); container.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers) // Fix IE Flash/Form bug if (window[this.movieName] == undefined) { window[this.movieName] = this.getMovieElement(); } }; // Private: replaceWithFlash replaces the button_placeholder element with the flash movie. SWFUpload.prototype.replaceWithFlash = function () { var targetElement, tempParent; // Make sure an element with the ID we are going to use doesn't already exist if (document.getElementById(this.movieName) !== null) { throw "ID " + this.movieName + " is already in use. The Flash Object could not be added"; } // Get the element where we will be placing the flash movie targetElement = document.getElementById(this.settings.button_placeholder_id); if (targetElement == undefined) { throw "Could not find the placeholder element."; } // Append the container and load the flash tempParent = document.createElement("div"); tempParent.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers) targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement); // Fix IE Flash/Form bug if (window[this.movieName] == undefined) { window[this.movieName] = this.getMovieElement(); } }; // Private: getFlashHTML generates the object tag needed to embed the flash in to the document SWFUpload.prototype.getFlashHTML = function () { // Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">', '<param name="wmode" value="', this.settings.button_window_mode , '" />', '<param name="movie" value="', this.settings.flash_url, '" />', '<param name="quality" value="high" />', '<param name="menu" value="false" />', '<param name="allowScriptAccess" value="always" />', '<param name="flashvars" value="' + this.getFlashVars() + '" />', '</object>'].join(""); }; // Private: getFlashVars builds the parameter string that will be passed // to flash in the flashvars param. SWFUpload.prototype.getFlashVars = function () { // Build a string from the post param object var paramString = this.buildParamString(); var httpSuccessString = this.settings.http_success.join(","); // Build the parameter string return ["movieName=", encodeURIComponent(this.movieName), "&amp;uploadURL=", encodeURIComponent(this.settings.upload_url), "&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string), "&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error), "&amp;httpSuccess=", encodeURIComponent(httpSuccessString), "&amp;params=", encodeURIComponent(paramString), "&amp;filePostName=", encodeURIComponent(this.settings.file_post_name), "&amp;fileTypes=", encodeURIComponent(this.settings.file_types), "&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description), "&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit), "&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit), "&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit), "&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled), "&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url), "&amp;buttonWidth=", encodeURIComponent(this.settings.button_width), "&amp;buttonHeight=", encodeURIComponent(this.settings.button_height), "&amp;buttonText=", encodeURIComponent(this.settings.button_text), "&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding), "&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding), "&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style), "&amp;buttonAction=", encodeURIComponent(this.settings.button_action), "&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled), "&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor) ].join(""); }; // Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload // The element is cached after the first lookup SWFUpload.prototype.getMovieElement = function () { if (this.movieElement == undefined) { this.movieElement = document.getElementById(this.movieName); } if (this.movieElement === null) { throw "Could not find Flash element"; } return this.movieElement; }; // Private: buildParamString takes the name/value pairs in the post_params setting object // and joins them up in to a string formatted "name=value&amp;name=value" SWFUpload.prototype.buildParamString = function () { var postParams = this.settings.post_params; var paramStringPairs = []; if (typeof(postParams) === "object") { for (var name in postParams) { if (postParams.hasOwnProperty(name)) { paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString())); } } } return paramStringPairs.join("&amp;"); }; // Public: Used to remove a SWFUpload instance from the page. This method strives to remove // all references to the SWF, and other objects so memory is properly freed. // Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state. // Credits: Major improvements provided by steffen SWFUpload.prototype.destroy = function () { try { // Make sure Flash is done before we try to remove it this.cancelUpload(null, false); // Remove the SWFUpload DOM nodes var movieElement = null; movieElement = this.getMovieElement(); if (movieElement) { // Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround) for (var i in movieElement) { try { if (typeof(movieElement[i]) === "function") { movieElement[i] = null; } } catch (ex1) {} } // Remove the Movie Element from the page try { movieElement.parentNode.removeChild(movieElement); } catch (ex) {} } // Remove IE form fix reference window[this.movieName] = null; // Destroy other references SWFUpload.instances[this.movieName] = null; delete SWFUpload.instances[this.movieName]; this.movieElement = null; this.settings = null; this.customSettings = null; this.eventQueue = null; this.movieName = null; return true; } catch (ex1) { return false; } }; // Public: displayDebugInfo prints out settings and configuration // information about this SWFUpload instance. // This function (and any references to it) can be deleted when placing // SWFUpload in production. SWFUpload.prototype.displayDebugInfo = function () { this.debug( [ "---SWFUpload Instance Info---\n", "Version: ", SWFUpload.version, "\n", "Movie Name: ", this.movieName, "\n", "Settings:\n", "\t", "upload_url: ", this.settings.upload_url, "\n", "\t", "flash_url: ", this.settings.flash_url, "\n", "\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n", "\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n", "\t", "http_success: ", this.settings.http_success.join(", "), "\n", "\t", "file_post_name: ", this.settings.file_post_name, "\n", "\t", "post_params: ", this.settings.post_params.toString(), "\n", "\t", "file_types: ", this.settings.file_types, "\n", "\t", "file_types_description: ", this.settings.file_types_description, "\n", "\t", "file_size_limit: ", this.settings.file_size_limit, "\n", "\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n", "\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n", "\t", "debug: ", this.settings.debug.toString(), "\n", "\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n", "\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n", "\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n", "\t", "button_width: ", this.settings.button_width.toString(), "\n", "\t", "button_height: ", this.settings.button_height.toString(), "\n", "\t", "button_text: ", this.settings.button_text.toString(), "\n", "\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n", "\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n", "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n", "\t", "button_action: ", this.settings.button_action.toString(), "\n", "\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n", "\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n", "Event Handlers:\n", "\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n", "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n", "\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n", "\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n", "\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n", "\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n", "\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n", "\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n", "\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n", "\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n" ].join("") ); }; /* Note: addSetting and getSetting are no longer used by SWFUpload but are included the maintain v2 API compatibility */ // Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used. SWFUpload.prototype.addSetting = function (name, value, default_value) { if (value == undefined) { return (this.settings[name] = default_value); } else { return (this.settings[name] = value); } }; // Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found. SWFUpload.prototype.getSetting = function (name) { if (this.settings[name] != undefined) { return this.settings[name]; } return ""; }; // Private: callFlash handles function calls made to the Flash element. // Calls are made with a setTimeout for some functions to work around // bugs in the ExternalInterface library. SWFUpload.prototype.callFlash = function (functionName, argumentArray) { argumentArray = argumentArray || []; var movieElement = this.getMovieElement(); var returnValue, returnString; // Flash's method if calling ExternalInterface methods (code adapted from MooTools). try { returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>'); returnValue = eval(returnString); } catch (ex) { throw "Call to " + functionName + " failed"; } // Unescape file post param values if (returnValue != undefined && typeof returnValue.post === "object") { returnValue = this.unescapeFilePostParams(returnValue); } return returnValue; }; /* ***************************** -- Flash control methods -- Your UI should use these to operate SWFUpload ***************************** */ // WARNING: this function does not work in Flash Player 10 // Public: selectFile causes a File Selection Dialog window to appear. This // dialog only allows 1 file to be selected. SWFUpload.prototype.selectFile = function () { this.callFlash("SelectFile"); }; // WARNING: this function does not work in Flash Player 10 // Public: selectFiles causes a File Selection Dialog window to appear/ This // dialog allows the user to select any number of files // Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names. // If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around // for this bug. SWFUpload.prototype.selectFiles = function () { this.callFlash("SelectFiles"); }; // Public: startUpload starts uploading the first file in the queue unless // the optional parameter 'fileID' specifies the ID SWFUpload.prototype.startUpload = function (fileID) { this.callFlash("StartUpload", [fileID]); }; // Public: cancelUpload cancels any queued file. The fileID parameter may be the file ID or index. // If you do not specify a fileID the current uploading file or first file in the queue is cancelled. // If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter. SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) { if (triggerErrorEvent !== false) { triggerErrorEvent = true; } this.callFlash("CancelUpload", [fileID, triggerErrorEvent]); }; // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue. // If nothing is currently uploading then nothing happens. SWFUpload.prototype.stopUpload = function () { this.callFlash("StopUpload"); }; /* ************************ * Settings methods * These methods change the SWFUpload settings. * SWFUpload settings should not be changed directly on the settings object * since many of the settings need to be passed to Flash in order to take * effect. * *********************** */ // Public: getStats gets the file statistics object. SWFUpload.prototype.getStats = function () { return this.callFlash("GetStats"); }; // Public: setStats changes the SWFUpload statistics. You shouldn't need to // change the statistics but you can. Changing the statistics does not // affect SWFUpload accept for the successful_uploads count which is used // by the upload_limit setting to determine how many files the user may upload. SWFUpload.prototype.setStats = function (statsObject) { this.callFlash("SetStats", [statsObject]); }; // Public: getFile retrieves a File object by ID or Index. If the file is // not found then 'null' is returned. SWFUpload.prototype.getFile = function (fileID) { if (typeof(fileID) === "number") { return this.callFlash("GetFileByIndex", [fileID]); } else { return this.callFlash("GetFile", [fileID]); } }; // Public: addFileParam sets a name/value pair that will be posted with the // file specified by the Files ID. If the name already exists then the // exiting value will be overwritten. SWFUpload.prototype.addFileParam = function (fileID, name, value) { return this.callFlash("AddFileParam", [fileID, name, value]); }; // Public: removeFileParam removes a previously set (by addFileParam) name/value // pair from the specified file. SWFUpload.prototype.removeFileParam = function (fileID, name) { this.callFlash("RemoveFileParam", [fileID, name]); }; // Public: setUploadUrl changes the upload_url setting. SWFUpload.prototype.setUploadURL = function (url) { this.settings.upload_url = url.toString(); this.callFlash("SetUploadURL", [url]); }; // Public: setPostParams changes the post_params setting SWFUpload.prototype.setPostParams = function (paramsObject) { this.settings.post_params = paramsObject; this.callFlash("SetPostParams", [paramsObject]); }; // Public: addPostParam adds post name/value pair. Each name can have only one value. SWFUpload.prototype.addPostParam = function (name, value) { this.settings.post_params[name] = value; this.callFlash("SetPostParams", [this.settings.post_params]); }; // Public: removePostParam deletes post name/value pair. SWFUpload.prototype.removePostParam = function (name) { delete this.settings.post_params[name]; this.callFlash("SetPostParams", [this.settings.post_params]); }; // Public: setFileTypes changes the file_types setting and the file_types_description setting SWFUpload.prototype.setFileTypes = function (types, description) { this.settings.file_types = types; this.settings.file_types_description = description; this.callFlash("SetFileTypes", [types, description]); }; // Public: setFileSizeLimit changes the file_size_limit setting SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) { this.settings.file_size_limit = fileSizeLimit; this.callFlash("SetFileSizeLimit", [fileSizeLimit]); }; // Public: setFileUploadLimit changes the file_upload_limit setting SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) { this.settings.file_upload_limit = fileUploadLimit; this.callFlash("SetFileUploadLimit", [fileUploadLimit]); }; // Public: setFileQueueLimit changes the file_queue_limit setting SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) { this.settings.file_queue_limit = fileQueueLimit; this.callFlash("SetFileQueueLimit", [fileQueueLimit]); }; // Public: setFilePostName changes the file_post_name setting SWFUpload.prototype.setFilePostName = function (filePostName) { this.settings.file_post_name = filePostName; this.callFlash("SetFilePostName", [filePostName]); }; // Public: setUseQueryString changes the use_query_string setting SWFUpload.prototype.setUseQueryString = function (useQueryString) { this.settings.use_query_string = useQueryString; this.callFlash("SetUseQueryString", [useQueryString]); }; // Public: setRequeueOnError changes the requeue_on_error setting SWFUpload.prototype.setRequeueOnError = function (requeueOnError) { this.settings.requeue_on_error = requeueOnError; this.callFlash("SetRequeueOnError", [requeueOnError]); }; // Public: setHTTPSuccess changes the http_success setting SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) { if (typeof http_status_codes === "string") { http_status_codes = http_status_codes.replace(" ", "").split(","); } this.settings.http_success = http_status_codes; this.callFlash("SetHTTPSuccess", [http_status_codes]); }; // Public: setDebugEnabled changes the debug_enabled setting SWFUpload.prototype.setDebugEnabled = function (debugEnabled) { this.settings.debug_enabled = debugEnabled; this.callFlash("SetDebugEnabled", [debugEnabled]); }; // Public: setButtonImageURL loads a button image sprite SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) { if (buttonImageURL == undefined) { buttonImageURL = ""; } this.settings.button_image_url = buttonImageURL; this.callFlash("SetButtonImageURL", [buttonImageURL]); }; // Public: setButtonDimensions resizes the Flash Movie and button SWFUpload.prototype.setButtonDimensions = function (width, height) { this.settings.button_width = width; this.settings.button_height = height; var movie = this.getMovieElement(); if (movie != undefined) { movie.style.width = width + "px"; movie.style.height = height + "px"; } this.callFlash("SetButtonDimensions", [width, height]); }; // Public: setButtonText Changes the text overlaid on the button SWFUpload.prototype.setButtonText = function (html) { this.settings.button_text = html; this.callFlash("SetButtonText", [html]); }; // Public: setButtonTextPadding changes the top and left padding of the text overlay SWFUpload.prototype.setButtonTextPadding = function (left, top) { this.settings.button_text_top_padding = top; this.settings.button_text_left_padding = left; this.callFlash("SetButtonTextPadding", [left, top]); }; // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button SWFUpload.prototype.setButtonTextStyle = function (css) { this.settings.button_text_style = css; this.callFlash("SetButtonTextStyle", [css]); }; // Public: setButtonDisabled disables/enables the button SWFUpload.prototype.setButtonDisabled = function (isDisabled) { this.settings.button_disabled = isDisabled; this.callFlash("SetButtonDisabled", [isDisabled]); }; // Public: setButtonAction sets the action that occurs when the button is clicked SWFUpload.prototype.setButtonAction = function (buttonAction) { this.settings.button_action = buttonAction; this.callFlash("SetButtonAction", [buttonAction]); }; // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button SWFUpload.prototype.setButtonCursor = function (cursor) { this.settings.button_cursor = cursor; this.callFlash("SetButtonCursor", [cursor]); }; /* ******************************* Flash Event Interfaces These functions are used by Flash to trigger the various events. All these functions a Private. Because the ExternalInterface library is buggy the event calls are added to a queue and the queue then executed by a setTimeout. This ensures that events are executed in a determinate order and that the ExternalInterface bugs are avoided. ******************************* */ SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) { // Warning: Don't call this.debug inside here or you'll create an infinite loop if (argumentArray == undefined) { argumentArray = []; } else if (!(argumentArray instanceof Array)) { argumentArray = [argumentArray]; } var self = this; if (typeof this.settings[handlerName] === "function") { // Queue the event this.eventQueue.push(function () { this.settings[handlerName].apply(this, argumentArray); }); // Execute the next queued event setTimeout(function () { self.executeNextEvent(); }, 0); } else if (this.settings[handlerName] !== null) { throw "Event handler " + handlerName + " is unknown or is not a function"; } }; // Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout // we must queue them in order to garentee that they are executed in order. SWFUpload.prototype.executeNextEvent = function () { // Warning: Don't call this.debug inside here or you'll create an infinite loop var f = this.eventQueue ? this.eventQueue.shift() : null; if (typeof(f) === "function") { f.apply(this); } }; // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have // properties that contain characters that are not valid for JavaScript identifiers. To work around this // the Flash Component escapes the parameter names and we must unescape again before passing them along. SWFUpload.prototype.unescapeFilePostParams = function (file) { var reg = /[$]([0-9a-f]{4})/i; var unescapedPost = {}; var uk; if (file != undefined) { for (var k in file.post) { if (file.post.hasOwnProperty(k)) { uk = k; var match; while ((match = reg.exec(uk)) !== null) { uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16))); } unescapedPost[uk] = file.post[k]; } } file.post = unescapedPost; } return file; }; SWFUpload.prototype.flashReady = function () { // Check that the movie element is loaded correctly with its ExternalInterface methods defined var movieElement = this.getMovieElement(); // Pro-actively unhook all the Flash functions if (typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)"); for (var key in movieElement) { try { if (typeof(movieElement[key]) === "function") { movieElement[key] = null; } } catch (ex) { } } } this.queueEvent("swfupload_loaded_handler"); }; /* This is a chance to do something before the browse window opens */ SWFUpload.prototype.fileDialogStart = function () { this.queueEvent("file_dialog_start_handler"); }; /* Called when a file is successfully added to the queue. */ SWFUpload.prototype.fileQueued = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("file_queued_handler", file); }; /* Handle errors that occur when an attempt to queue a file fails. */ SWFUpload.prototype.fileQueueError = function (file, errorCode, message) { file = this.unescapeFilePostParams(file); this.queueEvent("file_queue_error_handler", [file, errorCode, message]); }; /* Called after the file dialog has closed and the selected files have been queued. You could call startUpload here if you want the queued files to begin uploading immediately. */ SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued) { this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued]); }; SWFUpload.prototype.uploadStart = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("return_upload_start_handler", file); }; SWFUpload.prototype.returnUploadStart = function (file) { var returnValue; if (typeof this.settings.upload_start_handler === "function") { file = this.unescapeFilePostParams(file); returnValue = this.settings.upload_start_handler.call(this, file); } else if (this.settings.upload_start_handler != undefined) { throw "upload_start_handler must be a function"; } // Convert undefined to true so if nothing is returned from the upload_start_handler it is // interpretted as 'true'. if (returnValue === undefined) { returnValue = true; } returnValue = !!returnValue; this.callFlash("ReturnUploadStart", [returnValue]); }; SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]); }; SWFUpload.prototype.uploadError = function (file, errorCode, message) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_error_handler", [file, errorCode, message]); }; SWFUpload.prototype.uploadSuccess = function (file, serverData) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_success_handler", [file, serverData]); }; SWFUpload.prototype.uploadComplete = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_complete_handler", file); }; /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the internal debug console. You can override this event and have messages written where you want. */ SWFUpload.prototype.debug = function (message) { this.queueEvent("debug_handler", message); }; /* ********************************** Debug Console The debug console is a self contained, in page location for debug message to be sent. The Debug Console adds itself to the body if necessary. The console is automatically scrolled as messages appear. If you are using your own debug handler or when you deploy to production and have debug disabled you can remove these functions to reduce the file size and complexity. ********************************** */ // Private: debugMessage is the default debug_handler. If you want to print debug messages // call the debug() function. When overriding the function your own function should // check to see if the debug setting is true before outputting debug information. SWFUpload.prototype.debugMessage = function (message) { if (this.settings.debug) { var exceptionMessage, exceptionValues = []; // Check for an exception object and print it nicely if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") { for (var key in message) { if (message.hasOwnProperty(key)) { exceptionValues.push(key + ": " + message[key]); } } exceptionMessage = exceptionValues.join("\n") || ""; exceptionValues = exceptionMessage.split("\n"); exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: "); SWFUpload.Console.writeLine(exceptionMessage); } else { SWFUpload.Console.writeLine(message); } } }; SWFUpload.Console = {}; SWFUpload.Console.writeLine = function (message) { var console, documentForm; try { console = document.getElementById("SWFUpload_Console"); if (!console) { documentForm = document.createElement("form"); document.getElementsByTagName("body")[0].appendChild(documentForm); console = document.createElement("textarea"); console.id = "SWFUpload_Console"; console.style.fontFamily = "monospace"; console.setAttribute("wrap", "off"); console.wrap = "off"; console.style.overflow = "auto"; console.style.width = "700px"; console.style.height = "350px"; console.style.margin = "5px"; documentForm.appendChild(console); } console.value += message + "\n"; console.scrollTop = console.scrollHeight - console.clientHeight; } catch (ex) { alert("Exception: " + ex.name + " Message: " + ex.message); } };
holmes2136/ShopCart
Components/Upload/swfupload/swfupload.js
JavaScript
mit
35,885
iD.ui.Scale = function(context) { var projection = context.projection, imperial = (iD.detect().locale.toLowerCase() === 'en-us'), maxLength = 180, tickHeight = 8; function scaleDefs(loc1, loc2) { var lat = (loc2[1] + loc1[1]) / 2, conversion = (imperial ? 3.28084 : 1), dist = iD.geo.lonToMeters(loc2[0] - loc1[0], lat) * conversion, scale = { dist: 0, px: 0, text: '' }, buckets, i, val, dLon; if (imperial) { buckets = [5280000, 528000, 52800, 5280, 500, 50, 5, 1]; } else { buckets = [5000000, 500000, 50000, 5000, 500, 50, 5, 1]; } // determine a user-friendly endpoint for the scale for (i = 0; i < buckets.length; i++) { val = buckets[i]; if (dist >= val) { scale.dist = Math.floor(dist / val) * val; break; } } dLon = iD.geo.metersToLon(scale.dist / conversion, lat); scale.px = Math.round(projection([loc1[0] + dLon, loc1[1]])[0]); if (imperial) { if (scale.dist >= 5280) { scale.dist /= 5280; scale.text = String(scale.dist) + ' mi'; } else { scale.text = String(scale.dist) + ' ft'; } } else { if (scale.dist >= 1000) { scale.dist /= 1000; scale.text = String(scale.dist) + ' km'; } else { scale.text = String(scale.dist) + ' m'; } } return scale; } function update(selection) { // choose loc1, loc2 along bottom of viewport (near where the scale will be drawn) var dims = context.map().dimensions(), loc1 = projection.invert([0, dims[1]]), loc2 = projection.invert([maxLength, dims[1]]), scale = scaleDefs(loc1, loc2); selection.select('#scalepath') .attr('d', 'M0.5,0.5v' + tickHeight + 'h' + scale.px + 'v-' + tickHeight); selection.select('#scaletext') .attr('x', scale.px + 8) .attr('y', tickHeight) .text(scale.text); } return function(selection) { var g = selection.append('svg') .attr('id', 'scale') .append('g') .attr('transform', 'translate(10,11)'); g.append('path').attr('id', 'scalepath'); g.append('text').attr('id', 'scaletext'); update(selection); context.map().on('move.scale', function() { update(selection); }); }; };
daumann/chronas-application
umap/static/js/id/ui/scale.js
JavaScript
mit
2,636
import actions from './actions' import templates from './templates' const jasonette = { $jason: { head: { title: '{ ˃̵̑ᴥ˂̵̑}', actions: actions, templates: templates } } } export { actions, templates, jasonette }
brad/jasonette-webpack-plugin
test/files/source.jasonette.js
JavaScript
mit
254
'use strict'; angular .module('efg.responsiveService', ['ng']) .factory('responsive', function() { var assetprefix = '/assets/img/'; return { assetprefix: assetprefix, isimage: function(path) { return /\.(jpg|jpeg|png|gif)$/.test(path); }, isasset: function(path) { return path.indexOf(assetprefix) === 0; } }; });
dominikschreiber/efg-ludwigshafen.de
src/js/common/efg.responsiveService/efg.responsiveService.js
JavaScript
mit
380
/** * @desc Takes in an unformatted date string and formats it */ Handlebars.registerHelper('formatDateShort', function(dateStr, options) { var result = moment( dateStr ).format( 'MMM Do' ); return result; //return new Handlebars.SafeString( result ); });
alexanderscott/handlebars-helpers
formatDateShort.js
JavaScript
mit
278
// TYPE <form/short> TEST("The form's data is returned.", function(Query) { var example = { "owner": "person", "audience": { "fill": "anyone" }, "label": "Personal information", "custom": [1,2,3], "fields": [ { "id": "1", "label": "Why did you join our group ?", "kind": "text", "required": true }, { "id": "2", "label": "How often do you log in ?", "kind": "single", "choices" : [ "Every day", "Once a week", "Once a month", "Less than once a month" ], "required": false } ] }; var db = Query.mkdb(); var auth = Query.auth(db); return Query.post(["db/",db,"/forms"],example,auth).id().then(function(id) { var form = Query.get(["db/",db,"/forms"],auth).then(function(d,s,r) { return d.list[0]; }); var expected = { "id": id, "label": example.label, "owner": example.owner, "fields": 2, "access": ["admin","fill"] }; return Assert.areEqual(expected,form); }); });
RunOrg/RunOrg
test/form/short.js
JavaScript
mit
1,001
app.controller('searchCustomerController', function ($scope, $location, $rootScope, $modal, $timeout, maskFactory, paginationFactory, customerService, toast) { angular.extend($scope, maskFactory); angular.extend($scope, paginationFactory); $scope.isShow = true; $scope.edit = function (id) { $location.path('/edit-customer/' + id); }; $scope.search = function () { $rootScope.isBusy = true; $scope.itens = []; customerService.count($scope.nameCustomer, $scope.cpfCnpjCustomer, $scope.typeCustomer, null, null) .then(function (total) { if ($scope.validateSize(total.count)) { getList(); $rootScope.isBusy = false; } else { $rootScope.isBusy = false; $scope.isShow = false; } }); }; function getList() { customerService.search($scope.nameCustomer, $scope.cpfCnpjCustomer, $scope.typeCustomer, $scope.firstResult, $scope.maxResults).then(function (response) { $scope.itens = response; }); } $scope.search(); $scope.clear = function () { $scope.nameCustomer = $scope.cpfCnpjCustomer = $scope.typeCustomer = undefined; getList(); }; $scope.pageChanged = function (value) { $scope.firstResult = value; $scope.search(); }; $scope.remove = function (item) { var modalInstance = $modal.open({ templateUrl: 'app/src/module/customer/template/customer.delete.html', size: 'sm', controller: 'deleteCustomerController', resolve: { customer: function () { return item; } } }); modalInstance.result.then(function (response) { toast.open(response.type, response.msg); if(response.type != 'danger') { $scope.search(); } }); }; });
dfslima/portalCliente
src/main/webapp/app/src/module/customer/controllers/customer.search.js
JavaScript
mit
2,038
/** * Each section of the site has its own module. It probably also has * submodules, though this boilerplate is too simple to demonstrate it. Within * `src/app/home`, however, could exist several additional folders representing * additional modules that would then be listed as dependencies of this one. * For example, a `note` section could have the submodules `note.create`, * `note.delete`, `note.edit`, etc. * * Regardless, so long as dependencies are managed correctly, the build process * will automatically take take of the rest. * * The dependencies block here is also where component dependencies should be * specified, as shown below. */ angular.module( 'bigboldwords.user_create', [ 'ui.router', 'titleService', 'plusOne', 'passwordVerify' ]) /** * Each section or module of the site can also have its own routes. AngularJS * will handle ensuring they are all available at run-time, but splitting it * this way makes each module more "self-contained". */ .config(function config( $stateProvider ) { $stateProvider.state( 'user_create', { url: '/user/create', views: { "main": { controller: 'UserCreateCtrl', templateUrl: 'user_create/user_create.tpl.html' } } }); }) /** * And of course we define a controller for our route. */ .controller( 'UserCreateCtrl', function UserCreateCtrl( $scope, titleService, $stateParams, myAuthService ) { titleService.setTitle( 'User Create' ); $scope.buttonText = "Create"; $scope.disableForm = false; $scope.createUser = function(user) { /*if ($scope.form.$valid) { $scope.buttonText = "Submitting"; $scope.showErrors = false; $scope.disableForm = true; } else { $scope.showErrors = true; }*/ var callback = function() { console.log("Go to this other page"); //$location.path("//" + response.id); }; myAuthService.createUser(user, callback); }; }) ;
donmasakayan/bigboldwords
src/app/user_create/user_create.js
JavaScript
mit
1,886
import { COLORS } from '../../../constants/tetromino'; export default { color: COLORS.Z, grid: [[0, 1, 0], [1, 1, 0], [1, 0, 0]] };
ranoichman/Taramti-Mobile
Taramti-Mobile/Taramti-Mobile/src/components/Tetris/components/__fixtures__/Tetromino/rotated-Z-tetromino-3.js
JavaScript
mit
137
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import addMention from '../addMention'; import KeyDownHandler from '../../../event-handler/keyDown'; import SuggestionHandler from '../../../event-handler/suggestions'; import './styles.css'; class Suggestion { constructor(config) { const { separator, trigger, getSuggestions, onChange, getEditorState, getWrapperRef, caseSensitive, dropdownClassName, optionClassName, modalHandler, } = config; this.config = { separator, trigger, getSuggestions, onChange, getEditorState, getWrapperRef, caseSensitive, dropdownClassName, optionClassName, modalHandler, }; } findSuggestionEntities = (contentBlock, callback) => { if (this.config.getEditorState()) { const { separator, trigger, getSuggestions, getEditorState, } = this.config; const selection = getEditorState().getSelection(); if ( selection.get('anchorKey') === contentBlock.get('key') && selection.get('anchorKey') === selection.get('focusKey') ) { let text = contentBlock.getText(); text = text.substr( 0, selection.get('focusOffset') === text.length - 1 ? text.length : selection.get('focusOffset') + 1 ); let index = text.lastIndexOf(separator + trigger); let preText = separator + trigger; if ((index === undefined || index < 0) && text[0] === trigger) { index = 0; preText = trigger; } if (index >= 0) { const mentionText = text.substr(index + preText.length, text.length); const suggestionPresent = getSuggestions().some(suggestion => { if (suggestion.value) { if (this.config.caseSensitive) { return suggestion.value.indexOf(mentionText) >= 0; } return ( suggestion.value .toLowerCase() .indexOf(mentionText && mentionText.toLowerCase()) >= 0 ); } return false; }); if (suggestionPresent) { callback(index === 0 ? 0 : index + 1, text.length); } } } } }; getSuggestionComponent = getSuggestionComponent.bind(this); getSuggestionDecorator = () => ({ strategy: this.findSuggestionEntities, component: this.getSuggestionComponent(), }); } function getSuggestionComponent() { const { config } = this; return class SuggestionComponent extends Component { static propTypes = { children: PropTypes.array, }; state = { style: { left: 15 }, activeOption: -1, showSuggestions: true, }; componentDidMount() { const editorRect = config.getWrapperRef().getBoundingClientRect(); const suggestionRect = this.suggestion.getBoundingClientRect(); const dropdownRect = this.dropdown.getBoundingClientRect(); let left; let right; let bottom; if ( editorRect.width < suggestionRect.left - editorRect.left + dropdownRect.width ) { right = 15; } else { left = 15; } if (editorRect.bottom < dropdownRect.bottom) { bottom = 0; } this.setState({ // eslint-disable-line react/no-did-mount-set-state style: { left, right, bottom }, }); KeyDownHandler.registerCallBack(this.onEditorKeyDown); SuggestionHandler.open(); config.modalHandler.setSuggestionCallback(this.closeSuggestionDropdown); this.filterSuggestions(this.props); } componentDidUpdate(props) { const { children } = this.props; if (children !== props.children) { this.filterSuggestions(props); this.setState({ showSuggestions: true, }); } } componentWillUnmount() { KeyDownHandler.deregisterCallBack(this.onEditorKeyDown); SuggestionHandler.close(); config.modalHandler.removeSuggestionCallback(); } onEditorKeyDown = event => { const { activeOption } = this.state; const newState = {}; if (event.key === 'ArrowDown') { event.preventDefault(); if (activeOption === this.filteredSuggestions.length - 1) { newState.activeOption = 0; } else { newState.activeOption = activeOption + 1; } } else if (event.key === 'ArrowUp') { if (activeOption <= 0) { newState.activeOption = this.filteredSuggestions.length - 1; } else { newState.activeOption = activeOption - 1; } } else if (event.key === 'Escape') { newState.showSuggestions = false; SuggestionHandler.close(); } else if (event.key === 'Enter') { this.addMention(); } this.setState(newState); }; onOptionMouseEnter = event => { const index = event.target.getAttribute('data-index'); this.setState({ activeOption: index, }); }; onOptionMouseLeave = () => { this.setState({ activeOption: -1, }); }; setSuggestionReference = ref => { this.suggestion = ref; }; setDropdownReference = ref => { this.dropdown = ref; }; closeSuggestionDropdown = () => { this.setState({ showSuggestions: false, }); }; filteredSuggestions = []; filterSuggestions = props => { const mentionText = props.children[0].props.text.substr(1); const suggestions = config.getSuggestions(); this.filteredSuggestions = suggestions && suggestions.filter(suggestion => { if (!mentionText || mentionText.length === 0) { return true; } if (config.caseSensitive) { return suggestion.value.indexOf(mentionText) >= 0; } return ( suggestion.value .toLowerCase() .indexOf(mentionText && mentionText.toLowerCase()) >= 0 ); }); }; addMention = () => { const { activeOption } = this.state; const editorState = config.getEditorState(); const { onChange, separator, trigger } = config; const selectedMention = this.filteredSuggestions[activeOption]; if (selectedMention) { addMention(editorState, onChange, separator, trigger, selectedMention); } }; render() { const { children } = this.props; const { activeOption, showSuggestions } = this.state; const { dropdownClassName, optionClassName } = config; return ( <span className="rdw-suggestion-wrapper" ref={this.setSuggestionReference} onClick={config.modalHandler.onSuggestionClick} aria-haspopup="true" aria-label="rdw-suggestion-popup" > <span>{children}</span> {showSuggestions && ( <span className={classNames( 'rdw-suggestion-dropdown', dropdownClassName )} contentEditable="false" suppressContentEditableWarning style={this.state.style} ref={this.setDropdownReference} > {this.filteredSuggestions.map((suggestion, index) => ( <span key={index} spellCheck={false} onClick={this.addMention} data-index={index} onMouseEnter={this.onOptionMouseEnter} onMouseLeave={this.onOptionMouseLeave} className={classNames( 'rdw-suggestion-option', optionClassName, { 'rdw-suggestion-option-active': index === activeOption } )} > {suggestion.text} </span> ))} </span> )} </span> ); } }; } export default Suggestion;
jpuri/react-draft-wysiwyg
src/decorators/Mention/Suggestion/index.js
JavaScript
mit
8,211
'use strict'; describe('myApp.project module', function() { beforeEach(module('myApp.project')); describe('project controller', function(){ it('should ....', inject(function($controller) { //spec body var projectCtrl = $controller('ProjectCtrl'); expect(projectCtrl).toBeDefined(); })); }); });
BrianKolowitz/infsci2710
app/project/project_test.js
JavaScript
mit
331
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var fs = require('fs'); var AWS = require('aws-sdk'); /* * Time to do some non-default work. We are using Mongo DB and, * since this is a very simple app, Monk to interface with it. * So, lets grab both and then set up a variable to hold our * db. * * Note, this may have to change to use Amazon's db. We'll see. */ var mongo = require('mongodb'); var monk = require('monk'); var db = monk('localhost:27017/palindrome'); //Read config values from a JSON file. // var config = fs.readFileSync('./app_config.json', 'utf8'); // config = JSON.parse(config); //Create DynamoDB client and pass in region. // var db = new AWS.DynamoDB({region: config.AWS_REGION}); var routes = require('./routes/index'); var users = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); /* * Again, a bit of non-default work here. We need to make our * db accessible to our router. Again, a simple app so lets just * add the db as a param to our requests. */ app.use(function(req,res,next){ req.db = db; // req.dbTableName = config.STARTUP_SIGNUP_TABLE; next(); }); app.use('/', routes); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
shawncross/palindromeatrest
app.js
JavaScript
mit
2,398
import express from 'express'; import logger from 'morgan'; import bodyParser from 'body-parser'; import cookieParser from 'cookie-parser'; import compress from 'compression'; import busboy from 'connect-busboy'; import methodOverride from 'method-override'; import cors from 'cors'; import httpStatus from 'http-status'; import expressWinston from 'express-winston'; import expressValidation from 'express-validation'; import helmet from 'helmet'; import winstonInstance from './winston'; import routes from '../server/routes/index.route'; import robotCtrl from '../server/controllers/robot.controller'; import config from './config'; import APIError from '../server/helpers/APIError'; import path from 'path'; import schedule from 'node-schedule'; const app = express(); if (config.env === 'development') { app.use(logger('dev')); } // parse body params and attache them to req.body app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser()); app.use(compress()); app.use(methodOverride()); app.use('/public', express.static(path.join(__dirname, '../public'))); app.use(busboy({ limits: { fileSize: 4 * 1024 * 1024 }, })); function scheduleJob() { schedule.scheduleJob('* * 23 * * *', robotCtrl.requestFile); } scheduleJob(); // secure apps by setting various HTTP headers app.use(helmet()); // enable CORS - Cross Origin Resource Sharing app.use(cors()); // enable detailed API logging in dev env if (config.env === 'development') { expressWinston.requestWhitelist.push('body'); expressWinston.responseWhitelist.push('body'); app.use(expressWinston.logger({ winstonInstance, meta: true, // optional: log meta data about request (defaults to true) msg: 'HTTP {{req.method}} {{req.url}} {{res.statusCode}} {{res.responseTime}}ms', colorStatus: true // Color the status code (default green, 3XX cyan, 4XX yellow, 5XX red). })); } // mount all routes on /api path app.use('/api', routes); app.use('/static', express.static(path.join(__dirname, '../public'))); // if error is not an instanceOf APIError, convert it. app.use((err, req, res, next) => { if (err instanceof expressValidation.ValidationError) { return res.json({ status: 'err', msg: '参数错误' }); /*console.log('err = ',err); // validation error contains errors which is an array of error each containing message[] const unifiedErrorMessage = err.errors.map(error => error.messages.join('. ')).join(' and '); const error = new APIError(unifiedErrorMessage, err.status, true); return next(error);*/ } else if (!(err instanceof APIError)) { const apiError = new APIError(err.message, err.status, err.isPublic); return next(apiError); } return next(err); }); // catch 404 and forward to error handler app.use((req, res, next) => { const err = new APIError('API not found', httpStatus.NOT_FOUND); return next(err); }); // log error in winston transports except when executing test suite if (config.env !== 'test') { app.use(expressWinston.errorLogger({ winstonInstance })); } // error handler, send stacktrace only during development app.use((err, req, res, next) => // eslint-disable-line no-unused-vars res.status(err.status).json({ message: err.isPublic ? err.message : httpStatus[err.status], stack: config.env === 'development' ? err.stack : {} }) ); export default app;
ShenYiQian/node_test
config/express.js
JavaScript
mit
3,408
import PouchDB from 'pouchdb'; class DictionaryDatabase{ constructor(){ this.db = new PouchDB('dictionary-database'); } addWord(payload){ this.db.put({ _id : payload.word, definition : payload.definition },function(err,response){ if(!err){ console.log(response); }else{ console.log(err); } }); }; get(word){ return this.db.get(word); } allWords(){ return this.db.allDocs(); } }; export default DictionaryDatabase;
bhargav175/dictionary-offline
app/client/database/index.js
JavaScript
mit
466
var should = require('should'); var api = require('../../app/util/dataApi'); var alpha = require('../../../shared/cardConf'); describe('JSON data api test', function() { var map = api.map; it('should get equip ids', function() { var equipId = '5101'; var item = api.equip.findBy('equip_id', equipId); var s = item.initial; var t = 51; // game_master.equip_data.equip_id whith equip_id = 2504 s.should.eql(t); }); it('should get map ids', function() { var mapId = 2; var item = api.map.findBy('map_id', mapId); var ids = item.ids; var serialIds = [6,7,8,9,10,11]; //console.log(item); //console.log(ids); ids.should.eql(serialIds); }); it('should get nature ids', function() { var natureId = '10161'; var item = api.nature.findBy('nature_id', natureId); var condition = item.condition; var c = [1101, 1102]; // game_master.nature_condition.card_id whith nature_id = 10161 condition.should.eql(c); //should.strictEqual(undefined, item); }); it('should get pet ids', function() { var petId = '2504'; var item = api.pet.findBy('pet_id', petId); var s = item.star; var t = 5; // game_master.pet_data.pet_id whith pet_id = 2504 s.should.eql(t); //should.strictEqual(undefined, item); }); it('should get petSkill id', function() { var skillId = '4601'; var item = api.petSkill.findBy('skill_id', skillId); var s = item["2"].debuff; //console.log(item["2"]); var t = 5880; // game_master.pet_skill_effect.debuff with skill_id = 4601 s.should.eql(t); //should.strictEqual(undefined, item); }); it('should get skill id', function() { var skillId = '3005'; var item = api.skill.findBy('skill_id', skillId); var s = item["2"].effect; //console.log(item["2"]); var t = 18; // game_master.skill_data.effect with skill_id = 3005 s.should.eql(t); //should.strictEqual(undefined, item); }); it('should get skill id', function() { var skillId = '3007'; var item = api.skill.findBy('skill_id', skillId); var s = item["2"].effect; //console.log(item["2"]); var t = 28; // game_master.skill_data.effect with skill_id = 3005 s.should.eql(t); //should.strictEqual(undefined, item); }); it('should get skill id', function() { var skillId = '3010'; var item = api.skill.findBy('skill_id', skillId); var s = item["2"].effect; //console.log(item["2"]); var t = 16; // game_master.skill_data.effect with skill_id = 3005 s.should.eql(t); //should.strictEqual(undefined, item); }); it('should get card id', function() { var cardId = '1311'; var item = api.card.findBy('card_id', cardId); var s = item.star; var t = 3; // game_master.skill_data.effect with skill_id = 3005 s.should.eql(t); //should.strictEqual(undefined, item); //console.log(alpha.cardConf(item.star)); }); it('should get item id', function() { var itemId = 8002; var item = api.item.findBy('item_id', itemId); console.log(item); var s = item.star; var t = 4; // game_master.item_data.star with item_id = 8002 s.should.eql(t); }); });
iamcactus/rpg
game-server/test/util/01_dataApi.js
JavaScript
mit
3,188
'use strict'; // Configuring the Articles module angular.module('players').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'New Player', 'players/create'); } ]);
dylanjohnson/fantasy-sports-tools
public/modules/players/config/players.client.config.js
JavaScript
mit
207
/*! m.js v0.4.3 | Copyright (C) 2015 Mengma | Released under the MIT License */ ;(function(l,a,b){b(l);l.M=a()})(this,function(){function l(a){this.model=a;this.box={}}if("function"!==typeof window.jQuery)throw Error("M requires jQuery");l.prototype={is:function(a){var b=!1;"string"===typeof a&&(a=a.split(","));for(var m in a)if(this.model===a[m].trim()){b=!0;break}return b},not:function(a){return!this.is(a)},open:function(a,b){"undefined"!==typeof b&&(this.box[a]=b);return this.box[a]},close:function(a){this.box[a]=void 0;return!1}};l.ua=window.navigator.userAgent;l.mobile=/Mobile/.test(l.ua); l.ie=/MSIE/.test(l.ua);l.chrome=/Chrome/.test(l.ua)||/Chromium/.test(l.ua);l.safari=!l.chrome&&/Safari/.test(l.ua);l.firefox=/Firefox/.test(l.ua);l.opera=/Opera/.test(l.ua);l.ajax=function(a,b,m,p){return window.jQuery.ajax({url:a,type:"POST",data:b,dataType:"json",timeout:1E4,success:m,error:p})};l.storage={stack:window.localStorage||{},set:function(a,b){window.localStorage?l.storage.stack.setItem(a,b):l.storage.stack[a]=b},get:function(a){return window.localStorage?l.storage.stack.getItem(a):l.storage.stack[a]}, del:function(a){window.localStorage?l.storage.stack.removeItem(a):l.storage.stack[a]=void 0}};l.each=function(a,b){for(var m in a)if("function"===typeof b)a[m]=b(a[m]);else throw Error("Callback should be a function");return a};l.crypto={md5:function(a){function b(a,c){var d,k,e,g,f;e=a&2147483648;g=c&2147483648;d=a&1073741824;k=c&1073741824;f=(a&1073741823)+(c&1073741823);return d&k?f^2147483648^e^g:d|k?f&1073741824?f^3221225472^e^g:f^1073741824^e^g:f^e^g}function m(a,c,d,e,f,k,g){a=b(a,b(b(c&d| ~c&e,f),g));return b(a<<k|a>>>32-k,c)}function p(a,c,d,e,k,f,g){a=b(a,b(b(c&e|d&~e,k),g));return b(a<<f|a>>>32-f,c)}function c(a,c,d,e,f,k,g){a=b(a,b(b(c^d^e,f),g));return b(a<<k|a>>>32-k,c)}function n(a,c,d,e,k,f,g){a=b(a,b(b(d^(c|~e),k),g));return b(a<<f|a>>>32-f,c)}function q(a){var c="",f="",d;for(d=0;3>=d;d++)f=a>>>8*d&255,f="0"+f.toString(16),c+=f.substr(f.length-2,2);return c}var e=[],r,l,w,x,k,g,f,d;a=function(a){a=a.replace(/\r\n/g,"\n");for(var c="",f=0;f<a.length;f++){var d=a.charCodeAt(f); 128>d?c+=String.fromCharCode(d):(127<d&&2048>d?c+=String.fromCharCode(d>>6|192):(c+=String.fromCharCode(d>>12|224),c+=String.fromCharCode(d>>6&63|128)),c+=String.fromCharCode(d&63|128))}return c}(a);e=function(a){var c,d=a.length;c=d+8;for(var f=16*((c-c%64)/64+1),e=Array(f-1),k=0,g=0;g<d;)c=(g-g%4)/4,k=g%4*8,e[c]|=a.charCodeAt(g)<<k,g++;c=(g-g%4)/4;e[c]|=128<<g%4*8;e[f-2]=d<<3;e[f-1]=d>>>29;return e}(a);k=1732584193;g=4023233417;f=2562383102;d=271733878;for(a=0;a<e.length;a+=16)r=k,l=g,w=f,x=d,k= m(k,g,f,d,e[a+0],7,3614090360),d=m(d,k,g,f,e[a+1],12,3905402710),f=m(f,d,k,g,e[a+2],17,606105819),g=m(g,f,d,k,e[a+3],22,3250441966),k=m(k,g,f,d,e[a+4],7,4118548399),d=m(d,k,g,f,e[a+5],12,1200080426),f=m(f,d,k,g,e[a+6],17,2821735955),g=m(g,f,d,k,e[a+7],22,4249261313),k=m(k,g,f,d,e[a+8],7,1770035416),d=m(d,k,g,f,e[a+9],12,2336552879),f=m(f,d,k,g,e[a+10],17,4294925233),g=m(g,f,d,k,e[a+11],22,2304563134),k=m(k,g,f,d,e[a+12],7,1804603682),d=m(d,k,g,f,e[a+13],12,4254626195),f=m(f,d,k,g,e[a+14],17,2792965006), g=m(g,f,d,k,e[a+15],22,1236535329),k=p(k,g,f,d,e[a+1],5,4129170786),d=p(d,k,g,f,e[a+6],9,3225465664),f=p(f,d,k,g,e[a+11],14,643717713),g=p(g,f,d,k,e[a+0],20,3921069994),k=p(k,g,f,d,e[a+5],5,3593408605),d=p(d,k,g,f,e[a+10],9,38016083),f=p(f,d,k,g,e[a+15],14,3634488961),g=p(g,f,d,k,e[a+4],20,3889429448),k=p(k,g,f,d,e[a+9],5,568446438),d=p(d,k,g,f,e[a+14],9,3275163606),f=p(f,d,k,g,e[a+3],14,4107603335),g=p(g,f,d,k,e[a+8],20,1163531501),k=p(k,g,f,d,e[a+13],5,2850285829),d=p(d,k,g,f,e[a+2],9,4243563512), f=p(f,d,k,g,e[a+7],14,1735328473),g=p(g,f,d,k,e[a+12],20,2368359562),k=c(k,g,f,d,e[a+5],4,4294588738),d=c(d,k,g,f,e[a+8],11,2272392833),f=c(f,d,k,g,e[a+11],16,1839030562),g=c(g,f,d,k,e[a+14],23,4259657740),k=c(k,g,f,d,e[a+1],4,2763975236),d=c(d,k,g,f,e[a+4],11,1272893353),f=c(f,d,k,g,e[a+7],16,4139469664),g=c(g,f,d,k,e[a+10],23,3200236656),k=c(k,g,f,d,e[a+13],4,681279174),d=c(d,k,g,f,e[a+0],11,3936430074),f=c(f,d,k,g,e[a+3],16,3572445317),g=c(g,f,d,k,e[a+6],23,76029189),k=c(k,g,f,d,e[a+9],4,3654602809), d=c(d,k,g,f,e[a+12],11,3873151461),f=c(f,d,k,g,e[a+15],16,530742520),g=c(g,f,d,k,e[a+2],23,3299628645),k=n(k,g,f,d,e[a+0],6,4096336452),d=n(d,k,g,f,e[a+7],10,1126891415),f=n(f,d,k,g,e[a+14],15,2878612391),g=n(g,f,d,k,e[a+5],21,4237533241),k=n(k,g,f,d,e[a+12],6,1700485571),d=n(d,k,g,f,e[a+3],10,2399980690),f=n(f,d,k,g,e[a+10],15,4293915773),g=n(g,f,d,k,e[a+1],21,2240044497),k=n(k,g,f,d,e[a+8],6,1873313359),d=n(d,k,g,f,e[a+15],10,4264355552),f=n(f,d,k,g,e[a+6],15,2734768916),g=n(g,f,d,k,e[a+13],21, 1309151649),k=n(k,g,f,d,e[a+4],6,4149444226),d=n(d,k,g,f,e[a+11],10,3174756917),f=n(f,d,k,g,e[a+2],15,718787259),g=n(g,f,d,k,e[a+9],21,3951481745),k=b(k,r),g=b(g,l),f=b(f,w),d=b(d,x);return(q(k)+q(g)+q(f)+q(d)).toLowerCase()},sha256:function(a){function b(a,c){var b=(a&65535)+(c&65535);return(a>>16)+(c>>16)+(b>>16)<<16|b&65535}function m(a,c){return a>>>c|a<<32-c}a=function(a){a=a.replace(/\r\n/g,"\n");for(var c="",b=0;b<a.length;b++){var m=a.charCodeAt(b);128>m?c+=String.fromCharCode(m):(127<m&& 2048>m?c+=String.fromCharCode(m>>6|192):(c+=String.fromCharCode(m>>12|224),c+=String.fromCharCode(m>>6&63|128)),c+=String.fromCharCode(m&63|128))}return c}(a);return function(a){for(var c="",b=0;b<4*a.length;b++)c+="0123456789abcdef".charAt(a[b>>2]>>8*(3-b%4)+4&15)+"0123456789abcdef".charAt(a[b>>2]>>8*(3-b%4)&15);return c}(function(a,c){var n=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103, 3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187, 3204031479,3329325298],l=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],e=Array(64),r,y,w,x,k,g,f,d,z,t,u,v;a[c>>5]|=128<<24-c%32;a[(c+64>>9<<4)+15]=c;for(z=0;z<a.length;z+=16){r=l[0];y=l[1];w=l[2];x=l[3];k=l[4];g=l[5];f=l[6];d=l[7];for(t=0;64>t;t++){if(16>t)e[t]=a[t+z];else{u=t;v=e[t-2];v=m(v,17)^m(v,19)^v>>>10;v=b(v,e[t-7]);var A=e[t-15],A=m(A,7)^m(A,18)^A>>>3;e[u]=b(b(v,A),e[t-16])}u=k;u=m(u,6)^m(u,11)^m(u,25);u=b(b(b(b(d,u),k&g^~k&f),n[t]),e[t]);d=r;d= m(d,2)^m(d,13)^m(d,22);v=b(d,r&y^r&w^y&w);d=f;f=g;g=k;k=b(x,u);x=w;w=y;y=r;r=b(u,v)}l[0]=b(r,l[0]);l[1]=b(y,l[1]);l[2]=b(w,l[2]);l[3]=b(x,l[3]);l[4]=b(k,l[4]);l[5]=b(g,l[5]);l[6]=b(f,l[6]);l[7]=b(d,l[7])}return l}(function(a){for(var c=[],b=0;b<8*a.length;b+=8)c[b>>5]|=(a.charCodeAt(b/8)&255)<<24-b%32;return c}(a),8*a.length))},base64:{encode:function(a){var b,m,l,c,n=0,q=0,e="",e=[];if(!a)return a;do b=a.charCodeAt(n++),m=a.charCodeAt(n++),l=a.charCodeAt(n++),c=b<<16|m<<8|l,b=c>>18&63,m=c>>12&63, l=c>>6&63,c&=63,e[q++]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(b)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(m)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(l)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(c);while(n<a.length);e=e.join("");a=a.length%3;return(a?e.slice(0,a-3):e)+"===".slice(a||3)},decode:function(a){var b,m,l,c,n,q=0,e=0;c="";var r=[];if(!a)return a;a+=""; do b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(q++)),m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(q++)),c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(q++)),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(q++)),l=b<<18|m<<12|c<<6|n,b=l>>16&255,m=l>>8&255,l&=255,64==c?r[e++]=String.fromCharCode(b):64==n?r[e++]=String.fromCharCode(b,m):r[e++]= String.fromCharCode(b,m,l);while(q<a.length);return c=r.join("")}}};l.htmlspecialchars=function(a){a=a.replace(/&/g,"&amp;");a=a.replace(/</g,"&lt;");a=a.replace(/>/g,"&gt;");a=a.replace(/"/g,"&quot;");return a=a.replace(/'/g,"&#039;")};l.url={search:function(){var a={};l.each(window.location.search.slice(1).split("&"),function(b){b&&(a[b.split("=")[0]]=b.split("=")[1])});return a}(),location:function(a){if("string"===typeof window.location.hash)if("string"===typeof a)window.location.hash=a;else return window.location.hash.slice(1); else return window.location.href.split("#")[1]}};l.cookie={set:function(a,b,m,l,c,n){document.cookie=a+"="+(n?b:escape(b))+(c?"; expires="+c.toGMTString():"")+(l?"; path="+l:"; path=/")+(m?"; domain="+m:"")},get:function(a,b){var m=document.cookie.match(new RegExp("(^| )"+a+"=([^;]*)(;|$)"));return null!=m?unescape(m[2]):b},clear:function(a,b,m){this.get(a)&&(document.cookie=a+"="+(b?"; path="+b:"; path=/")+(m?"; domain="+m:"")+";expires=Fri, 02-Jan-1970 00:00:00 GMT")}};l.status={list:{100:["\u90ae\u7bb1\u9a8c\u8bc1\u6210\u529f", ""],101:["\u90ae\u7bb1\u9a8c\u8bc1\u5931\u8d25","\u5df2\u9a8c\u8bc1"],102:["\u90ae\u7bb1\u9a8c\u8bc1\u5931\u8d25","\u90ae\u7bb1\u5730\u5740\u4e3a\u7a7a"],103:["\u90ae\u7bb1\u9a8c\u8bc1\u5931\u8d25","\u90ae\u7bb1\u6821\u9a8c\u7801\u5931\u6548"],104:["\u4fe1\u606f\u83b7\u53d6\u5931\u8d25","\u5f53\u524d\u4f1a\u8bdd\u5931\u6548"],105:["\u4fe1\u606f\u83b7\u53d6\u5931\u8d25","\u7528\u6237\u4fe1\u606f\u83b7\u53d6\u9519\u8bef"],106:["\u6ce8\u518c\u5931\u8d25","\u90ae\u7bb1\u4e0d\u7b26\u5408\u89c4\u5219"], 107:["\u6ce8\u518c\u5931\u8d25","\u9a8c\u8bc1\u7801\u4e0d\u6b63\u786e"],108:["\u6ce8\u518c\u5931\u8d25","\u8bf7\u6c42\u65b9\u5f0f\u9519\u8bef"],109:["\u6ce8\u518c\u5931\u8d25","\u90ae\u7bb1\u5df2\u88ab\u6ce8\u518c"],110:["\u6ce8\u518c\u6210\u529f",""],111:["\u6ce8\u518c\u5931\u8d25","\u7f51\u7edc\u51fa\u73b0\u95ee\u9898"],112:["\u6ce8\u518c\u5931\u8d25","\u8bf7\u6c42\u65b9\u5f0f\u9519\u8bef"],113:["\u767b\u9646\u5931\u8d25","\u8bf7\u6c42\u65b9\u5f0f\u9519\u8bef"],114:["\u767b\u5f55\u5931\u8d25","\u90ae\u7bb1\u672a\u6ce8\u518c"], 115:["\u767b\u5f55\u5931\u8d25","\u5bc6\u7801\u9519\u8bef"],116:["\u767b\u9646\u6210\u529f",""],117:["\u4fe1\u606f\u83b7\u53d6\u5931\u8d25","\u7528\u6237\u4e0d\u5b58\u5728"],118:["\u767b\u9646\u5931\u8d25","\u8d26\u53f7\u672a\u9a8c\u8bc1"],119:["\u90ae\u7bb1\u9a8c\u8bc1\u5931\u8d25","\u4e0d\u9700\u8981\u9a8c\u8bc1"],120:["\u90ae\u7bb1\u9a8c\u8bc1\u5931\u8d25","\u90ae\u7bb1\u4e0d\u5b58\u5728"],121:["\u767b\u9646\u5931\u8d25","\u8d26\u53f7\u5f02\u5e38"]},getTitle:function(a){return l.status.list[a][0]}, getReason:function(a){return l.status.list[a][1]}};l.alert=function(a){return Phenix.init(a).show()};l.form=function(a){a=a?a:{};var b=a.id||"form";jQuery(b).attr("novalidate","");var m=["\u8fd9\u4e2a\u90ae\u7bb1\u8fd8\u6ca1\u6709\u6ce8\u518c\u54e6","\u5bc6\u7801\u9519\u8bef","\u9a8c\u8bc1\u7801\u8f93\u5165\u9519\u8bef","Email\u8f93\u5165\u9519\u8bef","Email\u5730\u5740\u5df2\u88ab\u4f7f\u7528"],p={maxLength:function(a,c){c=parseInt(c);return function(){a.val().length>c&&a.val(a.val().substring(0, c))}},minLength:function(a,e){e=parseInt(e);return function(){a.val().length<e?c(a,"\u957f\u5ea6\u4e0d\u80fd\u5c0f\u4e8e"+e+"\u4f4d"):n(a,"\u957f\u5ea6\u4e0d\u80fd\u5c0f\u4e8e"+e+"\u4f4d")}},equalTo:function(a,e){jQuery(e).on("blur",function(){a.trigger("input")});return function(){a.val()!==jQuery(e).val()?c(a,"\u4e24\u6b21\u8f93\u5165\u7684\u5bc6\u7801\u4e0d\u76f8\u540c"):n(a,"\u4e24\u6b21\u8f93\u5165\u7684\u5bc6\u7801\u4e0d\u76f8\u540c")}},email:function(a){return function(){/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/.test(a.val())? n(a,"\u90ae\u4ef6\u683c\u5f0f\u9519\u8bef"):c(a,"\u90ae\u7bb1\u683c\u5f0f\u9519\u8bef")}},require:function(a){return function(){""==a.val()?c(a,"\u8fd9\u91cc\u4e0d\u80fd\u4e3a\u7a7a\u54e6"):n(a,"\u8fd9\u91cc\u4e0d\u80fd\u4e3a\u7a7a\u54e6")}},clear:function(a){return function(){n(a)}}},c=function(a,c){0!==jQuery(".popover-content:visible").length&&!jQuery(".popover-content:visible").closest(".popover").prev().is(a)||a.data("content")===c||(a.popover("destroy"),a.focus().data("content",c).popover("show"))}, n=function(a,c){a.data("content")!==c&&c&&-1===jQuery.inArray(a.data("content"),m)||(a.popover("destroy"),a.data("content",""))},q=function(a){return function(){a&&a()}},e={};jQuery(b).find("input,textarea").each(function(){jQuery(this).data({trigger:"manual",placement:a.placement||"left",content:""});for(var c=jQuery(this).attr("listen-to-code")?jQuery(this).attr("listen-to-code").split(","):[],b=0;b<c.length;b++)e[c[b]]=jQuery(this);jQuery(this).attr("required")&&jQuery(this).on("input",q(p.require(jQuery(this)))); jQuery(this).attr("max-length")&&jQuery(this).on("input",q(p.maxLength(jQuery(this),jQuery(this).attr("max-length"))));jQuery(this).attr("min-length")&&jQuery(this).on("input",q(p.minLength(jQuery(this),jQuery(this).attr("min-length"))));jQuery(this).attr("equal-to")&&jQuery(this).on("input",q(p.equalTo(jQuery(this),jQuery(this).attr("equal-to"))));"email"===jQuery(this).attr("type")&&jQuery(this).on("blur",q(p.email(jQuery(this)))).on("keyup",q(p.clear(jQuery(this))))});jQuery(b).submit(function(b){b.preventDefault(); jQuery(this).find("input,textarea").trigger("input");if(0!==jQuery(".popover-content:visible").length)jQuery(".popover-content:visible").closest(".popover").prev().focus();else{var m=!0,n={};jQuery(this).find("input,textarea").each(function(){jQuery(this).attr("required")&&m&&!jQuery(this).val()&&(m=!1,c(jQuery(this),"\u8fd9\u91cc\u4e0d\u80fd\u4e3a\u7a7a\u54e6"));jQuery(this).attr&&(n[jQuery(this).attr("name")]="password"===jQuery(this).attr("type")?l.crypto.md5(jQuery(this).val()):jQuery(this).val())}); m&&l.ajax(jQuery(this).attr("action"),n,function(b){b=a.cb?a.cb(b)?b:{code:"0"}:b;"118"===b.code?l.alert("\u8bf7\u767b\u9646\u90ae\u7bb1\u8fdb\u884c\u9a8c\u8bc1"):"121"===b.code?l.alert("\u7528\u6237\u4fe1\u606f\u5f02\u5e38\uff0c\u8bf71\u5c0f\u65f6\u540e\u518d\u8bd5"):"207"===b.code?window.location.href="/guide/":"116"===b.code?window.location.href=c_url:"114"===b.code?c(e[b.code],"\u8fd9\u4e2a\u90ae\u7bb1\u8fd8\u6ca1\u6709\u6ce8\u518c\u54e6"):"115"===b.code?c(e[b.code],"\u5bc6\u7801\u9519\u8bef"): "107"===b.code?c(e[b.code],"\u9a8c\u8bc1\u7801\u8f93\u5165\u9519\u8bef"):"106"===b.code?c(e[b.code],"Email\u8f93\u5165\u9519\u8bef"):"109"===b.code?c(e[b.code],"Email\u5730\u5740\u5df2\u88ab\u4f7f\u7528"):"110"===b.code&&jQuery("#login-success-modal").modal("show")},function(){l.alert("\u7f51\u7edc\u6709\u95ee\u9898\uff01\u65e0\u6cd5\u767b\u5f55\uff01\u53ef\u80fd\u6728\u6709\u5403\u836f\uff0c\u611f\u89c9\u81ea\u5df1\u840c\u840c\u54d2\uff01")})}})};return l},function(l){var a={init:function(b){var l= a.element,c;for(c in a.defaults.style)l.style[c]=a.defaults.style[c];b="object"===typeof b?{width:parseInt(b.width)||a.defaults.width,height:parseInt(b.height)||a.defaults.height,template:b.template||"info",data:"object"===typeof b.data?b.data:a.defaults.config.data}:a.defaults.config;c=b.width;h=b.height;l.style.width=c+"px";l.style.height=h-100+"px";l.style["margin-top"]="-"+h/2+"px";l.style["margin-left"]="-"+c/2+"px";c=a.templates[b.template]||b.template;b=b.data;for(var n in b)c=c.replace(new RegExp("{{"+ n+"}}","g"),b[n]||"Phenix","g");l.innerHTML=c;return a}};a.dom=l.document;a.element=a.dom.createElement("div");a.element.setAttribute("id","phenix");a.mask=a.dom.createElement("div");a.mask.setAttribute("id","phenix-mask");a.mask.style.cssText="position:fixed;left:0;top:0;width:100%;height:100%;padding:0;margin:0;z-index:99998;background-color:rgba(0,0,0,0.4);";a.defaults={};a.defaults.config={width:500,height:300,template:"info",data:{color:"#36b14a",face:":)",title:"Welcome to Phenix",description:"Made with \u2764 by James Liu"}}; a.defaults.style={display:"block",color:"#221e1f","background-color":"#f1f2f2",width:a.defaults.config.width+"px",height:a.defaults.config.height-50+"px",border:"none",position:"fixed",top:"50%",left:"50%","text-align":"center",padding:"25px 0",margin:"-"+a.defaults.config.height/2+"px 0 0 -"+a.defaults.config.width/2+"px",opacity:"0",filter:"alpha(opacity=0)","z-index":"99999"};a.templates={};a.templates.info="<div style=\"font-size:60px;font-family:'Microsoft YaHei','Helvetica Neue',Helvetica,Arial,sans-serif;padding:10px 0;color:{{color}};\">{{face}}</div><div style=\"font-size:18px;font-family:'Microsoft YaHei','Helvetica Neue',Helvetica,Arial,sans-serif;padding:10px 0;\">{{title}}</div><div style=\"font-size:12px;font-family:'Microsoft YaHei','Helvetica Neue',Helvetica,Arial,sans-serif;padding:10px 0;color:#b9b9bd;\">{{description}}</div>"; var b=function(b){var l=a.element,c=a.mask;l.filter?l.style.filter="alpha(opacity="+b+")":l.style.opacity=b/100;c.filter?c.style.filter="alpha(opacity="+b+")":c.style.opacity=b/100};a.show=function(l){var p=a.mask;a.dom.body.appendChild(a.element);a.dom.body.appendChild(p);var c=0;(function(){b(c);c+=5;100>=c&&setTimeout(arguments.callee,20)})();"function"===typeof l&&l();return a};a.hide=function(l){var p=a.element,c=a.mask,n=100;(function(){b(n);n-=15;0<=n?setTimeout(arguments.callee,20):(a.dom.body.removeChild(p), a.dom.body.removeChild(c))})();"function"===typeof l&&l();return a};l.Phenix=a});
Mengma/m.js
m.min.js
JavaScript
mit
17,440
/*jslint browser:true, nomen:true*/ /*global define*/ define([ 'jquery', 'underscore', 'orotranslation/js/translator', 'oroui/js/mediator', './app/views/base/view' ], function ($, _, __, mediator, BaseView) { 'use strict'; var LoadingMaskView; /** * Loading mask widget * * @export oroui/js/loading-mask * @name oroui.LoadingMask * @deprecated since version 1.6 */ LoadingMaskView = BaseView.extend({ /** @property {Boolean} */ displayed: false, /** @property {Boolean} */ liveUpdate: true, /** @property {String} */ className: 'loading-mask', /** @property {String} */ loadingHint: __('Loading...'), /** @property */ template: _.template( '<div class="loading-wrapper"></div>' + '<div class="loading-frame">' + '<div class="box well">' + '<div class="loading-content">' + '<%= loadingHint %>' + '</div>' + '</div>' + '</div>' ), /** * Initialize * * @param {Object} options * @param {Boolean} [options.liveUpdate] Update position of loading animation on window scroll and resize */ initialize: function (options) { var updateProxy, options = options || {}; if (mediator.execute('retrieveOption', 'debug') && window.console) { console.warn('Module "oroui/js/loading-mask" is deprecated, use "oroui/js/app/views/loading-mask-view" instead'); } if (_.has(options, 'liveUpdate')) { this.liveUpdate = options.liveUpdate; } if (this.liveUpdate) { updateProxy = $.proxy(this.updatePos, this); $(window) .on('resize.' + this.cid, updateProxy) .on('scroll.' + this.cid, updateProxy); } this.loadingElement = options.loadingElement; LoadingMaskView.__super__.initialize.apply(this, arguments); }, /** * @inheritDoc */ dispose: function () { if (this.loadingElement) { this.loadingElement.data('loading-mask-visible', false); this.loadingElement.removeClass('hide-overlays'); } $(window).off('.' + this.cid); LoadingMaskView.__super__.dispose.call(this); }, /** * Show loading mask * * @return {*} */ show: function () { this.$el.show(); if (this.loadingElement) { this.loadingElement.addClass('hide-overlays'); } this.displayed = true; this.resetPos().updatePos(); return this; }, /** * Update position of loading animation * * @return {*} * @protected */ updatePos: function () { if (!this.displayed) { return this; } var $containerEl = this.$('.loading-wrapper'); var $loadingEl = this.$('.loading-frame'); var loadingHeight = $loadingEl.height(); var loadingWidth = $loadingEl.width(); var containerWidth = $containerEl.outerWidth(); var containerHeight = $containerEl.outerHeight(); if (loadingHeight > containerHeight) { $containerEl.css('height', loadingHeight + 'px'); } var halfLoadingHeight = loadingHeight / 2; var loadingTop = containerHeight / 2 - halfLoadingHeight; var loadingLeft = (containerWidth - loadingWidth) / 2; // Move loading message to visible center of container if container is visible var windowHeight = $(window).outerHeight(); var containerTop = $containerEl.offset().top; if (containerTop < windowHeight && (containerTop + loadingTop + loadingHeight) > windowHeight) { loadingTop = (windowHeight - containerTop) / 2 - halfLoadingHeight; } loadingTop = loadingHeight > 0 ? loadingTop : 0; loadingTop = loadingTop < containerHeight - loadingHeight ? loadingTop : containerHeight - loadingHeight; loadingLeft = loadingLeft > 0 ? Math.round(loadingLeft) : 0; loadingTop = loadingTop > 0 ? Math.round(loadingTop) : 0; $loadingEl.css('top', loadingTop + 'px'); $loadingEl.css('left', loadingLeft + 'px'); return this; }, /** * Update position of loading animation * * @return {*} * @protected */ resetPos: function () { this.$('.loading-wrapper').css('height', '100%'); return this; }, /** * Hide loading mask * * @return {*} */ hide: function () { this.$el.hide(); if (this.loadingElement) { this.loadingElement.removeClass('hide-overlays'); } this.displayed = false; this.resetPos(); return this; }, /** * Render loading mask * * @return {*} */ render: function () { this.$el.empty(); this.$el.append(this.template({ loadingHint: this.loadingHint })); this.hide(); return this; } }); return LoadingMaskView; });
morontt/platform
src/Oro/Bundle/UIBundle/Resources/public/js/loading-mask.js
JavaScript
mit
5,711
import './scss/availity-uikit.scss';
Availity/availity-uikit
packages/uikit/index.js
JavaScript
mit
37
'use strict'; module.exports = { db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/minnovell', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.min.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.min.css', ], js: [ 'public/lib/angular/angular.min.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.min.js', 'public/lib/angular-ui-utils/ui-utils.min.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js' ] }, css: 'public/dist/application.min.css', js: 'public/dist/application.min.js' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
merellDev/MinNovell
config/env/production.js
JavaScript
mit
2,055
const toArray = require('../../core/utils/toArray') const flatten = require('../../core/utils/flatten') const findFunctionInTypes = require('./typeLookup') /** translate an object in 2D/3D space * @param {Object} vector - 3D vector to translate the given object(s) by * @param {Object(s)|Array} objects either a single or multiple CSG/CAG objects to translate * @returns {CSG} new CSG object , translated by the given amount * * @example * let movedSphere = translate([10,2,0], sphere()) */ function translate (vector, ...shapes) { // v, obj or array let _shapes = flatten(toArray(shapes)) _shapes = (_shapes.length >= 1 && _shapes[0].length) ? _shapes[0] : _shapes const results = _shapes.map(function (shape) { const specificTranslate = findFunctionInTypes(shape, 'translate') return specificTranslate(vector, shape) }) return results.length === 1 ? results[0] : results } module.exports = translate
jscad/csg.js
src/api/ops-transformations/translate.js
JavaScript
mit
937
import { blue50 } from './colors' export default { color: '#424b50', colorReverse: 'transparent', title: '#424b50', titleReverse: 'transparent', link: blue50, }
meis5/ms5.me
react-stack/src/library/styles/variables/elementsColors.js
JavaScript
mit
172
/* | A mathematical addition | or a string concation. */ /* | The jion definition. */ if( JION ) { throw{ id : 'jion$ast_plus', attributes : { left : { comment : 'left expression', type : require( '../typemaps/astExpression' ) }, right : { comment : 'right expression', type : require( '../typemaps/astExpression' ) } } }; } /* | Capsule */ (function() { 'use strict'; var ast_plus, prototype; ast_plus = require( '../this' )( module, 'ouroboros' ); prototype = ast_plus.prototype; /**/if( CHECK ) /**/{ /**/ var /**/ util; /**/ /**/ util = require( 'util' ); /**/ /*** / **** | Custom inspect **** / ***/ prototype.inspect = /**/ function( /**/ depth, /**/ opts /**/ ) /**/ { /**/ var /**/ postfix, /**/ result; /**/ /**/ if( !opts.ast ) /**/ { /**/ result = 'ast{ '; /**/ /**/ postfix = ' }'; /**/ } /**/ else /**/ { /**/ result = postfix = ''; /**/ } /**/ /**/ opts.ast = true; /**/ /**/ result += '( ' + util.inspect( this.left, opts ) + ' )'; /**/ /**/ result += ' + '; /**/ /**/ result += '( ' + util.inspect( this.right, opts ) + ' )'; /**/ /**/ return result + postfix; /**/ }; /**/} } )( );
axkibe/jion
src/ast/plus.js
JavaScript
mit
1,189
'use strict'; /** * Module dependencies. */ var should = require('should'), mongoose = require('mongoose'), User = mongoose.model('User'), Featurette = mongoose.model('Featurette'); /** * Globals */ var user, featurette; /** * Unit tests */ describe('Featurette Model Unit Tests:', function() { beforeEach(function(done) { user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: 'username', password: 'password' }); user.save(function() { featurette = new Featurette({ name: 'Featurette Name', user: user }); done(); }); }); describe('Method Save', function() { it('should be able to save without problems', function(done) { return featurette.save(function(err) { should.not.exist(err); done(); }); }); it('should be able to show an error when try to save without name', function(done) { featurette.name = ''; return featurette.save(function(err) { should.exist(err); done(); }); }); }); afterEach(function(done) { Featurette.remove().exec(); User.remove().exec(); done(); }); });
helaili/humongolf
app/tests/featurette.server.model.test.js
JavaScript
mit
1,155
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M11 18V6l-8.5 6 8.5 6zm.5-6l8.5 6V6l-8.5 6z" }), 'FastRewindSharp');
AlloyTeam/Nuclear
components/icon/esm/fast-rewind-sharp.js
JavaScript
mit
191
/* eslint-disable prettier/prettier */ /* eslint-disable sort-imports-es6-autofix/sort-imports-es6 */ import CallTakerControls from './components/admin/call-taker-controls' import CallHistoryWindow from './components/admin/call-history-window' import FieldTripWindows from './components/admin/field-trip-windows' import MailablesWindow from './components/admin/mailables-window' import DateTimeModal from './components/form/date-time-modal' import DateTimePreview from './components/form/date-time-preview' import DefaultSearchForm from './components/form/default-search-form' import ErrorMessage from './components/form/error-message' import LocationField from './components/form/connected-location-field' import PlanTripButton from './components/form/plan-trip-button' import SettingsPreview from './components/form/settings-preview' import SwitchButton from './components/form/switch-button' import DefaultMap from './components/map/default-map' import GtfsRtVehicleOverlay from './components/map/gtfs-rt-vehicle-overlay' import Map from './components/map/map' import StylizedMap from './components/map/stylized-map' import OsmBaseLayer from './components/map/osm-base-layer' import TileOverlay from './components/map/tile-overlay' import DefaultItinerary from './components/narrative/default/default-itinerary' import ItineraryCarousel from './components/narrative/itinerary-carousel' import NarrativeItineraries from './components/narrative/narrative-itineraries' import NarrativeItinerary from './components/narrative/narrative-itinerary' import NarrativeRoutingResults from './components/narrative/narrative-routing-results' import RealtimeAnnotation from './components/narrative/realtime-annotation' import SimpleRealtimeAnnotation from './components/narrative/simple-realtime-annotation' import TransportationNetworkCompanyLeg from './components/narrative/default/tnc-leg' import TripDetails from './components/narrative/connected-trip-details' import TripTools from './components/narrative/trip-tools' import LineItinerary from './components/narrative/line-itin/line-itinerary' import MobileMain from './components/mobile/main' import MobileResultsScreen from './components/mobile/results-screen' import MobileSearchScreen from './components/mobile/search-screen' import NavLoginButton from './components/user/nav-login-button' import NavLoginButtonAuth0 from './components/user/nav-login-button-auth0' import StopViewer from './components/viewers/stop-viewer' import ViewStopButton from './components/viewers/view-stop-button' import ViewTripButton from './components/viewers/view-trip-button' import ViewerContainer from './components/viewers/viewer-container' import ResponsiveWebapp from './components/app/responsive-webapp' import AppMenu from './components/app/app-menu' import CallTakerPanel from './components/app/call-taker-panel' import DesktopNav from './components/app/desktop-nav' import DefaultMainPanel from './components/app/default-main-panel' import BatchRoutingPanel from './components/app/batch-routing-panel' import BatchResultsScreen from './components/mobile/batch-results-screen' import BatchSearchScreen from './components/mobile/batch-search-screen' import { setAutoPlan, setMapCenter } from './actions/config' import { getCurrentPosition } from './actions/location' import { setLocationToCurrent, clearLocation } from './actions/map' import { findNearbyStops } from './actions/api' import createCallTakerReducer from './reducers/call-taker' import createOtpReducer from './reducers/create-otp-reducer' import createUserReducer from './reducers/create-user-reducer' import otpUtils from './util' export { // module components CallHistoryWindow, CallTakerControls, FieldTripWindows, MailablesWindow, // form components DateTimeModal, DateTimePreview, DefaultSearchForm, ErrorMessage, LocationField, PlanTripButton, SettingsPreview, StylizedMap, SwitchButton, // map components DefaultMap, GtfsRtVehicleOverlay, ItineraryCarousel, Map, OsmBaseLayer, TileOverlay, // narrative components DefaultItinerary, LineItinerary, NarrativeItineraries, NarrativeItinerary, NarrativeRoutingResults, RealtimeAnnotation, SimpleRealtimeAnnotation, TransportationNetworkCompanyLeg, TripDetails, TripTools, // mobile components MobileMain, MobileResultsScreen, MobileSearchScreen, // viewer components StopViewer, ViewerContainer, ViewStopButton, ViewTripButton, // user-related components NavLoginButton, NavLoginButtonAuth0, // app components, ResponsiveWebapp, AppMenu, CallTakerPanel, DesktopNav, DefaultMainPanel, // batch routing components BatchResultsScreen, BatchRoutingPanel, BatchSearchScreen, // actions clearLocation, findNearbyStops, getCurrentPosition, setAutoPlan, setLocationToCurrent, setMapCenter, // redux utilities createCallTakerReducer, createOtpReducer, createUserReducer, // general utilities otpUtils }
opentripplanner/otp-react-redux
lib/index.js
JavaScript
mit
4,994
//{block name="backend/connect/store/import/remote_products"} Ext.define('Shopware.apps.Connect.store.import.RemoteProducts', { extend : 'Ext.data.Store', autoLoad: false, pageSize: 10, fields: [ { name: 'Article_id', type: 'integer' }, { name: 'Detail_number', type: 'string' }, { name: 'Article_name', type: 'string' }, { name: 'Supplier_name', type: 'string' }, { name: 'Article_active', type: 'boolean' }, { name: 'Price_basePrice', type: 'float' }, { name: 'Price_price', type: 'float' }, { name: 'Tax_name', type: 'string' } ], proxy : { type : 'ajax', api : { read : '{url controller=Import action=loadArticlesByRemoteCategory}' }, reader : { type : 'json', root: 'data', totalProperty:'total' }, listeners : { exception : function(proxy, response, operation) { var responseData = Ext.decode(response.responseText); Shopware.Notification.createGrowlMessage(responseData.message,""); } } }, listeners : { load : function(store, records, successful, eOpts) { if(!successful) { store.removeAll(); } } } }); //{/block}
shopware/SwagConnect
Views/backend/connect/store/import/remote_products.js
JavaScript
mit
1,358
/* eslint-disable strict */ 'use strict'; /* This plugin based on https://gist.github.com/Morhaus/333579c2a5b4db644bd5 Original license: -------- The MIT License (MIT) Copyright (c) 2015 Alexandre Kirszenberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------- And it's NPM-ified version: https://github.com/dcousineau/force-case-sensitivity-webpack-plugin Author Daniel Cousineau indicated MIT license as well but did not include it The originals did not properly case-sensitize the entire path, however. This plugin resolves that issue. This plugin license, also MIT: -------- The MIT License (MIT) Copyright (c) 2016 Michael Pratt Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------- */ const path = require('path'); function CaseSensitivePathsPlugin(options) { this.options = options || {}; this.reset(); } CaseSensitivePathsPlugin.prototype.reset = function () { this.pathCache = {}; this.fsOperations = 0; this.primed = false; }; CaseSensitivePathsPlugin.prototype.getFilenamesInDir = function (dir, callback) { const that = this; const fs = this.compiler.inputFileSystem; this.fsOperations += 1; if (Object.prototype.hasOwnProperty.call(this.pathCache, dir)) { callback(this.pathCache[dir]); return; } if (this.options.debug) { console.log('[CaseSensitivePathsPlugin] Reading directory', dir); } fs.readdir(dir, (err, files) => { if (err) { if (that.options.debug) { console.log('[CaseSensitivePathsPlugin] Failed to read directory', dir, err); } callback([]); return; } callback(files.map(f => f.normalize ? f.normalize('NFC') : f)); }); }; // This function based on code found at http://stackoverflow.com/questions/27367261/check-if-file-exists-case-sensitive // By Patrick McElhaney (No license indicated - Stack Overflow Answer) // This version will return with the real name of any incorrectly-cased portion of the path, null otherwise. CaseSensitivePathsPlugin.prototype.fileExistsWithCase = function (filepath, callback) { // Split filepath into current filename (or directory name) and parent directory tree. const that = this; const dir = path.dirname(filepath); const filename = path.basename(filepath); const parsedPath = path.parse(dir); // If we are at the root, or have found a path we already know is good, return. if (parsedPath.dir === parsedPath.root || dir === '.' || Object.prototype.hasOwnProperty.call(that.pathCache, filepath)) { callback(); return; } // Check all filenames in the current dir against current filename to ensure one of them matches. // Read from the cache if available, from FS if not. that.getFilenamesInDir(dir, (filenames) => { // If the exact match does not exist, attempt to find the correct filename. if (filenames.indexOf(filename) === -1) { // Fallback value which triggers us to abort. let correctFilename = '!nonexistent'; for (let i = 0; i < filenames.length; i += 1) { if (filenames[i].toLowerCase() === filename.toLowerCase()) { correctFilename = `\`${filenames[i]}\`.`; break; } } callback(correctFilename); return; } // If exact match exists, recurse through directory tree until root. that.fileExistsWithCase(dir, (recurse) => { // If found an error elsewhere, return that correct filename // Don't bother caching - we're about to error out anyway. if (!recurse) { that.pathCache[dir] = filenames; } callback(recurse); }); }); }; CaseSensitivePathsPlugin.prototype.primeCache = function (callback) { if (this.primed) { callback(); return; } const that = this; // Prime the cache with the current directory. We have to assume the current casing is correct, // as in certain circumstances people can switch into an incorrectly-cased directory. const currentPath = path.resolve(); that.getFilenamesInDir(currentPath, (files) => { that.pathCache[currentPath] = files; that.primed = true; callback(); }); }; CaseSensitivePathsPlugin.prototype.apply = function (compiler) { this.compiler = compiler; const onDone = () => { if (this.options.debug) { console.log('[CaseSensitivePathsPlugin] Total filesystem reads:', this.fsOperations); } this.reset(); }; const onAfterResolve = (data, done) => { this.primeCache(() => { // Trim ? off, since some loaders add that to the resource they're attemping to load let pathName = data.resource.split('?')[0]; pathName = pathName.normalize ? pathName.normalize('NFC') : pathName; this.fileExistsWithCase(pathName, (realName) => { if (realName) { if (realName === '!nonexistent') { // If file does not exist, let Webpack show a more appropriate error. done(null, data); } else { done(new Error(`[CaseSensitivePathsPlugin] \`${pathName}\` does not match the corresponding path on disk ${realName}`)); } } else { done(null, data); } }); }); }; if (compiler.hooks) { compiler.hooks.done.tap('CaseSensitivePathsPlugin', onDone); compiler.hooks.normalModuleFactory.tap('CaseSensitivePathsPlugin', (nmf) => { nmf.hooks.afterResolve.tapAsync('CaseSensitivePathsPlugin', onAfterResolve); }); } else { compiler.plugin('done', onDone); compiler.plugin('normal-module-factory', (nmf) => { nmf.plugin('after-resolve', onAfterResolve); }); } }; module.exports = CaseSensitivePathsPlugin;
brett-harvey/Smart-Contracts
Ethereum-based-Roll4Win/node_modules/case-sensitive-paths-webpack-plugin/index.js
JavaScript
mit
7,566
/** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#!/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ connection: 'mLabMongodbServer', /*************************************************************************** * * * How and whether Sails will attempt to automatically rebuild the * * tables/collections/etc. in your schema. * * * * See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ migrate: 'alter' };
iagocaldeira/sgvcweb
config/models.js
JavaScript
mit
1,453
(function(angular) { //= include_tree rottenTomatoes/ angular.module('ngRottenTomatoes', []) .provider('rottenTomatoes', RottenTomatoesProvider); })(window.angular);
hilios/angular-rotten-tomatoes
src/ngRottenTomatoes.js
JavaScript
mit
172
import 'whatwg-fetch'; class PomodoroService { static getAllPomodoros() { return new Promise((resolve) =>{ const myInit = { method: 'GET', mode: 'cors', 'Content-Type': 'application/json' }; fetch("https://campari-api.herokuapp.com/pomodoro/", myInit).then(function(response){ return response.json(); }).then(json=>{ let pomodoros = Object.assign([], json.data); resolve(pomodoros); }).catch(function(err){ console.log(err); }); }); } static savePomodoro(pomodoro){ return new Promise((resolve) =>{ let content = JSON.stringify({pomodoro}); const myInit = { method: 'POST', mode: 'cors', headers: { "Content-Type": "application/json; charset=UTF-8"}, body: content }; fetch("https://campari-api.herokuapp.com/pomodoro/", myInit).then(function(response){ return response.json(); }).then(json=>{ let pomodoros = Object.assign({}, json.data); resolve(pomodoros); }).catch(function(err){ console.log(err); }); }); } static updatePomodoro(pomodoro){ return new Promise((resolve) =>{ let content = JSON.stringify({pomodoro}); const myInit = { method: 'PUT', mode: 'cors', headers: { "Content-Type": "application/json; charset=UTF-8"}, body: content }; fetch("https://campari-api.herokuapp.com/pomodoro/" + pomodoro._id, myInit).then(function(response){ return response.json(); }).then(json=>{ let pomodoros = Object.assign({}, json.data); resolve(pomodoros); }).catch(function(err){ console.log(err); }); }); } static deletePomodoro(pomodoro){ return new Promise((resolve) =>{ const myInit = { method: 'DELETE', mode: 'cors', headers: { "Content-Type": "application/json; charset=UTF-8"} }; fetch("https://campari-api.herokuapp.com/pomodoro/" + pomodoro._id, myInit) .then(function(response){ resolve("Pomodoro deleted"+ response); }) .catch(function(error){ throw error; }); }); } } // var promise = new Promise((resolve) => { // fetch('http://localhost:30001/pomodoro', myInit) // .then(function(result){ // debugger; // resolve(Object.assign([], result)); // })}); // return fetch('http://localhost:30001/pomodoro', {mode: 'no-cors'}) // .then(result=> { // }); // .then((result)=>{ // resolve(Object.assign([], result)); // }); // return new Promise((resolve) => { // fetch('http://localhost:30001/pomodoro') // .then((result)=>{ // resolve(Object.assign([], x)); // }); // setTimeout(() => { // resolve(Object.assign([], pomodoros)); // }, delay); // }); // static saveCourse(course) { // course = Object.assign({}, course); // to avoid manipulating object passed in. // return new Promise((resolve, reject) => { // setTimeout(() => { // // Simulate server-side validation // const minCourseTitleLength = 1; // if (course.title.length < minCourseTitleLength) { // reject(`Title must be at least ${minCourseTitleLength} characters.`); // } // if (course.id) { // const existingCourseIndex = courses.findIndex(a => a.id == course.id); // courses.splice(existingCourseIndex, 1, course); // } else { // //Just simulating creation here. // //The server would generate ids and watchHref's for new courses in a real app. // //Cloning so copy returned is passed by value rather than by reference. // course.id = generateId(course); // course.watchHref = `http://www.pluralsight.com/courses/${course.id}`; // courses.push(course); // } // resolve(course); // }, delay); // }); // } // static deleteCourse(courseId) { // return new Promise((resolve, reject) => { // setTimeout(() => { // const indexOfCourseToDelete = courses.findIndex(course => { // course.courseId == courseId; // }); // courses.splice(indexOfCourseToDelete, 1); // resolve(); // }, delay); // }); // } export default PomodoroService;
kaizensauce/campari-app
src/services/pomodoro-service.js
JavaScript
mit
4,748
AUTH_CONSTANTS = { loginFormId : 'login-form', changePwdFormId : 'changepassword-form', changePwdPopupFlag : 'chpwd', authLoginPath : '/auth/login', authChangePwdPath : '/auth/changePassword', chpwdContentPath : '/content/changePassword', SUCCESS_CODE : 'success', ERROR_CODE : 'error', msgContaineId : 'auth-msg-container', emptyCredentials : "Username / Password can't be left empty", invalidUserName : "Only alphbates and '_' are allowed in User Name", emptyPasswords : "Password fields can't be left empty" }; var cssSelectors = { popupBg : '.popup-opacity-background', chpwdContainer : '#chpwd-container', chpwdLink : '.change-password-link' }; addEvent(window, 'load', function() { var forms = document.getElementsByClassName('auth-form'); for ( var index = 0; index < forms.length; index++) { var form = forms[index]; for ( var i = 0; i < form.length; i++) { if (form[i].nodeName === "INPUT") { var el = form[i]; addEvent(el, 'keypress', function(e) { if (e.keyCode == 13) { if (form.id == AUTH_CONSTANTS.loginFormId) { doLogin(form.id); } else if (form.id == AUTH_CONSTANTS.changePwdFormId) { changePassword(form.id); } } }); } } } }); function doLogin(formId) { var formElem = document.getElementById(formId); var formInputFields = [ formElem.username, formElem.password ]; if (validate(formElem, formInputFields, AUTH_CONSTANTS.emptyCredentials)) { $('#do-login').addClass('disabled'); $('#do-login').val(' Signing In... '); var formData = populateLoginFormData(formElem); AJAX.onreadystatechange = function() { if (AJAX.readyState == 4 && AJAX.status == 200) { var response = JSON.parse(AJAX.responseText); var msgContainerId = AUTH_CONSTANTS.msgContaineId; var msgContainer = document.getElementById(msgContainerId); if (response.code == AUTH_CONSTANTS.SUCCESS_CODE) { window.location.reload(); } else if (response.code == AUTH_CONSTANTS.ERROR_CODE) { msgContainer.className = "error-msg-div"; msgContainer.innerHTML = response.msg; msgContainer.style.display = "block"; $('#do-login').removeClass('disabled'); $('#do-login').val(' Sign In '); } } }; AJAX.open("POST", AUTH_CONSTANTS.authLoginPath); AJAX.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest'); AJAX.send(formData); } } function changePassword(formId) { var formElem = document.getElementById(formId); var formInputFields = [ formElem.currentpassword, formElem.newpassword ]; if (validate(formElem, formInputFields, AUTH_CONSTANTS.emptyPasswords)) { var formData = populateChpwdFormData(formElem); AJAX.onreadystatechange = function() { if (AJAX.readyState == 4 && AJAX.status == 200) { var response = JSON.parse(AJAX.responseText); var msgContainerId = AUTH_CONSTANTS.msgContaineId; var msgContainer = document.getElementById(msgContainerId); if (response.code == AUTH_CONSTANTS.SUCCESS_CODE) { msgContainer.className = "success-msg-div"; document.getElementById(formId).reset(); setTimeout(function() { closePopup(); }, 2000); } else if (response.code == AUTH_CONSTANTS.ERROR_CODE) { msgContainer.className = "error-msg-div"; } msgContainer.innerHTML = response.msg; msgContainer.style.display = "block"; } }; AJAX.open("POST", AUTH_CONSTANTS.authChangePwdPath); AJAX.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest'); AJAX.send(formData); } } function populateLoginFormData(formElem) { var formData = new FormData(); formData.append('username', formElem.username.value); formData.append('password', formElem.password.value); formData.append(APP_CONSTANTS.CSRF_TOKEN_NAME, formElem[APP_CONSTANTS.CSRF_TOKEN_NAME].value); formData.append('remember', formElem.remember.checked); formData.append('login-action-name', document .getElementById('login-action-name').value); return formData; } function populateChpwdFormData(formElem) { var formData = new FormData(); formData.append('currentpassword', formElem.currentpassword.value); formData.append('newpassword', formElem.newpassword.value); formData.append(APP_CONSTANTS.CSRF_TOKEN_NAME, formElem[APP_CONSTANTS.CSRF_TOKEN_NAME].value); formData.append('chpwd-action-name', document .getElementById('chpwd-action-name').value); return formData; } function validate(formElem, credential, errMsg) { var isError = false; var errorMsgElem = document.getElementById('auth-msg-container'); resetErrors(credential); for (index in credential) { if (credential[index].value == 0) { errorMsgElem.innerHTML = errMsg; errorMsgElem.className = "error-msg-div"; errorMsgElem.style.display = "block"; credential[index].className += " error-field"; isError = true; } } return (!isError); } function resetErrors(credential) { for (index in credential) { removeClass(credential[index], "error-field"); } } $('#do-login').click(function() { doLogin(AUTH_CONSTANTS.loginFormId); }); $(cssSelectors.chpwdLink).click( function() { attachPopupEvents(cssSelectors.popupBg, cssSelectors.chpwdContainer, AUTH_CONSTANTS.changePwdPopupFlag, getChangePasswordUI); $(APP_CONSTANTS.cssSelectors.accountDD).slideToggle(); }); function getChangePasswordUI() { formData = new FormData(); formData.append('time', 100000); AJAX.onreadystatechange = function() { if (AJAX.readyState == 4 && AJAX.status == 200) { var response = JSON.parse(AJAX.responseText); if (response.code == AUTH_CONSTANTS.SUCCESS_CODE) { $(cssSelectors.chpwdContainer).html(response.detail); } else if (response.code == AUTH_CONSTANTS.ERROR_CODE) { // msgContainer.className = "error-msg-div"; } } }; AJAX.open("GET", AUTH_CONSTANTS.chpwdContentPath); AJAX.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest'); AJAX.send(formData); }
cshekharsharma/crux
webroot/Auth/js/auth.js
JavaScript
mit
6,922
#!/usr/bin/env node require('yargs') .commandDir('lib/commands') .demandCommand() .help() .parse();
architshukla/brotli-cli
index.js
JavaScript
mit
109
var gulp = require('gulp'); var del = require('del'); var KarmaServer = require('karma').Server; var gulpDocs = require('gulp-ngdocs'); var browserSync = require('browser-sync').create(); var ghPages = require('gulp-gh-pages'); gulp.task('clean', function (done) { del(['dist', 'docs'], done); }); gulp.task('test', function (done) { new KarmaServer({ configFile: __dirname + '/karma.conf.js', singleRun: true }, done).start(); }); gulp.task('tdd', function (done) { new KarmaServer({ configFile: __dirname + '/karma.conf.js' }, done).start(); }); gulp.task('default', ['tdd']); gulp.task('ngdocs', ['clean'], function () { var options = { loadDefaults: { angular: false, angularAnimate: false, marked: false }, scripts: [ 'node_modules/jquery/dist/jquery.js', 'node_modules/angular/angular.js', 'node_modules/angular-animate/angular-animate.js', 'node_modules/marked/lib/marked.js', 'src/focus.js'], html5Mode: false } return gulp .src('src/*.js') .pipe(gulpDocs.process(options)) .pipe(gulp.dest('./docs')); }); gulp.task('deploy-docs', function () { return gulp .src('docs/**/*') .pipe(ghPages()); }); gulp.task('serve-docs', ['ngdocs'], function (done) { browserSync.init({ server: "./docs" }); gulp.watch("src/**/*", ['ngdocs']); gulp.watch("docs/index.html").on('change', browserSync.reload); }); gulp.task('default', ['tdd']);
ChunghwaTelecom/focus
gulpfile.js
JavaScript
mit
1,596
/* Author: */ $(document).ready(function(){ $("#topo span.bt a").click(function () { $(this).toggleClass('active'); if ($(this).hasClass('active')){ $("#topo").stop().animate({"height" : "377px"}); }else{ $("#topo").stop().animate({"height" : "20px"}); } }); $(".entry .post, footer nav a, .about aside article, .news .post, #comments .comment, article.border, article.content.left article.border").last().addClass('noBorder'); $(".entry .post:last").addClass('noBorder'); $(".eatMinorLinks article, .occasions .content img").last().addClass('noMargin'); $('header nav a').last().css('background', 'none', 'border','none'); $('.stay aside a, .playIns aside a').last().css('height', '51px'); $(".press .content .awards div").addClass('clearfix'); $(".spaExcl .columnOne p span").css({'color':'#e8519d'}); /* Stay */ $('.stay aside a').eq(1).addClass('padnav'); $('.stay aside a').eq(2).addClass('padnav'); $(".about aside article a").hover(function (){ $(this).find('span.play').stop().animate({'opacity':0.9},300);},function(){ $(this).find('span.play').stop().animate({'opacity':0.5},300); }); $('dl#freq dt').hover(function () { if(!$(this).hasClass('active')){ $(this).stop().animate({'backgroundColor':'#6d96a9' , 'color':'#fff'});}}, function () { if(!$(this).hasClass('active')){ $(this).stop().animate({'backgroundColor':'#caeeff' , 'color':'#000'});} }); $(".inline").colorbox({inline:true, width:"50%"}); //---------------------------------------------------------------------------// //FAQ - esconde todo o conteudo da dd //---------------------------------------------------------------------------// $('dl#freq dd').hide().first().show(); $('dl#freq dt').first().addClass('active').animate({'backgroundColor':'#6d96a9' , 'color':'#fff'}); $('dl#freq dt').click(function(){ var $this = $(this); if(!$(this).hasClass('active')){ window.location.hash = $(this).attr('id'); $('dl#freq dd').slideUp(); $('dl#freq dt').removeClass('active').stop().animate({'backgroundColor':'#caeeff' , 'color':'#000'}); } $(this).stop().animate({'backgroundColor':'#6d96a9' , 'color':'#fff'}).toggleClass('active').next('dl#freq dd').slideToggle(600,function(){$.scrollTo($this,400)}); }); $('.toTop').click(function (){ $('body').animate({'scrollTop':0},'slow'); return false; }); //hash faq if(window.location.hash != ''){ faqHash(window.location.hash); } function faqHash(hash){ $(hash).trigger('click'); } //AJAX PRESS $('a.postsPress').click(function(){ $('a.postsPress').removeClass('active'); $(this).parent().addClass('active'); var id = $(this).attr('id'); var $figure = $('#imgPress'); var html = ""; html += jsonPress[id].img; html += "<figcaption>"; html += "<span class=\"left\"><em>"+jsonPress[id].caption+"</em></span>"; if(jsonPress[id].attachs != ""){ html += "<span class=\"right\"><a href=\""+jsonPress[id].attachs+"\" title=\"Download PDF\">Download PDF</a></span>"; } html += "</figcaption>"; // $figure.stop().animate({'opacity':0},function(){ // $(this).html(html); // }).animate({'opacity':1}); $figure.html(html); }) //Execução de plugins $('.clearinput').clearInput(); //scroll pane if($('.scroll-pane').length){ var settings = { animateScroll : true, mouseWheelSpeed : 1, horizontalDragMinWidth : 87 }; var pane = $('.scroll-pane'); pane.jScrollPane(settings); var api = pane.data('jsp'); } //Carrossel $('.carrossel').carrossel({ auto:true }); //---------------------------------------------------------------------------// // get hash //---------------------------------------------------------------------------// function getHash(){ var query = location.href.split('#'); document.cookies = 'hash=' + query[1]; alert(document.cookies); } function getHashUrlVars(){ var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('&'); for(var i = 0; i < hashes.length; i++){ hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } });
sphrcl/goldeneye.com
js/script.js
JavaScript
mit
4,335
version https://git-lfs.github.com/spec/v1 oid sha256:8ca42e4a5d3f58711a402a56b553df246873f978f64a337e3dac55f0b00b5c74 size 8711
yogeshsaroya/new-cdnjs
ajax/libs/underscore.string/2.3.1/underscore.string.min.js
JavaScript
mit
129
module.exports = function (config) { config.set({ basePath : '', frameworks : ["jasmine"], files : [ '../../var/www/js/lib/jquery.js', '../../var/www/js/lib/lodash.underscore.min.js', '../../var/www/js/lib/angular.js', '../../var/www/js/lib/angular-route.js', '../../var/www/js/lib/angular-ui-router.js', '../../var/www/js/lib/angular-mocks.js', '../../var/www/js/lib/restangular.js', 'tests/testBase.js', '../../var/www/js/apps/**/*.js', '../../var/www/js/directives/**/*.js', 'tests/**/*.js' ], exclude: [ '../../var/www/js/apps/**/routes.js', ], logLevel: config.LOG_INFO, autoWatch : true, colors : true, port : 9877, runnerPort : 9101, browsers : ['PhantomJS'], reporters: ['progress'], junitReporter : { outputFile : 'test_out/unit.xml', suite : 'unit' } }); }
koriym/Spout
tests/js/karma.conf.js
JavaScript
mit
928
// @flow import type {DistrictInfo} from './types'; import {population} from './util'; // Return whether the precincts are adjacent. // // Each argument should be an object with properties x, y, width, and height. // TODO(benkraft): Maybe shouldn't allow just touching at corners? function adjacent(precinct1, precinct2) { return ( precinct1.x + precinct1.width >= precinct2.x && precinct2.x + precinct2.width >= precinct1.x && precinct1.y + precinct1.height >= precinct2.y && precinct2.y + precinct2.height >= precinct1.y); } // Return whether all precincts in the list are adjacent. // // See adjacent() above for details. function contiguous(precincts) { // TODO(benkraft): Maybe there is a non-n^2 way? if (precincts.length <= 1) { return true; // vacuously } // Build an adjacency list const adjacency = Array.from(precincts, () => []); precincts.forEach((p1, i) => { precincts.slice(i + 1).forEach((p2, j) => { if (adjacent(p1, p2)) { adjacency[i].push(j + i + 1); adjacency[j + i + 1].push(i); } }); }); // DFS on the list to see if we get to everything const found = adjacency.map(() => false); const stack = [0]; while (stack.length) { let item = stack.pop(); if (!found[item]) { found[item] = true; Array.prototype.push.apply(stack, adjacency[item]); } } return found.every(x => x); } /** * Validate a district. * * Returns a reason (e.g. "is not contiguous") or null if the district is * valid. */ function validate(districtInfo: DistrictInfo) { let invalidReason = null; if (districtInfo.idealSize) { if (!contiguous(districtInfo.precincts)) { invalidReason = "is not contiguous"; // $FlowIgnore } else if (population(districtInfo.precincts) > districtInfo.idealSize) { invalidReason = "is too large"; // $FlowIgnore } else if (population(districtInfo.precincts) < districtInfo.idealSize) { invalidReason = "is too small"; } } return invalidReason; } export default validate;
benjaminjkraft/elbridge
src/validate.js
JavaScript
mit
2,064
import Vue from 'vue' import VueRouter from 'vue-router' import routes from './router/router' import store from './store' import ajax from './config/ajax' import './style/common' import './config/rem' Vue.use(VueRouter) const router = new VueRouter({ routes }) new Vue({ router, store }).$mount('#app')
rookielzy/Learn-Vue.js
vue2-practise/src/main.js
JavaScript
mit
317
var ObjectId = require('mongodb').ObjectId; var _ = require('lodash'); //var moment = require('moment'); //service pattern //function ChickenNuggets() {} //factory pattern //ChickenNuggets = {}; //Models create a prototype of an object //we can set variables for orders here function Order(o) { this.userId = ObjectId(o.userId);//creates an id for user ordering nuggets this.name = o.name; this.style = o.style; this.qty = o.qty; this.createdAt = new Date(); this.complete = false; this.cost = this.qty * 0.25; } //defines the properties of the model and returns them to the database Object.defineProperty(Order, 'collection', { get: function () { return global.db.collection('chickenNuggets'); } }); Order.create = function (o, cb) { var order = new Order (o); order.save(cb); } //save the properties to the database Order.prototype.save = function (cb) { Order.collection.save(this, cb); }; //when we complete an order, update the database with this prototype Order.prototype.complete = function (cb) { Order.collection.update({ _id: this._id }, { $set: { complete: true } }, cb); }; //helper function for setPrototype Order.findById = function (id, cb) { Order.collection.find({ _id: ObjectId(id) }, function (err, order) { cb(err, setPrototype(order)); }); }; //use this in the router.get function in the chickennuggets.js route //this lets us get and display all the orders in chicken-index.ejs Order.findAllByUserId = function (id, cb) { Order.collection.find({userId: ObjectId(id)}).toArray(function (err, orders) { var prototypedOrders = orders.map(function (order) { return setPrototype(order); }); cb(err, prototypedOrders); }); }; module.exports = Order; function setPrototype(pojo) { return _.create(Order.prototype, pojo); } /* function formatAllOrders(orders) { return orders.map(function (order) { return order.format(); }) } function Order(o) { this._id = o._id; this.name = o.name; this.flavor = o.style; this.qty = o.qty; this.complete = o.complete || false; this.createdAt = moment(o._id.getTimestamp()).fromNow(); } */ /* var formattedOrders = orders.map(function (order) { //take an order and return an obect we want it to be console.log(complete) return { _id: order._id, name: order.Nuggets_for, flavor: order.style, qty: order.qty, createdAt: moment(order._id.getTimestamp()).fromNow(), }; }); return formattedOrders; };*/
edstros/expressbasics
models/ChickenNuggets.js
JavaScript
mit
2,489
{ const filePath = path .basename(file) .replace("-", "/") .replace("-", "/") .replace("-", "/") .replace(/\./g, "-") .replace(/\-md$/, ".html"); const res = extractMetadata( fs.readFileSync(file, { encoding: "utf8" }) ); const rawContent = res.rawContent; const metadata = Object.assign( { path: filePath, content: rawContent }, res.metadata ); metadata.id = metadata.title; metadatas.files.push(metadata); writeFileAndCreateFolder( "src/jest/blog/" + filePath.replace(/\.html$/, ".js"), buildFile("BlogPostLayout", metadata, rawContent) ); }
stas-vilchik/bdd-ml
data/5409.js
JavaScript
mit
634
export const ic_motorcycle = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M19.44 9.03L15.41 5H11v2h3.59l2 2H5c-2.8 0-5 2.2-5 5s2.2 5 5 5c2.46 0 4.45-1.69 4.9-4h1.65l2.77-2.77c-.21.54-.32 1.14-.32 1.77 0 2.8 2.2 5 5 5s5-2.2 5-5c0-2.65-1.97-4.77-4.56-4.97zM7.82 15C7.4 16.15 6.28 17 5 17c-1.63 0-3-1.37-3-3s1.37-3 3-3c1.28 0 2.4.85 2.82 2H5v2h2.82zM19 17c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z"}}]};
wmira/react-icons-kit
src/md/ic_motorcycle.js
JavaScript
mit
432
var myLatLng = {}; var lazyMapScript = () => { let s = document.createElement('script'); s.src = 'https://maps.googleapis.com/maps/api/js?callback=initMap'; document.getElementsByTagName('head')[0].appendChild(s); }; var getGeoFallback = () => { var _lat = window.prompt('Can\'t find geo-location automatically, please fill with latitude(lat)', '25.0327429'); var _lng = window.prompt('Can\'t find geo-location automatically, please fill with longitude(lng)', '121.5668311'); myLatLng.lat = parseFloat(_lat) || 25.0327429; myLatLng.lng = parseFloat(_lng) || 121.5668311; lazyMapScript(); }; /* global google */ if ('geolocation' in navigator) { navigator.geolocation.getCurrentPosition((geo) => { myLatLng.lat = geo.coords.latitude; myLatLng.lng = geo.coords.longitude; lazyMapScript(); }, getGeoFallback); } else { getGeoFallback(); } var map; window.initMap = () => { var latLngA = { lat: myLatLng.lat, lng: myLatLng.lng - 0.001 }; var latLngB = { lat: myLatLng.lat, lng: myLatLng.lng + 0.001 }; var getCircleStyle = (pos) => { return { strokeOpacity: 0.3, strokeWeight: 1, fillColor: '#000000', fillOpacity: 0.1, map: map, center: pos, radius: 200 }; }; map = new google.maps.Map(document.getElementById('map'), { center: myLatLng, zoomControl: true, mapTypeControl: false, streetViewControl: false, scaleControl: true, zoom: 17 }); // zero-point var marker = new google.maps.Marker({ position: myLatLng, map: map, draggable: false }); console.log(marker); var markerA = new google.maps.Marker({ position: latLngA, map: map, label: 'A', draggable: true }); var markerB = new google.maps.Marker({ position: latLngB, map: map, label: 'B', draggable: true }); var circleA = new google.maps.Circle(getCircleStyle(latLngA)); var circleB = new google.maps.Circle(getCircleStyle(latLngB)); markerA.addListener('dragend', (e) => { circleA.setMap(null); circleA = new google.maps.Circle(getCircleStyle({lat: e.latLng.lat(), lng: e.latLng.lng()})); }); markerB.addListener('dragend', (e) => { circleB.setMap(null); circleB = new google.maps.Circle(getCircleStyle({lat: e.latLng.lat(), lng: e.latLng.lng()})); }); };
Rplus/dev-pool
app/p-200m/js.js
JavaScript
mit
2,354
this.NesDb = this.NesDb || {}; NesDb[ '20B84965ABAD72421F67854FE3C7959BED7E256F' ] = { "$": { "name": "Twin Eagle", "class": "Licensed", "catalog": "NES-2E-USA", "publisher": "Romstar", "developer": "Seta", "region": "USA", "players": "2", "date": "1989-10" }, "cartridge": [ { "$": { "system": "NES-NTSC", "crc": "CF26A149", "sha1": "20B84965ABAD72421F67854FE3C7959BED7E256F", "dump": "ok", "dumper": "bootgod", "datedumped": "2006-10-10" }, "board": [ { "$": { "type": "NES-UNROM", "pcb": "NES-UNROM-08", "mapper": "2" }, "prg": [ { "$": { "name": "NES-2E-0 PRG", "size": "128k", "crc": "CF26A149", "sha1": "20B84965ABAD72421F67854FE3C7959BED7E256F" } } ], "vram": [ { "$": { "size": "8k" } } ], "chip": [ { "$": { "type": "74xx161" } }, { "$": { "type": "74xx32" } } ], "cic": [ { "$": { "type": "6113B1" } } ], "pad": [ { "$": { "h": "1", "v": "0" } } ] } ] } ], "gameGenieCodes": [ { "name": "Infinite lives--player 1", "codes": [ [ "SXOSVPVG" ] ] }, { "name": "Start with 7 lives--both players", "codes": [ [ "YEETIPLA" ] ] }, { "name": "Start with 4 lives--both players", "codes": [ [ "GEETIPLA" ] ] }, { "name": "Start with 1 life--both players", "codes": [ [ "PEETIPLA" ] ] }, { "name": "Infinite bombs on pick-up--player 1", "codes": [ [ "SXNSXSVK" ] ] }, { "name": "Infinite bombs on pick-up--player 2", "codes": [ [ "SZSIXNVK" ] ] }, { "name": "Player 1 has 1 life after a continue", "codes": [ [ "PAEKXTLA" ] ] }, { "name": "Player 1 has 4 lives after a continue", "codes": [ [ "GAEKXTLA" ] ] }, { "name": "Player 1 has 7 lives after a continue", "codes": [ [ "YAEKXTLA" ] ] }, { "name": "Never lose weapons--player 1", "codes": [ [ "EYKVVUSA", "YAKVNLKZ" ] ] }, { "name": "Never lose weapons--player 2", "codes": [ [ "ENXVKUSA", "YEXVSLSZ" ] ] } ] };
peteward44/WebNES
project/js/db/20B84965ABAD72421F67854FE3C7959BED7E256F.js
JavaScript
mit
2,446
console.log('gol.js'); // global variables prepended with var _delay = 100; function init(){ console.log('init'); var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var width=100,height=100; var livenodes = []; /*for(var i=0,end=width*height;i<end;i++){ if( Math.random() > 0.3 ) livenodes.push(i); }*/ // much faster and still gets the job done for( var i=0, end=width*height; i<end; i += Math.ceil(Math.random()*4) ){ livenodes.push(i); } console.log('livenodes.length',livenodes.length); render(livenodes,width,height,context); var btn = document.getElementById('_tick'); btn.addEventListener('click',function(){ // console.log('ln', livenodes); livenodes = tick(livenodes,width,height); render(livenodes,width,height,context); },false); var btn2 = document.getElementById('start'); btn2.canvas = canvas; btn2.addEventListener('click',function(){ //var interval = window.setInterval(tick, delay); console.log(livenodes); },false); // console.log('init end grid.livenodes',livenodes); } function render(nodes, width, height, context){ var _gridsize = 4; // clear viewport context.fillStyle = 'white'; context.fillRect(0,0,width*_gridsize,height*_gridsize); var toCheck = nodesToCheck(nodes,width,height); for(var i=0,end=toCheck.length;i<end;i++){ var x = toCheck[i] % width; var y = Math.floor( toCheck[i] / width ); drawPoint(x,y,_gridsize,context,'#aaffaa'); } for(var i=0,end=nodes.length;i<end;i++){ var x = nodes[i] % width; var y = Math.floor( nodes[i] / width ); drawPoint(x,y,_gridsize,context); } } function drawPoint(x,y,gridsize,context,color){ if(!color)color='black'; if(!gridsize)gridsize = 1; if (context){ //console.log("drawpoint is working"); context.fillStyle = color; context.fillRect(x*gridsize,y*gridsize,gridsize,gridsize); } } function tick(liveNodes,width,height){ // rules: // Any live cell with fewer than two live neighbours dies, as if caused by under-population. // Any live cell with two or three live neighbours lives on to the next generation. // Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. // Any live cell with more than three live neighbours dies, as if by overcrowding. var kill = []; var create = []; var check = nodesToCheck(liveNodes, width, height); // Make kill and create list for(var i=0,end=check.length;i<end;i++){ var node = check[i]; var n = numberOfNeigbours(node,liveNodes,width,height); // console.log('node',node,'n',n); var nodeIndex = liveNodes.indexOf(node); if( nodeIndex > -1 ){ // If node is live if( n < 2 ) kill.push(nodeIndex); else if ( n > 3 ) kill.push(nodeIndex); } else if( n == 3 ) { create.push(node); } // todo, save the index instead and splice from end to zero, will save one indexOf } // Kill nodes for(var i=kill.length-1; i>-1; i--){ var k = kill[i]; if(liveNodes[k]) liveNodes.splice(k,1); } // Create nodes // console.log('adding nodes',create); liveNodes = liveNodes.concat(create); liveNodes.sort(compareNumbers); //.removeDuplicates(); return liveNodes; } function nodesToCheck(liveNodes, width, height){ var toCheck = [].concat(liveNodes); for(var i=0,end=liveNodes.length; i<end; i++){ // in addition to self, check points around, unless next to a border var pSelf = liveNodes[i]; var check = getCheckMatrix(pSelf,width,height).map(function(item){return item+pSelf;}); check.push(pSelf); toCheck = toCheck.concat(check); } // sort, then remove all negative and duplicate numbers (in order) toCheck.sort(compareNumbers); toCheck.removeNegatives().removeDuplicates(); return toCheck; } function numberOfNeigbours(position,liveNodes,width,height){ var check = getCheckMatrix(position,width,height); var n = 0; // number of live neigbours for(var i=0,end=check.length;i<end;i++){ // See if the point exist within the list of live nodes if( liveNodes.indexOf( position + check[i] ) > -1 ) n++; } return n; } window.addEventListener('load',init,false);
RobertGresdal/javascript
gameOfLife/gol.js
JavaScript
mit
4,090
'use strict'; // service used for communicating with the projects REST endpoints angular.module('projects').factory('Projects', ['$resource', function ($resource) { return $resource('api/projects/:projectId', { projectId: '@_id' }, { update: { method: 'PUT' } }); } ]);
AbbasKhan01/RapidScrum
projects/client/services/projects.client.service.js
JavaScript
mit
329
const Promise = require('bluebird') const _ = require('lodash') const api = require('../core/api') const error = require('../core/error') const pathUtil = require('../util/path') /** * Controller util * * Exports helper methods that are attached to client side controllers */ /** * Load result from a given API endpoint, then attach result at given `source` * namespace in response body to given `dest` in the controller's scope * * @param {String} endpointNs * @param {Object=} body * @param {Object=} query * @return {Promise} */ function loadFromApi(endpointNs, body, query, dest = null, source = null) { return apiCall.call(this, endpointNs, body, query) .then(data => { let value = source ? _.get(data, source) : data if (!dest) { return _.extend(this, value) } _.set(this, dest, value) return data }) } /** * Perform API call, handle rejections, errors and loading state * * @param {String} endpointNs * @param {Object=} body * @param {Object=} query * @return {Promise} */ function apiCall(endpointNs, body = null, query = null) { return new Promise(resolve => { this.loading = true this.error = null let endpoint try { endpoint = _.get(api, endpointNs) } catch (e) { return error.handle(new Error(`Endpoint not found: ${ endpointNs }`)) } if (!endpoint) { return error.handle(new Error(`Endpoint not found: ${ endpointNs }`)) } return endpoint(body, query) .then(res => { this.loading = false resolve(res.body) }, res => { this.loading = false this.error = res.body }) .catch(error.handle) }) } module.exports = { apiCall, loadFromApi, link: pathUtil.link }
Workshape/mandi
client/util/controller.js
JavaScript
mit
1,718
define(function(require) { 'use strict'; const _ = require('underscore'); const Flotr = require('flotr2'); const dataFormatter = require('orochart/js/data_formatter'); const BaseChartComponent = require('orochart/js/app/components/base-chart-component'); /** * @class orochart.app.components.StackedBarChartComponent * @extends orochart.app.components.BaseChartComponent * @exports orochart/app/components/stackedbar-char-component */ const StackedBarChartComponent = BaseChartComponent.extend({ aspectRatio: 0.6, initialDatasetSize: 30, /** * @inheritDoc */ constructor: function StackedBarChartComponent(options) { StackedBarChartComponent.__super__.constructor.call(this, options); }, /** * Draw chart * * @overrides */ draw: function() { const container = this.$chart.get(0); const series = this.getSeries(); // speculatively use first series to set xaxis size const sample = series[0]; const xSize = { min: sample.data[sample.data.length - this.initialDatasetSize][0], max: sample.data[sample.data.length - 1][0] }; const graph = this.drawGraph(container, series, xSize); this.setupPanning(graph, container, series); }, setupPanning: function(initialGraph, container, series) { let graph = initialGraph; const drawGraph = _.bind(this.drawGraph, this); let start; Flotr.EventAdapter.observe(container, 'flotr:mousedown', function(e) { start = graph.getEventPosition(e); Flotr.EventAdapter.observe(container, 'flotr:mousemove', onMove); Flotr.EventAdapter.observe(container, 'flotr:mouseup', onStop); }); function onStop() { Flotr.EventAdapter.stopObserving(container, 'flotr:mousemove', onMove); } function onMove(e, o) { const xaxis = graph.axes.x; const offset = start.x - o.x; // Redrawl the graph with new axis graph = drawGraph( container, series, { min: xaxis.min + offset, max: xaxis.max + offset } ); } }, drawGraph: function(container, series, xSize) { const options = this.options; const settings = this.options.settings; const chartOptions = { colors: settings.chartColors, fontColor: settings.chartFontColor, fontSize: settings.chartFontSize, HtmlText: false, bars: { show: true, stacked: true, horizontal: false, shadowSize: 0, fillOpacity: 1, lineWidth: 7.5, centered: true }, mouse: { track: true, relative: false, position: 'ne', trackFormatter: _.bind(this.trackFormatter, this) }, yaxis: { autoscale: true, autoscaleMargin: 0.3, noTicks: 2, tickFormatter: _.bind(this.YTickFormatter, this), title: options.data_schema.value.label }, xaxis: { min: xSize.min, max: xSize.max, tickFormatter: _.bind(this.XTickFormatter, this), title: options.data_schema.label.label }, grid: { verticalLines: false }, legend: { show: true, noColumns: 1, position: 'nw' } }; return Flotr.draw(container, series, chartOptions); }, YTickFormatter: function(value) { const yFormat = this.options.data_schema.value.type; return dataFormatter.formatValue(value, yFormat); }, XTickFormatter: function(value) { const xFormat = this.options.data_schema.label.type; return dataFormatter.formatValue(value, xFormat); }, trackFormatter: function(pointData) { return pointData.series.label + ', ' + this.XTickFormatter(pointData.x) + ': ' + this.YTickFormatter(pointData.y); }, getSeries: function() { const yFormat = this.options.data_schema.value.type; const xFormat = this.options.data_schema.label.type; const seriesData = []; _.each(this.data, function(categoryDataSet, category) { const serieData = []; _.each(categoryDataSet, function(categoryData, i) { let yValue = dataFormatter.parseValue(categoryData.value, yFormat); yValue = yValue === null ? parseInt(i) : yValue; let xValue = dataFormatter.parseValue(categoryData.label, xFormat); xValue = xValue === null ? parseInt(i) : xValue; serieData.push([xValue, yValue]); }); seriesData.push({data: serieData, label: category}); }); return seriesData; } }); return StackedBarChartComponent; });
orocrm/platform
src/Oro/Bundle/ChartBundle/Resources/public/js/app/components/stackedbar-chart-component.js
JavaScript
mit
5,780
import makeLoader from "./utilities" import { loginUrlsSuccess } from "../actions/signin" const loginUrlsGet = makeLoader({ defaults: { kind: "loginUrls" }, actionCreators: { actionsSuccess: [loginUrlsSuccess] }, options: { isCached: (state, kind, key) => Object.keys(state.entities[kind]).length } }) export default loginUrlsGet
MerinEREN/iiClient
src/js/middlewares/signin.js
JavaScript
mit
347
(function () { var sammyApp = Sammy('#content', function () { this.get('#/', function () { this.redirect('#/home') }); this.get('#/home', homeController.all); this.get('#/login', usersController.login); this.get('#/register', usersController.register); this.get('#/todos', todosController.all); this.get('#/todos/add', todosController.add); this.get('#/events', eventsController.all); this.get('#/events/add', eventsController.add); }); $(function () { sammyApp.run('#/'); $.ajax('api/categories', { contentType: 'application/json', headers: { 'x-auth-key': localStorage.getItem('SPECIAL-AUTHENTICATION-KEY') }, success: function (categories) { toastr.info(JSON.stringify(categories)); } }) }); } ());
IvayloP/TelerikAcademy2016-2017
JavaScriptApplications/ExamPreparation/self manager/public/js/app.js
JavaScript
mit
927
/* DB access key */ module.exports = { mongo: 'mongodb://localhost:27017/users' }
pursuealong/web
auth/keys.js
JavaScript
mit
85
const letters = { blank: '00000000' + '00000000' + '00000000' + '00000000' + '00000000' + '00000000' + '00000000' + '00000000', A: '00010000' + '00010000' + '00101000' + '00101000' + '01000100' + '01111100' + '10000010' + '10000010', B: '11111100' + '10000010' + '10000010' + '11111100' + '10000010' + '10000010' + '10000010' + '11111100', C: '00111100' + '01000010' + '10000000' + '10000000' + '10000000' + '10000000' + '01000010' + '00111100', Ç: '00111100' + '01000010' + '10000000' + '10000000' + '01000010' + '00111100' + '00001000' + '00011000', D: '11111000' + '10000100' + '10000010' + '10000010' + '10000010' + '10000010' + '10000100' + '11111000', E: '11111110' + '10000000' + '10000000' + '11111000' + '10000000' + '10000000' + '10000000' + '11111110', F: '11111110' + '10000000' + '10000000' + '11111000' + '10000000' + '10000000' + '10000000' + '10000000', G: '00111100' + '01000010' + '10000000' + '10000000' + '10001110' + '10000010' + '01000010' + '00111110', H: '10000010' + '10000010' + '10000010' + '11111110' + '10000010' + '10000010' + '10000010' + '10000010', I: '00010000' + '00010000' + '00010000' + '00010000' + '00010000' + '00010000' + '00010000' + '00010000', J: '00000010' + '00000010' + '00000010' + '00000010' + '00000010' + '10000010' + '01000100' + '00111000', K: '10000010' + '10000100' + '10011000' + '11100000' + '10010000' + '10001000' + '10000100' + '10000010', L: '10000000' + '10000000' + '10000000' + '10000000' + '10000000' + '10000000' + '10000000' + '11111110', M: '10000010' + '11000110' + '10101010' + '10010010' + '10000010' + '10000010' + '10000010' + '10000010', N: '10000010' + '11000010' + '10100010' + '10010010' + '10010010' + '10001010' + '10000110' + '10000010', Ñ: '10111010' + '11000010' + '10100010' + '10010010' + '10010010' + '10001010' + '10000110' + '10000010', O: '00111000' + '01000100' + '10000010' + '10000010' + '10000010' + '10000010' + '01000100' + '00111000', P: '11111100' + '10000010' + '10000010' + '11111100' + '10000000' + '10000000' + '10000000' + '10000000', Q: '00111000' + '01000100' + '10000010' + '10000010' + '10000010' + '10001010' + '01000100' + '00111010', R: '11111000' + '10000100' + '10000010' + '10000100' + '11111000' + '10000100' + '10000010' + '10000010', S: '01111100' + '10000010' + '10000000' + '01111100' + '00000010' + '00000010' + '10000010' + '01111100', T: '11111110' + '00010000' + '00010000' + '00010000' + '00010000' + '00010000' + '00010000' + '00010000', U: '10000010' + '10000010' + '10000010' + '10000010' + '10000010' + '10000010' + '01000100' + '00111000', V: '10000010' + '10000010' + '01000100' + '01000100' + '00101000' + '00101000' + '00010000' + '00010000', W: '10000010' + '10000010' + '10000010' + '10000010' + '10000010' + '10010010' + '01010100' + '00101000', X: '10000010' + '01000100' + '00101000' + '00010000' + '00010000' + '00101000' + '01000100' + '10000010', Y: '10000010' + '01000100' + '00101000' + '00010000' + '00010000' + '00010000' + '00010000' + '00010000', Z: '11111110' + '00000100' + '00001000' + '00010000' + '00100000' + '01000000' + '10000000' + '11111110', '+': '00010000' + '00010000' + '00010000' + '11111110' + '00010000' + '00010000' + '00010000' + '00000000', '-': '00000000' + '00000000' + '00000000' + '11111110' + '00000000' + '00000000' + '00000000' + '00000000', ',': '00000000' + '00000000' + '00000000' + '00000000' + '00000000' + '00010000' + '00010000' + '00100000', '.': '00000000' + '00000000' + '00000000' + '00000000' + '00000000' + '00000000' + '00010000' + '00000000', 'SPACE':'00000000' + '00000000' + '00000000' + '00000000' + '00000000' + '00000000' + '00000000' + '00000000', 'Ú': '00001000' + '00010000' + '10000010' + '10000010' + '10000010' + '10000010' + '01000100' + '00111000', 'TAB': '01000100' + '11101110' + '11111110' + '11111110' + '01111100' + '00111000' + '00010000' + '00010000', '1': '00001000' + '00011000' + '00101000' + '00001000' + '00001000' + '00001000' + '00001000' + '00001000', '2': '00111100' + '01000010' + '00000010' + '00000100' + '00001000' + '00010000' + '00100000' + '01111110', '3': '00111100' + '01000010' + '00000010' + '00111100' + '00000010' + '00000010' + '01000010' + '00111100', '4': '01000010' + '01000010' + '01000010' + '01111110' + '00000010' + '00000010' + '00000010' + '00000010', '5': '01111110' + '01000000' + '01000000' + '01111000' + '00000100' + '00000010' + '00000100' + '01111000', '6': '00111100' + '01000010' + '01000000' + '01011000' + '01100100' + '01000010' + '01000100' + '00111000', '7': '01111110' + '00000010' + '00000100' + '00001000' + '00001000' + '00010000' + '00010000' + '00010000', '8': '00111100' + '01000010' + '01000010' + '00111100' + '01000010' + '01000010' + '01000010' + '00111100', '9': '00111100' + '01000010' + '01000010' + '01000010' + '00111110' + '00000010' + '00000010' + '00000010', '0': '00111100' + '01000010' + '01000010' + '01000010' + '01000010' + '01000010' + '01000010' + '00111100', }; export default letters;
guigrpa/sense-hat
src/letters.js
JavaScript
mit
8,512
'use strict'; var fs = require('fs'); var path = require('path'); var _ = require('lodash'); var gh = require('github-url-to-object'); var shell = require('shelljs'); var yeoman = require('yeoman-generator'); var chalk = require('chalk'); var yosay = require('yosay'); var mkdirp = require('mkdirp'); var getobject = require('getobject').get; var identifyLicense = require('nlf/lib/license-find'); module.exports = yeoman.generators.Base.extend({ initializing: function () { this.pkg = {}; try { this.originalPkg = require(path.join(this.destinationPath(), 'package.json')); } catch(e){} }, prompting: function () { var done = this.async(); // Have Yeoman greet the user. this.log(yosay( 'Welcome to the badass ' + chalk.red('Iceddev') + ' generator!' )); var prompts = [ { type: 'input', name: 'name', message: 'name:', default: this._defaultFromPackage('name', _.kebabCase(this.appname)) }, { type: 'input', name: 'version', message: 'version:', default: this._defaultFromPackage('version', '0.0.0') }, { type: 'input', name: 'description', message: 'description:', default: this._defaultFromPackage('description') }, { type: 'input', name: 'author', message: 'author:', default: this._defaultFromPackage('author', this._findAuthor()), store: true }, { type: 'input', name: 'repository', message: 'repository:', default: this._findRemote() }, { type: 'input', name: 'license', message: 'license:', default: this._defaultFromPackage('license', this._findLicense()) }, { type: 'input', name: 'main', message: 'entry point:', default: this._defaultFromPackage('main', 'index.js') }, { type: 'input', name: 'files', message: 'files in release:', default: this._defaultFromPackage('files') }, { type: 'input', name: 'test', message: 'test command:', default: this._defaultFromPackage('scripts.test') }, { type: 'input', name: 'keywords', message: 'keywords:', default: this._defaultFromPackage('keywords') }, { type: 'confirm', name: 'babel', message: 'use babel?', default: true } ]; this.prompt(prompts, function (props) { var pkg = this.pkg; _.assign(pkg, props); pkg.files = this._formatFiles(pkg.files); if(!pkg.test){ if(props.babel){ pkg.test = 'eslint src/**/*.js'; } else { pkg.test = 'eslint **/*.js'; } } pkg.keywords = this._formatKeywords(pkg.keywords); pkg.description = pkg.description || ''; var contributors = this._fromPackage('contributors', []); pkg.contributors = this._formatList(contributors); pkg.dependencies = this._defaultFromPackage('dependencies', {}); var scripts = { test: pkg.test }; var devDepDefaults = { 'eslint': '^0.23.0' }; if(props.babel){ devDepDefaults.babel = '^5.5.8'; scripts.build = 'babel ./src/ --out-dir ./'; scripts.prepublish = 'npm run build'; } pkg.scripts = this._objectToString(scripts); pkg.devDependencies = this._defaultFromPackage('devDependencies', devDepDefaults); done(); }.bind(this)); }, writing: { app: function () { this.fs.copyTpl( this.templatePath('_package.json'), this.destinationPath('package.json'), this.pkg ); }, babel: function(){ if(this.pkg.babel){ mkdirp.sync('./src/'); } }, projectfiles: function () { this.fs.copy( this.templatePath('editorconfig'), this.destinationPath('.editorconfig') ); this.fs.copy( this.templatePath('gitignore'), this.destinationPath('.gitignore') ); this.fs.copy( this.templatePath('eslintrc'), this.destinationPath('.eslintrc') ); this.fs.copy( this.templatePath('travis.yml'), this.destinationPath('.travis.yml') ); } }, install: function () { this.installDependencies({ bower: false, skipInstall: this.options['skip-install'] }); }, _fromPackage: function(key, fallback){ if(this.originalPkg){ return getobject(this.originalPkg, key); } return fallback; }, _defaultFromPackage: function(key, fallback){ var def = this._fromPackage(key, fallback); if(def == null){ return def; } if(_.isArray(def)){ return def.join(); } if(_.isString(def)){ return def; } return this._objectToString(def); }, _objectToString: function(obj){ return JSON.stringify(obj, null, 4).replace('\n}', '\n }'); }, _findAuthor: function(){ return this.user.git.name() + ' <' + this.user.git.email() + '> (http://iceddev.com)'; }, _findRemote: function(){ var remote; if(shell.which('git')){ remote = gh(shell.exec('git config --get remote.origin.url', { silent: true }).output.trim()); } if(remote){ return remote.user + '/' + remote.repo; } }, _formatFiles: function(input){ var licenses = this._findLicenseFiles(); if(input){ input = input.split(/,|\s/); } var files = _.union(input, licenses, this.main); return this._formatList(files); }, _formatKeywords: function(input){ var keywords = []; if(input){ keywords = input.split(','); } return this._formatList(keywords); }, _formatList: function(list){ var output = _(list) .compact() .map(_.trim) .unique() .sortBy() .value(); return JSON.stringify(output, null, 4).replace('\n]', '\n ]'); }, _findLicenseFiles: function(){ var dest = this.destinationRoot(); var files = fs.readdirSync(dest).filter(function(filename){ filename = filename.toUpperCase(); return filename.indexOf('LICENSE') > -1 || filename.indexOf('LICENCE') > -1; }); return files; }, _findLicense: function(){ var dest = this.destinationRoot(); var files = this._findLicenseFiles(); var license = files.reduce(function(result, filename){ var licenseFile = path.join(dest, filename); if (fs.lstatSync(licenseFile).isFile()) { return identifyLicense(fs.readFileSync(licenseFile, 'utf8')); } return result || null; }, null); return license; } });
iceddev/generator-iceddev
app/index.js
JavaScript
mit
6,785
import os from 'os'; import tty from 'tty'; import hasFlag from 'has-flag'; const {env} = process; let flagForceColor; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) { flagForceColor = 0; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { flagForceColor = 1; } function envForceColor() { if ('FORCE_COLOR' in env) { if (env.FORCE_COLOR === 'true') { return 1; } if (env.FORCE_COLOR === 'false') { return 0; } return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); } } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { const noFlagForceColor = envForceColor(); if (noFlagForceColor !== undefined) { flagForceColor = noFlagForceColor; } const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; if (forceColor === 0) { return 0; } if (sniffFlags) { if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } } if (haveStream && !streamIsTTY && forceColor === undefined) { return 0; } const min = forceColor || 0; if (env.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Windows 10 build 10586 is the first Windows release that supports 256 colors. // Windows 10 build 14931 is the first release that supports 16m/TrueColor. const osRelease = os.release().split('.'); if ( Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; } if (env.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env) { const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { return 1; } if ('COLORTERM' in env) { return 1; } return min; } export function createSupportsColor(stream, options = {}) { const level = _supportsColor(stream, { streamIsTTY: stream && stream.isTTY, ...options }); return translateLevel(level); } const supportsColor = { stdout: createSupportsColor({isTTY: tty.isatty(1)}), stderr: createSupportsColor({isTTY: tty.isatty(2)}) }; export default supportsColor;
sindresorhus/supports-color
index.js
JavaScript
mit
3,060
import chai from 'chai'; const { expect } = chai; import getOppositeVariation from '../../src/popper/utils/getOppositeVariation'; describe('utils/getOppositeVariation', () => { it('should return correct values', () => { expect(getOppositeVariation('start')).to.equal('end'); expect(getOppositeVariation('end')).to.equal('start'); expect(getOppositeVariation('invalid')).to.equal('invalid'); }); });
imkremen/popper.js
tests/unit/getOppositeVariation.js
JavaScript
mit
416
;(function() { 'use strict'; module.exports = (route, condition) => { let logger = route.logger.create('conditional'); let result; let split = condition.split(/\s+/); let func; switch (split[0]) { case 'method': func = method; break; case 'path': func = path; break; case 'parameter': func = parameter; break; default: logger.log(logger.warn, 'invalid condition: {0}', condition); return false; } result = func(route, split); if (result === null) { logger.log(logger.warn, 'invalid {0} condition: {1}', split[0], condition); return false; } logger.log(logger.info, '{0} condition result: {1} === {2}', split[0], condition, result); return result; }; function method(route, condition) { if (condition.length !== 2) { return null; } let result; return result || false; } function path(route, condition) { if (condition.length !== 3) { return null; } let result; let set = route.isOptionalPathSet(condition[1]); switch (condition[2]) { case 'set': result = set; break; case 'unset': result = !set; break; default: return null; } return result || false; } function parameter(route, condition) { if (condition.length !== 3) { return null; } let result; let set = route.getParameter(condition[1]); switch (condition[2]) { case 'set': result = set && set.length > 0; break; case 'unset': result = !set || set.length === 0; break; default: return null; } return result || false; } })();
xabinapal/verlag
conditional.js
JavaScript
mit
1,770
(function (angular) { 'use strict'; angular.module('cherry.signin') .config(['$routeProvider', function($routeProvider) { $routeProvider .when('/signin', { controller: 'signinController', templateUrl: 'modules/signin/views/signin.html' }); }]); })(angular);
robotnoises/CherryTask
app/modules/signin/routes.js
JavaScript
mit
301
// Generated by psc-bundle 0.11.6 var PS = {}; (function(exports) { // Generated by purs version 0.11.6 "use strict"; var Control_Category = PS["Control.Category"]; var $$const = function (a) { return function (v) { return a; }; }; exports["const"] = $$const; })(PS["Data.Function"] = PS["Data.Function"] || {}); (function(exports) { "use strict"; exports.unit = {}; })(PS["Data.Unit"] = PS["Data.Unit"] || {}); (function(exports) { // Generated by purs version 0.11.6 "use strict"; var $foreign = PS["Data.Unit"]; var Data_Show = PS["Data.Show"]; exports["unit"] = $foreign.unit; })(PS["Data.Unit"] = PS["Data.Unit"] || {}); (function(exports) { // Generated by purs version 0.11.6 "use strict"; var $foreign = PS["Data.Functor"]; var Control_Semigroupoid = PS["Control.Semigroupoid"]; var Data_Function = PS["Data.Function"]; var Data_Unit = PS["Data.Unit"]; var Functor = function (map) { this.map = map; }; var map = function (dict) { return dict.map; }; var $$void = function (dictFunctor) { return map(dictFunctor)(Data_Function["const"](Data_Unit.unit)); }; exports["Functor"] = Functor; exports["map"] = map; exports["void"] = $$void; })(PS["Data.Functor"] = PS["Data.Functor"] || {}); (function(exports) { // Generated by purs version 0.11.6 "use strict"; var $foreign = PS["Control.Apply"]; var Control_Category = PS["Control.Category"]; var Data_Function = PS["Data.Function"]; var Data_Functor = PS["Data.Functor"]; var Apply = function (Functor0, apply) { this.Functor0 = Functor0; this.apply = apply; }; var apply = function (dict) { return dict.apply; }; exports["Apply"] = Apply; exports["apply"] = apply; })(PS["Control.Apply"] = PS["Control.Apply"] || {}); (function(exports) { // Generated by purs version 0.11.6 "use strict"; var Control_Apply = PS["Control.Apply"]; var Data_Functor = PS["Data.Functor"]; var Data_Unit = PS["Data.Unit"]; var Applicative = function (Apply0, pure) { this.Apply0 = Apply0; this.pure = pure; }; var pure = function (dict) { return dict.pure; }; var liftA1 = function (dictApplicative) { return function (f) { return function (a) { return Control_Apply.apply(dictApplicative.Apply0())(pure(dictApplicative)(f))(a); }; }; }; exports["Applicative"] = Applicative; exports["liftA1"] = liftA1; exports["pure"] = pure; })(PS["Control.Applicative"] = PS["Control.Applicative"] || {}); (function(exports) { // Generated by purs version 0.11.6 "use strict"; var $foreign = PS["Control.Bind"]; var Control_Applicative = PS["Control.Applicative"]; var Control_Apply = PS["Control.Apply"]; var Control_Category = PS["Control.Category"]; var Data_Function = PS["Data.Function"]; var Data_Functor = PS["Data.Functor"]; var Data_Unit = PS["Data.Unit"]; var Bind = function (Apply0, bind) { this.Apply0 = Apply0; this.bind = bind; }; var bind = function (dict) { return dict.bind; }; exports["Bind"] = Bind; exports["bind"] = bind; })(PS["Control.Bind"] = PS["Control.Bind"] || {}); (function(exports) { // Generated by purs version 0.11.6 "use strict"; var Control_Applicative = PS["Control.Applicative"]; var Control_Apply = PS["Control.Apply"]; var Control_Bind = PS["Control.Bind"]; var Data_Functor = PS["Data.Functor"]; var Data_Unit = PS["Data.Unit"]; var Monad = function (Applicative0, Bind1) { this.Applicative0 = Applicative0; this.Bind1 = Bind1; }; var ap = function (dictMonad) { return function (f) { return function (a) { return Control_Bind.bind(dictMonad.Bind1())(f)(function (v) { return Control_Bind.bind(dictMonad.Bind1())(a)(function (v1) { return Control_Applicative.pure(dictMonad.Applicative0())(v(v1)); }); }); }; }; }; exports["Monad"] = Monad; exports["ap"] = ap; })(PS["Control.Monad"] = PS["Control.Monad"] || {}); (function(exports) { "use strict"; exports.pureE = function (a) { return function () { return a; }; }; exports.bindE = function (a) { return function (f) { return function () { return f(a())(); }; }; }; })(PS["Control.Monad.Eff"] = PS["Control.Monad.Eff"] || {}); (function(exports) { // Generated by purs version 0.11.6 "use strict"; var $foreign = PS["Control.Monad.Eff"]; var Control_Applicative = PS["Control.Applicative"]; var Control_Apply = PS["Control.Apply"]; var Control_Bind = PS["Control.Bind"]; var Control_Monad = PS["Control.Monad"]; var Data_Functor = PS["Data.Functor"]; var Data_Unit = PS["Data.Unit"]; var monadEff = new Control_Monad.Monad(function () { return applicativeEff; }, function () { return bindEff; }); var bindEff = new Control_Bind.Bind(function () { return applyEff; }, $foreign.bindE); var applyEff = new Control_Apply.Apply(function () { return functorEff; }, Control_Monad.ap(monadEff)); var applicativeEff = new Control_Applicative.Applicative(function () { return applyEff; }, $foreign.pureE); var functorEff = new Data_Functor.Functor(Control_Applicative.liftA1(applicativeEff)); exports["functorEff"] = functorEff; exports["applyEff"] = applyEff; exports["applicativeEff"] = applicativeEff; exports["bindEff"] = bindEff; exports["monadEff"] = monadEff; })(PS["Control.Monad.Eff"] = PS["Control.Monad.Eff"] || {}); (function(exports) { "use strict"; exports.newRef = function (val) { return function () { return { value: val }; }; }; exports.readRef = function (ref) { return function () { return ref.value; }; }; exports.writeRef = function (ref) { return function (val) { return function () { ref.value = val; return {}; }; }; }; })(PS["Control.Monad.Eff.Ref"] = PS["Control.Monad.Eff.Ref"] || {}); (function(exports) { // Generated by purs version 0.11.6 "use strict"; var $foreign = PS["Control.Monad.Eff.Ref"]; var Control_Monad_Eff = PS["Control.Monad.Eff"]; var Data_Unit = PS["Data.Unit"]; var Prelude = PS["Prelude"]; exports["newRef"] = $foreign.newRef; exports["readRef"] = $foreign.readRef; exports["writeRef"] = $foreign.writeRef; })(PS["Control.Monad.Eff.Ref"] = PS["Control.Monad.Eff.Ref"] || {}); (function(exports) { /* global window */ "use strict"; exports.window = function () { return window; }; })(PS["DOM.HTML"] = PS["DOM.HTML"] || {}); (function(exports) { // Generated by purs version 0.11.6 "use strict"; var $foreign = PS["DOM.HTML"]; var Control_Monad_Eff = PS["Control.Monad.Eff"]; var DOM = PS["DOM"]; var DOM_HTML_Types = PS["DOM.HTML.Types"]; exports["window"] = $foreign.window; })(PS["DOM.HTML"] = PS["DOM.HTML"] || {}); (function(exports) { "use strict"; exports._requestAnimationFrame = function(fn) { return function(window) { return function() { return window.requestAnimationFrame(fn); }; }; }; })(PS["DOM.HTML.Window"] = PS["DOM.HTML.Window"] || {}); (function(exports) { // Generated by purs version 0.11.6 "use strict"; var Control_Alt = PS["Control.Alt"]; var Control_Alternative = PS["Control.Alternative"]; var Control_Applicative = PS["Control.Applicative"]; var Control_Apply = PS["Control.Apply"]; var Control_Bind = PS["Control.Bind"]; var Control_Category = PS["Control.Category"]; var Control_Extend = PS["Control.Extend"]; var Control_Monad = PS["Control.Monad"]; var Control_MonadZero = PS["Control.MonadZero"]; var Control_Plus = PS["Control.Plus"]; var Data_Bounded = PS["Data.Bounded"]; var Data_Eq = PS["Data.Eq"]; var Data_Function = PS["Data.Function"]; var Data_Functor = PS["Data.Functor"]; var Data_Functor_Invariant = PS["Data.Functor.Invariant"]; var Data_Monoid = PS["Data.Monoid"]; var Data_Ord = PS["Data.Ord"]; var Data_Ordering = PS["Data.Ordering"]; var Data_Semigroup = PS["Data.Semigroup"]; var Data_Show = PS["Data.Show"]; var Data_Unit = PS["Data.Unit"]; var Prelude = PS["Prelude"]; var Nothing = (function () { function Nothing() { }; Nothing.value = new Nothing(); return Nothing; })(); var Just = (function () { function Just(value0) { this.value0 = value0; }; Just.create = function (value0) { return new Just(value0); }; return Just; })(); exports["Nothing"] = Nothing; exports["Just"] = Just; })(PS["Data.Maybe"] = PS["Data.Maybe"] || {}); (function(exports) { // Generated by purs version 0.11.6 "use strict"; var $foreign = PS["DOM.HTML.Window"]; var Control_Monad_Eff = PS["Control.Monad.Eff"]; var Control_Semigroupoid = PS["Control.Semigroupoid"]; var DOM = PS["DOM"]; var DOM_HTML_Types = PS["DOM.HTML.Types"]; var DOM_WebStorage_Types = PS["DOM.WebStorage.Types"]; var Data_Eq = PS["Data.Eq"]; var Data_Functor = PS["Data.Functor"]; var Data_Maybe = PS["Data.Maybe"]; var Data_Newtype = PS["Data.Newtype"]; var Data_Nullable = PS["Data.Nullable"]; var Data_Ord = PS["Data.Ord"]; var Prelude = PS["Prelude"]; var RequestAnimationFrameId = function (x) { return x; }; var requestAnimationFrame = function (fn) { return function ($31) { return Data_Functor.map(Control_Monad_Eff.functorEff)(RequestAnimationFrameId)($foreign._requestAnimationFrame(fn)($31)); }; }; exports["requestAnimationFrame"] = requestAnimationFrame; })(PS["DOM.HTML.Window"] = PS["DOM.HTML.Window"] || {}); (function(exports) { /* global exports */ "use strict"; exports.getCanvasElementByIdImpl = function(id, Just, Nothing) { return function() { var el = document.getElementById(id); if (el && el instanceof HTMLCanvasElement) { return Just(el); } else { return Nothing; } }; }; exports.getContext2D = function(c) { return function() { return c.getContext('2d'); }; }; exports.getCanvasWidth = function(canvas) { return function() { return canvas.width; }; }; exports.getCanvasHeight = function(canvas) { return function() { return canvas.height; }; }; exports.setFillStyle = function(style) { return function(ctx) { return function() { ctx.fillStyle = style; return ctx; }; }; }; exports.setStrokeStyle = function(style) { return function(ctx) { return function() { ctx.strokeStyle = style; return ctx; }; }; }; exports.beginPath = function(ctx) { return function() { ctx.beginPath(); return ctx; }; }; exports.stroke = function(ctx) { return function() { ctx.stroke(); return ctx; }; }; exports.lineTo = function(ctx) { return function(x) { return function(y) { return function() { ctx.lineTo(x, y); return ctx; }; }; }; }; exports.moveTo = function(ctx) { return function(x) { return function(y) { return function() { ctx.moveTo(x, y); return ctx; }; }; }; }; exports.closePath = function(ctx) { return function() { ctx.closePath(); return ctx; }; }; exports.fillRect = function(ctx) { return function(r) { return function() { ctx.fillRect(r.x, r.y, r.w, r.h); return ctx; }; }; }; exports.clearRect = function(ctx) { return function(r) { return function() { ctx.clearRect(r.x, r.y, r.w, r.h); return ctx; }; }; }; exports.save = function(ctx) { return function() { ctx.save(); return ctx; }; }; exports.restore = function(ctx) { return function() { ctx.restore(); return ctx; }; }; })(PS["Graphics.Canvas"] = PS["Graphics.Canvas"] || {}); (function(exports) { // Generated by purs version 0.11.6 "use strict"; var $foreign = PS["Graphics.Canvas"]; var Control_Applicative = PS["Control.Applicative"]; var Control_Bind = PS["Control.Bind"]; var Control_Monad_Eff = PS["Control.Monad.Eff"]; var Control_Monad_Eff_Exception_Unsafe = PS["Control.Monad.Eff.Exception.Unsafe"]; var Control_Semigroupoid = PS["Control.Semigroupoid"]; var Data_ArrayBuffer_Types = PS["Data.ArrayBuffer.Types"]; var Data_Eq = PS["Data.Eq"]; var Data_Function = PS["Data.Function"]; var Data_Function_Uncurried = PS["Data.Function.Uncurried"]; var Data_Functor = PS["Data.Functor"]; var Data_Maybe = PS["Data.Maybe"]; var Data_Semigroup = PS["Data.Semigroup"]; var Data_Show = PS["Data.Show"]; var Prelude = PS["Prelude"]; var withContext = function (ctx) { return function (action) { return function __do() { var v = $foreign.save(ctx)(); var v1 = action(); var v2 = $foreign.restore(ctx)(); return v1; }; }; }; var getCanvasElementById = function (elId) { return $foreign.getCanvasElementByIdImpl(elId, Data_Maybe.Just.create, Data_Maybe.Nothing.value); }; exports["getCanvasElementById"] = getCanvasElementById; exports["withContext"] = withContext; exports["beginPath"] = $foreign.beginPath; exports["clearRect"] = $foreign.clearRect; exports["closePath"] = $foreign.closePath; exports["fillRect"] = $foreign.fillRect; exports["getCanvasHeight"] = $foreign.getCanvasHeight; exports["getCanvasWidth"] = $foreign.getCanvasWidth; exports["getContext2D"] = $foreign.getContext2D; exports["lineTo"] = $foreign.lineTo; exports["moveTo"] = $foreign.moveTo; exports["setFillStyle"] = $foreign.setFillStyle; exports["setStrokeStyle"] = $foreign.setStrokeStyle; exports["stroke"] = $foreign.stroke; })(PS["Graphics.Canvas"] = PS["Graphics.Canvas"] || {}); (function(exports) { "use strict"; exports.cos = Math.cos; exports.sin = Math.sin; exports.pi = Math.PI; })(PS["Math"] = PS["Math"] || {}); (function(exports) { // Generated by purs version 0.11.6 "use strict"; var $foreign = PS["Math"]; exports["cos"] = $foreign.cos; exports["pi"] = $foreign.pi; exports["sin"] = $foreign.sin; })(PS["Math"] = PS["Math"] || {}); (function(exports) { // Generated by purs version 0.11.6 "use strict"; var Control_Applicative = PS["Control.Applicative"]; var Control_Bind = PS["Control.Bind"]; var Control_Monad_Eff = PS["Control.Monad.Eff"]; var Control_Monad_Eff_Ref = PS["Control.Monad.Eff.Ref"]; var DOM = PS["DOM"]; var DOM_HTML = PS["DOM.HTML"]; var DOM_HTML_Types = PS["DOM.HTML.Types"]; var DOM_HTML_Window = PS["DOM.HTML.Window"]; var Data_EuclideanRing = PS["Data.EuclideanRing"]; var Data_Function = PS["Data.Function"]; var Data_Functor = PS["Data.Functor"]; var Data_Maybe = PS["Data.Maybe"]; var Data_Ring = PS["Data.Ring"]; var Data_Semiring = PS["Data.Semiring"]; var Data_Unit = PS["Data.Unit"]; var Graphics_Canvas = PS["Graphics.Canvas"]; var $$Math = PS["Math"]; var Prelude = PS["Prelude"]; var Point3D = function (x) { return x; }; var Point2D = function (x) { return x; }; var Cube = function (x) { return x; }; var Angle3D = function (x) { return x; }; var withStroke = function (ctx) { return function (color) { return function (draw) { return Graphics_Canvas.withContext(ctx)(function __do() { var v = Graphics_Canvas.setStrokeStyle(color)(ctx)(); var v1 = Graphics_Canvas.beginPath(v)(); var v2 = draw(v1)(); var v3 = Graphics_Canvas.closePath(v2)(); return Graphics_Canvas.stroke(v3)(); }); }; }; }; var project = function (v) { return function (v1) { var yRot = v.y * $$Math.cos(v1.qz) - v.x * $$Math.sin(v1.qz); var yRotQx = yRot * $$Math.cos(v1.qx) + v.z * $$Math.sin(v1.qx); var zRotQx = v.z * $$Math.cos(v1.qx) - yRot * $$Math.sin(v1.qx); var xRot = v.x * $$Math.cos(v1.qz) + v.y * $$Math.sin(v1.qz); var xRotQxQy = xRot * $$Math.cos(v1.qy) + zRotQx * $$Math.sin(v1.qy); return { x: xRotQxQy, y: yRotQx }; }; }; var loopAnimation = function (window) { return function (ref) { return function (state) { return function (step) { return Data_Functor["void"](Control_Monad_Eff.functorEff)(DOM_HTML_Window.requestAnimationFrame(function __do() { loopAnimation(window)(ref)(state)(step)(); var v = Control_Monad_Eff_Ref.readRef(ref)(); var v1 = step(v)(); return Control_Monad_Eff_Ref.writeRef(ref)(v1)(); })(window)); }; }; }; }; var withAnimation = function (state) { return function (step) { return function __do() { var v = DOM_HTML.window(); var v1 = Control_Monad_Eff_Ref.newRef(state)(); return loopAnimation(v)(v1)(state)(step)(); }; }; }; var drawLine = function (ctx) { return function (v) { return function (v1) { return function __do() { var v2 = Graphics_Canvas.moveTo(ctx)(v.x)(v.y)(); return Graphics_Canvas.lineTo(v2)(v1.x)(v1.y)(); }; }; }; }; var drawCube = function (ctx) { return function (v) { return function (v1) { var half = v.size / 2.0; var v11 = project({ x: v.x - half, y: v.y - half, z: v.z - half })({ qx: v1.qx, qy: v1.qy, qz: v1.qz }); var v2 = project({ x: v.x - half, y: v.y + half, z: v.z - half })({ qx: v1.qx, qy: v1.qy, qz: v1.qz }); var v3 = project({ x: v.x - half, y: v.y - half, z: v.z + half })({ qx: v1.qx, qy: v1.qy, qz: v1.qz }); var v4 = project({ x: v.x - half, y: v.y + half, z: v.z + half })({ qx: v1.qx, qy: v1.qy, qz: v1.qz }); var v5 = project({ x: v.x + half, y: v.y - half, z: v.z - half })({ qx: v1.qx, qy: v1.qy, qz: v1.qz }); var v6 = project({ x: v.x + half, y: v.y + half, z: v.z - half })({ qx: v1.qx, qy: v1.qy, qz: v1.qz }); var v7 = project({ x: v.x + half, y: v.y - half, z: v.z + half })({ qx: v1.qx, qy: v1.qy, qz: v1.qz }); var v8 = project({ x: v.x + half, y: v.y + half, z: v.z + half })({ qx: v1.qx, qy: v1.qy, qz: v1.qz }); return withStroke(ctx)(v.color)(function (ctx2) { return function __do() { var v9 = drawLine(ctx2)(v11)(v5)(); var v10 = drawLine(v9)(v5)(v6)(); var v12 = drawLine(v10)(v6)(v2)(); var v13 = drawLine(v12)(v2)(v11)(); var v14 = drawLine(v13)(v3)(v7)(); var v15 = drawLine(v14)(v7)(v8)(); var v16 = drawLine(v15)(v8)(v4)(); var v17 = drawLine(v16)(v4)(v3)(); var v18 = drawLine(v17)(v11)(v3)(); var v19 = drawLine(v18)(v5)(v7)(); var v20 = drawLine(v19)(v6)(v8)(); return drawLine(v20)(v2)(v4)(); }; }); }; }; }; var drawBackground = function (ctx) { return function __do() { var v = Graphics_Canvas.setFillStyle("rgb(255,255,255)")(ctx)(); return Graphics_Canvas.fillRect(v)({ x: 0.0, y: 0.0, w: 1000.0, h: 700.0 })(); }; }; var clearCanvas = function (canvas) { return function __do() { var v = Graphics_Canvas.getCanvasWidth(canvas)(); var v1 = Graphics_Canvas.getCanvasHeight(canvas)(); var v2 = Graphics_Canvas.getContext2D(canvas)(); return Data_Functor["void"](Control_Monad_Eff.functorEff)(Graphics_Canvas.clearRect(v2)({ x: 0.0, y: 0.0, w: v, h: v1 }))(); }; }; var withAnimateContext = function (name) { return function (state) { return function (draw) { return function __do() { var v = Graphics_Canvas.getCanvasElementById(name)(); if (v instanceof Data_Maybe.Just) { var v1 = Graphics_Canvas.getContext2D(v.value0)(); return withAnimation(state)(function (state1) { return function __do() { clearCanvas(v.value0)(); return draw(v1)(state1)(); }; })(); }; if (v instanceof Data_Maybe.Nothing) { return Data_Unit.unit; }; throw new Error("Failed pattern match at Main line 144, column 3 - line 150, column 25: " + [ v.constructor.name ]); }; }; }; }; var main = (function () { var state = { x: 300.0, y: 600.0, qx: $$Math.pi / 4.0, qy: $$Math.pi / 3.0, qz: $$Math.pi / 4.0, acc: 0.998, drag: false }; var canvas = Graphics_Canvas.getCanvasElementById("thecanvas"); return withAnimateContext("thecanvas")(state)(function (ctx) { return function (state1) { return function __do() { var v = drawBackground(ctx)(); Data_Functor["void"](Control_Monad_Eff.functorEff)(drawCube(v)({ x: state1.x, y: state1.y, z: 0.0, size: 200.0, color: "rgb(0,1,0)" })({ qx: state1.qx, qy: state1.qy, qz: state1.qz }))(); var $85 = {}; for (var $86 in state1) { if ({}.hasOwnProperty.call(state1, $86)) { $85[$86] = state1[$86]; }; }; $85.x = state1.x; $85.y = state1.y; $85.qx = state1.qx + 5.0e-3; $85.qy = state1.qy + 5.0e-3; $85.qz = state1.qz + 5.0e-3; return $85; }; }; }); })(); exports["Angle3D"] = Angle3D; exports["Cube"] = Cube; exports["Point2D"] = Point2D; exports["Point3D"] = Point3D; exports["clearCanvas"] = clearCanvas; exports["drawBackground"] = drawBackground; exports["drawCube"] = drawCube; exports["drawLine"] = drawLine; exports["loopAnimation"] = loopAnimation; exports["main"] = main; exports["project"] = project; exports["withAnimateContext"] = withAnimateContext; exports["withAnimation"] = withAnimation; exports["withStroke"] = withStroke; })(PS["Main"] = PS["Main"] || {}); PS["Main"].main();
vooha123/cube
tryps.js
JavaScript
mit
25,737