code
stringlengths
2
1.05M
'use strict'; // MODULES // var isPositive = require( 'validate.io-positive-primitive' ); // MEDIAN // /** * FUNCTION median( v ) * Computes the distribution median for a Student t distribution with parameter v. * * @param {Number} v - degrees of freedom * @returns {Number} distribution median */ function median( v ) { if ( !isPositive( v ) ) { return NaN; } return 0; } // end FUNCTION median() // EXPORTS module.exports = median;
// Define default globals to be changed later var enterCode = "0000"; // Default PIN code var tries = 0; // PIN code tries var dragging = false; // User is dragging on screen var swish = ""; var state = {}; // State variable state.current = null; // Active user element state.processing = 0; // Processing a payment state.menuIsOpen = 0; // Run when website is ready to be manipulated $(function() { window.actionBar = $("div#action-bar-float"); // Define action bar window.actionBarArrow = $("div.action-bar-arrow"); // Define action bar arrow actionBarArrow.borderwidth = parseInt(actionBarArrow.css("border-width").substr(4,2)); // Set width of arrow if (isNaN(actionBarArrow.borderwidth)) { actionBarArrow.borderwidth = 16 // Default size of 1em in pixels } window.scrollTo(0, 0); // Scroll to top // scriptURL is read in config.php where it is fetched from the environment variables of the server if (scriptURL=="") $(".cell").html("Back-end är inte konfigurerad.<br>Konsultera installationsguiden."); // Read cookie and try saved PIN var pin = readCookie("PIN"); if (pin != null){ enterCode=pin; } sendPIN(0); tries--; // Reset tries // Disable plus menu $("#step2").css("opacity",0.5); $("#step3").css("opacity",0.5); $("#plusButtons").css("opacity",0.5); $("#plusSwish").css("opacity",0.5); // Click listener for PIN code buttons $("#numbers").on("click", "button", function() { var lengthOfCode = parseInt(enterCode.length); if (lengthOfCode < 4) { $("#message").removeClass("show"); var clickedNumber = $(this).text().toString(); // Save number from element text enterCode = enterCode + clickedNumber; lengthOfCode = parseInt(enterCode.length) - 1; $("#fields .numberfield:eq(" + lengthOfCode + ")").addClass("active"); // Fill dots according to length if (lengthOfCode == 3) { $("#numbers").addClass("load"); $("#fields .numberfield").removeClass("active"); $("#fields .numberfield").addClass("load"); tries++; if (tries<6) { $("#status").addClass("load"); sendPIN(1); // Check the PIN } else { $("#message").html("För många felaktiga försök!").addClass("show"); } } } }); }); // Send PIN to server and retrieve data if right function sendPIN(calledByUser) { // Send JSONP request $.getJSON(scriptURL+"?prefix=getData&pin="+enterCode+"&callback=?") .done(function(data) { // If response from server if (data==""){ // Wrong PIN $("section#pinput").fadeIn(500); $("#numbers").removeClass("load"); $("#fields .numberfield").removeClass("load"); $("#status").removeClass("load"); if (calledByUser) $("#message").html("Fel PIN-kod. "+(6-tries)+" försök kvar.").addClass("show"); enterCode = ""; } else { // Correct PIN $(".loading-ring-big div").css("animation","lds-dual-ring 0.8s ease-in-out infinite"); // Faster ring animation window.title = data.title; // Set global title from server document.title = window.title + " – Strecklista"; // Set tab/page title swish = data.swish; setData(data.table); // Setup table of users // Browser nagivation history window.onpopstate = function(event){ changePage(event.state); // Change page if user goes back or forward }; // If page was not refreshed, set list as default if (window.history.state != null) { changePage(window.history.state); } else { changePage("list"); window.history.replaceState("list","",""); } createCookie("PIN",enterCode,data.days_pin); // Set PIN as cookie $("#status").slideUp(500); // If users list is not empty, fill all user selections if (data.list!="") { var html = '<option value="">Välj..</option>'; for (li in data.list) { html += '<option value="'+data.list[li].cid+'">'+data.list[li].nick+'</option>'; } $("section.settings select.users").html(html); } // Read cookie for favorite user and setup var favorite = readCookie("favorite"); if (favorite != null) { $("#favoriteUser").val(favorite); // Dropdown selection list $("#plusUser").val(favorite); // Plus user list $("div#action-bar-top").attr("data-cid",favorite); // Top action bar user $("#action-bar-top > span").text("Strecka på "+$("#favoriteUser option:selected").text()); // Top action bar text } $("div.menu-button").fadeIn(500); $("section#pinput").hide(); // Hide PIN input = PINput // Set click listeners for all elements. This should probably be modularised into parts of the page rather than grouped by type, i.e. all data and listeners for e.g the menu should be handled in one function. setTouchEvents(); } }) .fail(function(data) { // If no response enterCode = ""; $("#numbers").removeClass("load"); $("#fields .numberfield").removeClass("load"); $("#status").removeClass("load"); $("#message").html("Kunde inte ansluta till servern.").addClass("show"); }); } // Setup list of users function setData(data) { $('section#list').hide(); // List $('section#list').html(createTable(data.groups, data.members)); // Create table of users // Find pictures for every user $("div.profile").each(function(i,el) { // Do this for every user var imgUrl = 'https://s.gravatar.com/avatar/'+MD5($(el).attr("data-email"))+'?r=pg&s=128&d=404'; // Set url to Gravatar of user // See if image exists $.ajax({ url:imgUrl, type:"HEAD", crossDomain:true, success: function(){ $(el).css("background-image", "url("+imgUrl+")"); // Set image if it exists }, error:function(){ imgUrl = 'https://s.gravatar.com/avatar/'+MD5($(el).attr("data-cid")+"@student.chalmers.se")+'?r=pg&s=128&d=blank'; // Else use CID-email $(el).css("background-image", "url("+imgUrl+")"); } }); }); // Get about data from JSON file $("section#about").load('/resources/data/about.html'); runActivityFun(); // Start activity list updater $("section.activity").slideDown(1000); $("#numbers").removeClass("load"); $("#fields .numberfield").removeClass("load"); $("#status").removeClass("load"); // Add buttons to action bars for (b in data.buttons) { $("div.action-bar ul").append('<li data-action="pay" data-amount="'+data.buttons[b]+'"><span>' + data.buttons[b] + '</span></li>'); } // Add #-button to action bars $("div.action-bar ul").append('<li data-action="input"><span>#</span></li>'); // Set windows resize callback and move action bar accordingly $(window).on('resize', function(e) { if (state.current != null) { ActionBar(1,{ left:state.current[0].offsetLeft, top:state.current[0].offsetTop, width:state.current[0].offsetWidth, height:state.current[0].offsetHeight, cid:state.current.attr("data-cid") }); } }); } // Click listener for all elements function setTouchEvents() { // If user starts touch event, disable draggign (anticipate tap) $("body").on("touchstart", function(){ dragging = false; }); // If user starts moving, enable dragging $("body").on("touchmove", function(){ dragging = true; }); // Click listener for users $("section#list ul.cards li").on("click touchend", function(e) { // Stop extra click event when tapping e.stopPropagation(); e.preventDefault(); // Do nothing if user is dragging if (dragging) { dragging = false; // Reset return; } if (!state.processing) { // If no transaction is processing closeMenu(); state.current = $(this); // Set active element to tapped user // If tapped user is not the currently active if (state.current.attr("data-cid")!=actionBar.attr("data-cid")) { scrollToCurrent(); $("div.action-bar li").each(function(i,el){ resetColor($(el)); }); // Move action bar ActionBar(1,{ left:state.current[0].offsetLeft, top:state.current[0].offsetTop, width:state.current[0].offsetWidth, height:state.current[0].offsetHeight, cid:state.current.attr("data-cid") }); } else { ActionBar(0); // Hide action bar state.current = null; // Remove active user } } }); // Click listener for action bar buttons $("div.action-bar li").on("click touchend", function(e) { e.stopPropagation(); e.preventDefault(); if (dragging) { dragging = false; return; } if (!state.processing) { // If user is active if ($(this).parent().parent().attr("data-cid")!="") { if ($(this).attr("data-action") == "pay") { // If normal button pay($(this), parseInt($(this).attr("data-amount"))); } else if ($(this).attr("data-action") == "input") { // If custom number input var amount = prompt("Antal kronor:"); // Dialog box // Check number is ok if (amount != null) { amount = parseInt(amount); if (amount > 0) { pay($(this), amount); } else if (amount != null) { flashColor($(this),"red"); $(this).removeClass("loading-ring-button"); } } } } } }); // Hijack touch event if action bar is tapped (no button). Else "body" will be regarded as tapped $("div.action-bar").on("click touchend", function(e) { e.stopPropagation(); e.preventDefault(); }); // Click listener for menu button (top right) $("div.menu-button").on("click touchend", function(e) { e.stopPropagation(); e.preventDefault(); if (dragging) { dragging = false; return; } if (!state.processing) { ActionBar(0); // Hide action bar if (state.menuIsOpen) { closeMenu(); } else { openMenu(); } } }); // Click listener for menu item $("nav ul.menu li").on("click touchend",function(e) { e.stopPropagation(); e.preventDefault(); if (dragging) { dragging = false; return; } // Change page according to link var link = $(this).attr("data-link"); changePage(link); if (window.history.state != link) { window.history.pushState(link, "", ""); // If not same page, add to page navigation history } }); // Favorite user dropdown is changed $("#favoriteUser").on("change",function(e) { var cid = $(this).val(); if (cid != "") { createCookie("favorite", cid); $("#plusUser").val(cid); // Change plus user default to favorite console.log(cid + " är satt som favorit."); } else { eraseCookie("favorite"); // Erase cookie if no favorite } $("#action-bar-top").attr("data-cid", cid); $("#action-bar-top > span").text("Strecka på "+$("#favoriteUser option:selected").text()); }); // Click listener for body, used for closing menus and such $(document).on("click touchend", function(e) { e.stopPropagation(); //e.preventDefault(); // Don't enable this, no idea why closeMenu(); if (dragging) { dragging = false; return; } if (!state.processing) { if (state.current != null) { ActionBar(0); state.current = null; } } }); // On change of plus input update Swish-link $("section#plus input#amount").on("input", function(e){ var amount = parseInt(this.value); if (isNaN(amount)) { this.value = ""; // Empty if not a Number } else if (amount < 1) { this.value = 1; // Min } else if (amount > 5000) { this.value = 5000; // Max } else { this.value = parseInt(this.value); } updateSwishLink(this.value, $("section#plus select#plusUser").val()); }); // On change of user to plus on $("section#plus select#plusUser").on("change", function(e){ updateSwishLink($("section#plus input#amount").val(),this.value); }); // Confirm plus button $("span#confirmPlus").on("click touchend",function(e) { e.stopPropagation(); e.preventDefault(); if (dragging) { dragging = false; return; } // If buttons are enabled if ($("#step3").css("opacity") == 1) { if (!state.processing) { $(this).css("color","hsl(0, 0%, 0%)"); $(this).css("background-color","hsl(0, 0%, 100%)"); state.processing = 1; var cid = $("section#plus select#plusUser").val(); var change = parseInt($("section#plus input#amount").val()); sendPayment(cid,change,'Plussning',$("a#swish-button").attr("data-ref"),$(this)); } } }); // Click listener for login button on admin page $("#loginBtn").on("click touchend",function(e) { e.stopPropagation(); e.preventDefault(); if (dragging) { dragging = false; return; } if ($("#loginBtn").attr("disabled") != "disabled") { adminLogin(); } }); } // Create html code for user list function createTable(group,members) { var html = ''; for (g in group) { html += '<h1>'+group[g]+'</h1>'; // Title for every group html += '<ul class="cards">'; // Start list // Loop through every person for (m in members[g]) { member = members[g][m].split(";"); // Split "cid;name;email" into array cid = member[0]; name = member[1]; email = member[2]; if (email == "") { email = cid+"@student.chalmers.se"; } // Create list items html += '<li data-cid=' + cid + '><div class="profile" data-cid="'+cid+'" data-email="'+email+'">'; html += '<div>'+name.substr(0,1)+'</div>'; // Set profile pic as first letter (if no image) html += '</div>'; html += '<div class="name">'; html += name; html += '</div></li>'; } html += '</ul>'; } return html; } // Disable steps 2 and 3 in plus menu function disableSteps() { $("#swish-button").removeAttr("href"); $("#step2").css("opacity",0.5); $("#step3").css("opacity",0.5); $("#plusButtons").css("opacity",0.5); $("#plusSwish").css("opacity",0.5); $("#plusButtons span.button").removeAttr("style"); } // Enable steps 2 and 3 in plus menu function enableSteps() { $("#plusButtons").css("opacity",1); $("#plusSwish").css("opacity",1); $("#step2").css("opacity",1); $("#step3").css("opacity",1); $("#plusButtons span.button").css("cursor","pointer"); $("swish-QR").removeAttr("src"); } function openMenu() { $("div.bar1, div.bar2, div.bar3").addClass("close"); // Turn 3 blocks to cross $("nav").slideDown(200); state.menuIsOpen = 1; } function closeMenu() { $("div.bar1, div.bar2, div.bar3").removeClass("close"); // cross to 3 blocks again $("nav").slideUp(200); state.menuIsOpen = 0; } // Change current page function changePage(link) { closeMenu(); $("section.main").hide(); $("section.activity").hide(); $("#action-bar-top").hide(); if (link == null || link == "list") { document.title = window.title + " – Strecklista"; $("a#logo").text("Strecklista"); $("section#list").show(); $("section.activity").slideDown(500); // If favorite is chosen, show top action bar if ($("#action-bar-top").attr("data-cid") != "") $("#action-bar-top").fadeIn(500); updateActivity(); // Load activity list } else if (link == "stats") { document.title = window.title + " – Statistik"; $("a#logo").text("Statistik"); $("section#stats").show(); } else if (link == "plus") { document.title = window.title + " – Plussa"; $("a#logo").text("Plussa"); $("section#plus").show(); } else if (link == "settings") { document.title = window.title + " – Inställningar"; $("a#logo").text("Inställningar"); $("section#settings").show(); } else if (link == "admin") { document.title = window.title + " – Admin"; $("a#logo").text("Admin"); $("section#admin").show(); } else if (link == "about") { document.title = window.title + " – Om appen"; $("a#logo").text("Om appen"); $("section#about").show(); } } // Update Swish-link and QR-code if amount and user is correct function updateSwishLink(amount, cid) { if (amount == "" || cid == "") { disableSteps(); } else { var ref = makeID(); // Create 5 character ID for reference var swishData = { "version": 1, "payee": { "value":swish }, "message":{ "value": "Plussa: "+ref }, "amount": { "value": parseInt(amount) } }; // Swish data to put in link $("a#swish-button").attr("href","swish://payment?data="+encodeURIComponent(JSON.stringify(swishData))); // Swish-link $("a#swish-button").attr("data-ref",ref); // Save reference code for fetching when confirmation button is pressed /* Create QR-code for Swish. Format: C##########;#;message;# 1st part is tel number 2nd part is amount 3rd part is message 4th part is digit for editable fields: # = [tel, amount, message] 0 = [0, 0, 0] 1 = [1, 0, 0] 2 = [0, 1, 0] 3 = [0, 0, 1] 4 = [1, 1, 0] 5 = [1, 0, 1] 6 = [0, 1, 1] 7 = [1, 1, 1] */ $("#swish-QR").attr("src",'https://chart.apis.google.com/chart?cht=qr&chs=200x200&chl=C'+swish+'%3B'+amount+'%3B'+"Plussa: "+ref+'%3B0&chld=H|1'); enableSteps(); } } // Scroll to selected user function scrollToCurrent() { // Relative reference point for scrolling is top left of profile picture var offset = 0; // Offset height from reference point (down) var cardHeight = $("section#list ul.cards li")[0].offsetHeight; var abHeight = actionBar[0].offsetHeight; // Action bar height // If profile picture height + action bar height is larger than window if ((cardHeight + abHeight) >= $(window).height()) { offset = (cardHeight + abHeight) - $(window).height(); } else { offset = -abHeight; } $('html, body').animate({ scrollTop: state.current.offset().top + offset }, 600); } // Show/hide action bar and move it function ActionBar(show, data) { if (show) { actionBar.attr("data-cid", data.cid); actionBar.css("top", data.top + actionBarArrow.borderwidth + data.height); // Set top position to top + arrow height var width = parseInt(actionBar.css('width')); // Set action bar aligned with middle of user var left = (data.left + data.width/2 - width/2); if (left <= 0.1*$(window).width()) { // If bar is too much to the left left = "10vw"; // Set to left limit } else if ((left + width) >= 0.9*$(window).width()) { // Too much right left = "calc(90vw - "+width+"px)"; // Set to right limit } actionBar.css("left", left); actionBar.css("transform", "scale(1)"); actionBar.css("opacity", 1); actionBarArrow.css("top", data.top + data.height); actionBarArrow.css("left", data.left + data.width/2 - actionBarArrow.borderwidth); actionBarArrow.css("transform", "scale(1)"); actionBarArrow.css("opacity", 1); // Set transitions AFTER (10 ms) previous calls else they will become instant setTimeout(function() { actionBar.css("transition","opacity 0.2s ease-in-out, transform 0.2s ease-in-out, left 0.3s ease-in-out, top 0.3s ease-in-out"); actionBarArrow.css("transition","opacity 0.2s ease-in-out, transform 0.2s ease-in-out, left 0.3s ease-in-out, top 0.3s ease-in-out"); },10); } else { // If hide actionBar.css("transition","opacity 0.2s ease-in-out, transform 0.2s ease-in-out, left 0s ease-in-out, top 0s ease-in-out"); actionBarArrow.css("transition","opacity 0.2s ease-in-out, transform 0.2s ease-in-out, left 0s ease-in-out, top 0s ease-in-out"); actionBarArrow.css("transform", "scale(0)"); actionBar.css("transform", "scale(0)"); actionBar.css("opacity", 0); actionBarArrow.css("opacity", 0); actionBar.attr("data-cid",""); } } // Continuous updates of activity list function runActivityFun() { setTimeout(function() { if (window.history.state == "list") updateActivity(); // Only update on list page runActivityFun(); // Call itself after 30 seconds }, 1000*30); } // Update activity list function updateActivity() { $.getJSON(scriptURL+"?prefix=getActivity&pin="+enterCode+"&callback=?") .done(function(data) { $("section.activity > ul > li").unbind(); // Unbind all listeners on previous items to clear memory if (data != "") { if (data.list!="") { var html = ''; // For every item up to 10 items for (var li = 0; li < data.list.length && li < 10; li++) { var category =""; if (data.list[li].category != "Minusning") { // Set verb for category of transaction switch (data.list[li].category) { case "Streckning": category = "streckade"; break; case "Makulering": category = "ångrade"; break; case "Plussning": category = "plussade"; break; default: category = "hackade in"; } html += '<li data-category="'+ data.list[li].category +'" data-cid="'+ data.list[li].cid +'" data-time="'+ data.list[li].time +'" data-name="'+ data.list[li].name +'" data-amount="'+ Math.abs(data.list[li].amount) +'">'; // List item data html += '<span class="time">'+ (data.list[li].time.substr(data.list[li].time.length - 8)).split(".").join(":") + '</span>'; // Time hh:mm:ss html += '<span class="name">'+ data.list[li].name +'</span> '; html += category; html += ' <span class="amount">'+ Math.abs(data.list[li].amount) +'</span>'; html += ' kr.</li>'; } } $("section.activity ul").html(html); // Set new listeners $('section.activity > ul > li[data-category="Streckning"]').on("click touchend", function(e) { e.stopPropagation(); e.preventDefault(); if (dragging) { dragging = false; return; } // Confirm dialog box if (confirm('Vill du ångra streckningen på '+ $(this).attr("data-name") +' för '+ $(this).attr("data-amount") +' kr?')) { var comment = prompt("Lämna en kort kommentar om vad som hände:"); if (comment != null) { if (comment.length >= 5) { sendPayment($(this).attr("data-cid"),parseInt($(this).attr("data-amount")),'Makulering',comment, $(this)); } else { alert("Ångerbegäran avbröts på grund av för kort kommentar."); } } else { alert("Du avbröt ångerbegäran."); } } }); } else { // Activity list is empty html = '<li><span class="time">Inga senaste transaktioner.</span></li>'; $("section.activity ul").html(html); } } else { alert("Fel PIN-kod!"); location.reload(true); // Refresh page if PIN is wrong } }); } // Add loaing ring to button and call sendPayment function pay(el,amount) { cid = el.parent().parent().attr("data-cid"); if (!isNaN(amount)) { if (!state.processing) { el.addClass("loading-ring-button"); el.prepend("<div></div>"); // Div for loading ring el.find("span").first().text(amount); // Change text to amount (for custom input) state.processing = 1; change = -amount; sendPayment(cid,change,'Streckning','',el); } } else { alert("Knappen är inte ett tal!"); } } // Send transaction to server function sendPayment(cid,change,category,comment,self) { $.getJSON(scriptURL+"?"+"pin="+enterCode+"&cid="+cid+"&change="+change+"&category="+category+"&comment="+comment+"&prefix=sendPayment&callback=?") .done(function (data) { state.processing = 0; // Styles $("section#plus p#plusButtons .button").attr("style",""); self.removeClass("loading-ring-button"); self.find('div').first().remove(); // Reset #-button if (self.attr("data-action")=="input") self.find("span").first().text("#"); if (data != "") { success = data.success; if (success) { updateActivity(); flashColor(self,"green") console.log(cid+" har ändrats med "+change+" kr. Nu: "+data.current+" kr."); if (data.current <= 0) { console.log(cid+" har "+(-data.current)+" kr i skuld!"); } else if (data.current <=10) { console.log(cid+" har endast "+(data.current)+" kr kvar att strecka på!"); } // Add temporary entry in activity list if (change < 0) { $("section.activity ul").prepend('<li><span class="time">Nyss&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="name">Du</span> streckade <span class="amount">'+Math.abs(change)+'</span> kr.</li>'); } else { $("section.activity ul").prepend('<li><span class="time">Nyss&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="name">Du</span> plussade <span class="amount">'+Math.abs(change)+'</span> kr.</li>') } // Set plus user dropdown to none just to show some confirmation $("section#plus select#plusUser").val("").change(); } else { // If not succesful (but connected to server) flashColor(self,"red"); if (change<0) { alert("Kunde inte strecka "+(-change)+" kr på "+cid+": "+data.message); } else { alert("Kunde inte lägga till "+change+" kr på "+cid+": "+data.message); } } } else { alert("Fel PIN-kod!"); location.reload(true); } }) .fail(function(data) { state.processing = 0; // Styles $("section#plus p#plusButtons .button").attr("style",""); self.removeClass("loading-ring-button"); self.find('div').first().remove(); // Reset #-button if (self.attr("data-action")=="input") self.find("span").first().text("#"); flashColor(self,"red"); if (change<0) { console.log("Kunde inte strecka "+(-change)+"kr på "+cid+": Ingen kontakt med servern. Försök igen!"); } else { alert("Kunde inte lägga till "+change+"kr på "+cid+": Ingen kontakt med servern. Bekräfta betalningen igen!"); } }); } // Flash jquery element with the selected color function flashColor(el,color) { el.css("transition",""); // Remove transition to make change instant el.css("transition"); // Load transition to enable (else it will not work) el.css("background-color",color); // Change background color el.css("background-color"); // Load again el.css("transition","background 10s"); // Change transition el.css("transition"); // Load transition el.css("background",""); // Remove background and it will fade } // Remove all flashing instantly function resetColor(el) { el.css("transition",""); el.css("transition"); el.css("background-color",""); el.css("background-color"); }
class friendsList{ constructor(unformattedList){ this.username = unformattedList.name this.id = unformattedList.id this.dateAdded = unformattedList.date } } module.exports = friendsList
var expect = require('../test_helper').expect; var assert = require('../test_helper').assert; /* istanbul ignore next */ describe('root route', function () { var server, route; before(function (done) { var db = require(__main_root + 'db/DB.js'); db.instance.sync().then(function () { server = require(__main_root + 'server/Server').listen(); server.start(function () { route = server.lookup('root'); done(); }); }); }); it("should not be null", function (done) { expect(route).to.not.be.null; done(); }); it("should have expected path", function (done) { expect(route.path).to.equal('/'); done(); }); it("should have expected method", function (done) { expect(route.method).to.equal('get'); done(); }); it("should have expected description", function (done) { expect(route.settings.description).to.equal('Gets all of the endpoint categories that the API supports'); done(); }); it("should have expected handler function", function (done) { assert.isFunction(route.settings.handler); expect(route.settings.handler.name).to.equal('apiDiscovery'); done(); }); });
import { NavigationActions } from 'react-navigation' const getNavigationParam = ( navigation, param ) => { if ( navigation.state && navigation.state.params ) { if ( navigation.state.params.hasOwnProperty( param ) ) { return navigation.state.params[ param ] } } return '' } const getCurrentRouteName = navigationState => { if ( !navigationState ) { return null } const route = navigationState.routes[ navigationState.index ] // dive into nested navigators if ( route.routes ) { return getCurrentRouteName( route ) } return route.routeName } const navigateOnce = getStateForAction => ( action, state ) => { const { type, routeName } = action return state && type === NavigationActions.NAVIGATE && routeName === state.routes[ state.routes.length - 1 ].routeName ? null : getStateForAction( action, state ) // you might want to replace 'null' with 'state' if you're using redux (see comments below) } export { getNavigationParam, getCurrentRouteName, navigateOnce }
const join = (sep, arr) => Array.prototype.join.call(arr, sep); export { join };
({ baseUrl: '.', name: 'lib/almond', include: ['main'], wrap: true })
var jwt = require('jsonwebtoken'); var config = require('../config.js'); var _authorizeID = function(req, res, next) { var token = req.headers['x-access-token']; if (token) { jwt.verify(token, config.sekretoJWT, function(err, decoded) { if (err) { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.' }); } else { if(req.originalUrl.split('/').includes(decoded.id.toString())) { if(req.method == "PUT"){ var permesatajKampoj = ["uzantnomo", "pasvorto", "retposxto", "tttpagxo", "telhejmo", "teloficejo", "telportebla", "titolo"]; if(permesatajKampoj.indexOf(req.body.kampo) > -1) { req.decoded = decoded; next(); } else { return res.status(403).send({ success: false, message: 'Vi ne rajtas ĝisdatigi tiun kampon.' }); } } else { req.decoded = decoded; next(); } } else { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.' }); } } }); } else { // Se ne estas ĵetono // redonas eraron return res.status(400).send({ success: false, message: 'Sen ĵetono (token).' }); } } var _authorizeUzanto = function(req, res, next) { var token = req.headers['x-access-token']; if (token) { jwt.verify(token, config.sekretoJWT, function(err, decoded) { if (err) { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.' }); } else { req.decoded = decoded; next(); } }); } } var _authorizeMembro = function(req, res, next) { var token = req.headers['x-access-token']; if(token) { jwt.verify(token, config.sekretoJWT, function(err, decoded) { if (err) { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } else { if(decoded.permesoj) { if((decoded.permesoj.indexOf('membro') > -1) ||(decoded.permesoj.indexOf(config.idAdministranto) > -1) || (decoded.permesoj.indexOf(config.idKomunikisto) > -1)) { req.decoded = decoded; next(); } else { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } } else { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } } }); } else { // Se ne estas ĵetono // redonas eraron return res.status(400).send({ success: false, message: 'Sen ĵetono (token).' }); } } var _authorizeAdmin = function(req, res, next) { var token = req.headers['x-access-token']; if(token) { jwt.verify(token, config.sekretoJWT, function(err, decoded) { if (err) { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } else { if(decoded.permesoj) { if(decoded.permesoj.indexOf(config.idAdministranto) > -1) { req.decoded = decoded; next(); } else { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } } else { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } } }); } else { // Se ne estas ĵetono // redonas eraron return res.status(400).send({ success: false, message: 'Sen ĵetono (token).' }); } } var _authorizeAdminKomunikisto = function(req, res, next) { var token = req.headers['x-access-token']; if(token) { jwt.verify(token, config.sekretoJWT, function(err, decoded) { if (err) { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } else { if(decoded.permesoj) { if((decoded.permesoj.indexOf(config.idAdministranto) > -1) || (decoded.permesoj.indexOf(config.idKomunikisto) > -1)) { req.decoded = decoded; next(); } else { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } } else { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } } }); } else { // Se ne estas ĵetono // redonas eraron return res.status(400).send({ success: false, message: 'Sen ĵetono (token).' }); } } var _authorizeAdminFinancoj = function(req, res, next) { var token = req.headers['x-access-token']; if(token) { jwt.verify(token, config.sekretoJWT, function(err, decoded) { if (err) { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } else { if(decoded.permesoj) { if((decoded.permesoj.indexOf(config.idAdministranto) > -1) || (decoded.permesoj.indexOf(config.idFinancoj) > -1)) { req.decoded = decoded; next(); } else { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } } else { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } } }); } else { // Se ne estas ĵetono // redonas eraron return res.status(400).send({ success: false, message: 'Sen ĵetono (token).' }); } } var _authorizeAdminJuna = function(req, res, next) { var token = req.headers['x-access-token']; if(token) { jwt.verify(token, config.sekretoJWT, function(err, decoded) { if (err) { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } else { if(decoded.permesoj) { if((decoded.permesoj.indexOf(config.idAdministranto) > -1) || (decoded.permesoj.indexOf(config.idFinancoj) > -1)) { req.decoded = decoded; next(); } else if (decoded.permesoj.indexOf(config.idJunaAdministranto) > -1) { var jaro = parseInt((new Date()).getFullYear()); var junaJaro = jaro - config.junaAgxo; req.query.naskigxtago = new Date(junaJaro + '-01-01'); req.decoded = decoded; next(); } else { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } } else { return res.status(403).send({ success: false, message: 'La ĵetono (token) ne estas ĝusta.'}); } } }); } else { // Se ne estas ĵetono // redonas eraron return res.status(400).send({ success: false, message: 'Sen ĵetono (token).' }); } } var _authorizeSenKondicxo = function(req, res, next) { var token = req.headers['x-access-token']; if(token) { jwt.verify(token, config.sekretoJWT, function(err, decoded) { if (err) { req.decoded = null; } else { req.decoded = decoded; } }); } else { req.decoded = null; } next(); } module.exports = { authorizeID: _authorizeID, authorizeSenKondicxo: _authorizeSenKondicxo, authorizeAdminJuna: _authorizeAdminJuna, authorizeAdmin: _authorizeAdmin, authorizeAdminKomunikisto: _authorizeAdminKomunikisto, authorizeUzanto: _authorizeUzanto, authorizeMembro: _authorizeMembro, authorizeAdminFinancoj: _authorizeAdminFinancoj }
////////////////////////////////////////////////////////////////////////// // // // This is a generated file. You can view the original // // source in your browser if your browser supports source maps. // // Source maps are supported by all recent versions of Chrome, Safari, // // and Firefox, and by Internet Explorer 11. // // // ////////////////////////////////////////////////////////////////////////// (function () { /* Imports */ var Meteor = Package.meteor.Meteor; var global = Package.meteor.global; var meteorEnv = Package.meteor.meteorEnv; var Accounts = Package['accounts-base'].Accounts; var Facebook = Package.facebook.Facebook; (function(){ ///////////////////////////////////////////////////////////////////////////////////////////////////////// // // // packages/accounts-facebook/facebook.js // // // ///////////////////////////////////////////////////////////////////////////////////////////////////////// // Accounts.oauth.registerService('facebook'); // 1 // 2 if (Meteor.isClient) { // 3 Meteor.loginWithFacebook = function(options, callback) { // 4 // support a callback without options // 5 if (! callback && typeof options === "function") { // 6 callback = options; // 7 options = null; // 8 } // 9 // 10 var credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback); Facebook.requestCredential(options, credentialRequestCompleteCallback); // 12 }; // 13 } else { // 14 Accounts.addAutopublishFields({ // 15 // publish all fields including access token, which can legitimately // 16 // be used from the client (if transmitted over ssl or on // 17 // localhost). https://developers.facebook.com/docs/concepts/login/access-tokens-and-types/, // 18 // "Sharing of Access Tokens" // 19 forLoggedInUser: ['services.facebook'], // 20 forOtherUsers: [ // 21 // https://www.facebook.com/help/167709519956542 // 22 'services.facebook.id', 'services.facebook.username', 'services.facebook.gender' // 23 ] // 24 }); // 25 } // 26 // 27 ///////////////////////////////////////////////////////////////////////////////////////////////////////// }).call(this); /* Exports */ if (typeof Package === 'undefined') Package = {}; Package['accounts-facebook'] = {}; })();
angular .module('app') .controller('homeController', [ '$rootScope', '$scope', function($rootScope, $scope) { // this allows us to auto set login credentials based on demo path $scope.loginAs = function(userType) { $rootScope.goTo('/login?demo=' + userType); }; } ]);
'use strict'; const path = require('path'); const { promisify } = require('util'); const helpers = require('yeoman-test'); const GENERATOR_DIRECTORY = path.join(__dirname, 'temp'); async function createGeneratorDirectory () { await promisify(helpers.testDirectory)(GENERATOR_DIRECTORY); } async function createGenerator (options = {}) { await createGeneratorDirectory(); return helpers.createGenerator( 'testcafe-reporter:app', ['../../generators/app'], null, options ); } async function runGenerator (generator) { helpers.mockPrompt(generator, { reporterName: 'test-reporter', githubUsername: 'test-user', website: 'test.com' }); await promisify((...args) => generator.run(...args))(); } async function createReporter () { const generator = await createGenerator(); await runGenerator(generator); } module.exports = { createGenerator, runGenerator, createReporter };
var WebSocketServer = require('websocket').server , config = require('./../etc/config.json') var plugins = {}; var validPlugins = []; var subscribers = {}; var wsServer; function notifySubscribers(pl, mess) { var sp = pl.split('.'); var plugin = sp[0]; var graph = sp.slice(1).join('.'); mess.name = pl; var m = JSON.stringify({type: 'data', data: mess}); subscribers[plugin][graph].forEach(function (c) { c.sendUTF(m); }); } function init(server) { config.plugins.forEach(function (p) { var instanceName = p.instanceName || p.plugin; var plug = new (require('./../plugins/' + p.plugin))(); plugins[instanceName] = plug; plugins[instanceName].setName(instanceName); plugins[instanceName].setHandler(notifySubscribers); if ( plugins[instanceName].setup && config.pluginConfig[instanceName] ) { plugins[instanceName].setup(config.pluginConfig[instanceName]); } }); Object.keys(plugins).forEach(function (p) { var datasets = plugins[p].test(); if ( datasets instanceof Array ) { subscribers[p] = {}; datasets.forEach(function (ds) { validPlugins.push(p + '.' + ds); subscribers[p][ds] = []; }); } }); validPlugins.sort(); wsServer = new WebSocketServer({ httpServer: server }); wsServer.on('request', function(req) { var connection = req.accept(null, req.origin); connection.sendUTF(JSON.stringify({type: 'plugins', valid: validPlugins})); connection.on('message', function(m) { var mess = JSON.parse(m.utf8Data); switch(mess.type) { case 'subscribe': var mp = mess.plugin.split(/\./); var plugin = mp[0]; var graph = mp.slice(1).join('.'); if ( subscribers[plugin] && subscribers[plugin][graph] && subscribers[plugin][graph].indexOf(connection) === -1 ) { subscribers[plugin][graph].push(connection); } else { connection.sendUTF(JSON.stringify({type: 'error', message: 'No such plugin'})); } break; case 'unsubscribe': var mp = mess.plugin.split(/\./); var plugin = mp[0]; var graph = mp.slice(1).join('.'); subscribers[plugin][graph] = subscribers[mp[0]][mp[1]].filter(function (ar) { return (ar != connection); }); break; } }); connection.on('close', function(conn) { validPlugins.forEach(function (pl) { var mp = pl.split(/\./); var plugin = mp[0]; var graph = mp.slice(1).join('.'); subscribers[plugin][graph] = subscribers[plugin][graph].filter(function (ar) { return (ar != connection); }); }); }); }); // We want to sleep a little to align the graphs with whole seconds. It's prettier. var _ws = (Math.ceil(new Date().getTime() / 1000) * 1000) - new Date().getTime(); setTimeout(function () { setInterval(function () { Object.keys(subscribers).forEach(function (pl) { plugins[pl].run(); }); }, 1000); }, _ws); } exports.init = init;
(function () { 'use strict'; angular .module('app', ['ui.router', 'ngMessages', 'ngStorage', 'xeditable', 'cgNotify']) .config(config) .run(run); function config($stateProvider, $urlRouterProvider) { // default route $urlRouterProvider.otherwise("/"); // app routes $stateProvider .state('home', { url: '/', templateUrl: 'home/index.view.html', controller: 'Home.IndexController', controllerAs: 'vm' }) .state('login', { url: '/login', templateUrl: 'login/index.view.html', controller: 'Login.IndexController', controllerAs: 'vm' }); } function run($rootScope, $http, $location, $localStorage, editableOptions) { editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default') { // keep user logged in after page refresh if ($localStorage.currentUser) { $http.defaults.headers.common.Authorization = 'Bearer ' + $localStorage.currentUser.token; } // redirect to login page if not logged in and trying to access a restricted page $rootScope.$on('$locationChangeStart', function (event, next, current) { var publicPages = ['/login']; var restrictedPage = publicPages.indexOf($location.path()) === -1; if (restrictedPage && !$localStorage.currentUser) { $location.path('/login'); } }); } })();
const mongoose = require('mongoose'); const Schema = mongoose.Schema; /** * FsFile Schema */ const FsFileSchema = new Schema({ filename: { type: String, required: 'File name is required' }, length: { type: Number }, contentType: { type: String }, uploadDate: { type: Date }, metadata: { type: { type: String }, attribute: { type: Object }, uploader: { type: Schema.Types.ObjectId, ref: 'User' }, desc: { type: String } } }); /** * @typedef FsFile */ module.exports = mongoose.model('FsFile', FsFileSchema, 'fs.files');
$(function(){ $(".drawer").drawer(); // Initiate Fast Click for faster touch support FastClick.attach(document.body); // HEADROOM.js // grab an element var myElement = document.getElementById("navbar"); // construct an instance of Headroom, passing the element var headroom = new Headroom(myElement); // initialise headroom.init(); // Check the viewport window size var windowSize = $(window).width(); // If the viewport window is a small screen if(windowSize < 832){ // Push navigation menu off canvas, plan for Headroom pause $('#navLinksWrapper').addClass('pushy pushed-off pushy-right menu-expanded'); // Add mobile watcher class $('#navLinksWrapper a').each(function(){ $(this).addClass('mobile'); }); } else { // Do not show Menu button $('#menuButtonWrapper').hide(); } // When the viewport window resizes $(window).resize(function(){ // Check viewport window size var windowSize = $(window).width(); // If the viewport window size is a small screen if(windowSize < 832){ // Add transition to menu button $('#menuButtonWrapper, #emblemWrapper').addClass('push'); // Push navigation menu off canvas, plan for Headroom pause $('#navLinksWrapper').addClass('pushy pushed-off pushy-right menu-expanded'); // Add mobile watcher class $('#navLinksWrapper a').each(function(){ $(this).addClass('mobile'); }); // Show Menu button $('#menuButtonWrapper').show(); } else { // Remove off-canvas navigation styles from the menu $('#navLinksWrapper').removeClass('pushy pushy-right'); // Float navigation links to the left when menu is collapsed $('#navLinks').addClass('float-l'); // Float Account and Log Out container to the right when menu is collapsed $('#accountWrapper').addClass('float-r'); // Hide logo container $('#logoWrapper').addClass('hide'); // Remove mobile watcher class $('#navLinksWrapper a').each(function(){ $(this).removeClass('mobile'); }); // Do not show Menu button $('#menuButtonWrapper').hide(); } }); // Clicking the menu button reveals off-canvas navigation $('#menuButton').click(function(){ // If mobile menu is open if($('#navLinksWrapper').hasClass('open')){ // Remove watcher class from navigation links $('#navLinksWrapper').removeClass('open'); // Add transition to menu button $('#menuButtonWrapper, #emblemWrapper').removeClass('push-push push').addClass('slide-right close'); // Remove expanded styles and push menu off canvas $('#navLinksWrapper').removeClass('pushy-open shadow').addClass('pushy-right'); // Remove menu button active styling $('#menuButton').removeClass('expanded'); // Resume Headroom scrolling $('#navbar').removeClass('headroom--paused'); } else { // Add transition to menu button $('#menuButtonWrapper, #emblemWrapper').addClass('push-push push').removeClass('slide-right close'); // Add watcher class to mobile menu $('#navLinksWrapper').addClass('open'); // Remove off-canvas style and add expanded menu styles $('#navLinksWrapper').addClass('pushy-open shadow').removeClass('pushed-off'); // Show logo container $('#logoWrapper').removeClass('hide'); // Remove floated style from navigation links $('#navLinks').removeClass('float-l'); // Remove floated style from Account and Log Out container $('#accountWrapper').removeClass('float-r'); // Add menu button active styling $('#menuButton').addClass('expanded'); // Pause Headroom scrolling $('#navbar').addClass('headroom--paused'); } }); // Clicking away from off-canvas navigation when open // pushes the off-canvas navigation off of the screen $('#siteOverlay').click(function(){ // Add transition to menu button $('#menuButtonWrapper, #emblemWrapper').removeClass('push-push push').addClass('slide-right close'); // Remove watcher class from mobile menu $('#navLinksWrapper').removeClass('open'); // Remove expanded styles and push menu off canvas $('#navLinksWrapper').removeClass('pushy-open shadow').addClass('pushy-right'); // Remove menu button active styling $('#menuButton').removeClass('expanded'); // Resume Headroom scrolling $('#navbar').removeClass('headroom--paused'); }); });
(function () { function getTags() { var self = this; } angular.module('clipto') .factory('GetTags', [getTags]) }());
import KLTable from './src/table.vue'; KLTable.install = function(Vue) { Vue.component(KLTable.name, KLTable); }; export default KLTable;
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M4 17.17L5.17 16H20V4H4v13.17zm6.43-8.74L12 5l1.57 3.43L17 10l-3.43 1.57L12 15l-1.57-3.43L7 10l3.43-1.57z" opacity=".3" /><path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H5.17L4 17.17V4h16v12z" /><path d="M12 15l1.57-3.43L17 10l-3.43-1.57L12 5l-1.57 3.43L7 10l3.43 1.57z" /></React.Fragment> , 'TryTwoTone');
'use strict'; const path = require('path'), migrator = require(path.resolve('./custom_functions/advanced_settings_migrator.js')), winston = require("winston"); module.exports = { up: (queryInterface, Sequelize) => { return migrator.migrate(queryInterface, { operation: 'add', path: '.', name: "akamai_segment_media", value: { "description": "Integration configuration for akamai segment media token.", "key": "", "window": "", "salt": "", } }).catch(err => { winston.error("Error at adding akamai_segment_media ", err); }); }, down: (queryInterface, Sequelize) => { return migrator.migrate(queryInterface, { operation: 'remove', path: '.', name: "akamai_segment_media", }).catch(err => { winston.error("Error at removing akamai_segment_media", err); }); } };
var gulp = require('gulp'), file = require('gulp-file'), filenames = require('gulp-filenames'), gulpif = require('gulp-if'), imagemin = require('gulp-imagemin'), beautify = require('gulp-jsbeautify'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), Elixir = require('laravel-elixir'), merge = require('merge-stream'), path = require('path'), exists = require('path-exists').sync, sequence = require('run-sequence'), config = Elixir.config; /** * Publish javascript main files into another folder * @param {string|object} outputDir The destination folder or an options object * @param {object} options Options object passed to bower-files */ Elixir.extend('bowerJs', function(outputDir, options) { // Options were provided on the outputDir parameter if (typeof outputDir == 'object') { options = outputDir; outputDir = null; } options = typeof options == 'undefined' ? {camelCase: false} : options; var paths = new Elixir.GulpPaths() .output(outputDir || config.get('assets.js.folder') + '/vendor'); new Elixir.Task('bowerJs', function () { var bower_components = require('bower-files')(options); var getMinifiedScripts = function (path, index, arr) { var newPath = path.replace(/.([^.]+)$/g, '.min.$1'); return exists( newPath ) ? newPath : path; }, isNotMinified = function(file) { var filename = file.history[file.history.length - 1]; return !(/\.min\.js$/.test(filename)); }, uglifyScripts = function(file) { return isNotMinified(file) && config.production; }, jsfiles = bower_components.ext('js').deps, tasks = [], createFolder; for (var packageName in jsfiles) { if (jsfiles[packageName].length) { jsfiles[packageName].map(getMinifiedScripts); createFolder = jsfiles[packageName].length > 1; tasks.push( gulp.src(jsfiles[packageName]) .pipe(gulpif(uglifyScripts, uglify())) .pipe(gulpif(createFolder, rename({dirname: packageName.replace(/\.js$/, '')}))) .pipe(gulpif(!createFolder, rename({basename: packageName.replace(/\.js$/, '')}))) .pipe(filenames(packageName.replace(/\.js$/, ''))) .pipe(gulp.dest(paths.output.path)) ); } } return merge.apply(this, tasks); }); }); /** * Generate a requirejs main file from the proccessed files * @param {string} filename The filename of the main file * @param {object} shim The requirejs shim definitions * @param {object} outputDir Options object passed to bower-files */ Elixir.extend('bowerRequireMain', function(filename, shim, outputDir) { var paths = new Elixir.GulpPaths() .output(outputDir || config.get('assets.js.folder')); new Elixir.Task('bowerRequireMain', function() { var main = {paths: {}, baseUrl: 'js', shim: (shim || {})}; var files = filenames.get("all"), packages = []; for (var packageName in files) { packages.push(packageName); } packages = packages.sort() for (var i in packages) { main.paths[packages[i]] = 'vendor/' + packages[i]; } var main_str = 'require.config(' + JSON.stringify(main) + ');'; return file(filename, main_str) .pipe(beautify({indentSize: 4})) .pipe(gulp.dest(paths.output.path)); }); }); /** * Publish font main files into another folder * @param {string|object} outputDir The destination folder or an options object * @param {object} options Options object passed to bower-files */ Elixir.extend('bowerFonts', function(outputDir, options) { // Options were provided on the outputDir parameter if (typeof outputDir == 'object') { options = outputDir; outputDir = null; } options = typeof options == 'undefined' ? {camelCase: false} : options; var paths = new Elixir.GulpPaths() .output(outputDir || config.publicPath + '/fonts'); new Elixir.Task('bowerFonts', function() { var bower_components = require('bower-files')(options); var fonts = bower_components.ext(['eot', 'woff', 'woff2', 'ttf', 'svg']).deps, tasks = []; for (var packageName in fonts) { if (fonts[packageName].length) { tasks.push( gulp.src(fonts[packageName]) .pipe(gulp.dest(paths.output.path + '/' + packageName)) ); } } return merge.apply(this, tasks); }); }); /** * Publish image main files into another folder * @param {string|object} outputDir The destination folder or an options object * @param {object} options Options object passed to bower-files */ Elixir.extend('bowerImages', function(outputDir, options) { // Options were provided on the outputDir parameter if (typeof outputDir == 'object') { options = outputDir; outputDir = null; } options = typeof options == 'undefined' ? {camelCase: false} : options; var paths = new Elixir.GulpPaths() .output(outputDir || config.publicPath + '/img/vendor'); new Elixir.Task('bowerImages', function() { var bower_components = require('bower-files')(options); var images = bower_components.ext(['png', 'jpg', 'gif', 'jpeg']).deps, tasks = []; for (var packageName in images) { if (images[packageName].length) { tasks.push( gulp.src(images[packageName]) .pipe(imagemin()) .pipe(gulp.dest(paths.output.path + '/' + packageName)) ); } } return merge.apply(this, tasks); }); });
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { PropTypes } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Contact.scss'; const title = 'Contact Us'; function Contact(props, context) { context.setTitle(title); return ( <div className={s.root}> <div className={s.container}> <h1>{title}</h1> <p>...</p> </div> </div> ); } Contact.contextTypes = { setTitle: PropTypes.func.isRequired }; export default withStyles(Contact, s);
module.exports = require('./dist/medium');
import React, { Component, PropTypes } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import { Button } from 'react-bootstrap'; import FieldGroupComp from '../FieldGroup'; import AlertMessageComp from '../AlertMessage'; class Signup extends Component { static propTypes = { onSubmit: PropTypes.func.isRequired, }; constructor() { super(); this.state = { errorMsg: '', name: '', email: '', password: '', rePassword: '' }; } _onSignup() { if (this.state.name === '' || this.state.email === '' || this.state.password === '' || this.state.rePassword === '') { this.setState({errorMsg: '不能为空'}); return; } this.props.onSubmit(this.state.name, this.state.email, this.state.password, this.state.rePassword); } _onNameChange(e) { this.setState({name: e.target.value}); } _onEmailChange(e) { this.setState({email: e.target.value}); } _onPasswordChange(e) { this.setState({password: e.target.value}); } _onRePasswordChange(e) { this.setState({rePassword: e.target.value}); } render() { let errorMsgNode = null; if (this.state.errorMsg !== '') { errorMsgNode = ( <AlertMessageComp message={this.state.errorMsg} /> ); } return ( <form> {errorMsgNode} <FieldGroupComp id="nameText" ref="nameText" type="text" label="" placeholder="账号" onChange={this._onNameChange.bind(this)} /> <FieldGroupComp id="emailText" ref="emailText" type="email" label="" placeholder="邮箱" onChange={this._onEmailChange.bind(this)} /> <FieldGroupComp id="passwordText" ref="passwordText" type="password" label="" placeholder="密码" onChange={this._onPasswordChange.bind(this)} /> <FieldGroupComp id="re-passwordText" ref="re-passwordText" type="password" label="" placeholder="密码" onChange={this._onRePasswordChange.bind(this)} /> <Button onClick={this._onSignup.bind(this)}> 注册 </Button> </form> ); } } export default(Signup);
if (typeof Sizzle.selectors.pseudos.hidden == 'undefined') { Sizzle.selectors.pseudos.hidden = Sizzle.selectors.createPseudo(function() { return function(el) { return (el.offsetWidth <= 0 || el.offsetHeight <= 0) } }); }
export { default as AsyncBundle } from './AsyncBundle'; export { default as AsyncRoute } from './AsyncRoute'; export { default as asyncInjectors } from './asyncInjectors';
import React from 'react' import Accounts from './Accounts/Accounts' import OrderForm from './OrderForm/OrderForm' import './Sidebar.css' export default props => ( <div className='sidebar'> <Accounts /> <OrderForm /> </div> )
var shared = require('./shared.js'); var _ = require('lodash'); var data = null; var start = function(_data) { console.log("open tables started"); data = _data; poll(); } var poll = function() { var mysql = data.connections.mysql; var statsd = data.connections.statsd; var startMs = Date.now(); console.log('open tabled query started'); mysql.query("SHOW OPEN TABLES", function(err, rows){ process(rows); var ms = Date.now() - startMs; console.log('open tabled query finished: ' + ms.toString()); statsd.timing(shared.getMetricName(data.settings, 'watcher.poll_opentables'), ms); setTimeout(poll, data.settings.watcher.pollInterval); }); } var process = function(rows) { var statsd = data.connections.statsd; // Setup variables to store results in var total_open_tables = 0; var total_in_use = 0; var total_locked = 0; // Iterate over the rows _.forEach(rows, function(row){ total_open_tables++; total_in_use += row.In_use; total_locked += row.Name_locked; statsd.gauge(shared.getMetricName(data.settings, 'open_tables.' + row.Database + '.' + row.Table + '.in_use'), row.In_use); statsd.gauge(shared.getMetricName(data.settings, 'open_tables.' + row.Database + '.' + row.Table + '.name_locked'), row.Name_locked); }); statsd.gauge(shared.getMetricName(data.settings, 'open_tables.total_in_use'), total_in_use); statsd.gauge(shared.getMetricName(data.settings, 'open_tables.total_name_locked'), total_locked); } module.exports = { start: start };
#!/usr/bin/env node const Mustache = require("mustache"); const path = require("path"); const fs = require("fs"); const fsp = fs.promises; const { renderDocForName, renderIndexJson } = require("./render-api"); const root = path.resolve(path.join(__dirname, "..")); const repository = "https://github.com/crucialfelix/supercolliderjs"; const typedocRoot = "https://crucialfelix.github.io/supercolliderjs"; const docsRoot = "https://crucialfelix.github.io/supercolliderjs/#"; // Test locally with: // TODO: should be a fixed path for each to api.md // const docsRoot = "http://localhost:3000/#"; const packageNames = async () => { const names = (await fsp.readdir(path.join(root, "packages"))).filter(name => name.match(/^[a-z\-]+$/)); // preferred order const nn = ["supercolliderjs", "server", "server-plus", "lang", "dryads", "osc"]; // add any not already in that list names.forEach(n => { if (!nn.includes(n)) { nn.push(n); } }); return nn; }; async function fileExists(...paths) { return fsp.stat(path.join(root, ...paths)).then( stat => true, err => false, ); } const readFile = (...paths) => fs.readFileSync(path.join(root, ...paths), { encoding: "utf-8" }); const readJson = (...paths) => JSON.parse(readFile(...paths)); const writeFile = (paths, content) => fs.writeFileSync(path.join(root, ...paths), content, { encoding: "utf-8" }); const triple = "```"; const partials = { header: readFile("docs", "src", "partials", "header.md"), footer: readFile("docs", "src", "partials", "footer.md"), }; /** * Insert an example from /examples/ */ const example = text => { const body = readFile(text); const link = `${repository}/blob/develop/${text}`; return `${triple}js\n${body}\n${triple}\n<small class="source-link"><a href=${link}>source</a></small>\n`; }; /** * Insert a link to the TypeDocs page. * This was used when typedocs was rendered with it's default html export. * * @deprecated * @param {*} text */ const typedocLink = text => { const [title, link] = text.split(":", 2); const body = `[${title}](${typedocRoot}${link})`; return body; }; /** * Render Typedocs for an entity in package * Entity can be the name of a module, class, function, interface etc. * It searches down the API by name or "name" (with added quotes to detect module names). * @param {*} text package:EntityName */ const renderApi = text => { const [package, name] = text.split(":", 2); return renderDocForName(package, name); }; async function renderTplPath(srcPath, destPath, data) { const absTplPath = path.join(root, srcPath); if (!(await fileExists(srcPath))) { await fsp.mkdir(path.dirname(absTplPath), { recursive: true }); await fsp.writeFile(absTplPath, ""); } const tpl = readFile(srcPath); return renderTpl(tpl, destPath, data); } async function renderTpl(tpl, destPath, data) { const content = Mustache.render(tpl, data, partials); await fsp.writeFile(path.join(root, destPath), content); } const mdLink = (title, links) => `[${title}](${links.join("/")})`; const isString = thing => typeof thing === "string"; /** * Generate _sidebar.md * and return */ async function generateSidebar(packages) { const sb = []; sb.push("- " + mdLink("Getting started", ["README.md"])); sb.push("- npm packages"); const autos = {}; packages.forEach(short => { autos[short] = []; const index = readJson("packages", short, "index.json"); const { name } = readJson("packages", short, "package.json"); sb.push(` - ${mdLink(name, ["packages", short, "README.md"])}`); sb.push(` - ` + mdLink("API", ["packages", short, "api.md"])); // push one for each top level export for (const [key, value] of Object.entries(index)) { const page = isString(value) ? { title: value, filename: value + ".md" } : { title: key, filename: key + ".md" }; autos[short].push(page); // top level export sb.push(` - ` + mdLink(page.title, ["packages", short, page.filename])); } }); sb.push("- Guide"); sb.push(" - " + mdLink("Guide", ["https://crucialfelix.gitbooks.io/supercollider-js-guide/content/"])); sb.push(" - " + mdLink("Examples", ["https://github.com/crucialfelix/supercolliderjs-examples"])); const content = sb.join("\n"); writeFile(["docs", "_sidebar.md"], content); return autos; } function generateAutodocument(package, { title, filename }) { const BBL = "{{"; const BBR = "}}"; const BBBL = "{{{"; const BBBR = "}}}"; const fullname = filename.replace("_", "/").replace(".md", ""); const packageLink = `#/packages/${package}/api`; const body = `# ${title} Package: <a href="${packageLink}">${BBBL}name${BBBR}</a> ${BBL}#api${BBR}${package}:${fullname}${BBL}/api${BBR} `; return body; } /** * Make api.md file for a package */ function generateApi(name, short, packages) { const index = readJson("packages", short, "index.json"); // would want to know which file/url to link to for all of these // based on the sidebar? you would need a different way to specify pages to make. const content = renderIndexJson(index, short, packages); const body = `# ${name} ${content} `; writeFile(["docs", "src", "packages", short, "api.md"], body); } async function main(version) { const packages = await packageNames(); const pkg = readJson("package.json"); const rootData = { name: pkg.name, short: pkg.name.replace("@supercollider/", ""), description: pkg.description, version: version || pkg.version, homepage: pkg.hompage, repository, docsRoot, typedocRoot, example: () => example, typedocLink: () => typedocLink, api: () => renderApi, }; await renderTplPath("docs/src/_coverpage.md", "docs/_coverpage.md", rootData); const autos = await generateSidebar(packages); for (const pkgdir of packages) { const pkg = readJson("packages", pkgdir, "package.json"); const short = pkg.name.replace("@supercollider/", ""); const data = { ...rootData, name: pkg.name, short, description: pkg.description, version: pkg.version, homepage: pkg.hompage, }; // Generate api.md file for the module exports generateApi(pkg.name, short, packages); // Generate autodocument for each entry in autos for (const sidebarLink of autos[short] || []) { const tplBody = generateAutodocument(short, sidebarLink); await renderTpl(tplBody, path.join("docs", "packages", short, sidebarLink.filename), data); } for (const filename of fs.readdirSync(path.join("docs/src/packages", pkgdir))) { if (filename.endsWith(".md")) { const tplPath = path.join("docs/src/packages", pkgdir, filename); // Write it to docs await renderTplPath(tplPath, path.join("docs/packages", pkgdir, filename), data); if (filename === "README.md") { // Write to packages for publishing to npm await renderTplPath(tplPath, path.join("packages", pkgdir, filename), data); if (pkgdir === "supercolliderjs") { // Is also the main page in docs await renderTplPath(tplPath, path.join("docs", "README.md"), data); // and main page on github await renderTplPath(tplPath, "README.md", data); } } } } } } main(process.argv[2]).catch(console.error);
require( "../setup" ); var os = require( "os" ); var controlFn = require( "../../src/control" ); var fsm = { reset: _.noop, start: _.noop, stop: _.noop }; function getConfig() { return require( "../../src/config.js" )( { index: { frequency: 100 }, package: { // jshint ignore : line branch: "master", owner: "me", project: "test", build: 1 } } ); } describe( "Control", function() { var control; describe( "when changing service configuration", function() { describe( "and setting branch and version", function() { var fsmMock, config; before( function() { config = getConfig(); fsmMock = sinon.mock( fsm ); fsmMock.expects( "reset" ) .withArgs( config ) .once(); control = controlFn( config, fsm ); control.configure( [ { op: "change", field: "branch", value: "develop" }, { op: "change", field: "version", value: "0.1.1" }, { op: "change", field: "owner", value: "person" }, { op: "change", field: "releaseOnly", value: true } ] ); } ); it( "should change configuration", function() { config.package.should.eql( { architecture: "x64", branch: "develop", files: path.resolve( "./downloads" ), os: {}, osName: "any", osVersion: "any", owner: "person", platform: os.platform(), project: "test", releaseOnly: true, version: "0.1.1" } ); } ); it( "should change filter", function() { config.filter.toHash().should.eql( { architecture: "x64", branch: "develop", osName: "any", osVersion: "any", owner: "person", platform: os.platform(), project: "test", releaseOnly: true, version: "0.1.1" } ); } ); it( "should call fsm reset with config", function() { fsmMock.verify(); } ); describe( "then removing version", function() { var fsmMock; before( function() { fsmMock = sinon.mock( fsm ); fsmMock.expects( "reset" ) .withArgs( config ) .once(); control = controlFn( config, fsm ); control.configure( [ { op: "remove", field: "version" }, { op: "change", field: "releaseOnly", value: false } ] ); } ); it( "should remove version from config.package", function() { config.package.should.eql( { architecture: "x64", branch: "develop", files: path.resolve( "./downloads" ), os: {}, osName: "any", osVersion: "any", owner: "person", platform: os.platform(), project: "test", releaseOnly: false, version: undefined } ); } ); it( "should remove version filter", function() { config.filter.toHash().should.eql( { architecture: "x64", branch: "develop", osName: "any", osVersion: "any", owner: "person", platform: os.platform(), project: "test", releaseOnly: false } ); } ); it( "should call fsm reset with config", function() { fsmMock.verify(); } ); } ); describe( "then chaning owner and version with build included", function() { var fsmMock; before( function() { fsmMock = sinon.mock( fsm ); fsmMock.expects( "reset" ) .withArgs( config ) .once(); control = controlFn( config, fsm ); control.configure( [ { op: "change", field: "version", value: "0.1.1-10" }, { op: "change", field: "owner", value: "you" } ] ); } ); it( "should remove version from config.package", function() { config.package.should.eql( { architecture: "x64", branch: "develop", build: "10", files: path.resolve( "./downloads" ), os: {}, osName: "any", osVersion: "any", owner: "you", platform: os.platform(), project: "test", releaseOnly: false, version: "0.1.1" } ); } ); it( "should remove version filter", function() { config.filter.toHash().should.eql( { architecture: "x64", branch: "develop", build: "10", osName: "any", osVersion: "any", owner: "you", platform: os.platform(), project: "test", version: "0.1.1", releaseOnly: false } ); } ); it( "should call fsm reset with config", function() { fsmMock.verify(); } ); } ); } ); } ); describe( "when changing environment", function() { var config, fsmMock, fsm, result; before( function() { process.env.TO_REMOVE = "remove this"; process.env.TO_CHANGE = "change this"; config = getConfig(); fsmMock = sinon.mock( fsm ); control = controlFn( config, fsm ); result = control.setEnvironment( [ { op: "change", variable: "TO_CHANGE", value: "new value" }, { op: "remove", variable: "TO_REMOVE" } ] ); } ); it( "should have changed a variable and removed another", function() { result.should.eql( { TO_CHANGE: "new value", removed: [ "TO_REMOVE" ] } ); } ); } ); } );
/* ----------------------------------------------- /* How to use? : Check the GitHub README /* ----------------------------------------------- */ /* To load a config file (particles.json) you need to host this demo (MAMP/WAMP/local)... */ /* particlesJS.load('particles-js', 'particles.json', function() { console.log('particles.js loaded - callback'); }); */ /* Otherwise just put the config content (json): */ particlesJS('particles-js', { "particles": { "number": { "value": 80, "density": { "enable": true, "value_area": 800 } }, "color": { "value": "#ffffff" }, "shape": { "type": "triangle", "stroke": { "width": 0, "color": "#000000" }, "polygon": { "nb_sides": 5 }, "image": { "src": "img/github.svg", "width": 100, "height": 100 } }, "opacity": { "value": 0.8, "random": false, "anim": { "enable": false, "speed": 1, "opacity_min": 0.1, "sync": false } }, "size": { "value": 5, "random": true, "anim": { "enable": true, "speed": 40, "size_min": 0.1, "sync": false } }, "line_linked": { "enable": true, "distance": 150, "color": "#ffffff", "opacity": 0.4, "width": 1 }, "move": { "enable": true, "speed": 6, "direction": "none", "random": false, "straight": false, "out_mode": "out", "attract": { "enable": false, "rotateX": 600, "rotateY": 1200 } } }, "interactivity": { "detect_on": "canvas", "events": { "onhover": { "enable": true, "mode": "repulse" }, "onclick": { "enable": true, "mode": "push" }, "resize": true }, "modes": { "grab": { "distance": 400, "line_linked": { "opacity": 1 } }, "bubble": { "distance": 400, "size": 40, "duration": 2, "opacity": 8, "speed": 3 }, "repulse": { "distance": 200 }, "push": { "particles_nb": 4 }, "remove": { "particles_nb": 2 } } }, "retina_detect": true, "config_demo": { "hide_card": false, "background_color": "#b61924", "background_image": "", "background_position": "50% 50%", "background_repeat": "no-repeat", "background_size": "cover" } } ); function shadeBlendConvert(p, from, to) { if(typeof(p)!="number"||p<-1||p>1||typeof(from)!="string"||(from[0]!='r'&&from[0]!='#')||(typeof(to)!="string"&&typeof(to)!="undefined"))return null; //ErrorCheck if(!this.sbcRip)this.sbcRip=function(d){ var l=d.length,RGB=new Object(); if(l>9){ d=d.split(","); if(d.length<3||d.length>4)return null;//ErrorCheck RGB[0]=i(d[0].slice(4)),RGB[1]=i(d[1]),RGB[2]=i(d[2]),RGB[3]=d[3]?parseFloat(d[3]):-1; }else{ switch(l){case 8:case 6:case 3:case 2:case 1:return null;} //ErrorCheck if(l<6)d="#"+d[1]+d[1]+d[2]+d[2]+d[3]+d[3]+(l>4?d[4]+""+d[4]:""); //3 digit d=i(d.slice(1),16),RGB[0]=d>>16&255,RGB[1]=d>>8&255,RGB[2]=d&255,RGB[3]=l==9||l==5?r(((d>>24&255)/255)*10000)/10000:-1; } return RGB;} var i=parseInt,r=Math.round,h=from.length>9,h=typeof(to)=="string"?to.length>9?true:to=="c"?!h:false:h,b=p<0,p=b?p*-1:p,to=to&&to!="c"?to:b?"#000000":"#FFFFFF",f=sbcRip(from),t=sbcRip(to); if(!f||!t)return null; //ErrorCheck if(h)return "rgb("+r((t[0]-f[0])*p+f[0])+","+r((t[1]-f[1])*p+f[1])+","+r((t[2]-f[2])*p+f[2])+(f[3]<0&&t[3]<0?")":","+(f[3]>-1&&t[3]>-1?r(((t[3]-f[3])*p+f[3])*10000)/10000:t[3]<0?f[3]:t[3])+")"); else return "#"+(0x100000000+(f[3]>-1&&t[3]>-1?r(((t[3]-f[3])*p+f[3])*255):t[3]>-1?r(t[3]*255):f[3]>-1?r(f[3]*255):255)*0x1000000+r((t[0]-f[0])*p+f[0])*0x10000+r((t[1]-f[1])*p+f[1])*0x100+r((t[2]-f[2])*p+f[2])).toString(16).slice(f[3]>-1||t[3]>-1?1:3); } var element = document.getElementById("particles-js"); function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } window.setInterval(function(){ var r = getRandomArbitrary(0, 256); var g = getRandomArbitrary(0, 256); var b = getRandomArbitrary(0, 256); var rgb = "rgb("+r+","+g+","+b+")"; element.style.backgroundColor = shadeBlendConvert(0.3, rgb); }, 2000);
var searchData= [ ['terminateapp',['terminateApp',['../interface_app_controller.html#ae0129a03b62ed931ba468b50575661db',1,'AppController']]], ['termio',['termio',['../class_p_v_r_shell_init_o_s.html#a3b3c814c7c4cab3433bd4ac8e66606c5',1,'PVRShellInitOS']]], ['termio_5forig',['termio_orig',['../class_p_v_r_shell_init_o_s.html#a47c96e5dafa0b228248776c0ffca083d',1,'PVRShellInitOS']]], ['touchbegan',['TouchBegan',['../class_p_v_r_shell_init.html#ab5f5b886d015c504cb90e71d2c26f09f',1,'PVRShellInit']]], ['touchended',['TouchEnded',['../class_p_v_r_shell_init.html#a773d16f57f82ca258983bfc99de38b6c',1,'PVRShellInit']]], ['touchmoved',['TouchMoved',['../class_p_v_r_shell_init.html#a1d9afa797314503bd7f641c49e1be3a4',1,'PVRShellInit']]] ];
import React from "react"; import { mount } from "enzyme"; test("react/multiple: test trim spaces functionality", () => { require("../../../src/inputs/multiple"); require("../../../src/plugins/tokenizer"); require("../../../src/templates"); const SelectivityReact = require("../../../src/apis/react").default; const el = mount( <SelectivityReact multiple={true} showDropdown={false} tokenSeparators={[","]} trimSpaces={true} />, ).getDOMNode(); el.querySelector(".selectivity-multiple-input").value = " Amsterdam , Berlin , "; el.querySelector(".selectivity-multiple-input").dispatchEvent(new KeyboardEvent("keyup")); expect(el.selectivity.getData()).toEqual([ { id: "Amsterdam", text: "Amsterdam" }, { id: "Berlin", text: "Berlin" }, ]); expect(el.selectivity.getValue()).toEqual(["Amsterdam", "Berlin"]); }); test("react/multiple: test allow duplicates", () => { require("../../../src/inputs/multiple"); require("../../../src/plugins/tokenizer"); require("../../../src/templates"); const SelectivityReact = require("../../../src/apis/react").default; const el = mount( <SelectivityReact allowDuplicates={true} multiple={true} showDropdown={false} tokenSeparators={[","]} />, ).getDOMNode(); el.querySelector(".selectivity-multiple-input").value = "Berlin,Amsterdam,Berlin,"; el.querySelector(".selectivity-multiple-input").dispatchEvent(new KeyboardEvent("keyup")); expect(el.selectivity.getData()).toEqual([ { id: "Berlin", text: "Berlin" }, { id: "Amsterdam", text: "Amsterdam" }, { id: "Berlin", text: "Berlin" }, ]); expect(el.selectivity.getValue()).toEqual(["Berlin", "Amsterdam", "Berlin"]); });
var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); function preload() { game.load.tilemap('level3', 'assets/tilemaps/maps/cybernoid.json', null, Phaser.Tilemap.TILED_JSON); game.load.image('tiles', 'assets/tilemaps/tiles/cybernoid.png', 16, 16); } var map; var layer; var cursors; function create() { map = game.add.tilemap('level3'); map.addTilesetImage('CybernoidMap3BG_bank.png', 'tiles'); // Start with a small layer only 400x200 and increase it by 100px // each time we click layer = map.createLayer(0, 400, 200); layer.resizeWorld(); cursors = game.input.keyboard.createCursorKeys(); game.input.onDown.add(resize, this); } function resize() { // 400,500,600,700,800 // 200,300,400,500,600 if (layer.width < 800) { var w = layer.width + 100; var h = layer.height + 100; layer.resize(w, h); } } function update() { if (cursors.up.isDown) { game.camera.y--; } else if (cursors.down.isDown) { game.camera.y++; } if (cursors.left.isDown) { game.camera.x--; } else if (cursors.right.isDown) { game.camera.x++; } }
import m from 'mithril'; import prop from 'mithril/stream'; import mq from 'mithril-query'; import userBalanceRequestModelContent from '../../src/c/user-balance-request-modal-content'; import { catarse } from '../../src/api'; import models from '../../src/models'; xdescribe('UserBalanceRequestModalContent', () => { describe('view', function () { const user_id = 1000; const userIdVM = catarse.filtersVM({ user_id: 'eq' }); let attrs = null; let userBankAccount = null; let component = null; beforeAll(() => { // User Bank Account // catarse api /bank_accounts?user_id=eq.1000 jasmine.Ajax.stubRequest(new RegExp('(' + apiPrefix + `\/bank_accounts?user_id=eq.${user_id})` + '(.*)')).andReturn({ responseText: JSON.stringify([ UserBalanceRequestModalContentUserBankAccountMock() ]) }); attrs = UserBalanceRequestModalContentMock(); userBankAccount = UserBalanceRequestModalContentUserBankAccountMock(); userIdVM.user_id(user_id); attrs.bankCode = prop(''); attrs.bankInput = prop(''); attrs.balanceManager = (() => { const collection = prop([{ amount: 0, user_id }]); const load = () => { return models.balance .getRowWithToken(userIdVM.parameters()) .then(collection) .then(_ => m.redraw()); }; return { collection, load }; })(); attrs.bankAccountManager = (() => { const collection = prop([]); const loader = (() => catarse.loaderWithToken(models.bankAccount.getRowOptions(userIdVM.parameters())))(); const load = () => { return loader .load() .then(collection) .then(() => m.redraw()); }; return { collection, load, loader }; })(); component = mq(m(userBalanceRequestModelContent, attrs)); }); it('should load user bank account', (done) => { const testInterval = setInterval(() => { try { component.should.have(`select.select.required.w-input.text-field.bank-select.positive > option[value='${userBankAccount.bank_id}']`); clearInterval(testInterval); done(); } catch (e) { } }, 50); }); }); });
module.exports = { transform: { '^.+\\.js$': '<rootDir>/jest.transform.js' } }
/* * Copyright (C) 2015 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. All Rights Reserved. */ /** * @exports SurfaceRenderable * @version $Id: SurfaceRenderable.js 3351 2015-07-28 22:03:20Z dcollins $ */ define(['../util/Logger', '../error/UnsupportedOperationError' ], function (Logger, UnsupportedOperationError) { "use strict"; /** * Applications must not call this constructor. It is an interface class and is not meant to be instantiated * directly. * @alias SurfaceRenderable * @constructor * @classdesc Represents a surface renderable. * This is an interface class and is not meant to be instantiated directly. */ var SurfaceRenderable = function () { /** * This surface renderable's display name. * @type {String} * @default Renderable */ this.displayName = "Renderable"; /** * Indicates whether this surface renderable is enabled. * @type {Boolean} * @default true */ this.enabled = true; throw new UnsupportedOperationError( Logger.logMessage(Logger.LEVEL_SEVERE, "SurfaceRenderable", "constructor", "abstractInvocation")); }; /** * Renders this surface renderable. * @param {DrawContext} dc The current draw context. */ SurfaceRenderable.prototype.renderSurface = function (dc) { throw new UnsupportedOperationError( Logger.logMessage(Logger.LEVEL_SEVERE, "SurfaceRenderable", "renderSurface", "abstractInvocation")); }; return SurfaceRenderable; });
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { FormattedMessage, FormattedHTMLMessage } from 'react-intl'; import injectIntl from '../utils/injectIntl'; import GlobalLeaderBoards from './GlobalLeaderBoards'; import LeaderBoard from './LeaderBoard'; import ChallengeList from '../components/ChallengeList'; import Footer from '../components/Footer'; import HiddenText from '../components/HiddenText'; import LanguageSelection from '../components/LanguageSelection'; import mosaic from '../images/mosaic.png'; const FrontPage = (props, context) => ( <div className="front-page"> <main> <h1> <FormattedMessage id="app.name" /> <span className="subtitle"> <FormattedHTMLMessage id="app.tagline" /> </span> </h1> <div className="mosaic" style={{ backgroundImage: `url(${mosaic})` }}> <div className="fade" /> </div> <div className="game-info"> <p> <strong><FormattedHTMLMessage id="app.description" /></strong> </p> <HiddenText buttonText={context.intl.formatMessage({ id: 'frontPage.readDescription' })} > <div className="etm-description"> <FormattedHTMLMessage id="frontPage.etmDescription" /> </div> </HiddenText> <div className="play-wrapper"> <Link to="/play" className="button"> <FormattedMessage id="frontPage.playGame" />{' '} <span className="arrows">&raquo;</span> </Link> <LanguageSelection setLocale={props.setLocale} /> </div> </div> <div className="global-leaderboards"> <h2><FormattedMessage id="leaderboard.all" /></h2> <GlobalLeaderBoards base={props.base} /> </div> <div className="challenges"> <h2><FormattedMessage id="challenges.title" /></h2> <ChallengeList base={props.base} active /> <Link to="/new-challenge" className="button new-challenge"> <FormattedMessage id="challenges.create" /> </Link> <p className="challenge-info"> <FormattedMessage id="challenges.description" /> </p> </div> </main> <Footer setLocale={props.setLocale} /> </div> ); FrontPage.propTypes = { base: PropTypes.shape({ ...LeaderBoard.propTypes.base, ...ChallengeList.propTypes.base }), setLocale: PropTypes.func.isRequired }; export default injectIntl(FrontPage);
module.exports = { description: "", ns: "react-material-ui", type: "ReactNode", dependencies: { npm: { "material-ui/svg-icons/maps/local-movies": require('material-ui/svg-icons/maps/local-movies') } }, name: "MapsLocalMovies", ports: { input: {}, output: { component: { title: "MapsLocalMovies", type: "Component" } } } }
'use strict'; function wait (time) { return new Promise((fulfill) => { setTimeout(fulfill, time); }); } module.exports = wait;
import React from 'react' import { render } from 'react-dom' import HandsUpApp from './components/HandsUpApp' import { ApolloProvider } from 'react-apollo' import { client } from './client' import { createStore, combineReducers, applyMiddleware, compose } from 'redux' import { HashRouter, Route } from 'react-router-dom' import Authorisation from './services/Authorisation' import './style.css' import 'react-s-alert/dist/s-alert-default.css' import 'react-s-alert/dist/s-alert-css-effects/slide.css' const combinedReducer = combineReducers({ apollo: client.reducer(), }) const store = compose( applyMiddleware( client.middleware(), ), window.devToolsExtension ? window.devToolsExtension() : f => f )(createStore)(combinedReducer) const auth = new Authorisation() class HandsUpAppWrapper extends React.Component { render() { return ( <HandsUpApp auth={auth} client={client} /> ) } } render( <ApolloProvider store={store} client={client}> <HashRouter> <Route path='/' component={HandsUpAppWrapper} /> </HashRouter> </ApolloProvider>, document.getElementById('root') )
import React, { PropTypes } from 'react'; import { Link } from 'react-router'; import userStore from '../stores/users'; import UserTeaser from './UserTeaser'; class UserList extends React.Component { constructor() { super(); this.state = {}; userStore.findAll() .then(users => this.setState({ users })) .catch(err => console.error(err)); } render() { const users = this.state.users; let listDisplay = null; if (users) { listDisplay = ( <ul className="member-list-members"> {users.map((user, i) => <li className="stats-list-item" key={i}><UserTeaser user={user}/></li>)} </ul> ); } return ( <section className="member-list stats-list"> {listDisplay || (<div className="member-list-loading">Contributor list loading…</div>)} </section> ); } } export default UserList;
'use strict'; var _ = require('underscore'); var utils = require('./utils'); module.exports = EntityLookup; function EntityLookup() { var entities = {}, noWhiteSpaceEntities = {}, entityProcessors = {}, versionCheckers = {}, self = this; this.configureEntity = function(entityName, processors, versionChecker) { entities[entityName] = {}; noWhiteSpaceEntities[entityName] = {}; entityProcessors[entityName] = processors; versionCheckers[entityName] = versionChecker; }; this.addEntities = function(entitiesObject) { var results = { errors: [] }; _.chain(entitiesObject) .omit('version', 'patch') .each(function(entityArray, type) { results[type] = { withErrors: [], skipped: [], deleted: [], patched: [], added: [] }; if(!entities[type]) { results.errors.push({ entity: 'general', errors: ['Unrecognised entity type ' + type] }); return; } if(!versionCheckers[type](entitiesObject.version, results.errors)) { return; } _.each(entityArray, function(entity) { var key = entity.name.toLowerCase(); var operation = !!entities[type][key] ? (entitiesObject.patch ? 'patched' : 'skipped') : 'added'; if(operation === 'patched') { entity = patchEntity(entities[type][key], entity); if(!entity) { operation = 'deleted'; delete entities[type][key]; delete noWhiteSpaceEntities[type][key.replace(/\s+/g, '')]; } } if(_.contains(['patched', 'added'], operation)) { var processed = _.reduce(entityProcessors[type], utils.executor, { entity: entity, type: type, version: entitiesObject.version, errors: [] }); if(!_.isEmpty(processed.errors)) { processed.entity = processed.entity.name; results.errors.push(processed); operation = 'withErrors'; } else { if(processed.entity.name.toLowerCase() !== key) { results[type].deleted.push(key); delete entities[type][key]; delete noWhiteSpaceEntities[type][key.replace(/\s+/g, '')]; key = processed.entity.name.toLowerCase(); } entities[type][key] = processed.entity; noWhiteSpaceEntities[type][key.replace(/\s+/g, '')] = processed.entity; } } results[type][operation].push(key); }); }); return results; }; this.findEntity = function(type, name, tryWithoutWhitespace) { var key = name.toLowerCase(); if(!entities[type]) { throw new Error('Unrecognised entity type ' + type); } var found = entities[type][key]; if(!found && tryWithoutWhitespace) { found = noWhiteSpaceEntities[type][key.replace(/\s+/g, '')]; } return found && utils.deepClone(found); }; this.getAll = function(type) { if(!entities[type]) { throw new Error('Unrecognised entity type: ' + type); } return utils.deepClone(_.values(entities[type])); }; /** * Gets all of the keys for the specified entity type * @param {string} type - The entity type to retrieve keys for (either 'monster' or 'spell') * @param {boolean} sort - True if the returned array should be sorted alphabetically; false otherwise * @function * @public * @name EntityLookup#getKeys * @return {Array} An array containing all keys for the specified entity type */ this.getKeys = function(type, sort) { if(!entities[type]) { throw new Error('Unrecognised entity type: ' + type); } var keys = _.keys(entities[type]); if(sort) { keys.sort(); } return keys; }; /** * Gets spell hydrator * @function * @public * @name EntityLookup#getSpellHydrator * @return {function} */ this.getSpellHydrator = function() { return function(monsterInfo) { var monster = monsterInfo.entity; if(monster.spells) { monster.spells = _.map(monster.spells.split(', '), function(spellName) { return self.findEntity('spells', spellName) || spellName; }); } return monsterInfo; }; }; this.getMonsterSpellUpdater = function() { return function(spellInfo) { var spell = spellInfo.entity; _.chain(entities.monsters) .pluck('spells') .compact() .each(function(spellArray) { var spellIndex = _.findIndex(spellArray, function(monsterSpell) { if(typeof monsterSpell === 'string') { return monsterSpell.toLowerCase() === spell.name.toLowerCase(); } else { return monsterSpell !== spell && monsterSpell.name.toLowerCase() === spell.name.toLowerCase(); } }); if(spellIndex !== -1) { spellArray[spellIndex] = spell; } }); return spellInfo; }; }; this.toJSON = function() { return { monsterCount: _.size(entities.monsters), spellCount: _.size(entities.spells) }; }; } EntityLookup.prototype.logWrap = 'entityLookup'; EntityLookup.jsonValidatorAsEntityProcessor = function(jsonValidator) { return function(entityInfo) { var wrapper = { version: entityInfo.version }; wrapper[entityInfo.type] = [entityInfo.entity]; var errors = jsonValidator.validate(wrapper); var flattenedErrors = _.chain(errors).values().flatten().value(); entityInfo.errors = entityInfo.errors.concat(flattenedErrors); return entityInfo; }; }; EntityLookup.jsonValidatorAsVersionChecker = function(jsonValidator) { return EntityLookup.getVersionChecker(jsonValidator.getVersionNumber()); }; EntityLookup.getVersionChecker = function(requiredVersion) { return function(version, errorsArray) { var valid = version === requiredVersion; if(!valid) { errorsArray.push({ entity: 'general', errors: ['Incorrect entity objects version: [' + version + ']. Required is: ' + requiredVersion] }); } return valid; }; }; function patchEntity(original, patch) { if(patch.remove) { return undefined; } return _.mapObject(original, function(propVal, propName) { if(propName === 'name' && patch.newName) { return patch.newName; } return patch[propName] || propVal; }); }
/******************************************************************************* * Copyright 2013-2014 Aerospike, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ // we want to test the built aerospike module var aerospike = require('../lib/aerospike'); var options = require('./util/options'); var assert = require('assert'); var expect = require('expect.js'); var keygen = require('./generators/key'); var metagen = require('./generators/metadata'); var recgen = require('./generators/record'); var putgen = require('./generators/put'); var status = aerospike.status; var policy = aerospike.policy; describe('client.index()', function() { var config = options.getConfig(); var client = aerospike.client(config); before(function(done) { client.connect(function(err){ done(); }); }); after(function(done) { client.close(); client = null; done(); }); it('should create an integer index', function(done) { var args = { ns: options.namespace, set: options.set, bin : "integer_bin", index: "integer_index" } client.createIntegerIndex(args, function(err) { expect(err).to.be.ok(); expect(err.code).to.equal(status.AEROSPIKE_OK); done(); }); }); it('should create an string index', function(done) { var args = { ns: options.namespace, set: options.set, bin : "string_bin", index: "string_index" } client.createStringIndex(args, function(err) { expect(err).to.be.ok(); expect(err.code).to.equal(status.AEROSPIKE_OK); done(); }); }); it('should create an integer index with info policy', function(done) { var args = { ns: options.namespace, set: options.set, bin : "policy_bin", index: "policy_index", policy:{ timeout : 1000, send_as_is: true, check_bounds: false }} client.createIntegerIndex(args, function(err) { expect(err).to.be.ok(); expect(err.code).to.equal(status.AEROSPIKE_OK); done(); }); }); it('should drop an index', function(done) { client.indexRemove(options.namespace, "string_integer", function(err) { expect(err).to.be.ok(); expect(err.code).to.equal(status.AEROSPIKE_OK); done(); }); }); it('should create an integer index and wait until index creation is done', function(done) { var args = { ns: options.namespace, set: options.set, bin : "integer_done", index: "integer_index_done" } client.createIntegerIndex(args, function(err) { expect(err).to.be.ok(); expect(err.code).to.equal(status.AEROSPIKE_OK); client.indexCreateWait(options.namespace, "integer_index_done", 1000, function(err) { expect(err).to.be.ok(); expect(err.code).to.equal(status.AEROSPIKE_OK); done(); }); }); }); it('should create a string index and wait until index creation is done', function(done) { var args = { ns: options.namespace, set: options.set, bin : "string_done", index: "string_index_done" } client.createStringIndex(args, function(err) { expect(err).to.be.ok(); expect(err.code).to.equal(status.AEROSPIKE_OK); client.indexCreateWait(options.namespace, "string_index_done", 1000, function(err) { expect(err).to.be.ok(); expect(err.code).to.equal(status.AEROSPIKE_OK); done(); }); }); }); });
'use strict'; function SettingCopyCtrl($scope, Utils, $modal, SettingsRepository) { var vm = this; var viewPath = 'gzero/admin/views/settings/directives/'; // Copy modal vm.copyModal = { /** * Function initiates the AngularStrap modal * * @param title translatable title of modal * @param message translatable messages of modal */ initModal: function(title, message) { var self = this; self.modal = $modal({ scope: $scope, title: title, content: message, templateUrl: viewPath + 'settingCopyModal.tpl.html', show: true, placement: 'center' }); }, /** * Function shows the AngularStrap modal * * @param attrs attributes from directive */ showModal: function(attrs) { var self = this; vm.attrs = attrs; self.initModal('PLEASE_CONFIRM', 'OPTIONS_LANG.COPY_OPTION_QUESTION'); }, /** * Function close the modal * */ closeModal: function() { var self = this; self.modal.hide(); }, /** * Function apply setting value to other languages and performs the RestAngular PUT action for option value * */ saveSetting: function() { var self = this; self.closeModal(); // prepare option data var data = { key: vm.attrs.optionKey, value: angular.fromJson(vm.attrs.optionValue) }; // set option value to all other languages _.forEach(data.value, function(n, key) { data.value[key] = vm.attrs.optionNewValue; }); // save option SettingsRepository.update(vm.attrs.categoryKey, data).then(function() { Utils.Notifications.addSuccess('OPTIONS_LANG.COPY_CONFIRM'); Utils.$state.reload(); }); } }; } SettingCopyCtrl.$inject = ['$scope', 'Utils', '$modal', 'SettingsRepository']; module.exports = SettingCopyCtrl;
export default { props: { foo: true, bar: true }, html: '<div class="foo bar"></div>', test({ assert, component, target }) { component.foo = false; assert.htmlEqual(target.innerHTML, ` <div class="bar"></div> `); } };
var componentsUtil = require("./util"); var runtimeId = componentsUtil.___runtimeId; var componentLookup = componentsUtil.___componentLookup; var getMarkoPropsFromEl = componentsUtil.___getMarkoPropsFromEl; var TEXT_NODE = 3; // We make our best effort to allow multiple marko runtimes to be loaded in the // same window. Each marko runtime will get its own unique runtime ID. var listenersAttachedKey = "$MDE" + runtimeId; var delegatedEvents = {}; function getEventFromEl(el, eventName) { var virtualProps = getMarkoPropsFromEl(el); var eventInfo = virtualProps[eventName]; if (typeof eventInfo === "string") { eventInfo = eventInfo.split(" "); if (eventInfo[2]) { eventInfo[2] = eventInfo[2] === "true"; } if (eventInfo.length == 4) { eventInfo[3] = parseInt(eventInfo[3], 10); } } return eventInfo; } function delegateEvent(node, eventName, target, event) { var targetMethod = target[0]; var targetComponentId = target[1]; var isOnce = target[2]; var extraArgs = target[3]; if (isOnce) { var virtualProps = getMarkoPropsFromEl(node); delete virtualProps[eventName]; } var targetComponent = componentLookup[targetComponentId]; if (!targetComponent) { return; } var targetFunc = typeof targetMethod === "function" ? targetMethod : targetComponent[targetMethod]; if (!targetFunc) { throw Error("Method not found: " + targetMethod); } if (extraArgs != null) { if (typeof extraArgs === "number") { extraArgs = targetComponent.___bubblingDomEvents[extraArgs]; } } // Invoke the component method if (extraArgs) { targetFunc.apply(targetComponent, extraArgs.concat(event, node)); } else { targetFunc.call(targetComponent, event, node); } } function addDelegatedEventHandler(eventType) { if (!delegatedEvents[eventType]) { delegatedEvents[eventType] = true; } } function addDelegatedEventHandlerToHost(eventType, host) { var listeners = (host[listenersAttachedKey] = host[listenersAttachedKey] || {}); if (!listeners[eventType]) { (host.body || host).addEventListener( eventType, (listeners[eventType] = function (event) { var propagationStopped = false; // Monkey-patch to fix #97 var oldStopPropagation = event.stopPropagation; event.stopPropagation = function () { oldStopPropagation.call(event); propagationStopped = true; }; var curNode = event.target; if (!curNode) { return; } curNode = // event.target of an SVGElementInstance does not have a // `getAttribute` function in IE 11. // See https://github.com/marko-js/marko/issues/796 curNode.correspondingUseElement || // in some browsers the event target can be a text node // one example being dragenter in firefox. (curNode.nodeType === TEXT_NODE ? curNode.parentNode : curNode); // Search up the tree looking DOM events mapped to target // component methods var propName = "on" + eventType; var target; // Attributes will have the following form: // on<event_type>("<target_method>|<component_id>") do { if ((target = getEventFromEl(curNode, propName))) { delegateEvent(curNode, propName, target, event); if (propagationStopped) { break; } } } while ((curNode = curNode.parentNode) && curNode.getAttribute); }), true ); } } function noop() {} exports.___handleNodeAttach = noop; exports.___handleNodeDetach = noop; exports.___delegateEvent = delegateEvent; exports.___getEventFromEl = getEventFromEl; exports.___addDelegatedEventHandler = addDelegatedEventHandler; exports.___init = function (host) { Object.keys(delegatedEvents).forEach(function (eventType) { addDelegatedEventHandlerToHost(eventType, host); }); };
'use strict'; /** * Logger module */ const winston = require('winston'); const mkdirp = require('mkdirp'); const time = require('./time'); const config = require('../config/config'); const LOG_DIR = config.logging.pathDir; const FORMAT_TIME = 'DD/MM/YYYY HH:mm:ss:SSS'; const transports = []; const console = new winston.transports.Console({ level: 'debug', colorize: true, prettyPrint: true, handleExceptions: true, timestamp: () => { return time.getMoment(FORMAT_TIME); } }); const allFile = new winston.transports.File({ name: 'file.info', level: 'info', filename: `${LOG_DIR}/all.log`, maxFiles: 10, maxsize: 10485760, json: false, colorize: true, prettyPrint: true, handleExceptions: true, timestamp: () => { return time.getMoment(FORMAT_TIME); } }); const errorFile = new winston.transports.File({ name: 'file.error', level: 'error', filename: `${LOG_DIR}/errors.log`, maxFiles: 10, maxsize: 10485760, json: false, colorize: true, prettyPrint: true, handleExceptions: true, timestamp: () => { return time.getMoment(FORMAT_TIME); } }); if (config.logging.files) { mkdirp.sync(LOG_DIR); transports.push(console, allFile, errorFile); } else { transports.push(console); } const log = new winston.Logger({transports}); function removeConsoleTransport() { log.remove(winston.transports.Console); } module.exports = log; module.exports.removeConsoleTransport = removeConsoleTransport; module.exports.stream = { write: (message) => { log.info(message); } };
/** * The `Matter.Engine` module contains methods for creating and manipulating engines. * An engine is a controller that manages updating the simulation of the world. * See `Matter.Runner` for an optional game loop utility. * * See the included usage [examples](https://github.com/liabru/matter-js/tree/master/examples). * * @class Engine */ var Engine = {}; module.exports = Engine; var World = require('../body/World'); var Sleeping = require('./Sleeping'); var Resolver = require('../collision/Resolver'); var Render = require('../render/Render'); var Pairs = require('../collision/Pairs'); var Metrics = require('./Metrics'); var Grid = require('../collision/Grid'); var Events = require('./Events'); var Composite = require('../body/Composite'); var Constraint = require('../constraint/Constraint'); var Common = require('./Common'); var Body = require('../body/Body'); (function() { /** * Creates a new engine. The options parameter is an object that specifies any properties you wish to override the defaults. * All properties have default values, and many are pre-calculated automatically based on other properties. * See the properties section below for detailed information on what you can pass via the `options` object. * @method create * @param {object} [options] * @return {engine} engine */ Engine.create = function(element, options) { // options may be passed as the first (and only) argument options = Common.isElement(element) ? options : element; element = Common.isElement(element) ? element : null; options = options || {}; if (element || options.render) { Common.warn('Engine.create: engine.render is deprecated (see docs)'); } var defaults = { positionIterations: 6, velocityIterations: 4, constraintIterations: 2, enableSleeping: false, events: [], plugin: {}, timing: { timestamp: 0, timeScale: 1 }, broadphase: { controller: Grid } }; var engine = Common.extend(defaults, options); // @deprecated if (element || engine.render) { var renderDefaults = { element: element, controller: Render }; engine.render = Common.extend(renderDefaults, engine.render); } // @deprecated if (engine.render && engine.render.controller) { engine.render = engine.render.controller.create(engine.render); } // @deprecated if (engine.render) { engine.render.engine = engine; } engine.world = options.world || World.create(engine.world); engine.pairs = Pairs.create(); engine.broadphase = engine.broadphase.controller.create(engine.broadphase); engine.metrics = engine.metrics || { extended: false }; // @if DEBUG engine.metrics = Metrics.create(engine.metrics); // @endif return engine; }; /** * Moves the simulation forward in time by `delta` ms. * The `correction` argument is an optional `Number` that specifies the time correction factor to apply to the update. * This can help improve the accuracy of the simulation in cases where `delta` is changing between updates. * The value of `correction` is defined as `delta / lastDelta`, i.e. the percentage change of `delta` over the last step. * Therefore the value is always `1` (no correction) when `delta` constant (or when no correction is desired, which is the default). * See the paper on <a href="http://lonesock.net/article/verlet.html">Time Corrected Verlet</a> for more information. * * Triggers `beforeUpdate` and `afterUpdate` events. * Triggers `collisionStart`, `collisionActive` and `collisionEnd` events. * @method update * @param {engine} engine * @param {number} [delta=16.666] * @param {number} [correction=1] */ Engine.update = function(engine, delta, correction) { delta = delta || 1000 / 60; correction = correction || 1; var world = engine.world, timing = engine.timing, broadphase = engine.broadphase, broadphasePairs = [], i; // increment timestamp timing.timestamp += delta * timing.timeScale; // create an event object var event = { timestamp: timing.timestamp }; Events.trigger(engine, 'beforeUpdate', event); // get lists of all bodies and constraints, no matter what composites they are in var allBodies = Composite.allBodies(world), allConstraints = Composite.allConstraints(world); // @if DEBUG // reset metrics logging Metrics.reset(engine.metrics); // @endif // if sleeping enabled, call the sleeping controller if (engine.enableSleeping) Sleeping.update(allBodies, timing.timeScale); // applies gravity to all bodies _bodiesApplyGravity(allBodies, world.gravity); // update all body position and rotation by integration _bodiesUpdate(allBodies, delta, timing.timeScale, correction, world.bounds); // update all constraints (first pass) Constraint.preSolveAll(allBodies); for (i = 0; i < engine.constraintIterations; i++) { Constraint.solveAll(allConstraints, timing.timeScale); } Constraint.postSolveAll(allBodies); // broadphase pass: find potential collision pairs if (broadphase.controller) { // if world is dirty, we must flush the whole grid if (world.isModified) broadphase.controller.clear(broadphase); // update the grid buckets based on current bodies broadphase.controller.update(broadphase, allBodies, engine, world.isModified); broadphasePairs = broadphase.pairsList; } else { // if no broadphase set, we just pass all bodies broadphasePairs = allBodies; } // clear all composite modified flags if (world.isModified) { Composite.setModified(world, false, false, true); } // narrowphase pass: find actual collisions, then create or update collision pairs var collisions = broadphase.detector(broadphasePairs, engine); // update collision pairs var pairs = engine.pairs, timestamp = timing.timestamp; Pairs.update(pairs, collisions, timestamp); Pairs.removeOld(pairs, timestamp); // wake up bodies involved in collisions if (engine.enableSleeping) Sleeping.afterCollisions(pairs.list, timing.timeScale); // trigger collision events if (pairs.collisionStart.length > 0) Events.trigger(engine, 'collisionStart', { pairs: pairs.collisionStart }); // iteratively resolve position between collisions Resolver.preSolvePosition(pairs.list); for (i = 0; i < engine.positionIterations; i++) { Resolver.solvePosition(pairs.list, timing.timeScale); } Resolver.postSolvePosition(allBodies); // update all constraints (second pass) Constraint.preSolveAll(allBodies); for (i = 0; i < engine.constraintIterations; i++) { Constraint.solveAll(allConstraints, timing.timeScale); } Constraint.postSolveAll(allBodies); // iteratively resolve velocity between collisions Resolver.preSolveVelocity(pairs.list); for (i = 0; i < engine.velocityIterations; i++) { Resolver.solveVelocity(pairs.list, timing.timeScale); } // trigger collision events if (pairs.collisionActive.length > 0) Events.trigger(engine, 'collisionActive', { pairs: pairs.collisionActive }); if (pairs.collisionEnd.length > 0) Events.trigger(engine, 'collisionEnd', { pairs: pairs.collisionEnd }); // @if DEBUG // update metrics log Metrics.update(engine.metrics, engine); // @endif // clear force buffers _bodiesClearForces(allBodies); Events.trigger(engine, 'afterUpdate', event); return engine; }; /** * Merges two engines by keeping the configuration of `engineA` but replacing the world with the one from `engineB`. * @method merge * @param {engine} engineA * @param {engine} engineB */ Engine.merge = function(engineA, engineB) { Common.extend(engineA, engineB); if (engineB.world) { engineA.world = engineB.world; Engine.clear(engineA); var bodies = Composite.allBodies(engineA.world); for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; Sleeping.set(body, false); body.id = Common.nextId(); } } }; /** * Clears the engine including the world, pairs and broadphase. * @method clear * @param {engine} engine */ Engine.clear = function(engine) { var world = engine.world; Pairs.clear(engine.pairs); var broadphase = engine.broadphase; if (broadphase.controller) { var bodies = Composite.allBodies(world); broadphase.controller.clear(broadphase); broadphase.controller.update(broadphase, bodies, engine, true); } }; /** * Zeroes the `body.force` and `body.torque` force buffers. * @method bodiesClearForces * @private * @param {body[]} bodies */ var _bodiesClearForces = function(bodies) { for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; // reset force buffers body.force.x = 0; body.force.y = 0; body.torque = 0; } }; /** * Applys a mass dependant force to all given bodies. * @method bodiesApplyGravity * @private * @param {body[]} bodies * @param {vector} gravity */ var _bodiesApplyGravity = function(bodies, gravity) { var gravityScale = typeof gravity.scale !== 'undefined' ? gravity.scale : 0.001; if ((gravity.x === 0 && gravity.y === 0) || gravityScale === 0) { return; } for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (body.isStatic || body.isSleeping) continue; // apply gravity body.force.y += body.mass * gravity.y * gravityScale; body.force.x += body.mass * gravity.x * gravityScale; } }; /** * Applys `Body.update` to all given `bodies`. * @method updateAll * @private * @param {body[]} bodies * @param {number} deltaTime * The amount of time elapsed between updates * @param {number} timeScale * @param {number} correction * The Verlet correction factor (deltaTime / lastDeltaTime) * @param {bounds} worldBounds */ var _bodiesUpdate = function(bodies, deltaTime, timeScale, correction, worldBounds) { for (var i = 0; i < bodies.length; i++) { var body = bodies[i]; if (body.isStatic || body.isSleeping) continue; Body.update(body, deltaTime, timeScale, correction); } }; /** * An alias for `Runner.run`, see `Matter.Runner` for more information. * @method run * @param {engine} engine */ /** * Fired just before an update * * @event beforeUpdate * @param {} event An event object * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired after engine update and all collision events * * @event afterUpdate * @param {} event An event object * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired after engine update, provides a list of all pairs that have started to collide in the current tick (if any) * * @event collisionStart * @param {} event An event object * @param {} event.pairs List of affected pairs * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired after engine update, provides a list of all pairs that are colliding in the current tick (if any) * * @event collisionActive * @param {} event An event object * @param {} event.pairs List of affected pairs * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /** * Fired after engine update, provides a list of all pairs that have ended collision in the current tick (if any) * * @event collisionEnd * @param {} event An event object * @param {} event.pairs List of affected pairs * @param {number} event.timestamp The engine.timing.timestamp of the event * @param {} event.source The source object of the event * @param {} event.name The name of the event */ /* * * Properties Documentation * */ /** * An integer `Number` that specifies the number of position iterations to perform each update. * The higher the value, the higher quality the simulation will be at the expense of performance. * * @property positionIterations * @type number * @default 6 */ /** * An integer `Number` that specifies the number of velocity iterations to perform each update. * The higher the value, the higher quality the simulation will be at the expense of performance. * * @property velocityIterations * @type number * @default 4 */ /** * An integer `Number` that specifies the number of constraint iterations to perform each update. * The higher the value, the higher quality the simulation will be at the expense of performance. * The default value of `2` is usually very adequate. * * @property constraintIterations * @type number * @default 2 */ /** * A flag that specifies whether the engine should allow sleeping via the `Matter.Sleeping` module. * Sleeping can improve stability and performance, but often at the expense of accuracy. * * @property enableSleeping * @type boolean * @default false */ /** * An `Object` containing properties regarding the timing systems of the engine. * * @property timing * @type object */ /** * A `Number` that specifies the global scaling factor of time for all bodies. * A value of `0` freezes the simulation. * A value of `0.1` gives a slow-motion effect. * A value of `1.2` gives a speed-up effect. * * @property timing.timeScale * @type number * @default 1 */ /** * A `Number` that specifies the current simulation-time in milliseconds starting from `0`. * It is incremented on every `Engine.update` by the given `delta` argument. * * @property timing.timestamp * @type number * @default 0 */ /** * An instance of a `Render` controller. The default value is a `Matter.Render` instance created by `Engine.create`. * One may also develop a custom renderer module based on `Matter.Render` and pass an instance of it to `Engine.create` via `options.render`. * * A minimal custom renderer object must define at least three functions: `create`, `clear` and `world` (see `Matter.Render`). * It is also possible to instead pass the _module_ reference via `options.render.controller` and `Engine.create` will instantiate one for you. * * @property render * @type render * @deprecated see cmdci.js for an example of creating a renderer * @default a Matter.Render instance */ /** * An instance of a broadphase controller. The default value is a `Matter.Grid` instance created by `Engine.create`. * * @property broadphase * @type grid * @default a Matter.Grid instance */ /** * A `World` composite object that will contain all simulated bodies and constraints. * * @property world * @type world * @default a Matter.World instance */ /** * An object reserved for storing plugin-specific properties. * * @property plugin * @type {} */ })();
'use strict'; // MODULES // var isArray = require( 'validate.io-array' ), isObject = require( 'validate.io-object' ), isBoolean = require( 'validate.io-boolean-primitive' ), isFunction = require( 'validate.io-function' ); // CUMULATIVE PRODUCT // /** * FUNCTION: cprod( arr[, options] ) * Computes the cumulative product of an array. * * @param {Array} arr - input array * @param {Object} [options] - function options * @param {Function} [options.accessor] - accessor function for accessing array values * @param {Boolean} [options.copy=true] - boolean indicating whether to return new array * @returns {Number[]} cumulative product array */ function cprod( arr, opts ) { var copy = true, clbk; if ( !isArray( arr ) ) { throw new TypeError( 'cprod()::invalid input argument. Must provide an array. Value: `' + arr + '`.' ); } if ( arguments.length > 1 ) { if ( !isObject( opts ) ) { throw new TypeError( 'cprod()::invalid input argument. Options argument must be an object. Value: `' + opts + '`.' ); } if ( opts.hasOwnProperty( 'accessor' ) ) { clbk = opts.accessor; if ( !isFunction ( clbk ) ) { throw new TypeError( 'cprod()::invalid option. Accessor must be a function. Value: `' + clbk + '`.' ); } } if ( opts.hasOwnProperty( 'copy' ) ) { copy = opts.copy; if ( !isBoolean( copy ) ) { throw new TypeError( 'cprod()::invalid option. Copy option must be a boolean primitive. Value: `' + copy + '`.' ); } } } var len = arr.length, out, v, i; if ( copy === true ) { out = new Array( len ); } else { out = arr; } if ( clbk ) { out[ 0 ] = clbk( arr[ 0 ], 0 ); for ( i = 1; i < len; i++ ) { v = out[ i-1 ]; if ( v === 0 ) { out[ i ] = 0; } else { out[ i ] = v * clbk( arr[ i ], i ); } } } else { out[ 0 ] = arr[ 0 ]; for ( i = 1; i < len; i++ ) { out[ i ] = out[ i-1 ] * arr[ i ]; } } return out; } // end FUNCTION cprod() // EXPORTS // module.exports = cprod;
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {TreeNode} */ var subtreeWithAllDeepest = function (root) { const map = new Map() const countDep = (node, dep) => { if (!node) return map.set(node, dep) countDep(node.left, dep + 1) countDep(node.right, dep + 1) } countDep(root, 1) const maxDep = Math.max(...Object.values(map)) const helper = node => { } }
define( [ 'js/app', 'marionette', 'handlebars','jqueryuitouch', 'text!js/views/Erosketak/erosketak.html'], function( App, Marionette, Handlebars,jqueryuitouch, template) { //ItemView provides some default rendering logic return Marionette.ItemView.extend( { //Template HTML string template: Handlebars.compile(template), hide: function(){ $(".albiste").removeClass("fadeInLeft"); $(".albiste").addClass("fadeOutUp"); }, onDomRefresh: function(){ $(".produktu").draggable(); $( "#ontzia" ).droppable({ drop: function( event, ui ) { $( this ) .addClass( "ui-state-highlight" ); } }); }, // View Event Handlers events: { } }); });
import * as authSaga from '../../src/sagas/auth.saga'; import * as types from '../../src/constants/actionTypes'; import {call, put} from 'redux-saga/effects'; import * as api from '../../src/connectivity/api.auth'; describe('Auth Saga', () => { describe('doLogin', () => { it('has a happy path', () => { const generator = authSaga.doLogin({ payload: { username: 'bob', password: 'testpass' } }); expect( generator.next().value ).toEqual( put({ type: types.REQUEST__STARTED, payload: { requestFrom: 'authSaga.doLogin' } }) ); expect( generator.next().value ).toEqual( call(api.login, 'bob', 'testpass') ); let fakeResponseBody = { token: 'some-token' }; expect( generator.next(fakeResponseBody).value ).toEqual( put({ type: types.LOGIN__SUCCEEDED, payload: { idToken: 'some-token' } }) ); expect( generator.next().value ).toEqual( put({ type: types.REQUEST__FINISHED, payload: { requestFrom: 'authSaga.doLogin' } }) ); expect( generator.next().done ).toBeTruthy(); }); it('throws when a call to api.login fails', () => { const generator = authSaga.doLogin({ payload: { username: 'bob', password: 'testpass' } }); expect( generator.next().value ).toEqual( put({ type: types.REQUEST__STARTED, payload: { requestFrom: 'authSaga.doLogin' } }) ); expect( generator.next().value ).toEqual( call(api.login, 'bob', 'testpass') ); expect( generator.throw({ message: 'something went wrong', statusCode: 123, }).value ).toEqual( put({ type: types.LOGIN__FAILED, payload: { message: 'something went wrong', statusCode: 123, } }) ); expect( generator.next().value ).toEqual( put({ type: types.REQUEST__FINISHED, payload: { requestFrom: 'authSaga.doLogin' } }) ); expect( generator.next().done ).toBeTruthy(); }); it('throws if unable to find a token in the response.body', () => { const generator = authSaga.doLogin({ payload: { username: 'bob', password: 'testpass' } }); expect( generator.next().value ).toEqual( put({ type: types.REQUEST__STARTED, payload: { requestFrom: 'authSaga.doLogin' } }) ); expect( generator.next().value ).toEqual( call(api.login, 'bob', 'testpass') ); let fakeResponseBody = { bad: 'response' }; expect( generator.next(fakeResponseBody).value ).toEqual( put({ type: types.LOGIN__FAILED, payload: { message: 'Unable to find JWT in response body', statusCode: undefined } }) ); expect( generator.next().value ).toEqual( put({ type: types.REQUEST__FINISHED, payload: { requestFrom: 'authSaga.doLogin' } }) ); expect( generator.next().done ).toBeTruthy(); }); }); });
var userModel = __MODEL.User, roleModel = __MODEL.Role, then = require("thenjs"); exports.add = function (req, res) { var role = new roleModel({ name: req.body.name, description: req.body.description, menu: req.body.menu }); role.save(function (err, doc) { __REST.http(res, doc, err) }); }; exports.list = function (req, res) { roleModel.find().exec(function(err, doc){ __REST.http(res, doc, err) }); }; exports.detail = function (req, res) { roleModel.findById(req.body.id).exec(function (err, doc) { __REST.http(res, doc, err) }); }; exports.edit = function (req, res) { var update = { name: req.body.name, description: req.body.description, menu: req.body.menu }; roleModel.findByIdAndUpdate(req.body.id, update, undefined, function (err, doc) { __REST.http(res, doc, err) }); }; exports.delete = function (req, res) { var condition = {role: req.body.id}; userModel.findOne(condition).exec(function(err, doc){ if(doc){ __REST.fail(res, new Error(__MSG.ROLE.roleInUse)) }else{ roleModel.findByIdAndRemove(req.body.id, undefined, function (err, doc) { __REST.http(res, doc, err) }); } }) };
define([ 'backbone', 'hbs!tmpl/item/jui-dialog-view', 'TweenMax', 'jui-commons' ], function( Backbone, tmpl ) { 'use strict'; /* Return a ItemView class definition */ return Backbone.Marionette.ItemView.extend({ template: tmpl, ui: { content1: '.dialog-content-1', content2: '.dialog-content-2' }, onShow: function () { var self = this, btn = $('.toggle-example-1-state'); btn.click(function () { self.ui.content1.juiDialog({ className: 'my-dialog', titleText: 'Title set via javascript' }); }); btn.juiScalableBtn(); } }); });
/* eslint-disable max-len */ import { FETCH_GROUP_TIMETABLE } from '../constants'; import { request } from './helpers'; export function fetchGroupTimetable({ groupId, date }) { // eslint-disable-line import/prefer-default-export const url = `/api/team/${groupId}?date=${date}`; return { type: FETCH_GROUP_TIMETABLE, meta: { groupId, date }, payload: { promise: request(url) }, }; }
(function() { describe('simditor-mark', function() { var destroySimditor, editor, generateSimditor, simditor; editor = null; simditor = null; generateSimditor = function() { var $textarea, content; content = '<p>Simditor 是团队协作工具 <a href="http://tower.im">Tower</a> 使用的富文本编辑器。</p>\n<p>相比传统的编辑器它的特点是:</p>\n<ul>\n <li>功能精简,加载快速</li>\n <li>输出格式化的标准 HTML</li>\n <li>每一个功能都有非常优秀的使用体验</li>\n</ul>\n<p>兼容的浏览器:IE10+、Chrome、Firefox、Safari。</p>'; $textarea = $('<textarea id="editor"></textarea>').val(content).appendTo('body'); return simditor = new Simditor({ textarea: $textarea, toolbar: ['mark', 'title', 'bold', 'italic', 'underline'] }); }; destroySimditor = function() { var $textarea; $textarea = $('#editor'); editor = $textarea.data('simditor'); if (editor != null) { editor.destroy(); } return $textarea.remove(); }; beforeEach(function() { return editor = generateSimditor(); }); afterEach(function() { destroySimditor(); editor = null; return simditor = null; }); it('should render button in simditor', function() { var $simditor; $simditor = $('.simditor'); expect($simditor).toExist(); return expect($simditor.find('.simditor-toolbar ul li a.toolbar-item-mark')).toExist(); }); it('should mark and unmark selected content', function() { var $body, $mark, $simditor, range; $simditor = $('.simditor'); $body = $simditor.find('.simditor-body'); range = document.createRange(); range.setStart($body.find('p').eq(0)[0], 1); range.setEnd($body.find('p').eq(0)[0], 3); simditor.focus(); simditor.selection.range(range); expect(range.toString()).toBe('Tower 使用的富文本编辑器。'); $mark = $simditor.find('a.toolbar-item-mark'); $mark.trigger('mousedown'); expect($body.find('mark')).toExist(); expect($body.find('mark').text()).toBe('Tower 使用的富文本编辑器。'); range.setStart($body.find('mark')[0], 0); range.setEnd($body.find('mark')[0], 2); simditor.focus(); simditor.selection.range(range); simditor.trigger('selectionchanged'); $mark.trigger('mousedown'); return expect($body.find('mark')).not.toExist(); }); return it('should mark content without extra mark tag', function() { var $body, $simditor; $simditor = $('simditor'); return $body = $simditor.find('body'); }); }); }).call(this);
version https://git-lfs.github.com/spec/v1 oid sha256:a7b301f9a70de9b9d79b9e3e50478ecf24175ec6848a63cbaa195b72931db38b size 18139
/** * @ignore * io xhr transport class, route subdomain, xdr * @author yiminghe@gmail.com */ KISSY.add(function (S, require) { var IO = require('./base'), XhrTransportBase = require('./xhr-transport-base'), XdrFlashTransport = require('./xdr-flash-transport'), SubDomainTransport = require('./sub-domain-transport'); var logger = S.getLogger('s/io'); var win = S.Env.host, doc = win.document, XDomainRequest_ = XhrTransportBase.XDomainRequest_; // express: subdomain offset function isSubDomain(hostname) { // phonegap does not have doc.domain return doc.domain && S.endsWith(hostname, doc.domain); } /** * @class * @ignore */ function XhrTransport(io) { var c = io.config, crossDomain = c.crossDomain, self = this, xhr, xdrCfg = c.xdr || {}, subDomain = xdrCfg.subDomain = xdrCfg.subDomain || {}; self.io = io; if (crossDomain && !XhrTransportBase.supportCORS) { // 跨子域 if (isSubDomain(c.uri.getHostname())) { // force to not use sub domain transport if (subDomain.proxy !== false) { return new SubDomainTransport(io); } } /* ie>7 通过配置 use='flash' 强制使用 flash xdr 使用 withCredentials 检测是否支持 CORS http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/ */ if ((String(xdrCfg.use) === 'flash' || !XDomainRequest_)) { return new XdrFlashTransport(io); } } xhr = self.nativeXhr = XhrTransportBase.nativeXhr(crossDomain); var msg = 'crossDomain: ' + crossDomain + ', use ' + (XDomainRequest_ && (xhr instanceof XDomainRequest_) ? 'XDomainRequest' : 'XhrTransport') + ' for: ' + c.url; logger.debug(msg); return self; } S.augment(XhrTransport, XhrTransportBase.proto, { send: function () { this.sendInternal(); } }); IO.setupTransport('*', XhrTransport); return IO; }); /* 2012-11-28 note ie port problem: - ie 的 xhr 可以跨端口发请求,例如 localhost:8888 发请求到 localhost:9999 - ie iframe 间访问不设置 document.domain 完全不考虑 port! - localhost:8888 访问 iframe 内的 localhost:9999 CORS : http://www.nczonline.net/blog/2010/05/25/cross-domain-io-with-cross-origin-resource-sharing/ */
/* * Home Actions * * Actions change things in your application * Since this boilerplate uses a uni-directional data flow, specifically redux, * we have these actions which are the only way your application interacts with * your appliction state. This guarantees that your state is up to date and nobody * messes it up weirdly somewhere. * * To add a new Action: * 1) Import your constant * 2) Add a function like this: * export function yourAction(var) { * return { type: YOUR_ACTION_CONSTANT, var: var } * } */ import { CHANGE_USERNAME, } from './constants'; /** * Changes the input field of the form * * @param {name} name The new text of the input field * * @return {object} An action object with a type of CHANGE_USERNAME */ export function changeUsername(name) { return { type: CHANGE_USERNAME, name, }; }
module.exports = MongoStorage; var RecursorRepository = require("../ports/RecursorRepository"); var util = require("util"); var _ = require("underscore"); function MongoStorage(recursorName, recursorCollection) { if (!(this instanceof MongoStorage)) return new MongoStorage(recursorName, recursorCollection); this._name = recursorName; this._recursorCollection = recursorCollection; } util.inherits(MongoStorage, RecursorRepository); MongoStorage.prototype._get = function (callback) { return this._recursorCollection.findOne({_id: this._name}, function (err, obj) { if (err) return callback(err); if (obj == null || _.isUndefined(obj.cursor)) return callback(null, {}); callback(null, obj.cursor); }.bind(this)); } MongoStorage.prototype._set = function (cursor, callback) { return this._recursorCollection.findAndModify({_id: this._name}, {}, {_id: this._name, cursor: cursor}, {upsert: true}, function (err, obj) { if (err) return callback(err); callback(null, cursor); }.bind(this)); }
// author: InMon Corp. // version: 2.0 // date: 8/2/2017 // description: Fabric View - Custom TopN module // copyright: Copyright (c) 2017 InMon Corp. ALL RIGHTS RESERVED include(scriptdir()+'/inc/common.js'); include(scriptdir()+'/inc/trend.js'); var userFlows = {}; var maxFlows = 10; var specID = 0; function flowSpec(keys,value,filter) { var keysStr = keys ? keys.join(',') : ''; var valueStr = value ? value.join(',') : ''; var filterStr = filter ? filter.join('&') : ''; if(keysStr.length === 0 || valueStr.length === 0) return null; var key = keysStr || ''; if(valueStr) key += '#' + valueStr; if(filterStr) key += '#' + filterStr; var entry = userFlows[key]; if(!entry) { // try to create flow var name = 'fv-' + specID; try { setFlow(name,{keys:keysStr, value:valueStr, filter: filterStr.length > 0 ? filterStr : null, t:flow_timeout, n:maxFlows, fs:SEP}); entry = {name:name, trend: new Trend(300,1)}; entry.trend.addPoints(Date.now(), {topn:{}}); userFlows[key] = entry; specID++; } catch(e) { entry = null; } } if(!entry) return null; entry.lastQuery = (new Date()).getTime(); return entry; } setIntervalHandler(function(now) { var key, entry, top, topN, i; for(key in userFlows) { entry = userFlows[key]; if(now - entry.lastQuery > 10000) { clearFlow(entry.name); delete userFlows[key]; } else { topN = {}; top = activeFlows('TOPOLOGY',entry.name,maxFlows,1,'edge'); if(top) { for(i = 0; i < top.length; i++) { topN[top[i].key] = top[i].value; } } entry.trend.addPoints(now,{topn:topN}); } } },1); setHttpHandler(function(req) { var result, trend, key, entry, path = req.path; if(!path || path.length === 0) throw "not_found"; switch(path[0]) { case 'flowkeys': if(path.length > 1) throw "not_found"; result = []; var search = req.query['search']; if(search) { var matcher = new RegExp('^' + search[0].replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), 'i'); for(key in flowKeys()) { if(matcher.test(key)) result.push(key); } } else { for(key in flowKeys()) result.push(key); } result.sort(); break; case 'flows': if(path.length > 1) throw "not_found"; entry = flowSpec(req.query['keys'],req.query['value'],req.query['filter']); if(!entry) throw 'bad_request'; trend = entry.trend; result = {}; result.trend = req.query.after ? trend.after(parseInt(req.query.after)) : trend; break; default: throw 'not_found'; } return result; });
var Layout = { view: function(vnode) { var isAdmin = false; if (Session.getProfile()) { isAdmin = Session.getProfile().groupMemberships.indexOf("Administrators") != -1; } var area = null; var route = m.route.get(); if (route == "/secrets" || route.indexOf("/secrets/") === 0) area = "secrets"; if (route == "/admin" || route.indexOf("/admin/") === 0) area = "admin"; var menu = m("#menu", [ m(".pure-menu", [ m("a.pure-menu-heading[href=#]", "PwBox"), m("ul.pure-menu-list", [ m("li.pure-menu-item", {class: area == "secrets" ? "pure-menu-selected" : ""}, m("a.pure-menu-link[href=/secrets]", {oncreate: m.route.link}, [m("span.fa.fa-book"), " Secrets"])), !isAdmin ? null : m("li.pure-menu-item", {class: area == "admin" ? "pure-menu-selected" : ""}, m("a.pure-menu-link[href=/admin]", {oncreate: m.route.link}, [m("span.fa.fa-cog"), " Admin"])), m("li.pure-menu-item.menu-item-divided"), m("li.pure-menu-item", m("a.pure-menu-link[href=/admin/profile]", {oncreate: m.route.link}, [m("span.fa.fa-user"), " " + Session.getUsername()])), m("li.pure-menu-item", m("a.pure-menu-link[href=/logout]", {oncreate: m.route.link}, [m("span.fa.fa-sign-out"), " Log out"])), m("li.pure-menu-item", m("#sessionTimeRemaining.non-link-item", "")), ]) ]) ]); // Hamburger button for small-screen mode var hamburgerLink = m("a#menuLink.menu-link[href=#menu]", m("span")); var contentArea = m("#main", m(".content", vnode.children)); layout = m("#layout", [ hamburgerLink, menu, contentArea ]); // This hamburger-menu logic is based on Pure.css's responsive side menu ui.js var toggleMenu = function(e) { e.preventDefault(); layout.dom.classList.toggle("active"); menu.dom.classList.toggle("active"); hamburgerLink.dom.classList.toggle("active"); }; hamburgerLink.attrs.onclick = toggleMenu; contentArea.attrs.onclick = function(e) { if (menu.dom.classList.contains("active")) { toggleMenu(e); } }; Session.setupLogoutOnSessionExpire(); return layout; } }
/** * app.js * * This is the entry file for the application, only setup and epiaggregator * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import FontFaceObserver from 'fontfaceobserver'; import { useScroll } from 'react-router-scroll'; import 'sanitize.css/sanitize.css'; // Material-UI import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); // Import root app import App from 'containers/App'; // Import selector for `syncHistoryWithStore` import { makeSelectLocationState } from 'containers/App/selectors'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Load the favicon, the manifest.json file and the .htaccess file /* eslint-disable import/no-webpack-loader-syntax */ import '!file-loader?name=[name].[ext]!./favicon.ico'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; // eslint-disable-line import/extensions /* eslint-enable import/no-webpack-loader-syntax */ import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS reset and Global Styles import './global-styles'; // Import routes import createRoutes from './routes'; //Import Global sagas import { injectGlobalSagas } from './sagas'; // Observe loading of Open Sans (to remove open sans, remove the <link> tag in // the index.html file and this observer) const openSansObserver = new FontFaceObserver('Open Sans', {}); // When Open Sans is loaded, add a font-family using Open Sans to the body openSansObserver.load().then(() => { document.body.classList.add('fontLoaded'); }, () => { document.body.classList.remove('fontLoaded'); }); // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); if (JSON.parse(localStorage.getItem('token')) === null) { localStorage.setItem('token', JSON.stringify({})); } // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: makeSelectLocationState(), }); // https://github.com/react-boilerplate/react-boilerplate/issues/537#issuecomment-274056491 //Inject global sagas injectGlobalSagas(store); // Set up the router, wrapping all Routes in the App component const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (messages) => { ReactDOM.render( <MuiThemeProvider muiTheme={getMuiTheme()}> <Provider store={store}> <LanguageProvider messages={messages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider> </MuiThemeProvider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(import('intl')); })) .then(() => Promise.all([ import('intl/locale-data/jsonp/en.js'), import('intl/locale-data/jsonp/de.js'), import('intl/locale-data/jsonp/fr.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require }
var TodosApp = angular.module('TodosApp', []); TodosApp.controller('TodosCtrl', ['$scope', 'database', function($scope, database){ $scope.todosArray = database.todosArray() $scope.newTodo = '' $scope.addTodo = function(){ let newTodo = {task: $scope.newTodo, completed: false} if (newTodo.task === '') return; $scope.todosArray.push(newTodo) $scope.newTodo = '' } $scope.clearCompleted = function(){ $scope.todosArray = $scope.todosArray.filter(function(t){ return !t.completed }) } $scope.checkboxClick = function(index){ $scope.todosArray[index].completed = !$scope.todosArray[index].completed } $scope.deleteTodo = function(index){ $scope.todosArray.splice(index, 1) } }]) TodosApp.factory('database', function(){ var todos = [ {task: 'mow lawn', completed: false}, {task: 'phone call', completed: true}, {task: 'pay bills', completed: false} ] var todosArray = function(){ return todos } return { todosArray: todosArray } })
'use strict'; /** * @ngdoc function * @name upit.controller:MainCtrl * @description # Paste Module */ angular.module('upit-web.upitRestApi') .factory('UploadedFileResource', ['$q', 'SimpleResourceClient', function ($q, SimpleResourceClient) { var self = this; var resourceContext = { resourceName: 'uploadedFile' }; self.getById = function (id) { return SimpleResourceClient.getById(resourceContext, id); }; self.create = function (paste) { return SimpleResourceClient.create(resourceContext, paste); }; self.update = function (paste) { return SimpleResourceClient.update(resourceContext, paste); }; self.remove = function (paste) { return SimpleResourceClient.remove(resourceContext, paste); }; self.getByIdHash = function (hash) { return SimpleResourceClient.makeRestRequest(resourceContext, { url: '/hash/' + hash, method: 'GET' }); }; return { getById: self.getById, getByIdHash: self.getByIdHash, create: self.create, update: self.update, remove: self.remove }; }]);
import { Meteor } from 'meteor/meteor' import { check } from 'meteor/check' import { Mongo } from 'meteor/mongo' import { _ } from 'meteor/underscore' import { EJSON } from 'meteor/ejson' import { MongoID } from 'meteor/minimongo' import { CollectionExtensions } from 'meteor/lai:collection-extensions' const Decimal = Package['mongo-decimal']?.Decimal || class DecimalStub {} // eslint-disable-line no-undef let _batchInsert if (Meteor.isServer) { ({ _batchInsert } = require('./batch-insert-server.js')) } Mongo.Collection.prototype._defineBatchInsert = function () { const self = this // don't define a method for a null collection if (!self._name || !self._connection) return const m = {} m['/' + self._name + '/batchInsert'] = function (docs) { check(docs, [Object]) // 'this' refers to method context if (this.isSimulation) { return docs.map(function (doc) { if (!doc._id) { doc._id = self._makeNewID() } return self.insert(doc) }) } // client returned so server code below const userId = this.userId const generatedIds = docs.map(function (doc) { if (!_.has(doc, '_id')) { return self._makeNewID() } else { return doc._id } }) docs.forEach(function (doc, ii) { if (this.connection) { // server method called by client so check allow / deny rules. if (!((doc && _type(doc)) && !EJSON._isCustomType(doc))) { throw new Error('Invalid modifier. Modifier must be an object.') } // call user validators. // Any deny returns true means denied. if (_.any(self._validators.insert.deny, function (validator) { return validator(userId, docToValidate(validator, doc, generatedIds[ii])) })) { throw new Meteor.Error(403, 'Access denied') } // Any allow returns true means proceed. Throw error if they all fail. if (_.all(self._validators.insert.allow, function (validator) { return !validator(userId, docToValidate(validator, doc, generatedIds[ii])) })) { throw new Meteor.Error(403, 'Access denied') } } doc._id = generatedIds[ii] }, this) // pass context of method into forEach return _batchInsert(self, docs) // end of method definition } self._connection.methods(m) } Mongo.Collection.prototype.batchInsert = function (/* args */) { const self = this const args = _.toArray(arguments) let cb if (typeof args[args.length - 1] === 'function') { cb = args.pop() } if (!self._name || !self._connection) { let res, err try { res = args[0].map(function (doc) { return self._collection.insert(doc) }) } catch (e) { if (!cb) { throw e } err = e }; cb && cb(err, res) return res } else if (self._connection && self._connection === Meteor.server) { const docs = args[0].map(function (doc) { if (!doc._id) doc._id = self._makeNewID() return doc }) return _batchInsert(self, docs, cb) } if (cb) { return self._connection.apply('/' + self._name + '/batchInsert', args, { returnStubValue: true }, cb) } return self._connection.apply('/' + self._name + '/batchInsert', args, { returnStubValue: true }) } CollectionExtensions.addExtension(function (name, options) { this._defineBatchInsert() }) Meteor.Collection = Mongo.Collection // function copied from MDG Mongo.Collection._validateInsert. Needed in allow / deny checks. function docToValidate (validator, doc, generatedId) { let ret = doc if (validator.transform) { ret = EJSON.clone(doc) // If you set a server-side transform on your collection, then you don't get // to tell the difference between "client specified the ID" and "server // generated the ID", because transforms expect to get _id. If you want to // do that check, you can do it with a specific // `C.allow({insert: f, transform: null})` validator. if (generatedId !== null) { ret._id = generatedId } ret = validator.transform(ret) } return ret }; function _type (v) { if (typeof v === 'number') { return 1 } if (typeof v === 'string') { return 2 } if (typeof v === 'boolean') { return 8 } if (_.isArray(v)) { return 4 } if (v === null) { return 10 } if (v instanceof RegExp) { return 11 } // note that typeof(/x/) === "object" if (typeof v === 'function') { return 13 } if (v instanceof Date) { return 9 } if (EJSON.isBinary(v)) { return 5 } if (v instanceof MongoID._ObjectID) { return 7 } if (v instanceof Decimal) { return 1 } return 3 // object // XXX support some/all of these: // 14, symbol // 15, javascript code with scope // 16, 18: 32-bit/64-bit integer // 17, timestamp // 255, minkey // 127, maxkey };
/** * MVCApp * © 2011 Studio Melonpie */ var App = { controllers: {}, _controller: null, android: null, iphone: null, toArray: function(o) {return Array().slice.call(o)}, controller: function(c) {App._controller = c}, create: function(what, params) { var method = 'create' + what; params = params || {}; if(!Ti.UI[method]) { Ti.API.error('[MVCApp] create: ' + method + ' is an invalid method'); return; } var object = Ti.UI[method](params); object.android = App.android; object.iphone = App.iphone; object.dispatch = App.dispatch; return object; }, /** * App.view(file, params) to load the specified file with the additional parameters */ view: function(name, params) { params = params || {}; var type = 'Window'; params.url = params.url || 'Views/' + name + '.js'; if(params._type) { type = params._type; delete params._type; } return App.create(type, params); }, onDispatch: function(data) { if(typeof App.controllers[data.url] == 'undefined') { try { Ti.include(data.url); App.controllers[data.url] = new App._controller; App._controller = null; if(App.controllers[data.url] && typeof App.controllers[data.url].init == 'function') { App.controllers[data.url].init(); } } catch(e) { Ti.API.error('[MVCApp] Invalid controller: ' + data.url); return null; } } if(typeof App.controllers[data.url] == 'undefined' || !App.controllers[data.url]) { Ti.API.error('[MVCApp] Invalid controller: ' + data.url.replace(/^Controllers\/(.+?)\.js$/, '$1')); return null; } if(typeof App.controllers[data.url][data.action] != 'function') { Ti.API.error('[MVCApp] Action ' + data.action + ' not found in controller ' + data.url.replace(/^Controllers\/(.+?)\.js$/, '$1')); return null; } try { return App.controllers[data.url][data.action].apply(this, data.params); } catch (e) { Ti.API.error('[MVCApp] ' + e.name + ' at ' + data.url + ' line ' + e.line + ': ' + e.message); return null; } }, dispatch: function(/* location, param, param, ... */) { var params = App.toArray(arguments); var location = params.shift(); var action = location.split('/'); if(action.length == 1) { action = 'defaultAction'; } else if(action.length == 2){ location = action[0]; action = action[1] + 'Action'; } return App.onDispatch({url: 'Controllers/' + location + '.js', action: action, params: params || []}); }, init: function() { App.iphone = Ti.Platform.name == 'iPhone OS'; App.android = Ti.Platform.name == 'android'; Ti.App.addEventListener('App.dispatch', function(e) { if(!e.url) { Ti.API.error('App.dispatch: missing URL'); return null; } App.dispatch(e.url, e.data || null); }); } }; App.init();
 function Logo() {} Logo.prototype.init = function( w, h ) { var zindex = 10; var el, els, body = document.body; var me = this; el = this.traceTF = document.createElement("div"); els = el.style; el.innerHTML = "trace"; body.appendChild( el ); els.position = "absolute"; els.fontSize = "9px"; els.left = "16px"; els.top = "70px"; el = this.aboutbtn = document.createElement("a"); els = el.style; body.appendChild( el ); el.href = "http://roxik.com/"; el.target = "_blank"; el.innerHTML = "about me"; els.position = "absolute"; els.fontSize = isPC ? "11px" : "11px"; els.zIndex = ++zindex; els.textDecoration = "none"; els.whiteSpace = "nowrap"; els.padding = "4px"; el.normalColor = "#F9A"; el.overColor = "#FFF"; setBtnEvent( el ); el.addEventListener( ( isMouse ? "mousedown" : "touchstart" ), function(){ this.style.color = "#FFF";}, false ); el.addEventListener( ( isMouse ? "mouseup" : "touchend" ), function() { this.style.color = "#F9A"; } , false ); el = this.subtxt = document.createElement("div"); els = el.style; el.innerHTML = "change view"; body.appendChild( el ); els.position = "absolute"; els.color = "#F9A"; els.fontSize = isPC ? "11px" : "11px"; els.zIndex = ++zindex; els.padding = "4px"; els.whiteSpace = "nowrap"; el.style.cursor = "pointer"; el.addEventListener( "mouseover", function() { this.style.color = "#FFF"; } , false ); el.addEventListener( "mouseout", function() { this.style.color = "#F9A"; } , false ); el.addEventListener( ( isMouse ? "mousedown" : "touchstart" ), function(){ this.style.color = "#F9A"; isDebugMode = !isDebugMode; }, false ); el.addEventListener( ( isMouse ? "mouseup" : "touchend" ), function() { this.style.color = "#F9A"; } , false ); this.aboutbtn.style.top = 16 + "px"; this.subtxt.style.top = 42 + "px"; this.aboutbtn.style.left = this.subtxt.style.left = "12px"; this.anum = -1; this.show( false ); } Logo.prototype.show = function( isShow ) { this.aboutbtn.style.display = this.subtxt.style.display = isShow ? "block" : "none"; }; Logo.prototype.trace = function( str ) { if( this.traceStr ){ if( this.traceStr.length > 6 ){ this.traceStr.shift(); } }else{ this.traceStr = []; } this.traceStr.push( str ); this.traceTF.innerHTML = this.traceStr.join("<br>"); };
$(function() { function clickTarget() { var stopAllEnabled = false; var deleteAllEnabled = false; $(".checkTarget:checked").each(function(){ if($(this).data('status') != '2') { stopAllEnabled = true; deleteAllEnabled = false; return false; } else { stopAllEnabled = false; deleteAllEnabled = true; } }); $("#game_sessions_btns input[name=stop_all]").attr("disabled", !stopAllEnabled); $("#game_sessions_btns input[name=delete_all]").attr("disabled", !deleteAllEnabled); } $("#check_all").on('click', function() { $("input:checkbox").prop("checked", this.checked); clickTarget(); }); $(".checkTarget").on('click', clickTarget); $("#game_sessions_btns input[type=submit]").attr("disabled", true); });
import app from 'flarum/app'; import AkismetSettingsModal from 'akismet/components/AkismetSettingsModal'; app.initializers.add('akismet', () => { app.extensionSettings.akismet = () => app.modal.show(new AkismetSettingsModal()); });
import $ from 'jquery'; import Backbone from 'backbone'; import Marionette from 'backbone.marionette'; import Responder from '../../responder/contacts/index'; import Contacts from '../../domain/contacts/repository'; export default Marionette.Object.extend({ initialize: function(App) { this.app = App; this.contacts = new Contacts; }, respond: function() { var responder = new Responder(App, this.data()); return responder.respond(); }, data: function() { return { contacts: this.contacts.all() }; } });
module.exports = (req, res, next) => { const err = new Error('Not Found'); err.status = 404; next(err); };
/* @flow */ /* eslint-disable no-param-reassign */ import { ObjectTypeComposer, graphql } from 'graphql-compose'; import type { GraphQLFieldConfig } from 'graphql'; import elasticsearch from 'elasticsearch'; import ElasticApiParser from './ElasticApiParser'; const DEFAULT_ELASTIC_API_VERSION = '_default'; const { GraphQLString } = graphql; export function elasticApiFieldConfig(esClientOrOpts: Object): GraphQLFieldConfig<any, any> { if (!esClientOrOpts || typeof esClientOrOpts !== 'object') { throw new Error( 'You should provide ElasticClient instance or ElasticClientConfig in first argument.' ); } if (isElasticClient(esClientOrOpts)) { return instanceElasticClient(esClientOrOpts); } else { return contextElasticClient(esClientOrOpts); } } function instanceElasticClient(elasticClient: Object): GraphQLFieldConfig<any, any> { const apiVersion = elasticClient.transport._config.apiVersion || DEFAULT_ELASTIC_API_VERSION; const prefix = `ElasticAPI${apiVersion.replace('.', '')}`; const apiParser = new ElasticApiParser({ elasticClient, prefix, }); return { description: `Elastic API v${apiVersion}`, type: ObjectTypeComposer.createTemp({ name: prefix, fields: apiParser.generateFieldMap(), }).getType(), resolve: () => ({}), }; } function contextElasticClient(elasticConfig: Object): GraphQLFieldConfig<any, any> { if (!elasticConfig.apiVersion) { elasticConfig.apiVersion = DEFAULT_ELASTIC_API_VERSION; } const { apiVersion } = elasticConfig; const prefix = `ElasticAPI${apiVersion.replace('.', '')}`; const apiParser = new ElasticApiParser({ apiVersion, prefix, }); return { description: `Elastic API v${apiVersion}`, type: ObjectTypeComposer.createTemp({ name: prefix, fields: apiParser.generateFieldMap(), }).getType(), args: { host: { type: GraphQLString, defaultValue: elasticConfig.host || 'http://user:pass@localhost:9200', }, }, resolve: (src: any, args: Object, context: Object) => { if (typeof context === 'object') { const opts = args.host ? { ...elasticConfig, host: args.host, } : elasticConfig; context.elasticClient = new elasticsearch.Client(opts); } return {}; }, }; } function isElasticClient(obj) { if (obj instanceof elasticsearch.Client) { return true; } if (obj && obj.transport && obj.transport._config && obj.transport._config.__reused) { return true; } return false; }
var structtesting_1_1gmock__more__actions__test_1_1_sum_of6_functor = [ [ "operator()", "structtesting_1_1gmock__more__actions__test_1_1_sum_of6_functor.html#adc0cc4dbd423db7298497b8a9630067e", null ] ];
function getChartData(){ var options=myChart1.getOption(); var date=new Date(); var d=date.getDate(); var param=$.trim(date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()); //alert(param); $.ajax({ url:"${pageContext.request.contextPath}/showCommonAction/show_data1_gangying", //data:{param:param}, data:{param:'2015-11-01'}, type:"post", async:false, //dataType:"json", contentType: "application/x-www-form-urlencoded; charset=utf-8", success:function(data){ if(data){ //alert(data); //alert(data.series); var obj=eval('('+data+')'); //alert(obj.series[0].name); options.series[0].data=obj.series; myChart1.hideLoading(); myChart1.setOption(options); } }, error:function(XMLHttpRequest, textStatus, errorThrown){ //alert("执行错误"+data); alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(textStatus); } }); }
// Chris Kayode Samuel // Github: Alayode // Email : ksamuel.chris@icloud.com //Description: understanding the caution when using closures with loops //Now that the danger zones and obstacles are in order and ready to be dealt // with , the Dev Girls need your assistance with directing the Cold Closures //Cove sharks to their custom fitted lasers. That's right Lasers. // Sharks are suppise to be directed to the laser-strapping station that matches the index that their name is in within the sharkList array, which looks like this: /* ["Sea Pain", "Great Wheezy", "DJ Chewie", "Lil' Bitey", "Finmaster Flex", "Swim Khalifa", "Ice Teeth", "The Notorious J.A.W."] */ //But they've got a problem with their assignLaser function. Something is up, and // now there's a traffic jam at the last shark's station. // // Figure out what happened and apply a fix from this section's video lecture: // // 1. Don't hange the position of the function inside the for loop. // 2.Instead of assigning to the stationAssignment variable, return // the anonymous function. // 3. Remove the subsequently uneccessary lines with stationAssignment. // // Note: You do not need to call the assignLaser function. var sharkList = ["Jaws","Sharpy","RazorSharp"]; function assignLaser(shark, sharkList) { var stationAssignment; for (var i = 0; i < sharkList.length; i++) { if (shark == sharkList[i]) { stationAssignment = function() { alert("Yo, " + shark + "!\n" ) }; return stationAssignment; } } } var f = assignLaser("Sharkie",sharkList); f();
/** * @fileOverview server.page test suite * @author Max **/ const assert = require('assert'); const PageUtils = require('../../dist/server/page/utils'); const exportConfigToGlobalConst = PageUtils.exportConfigToGlobalConst; const testObj = { 'A': 1, 'B': { "C": '222', "@D": 5, "E": { "F": 1 } }, "@C": { "K": 100 } }; describe('server.page', function() { it('normal', function() { let result = exportConfigToGlobalConst(testObj); assert(result.__A__ === 1); assert(result.__B_C__ === '222'); assert(result['__B_@D__'] === undefined); assert(result.__B_E_F__ === 1); assert(result['__@C_K__'] === undefined); }); });
module.exports = require('./lib/index')
!function(window){ var algo = algo || {}; var operation = { REMOVE_ORIGIN: 0, //从源数组删除 INSERT_ORIGIN: 1, //在源数组插入 UPDATE_ORIGIN: 2, //更新数组元素 SWAP_ORIGIN: 3, //在源数组交换位置 REMOVE: 4, //删除 INSERT: 5, //插入 SWAP: 6, //交换位置 COMPARE: 7, //对比操作(判断条件) HIT: 8, //命中(判断条件达成) COMPLETE: 9, //完成(算法完成) SET_GUARD: 10, //设置哨兵(清除其他哨兵) ADD_GUARD: 11, //添加哨兵(允许添加多个哨兵) CHANGE_GUARD: 12, //更换哨兵(移动哨兵) CLEAR_GUARD: 13, //清除所有哨兵 SET_TEMP: 14, //设置临时值(清除其他临时值) ADD_TEMP: 15, //添加临时值(允许添加多个临时值) CHANGE_TEMP: 16, //更换临时值 CLEAR_TEMP: 17 //清除所有临时值 }; var Algo = function(view){ this.view = view || new DefaultView(); this.frameIndex = 0; this.frames = []; this.origin = []; this.input = []; }; Algo.prototype = { removeOrigin: function(index, log){ this.frames.push([operation.REMOVE_ORIGIN, index, log]); }, swapOrigin: function(from, to, log){ this.frames.push([operation.SWAP_ORIGIN, from, to, log]); }, insertOrigin: function(after, value, log){ this.frames.push([operation.INSERT_ORIGIN, after, value, log]); }, updateOrigin: function(i, value, log){ this.frames.push([operation.UPDATE_ORIGIN, i, value, log]); }, remove: function(index, log){ this.frames.push([operation.REMOVE, index, log]); }, swap: function(from, to, log){ this.frames.push([operation.SWAP, from, to, log]); }, insert: function(after, value, log){ this.frames.push([operation.INSERT, after, value, log]); }, compare: function(t1, t2, log){ this.frames.push([operation.COMPARE, t1, t2, log]); }, hit: function(t1, t2, log){ this.frames.push([operation.HIT, t1, t2, log]); }, start: function(inputData){ this.origin = inputData.slice(0); this.input = inputData.slice(0); this.view.render(this.input); }, complete: function(log){ this.frames.push([operation.COMPLETE, log]); }, setGuard: function(i, log){ this.frames.push([operation.SET_GUARD, i, log]); }, addGuard: function(i, log){ this.frames.push([operation.ADD_GUARD, i, log]); }, changeGuard: function(from, to, log){ this.frames.push([operation.CHANGE_GUARD, from, to, log]); }, clearGuard: function(log){ this.frames.push([operation.CLEAR_GUARD, log]); }, setTemp: function(value, log){ this.frames.push([operation.SET_TEMP, value, log]); }, addTemp: function(value, log){ this.frames.push([operation.ADD_TEMP, value, log]); }, changeTemp: function(i, value, log){ this.frames.push([operation.CHANGE_TEMP, i, value, log]); }, clearTemp: function(log){ this.frames.push([operation.CLEAR_TEMP, log]); }, reset: function(){ this.frameIndex = 0; this.frames = []; this.origin = []; this.input = []; }, resetPlay: function(){ this.frameIndex = 0; this.input = this.origin.slice(0); this.view.reset(this.input); }, next: function(){ if(this.frameIndex >= this.frames.length){ return; } var frame = this.frames[this.frameIndex], args = frame.slice(1); switch(frame[0]){ case 0: this.input.splice(args[0], 1); this.view.render(this.input); this.view.removeOrigin(args); break; case 1: this.input.splice(args[0], 0, args[1]); this.view.render(this.input); this.view.insertOrigin(args); break; case 2: this.input[args[0]] = args[1]; this.view.render(this.input); this.view.updateOrigin(args); break; case 3: var temp = this.input[args[0]]; this.input[args[0]] = this.input[args[1]]; this.input[args[1]] = temp; this.view.render(this.input); this.view.swapOrigin(args); break; case 4: this.view.remove(args); break; case 5: this.view.insert(args); break; case 6: this.view.swap(args); break; case 7: this.view.compare(args); break; case 8: this.view.hit(args); break; case 9: this.view.complete(args); break; case 10: this.view.setGuard(args); this.view.render(this.input); break; case 11: this.view.addGuard(args); this.view.render(this.input); break; case 12: this.view.changeGuard(args); this.view.render(this.input); break; case 13: this.view.clearGuard(args); this.view.render(this.input); break; case 14: this.view.setTemp(args); this.view.render(this.input); break; case 15: this.view.addTemp(args); this.view.render(this.input); break; case 16: this.view.changeTemp(args); this.view.render(this.input); break; case 17: this.view.clearTemp(args); this.view.render(this.input); break; } this.frameIndex++; }, getInstance: function(view){ return new Algo(view); } }; var DefaultView = function(){ this.logIndex = 0; this.guardIndex = []; this.tempValue = []; }; DefaultView.prototype = { render: function(data){ var html = '', i, len; for(i=0, len=data.length; i<len; i++){ html += '<li class="'+(this.guardIndex[i] ? 'guard' : '')+'"><span>'+data[i]+'</span><em class="g">-></em><em class="t">-></em></li>'; } if(this.tempValue.length){ html += '<li class="temp-title"><b>Temp value</b></li>'; for(i=0, len=this.tempValue.length; i<len; i++){ html += '<li class="temp"><span>'+this.tempValue[i]+'</span><em class="g">-></em><em class="t">-></em></li>'; } } $('#args').html(html); }, reset: function(data){ this.logIndex = 0; this.guardIndex = []; this.tempValue = []; this.render(data); $('#log').html(''); }, removeOrigin: function(args){ this.log(args[1]); }, swapOrigin: function(args){ $('#args').children('li').eq(args[0]).addClass('active').end().eq(args[1]).addClass('active'); this.log(args[2]); }, insertOrigin: function(args){ this.log(args[2]); }, updateOrigin: function(args){ this.log(args[2]); }, compare: function(args){ $('#args').children('li').removeClass('active') .eq(args[0]).addClass('active').end().eq(args[1]).addClass('active'); this.log(args[2]); }, hit: function(args){ $('#args').children('li').removeClass('hit') .eq(args[0]).addClass('hit'); this.log(args[1]); }, log: function(msg){ this.logIndex++; msg && $('#log').prepend('<li><span>'+msg+'</span><i>'+this.logIndex+'.</i><li>'); }, complete: function(args){ this.log(args[0]); this.tempValue = []; $('#args').children('li').removeClass('hit').removeClass('active').removeClass('guard').filter('.temp,.temp-title').remove(); }, setGuard: function(args){ this.log(args[1]); this.guardIndex = []; this.guardIndex[args[0]] = 1; }, addGuard: function(args){ this.log(args[1]); this.guardIndex[args[0]] = 1; }, changeGuard: function(args){ this.log(args[2]); this.guardIndex[args[0]] = undefined; this.guardIndex[args[1]] = 1; }, clearGuard: function(args){ this.log(args[0]); this.guardIndex = []; }, setTemp: function(args){ this.log(args[1]); this.tempValue= [args[0]]; }, addTemp: function(args){ this.log(args[1]); this.tempValue.push(args[0]); }, changeTemp: function(args){ this.log(args[2]); this.tempValue[args[0]] = args[1]; }, clearTemp: function(args){ this.log(args[0]); this.tempValue= []; } }; window.algo = new Algo(); }(this);
(function(module) { function Project(projObj) { for (var key in projObj) { this[key] = projObj[key]; } for (var key in this.code) { this.codehtml = this.codehtml + '<p>'+ key + ': ' + this.code[key] + ' lines</p>'; } }; Project.projects = []; Project.toHTML = function(whichStuff, whichTemplate) { var template = $(whichTemplate).html(); var templateRender = Handlebars.compile(template); return templateRender(whichStuff); }; Project.loadAll = function(inputData) { inputData.forEach(function(proj) { Project.projects.push(new Project(proj)); }); }; Project.fetchAll = function() { $.ajax({ type: 'HEAD', url: '../../data/projects.json', success: function(data, message, xhr) { if (!localStorage.eTag || localStorage.eTag !== xhr.getResponseHeader('ETag')) { console.log('load new data'); $.getJSON('../../data/projects.json', function(data) { localStorage.setItem('eTag', xhr.getResponseHeader('ETag')); localStorage.setItem('projectData', JSON.stringify(data)); Project.loadAll(data); github.requestEvents(viewController.renderProjects); }); } else { console.log('load from local'); Project.loadAll(JSON.parse(localStorage.getItem('projectData'))); github.requestEvents(viewController.renderProjects); } } }); }; Project.makeCodeStatsArray = function(project) { var array = []; for (var lang in project.code) { array.push(project.code[lang]); } return array; }; Project.totalLinesOfCode = function() { return Project.projects.map(function(project) { return Project.makeCodeStatsArray(project).reduce(function(sum,cur,idx,array) { return cur + sum; }); }) .reduce(function(sum,cur,idx,array) { return cur + sum; }); }; Project.linesOfCode = function() { var obj = {html:0,js:0,css:0}; Project.projects.forEach(function(proj) { for (var key in proj.code) { obj[key] += proj.code[key]; } }); obj.total = Project.totalLinesOfCode(); return obj; }; module.Project = Project; })(window);
/** * Smokescreen Player - A Flash player written in JavaScript * http://smokescreen.us/ * * Copyright 2011, Chris Smoak * Released under the MIT License. * http://www.opensource.org/licenses/mit-license.php */ define(function(require, exports, module) { var ext = require('lib/ext') var env = require('lib/env') var zip = require('lib/zip') var LittleEndianStringReader = require('util/little_endian_string_reader').LittleEndianStringReader var PngWriter = require('util/png_writer').PngWriter var SwfReader = require('swf/swf_reader').SwfReader var BigEndianStringReader = require('util/big_endian_string_reader').BigEndianStringReader /* fljs.swf.TagTypes = { End: 0, ShowFrame: 1, DefineShape: 2, PlaceObject: 4, RemoveObject: 5, DefineBits: 6, JpegTables: 8, SetBackgroundColor: 9, DefineFont: 10, DefineText: 11, DoAction: 12, DefineFontInfo: 13, DefineSound: 14, StartSound: 15, SoundStreamHead: 18, SoundStreamBlock: 19, DefineBitsLossless: 20, DefineBitsJpeg2: 21, DefineShape2: 22, Protect: 24, PlaceObject2: 26, RemoveObject2: 28, DefineShape3: 32, DefineText2: 33, DefineButton2: 34, DefineBitsJpeg3: 35, DefineBitsLossless2: 36, DefineEditText: 37, DefineSprite: 39, FrameLabel: 43, SoundStreamHead2: 45, DefineFont2: 48, ExportAssets: 56, DoInitAction: 59, DefineFontInfo2: 62, PlaceObject3: 70, DefineFontAlignZones: 73, DefineFont3: 75, DoAbc: 82, DefineShape4: 83 } */ var SwfReader = function(stream) { this.stream = stream this.twipsPerPixel = 20 this.logger = ext.console('parse') this.loader = null this.bytesRead = 0 this.target = null this.frames = [0] }; ext.add(SwfReader.prototype, { hasMore : function() { return this.stream.hasMore() }, skipBytes : function(count) { this.stream.skipBytes(count) }, bytes : function(count) { return this.stream.bytes(count) }, ui8 : function() { return this.stream.uByte() }, ui16 : function() { var value = this.stream.uShort() return value }, ui32 : function() { return this.stream.nextULong() }, si8 : function() { return this.stream.sByte() }, si16 : function() { return this.stream.sShort() }, si32 : function() { return this.stream.nextSLong() }, ub : function(bits) { return this.stream.nextUBits(bits) }, sb : function(bits) { return this.stream.nextSBits(bits) }, readFB : function(bits) { return this.stream.nextFBits(bits) }, readFixed : function() { return this.stream.nextFLong() }, readFixed8 : function() { return this.stream.nextFShort() }, readFloat16 : function() { return this.stream.nextHalfFloat() }, readFloat : function() { return this.stream.nextSingleFloat() }, readFloats : function(count) { var floats = [] for (var i = 0; i < count; i++) { floats.push(this.readFloat()) } return floats }, readDouble : function() { return this.stream.nextDoubleFloat() }, readEncodedU32 : function() { return this.stream.nextEncodedULong() }, string : function() { return this.stream.nextString() }, readSwfHeader : function() { var Signature = String.fromCharCode( this.ui8(), this.ui8(), this.ui8() ) var Version = this.ui8() var FileLength = this.ui32() if (Signature == 'CWS') { var zipped = this.stream.buffer.substr(this.stream.byteIndex + 2) var inflated = zip.inflate(zipped) this.stream = new LittleEndianStringReader(inflated) } var FrameSize = this.readRect() var FrameRate = this.readFixed8() //this.ui16() var FrameCount = this.ui16() var header = this.header = { Signature : Signature, Version : Version, FileLength : FileLength, FrameSize : FrameSize, FrameRate : FrameRate, FrameCount : FrameCount } return header }, readRecordHeader : function() { var d = {} var TagCodeAndLength = this.ui16() d.TagLength = TagCodeAndLength & 0x3f d.TagType = (TagCodeAndLength >> 6) & 0x3ff if (d.TagLength == 0x3f) { d.TagLength = this.si32() } d.tagPos = d.byteIndex = this.stream.byteIndex this.header = d return d }, tagBytesLeft : function() { var header = this.header return header.TagLength - (this.stream.byteIndex - header.tagPos) }, readCxform : function(alpha) { if (alpha) { this.stream.align() } var d = {} d.HasAddTerms = this.ub(1) d.HasMultTerms = this.ub(1) var n = d.Nbits = this.ub(4) d.AlphaMultTerm = 1 d.AlphaAddTerm = 0 if (d.HasMultTerms) { d.RedMultTerm = this.sb(n) / 256 d.GreenMultTerm = this.sb(n) / 256 d.BlueMultTerm = this.sb(n) / 256 if (alpha) { d.AlphaMultTerm = this.sb(n) / 256 } } else { d.RedMultTerm = 1 d.GreenMultTerm = 1 d.BlueMultTerm = 1 } if (d.HasAddTerms) { d.RedAddTerm = this.sb(n) d.GreenAddTerm = this.sb(n) d.BlueAddTerm = this.sb(n) if (alpha) { d.AlphaAddTerm = this.sb(n) } } else { d.RedAddTerm = 0 d.GreenAddTerm = 0 d.BlueAddTerm = 0 } return d }, readClipActions : function() { this.ui16() var AllEventFlags = this.readClipEventFlags() var ClipActionRecords = this.readClipActionRecords() return { AllEventFlags : AllEventFlags, ClipActionRecords : ClipActionRecords } }, readClipActionRecords : function() { var records = [] var record while (record = this.readClipActionRecord()) { records.push(record) } return records }, readClipActionRecord : function() { var EventFlags = this.readClipEventFlags() if (!EventFlags) { return null } var ActionRecordSize = this.ui32() var bytesToRead = ActionRecordSize var KeyCode if (EventFlags & (1 << 9)) { //fljs.swf.ClipEventFlags.ClipEventKeyPress KeyCode = this.ui8() bytesToRead -= 1 } var Actions = this.readActionRecords(bytesToRead) return { EventFlags : EventFlags, ActionRecordSize : ActionRecordSize, KeyCode : KeyCode, Actions : Actions } }, readActionRecords : function(bytes) { var startIndex = this.stream.byteIndex var actions = [] while (this.stream.byteIndex != startIndex + bytes) { actions.push(this.readActionRecord()) } // need for jumps at end of code block if (actions.length) { var lastAction = actions[actions.length - 1] if (lastAction.ActionCode != 0) { actions.push({ code: '0x0', address: lastAction.address + lastAction.Length, ActionCode: 0, Action: 'End' }) } } return actions }, readActionRecord : function() { var address = this.stream.byteIndex var ActionCode = this.ui8() var record = { code : '0x' + ActionCode.toString(16), address : address, ActionCode : ActionCode } if (ActionCode >= 0x80) { record.Length = this.ui16() } //var logger = goog.debug.Logger.getLogger('parse') //logger.info(record.ActionCode.toString(16) + ', ' + goog.debug.expose(record)) switch (ActionCode) { // SWF3 case 0x81 : // ActionGotoFrame // record.Action = 'ActionGotoFrame' record.Frame = this.ui16() break case 0x83 : // ActionGetURL // record.Action = 'ActionGetUrl' record.UrlString = this.string() record.TargetString = this.string() break /* case 0x04 : record.Action = 'ActionNextFrame' break case 0x05 : // record.Action = 'ActionPrevFrame' break case 0x06 : // record.Action = 'ActionPlay' break case 0x07 : // record.Action = 'ActionStop' break case 0x08 : // record.Action = 'ActionToggleQuality' break case 0x09 : // record.Action = 'ActionStopSounds' break */ case 0x8a : // record.Action = 'ActionWaitForFrame' record.Frame = this.ui16() record.SkipCount = this.ui8() break case 0x8b : // record.Action = 'ActionSetTarget' record.TargetName = this.string() break /* case 0x08 : record.Action = 'ActionToggleQuality' break */ case 0x8b : // record.Action = 'ActionSetTarget' record.TargetName = this.string() break case 0x8c : // record.Action = 'ActionGotoLabel' record.Label = this.string() break // SWF4 case 0x96 : this.readActionPush(record) break // ... case 0x99 : // record.Action = 'ActionJump' record.BranchOffset = this.si16() break case 0x9d : // record.Action = 'ActionIf' record.BranchOffset = this.si16() break case 0x9a : // record.Action = 'ActionGetUrl2' record.SendVarsMethod = this.ub(2) record.Reserved = this.ub(4) record.LoadTargetFlag = this.ub(1) record.LoadVariablesFlag = this.ub(1) break case 0x9f : this.readActionGotoFrame2(record) break case 0x8d : // record.Action = 'ActionWaitForFrame2' record.SkipCount = this.ui8() break // SWF5 case 0x88 : this.readActionConstantPool(record) break case 0x9b : this.readActionDefineFunction(record) break case 0x94 : this.readActionWith(record) break case 0x87 : // record.Action = 'ActionStoreRegister' record.RegisterNumber = this.ui8() break // SWF6 case 0x8e : this.readActionDefineFunction2(record) break case 0x8f : this.readActionTry(record) break default : // record.Action = 'Unknown' break } //logger.info(record.ActionCode.toString(16) + ', ' + goog.debug.expose(record)) return record }, readActionPush : function(record) { //var Count = this.ui16() var Count = record.Length var startByteIndex = this.stream.byteIndex var values = [] //var logger = goog.debug.Logger.getLogger('parse') while (this.stream.byteIndex < startByteIndex + Count) { var Type = this.ui8() var value switch (Type) { case 0: value = this.string() break case 1: value = this.readFloat() break case 2: value = null break case 3: value = undefined break case 4: case 8: value = this.ui8() break case 5: value = !!this.ui8() break case 6: value = this.readDouble() break case 7: value = this.si32() // spec says UI32 break case 9: value = this.si16() // spec says UI16 break } //logger.info(Type + ': ' + value) values.push({Type : Type, Value : value}) } // record.Action = 'ActionPush' record.Values = values }, readActionGotoFrame2 : function(record) { this.ub(6) var SceneBiasFlag = this.ub(1) var PlayFlag = this.ub(1) var SceneBias if (SceneBiasFlag) { SceneBias = this.ui16() } // record.Action = 'ActionGotoFrame2' record.SceneBiasFlag = SceneBiasFlag record.PlayFlag = PlayFlag record.SceneBias = SceneBias }, readActionConstantPool : function(record) { var Count = record.Length var startByteIndex = this.stream.byteIndex var ConstantPool = [] //for (var i = 0; i < Count; i++) { var i = 0 while (this.stream.byteIndex < startByteIndex + Count) { var str = this.string() if (i > 0) { ConstantPool.push(str) } i++ } // record.Action = 'ActionConstantPool' record.Count = Count record.ConstantPool = ConstantPool }, readActionDefineFunction : function(record) { var FunctionName = this.string() var NumParams = this.ui16() var Params = [] for (var i = 0; i < NumParams; i++) { Params.push(this.string()) } var CodeSize = this.ui16() var Code = this.readActionRecords(CodeSize) // record.Action = 'ActionDefineFunction' record.FunctionName = FunctionName record.NumParams = NumParams record.Parameters = Params record.CodeSize = CodeSize record.Code = Code }, readActionWith : function(record) { var Size = this.ui16() var Code = this.readActionRecords(Size) // record.Action = 'ActionWith' record.Size = Size record.Code = Code }, readActionDefineFunction2 : function(record) { record.FunctionName = this.string() record.NumParams = this.ui16() record.RegisterCount = this.ui8() record.PreloadParentFlag = this.ub(1) record.PreloadRootFlag = this.ub(1) record.SupressSuperFlag = this.ub(1) record.PreloadSuperFlag = this.ub(1) record.SupressArgumentsFlag = this.ub(1) record.PreloadArgumentsFlag = this.ub(1) record.SupressThisFlag = this.ub(1) record.PreloadThisFlag = this.ub(1) this.ub(7) record.PreloadGlobalFlag = this.ub(1) record.Parameters = [] for (var i = 0; i < record.NumParams; i++) { record.Parameters.push(this.readRegisterParam()) } record.CodeSize = this.ui16() var Code = this.readActionRecords(record.CodeSize) // record.Action = 'ActionDefineFunction2' record.Code = Code }, readRegisterParam : function() { return { Register : this.ui8(), ParamName : this.string() } }, readActionTry : function(record) { this.ub(5) record.CatchInRegisterFlag = this.ub(1) record.FinallyBlockFlag = this.ub(1) record.CatchBlockFlag = this.ub(1) record.TrySize = this.ui16() record.CatchSize = this.ui16() record.FinallySize = this.ui16() if (record.CatchInRegisterFlag) { record.CatchRegister = this.ui8() } else { record.CatchName = this.string() } this.skipBytes(record.TrySize) this.skipBytes(record.CatchSize) this.skipBytes(record.FinallySize) }, readClipEventFlags : function() { var Flags if (this.header.Version <= 5) { Flags = this.ub(16) << 16 } else { Flags = this.ub(32) } return Flags }, readRgb : function() { return { Red : this.ui8(), Green : this.ui8(), Blue : this.ui8(), Alpha : 0xff } }, readRgba : function() { return { Red : this.ui8(), Green : this.ui8(), Blue : this.ui8(), Alpha : this.ui8() } }, readArgb : function() { return { Alpha : this.ui8(), Red : this.ui8(), Green : this.ui8(), Blue : this.ui8() } }, readRect : function() { this.stream.align() // as per adb var Nbits = this.ub(5) var value = { Nbits : Nbits, Xmin : this.sb(Nbits) / this.twipsPerPixel, Xmax : this.sb(Nbits) / this.twipsPerPixel, Ymin : this.sb(Nbits) / this.twipsPerPixel, Ymax : this.sb(Nbits) / this.twipsPerPixel } return value }, readShapeWithStyle : function() { this.stream.align() // as per adb var FillStyles = this.readFillStyleArray() var LineStyles = this.readLineStyleArray() this.stream.align() var NumFillBits = this.ub(4) var NumLineBits = this.ub(4) this.NumFillBits = NumFillBits this.NumLineBits = NumLineBits var ShapeRecords = this.readShapeRecords() return { FillStyles : FillStyles, LineStyles : LineStyles, NumFillBits : NumFillBits, NumLineBits : NumLineBits, ShapeRecords : ShapeRecords } }, readShapeRecords : function() { var records = [] var record = this.readShapeRecord() while (!record.isEndOfShape) { records.push(record) record = this.readShapeRecord() } this.stream.align() return records }, readShapeRecord : function() { var TypeFlag = this.ub(1) if (TypeFlag == 0) { return this.readNonEdgeShapeRecord() } else { return this.readEdgeShapeRecord() } }, readNonEdgeShapeRecord : function() { var StateNewStyles = this.ub(1) var StateLineStyle = this.ub(1) var StateFillStyle1 = this.ub(1) var StateFillStyle0 = this.ub(1) var StateMoveTo = this.ub(1) if ( StateNewStyles == 0 && StateLineStyle == 0 && StateFillStyle1 == 0 && StateFillStyle0 == 0 && StateMoveTo == 0 ) { return { isEndOfShape : true, type : 'END' } } else { var MoveBits var MoveDeltaX var MoveDeltaY if (StateMoveTo) { MoveBits = this.ub(5) MoveDeltaX = this.sb(MoveBits) MoveDeltaY = this.sb(MoveBits) } var FillStyle0 if (StateFillStyle0) { FillStyle0 = this.ub(this.NumFillBits) } var FillStyle1 if (StateFillStyle1) { FillStyle1 = this.ub(this.NumFillBits) } var LineStyle if (StateLineStyle) { LineStyle = this.ub(this.NumLineBits) } var FillStyles var LineStyles var NumFillBits var NumLineBits if (StateNewStyles) { FillStyles = this.readFillStyleArray() LineStyles = this.readLineStyleArray() this.stream.align() NumFillBits = this.ub(4) NumLineBits = this.ub(4) this.NumFillBits = NumFillBits this.NumLineBits = NumLineBits } return { isEndOfShape : false, type : 'NONEDGE', StateNewStyles : StateNewStyles, StateLineStyle : StateLineStyle, StateFillStyle1 : StateFillStyle1, StateFillStyle0 : StateFillStyle0, StateMoveTo : StateMoveTo, MoveBits : MoveBits, MoveDeltaX : MoveDeltaX / this.twipsPerPixel, MoveDeltaY : MoveDeltaY / this.twipsPerPixel, FillStyle0 : FillStyle0, FillStyle1 : FillStyle1, LineStyle : LineStyle, FillStyles : FillStyles, LineStyles : LineStyles, NumFillBits : NumFillBits, NumLineBits : NumLineBits } } }, readEdgeShapeRecord : function() { var StraightFlag = this.ub(1) if (StraightFlag == 1) { return this.readStraightEdgeRecord() } else { return this.readCurvedEdgeRecord() } }, readStraightEdgeRecord : function() { var NumBits = this.ub(4) var GeneralLineFlag = this.ub(1) var VertLineFlag if (GeneralLineFlag == 0) { VertLineFlag = this.ub(1) // spec says SB[1] } var DeltaX if (GeneralLineFlag == 1 || VertLineFlag == 0) { DeltaX = this.sb(NumBits + 2) if (VertLineFlag == 0) { DeltaY = 0 } } var DeltaY if (GeneralLineFlag == 1 || VertLineFlag == 1) { DeltaY = this.sb(NumBits + 2) if (VertLineFlag == 1) { DeltaX = 0 } } return { isStraightEdge : true, type : 'STRAIGHT', NumBits : NumBits, GeneralLineFlag : GeneralLineFlag, VertLineFlag : VertLineFlag, DeltaX : DeltaX / this.twipsPerPixel, DeltaY : DeltaY / this.twipsPerPixel } }, readCurvedEdgeRecord : function() { var NumBits = this.ub(4) var ControlDeltaX = this.sb(NumBits + 2) var ControlDeltaY = this.sb(NumBits + 2) var AnchorDeltaX = this.sb(NumBits + 2) var AnchorDeltaY = this.sb(NumBits + 2) return { isCurvedEdge : true, type : 'CURVED', NumBits : NumBits, ControlDeltaX : ControlDeltaX / this.twipsPerPixel, ControlDeltaY : ControlDeltaY / this.twipsPerPixel, AnchorDeltaX : AnchorDeltaX / this.twipsPerPixel, AnchorDeltaY : AnchorDeltaY / this.twipsPerPixel } }, readFillStyleArray : function() { var FillStyleCount = this.ui8(); var FillStyleCountExtended; // var t = fljs.swf.TagTypes if ( this.context == 22//t.DefineShape2 || this.context == 32//t.DefineShape3 || this.context == 83//t.DefineShape4 ) { if (FillStyleCount == 0xff) { FillStyleCountExtended = this.ui16(); FillStyleCount = FillStyleCountExtended; } } var FillStyles = []; for (var i = 0; i < FillStyleCount; i++) { FillStyles[i] = this.readFillStyle() } return FillStyles; }, readFillStyle : function() { var FillStyleType = this.ui8(); var Color; if (FillStyleType == 0x00) { if (this.context == 32/*fljs.swf.TagTypes.DefineShape3*/ || this.context == 83/*fljs.swf.TagTypes.DefineShape4*/) { Color = this.readRgba(); } else { Color = this.readRgb(); } } var GradientMatrix; var Gradient; if (FillStyleType == 0x10 || FillStyleType == 0x12) { GradientMatrix = this.readMatrix(); Gradient = this.readGradient(); } if (FillStyleType == 0x13) { GradientMatrix = this.readMatrix(); // as per adb Gradient = this.readFocalGradient(); } var BitmapId var BitmapMatrix if (FillStyleType == 0x40 || FillStyleType == 0x41 || FillStyleType == 0x42 || FillStyleType == 0x43) { BitmapId = this.ui16(); BitmapMatrix = this.readMatrix(); } this.stream.align() // as per adb return { FillStyleType : FillStyleType, Color : Color, GradientMatrix : GradientMatrix, Gradient : Gradient, BitmapId : BitmapId, BitmapMatrix : BitmapMatrix }; }, readLineStyleArray : function() { var LineStyleCount = this.ui8() var LineStyleCountExtended if (LineStyleCount == 0xff) { LineStyleCountExtended = this.ui16() LineStyleCount = LineStyleCountExtended } var LineStyles = []; if (this.context == 83/*fljs.swf.TagTypes.DefineShape4*/) { for (var i = 0; i < LineStyleCount; i++) { LineStyles[i] = this.readLineStyle2(); } } else { for (var i = 0; i < LineStyleCount; i++) { LineStyles[i] = this.readLineStyle(); } } return LineStyles; }, readLineStyle : function() { var Width = this.ui16() var Color if ( this.context == 2//fljs.swf.TagTypes.DefineShape || this.context == 22//fljs.swf.TagTypes.DefineShape2 ) { Color = this.readRgb() } else { Color = this.readRgba() } return { Width : Width / this.twipsPerPixel, Color : Color } }, readLineStyle2 : function() { var Width = this.ui16() var StartCapStyle = this.ub(2) var JoinStyle = this.ub(2) var HasFillFlag = this.ub(1) var NoHScaleFlag = this.ub(1) var NoVScaleFlag = this.ub(1) var PixelHintingFlag = this.ub(1) this.ub(5) var NoClose = this.ub(1) var EndCapStyle = this.ub(2) var MiterLimitFactor if (JoinStyle == 2) { MiterLimitFactor = this.ui16() } var Color if (HasFillFlag == 0) { Color = this.readRgba() } var FillType if (HasFillFlag == 1) { FillType = this.readFillStyle() } return { Width : Width / this.twipsPerPixel, StartCapStyle : StartCapStyle, JoinStyle : JoinStyle, HasFillFlag : HasFillFlag, NoHScaleFlag : NoHScaleFlag, NoVScaleFlag : NoVScaleFlag, PixelHintingFlag : PixelHintingFlag, NoClose : NoClose, EndCapStyle : EndCapStyle, MiterLimitFactor : MiterLimitFactor, Color : Color, FillType : FillType } }, readGradient : function() { this.stream.align() // as per adb var SpreadMode = this.ub(2) var InterpolationMode = this.ub(2) var NumGradients = this.ub(4) var GradientRecords = [] for (var i = 0; i < NumGradients; i++) { GradientRecords.push(this.readGradRecord()) } return { SpreadMode : SpreadMode, InterpolationMode : InterpolationMode, NumGradients : NumGradients, GradientRecords : GradientRecords } }, readFocalGradient : function() { this.stream.align() // as per adb var SpreadMode = this.ub(2) var InterpolationMode = this.ub(2) var NumGradients = this.ub(4) var GradientRecords = [] for (var i = 0; i < NumGradients; i++) { GradientRecords.push(this.readGradRecord()) } var FocalPoint = this.readFixed8() return { SpreadMode : SpreadMode, InterpolationMode : InterpolationMode, NumGradients : NumGradients, GradientRecords : GradientRecords, FocalPoint : FocalPoint } }, readGradRecord : function() { var Ratio = this.ui8() var Color if ( this.context == 2//fljs.swf.TagTypes.DefineShape || this.context == 22//fljs.swf.TagTypes.DefineShape2 ) { Color = this.readRgb() } else { Color = this.readRgba() } return { Ratio : Ratio, Color : Color } }, readMatrix : function() { var d = {} this.stream.align() // as per adb d.HasScale = this.ub(1) if (d.HasScale) { d.NScaleBits = this.ub(5) d.ScaleX = this.readFB(d.NScaleBits) d.ScaleY = this.readFB(d.NScaleBits) } d.HasRotate = this.ub(1) if (d.HasRotate) { d.NRotateBits = this.ub(5) d.RotateSkew0 = this.readFB(d.NRotateBits) d.RotateSkew1 = this.readFB(d.NRotateBits) } d.NTranslateBits = this.ub(5) d.TranslateX = this.sb(d.NTranslateBits) / this.twipsPerPixel d.TranslateY = this.sb(d.NTranslateBits) / this.twipsPerPixel return d }, readShape : function() { var NumFillBits = this.ub(4) var NumLineBits = this.ub(4) this.NumFillBits = NumFillBits this.NumLineBits = NumLineBits var ShapeRecords = this.readShapeRecords() return { NumFillBits : NumFillBits, NumLineBits : NumLineBits, ShapeRecords : ShapeRecords } }, readTextRecords : function() { var records = [] while (true) { this.stream.align() var TextRecordType = this.ub(1) if (TextRecordType) { records.push(this.readTextRecord()) } else { this.stream.align() break } } return records }, readTextRecord : function() { // no align var StyleFlagsReserved = this.ub(3) var StyleFlagsHasFont = this.ub(1) var StyleFlagsHasColor = this.ub(1) var StyleFlagsHasYOffset = this.ub(1) var StyleFlagsHasXOffset = this.ub(1) var FontId if (StyleFlagsHasFont) { FontId = this.ui16() } var TextColor if (StyleFlagsHasColor) { if (this.context == 33/*fljs.swf.TagTypes.DefineText2*/) { TextColor = this.readRgba() } else { TextColor = this.readRgb() } } var XOffset if (StyleFlagsHasXOffset) { XOffset = this.si16() / this.twipsPerPixel } var YOffset if (StyleFlagsHasYOffset) { YOffset = this.si16() / this.twipsPerPixel } var TextHeight if (StyleFlagsHasFont) { TextHeight = this.ui16() / this.twipsPerPixel } var GlyphCount = this.ui8() var GlyphEntries = [] for (var i = 0; i < GlyphCount; i++) { GlyphEntries.push(this.readGlyphEntry()) } return { StyleFlagsReserved : StyleFlagsReserved, StyleFlagsHasFont : StyleFlagsHasFont, StyleFlagsHasColor : StyleFlagsHasColor, StyleFlagsHasYOffset : StyleFlagsHasYOffset, StyleFlagsHasXOffset : StyleFlagsHasXOffset, FontId : FontId, TextColor : TextColor, XOffset : XOffset, YOffset : YOffset, TextHeight : TextHeight, GlyphCount : GlyphCount, GlyphEntries : GlyphEntries } }, readGlyphEntry : function() { return { GlyphIndex : this.ub(this.GlyphBits), GlyphAdvance : this.sb(this.AdvanceBits) / this.twipsPerPixel } }, readLangCode : function() { return this.ui8() }, readKerningRecord : function() { var FontKerningCode1 var FontKerningCode2 if (this.FontFlagsWideCodes) { FontKerningCode1 = this.ui16() FontKerningCode2 = this.ui16() } else { FontKerningCode1 = this.ui8() FontKerningCode2 = this.ui8() } var FontKerningAdjustment = this.si16() return { FontKerningCode1 : FontKerningCode1, FontKerningCode2 : FontKerningCode2, FontKerningAdjustment : FontKerningAdjustment } }, readMp3SoundData : function(byteCount) { var startByteIndex = this.stream.byteIndex var SeekSamples = this.si16() var byteIndex = this.stream.byteIndex var Mp3Frames = [] while (this.stream.byteIndex < startByteIndex + byteCount) { Mp3Frames.push(this.readMp3Frame(Mp3Frames.length)) } var byteCount = this.stream.byteIndex - byteIndex return { SeekSamples : SeekSamples, Mp3Frames : Mp3Frames, byteIndex : byteIndex, byteCount : byteCount, buffer : this.stream.buffer } }, readMp3Frame : function() { var Syncword = this.ub(11) if (Syncword != 0x7ff) { throw new Error('readMp3Frame: Syncword is wrong in frame# ' + arguments[0] + ' @ ' + this.stream.byteIndex) } var MpegVersion = this.ub(2) var Layer = this.ub(2) var ProtectionBit = this.ub(1) var Bitrate = this.ub(4) var SamplingRate = this.ub(2) var PaddingBit = this.ub(1) this.ub(1) var ChannelMode = this.ub(2) var ModeExtension = this.ub(2) var Copyright = this.ub(1) var Original = this.ub(1) var Emphasis = this.ub(2) if (ProtectionBit == 0) { this.ui16() } var mpegVersions = { MPEG2_5 : 0, MPEG2 : 2, MPEG1 : 3 } var mpegVersionNumbers = { 0 : 2, 2 : 2, 3 : 1 } var bitrates = { 1 : [ null, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 ], 2 : [ null, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 ] } var samplingRates = { 0 : [11025, 12000, 8000], 2 : [22050, 24000, 16000], 3 : [44100, 48000, 32000] } var byteCount = Math.floor( (MpegVersion == mpegVersions.MPEG1 ? 144 : 72) * bitrates[mpegVersionNumbers[MpegVersion]][Bitrate] * 1000 / samplingRates[MpegVersion][SamplingRate] ) + PaddingBit - 4 var SampleData = this.bytes(byteCount) return { Syncword : Syncword, MpegVersion : MpegVersion, Layer : Layer, ProtectionBit : ProtectionBit, Bitrate : Bitrate, SamplingRate : SamplingRate, PaddingBit : PaddingBit, ChannelMode : ChannelMode, ModeExtension : ModeExtension, Copyright : Copyright, Original : Original, Emphasis : Emphasis, byteCount : byteCount, SampleData : SampleData } }, readSoundInfo : function() { this.ub(2) var SyncStop = this.ub(1) var SyncNoMultiple = this.ub(1) var HasEnvelope = this.ub(1) var HasLoops = this.ub(1) var HasOutPoint = this.ub(1) var HasInPoint = this.ub(1) var InPoint if (HasInPoint) { InPoint = this.ui32() } var OutPoint if (HasOutPoint) { OutPoint = this.ui32() } var LoopCount if (HasLoops) { LoopCount = this.ui16() } var EnvPoints var EnvelopeRecords if (HasEnvelope) { EnvPoints = this.ui8() EnvelopeRecords = [] for (var i = 0; i < EnvPoints; i++) { EnvelopeRecords.push(this.readEnvelopeRecord()) } } return { SyncStop : SyncStop, SyncNoMultiple : SyncNoMultiple, HasEnvelope : HasEnvelope, HasLoops : HasLoops, HasOutPoint : HasOutPoint, HasInPoint : HasInPoint, InPoint : InPoint, OutPoint : OutPoint, LoopCount : LoopCount, EnvPoints : EnvPoints, EnvelopeRecords : EnvelopeRecords } }, readEnvelopeRecord : function() { return { Pos44 : this.ui32(), LeftLevel : this.ui16(), RightLevel : this.ui16() } }, readButtonRecords : function() { var records = [] var record while (record = this.readButtonRecord()) { records.push(record) } return records }, readButtonRecord : function() { var record = {} this.stream.align() this.ub(2) record.ButtonHasBlendMode = this.ub(1) record.ButtonHasFilterList = this.ub(1) record.ButtonStateHitTest = this.ub(1) record.ButtonStateDown = this.ub(1) record.ButtonStateOver = this.ub(1) record.ButtonStateUp = this.ub(1) if ( !record.ButtonHasBlendMode && !record.ButtonHasFilterList && !record.ButtonStateHitTest && !record.ButtonStateDown && !record.ButtonStateOver && !record.ButtonStateUp ) { return null } record.CharacterId = this.ui16() record.PlaceDepth = this.ui16() record.PlaceMatrix = this.readMatrix() if (this.context == 34/*fljs.swf.TagTypes.DefineButton2*/) { record.ColorTransform = this.readCxform(true) if (record.ButtonHasFilterList) { record.FilterList = this.readFilterList() } if (record.ButtonHasBlendMode) { record.BlendMode = this.ui8() } } return record }, readFilterList : function() { var list = [] var count = this.ui8() for (var i = 0; i < count; i++) { list.push(this.readFilter()) } return list }, readFilter : function() { var filter = {} filter.FilterId = this.ui8() switch (filter.FilterId) { case 0: filter.DropShadowFilter = this.readDropShadowFilter() break case 1: filter.BlurFilter = this.readBlurFilter() break case 2: filter.GlowFilter = this.readGlowFilter() break case 3: filter.BevelFilter = this.readBevelFilter() break case 4: filter.GradientGlowFilter = this.readGradientGlowFilter() break case 5: filter.ConvolutionFilter = this.readConvolutionFilter() break case 6: filter.ColorMatrixFilter = this.readColorMatrixFilter() break case 7: filter.GradientBevelFitler = this.readGradientBevelFilter() break } return filter }, readColorMatrixFilter : function() { return { Matrix : this.readFloats(20) } }, readConvolutionFilter : function() { var d = {} d.MatrixX = this.ui8() d.MatrixY = this.ui8() d.Divisor = this.readFloat() d.Bias = this.readFloat() d.Matrix = this.readFloats(d.MatrixX * d.MatrixY) d.DefaultColor = this.readRgba() this.ub(6) d.Clamp = this.ub(1) d.PreserveAlpha = this.ub(1) return d }, readBlurFilter : function() { var d = { BlurX : this.readFixed(), BlurY : this.readFixed(), Passes : this.ub(5) } this.ub(3) return d }, readDropShadowFilter : function() { return { DropShadowColor : this.readRgba(), BlurX : this.readFixed(), BlurY : this.readFixed(), Angle : this.readFixed(), Distance : this.readFixed(), Strength : this.readFixed8(), InnerShadow : this.ub(1), Knockout : this.ub(1), CompositeSource : this.ub(1), Passes : this.ub(5) } }, readGlowFilter : function() { return { GlowColor : this.readRgba(), BlurX : this.readFixed(), BlurY : this.readFixed(), Strength : this.readFixed8(), InnerGlow : this.ub(1), Knockout : this.ub(1), CompositeSource : this.ub(1), Passes : this.ub(5) } }, readBevelFilter : function() { return { ShadowColor : this.readRgba(), HighlightColor : this.readRgba(), BlurX : this.readFixed(), BlurY : this.readFixed(), Angle : this.readFixed(), Distance : this.readFixed(), Strength : this.readFixed8(), InnerShadow : this.ub(1), Knockout : this.ub(1), CompositeSource : this.ub(1), OnTop : this.ub(1), Passes : this.ub(4) } }, readGradientGlowFilter : function() { var filter = {} filter.NumColors = this.ui8() filter.GradientColors = [] for (var i = 0; i < filter.NumColors; i++) { filter.GradientColors.push(this.readRgba()) } filter.GradientRatios = [] for (var i = 0; i < filter.NumColors; i++) { filter.GradientRatios.push(this.ui8()) } filter.BlurX = this.readFixed() filter.BlurY = this.readFixed() filter.Angle = this.readFixed() filter.Distance = this.readFixed() filter.Strength = this.readFixed8() filter.InnerShadow = this.ub(1) filter.Knockout = this.ub(1) filter.CompositeSource = this.ub(1) filter.OnTop = this.ub(1) filter.Passes = this.ub(4) return filter }, readGradientBevelFilter : function() { var filter = {} filter.NumColors = this.ui8() filter.GradientColors = [] for (var i = 0; i < filter.NumColors; i++) { filter.GradientColors.push(this.readRgba()) } filter.GradientRatios = [] for (var i = 0; i < filter.NumColors; i++) { filter.GradientRatios.push(this.ui8()) } filter.BlurX = this.readFixed() filter.BlurY = this.readFixed() filter.Angle = this.readFixed() filter.Distance = this.readFixed() filter.Strength = this.readFixed8() filter.InnerShadow = this.ub(1) filter.Knockout = this.ub(1) filter.CompositeSource = this.ub(1) filter.OnTop = this.ub(1) filter.Passes = this.ub(4) return filter }, readButtonCondActions : function(bytes) { var actions = [] // rar.rar = rar var startByteIndex = this.stream.byteIndex var recordBytes while (recordBytes = this.ui16()) { actions.push(this.readButtonCondAction(recordBytes - 2)) } actions.push(this.readButtonCondAction(bytes - (this.stream.byteIndex - startByteIndex))) return actions }, readButtonCondAction : function(bytes) { var action = {} action.CondActionSize = bytes + 2 action.CondIdleToOverDown = this.ub(1) action.CondOutDownToIdle = this.ub(1) action.CondOutDownToOverDown = this.ub(1) action.CondOverDownToOutDown = this.ub(1) action.CondOverDownToOverUp = this.ub(1) action.CondOverUpToOverDown = this.ub(1) action.CondOverUpToIdle = this.ub(1) action.CondIdleToOverUp = this.ub(1) action.CondKeyPress = this.ub(7) action.CondOverDownToIdle = this.ub(1) action.Actions = this.readActionRecords(bytes - 2) return action }, readPix15 : function() { this.stream.align() this.ub(1) return { Red : Math.floor(this.ub(5) * 8.226), Green : Math.floor(this.ub(5) * 8.226), Blue : Math.floor(this.ub(5) * 8.226) } }, readZoneRecord : function() { var d = {} d.NumZoneData = this.ui8() d.ZoneData = [] for (var i = 0; i < d.NumZoneData; i++) { d.ZoneData.push(this.readZoneData()) } this.ub(6) d.ZoneMaskY = this.ub(1) d.ZoneMaskX = this.ub(1) return d }, readZoneData : function() { return { AlignmentCoordinate: this.readFloat16(), Range: this.readFloat16() } }, beginContext : function(tag) { this.context = tag }, endContext : function() { this.context = null this.NumFillBits = null this.NumLineBits = null }, readRecord : function(skip) { var header = this.header var d = {} d.header = header if (skip) { this.stream.skipBytes(header.TagLength) return d } // var t = fljs.swf.TagTypes var keepExtra = false // TODO: which need to be kept? switch (header.TagType) { case 6://t.DefineBits: case 21://t.DefineBitsJpeg2: d.CharacterId = this.ui16() var byteCount = header.TagLength - 2 var useTables = header.TagType == 6//t.DefineBits this.readJpeg(d, byteCount, useTables) break case 35://t.DefineBitsJpeg3: var startByteIndex = this.stream.byteIndex d.CharacterId = this.ui16() var loader = this.loader if (env.loadExtResources()) { this.skipBytes(header.TagLength - 2) var imageUrl = 'img/' + loader.name + '-' + d.CharacterId + '.png' ext.console('image').info(imageUrl) var image = new Image() var onLoad = ext.bind(this.onLoadJpegImage, this, d, header, image) image.addEventListener('load', onLoad, false) loader.delayFrame++ image.src = imageUrl } else { d.AlphaDataOffset = this.ui32() var byteCount = d.AlphaDataOffset this.readJpeg(d, byteCount, false) byteCount = header.TagLength - (this.stream.byteIndex - startByteIndex) var byteIndex = this.stream.byteIndex var writer = new PngWriter() d.alphaDataUri = writer.buildPng( this.stream.buffer, byteIndex, byteCount, d.Width, d.Height, 3, // indexed PngWriter.WhitePalette, PngWriter.LinearTransparency ) } break case 20://t.DefineBitsLossless: case 36://t.DefineBitsLossless2: var startByteIndex = this.stream.byteIndex d.CharacterId = this.ui16() d.BitmapFormat = this.ui8() d.Width = d.BitmapWidth = this.ui16() d.Height = d.BitmapHeight = this.ui16() if (d.BitmapFormat == 3) { d.BitmapColorTableSize = this.ui8() } var byteCount = header.TagLength - (this.stream.byteIndex - startByteIndex) if (env.loadExtLargeImg && byteCount > 50000) { this.delay = true } else { var zipped = this.stream.buffer.substr(this.stream.byteIndex + 2, byteCount - 2) var inflated = zip.inflate(zipped) var bitmapData = new SwfReader(new LittleEndianStringReader(inflated)) var canvas = document.createElement('canvas') canvas.width = d.BitmapWidth canvas.height = d.BitmapHeight var ctx = canvas.getContext('2d') var img = ctx.createImageData(d.BitmapWidth, d.BitmapHeight) var data = img.data // indexed if (d.BitmapFormat == 3) { d.ColorTableRgb = [] for (var i = 0; i < d.BitmapColorTableSize + 1; i++) { if (header.TagType == 20/*t.DefineBitsLossless*/) { d.ColorTableRgb[i] = bitmapData.readRgb() d.ColorTableRgb[i].Alpha = 0xff } else { d.ColorTableRgb[i] = bitmapData.readRgba() } } var dataWidth = Math.floor((d.BitmapWidth + 3) / 4) * 4 var i = 0 var x = 0 while (i < d.BitmapWidth * d.BitmapHeight * 4) { var idx = bitmapData.ui8() var clr if (idx in d.ColorTableRgb) { clr = d.ColorTableRgb[idx] } else { clr = {Red:0, Green:0, Blue:0, Alpha:0} } data[i++] = clr.Red data[i++] = clr.Green data[i++] = clr.Blue data[i++] = clr.Alpha x++ if (x == d.BitmapWidth) { bitmapData.skipBytes(dataWidth - d.BitmapWidth) x = 0 } } } // truecolor else if (d.BitmapFormat == 4) { var dataWidth = Math.floor((d.BitmapWidth * 2 + 3) / 4) * 4 var i = 0 var x = 0 while (i < d.BitmapWidth * d.BitmapHeight * 4) { var clr = bitmapData.readPix15() data[i++] = clr.Red data[i++] = clr.Green data[i++] = clr.Blue data[i++] = 0xff x++ if (x == d.BitmapWidth) { bitmapData.skipBytes(dataWidth - d.BitmapWidth) x = 0 } } } // truecolor with alpha else if (d.BitmapFormat == 5) { var i = 0 while (i < d.BitmapWidth * d.BitmapHeight * 4) { var clr = bitmapData.readArgb() if (header.TagType == 20/*t.DefineBitsLossless*/) { clr.Alpha = 0xff } data[i++] = clr.Red data[i++] = clr.Green data[i++] = clr.Blue data[i++] = clr.Alpha } } ctx.putImageData(img, 0, 0) d.canvas = canvas d.DataUri = canvas.toDataURL() } break case 34://t.DefineButton2: var byteIndex = this.stream.byteIndex this.context = 34//t.DefineButton2 d.ButtonId = this.ui16() this.ub(7) d.TrackAsMenu = this.ub(1) d.ActionOffset = this.ui16() d.Characters = this.readButtonRecords() if (d.ActionOffset) { d.Actions = this.readButtonCondActions(header.TagLength - (this.stream.byteIndex - byteIndex)) } else { d.Actions = [] } this.context = null break case 37://t.DefineEditText: d.CharacterId = this.ui16() d.Bounds = this.readRect() this.stream.align() d.HasText = this.ub(1) d.WordWrap = this.ub(1) d.Multiline = this.ub(1) d.Password = this.ub(1) d.ReadOnly = this.ub(1) d.HasTextColor = this.ub(1) d.HasMaxLength = this.ub(1) d.HasFont = this.ub(1) d.HasFontClass = this.ub(1) d.AutoSize = this.ub(1) d.HasLayout = this.ub(1) d.NoSelect = this.ub(1) d.Border = this.ub(1) d.WasStatic = this.ub(1) d.HTML = this.ub(1) d.UseOutlines = this.ub(1) if (d.HasFont) { d.FontId = this.ui16() } if (d.HasFontClass) { d.FontClass = this.string() } if (d.HasFont) { d.FontHeight = this.ui16() / this.twipsPerPixel } if (d.HasTextColor) { d.TextColor = this.readRgba() } if (d.HasMaxLength) { d.MaxLength = this.ui16() } if (d.HasLayout) { d.Align = this.ui8() d.LeftMargin = this.ui16() d.RightMargin = this.ui16() d.Indent = this.ui16() d.Leading = this.ui16() } d.VariableName = this.string() if (d.HasText) { d.InitialText = this.string() } break case 10://t.DefineFont: d.FontId = this.ui16() d.OffsetTable = [this.ui16()] var glyphCount = d.OffsetTable[0] / 2 d.NumGlyphs = glyphCount for (var i = 1; i < glyphCount; i++) { d.OffsetTable.push(this.ui16()) } d.GlyphShapeTable = [] for (var j = 0; j < glyphCount; j++) { d.GlyphShapeTable.push(this.readShape()) } break case 48://t.DefineFont2: case 75://t.DefineFont3: var i d.FontId = this.ui16() d.FontFlagsHasLayout = this.ub(1) d.FontFlagsShiftJIS = this.ub(1) d.FontFlagsSmallText = this.ub(1) d.FontFlagsANSI = this.ub(1) d.FontFlagsWideOffsets = this.ub(1) d.FontFlagsWideCodes = this.ub(1) this.FontFlagsWideCodes = d.FontFlagsWideCodes d.FontFlagsItalic = this.ub(1) d.FontFlagsBold = this.ub(1) d.LanguageCode = this.readLangCode() d.FontNameLen = this.ui8() var chars = [] for (i = 0; i < d.FontNameLen; i++) { chars.push(String.fromCharCode(this.ui8())) } d.FontName = chars.join('') d.NumGlyphs = this.ui16() d.OffsetTable = [] if (d.FontFlagsWideOffsets) { for (i = 0; i < d.NumGlyphs; i++) { d.OffsetTable.push(this.ui32()) } d.CodeTableOffset = this.ui32() } else { for (i = 0; i < d.NumGlyphs; i++) { d.OffsetTable.push(this.ui16()) } d.CodeTableOffset = this.ui16() } d.GlyphShapeTable = [] for (i = 0; i < d.NumGlyphs; i++) { d.GlyphShapeTable.push(this.readShape()) } d.CodeTable = [] d.GlyphIndex = {} if (d.FontFlagsWideCodes) { for (i = 0; i < d.NumGlyphs; i++) { var code = this.ui16() d.CodeTable.push(code) d.GlyphIndex[code] = i } } else { for (i = 0; i < d.NumGlyphs; i++) { var code = this.ui8() d.CodeTable.push(code) d.GlyphIndex[code] = i } } if (d.FontFlagsHasLayout) { d.FontAscent = this.si16() d.FontDescent = this.si16() d.FontLeading = this.si16() d.FontAdvanceTable = [] for (i = 0; i < d.NumGlyphs; i++) { d.FontAdvanceTable.push(this.si16()) } d.FontBoundsTable = [] for (i = 0; i < d.NumGlyphs; i++) { d.FontBoundsTable.push(this.readRect()) this.stream.align() } d.KerningCount = this.ui16() d.FontKerningTable = [] for (i = 0; i < d.KerningCount; i++) { d.FontKerningTable.push(this.readKerningRecord()) } } break case 13://t.DefineFontInfo: case 62://t.DefineFontInfo2: var startByteIndex = this.stream.byteIndex d.FontId = this.ui16() d.FontNameLen = this.ui8() var chars = [] for (i = 0; i < d.FontNameLen; i++) { chars.push(String.fromCharCode(this.ui8())) } d.FontName = chars.join('') this.ub(2) d.FontFlagsSmallText = this.ub(1) d.FontFlagsShiftJis = this.ub(1) d.FontFlagsAnsi = this.ub(1) d.FontFlagsItalic = this.ub(1) d.FontFlagsBold = this.ub(1) d.FontFlagsWideCodes = this.ub(1) if (header.TagType == 62/*t.DefineFontInfo2*/) { d.LanguageCode = this.readLangCode() } var byteCount = header.TagLength - (this.stream.byteIndex - startByteIndex) d.CodeTable = [] if (d.FontFlagsWideCodes) { var numGlyphs = byteCount / 2 for (i = 0; i < numGlyphs; i++) { d.CodeTable.push(this.ui16()) } } else { var numGlyphs = byteCount for (i = 0; i < numGlyphs; i++) { d.CodeTable.push(this.ui8()) } } break case 2://t.DefineShape: case 22://t.DefineShape2: case 32://t.DefineShape3: case 83://t.DefineShape4: this.beginContext(header.TagType) this.endByteIndex = this.stream.byteIndex + header.TagLength d.defId = d.ShapeId = this.ui16() d.ShapeBounds = this.readRect() if (header.TagType == 83/*t.DefineShape4*/) { this.EdgeBounds = this.readRect(); this.ub(6) this.UsesNonScalingStrokes = this.ub(1) this.UsesScalingStrokes = this.ub(1) } else { this.stream.align() } d.Shapes = this.readShapeWithStyle() this.endContext() break case 15://t.DefineSound: d.SoundId = this.ui16() d.SoundFormat = this.ub(4) d.SoundRate = this.ub(2) d.SoundSize = this.ub(1) d.SoundType = this.ub(1) d.SoundSampleCount = this.ui32() var byteCount = header.TagLength - 2 - 1 - 4 d.SoundData = this.readMp3SoundData(byteCount) d.Mp3SoundData = d.SoundData break case 39://t.DefineSprite: keepExtra = true var startByteIndex = this.stream.byteIndex d.CharacterId = d.defId = d.SpriteId = this.ui16() d.FrameCount = this.ui16() d.frameData_ = [{tags: []}] d.labels_ = {} d.framesLoaded_ = 0 d.totalFrames_ = d.FrameCount break case 11://t.DefineText: case 33://t.DefineText2: d.CharacterId = this.ui16() d.TextBounds = this.readRect() this.stream.align() d.TextMatrix = this.readMatrix() d.GlyphBits = this.ui8() d.AdvanceBits = this.ui8() this.GlyphBits = d.GlyphBits this.AdvanceBits = d.AdvanceBits this.context = header.TagType d.TextRecords = this.readTextRecords() this.context = null if (d.TextRecords && d.TextRecords.length) { d.FontId = d.TextRecords[0].FontId } d.Bounds = d.TextBounds break /* case t.DefineVideoStream: d.defId = d.CharacterId = this.ui16() d.NumFrames = this.ui16() d.Width = this.ui16() d.Height = this.ui16() this.ub(4) d.VideoFlagsDeblocking = this.ub(3) d.VideoFlagsSmoothing = this.ub(1) d.CodecId = this.ui8() break */ case 12://t.DoAction: d.Actions = this.readActionRecords(header.TagLength) break case 59://t.DoInitAction: d.SpriteId = this.ui16() var byteCount = header.TagLength - 2 - 1 d.Actions = this.readActionRecords(byteCount) d.ActionEndFlag = this.ui8() break case 0://t.End: break case 56://t.ExportAssets: d.Count = this.ui16() d.Tags = [] d.Names = [] for (var i = 0; i < d.Count; i++) { d.Tags[i] = this.ui16() d.Names[i] = this.string() } break case 43://t.FrameLabel: d.Name = this.string() break case 8://t.JpegTables: if (header.TagLength > 0) { var data = this.bytes(header.TagLength).join('') var reader = new BigEndianStringReader(data) var header, count var soi = reader.uShort() var offset = 0 if (soi == 0xffd9) { offset = 4 reader.uShort() reader.uShort() } d.JpegData = data.substr(offset, data.length - offset - 2) } break case 4://t.PlaceObject: var startByteIndex = this.stream.byteIndex d.CharacterId = this.ui16() d.Depth = this.ui16() d.Matrix = this.readMatrix() this.stream.align() if (this.stream.byteIndex != startByteIndex + header.TagLength) { d.ColorTransform = this.readCxform() } this.stream.align() break case 26://t.PlaceObject2: case 70://t.PlaceObject3: d.startByteIndex = this.stream.byteIndex d.PlaceFlagHasClipActions = this.ub(1) d.PlaceFlagHasClipDepth = this.ub(1) d.PlaceFlagHasName = this.ub(1) d.PlaceFlagHasRatio = this.ub(1) d.PlaceFlagHasColorTransform = this.ub(1) d.PlaceFlagHasMatrix = this.ub(1) d.PlaceFlagHasCharacter = this.ub(1) d.PlaceFlagMove = this.ub(1) if (header.TagType == 70/*t.PlaceObject3*/) { this.ub(3) d.PlaceFlagHasImage = this.ub(1) d.PlaceFlagHasClassName = this.ub(1) d.PlaceFlagHasCacheAsBitmap = this.ub(1) d.PlaceFlagHasBlendMode = this.ub(1) d.PlaceFlagHasFilterList = this.ub(1) d.Depth = this.ui16() if (d.PlaceFlagHasClassName || (d.PlaceFlagHasImage && d.PlaceFlagHasCharacter)) { d.ClassName = this.string() } } else { d.Depth = this.ui16() } if (d.PlaceFlagHasCharacter) { d.CharacterId = this.ui16() } if (d.PlaceFlagHasMatrix) { d.Matrix = this.readMatrix() } if (d.PlaceFlagHasColorTransform) { d.ColorTransform = this.readCxform(true) } if (d.PlaceFlagHasRatio) { d.Ratio = this.ui16() } if (d.PlaceFlagHasName) { d.Name = this.string() } if (d.PlaceFlagHasClipDepth) { d.ClipDepth = this.ui16() } if (header.TagType == 70/*t.PlaceObject3*/) { if (d.PlaceFlagHasFilterList) { d.SurfaceFilterList = this.readFilterList() } if (d.PlaceFlagHasBlendMode) { d.BlendMode = this.ui8() } } if (d.PlaceFlagHasClipActions) { d.ClipActions = this.readClipActions() } break case 24://t.Protect: this.skipBytes(header.TagLength) break case 5://t.RemoveObject: d.CharacterId = this.ui16() d.Depth = this.ui16() break case 28://t.RemoveObject2: d.Depth = this.ui16() break case 9://t.SetBackgroundColor: d.BackgroundColor = this.readRgb() break case 1://t.ShowFrame: break case 19://t.SoundStreamBlock: d.SampleCount = this.ui16() var byteCount = header.TagLength - 2 d.Mp3SoundData = this.readMp3SoundData(byteCount) break case 18://t.SoundStreamHead: case 45://t.SoundStreamHead2: this.ub(4) d.PlaybackSoundRate = this.ub(2) d.PlaybackSoundSize = this.ub(1) d.PlaybackSoundType = this.ub(1) d.StreamSoundCompression = this.ub(4) d.StreamSoundRate = this.ub(2) d.StreamSoundSize = this.ub(1) d.StreamSoundType = this.ub(1) d.StreamSoundSampleCount = this.ui16() if (d.StreamSoundCompression == 2) { d.LatencySeek = this.si16() } break case 15://t.StartSound: d.SoundId = this.ui16() d.SoundInfo = this.readSoundInfo() break case 73://t.DefineFontAlignZones: var startByteIndex = this.stream.byteIndex d.FontId = this.ui16() d.CsmTableHint = this.ub(2) this.ub(6) // reserved d.ZoneTable = [] while (this.stream.byteIndex != startByteIndex + header.TagLength) { d.ZoneTable.push(this.readZoneRecord()) } break default: this.stream.skipBytes(header.TagLength) break } var bytesLeft = this.tagBytesLeft() if (!keepExtra && bytesLeft > 0) { this.stream.skipBytes(bytesLeft) } else if (!keepExtra && bytesLeft != 0) { //debugger } return d }, readJpeg : function(tag, byteCount, useTables) { var data = String(this.bytes(byteCount).join('')) var reader = new BigEndianStringReader(data) var header, count var loader = this.loader var soi = reader.uShort() var offset if (soi == 0xffd9) { if (useTables && loader.jpegTables) { offset = 6 } else { offset = 4 } reader.uShort() reader.uShort() } else { if (useTables && loader.jpegTables) { offset = 2 } else { offset = 0 } } var middleSoi = 0 while (reader.byteIndex < byteCount) { header = reader.uShort() count = reader.uShort() if (header == 0xffc0) { reader.uByte() tag.Height = reader.uShort() tag.Width = reader.uShort() break } if (header == 0xffd9) { middleSoi = reader.byteIndex - 6 } else { reader.skipBytes(count - 2) } } // deal with messed up jpegs if (middleSoi) { data = data.substr(0, middleSoi) + data.substr(middleSoi + 6) } if (offset) { data = data.substr(offset) } var tables if (useTables && loader.jpegTables) { tables = loader.jpegTables.JpegData } else { tables = '' } tag.DataUri = 'data:image/jpeg;base64,' + btoa(tables + data) }, readTags : function(limit) { //var t = fljs.swf.TagTypes var loader = this.loader var canSkip = 'isSkipTag' in loader loop: while (this.hasMore() && this.someBytesLeft(limit) > 0) { var header = this.readRecordHeader() var skip = canSkip && loader.isSkipTag(header) this.delay = false var tag = this.readRecord(skip) loader.onTag(tag, this.target, this.frames) switch (header.TagType) { case 39://t.DefineSprite: this.target = tag this.frames.unshift(0) break case 1://t.ShowFrame: this.frames[0] += 1 break case 0://t.End: this.target = null this.frames.shift() break case 6://t.DefineBits: case 21://t.DefineBitsJpeg2: case 35://t.DefineBitsJpeg3: break loop break } if (this.delay) { break loop } } this.bytesRead = this.stream.byteIndex return this.hasMore() }, someBytesLeft : function(limit) { if (limit) { return limit - (this.stream.byteIndex - this.bytesRead) } else { return 1 } } }) exports.SwfReader = SwfReader })
import React from 'react'; import TrialItem from '../../../containers/TimelineNodeOrganizer/SortableTreeMenu/TrialItemContainer'; import TimelineItem from '../../../containers/TimelineNodeOrganizer/SortableTreeMenu/TimelineItemContainer'; class TreeNode extends React.Component { render() { const { id, children, } = this.props; return ( <div className="Tree-Node"> {(this.props.isTimeline) ? (<TimelineItem id={id} children={children} openTimelineEditorCallback={this.props.openTimelineEditorCallback} closeTimelineEditorCallback={this.props.closeTimelineEditorCallback} />) : (<TrialItem id={id} openTimelineEditorCallback={this.props.openTimelineEditorCallback} closeTimelineEditorCallback={this.props.closeTimelineEditorCallback} />)} </div> ) } } export default TreeNode;
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var mongo = require('mongodb'); var monk = require('monk'); var db = monk('localhost:27017/filmList'); var routes = require('./routes/index'); var watchedlist = require('./routes/watchedlist'); var wantlist = require('./routes/wantlist'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(function(req, res, next) { req.db = db; next(); }); app.use('/', routes); var MongoClient = require('mongodb').MongoClient; var assert = require('assert'); var mongoUrl = 'mongodb://localhost:27017/test'; MongoClient.connect(mongoUrl, function(err, db) { // 测试数据库连接 assert.equal(null, err); console.log("Connected correctly to server."); db.close(); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
'use strict'; // Declare app level module which depends on filters, and services angular.module('kidClock', [ //'ngRoute', '$strap.directives', 'kidClock.filters', 'kidClock.services', 'kidClock.directives', 'kidClock.controllers' ]). config(['$routeProvider', function($routeProvider) { $routeProvider.when('/clock', {templateUrl: 'partials/clock.html', controller: 'DisplayCtrl'}); $routeProvider.when('/config', {templateUrl: 'partials/config.html', controller: 'ConfigCtrl'}); $routeProvider.otherwise({redirectTo: '/clock'}); }]);
// - $.ui.msg $.ui.msg(Function func) // - $.ui.msg $.ui.msg(Function func, $.dom dom) RAON.ui.msg = RAON.toFnStClass(function(func, dom) { var attr = RAON.ui.msg._DAT; var body = RAON.ui.msg._DAT_BODY; if (arguments.length == 0) { var el = RAON.findsAttr(attr); for (var i = 0 ; i < el.length ; i++) { var e = el.get(i); var obj = e.attr(attr).trim().eval(); obj.dom = e; obj.body = e.findsAttr(body); if (obj.body.length == 0) { obj.body = e; } e.hide(); } } else { var g = this.get(); g.func = func.bind(g); if (arguments.length == 2) { g.dom = dom; g.body = dom.findsAttr(body); if (g.body.length == 0) { g.body = dom; } dom.hide(); } return g; } }, { _DAT : 'raon-msg', _DAT_BODY : 'raon-msg-body' }, { _RAON_TYPEOF : '$.ui.msg', dom : null, // dom body : null, // body func : function(code) {}, call : function(code) { if (this.dom != null) { this.func(code); } }, text : function(text) { if (this.show()) { this.body.text(text); } }, html : function(html) { if (this.show()) { this.body.html(html); } }, show : function() { if (this.dom != null) { this.dom.show(); return true; } return false; }, hide : function() { if (this.dom != null) { this.dom.hide(); return true; } return false; } });
// Define a koa server to host the universal web app import path from 'path'; import koa from 'koa'; import serveStatic from 'koa-static'; import favicon from 'koa-favi'; import jade from 'koa-jade'; import React from 'react'; import resolveAssetPath from './resolveAssetPath'; import HelloWorld from '../app/components/HelloWorld'; export default (config, callback) => { global.__CLIENT__ = false; global.__SERVER__ = true; global.__DEV__ = config.env !== 'production'; const app = koa(); // use default node favicon app.use(favicon()); // serve static assets generated by the build process app.use(serveStatic(path.resolve(__dirname, '../dist'))); // register jade middleware app.use(jade.middleware({ viewPath: __dirname + '/views', debug: false, pretty: false, compileDebug: false, noCache: true })); app.use(function *() { // replace jade vars here const locals = { jsAssets: resolveAssetPath('app','js'), body: React.renderToString( <HelloWorld location="server" /> ) }; this.render('index', locals) }); return app.listen(config.port, () => callback(config, app)); }
import clientEnv from '../../client-env'; function renderer(view, locals) { return function* () { let webpackAssets = {}; try { webpackAssets = require('../../webpack-assets.json'); } catch (err) { console.log('webpack-assets.json is not ready.'); } const newLocals = { ...webpackAssets, ...locals, env: clientEnv, }; yield this.render(view, newLocals); }; } export default renderer;
// All spec files must be required by `./spec/unit/spec.js`. // You are free to add a directory-importing Browserify transform, but // Watchify may be unable to detect spec file changes. Also, gulp.watch does // not watch for new or deleted files. import './example_spec';
export default function (params = {}) { //let count, // currentRowIndex, // currentCellIndex, // table = table, // page = parseResult.pages[currentPageIndex], // body = table ? this._getTableBody(table) : null, // row = body ? body[body.children.length - 1] : null; // //row = row || this._initRow(); // //if (!table) { // table = this._initTable({ // row: row, // parseParams, // parentElementsList: page.children, // parentElementsIndex: currentElementIndex, // data: currentElementParent // }); // body = this._getTableBody(table); //} // //currentElementParent.css = copy( // {}, // currentElementParent.css, // styles.cells.css //); // //currentElementParent.style = copy( // {}, // currentElementParent.style, // styles.cells.style //); // //row.children.push(currentElementParent); // //count = body.children.length; //currentRowIndex = count ? count - 1 : 0; //count = row.children.length; //currentCellIndex = count ? count - 1 : 0; // //if ( // table.options.cellsWidth[currentRowIndex] && // table.options.cellsWidth[currentRowIndex][currentCellIndex] //) { // currentElementParent.style.width = // currentElementParent.style.width || // table.options.cellsWidth[currentRowIndex][currentCellIndex]; //} //currentElementParent = { // options: {}, // css: {}, // style: {}, // children: [] //}; //currentElement = { // options: {}, // css: {}, // style: {}, // properties: { // textContent: '' // } //}; return params; }
angular.module('app') .factory('MessageService', ['$rootScope', '$pubnubChannel','currentUser', function MessageServiceFactory($rootScope, $pubnubChannel, currentUser) { // We create an extended $pubnubChannel channel object that add a additionnal sendScore method // that publish a score with the name of the player preloaded. var Channel = $pubnubChannel.$extend({ sendMessage: function(messageContent) { return this.$publish({ uuid: (Date.now() + currentUser.get().id.toString()), content: messageContent, sender: { uuid: currentUser.get().id.toString(), login: currentUser.get().login }, date: Date.now() }) } }); return Channel('messages-channel-blog5', {autoload: 20, presence: true}); }]);
var scene = document.getElementById('animation-mer'); var parallax = new Parallax(scene);
import * as assert2 from "./assert2.js"; export function find(a, fn) { for (let i = 0; i < a.length; i++) { const item = a[i]; if (fn(item)) return item; } return null; } export function merge() { const tar = arguments[0]; const fn = arguments[arguments.length - 1]; for (let a = 1; a < arguments.length - 1; a++) { const src = arguments[a]; sloop: for (let s = 0; s < src.length; s++) { for (let t = 0; t < tar.length; t++) { if (fn(tar[t], src[s])) { tar[t] = src[s]; continue sloop; } } tar.push(src[s]); } } }
const express = require('express'); const path = require('path'); const bodyParser = require('body-parser'); const cors = require('cors'); const passport = require('passport'); const mongoose = require('mongoose'); const config = require('./config/database'); //Connect to database mongoose.connect(config.database, { useMongoClient: true, }); //On connection mongoose.connection.on('connected', () => { console.log('connected to database' + config.database); }) //Error connection mongoose.connection.on('error', (err) => { console.log('database error' + err); }) const app = express(); const users = require('./routes/users'); //PORT Number const port = process.env.PORT || 8080; //CORS Middleware app.use(cors()); //Static Folder app.use(express.static(path.join(__dirname, 'public'))); //Body Parser Middleware app.use(bodyParser.json()); //passport Middleware app.use(passport.initialize()); app.use(passport.session()); require('./config/passport')(passport); app.use('/users', users); //Index Route app.get('/', (req, res) => { res.send('123'); }) app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'public/index.html')); }) //Start Serve app.listen(port, () => { console.log('listen on port ' + port); })
(function() { var tests = { testIterArray: function(test) { test.expect(5); var iter = sloth.iterArray([1, 2, 3, 4]); test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(4, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testIterString: function(test) { test.expect(5); var iter = sloth.iterString("test"); test.strictEqual("t", iter()); test.strictEqual("e", iter()); test.strictEqual("s", iter()); test.strictEqual("t", iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testIterObject: function(test) { test.expect(5); var iter = sloth.iterObject({a: 1, b: 2, c: 3, d: 4}); test.deepEqual(["a", 1], iter()); test.deepEqual(["b", 2], iter()); test.deepEqual(["c", 3], iter()); test.deepEqual(["d", 4], iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testIterGenerator: function(test) { if(typeof StopIteration === "undefined") { test.expect(1); test.ok(true, "browser does not support generators"); test.done(); } else { test.expect(4); eval("var gen = function() { for(;;) yield 1; };"); var iter = sloth.iterNextable(gen()); test.strictEqual(1, iter()); test.strictEqual(1, iter()); test.strictEqual(1, iter()); test.strictEqual(1, iter()); test.done(); } }, testJS17Iteration: function(test) { if(typeof StopIteration === "undefined") { test.expect(1); test.ok(true, "browser does not support JavaScript 1.7 iteration"); test.done(); } else { test.expect(4); var i = 1; for(var v in new sloth.Slothified(sloth.iterArray([1, 2, 3, 4]))) { test.strictEqual(i++, v); } test.done(); } }, testIfyFunction: function(test) { test.expect(4); var iter = sloth.ify(function() { return 1; }).next; test.strictEqual(1, iter()); test.strictEqual(1, iter()); test.strictEqual(1, iter()); test.strictEqual(1, iter()); test.done(); }, testIfyArray: function(test) { test.expect(5); var iter = sloth.ify([1, 2, 3, 4]).next; test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(4, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testIfyString: function(test) { test.expect(5); var iter = sloth.ify("test").next; test.strictEqual("t", iter()); test.strictEqual("e", iter()); test.strictEqual("s", iter()); test.strictEqual("t", iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testIfyObject: function(test) { test.expect(5); var iter = sloth.ify({a: 1, b: 2, c: 3, d: 4}).next; test.deepEqual(["a", 1], iter()); test.deepEqual(["b", 2], iter()); test.deepEqual(["c", 3], iter()); test.deepEqual(["d", 4], iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testIfySlothified: function(test) { test.expect(1); var iter = sloth.ify([1, 2, 3, 4]); test.strictEqual(sloth.ify(iter), iter); test.done(); }, testIfyGenerator: function(test) { if(typeof StopIteration === "undefined") { test.expect(1); test.ok(true, "browser does not support generators"); test.done(); } else { test.expect(4); eval("var gen = function() { for(;;) yield 1; };"); var iter = sloth.ify(gen()).next; test.strictEqual(1, iter()); test.strictEqual(1, iter()); test.strictEqual(1, iter()); test.strictEqual(1, iter()); test.done(); } }, testCmpNumber: function(test) { test.expect(3); test.ok(sloth.cmp(2, 10) < 0); test.ok(sloth.cmp(10, 2) > 0); test.ok(sloth.cmp(2, 2) == 0); test.done(); }, testRange: function(test) { test.expect(3); var iter = sloth.range(1, 5, 2).next; test.strictEqual(1, iter()); test.strictEqual(3, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testRangeDefaultStep: function(test) { test.expect(5); var iter = sloth.range(1, 5).next; test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(4, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testRangeLeft: function(test) { test.expect(5); var iter = sloth.range(4).next; test.strictEqual(0, iter()); test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testRangeInfinite: function(test) { test.expect(4); var iter = sloth.range(0, null).next; test.strictEqual(0, iter()); test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.done(); }, testRepeatFinite: function(test) { test.expect(5); var iter = sloth.repeat(0, 4).next; test.strictEqual(0, iter()); test.strictEqual(0, iter()); test.strictEqual(0, iter()); test.strictEqual(0, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testRepeatInfinite: function(test) { test.expect(4); var iter = sloth.repeat(0).next; test.strictEqual(0, iter()); test.strictEqual(0, iter()); test.strictEqual(0, iter()); test.strictEqual(0, iter()); test.done(); }, testCmpString: function(test) { test.expect(3); test.ok(sloth.cmp("t", "te") < 0); test.ok(sloth.cmp("te", "t") > 0); test.ok(sloth.cmp("t", "t") == 0); test.done(); }, testMap: function(test) { test.expect(5); var iter = sloth.ify([1, 2, 3, 4]) .map(function(x) { return x + 1; }) .next; test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(4, iter()); test.strictEqual(5, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testMapInfinite: function(test) { test.expect(4); var iter = sloth.ify(function() { return 1; }) .map(function(x) { return x + 1; }) .next; test.strictEqual(2, iter()); test.strictEqual(2, iter()); test.strictEqual(2, iter()); test.strictEqual(2, iter()); test.done(); }, testFilter: function(test) { test.expect(3); var iter = sloth.ify([1, 2, 3, 4]) .filter(function(x) { return x > 2 }) .next; test.strictEqual(3, iter()); test.strictEqual(4, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testFilterInfinite: function(test) { test.expect(2); var iter = sloth.ify((function() { var n = 0; return function() { return n++; }; })()).filter(function(x) { return x > 2 }).next; test.strictEqual(3, iter()); test.strictEqual(4, iter()); test.done(); }, testEach: function(test) { test.expect(8); var i = 0; sloth.ify([1, 2, 3, 4]).each(function(x, j) { test.strictEqual(i, j); test.strictEqual(++i, x); }); test.done(); }, testForce: function(test) { test.expect(1); test.deepEqual([1, 2, 3, 4], sloth.ify([1, 2, 3, 4]).force()); test.done(); }, testEnumerate: function(test) { test.expect(5); var iter = sloth.ify([1, 2, 3, 4]) .enumerate() .next; test.deepEqual([0, 1], iter()); test.deepEqual([1, 2], iter()); test.deepEqual([2, 3], iter()); test.deepEqual([3, 4], iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testReverse: function(test) { test.expect(5); var iter = sloth.ify([1, 2, 3, 4]) .reverse() .next; test.strictEqual(4, iter()); test.strictEqual(3, iter()); test.strictEqual(2, iter()); test.strictEqual(1, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testSort: function(test) { test.expect(5); var iter = sloth.ify([1, 2, 10, 3]) .sort() .next; test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(10, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testSortCompareFunction: function(test) { test.expect(5); var iter = sloth.ify([1, 2, 3, 4]) .sort(function(a, b) { return b - a; }) .next; test.strictEqual(4, iter()); test.strictEqual(3, iter()); test.strictEqual(2, iter()); test.strictEqual(1, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testGroup: function(test) { test.expect(1); var groups = sloth.ify([9, 2, 3, 2, 4, 1, 1, 2]) .group() .map(function(x) { return x.force(); } ) .force(); test.deepEqual([[9], [2, 2, 2], [3], [4], [1, 1]], groups); test.done(); }, testGroupAlternativeForce: function(test) { test.expect(1); var groups = sloth.ify([9, 2, 3, 2, 4, 1, 1, 2]).group().force(); for(var i = 0; i < groups.length; ++i) { groups[i] = groups[i].force(); } test.deepEqual([[9], [2, 2, 2], [3], [4], [1, 1]], groups); test.done(); }, testGroupPredicate: function(test) { test.expect(1); var groups = sloth.ify([{n:9}, {n:2}, {n:3}, {n:2}, {n:4}, {n:1}, {n:1}, {n:2}]) .group(function(x, y) { return x.n == y.n; }) .map(function(x) { return x.force(); } ) .force(); test.deepEqual([[{n:9}], [{n:2}, {n:2}, {n:2}], [{n:3}], [{n:4}], [{n:1}, {n:1}]], groups); test.done(); }, testFoldl: function(test) { test.expect(1); test.strictEqual(-8, sloth.ify([1, 2, 3, 4]) .foldl(function(acc, x) { return acc - x; }) ); test.done(); }, testFoldlWithAcc: function(test) { test.expect(1); test.strictEqual(0, sloth.ify([1, 2, 3, 4]) .foldl(function(acc, x) { return acc - x; }, 10) ); test.done(); }, testFoldlWithSingle: function(test) { test.expect(1); test.strictEqual(1, sloth.ify([1]) .foldl(function(acc, x) { return acc - x; }) ); test.done(); }, testFoldlWithSingleAcc: function(test) { test.expect(1); test.strictEqual(9, sloth.ify([1]) .foldl(function(acc, x) { return acc - x; }, 10) ); test.done(); }, testFoldr: function(test) { test.expect(1); test.strictEqual(-2, sloth.ify([1, 2, 3, 4]) .foldr(function(x, acc) { return acc - x; }) ); test.done(); }, testFoldrWithAcc: function(test) { test.expect(1); test.strictEqual(0, sloth.ify([1, 2, 3, 4]) .foldr(function(x, acc) { return acc - x; }, 10) ); test.done(); }, testFoldrWithSingle: function(test) { test.expect(1); test.strictEqual(1, sloth.ify([1]) .foldr(function(x, acc) { return acc - x; }) ); test.done(); }, testFoldrWithSingleAcc: function(test) { test.expect(1); test.strictEqual(9, sloth.ify([1]) .foldr(function(x, acc) { return acc - x; }, 10) ); test.done(); }, testAll: function(test) { test.expect(1); test.strictEqual(true, sloth.ify([true, true, true, true]) .all() ); test.done(); }, testAllPredicated: function(test) { test.expect(1); test.strictEqual(true, sloth.ify([1, 2, 3, 4]) .any(function(x) { return x >= 2; }) ); test.done(); }, testAllFalse: function(test) { test.expect(1); test.strictEqual(false, sloth.ify([true, false, true, true]) .all() ); test.done(); }, testAllInfinite: function(test) { test.expect(1); test.strictEqual(false, sloth.ify(function() { return false; }) .all() ); test.done(); }, testAny: function(test) { test.expect(1); test.strictEqual(true, sloth.ify([true, false, false, false]) .any() ); test.done(); }, testAnyFalse: function(test) { test.expect(1); test.strictEqual(false, sloth.ify([false, false, false, false]) .any() ); test.done(); }, testAnyPredicated: function(test) { test.expect(1); test.strictEqual(true, sloth.ify([1, 2, 3, 4]) .all(function(x) { return x >= 1; }) ); test.done(); }, testAnyInfinite: function(test) { test.expect(1); test.strictEqual(true, sloth.ify(function() { return true; }) .any() ); test.done(); }, testMax: function(test) { test.expect(1); test.strictEqual(4, sloth.ify([1, 2, 4, 3]) .max() ); test.done(); }, testMaxComparator: function(test) { test.expect(1); test.strictEqual(1, sloth.ify([1, 2, 4, 3]) .max(function(a, b) { return b - a; }) ); test.done(); }, testMin: function(test) { test.expect(1); test.strictEqual(1, sloth.ify([1, 2, 4, 3]) .min() ); test.done(); }, testMinComparator: function(test) { test.expect(1); test.strictEqual(4, sloth.ify([1, 2, 4, 3]) .min(function(a, b) { return b - a; }) ); test.done(); }, testTake: function(test) { test.expect(5); var iter = sloth.ify((function() { var n = 1; return function() { return n++; }; })()) .take(4) .next; test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(4, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testDrop: function(test) { test.expect(4); var iter = sloth.ify((function() { var n = 1; return function() { return n++; }; })()) .drop(4) .next; test.strictEqual(5, iter()); test.strictEqual(6, iter()); test.strictEqual(7, iter()); test.strictEqual(8, iter()); test.done(); }, testTakeWhile: function(test) { test.expect(5); var iter = sloth.ify([1, 2, 3, 4, 5, 1]) .takeWhile(function(x) { return x < 5 }) .next; test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(4, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testDropWhile: function(test) { test.expect(5); var iter = sloth.ify([4, 5, 6, 7, 4]) .dropWhile(function(x) { return x < 5 }) .next; test.strictEqual(5, iter()); test.strictEqual(6, iter()); test.strictEqual(7, iter()); test.strictEqual(4, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testCycle: function(test) { test.expect(4); var iter = sloth.ify([1, 2]).cycle().next; test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.done(); }, testConcat: function(test) { test.expect(5); var iter = sloth.ify([1, 2]) .concat([3, 4]).next; test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(4, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testProduct: function(test) { test.expect(5); var iter = sloth.ify([1, 2]) .product([3, 4]).next; test.deepEqual([1, 3], iter()); test.deepEqual([1, 4], iter()); test.deepEqual([2, 3], iter()); test.deepEqual([2, 4], iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testProduct3: function(test) { test.expect(9); var iter = sloth.ify([1, 2]) .product([3, 4], [5, 6]).next; test.deepEqual([1, 3, 5], iter()); test.deepEqual([1, 3, 6], iter()); test.deepEqual([1, 4, 5], iter()); test.deepEqual([1, 4, 6], iter()); test.deepEqual([2, 3, 5], iter()); test.deepEqual([2, 3, 6], iter()); test.deepEqual([2, 4, 5], iter()); test.deepEqual([2, 4, 6], iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testTee: function(test) { test.expect(10); var iters = sloth.ify([1, 2, 3, 4]).tee(); var iter = iters[0].next; test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(4, iter()); try { iter() } catch(e) { test.strictEqual(sloth.StopIteration, e); } var iter = iters[1].next; test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(4, iter()); try { iter() } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testTee3: function(test) { test.expect(15); var iters = sloth.ify([1, 2, 3, 4]).tee(3); var iter = iters[0].next; test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(4, iter()); try { iter() } catch(e) { test.strictEqual(sloth.StopIteration, e); } var iter = iters[1].next; test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(4, iter()); try { iter() } catch(e) { test.strictEqual(sloth.StopIteration, e); } var iter = iters[2].next; test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(4, iter()); try { iter() } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testZip: function(test) { test.expect(5); var iter = sloth.ify([1, 2, 3, 4]) .zip([1, 2, 3, 4, 5], [2, 3, 4, 5, 6]) .next; test.deepEqual([1, 1, 2], iter()); test.deepEqual([2, 2, 3], iter()); test.deepEqual([3, 3, 4], iter()); test.deepEqual([4, 4, 5], iter()); try { iter() } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testNub: function(test) { test.expect(6); var iter = sloth.ify([0, 1, 1, 2, 3, 4, 4, 4]) .nub() .next; test.strictEqual(0, iter()); test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(4, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testNubPredicate: function(test) { test.expect(3); var iter = sloth.ify(["cat", "coffee", "dog"]) .nub(function(x, y) { return x.charAt(0) == y.charAt(0); }) .next; test.strictEqual("cat", iter()); test.strictEqual("dog", iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testUnion: function(test) { test.expect(8); var iter = sloth.ify([1, 1, 2, 3, 4, 4, 4]) .union([3, 3, 4, 5, 6, 7, 7]) .next; test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(3, iter()); test.strictEqual(4, iter()); test.strictEqual(5, iter()); test.strictEqual(6, iter()); test.strictEqual(7, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testUnionPredicate: function(test) { test.expect(4); var iter = sloth.ify(["cat", "coffee", "dog"]) .union(["dish", "rabbit", "rock"], function(x, y) { return x.charAt(0) == y.charAt(0); }) .next; test.strictEqual("cat", iter()); test.strictEqual("dog", iter()); test.strictEqual("rabbit", iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testIntersect: function(test) { test.expect(3); var iter = sloth.ify([0, 1, 1, 2, 3, 4, 4, 4]) .intersect([0, 3, 3, 5, 6, 7, 7]) .next; test.strictEqual(0, iter()); test.strictEqual(3, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testIntersectPredicate: function(test) { test.expect(2); var iter = sloth.ify(["cat", "coffee", "dog"]) .intersect(["dish", "rabbit", "rock"], function(x, y) { return x.charAt(0) == y.charAt(0); }) .next; test.strictEqual("dish", iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testDifference: function(test) { test.expect(5); var iter = sloth.ify([0, 1, 1, 2, 3, 4, 4, 4]) .difference([3, 3, 4, 5, 6, 7, 7]) .next; test.strictEqual(0, iter()); test.strictEqual(1, iter()); test.strictEqual(1, iter()); test.strictEqual(2, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testDifferencePredicate: function(test) { test.expect(3); var iter = sloth.ify(["cat", "coffee", "dog"]) .difference(["dish", "rabbit", "rock"], function(x, y) { return x.charAt(0) == y.charAt(0); }) .next; test.strictEqual("cat", iter()); test.strictEqual("coffee", iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testSymmetricDifference: function(test) { test.expect(8); var iter = sloth.ify([1, 1, 2, 3, 4, 4, 4]) .symmetricDifference([3, 3, 4, 5, 6, 7, 7]) .next; test.strictEqual(1, iter()); test.strictEqual(1, iter()); test.strictEqual(2, iter()); test.strictEqual(5, iter()); test.strictEqual(6, iter()); test.strictEqual(7, iter()); test.strictEqual(7, iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); }, testSymmetricDifferencePredicate: function(test) { test.expect(5); var iter = sloth.ify(["cat", "coffee", "dog"]) .symmetricDifference(["dish", "rabbit", "rock"], function(x, y) { return x.charAt(0) == y.charAt(0); }) .next; test.strictEqual("cat", iter()); test.strictEqual("coffee", iter()); test.strictEqual("rabbit", iter()); test.strictEqual("rock", iter()); try { iter(); } catch(e) { test.strictEqual(sloth.StopIteration, e); } test.done(); } }; var sloth; if(typeof module !== "undefined" && module.exports) { sloth = require(__dirname + '/../sloth.js'); module.exports = tests; } if(typeof window !== "undefined") { sloth = window.sloth; window.tests = tests; } })()
/** * AuthenticateModule - Module for authenticating users through their accesstoken * * */ var User = require('../models/user.model.js'); var exports = module.exports; exports.isValid = function(accessToken) { var query = User.findOne({accesstoken: accessToken}); return query.exec(); };
import ApplicationSerializer from 'ember-fhir-adapter/serializers/application'; var ClinicalImpressionInvestigationsComponent = ApplicationSerializer.extend({ attrs:{ code : {embedded: 'always'}, item : {embedded: 'always'} } }); export default ClinicalImpressionInvestigationsComponent;
module.exports = function() { //set paths this .path('{{name}}' , this.path('package') + '/{{name}}') .path('{{name}}/action' , this.path('package') + '/{{name}}/action') .path('{{name}}/event' , this.path('package') + '/{{name}}/event') .path('{{name}}/template' , this.path('package') + '/{{name}}/template'); //load the factory require(this.path('{{name}}') + '/factory.js', function(factory) { //add it to the global factory this.package('{{name}}', factory); //get event path var events = this.Folder(this.package('{{name}}').path('event')); if(!events.isFolder()) { this.trigger('{{name}}-init'); return; } //get files in the event folder events.getFiles(null, false, function(error, files) { //loop through files for(var events = [], callbacks = [], i = 0; i < files.length; i++) { //accept only js if(files[i].getExtension() !== 'js') { continue; } events.push(files[i].getBase()); callbacks.push(files[i].path); } require(callbacks, function() { var callbacks = Array.prototype.slice.apply(arguments); //loop through events for(var i = 0; i < callbacks.length; i++) { //only listen if it is a callback if(typeof callbacks[i] !== 'function') { continue; } //now listen this.on(events[i], callbacks[i]); } this.trigger('{{name}}-init'); }.bind(this)); }.bind(this)); }.bind(this)); return '{{name}}-init'; };
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var common_1 = require("@angular/common"); var datagriddemo_1 = require("./datagriddemo"); var datagriddemo_routing_module_1 = require("./datagriddemo-routing.module"); var datagrid_1 = require("../../../components/datagrid/datagrid"); var panel_1 = require("../../../components/panel/panel"); var dialog_1 = require("../../../components/dialog/dialog"); var tabview_1 = require("../../../components/tabview/tabview"); var codehighlighter_1 = require("../../../components/codehighlighter/codehighlighter"); var DataGridDemoModule = (function () { function DataGridDemoModule() { } return DataGridDemoModule; }()); DataGridDemoModule = __decorate([ core_1.NgModule({ imports: [ common_1.CommonModule, datagriddemo_routing_module_1.DataGridDemoRoutingModule, datagrid_1.DataGridModule, panel_1.PanelModule, dialog_1.DialogModule, tabview_1.TabViewModule, codehighlighter_1.CodeHighlighterModule ], declarations: [ datagriddemo_1.DataGridDemo ] }) ], DataGridDemoModule); exports.DataGridDemoModule = DataGridDemoModule; //# sourceMappingURL=datagriddemo.module.js.map
const assert = require('chai').assert, expect = require('chai').expect, five = require('johnny-five'), placeholder = require('../lib/placeholder-io');; describe('ping', function () { var board; before(done => { board = new five.Board({ io: new placeholder() }).on('ready', done); }); describe('Reading', function () { describe('pingRead(settings, handler)', function () { it('TODO') }); }); });
#!/usr/bin/env node // jshint asi:true /** * Should be called via npm run * * Ensures that all slides exists */ 'use strict'; var _ = require('underscore/underscore') var exec = require('child_process').exec var slides = _.flatten(require(process.cwd() + '/slides/list.json')) slides.forEach(function(f) { exec('touch slides/' + f) })