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
$(document).ready(function(){ //enable the return time input and dropdown $("#round").change(function() { if(this.checked) { console.log("Return data field open!"); $("#rD").removeClass('ui disabled input').addClass('ui input'); $("#rY").removeClass('ui disabled input').addClass('ui input'); $("#retMonth").removeClass('ui disabled dropdown').addClass('ui dropdown'); } else { console.log("Return data field close!"); $("#rD").removeClass('ui input').addClass('ui disabled input'); $("#rY").removeClass('ui input').addClass('ui disabled input'); $("#retMonth").removeClass('ui dropdown').addClass('ui disabled dropdown'); } }); //check if the input is a valid format function validateForm() { numdays = [31,28,31,30,31,30,31,31,30,31,30,31]; namemonth = ["January","Feburary","March","April","May","June","July","August","September","October","November","December"]; if ($("#dpYear").val() == "" || $("#dpMonth").val() == "" || $("#dpDay").val() == "" || $("#origin").val() == "" || $("#des").val() == "" || $('#num').val() == "" || $("#email").val() == "" || $("#waiting").val() == "") { console.log("not fill in all the blanks") alert("Please fill in all fields"); return false; } if ($("#dpYear").val().length != 4 || $("#dpDay").val().length != 2) { console.log("invalid departure date or year") alert("Please enter valid departure date or year in the format of DD and YYYY.") return false; } if ($("#origin").val().length != 3 || $("#des").val().length != 3 || /^[a-zA-Z]+$/.test($("#origin").val()) == false || /^[a-zA-Z]+$/.test($("#des").val()) == false ) { console.log("invalid input for destination or origin"); alert("Please enter valid airport code.") return false; } if ($("#origin").val() == $("#des").val()) { console.log("same origin and destination"); alert("You cannot enter same value for origin and destination"); return false; } console.log("fields valid!") var today = new Date(); if (parseInt($("#dpYear").val()) < today.getFullYear()) { alert("You cannot check past ticket's value"); return false; } else { if (parseInt($("#dpYear").val()) == today.getFullYear()) { if (parseInt($("#dpMonth").val()) < today.getMonth()+1 ) { alert("You cannot check past ticket's value"); return false; } else { if (parseInt($("#dpMonth").val()) == today.getMonth()+1 ) { if (parseInt($("#dpDay").val()) < today.getDate()) { alert("You cannot check past ticket's value"); return false; } } } } } console.log("departure date valid!") if ($("#round").is(':checked')) { console.log("roundtrip checked!") if ($("#retYear").val() == "" || $("#retMonth").val() == "" || $("#retDay").val() == "" ) { alert("please enter return date"); return false; } if ($("#retYear").val().length != 4 || $("#retDay").val().length != 2) { console.log("invalid return date or year") alert("Please enter valid return date or year in the format of DD and YYYY.") return false; } if (parseInt($("#retYear").val()) < parseInt($("#dpYear").val())) { alert("Return date cannot be before departure date."); return false; } else { if (parseInt($("#retYear").val()) == parseInt($("#dpYear").val())) { if (parseInt($("#retMonth").val()) < parseInt($("#dpMonth").val()) ) { alert("Return date cannot be before departure date."); return false; } else { if (parseInt($("#retMonth").val()) == parseInt($("#dpMonth").val()) ) { if (parseInt($("#retDay").val()) < parseInt($("#dpDay").val())) { alert("Return date cannot be before departure date."); return false; } } } } } } console.log("return date valid!") if ($("#dpMonth").val() == "2" && parseInt($("#dpYear".val()))%4 == 0 && parseInt($("#dpYear".val()))%100 != 0) { if (parseInt($("#dpDay".val())) > 29) { alert(namemonth[parseInt($("#dpMonth").val())-1]+" does not have more than 29 days"); return false; } } else { var m = parseInt($("#dpMonth").val()); if ( parseInt($("#dpDay").val()) > numdays[m-1]) { alert(namemonth[m-1]+" does not have more than "+numdays[m-1]+" days"); return false; } } return true; } //send the user data to server //not using the form submit function as the it will not reveive the data $("#sub").click(function() { if (validateForm()) { var rq = {}; rq.origin = $("#origin").val(); rq.destination = $("#des").val(); rq.dpdate = $("#dpYear").val()+'-'+$("#dpMonth").val()+'-'+$("#dpDay").val(); rq.waiting = parseInt(parseFloat($("#waiting").val())*60); rq.num = parseInt($('#num').val()); rq.email = $("#email").val(); rq.round = 0; if ($("#round").is(':checked')) { rq.round = 1; rq.retdate = $("#retYear").val()+'-'+$("#retMonth").val()+'-'+$("#retDay").val(); } console.log("data post to server formed!"); $.ajax({ type: "POST", url: "/user", dataType: 'json', contentType: 'application/json', data: JSON.stringify(rq), success: function(data) { alert("Data goes into our system!"); }, error: function(error) { console.log(error); alert("Unable to send!"); } }); } }); });
yanx611/Flightonight
public/resources/main.js
JavaScript
mit
6,549
(function(){ angular.module('list-products', []) .directive('productInfo', function() { return { restrict: 'E', templateUrl: 'partials/product-info.html' } }) .directive('productForm', function() { return { restrict: 'E', templateUrl: 'partials/product-form.html', controller: function() { this.review = {}; this.item = {mark:{}}; this.addReview = function(item) { item.reviews.push(this.review); this.review = {}; }; }, controllerAs: 'reviewCtrl', scope: { items: "=", marks: "=" } }; }) .directive('productPanels', function() { return { restrict: 'E', templateUrl: 'partials/product-panels.html', controller: function(){ this.tab = 1; this.selectTab = function(setTab) { this.tab = setTab; }; this.isSelected = function(checkTab) { return checkTab === this.tab; }; }, controllerAs: 'panelCtrl', scope: { items: "=", marks: "=" } }; }); })();
portojs/angular-project-1
app/products.js
JavaScript
mit
1,211
angular.module('material.animations') .directive('inkRipple', [ '$materialInkRipple', InkRippleDirective ]) .factory('$materialInkRipple', [ '$window', '$$rAF', '$materialEffects', '$timeout', InkRippleService ]); function InkRippleDirective($materialInkRipple) { return function(scope, element, attr) { if (attr.inkRipple == 'checkbox') { $materialInkRipple.attachCheckboxBehavior(element); } else { $materialInkRipple.attachButtonBehavior(element); } }; } function InkRippleService($window, $$rAF, $materialEffects, $timeout) { // TODO fix this. doesn't support touch AND click devices (eg chrome pixel) var hasTouch = !!('ontouchend' in document); var POINTERDOWN_EVENT = hasTouch ? 'touchstart' : 'mousedown'; var POINTERUP_EVENT = hasTouch ? 'touchend touchcancel' : 'mouseup mouseleave'; return { attachButtonBehavior: attachButtonBehavior, attachCheckboxBehavior: attachCheckboxBehavior, attach: attach }; function attachButtonBehavior(element) { return attach(element, { mousedown: true, center: false, animationDuration: 350, mousedownPauseTime: 175, animationName: 'inkRippleButton', animationTimingFunction: 'linear' }); } function attachCheckboxBehavior(element) { return attach(element, { mousedown: true, center: true, animationDuration: 300, mousedownPauseTime: 180, animationName: 'inkRippleCheckbox', animationTimingFunction: 'linear' }); } function attach(element, options) { // Parent element with noink attr? Abort. if (element.controller('noink')) return angular.noop; options = angular.extend({ mousedown: true, hover: true, focus: true, center: false, animationDuration: 300, mousedownPauseTime: 150, animationName: '', animationTimingFunction: 'linear' }, options || {}); var rippleContainer; var node = element[0]; if (options.mousedown) { listenPointerDown(true); } // Publish self-detach method if desired... return function detach() { listenPointerDown(false); if (rippleContainer) { rippleContainer.remove(); } }; function listenPointerDown(shouldListen) { element[shouldListen ? 'on' : 'off'](POINTERDOWN_EVENT, onPointerDown); } function rippleIsAllowed() { return !Util.isParentDisabled(element); } function createRipple(left, top, positionsAreAbsolute) { var rippleEl = angular.element('<div class="material-ripple">') .css($materialEffects.ANIMATION_DURATION, options.animationDuration + 'ms') .css($materialEffects.ANIMATION_NAME, options.animationName) .css($materialEffects.ANIMATION_TIMING, options.animationTimingFunction) .on($materialEffects.ANIMATIONEND_EVENT, function() { rippleEl.remove(); }); if (!rippleContainer) { rippleContainer = angular.element('<div class="material-ripple-container">'); element.append(rippleContainer); } rippleContainer.append(rippleEl); var containerWidth = rippleContainer.prop('offsetWidth'); if (options.center) { left = containerWidth / 2; top = rippleContainer.prop('offsetHeight') / 2; } else if (positionsAreAbsolute) { var elementRect = node.getBoundingClientRect(); left -= elementRect.left; top -= elementRect.top; } var css = { 'background-color': $window.getComputedStyle(rippleEl[0]).color || $window.getComputedStyle(node).color, 'border-radius': (containerWidth / 2) + 'px', left: (left - containerWidth / 2) + 'px', width: containerWidth + 'px', top: (top - containerWidth / 2) + 'px', height: containerWidth + 'px' }; css[$materialEffects.ANIMATION_DURATION] = options.fadeoutDuration + 'ms'; rippleEl.css(css); return rippleEl; } function onPointerDown(ev) { if (!rippleIsAllowed()) return; var rippleEl = createRippleFromEvent(ev); var ripplePauseTimeout = $timeout(pauseRipple, options.mousedownPauseTime, false); rippleEl.on('$destroy', cancelRipplePause); // Stop listening to pointer down for now, until the user lifts their finger/mouse listenPointerDown(false); element.on(POINTERUP_EVENT, onPointerUp); function onPointerUp() { cancelRipplePause(); rippleEl.css($materialEffects.ANIMATION_PLAY_STATE, 'running'); element.off(POINTERUP_EVENT, onPointerUp); listenPointerDown(true); } function pauseRipple() { rippleEl.css($materialEffects.ANIMATION_PLAY_STATE, 'paused'); } function cancelRipplePause() { $timeout.cancel(ripplePauseTimeout); } function createRippleFromEvent(ev) { ev = ev.touches ? ev.touches[0] : ev; return createRipple(ev.pageX, ev.pageY, true); } } } }
mauricionr/material
src/components/animate/inkCssRipple.js
JavaScript
mit
5,058
var boletesPinya = $.merge($.merge($.merge($("#cDB").find("path"), $("#cB4").find("path")), $("#cB3").find("path")), $("#cB2").find("path")); var boletesTronc = $.merge($.merge($("#cB4").find("path"), $("#cB3").find("path")), $("#cB2").find("path")); var usedTweets = {}; $(document).ready(function () { $.each(boletesPinya, function (i, e) { $(e).tooltipster({ delay: 100, maxWidth: 500, speed: 300, interactive: true, content: '', contentAsHTML: true, animation: 'grow', trigger: 'custom', contentCloning: false }); }); }); function initTweets() { var path = EMOCIO.properties[lastEmotionPlayed].name + ".php"; $.ajax({ type: 'GET', url: path, success: function (data) { var tweets = null; var text, user, hashtag, ttContent, img; tweets = JSON.parse(data); $(boletesPinya).shuffle().each(function (i, e) { var cTweet = tweets.statuses[i]; if (typeof cTweet === 'undefined') return false; var content = buildContent(cTweet); if (content !== false) { $(e).tooltipster('content', content); themesAndEvents(e); } }); }, error: function (res) { alert("Error finding tweets"); } }); } function actualitzarTweets() { var path = EMOCIO.properties[lastEmotionPlayed].name + ".php"; resetTooltips(); $.ajax({ type: 'GET', url: path, success: function (data) { var tweets = null; var text, img, user, hashtag, ttContent, url; tweets = JSON.parse(data); var boletes = boletesPinya; if (fase >= FASE.Tercos) boletes = boletesTronc; $(boletes).shuffle().each(function (i, e) { var currentTweet = tweets.statuses[i]; if (typeof currentTweet === 'undefined') return false; var content = buildContent(currentTweet); if (content !== false) { $(e).tooltipster('content', content); themesAndEvents(e); } }); }, error: function (res) { alert("Error finding tweets"); } }); } function buildContent(info) { var tweet = info; if (DictContainsValue(usedTweets, tweet.id_str) || typeof tweet === 'undefined') { usedTweets[tweet.id_str] = usedTweets[tweet.id_str] + 1; return false; } usedTweets[tweet.id_str] = 1; var text = tweet.full_text; var user = "@" + tweet.user.screen_name + ": "; var img = ''; var url = 'href="https://twitter.com/statuses/' + tweet.id_str + '" target="_blank"'; if ((typeof tweet.entities.media !== "undefined") && (tweet.entities.media !== null)) { var media = tweet.entities.media; img = '<div class="row">' + '<div class="col">' + '<img style="max-width: 75%; height: auto;" class="rounded mx-auto d-block" src=\'' + media[0].media_url_https + '\'/>' + '</div></div>'; text = text.replace(' ' + tweet.entities.media[0].url, ''); } return $('<a '+ url +'>' + img + '<div class="row"><div class="col text-left"><p style="margin-bottom: 0 !important;"><b>' + user + '</b>' + text + '</p></div></div></a>'); } function themesAndEvents(e) { var theme = 'tooltipster-' + EMOCIO.properties[lastEmotionPlayed].name.toString(); $(e).tooltipster('option', 'theme', theme); $(e).tooltipster('option', 'trigger', 'click'); $(e).mouseenter(function () { if (lastEmotionPlayed !== null) { $(this).css("fill", EMOCIO.properties[lastEmotionPlayed].color).css("cursor", "pointer"); $(this).addClass("pathHover"); } }).mouseleave(function () { if (lastEmotionPlayed !== null) { var gradient = "url(#gradient" + EMOCIO.properties[lastEmotionPlayed].name.toString().charAt(0).toUpperCase() + EMOCIO.properties[lastEmotionPlayed].name.substr(1) + ")"; $(this).css("fill", gradient).css("cursor", "default"); $(this).removeClass("pathHover"); } }); } function resetTooltips() { usedTweets = {}; $.each(boletesPinya, function (i, e) { $(e).tooltipster('destroy'); $(e).off(); $(e).unbind("mouseenter"); $(e).unbind("mouseleave"); }); $.each(boletesPinya, function (i, e) { $(e).tooltipster({ delay: 100, maxWidth: 500, speed: 300, interactive: true, content: '', contentAsHTML: true, animation: 'grow', trigger: 'custom', contentCloning: false }); }); }
MPapus/QuanHiSomTots
js/tweets.js
JavaScript
mit
5,021
var sc1 = { //funhouse mirror setup:function(){ // videoSetup(); tree = new TREE(); tree.generate({ joints: [5,3,1,10], divs: [1], start: [0,0,2,0], angles: [0,Math.PI/2,1], length: [20,15,4,1], rads: [1,2,1,3], width: [1,2,2,1] }); scene.add(tree); tree.position.y=-50; console.log(tree); var ball = new THREE.SphereGeometry(15,15,15); var ball2 = new THREE.Geometry(); tree.xform(tree.makeInfo([ [0,0,"all"],{ballGeo:ball,ballGeo2:ball2}, ]),tree.setGeo); tree.xform(tree.makeInfo([ [0,0,"all"],{ty:-15}, ]),function(obj,args){obj.children[0].children[0].position.y=7.5;}); // scene.add(tree.makeTubes({minWidth:1,func:function(t){return Math.sin(t)*2}})); }, draw:function(time){ time=time*3; tree.position.y = -40+Math.sin(omouseY*Math.PI*4)*3; tree.xform(tree.makeInfo([ [0,0,[1,5]],{rz:omouseX,ry:omouseY,sc:.9}, //legs [0,0,0,[0,1],1],{rz:Math.PI/2}, [0,0,0,[0,1],1],{ry:omouseX*3}, [0,0,0,[0,1],2],{rx:omouseY*3}, //feet [0,0,0,[0,1],0,0,0],{rz:0}, [0,0,0,[0,1],0,0,0],{rx:omouseY*3}, [0,0,[0,4],[0,1],0],{ty:-10}, [0,0,[1,4],[0,1],[1,2]],{rz:mouseY,freq:1,offMult:.2,off:time}, //fingers [0,0,[1,4],[0,1],0,0,0,[0,2],"all"],{rz:0,freq:1,offMult:.2,off:time}, [0,0,[1,4],[0,1],0,0,0],{rz:0,freq:1,offMult:.3,off:time+.2}, //feet [0,0,0,[0,1],0,0,0,[0,2],"all"],{ry:0,rz:omouseY*.1,sc:.9}, [0,0,0,0,0,0,0,[0,2],0],{sc:2,ry:-2*omouseY+1.5,rz:1}, [0,0,0,1,0,0,0,[0,2],0],{sc:2,ry:-2*omouseY-1.5,rz:1}, //toes [0,0,0,0,0,0,0,[0,2],0],{sc:2,ry:0,freq:1,offMult:.2 ,offsetter2:.5}, [0,0,0,1,0,0,0,[0,2],0],{sc:2,ry:Math.PI-.3,freq:1,offMult:.2,offsetter2:.5}, ]),tree.transform); } }
dlobser/treejs
sketches/sc27.js
JavaScript
mit
1,772
'use strict'; // 頑シミュさんの装飾品検索の結果と比較しやすくする function simplifyDecombs(decombs) { return decombs.map(decomb => { let torsoUp = Object.keys(decomb).map(part => decomb[part]).some(comb => { if (comb == null) return false; return comb.skills['胴系統倍加'] ? true : false; }); let names = []; Object.keys(decomb).forEach(part => { let comb = decomb[part]; let decos = comb ? comb.decos : []; if (torsoUp && part === 'body') decos = decos.map(deco => deco += '(胴)'); names = names.concat(decos); }); return names.sort().join(','); }); } exports.simplifyDecombs = simplifyDecombs;
sakusimu/mh-skillsimu
test/support/util.js
JavaScript
mit
755
"use strict"; let datafire = require('datafire'); let openapi = require('./openapi.json'); module.exports = datafire.Integration.fromOpenAPI(openapi, "billbee");
DataFire/Integrations
integrations/generated/billbee/index.js
JavaScript
mit
161
// Generated by CoffeeScript 1.6.3 /*! @author Branko Vukelic <[email protected]> @license MIT */ var _this = this; if (typeof define !== 'function' || !define.amd) { this.require = function(dep) { return (function() { switch (dep) { case 'jquery': return _this.jQuery; default: return null; } })() || (function() { throw new Error("Unmet dependency " + dep); })(); }; this.define = function(factory) { return _this.ribcage.utils.deserializeForm = factory(_this.require); }; } define(function(require) { var $; $ = require('jquery'); $.deserializeForm = function(form, data) { form = $(form); form.find(':input').each(function() { var currentValue, input, name, type; input = $(this); name = input.attr('name'); type = input.attr('type'); currentValue = input.val(); if (!name) { return; } switch (type) { case 'checkbox': return input.prop('checked', data[name] === 'on'); case 'radio': return input.prop('checked', data[name] === currentValue); default: return input.val(data[name]); } }); return form; }; $.fn.deserializeForm = function(data) { return $.deserializeForm(this, data); }; return $.deserializeForm; });
foxbunny/ribcage
utils/deserializeform.js
JavaScript
mit
1,357
'use strict' module.exports = function (config) { if (!process.env.COOKING_PATH) { return } const rootPath = process.env.COOKING_PATH.split(',') config.resolve = config.resolve || {} config.resolveLoader = config.resolveLoader || {} config.resolve.modules = (config.resolve.root || []).concat(rootPath) config.resolveLoader.modules = (config.resolveLoader.root || []).concat(rootPath) }
ElemeFE/cooking
packages/cooking/util/load-resolve-path.js
JavaScript
mit
408
var xhrGet = function (url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.onload = callback; xhr.send(); };
denys-liubushkin/Elemental-Tower
js/xhr.js
JavaScript
mit
147
/*jslint browser: true*/ /*global Tangram, gui */ map = (function () { 'use strict'; var locations = { 'Yangon': [16.8313077,96.2187007,7] }; var map_start_location = locations['Yangon']; /*** Map ***/ var map = L.map('map', {"keyboardZoomOffset" : .05, maxZoom: 20 } ); var layer = Tangram.leafletLayer({ scene: 'cinnabar-style-more-labels.yaml?r=2', attribution: '<a href="https://mapzen.com/tangram" target="_blank">Tangram</a> | &copy; OSM contributors | <a href="https://mapzen.com/" target="_blank">Mapzen</a>' }); window.layer = layer; var scene = layer.scene; window.scene = scene; // setView expects format ([lat, long], zoom) map.setView(map_start_location.slice(0, 3), map_start_location[2]); function long2tile(lon,zoom) { return (Math.floor((lon+180)/360*Math.pow(2,zoom))); } function lat2tile(lat,zoom) { return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom))); } /***** Render loop *****/ function addGUI () { // Link to edit in OSM - hold 'e' and click } // Feature selection function initFeatureSelection () { // Selection info shown on hover var selection_info = document.createElement('div'); selection_info.setAttribute('class', 'label'); selection_info.style.display = 'block'; // Show selected feature on hover scene.container.addEventListener('mousemove', function (event) { var pixel = { x: event.clientX, y: event.clientY }; scene.getFeatureAt(pixel).then(function(selection) { if (!selection) { return; } var feature = selection.feature; if (feature != null) { // console.log("selection map: " + JSON.stringify(feature)); var label = ''; if (feature.properties.name != null) { label = feature.properties.name; } if (label != '') { selection_info.style.left = (pixel.x + 5) + 'px'; selection_info.style.top = (pixel.y + 15) + 'px'; selection_info.innerHTML = '<span class="labelInner">' + label + '</span>'; scene.container.appendChild(selection_info); } else if (selection_info.parentNode != null) { selection_info.parentNode.removeChild(selection_info); } } else if (selection_info.parentNode != null) { selection_info.parentNode.removeChild(selection_info); } }); // Don't show labels while panning if (scene.panning == true) { if (selection_info.parentNode != null) { selection_info.parentNode.removeChild(selection_info); } } }); // Show selected feature on hover scene.container.addEventListener('click', function (event) { var pixel = { x: event.clientX, y: event.clientY }; scene.getFeatureAt(pixel).then(function(selection) { if (!selection) { return; } var feature = selection.feature; if (feature != null) { // console.log("selection map: " + JSON.stringify(feature)); var label = ''; if (feature.properties != null) { // console.log(feature.properties); var obj = JSON.parse(JSON.stringify(feature.properties)); for (var x in feature.properties) { var val = feature.properties[x] label += "<span class='labelLine' key="+x+" value="+val+" onclick='setValuesFromSpan(this)'>"+x+" : "+val+"</span><br>" } } if (label != '') { selection_info.style.left = (pixel.x + 5) + 'px'; selection_info.style.top = (pixel.y + 15) + 'px'; selection_info.innerHTML = '<span class="labelInner">' + label + '</span>'; scene.container.appendChild(selection_info); } else if (selection_info.parentNode != null) { selection_info.parentNode.removeChild(selection_info); } } else if (selection_info.parentNode != null) { selection_info.parentNode.removeChild(selection_info); } }); // Don't show labels while panning if (scene.panning == true) { if (selection_info.parentNode != null) { selection_info.parentNode.removeChild(selection_info); } } }); } window.addEventListener('load', function () { // Scene initialized layer.on('init', function() { addGUI(); //initFeatureSelection(); }); layer.addTo(map); }); return map; }());
mapmeld/mvoter-usage
main.js
JavaScript
mit
4,919
var height = window.innerHeight; // console.log(height); var main = document.getElementById('main'); var btn = document.getElementById("btn"); main.style.height = height + 'px'; btn.style.top = (height-90) + 'px'; document.getElementById('usr_name').onkeydown = function(e) { e = e || event; if(e.keyCode === 13) { btn.click(); } }; btn.addEventListener("click", function() { var name = document.getElementById("usr_name").value; name = name.replace(/(^\s*)|(\s*$)/g, ""); if(name=='') { alert("请填写用户名哦!"); return false; } var url = window.location.href; var splited = url.split('/'); var roomID = splited[splited.length - 1]; ajax({ url: "/login/"+roomID, //请求地址 type: "POST", //请求方式 data: {new_topic:true,username: name}, //请求参数 dataType: "json", success: function (data) { data=JSON.parse(data); if(data.status==1){ //alert("登录成功"); window.location.href="/show"; } else if(data.status==0){ alert("已经有人登录了哦"); } // 此处放成功后执行的代码 }, fail: function (status) { // 此处放失败后执行的代码 } }); });
Jfmaily/Draw-Guess
public/javascripts/index.js
JavaScript
mit
1,201
/* * default/mouse-push-button.js */ "use strict"; var Q = require('q'), Button = require('./../../button'); var MousePushButton = function (options) { Button.prototype.constructor.call(this, options); this.delay = options.delay > 0 ? options.delay : 0; this.g = null; if(typeof options.g === 'function') this.g = options.g; this.promisef = null; this.boundaries = { minX : 0, maxX : 0, minY : 0, maxY : 0 }; this.leftOrEnded = false; }; MousePushButton.prototype = (function (proto) { function F() {}; F.prototype = proto; return new F(); })(Button.prototype); MousePushButton.prototype.constructor = MousePushButton; MousePushButton.prototype.setG = function (g) { if (typeof g !== 'function') throw new Error("Button setG method needs a g function as argument."); this.g = g; return this; }; MousePushButton.prototype._isInActiveZone = function (touch) { var x = touch.clientX, y = touch.clientY, b = this.boundaries; return x < b.maxX && x > b.minX && y < b.maxY && y > b.minY; }; MousePushButton.prototype.bind = function () { Button.prototype.bind.call(this); this.el.addEventListener('mousedown', this, false); this.binded = true; return this; }; MousePushButton.prototype.unbind = function () { Button.prototype.unbind.call(this); this.el.removeEventListener('mousedown', this, false); this.binded = false; return this; }; MousePushButton.prototype.handleEvent = function (evt) { switch (evt.type) { case 'mousedown': this.onMousedown(evt); break; case 'mousemove': this.onMousemove(evt); break; case 'mouseup': this.onMouseup(evt); break; } }; MousePushButton.prototype.onMousedown = function (evt) { if (!this.active) { if (evt.button === 0) { evt.preventDefault(); this.setActive(true); var boundingRect = this.el.getBoundingClientRect(); this.boundaries.minX = boundingRect.left; this.boundaries.maxX = boundingRect.left + boundingRect.width; this.boundaries.minY = boundingRect.top; this.boundaries.maxY = boundingRect.bottom; this.el.ownerDocument.addEventListener('mousemove', this, false); this.el.ownerDocument.addEventListener('mouseup', this, false); this.promisef = Q.delay(evt, this.delay).then(this.f); } } }; MousePushButton.prototype.onMousemove = function (evt) { if(this.active && !this.leftOrEnded) { evt.preventDefault(); if (!this._isInActiveZone(evt)) this.onMouseup(evt); } }; MousePushButton.prototype.onMouseup = function (evt) { if(this.active && !this.leftOrEnded) { this._removeCls(); this.leftOrEnded = true; this.promisef .then(evt) .then(this.g) .finally(this._done(evt)) .done(); } }; MousePushButton.prototype._done = function (evt) { var btn = this; return function () { btn.setActive(false); btn.leftOrEnded = false; btn.el.ownerDocument.removeEventListener('mousemove', btn, false); btn.el.ownerDocument.removeEventListener('mouseup', btn, false); }; }; module.exports = MousePushButton;
peutetre/mobile-button
lib/mouse/default/mouse-push-button.js
JavaScript
mit
3,393
const industry = [ { "name": "金融", "children": [ { "name": "银行" }, { "name": "保险" }, { "name": "证券公司" }, { "name": "会计/审计" }, { "name": "其它金融服务" } ] }, { "name": "专业服务", "children": [ { "name": "科研/教育" }, { "name": "顾问/咨询服务" }, { "name": "法律服务" }, { "name": "医疗/保健" }, { "name": "其它专业服务" } ] }, { "name": "政府", "children": [ { "name": "政府机关" }, { "name": "协会/非赢利性组织" } ] }, { "name": "IT/通信", "children": [ { "name": "计算机软/硬件" }, { "name": "系统集成/科技公司" }, { "name": "电信服务提供商" }, { "name": "电信增值服务商" }, { "name": "其它IT/通信业" } ] }, { "name": "媒体/娱乐", "children": [ { "name": "媒体/信息传播" }, { "name": "广告公司/展会公司" }, { "name": "印刷/出版" }, { "name": "酒店/饭店/旅游/餐饮" }, { "name": "文化/体育/娱乐" }, { "name": "其它媒体/娱乐" } ] }, { "name": "制造", "children": [ { "name": "汽车制造" }, { "name": "电子制造" }, { "name": "快速消费品制造" }, { "name": "制药/生物制造" }, { "name": "工业设备制造" }, { "name": "化工/石油制造" }, { "name": "其它制造业" } ] }, { "name": "建筑", "children": [ { "name": "建筑工程/建设服务" }, { "name": "楼宇" }, { "name": "房地产" }, { "name": "其它建筑业" } ] }, { "name": "能源/公共事业", "children": [ { "name": "能源开采" }, { "name": "水/电/气等" }, { "name": "公共事业" } ] }, { "name": "其它行业", "children": [ { "name": "交通运输/仓储物流" }, { "name": "批发/零售/分销" }, { "name": "贸易/进出口" }, { "name": "其它" } ] } ]; export default industry;
FTChinese/next-signup
client/js/data/industry.js
JavaScript
mit
2,311
onst bcrypt = require('bcrypt-nodejs'); const crypto = require('crypto'); console.log('start'); bcrypt.genSalt(10, (err, salt) => { bcrypt.hash('passwd', salt, null, (err, hash) => { console.log(hash); }); });
mrwolfyu/meteo-bbb
xxx.js
JavaScript
mit
231
'use strict' const { spawn } = require('@malept/cross-spawn-promise') const which = require('which') function updateExecutableMissingException (err, hasLogger) { if (hasLogger && err.code === 'ENOENT' && err.syscall === 'spawn mono') { let installer let pkg if (process.platform === 'darwin') { installer = 'brew' pkg = 'mono' } else if (which.sync('dnf', { nothrow: true })) { installer = 'dnf' pkg = 'mono-core' } else { // assume apt-based Linux distro installer = 'apt' pkg = 'mono-runtime' } err.message = `Your system is missing the ${pkg} package. Try, e.g. '${installer} install ${pkg}'` } } module.exports = async function (cmd, args, logger) { if (process.platform !== 'win32') { args.unshift(cmd) cmd = 'mono' } return spawn(cmd, args, { logger, updateErrorCallback: updateExecutableMissingException }) }
unindented/electron-installer-windows
src/spawn.js
JavaScript
mit
913
import Ember from 'ember'; export default Ember.Object.extend({ animate($element, effect, duration) { }, finish($elements) { } });
null-null-null/ember-letter-by-letter
blueprints/lxl-tween-adapter/files/__root__/lxl-tween-adapters/__name__.js
JavaScript
mit
147
// validate and import user arguments (function(args){ for (_i = 0; _i < args.length; _i += 1) { // import arguments if defined, else defaults _settings[args[_i]] = options && options[args[_i]] ? options[args[_i]] : defaults[args[_i]]; // validate data types if(typeof _settings[args[_i]] !== "number") { throw "textStretch error. Argument \"" + args[_i] + "\" must be a number. Argument given was \"" + _settings[args[_i]] + "\"."; } } }(["minFontSize", "maxFontSize"])); _settings.maxFontSize = _settings.maxFontSize || Number.POSITIVE_INFINITY;
friday/textStretch.js
src/_validateArgs.js
JavaScript
mit
564
import MailPreview from '../components/MailPreview.vue'; import icons from "trumbowyg/dist/ui/icons.svg"; import "trumbowyg/dist/ui/trumbowyg.css"; import "trumbowyg/dist/trumbowyg.js"; import "./trumbowyg-snippets-plugin.js"; $.trumbowyg.svgPath = icons; window.remplib = typeof(remplib) === 'undefined' ? {} : window.remplib; let beautify = require('js-beautify').html; (function() { 'use strict'; remplib.templateForm = { textareaSelector: '.js-mail-body-html-input', codeMirror: (element) => { return CodeMirror( element, { value: beautify($(remplib.templateForm.textareaSelector).val()), theme: 'base16-dark', mode: 'htmlmixed', indentUnit: 4, indentWithTabs: true, lineNumbers: true, lineWrapping: false, styleActiveLine: true, styleSelectedText: true, continueComments: true, gutters:[ 'CodeMirror-lint-markers' ], lint: true, autoRefresh: true, autoCloseBrackets: true, autoCloseTags: true, matchBrackets: true, matchTags: { bothTags: true }, htmlhint: { 'doctype-first': false, 'alt-require': false, 'space-tab-mixed-disabled': 'tab' } }); }, trumbowyg: (element) => { let buttons = $.trumbowyg.defaultOptions.btns; let plugins = {}; const snippetsData = $(element).data('snippets'); const viewHTMLButton = 'viewHTML'; buttons = $.grep(buttons, function (value) { return value.toString() !== viewHTMLButton; }); if (snippetsData) { buttons.push([['snippets']]); for (const item in snippetsData) { // let html = `<div contentEditable="false">{{ include('${snippetsData[item].name}') }}</div>`; let html = `{{ include('${snippetsData[item].code}') }}`; snippetsData[item].html = html; } plugins.snippets = snippetsData; } return $(element).trumbowyg({ semanticKeepAttributes: true, semantic: false, autogrow: true, btns: buttons, plugins: plugins, }); }, codeMirrorChanged: false, trumbowygChanged: false, editorChoice: () => { return $('.js-editor-choice:checked').val(); }, previewInit: (element, mailLayoutSelect, layoutsHtmlTemplates, initialContent) => { const getLayoutValue = () => mailLayoutSelect[mailLayoutSelect.selectedIndex].value; const getLayoutTemplate = () => layoutsHtmlTemplates[getLayoutValue()]; const vue = new Vue({ el: element, data: function() { return { "htmlContent": initialContent, "htmlLayout": getLayoutTemplate().layout_html, } }, render: h => h(MailPreview), }); mailLayoutSelect.addEventListener('change', function(e) { vue.htmlLayout = getLayoutTemplate().layout_html; $('body').trigger('preview:change'); }); return vue; }, showTrumbowyg: (codeMirror, trumbowyg) => { trumbowyg.data('trumbowyg').$box.show(); // load changed data from codemirror if (remplib.templateForm.codeMirrorChanged) { trumbowyg.trumbowyg('html', codeMirror.doc.getValue()); remplib.templateForm.codeMirrorChanged = false; } $(codeMirror.display.wrapper).hide(); }, showCodemirror: (codeMirror, trumbowyg) => { trumbowyg.data('trumbowyg').$box.hide(); // load changed and beautified data from trumbowyg if (remplib.templateForm.trumbowygChanged) { codeMirror.doc.setValue(beautify(trumbowyg.trumbowyg('html'))); remplib.templateForm.trumbowygChanged = false; } setTimeout(function() { codeMirror.refresh(); }, 0); $(codeMirror.display.wrapper).show(); }, selectEditor: (codeMirror, trumbowyg) => { if (remplib.templateForm.editorChoice() === 'editor') remplib.templateForm.showTrumbowyg(codeMirror, trumbowyg); else { remplib.templateForm.showCodemirror(codeMirror, trumbowyg); } }, init: () => { // initialize preview right away so user can see the email const vue = remplib.templateForm.previewInit( '#js-mail-preview', $('[name="mail_layout_id"]')[0], $('.js-mail-layouts-templates').data('mail-layouts'), $('.js-mail-body-html-input').val(), ); const codeMirror = remplib.templateForm.codeMirror($('.js-codemirror')[0]); const trumbowyg = remplib.templateForm.trumbowyg('.js-html-editor'); remplib.templateForm.syncCodeMirrorWithPreview(vue, codeMirror); remplib.templateForm.syncTrumbowygWithPreview(vue, trumbowyg); // initialize code editors on tab change, prevents bugs with initialisation of invisible elements. $('a[data-toggle="tab"]').one('shown.bs.tab', function (e) { const target = $(e.target).attr("href") // activated tab if (target === '#email') { remplib.templateForm.selectEditor(codeMirror, trumbowyg); } }); // change editor when user wants to change it (radio buttons) $('.js-editor-choice').on('change', function(e) { e.stopPropagation(); remplib.templateForm.selectEditor(codeMirror, trumbowyg) }); }, syncTrumbowygWithPreview: (vue, trumbowyg) => { trumbowyg.on('tbwchange', () => { if (remplib.templateForm.editorChoice() !== 'editor') { return; } vue.htmlContent = trumbowyg.trumbowyg('html'); $('body').trigger('preview:change'); remplib.templateForm.trumbowygChanged = true; }); }, syncCodeMirrorWithPreview: (vue, codeMirror) => { codeMirror.on('change', function( editor, change ) { if (remplib.templateForm.editorChoice() !== 'code') { return; } // ignore if update is made programmatically and not by user (avoid circular loop) if ( change.origin === 'setValue' ) { return; } vue.htmlContent = editor.doc.getValue(); $(remplib.templateForm.textareaSelector).val(editor.doc.getValue()); $('body').trigger('preview:change'); remplib.templateForm.codeMirrorChanged = true; }); } } })();
remp2020/remp
Mailer/extensions/mailer-module/assets/js/forms/mailPreview.js
JavaScript
mit
7,471
var baseSortedIndex = require('./_baseSortedIndex'); /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted into `array`. * @specs * * _.sortedLastIndex([4, 5], 4); * // => 1 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } module.exports = sortedLastIndex;
mdchristopher/Protractor
node_modules/lodash/sortedLastIndex.js
JavaScript
mit
648
/** * Created by RSC on 05.04.2016. */ myApp.factory('HomeWatchFactory', function ($http, $q, $rootScope, $log) { return { getFhemJsonList: function (name, type) { var url = ''; if ($rootScope.config.connection.isDebug) { url = 'json/homewatch/data/' + name + '.json'; } else { url = $rootScope.MetaDatafhemweb_url + $rootScope.config.globals.cmd + type + '=' + name + $rootScope.config.globals.param; } $log.debug('HomeWatchFactory: ' + url); var deferred = $q.defer(); $http({method: "GET", url: url}) .success(function (data, status, headers, config) { deferred.resolve(data); }).error(function (data, status, headers, config) { deferred.reject(status); }); return deferred.promise; }, getJson: function (name) { var url = 'json/homewatch/' + name + '.json'; var deferred = $q.defer(); $http({method: "GET", url: url}) .success(function (data, status, headers, config) { deferred.resolve(data); }).error(function (data, status, headers, config) { deferred.reject(status); }); return deferred.promise; }, getLocationWidgets: function (location) { // no values if (angular.isUndefined(location) || location == '') { $log.debug('HomeWatchFactory.getLocationWidgets: location isUndefined'); return; } var widget = $rootScope.config.home; if (widget.length == 0) return; var deferred = $q.defer(); var len = widget.length; for (var i = 0; i < len; i++) { if (widget[i].location == location) { data = widget[i]; deferred.resolve(data); break; } } return deferred.promise; } }; });
RainerSchulz/HomeWatch
js/services/api/hw.api.homewatch.jsonlist.js
JavaScript
mit
2,128
module.exports = function(grunt) { 'use strict'; // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), bowercopy: { options: { clean: false }, glob: { files: { 'static/libs/js': [ 'sprintf/dist/*.js', 'mocha/*.js', 'assert/*.js' ], 'static/libs/css': [ 'mocha/*.css' ], 'static/libs/fonts': [ ] } } } }) grunt.loadNpmTasks('grunt-bowercopy'); // Default tasks grunt.registerTask('default', ['bowercopy']); }
if1live/new-life
Gruntfile.js
JavaScript
mit
626
import _ from 'lodash' import Vue from 'vue' import test from 'ava' import FlexTableColumn from '../../src/components/FlexTableColumn.vue' Vue.config.productionTip = false test('has a mounted hook', (t) => { t.true(_.isFunction(FlexTableColumn.mounted)) }) test('has data as function', (t) => { t.true(_.isFunction(FlexTableColumn.data)) })
nrobates/vue-flex-datatable
test/components/FlexTableColumn.spec.js
JavaScript
mit
348
export const plus = (f, l) => { let next = {}; if (typeof l === 'number') { next.low = l; next.high = 0; } else if (typeof l === 'object') { if (l.high && l.low && l.unsigned) { next = l; } else { throw new Error('Not a uint64 data'); } } return { high: f.high + next.high, low: f.low + next.low, unsigned: true }; }; export const generateKeyString = (uint64Object) => { if (typeof uint64Object === 'number') { return uint64Object.toString(); } if (typeof uint64Object === 'object' && typeof uint64Object.high === 'number') { return `${uint64Object.high}${uint64Object.low}`; } return Symbol(uint64Object).toString(); };
Jawnkuin/electron-618-im
app/utils/uint64.js
JavaScript
mit
697
'use strict'; var maxBot = 11; var mode; var mw = {}; var mwId; function getMwId() { mwId = $.url().segment(4); } function isNewMicroworld() { return ($.url().segment(3) === 'new'); } function showStatusTableOptions() { var behaviour_name = $(this).attr('id'); var behaviour_type = $(this).text(); $(this).closest('.dropdown').find('span#btn_txt').text(behaviour_type+" ") $("."+behaviour_name).removeClass('hide'); if(behaviour_name == "static_option"){ $(".dynamic_option").addClass('hide'); } else { $(".static_option").addClass('hide'); } } function readyTooltips() { $('#early-end-tooltip').tooltip(); $('#max-fish-tooltip').tooltip(); $('#available-mystery-tooltip').tooltip(); $('#reported-mystery-tooltip').tooltip(); $('#spawn-factor-tooltip').tooltip(); $('#chance-catch-tooltip').tooltip(); $('#show-fisher-status-tooltip').tooltip(); $('#erratic-tooltip').tooltip(); $('#greed-tooltip').tooltip(); $('#greed-spread-tooltip').tooltip(); $('#trend-tooltip').tooltip(); $('#predictability-tooltip').tooltip(); $('#prob-action-tooltip').tooltip(); $('#attempts-second-tooltip').tooltip(); } function changeBotRowVisibility() { var numFishers = parseInt($('#num-fishers').val(), 10); var numHumans = parseInt($('#num-humans').val(), 10); if (numFishers < 1) numFishers = 1; if (numFishers > maxBot + numHumans) { numFishers = maxBot + numHumans; } if (numHumans > numFishers) numHumans = numFishers; for (var i = 1; i <= numFishers - numHumans; i++) { $('#bot-' + i + '-row').removeClass('collapse'); } for (var i = numFishers - numHumans + 1; i <= maxBot; i++) { $('#bot-' + i + '-row').addClass('collapse'); } } function changeGreedUniformity() { if ($('#uniform-greed').prop('checked') === true) { var greed = $('#bot-1-greed').val(); for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-greed').val(greed).attr('disabled', true); } } else { for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-greed').attr('disabled', false); } } } function changeGreedSpreadUniformity() { if ($('#uniform-greed-spread').prop('checked') === true) { var greedSpread = $('#bot-1-greed-spread').val(); for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-greed-spread').val(greedSpread).attr('disabled', true); } } else { for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-greedSpread').attr('disabled', false); } } } function changeTrendUniformity() { if ($('#uniform-trend').prop('checked') === true) { var trend = $('#bot-1-trend').val(); for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-trend').val(trend).attr('disabled', true); } } else { for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-trend').attr('disabled', false); } } } function changePredictabilityUniformity() { if ($('#uniform-predictability').prop('checked') === true) { var predictability = $('#bot-1-predictability').val(); for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-predictability').val(predictability).attr('disabled', true); } } else { for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-predictability').attr('disabled', false); } } } function changeProbActionUniformity() { if ($('#uniform-prob-action').prop('checked') === true) { var probAction = $('#bot-1-prob-action').val(); for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-prob-action').val(probAction).attr('disabled', true); } } else { for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-prob-action').attr('disabled', false); } } } function changeAttemptsSecondUniformity() { if ($('#uniform-attempts-second').prop('checked') === true) { var attemptsSecond = $('#bot-1-attempts-second').val(); for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-attempts-second').val(attemptsSecond).attr('disabled', true); } } else { for (var i = 2; i <= maxBot; i++) { $('#bot-' + i + '-attempts-second').attr('disabled', false); } } } function validate() { var errors = []; if ($('#name').val().length < 1) { errors.push('The microworld name is missing.'); } var numFishers = parseInt($('#num-fishers').val(), 10); if (numFishers < 1) { errors.push('There must be at least one fisher per simulation'); } if (numFishers > 12) { errors.push('The maximum number of fishers per simulation is twelve.'); } var numHumans = parseInt($('#num-humans').val(), 10); if (numHumans < 0) { errors.push('There must be zero or more humans per simulation.'); } if (numHumans > numFishers) { errors.push('There cannot be more human fishers than total fishers.'); } if (parseInt($('#num-seasons').val(), 10) < 1) { errors.push('There must be at least one season per simulation.'); } if (parseInt($('#season-duration').val(), 10) < 1) { errors.push('Seasons must have a duration of at least one second.'); } if (parseInt($('#initial-delay').val(), 10) < 1) { errors.push('The initial delay must be at least one second long.'); } if (parseInt($('#season-delay').val(), 10) < 1) { errors.push('The delay between seasons must be at least one second.'); } if (parseFloat($('#fish-value').val()) < 0) { errors.push('The value per fish cannot be negative'); } if (parseFloat($('#cost-cast').val()) < 0) { errors.push('The cost to attempt to fish cannot be negative.'); } if (parseFloat($('#cost-departure').val()) < 0) { errors.push('The cost to set sail cannot be negative.'); } if (parseFloat($('#cost-second').val()) < 0) { errors.push('The cost per second at sea cannot be negative.'); } var certainFish = parseInt($('#certain-fish').val(), 10); if (certainFish < 1) { errors.push('There must be at least one initial fish.'); } var availMysteryFish = parseInt($('#available-mystery-fish').val(), 10); if (availMysteryFish < 0) { errors.push('The number of available mystery fish cannot be negative'); } var repMysteryFish = parseInt($('#reported-mystery-fish').val(), 10); if (repMysteryFish < availMysteryFish) { errors.push('The number of reported mystery fish must be equal or ' + 'greater than the number of actually available mystery fish.'); } var maxFish = parseInt($('#max-fish').val(), 10); if (maxFish < certainFish + availMysteryFish) { errors.push('The maximum fish capacity must be equal or greater ' + 'than the sum of certain and available mystery fish.'); } if (parseFloat($('#spawn-factor').val()) < 0) { errors.push('The spawn factor cannot be negative.'); } var chanceCatch = parseFloat($('#chance-catch').val()); if (chanceCatch < 0 || chanceCatch > 1) { errors.push('The chance of catch must be a number between 0 and 1.'); } if ($('#preparation-text').val().length < 1) { errors.push('The preparation text is missing.'); } if ($('#end-time-text').val().length < 1) { errors.push('The text for ending on time is missing.'); } if ($('#end-depletion-text').val().length < 1) { errors.push('The text for ending on depletion is missing.'); } for (var i = 1; i <= (numFishers - numHumans); i++) { if ($('#bot-' + i + '-name').val().length < 1) { errors.push('Bot ' + i + ' needs a name.'); } var botGreed = parseFloat($('#bot-' + i + '-greed').val()); if (botGreed < 0 || botGreed > 1) { errors.push('The greed of bot ' + i + ' must be between 0 and 1.'); } var botGreedSpread = parseFloat($('#bot-' + i + '-greed-spread').val()); if (botGreedSpread < 0) { errors.push('The greed spread of bot ' + i + ' must be greater than 0.'); } if (botGreedSpread > 2 * botGreed) { errors.push('The greed spread of bot ' + i + ' must be less than twice its greed.'); } var botProbAction = parseFloat($('#bot-' + i + '-prob-action').val()); if (botProbAction < 0 || botProbAction > 1) { errors.push('The probability of action of bot ' + i + ' must be between 0 and 1.'); } var botAttempts = parseFloat($('#bot-' + i + '-attempts-second').val()); if (botAttempts < 1) { errors.push('The attempts per second of bot ' + i + ' must be between at least 1.'); } } if (errors.length === 0) return null; return errors; } function prepareMicroworldObject() { var mw = {}; mw.name = $('#name').val(); mw.desc = $('#desc').val(); mw.numFishers = $('#num-fishers').val(); mw.numHumans = $('#num-humans').val(); mw.numSeasons = $('#num-seasons').val(); mw.seasonDuration = $('#season-duration').val(); mw.initialDelay = $('#initial-delay').val(); mw.seasonDelay = $('#season-delay').val(); mw.enablePause = $('#enable-pause').prop('checked'); mw.enableEarlyEnd = $('#enable-early-end').prop('checked'); mw.enableTutorial = $('#enable-tutorial').prop('checked'); mw.enableRespawnWarning = $('#change-ocean-colour').prop('checked'); mw.fishValue = $('#fish-value').val(); mw.costCast = $('#cost-cast').val(); mw.costDeparture = $('#cost-departure').val(); mw.costSecond = $('#cost-second').val(); mw.currencySymbol = $('#currency-symbol').val(); mw.certainFish = $('#certain-fish').val(); mw.availableMysteryFish = $('#available-mystery-fish').val(); mw.reportedMysteryFish = $('#reported-mystery-fish').val(); mw.maxFish = $('#max-fish').val(); mw.spawnFactor = $('#spawn-factor').val(); mw.chanceCatch = $('#chance-catch').val(); mw.showFishers = $('#show-fishers').prop('checked'); mw.showFisherNames = $('#show-fisher-names').prop('checked'); mw.showFisherStatus = $('#show-fisher-status').prop('checked'); mw.showNumCaught = $('#show-num-caught').prop('checked'); mw.showFisherBalance = $('#show-fisher-balance').prop('checked'); mw.preparationText = $('#preparation-text').val(); mw.endTimeText = $('#end-time-text').val(); mw.endDepletionText = $('#end-depletion-text').val(); mw.bots = []; for (var i = 1; i <= mw.numFishers - mw.numHumans; i++) { var botPrefix = '#bot-' + i + '-'; mw.bots.push({ name: $(botPrefix + 'name').val(), greed: $(botPrefix + 'greed').val(), greedSpread: $(botPrefix + 'greed-spread').val(), trend: $(botPrefix + 'trend').val(), predictability: $(botPrefix + 'predictability').val(), probAction: $(botPrefix + 'prob-action').val(), attemptsSecond: $(botPrefix + 'attempts-second').val() }); } mw.oceanOrder = $("input[name=ocean_order]:checked").val(); return mw; } function reportErrors(err) { var errMessage = 'The form has the following errors:\n\n'; for (var i in err) { errMessage += err[i] + '\n'; } alert(errMessage); return; } function badMicroworld(jqXHR) { reportErrors(JSON.parse(jqXHR.responseText).errors); return; } function goodMicroworld() { location.href = '../dashboard'; } function createMicroworld() { var err = validate(); if (err) { reportErrors(err); return; } var mw = prepareMicroworldObject(); $.ajax({ type: 'POST', url: '/microworlds', data: mw, error: badMicroworld, success: goodMicroworld }); } function cloneMicroworld() { var err = validate(); if (err) { reportErrors(err); return; } var mw = prepareMicroworldObject(); mw.clone = true; $.ajax({ type: 'POST', url: '/microworlds', data: mw, error: badMicroworld, success: goodMicroworld }); } function updateMicroworld(changeTo) { var err = validate(); if (err) { reportErrors(err); return; } var mw = prepareMicroworldObject(); if (changeTo) mw.changeTo = changeTo; $.ajax({ type: 'PUT', url: '/microworlds/' + mwId, data: mw, error: badMicroworld, success: goodMicroworld }); } function saveMicroworld() { updateMicroworld(); } function activateMicroworld() { updateMicroworld('active'); } function archiveMicroworld() { updateMicroworld('archived'); } function deleteMicroworld() { $.ajax({ type: 'DELETE', url: '/microworlds/' + mwId, error: badMicroworld, success: goodMicroworld }); } function populatePage() { $('#name').val(mw.name); $('#desc').val(mw.desc); $('#num-fishers').val(mw.params.numFishers); $('#num-humans').val(mw.params.numHumans); $('#num-seasons').val(mw.params.numSeasons); $('#season-duration').val(mw.params.seasonDuration); $('#initial-delay').val(mw.params.initialDelay); $('#season-delay').val(mw.params.seasonDelay); $('#enable-pause').prop('checked', mw.params.enablePause); $('#enable-early-end').prop('checked', mw.params.enableEarlyEnd); $('#enable-tutorial').prop('checked', mw.params.enableTutorial); $('#change-ocean-colour').prop('checked', mw.params.enableRespawnWarning); $('#fish-value').val(mw.params.fishValue); $('#cost-cast').val(mw.params.costCast); $('#cost-departure').val(mw.params.costDeparture); $('#cost-second').val(mw.params.costSecond); $('#currency-symbol').val(mw.params.currencySymbol); $('#certain-fish').val(mw.params.certainFish); $('#available-mystery-fish').val(mw.params.availableMysteryFish); $('#reported-mystery-fish').val(mw.params.reportedMysteryFish); $('#max-fish').val(mw.params.maxFish); $('#spawn-factor').val(mw.params.spawnFactor); $('#chance-catch').val(mw.params.chanceCatch); $('#preparation-text').val(mw.params.preparationText); $('#end-time-text').val(mw.params.endTimeText); $('#end-depletion-text').val(mw.params.endDepletionText); $('#show-fishers').prop('checked', mw.params.showFishers); $('#show-fisher-names').prop('checked', mw.params.showFisherNames); $('#show-fisher-status').prop('checked', mw.params.showFisherStatus); $('#show-num-caught').prop('checked', mw.params.showNumCaught); $('#show-fisher-balance').prop('checked', mw.params.showFisherBalance); $('#uniform-greed').prop('checked', false); $('#uniform-greed-spread').prop('checked', false); $('#uniform-trend').prop('checked', false); $('#uniform-predictability').prop('checked', false); $('#uniform-prob-action').prop('checked', false); $('#uniform-attempts-second').prop('checked', false); for (var i = 1; i <= mw.params.numFishers - mw.params.numHumans; i++) { var botPrefix = '#bot-' + i + '-'; $(botPrefix + 'name').val(mw.params.bots[i - 1].name); $(botPrefix + 'greed').val(mw.params.bots[i - 1].greed); $(botPrefix + 'greed-spread').val(mw.params.bots[i - 1].greedSpread); $(botPrefix + 'trend').val(mw.params.bots[i - 1].trend); $(botPrefix + 'predictability').val(mw.params.bots[i - 1].predictability); $(botPrefix + 'prob-action').val(mw.params.bots[i - 1].probAction); $(botPrefix + 'attempts-second').val(mw.params.bots[i - 1].attemptsSecond); } $("#"+mw.params.oceanOrder).prop('checked', true); changeBotRowVisibility(); } function noMicroworld(jqXHR) { alert(jqXHR.responseText); } function gotMicroworld(m) { mw = m; mode = mw.status; populatePage(); prepareControls(); } function getMicroworld() { $.ajax({ type: 'GET', url: '/microworlds/' + mwId, error: noMicroworld, success: gotMicroworld }); } function noRuns(jqXHR) { alert(jqXHR.responseText); } function gotRuns(r) { var table = ''; for (var i in r) { var button = '<button class="btn btn-sm btn-info" type="submit" onclick=location.href=\'/runs/' + r[i]._id + '?csv=true\'>Download <span class="glyphicon glyphicon-download-alt"></span></button>'; table += '<tr><td><a href="../runs/' + r[i]._id + '">' + moment(r[i].time).format('llll') + '</a></td>' + '<td>' + r[i].participants + '</td>' + '<td>' + button + '</tr>'; } $('#microworld-runs-table-rows').html(table); // enabled or disable the download all button depending on if there are any completed runs if (r.length == 0) { $('#download-all-button').attr("disabled", "disabled"); } else { $('#download-all-button').removeAttr("disabled"); } setTimeout(getRuns, 60000); } function getRuns() { $.ajax({ type: 'GET', url: '/runs/?mw=' + mwId, error: noRuns, success: gotRuns }); } function backToList() { location.href = '../dashboard'; } // Makes downloading all runs possible function initDownloadAll() { $('#download-all-button').attr("onclick", "location.href='/runs?csv=true&mw="+mwId+"'"); } function setButtons() { $('#create').click(createMicroworld); $('#create-2').click(createMicroworld); $('#save').click(saveMicroworld); $('#save-2').click(saveMicroworld); $('#cancel').click(backToList); $('#cancel-2').click(backToList); $('#clone-confirmed').click(cloneMicroworld) $('#activate-confirmed').click(activateMicroworld); $('#archive-confirmed').click(archiveMicroworld); $('#delete-confirmed').click(deleteMicroworld); $(".behaviour_group_select").click(showStatusTableOptions); initDownloadAll(); } function setOnPageChanges() { $('#num-fishers').on('change', changeBotRowVisibility); $('#num-humans').on('change', changeBotRowVisibility); $('#uniform-greed').on('change', changeGreedUniformity); $('#bot-1-greed').on('input', changeGreedUniformity); $('#uniform-greed-spread').on('change', changeGreedSpreadUniformity); $('#bot-1-greed-spread').on('input', changeGreedSpreadUniformity); $('#uniform-trend').on('change', changeTrendUniformity); $('#bot-1-trend').on('change', changeTrendUniformity); $('#uniform-predictability').on('change', changePredictabilityUniformity); $('#bot-1-predictability').on('change', changePredictabilityUniformity); $('#uniform-prob-action').on('change', changeProbActionUniformity); $('#bot-1-prob-action').on('input', changeProbActionUniformity); $('#uniform-attempts-second').on('change', changeAttemptsSecondUniformity); $('#bot-1-attempts-second').on('input', changeAttemptsSecondUniformity); } function loadTexts() { $('#preparation-text').val(prepText); $('#end-time-text').val(endTimeText); $('#end-depletion-text').val(endDepletedText); } function prepareControls() { $('#microworld-panel-body-text').text(panelBody[mode]); $('#microworld-panel-2-body-text').text(panelBody[mode]); if (mode === 'new') { $('#microworld-header').text(pageHeader[mode]); $('#microworld-panel-title').text(panelTitle[mode]); $('#microworld-panel-2-title').text(panelTitle[mode]); loadTexts(); $('#create').removeClass('collapse'); $('#create-2').removeClass('collapse'); $("#ocean_order_user_top").prop("checked", true); uniformityChanges(); } else if (mode === 'test') { $('title').text('Fish - Microworld in Test'); $('#microworld-header').text(pageHeader[mode] + mw.code); $('#microworld-panel-title').text(panelTitle[mode] + mw.code); $('#microworld-panel-2-title').text(panelTitle[mode] + mw.code); $('#save').removeClass('collapse'); $('#save-2').removeClass('collapse'); $('#clone').removeClass('collapse'); $('#clone-2').removeClass('collapse'); $('#activate').removeClass('collapse'); $('#activate-2').removeClass('collapse'); $('#delete').removeClass('collapse'); $('#delete-2').removeClass('collapse'); if($('input[type="radio"]:checked').parent().parent().hasClass('dynamic_option')) { $(".static_option").addClass('hide'); $(".dynamic_option").removeClass("hide"); $('span#btn_txt').text("Dynamic Behaviour\xa0\xa0"); //\xa0 is the char &nbsp; makes } uniformityChanges(); } else if (mode === 'active') { $('title').text('Fish - Active Microworld'); $('#microworld-header').text(pageHeader[mode] + mw.code); $('#microworld-panel-title').text(panelTitle[mode] + mw.code); $('#microworld-panel-2-title').text(panelTitle[mode] + mw.code); $('#clone').removeClass('collapse'); $('#clone-2').removeClass('collapse'); $('#archive').removeClass('collapse'); $('#archive-2').removeClass('collapse'); $('#delete').removeClass('collapse'); $('#delete-2').removeClass('collapse'); $('.to-disable').each( function() { $(this).prop('disabled', true); }); $('#results').removeClass('collapse'); $(".dynamic_option").removeClass("hide"); } else if (mode === 'archived') { $('title').text('Fish - Archived Microworld'); $('#microworld-header').text(pageHeader[mode]); $('#microworld-panel-title').text(panelTitle[mode]); $('#microworld-panel-2-title').text(panelTitle[mode]); $('#clone').removeClass('collapse'); $('#clone-2').removeClass('collapse'); $('#activate').removeClass('collapse'); $('#activate-2').removeClass('collapse'); $('#delete').removeClass('collapse'); $('#delete-2').removeClass('collapse'); $('.to-disable').each( function() { $(this).prop('disabled', true); }); $('#results').removeClass('collapse'); $(".dynamic_option").removeClass("hide"); } } function loadData() { if (isNewMicroworld()) { mode = 'new'; prepareControls(); } else { getMicroworld(); // will eventually call prepareControls() getRuns(); } } function uniformityChanges() { changeGreedUniformity(); changeGreedSpreadUniformity(); changeTrendUniformity(); changePredictabilityUniformity(); changeProbActionUniformity(); changeAttemptsSecondUniformity(); } function main() { getMwId(); isNewMicroworld() readyTooltips(); setButtons(); setOnPageChanges(); loadData(); } $(document).ready(main);
jorgearanda/fish
public/js/microworld.js
JavaScript
mit
23,070
/* ===================================================== file.js ======================================================== */ (function($){ // jQuery no conflict 'use strict'; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - Section - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ console.log('file.js loaded'); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - */ })(jQuery); // jQuery no conflict
minimit/gulp-starter-kit
src/scripts/file.js
JavaScript
mit
437
var q = require("./quasi"); exports.ps = function (opt) { opt = opt || {}; var strokeWidth = opt.strokeWidth || "0.015"; if (opt.color) console.error("The ps module does not support the `color` option."); // PS header var ret = [ "%%!PS-Adobe-1.0 " , "%%%%BoundingBox: -1 -1 766.354 567.929 " , "%%%%EndComments " , "%%%%EndProlog " , "gsave " , " " , "/f {findfont exch scalefont setfont} bind def " , "/s {show} bind def " , "/ps {true charpath} bind def " , "/l {lineto} bind def " , "/m {newpath moveto} bind def " , "/sg {setgray} bind def" , "/a {stroke} bind def" , "/cp {closepath} bind def" , "/g {gsave} bind def" , "/h {grestore} bind def" , "matrix currentmatrix /originmat exch def " , "/umatrix {originmat matrix concatmatrix setmatrix} def " , " " , "%% Flipping coord system " , "[8.35928e-09 28.3465 -28.3465 8.35928e-09 609.449 28.6299] umatrix " , "[] 0 setdash " , "0 0 0 setrgbcolor " , "0 0 m " , strokeWidth + " setlinewidth " ]; q.quasi( opt , { newPath: function () {} , moveTo: function (x, y) { ret.push(x.toFixed(2) + " " + y.toFixed(2) + " m"); } , lineTo: function (x, y) { ret.push(x.toFixed(2) + " " + y.toFixed(2) + " l"); } , closePath: function () { ret.push("cp"); } , startGroup: function () { ret.push("g"); } , endGroup: function () { ret.push("h"); } , setFillGrey: function (colour) { ret.push(colour + " sg"); ret.push("fill"); } , setStrokeGrey: function (colour) { ret.push(colour + " sg"); ret.push("a"); } // we don't take these into account , boundaries: function () {} } ); // PS Footer ret.push("showpage grestore "); ret.push("%%%%Trailer"); return ret.join("\n"); };
darobin/quasi
lib/ps.js
JavaScript
mit
2,203
print('this is a'); print(__FILE__, __LINE__, __DIR__); load('./b.js'); // 不能简单的加载同目录的 b,因为 engine.get(FILENAME) 未变
inshua/d2js
test/load_test/a.js
JavaScript
mit
148
import PropTypes from 'prop-types'; export const validAxisType = PropTypes.oneOf([ 'category', 'linear', 'logarithmic', 'datetime' ]); export const validChartType = PropTypes.oneOf([ 'area', 'arearange', 'areaspline', 'areasplinerange', 'bar', 'boxplot', 'bubble', 'candlestick', 'column', 'columnrange', 'errorbar', 'flags', 'funnel', 'line', 'ohlc', 'pie', 'polygon', 'pyramid', 'scatter', 'solidgauge', 'spline', 'waterfall' ]);
govau/datavizkit
src/helpers/propsValidators.js
JavaScript
mit
486
/** * @author Richard Davey <[email protected]> * @copyright 2019 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ var Line = require('./Line'); Line.Angle = require('./Angle'); Line.BresenhamPoints = require('./BresenhamPoints'); Line.CenterOn = require('./CenterOn'); Line.Clone = require('./Clone'); Line.CopyFrom = require('./CopyFrom'); Line.Equals = require('./Equals'); Line.Extend = require('./Extend'); Line.GetMidPoint = require('./GetMidPoint'); Line.GetNearestPoint = require('./GetNearestPoint'); Line.GetNormal = require('./GetNormal'); Line.GetPoint = require('./GetPoint'); Line.GetPoints = require('./GetPoints'); Line.GetShortestDistance = require('./GetShortestDistance'); Line.Height = require('./Height'); Line.Length = require('./Length'); Line.NormalAngle = require('./NormalAngle'); Line.NormalX = require('./NormalX'); Line.NormalY = require('./NormalY'); Line.Offset = require('./Offset'); Line.PerpSlope = require('./PerpSlope'); Line.Random = require('./Random'); Line.ReflectAngle = require('./ReflectAngle'); Line.Rotate = require('./Rotate'); Line.RotateAroundPoint = require('./RotateAroundPoint'); Line.RotateAroundXY = require('./RotateAroundXY'); Line.SetToAngle = require('./SetToAngle'); Line.Slope = require('./Slope'); Line.Width = require('./Width'); module.exports = Line;
englercj/phaser
src/geom/line/index.js
JavaScript
mit
1,403
'use strict'; // User routes use users controller var users = require('../controllers/users'); module.exports = function(app, passport) { app.route('/logout') .get(users.signout); app.route('/users/me') .get(users.me); // Setting up the users api app.route('/register') .post(users.create); // Setting up the userId param app.param('userId', users.user); // AngularJS route to check for authentication app.route('/loggedin') .get(function(req, res) { res.send(req.isAuthenticated() ? req.user : '0'); }); // Setting the local strategy route app.route('/login') .post(passport.authenticate('local', { failureFlash: true }), function(req, res) { res.send({ user: req.user, redirect: (req.user.roles.indexOf('admin') !== -1) ? req.get('referer') : false }); }); };
dflynn15/flomo
server/routes/users.js
JavaScript
mit
953
'use strict'; // Disable eval and Buffer. window.eval = global.eval = global.Buffer = function() { throw new Error("Can't use eval and Buffer."); } const Electron = require('electron') const IpcRenderer = Electron.ipcRenderer; var Urlin = null; // element of input text window.addEventListener('load', ()=> { Urlin = document.getElementById('input-url'); Urlin.addEventListener("keypress", (event)=>{ if(13!=event.keyCode) return; Urlin.blur(); IpcRenderer.sendToHost('url-input', Urlin.value); }, false); }, false); IpcRenderer.on('url-input', (event, s_url)=>{ Urlin.value = s_url; });
yujakudo/glasspot
app/header.js
JavaScript
mit
639
var roshamboApp = angular.module('roshamboApp', []), roshambo= [ { name:'Rock', src:'img/rock.png' }, { name:'Paper', src:'img/paper.png' }, { name:'Scissors', src:'img/scissors.png' } ], roshamboMap=roshambo.reduce(function(roshamboMap,thro){ roshamboMap[thro.name.toLowerCase()]=thro.src; return roshamboMap; },{}); roshamboApp.controller('RoshamboCtrl', function ($scope,$http) { $scope.roshambo=roshambo; $scope.selection=roshambo[0]; $scope.outcome=void 0; $scope.selectThrow=function(selected){ $scope.outcome=void 0; $scope.selection=selected; }; $scope.throwSelected=function(){ $http.post('http://localhost:8080/api/throw',{playerThrow:$scope.selection.name}) .then(function(successResponse){ $scope.outcome=successResponse.data; $scope.outcome.playerSrc=roshamboMap[$scope.outcome.playerThrow]; $scope.outcome.opponentSrc=roshamboMap[$scope.outcome.opponentThrow]; $scope.outcome.announce=function(){ if($scope.outcome.outcome==='draw'){ return 'It\'s a Draw!'; }else{ return $scope.outcome.outcome.charAt(0).toUpperCase()+$scope.outcome.outcome.slice(1)+' Wins!'; } } },function(errorResponse){ alert('Error!'); console.log('Caught error posting throw:\n%s',JSON.stringify(errorResponse,null,2)); }); }; });
timfulmer/jswla-advanced
app/app.js
JavaScript
mit
1,479
"use strict"; module.exports = { "wires.json": { ":path/": `./path-`, }, "path-test.js"() { module.exports = `parent`; }, "/child": { "wires-defaults.json": { ":path/": `./defaults-`, }, "wires.json": { ":path/": `./child-`, }, "defaults-test.js"() { module.exports = `defaults`; }, "child-test.js"() { module.exports = `child`; }, "dirRouteOverride.unit.js"() { module.exports = { "dir route override"( __ ) { __.expect( 1 ); __.strictEqual( require( `:path/test` ), `child` ); __.done(); }, }; }, }, };
jaubourg/wires
test/units/common/dirRoutesOverride.dirunit.js
JavaScript
mit
790
/** * highcharts-ng * @version v0.0.13 - 2016-10-04 * @link https://github.com/pablojim/highcharts-ng * @author Barry Fitzgerald <> * @license MIT License, http://www.opensource.org/licenses/MIT */ if (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.exports === exports){ module.exports = 'highcharts-ng'; } (function () { 'use strict'; /*global angular: false, Highcharts: false */ angular.module('highcharts-ng', []) .factory('highchartsNG', ['$q', '$window', highchartsNG]) .directive('highchart', ['highchartsNG', '$timeout', highchart]); //IE8 support function indexOf(arr, find, i /*opt*/) { if (i === undefined) i = 0; if (i < 0) i += arr.length; if (i < 0) i = 0; for (var n = arr.length; i < n; i++) if (i in arr && arr[i] === find) return i; return -1; } function prependMethod(obj, method, func) { var original = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); func.apply(this, args); if (original) { return original.apply(this, args); } else { return; } }; } function deepExtend(destination, source) { //Slightly strange behaviour in edge cases (e.g. passing in non objects) //But does the job for current use cases. if (angular.isArray(source)) { destination = angular.isArray(destination) ? destination : []; for (var i = 0; i < source.length; i++) { destination[i] = deepExtend(destination[i] || {}, source[i]); } } else if (angular.isObject(source)) { destination = angular.isObject(destination) ? destination : {}; for (var property in source) { destination[property] = deepExtend(destination[property] || {}, source[property]); } } else { destination = source; } return destination; } function highchartsNG($q, $window) { var highchartsProm = $q.when($window.Highcharts); function getHighchartsOnce() { return highchartsProm; } return { getHighcharts: getHighchartsOnce, ready: function ready(callback, thisArg) { getHighchartsOnce().then(function() { callback.call(thisArg); }); } }; } function highchart(highchartsNGUtils, $timeout) { // acceptable shared state var seriesId = 0; var ensureIds = function (series) { var changed = false; angular.forEach(series, function(s) { if (!angular.isDefined(s.id)) { s.id = 'series-' + seriesId++; changed = true; } }); return changed; }; // immutable var axisNames = [ 'xAxis', 'yAxis' ]; var chartTypeMap = { 'stock': 'StockChart', 'map': 'Map', 'chart': 'Chart' }; var getMergedOptions = function (scope, element, config) { var mergedOptions = {}; var defaultOptions = { chart: { events: {} }, title: {}, subtitle: {}, series: [], credits: {}, plotOptions: {}, navigator: {enabled: false}, xAxis: { events: {} }, yAxis: { events: {} } }; if (config.options) { mergedOptions = deepExtend(defaultOptions, config.options); } else { mergedOptions = defaultOptions; } mergedOptions.chart.renderTo = element[0]; angular.forEach(axisNames, function(axisName) { if(angular.isDefined(config[axisName])) { mergedOptions[axisName] = deepExtend(mergedOptions[axisName] || {}, config[axisName]); if(angular.isDefined(config[axisName].currentMin) || angular.isDefined(config[axisName].currentMax)) { prependMethod(mergedOptions.chart.events, 'selection', function(e){ var thisChart = this; if (e[axisName]) { scope.$apply(function () { scope.config[axisName].currentMin = e[axisName][0].min; scope.config[axisName].currentMax = e[axisName][0].max; }); } else { //handle reset button - zoom out to all scope.$apply(function () { scope.config[axisName].currentMin = thisChart[axisName][0].dataMin; scope.config[axisName].currentMax = thisChart[axisName][0].dataMax; }); } }); prependMethod(mergedOptions.chart.events, 'addSeries', function(e){ scope.config[axisName].currentMin = this[axisName][0].min || scope.config[axisName].currentMin; scope.config[axisName].currentMax = this[axisName][0].max || scope.config[axisName].currentMax; }); prependMethod(mergedOptions[axisName].events, 'setExtremes', function (e) { if (e.trigger && e.trigger !== 'zoom') { // zoom trigger is handled by selection event $timeout(function () { scope.config[axisName].currentMin = e.min; scope.config[axisName].currentMax = e.max; scope.config[axisName].min = e.min; // set min and max to adjust scrollbar/navigator scope.config[axisName].max = e.max; }, 0); } }); } } }); if(config.title) { mergedOptions.title = config.title; } if (config.subtitle) { mergedOptions.subtitle = config.subtitle; } if (config.credits) { mergedOptions.credits = config.credits; } if(config.size) { if (config.size.width) { mergedOptions.chart.width = config.size.width; } if (config.size.height) { mergedOptions.chart.height = config.size.height; } } return mergedOptions; }; var updateZoom = function (axis, modelAxis) { var extremes = axis.getExtremes(); if(modelAxis.currentMin !== extremes.dataMin || modelAxis.currentMax !== extremes.dataMax) { if (axis.setExtremes) { axis.setExtremes(modelAxis.currentMin, modelAxis.currentMax, false); } else { axis.detachedsetExtremes(modelAxis.currentMin, modelAxis.currentMax, false); } } }; var processExtremes = function(chart, axis, axisName) { if(axis.currentMin || axis.currentMax) { chart[axisName][0].setExtremes(axis.currentMin, axis.currentMax, true); } }; var chartOptionsWithoutEasyOptions = function (options) { return angular.extend( deepExtend({}, options), { data: null, visible: null } ); }; var getChartType = function(scope) { if (scope.config === undefined) return 'Chart'; return chartTypeMap[('' + scope.config.chartType).toLowerCase()] || (scope.config.useHighStocks ? 'StockChart' : 'Chart'); }; function linkWithHighcharts(Highcharts, scope, element, attrs) { // We keep some chart-specific variables here as a closure // instead of storing them on 'scope'. // prevSeriesOptions is maintained by processSeries var prevSeriesOptions = {}; // chart is maintained by initChart var chart = false; var processSeries = function(series, seriesOld) { var i; var ids = []; if(series) { var setIds = ensureIds(series); if(setIds && !scope.disableDataWatch) { //If we have set some ids this will trigger another digest cycle. //In this scenario just return early and let the next cycle take care of changes return false; } //Find series to add or update angular.forEach(series, function(s, idx) { ids.push(s.id); var chartSeries = chart.get(s.id); if (chartSeries) { if (!angular.equals(prevSeriesOptions[s.id], chartOptionsWithoutEasyOptions(s))) { chartSeries.update(angular.copy(s), false); } else { if (s.visible !== undefined && chartSeries.visible !== s.visible) { chartSeries.setVisible(s.visible, false); } // Make sure the current series index can be accessed in seriesOld if (idx < seriesOld.length) { var sOld = seriesOld[idx]; var sCopy = angular.copy(sOld); // Get the latest data point from the new series var ptNew = s.data[s.data.length - 1]; // Check if the new and old series are identical with the latest data point added // If so, call addPoint without shifting sCopy.data.push(ptNew); if (angular.equals(sCopy, s)) { chartSeries.addPoint(ptNew, false); } // Check if the data change was a push and shift operation // If so, call addPoint WITH shifting else { sCopy.data.shift(); if (angular.equals(sCopy, s)) { chartSeries.addPoint(ptNew, false, true); } else { chartSeries.setData(angular.copy(s.data), false); } } } else { chartSeries.setData(angular.copy(s.data), false); } } } else { chart.addSeries(angular.copy(s), false); } prevSeriesOptions[s.id] = chartOptionsWithoutEasyOptions(s); }); // Shows no data text if all series are empty if(scope.config.noData) { var chartContainsData = false; for(i = 0; i < series.length; i++) { if (series[i].data && series[i].data.length > 0) { chartContainsData = true; break; } } if (!chartContainsData) { chart.showLoading(scope.config.noData); } else { chart.hideLoading(); } } } //Now remove any missing series for(i = chart.series.length - 1; i >= 0; i--) { var s = chart.series[i]; if (s.options.id !== 'highcharts-navigator-series' && indexOf(ids, s.options.id) < 0) { s.remove(false); } } return true; }; var initChart = function() { if (chart) chart.destroy(); prevSeriesOptions = {}; var config = scope.config || {}; var mergedOptions = getMergedOptions(scope, element, config); var func = config.func || undefined; var chartType = getChartType(scope); chart = new Highcharts[chartType](mergedOptions, func); for (var i = 0; i < axisNames.length; i++) { if (config[axisNames[i]]) { processExtremes(chart, config[axisNames[i]], axisNames[i]); } } if(config.loading) { chart.showLoading(); } config.getHighcharts = function() { return chart; }; }; initChart(); if(scope.disableDataWatch){ scope.$watchCollection('config.series', function (newSeries, oldSeries) { processSeries(newSeries); chart.redraw(); }); } else { scope.$watch('config.series', function (newSeries, oldSeries) { var needsRedraw = processSeries(newSeries, oldSeries); if(needsRedraw) { chart.redraw(); } }, true); } scope.$watch('config.title', function (newTitle) { chart.setTitle(newTitle, true); }, true); scope.$watch('config.subtitle', function (newSubtitle) { chart.setTitle(true, newSubtitle); }, true); scope.$watch('config.loading', function (loading) { if(loading) { chart.showLoading(loading === true ? null : loading); } else { chart.hideLoading(); } }); scope.$watch('config.noData', function (noData) { if(scope.config && scope.config.loading) { chart.showLoading(noData); } }, true); scope.$watch('config.credits.enabled', function (enabled) { if (enabled) { chart.credits.show(); } else if (chart.credits) { chart.credits.hide(); } }); scope.$watch(getChartType, function (chartType, oldChartType) { if (chartType === oldChartType) return; initChart(); }); angular.forEach(axisNames, function(axisName) { scope.$watch('config.' + axisName, function(newAxes) { if (!newAxes) { return; } if (angular.isArray(newAxes)) { for (var axisIndex = 0; axisIndex < newAxes.length; axisIndex++) { var axis = newAxes[axisIndex]; if (axisIndex < chart[axisName].length) { chart[axisName][axisIndex].update(axis, false); updateZoom(chart[axisName][axisIndex], angular.copy(axis)); } } } else { // update single axis chart[axisName][0].update(newAxes, false); updateZoom(chart[axisName][0], angular.copy(newAxes)); } chart.redraw(); }, true); }); scope.$watch('config.options', function (newOptions, oldOptions, scope) { //do nothing when called on registration if (newOptions === oldOptions) return; initChart(); processSeries(scope.config.series); chart.redraw(); }, true); scope.$watch('config.size', function (newSize, oldSize) { if(newSize === oldSize) return; if(newSize) { chart.setSize(newSize.width || chart.chartWidth, newSize.height || chart.chartHeight); } }, true); scope.$on('highchartsng.reflow', function () { chart.reflow(); }); scope.$on('$destroy', function() { if (chart) { try{ chart.destroy(); }catch(ex){ // fail silently as highcharts will throw exception if element doesn't exist } $timeout(function(){ element.remove(); }, 0); } }); } function link(scope, element, attrs) { function highchartsCb(Highcharts) { linkWithHighcharts(Highcharts, scope, element, attrs); } highchartsNGUtils .getHighcharts() .then(highchartsCb); } return { restrict: 'EAC', replace: true, template: '<div></div>', scope: { config: '=', disableDataWatch: '=' }, link: link }; } }()); (function (angular) { 'use strict'; angular.module('tubular-hchart.directives', ['tubular.services', 'highcharts-ng']) /** * @ngdoc component * @name tbHighcharts * * @description * The `tbHighcharts` component is the base to create any Highcharts component. * * @param {string} serverUrl Set the HTTP URL where the data comes. * @param {string} chartName Defines the chart name. * @param {string} chartType Defines the chart type. * @param {string} title Defines the title. * @param {bool} requireAuthentication Set if authentication check must be executed, default true. * @param {function} onLoad Defines a method to run in chart data load * @param {string} emptyMessage The empty message. * @param {string} errorMessage The error message. * @param {object} options The Highcharts options method. */ .component('tbHighcharts', { template: '<div class="tubular-chart">' + '<highchart config="$ctrl.options" ng-hide="$ctrl.isEmpty || $ctrl.hasError">' + '</highchart>' + '<div class="alert alert-info" ng-show="$ctrl.isEmpty">{{$ctrl.emptyMessage}}</div>' + '<div class="alert alert-warning" ng-show="$ctrl.hasError">{{$ctrl.errorMessage}}</div>' + '</div>', bindings: { serverUrl: '@', title: '@?', requireAuthentication: '=?', name: '@?chartName', chartType: '@?', emptyMessage: '@?', errorMessage: '@?', onLoad: '=?', options: '=?', onClick: '=?' }, controller: [ '$scope', 'tubularHttp', '$timeout', 'tubularConfig', function ($scope, tubularHttp, $timeout, tubularConfig) { var $ctrl = this; $ctrl.dataService = tubularHttp.getDataService($ctrl.dataServiceName); $ctrl.showLegend = angular.isUndefined($ctrl.showLegend) ? true : $ctrl.showLegend; $ctrl.chartType = $ctrl.chartType || 'line'; $ctrl.options = angular.extend({}, $ctrl.options, { options: { chart: { type: $ctrl.chartType }, plotOptions: { pie: { point: { events: { click: ($ctrl.onClick || angular.noop) } } }, series: { point: { events: { click: ($ctrl.onClick || angular.noop) } } } } }, title: { text: $ctrl.title || '' }, xAxis: { categories: [] }, yAxis: {}, series: [] }); // Setup require authentication $ctrl.requireAuthentication = angular.isUndefined($ctrl.requireAuthentication) ? true : $ctrl.requireAuthentication; $ctrl.loadData = function () { tubularConfig.webApi.requireAuthentication($ctrl.requireAuthentication); $ctrl.hasError = false; tubularHttp.get($ctrl.serverUrl).then($ctrl.handleData, function (error) { $scope.$emit('tbChart_OnConnectionError', error); $ctrl.hasError = true; }); }; $ctrl.handleData = function (data) { if (!data || !data.Data || data.Data.length === 0) { $ctrl.isEmpty = true; $ctrl.options.series = [{ data: [] }]; if ($ctrl.onLoad) { $ctrl.onLoad($ctrl.options, {}); } return; } $ctrl.isEmpty = false; if (data.Series) { $ctrl.options.xAxis.categories = data.Labels; $ctrl.options.series = data.Series.map(function (el, ix) { return { name: el, data: data.Data[ix] }; }); } else { var uniqueSerie = data.Labels.map(function (el, ix) { return { name: el, y: data.Data[ix] }; }); $ctrl.options.series = [{ name: data.SerieName || '', data: uniqueSerie, showInLegend: (data.SerieName || '') !== '' }]; } if ($ctrl.onLoad) { $timeout(function () { $ctrl.onLoad($ctrl.options, {}, $ctrl.options.getHighcharts().series); }, 100); $ctrl.onLoad($ctrl.options, {}, null); } }; $scope.$watch('$ctrl.serverUrl', function (val) { if (angular.isDefined(val) && val != null && val !== '') { $ctrl.loadData(); } }); $scope.$watch('$ctrl.chartType', function (val) { if (angular.isDefined(val) && val != null) { $ctrl.options.options.chart.type = val; } }); } ] }); })(angular);
unosquare/tubular-boilerplate-csharp
Scripts/tubular/tubular-highcharts-bundle.js
JavaScript
mit
21,488
angular.module("uiSwitch",[]).directive("switch",function(){return{restrict:"AE",replace:!0,transclude:!0,template:function(n,e){var s="";return s+="<span",s+=' class="switch'+(e['class']?" "+e['class']:"")+'"',s+=e.ngModel?' ng-click="'+e.disabled+" ? "+e.ngModel+" : "+e.ngModel+"=!"+e.ngModel+(e.ngChange?"; "+e.ngChange+'()"':'"'):"",s+=' ng-class="{ checked:'+e.ngModel+", disabled:"+e.disabled+' }"',s+=">",s+="<small></small>",s+='<input type="checkbox"',s+=e.id?' id="'+e.id+'"':"",s+=e.name?' name="'+e.name+'"':"",s+=e.ngModel?' ng-model="'+e.ngModel+'"':"",s+=' style="display:none" />',s+='<span class="switch-text">',s+=e.on?'<span class="on">'+e.on+"</span>":"",s+=e.off?'<span class="off">'+e.off+"</span>":" ",s+="</span>"}}});
fyl080801/management
src/js/angular-ui-switch.min.js
JavaScript
mit
743
var assert = require('assert') var parse = require('../').parse function addTest(arg, bulk) { function fn_json5() { //console.log('testing: ', arg) try { var x = parse(arg) } catch(err) { x = 'fail' } try { var z = eval('(function(){"use strict"\nreturn ('+String(arg)+'\n)\n})()') } catch(err) { z = 'fail' } assert.deepEqual(x, z) } function fn_strict() { //console.log('testing: ', arg) try { var x = parse(arg, {mode: 'json'}) } catch(err) { x = 'fail' } try { var z = JSON.parse(arg) } catch(err) { z = 'fail' } assert.deepEqual(x, z) } if (typeof(describe) === 'function' && !bulk) { it('test_parse_json5: ' + JSON.stringify(arg), fn_json5) it('test_parse_strict: ' + JSON.stringify(arg), fn_strict) } else { fn_json5() fn_strict() } } addTest('"\\uaaaa\\u0000\\uFFFF\\uFaAb"') addTest(' "\\xaa\\x00\xFF\xFa\0\0" ') addTest('"\\\'\\"\\b\\f\\t\\n\\r\\v"') addTest('"\\q\\w\\e\\r\\t\\y\\\\i\\o\\p\\[\\/\\\\"') addTest('"\\\n\\\r\n\\\n"') addTest('\'\\\n\\\r\n\\\n\'') addTest(' null') addTest('true ') addTest('false') addTest(' Infinity ') addTest('+Infinity') addTest('[]') addTest('[ 0xA2, 0X024324AaBf]') addTest('-0x12') addTest(' [1,2,3,4,5]') addTest('[1,2,3,4,5,] ') addTest('[1e-13]') addTest('[null, true, false]') addTest(' [1,2,"3,4,",5,]') addTest('[ 1,\n2,"3,4," \r\n,\n5,]') addTest('[ 1 , 2 , 3 , 4 , 5 , ]') addTest('{} ') addTest('{"2":1,"3":null,}') addTest('{ "2 " : 1 , "3":null , }') addTest('{ \"2\" : 25e245 , \"3\": 23 }') addTest('{"2":1,"3":nul,}') addTest('{:1,"3":nul,}') addTest('[1,2] // ssssssssss 3,4,5,] ') addTest('[1,2 , // ssssssssss \n//xxx\n3,4,5,] ') addTest('[1,2 /* ssssssssss 3,4,*/ /* */ , 5 ] ') addTest('[1,2 /* ssssssssss 3,4,*/ /* * , 5 ] ') addTest('{"3":1,"3":,}') addTest('{ чйуач:1, щцкшчлм : 4,}') addTest('{ qef-:1 }') addTest('{ $$$:1 , ___: 3}') addTest('{3:1,2:1}') addTest('{3.4e3:1}') addTest('{-3e3:1}') addTest('{+3e3:1}') addTest('{.3e3:1}') for (var i=0; i<200; i++) { addTest('"' + String.fromCharCode(i) + '"', true) } // strict JSON test cases addTest('"\\xaa"') addTest('"\\0"') addTest('"\0"') addTest('"\\v"') addTest('{null: 123}') addTest("{'null': 123}") assert.throws(function() { parse('0o') }) assert.strictEqual(parse('01234567'), 342391) assert.strictEqual(parse('0o1234567'), 342391) // undef assert.strictEqual(parse(undefined), undefined) // whitespaces addTest('[1,\r\n2,\r3,\n]') '\u0020\u00A0\uFEFF\x09\x0A\x0B\x0C\x0D\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000'.split('').forEach(function(x) { addTest(x+'[1,'+x+'2]'+x) addTest('"'+x+'"'+x) }) '\u000A\u000D\u2028\u2029'.split('').forEach(function(x) { addTest(x+'[1,'+x+'2]'+x) addTest('"\\'+x+'"'+x) }) /* weird ES6 stuff, not working if (process.version > 'v0.11.7') { assert(Array.isArray(parse('{__proto__:[]}').__proto__)) assert.equal(parse('{__proto__:{xxx:5}}').xxx, undefined) assert.equal(parse('{__proto__:{xxx:5}}').__proto__.xxx, 5) var o1 = parse('{"__proto__":[]}') assert.deepEqual([], o1.__proto__) assert.deepEqual(["__proto__"], Object.keys(o1)) assert.deepEqual([], Object.getOwnPropertyDescriptor(o1, "__proto__").value) assert.deepEqual(["__proto__"], Object.getOwnPropertyNames(o1)) assert(o1.hasOwnProperty("__proto__")) assert(Object.prototype.isPrototypeOf(o1)) // Parse a non-object value as __proto__. var o2 = JSON.parse('{"__proto__":5}') assert.deepEqual(5, o2.__proto__) assert.deepEqual(["__proto__"], Object.keys(o2)) assert.deepEqual(5, Object.getOwnPropertyDescriptor(o2, "__proto__").value) assert.deepEqual(["__proto__"], Object.getOwnPropertyNames(o2)) assert(o2.hasOwnProperty("__proto__")) assert(Object.prototype.isPrototypeOf(o2)) }*/ assert.throws(parse.bind(null, "{-1:42}")) for (var i=0; i<100; i++) { var str = '-01.e'.split('') var rnd = [1,2,3,4,5].map(function(x) { x = ~~(Math.random()*str.length) return str[x] }).join('') try { var x = parse(rnd) } catch(err) { x = 'fail' } try { var y = JSON.parse(rnd) } catch(err) { y = 'fail' } try { var z = eval(rnd) } catch(err) { z = 'fail' } //console.log(rnd, x, y, z) if (x !== y && x !== z) throw 'ERROR' }
MediaYouCanFeel/Azzenda
nodejs/node_modules/npm/node_modules/read-package-json/node_modules/json-parse-helpfulerror/node_modules/jju/test/test_parse.js
JavaScript
mit
4,418
/** * options.js * * A test helper to detect which html-snapshots options to use * * phantomjs * If a global phantomjs is defined, decorates html-snapshots options to specify that global * In some test environments (travis), local phantomjs will not install if a global is found. */ const spawn = require("child_process").spawn; module.exports = { // for now, callback is passed true if global phantomjs should be used detector: callback => { // try to run phantom globally const cp = spawn("phantomjs", ["--version"]); // if it fails, use local per the defaults cp.on("error", () => { callback(false); }); // if it succeeds, use the global cp.on("exit", code => { if (code === 0) { callback(true); } }); } };
localnerve/grunt-html-snapshots
test/helpers/options.js
JavaScript
mit
787
/* * Copyright (c) 2012-2014 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ const { assertSame, assertDataProperty, assertBuiltinConstructor, assertBuiltinPrototype, } = Assert; function assertFunctionProperty(object, name, value = object[name]) { return assertDataProperty(object, name, {value, writable: true, enumerable: false, configurable: true}); } function assertCreateFunctionProperty(object, name, value = object[name]) { return assertDataProperty(object, name, {value, writable: false, enumerable: false, configurable: true}); } function assertConstructorProperty(object, name = "constructor", value = object[name]) { return assertDataProperty(object, name, {value, writable: true, enumerable: false, configurable: true}); } function assertPrototypeProperty(object, name = "prototype", value = object[name]) { return assertDataProperty(object, name, {value, writable: false, enumerable: false, configurable: false}); } /* Promise Objects */ assertBuiltinConstructor(Promise, "Promise", 1); assertBuiltinPrototype(Promise.prototype); assertSame(Promise, Promise.prototype.constructor); /* Properties of the Promise Constructor */ assertPrototypeProperty(Promise); assertCreateFunctionProperty(Promise, Symbol.create); assertFunctionProperty(Promise, "all"); assertFunctionProperty(Promise, "cast"); assertFunctionProperty(Promise, "race"); assertFunctionProperty(Promise, "reject"); assertFunctionProperty(Promise, "resolve"); /* Properties of the Promise Prototype Object */ assertConstructorProperty(Promise.prototype); assertFunctionProperty(Promise.prototype, "catch"); assertFunctionProperty(Promise.prototype, "then");
rwaldron/es6draft
src/test/scripts/suite/objects/Promise/surface.js
JavaScript
mit
1,761
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.0.0-rc5-master-76c6299 */ goog.provide('ng.material.components.backdrop'); goog.require('ng.material.core'); /* * @ngdoc module * @name material.components.backdrop * @description Backdrop */ /** * @ngdoc directive * @name mdBackdrop * @module material.components.backdrop * * @restrict E * * @description * `<md-backdrop>` is a backdrop element used by other components, such as dialog and bottom sheet. * Apply class `opaque` to make the backdrop use the theme backdrop color. * */ angular .module('material.components.backdrop', ['material.core']) .directive('mdBackdrop', ["$mdTheming", "$animate", "$rootElement", "$window", "$log", "$$rAF", "$document", function BackdropDirective($mdTheming, $animate, $rootElement, $window, $log, $$rAF, $document) { var ERROR_CSS_POSITION = "<md-backdrop> may not work properly in a scrolled, static-positioned parent container."; return { restrict: 'E', link: postLink }; function postLink(scope, element, attrs) { // If body scrolling has been disabled using mdUtil.disableBodyScroll(), // adjust the 'backdrop' height to account for the fixed 'body' top offset var body = $window.getComputedStyle($document[0].body); if (body.position == 'fixed') { var hViewport = parseInt(body.height, 10) + Math.abs(parseInt(body.top, 10)); element.css({ height: hViewport + 'px' }); } // backdrop may be outside the $rootElement, tell ngAnimate to animate regardless if ($animate.pin) $animate.pin(element, $rootElement); $$rAF(function () { // Often $animate.enter() is used to append the backDrop element // so let's wait until $animate is done... var parent = element.parent()[0]; if (parent) { if ( parent.nodeName == 'BODY' ) { element.css({position : 'fixed'}); } var styles = $window.getComputedStyle(parent); if (styles.position == 'static') { // backdrop uses position:absolute and will not work properly with parent position:static (default) $log.warn(ERROR_CSS_POSITION); } } $mdTheming.inherit(element, element.parent()); }); } }]); ng.material.components.backdrop = angular.module("material.components.backdrop");
devMonkies/FSwebApp
bower_components/angular-material/modules/closure/backdrop/backdrop.js
JavaScript
mit
2,440
const errors = require('@tryghost/errors'); const should = require('should'); const sinon = require('sinon'); const fs = require('fs-extra'); const moment = require('moment'); const Promise = require('bluebird'); const path = require('path'); const LocalFileStore = require('../../../../../core/server/adapters/storage/LocalFileStorage'); let localFileStore; const configUtils = require('../../../../utils/configUtils'); describe('Local File System Storage', function () { let image; let momentStub; function fakeDate(mm, yyyy) { const month = parseInt(mm, 10); const year = parseInt(yyyy, 10); momentStub.withArgs('YYYY').returns(year.toString()); momentStub.withArgs('MM').returns(month < 10 ? '0' + month.toString() : month.toString()); } beforeEach(function () { // Fake a date, do this once for all tests in this file momentStub = sinon.stub(moment.fn, 'format'); }); afterEach(function () { sinon.restore(); configUtils.restore(); }); beforeEach(function () { sinon.stub(fs, 'mkdirs').resolves(); sinon.stub(fs, 'copy').resolves(); sinon.stub(fs, 'stat').rejects(); sinon.stub(fs, 'unlink').resolves(); image = { path: 'tmp/123456.jpg', name: 'IMAGE.jpg', type: 'image/jpeg' }; localFileStore = new LocalFileStore(); fakeDate(9, 2013); }); it('should send correct path to image when date is in Sep 2013', function (done) { localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/IMAGE.jpg'); done(); }).catch(done); }); it('should send correct path to image when original file has spaces', function (done) { image.name = 'AN IMAGE.jpg'; localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/AN-IMAGE.jpg'); done(); }).catch(done); }); it('should allow "@" symbol to image for Apple hi-res (retina) modifier', function (done) { image.name = '[email protected]'; localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/[email protected]'); done(); }).catch(done); }); it('should send correct path to image when date is in Jan 2014', function (done) { fakeDate(1, 2014); localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2014/01/IMAGE.jpg'); done(); }).catch(done); }); it('should create month and year directory', function (done) { localFileStore.save(image).then(function () { fs.mkdirs.calledOnce.should.be.true(); fs.mkdirs.args[0][0].should.equal(path.resolve('./content/images/2013/09')); done(); }).catch(done); }); it('should copy temp file to new location', function (done) { localFileStore.save(image).then(function () { fs.copy.calledOnce.should.be.true(); fs.copy.args[0][0].should.equal('tmp/123456.jpg'); fs.copy.args[0][1].should.equal(path.resolve('./content/images/2013/09/IMAGE.jpg')); done(); }).catch(done); }); it('can upload two different images with the same name without overwriting the first', function (done) { fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-1.jpg')).rejects(); // if on windows need to setup with back slashes // doesn't hurt for the test to cope with both fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-1.jpg')).rejects(); localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/IMAGE-1.jpg'); done(); }).catch(done); }); it('can upload five different images with the same name without overwriting the first', function (done) { fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-1.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-2.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-3.jpg')).resolves(); fs.stat.withArgs(path.resolve('./content/images/2013/09/IMAGE-4.jpg')).rejects(); // windows setup fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-1.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-2.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-3.jpg')).resolves(); fs.stat.withArgs(path.resolve('.\\content\\images\\2013\\Sep\\IMAGE-4.jpg')).rejects(); localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/IMAGE-4.jpg'); done(); }).catch(done); }); describe('read image', function () { beforeEach(function () { // we have some example images in our test utils folder localFileStore.storagePath = path.join(__dirname, '../../../../utils/fixtures/images/'); }); it('success', function (done) { localFileStore.read({path: 'ghost-logo.png'}) .then(function (bytes) { bytes.length.should.eql(8638); done(); }); }); it('success', function (done) { localFileStore.read({path: '/ghost-logo.png/'}) .then(function (bytes) { bytes.length.should.eql(8638); done(); }); }); it('image does not exist', function (done) { localFileStore.read({path: 'does-not-exist.png'}) .then(function () { done(new Error('image should not exist')); }) .catch(function (err) { (err instanceof errors.NotFoundError).should.eql(true); err.code.should.eql('ENOENT'); done(); }); }); }); describe('validate extentions', function () { it('name contains a .\d as extension', function (done) { localFileStore.save({ name: 'test-1.1.1' }).then(function (url) { should.exist(url.match(/test-1.1.1/)); done(); }).catch(done); }); it('name contains a .zip as extension', function (done) { localFileStore.save({ name: 'test-1.1.1.zip' }).then(function (url) { should.exist(url.match(/test-1.1.1.zip/)); done(); }).catch(done); }); it('name contains a .jpeg as extension', function (done) { localFileStore.save({ name: 'test-1.1.1.jpeg' }).then(function (url) { should.exist(url.match(/test-1.1.1.jpeg/)); done(); }).catch(done); }); }); describe('when a custom content path is used', function () { beforeEach(function () { const configPaths = configUtils.defaultConfig.paths; configUtils.set('paths:contentPath', configPaths.appRoot + '/var/ghostcms'); }); it('should send the correct path to image', function (done) { localFileStore.save(image).then(function (url) { url.should.equal('/content/images/2013/09/IMAGE.jpg'); done(); }).catch(done); }); }); // @TODO: remove path.join mock... describe('on Windows', function () { const truePathSep = path.sep; beforeEach(function () { sinon.stub(path, 'join'); sinon.stub(configUtils.config, 'getContentPath').returns('content/images/'); }); afterEach(function () { path.sep = truePathSep; }); it('should return url in proper format for windows', function (done) { path.sep = '\\'; path.join.returns('content\\images\\2013\\09\\IMAGE.jpg'); localFileStore.save(image).then(function (url) { if (truePathSep === '\\') { url.should.equal('/content/images/2013/09/IMAGE.jpg'); } else { // if this unit test is run on an OS that uses forward slash separators, // localfilesystem.save() will use a path.relative() call on // one path with backslash separators and one path with forward // slashes and it returns a path that needs to be normalized path.normalize(url).should.equal('/content/images/2013/09/IMAGE.jpg'); } done(); }).catch(done); }); }); });
janvt/Ghost
test/unit/server/adapters/storage/LocalFileStorage.test.js
JavaScript
mit
9,369
import UnexpectedHtmlLike from 'unexpected-htmllike'; import React from 'react'; import REACT_EVENT_NAMES from '../reactEventNames'; const PENDING_TEST_EVENT_TYPE = { dummy: 'Dummy object to identify a pending event on the test renderer' }; function getDefaultOptions(flags) { return { diffWrappers: flags.exactly || flags.withAllWrappers, diffExtraChildren: flags.exactly || flags.withAllChildren, diffExtraAttributes: flags.exactly || flags.withAllAttributes, diffExactClasses: flags.exactly, diffExtraClasses: flags.exactly || flags.withAllClasses }; } /** * * @param options {object} * @param options.ActualAdapter {function} constructor function for the HtmlLike adapter for the `actual` value (usually the renderer) * @param options.ExpectedAdapter {function} constructor function for the HtmlLike adapter for the `expected` value * @param options.QueryAdapter {function} constructor function for the HtmlLike adapter for the query value (`queried for` and `on`) * @param options.actualTypeName {string} name of the unexpected type for the `actual` value * @param options.expectedTypeName {string} name of the unexpected type for the `expected` value * @param options.queryTypeName {string} name of the unexpected type for the query value (used in `queried for` and `on`) * @param options.actualRenderOutputType {string} the unexpected type for the actual output value * @param options.getRenderOutput {function} called with the actual value, and returns the `actualRenderOutputType` type * @param options.getDiffInputFromRenderOutput {function} called with the value from `getRenderOutput`, result passed to HtmlLike diff * @param options.rewrapResult {function} called with the `actual` value (usually the renderer), and the found result * @param options.wrapResultForReturn {function} called with the `actual` value (usually the renderer), and the found result * from HtmlLike `contains()` call (usually the same type returned from `getDiffInputFromRenderOutput`. Used to create a * value that can be passed back to the user as the result of the promise. Used by `queried for` when no further assertion is * provided, therefore the return value is provided as the result of the promise. If this is not present, `rewrapResult` is used. * @param options.triggerEvent {function} called the `actual` value (renderer), the optional target (or null) as the result * from the HtmlLike `contains()` call target, the eventName, and optional eventArgs when provided (undefined otherwise) * @constructor */ function AssertionGenerator(options) { this._options = Object.assign({}, options); this._PENDING_EVENT_IDENTIFIER = (options.mainAssertionGenerator && options.mainAssertionGenerator.getEventIdentifier()) || { dummy: options.actualTypeName + 'PendingEventIdentifier' }; this._actualPendingEventTypeName = options.actualTypeName + 'PendingEvent'; } AssertionGenerator.prototype.getEventIdentifier = function () { return this._PENDING_EVENT_IDENTIFIER; }; AssertionGenerator.prototype.installInto = function installInto(expect) { this._installEqualityAssertions(expect); this._installQueriedFor(expect); this._installPendingEventType(expect); this._installWithEvent(expect); this._installWithEventOn(expect); this._installEventHandlerAssertions(expect); }; AssertionGenerator.prototype.installAlternativeExpected = function (expect) { this._installEqualityAssertions(expect); this._installEventHandlerAssertions(expect); } AssertionGenerator.prototype._installEqualityAssertions = function (expect) { const { actualTypeName, expectedTypeName, getRenderOutput, actualRenderOutputType, getDiffInputFromRenderOutput, ActualAdapter, ExpectedAdapter } = this._options; expect.addAssertion([`<${actualTypeName}> to have [exactly] rendered <${expectedTypeName}>`, `<${actualTypeName}> to have rendered [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}>`], function (expect, subject, renderOutput) { var actual = getRenderOutput(subject); return expect(actual, 'to have [exactly] rendered [with all children] [with all wrappers] [with all classes] [with all attributes]', renderOutput) .then(() => subject); }); expect.addAssertion([ `<${actualRenderOutputType}> to have [exactly] rendered <${expectedTypeName}>`, `<${actualRenderOutputType}> to have rendered [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}>` ], function (expect, subject, renderOutput) { const exactly = this.flags.exactly; const withAllChildren = this.flags['with all children']; const withAllWrappers = this.flags['with all wrappers']; const withAllClasses = this.flags['with all classes']; const withAllAttributes = this.flags['with all attributes']; const actualAdapter = new ActualAdapter(); const expectedAdapter = new ExpectedAdapter(); const testHtmlLike = new UnexpectedHtmlLike(actualAdapter); if (!exactly) { expectedAdapter.setOptions({concatTextContent: true}); actualAdapter.setOptions({concatTextContent: true}); } const options = getDefaultOptions({exactly, withAllWrappers, withAllChildren, withAllClasses, withAllAttributes}); const diffResult = testHtmlLike.diff(expectedAdapter, getDiffInputFromRenderOutput(subject), renderOutput, expect, options); return testHtmlLike.withResult(diffResult, result => { if (result.weight !== 0) { return expect.fail({ diff: function (output, diff, inspect) { return output.append(testHtmlLike.render(result, output.clone(), diff, inspect)); } }); } return result; }); }); expect.addAssertion([`<${actualTypeName}> [not] to contain [exactly] <${expectedTypeName}|string>`, `<${actualTypeName}> [not] to contain [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}|string>`], function (expect, subject, renderOutput) { var actual = getRenderOutput(subject); return expect(actual, '[not] to contain [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]', renderOutput); }); expect.addAssertion([`<${actualRenderOutputType}> [not] to contain [exactly] <${expectedTypeName}|string>`, `<${actualRenderOutputType}> [not] to contain [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}|string>`], function (expect, subject, expected) { var not = this.flags.not; var exactly = this.flags.exactly; var withAllChildren = this.flags['with all children']; var withAllWrappers = this.flags['with all wrappers']; var withAllClasses = this.flags['with all classes']; var withAllAttributes = this.flags['with all attributes']; var actualAdapter = new ActualAdapter(); var expectedAdapter = new ExpectedAdapter(); var testHtmlLike = new UnexpectedHtmlLike(actualAdapter); if (!exactly) { actualAdapter.setOptions({concatTextContent: true}); expectedAdapter.setOptions({concatTextContent: true}); } var options = getDefaultOptions({exactly, withAllWrappers, withAllChildren, withAllClasses, withAllAttributes}); const containsResult = testHtmlLike.contains(expectedAdapter, getDiffInputFromRenderOutput(subject), expected, expect, options); return testHtmlLike.withResult(containsResult, result => { if (not) { if (result.found) { expect.fail({ diff: (output, diff, inspect) => { return output.error('but found the following match').nl().append(testHtmlLike.render(result.bestMatch, output.clone(), diff, inspect)); } }); } return; } if (!result.found) { expect.fail({ diff: function (output, diff, inspect) { return output.error('the best match was').nl().append(testHtmlLike.render(result.bestMatch, output.clone(), diff, inspect)); } }); } }); }); // More generic assertions expect.addAssertion(`<${actualTypeName}> to equal <${expectedTypeName}>`, function (expect, subject, expected) { expect(getRenderOutput(subject), 'to equal', expected); }); expect.addAssertion(`<${actualRenderOutputType}> to equal <${expectedTypeName}>`, function (expect, subject, expected) { expect(subject, 'to have exactly rendered', expected); }); expect.addAssertion(`<${actualTypeName}> to satisfy <${expectedTypeName}>`, function (expect, subject, expected) { expect(getRenderOutput(subject), 'to satisfy', expected); }); expect.addAssertion(`<${actualRenderOutputType}> to satisfy <${expectedTypeName}>`, function (expect, subject, expected) { expect(subject, 'to have rendered', expected); }); }; AssertionGenerator.prototype._installQueriedFor = function (expect) { const { actualTypeName, queryTypeName, getRenderOutput, actualRenderOutputType, getDiffInputFromRenderOutput, rewrapResult, wrapResultForReturn, ActualAdapter, QueryAdapter } = this._options; expect.addAssertion([`<${actualTypeName}> queried for [exactly] <${queryTypeName}> <assertion?>`, `<${actualTypeName}> queried for [with all children] [with all wrapppers] [with all classes] [with all attributes] <${queryTypeName}> <assertion?>` ], function (expect, subject, query, assertion) { return expect.apply(expect, [ getRenderOutput(subject), 'queried for [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]', query ].concat(Array.prototype.slice.call(arguments, 3))); }); expect.addAssertion([`<${actualRenderOutputType}> queried for [exactly] <${queryTypeName}> <assertion?>`, `<${actualRenderOutputType}> queried for [with all children] [with all wrapppers] [with all classes] [with all attributes] <${queryTypeName}> <assertion?>`], function (expect, subject, query) { var exactly = this.flags.exactly; var withAllChildren = this.flags['with all children']; var withAllWrappers = this.flags['with all wrappers']; var withAllClasses = this.flags['with all classes']; var withAllAttributes = this.flags['with all attributes']; var actualAdapter = new ActualAdapter(); var queryAdapter = new QueryAdapter(); var testHtmlLike = new UnexpectedHtmlLike(actualAdapter); if (!exactly) { actualAdapter.setOptions({concatTextContent: true}); queryAdapter.setOptions({concatTextContent: true}); } const options = getDefaultOptions({exactly, withAllWrappers, withAllChildren, withAllClasses, withAllAttributes}); options.findTargetAttrib = 'queryTarget'; const containsResult = testHtmlLike.contains(queryAdapter, getDiffInputFromRenderOutput(subject), query, expect, options); const args = arguments; return testHtmlLike.withResult(containsResult, function (result) { if (!result.found) { expect.fail({ diff: (output, diff, inspect) => { const resultOutput = output.error('`queried for` found no match.'); if (result.bestMatch) { resultOutput.error(' The best match was') .nl() .append(testHtmlLike.render(result.bestMatch, output.clone(), diff, inspect)); } return resultOutput; } }); } if (args.length > 3) { // There is an assertion continuation... expect.errorMode = 'nested' const s = rewrapResult(subject, result.bestMatch.target || result.bestMatchItem); return expect.apply(null, [ rewrapResult(subject, result.bestMatch.target || result.bestMatchItem) ].concat(Array.prototype.slice.call(args, 3))) return expect.shift(rewrapResult(subject, result.bestMatch.target || result.bestMatchItem)); } // There is no assertion continuation, so we need to wrap the result for public consumption // i.e. create a value that we can give back from the `expect` promise return expect.shift((wrapResultForReturn || rewrapResult)(subject, result.bestMatch.target || result.bestMatchItem)); }); }); }; AssertionGenerator.prototype._installPendingEventType = function (expect) { const actualPendingEventTypeName = this._actualPendingEventTypeName; const PENDING_EVENT_IDENTIFIER = this._PENDING_EVENT_IDENTIFIER; expect.addType({ name: actualPendingEventTypeName, base: 'object', identify(value) { return value && typeof value === 'object' && value.$$typeof === PENDING_EVENT_IDENTIFIER; }, inspect(value, depth, output, inspect) { return output.append(inspect(value.renderer)).red(' with pending event \'').cyan(value.eventName).red('\''); } }); }; AssertionGenerator.prototype._installWithEvent = function (expect) { const { actualTypeName, actualRenderOutputType, triggerEvent, canTriggerEventsOnOutputType } = this._options; let { wrapResultForReturn = (value) => value } = this._options; const actualPendingEventTypeName = this._actualPendingEventTypeName; const PENDING_EVENT_IDENTIFIER = this._PENDING_EVENT_IDENTIFIER; expect.addAssertion(`<${actualTypeName}> with event <string> <assertion?>`, function (expect, subject, eventName, ...assertion) { if (arguments.length > 3) { return expect.apply(null, [{ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject, eventName: eventName }].concat(assertion)); } else { triggerEvent(subject, null, eventName); return expect.shift(wrapResultForReturn(subject)); } }); expect.addAssertion(`<${actualTypeName}> with event (${REACT_EVENT_NAMES.join('|')}) <assertion?>`, function (expect, subject, ...assertion) { return expect(subject, 'with event', expect.alternations[0], ...assertion); }); expect.addAssertion(`<${actualTypeName}> with event <string> <object> <assertion?>`, function (expect, subject, eventName, eventArgs) { if (arguments.length > 4) { return expect.shift({ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject, eventName: eventName, eventArgs: eventArgs }); } else { triggerEvent(subject, null, eventName, eventArgs); return expect.shift(subject); } }); expect.addAssertion(`<${actualTypeName}> with event (${REACT_EVENT_NAMES.join('|')}) <object> <assertion?>`, function (expect, subject, eventArgs, ...assertion) { return expect(subject, 'with event', expect.alternations[0], eventArgs, ...assertion); }); if (canTriggerEventsOnOutputType) { expect.addAssertion(`<${actualRenderOutputType}> with event <string> <assertion?>`, function (expect, subject, eventName, ...assertion) { if (arguments.length > 3) { return expect.apply(null, [{ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject, eventName: eventName, isOutputType: true }].concat(assertion)); } else { triggerEvent(subject, null, eventName); return expect.shift(wrapResultForReturn(subject)); } }); expect.addAssertion(`<${actualRenderOutputType}> with event (${REACT_EVENT_NAMES.join('|')}) <assertion?>`, function (expect, subject, ...assertion) { return expect(subject, 'with event', expect.alternations[0], ...assertion); }); expect.addAssertion(`<${actualRenderOutputType}> with event <string> <object> <assertion?>`, function (expect, subject, eventName, args) { if (arguments.length > 4) { return expect.shift({ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject, eventName: eventName, eventArgs: args, isOutputType: true }); } else { triggerEvent(subject, null, eventName, args); return expect.shift(subject); } }); expect.addAssertion(`<${actualRenderOutputType}> with event (${REACT_EVENT_NAMES.join('|')}) <object> <assertion?>`, function (expect, subject, eventArgs, ...assertion) { return expect(subject, 'with event', expect.alternations[0], eventArgs, ...assertion); }); } expect.addAssertion(`<${actualPendingEventTypeName}> [and] with event <string> <assertion?>`, function (expect, subject, eventName) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); if (arguments.length > 3) { return expect.shift({ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject.renderer, eventName: eventName }); } else { triggerEvent(subject.renderer, null, eventName); return expect.shift(subject.renderer); } }); expect.addAssertion(`<${actualPendingEventTypeName}> [and] with event (${REACT_EVENT_NAMES.join('|')}) <assertion?>`, function (expect, subject, ...assertion) { return expect(subject, 'with event', expect.alternations[0], ...assertion); }); expect.addAssertion(`<${actualPendingEventTypeName}> [and] with event <string> <object> <assertion?>`, function (expect, subject, eventName, eventArgs) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); if (arguments.length > 4) { return expect.shift({ $$typeof: PENDING_EVENT_IDENTIFIER, renderer: subject.renderer, eventName: eventName, eventArgs: eventArgs }); } else { triggerEvent(subject.renderer, null, eventName, eventArgs); return expect.shift(subject.renderer); } }); expect.addAssertion(`<${actualPendingEventTypeName}> [and] with event (${REACT_EVENT_NAMES.join('|')}) <object> <assertion?>`, function (expect, subject, eventArgs, ...assertion) { return expect(subject, 'with event', expect.alternations[0], eventArgs, ...assertion); }); }; AssertionGenerator.prototype._installWithEventOn = function (expect) { const { actualTypeName, queryTypeName, expectedTypeName, getRenderOutput, getDiffInputFromRenderOutput, triggerEvent, ActualAdapter, QueryAdapter } = this._options; const actualPendingEventTypeName = this._actualPendingEventTypeName; expect.addAssertion(`<${actualPendingEventTypeName}> on [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]<${queryTypeName}> <assertion?>`, function (expect, subject, target) { const actualAdapter = new ActualAdapter({ convertToString: true, concatTextContent: true }); const queryAdapter = new QueryAdapter({ convertToString: true, concatTextContent: true }); const testHtmlLike = new UnexpectedHtmlLike(actualAdapter); const exactly = this.flags.exactly; const withAllChildren = this.flags['with all children']; const withAllWrappers = this.flags['with all wrappers']; const withAllClasses = this.flags['with all classes']; const withAllAttributes = this.flags['with all attributes']; const options = getDefaultOptions({ exactly, withAllWrappers, withAllChildren, withAllClasses, withAllAttributes}); options.findTargetAttrib = 'eventTarget'; const containsResult = testHtmlLike.contains(queryAdapter, getDiffInputFromRenderOutput(getRenderOutput(subject.renderer)), target, expect, options); return testHtmlLike.withResult(containsResult, result => { if (!result.found) { return expect.fail({ diff: function (output, diff, inspect) { output.error('Could not find the target for the event. '); if (result.bestMatch) { output.error('The best match was').nl().nl().append(testHtmlLike.render(result.bestMatch, output.clone(), diff, inspect)); } return output; } }); } const newSubject = Object.assign({}, subject, { target: result.bestMatch.target || result.bestMatchItem }); if (arguments.length > 3) { return expect.shift(newSubject); } else { triggerEvent(newSubject.renderer, newSubject.target, newSubject.eventName, newSubject.eventArgs); return expect.shift(newSubject.renderer); } }); }); expect.addAssertion([`<${actualPendingEventTypeName}> queried for [exactly] <${queryTypeName}> <assertion?>`, `<${actualPendingEventTypeName}> queried for [with all children] [with all wrappers] [with all classes] [with all attributes] <${queryTypeName}> <assertion?>`], function (expect, subject, expected) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); return expect.apply(expect, [subject.renderer, 'queried for [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]', expected] .concat(Array.prototype.slice.call(arguments, 3))); } ); }; AssertionGenerator.prototype._installEventHandlerAssertions = function (expect) { const { actualTypeName, expectedTypeName, triggerEvent } = this._options; const actualPendingEventTypeName = this._actualPendingEventTypeName; expect.addAssertion([`<${actualPendingEventTypeName}> [not] to contain [exactly] <${expectedTypeName}>`, `<${actualPendingEventTypeName}> [not] to contain [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}>`], function (expect, subject, expected) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); return expect(subject.renderer, '[not] to contain [exactly] [with all children] [with all wrappers] [with all classes] [with all attributes]', expected); }); expect.addAssertion(`<${actualPendingEventTypeName}> to have [exactly] rendered [with all children] [with all wrappers] [with all classes] [with all attributes] <${expectedTypeName}>`, function (expect, subject, expected) { triggerEvent(subject.renderer, subject.target, subject.eventName, subject.eventArgs); return expect(subject.renderer, 'to have [exactly] rendered [with all children] [with all wrappers] [with all classes] [with all attributes]', expected); }); }; export default AssertionGenerator;
bruderstein/unexpected-react
src/assertions/AssertionGenerator.js
JavaScript
mit
22,599
// Generated by CoffeeScript 1.7.1 (function() { var $, CSV, ES, TEXT, TRM, TYPES, alert, badge, create_readstream, debug, echo, help, info, log, njs_fs, rainbow, route, rpr, urge, warn, whisper; njs_fs = require('fs'); TYPES = require('coffeenode-types'); TEXT = require('coffeenode-text'); TRM = require('coffeenode-trm'); rpr = TRM.rpr.bind(TRM); badge = 'TIMETABLE/read-gtfs-data'; log = TRM.get_logger('plain', badge); info = TRM.get_logger('info', badge); whisper = TRM.get_logger('whisper', badge); alert = TRM.get_logger('alert', badge); debug = TRM.get_logger('debug', badge); warn = TRM.get_logger('warn', badge); help = TRM.get_logger('help', badge); urge = TRM.get_logger('urge', badge); echo = TRM.echo.bind(TRM); rainbow = TRM.rainbow.bind(TRM); create_readstream = require('../create-readstream'); /* http://c2fo.github.io/fast-csv/index.html, https://github.com/C2FO/fast-csv */ CSV = require('fast-csv'); ES = require('event-stream'); $ = ES.map.bind(ES); this.$count = function(input_stream, title) { var count; count = 0; input_stream.on('end', function() { return info((title != null ? title : 'Count') + ':', count); }); return $((function(_this) { return function(record, handler) { count += 1; return handler(null, record); }; })(this)); }; this.$skip_empty = function() { return $((function(_this) { return function(record, handler) { if (record.length === 0) { return handler(); } return handler(null, record); }; })(this)); }; this.$show = function() { return $((function(_this) { return function(record, handler) { urge(rpr(record.toString())); return handler(null, record); }; })(this)); }; this.read_trips = function(route, handler) { var input; input = CSV.fromPath(route); input.on('end', function() { log('ok: trips'); return handler(null); }); input.setMaxListeners(100); input.pipe(this.$count(input, 'trips A')).pipe(this.$show()); return null; }; if (!module.parent) { route = '/Volumes/Storage/cnd/node_modules/timetable-data/germany-berlin-2014/agency.txt'; this.read_trips(route, function(error) { if (error != null) { throw error; } return log('ok'); }); } }).call(this);
loveencounterflow/timetable
lib/scratch/test-fast-csv.js
JavaScript
mit
2,430
"use strict"; var request = require(__dirname + "/request"); var db = require(__dirname + "/db"); /** * Steam utils */ var steamapi = {}; /** * Request to our api * @param {string} type * @param {string[]} ids * @param {function} callback */ steamapi.request = function (type, ids, callback) { if (!ids.length) { callback({}); return; } var res = {}; var missingIds = []; for (var i = 0; i < ids.length; i++) { var id = ids[i]; var steamData = steamapi.getDataForId(type, id); if (steamData) { res[id] = steamData; } else { missingIds.push(id); } } if (missingIds.length) { request.get("https://scripts.0x.at/steamapi/api.php?action=" + type + "&ids=" + missingIds.join(","), false, function (result) { if (result !== null) { var steamData = null; var data = JSON.parse(result); if (type == "bans") { for (var i = 0; i < data.players.length; i++) { steamData = data.players[i]; steamapi.saveDataForId(type, steamData.SteamId, steamData); res[steamData.SteamId] = steamData; } } if (type == "summaries") { if(data.response){ for (var playerIndex in data.response.players) { if (data.response.players.hasOwnProperty(playerIndex)) { steamData = data.response.players[playerIndex]; steamapi.saveDataForId(type, steamData.steamid, steamData); res[steamData.steamid] = steamData; } } } } } callback(res); }); } else { callback(res); } }; /** * Get db data for steamid * @param {string} type * @param {string} id * @returns {*} */ steamapi.getDataForId = function (type, id) { var sdb = db.get("steamapi"); var playerData = sdb.get(id).value(); if (!playerData || !playerData[type]) return null; if (playerData[type].timestamp < (new Date().getTime() / 1000 - 86400)) { delete playerData[type]; } return playerData[type] || null; }; /** * Save db data for steamid * @param {string} type * @param {string} id * @param {object} data * @returns {*} */ steamapi.saveDataForId = function (type, id, data) { var sdb = db.get("steamapi"); var playerData = sdb.get(id).value(); if (!playerData) playerData = {}; data.timestamp = new Date().getTime() / 1000; playerData[type] = data; sdb.set(id, playerData).value(); }; /** * Delete old entries */ steamapi.cleanup = function () { try { var data = db.get("steamapi").value(); var timeout = new Date() / 1000 - 86400; for (var steamId in data) { if (data.hasOwnProperty(steamId)) { var entries = data[steamId]; for (var entryIndex in entries) { if (entries.hasOwnProperty(entryIndex)) { var entryRow = entries[entryIndex]; if (entryRow.timestamp < timeout) { delete entries[entryIndex]; } } } } } db.get("steamapi").setState(data); } catch (e) { console.error(new Date(), "Steamapi cleanup failed", e, e.stack); } }; // each 30 minutes cleanup the steamapi db and remove old entries setInterval(steamapi.cleanup, 30 * 60 * 1000); steamapi.cleanup(); module.exports = steamapi;
brainfoolong/rcon-web-admin
src/steamapi.js
JavaScript
mit
3,790
//THREEJS RELATED VARIABLES var scene, camera, fieldOfView, aspectRatio, nearPlane, farPlane, gobalLight, shadowLight, backLight, renderer, container, controls; //SCREEN & MOUSE VARIABLES var HEIGHT, WIDTH, windowHalfX, windowHalfY, mousePos = { x: 0, y: 0 }, oldMousePos = {x:0, y:0}, ballWallDepth = 28; //3D OBJECTS VARIABLES var hero; //INIT THREE JS, SCREEN AND MOUSE EVENTS function initScreenAnd3D() { HEIGHT = window.innerHeight; WIDTH = window.innerWidth; windowHalfX = WIDTH / 2; windowHalfY = HEIGHT / 2; scene = new THREE.Scene(); aspectRatio = WIDTH / HEIGHT; fieldOfView = 50; nearPlane = 1; farPlane = 2000; camera = new THREE.PerspectiveCamera( fieldOfView, aspectRatio, nearPlane, farPlane ); camera.position.x = 0; camera.position.z = 300; camera.position.y = 250; camera.lookAt(new THREE.Vector3(0, 60, 0)); renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); renderer.setSize(WIDTH, HEIGHT); renderer.shadowMapEnabled = true; container = document.getElementById('world'); container.appendChild(renderer.domElement); window.addEventListener('resize', handleWindowResize, false); document.addEventListener('mousemove', handleMouseMove, false); document.addEventListener('touchmove', handleTouchMove, false); /* controls = new THREE.OrbitControls(camera, renderer.domElement); controls.minPolarAngle = -Math.PI / 2; controls.maxPolarAngle = Math.PI / 2; controls.noZoom = true; controls.noPan = true; //*/ } function handleWindowResize() { HEIGHT = window.innerHeight; WIDTH = window.innerWidth; windowHalfX = WIDTH / 2; windowHalfY = HEIGHT / 2; renderer.setSize(WIDTH, HEIGHT); camera.aspect = WIDTH / HEIGHT; camera.updateProjectionMatrix(); } function handleMouseMove(event) { mousePos = {x:event.clientX, y:event.clientY}; } function handleTouchMove(event) { if (event.touches.length == 1) { event.preventDefault(); mousePos = {x:event.touches[0].pageX, y:event.touches[0].pageY}; } } function createLights() { globalLight = new THREE.HemisphereLight(0xffffff, 0xffffff, .5) shadowLight = new THREE.DirectionalLight(0xffffff, .9); shadowLight.position.set(200, 200, 200); shadowLight.castShadow = true; shadowLight.shadowDarkness = .2; shadowLight.shadowMapWidth = shadowLight.shadowMapHeight = 2048; backLight = new THREE.DirectionalLight(0xffffff, .4); backLight.position.set(-100, 100, 100); backLight.castShadow = true; backLight.shadowDarkness = .1; backLight.shadowMapWidth = shadowLight.shadowMapHeight = 2048; scene.add(globalLight); scene.add(shadowLight); scene.add(backLight); } function createFloor(){ floor = new THREE.Mesh(new THREE.PlaneBufferGeometry(1000,1000), new THREE.MeshBasicMaterial({color: 0x004F65})); floor.rotation.x = -Math.PI/2; floor.position.y = 0; floor.receiveShadow = true; scene.add(floor); } function createHero() { hero = new Cat(); scene.add(hero.threeGroup); } function createBall() { ball = new Ball(); scene.add(ball.threeGroup); } // BALL RELATED CODE var woolNodes = 10, woolSegLength = 2, gravity = -.8, accuracy =1; Ball = function(){ var redMat = new THREE.MeshLambertMaterial ({ color: 0x630d15, shading:THREE.FlatShading }); var stringMat = new THREE.LineBasicMaterial({ color: 0x630d15, linewidth: 3 }); this.threeGroup = new THREE.Group(); this.ballRay = 8; this.verts = []; // string var stringGeom = new THREE.Geometry(); for (var i=0; i< woolNodes; i++ ){ var v = new THREE.Vector3(0, -i*woolSegLength, 0); stringGeom.vertices.push(v); var woolV = new WoolVert(); woolV.x = woolV.oldx = v.x; woolV.y = woolV.oldy = v.y; woolV.z = 0; woolV.fx = woolV.fy = 0; woolV.isRootNode = (i==0); woolV.vertex = v; if (i > 0) woolV.attach(this.verts[(i - 1)]); this.verts.push(woolV); } this.string = new THREE.Line(stringGeom, stringMat); // body var bodyGeom = new THREE.SphereGeometry(this.ballRay, 5,4); this.body = new THREE.Mesh(bodyGeom, redMat); this.body.position.y = -woolSegLength*woolNodes; var wireGeom = new THREE.TorusGeometry( this.ballRay, .5, 3, 10, Math.PI*2 ); this.wire1 = new THREE.Mesh(wireGeom, redMat); this.wire1.position.x = 1; this.wire1.rotation.x = -Math.PI/4; this.wire2 = this.wire1.clone(); this.wire2.position.y = 1; this.wire2.position.x = -1; this.wire1.rotation.x = -Math.PI/4 + .5; this.wire1.rotation.y = -Math.PI/6; this.wire3 = this.wire1.clone(); this.wire3.rotation.x = -Math.PI/2 + .3; this.wire4 = this.wire1.clone(); this.wire4.position.x = -1; this.wire4.rotation.x = -Math.PI/2 + .7; this.wire5 = this.wire1.clone(); this.wire5.position.x = 2; this.wire5.rotation.x = -Math.PI/2 + 1; this.wire6 = this.wire1.clone(); this.wire6.position.x = 2; this.wire6.position.z = 1; this.wire6.rotation.x = 1; this.wire7 = this.wire1.clone(); this.wire7.position.x = 1.5; this.wire7.rotation.x = 1.1; this.wire8 = this.wire1.clone(); this.wire8.position.x = 1; this.wire8.rotation.x = 1.3; this.wire9 = this.wire1.clone(); this.wire9.scale.set(1.2,1.1,1.1); this.wire9.rotation.z = Math.PI/2; this.wire9.rotation.y = Math.PI/2; this.wire9.position.y = 1; this.body.add(this.wire1); this.body.add(this.wire2); this.body.add(this.wire3); this.body.add(this.wire4); this.body.add(this.wire5); this.body.add(this.wire6); this.body.add(this.wire7); this.body.add(this.wire8); this.body.add(this.wire9); this.threeGroup.add(this.string); this.threeGroup.add(this.body); this.threeGroup.traverse( function ( object ) { if ( object instanceof THREE.Mesh ) { object.castShadow = true; object.receiveShadow = true; }}); } /* The next part of the code is largely inspired by this codepen : http://codepen.io/dissimulate/pen/KrAwx?editors=001 thanks to dissimulate for his great work */ /* Copyright (c) 2013 dissimulate at Codepen 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. */ WoolVert = function(){ this.x = 0; this.y = 0; this.z = 0; this.oldx = 0; this.oldy = 0; this.fx = 0; this.fy = 0; this.isRootNode = false; this.constraints = []; this.vertex = null; } WoolVert.prototype.update = function(){ var wind = 0;//.1+Math.random()*.5; this.add_force(wind, gravity); nx = this.x + ((this.x - this.oldx)*.9) + this.fx; ny = this.y + ((this.y - this.oldy)*.9) + this.fy; this.oldx = this.x; this.oldy = this.y; this.x = nx; this.y = ny; this.vertex.x = this.x; this.vertex.y = this.y; this.vertex.z = this.z; this.fy = this.fx = 0 } WoolVert.prototype.attach = function(point) { this.constraints.push(new Constraint(this, point)); }; WoolVert.prototype.add_force = function(x, y) { this.fx += x; this.fy += y; }; Constraint = function(p1, p2) { this.p1 = p1; this.p2 = p2; this.length = woolSegLength; }; Ball.prototype.update = function(posX, posY, posZ){ var i = accuracy; while (i--) { var nodesCount = woolNodes; while (nodesCount--) { var v = this.verts[nodesCount]; if (v.isRootNode) { v.x = posX; v.y = posY; v.z = posZ; } else { var constraintsCount = v.constraints.length; while (constraintsCount--) { var c = v.constraints[constraintsCount]; var diff_x = c.p1.x - c.p2.x, diff_y = c.p1.y - c.p2.y, dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y), diff = (c.length - dist) / dist; var px = diff_x * diff * .5; var py = diff_y * diff * .5; c.p1.x += px; c.p1.y += py; c.p2.x -= px; c.p2.y -= py; c.p1.z = c.p2.z = posZ; } if (nodesCount == woolNodes-1){ this.body.position.x = this.verts[nodesCount].x; this.body.position.y = this.verts[nodesCount].y; this.body.position.z = this.verts[nodesCount].z; this.body.rotation.z += (v.y <= this.ballRay)? (v.oldx-v.x)/10 : Math.min(Math.max( diff_x/2, -.1 ), .1); } } if (v.y < this.ballRay) { v.y = this.ballRay; } } } nodesCount = woolNodes; while (nodesCount--) this.verts[nodesCount].update(); this.string.geometry.verticesNeedUpdate = true; } Ball.prototype.receivePower = function(tp){ this.verts[woolNodes-1].add_force(tp.x, tp.y); } // Enf of the code inspired by dissmulate // Make everything work together : var t=0; function loop(){ render(); t+=.05; hero.updateTail(t); var ballPos = getBallPos(); ball.update(ballPos.x,ballPos.y, ballPos.z); ball.receivePower(hero.transferPower); hero.interactWithBall(ball.body.position); requestAnimationFrame(loop); } function getBallPos(){ var vector = new THREE.Vector3(); vector.set( ( mousePos.x / window.innerWidth ) * 2 - 1, - ( mousePos.y / window.innerHeight ) * 2 + 1, 0.1 ); vector.unproject( camera ); var dir = vector.sub( camera.position ).normalize(); var distance = (ballWallDepth - camera.position.z) / dir.z; var pos = camera.position.clone().add( dir.multiplyScalar( distance ) ); return pos; } function render(){ if (controls) controls.update(); renderer.render(scene, camera); } window.addEventListener('load', init, false); function init(event){ initScreenAnd3D(); createLights(); createFloor() createHero(); createBall(); loop(); }
exildev/webpage
exile_ui/static/404/js/index.js
JavaScript
mit
10,479
var class_redis_cache_test = [ [ "__construct", "class_redis_cache_test.html#ae22c12eb0d136f444b6c9c0735f70382", null ], [ "testArray", "class_redis_cache_test.html#a76100cea2dba0b01bfffb70a193dfb9f", null ], [ "testGet", "class_redis_cache_test.html#afb35249bbbb21b7eac20b12d6f5a8739", null ], [ "testHas", "class_redis_cache_test.html#a8ff5d29b2ceab16b9e10aead821f3707", null ], [ "testLeveledArray", "class_redis_cache_test.html#a56c8a7551fcbda565b8f81bd9a9e3b57", null ], [ "testReinitializedGet", "class_redis_cache_test.html#addb63e1b14cdbfcdc65837dff633f7f2", null ], [ "testReinitializedHas", "class_redis_cache_test.html#a39dc99ba8e9efe29f3939ecbe99210be", null ], [ "testRemove", "class_redis_cache_test.html#a10b3034f21731f5a6507dbb5207097cf", null ] ];
Palethorn/Yeah
docs/class_redis_cache_test.js
JavaScript
mit
796
import { Widget, startAppLoop, Url, History } from 'cx/ui'; import { Timing, Debug } from 'cx/util'; import { Store } from 'cx/data'; import Routes from './routes'; import 'whatwg-fetch'; import "./index.scss"; let stop; const store = new Store(); if(module.hot) { // accept itself module.hot.accept(); // remember data on dispose module.hot.dispose(function (data) { data.state = store.getData(); if (stop) stop(); }); //apply data on hot replace if (module.hot.data) store.load(module.hot.data.state); } Url.setBaseFromScript('app.js'); History.connect(store, 'url'); Widget.resetCounter(); Timing.enable('app-loop'); Debug.enable('app-data'); stop = startAppLoop(document.getElementById('app'), store, Routes);
codaxy/employee-directory-demo
client/app/index.js
JavaScript
mit
755
import React from 'react'; import { default as TriggersContainer } from './TriggersContainer'; import { mount } from 'enzyme'; const emptyDispatch = () => null; const emptyActions = { setGeoJSON: () => null }; describe('(Container) TriggersContainer', () => { it('Renders a TriggersContainer', () => { const _component = mount(<TriggersContainer dispatch={emptyDispatch} actions={emptyActions} />); expect(_component.type()).to.eql(TriggersContainer); }); });
maartenlterpstra/GeoWeb-FrontEnd
src/containers/TriggersContainer.spec.js
JavaScript
mit
474
window.NavigationStore = function() { function isSet(menu) { return localStorage["navigation_" + menu] !== undefined; } function fetch(menu) { return localStorage["navigation_" + menu] == "true" || false; } function set(menu, value) { localStorage["navigation_" + menu] = value; } return { isSet: isSet, fetch: fetch, set: set } }();
appsignal/appsignal-docs
source/assets/javascripts/navigation_store.js
JavaScript
mit
377
import { describe, it, beforeEach, afterEach } from 'mocha'; import { expect } from 'chai'; import startApp from 'my-app/tests/helpers/start-app'; import { run } from '@ember/runloop'; describe('Acceptance | foo', function () { let application; beforeEach(function () { application = startApp(); }); afterEach(function () { run(application, 'destroy'); }); it('can visit /foo', function () { visit('/foo'); return andThen(() => { expect(currentURL()).to.equal('/foo'); }); }); });
emberjs/ember.js
node-tests/fixtures/acceptance-test/mocha.js
JavaScript
mit
526
let mongoose = require('mongoose') let userSchema = mongoose.Schema({ // userModel properties here... local: { email: { type: String, required: true }, password: { type: String, required: true } }, facebook: { id: String, token: String, email: String, name: String } }) userSchema.methods.generateHash = async function(password) { return await bcrypt.promise.hash(password, 8) } userSchema.methods.validatePassword = async function(password) { return await bcrypt.promise.compare(password, this.password) } userSchema.methods.linkAccount = function(type, values) { // linkAccount('facebook', ...) => linkFacebookAccount(values) return this['link' + _.capitalize(type) + 'Account'](values) } userSchema.methods.linkLocalAccount = function({ email, password }) { throw new Error('Not Implemented.') } userSchema.methods.linkFacebookAccount = function({ account, token }) { throw new Error('Not Implemented.') } userSchema.methods.linkTwitterAccount = function({ account, token }) { throw new Error('Not Implemented.') } userSchema.methods.linkGoogleAccount = function({ account, token }) { throw new Error('Not Implemented.') } userSchema.methods.linkLinkedinAccount = function({ account, token }) { throw new Error('Not Implemented.') } userSchema.methods.unlinkAccount = function(type) { throw new Error('Not Implemented.') } module.exports = mongoose.model('User', userSchema)
linghuaj/node-social-auth
app/models/user.js
JavaScript
mit
1,581
Photos = new orion.collection('photos', { singularName: 'photo', pluralName: 'photos', link: { title: 'Photos' }, tabular: { columns: [ {data: 'title', title: 'Title'}, {data: 'state', title: 'State'}, //ToDo: Thumbnail orion.attributeColumn('markdown', 'body', 'Content'), orion.attributeColumn('createdAt', 'createdAt', 'Created At'), orion.attributeColumn('createdBy', 'createdBy', 'Created By') ] } }); Photos.attachSchema(new SimpleSchema({ title: {type: String}, state: { type: String, allowedValues: [ "draft", "published", "archived" ], label: "State" }, userId: orion.attribute('hasOne', { type: String, label: 'Author', optional: false }, { collection: Meteor.users, // the key whose value you want to show for each Post document on the Update form titleField: 'profile.name', publicationName: 'PB_Photos_Author', }), image: orion.attribute('image', { optional: true, label: 'Image' }), body: orion.attribute('markdown', { label: 'Body' }), createdBy: orion.attribute('createdBy', { label: 'Created By' }), createdAt: orion.attribute('createdAt', { label: 'Created At' }), lockedBy: { type: String, autoform: { type: 'hidden' }, optional: true } }));
JavaScript-NZ/javascript-website-v2
app/lib/collections/2_photos.js
JavaScript
mit
1,358
import browserSync from 'browser-sync'; import config from '../../config'; import middlewaresStack from '../middlewares_stack'; import apiMiddleware from '../middlewares/api'; import mockMiddleware from '../middlewares/mock'; export default () => { const port = process.env.PORT; const middlewares = apiMiddleware() || mockMiddleware(); const server = browserSync.create(); server.init({ port, open: false, notify: false, server: { baseDir: config.distDir, middleware(req, res, next) { middlewaresStack(middlewares, req, res, next); } }, files: [ `${config.distDir}/**/*`, `!${config.distDir}/**/*.map` ] }); };
fs/backbone-base
gulp/modules/server/development.js
JavaScript
mit
690
'use strict'; module.exports.name = 'cssnano/postcss-minify-font-values'; module.exports.tests = [{ message: 'should unquote font names', fixture: 'h1{font-family:"Helvetica Neue"}', expected: 'h1{font-family:Helvetica Neue}' }, { message: 'should unquote and join identifiers with a slash, if numeric', fixture: 'h1{font-family:"Bond 007"}', expected: 'h1{font-family:Bond\\ 007}' }, { message: 'should not unquote if it would produce a bigger identifier', fixture: 'h1{font-family:"Call 0118 999 881 999 119 725 3"}', expected: 'h1{font-family:"Call 0118 999 881 999 119 725 3"}' }, { message: 'should not unquote font names if they contain keywords', fixture: 'h1{font-family:"slab serif"}', expected: 'h1{font-family:"slab serif"}' }, { message: 'should minimise space inside a legal font name', fixture: 'h1{font-family:Lucida Grande}', expected: 'h1{font-family:Lucida Grande}' }, { message: 'should minimise space around a list of font names', fixture: 'h1{font-family:Arial, Helvetica, sans-serif}', expected: 'h1{font-family:Arial,Helvetica,sans-serif}' }, { message: 'should dedupe font family names', fixture: 'h1{font-family:Helvetica,Arial,Helvetica,sans-serif}', expected: 'h1{font-family:Helvetica,Arial,sans-serif}' }, { message: 'should discard the rest of the declaration after a keyword', fixture: 'h1{font-family:Arial,sans-serif,Arial,"Trebuchet MS"}', expected: 'h1{font-family:Arial,sans-serif}' }, { message: 'should convert the font shorthand property', fixture: 'h1{font:italic small-caps normal 13px/150% "Helvetica Neue", sans-serif}', expected: 'h1{font:italic small-caps normal 13px/150% Helvetica Neue,sans-serif}' }, { message: 'should convert shorthand with zero unit line height', fixture: 'h1{font:italic small-caps normal 13px/1.5 "Helvetica Neue", sans-serif}', expected: 'h1{font:italic small-caps normal 13px/1.5 Helvetica Neue,sans-serif}', }, { message: 'should convert the font shorthand property, unquoted', fixture: 'h1{font:italic Helvetica Neue,sans-serif,Arial}', expected: 'h1{font:italic Helvetica Neue,sans-serif}' }, { message: 'should join identifiers in the shorthand property', fixture: 'h1{font:italic "Bond 007",sans-serif}', expected: 'h1{font:italic Bond\\ 007,sans-serif}' }, { message: 'should join non-digit identifiers in the shorthand property', fixture: 'h1{font:italic "Bond !",serif}', expected: 'h1{font:italic Bond\\ !,serif}' }, { message: 'should correctly escape special characters at the start', fixture: 'h1{font-family:"$42"}', expected: 'h1{font-family:\\$42}' }, { message: 'should not escape legal characters', fixture: 'h1{font-family:€42}', expected: 'h1{font-family:€42}', options: {normalizeCharset: false} }, { message: 'should not join identifiers in the shorthand property', fixture: 'h1{font:italic "Bond 007 008 009",sans-serif}', expected: 'h1{font:italic "Bond 007 008 009",sans-serif}' }, { message: 'should escape special characters if unquoting', fixture: 'h1{font-family:"Ahem!"}', expected: 'h1{font-family:Ahem\\!}' }, { message: 'should not escape multiple special characters', fixture: 'h1{font-family:"Ahem!!"}', expected: 'h1{font-family:"Ahem!!"}' }, { message: 'should not mangle legal unquoted values', fixture: 'h1{font-family:\\$42}', expected: 'h1{font-family:\\$42}' }, { message: 'should not mangle font names', fixture: 'h1{font-family:Glyphicons Halflings}', expected: 'h1{font-family:Glyphicons Halflings}' }];
pieter-lazzaro/cssnano
tests/modules/postcss-font-family.js
JavaScript
mit
3,673
function Tw2VectorSequencer() { this.name = ''; this.start = 0; this.value = vec3.create(); this.operator = 0; this.functions = []; this._tempValue = vec3.create(); } Tw2VectorSequencer.prototype.GetLength = function () { var length = 0; for (var i = 0; i < this.functions.length; ++i) { if ('GetLength' in this.functions[i]) { length = Math.max(length, this.functions[i].GetLength()); } } return length; } Tw2VectorSequencer.prototype.UpdateValue = function (t) { this.GetValueAt(t, this.value); } Tw2VectorSequencer.prototype.GetValueAt = function (t, value) { if (this.operator == 0) { value[0] = 1; value[1] = 1; value[2] = 1; var tempValue = this._tempValue; var functions = this.functions; for (var i = 0; i < functions.length; ++i) { functions[i].GetValueAt(t, tempValue); value[0] *= tempValue[0]; value[1] *= tempValue[1]; value[2] *= tempValue[2]; } } else { value[0] = 0; value[1] = 0; value[2] = 0; var tempValue = this._tempValue; var functions = this.functions; for (var i = 0; i < functions.length; ++i) { functions[i].GetValueAt(t, tempValue); value[0] += tempValue[0]; value[1] += tempValue[1]; value[2] += tempValue[2]; } } return value; }
reactormonk/ccpwgl
src/curves/Tw2VectorSequencer.js
JavaScript
mit
1,489
// Include gulp var gulp = require('gulp'); // Include Our Plugins var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var header = require('gulp-header'); var footer = require('gulp-footer'); // Build Task gulp.task('default', function() { gulp.src([ "src/promises.js", "src/util.js", "src/request.js", "src/legends.js", "src/static.js" ]) .pipe(concat('legends.js', { newLine: "\n\n" })) .pipe(header("/*!\n" + " * Legends.js\n" + " * Copyright (c) {{year}} Tyler Johnson\n" + " * MIT License\n" + " */\n\n" + "(function() {\n")) .pipe(footer("\n// API Factory\n" + "if (typeof module === \"object\" && module.exports != null) {\n" + "\tmodule.exports = Legends;\n" + "} else if (typeof window != \"undefined\") {\n" + "\twindow.Legends = Legends;\n" + "}\n\n" + "})();")) .pipe(gulp.dest('./dist')) .pipe(rename('legends.min.js')) .pipe(uglify({ output: { comments: /^!/i } })) .pipe(gulp.dest('./dist')); });
tyler-johnson/Legends
gulpfile.js
JavaScript
mit
1,023
var myTimeout = 12000; Storage.prototype.setObject = function(key, value) { this.setItem(key, JSON.stringify(value)); }; Storage.prototype.getObject = function(key) { var value = this.getItem(key); return value && JSON.parse(value); }; // Обеспечиваем поддержу XMLHttpRequest`а в IE var xmlVersions = new Array( "Msxml2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ); if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() { for(var i in xmlVersions) { try { return new ActiveXObject(xmlVersions[i]); } catch(e) {} } throw new Error( "This browser does not support XMLHttpRequest." ); }; // Собственно, сам наш обработчик. function myErrHandler(message, url, line) { var tmp = window.location.toString().split("/"); var server_url = tmp[0] + '//' + tmp[2]; var params = "logJSErr=logJSErr&message="+message+'&url='+url+'&line='+line; var req = new XMLHttpRequest(); req.open('POST', server_url+'/jslogerror?ajax=1', true); req.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); req.setRequestHeader("Content-length", params.length); req.setRequestHeader("Connection", "close"); req.send(params); // Чтобы подавить стандартный диалог ошибки JavaScript, // функция должна возвратить true return true; } // window.onerror = myErrHandler; //назначаем обработчик для события onerror // ПОТОМ ВКЛЮЧИТЬ window.onerror = myErrHandler; function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function nl2br(str) { return str.replace(/([^>])\n/g, '$1<br>'); } function htmlspecialchars(text) { var map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }; return text.replace(/[&<>"']/g, function(m) { return map[m]; }); }
schoolphp/library
Core/fw.js
JavaScript
mit
2,095
/*! YAD - v1.0.0 - 82bbc70 - 2014-12-02 * Yahoo Personalised Content Widget * Copyright (c) 2014 ; Licensed */ (function(){var f=window.document,e={Error:function(a){this.message=a},Bootstrap:function(a,b,c){this.widgetInitialisationStartedAt=this.timeSinceNavigationStart();this.snippetLoadedAt=c?this.timeSinceNavigationStart(c):null;this.config=b;this.publisherId=a;this.config.analytics||(this.config.analytics={});this.id=this.config.id;this.config.analytics.pageURL=e.Helper.detectPageURL();this.config.analytics.referrer=e.Helper.detectReferrer();this.config.analytics.click_postmsg={payload:{action:"redirect", id:this.id}};this.config.canonicalURL=e.Helper.detectCanonical();this.init()}};e.Bootstrap.prototype={init:function(){this.element="undefined"!==typeof this.config.element?this.config.element:e.Helper.detectScriptTag();delete this.config.element;var a=this.iframeURL();this.iframe=this.createIframeElement(a);var b=this;window.addEventListener?this.iframe.addEventListener("load",function(){b.sendPostMessage({action:"init",config:b.config,id:b.id,url:e.Helper.detectPageURL(),tti:b.widgetInitialisationStartedAt, tts:b.snippetLoadedAt,cid:b.publisherId})}):window.attachEvent&&this.iframe.attachEvent("onload",function(){b.sendPostMessage({action:"init",config:b.config,id:b.id,url:e.Helper.detectPageURL(),tti:b.widgetInitialisationStartedAt,tts:b.snippetLoadedAt,cid:b.publisherId})});this.listen();this.render()},listenForViewport:function(){var a=this,b=null,c=null,d=function(d){return function(){var e=a.isElementInViewport(d,0);e&&!a.hasBeenInViewport&&(a.hasBeenInViewport=!0,a.sendPostMessage({action:"inViewport"})); if(e){var f=function(){var b=a.iframeRelativeScrollPosition(d);a.sendPostMessage({action:"scroll",scrollTop:b[0],scrollLeft:b[1],height:a.iframeRelativeHeight(d),width:a.iframeRelativeWidth(d)})};window.clearTimeout(b);b=window.setTimeout(function(){window.clearInterval(c);f();c=null},350);null===c&&(c=window.setInterval(f,500),f())}}}(this.iframe);window.addEventListener?(window.addEventListener("DOMContentLoaded",d,!1),window.addEventListener("load",d,!1),window.addEventListener("scroll",d,!1), window.addEventListener("resize",d,!1)):window.attachEvent&&(window.attachEvent("DOMContentLoaded",d),window.attachEvent("onload",d),window.attachEvent("onscroll",d),window.attachEvent("onresize",d));d()},iframeURL:function(){return e.Bootstrap.IFRAME_URL},createIframeElement:function(a){var b=f.createElement("iframe");b.frameBorder=0;b.width="100%";b.height="0";b.setAttribute("style","display:block");b.setAttribute("src",a);b.setAttribute("allowtransparency",!0);return b},sendPostMessage:function(a){return e.PostMessage.send(a, e.Bootstrap.IFRAME_DOMAIN,this.iframe.contentWindow)},listen:function(){e.PostMessage.listen(this.onReceivePostMessage,e.Bootstrap.IFRAME_DOMAIN,this)},render:function(){this.element.appendChild(this.iframe)},onReceivePostMessage:function(a){if(a.id===this.id)switch(a.action){case "data":this.listenForViewport();break;case "height":this.setHeight(a.height);break;case "redirect":this.redirect(a.href);break;case "hide":this.hide();break;case "error":this.config.onError&&"function"===typeof this.config.onError&& this.config.onError.apply(this,[Error("widget failed to load")]);break;case "about":e.Lightbox.About()}},hide:function(){this.iframe&&(this.iframe.style.display="none");this.element&&this.element.setAttribute("class",this.element.getAttribute("class")+" yad-empty")},redirect:function(a){window.location=a},setHeight:function(a){this.iframe.height=a+"px"},isElementInViewport:function(a,b){"undefined"===typeof b&&(b=0);var c,d;"undefined"!==typeof window.pageXOffset?c=window.pageXOffset:f.documentElement&& "undefined"!==typeof f.documentElement.scrollLeft?c=f.documentElement.scrollLeft:"undefined"!==typeof f.body.scrollLeft&&(c=f.body.scrollLeft);"undefined"!==typeof window.pageYOffset?d=window.pageYOffset:f.documentElement&&"undefined"!==typeof f.documentElement.scrollTop?d=f.documentElement.scrollTop:"undefined"!==typeof f.body.scrollTop&&(d=f.body.scrollTop);var e,g;g=e=0;e="undefined"!==typeof window.innerWidth?window.innerWidth:f.documentElement.clientWidth;g="undefined"!==typeof window.innerHeight? window.innerHeight:f.documentElement.clientHeight;e=c+e;g=d+g;var h=b,k=a.getBoundingClientRect(),l=k.right-k.left,n=k.bottom-k.top,m=k.top+d,k=k.left+c,p,q;p=k+l*(1-h);q=m+n*(1-h);return!(e<k+l*h||c>p||g<m+n*h||d>q)},iframeRelativeHeight:function(a){var b=a.getBoundingClientRect(),c=b.top,d=window.innerHeight||f.documentElement.clientHeight;a=a.scrollTop;b=b.bottom-b.top;return c<a&&b-a>=d?d:c<a?Math.max(0,b-(a-c)):c>a&&c+b<d?b:Math.max(0,d-(c-a))},iframeRelativeWidth:function(a){var b=a.getBoundingClientRect(), c=b.left,d=window.innerWidth||f.documentElement.clientWidth;a=a.scrollLeft;b=b.right-b.left;return c<a&&b-a>=d?d:c<a?Math.max(0,b-(a-c)):c>a&&c+b<d?b:Math.max(0,d-(c-a))},iframeRelativeScrollPosition:function(a){a=a.getBoundingClientRect();var b=-1*a.top,c=-1*a.left;0<a.left&&(c=0);0<a.top&&(b=0);return 0>b||0>c?[0,0]:[Math.max(0,b),Math.max(0,c)]},timeSinceNavigationStart:function(a){if("undefined"===typeof window.performance)return!1;a||(a=(new Date).getTime());return a-window.performance.timing.domLoading}}; e.Helper={templateShortname:function(a){switch(a){case "single-column-text":return"sctext";case "single-column-thumbnail":return"scthumb";case "dual-column-thumbnail":return"dcthumb";case "dual-column-text":return"dctext";case "dual-column-text-web":return"dcwtext";case "dual-column-thumbnail-web":return"dcwthumb";case "single-row-carousel":return"srcarousel";case "dual-row-carousel":return"drcarousel";case "dual-row-carousel-web":return"drwcarousel";case "instrumentation-beacon":return"insbeacon"; case "error":return"error";default:throw new e.Error("Could not get shortname for template: "+a);}},addClass:function(a,b){var c,d=a instanceof Array?a:[a];for(c=0;c<d.length;c++)e.Helper._addClass(d[c],b)},_addClass:function(a,b){a.classList?a.classList.add(b):e.Helper.containClass(a,b)||(a.className+=" "+b)},removeClass:function(a,b){var c,d=a instanceof Array?a:[a];for(c=0;c<d.length;c++)e.Helper._removeClass(d[c],b)},_removeClass:function(a,b){var c=RegExp("(\\s|^)"+b+"(\\s|$)","g");a.classList? a.classList.remove(b):a.className=a.className.replace(c," ").replace(/\s\s+/g," ")},replaceClass:function(a,b,c){var d=a instanceof Array?a:[a];for(a=0;a<d.length;a++)e.Helper._removeClass(d[a],b),e.Helper._addClass(d[a],c)},toggleClass:function(a,b,c){var d=a instanceof Array?a:[a];for(a=0;a<d.length;a++)!0===c?e.Helper._addClass(d[a],b):!1===c?e.Helper._removeClass(d[a],b):e.Helper.containClass(d[a],b)?e.Helper._removeClass(d[a],b):e.Helper._addClass(d[a],b)},containClass:function(a,b){var c=RegExp("(\\s|^)"+ b+"(\\s|$)");return a.classList?a.classList.contains(b):c.test(a.className)},getEventListenerCompatible:function(){return f.createElement("div").addEventListener?!0:!1},bind:function(a,b,c,d,f){if(!a)throw new e.Error("Valid event not supplied");if(!b)throw new e.Error("Valid element not supplied");if(!c)throw new e.Error("Valid callback not supplied");f=f||[];a=a.split(" ");for(var g=0;g<a.length;g++)e.Helper._addEventListener(a[g],b,c,d,f)},unbind:function(a,b,c){if(!a)throw new e.Error("Valid event not supplied"); if(!b)throw new e.Error("Valid element not supplied");if(!c)throw new e.Error("Valid callback not supplied");a=a.split(" ");for(var d=0;d<a.length;d++)e.Helper._removeEventListener(a[d],b,c)},bindCustom:function(a,b,c,d,f){if(b.addEventListener)return e.Helper.bind(a,b,c,d,f);b[a]=0;return e.Helper.bind("propertychange",b,function(b){b.propertyName===a&&c.call(this,Array.prototype.slice.call(arguments,1))},d,f)},bindAll:function(a,b,c,d,f){if(b)for(var g=b.length-1;0<=g;g-=1)e.Helper.bind(a,b[g], c,d,f)},_addEventListener:function(a,b,c,d,f){if(b.addEventListener)b.addEventListener(a,function(a){a.preventDefault||(a.preventDefault=function(){this.returnValue=!1});c.apply(d,[a].concat(f))},!1);else if(b.attachEvent)b.attachEvent("on"+a,function(a){a.preventDefault||(a.preventDefault=function(){this.returnValue=!1});c.apply(d,[a].concat(f))});else throw new e.Error("Tried to bind event to incompatible object. Object needs addEventListener (or attachEvent).");},_removeEventListener:function(a, b,c){if(b.removeEventListener)b.removeEventListener(a,c,!1);else if(b.detachEvent)b.detachEvent("on"+a,c);else throw new e.Error("Tried to bind event to incompatible object. Object needs removeEventListener (or detachEvent).");},dispatchEvent:function(a,b,c){var d;f.createEvent?(d=f.createEvent("HTMLEvents"),d.initEvent(b,!0,!0)):f.createEventObject&&(d=f.createEventObject(),d.eventType=b);if(!d)throw new e.Error("dispatchEvent could not create click event");for(var r in c)c.hasOwnProperty(r)&&(d[r]= c[r]);d.eventName=b;if(a.dispatchEvent)a.dispatchEvent(d);else if(a.fireEvent)switch(d.eventType){case "click":case "mousedown":case "mouseover":a.fireEvent("on"+d.eventType,d);break;default:a[d.eventType]=d}else if(a[b])a[b](d);else if(a["on"+b])a["on"+b](d)},createElement:function(a){return f.createElement(a)},addScript:function(a,b,c){return e.Helper.Ajax.addScript(a,b,c)},isVisible:function(a){return a===f?!0:a&&a.parentNode&&"none"!==e.Helper.getComputedStyleCssProperty(a,"display")&&"hidden"!== e.Helper.getComputedStyleCssProperty(a,"visibility")?e.Helper.isVisible(a.parentNode):!1},getOuterHeight:function(a){var b=e.Helper.getComputedStyleCssProperty(a,"margin-top"),c=e.Helper.getComputedStyleCssProperty(a,"margin-bottom");try{b=parseInt(b,10),c=parseInt(c,10)}catch(d){c=b=0}return a.offsetHeight+b+c},getComputedStyleCssProperty:function(a,b){var c;if(window.getComputedStyle)return window.getComputedStyle(a).getPropertyValue(b);c=e.Helper._getCamelCasedCssProperty(b);return a.currentStyle? a.currentStyle[c]:a.style[c]},_getCamelCasedCssProperty:function(a){return a.replace(/-([a-z])/g,function(a){return a[1].toUpperCase()})},truncateString:function(a,b){if("undefined"===typeof a)return"";if(void 0===b||a.length<b)return a;if(0>=b)return"";var c=a.substring(0,b-1),d=c.lastIndexOf(" ");d<b&&-1!==d&&(c=c.substr(0,Math.min(c.length,d)));return c+"\u2026"},htmlEntities:function(a){return String(a).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g, "&gt;").replace(/\//g,"&#x2F;").replace(/`/g,"&#x60;")},fragmentFromString:function(a){var b=f.createDocumentFragment(),c=f.createElement("body");for(c.innerHTML=a;null!==(a=c.firstChild);)b.appendChild(a);return b},stringFromFragment:function(a){var b=f.createElement("div");b.appendChild(a);return b.innerHTML},template:function(a,b){var c,d=0,f=[];for(c in b)if(b.hasOwnProperty(c)){var g=b[c];if(this.isDocumentFragment(g)){var h="yad-template-fragment-"+d;f.push([h,g]);g='<span id="'+h+'"></span>'; d++}a=a.split("{{"+c.toUpperCase()+"}}").join(g)}c=e.Helper.fragmentFromString(a);for(d=0;d<f.length;d++)g=c.querySelector("#"+f[d][0]),g.parentNode.replaceChild(f[d][1],g);return c},isDocumentFragment:function(a){try{return"undefined"!==typeof DocumentFragment&&a instanceof DocumentFragment||"undefined"!==typeof HTMLDocument&&a instanceof HTMLDocument}catch(b){return"string"!==typeof a&&"number"!==typeof a}},merge:function(a,b){for(var c in b)b[c]&&b[c].constructor&&b[c].constructor===Object?(a[c]= a[c]||{},e.Helper.merge(a[c],b[c])):a[c]=b[c];return a},clone:function(a){return JSON.parse(JSON.stringify(a))},addStyleTag:function(a){var b=e.Helper.createElement("style");b.setAttribute("type","text/css");b.styleSheet?(f.getElementsByTagName("head")[0].appendChild(b),b.styleSheet.cssText=a):(b.innerHTML=a,f.getElementsByTagName("head")[0].appendChild(b))},addLinkTag:function(a){var b,c=e.Helper.createElement("link");for(b in a)a.hasOwnProperty(b)&&c.setAttribute(b,a[b]);f.getElementsByTagName("head")[0].appendChild(c)}, addDynamicCSS:function(a){var b,c={rel:"stylesheet",type:"text/css"},d;a.hasConfigCSS()&&e.Helper.addStyleTag("/* config CSS */ "+a.getConfigCSS());if(a.hasCSSURLs())for(b=a.getCSSURLs(),d=0;d<b.length;d++)c.href=b[d],e.Helper.addLinkTag(c);a.hasCustomCSS()&&e.Helper.addStyleTag("/* custom CSS */ "+a.getCustomCSS())},isElementInViewport:function(a,b,c,d,e,g){"undefined"===typeof b&&(b=0);var h,k;"undefined"!==typeof window.pageXOffset?h=window.pageXOffset:f.documentElement&&"undefined"!==typeof f.documentElement.scrollLeft? h=f.documentElement.scrollLeft:"undefined"!==typeof f.body.scrollLeft&&(h=f.body.scrollLeft);"undefined"!==typeof window.pageYOffset?k=window.pageYOffset:f.documentElement&&"undefined"!==typeof f.documentElement.scrollTop?k=f.documentElement.scrollTop:"undefined"!==typeof f.body.scrollTop&&(k=f.body.scrollTop);var l=0,n=0,l="undefined"!==typeof e?e:"undefined"!==typeof window.innerWidth?window.innerWidth:f.documentElement.clientWidth,n="undefined"!==typeof g?g:"undefined"!==typeof window.innerHeight? window.innerHeight:f.documentElement.clientHeight;c=c?c:k;d=d?d:h;l=d+l;n=c+n;g=a.getBoundingClientRect();a=g.right-g.left;h=g.bottom-g.top;e=g.top;g=g.left;var m;k=g+a*(1-b);m=e+h*(1-b);return!(l<g+a*b||d>k||n<e+h*b||c>m)},arrayIndexOf:function(a,b){if(Array.prototype.indexOf)return b.indexOf(a);var c=b.length>>>0,d=0;Infinity===Math.abs(d)&&(d=0);0>d&&(d+=c,0>d&&(d=0));for(;d<c;d++)if(b[d]===a)return d;return-1},detectPageURL:function(){return window.location.href},detectReferrer:function(){return window.document.referrer}, detectCanonical:function(){var a=f.querySelector("link[rel='canonical']");return a?a.href:!1},detectScriptTag:function(){var a=f.querySelectorAll("script");if(!a)throw new e.Error("No script tags could be found on the page");return a[a.length-1]},getRSSUrls:function(){var a=f.querySelectorAll('link[type="application/rss+xml"]'),b,c=[];if(a){for(b=0;b<a.length;b+=1)a[b].getAttribute("href")&&c.push(a[b].getAttribute("href"));return c}},getDocumentHeight:function(a){return a.documentElement.scrollHeight}, timestamp:function(){return Math.floor((new Date).valueOf()/1E3)},urlencode:function(a){return window.encodeURIComponent(a)},stripProtocol:function(a){var b=a.split("://");return 1<b.length?b[1]:a},applyEllipsis:function(a,b){a.textContent=b&&b.replace?b.replace(/\s+$/g,"")+"\u2026":""},computeStyle:function(a,b){return window.getComputedStyle?window.getComputedStyle(a,null).getPropertyValue(b):!1},getLineHeight:function(a){var b=this.computeStyle(a,"line-height");"normal"===b&&(b=Math.ceil(1.2*parseFloat(this.computeStyle(a, "font-size"),10)));return parseFloat(b,10)},getMaxHeight:function(a,b){return this.getLineHeight(b)*a},getLastChild:function(a,b){if(a.lastChild.children&&0<a.lastChild.children.length)return this.getLastChild(Array.prototype.slice.call(a.children).pop(),b);if(a.lastChild&&""!==a.lastChild.nodeValue)return a.lastChild;a.lastChild.parentNode.removeChild(a.lastChild);return this.getLastChild(b,b)},truncateToHeight:function(a,b,c,d){if(b&&!(0>=b)){var e=a.textContent.replace("\u2026",""),g=d.element, f=d.splitOnChars,k=d.splitChar,l=d.chunks,n=d.lastChunk;l||(k=0<f.length?f.shift():"",l=e.split(k));1<l.length?(n=l.pop(),this.applyEllipsis(a,l.join(k))):l=null;if(l){if(g.clientHeight&&g.clientHeight<=b||g.offsetHeight&&g.offsetHeight<=b)if(0<=f.length&&""!==k)this.applyEllipsis(a,l.join(k)+k+n);else return!1}else""===k&&(this.applyEllipsis(a,""),a=this.getLastChild(g,g),d.splitOnChars=c.slice(0),d.splitChar=d.splitOnChars[0],d.chunks=null,d.lastChunk=null);this.truncateToHeight(a,b,c,d)}},clamp:function(a, b){b=b||{};if(!("undefined"!==typeof b.clamp&&1>b.clamp)){var c={clamp:b.clamp||2,splitOnChars:b.splitOnChars||[".","-"," "]},d=c.splitOnChars.slice(0),e=d[0],c=this.getMaxHeight(c.clamp,a);(a.clientHeight&&c<a.clientHeight||a.offsetHeight&&c<a.offsetHeight)&&this.truncateToHeight(this.getLastChild(a,a),c,d,{element:a,splitOnChars:d,splitChar:e,chunks:null,lastChunk:null})}},clampTitle:function(a,b,c){if(!(1>c)&&!1!==c&&window.getComputedStyle)for(a=a.querySelectorAll(b),b=0;b<a.length;b++)this.clamp(a[b], {clamp:c})}};e.PostMessage={lastHeight:null,send:function(a,b,c){if("undefined"===typeof b)throw new e.Error("You must supply a target as a string");"undefined"===typeof c&&(c=window.parent);c.postMessage(e.PostMessage._serialize(a),b)},listen:function(a,b,c){if("undefined"===typeof b)throw new e.Error("You must supply an origin or an array of origins");var d=function(d){if("*"!==b&&b!==d.origin)return!1;a.call(c,e.PostMessage._unserialize(d.data),d.origin,d.source)};window.addEventListener?window.addEventListener("message", d,!1):window.attachEvent("onmessage",d)},sendHeight:function(a,b,c){e.PostMessage._sendUpdateHeightMessage(a,b,c);window.setInterval(function(){e.PostMessage._sendUpdateHeightMessage(a,b,c)},1E3)},_sendUpdateHeightMessage:function(a,b,c){var d=e.Helper.getDocumentHeight(f);e.PostMessage.lastHeight!==d&&(void 0===c&&(c={}),c.action="height",c.height=d,e.PostMessage.send(c,a,b),e.PostMessage.lastHeight=d)},_unserialize:function(a){var b=null;if("string"===typeof a){try{b=JSON.parse(a)}catch(c){}return b}return a}, _serialize:function(a){return JSON.stringify(a)}};e.Lightbox=function(){this.init()};e.Lightbox.MASK_STYLE="position:fixed;top:0;left:0;z-index:99999;background-color:#000;background-color:rgba(0,0,0,0.5);width:100%;height:100%;";e.Lightbox.CONTENT_STYLE='position:relative;margin:0 auto;top:10%;z-index:999999;background-color:#fff;width:100%;min-height:100px;max-height:80%;overflow:auto;width:400px;max-width:90%;border-radius: 5px;box-shadow: 0px 0px 20px 0px rgba(0,0,0,0.55);"';e.Lightbox.CLOSE_STYLE= "position:absolute;right:0;top:0;padding:5px;cursor:pointer;text-decoration:none;color: #5f5f5f;line-height: 6px;text-align:center;margin: 6px;font-size: 22px;";e.Lightbox.About=function(){var a=new e.Lightbox;a.setContent("<iframe src='"+e.Lightbox.ABOUT_IFRAME_URL+"' style='width:100%;height:300px' frameborder='0'></iframe>");a.show();return a};e.Lightbox.prototype={init:function(){this.lightboxContent=""},show:function(){this.exists()?this.container().style.display="block":(this.create(),this.show())}, hide:function(){this.exists()&&(this.container().style.display="none")},create:function(){this.createMask();this.createContentPane();this.createCloseButton();this.bindClose()},createMask:function(){var a=f.createElement("div");a.setAttribute("class","yad-lightbox");a.setAttribute("style",e.Lightbox.MASK_STYLE);a.style.display="none";f.getElementsByTagName("body")[0].appendChild(a);return this.containerDiv=a},createContentPane:function(){var a=f.createElement("div");a.setAttribute("class","yad-lightbox-content"); a.setAttribute("style",e.Lightbox.CONTENT_STYLE);this.container().appendChild(a);this.lightboxContent&&"string"===typeof this.lightboxContent?a.innerHTML=this.lightboxContent:this.lightboxContent&&a.appendChild(this.lightboxContent);return this.contentPane=a},createCloseButton:function(){var a=f.createElement("a");a.setAttribute("class","yad-lightbox-close");a.setAttribute("style",e.Lightbox.CLOSE_STYLE);a.innerHTML="\u00d7";this.contentPane.appendChild(a);return a},bindClose:function(){var a=this; window.addEventListener?(this.container().addEventListener("click",function(b){b.target===a.container()&&a.closeHandler.call(a)},!1),this.container().querySelector(".yad-lightbox-close").addEventListener("click",function(){a.closeHandler.call(a)}),window.addEventListener("keydown",function(b){27===b.keyCode&&a.closeHandler.call(a)},!1)):window.attachEvent&&(this.container().attachEvent("onclick",function(b){b.target===a.container()&&a.closeHandler.call(a)},!1),this.container().querySelector(".yad-lightbox-close").attachEvent("onclick", function(){a.closeHandler.call(a)}),window.attachEvent("onkeydown",function(b){27===b.keyCode&&a.closeHandler.call(a)},!1))},closeHandler:function(){this.hide()},container:function(){return this.containerDiv},exists:function(){return!!this.container()},setContent:function(a){this.lightboxContent=a}};e.Helper=e.Helper||{};e.Helper.Ajax={JSONPCallbacks:{},timeouts:{},AJAX_TIMEOUT:1E3,ajax:function(a,b,c,d,f){return e.Helper.Ajax.jsonp(a,b,c,d,f)},xhr:function(a,b,c,d,e){var f=new XMLHttpRequest;f.onreadystatechange= function(){4>f.readyState||200===f.status&&4===f.readyState&&c.call(e,f)};f.open("GET",a,!0);try{f.send("")}catch(h){"function"===typeof d&&d(h)}},jsonp:function(a,b,c,d,f){var g=(new Date).getTime(),h,k={},l;b&&b.publisher_url_params&&(h=b.publisher_url_params,delete b.publisher_url_params);b&&(a+=(-1<a.indexOf("?")?"&":"?")+e.Helper.Ajax.urlencode(b));if(h){for(l in h)if(h.hasOwnProperty(l))if("string"===typeof h[l]||"number"===typeof h[l]||"boolean"===typeof h[l])k[l]=h[l];else if("undefined"=== typeof h[l]||null===h[l])k[l]=null;a+=(-1<a.indexOf("?")?"&":"?")+"publisher_url_params="+encodeURIComponent(JSON.stringify(k))}a=a+(-1<a.indexOf("?")?"&":"?")+"callback="+("YADJSONPCallbacks.receiveCallback_"+g);e.Helper.Ajax.JSONPCallbacks["receiveCallback_"+g]=function(a){window.clearTimeout(e.Helper.Ajax.timeouts[g]);a&&a.error&&d?d.call(f,a):a&&a.error?console.error("JSONP called returned an error, but there was no handler provided."):c&&c.call(f,a);delete e.Helper.Ajax.JSONPCallbacks["receiveCallback_"+ g]};b=setTimeout(function(){e.Helper.Ajax.JSONPCallbacks["receiveCallback_"+g]=function(){delete e.Helper.Ajax.JSONPCallbacks["receiveCallback_"+g]};d&&d.call(f,{error:!0,isTimeout:!0})},e.Helper.Ajax.AJAX_TIMEOUT);e.Helper.Ajax.timeouts[g]=b;e.Helper.Ajax.addScript(a)},createElement:function(a){return f.createElement(a)},addScript:function(a,b,c){var d=e.Helper.Ajax.createElement("script"),m=f.getElementsByTagName("head")[0],g=!1;d.type="text/javascript";d.src=a;b&&(d.onload=d.onreadystatechange= function(){g||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState||(g=!0,d.onload=d.onreadystatechange=null,b.call(c))});m.insertBefore(d,m.firstChild)},urlencode:function(a,b){var c=[],d,f,g;for(d in a)if(a.hasOwnProperty(d))switch(f=b&&a instanceof Array?b+"[]":b?b+"["+d+"]":d,g=a[d],typeof g){case "object":g instanceof Array&&!(0<g.length)||c.push(e.Helper.Ajax.urlencode(g,f));break;default:c.push(encodeURIComponent(f)+"="+encodeURIComponent(g))}return c.join("&")},generateRequestID:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(a){var b=16*Math.random()|0;return("x"===a?b:b&3|8).toString(16)})}};window.YADJSONPCallbacks=window.YADJSONPCallbacks||e.Helper.Ajax.JSONPCallbacks;e.Bootstrap.IFRAME_DOMAIN="https://s.yimg.com";e.Bootstrap.LOG_PATH="//syndication.streamads.yahoo.com/na_stream_brewer/error/v1";e.Bootstrap.IFRAME_URL=e.Bootstrap.IFRAME_DOMAIN+"/uq/syndication/yad-iframe.82bbc70.html";e.Lightbox.ABOUT_IFRAME_URL=e.Bootstrap.IFRAME_DOMAIN+"/uq/syndication/yad-about.html";if("undefined"===typeof window.yad|| !window.yad.initialized){var t="undefined"!==typeof window.yad&&"undefined"!==typeof window.yad.q?window.yad.q:[],q=[],p={},s={};window.yad=function(a,b,c){b=b||{};var d=b.debug&&window.console&&window.console.error,m=null,g=window.location&&window.location.pathname+window.location.search;g?(s[g]||(s[g]=e.Helper.Ajax.generateRequestID()),g=s[g]):g=e.Helper.Ajax.generateRequestID();try{"undefined"===typeof p[a]&&(p[a]=0);b.element||(b.element=f.querySelectorAll(".YAD-"+a)[p[a]]);b.element||(b.element= f.querySelectorAll(".YAD")[q.length]);if(!b.element)throw new e.Error("Element with index #"+q.length+" not found");b.id=window.yad.i;b.pageviewID=g;m=new e.Bootstrap(a,b,c);q.push(m);p[a]+=1;window.yad.i++}catch(h){m&&m.hide();try{e.Helper.Ajax.ajax(e.Bootstrap.LOG_PATH,{exception:h.message,type:"Bootstrap",cid:a,pvid:g,url:window.location&&window.location.href})}catch(k){d&&window.console.error("YAD: Unable to send following message to log due to "+k.message)}if(d)if(h instanceof e.Error)window.console.error("YAD: "+ h.message);else throw h;}};window.yad.initialized=!0;window.yad.i=1;for(var m;t&&(m=t.shift());)"string"===typeof m[0]?window.yad(m[0],m[1]):(m[0]instanceof Array||m[0]instanceof Object)&&window.yad(m[0][0],m[0][1],m[1])}e.VERSION="82bbc70"})();
izakfilmalter/the-verge
the-verge-article/Google is killing CAPTCHA as we know it The Verge_files/yad.js
JavaScript
mit
24,061
/** * grunt-webfont: fontforge engine * * @requires fontforge, ttfautohint 1.00+ (optional), eotlitetool.py * @author Artem Sapegin (http://sapegin.me) */ module.exports = function(o, allDone) { 'use strict'; var fs = require('fs'); var path = require('path'); var temp = require('temp'); var async = require('async'); var glob = require('glob'); var exec = require('exec'); var chalk = require('chalk'); var _ = require('lodash'); var logger = o.logger || require('winston'); var wf = require('../util/util'); // Copy source files to temporary directory var tempDir = temp.mkdirSync(); o.files.forEach(function(file) { fs.writeFileSync(path.join(tempDir, o.rename(file)), fs.readFileSync(file)); }); // Run Fontforge var args = [ 'fontforge', '-script', path.join(__dirname, 'fontforge/generate.py') ]; var proc = exec(args, function(err, out, code) { if (err instanceof Error && err.code === 'ENOENT') { return error('fontforge not found. Please install fontforge and all other requirements.'); } else if (err) { if (err instanceof Error) { return error(err.message); } // Skip some fontforge output such as copyrights. Show warnings only when no font files was created // or in verbose mode. var success = !!generatedFontFiles(); var notError = /(Copyright|License |with many parts BSD |Executable based on sources from|Library based on sources from|Based on source from git)/; var lines = err.split('\n'); var warn = []; lines.forEach(function(line) { if (!line.match(notError) && !success) { warn.push(line); } else { logger.verbose(chalk.grey('fontforge: ') + line); } }); if (warn.length) { return error(warn.join('\n')); } } // Trim fontforge result var json = out.replace(/^[^{]+/, '').replace(/[^}]+$/, ''); // Parse json var result; try { result = JSON.parse(json); } catch (e) { return error('Webfont did not receive a proper JSON result.\n' + e + '\n' + out); } allDone({ fontName: path.basename(result.file) }); }); // Send JSON with params if (!proc) return; var params = _.extend(o, { inputDir: tempDir }); proc.stdin.write(JSON.stringify(params)); proc.stdin.end(); function generatedFontFiles() { return glob.sync(path.join(o.dest, o.fontBaseName + wf.fontFileMask)); } function error() { logger.error.apply(null, arguments); allDone(false); return false; } };
jnaO/grunt-webfont
tasks/engines/fontforge.js
JavaScript
mit
2,457
'use strict'; var fs = require('fs'), path = require('path'); // path.basename('/foo/bar/baz/asdf/quux.html', '.html') = quux // path.dirname('/foo/bar/baz/asdf/quux.html') = /foo/bar/baz/asdf/ // path.parse('/home/user/dir/file.txt') // returns // { // root : "/", // dir : "/home/user/dir", // base : "file.txt", // ext : ".txt", // name : "file" // } var walk = function(dir, done){ var results = {}; fs.readdir(dir, function(err, list){ if (err) { return done(err); } var pending = list.length; if (!pending) { return done(null, results); } list.forEach(function(layer){ var target = path.resolve(dir, layer); fs.stat(target, function(err, stat){ if (stat && stat.isDirectory()) { console.log(layer); results[layer] = []; walk(target, function(err, file){ console.log(file); if (!--pending) { done(null, results); } }); } else { var file = path.basename(target); if (file[0] === '_') { // results[layer][].push(file); null; } if (!--pending) { done(null, results); } } }); }); }); }; var walking = function(config, done){ var results = {}; var pending = config.layers.length; config.layers.forEach(function(layer){ results[layer] = []; if (!pending) { return done(null, results); } fs.readdir(config.src.scss + '/' + layer, function(err, files){ if (err) { return 'error #1'; } files.forEach(function(file){ if (file[0] !== '.') { if (file[0] !== '_') { results[layer].push(file); } else { results[layer].push(file.slice(1, -5)); } } }); }); if (pending === 1) { done(null, results); } else { --pending; } }); }; var layers = function(dir){ var results = walk(dir, function(err, results){ if (err) { throw err; } results = JSON.stringify(results, null, 4); console.log(results); fs.writeFile('guide/app.json', results); return results; }); } module.exports = layers;
hanakin/rotory
src/model/layers/index.js
JavaScript
mit
2,763
var NULL = null; function NOP() {} function NOT_IMPLEMENTED() { throw new Error("not implemented."); } function int(x) { return x|0; } function pointer(src, offset, length) { offset = src.byteOffset + offset * src.BYTES_PER_ELEMENT; if (typeof length === "number") { return new src.constructor(src.buffer, offset, length); } else { return new src.constructor(src.buffer, offset); } } var uint8 = 0; var int32 = 1; function calloc(n, type) { switch (type) { case uint8: return new Uint8Array(n); case int32: return new Int32Array(n); } throw new Error("calloc failed."); } function realloc(src, newSize) { var ret = new src.constructor(newSize); ret.set(src); return ret; } function copy(dst, src, offset) { dst.set(src, offset||0); }
mohayonao/libogg.js
include/stdlib.js
JavaScript
mit
777
var _ = require('../../util') var handlers = { text: require('./text'), radio: require('./radio'), select: require('./select'), checkbox: require('./checkbox') } module.exports = { priority: 800, twoWay: true, handlers: handlers, /** * Possible elements: * <select> * <textarea> * <input type="*"> * - text * - checkbox * - radio * - number * - TODO: more types may be supplied as a plugin */ bind: function () { // friendly warning... this.checkFilters() if (this.hasRead && !this.hasWrite) { process.env.NODE_ENV !== 'production' && _.warn( 'It seems you are using a read-only filter with ' + 'v-model. You might want to use a two-way filter ' + 'to ensure correct behavior.' ) } var el = this.el var tag = el.tagName var handler if (tag === 'INPUT') { handler = handlers[el.type] || handlers.text } else if (tag === 'SELECT') { handler = handlers.select } else if (tag === 'TEXTAREA') { handler = handlers.text } else { process.env.NODE_ENV !== 'production' && _.warn( 'v-model does not support element type: ' + tag ) return } handler.bind.call(this) this.update = handler.update this.unbind = handler.unbind }, /** * Check read/write filter stats. */ checkFilters: function () { var filters = this.filters if (!filters) return var i = filters.length while (i--) { var filter = _.resolveAsset(this.vm.$options, 'filters', filters[i].name) if (typeof filter === 'function' || filter.read) { this.hasRead = true } if (filter.write) { this.hasWrite = true } } } }
goforward01/follow_vue
src/directives/model/index.js
JavaScript
mit
1,765
var classes = [ { "name": "Hal\\Report\\Html\\Reporter", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "generate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "renderPage", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getTrend", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 1, "nbMethodsPublic": 3, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 14, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Component\\Output\\Output", "Hal\\Metric\\Metrics", "Hal\\Metric\\Consolidated", "Hal\\Metric\\Consolidated" ], "lcom": 1, "length": 360, "vocabulary": 90, "volume": 2337.07, "difficulty": 12.54, "effort": 29298.84, "level": 0.08, "bugs": 0.78, "time": 1628, "intelligentContent": 186.42, "number_operators": 103, "number_operands": 257, "number_operators_unique": 8, "number_operands_unique": 82, "cloc": 30, "loc": 151, "lloc": 124, "mi": 60.71, "mIwoC": 28.86, "commentWeight": 31.85, "kanDefect": 1.36, "relativeStructuralComplexity": 81, "relativeDataComplexity": 0.68, "relativeSystemComplexity": 81.68, "totalStructuralComplexity": 324, "totalDataComplexity": 2.7, "totalSystemComplexity": 326.7, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 5, "instability": 0.83, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Report\\Violations\\Xml\\Reporter", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "generate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 7, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Component\\Output\\Output", "Hal\\Metric\\Metrics", "DOMDocument" ], "lcom": 1, "length": 96, "vocabulary": 40, "volume": 510.91, "difficulty": 5.71, "effort": 2919.46, "level": 0.18, "bugs": 0.17, "time": 162, "intelligentContent": 89.41, "number_operators": 16, "number_operands": 80, "number_operators_unique": 5, "number_operands_unique": 35, "cloc": 15, "loc": 61, "lloc": 47, "mi": 78.36, "mIwoC": 43.62, "commentWeight": 34.74, "kanDefect": 0.75, "relativeStructuralComplexity": 100, "relativeDataComplexity": 0.23, "relativeSystemComplexity": 100.23, "totalStructuralComplexity": 200, "totalDataComplexity": 0.45, "totalSystemComplexity": 200.45, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Report\\Cli\\Reporter", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "generate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 9, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Component\\Output\\Output", "Hal\\Metric\\Metrics", "Hal\\Metric\\Consolidated" ], "lcom": 1, "length": 168, "vocabulary": 68, "volume": 1022.69, "difficulty": 7.75, "effort": 7921.69, "level": 0.13, "bugs": 0.34, "time": 440, "intelligentContent": 132.03, "number_operators": 33, "number_operands": 135, "number_operators_unique": 7, "number_operands_unique": 61, "cloc": 14, "loc": 105, "lloc": 85, "mi": 62.43, "mIwoC": 35.63, "commentWeight": 26.8, "kanDefect": 1.03, "relativeStructuralComplexity": 36, "relativeDataComplexity": 0.36, "relativeSystemComplexity": 36.36, "totalStructuralComplexity": 72, "totalDataComplexity": 0.71, "totalSystemComplexity": 72.71, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\Consolidated", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getAvg", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getSum", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getClasses", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getFiles", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getProject", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 6, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 5, "nbMethodsSetters": 0, "ccn": 9, "externals": [ "Hal\\Metric\\Metrics" ], "lcom": 1, "length": 181, "vocabulary": 53, "volume": 1036.75, "difficulty": 10.5, "effort": 10885.91, "level": 0.1, "bugs": 0.35, "time": 605, "intelligentContent": 98.74, "number_operators": 43, "number_operands": 138, "number_operators_unique": 7, "number_operands_unique": 46, "cloc": 37, "loc": 123, "lloc": 86, "mi": 73.03, "mIwoC": 35.47, "commentWeight": 37.55, "kanDefect": 1.67, "relativeStructuralComplexity": 9, "relativeDataComplexity": 1.29, "relativeSystemComplexity": 10.29, "totalStructuralComplexity": 54, "totalDataComplexity": 7.75, "totalSystemComplexity": 61.75, "pageRank": 0.01, "afferentCoupling": 3, "efferentCoupling": 1, "instability": 0.25, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\InterfaceMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\ClassMetric" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 4, "lloc": 4, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\FunctionMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\Metric", "JsonSerializable" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 5, "lloc": 5, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0.01, "afferentCoupling": 4, "efferentCoupling": 2, "instability": 0.33, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\FileMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\Metric", "JsonSerializable" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 5, "lloc": 5, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\Metrics", "interface": false, "methods": [ { "name": "attach", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "get", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "has", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "all", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "jsonSerialize", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 1, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "JsonSerializable" ], "lcom": 1, "length": 21, "vocabulary": 5, "volume": 48.76, "difficulty": 5, "effort": 243.8, "level": 0.2, "bugs": 0.02, "time": 14, "intelligentContent": 9.75, "number_operators": 6, "number_operands": 15, "number_operators_unique": 2, "number_operands_unique": 3, "cloc": 25, "loc": 51, "lloc": 26, "mi": 101.39, "mIwoC": 57.18, "commentWeight": 44.21, "kanDefect": 0.15, "relativeStructuralComplexity": 9, "relativeDataComplexity": 1.4, "relativeSystemComplexity": 10.4, "totalStructuralComplexity": 45, "totalDataComplexity": 7, "totalSystemComplexity": 52, "pageRank": 0.02, "afferentCoupling": 18, "efferentCoupling": 1, "instability": 0.05, "numberOfUnitTests": 12, "violations": {} }, { "name": "Hal\\Metric\\ProjectMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\Metric", "JsonSerializable" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 5, "lloc": 5, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\Helper\\RoleOfMethodDetector", "interface": false, "methods": [ { "name": "detects", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [], "lcom": 1, "length": 52, "vocabulary": 21, "volume": 228.4, "difficulty": 8.75, "effort": 1998.5, "level": 0.11, "bugs": 0.08, "time": 111, "intelligentContent": 26.1, "number_operators": 17, "number_operands": 35, "number_operators_unique": 7, "number_operands_unique": 14, "cloc": 15, "loc": 44, "lloc": 29, "mi": 90.35, "mIwoC": 51.05, "commentWeight": 39.31, "kanDefect": 0.66, "relativeStructuralComplexity": 0, "relativeDataComplexity": 6, "relativeSystemComplexity": 6, "totalStructuralComplexity": 0, "totalDataComplexity": 6, "totalSystemComplexity": 6, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 0, "instability": 0, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Component\\MaintainabilityIndexVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 10, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Metric\\FunctionMetric", "LogicException", "LogicException", "LogicException", "LogicException", "LogicException" ], "lcom": 1, "length": 111, "vocabulary": 36, "volume": 573.86, "difficulty": 10.14, "effort": 5820.6, "level": 0.1, "bugs": 0.19, "time": 323, "intelligentContent": 56.58, "number_operators": 40, "number_operands": 71, "number_operators_unique": 8, "number_operands_unique": 28, "cloc": 31, "loc": 77, "lloc": 46, "mi": 84.67, "mIwoC": 43.07, "commentWeight": 41.61, "kanDefect": 0.78, "relativeStructuralComplexity": 16, "relativeDataComplexity": 0.2, "relativeSystemComplexity": 16.2, "totalStructuralComplexity": 32, "totalDataComplexity": 0.4, "totalSystemComplexity": 32.4, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 9, "instability": 0.9, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Coupling\\ExternalsVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 20, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node" ], "lcom": 1, "length": 102, "vocabulary": 25, "volume": 473.67, "difficulty": 14.97, "effort": 7091.94, "level": 0.07, "bugs": 0.16, "time": 394, "intelligentContent": 31.64, "number_operators": 25, "number_operands": 77, "number_operators_unique": 7, "number_operands_unique": 18, "cloc": 27, "loc": 102, "lloc": 75, "mi": 73.44, "mIwoC": 37.67, "commentWeight": 35.77, "kanDefect": 2.66, "relativeStructuralComplexity": 25, "relativeDataComplexity": 0.17, "relativeSystemComplexity": 25.17, "totalStructuralComplexity": 50, "totalDataComplexity": 0.33, "totalSystemComplexity": 50.33, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 3, "instability": 0.75, "numberOfUnitTests": 2, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Text\\HalsteadVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Metric\\FunctionMetric" ], "lcom": 1, "length": 218, "vocabulary": 50, "volume": 1230.36, "difficulty": 11.97, "effort": 14721.41, "level": 0.08, "bugs": 0.41, "time": 818, "intelligentContent": 102.83, "number_operators": 71, "number_operands": 147, "number_operators_unique": 7, "number_operands_unique": 43, "cloc": 29, "loc": 88, "lloc": 59, "mi": 78.03, "mIwoC": 39.2, "commentWeight": 38.83, "kanDefect": 0.57, "relativeStructuralComplexity": 16, "relativeDataComplexity": 0.2, "relativeSystemComplexity": 16.2, "totalStructuralComplexity": 32, "totalDataComplexity": 0.4, "totalSystemComplexity": 32.4, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Text\\LengthVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 5, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Metric\\FunctionMetric", "PhpParser\\PrettyPrinter\\Standard" ], "lcom": 1, "length": 80, "vocabulary": 25, "volume": 371.51, "difficulty": 7.75, "effort": 2879.19, "level": 0.13, "bugs": 0.12, "time": 160, "intelligentContent": 47.94, "number_operators": 18, "number_operands": 62, "number_operators_unique": 5, "number_operands_unique": 20, "cloc": 20, "loc": 55, "lloc": 36, "mi": 87.59, "mIwoC": 47.38, "commentWeight": 40.21, "kanDefect": 0.59, "relativeStructuralComplexity": 25, "relativeDataComplexity": 0.17, "relativeSystemComplexity": 25.17, "totalStructuralComplexity": 50, "totalDataComplexity": 0.33, "totalSystemComplexity": 50.33, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 5, "instability": 0.83, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Complexity\\KanDefectVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 2, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node" ], "lcom": 1, "length": 50, "vocabulary": 21, "volume": 219.62, "difficulty": 7, "effort": 1537.31, "level": 0.14, "bugs": 0.07, "time": 85, "intelligentContent": 31.37, "number_operators": 15, "number_operands": 35, "number_operators_unique": 6, "number_operands_unique": 15, "cloc": 15, "loc": 48, "lloc": 33, "mi": 88.3, "mIwoC": 50.21, "commentWeight": 38.09, "kanDefect": 0.44, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.25, "relativeSystemComplexity": 9.25, "totalStructuralComplexity": 18, "totalDataComplexity": 0.5, "totalSystemComplexity": 18.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 3, "instability": 0.75, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Complexity\\CyclomaticComplexityVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node" ], "lcom": 1, "length": 68, "vocabulary": 19, "volume": 288.86, "difficulty": 18.91, "effort": 5462.06, "level": 0.05, "bugs": 0.1, "time": 303, "intelligentContent": 15.28, "number_operators": 16, "number_operands": 52, "number_operators_unique": 8, "number_operands_unique": 11, "cloc": 27, "loc": 80, "lloc": 53, "mi": 83.79, "mIwoC": 44.62, "commentWeight": 39.17, "kanDefect": 1.04, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.5, "relativeSystemComplexity": 9.5, "totalStructuralComplexity": 18, "totalDataComplexity": 1, "totalSystemComplexity": 19, "pageRank": 0, "afferentCoupling": 2, "efferentCoupling": 3, "instability": 0.6, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\ClassEnumVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 8, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Metric\\InterfaceMetric", "Hal\\Metric\\ClassMetric", "Hal\\Metric\\Helper\\RoleOfMethodDetector", "Hal\\Metric\\FunctionMetric" ], "lcom": 1, "length": 113, "vocabulary": 35, "volume": 579.61, "difficulty": 12.59, "effort": 7298.78, "level": 0.08, "bugs": 0.19, "time": 405, "intelligentContent": 46.03, "number_operators": 28, "number_operands": 85, "number_operators_unique": 8, "number_operands_unique": 27, "cloc": 8, "loc": 73, "lloc": 65, "mi": 64.56, "mIwoC": 40.03, "commentWeight": 24.53, "kanDefect": 1.09, "relativeStructuralComplexity": 49, "relativeDataComplexity": 0.13, "relativeSystemComplexity": 49.13, "totalStructuralComplexity": 98, "totalDataComplexity": 0.25, "totalSystemComplexity": 98.25, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 7, "instability": 0.88, "numberOfUnitTests": 11, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Structural\\SystemComplexityVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node" ], "lcom": 1, "length": 98, "vocabulary": 27, "volume": 465.98, "difficulty": 8.3, "effort": 3865.51, "level": 0.12, "bugs": 0.16, "time": 215, "intelligentContent": 56.17, "number_operators": 25, "number_operands": 73, "number_operators_unique": 5, "number_operands_unique": 22, "cloc": 23, "loc": 63, "lloc": 40, "mi": 86.09, "mIwoC": 45.83, "commentWeight": 40.26, "kanDefect": 0.74, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.25, "relativeSystemComplexity": 9.25, "totalStructuralComplexity": 18, "totalDataComplexity": 0.5, "totalSystemComplexity": 18.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 3, "instability": 0.75, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\Class_\\Structural\\LcomVisitor", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "traverse", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 3, "nbMethods": 3, "nbMethodsPrivate": 1, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 8, "externals": [ "PhpParser\\NodeVisitorAbstract", "Hal\\Metric\\Metrics", "PhpParser\\Node", "Hal\\Component\\Tree\\Graph", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node" ], "lcom": 1, "length": 111, "vocabulary": 23, "volume": 502.12, "difficulty": 20.53, "effort": 10310.1, "level": 0.05, "bugs": 0.17, "time": 573, "intelligentContent": 24.45, "number_operators": 34, "number_operands": 77, "number_operators_unique": 8, "number_operands_unique": 15, "cloc": 27, "loc": 89, "lloc": 62, "mi": 78.59, "mIwoC": 40.91, "commentWeight": 37.67, "kanDefect": 1.47, "relativeStructuralComplexity": 81, "relativeDataComplexity": 0.5, "relativeSystemComplexity": 81.5, "totalStructuralComplexity": 243, "totalDataComplexity": 1.5, "totalSystemComplexity": 244.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 8, "instability": 0.89, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Metric\\System\\Changes\\GitChanges", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "calculate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "doesThisFileShouldBeCounted", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 3, "nbMethods": 3, "nbMethodsPrivate": 1, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 14, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Metric\\Metrics", "Hal\\Application\\Config\\ConfigException", "DateTime", "Hal\\Metric\\ProjectMetric", "Hal\\Metric\\FileMetric" ], "lcom": 1, "length": 256, "vocabulary": 49, "volume": 1437.37, "difficulty": 16.17, "effort": 23237.41, "level": 0.06, "bugs": 0.48, "time": 1291, "intelligentContent": 88.91, "number_operators": 62, "number_operands": 194, "number_operators_unique": 7, "number_operands_unique": 42, "cloc": 36, "loc": 142, "lloc": 106, "mi": 66.99, "mIwoC": 31.83, "commentWeight": 35.17, "kanDefect": 1.82, "relativeStructuralComplexity": 49, "relativeDataComplexity": 0.54, "relativeSystemComplexity": 49.54, "totalStructuralComplexity": 147, "totalDataComplexity": 1.63, "totalSystemComplexity": 148.63, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 6, "instability": 0.86, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\System\\Coupling\\PageRank", "interface": false, "methods": [ { "name": "calculate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "calculatePageRank", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 1, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 12, "externals": [ "Hal\\Metric\\Metrics" ], "lcom": 1, "length": 136, "vocabulary": 40, "volume": 723.78, "difficulty": 24.31, "effort": 17598.63, "level": 0.04, "bugs": 0.24, "time": 978, "intelligentContent": 29.77, "number_operators": 35, "number_operands": 101, "number_operators_unique": 13, "number_operands_unique": 27, "cloc": 20, "loc": 75, "lloc": 55, "mi": 76.27, "mIwoC": 40.4, "commentWeight": 35.87, "kanDefect": 2.13, "relativeStructuralComplexity": 16, "relativeDataComplexity": 0.5, "relativeSystemComplexity": 16.5, "totalStructuralComplexity": 32, "totalDataComplexity": 1, "totalSystemComplexity": 33, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\System\\Coupling\\Coupling", "interface": false, "methods": [ { "name": "calculate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 14, "externals": [ "Hal\\Metric\\Metrics", "Hal\\Component\\Tree\\Graph", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node" ], "lcom": 1, "length": 84, "vocabulary": 23, "volume": 379.98, "difficulty": 11.12, "effort": 4224.47, "level": 0.09, "bugs": 0.13, "time": 235, "intelligentContent": 34.18, "number_operators": 21, "number_operands": 63, "number_operators_unique": 6, "number_operands_unique": 17, "cloc": 12, "loc": 56, "lloc": 44, "mi": 77.06, "mIwoC": 44.2, "commentWeight": 32.86, "kanDefect": 1.56, "relativeStructuralComplexity": 100, "relativeDataComplexity": 0.09, "relativeSystemComplexity": 100.09, "totalStructuralComplexity": 100, "totalDataComplexity": 0.09, "totalSystemComplexity": 100.09, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Metric\\ClassMetric", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Metric\\Metric", "JsonSerializable" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 5, "lloc": 5, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0.01, "afferentCoupling": 2, "efferentCoupling": 2, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Ast\\NodeTraverser", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "traverseArray", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 1, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 6, "externals": [ "PhpParser\\NodeTraverser", "parent" ], "lcom": 1, "length": 93, "vocabulary": 19, "volume": 395.06, "difficulty": 17.79, "effort": 7028.73, "level": 0.06, "bugs": 0.13, "time": 390, "intelligentContent": 22.2, "number_operators": 32, "number_operands": 61, "number_operators_unique": 7, "number_operands_unique": 12, "cloc": 5, "loc": 65, "lloc": 60, "mi": 63.05, "mIwoC": 42.22, "commentWeight": 20.83, "kanDefect": 1.63, "relativeStructuralComplexity": 25, "relativeDataComplexity": 0.75, "relativeSystemComplexity": 25.75, "totalStructuralComplexity": 50, "totalDataComplexity": 1.5, "totalSystemComplexity": 51.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Output\\CliOutput", "interface": false, "methods": [ { "name": "writeln", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "write", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "err", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "clearln", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "setQuietMode", "role": "setter", "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 1, "ccn": 2, "externals": [ "Hal\\Component\\Output\\Output" ], "lcom": 2, "length": 30, "vocabulary": 11, "volume": 103.78, "difficulty": 6.29, "effort": 652.35, "level": 0.16, "bugs": 0.03, "time": 36, "intelligentContent": 16.51, "number_operators": 8, "number_operands": 22, "number_operators_unique": 4, "number_operands_unique": 7, "cloc": 25, "loc": 54, "lloc": 31, "mi": 96.55, "mIwoC": 53.08, "commentWeight": 43.47, "kanDefect": 0.15, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.93, "relativeSystemComplexity": 5.93, "totalStructuralComplexity": 20, "totalDataComplexity": 9.67, "totalSystemComplexity": 29.67, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Output\\ProgressBar", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "start", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "advance", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "clear", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "hasAnsi", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 5, "nbMethodsPrivate": 1, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "Hal\\Component\\Output\\Output" ], "lcom": 1, "length": 66, "vocabulary": 29, "volume": 320.63, "difficulty": 12.83, "effort": 4114.71, "level": 0.08, "bugs": 0.11, "time": 229, "intelligentContent": 24.98, "number_operators": 24, "number_operands": 42, "number_operators_unique": 11, "number_operands_unique": 18, "cloc": 40, "loc": 83, "lloc": 43, "mi": 90.27, "mIwoC": 46.28, "commentWeight": 43.99, "kanDefect": 0.36, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.6, "relativeSystemComplexity": 9.6, "totalStructuralComplexity": 45, "totalDataComplexity": 3, "totalSystemComplexity": 48, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Issue\\Issuer", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "onError", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "enable", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "disable", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "terminate", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "log", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "set", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "clear", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 8, "nbMethods": 8, "nbMethodsPrivate": 2, "nbMethodsPublic": 6, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 7, "externals": [ "Hal\\Component\\Output\\Output", "PhpParser\\PrettyPrinter\\Standard" ], "lcom": 3, "length": 123, "vocabulary": 49, "volume": 690.61, "difficulty": 6.77, "effort": 4673.66, "level": 0.15, "bugs": 0.23, "time": 260, "intelligentContent": 102.05, "number_operators": 26, "number_operands": 97, "number_operators_unique": 6, "number_operands_unique": 43, "cloc": 44, "loc": 152, "lloc": 95, "mi": 73.05, "mIwoC": 36.04, "commentWeight": 37.01, "kanDefect": 0.89, "relativeStructuralComplexity": 16, "relativeDataComplexity": 1.48, "relativeSystemComplexity": 17.48, "totalStructuralComplexity": 128, "totalDataComplexity": 11.8, "totalSystemComplexity": 139.8, "pageRank": 0, "afferentCoupling": 2, "efferentCoupling": 2, "instability": 0.5, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Tree\\Edge", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getFrom", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getTo", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "asString", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 2, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node" ], "lcom": 1, "length": 16, "vocabulary": 6, "volume": 41.36, "difficulty": 2.75, "effort": 113.74, "level": 0.36, "bugs": 0.01, "time": 6, "intelligentContent": 15.04, "number_operators": 5, "number_operands": 11, "number_operators_unique": 2, "number_operands_unique": 4, "cloc": 23, "loc": 47, "lloc": 24, "mi": 102.62, "mIwoC": 58.44, "commentWeight": 44.19, "kanDefect": 0.15, "relativeStructuralComplexity": 1, "relativeDataComplexity": 1.75, "relativeSystemComplexity": 2.75, "totalStructuralComplexity": 4, "totalDataComplexity": 7, "totalSystemComplexity": 11, "pageRank": 0.37, "afferentCoupling": 2, "efferentCoupling": 2, "instability": 0.5, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Component\\Tree\\Node", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getKey", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getAdjacents", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getEdges", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "addEdge", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getData", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "setData", "role": "setter", "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 7, "nbMethods": 3, "nbMethodsPrivate": 0, "nbMethodsPublic": 3, "nbMethodsGetter": 3, "nbMethodsSetters": 1, "ccn": 4, "externals": [ "Hal\\Component\\Tree\\Edge" ], "lcom": 1, "length": 47, "vocabulary": 9, "volume": 148.99, "difficulty": 12.4, "effort": 1847.43, "level": 0.08, "bugs": 0.05, "time": 103, "intelligentContent": 12.02, "number_operators": 16, "number_operands": 31, "number_operators_unique": 4, "number_operands_unique": 5, "cloc": 40, "loc": 89, "lloc": 49, "mi": 90.46, "mIwoC": 47.38, "commentWeight": 43.08, "kanDefect": 0.52, "relativeStructuralComplexity": 9, "relativeDataComplexity": 1.64, "relativeSystemComplexity": 10.64, "totalStructuralComplexity": 63, "totalDataComplexity": 11.5, "totalSystemComplexity": 74.5, "pageRank": 0.35, "afferentCoupling": 13, "efferentCoupling": 1, "instability": 0.07, "numberOfUnitTests": 42, "violations": {} }, { "name": "Hal\\Component\\Tree\\Graph", "interface": false, "methods": [ { "name": "insert", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "addEdge", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "asString", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getEdges", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "get", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "has", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "count", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "all", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 8, "nbMethods": 6, "nbMethodsPrivate": 0, "nbMethodsPublic": 6, "nbMethodsGetter": 2, "nbMethodsSetters": 0, "ccn": 6, "externals": [ "Countable", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\GraphException", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\Node", "Hal\\Component\\Tree\\GraphException", "Hal\\Component\\Tree\\GraphException", "Hal\\Component\\Tree\\Edge" ], "lcom": 1, "length": 67, "vocabulary": 16, "volume": 268, "difficulty": 8.5, "effort": 2278, "level": 0.12, "bugs": 0.09, "time": 127, "intelligentContent": 31.53, "number_operators": 16, "number_operands": 51, "number_operators_unique": 4, "number_operands_unique": 12, "cloc": 35, "loc": 94, "lloc": 59, "mi": 84.1, "mIwoC": 43.56, "commentWeight": 40.53, "kanDefect": 0.82, "relativeStructuralComplexity": 36, "relativeDataComplexity": 1.23, "relativeSystemComplexity": 37.23, "totalStructuralComplexity": 288, "totalDataComplexity": 9.86, "totalSystemComplexity": 297.86, "pageRank": 0.01, "afferentCoupling": 3, "efferentCoupling": 8, "instability": 0.73, "numberOfUnitTests": 10, "violations": {} }, { "name": "Hal\\Component\\Tree\\Operator\\CycleDetector", "interface": false, "methods": [ { "name": "isCyclic", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "detectCycle", "role": null, "public": false, "private": true, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 1, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 9, "externals": [ "Hal\\Component\\Tree\\Graph", "Hal\\Component\\Tree\\Node" ], "lcom": 1, "length": 64, "vocabulary": 12, "volume": 229.44, "difficulty": 14.29, "effort": 3277.68, "level": 0.07, "bugs": 0.08, "time": 182, "intelligentContent": 16.06, "number_operators": 24, "number_operands": 40, "number_operators_unique": 5, "number_operands_unique": 7, "cloc": 23, "loc": 64, "lloc": 41, "mi": 87.12, "mIwoC": 47.08, "commentWeight": 40.04, "kanDefect": 1.12, "relativeStructuralComplexity": 36, "relativeDataComplexity": 0.79, "relativeSystemComplexity": 36.79, "totalStructuralComplexity": 72, "totalDataComplexity": 1.57, "totalSystemComplexity": 73.57, "pageRank": 0, "afferentCoupling": 0, "efferentCoupling": 2, "instability": 1, "numberOfUnitTests": 4, "violations": {} }, { "name": "Hal\\Component\\Tree\\GraphException", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "LogicException" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 4, "lloc": 4, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0.01, "afferentCoupling": 3, "efferentCoupling": 1, "instability": 0.25, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Component\\Tree\\HashMap", "interface": false, "methods": [ { "name": "attach", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "get", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "has", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "count", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getIterator", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 5, "nbMethodsPrivate": 0, "nbMethodsPublic": 5, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Countable", "IteratorAggregate", "Hal\\Component\\Tree\\Node", "ArrayIterator" ], "lcom": 1, "length": 21, "vocabulary": 5, "volume": 48.76, "difficulty": 5, "effort": 243.8, "level": 0.2, "bugs": 0.02, "time": 14, "intelligentContent": 9.75, "number_operators": 6, "number_operands": 15, "number_operators_unique": 2, "number_operands_unique": 3, "cloc": 21, "loc": 47, "lloc": 26, "mi": 100.19, "mIwoC": 57.18, "commentWeight": 43.01, "kanDefect": 0.15, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.87, "relativeSystemComplexity": 5.87, "totalStructuralComplexity": 20, "totalDataComplexity": 9.33, "totalSystemComplexity": 29.33, "pageRank": 0, "afferentCoupling": 0, "efferentCoupling": 4, "instability": 1, "numberOfUnitTests": 3, "violations": {} }, { "name": "Hal\\Component\\File\\Finder", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "fetch", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 4, "externals": [ "RecursiveDirectoryIterator", "RecursiveIteratorIterator", "RegexIterator" ], "lcom": 1, "length": 64, "vocabulary": 25, "volume": 297.21, "difficulty": 4.38, "effort": 1302.05, "level": 0.23, "bugs": 0.1, "time": 72, "intelligentContent": 67.84, "number_operators": 18, "number_operands": 46, "number_operators_unique": 4, "number_operands_unique": 21, "cloc": 35, "loc": 68, "lloc": 33, "mi": 93.84, "mIwoC": 49.02, "commentWeight": 44.82, "kanDefect": 0.68, "relativeStructuralComplexity": 0, "relativeDataComplexity": 3, "relativeSystemComplexity": 3, "totalStructuralComplexity": 0, "totalDataComplexity": 6, "totalSystemComplexity": 6, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 3, "instability": 0.75, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\Violations", "interface": false, "methods": [ { "name": "getIterator", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "add", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "count", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "__toString", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 2, "externals": [ "IteratorAggregate", "Countable", "ArrayIterator", "Hal\\Violation\\Violation" ], "lcom": 1, "length": 20, "vocabulary": 9, "volume": 63.4, "difficulty": 5.2, "effort": 329.67, "level": 0.19, "bugs": 0.02, "time": 18, "intelligentContent": 12.19, "number_operators": 7, "number_operands": 13, "number_operators_unique": 4, "number_operands_unique": 5, "cloc": 19, "loc": 44, "lloc": 25, "mi": 99.17, "mIwoC": 56.62, "commentWeight": 42.55, "kanDefect": 0.38, "relativeStructuralComplexity": 1, "relativeDataComplexity": 1.63, "relativeSystemComplexity": 2.63, "totalStructuralComplexity": 4, "totalDataComplexity": 6.5, "totalSystemComplexity": 10.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 4, "instability": 0.8, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Violation\\Class_\\Blob", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 6, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 47, "vocabulary": 19, "volume": 199.65, "difficulty": 4.27, "effort": 851.85, "level": 0.23, "bugs": 0.07, "time": 47, "intelligentContent": 46.79, "number_operators": 15, "number_operands": 32, "number_operators_unique": 4, "number_operands_unique": 15, "cloc": 12, "loc": 56, "lloc": 42, "mi": 80.54, "mIwoC": 47.68, "commentWeight": 32.86, "kanDefect": 0.5, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.42, "relativeSystemComplexity": 5.42, "totalStructuralComplexity": 16, "totalDataComplexity": 5.67, "totalSystemComplexity": 21.67, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Violation\\Class_\\TooComplexCode", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 28, "vocabulary": 15, "volume": 109.39, "difficulty": 3.45, "effort": 377.9, "level": 0.29, "bugs": 0.04, "time": 21, "intelligentContent": 31.67, "number_operators": 9, "number_operands": 19, "number_operators_unique": 4, "number_operands_unique": 11, "cloc": 12, "loc": 46, "lloc": 32, "mi": 88.05, "mIwoC": 52.49, "commentWeight": 35.56, "kanDefect": 0.29, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.75, "relativeSystemComplexity": 5.75, "totalStructuralComplexity": 16, "totalDataComplexity": 7, "totalSystemComplexity": 23, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\Class_\\TooDependent", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 28, "vocabulary": 14, "volume": 106.61, "difficulty": 3.8, "effort": 405.1, "level": 0.26, "bugs": 0.04, "time": 23, "intelligentContent": 28.05, "number_operators": 9, "number_operands": 19, "number_operators_unique": 4, "number_operands_unique": 10, "cloc": 12, "loc": 45, "lloc": 31, "mi": 88.73, "mIwoC": 52.87, "commentWeight": 35.87, "kanDefect": 0.29, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.75, "relativeSystemComplexity": 5.75, "totalStructuralComplexity": 16, "totalDataComplexity": 7, "totalSystemComplexity": 23, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\Class_\\TooLong", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 27, "vocabulary": 15, "volume": 105.49, "difficulty": 3.45, "effort": 364.41, "level": 0.29, "bugs": 0.04, "time": 20, "intelligentContent": 30.54, "number_operators": 8, "number_operands": 19, "number_operators_unique": 4, "number_operands_unique": 11, "cloc": 12, "loc": 45, "lloc": 31, "mi": 88.77, "mIwoC": 52.9, "commentWeight": 35.87, "kanDefect": 0.29, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.42, "relativeSystemComplexity": 5.42, "totalStructuralComplexity": 16, "totalDataComplexity": 5.67, "totalSystemComplexity": 21.67, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\Class_\\ProbablyBugged", "interface": false, "methods": [ { "name": "getName", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getLevel", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "getDescription", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 4, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Violation\\Violation", "Hal\\Metric\\Metric" ], "lcom": 3, "length": 31, "vocabulary": 17, "volume": 126.71, "difficulty": 3.23, "effort": 409.38, "level": 0.31, "bugs": 0.04, "time": 23, "intelligentContent": 39.22, "number_operators": 10, "number_operands": 21, "number_operators_unique": 4, "number_operands_unique": 13, "cloc": 13, "loc": 48, "lloc": 34, "mi": 87.55, "mIwoC": 51.46, "commentWeight": 36.08, "kanDefect": 0.29, "relativeStructuralComplexity": 4, "relativeDataComplexity": 1.75, "relativeSystemComplexity": 5.75, "totalStructuralComplexity": 16, "totalDataComplexity": 7, "totalSystemComplexity": 23, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 2, "instability": 0.67, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Violation\\ViolationParser", "interface": false, "methods": [ { "name": "apply", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 3, "externals": [ "Hal\\Metric\\Metrics", "Hal\\Violation\\Class_\\Blob", "Hal\\Violation\\Class_\\TooComplexCode", "Hal\\Violation\\Class_\\ProbablyBugged", "Hal\\Violation\\Class_\\TooLong", "Hal\\Violation\\Class_\\TooDependent", "Hal\\Violation\\Violations" ], "lcom": 1, "length": 13, "vocabulary": 7, "volume": 36.5, "difficulty": 2.2, "effort": 80.29, "level": 0.45, "bugs": 0.01, "time": 4, "intelligentContent": 16.59, "number_operators": 2, "number_operands": 11, "number_operators_unique": 2, "number_operands_unique": 5, "cloc": 4, "loc": 19, "lloc": 15, "mi": 95.62, "mIwoC": 63, "commentWeight": 32.62, "kanDefect": 0.61, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.5, "relativeSystemComplexity": 9.5, "totalStructuralComplexity": 9, "totalDataComplexity": 0.5, "totalSystemComplexity": 9.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 7, "instability": 0.88, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Analyze", "interface": false, "methods": [ { "name": "__construct", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "run", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 2, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Component\\Output\\Output", "Hal\\Component\\Issue\\Issuer", "Hal\\Metric\\Metrics", "PhpParser\\ParserFactory", "Hal\\Component\\Ast\\NodeTraverser", "PhpParser\\NodeVisitor\\NameResolver", "Hal\\Metric\\Class_\\ClassEnumVisitor", "Hal\\Metric\\Class_\\Complexity\\CyclomaticComplexityVisitor", "Hal\\Metric\\Class_\\Coupling\\ExternalsVisitor", "Hal\\Metric\\Class_\\Structural\\LcomVisitor", "Hal\\Metric\\Class_\\Text\\HalsteadVisitor", "Hal\\Metric\\Class_\\Text\\LengthVisitor", "Hal\\Metric\\Class_\\Complexity\\CyclomaticComplexityVisitor", "Hal\\Metric\\Class_\\Component\\MaintainabilityIndexVisitor", "Hal\\Metric\\Class_\\Complexity\\KanDefectVisitor", "Hal\\Metric\\Class_\\Structural\\SystemComplexityVisitor", "Hal\\Component\\Output\\ProgressBar", "Hal\\Metric\\System\\Coupling\\PageRank", "Hal\\Metric\\System\\Coupling\\Coupling", "Hal\\Metric\\System\\Changes\\GitChanges", "Hal\\Metric\\System\\UnitTesting\\UnitTesting" ], "lcom": 1, "length": 88, "vocabulary": 21, "volume": 386.52, "difficulty": 6.25, "effort": 2415.77, "level": 0.16, "bugs": 0.13, "time": 134, "intelligentContent": 61.84, "number_operators": 13, "number_operands": 75, "number_operators_unique": 3, "number_operands_unique": 18, "cloc": 27, "loc": 86, "lloc": 59, "mi": 81.14, "mIwoC": 42.99, "commentWeight": 38.15, "kanDefect": 0.38, "relativeStructuralComplexity": 100, "relativeDataComplexity": 0.36, "relativeSystemComplexity": 100.36, "totalStructuralComplexity": 200, "totalDataComplexity": 0.73, "totalSystemComplexity": 200.73, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 22, "instability": 0.96, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Application", "interface": false, "methods": [ { "name": "run", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 2, "externals": [ "Hal\\Component\\Output\\CliOutput", "Hal\\Component\\Issue\\Issuer", "Hal\\Application\\Config\\Parser", "Hal\\Application\\Config\\Validator", "Hal\\Application\\Config\\Validator", "Hal\\Application\\Config\\Validator", "Hal\\Component\\File\\Finder", "Hal\\Application\\Analyze", "Hal\\Violation\\ViolationParser", "Hal\\Report\\Cli\\Reporter", "Hal\\Report\\Html\\Reporter", "Hal\\Report\\Violations\\Xml\\Reporter" ], "lcom": 1, "length": 71, "vocabulary": 23, "volume": 321.17, "difficulty": 4.5, "effort": 1445.28, "level": 0.22, "bugs": 0.11, "time": 80, "intelligentContent": 71.37, "number_operators": 11, "number_operands": 60, "number_operators_unique": 3, "number_operands_unique": 20, "cloc": 13, "loc": 55, "lloc": 43, "mi": 80.74, "mIwoC": 46.55, "commentWeight": 34.2, "kanDefect": 0.36, "relativeStructuralComplexity": 144, "relativeDataComplexity": 0.08, "relativeSystemComplexity": 144.08, "totalStructuralComplexity": 144, "totalDataComplexity": 0.08, "totalSystemComplexity": 144.08, "pageRank": 0, "afferentCoupling": 0, "efferentCoupling": 12, "instability": 1, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Config\\Validator", "interface": false, "methods": [ { "name": "validate", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "help", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 2, "nbMethodsPrivate": 0, "nbMethodsPublic": 2, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 8, "externals": [ "Hal\\Application\\Config\\Config", "Hal\\Application\\Config\\ConfigException", "Hal\\Application\\Config\\ConfigException", "Hal\\Application\\Config\\ConfigException" ], "lcom": 2, "length": 57, "vocabulary": 23, "volume": 257.84, "difficulty": 8.12, "effort": 2093.08, "level": 0.12, "bugs": 0.09, "time": 116, "intelligentContent": 31.76, "number_operators": 11, "number_operands": 46, "number_operators_unique": 6, "number_operands_unique": 17, "cloc": 15, "loc": 81, "lloc": 54, "mi": 75.17, "mIwoC": 44.25, "commentWeight": 30.92, "kanDefect": 0.96, "relativeStructuralComplexity": 9, "relativeDataComplexity": 0.38, "relativeSystemComplexity": 9.38, "totalStructuralComplexity": 18, "totalDataComplexity": 0.75, "totalSystemComplexity": 18.75, "pageRank": 0, "afferentCoupling": 3, "efferentCoupling": 4, "instability": 0.57, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Config\\ConfigException", "interface": false, "methods": [], "nbMethodsIncludingGettersSetters": 0, "nbMethods": 0, "nbMethodsPrivate": 0, "nbMethodsPublic": 0, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 1, "externals": [ "Exception" ], "lcom": 0, "length": 0, "vocabulary": 0, "volume": 0, "difficulty": 0, "effort": 0, "level": 0, "bugs": 0, "time": 0, "intelligentContent": 0, "number_operators": 0, "number_operands": 0, "number_operators_unique": 0, "number_operands_unique": 0, "cloc": 0, "loc": 4, "lloc": 4, "mi": 171, "mIwoC": 171, "commentWeight": 0, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 0, "relativeSystemComplexity": 0, "totalStructuralComplexity": 0, "totalDataComplexity": 0, "totalSystemComplexity": 0, "pageRank": 0.01, "afferentCoupling": 4, "efferentCoupling": 1, "instability": 0.2, "numberOfUnitTests": 0, "violations": {} }, { "name": "Hal\\Application\\Config\\Parser", "interface": false, "methods": [ { "name": "parse", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 1, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 0, "ccn": 8, "externals": [ "Hal\\Application\\Config\\Config" ], "lcom": 1, "length": 67, "vocabulary": 23, "volume": 303.08, "difficulty": 9.18, "effort": 2781.19, "level": 0.11, "bugs": 0.1, "time": 155, "intelligentContent": 33.03, "number_operators": 15, "number_operands": 52, "number_operators_unique": 6, "number_operands_unique": 17, "cloc": 3, "loc": 36, "lloc": 33, "mi": 70.05, "mIwoC": 48.42, "commentWeight": 21.62, "kanDefect": 0.96, "relativeStructuralComplexity": 1, "relativeDataComplexity": 1.5, "relativeSystemComplexity": 2.5, "totalStructuralComplexity": 1, "totalDataComplexity": 1.5, "totalSystemComplexity": 2.5, "pageRank": 0, "afferentCoupling": 1, "efferentCoupling": 1, "instability": 0.5, "numberOfUnitTests": 1, "violations": {} }, { "name": "Hal\\Application\\Config\\Config", "interface": false, "methods": [ { "name": "set", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "has", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "get", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "all", "role": "getter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "fromArray", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 5, "nbMethods": 4, "nbMethodsPrivate": 0, "nbMethodsPublic": 4, "nbMethodsGetter": 1, "nbMethodsSetters": 0, "ccn": 2, "externals": [], "lcom": 1, "length": 29, "vocabulary": 6, "volume": 74.96, "difficulty": 5.75, "effort": 431.04, "level": 0.17, "bugs": 0.02, "time": 24, "intelligentContent": 13.04, "number_operators": 6, "number_operands": 23, "number_operators_unique": 2, "number_operands_unique": 4, "cloc": 23, "loc": 52, "lloc": 29, "mi": 97.58, "mIwoC": 54.7, "commentWeight": 42.87, "kanDefect": 0.38, "relativeStructuralComplexity": 4, "relativeDataComplexity": 2, "relativeSystemComplexity": 6, "totalStructuralComplexity": 20, "totalDataComplexity": 10, "totalSystemComplexity": 30, "pageRank": 0.01, "afferentCoupling": 7, "efferentCoupling": 0, "instability": 0, "numberOfUnitTests": 0, "violations": {} }, { "name": "MyVisitor", "interface": false, "methods": [ { "name": "__construct", "role": "setter", "_type": "Hal\\Metric\\FunctionMetric" }, { "name": "leaveNode", "role": null, "public": true, "private": false, "_type": "Hal\\Metric\\FunctionMetric" } ], "nbMethodsIncludingGettersSetters": 2, "nbMethods": 1, "nbMethodsPrivate": 0, "nbMethodsPublic": 1, "nbMethodsGetter": 0, "nbMethodsSetters": 1, "ccn": 1, "externals": [ "PhpParser\\NodeVisitorAbstract", "PhpParser\\Node" ], "lcom": 1, "length": 7, "vocabulary": 4, "volume": 14, "difficulty": 1, "effort": 14, "level": 1, "bugs": 0, "time": 1, "intelligentContent": 14, "number_operators": 1, "number_operands": 6, "number_operators_unique": 1, "number_operands_unique": 3, "cloc": 13, "loc": 26, "lloc": 13, "mi": 112, "mIwoC": 67.54, "commentWeight": 44.46, "kanDefect": 0.15, "relativeStructuralComplexity": 0, "relativeDataComplexity": 1, "relativeSystemComplexity": 1, "totalStructuralComplexity": 0, "totalDataComplexity": 2, "totalSystemComplexity": 2, "pageRank": 0, "afferentCoupling": 0, "efferentCoupling": 2, "instability": 1, "numberOfUnitTests": 0, "violations": {} } ]
phpmetrics/website
report/v2/js/classes.js
JavaScript
mit
98,017
(function() { 'use strict'; var jhiAlert = { template: '<div class="alerts" ng-cloak="">' + '<div ng-repeat="alert in $ctrl.alerts" ng-class="[alert.position, {\'toast\': alert.toast}]">' + '<uib-alert ng-cloak="" type="{{alert.type}}" close="alert.close($ctrl.alerts)"><pre ng-bind-html="alert.msg"></pre></uib-alert>' + '</div>' + '</div>', controller: jhiAlertController }; angular .module('noctemApp') .component('jhiAlert', jhiAlert); jhiAlertController.$inject = ['$scope', 'AlertService']; function jhiAlertController($scope, AlertService) { var vm = this; vm.alerts = AlertService.get(); $scope.$on('$destroy', function () { vm.alerts = []; }); } })();
gcorreageek/noctem
src/main/webapp/app/components/alert/alert.directive.js
JavaScript
mit
864
const test = require('tape') const Queue = require('./Queue') test('peek on empty queue', assert => { const queue = new Queue() assert.strictEqual(queue.peek(), null) assert.end() }) test('enqueue items to the queue', assert => { const queue = new Queue() queue.enqueue('foo') queue.enqueue('bar') assert.equal(queue.length, 2) assert.equal(queue.peek(), 'foo') assert.end() }) test('dequeue items from the queue', assert => { const queue = new Queue() queue.enqueue('A') queue.enqueue('B') queue.enqueue('C') assert.equal(queue.dequeue(), 'A') assert.equal(queue.dequeue(), 'B') assert.equal(queue.dequeue(), 'C') assert.end() }) test('create queue from array', assert => { const queue = new Queue(['A', 'B', 'C']) assert.equal(queue.peek(), 'A') assert.equal(queue.dequeue(), 'A') assert.equal(queue.dequeue(), 'B') assert.equal(queue.dequeue(), 'C') assert.end() }) test('throws error when trying to dequeue empty queue', assert => { const queue = new Queue() assert.throws(() => queue.dequeue(), RangeError) assert.end() })
ayastreb/cs101
src/DataStructures/Queue.test.js
JavaScript
mit
1,085
var EVENTS, ProxyClient, _r, bindSocketSubscriber, getSystemAddresses, io, mazehallGridRegister; _r = require('kefir'); io = require('socket.io-client'); EVENTS = require('./events'); ProxyClient = function(server, hosts) { server.on('listening', function() { return bindSocketSubscriber(server, hosts); }); return this; }; bindSocketSubscriber = function(server, hosts) { var socket; socket = io.connect(process.env.MAZEHALL_PROXY_MASTER || 'ws://localhost:3300/proxy'); socket.on(EVENTS.HELLO, function() { return mazehallGridRegister(server, socket, hosts); }); socket.on(EVENTS.MESSAGE, function(x) { return console.log('proxy-message: ' + x); }); socket.on(EVENTS.ERROR, function(err) { return console.error(err); }); socket.on('connect_timeout', function() { return console.log('proxy-connection: timeout'); }); socket.on('reconnect_failed', function() { return console.log('proxy-connection: couldn’t reconnect within reconnectionAttempts'); }); }; module.exports = ProxyClient; /* helper */ getSystemAddresses = function() { var address, addresses, interfaces, k, k2, os; os = require('os'); interfaces = os.networkInterfaces(); addresses = []; for (k in interfaces) { for (k2 in interfaces[k]) { address = interfaces[k][k2]; if (address.family === 'IPv4' && !address.internal) { addresses.push(address.address); } } } return addresses; }; mazehallGridRegister = function(server, socket, hosts) { var addresses, port; port = server.address().port; addresses = getSystemAddresses(); hosts = hosts || ['localhost']; if (!Array.isArray(hosts)) { hosts = [hosts]; } return hosts.forEach(function(host) { var msg; msg = { target: host, port: port, addresses: addresses }; return socket.emit(EVENTS.REGISTER, msg); }); };
mazehall/mazehall-proxy
lib/client.js
JavaScript
mit
1,895
var Router = require('restify-router').Router; var db = require("../../../../db"); var ProductionOrderManager = require("dl-module").managers.sales.ProductionOrderManager; var resultFormatter = require("../../../../result-formatter"); var passport = require('../../../../passports/jwt-passport'); const apiVersion = '1.0.0'; function getRouter() { var router = new Router(); router.get("/", passport, function (request, response, next) { db.get().then(db => { var manager = new ProductionOrderManager(db, request.user); var query = request.queryInfo; query.accept =request.headers.accept; manager.getSalesMonthlyReport(query) .then(docs => { var dateFormat = "DD MMM YYYY"; var locale = 'id'; var moment = require('moment'); moment.locale(locale); if ((request.headers.accept || '').toString().indexOf("application/xls") < 0) { for (var a in docs.data) { docs.data[a]._createdDate = moment(new Date(docs.data[a]._createdDate)).format(dateFormat); docs.data[a].deliveryDate = moment(new Date(docs.data[a].deliveryDate)).format(dateFormat); } var result = resultFormatter.ok(apiVersion, 200, docs.data); delete docs.data; result.info = docs; response.send(200, result); } else { var index = 0; var data = []; for (var order of docs.data) { index++; var item = {}; item["No"] = index; item["Sales"] = order._id.sales; item["Januari"] = order.jan.toFixed(2); item["Februari"] = order.feb.toFixed(2); item["Maret"] = order.mar.toFixed(2); item["April"] = order.apr.toFixed(2); item["Mei"] = order.mei.toFixed(2); item["Juni"] = order.jun.toFixed(2); item["Juli"] = order.jul.toFixed(2); item["Agustus"] = order.agu.toFixed(2); item["September"] = order.sep.toFixed(2); item["Oktober"] = order.okt.toFixed(2); item["November"] = order.nov.toFixed(2); item["Desember"] = order.des.toFixed(2); item["Total"] = order.totalOrder.toFixed(2); data.push(item); } var options = { "No": "number", "Sales": "string", "Januari": "string", "Februari": "string", "Maret": "string", "April": "string", "Mei": "string", "Juni": "string", "Juli": "string", "Agustus": "string", "September": "string", "Oktober": "string", "November": "string", "Desember": "string", "Total": "string", }; response.xls(`Sales Monthly Report.xlsx`, data, options); } }) .catch(e => { response.send(500, "gagal ambil data"); }); }) .catch(e => { var error = resultFormatter.fail(apiVersion, 400, e); response.send(400, error); }); }); return router; } module.exports = getRouter; /* SUKSES var Router = require('restify-router').Router; var db = require("../../../../db"); var ProductionOrderManager = require("dl-module").managers.sales.ProductionOrderManager; var resultFormatter = require("../../../../result-formatter"); var passport = require('../../../../passports/jwt-passport'); const apiVersion = '1.0.0'; function getRouter() { var router = new Router(); router.get("/", passport, function (request, response, next) { db.get().then(db => { var manager = new ProductionOrderManager(db, request.user); var query = request.queryInfo; query.accept =request.headers.accept; if(!query.page){ query.page=1; }if(!query.size){ query.size=20; } manager.getSalesMonthlyReport(query) .then(docs => { var dateFormat = "DD MMM YYYY"; var locale = 'id'; var moment = require('moment'); moment.locale(locale); if ((request.headers.accept || '').toString().indexOf("application/xls") < 0) { for (var a in docs.data) { docs.data[a]._createdDate = moment(new Date(docs.data[a]._createdDate)).format(dateFormat); docs.data[a].deliveryDate = moment(new Date(docs.data[a].deliveryDate)).format(dateFormat); } var result = resultFormatter.ok(apiVersion, 200, docs.data); delete docs.data; result.info = docs; response.send(200, result); } else { var index = 0; var data = []; for (var order of docs.data) { index++; var item = {}; var firstname = ""; var lastname = ""; if (order.firstname) firstname = order.firstname; if (order.lastname) lastname = order.lastname; item["No"] = index; item["Nomor Sales Contract"] = order.salesContractNo; item["Tanggal Surat Order Produksi"] = moment(new Date(order._createdDate)).format(dateFormat); item["Nomor Surat Order Produksi"] = order.orderNo; item["Jenis Order"] = order.orderType; item["Jenis Proses"] = order.processType; item["Buyer"] = order.buyer; item["Tipe Buyer"] = order.buyerType; item["Jumlah Order"] = order.orderQuantity; item["Satuan"] = order.uom; item["Acuan Warna / Desain"] = order.colorTemplate; item["Warna Yang Diminta"] = order.colorRequest; item["Jenis Warna"] = order.colorType; item["Jumlah"] = order.quantity; item["Satuan Detail"] = order.uomDetail; item["Tanggal Delivery"] = moment(new Date(order.deliveryDate)).format(dateFormat); item["Staff Penjualan"] = `${firstname} ${lastname}`; item["Status"] = order.status; item["Detail"] = order.detail; data.push(item); } var options = { "No": "number", "Nomor Sales Contract": "string", "Tanggal Surat Order Produksi": "string", "Nomor Surat Order Produksi": "string", "Jenis Order": "string", "Jenis Proses": "string", "Buyer": "string", "Tipe Buyer": "string", "Jumlah Order": "number", "Satuan": "string", "Acuan Warna / Desain": "string", "Warna Yang Diminta": "string", "Jenis Warna": "string", "Jumlah": "number", "Satuan Detail": "string", "Tanggal Delivery": "string", "Staff Penjualan": "string", "Status": "string", "Detail": "string" }; response.xls(`Sales Monthly Report.xlsx`, data, options); // } }) .catch(e => { response.send(500, "gagal ambil data"); }); }) .catch(e => { var error = resultFormatter.fail(apiVersion, 400, e); response.send(400, error); }); }); return router; } module.exports = getRouter; */
danliris/dl-production-webapi
src/routers/v1/sales/reports/sales-monthly-report-router.js
JavaScript
mit
9,361
var Icon = require('../icon'); var element = require('magic-virtual-element'); var clone = require('../clone'); exports.render = function render(component) { var props = clone(component.props); delete props.children; return element( Icon, props, element('path', { d: 'M3 21h2v-2H3v2zM5 7H3v2h2V7zM3 17h2v-2H3v2zm4 4h2v-2H7v2zM5 3H3v2h2V3zm4 0H7v2h2V3zm8 0h-2v2h2V3zm-4 4h-2v2h2V7zm0-4h-2v2h2V3zm6 14h2v-2h-2v2zm-8 4h2v-2h-2v2zm-8-8h18v-2H3v2zM19 3v2h2V3h-2zm0 6h2V7h-2v2zm-8 8h2v-2h-2v2zm4 4h2v-2h-2v2zm4 0h2v-2h-2v2z' }) ); };
goto-bus-stop/deku-material-svg-icons
lib/editor/border-horizontal.js
JavaScript
mit
548
define(['./alasqlportfoliodividenddata', './monthstaticvalues', './bankdatadividend', './dateperiod'], function(alasqlportfoliodividenddata, monthstaticvalues, bankdatadividend, dateperiod) { var gridData = []; var gridId; var months = monthstaticvalues.getMonthWithLettersValues(); var currentMonth = new Date().getMonth(); var selectedYear = new Date().getFullYear(); function setId(fieldId) { gridId = fieldId; } function setData(year) { selectedYear = year; var result = alasqlportfoliodividenddata.getPortfolioDividends(selectedYear); var data = []; var id = 0; result.forEach(function(entry) { if(entry == null) return; var månad = months[entry.Månad -1]; var land = entry.Land == null ? "x" : entry.Land.toLowerCase(); data.push({ Id: id, Name : entry.Värdepapper, Antal : entry.Antal, Typ: entry.Typ, Månad: månad, Utdelningsdatum : entry.Utdelningsdag, Utdelningsbelopp : entry.UtdelningaktieValuta, Utdelningtotal: entry.Belopp, Valuta: entry.Valuta, ValutaKurs: entry.ValutaKurs, Land: land, UtdelningDeklarerad: entry.UtdelningDeklarerad, Utv: entry.Utv }); id++; }); gridData = data; } function onDataBound(e) { var columns = e.sender.columns; var dataItems = e.sender.dataSource.view(); var today = new Date().toISOString(); for (var j = 0; j < dataItems.length; j++) { if(dataItems[j].items == null) return; for (var i = 0; i < dataItems[j].items.length; i++) { var utdelningsdatum = new Date(dataItems[j].items[i].get("Utdelningsdatum")).toISOString(); var utdelningdeklarerad = dataItems[j].items[i].get("UtdelningDeklarerad"); var row = e.sender.tbody.find("[data-uid='" + dataItems[j].items[i].uid + "']"); if(utdelningsdatum <= today) row.addClass("grid-ok-row"); if(utdelningdeklarerad == "N") row.addClass("grid-yellow-row"); } } } function load() { var today = new Date().toISOString().slice(0, 10); var grid = $(gridId).kendoGrid({ toolbar: ["excel", "pdf"], excel: { fileName: "förväntade_utdelningar" + "_" + today + ".xlsx", filterable: true }, pdf: { fileName: "förväntade_utdelningar" + "_" + today + ".pdf", allPages: true, avoidLinks: true, paperSize: "A4", margin: { top: "2cm", left: "1cm", right: "1cm", bottom: "1cm" }, landscape: true, repeatHeaders: true, scale: 0.8 }, theme: "bootstrap", dataBound: onDataBound, dataSource: { data: gridData, schema: { model: { fields: { Name: { type: "string" }, Antal: { type: "number" }, Typ: { type: "string" }, Utdelningsdatum: { type: "date" }, Utdelningsbelopp: { type: "string" }, Utdelningtotal: { type: "number"}, Land: {type: "string" }, ValutaKurs: { type: "string"}, Valuta: {type: "string" } } } }, group: { field: "Månad", dir: "asc", aggregates: [ { field: "Månad", aggregate: "sum" }, { field: "Name", aggregate: "count" }, { field: "Utdelningtotal", aggregate: "sum"} ] }, aggregate: [ { field: "Månad", aggregate: "sum" }, { field: "Name", aggregate: "count" }, { field: "Utdelningtotal", aggregate: "sum" } ], sort: ({ field: "Utdelningsdatum", dir: "asc" }), pageSize: gridData.length }, scrollable: true, sortable: true, filterable: true, groupable: true, pageable: false, columns: [ { field: "Månad", groupHeaderTemplate: "#= value.substring(2, value.length) #", hidden: true }, { field: "UtdelningDeklarerad", hidden: true }, { field: "Name", title: "Värdepapper", template: "<div class='gridportfolio-country-picture' style='background-image: url(/styles/images/#:data.Land#.png);'></div><div class='gridportfolio-country-name'>#: Name #</div>", width: "150px", aggregates: ["count"], footerTemplate: "Totalt antal förväntade utdelningar: #=count# st", groupFooterTemplate: gridNameGroupFooterTemplate }, { field: "Utdelningsdatum", title: "Utd/Handl. utan utd", format: "{0:yyyy-MM-dd}", width: "75px" }, { field: "Typ", title: "Typ", width: "70px" }, { field: "Antal", title: "Antal", format: "{0} st", width: "40px" }, { field: "Utdelningsbelopp", title: "Utdelning/aktie", width: "60px" }, { title: "Utv.", template: '<span class="#= gridPortfolioDividendDivChangeClass(data) #"></span>', width: "15px" }, { field: "Utdelningtotal", title: "Belopp", width: "110px", format: "{0:n2} kr", aggregates: ["sum"], footerTemplate: gridUtdelningtotalFooterTemplate, groupFooterTemplate: gridUtdelningtotalGroupFooterTemplate }, { title: "", template: '<span class="k-icon k-i-info" style="#= gridPortfolioDividendInfoVisibility(data) #"></span>', width: "15px" } ], excelExport: function(e) { var sheet = e.workbook.sheets[0]; for (var i = 0; i < sheet.columns.length; i++) { sheet.columns[i].width = getExcelColumnWidth(i); } } }).data("kendoGrid"); grid.thead.kendoTooltip({ filter: "th", content: function (e) { var target = e.target; return $(target).text(); } }); addTooltipForColumnFxInfo(grid, gridId); addTooltipForColumnUtvInfo(grid, gridId); } function addTooltipForColumnUtvInfo(grid, gridId) { $(gridId).kendoTooltip({ show: function(e){ if(this.content.text().length > 1){ this.content.parent().css("visibility", "visible"); } }, hide:function(e){ this.content.parent().css("visibility", "hidden"); }, filter: "td:nth-child(9)", position: "left", width: 200, content: function(e) { var dataItem = grid.dataItem(e.target.closest("tr")); if(dataItem == null || e.target[0].parentElement.className == "k-group-footer" || dataItem.Utv == 0) return ""; var content = "Utdelningsutveckling jmf fg utdelning: " + dataItem.Utv.replace('.', ',') + " %"; return content } }).data("kendoTooltip"); } function addTooltipForColumnFxInfo(grid, gridId) { $(gridId).kendoTooltip({ show: function(e){ if(this.content.text().length > 1){ this.content.parent().css("visibility", "visible"); } }, hide:function(e){ this.content.parent().css("visibility", "hidden"); }, filter: "td:nth-child(11)", position: "left", width: 200, content: function(e) { var dataItem = grid.dataItem(e.target.closest("tr")); if(dataItem == null || dataItem.ValutaKurs <= 1 || e.target[0].parentElement.className == "k-group-footer") return ""; var content = "Förväntat belopp beräknat med " + dataItem.Valuta + " växelkurs: " + (dataItem.ValutaKurs).replace(".", ",") + "kr"; return content } }).data("kendoTooltip"); } window.gridPortfolioDividendDivChangeClass = function gridPortfolioDividendDivChangeClass(data) { if(data.Utv == 0 || data.Utv == null) return "hidden"; else if(data.Utv > 0) return "k-icon k-i-arrow-up"; else return "k-icon k-i-arrow-down"; } window.gridPortfolioDividendInfoVisibility = function gridPortfolioDividendInfoVisibility(data) { return data.ValutaKurs > 1 ? "" : "display: none;"; } function getExcelColumnWidth(index) { var columnWidth = 150; switch(index) { case 0: // Månad columnWidth = 80; break; case 1: // Värdepapper columnWidth = 220; break; case 2: // Datum columnWidth = 80; break; case 3: // Typ columnWidth = 130; break; case 4: // Antal columnWidth = 70; break; case 5: // Utdelning/aktie columnWidth = 120; break; case 6: // Belopp columnWidth = 260; break; default: columnWidth = 150; } return columnWidth; } function gridNameGroupFooterTemplate(e) { var groupNameValue = e.Månad.sum; if(typeof e.Name.group !== 'undefined') groupNameValue = e.Name.group.value; var groupMonthValue = months.indexOf(groupNameValue); if(currentMonth <= groupMonthValue) { return "Antal förväntade utdelningar: " + e.Name.count + " st"; } else { return "Antal erhållna utdelningar: " + e.Name.count + " st"; } } function gridUtdelningtotalFooterTemplate(e) { var startPeriod = dateperiod.getStartOfYear((selectedYear -1)); var endPeriod = dateperiod.getEndOfYear((selectedYear -1)); var isTaxChecked = $('#checkboxTax').is(":checked"); var selectedYearTotalNumeric = e.Utdelningtotal.sum; var selectedYearTotal = kendo.toString(selectedYearTotalNumeric, 'n2') + " kr"; var lastYearTotalNumeric = bankdatadividend.getTotalDividend(startPeriod, endPeriod, isTaxChecked); var lastYearTotal = kendo.toString(lastYearTotalNumeric, 'n2') + " kr"; var growthValueNumeric = calculateGrowthChange(selectedYearTotalNumeric, lastYearTotalNumeric); var growthValue = kendo.toString(growthValueNumeric, 'n2').replace(".", ",") + "%"; var spanChange = buildSpanChangeArrow(selectedYearTotalNumeric, lastYearTotalNumeric); return "Totalt förväntat belopp: " + selectedYearTotal + " " + spanChange + growthValue + " (" + lastYearTotal + ")"; } function gridUtdelningtotalGroupFooterTemplate(e) { var groupNameValue = e.Månad.sum; if(typeof e.Name.group !== 'undefined') groupNameValue = e.Name.group.value; var groupMonthValue = months.indexOf(groupNameValue); var isTaxChecked = $('#checkboxTax').is(":checked"); var lastYearValueNumeric = bankdatadividend.getDividendMonthSumBelopp((selectedYear -1), (groupMonthValue +1), isTaxChecked); var selectedYearValueNumeric = e.Utdelningtotal.sum; var lastYearValue = kendo.toString(lastYearValueNumeric, 'n2') + " kr"; var selectedYearValue = kendo.toString(selectedYearValueNumeric, 'n2') + " kr"; var monthName = groupNameValue.substring(3, groupNameValue.length).toLowerCase(); var spanChange = buildSpanChangeArrow(selectedYearValueNumeric, lastYearValueNumeric); var growthValueNumeric = calculateGrowthChange(selectedYearValueNumeric, lastYearValueNumeric); var growthValue = kendo.toString(growthValueNumeric, 'n2').replace(".", ",") + "%"; if(months.includes(groupNameValue)) { if(currentMonth <= groupMonthValue) { return "Förväntat belopp " + monthName + ": " + selectedYearValue + " " + spanChange + growthValue + " (" + lastYearValue + ")"; } else { return "Erhållet belopp " + monthName + ": " + selectedYearValue + " " + spanChange + growthValue + " (" + lastYearValue + ")"; } } else { return "Förväntat belopp " + groupNameValue + ": " + selectedYearValue + " " + spanChange + growthValue + " (" + lastYearValue + ")"; } } function buildSpanChangeArrow(current, last) { var spanArrowClass = current > last ? "k-i-arrow-up" : "k-i-arrow-down"; var titleText = current > last ? "To the moon" : "Back to earth"; return "<span class='k-icon " + spanArrowClass + "' title='" + titleText + "'></span>"; } function calculateGrowthChange(current, last) { if(last == 0) return 0; var changeValue = current - last; return ((changeValue / last) * 100).toFixed(2); } return { setId: setId, setData: setData, load: load }; });
nnava/nnava.github.io
js/gridportfoliodividend.js
JavaScript
mit
13,859
/* eslint-disable global-require */ // polyfills and vendors if (!window._babelPolyfill) { require('babel-polyfill') }
ri/news-emote
src/vendor.js
JavaScript
mit
123
const iNaturalistAPI = require( "../inaturalist_api" ); const ControlledTerm = require( "../models/controlled_term" ); const Observation = require( "../models/observation" ); const Project = require( "../models/project" ); const Taxon = require( "../models/taxon" ); const User = require( "../models/user" ); const observations = class observations { static create( params, options ) { return iNaturalistAPI.post( "observations", params, options ) .then( Observation.typifyInstanceResponse ); } static update( params, options ) { return iNaturalistAPI.put( "observations/:id", params, options ) .then( Observation.typifyInstanceResponse ); } static delete( params, options ) { return iNaturalistAPI.delete( "observations/:id", params, options ); } static fave( params, options ) { return observations.vote( params, options ); } static unfave( params, options ) { return observations.unvote( params, options ); } static vote( params, options ) { let endpoint = "votes/vote/observation/:id"; if ( iNaturalistAPI.apiURL && iNaturalistAPI.apiURL.match( /\/v2/ ) ) { endpoint = "observations/:id/vote"; } return iNaturalistAPI.post( endpoint, params, options ) .then( Observation.typifyInstanceResponse ); } static unvote( params, options ) { let endpoint = "votes/unvote/observation/:id"; if ( iNaturalistAPI.apiURL && iNaturalistAPI.apiURL.match( /\/v2/ ) ) { endpoint = "observations/:id/vote"; } return iNaturalistAPI.delete( endpoint, params, options ); } static subscribe( params, options ) { if ( iNaturalistAPI.apiURL && iNaturalistAPI.apiURL.match( /\/v2/ ) ) { return iNaturalistAPI.put( "observations/:id/subscription", params, options ); } return iNaturalistAPI.post( "subscriptions/Observation/:id/subscribe", params, options ); } static review( params, options ) { const p = Object.assign( { }, params ); p.reviewed = "true"; return iNaturalistAPI.post( "observations/:id/review", p, options ); } static unreview( params, options ) { const p = Object.assign( { }, params ); return iNaturalistAPI.delete( "observations/:id/review", p, options ); } static qualityMetrics( params, options ) { return iNaturalistAPI.get( "observations/:id/quality_metrics", params, options ); } static setQualityMetric( params, options ) { return iNaturalistAPI.post( "observations/:id/quality/:metric", params, options ); } static deleteQualityMetric( params, options ) { return iNaturalistAPI.delete( "observations/:id/quality/:metric", params, options ); } static fetch( ids, params ) { return iNaturalistAPI.fetch( "observations", ids, params ) .then( Observation.typifyResultsResponse ); } static search( params, opts = { } ) { return iNaturalistAPI.get( "observations", params, { ...opts, useAuth: true } ) .then( Observation.typifyResultsResponse ); } static identifiers( params ) { return iNaturalistAPI.get( "observations/identifiers", params ) .then( response => { if ( response.results ) { response.results = response.results.map( r => ( Object.assign( { }, r, { user: new User( r.user ) } ) ) ); } return response; } ); } static observers( params ) { return iNaturalistAPI.get( "observations/observers", params ) .then( response => { if ( response.results ) { response.results = response.results.map( r => ( Object.assign( { }, r, { user: new User( r.user ) } ) ) ); } return response; } ); } static speciesCounts( params, opts = { } ) { return iNaturalistAPI.get( "observations/species_counts", params, { ...opts, useAuth: true } ) .then( response => { if ( response.results ) { response.results = response.results.map( r => ( Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } ) ) ); } return response; } ); } static iconicTaxaCounts( params, opts = { } ) { return iNaturalistAPI.get( "observations/iconic_taxa_counts", params, { ...opts, useAuth: true } ) .then( response => { if ( response.results ) { response.results = response.results.map( r => ( Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } ) ) ); } return response; } ); } static iconicTaxaSpeciesCounts( params, opts = { } ) { return iNaturalistAPI.get( "observations/iconic_taxa_species_counts", params, { ...opts, useAuth: true } ) .then( response => { if ( response.results ) { response.results = response.results.map( r => ( Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } ) ) ); } return response; } ); } static popularFieldValues( params ) { return iNaturalistAPI.get( "observations/popular_field_values", params ) .then( response => { if ( response.results ) { response.results = response.results.map( res => { const r = Object.assign( { }, res ); r.controlled_attribute = new ControlledTerm( r.controlled_attribute ); r.controlled_value = new ControlledTerm( r.controlled_value ); return r; } ); } return response; } ); } static umbrellaProjectStats( params ) { return iNaturalistAPI.get( "observations/umbrella_project_stats", params ) .then( response => { if ( response.results ) { response.results = response.results.map( r => ( Object.assign( { }, r, { project: new Project( r.project ) } ) ) ); } return response; } ); } static histogram( params ) { return iNaturalistAPI.get( "observations/histogram", params ); } static qualityGrades( params ) { return iNaturalistAPI.get( "observations/quality_grades", params ); } static subscriptions( params, options ) { return iNaturalistAPI.get( "observations/:id/subscriptions", params, iNaturalistAPI.optionsUseAuth( options ) ); } static taxonSummary( params ) { return iNaturalistAPI.get( "observations/:id/taxon_summary", params ); } static updates( params, options ) { return iNaturalistAPI.get( "observations/updates", params, iNaturalistAPI.optionsUseAuth( options ) ); } static viewedUpdates( params, options ) { return iNaturalistAPI.put( "observations/:id/viewed_updates", params, iNaturalistAPI.optionsUseAuth( options ) ); } static identificationCategories( params ) { return iNaturalistAPI.get( "observations/identification_categories", params ); } static taxonomy( params ) { return iNaturalistAPI.get( "observations/taxonomy", params ) .then( Taxon.typifyResultsResponse ); } static similarSpecies( params, opts ) { const options = Object.assign( { }, opts || { } ); options.useAuth = true; return iNaturalistAPI.get( "observations/similar_species", params, options ) .then( response => { if ( response.results ) { response.results = response.results.map( r => ( Object.assign( { }, r, { taxon: new Taxon( r.taxon ) } ) ) ); } return response; } ); } static taxa( params ) { return iNaturalistAPI.get( "observations/taxa", params ); } }; module.exports = observations;
inaturalist/inaturalistjs
lib/endpoints/observations.js
JavaScript
mit
7,513
/** * @author Adam Meadows <[email protected]> * @copyright 2015 Adam Meadows. All rights reserved. */ 'use strict'; /* eslint-disable max-nested-callbacks */ let $ = require('jquery'); let main = require('aiw-ui'); describe('main', () => { let $container; beforeEach(() => { $container = $('<div/>'); main.render($container[0]); }); it('renders template', () => { expect($('.main p', $container)).toHaveText('This is my first webpack project!'); }); });
jobsquad/aiw-ui
spec/karma/index-spec.6.js
JavaScript
mit
513
import {Sample} from './sample' import {context} from './init_audio' let instanceIndex = 0 export class SampleOscillator extends Sample{ constructor(sampleData, event){ super(sampleData, event) this.id = `${this.constructor.name}_${instanceIndex++}_${new Date().getTime()}` if(this.sampleData === -1){ // create dummy source this.source = { start(){}, stop(){}, connect(){}, } }else{ // @TODO add type 'custom' => PeriodicWave let type = this.sampleData.type this.source = context.createOscillator() switch(type){ case 'sine': case 'square': case 'sawtooth': case 'triangle': this.source.type = type break default: this.source.type = 'square' } this.source.frequency.value = event.frequency } this.output = context.createGain() this.volume = event.data2 / 127 this.output.gain.value = this.volume this.source.connect(this.output) //this.output.connect(context.destination) } }
abudaan/qambi
src/sample_oscillator.js
JavaScript
mit
1,076
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.markdown_wiki = { setUp: function(done) { // setup here if necessary done(); }, default_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/default_options'); var expected = grunt.file.read('test/expected/default_options'); test.equal(actual, expected, 'should describe what the default behavior is.'); test.done(); }, custom_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/custom_options'); var expected = grunt.file.read('test/expected/custom_options'); test.equal(actual, expected, 'should describe what the custom option(s) behavior is.'); test.done(); }, };
lihebi/grunt-markdown-wiki
test/markdown_wiki_test.js
JavaScript
mit
1,353
import { Client } from 'discord.js'; import { isFunction, isRegExp, isString } from 'lodash/lang'; import CommandRegistry from '../command/CommandRegistry'; import Dispatcher from './dispatcher/Dispatcher'; import ServiceContainer from './services/ServiceContainer'; /** * @external {ClientOptions} https://discord.js.org/#/docs/main/stable/typedef/ClientOptions */ /** * @desc The Ghastly client. * @extends Client */ export default class Ghastly extends Client { /** * Constructor. * @param {ClientOptions} options - The options for the client. * @param {PrefixType} options.prefix - The prefix for the client's dispatcher. * If a function is provided, it is given a received `Message` as an argument * and must return a `boolean` indicating if it passes the filter. * @throws {TypeError} Thrown if any option is of the wrong type. */ constructor(options) { const { prefix, ...rest } = options; if (!isString(prefix) && !isRegExp(prefix) && !isFunction(prefix)) { throw new TypeError('Expected prefix to be a string, RegExp or function.'); } super(rest); /** * The command registry for the client. * @type {CommandRegistry} */ this.commands = new CommandRegistry(); /** * The client's service container. * @type {ServiceContainer} */ this.services = new ServiceContainer(); /** * The client's dispatcher. * @type {Dispatcher} * @private */ this.dispatcher = new Dispatcher({ client: this, prefix }); } }
hkwu/ghastly
src/client/Ghastly.js
JavaScript
mit
1,545
// This code is largely borrowed from: github.com/louischatriot/nedb-to-mongodb // This code moves your data from NeDB to MongoDB // You will first need to create the MongoDB connection in your /routes/config.json file // You then need to ensure your MongoDB Database has been created. // ** IMPORTANT ** // There are no duplication checks in place. Please only run this script once. // ** IMPORTANT ** const Nedb = require('nedb'); const mongodb = require('mongodb'); const async = require('async'); const path = require('path'); const common = require('../routes/common'); const config = common.read_config(); let ndb; // check for DB config if(!config.settings.database.connection_string){ console.log('No MongoDB configured. Please see README.md for help'); process.exit(1); } // Connect to the MongoDB database mongodb.connect(config.settings.database.connection_string, {}, (err, mdb) => { if(err){ console.log('Couldn\'t connect to the Mongo database'); console.log(err); process.exit(1); } console.log('Connected to: ' + config.settings.database.connection_string); console.log(''); insertKB(mdb, (KBerr, report) => { insertUsers(mdb, (Usererr, report) => { if(KBerr || Usererr){ console.log('There was an error upgrading to MongoDB. Check the console output'); }else{ console.log('MongoDB upgrade completed successfully'); process.exit(); } }); }); }); function insertKB(db, callback){ const collection = db.collection('kb'); console.log(path.join(__dirname, 'kb.db')); ndb = new Nedb(path.join(__dirname, 'kb.db')); ndb.loadDatabase((err) => { if(err){ console.error('Error while loading the data from the NeDB database'); console.error(err); process.exit(1); } ndb.find({}, (err, docs) => { if(docs.length === 0){ console.error('The NeDB database contains no data, no work required'); console.error('You should probably check the NeDB datafile path though!'); }else{ console.log('Loaded ' + docs.length + ' article(s) data from the NeDB database'); console.log(''); } console.log('Inserting articles into MongoDB...'); async.each(docs, (doc, cb) => { console.log('Article inserted: ' + doc.kb_title); // check for permalink. If it is not set we set the old NeDB _id to the permalink to stop links from breaking. if(!doc.kb_permalink || doc.kb_permalink === ''){ doc.kb_permalink = doc._id; } // delete the old ID and let MongoDB generate new ones delete doc._id; collection.insert(doc, (err) => { return cb(err); }); }, (err) => { if(err){ console.log('An error happened while inserting data'); callback(err, null); }else{ console.log('All articles successfully inserted'); console.log(''); callback(null, 'All articles successfully inserted'); } }); }); }); }; function insertUsers(db, callback){ const collection = db.collection('users'); ndb = new Nedb(path.join(__dirname, 'users.db')); ndb.loadDatabase((err) => { if(err){ console.error('Error while loading the data from the NeDB database'); console.error(err); process.exit(1); } ndb.find({}, (err, docs) => { if(docs.length === 0){ console.error('The NeDB database contains no data, no work required'); console.error('You should probably check the NeDB datafile path though!'); }else{ console.log('Loaded ' + docs.length + ' user(s) data from the NeDB database'); console.log(''); } console.log('Inserting users into MongoDB...'); async.each(docs, (doc, cb) => { console.log('User inserted: ' + doc.user_email); // delete the old ID and let MongoDB generate new ones delete doc._id; collection.insert(doc, (err) => { return cb(err); }); }, (err) => { if(err){ console.error('An error happened while inserting user data'); callback(err, null); }else{ console.log('All users successfully inserted'); console.log(''); callback(null, 'All users successfully inserted'); } }); }); }); };
mrvautin/openKB
data/mongodbUpgrade.js
JavaScript
mit
4,886
var React = require('react'), cx = require('classnames'), constants = require('./constants'); var Preloader = React.createClass({ propTypes: { size: React.PropTypes.oneOf(constants.SCALES), active: React.PropTypes.bool, colors: React.PropTypes.array }, getDefaultProps() { return { active: true, colors: ['blue', 'red', 'yellow', 'green'] }; }, render() { var classes = { 'preloader-wrapper': true, active: this.props.active }; if (this.props.size) { classes[this.props.size] = true; } return ( <div className={cx(this.props.className, classes)}> {this.props.colors.map(color => { var spinnerClasses = { 'spinner-layer': true }; spinnerClasses['spinner-' + color] = true; return ( <div className={cx(spinnerClasses)}> <div className="circle-clipper left"> <div className="circle"></div> </div><div className="gap-patch"> <div className="circle"></div> </div><div className="circle-clipper right"> <div className="circle"></div> </div> </div> ); })} </div> ); } }); module.exports = Preloader;
openmaphub/react-materialize
src/Preloader.js
JavaScript
mit
1,309
let userDao = require('../dao/userDao'), articleDao = require('../dao/articleDao'), commentDao = require('../dao/commentDao'), starDao = require('../dao/starDao'), messageDao = require('../dao/messageDao'), voteDao = require('../dao/voteDao'), settings = require('../config/settings'), tools = require('../config/tools'), jwt = require("jsonwebtoken"), moment = require("moment"), request = require('request'), crypto = require('crypto'), //crypto 是 Node.js 的一个核心模块,我们用它生成散列值来加密密码 sha1 = crypto.createHash('sha1'); module.exports = app => { function getAccToken(req, res) { // let options = { // uri: "https://api.weixin.qq.com/cgi-bin/token", // method: "get", // json: true, // qs: { // grant_type: "client_credential", // appid: "wx7b739a344a69a410", // secret: "9296286bb73ac0391d2eaf2b668c668a" // } // }; if (tools.isBlank(req.body.grant_type) || tools.isBlank(req.body.appid) || tools.isBlank(req.body.secret) || tools.isBlank(req.body.url)) { res.json({ code: 500, msg: '缺少参数' }) return; } let options = { uri: "https://api.weixin.qq.com/cgi-bin/token", method: "get", json: true, qs: { grant_type: req.body.grant_type, appid: req.body.appid, secret: req.body.secret } }; function callback(error, response, data) { if (!error && response.statusCode == 200 && tools.isNotBlank(data) && tools.isNotBlank(data.access_token)) { getTicket(req, res, data.access_token); } else { res.json({ code: 500, msg: '获取access_token失败', data: data }) } } request(options, callback); } function getTicket(req, res, access_token) { let options = { uri: "https://api.weixin.qq.com/cgi-bin/ticket/getticket", method: "get", json: true, qs: { access_token: access_token, type: "jsapi" } }; function callback(error, response, data) { if (!error && response.statusCode == 200 && tools.isNotBlank(data) && data.errcode == 0 && tools.isNotBlank(data.ticket)) { getSignature(req, res, access_token, data.ticket); } else { res.json({ code: 500, msg: '获取ticket失败', data: data }) } } request(options, callback); } function getSignature(req, res, access_token, ticket) { let jsapi_ticket = ticket, nonceStr = tools.randomWord(false, 32), timestamp = parseInt((new Date().getTime())/1000), url = req.body.url; let str = `jsapi_ticket=${jsapi_ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}` let signature = sha1.update(str).digest('hex'); res.json({ code: 200, msg: 'ok', ob: { accessToken: access_token, timestamp: timestamp, nonceStr: nonceStr, signature: signature } }) } //检查收到的参数确认是否来自微信调用 function checkSignature(req) { let signature = req.query.signature, timestamp = req.query.timestamp, nonce = req.query.timestamp; let arr = ['yourToken', timestamp, nonce]; let str = arr.sort().join(''); let sig = sha1.update(str).digest('hex'); if (sig === signature) { return true; } else { return false; } } //给微信调用 app.get('/forWechat', (req, res, next) => { if (tools.isBlank(req.query.signature) || tools.isBlank(req.query.timestamp) || tools.isBlank(req.query.nonce) || tools.isBlank(req.query.echostr) || checkSignature(req)) { next(); } else { res.send(req.query.echostr); } }); //获取微信签名 app.post('/getAccToken', (req, res, next) => { getAccToken(req, res); }); app.get('/login', (req, res, next) => { let user = { id: '5902bc7cd7e7550ab6203037', name: 'name', level: '初级', avatar: 'http://image.beekka.com/blog/2014/bg2014051201.png' } let authToken = jwt.sign({ user: user, exp: moment().add('days', 30).valueOf(), }, settings.jwtSecret); res.json({ code: 200, msg: 'ok', token: authToken }); }); app.get('/w', (req, res, next) => { res.json({ code: 200, msg: 'ok', user: req.users }); }); //添加用户 app.get('/addUser', (req, res, next) => { userDao.addUser(req, res, next) }); //获取用户 app.get('/getUser', (req, res, next) => { userDao.getUser(req, res, next) }); //删除用户 app.get('/removeUser', (req, res, next) => { userDao.removeUser(req, res, next) }); //发表文章 app.post('/addArticle', (req, res, next) => { articleDao.addArticle(req, res, next) }); //删除文章 app.get('/removeArticle', (req, res, next) => { articleDao.removeArticle(req, res, next) }); //更新文章 -- 暂时不做 // app.get('/updateArticle', (req, res, next) => { // articleDao.updateArticle(req, res, next) // }); //获取文章详情 app.get('/article', (req, res, next) => { articleDao.getArticle(req, res, next) }); //获取文章列表 app.get('/articleList', (req, res, next) => { articleDao.getArticleList(req, res, next) }); //获取精选文章 app.get('/handpickList', (req, res, next) => { articleDao.getHandpickList(req, res, next) }); //根据类型获取文章 app.get('/articleListByType', (req, res, next) => { articleDao.getArticleListByType(req, res, next) }); //获取用户文章 app.get('/articleListByUser', (req, res, next) => { articleDao.getArticleListByUser(req, res, next) }); //获取收藏的文章 app.get('/articleListByCollection', (req, res, next) => { articleDao.getArticleListByCollection(req, res, next) }); //收藏 app.post('/addCollection', (req, res, next) => { articleDao.addArticleCollections(req, res, next) }); //取消收藏 app.get('/removeCollection', (req, res, next) => { articleDao.removeArticleCollections(req, res, next) }); //发表评论 app.post('/addComment', (req, res, next) => { commentDao.addComment(req, res, next) }); //删除评论 app.get('/removeComment', (req, res, next) => { commentDao.removeComment(req, res, next) }); //评论列表 app.get('/commentList', (req, res, next) => { commentDao.getCommentList(req, res, next) }); //消息列表 app.get('/message', (req, res, next) => { messageDao.getMessageList(req, res, next) }); //点赞 app.post('/addStar', (req, res, next) => { starDao.addStar(req, res, next) }); //取消赞 app.get('/removeStar', (req, res, next) => { starDao.removeStar(req, res, next) }); //赞列表 app.get('/starList', (req, res, next) => { starDao.getStarList(req, res, next) }); //他人信息 app.get('/otherInfo', (req, res, next) => { userDao.getOtherInfo(req, res, next) }); //自己信息 app.get('/selfInfo', (req, res, next) => { userDao.getUserInfo(req, res, next) }); //添加投票 app.post('/addVote', (req, res, next) => { voteDao.addVote(req, res, next) }); //确定投票 app.post('/commitVote', (req, res, next) => { voteDao.commitVote(req, res, next) }); //获取投票详情 app.get('/vote', (req, res, next) => { voteDao.getVote(req, res, next) }); //获取投票列表 app.get('/voteList', (req, res, next) => { voteDao.getVoteList(req, res, next) }); //已投票用户列表 app.get('/voteUserList', (req, res, next) => { voteDao.getVoteUserList(req, res, next) }); //获取顶部3条,1条投票2条精选 app.get('/getTopList', (req, res, next) => { articleDao.getTopList(req, res, next) }); }
wayshon/community-server
routes/api.js
JavaScript
mit
8,947
/* @flow */ import * as React from 'react'; import cn from 'classnames'; import { StyleClasses } from '../theme/styleClasses'; type Props = { // An optional inline-style to apply to the overlay. style: ?Object, // An optional css className to apply. className: ?string, // Boolean if this divider should be inset relative to it's container inset: ?boolean, // Boolean if the divider should be vertical instead of horizontal. vertical: ?boolean, }; const BASE_ELEMENT = StyleClasses.DIVIDER; /** * The divider component will pass all other props such as style or * event listeners on to the component. */ class Divider extends React.PureComponent<Props, *> { props: Props; render() { const { className, inset, vertical, ...props } = this.props; const Component = vertical ? 'div' : 'hr'; return ( <Component {...props} className={cn( BASE_ELEMENT, { 'boldrui-divider__vertical': vertical, 'boldrui-divider__inset': inset, }, className, )} /> ); } } export default Divider;
boldr/boldr-ui
src/Divider/Divider.js
JavaScript
mit
1,118
var windowHeight = $(window).height(); var menuBarHeight = $('#codeplayer-menubar').height(); $('.codeplayer-code-container').css('height', (windowHeight - menuBarHeight) + 'px'); $('.codeplayer-toogle').click(function() { $(this).toggleClass('codeplayer-selected'); var codeContainerDiv = '#codeplayer-' + $(this).html() + '-container'; $(codeContainerDiv).toggle(); var showingDivs = $('.codeplayer-code-container').filter(function() { return $((this)).css('display') != 'none'; }).length; var divWidthPercentage = 100 / showingDivs; $('.codeplayer-code-container').css('width', divWidthPercentage + '%'); }); $('#codeplayer-runbuttondiv').click(function() { var iframeContent = '<style>' + $('#codeplayer-cssCode').val() + '</style>' + $('#codeplayer-htmlCode').val(); $('#codeplayer-iframe').contents().find('html').html(iframeContent); document.getElementById('codeplayer-iframe').contentWindow. eval($('#codeplayer-jsCode').val()) });
phillipemoreira/web-development
robpercival/4.jQuery/js/codeplayer.js
JavaScript
mit
1,020
var randomBytes = require('mz/crypto').randomBytes; module.exports = function* trace(next) { this.id = yield randomBytes(24); var ctx = this; var req = this.req; var res = this.res; // request start this.trace('time.start'); // request end req.once('end', this.trace.bind(this, 'time.end')); // response headers var writeHead = res.writeHead; res.writeHead = function () { ctx.trace('time.headers'); return writeHead.apply(this, arguments); } // response finish res.once('finish', this.trace.bind(this, 'time.finish')); yield* next; }
phamann/wedding-holding-page
server/lib/middleware/trace.js
JavaScript
mit
615
(function() { 'use strict'; angular.module('cd.app.registerForm') .controller('RegisterFormController', RegisterFormController); /* @ngInject */ function RegisterFormController ($location, StepsService) { var $ctrl = this; $ctrl.selectedPlatform = JSON.parse(localStorage.getItem('selectedPlatform')); $ctrl.selectedPackage = JSON.parse(localStorage.getItem('selectedPackage')); if (StepsService.currentStep < StepsService.REGISTER) { $location.path('/package'); } else { _init(); } function _init () { $ctrl.registerForm = { nome: '', email: '', nascimento: '', cpf: '', telefone: '' }; $ctrl.submit = submit; function submit () { console.groupCollapsed('Formulário Enviado'); console.log('Formulário de registro', $ctrl.registerForm); console.log('Plano Selecionado', $ctrl.selectedPackage); console.log('Plataforma Selecionada', $ctrl.selectedPlatform); console.groupEnd(); }; }; }; })();
RaphaelGuimaraes/celular-direto
src/pages/register-form/register-form.controller.js
JavaScript
mit
1,265
'use strict'; function fixImports() { let editor = atom.workspace.getActiveTextEditor() if (editor) { // fixImports(editor) // editor.selectLinesContainingCursors() } } module.exports = { fixImports, };
madhusudhand/atom-angular2
lib/command-handlers.js
JavaScript
mit
231
var $iterators = require('./es6.array.iterator') , redefine = require('./_redefine') , global = require('./_global') , hide = require('./_hide') , Iterators = require('./_iterators') , wks = require('./_wks') , CORRECT_SYMBOL = require('./_correct-symbol') , ITERATOR = wks('iterator') , TO_STRING_TAG = wks('toStringTag') , ArrayValues = Iterators.Array; require('./_').each.call(( 'CSSRuleList,CSSStyleDeclaration,DOMStringList,DOMTokenList,FileList,HTMLCollection,MediaList,' + 'MimeTypeArray,NamedNodeMap,NodeList,NodeListOf,Plugin,PluginArray,StyleSheetList,TouchList' ).split(','), function(NAME){ var Collection = global[NAME] , proto = Collection && Collection.prototype , key; if(proto){ if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues); if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = ArrayValues; for(key in $iterators){ if(!CORRECT_SYMBOL || !proto[key])redefine(proto, key, $iterators[key], true); } } });
eteeselink/core-js
modules/web.dom.iterable.js
JavaScript
mit
1,075
/** * Copyright (c) 2014 Famous Industries, Inc. * * 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. * * @license MIT */ /** * HeaderFooterLayout * ------------------ * * HeaderFooterLayout is a layout which will arrange three renderables * into a header and footer area of defined size and a content area * of flexible size. * * In this example we create a basic HeaderFooterLayout and define a * size for the header and footer */ define(function(require, exports, module) { var Engine = require('famous/core/Engine'); var Surface = require('famous/core/Surface'); var Modifier = require('famous/core/Modifier'); var StateModifier = require('famous/modifiers/StateModifier'); var Transform = require('famous/core/Transform'); var HeaderFooterLayout = require('famous/views/HeaderFooterLayout'); var Easing = require('famous/transitions/Easing'); var RenderController = require("famous/views/RenderController"); var MenuView = require('./views/MenuView'); var PlayHeaderView = require('./views/PlayHeaderView'); var PlayBodyView = require('./views/PlayBodyView'); var PlayFooterView = require('./views/PlayFooterView'); var Transitionable = require('famous/transitions/Transitionable'); var SpringTransition = require('famous/transitions/SpringTransition'); Transitionable.registerMethod('spring', SpringTransition); var mainContext = Engine.createContext(); var layout = new HeaderFooterLayout({ headerSize: 50, footerSize: 50 }); layout.header.add(PlayHeaderView); //position to the center var bodyRenderController = new RenderController(); layout.content.add(bodyRenderController); var bodySurfaces = []; bodySurfaces.push(PlayBodyView); bodySurfaces.push(MenuView); bodyRenderController.show(bodySurfaces[0]); PlayBodyView.eventHandler.on('seekToPosition', function(data) { PlayHeaderView.setIsPlaying(false); }); PlayBodyView.eventHandler.on('finishedSpeaking', function(data) { PlayHeaderView.setIsPlaying(true); }); var togglemenu = false; PlayHeaderView.eventHandler.on('showMenu', function(data) { bodySurfaces[1].toggle(); togglemenu = !togglemenu; if (togglemenu) { bodyRenderController.show(bodySurfaces[1]); } else { bodyRenderController.show(bodySurfaces[0]); } }); PlayHeaderView.eventHandler.on('shouldFlipViews', function(data) { PlayBodyView.flip(); }); PlayHeaderView.eventHandler.on('shouldPlay', function(data) { PlayBodyView.play(); }); PlayHeaderView.eventHandler.on('toTop', function(data) { PlayBodyView.scrollTo(0); }); MenuView.eventHandler.on('changeContent', function(title) { PlayHeaderView.setTitle(title); PlayHeaderView.setIsPlaying(true); PlayHeaderView.showMenu(); PlayBodyView.switchContent(title); }); layout.footer.add(PlayFooterView); mainContext.add(layout); });
hemantasapkota/pdfspeaker
src/app/js/main.js
JavaScript
mit
4,131
import React, { Component, PropTypes } from 'react'; import Select from 'react-select'; import { omit } from 'lodash'; import classNames from 'classnames'; import styles from './styles.scss'; import chevronIcon from '../../../assets/images/icons/chevron-down.svg'; export const THEMES = { OLD: 'old', INTERNAL: 'internal' }; export default class SelectField extends Component { static propTypes = { theme: PropTypes.string, label: PropTypes.string, error: PropTypes.string, className: PropTypes.string, }; static defaultProps = { theme: THEMES.OLD, }; constructor(props, context) { super(props, context); this.renderArrow = ::this.renderArrow; } renderArrow() { return ( <div className={styles.selectArrow}> <img src={chevronIcon} alt="chevron" /> </div> ); } renderOption(option, i) { return ( <div key={i} className={styles.selectFieldOption}>{option.label}</div> ); } renderLabel() { const labelStyles = classNames(styles.selectLabel, { [styles.selectLabelInvalid]: this.props.error }); return this.props.label ? ( <div className={labelStyles}>{this.props.label}</div> ) : null; } renderError() { return this.props.error ? ( <div className={styles.selectFieldError}> {this.props.error} </div> ) : null; } renderSelectField() { const selectStyles = classNames(styles.selectField, { [styles.selectFieldInvalid]: this.props.error }); const props = omit(this.props, ['error', 'label']); return ( <div className={selectStyles}> <Select {...props} arrowRenderer={this.renderArrow} optionRenderer={this.renderOption} /> {this.renderError()} </div> ); } render() { const selectStyles = classNames(styles.select, this.props.className, { [styles.selectOld]: this.props.theme === THEMES.OLD, [styles.selectInternal]: this.props.theme === THEMES.INTERNAL, }); return ( <div className={selectStyles}> {this.renderLabel()} {this.renderSelectField()} </div> ); } }
singaporesamara/SOAS-DASHBOARD
app/components/UIKit/SelectField/index.js
JavaScript
mit
2,115
Notify = function(text, callback, close_callback, style) { var time = '10000'; var $container = $('#notifications'); var icon = '<i class="fa fa-info-circle "></i>'; if (typeof style == 'undefined' ) style = 'warning' var html = $('<div class="alert alert-' + style + ' hide">' + icon + " " + text + '</div>'); $('<a>',{ text: '×', class: 'close', style: 'padding-left: 10px;', href: '#', click: function(e){ e.preventDefault() close_callback && close_callback() remove_notice() } }).prependTo(html) $container.prepend(html) html.removeClass('hide').hide().fadeIn('slow') function remove_notice() { html.stop().fadeOut('slow').remove() } var timer = setInterval(remove_notice, time); $(html).hover(function(){ clearInterval(timer); }, function(){ timer = setInterval(remove_notice, time); }); html.on('click', function () { clearInterval(timer) callback && callback() remove_notice() }); }
nil1990/earth_nine_ecomm
assets/js/notify.js
JavaScript
mit
966
import React from 'react'; import Link from 'gatsby-link'; import { BlogPostContent, BlogPostContainer, TagList } from '../utils/styles'; import { arrayReducer } from '../utils/helpers.js'; export default function TagsPage({ data }) { const { edges: posts } = data.allMarkdownRemark; const categoryArray = arrayReducer(posts, 'category'); const categoryLinks = categoryArray.map((category, index) => { return ( <li className="category-item" key={index}> <Link className='category-list-link' to={`/categories/${category}`} key={index}>{category}</Link> </li> ) }); return ( <BlogPostContainer> <BlogPostContent> <h2>Categories</h2> <TagList className='categories-list'>{categoryLinks}</TagList> </BlogPostContent> </BlogPostContainer> ); } export const query = graphql` query CategoryPage { allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) { totalCount edges { node { frontmatter { category } } } } } `;
aberkow/gatsby-blog
src/pages/categories.js
JavaScript
mit
1,085
/* -*- javascript -*- */ "use strict"; import {StageComponent} from 'aurelia-testing'; import {bootstrap} from 'aurelia-bootstrapper'; import {LogManager} from 'aurelia-framework'; import {ConsoleAppender} from 'aurelia-logging-console'; import {customMatchers} from '../helpers'; describe('ui-icon', () => { let component, logger; beforeAll(() => { jasmine.addMatchers( customMatchers ); logger = LogManager.getLogger( 'ui-icon-spec' ); }); beforeEach(() => { component = StageComponent.withResources('src/elements/ui-icon'); }); afterEach(() => { component.dispose(); }); describe( 'as a custom attribute', () => { it( 'adds semantic classes when bound', done => { component. inView(` <i ui-icon="name: cloud"></i> `). boundTo({}). create( bootstrap ).then( () => { expect( component.element ).toHaveCssClasses( 'cloud', 'icon' ); }). then( done ). catch( done.fail ); }); it( 'has a reasonable name default', done => { component. inView(` <i ui-icon></i> `). boundTo({}). create( bootstrap ).then( () => { expect( component.element ).toHaveCssClasses( 'help', 'circle', 'icon' ); }). then( done ). catch( done.fail ); }); it( 'adds a size class when one is set', done => { component. inView(` <i ui-icon="name: cloud; size: huge"></i> `). boundTo({}). create( bootstrap ).then( () => { expect( component.element ).toHaveCssClasses( 'huge', 'cloud', 'icon' ); }). then( done ). catch( done.fail ); }); it( 'adds a color class when one is set', done => { component. inView(` <i ui-icon="name: user; color: red">Erase History</i> `). boundTo({}). create( bootstrap ).then( () => { expect( component.element ).toHaveCssClasses( 'red', 'user', 'icon' ); }). then( done ). catch( done.fail ); }); it( 'adds a disabled class when it is set', done => { component. inView(` <i ui-icon="disabled: true">Eject!</i> `). boundTo({}). create( bootstrap ).then( () => { expect( component.element ).toHaveCssClasses( 'disabled', 'icon' ); }). then( done ). catch( done.fail ); }); }); describe( 'as a custom element', () => { it( 'uses the icon name', done => { component. inView(` <ui-icon name="cloud"></ui-icon> `). boundTo({}). create( bootstrap ).then( () => { let icon = component.viewModel.semanticElement; expect( icon ).toBeDefined(); expect( icon.nodeType ).toEqual( 1 ); expect( icon ).toHaveCssClasses( 'cloud' ); }). then( done ). catch( done.fail ); }); it( 'support multiple names', done => { component. inView(` <ui-icon name="circular inverted users"></ui-icon> `). boundTo({}). create( bootstrap ).then( () => { let icon = component.viewModel.semanticElement; expect( icon ).toBeDefined(); expect( icon.nodeType ).toEqual( 1 ); expect( icon ).toHaveCssClasses( 'circular', 'inverted', 'users' ); }). then( done ). catch( done.fail ); }); it( 'has a reasonable default name', done => { component. inView(` <ui-icon></ui-icon> `). boundTo({}). create( bootstrap ).then( () => { let icon = component.viewModel.semanticElement; expect( icon ).toBeDefined(); expect( icon.nodeType ).toEqual( 1 ); expect( icon ).toHaveCssClasses( 'help', 'circle' ); }). then( done ). catch( done.fail ); }); it( 'adds a size class when one is set', done => { component. inView(` <ui-icon size="huge"></ui-icon> `). boundTo({}). create( bootstrap ).then( () => { let icon = component.viewModel.semanticElement; expect( icon ).toBeDefined(); expect( icon.nodeType ).toEqual( 1 ); expect( icon ).toHaveCssClasses( 'huge' ); }). then( done ). catch( done.fail ); }); it( 'adds a color class when one is set', done => { component. inView(` <ui-icon color="red"></ui-icon> `). boundTo({}). create( bootstrap ).then( () => { let icon = component.viewModel.semanticElement; expect( icon ).toBeDefined(); expect( icon.nodeType ).toEqual( 1 ); expect( icon ).toHaveCssClasses( 'red' ); }). then( done ). catch( done.fail ); }); it( 'adds a disabled class when it is set', done => { component. inView(` <ui-icon disabled="true"></ui-icon> `). boundTo({}). create( bootstrap ).then( () => { let icon = component.viewModel.semanticElement; expect( icon ).toBeDefined(); expect( icon.nodeType ).toEqual( 1 ); expect( icon ).toHaveCssClasses( 'disabled' ); }). then( done ). catch( done.fail ); }); }); });
ged/aurelia-semantic-ui
test/unit/elements/ui-icon_spec.js
JavaScript
mit
4,822
// // This software is released under the 3-clause BSD license. // // Copyright (c) 2015, Xin Chen <[email protected]> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the author nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /******************************************************************************* * 1) MidiPlayer.js. ******************************************************************************/ /** * MidiPlayer class. Used to play midi by javascript, without any plugin. * Requires a HTML5 browser: firefox, chrome, safari, opera, IE10+. * * The other 5 js files are from [2][3], which is a demo of [1]: * [1] http://matt.west.co.tt/music/jasmid-midi-synthesis-with-javascript-and-html5-audio/ * [2] http://jsspeccy.zxdemo.org/jasmid/ * [3] https://github.com/gasman/jasmid * * Modification is done to audio.js: * - added function fireEventEnded(). * - added 'ended' event firing when generator.finished is true. * - move 'context' outside function AudioPlayer, so in chrome it won't have this error * when you loop the play: * Failed to construct 'AudioContext': number of hardware contexts reached maximum (6) * * Github site: https://github.com/chenx/MidiPlayer * * @by: X. Chen * @Create on: 4/1/2015 * @Last modified: 4/3/2015 */ if (typeof (MidiPlayer) == 'undefined') { /** * Constructor of MidiPlayer class. * @param midi MIDI file path. * @param target Target html element that this MIDI player is attached to. * @param loop Optinoal. Whether loop the play. Value is true/false, default is false. * @param maxLoop Optional. max number of loops to play when loop is true. * Negative or 0 means infinite. Default is 1. * @param end_callback Optional. Callback function when MIDI ends. * @author X. Chen. April 2015. */ var MidiPlayer = function(midi, target, loop, maxLoop, end_callback) { this.midi = midi; this.target = document.getElementById(target); this.loop = (typeof (loop) == 'undefined') ? false : loop; if (! loop) { this.max_loop_ct = 1; } else { this.max_loop_ct = (typeof (maxLoop) == 'undefined') ? 1 : (maxLoop <= 0 ? 0 : maxLoop); } this.end_callback = (typeof (end_callback) == 'function') ? end_callback : null; this.debug_div = null; this.midiFile = null; this.synth = null; this.replayer = null; this.audio = null; this.ct = 0; // loop counter. this.started = false; // state of play: started/stopped. this.listener_added = false; } MidiPlayer.prototype.setDebugDiv = function(debug_div_id) { this.debug_div = (typeof (debug_div_id) == 'undefined') ? null : document.getElementById(debug_div_id); } MidiPlayer.prototype.debug = function(msg) { if (this.debug_div) { this.debug_div.innerHTML += msg + '<br/>'; } } MidiPlayer.prototype.stop = function() { this.started = false; this.ct = 0; if (this.audio) { this.audio.stop(); this.audio = null; } if (this.max_loop_ct > 0) { if (this.end_callback) { this.end_callback(); } } } MidiPlayer.prototype.play = function() { if (this.started) { this.stop(); //return; } this.started = true; var o = this.target; var _this = this; // must be 'var', otherwise _this is public, and causes problem. var file = this.midi; var loop = this.loop; if (window.addEventListener) { // Should not add more than one listener after first call, otherwise o has more // and more listeners attached, and will fire n events the n-th time calling play. if (! this.listener_added) { this.listener_added = true; if (o) { // If o does not exist, don't add listener. o.addEventListener('ended', function() { // addEventListener not work for IE8. //alert('ended'); if (_this.max_loop_ct <= 0 || (++ _this.ct) < _this.max_loop_ct) { _this.replayer = Replayer(_this.midiFile, _this.synth); _this.audio = AudioPlayer(_this.replayer, o, loop); _this.debug( file + ': loop ' + (1 +_this.ct) ); } else if (_this.max_loop_ct > 0) { _this.stop(); } }, false); } } } else if (window.attachEvent) { // IE don't work anyway. //document.getElementById('music').attachEvent( // 'onclick', function(e) { alert('IE end'); }, true); } loadRemote(file, function(data) { if (_this.ct == 0) { _this.midiFile = MidiFile(data); _this.synth = Synth(44100); } _this.replayer = Replayer(_this.midiFile, _this.synth); _this.audio = AudioPlayer(_this.replayer, o, loop); _this.debug( file + ': loop ' + (1 + _this.ct) ); //alert(_this.audio.type); // webkit for firefox, chrome; flash for opera/safari. }); } // This function is modified from [2] by adding support for IE. See: // http://stackoverflow.com/questions/1919972/how-do-i-access-xhr-responsebody-for-binary-data-from-javascript-in-ie // https://code.google.com/p/jsdap/source/browse/trunk/?r=64 // // However, IE8 and before do not support HTML5 Audio tag so this still will not work. // See: http://www.impressivewebs.com/html5-support-ie9/ // // A private function, defined by 'var'. // Original definition in [2] is: function loadRemote(path, callback) { var loadRemote = function(path, callback) { var fetch = new XMLHttpRequest(); fetch.open('GET', path); if (fetch.overrideMimeType) { fetch.overrideMimeType("text/plain; charset=x-user-defined"); // for non-IE. } else { fetch.setRequestHeader('Accept-Charset', 'x-user-defined'); // for IE. } fetch.onreadystatechange = function() { if(this.readyState == 4 && this.status == 200) { // munge response into a binary string if (IE_HACK) { // for IE. var t = BinaryToArray(fetch.responseBody).toArray(); var ff = []; var mx = t.length; var scc= String.fromCharCode; for (var z = 0; z < mx; z++) { // t[z] here is equivalent to 't.charCodeAt(z) & 255' below. // e.g., t[z] is 238, below t.charCodeAt[z] is 63470. 63470 & 255 = 238. // But IE8 has no Audio element, so can't play anyway, // and will report this error in audio.js: 'Audio' is undefined. ff[z] = scc(t[z]); } callback(ff.join("")); } else { // for non-IE. var t = this.responseText || "" ; var ff = []; var mx = t.length; var scc= String.fromCharCode; for (var z = 0; z < mx; z++) { ff[z] = scc(t.charCodeAt(z) & 255); } callback(ff.join("")); } } } fetch.send(); } // Now expand definition of MidiPlayer to include the other 6 files below. // So comment out the line below, and add the back curly bracket at the end of file. //} // (previous) end of: if (typeof (MidiPlayer) == 'undefined') /******************************************************************************* * 2) vbscript.js ******************************************************************************/ /** * Convert binary string to array. * * See: * [1] http://stackoverflow.com/questions/1919972/how-do-i-access-xhr-responsebody-for-binary-data-from-javascript-in-ie * [2] https://code.google.com/p/jsdap/source/browse/trunk/?r=64 */ var IE_HACK = (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)); if (IE_HACK) { //alert('IE hack'); document.write('<script type="text/vbscript">\n\ Function BinaryToArray(Binary)\n\ Dim i\n\ ReDim byteArray(LenB(Binary))\n\ For i = 1 To LenB(Binary)\n\ byteArray(i-1) = AscB(MidB(Binary, i, 1))\n\ Next\n\ BinaryToArray = byteArray\n\ End Function\n\ </script>'); } /******************************************************************************* * Files 3) to 7) below are by: * Matt Westcott <[email protected]> - @gasmanic - http://matt.west.co.tt/ * See: * - http://matt.west.co.tt/music/jasmid-midi-synthesis-with-javascript-and-html5-audio/ * - http://jsspeccy.zxdemo.org/jasmid/ * - https://github.com/gasman/jasmid ******************************************************************************/ /******************************************************************************* * 3) audio.js. ******************************************************************************/ var sampleRate = 44100; /* hard-coded in Flash player */ var context = null // XC. // Note this may cause name conflict. So be careful of variable name "context". // // http://stackoverflow.com/questions/2856513/how-can-i-trigger-an-onchange-event-manually // Added by XC. // function fireEventEnded(target) { if (! target) return; if (document.createEvent) { var evt = document.createEvent("HTMLEvents"); evt.initEvent("ended", false, true); target.dispatchEvent(evt); } else if (document.createEventObject) { // IE before version 9 var myEvent = document.createEventObject(); target.fireEvent('onclick', myEvent); } } //function AudioPlayer(generator, opts) { function AudioPlayer(generator, targetElement, opts) { if (!opts) opts = {}; var latency = opts.latency || 1; var checkInterval = latency * 100 /* in ms */ var audioElement = new Audio(); var webkitAudio = window.AudioContext || window.webkitAudioContext; var requestStop = false; if (audioElement.mozSetup) { audioElement.mozSetup(2, sampleRate); /* channels, sample rate */ var buffer = []; /* data generated but not yet written */ var minBufferLength = latency * 2 * sampleRate; /* refill buffer when there are only this many elements remaining */ var bufferFillLength = Math.floor(latency * sampleRate); function checkBuffer() { if (requestStop) return; // no more data feed after request stop. xc. if (buffer.length) { var written = audioElement.mozWriteAudio(buffer); buffer = buffer.slice(written); } if (buffer.length < minBufferLength && !generator.finished) { buffer = buffer.concat(generator.generate(bufferFillLength)); } if (!requestStop && (!generator.finished || buffer.length)) { setTimeout(checkBuffer, checkInterval); } if (!requestStop && generator.finished) { fireEventEnded(targetElement); // xc. } } checkBuffer(); return { 'type': 'Firefox Audio', 'stop': function() { requestStop = true; } } } else if (webkitAudio) { // Uses Webkit Web Audio API if available // chrome stops after 5 invocation. XC. Error is: // Failed to construct 'AudioContext': number of hardware contexts reached maximum (6) //var context = new webkitAudio(); if (! context) context = new webkitAudio(); // fixed by this. XC. sampleRate = context.sampleRate; var channelCount = 2; var bufferSize = 4096*4; // Higher for less gitches, lower for less latency var node = context.createScriptProcessor(bufferSize, 0, channelCount); node.onaudioprocess = function(e) { process(e) }; function process(e) { if (generator.finished) { node.disconnect(); //alert('done: ' + targetElement); // xc. fireEventEnded(targetElement); // xc. return; } var dataLeft = e.outputBuffer.getChannelData(0); var dataRight = e.outputBuffer.getChannelData(1); var generate = generator.generate(bufferSize); for (var i = 0; i < bufferSize; ++i) { dataLeft[i] = generate[i*2]; dataRight[i] = generate[i*2+1]; } } // start node.connect(context.destination); return { 'stop': function() { // pause node.disconnect(); requestStop = true; }, 'type': 'Webkit Audio' } } else { // Fall back to creating flash player var c = document.createElement('div'); c.innerHTML = '<embed type="application/x-shockwave-flash" id="da-swf" src="da.swf" width="8" height="8" allowScriptAccess="always" style="position: fixed; left:-10px;" />'; document.body.appendChild(c); var swf = document.getElementById('da-swf'); var minBufferDuration = latency * 1000; /* refill buffer when there are only this many ms remaining */ var bufferFillLength = latency * sampleRate; function write(data) { var out = new Array(data.length); for (var i = data.length-1; i != 0; i--) { out[i] = Math.floor(data[i]*32768); } return swf.write(out.join(' ')); } function checkBuffer() { if (requestStop) return; // no more data feed after request stop. xc. if (swf.bufferedDuration() < minBufferDuration) { write(generator.generate(bufferFillLength)); }; if (!requestStop && !generator.finished) setTimeout(checkBuffer, checkInterval); if (!requestStop && generator.finished) fireEventEnded(targetElement); // xc. } function checkReady() { if (swf.write) { checkBuffer(); } else { setTimeout(checkReady, 10); } } checkReady(); return { 'stop': function() { swf.stop(); requestStop = true; }, 'bufferedDuration': function() { return swf.bufferedDuration(); }, 'type': 'Flash Audio' } } } /******************************************************************************* * 4) midifile.js ******************************************************************************/ /** * Class to parse the .mid file format. Depends on stream.js. */ function MidiFile(data) { function readChunk(stream) { var id = stream.read(4); var length = stream.readInt32(); return { 'id': id, 'length': length, 'data': stream.read(length) }; } var lastEventTypeByte; function readEvent(stream) { var event = {}; event.deltaTime = stream.readVarInt(); var eventTypeByte = stream.readInt8(); if ((eventTypeByte & 0xf0) == 0xf0) { /* system / meta event */ if (eventTypeByte == 0xff) { /* meta event */ event.type = 'meta'; var subtypeByte = stream.readInt8(); var length = stream.readVarInt(); switch(subtypeByte) { case 0x00: event.subtype = 'sequenceNumber'; if (length != 2) throw "Expected length for sequenceNumber event is 2, got " + length; event.number = stream.readInt16(); return event; case 0x01: event.subtype = 'text'; event.text = stream.read(length); return event; case 0x02: event.subtype = 'copyrightNotice'; event.text = stream.read(length); return event; case 0x03: event.subtype = 'trackName'; event.text = stream.read(length); return event; case 0x04: event.subtype = 'instrumentName'; event.text = stream.read(length); return event; case 0x05: event.subtype = 'lyrics'; event.text = stream.read(length); return event; case 0x06: event.subtype = 'marker'; event.text = stream.read(length); return event; case 0x07: event.subtype = 'cuePoint'; event.text = stream.read(length); return event; case 0x20: event.subtype = 'midiChannelPrefix'; if (length != 1) throw "Expected length for midiChannelPrefix event is 1, got " + length; event.channel = stream.readInt8(); return event; case 0x2f: event.subtype = 'endOfTrack'; if (length != 0) throw "Expected length for endOfTrack event is 0, got " + length; return event; case 0x51: event.subtype = 'setTempo'; if (length != 3) throw "Expected length for setTempo event is 3, got " + length; event.microsecondsPerBeat = ( (stream.readInt8() << 16) + (stream.readInt8() << 8) + stream.readInt8() ) return event; case 0x54: event.subtype = 'smpteOffset'; if (length != 5) throw "Expected length for smpteOffset event is 5, got " + length; var hourByte = stream.readInt8(); event.frameRate = { 0x00: 24, 0x20: 25, 0x40: 29, 0x60: 30 }[hourByte & 0x60]; event.hour = hourByte & 0x1f; event.min = stream.readInt8(); event.sec = stream.readInt8(); event.frame = stream.readInt8(); event.subframe = stream.readInt8(); return event; case 0x58: event.subtype = 'timeSignature'; if (length != 4) throw "Expected length for timeSignature event is 4, got " + length; event.numerator = stream.readInt8(); event.denominator = Math.pow(2, stream.readInt8()); event.metronome = stream.readInt8(); event.thirtyseconds = stream.readInt8(); return event; case 0x59: event.subtype = 'keySignature'; if (length != 2) throw "Expected length for keySignature event is 2, got " + length; event.key = stream.readInt8(true); event.scale = stream.readInt8(); return event; case 0x7f: event.subtype = 'sequencerSpecific'; event.data = stream.read(length); return event; default: // console.log("Unrecognised meta event subtype: " + subtypeByte); event.subtype = 'unknown' event.data = stream.read(length); return event; } event.data = stream.read(length); return event; } else if (eventTypeByte == 0xf0) { event.type = 'sysEx'; var length = stream.readVarInt(); event.data = stream.read(length); return event; } else if (eventTypeByte == 0xf7) { event.type = 'dividedSysEx'; var length = stream.readVarInt(); event.data = stream.read(length); return event; } else { throw "Unrecognised MIDI event type byte: " + eventTypeByte; } } else { /* channel event */ var param1; if ((eventTypeByte & 0x80) == 0) { /* running status - reuse lastEventTypeByte as the event type. eventTypeByte is actually the first parameter */ param1 = eventTypeByte; eventTypeByte = lastEventTypeByte; } else { param1 = stream.readInt8(); lastEventTypeByte = eventTypeByte; } var eventType = eventTypeByte >> 4; event.channel = eventTypeByte & 0x0f; event.type = 'channel'; switch (eventType) { case 0x08: event.subtype = 'noteOff'; event.noteNumber = param1; event.velocity = stream.readInt8(); return event; case 0x09: event.noteNumber = param1; event.velocity = stream.readInt8(); if (event.velocity == 0) { event.subtype = 'noteOff'; } else { event.subtype = 'noteOn'; } return event; case 0x0a: event.subtype = 'noteAftertouch'; event.noteNumber = param1; event.amount = stream.readInt8(); return event; case 0x0b: event.subtype = 'controller'; event.controllerType = param1; event.value = stream.readInt8(); return event; case 0x0c: event.subtype = 'programChange'; event.programNumber = param1; return event; case 0x0d: event.subtype = 'channelAftertouch'; event.amount = param1; return event; case 0x0e: event.subtype = 'pitchBend'; event.value = param1 + (stream.readInt8() << 7); return event; default: throw "Unrecognised MIDI event type: " + eventType /* console.log("Unrecognised MIDI event type: " + eventType); stream.readInt8(); event.subtype = 'unknown'; return event; */ } } } stream = Stream(data); var headerChunk = readChunk(stream); if (headerChunk.id != 'MThd' || headerChunk.length != 6) { throw "Bad .mid file - header not found"; } var headerStream = Stream(headerChunk.data); var formatType = headerStream.readInt16(); var trackCount = headerStream.readInt16(); var timeDivision = headerStream.readInt16(); if (timeDivision & 0x8000) { throw "Expressing time division in SMTPE frames is not supported yet" } else { ticksPerBeat = timeDivision; } var header = { 'formatType': formatType, 'trackCount': trackCount, 'ticksPerBeat': ticksPerBeat } var tracks = []; for (var i = 0; i < header.trackCount; i++) { tracks[i] = []; var trackChunk = readChunk(stream); if (trackChunk.id != 'MTrk') { throw "Unexpected chunk - expected MTrk, got "+ trackChunk.id; } var trackStream = Stream(trackChunk.data); while (!trackStream.eof()) { var event = readEvent(trackStream); tracks[i].push(event); //console.log(event); } } return { 'header': header, 'tracks': tracks } } /******************************************************************************* * 5) replayer.js ******************************************************************************/ function Replayer(midiFile, synth) { var trackStates = []; var beatsPerMinute = 120; var ticksPerBeat = midiFile.header.ticksPerBeat; var channelCount = 16; for (var i = 0; i < midiFile.tracks.length; i++) { trackStates[i] = { 'nextEventIndex': 0, 'ticksToNextEvent': ( midiFile.tracks[i].length ? midiFile.tracks[i][0].deltaTime : null ) }; } function Channel() { var generatorsByNote = {}; var currentProgram = PianoProgram; function noteOn(note, velocity) { if (generatorsByNote[note] && !generatorsByNote[note].released) { /* playing same note before releasing the last one. BOO */ generatorsByNote[note].noteOff(); /* TODO: check whether we ought to be passing a velocity in */ } generator = currentProgram.createNote(note, velocity); synth.addGenerator(generator); generatorsByNote[note] = generator; } function noteOff(note, velocity) { if (generatorsByNote[note] && !generatorsByNote[note].released) { generatorsByNote[note].noteOff(velocity); } } function setProgram(programNumber) { currentProgram = PROGRAMS[programNumber] || PianoProgram; } return { 'noteOn': noteOn, 'noteOff': noteOff, 'setProgram': setProgram } } var channels = []; for (var i = 0; i < channelCount; i++) { channels[i] = Channel(); } var nextEventInfo; var samplesToNextEvent = 0; function getNextEvent() { var ticksToNextEvent = null; var nextEventTrack = null; var nextEventIndex = null; for (var i = 0; i < trackStates.length; i++) { if ( trackStates[i].ticksToNextEvent != null && (ticksToNextEvent == null || trackStates[i].ticksToNextEvent < ticksToNextEvent) ) { ticksToNextEvent = trackStates[i].ticksToNextEvent; nextEventTrack = i; nextEventIndex = trackStates[i].nextEventIndex; } } if (nextEventTrack != null) { /* consume event from that track */ var nextEvent = midiFile.tracks[nextEventTrack][nextEventIndex]; if (midiFile.tracks[nextEventTrack][nextEventIndex + 1]) { trackStates[nextEventTrack].ticksToNextEvent += midiFile.tracks[nextEventTrack][nextEventIndex + 1].deltaTime; } else { trackStates[nextEventTrack].ticksToNextEvent = null; } trackStates[nextEventTrack].nextEventIndex += 1; /* advance timings on all tracks by ticksToNextEvent */ for (var i = 0; i < trackStates.length; i++) { if (trackStates[i].ticksToNextEvent != null) { trackStates[i].ticksToNextEvent -= ticksToNextEvent } } nextEventInfo = { 'ticksToEvent': ticksToNextEvent, 'event': nextEvent, 'track': nextEventTrack } var beatsToNextEvent = ticksToNextEvent / ticksPerBeat; var secondsToNextEvent = beatsToNextEvent / (beatsPerMinute / 60); samplesToNextEvent += secondsToNextEvent * synth.sampleRate; } else { nextEventInfo = null; samplesToNextEvent = null; self.finished = true; } } getNextEvent(); function generate(samples) { var data = new Array(samples*2); var samplesRemaining = samples; var dataOffset = 0; while (true) { if (samplesToNextEvent != null && samplesToNextEvent <= samplesRemaining) { /* generate samplesToNextEvent samples, process event and repeat */ var samplesToGenerate = Math.ceil(samplesToNextEvent); if (samplesToGenerate > 0) { synth.generateIntoBuffer(samplesToGenerate, data, dataOffset); dataOffset += samplesToGenerate * 2; samplesRemaining -= samplesToGenerate; samplesToNextEvent -= samplesToGenerate; } handleEvent(); getNextEvent(); } else { /* generate samples to end of buffer */ if (samplesRemaining > 0) { synth.generateIntoBuffer(samplesRemaining, data, dataOffset); samplesToNextEvent -= samplesRemaining; } break; } } return data; } function handleEvent() { var event = nextEventInfo.event; switch (event.type) { case 'meta': switch (event.subtype) { case 'setTempo': beatsPerMinute = 60000000 / event.microsecondsPerBeat } break; case 'channel': switch (event.subtype) { case 'noteOn': channels[event.channel].noteOn(event.noteNumber, event.velocity); break; case 'noteOff': channels[event.channel].noteOff(event.noteNumber, event.velocity); break; case 'programChange': //console.log('program change to ' + event.programNumber); channels[event.channel].setProgram(event.programNumber); break; } break; } } function replay(audio) { console.log('replay'); audio.write(generate(44100)); setTimeout(function() {replay(audio)}, 10); } var self = { 'replay': replay, 'generate': generate, 'finished': false } return self; } /******************************************************************************* * 6) stream.js ******************************************************************************/ /** * Wrapper for accessing strings through sequential reads. */ function Stream(str) { var position = 0; function read(length) { var result = str.substr(position, length); position += length; return result; } /* read a big-endian 32-bit integer */ function readInt32() { var result = ( (str.charCodeAt(position) << 24) + (str.charCodeAt(position + 1) << 16) + (str.charCodeAt(position + 2) << 8) + str.charCodeAt(position + 3)); position += 4; return result; } /* read a big-endian 16-bit integer */ function readInt16() { var result = ( (str.charCodeAt(position) << 8) + str.charCodeAt(position + 1)); position += 2; return result; } /* read an 8-bit integer */ function readInt8(signed) { var result = str.charCodeAt(position); if (signed && result > 127) result -= 256; position += 1; return result; } function eof() { return position >= str.length; } /* read a MIDI-style variable-length integer (big-endian value in groups of 7 bits, with top bit set to signify that another byte follows) */ function readVarInt() { var result = 0; while (true) { var b = readInt8(); if (b & 0x80) { result += (b & 0x7f); result <<= 7; } else { /* b is the last byte */ return result + b; } } } return { 'eof': eof, 'read': read, 'readInt32': readInt32, 'readInt16': readInt16, 'readInt8': readInt8, 'readVarInt': readVarInt } } /******************************************************************************* * 7) synth.js ******************************************************************************/ function SineGenerator(freq) { var self = {'alive': true}; var period = sampleRate / freq; var t = 0; self.generate = function(buf, offset, count) { for (; count; count--) { var phase = t / period; var result = Math.sin(phase * 2 * Math.PI); buf[offset++] += result; buf[offset++] += result; t++; } } return self; } function SquareGenerator(freq, phase) { var self = {'alive': true}; var period = sampleRate / freq; var t = 0; self.generate = function(buf, offset, count) { for (; count; count--) { var result = ( (t / period) % 1 > phase ? 1 : -1); buf[offset++] += result; buf[offset++] += result; t++; } } return self; } function ADSRGenerator(child, attackAmplitude, sustainAmplitude, attackTimeS, decayTimeS, releaseTimeS) { var self = {'alive': true} var attackTime = sampleRate * attackTimeS; var decayTime = sampleRate * (attackTimeS + decayTimeS); var decayRate = (attackAmplitude - sustainAmplitude) / (decayTime - attackTime); var releaseTime = null; /* not known yet */ var endTime = null; /* not known yet */ var releaseRate = sustainAmplitude / (sampleRate * releaseTimeS); var t = 0; self.noteOff = function() { if (self.released) return; releaseTime = t; self.released = true; endTime = releaseTime + sampleRate * releaseTimeS; } self.generate = function(buf, offset, count) { if (!self.alive) return; var input = new Array(count * 2); for (var i = 0; i < count*2; i++) { input[i] = 0; } child.generate(input, 0, count); childOffset = 0; while(count) { if (releaseTime != null) { if (t < endTime) { /* release */ while(count && t < endTime) { var ampl = sustainAmplitude - releaseRate * (t - releaseTime); buf[offset++] += input[childOffset++] * ampl; buf[offset++] += input[childOffset++] * ampl; t++; count--; } } else { /* dead */ self.alive = false; return; } } else if (t < attackTime) { /* attack */ while(count && t < attackTime) { var ampl = attackAmplitude * t / attackTime; buf[offset++] += input[childOffset++] * ampl; buf[offset++] += input[childOffset++] * ampl; t++; count--; } } else if (t < decayTime) { /* decay */ while(count && t < decayTime) { var ampl = attackAmplitude - decayRate * (t - attackTime); buf[offset++] += input[childOffset++] * ampl; buf[offset++] += input[childOffset++] * ampl; t++; count--; } } else { /* sustain */ while(count) { buf[offset++] += input[childOffset++] * sustainAmplitude; buf[offset++] += input[childOffset++] * sustainAmplitude; t++; count--; } } } } return self; } function midiToFrequency(note) { return 440 * Math.pow(2, (note-69)/12); } PianoProgram = { 'attackAmplitude': 0.2, 'sustainAmplitude': 0.1, 'attackTime': 0.02, 'decayTime': 0.3, 'releaseTime': 0.02, 'createNote': function(note, velocity) { var frequency = midiToFrequency(note); return ADSRGenerator( SineGenerator(frequency), this.attackAmplitude * (velocity / 128), this.sustainAmplitude * (velocity / 128), this.attackTime, this.decayTime, this.releaseTime ); } } StringProgram = { 'createNote': function(note, velocity) { var frequency = midiToFrequency(note); return ADSRGenerator( SineGenerator(frequency), 0.5 * (velocity / 128), 0.2 * (velocity / 128), 0.4, 0.8, 0.4 ); } } PROGRAMS = { 41: StringProgram, 42: StringProgram, 43: StringProgram, 44: StringProgram, 45: StringProgram, 46: StringProgram, 47: StringProgram, 49: StringProgram, 50: StringProgram }; function Synth(sampleRate) { var generators = []; function addGenerator(generator) { generators.push(generator); } function generate(samples) { var data = new Array(samples*2); generateIntoBuffer(samples, data, 0); return data; } function generateIntoBuffer(samplesToGenerate, buffer, offset) { for (var i = offset; i < offset + samplesToGenerate * 2; i++) { buffer[i] = 0; } for (var i = generators.length - 1; i >= 0; i--) { generators[i].generate(buffer, offset, samplesToGenerate); if (!generators[i].alive) generators.splice(i, 1); } } return { 'sampleRate': sampleRate, 'addGenerator': addGenerator, 'generate': generate, 'generateIntoBuffer': generateIntoBuffer } } } // end of: if (typeof (MidiPlayer) == 'undefined')
fosscellcet/drishticryptex2017
assets/js/midi.js
JavaScript
mit
40,433
import uglify from 'rollup-plugin-uglify' import buble from 'rollup-plugin-buble' export default { entry: 'js/index.js', dest: 'public/bundle.js', format: 'iife', plugins: [buble(), uglify()], }
brbrakus/adomis
rollup.config.js
JavaScript
mit
204
function filterSinceSync(d) { var isValid = typeof d === 'number' || d instanceof Number || d instanceof Date; if (!isValid) { throw new Error('expected since option to be a date or a number'); } return file.stat && file.stat.mtime > d; }; module.exports = filterSinceSync;
xareelee/gulp-on-rx
src/filterSinceSync.js
JavaScript
mit
300
var expect = require('chai').expect; var sinon = require('sinon'); var ColumnShifter = require('component/grid/projection/column-shifter'); var Base = require('component/grid/projection/base'); var Response = require('component/grid/model/response'); describe('projection ColumnShifter', function () { it('update should run normal', function () { var model = new ColumnShifter(); var originalData = new Base(); originalData.data = new Response({ columns: { name: { name: 'hello', property: 'name' }, id: { id: '007', property: 'id' }, }, select: ['name', 'id'], }); originalData.pipe(model); expect(model.data.get('select')[0]).to.be.equal('column.skip.less'); expect(model.data.get('select')[3]).to.be.equal('column.skip.more'); }); it('thClick should run normal', function () { var model = new ColumnShifter(); model.get = sinon.stub().returns(1); sinon.spy(model, 'set'); model.thClick({}, { column: { $metadata: { enabled: true } }, property: 'column.skip.less', }); expect(model.set.calledWith({ 'column.skip': 0 })).to.be.true; }); });
steins024/projection-grid
spec/unit/column-shifter-spec.js
JavaScript
mit
1,152
'use strict'; let TimeseriesShowController = function($scope, $controller, $timeout, NpolarApiSecurity, NpolarTranslate, npdcAppConfig, Timeseries, TimeseriesModel, TimeseriesCitation, google, Sparkline) { 'ngInject'; let ctrl = this; ctrl.authors = (t) => { return t.authors.map(a => { return { name: a['@id']}; }); }; // @todo NpolarLinkModel? ctrl.collection_link = (links,hreflang='en') => { return links.find(l => l.rel === 'collection' && l.hreflang === hreflang); }; $controller("NpolarBaseController", {$scope: $scope}); $scope.resource = Timeseries; let chartElement = Sparkline.getElement(); if (chartElement) { chartElement.innerHTML = ''; } $scope.show().$promise.then(timeseries => { $scope.data = timeseries.data; $scope.data_not_null = timeseries.data.filter(t => t.value !== undefined); // Create facet-style links with counts to timeseries with all of the same keywords... if (!$scope.keywords && timeseries.keywords && timeseries.keywords.length > 0) { $scope.keywords = {}; let keywords = TimeseriesModel.keywords(timeseries); ['en', 'no'].forEach(l => { let k = keywords[l]; let href = $scope.resource.uiBase+`?filter-keywords.@value=${ k.join(',') }`; let link = { keywords: keywords[l], count: 0, href }; Timeseries.feed({"filter-keywords.@value": k.join(','), facets: 'keywords,species,locations.placename', limit: 0}).$promise.then((r) => { link.count = r.feed.opensearch.totalResults; // All keywords // Count for all keywords + species if (timeseries.species) { let f = r.feed.facets.find(f => f.hasOwnProperty('species')); if (f && f.species) { let c = f.species.find(f => f.term === timeseries.species); link.count_keywords_and_species = c.count; } } // Count for first all keywords + placename[0] if (timeseries.locations && timeseries.locations.length > 0) { let f = r.feed.facets.find(f => f.hasOwnProperty('locations.placename')); if (f && f['locations.placename']) { let c = f['locations.placename'].find(f => f.term === timeseries.locations[0].placename); link.count_keywords_and_placename = c.count; } } $scope.keywords[l] = link; }, (e) => { $scope.keywords[l] = link; }); }); } $scope.citation = (t) => { if (!t) { return; } return TimeseriesCitation.citation(timeseries); }; // Create graph if ($scope.data && $scope.data.length > 0) { $timeout(function(){ $scope.sparkline = true; let sparkline = timeseries.data.map(d => [d.value]); google.setOnLoadCallback(Sparkline.draw(sparkline)); }); } // Count number of timeseries belonging to the same collection if (timeseries.links && timeseries.links.length > 0) { ['en', 'nb'].forEach(l => { if (!$scope.collection || !$scope.collection[l]) { let link = ctrl.collection_link(timeseries.links, l); if (link && link.href) { let query = {"filter-links.href": link.href, limit: 0 }; Timeseries.feed(query).$promise.then(r => { if (!$scope.collection) { $scope.collection = {}; } $scope.collection[l] = { href: $scope.resource.uiBase+`?filter-links.href=${link.href}`, title: link.title, count: r.feed.opensearch.totalResults }; }); } } }); } }); }; module.exports = TimeseriesShowController;
npolar/npdc-indicator
src/indicator-timeseries/TimeseriesShowController.js
JavaScript
mit
3,741
var should = require('should'); var npg = require('../core/npg').npg; var config = require('./_test_config_npg'); var request = ({body: {phrase: "111"}}); describe('NPG w/ config', function () { it('should using fixed key', function () { config.useFixedKey.should.be.ok; }); it('should return correct answer', function () { npg("111",config.key1,config.key2).should.eql({ md5: '747207ac', b64: '!QWOwMWY3AjM3QzN' }) }) });
nykma/npg
test/config-test.js
JavaScript
mit
440
/** * LICENSE : MIT */ "use strict"; (function (mod) { if (typeof exports == "object" && typeof module == "object") { mod(require("codemirror")); } else if (typeof define == "function" && define.amd) { define(["codemirror"], mod); } else { mod(CodeMirror); } })(function (CodeMirror) { "use strict"; CodeMirror.commands.scrollSelectionToCenter = function (cm) { if (cm.getOption("disableInput")) { return CodeMirror.Pass; } var cursor = cm.getCursor('anchor'); var top = cm.charCoords({line: cursor.line, ch: 0}, "local").top; var halfWindowHeight = cm.getWrapperElement().offsetHeight / 2; var scrollTo = Math.round((top - halfWindowHeight)); cm.scrollTo(null, scrollTo); }; CodeMirror.defineOption("typewriterScrolling", false, function (cm, val, old) { if (old && old != CodeMirror.Init) { cm.off("changes", onChanges); } if (val) { cm.on("changes", onChanges); } }); function onChanges(cm, changes) { if (cm.getSelection().length !== 0) { return; } for (var i = 0, len = changes.length; i < len; i++) { var each = changes[i]; if (each.origin === '+input' || each.origin === '+delete') { cm.execCommand("scrollSelectionToCenter"); return; } } } });
azu/codemirror-typewriter-scrolling
typewriter-scrolling.js
JavaScript
mit
1,466
/** * @name Evemit * @description Minimal and fast JavaScript event emitter for Node.js and front-end. * @author Nicolas Tallefourtane <[email protected]> * @link https://github.com/Nicolab/evemit * @license MIT https://github.com/Nicolab/evemit/blob/master/LICENSE */ ;(function() { 'use strict'; /** * Evemit * * @constructor * @api public */ function Evemit() { this.events = {}; } /** * Register a new event listener for a given event. * * @param {string} event Event name. * @param {function} fn Callback function (listener). * @param {*} [context] Context for function execution. * @return {Evemit} Current instance. * @api public */ Evemit.prototype.on = function(event, fn, context) { if (!this.events[event]) { this.events[event] = []; } if(context) { fn._E_ctx = context; } this.events[event].push(fn); return this; }; /** * Add an event listener that's only called once. * * @param {string} event Event name. * @param {function} fn Callback function (listener). * @param {*} [context] Context for function execution. * @return {Evemit} Current instance. * @api public */ Evemit.prototype.once = function(event, fn, context) { fn._E_once = true; return this.on(event, fn, context); }; /** * Emit an event to all registered event listeners. * * @param {string} event Event name. * @param {*} [...arg] One or more arguments to pass to the listeners. * @return {bool} Indication, `true` if at least one listener was executed, * otherwise returns `false`. * @api public */ Evemit.prototype.emit = function(event, arg1, arg2, arg3, arg4) { var fn, evs, args, aLn; if(!this.events[event]) { return false; } args = Array.prototype.slice.call(arguments, 1); aLn = args.length; evs = this.events[event]; for(var i = 0, ln = evs.length; i < ln; i++) { fn = evs[i]; if (fn._E_once) { this.off(event, fn); } // Function.apply() is a bit slower, so try to do without switch (aLn) { case 0: fn.call(fn._E_ctx); break; case 1: fn.call(fn._E_ctx, arg1); break; case 2: fn.call(fn._E_ctx, arg1, arg2); break; case 3: fn.call(fn._E_ctx, arg1, arg2, arg3); break; case 4: fn.call(fn._E_ctx, arg1, arg2, arg3, arg4); break; default: fn.apply(fn._E_ctx, args); } } return true; }; /** * Remove event listeners. * * @param {string} event The event to remove. * @param {function} fn The listener that we need to find. * @return {Evemit} Current instance. * @api public */ Evemit.prototype.off = function(event, fn) { if (!this.events[event]) { return this; } for (var i = 0, ln = this.events[event].length; i < ln; i++) { if (this.events[event][i] === fn) { this.events[event][i] = null; delete this.events[event][i]; } } // re-index this.events[event] = this.events[event].filter(function(ltns) { return typeof ltns !== 'undefined'; }); return this; }; /** * Get a list of assigned event listeners. * * @param {string} [event] The events that should be listed. * If not provided, all listeners are returned. * Use the property `Evemit.events` if you want to get an object like * ``` * {event1: [array of listeners], event2: [array of listeners], ...} * ``` * * @return {array} * @api public */ Evemit.prototype.listeners = function(event) { var evs, ltns; if(event) { return this.events[event] || []; } evs = this.events; ltns = []; for(var ev in evs) { ltns = ltns.concat(evs[ev].valueOf()); } return ltns; }; /** * Expose Evemit * @type {Evemit} */ if(typeof module !== 'undefined' && module.exports) { module.exports = Evemit; } else { window.Evemit = Evemit; } })();
Nicolab/evemit
evemit.js
JavaScript
mit
4,182
(function() { //########################################################################################################### var CND, Multimix, alert, badge, debug, dec, decG, echo, help, hex, hexG, info, isa, log, name, nameO, nameOG, rpr, type_of, types, urge, validate, warn, whisper; CND = require('cnd'); rpr = CND.rpr.bind(CND); badge = 'NCR'; log = CND.get_logger('plain', badge); info = CND.get_logger('info', badge); alert = CND.get_logger('alert', badge); debug = CND.get_logger('debug', badge); warn = CND.get_logger('warn', badge); urge = CND.get_logger('urge', badge); whisper = CND.get_logger('whisper', badge); help = CND.get_logger('help', badge); echo = CND.echo.bind(CND); //........................................................................................................... this._input_default = 'plain'; // @_input_default = 'ncr' // @_input_default = 'xncr' //........................................................................................................... Multimix = require('multimix006modern'); this.cloak = (require('./cloak')).new(); this._aggregate = null; this._ISL = require('interskiplist'); this.unicode_isl = (() => { var R, i, interval, len, ref; R = this._ISL.new(); this._ISL.add_index(R, 'rsg'); this._ISL.add_index(R, 'tag'); ref = require('../data/unicode-9.0.0-intervals.json'); for (i = 0, len = ref.length; i < len; i++) { interval = ref[i]; this._ISL.add(R, interval); } this._aggregate = this._ISL.aggregate.use(R); return R; })(); types = require('./types'); ({isa, validate, type_of} = types.export()); //=========================================================================================================== //----------------------------------------------------------------------------------------------------------- this._copy_library = function(input_default = 'plain') { /* TAINT makeshift method until we have something better; refer to `tests[ "(v2) create derivatives of NCR (2)" ]` for example usage */ var R, mix, reducers; reducers = { fallback: 'assign', fields: { unicode_isl: (values) => { return this._ISL.copy(this.unicode_isl); } } }; //......................................................................................................... mix = (require('multimix006modern')).mix.use(reducers); R = mix(this, { _input_default: input_default }); R._aggregate = R._ISL.aggregate.use(R.unicode_isl); //......................................................................................................... return R; }; //=========================================================================================================== // CLOAK //----------------------------------------------------------------------------------------------------------- this._XXX_escape_chrs = (text) => { return this.cloak.backslashed.hide(this.cloak.hide(text)); }; this._XXX_unescape_escape_chrs = (text) => { return this.cloak.reveal(this.cloak.backslashed.reveal(text)); }; this._XXX_remove_escaping_backslashes = (text) => { return this.cloak.backslashed.remove(text); }; //=========================================================================================================== // SPLIT TEXT INTO CHARACTERS //----------------------------------------------------------------------------------------------------------- this.chrs_from_esc_text = function(text, settings) { var R, chrs, i, is_escaped, len, part, parts; R = []; parts = text.split(/\\([^.])/); is_escaped = true; for (i = 0, len = parts.length; i < len; i++) { part = parts[i]; if (is_escaped = !is_escaped) { /* almost */ R.push(part); continue; } chrs = this.chrs_from_text(part, settings); if (chrs[chrs.length - 1] === '\\') { chrs.pop(); } R.splice(R.length, 0, ...chrs); } //......................................................................................................... return R; }; //----------------------------------------------------------------------------------------------------------- this.chrs_from_text = function(text, settings) { var input_mode, ref, splitter; if (text.length === 0) { return []; } //......................................................................................................... switch (input_mode = (ref = settings != null ? settings['input'] : void 0) != null ? ref : this._input_default) { case 'plain': splitter = this._plain_splitter; break; case 'ncr': splitter = this._ncr_splitter; break; case 'xncr': splitter = this._xncr_splitter; break; default: throw new Error(`unknown input mode: ${rpr(input_mode)}`); } //......................................................................................................... return (text.split(splitter)).filter(function(element, idx) { return element.length !== 0; }); }; //----------------------------------------------------------------------------------------------------------- this._new_chunk = function(csg, rsg, chrs) { var R; R = { '~isa': 'NCR/chunk', 'csg': csg, 'rsg': rsg, // 'chrs': chrs 'text': chrs.join('') }; //......................................................................................................... return R; }; //----------------------------------------------------------------------------------------------------------- this.chunks_from_text = function(text, settings) { /* Given a `text` and `settings` (of which `csg` is irrelevant here), return a list of `NCR/chunk` objects (as returned by `NCR._new_chunk`) that describes stretches of characters with codepoints in the same 'range' (Unicode block). */ var R, chr, chrs, csg, description, i, last_csg, last_rsg, len, output_mode, ref, ref1, rsg, transform_output; R = []; if (text.length === 0) { return R; } last_csg = 'u'; last_rsg = null; chrs = []; //......................................................................................................... switch (output_mode = (ref = settings != null ? settings['output'] : void 0) != null ? ref : this._input_default) { case 'plain': transform_output = function(chr) { return chr; }; break; case 'html': transform_output = function(chr) { switch (chr) { case '&': return '&amp;'; case '<': return '&lt;'; case '>': return '&gt;'; default: return chr; } }; break; default: throw new Error(`unknown output mode: ${rpr(output_mode)}`); } ref1 = this.chrs_from_text(text, settings); //......................................................................................................... for (i = 0, len = ref1.length; i < len; i++) { chr = ref1[i]; description = this.analyze(chr, settings); ({csg, rsg} = description); chr = description[csg === 'u' ? 'chr' : 'ncr']; if (rsg !== last_rsg) { if (chrs.length > 0) { R.push(this._new_chunk(last_csg, last_rsg, chrs)); } last_csg = csg; last_rsg = rsg; chrs = []; } //....................................................................................................... chrs.push(transform_output(chr)); } if (chrs.length > 0) { //......................................................................................................... R.push(this._new_chunk(last_csg, last_rsg, chrs)); } return R; }; //----------------------------------------------------------------------------------------------------------- this.html_from_text = function(text, settings) { var R, chunk, chunks, i, input_mode, len, ref, ref1; R = []; //......................................................................................................... input_mode = (ref = settings != null ? settings['input'] : void 0) != null ? ref : this._input_default; chunks = this.chunks_from_text(text, { input: input_mode, output: 'html' }); for (i = 0, len = chunks.length; i < len; i++) { chunk = chunks[i]; R.push(`<span class="${(ref1 = chunk['rsg']) != null ? ref1 : chunk['csg']}">${chunk['text']}</span>`); } //......................................................................................................... return R.join(''); }; //=========================================================================================================== // CONVERTING TO CID //----------------------------------------------------------------------------------------------------------- this.cid_from_chr = function(chr, settings) { var input_mode, ref; input_mode = (ref = settings != null ? settings['input'] : void 0) != null ? ref : this._input_default; return (this._chr_csg_cid_from_chr(chr, input_mode))[2]; }; //----------------------------------------------------------------------------------------------------------- this.csg_cid_from_chr = function(chr, settings) { var input_mode, ref; input_mode = (ref = settings != null ? settings['input'] : void 0) != null ? ref : this._input_default; return (this._chr_csg_cid_from_chr(chr, input_mode)).slice(1); }; //----------------------------------------------------------------------------------------------------------- this._chr_csg_cid_from_chr = function(chr, input_mode) { /* thx to http://perldoc.perl.org/Encode/Unicode.html */ var cid, cid_dec, cid_hex, csg, first_chr, hi, lo, match, matcher; if (chr.length === 0) { /* Given a text with one or more characters, return the first character, its CSG, and its CID (as a non-negative integer). Additionally, an input mode may be given as either `plain`, `ncr`, or `xncr`. */ //......................................................................................................... throw new Error("unable to obtain CID from empty string"); } //......................................................................................................... if (input_mode == null) { input_mode = 'plain'; } switch (input_mode) { case 'plain': matcher = this._first_chr_matcher_plain; break; case 'ncr': matcher = this._first_chr_matcher_ncr; break; case 'xncr': matcher = this._first_chr_matcher_xncr; break; default: throw new Error(`unknown input mode: ${rpr(input_mode)}`); } //......................................................................................................... match = chr.match(matcher); if (match == null) { throw new Error(`illegal character sequence in ${rpr(chr)}`); } first_chr = match[0]; //......................................................................................................... switch (first_chr.length) { //....................................................................................................... case 1: return [first_chr, 'u', first_chr.charCodeAt(0)]; //....................................................................................................... case 2: hi = first_chr.charCodeAt(0); lo = first_chr.charCodeAt(1); cid = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000; return [first_chr, 'u', cid]; default: //....................................................................................................... [chr, csg, cid_hex, cid_dec] = match; cid = cid_hex != null ? parseInt(cid_hex, 16) : parseInt(cid_dec, 10); if (csg.length === 0) { csg = 'u'; } return [first_chr, csg, cid]; } }; // #----------------------------------------------------------------------------------------------------------- // @cid_from_ncr = ( ) -> // #----------------------------------------------------------------------------------------------------------- // @cid_from_xncr = ( ) -> // #----------------------------------------------------------------------------------------------------------- // @cid_from_fncr = ( ) -> //=========================================================================================================== // CONVERTING FROM CID &c //----------------------------------------------------------------------------------------------------------- this.as_csg = function(cid_hint, O) { return (this._csg_cid_from_hint(cid_hint, O))[0]; }; this.as_cid = function(cid_hint, O) { return (this._csg_cid_from_hint(cid_hint, O))[1]; }; //........................................................................................................... this.as_chr = function(cid_hint, O) { return this._as_chr.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; this.as_uchr = function(cid_hint, O) { return this._as_uchr.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; this.as_fncr = function(cid_hint, O) { return this._as_fncr.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; this.as_sfncr = function(cid_hint, O) { return this._as_sfncr.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; this.as_xncr = function(cid_hint, O) { return this._as_xncr.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; this.as_ncr = function(cid_hint, O) { return this._as_xncr.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; this.as_rsg = function(cid_hint, O) { return this._as_rsg.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; this.as_range_name = function(cid_hint, O) { return this._as_range_name.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; //........................................................................................................... this.analyze = function(cid_hint, O) { return this._analyze.apply(this, this._csg_cid_from_hint(cid_hint, O)); }; //----------------------------------------------------------------------------------------------------------- this._analyze = function(csg, cid) { var R, chr, ncr, xncr; if (csg === 'u') { chr = this._unicode_chr_from_cid(cid); ncr = xncr = this._as_xncr(csg, cid); } else { chr = this._as_xncr(csg, cid); xncr = this._as_xncr(csg, cid); ncr = this._as_xncr('u', cid); } //......................................................................................................... R = { '~isa': 'NCR/info', 'chr': chr, 'uchr': this._unicode_chr_from_cid(cid), 'csg': csg, 'cid': cid, 'fncr': this._as_fncr(csg, cid), 'sfncr': this._as_sfncr(csg, cid), 'ncr': ncr, 'xncr': xncr, 'rsg': this._as_rsg(csg, cid) }; //......................................................................................................... return R; }; //----------------------------------------------------------------------------------------------------------- this._as_chr = function(csg, cid) { if (csg === 'u') { return this._unicode_chr_from_cid(cid); } return (this._analyze(csg, cid))['chr']; }; //----------------------------------------------------------------------------------------------------------- this._as_uchr = function(csg, cid) { return this._unicode_chr_from_cid(cid); }; //----------------------------------------------------------------------------------------------------------- this._unicode_chr_from_cid = function(cid) { if (!((0x000000 <= cid && cid <= 0x10ffff))) { return null; } return String.fromCodePoint(cid); }; // ### thx to http://perldoc.perl.org/Encode/Unicode.html ### // hi = ( Math.floor ( cid - 0x10000 ) / 0x400 ) + 0xD800 // lo = ( cid - 0x10000 ) % 0x400 + 0xDC00 // return ( String.fromCharCode hi ) + ( String.fromCharCode lo ) //----------------------------------------------------------------------------------------------------------- this._as_fncr = function(csg, cid) { var ref, rsg; rsg = (ref = this._as_rsg(csg, cid)) != null ? ref : csg; return `${rsg}-${cid.toString(16)}`; }; //----------------------------------------------------------------------------------------------------------- this._as_sfncr = function(csg, cid) { return `${csg}-${cid.toString(16)}`; }; //----------------------------------------------------------------------------------------------------------- this._as_xncr = function(csg, cid) { if (csg === 'u' || (csg == null)) { csg = ''; } return `&${csg}#x${cid.toString(16)};`; }; //----------------------------------------------------------------------------------------------------------- this._as_rsg = function(csg, cid) { var ref; if (csg !== 'u') { return csg; } return (ref = (this._aggregate(cid))['rsg']) != null ? ref : csg; }; //----------------------------------------------------------------------------------------------------------- this._as_range_name = function(csg, cid) { var ref; if (csg !== 'u') { return this._as_rsg(csg, cid); } return (ref = (this._aggregate(cid))['block']) != null ? ref : this._as_rsg(csg, cid); }; //=========================================================================================================== // ANALYZE ARGUMENTS //----------------------------------------------------------------------------------------------------------- this._csg_cid_from_hint = function(cid_hint, settings) { var cid, csg, csg_of_cid_hint, csg_of_options, input_mode, type; /* This helper is used to derive the correct CSG and CID from arguments as accepted by the `as_*` family of methods, such as `NCR.as_fncr`, `NCR.as_rsg` and so on; its output may be directly applied to the respective namesake private method (`NCR._as_fncr`, `NCR._as_rsg` and so on). The method arguments should obey the following rules: * Methods may be called with one or two arguments; the first is known as the 'CID hint', the second as 'settings'. * The CID hint may be a number or a text; if it is a number, it is understood as a CID; if it is a text, its interpretation is subject to the `settings[ 'input' ]` setting. * Options must be an object with the optional members `input` and `csg`. * `settings[ 'input' ]` is *only* observed if the CID hint is a text; it governs which kinds of character references are recognized in the text. `input` may be one of `plain`, `ncr`, or `xncr`; it defaults to `plain` (no character references will be recognized). * `settings[ 'csg' ]` sets the character set sigil. If `csg` is set in the settings, then it will override whatever the outcome of `NCR.csg_cid_from_chr` w.r.t. CSG is—in other words, if you call `NCR.as_sfncr '&jzr#xe100', input: 'xncr', csg: 'u'`, you will get `u-e100`, with the numerically equivalent codepoint from the `u` (Unicode) character set. * Before CSG and CID are returned, they will be validated for plausibility. */ //......................................................................................................... switch (type = type_of(settings)) { case 'null': case 'undefined': csg_of_options = null; input_mode = null; break; case 'object': csg_of_options = settings['csg']; input_mode = settings['input']; break; default: throw new Error(`expected an object as second argument, got a ${type}`); } //......................................................................................................... switch (type = type_of(cid_hint)) { case 'float': csg_of_cid_hint = null; cid = cid_hint; break; case 'text': [csg_of_cid_hint, cid] = this.csg_cid_from_chr(cid_hint, { input: input_mode }); break; default: throw new Error(`expected a text or a number as first argument, got a ${type}`); } //......................................................................................................... if (csg_of_options != null) { csg = csg_of_options; } else if (csg_of_cid_hint != null) { csg = csg_of_cid_hint; } else { csg = 'u'; } //......................................................................................................... // @validate_is_csg csg this.validate_cid(csg, cid); return [csg, cid]; }; //=========================================================================================================== // PATTERNS //----------------------------------------------------------------------------------------------------------- // G: grouped // O: optional name = /(?:[a-z][a-z0-9]*)/.source; // nameG = ( /// ( (?: [a-z][a-z0-9]* ) | ) /// ).source nameO = /(?:(?:[a-z][a-z0-9]*)|)/.source; nameOG = /((?:[a-z][a-z0-9]*)|)/.source; hex = /(?:x[a-fA-F0-9]+)/.source; hexG = /(?:x([a-fA-F0-9]+))/.source; dec = /(?:[0-9]+)/.source; decG = /(?:([0-9]+))/.source; //........................................................................................................... this._csg_matcher = RegExp(`^${name}$`); this._ncr_matcher = RegExp(`(?:&\\#(?:${hex}|${dec});)`); this._xncr_matcher = RegExp(`(?:&${nameO}\\#(?:${hex}|${dec});)`); this._ncr_csg_cid_matcher = RegExp(`(?:&()\\#(?:${hexG}|${decG});)`); this._xncr_csg_cid_matcher = RegExp(`(?:&${nameOG}\\#(?:${hexG}|${decG});)`); //........................................................................................................... /* Matchers for surrogate sequences and non-surrogate, 'ordinary' characters: */ this._surrogate_matcher = /(?:[\ud800-\udbff][\udc00-\udfff])/; this._nonsurrogate_matcher = /[^\ud800-\udbff\udc00-\udfff]/; //........................................................................................................... /* Matchers for the first character of a string, in three modes (`plain`, `ncr`, `xncr`): */ this._first_chr_matcher_plain = RegExp(`^(?:${this._surrogate_matcher.source}|${this._nonsurrogate_matcher.source})`); this._first_chr_matcher_ncr = RegExp(`^(?:${this._surrogate_matcher.source}|${this._ncr_csg_cid_matcher.source}|${this._nonsurrogate_matcher.source})`); this._first_chr_matcher_xncr = RegExp(`^(?:${this._surrogate_matcher.source}|${this._xncr_csg_cid_matcher.source}|${this._nonsurrogate_matcher.source})`); //........................................................................................................... this._plain_splitter = RegExp(`(${this._surrogate_matcher.source}|${this._nonsurrogate_matcher.source})`); this._ncr_splitter = RegExp(`(${this._ncr_matcher.source}|${this._surrogate_matcher.source}|${this._nonsurrogate_matcher.source})`); this._xncr_splitter = RegExp(`(${this._xncr_matcher.source}|${this._surrogate_matcher.source}|${this._nonsurrogate_matcher.source})`); // #----------------------------------------------------------------------------------------------------------- // @cid_range_from_rsg = ( rsg ) -> // # [ csg, ... ] = rsg.split '-' // unless ( R = @_ranges_by_rsg[ rsg ] )? // throw new Error "unknown RSG: #{rpr rsg}" // return R // #----------------------------------------------------------------------------------------------------------- // @validate_is_csg = ( x ) -> // validate.text x // throw new Error "not a valid CSG: #{rpr x}" unless ( x.match @_csg_matcher )? // throw new Error "unknown CSG: #{rpr x}" unless @_names_and_ranges_by_csg[ x ]? // return null //----------------------------------------------------------------------------------------------------------- this.validate_cid = function(csg, cid) { validate.float(cid); if (cid !== Math.floor(cid)) { throw new Error(`expected an integer, got ${cid}`); } if (!(cid >= 0)) { throw new Error(`expected a positive integer, got ${cid}`); } if ((csg === 'u') && !((0x000000 <= cid && cid <= 0x10ffff))) { throw new Error(`expected an integer between 0x000000 and 0x10ffff, got 0x${cid.toString(16)}`); } return null; }; // #=========================================================================================================== // class @XXX_Ncr extends Multimix // @include @, { overwrite: true, } # instance methods // # @include @, { overwrite: false, } # instance methods // # @extend @, { overwrite: false, } # class methods // #--------------------------------------------------------------------------------------------------------- // constructor: ( input_default = 'plain' ) -> // super() // debug '^44443^', ( k for k of @ ) // return undefined }).call(this); //# sourceMappingURL=main.js.map
loveencounterflow/ncr
lib/main.js
JavaScript
mit
25,632
/** * Checks if a given DOM property of an element has the expected value. For all the available DOM element properties, consult the [Element doc at MDN](https://developer.mozilla.org/en-US/docs/Web/API/element). * * @example * this.demoTest = function (browser) { * browser.expect.element('body').to.have.property('className').equals('test-class'); * browser.expect.element('body').to.have.property('className').matches(/^something\ else/); * browser.expect.element('body').to.not.have.property('classList').equals('test-class'); * browser.expect.element('body').to.have.property('classList').deep.equal(['class-one', 'class-two']); * browser.expect.element('body').to.have.property('classList').contain('class-two'); * }; * * @method property * @param {string} property The property name * @param {string} [message] Optional log message to display in the output. If missing, one is displayed by default. * @display .property(name) * @api expect.element */ const BaseAssertion = require('./_element-assertion.js'); class PropertyAssertion extends BaseAssertion { static get assertionType() { return BaseAssertion.AssertionType.METHOD; } init(property, msg) { super.init(); this.flag('attributeFlag', true); this.property = property; this.hasCustomMessage = typeof msg != 'undefined'; this.message = msg || 'Expected element <%s> to ' + (this.negate ? 'not have' : 'have') + ' dom property "' + property + '"'; this.start(); } executeCommand() { return this.executeProtocolAction('getElementProperty', [this.property]).then(result => { if (!this.transport.isResultSuccess(result) || result.value === null) { throw result; } return result; }).catch(result => { this.propertyNotFound(); return false; }); } onResultSuccess() { if (this.retries > 0 && this.negate) { return; } if (!this.hasCondition()) { this.passed = !this.negate; this.expected = this.negate ? 'not found' : 'found'; this.actual = 'found'; } this.addExpectedInMessagePart(); } propertyNotFound() { this.processFlags(); this.passed = this.hasCondition() ? false : this.negate; if (!this.passed && this.shouldRetry()) { this.scheduleRetry(); } else { this.addExpectedInMessagePart(); if (!this.hasCondition()) { //this.expected = this.negate ? 'not found' : 'found'; this.actual = 'not found'; } if (!this.negate) { this.messageParts.push(' - property was not found'); } this.done(); } } onResultFailed() { this.passed = false; } } module.exports = PropertyAssertion;
beatfactor/nightwatch
lib/api/expect/assertions/element/property.js
JavaScript
mit
2,710
const rangeParser = require(`parse-numeric-range`) module.exports = language => { if (!language) { return `` } if (language.split(`{`).length > 1) { let [splitLanguage, ...options] = language.split(`{`) let highlightLines = [], numberLines = false, numberLinesStartAt // Options can be given in any order and are optional options.forEach(option => { option = option.slice(0, -1) // Test if the option is for line hightlighting if (rangeParser.parse(option).length > 0) { highlightLines = rangeParser.parse(option).filter(n => n > 0) } option = option.split(`:`) // Test if the option is for line numbering // Option must look like `numberLines: true` or `numberLines: <integer>` // Otherwise we disable line numbering if ( option.length === 2 && option[0] === `numberLines` && (option[1].trim() === `true` || Number.isInteger(parseInt(option[1].trim(), 10))) ) { numberLines = true numberLinesStartAt = option[1].trim() === `true` ? 1 : parseInt(option[1].trim(), 10) } }) return { splitLanguage, highlightLines, numberLines, numberLinesStartAt, } } return { splitLanguage: language } }
mingaldrichgan/gatsby
packages/gatsby-remark-prismjs/src/parse-line-number-range.js
JavaScript
mit
1,302