text
stringlengths
2
6.14k
var MyToken = artifacts.require("./MyToken.sol"); contract('MyToken', function(accounts) { it("should put 12000 MyToken in the first account", function() { return MyToken.deployed().then(function(instance) { return instance.balanceOf(accounts[0]); }).then(function(balance) { assert.equal(balance.valueOf(), 12000, "12000 wasn't in the first account"); }); }); });
/** * Copyright 2020 Google LLC * * 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. */ import dts from 'rollup-plugin-dts'; import typescript from 'rollup-plugin-typescript2'; import rollupJson from '@rollup/plugin-json'; import { terser } from 'rollup-plugin-terser'; export default [ { input: 'src/button-react/index.ts', output: [ { file: 'src/button-react/dist/index.js', format: 'es', }, { file: 'src/button-react/dist/index.min.js', format: 'es', plugins: [terser()], }, { file: 'src/button-react/dist/index.umd.js', format: 'umd', name: 'GooglePayButton', globals: { react: 'React', }, }, { file: 'src/button-react/dist/index.umd.min.js', format: 'umd', name: 'GooglePayButton', globals: { react: 'React', }, plugins: [terser()], }, ], external: ['react'], plugins: [rollupJson(), typescript()], }, { input: 'src/button-react/index.ts', output: [ { file: 'src/button-react/dist/index.es5.min.js', format: 'umd', name: 'GooglePayButton', globals: { react: 'React', }, plugins: [terser()], }, ], external: ['react'], plugins: [ rollupJson(), typescript({ tsconfigOverride: { compilerOptions: { target: 'es5', }, }, }), ], }, { input: 'src/button-react/index.ts', output: { file: 'src/button-react/dist/index.d.ts', format: 'es', }, plugins: [dts()], }, { input: 'src/button-element/index.ts', output: [ { file: 'src/button-element/dist/index.js', format: 'es', name: 'GooglePayButton', }, { file: 'src/button-element/dist/index.min.js', format: 'es', name: 'GooglePayButton', plugins: [terser()], }, { file: 'src/button-element/dist/index.umd.js', format: 'umd', name: 'GooglePayButton', }, { file: 'src/button-element/dist/index.umd.min.js', format: 'umd', name: 'GooglePayButton', plugins: [terser()], }, ], plugins: [rollupJson(), typescript()], }, { input: 'src/button-element/index.ts', output: [ { file: 'src/button-element/dist/index.es5.min.js', format: 'umd', name: 'GooglePayButton', plugins: [terser()], }, ], plugins: [ rollupJson(), typescript({ tsconfigOverride: { compilerOptions: { target: 'es5', }, }, }), ], }, { input: 'src/button-element/index.ts', output: { file: 'src/button-element/dist/index.d.ts', format: 'es', }, plugins: [dts()], }, ];
function get_audit_targets() { $.ajax({ type: 'POST', url: '/audit_targets', success: function(data, status, request){ var ul = $("#targets") for(i = 0; i < data.length; i++){ var target = document.createElement("li"); target.appendChild(document.createTextNode(data[i])) ul.appendChild(target) } }, error: function(){ alert('things done broke') } }) }
function __processArg(obj, key) { var arg = null; if (obj) { arg = obj[key] || null; delete obj[key]; } return arg; } function Controller() { function openClickedSettings(e) { if ("FTR" == e.source.window) { var isFTR = Titanium.App.Properties.getObject("FTR"); Titanium.App.Properties.setObject("FTR", !isFTR); alert("FTR will start after restarting the app."); return; } var selectedSettingWin; if (-1 != e.source.window.search("http")) selectedSettingWin = Alloy.createController("webViewWin", { url: e.source.window }).getView(); else { var windowUrl = "Settings/" + e.source.window; selectedSettingWin = Alloy.createController(windowUrl).getView(); } if (-1 != e.source.window.search("EditProfile") && true) { tempNavWin.navBarHidden = true; tempRootWin.navBarHidden = true; } Alloy.Globals.openNavigationWindow(selectedSettingWin, true); $.win.fireEvent("close"); } require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "settingsWin"; if (arguments[0]) { { __processArg(arguments[0], "__parentSymbol"); } { __processArg(arguments[0], "$model"); } { __processArg(arguments[0], "__itemTemplate"); } } var $ = this; var exports = {}; var __defers = {}; $.__views.win = Ti.UI.createWindow({ backgroundColor: "white", id: "win", title: "Settings" }); $.__views.win && $.addTopLevelView($.__views.win); $.__views.__alloyId23 = Ti.UI.createLabel({ font: { fontSize: "30", fontWeight: "bold" }, color: "#2279bc", height: "10%", top: "8%", text: "Settings", id: "__alloyId23" }); $.__views.win.add($.__views.__alloyId23); var __alloyId25 = []; $.__views.__alloyId26 = Ti.UI.createTableViewRow({ window: "EditProfile/editProfileIndex", id: "__alloyId26" }); __alloyId25.push($.__views.__alloyId26); $.__views.__alloyId27 = Ti.UI.createLabel({ font: { fontSize: "20" }, color: "black", height: "60", text: "My Profile", window: "EditProfile/editProfileIndex", id: "__alloyId27" }); $.__views.__alloyId26.add($.__views.__alloyId27); $.__views.__alloyId28 = Ti.UI.createTableViewRow({ window: "http://www.bofffme.com", id: "__alloyId28" }); __alloyId25.push($.__views.__alloyId28); $.__views.__alloyId29 = Ti.UI.createLabel({ font: { fontSize: "20" }, color: "black", height: "60", text: "About", window: "http://www.bofffme.com", id: "__alloyId29" }); $.__views.__alloyId28.add($.__views.__alloyId29); $.__views.__alloyId30 = Ti.UI.createTableViewRow({ window: "http://www.google.com", id: "__alloyId30" }); __alloyId25.push($.__views.__alloyId30); $.__views.__alloyId31 = Ti.UI.createLabel({ font: { fontSize: "20" }, color: "black", height: "60", text: "FAQ", window: "http://www.google.com", id: "__alloyId31" }); $.__views.__alloyId30.add($.__views.__alloyId31); $.__views.__alloyId32 = Ti.UI.createTableViewRow({ window: "tutorialWin", id: "__alloyId32" }); __alloyId25.push($.__views.__alloyId32); $.__views.__alloyId33 = Ti.UI.createLabel({ font: { fontSize: "20" }, color: "black", height: "60", text: "Video Tutorial", window: "tutorialWin", id: "__alloyId33" }); $.__views.__alloyId32.add($.__views.__alloyId33); $.__views.__alloyId34 = Ti.UI.createTableViewRow({ window: "insertBofffWin", id: "__alloyId34" }); __alloyId25.push($.__views.__alloyId34); $.__views.__alloyId35 = Ti.UI.createLabel({ font: { fontSize: "20" }, color: "black", height: "60", text: "Add Bofff Contact (DEBUG)", window: "insertBofffWin", id: "__alloyId35" }); $.__views.__alloyId34.add($.__views.__alloyId35); $.__views.__alloyId36 = Ti.UI.createTableViewRow({ window: "changeUserPinWin", id: "__alloyId36" }); __alloyId25.push($.__views.__alloyId36); $.__views.__alloyId37 = Ti.UI.createLabel({ font: { fontSize: "20" }, color: "black", height: "60", text: "Change User Pin (DEBUG)", window: "changeUserPinWin", id: "__alloyId37" }); $.__views.__alloyId36.add($.__views.__alloyId37); $.__views.__alloyId38 = Ti.UI.createTableViewRow({ window: "FTR", id: "__alloyId38" }); __alloyId25.push($.__views.__alloyId38); $.__views.__alloyId39 = Ti.UI.createLabel({ font: { fontSize: "20" }, color: "black", height: "60", text: "Start FTR (DEBUG)", window: "FTR", id: "__alloyId39" }); $.__views.__alloyId38.add($.__views.__alloyId39); $.__views.__alloyId24 = Ti.UI.createTableView({ top: "23%", rowHeight: 60, height: Ti.UI.SIZE, data: __alloyId25, id: "__alloyId24" }); $.__views.win.add($.__views.__alloyId24); openClickedSettings ? $.__views.__alloyId24.addEventListener("click", openClickedSettings) : __defers["$.__views.__alloyId24!click!openClickedSettings"] = true; exports.destroy = function() {}; _.extend($, $.__views); __defers["$.__views.__alloyId24!click!openClickedSettings"] && $.__views.__alloyId24.addEventListener("click", openClickedSettings); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;
(function(){var baseCallback = require('../internal/baseCallback'), binaryIndex = require('../internal/binaryIndex'), binaryIndexBy = require('../internal/binaryIndexBy'); /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function|Object|string} [iteratee=_.identity] The function invoked * per iteration. If a property name or object is provided it is used to * create a "_.property" or "_.matches" style callback respectively. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 4, 5, 5, 6, 6], 5); * // => 4 */ function sortedLastIndex(array, value, iteratee, thisArg) { return iteratee == null ? binaryIndex(array, value, true) : binaryIndexBy(array, value, baseCallback(iteratee, thisArg, 1), true); } module.exports = sortedLastIndex; })();
(function() { function LandingCtrl() { this.heroTitle = "Turn Down For What!" } angular .module('blocJams') .controller('LandingCtrl', LandingCtrl); })();
sap.ui.define(["sap/ui/core/mvc/ControllerExtension"], function(ControllerExtension) { "use strict"; return ControllerExtension.extend("my.test.reuse.Extension", { metadata: { methods: { "myFinalMethod": {"public": true, "final": true}, "myPrivateMethod1": {"public": false, "final": true} } }, myFinalMethod: function() { return "I am final"; }, myPublicMethod: function() { return "myPublicMethodReuseExtension"; }, myPrivateMethod1: function() { }, _myPrivateMethod2: function() { }, onBeforeSomething: function() { }, override: { onInit: function() { window.assert.ok(this instanceof ControllerExtension, "onInit: Context is ControllerExtension 'Extension'"); window.assert.equal(this.getMetadata().getNamespace(), "my.test.reuse", "onInit: Context is correct ControllerExtension 'Extension'") }, onExit: function() { window.assert.ok(this instanceof ControllerExtension, "onExit: Context is ControllerExtension 'Extension'"); window.assert.equal(this.getMetadata().getNamespace(), "my.test.reuse", "onExit: Context is correct ControllerExtension 'Extension'") }, onBeforeRendering:function() { window.assert.ok(this instanceof ControllerExtension, "onBeforeRendering: Context is ControllerExtension 'Extension'"); window.assert.equal(this.getMetadata().getNamespace(), "my.test.reuse", "onBeforeRendering: Context is correct ControllerExtension 'Extension'") }, onAfterRendering: function() { window.assert.ok(this instanceof ControllerExtension, "onAfterRendering: Context is ControllerExtension 'Extension'"); window.assert.equal(this.getMetadata().getNamespace(), "my.test.reuse", "onAfterRendering: Context is correct ControllerExtension 'Extension'") }, myFinalMethod: function() { return "Final Methods could not be overidden by an extension"; } } }); });
/** * Created by desha on 10/4/2017. */ $(document).pjax('[data-pjax] a, a[data-pjax]', '#pjax-container') $.pjax.defaults.timeout = 6000; $('#pjax-container').on('pjax:start', function() { NProgress.start(); }); $('#pjax-container').on('pjax:end', function() { NProgress.done(); $('#pjax-container').fadeOut(0); $('#pjax-container').fadeIn(500); });
_collectionId = null; _testTables = {} $(document).ready(function(){ loadUrlParams(); initTabs(); initTestTables(); }); function initTestTables() { $.each($('.test-table'), function(){ createDataTable($(this).attr('id')); }); } function createDataTable(id) { _testTables[id] = $('#' + id).DataTable( { paging: true, lengtMenu : [10, 20, 50, 100], ordering: true, info: true, filter : true }); $('#' + id +' tbody').on('click', 'tr', function () { if ( $(this).hasClass('selected') ) { $(this).removeClass('selected'); } else { _brokenEventsTable.$('tr.selected').removeClass('selected'); $(this).addClass('selected'); } } ); } function initTabs(){ /*$('#collection_tabs a').click(function(a) { if(a && a.target && a.target.href) { document.location.href = a.target.href; } });*/ $('#collection_tabs li:eq(0)').addClass('active'); $('.tab-content .tab-pane:eq(0)').addClass('active'); } function loadUrlParams() { var match, pl = /\+/g, // Regex for replacing addition symbol with a space search = /([^&=]+)=?([^&]*)/g, decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }, query = window.location.search.substring(1); urlParams = {}; while (match = search.exec(query)) urlParams[decode(match[1])] = decode(match[2]); console.debug(urlParams); _collectionId = urlParams['c']; } function setCollection(elm) { var uid = $(elm).attr('id'); var c = $('#' + uid + ' option:selected').val(); console.debug('uid=' + uid); console.debug('collection=' + c); var url = document.location.href; if(url.indexOf('c=') == -1) { document.location.href = url + '?c=' + c; } else { document.location.href = url.substring(0, url.indexOf('c=')) + 'c=' + c; } } function gotoPage(page, extras='') { var url = document.location.protocol + '//' + document.location.host; url += '/'+page+'?c=' + _collectionId + extras; document.location.href = url; }
/* Copyright 2015, SAP SE 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. */ define([], function() { return sap.bi.framework.declareBundle({ "id" : "sap.lumira.sampleextension", "version" : "REPLACE_VERSION", "components" : [{ "id" : "sap.lumira.sampleextension", "provide" : "sap.bi.da.extension.client", "module" : "SampleExtension", "customProperties" : { "displayName" : "SAP Lumira Sample Extension", "description" : "for SAP Lumira Data Acquisition Framework" } }], "dependencies": ["sap.bi.da.extension.sdk.clientRequestService"] }); });
var class_r_e_view = [ [ "REView", "class_r_e_view.html#af9ffb885b5757a44966ea8b1f5d9697e", null ], [ "~REView", "class_r_e_view.html#ad4c5f387d0cc5a3cb6d3a22bd485b10a", null ], [ "addSubview", "class_r_e_view.html#a8bcceb614387eea9fea96dfdaaeaba82", null ], [ "alpha", "class_r_e_view.html#a2eafe4f47cd6d4d1b49c1fde0f43e424", null ], [ "animationsCount", "class_r_e_view.html#adb93d9512bd700cc6f480df3957d5b49", null ], [ "classNameKey", "class_r_e_view.html#ae341f7122890350ae3b4f2363afef9ba", null ], [ "color", "class_r_e_view.html#ae97198abada529bda40e9dd130865ef7", null ], [ "create", "class_r_e_view.html#af6f2fd3c00d3026eea5f9bb0f0847d44", null ], [ "createWithDeserializableDictionary", "class_r_e_view.html#a8738e68dd91f74fc90fcf36b7f8184e8", null ], [ "createWithFrame", "class_r_e_view.html#a7a441e027ba12d5c86601514f1215792", null ], [ "deleteObject", "class_r_e_view.html#a0817ee5ded0b4afc4fc37ebd5127b415", null ], [ "deserializeWithDictionary", "class_r_e_view.html#a6d9b7ec593aadfa48de5c93c0d658b6c", null ], [ "frame", "class_r_e_view.html#a63a3af5e1a9225ca441680ddbebdac21", null ], [ "isAnimating", "class_r_e_view.html#a32a8ebcd3cbdab877292408fdad551d7", null ], [ "isEqual", "class_r_e_view.html#aee0ea2a1b38c6d3838da56c0fac77812", null ], [ "isHasSubviews", "class_r_e_view.html#a1577433edbf5a74a4de0df8542326053", null ], [ "isInterceptsUserAction", "class_r_e_view.html#adc961e48978fc68ef2efc0d966923a5c", null ], [ "isRespondsForUserAction", "class_r_e_view.html#aeab9151618c19b83fef8a399fe90f781", null ], [ "isVisible", "class_r_e_view.html#a470272585c7e7c1df72730f9dec3badb", null ], [ "objectIdentifier", "class_r_e_view.html#a459f945cc9b1ab759bdce2afa4de0a7e", null ], [ "onReleased", "class_r_e_view.html#a7f72cd46892ec5f05fd67e24ab73bb78", null ], [ "parentSubviewsContainer", "class_r_e_view.html#a13c4b57733e14ec19698c264d676f9dc", null ], [ "release", "class_r_e_view.html#a797f9faff3763c2ae993bae26002b795", null ], [ "removeAllSubviews", "class_r_e_view.html#a451e494b7a8ed6d5ddb394ffd499e4d2", null ], [ "removeFromParentView", "class_r_e_view.html#afe9c4a057fdcf486de831f084cdb2b11", null ], [ "removeSubview", "class_r_e_view.html#a5fc1d016b1c82b846fab0be09f96fe01", null ], [ "render", "class_r_e_view.html#a02bd267d5456a52579e3c7680e41779e", null ], [ "renderSubviews", "class_r_e_view.html#a078a24389c3601cf67b5f2ff4690bfb5", null ], [ "renderWithOffset", "class_r_e_view.html#a7bbb13ccc842b18c361559fc68ab0b41", null ], [ "retain", "class_r_e_view.html#a68fc17de689649406dcb6083e549555e", null ], [ "retainCount", "class_r_e_view.html#afba219529cbf7947087c418255d43333", null ], [ "screenFrame", "class_r_e_view.html#a238d39b76e27b9d1f040b9ad5684e0e6", null ], [ "serializeToDictionary", "class_r_e_view.html#ac3c45099ca680d97aa9271eb6dc09667", null ], [ "setAlpha", "class_r_e_view.html#ad30dc228d02dd0c0cc2a9f1e86ca7103", null ], [ "setAlphaAnimated", "class_r_e_view.html#a66fcd685696e9f4a1e8cf3e29d443117", null ], [ "setColor", "class_r_e_view.html#aa63006ea967897405dba97ea6ac54bb4", null ], [ "setColorAnimated", "class_r_e_view.html#a93fdf99fc17f33a558159ca4ec0b5b82", null ], [ "setFrame", "class_r_e_view.html#a3d7119c2e58b8b56a54243396120b44d", null ], [ "setFrameAnimated", "class_r_e_view.html#a4a73160e38046f5a6de697f93493c371", null ], [ "setInterceptsUserAction", "class_r_e_view.html#ac6b51dedeec1e6dcab4c57bdc05a2161", null ], [ "setRespondsForUserAction", "class_r_e_view.html#a3efce341ed9b2c61f07ce94fb2796e33", null ], [ "setTag", "class_r_e_view.html#a0fa3bbfc2513f9d3d88853639beacccc", null ], [ "setTexture", "class_r_e_view.html#a25af066326f8a8f734fd435321621315", null ], [ "setVisible", "class_r_e_view.html#a1ff3815df6cd87b730cc0140d8ebd826", null ], [ "stopAnimation", "class_r_e_view.html#a095537e219a5aea216cf27d17c35b1e8", null ], [ "subviewsIterator", "class_r_e_view.html#a203508c9baa703e8f02fb28ad636d75e", null ], [ "subviewWithTag", "class_r_e_view.html#a90f42462e77475a524732b9d72e4273b", null ], [ "tag", "class_r_e_view.html#ae3dd2b63c45beb3b1e6c73853795dcf9", null ], [ "texture", "class_r_e_view.html#aef3214a35e3c88070b5b8cc352e2c3c7", null ], [ "userActionClickDidEnd", "class_r_e_view.html#a0c7c81f595cead87f89e9146f0bc40e5", null ], [ "userActionClickDidStart", "class_r_e_view.html#a5772a55b6047e21cf14191f56d3c9afe", null ], [ "userActionClickMoving", "class_r_e_view.html#a79fa5c9ab021c14c71afe04498614915", null ], [ "userActionClickMovingDidEnd", "class_r_e_view.html#a2b8c27f26cf6abe894b6f321e406f897", null ], [ "_animationsCount", "class_r_e_view.html#a87058367017ab5154fa6bdad8cf53601", null ], [ "_color", "class_r_e_view.html#aee97af4af5a91721af38180aabebb546", null ], [ "_frame", "class_r_e_view.html#aafccc0a0f3780dfb3e7a2447fc73fdd6", null ], [ "_isInterceptsUserAction", "class_r_e_view.html#a1b56933fc6133f3d752d779754ca6240", null ], [ "_isRespondsForUserAction", "class_r_e_view.html#a7e3fecdc442b5e3dc92848f42f1dc6d4", null ], [ "_isVisible", "class_r_e_view.html#aba0fbe0472e63835b9cc44c3b196ed73", null ], [ "_tag", "class_r_e_view.html#ad73801527d5865d377d88f1c25029def", null ], [ "_texture", "class_r_e_view.html#a4cfc431d2f55bb8130c8eed7625902fe", null ] ];
module.exports = function (hljs) { return { keywords: { special_functions: 'spawn spawn_link self', reserved: 'after and andalso|10 band begin bnot bor bsl bsr bxor case catch cond div end fun if ' + 'let not of or orelse|10 query receive rem try when xor' }, contains: [ { className: 'prompt', begin: '^[0-9]+> ', relevance: 10 }, { className: 'comment', begin: '%', end: '$' }, { className: 'number', begin: '\\b(\\d+#[a-fA-F0-9]+|\\d+(\\.\\d+)?([eE][-+]?\\d+)?)', relevance: 0 }, hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE, { className: 'constant', begin: '\\?(::)?([A-Z]\\w*(::)?)+' }, { className: 'arrow', begin: '->' }, { className: 'ok', begin: 'ok' }, { className: 'exclamation_mark', begin: '!' }, { className: 'function_or_atom', begin: '(\\b[a-z\'][a-zA-Z0-9_\']*:[a-z\'][a-zA-Z0-9_\']*)|(\\b[a-z\'][a-zA-Z0-9_\']*)', relevance: 0 }, { className: 'variable', begin: '[A-Z][a-zA-Z0-9_\']*', relevance: 0 } ] }; };
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; var randu = require( '@stdlib/random/base/randu' ); var incrmvariance = require( './../lib' ); var accumulator; var s2; var v; var i; // Initialize an accumulator: accumulator = incrmvariance( 5 ); // For each simulated datum, update the moving unbiased sample variance... console.log( '\nValue\tSample Variance\n' ); for ( i = 0; i < 100; i++ ) { v = randu() * 100.0; s2 = accumulator( v ); console.log( '%d\t%d', v.toFixed( 4 ), s2.toFixed( 4 ) ); }
exports.openWin = function(navGroup, winName, payload) { if ( typeof Alloy === 'undefined') { var w = winName; // transfer the value to a new variable so the rest of the code remains the same // if there was a payload object transfer the values to the window if (payload) { var payloadKeys = Object.keys(payload); payloadKeys.forEach(function(item, index) { w[payloadKeys[index]] = payload[item]; }); } } else { var w = Alloy.createController(winName,payload||{}).getView(); }; if (Ti.Platform.osname === 'android') { w.addEventListener('open', function(e) { if (! w.getActivity()) { Ti.API.error("Can't access action bar on a lightweight window."); } else { actionBar = w.activity.actionBar; if (actionBar) { actionBar.backgroundImage = "/images/"+Alloy.Globals.clientName+"/imageBG.png"; if (winName === "refillSuccess") { actionBar.displayHomeAsUp = false; } else { actionBar.displayHomeAsUp = true; actionBar.onHomeIconItemSelected = function() { w.close(); }; } } w.activity.invalidateOptionsMenu(); } }); w.open(); } else if (OS_MOBILEWEB) { navGroup.open(w, { animated : true }); } else { navGroup.openWindow(w, { animated : true }); } };
/** * Copyright 2015-2019 OpenCB * * 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. */ import {LitElement, html} from "lit"; import UtilsNew from "../../core/utilsNew.js"; import "../commons/tool-header.js"; export default class StudyForm extends LitElement { constructor() { super(); this._init(); } createRenderRoot() { return this; } static get properties() { return { project: { type: Object }, opencgaSession: { type: Object }, config: { type: Object } }; } _init() { this._prefix = UtilsNew.randomString(8); this.study = {}; } onFieldChange(e) { const field = e.detail.param; switch (e.detail.param) { case "id": case "name": case "description": this.study = { ...this.study, [field]: e.detail.value }; break; } // Study is not a lit property #L32, // so it's necessary use requestUpdate(); this.requestUpdate(); console.log("New Study", this.study); } getSaveForm(e) { console.log(e.detail.param); } onSave(e) { // TODO: Check it's ok ? this.opencgaSession.opencgaClient.studies().create(this.study, {project: this.project.fqn}) .then(res => { this.study = {}; this.requestUpdate(); this.dispatchEvent(new CustomEvent("sessionUpdateRequest", { detail: { }, bubbles: true, composed: true })); Swal.fire( "New Study", "New Study created correctly.", "success" ); }) .catch(err => { console.error(err); params.error(err); }); $("#newStudy").modal("hide"); // TODO: refactor this function. } onHide() { this.dispatchEvent(new CustomEvent("hide", { detail: {}, bubbles: true, composed: true })); } getStudyFormConfig() { return { title: "Edit", icon: "fas fa-edit", type: "form", buttons: { show: true, cancelText: "Cancel", okText: "Save" }, display: { style: "margin: 25px 50px 0px 0px", // mode: { // type: "modal", // title: "Review Variant", // buttonClass: "btn-link" // }, labelWidth: 3, labelAlign: "right", defaultValue: "", defaultLayout: "horizontal", }, sections: [ { elements: [ { name: "id", field: "id", type: "input-text", display: { placeholder: "Add a short ID...", } }, { name: "Name", field: "name", type: "input-text", display: { placeholder: "Study name...", } }, { name: "Description", field: "description", type: "input-text", display: { rows: 3, placeholder: "Study description...", } }, ] } ] }; } render() { return html` <data-form .data=${this.study} .config="${this.getStudyFormConfig()}" @fieldChange="${e => this.onFieldChange(e)}" @clear="${this.onHide}" @submit="${this.onSave}"> </data-form> `; } } customElements.define("study-form", StudyForm);
define(['jquery', 'stem/BodhiManager', 'stem/PanelManager'], function($, BodhiManager, PanelManager) { var BasePanel = function(options) { // this.moveable = options && options.moveable; // this.resizeable = options && options.resizeable; // this.closeable = options && options.closeable; this.label = options && options.label; this.widgetConfg = options && options.config; this.position = options && options.position; this.map = options && options.map; this.bodhiManager = BodhiManager.getInstance(); this.panelManager = PanelManager.getInstance(); this.id = options && options.pid; this.windowState = null; this.state = null; this.started = false; this.container = null; this.templateString = "<div></div>"; }; BasePanel.prototype.init = function() { this.postMixInProperties(); this.buildRendering(); this.postCreate(); this.element.appendTo(this.container); }; BasePanel.prototype.postMixInProperties = function() { }; BasePanel.prototype.buildRendering = function() { this.element = $(this.templateString); } BasePanel.prototype.postCreate = function() { }; BasePanel.prototype.startup = function() { this.started = true; }; BasePanel.prototype.resize = function() { }; BasePanel.prototype.moveTo = function(position) { var style = { 'position': 'absolute' }; if ('left' in position) { style.left = position.left; } if ('top' in position) { style.top = position.top; } this.element.css(style); }; BasePanel.prototype.setPosition = function(position) { var style = { 'position': 'absolute'; }; for (var p in position) { style[p] = position[p]; } this.element.css(style); }; BasePanel.prototype.setWidget = function(w) { this.widget = w; // this.widget.element.appendTo(this.element); }; BasePanel.prototype.destroy = function() { if (this.widget && this.widget.element) { this.widget.destroy(); } $.empty(this.element); }; })
dojo.provide("com.copacabana.search.SearchResultsManagerWidget"); dojo.require("dijit._Widget"); dojo.require("dijit._Templated"); dojo.require("dijit.form.Form"); dojo.require("dijit.form.Button"); dojo.require("dijit.form.ValidationTextBox"); dojo.require("dijit.form.DateTextBox"); dojo.require("dijit.form.CheckBox"); dojo.require("com.copacabana.DeclarativeTemplate"); dojo.require("com.copacabana.util"); dojo.require("com.copacabana.search.SearchResultsItem"); //I18N dojo.require("dojo.string"); dojo.require("dojo.i18n"); dojo.requireLocalization("com.copacabana.search", "SearchResultsManagerWidgetStrings"); dojo.declare("com.copacabana.search.SearchResultsManagerWidget", [ dijit._Widget, dijit._Templated,com.copacabana.DeclarativeTemplate ], { i18nStrings: null, templatePath : dojo.moduleUrl("com.copacabana.search","templates/SearchResultsManagerWidget.html"), constructor : function() { console.log('manager created'); }, domValues : { totalRestaurants : 0, totalItems : 0, showingStart : 0, showingEnd : 0, searchedValue : '' }, postMixInProperties : function() { this.inherited(arguments); console.log('manager postMixInProperties') }, postCreate : function() { this.inherited(arguments); console.log('manager postCreate') dojo.subscribe("onSearchBeingExecuted",this,"cleanResultsNWait"); this.i18nStrings=dojo.i18n.getLocalization("com.copacabana.search", "SearchResultsManagerWidgetStrings"); }, headerNode:null, resultsNode:null, startup : function() { try { console.log('starting manager') this.headerNode = dojo.query(".resultadoMensagem",this.domNode)[0]; this.resultsNode = dojo.query(".resultsList",this.domNode)[0]; console.log("this.resultsNode",this.resultsNode); //this.imageNode = dojo.create('img',{src:dojo.moduleUrl("com.copacabana", "images/loader.gif"),title:'buscando...',alt:'buscando...'}); //dojo.parser.parse(this.domNode); } catch (e) { console.error(e); } }, cleanResultsNWait:function(){ console.log('cleanResultsNWait',this.resultsNode); com.copacabana.util.cleanNode(this.resultsNode); //this.resultsNode.appendChild(this.imageNode); dojo.create('img',{src:dojo.moduleUrl("com.copacabana", "images/loader.gif"),title:'buscando...',alt:'buscando...',width:32,height:32},this.resultsNode) }, updateResults:function(results,searchCriteria){ com.copacabana.util.cleanNode(this.resultsNode); if(searchCriteria.openStatus==true){ var auxList=[]; for ( var i = 0; i < results.length; i++) { if(results[i].isOpen==true){ auxList.push(results[i]); } } results=auxList; } var criteria; if(searchCriteria.value && searchCriteria.value!=''){ if(searchCriteria.openStatus==true){ criteria= dojo.string.substitute(this.i18nStrings.searchCriteriaOpenNeigFreeform, [searchCriteria.neighborName,searchCriteria.value ]); }else{ criteria= dojo.string.substitute(this.i18nStrings.searchCriteriaNeigFreeform, [searchCriteria.neighborName,searchCriteria.value ]); } }else{ if(searchCriteria.openStatus==true){ criteria= dojo.string.substitute(this.i18nStrings.searchCriteriaNeigOpen, [searchCriteria.neighborName ]); }else{ criteria= dojo.string.substitute(this.i18nStrings.searchCriteriaNeig, [searchCriteria.neighborName ]); } } if(results.length===0){ criteria+= this.i18nStrings.suggestLink; this.headerNode.innerHTML = dojo.string.substitute(this.i18nStrings.noResultsFoundLable, [criteria]); } else { var str = dojo.string.substitute(this.i18nStrings.foundResultsLabel, [results.length, 0,criteria]); var start = 1; str += dojo.string.substitute(this.i18nStrings.showingLabel, [ start, results.length]); this.headerNode.innerHTML = str; for ( var j = 0; j < results.length; j++) { var item = new com.copacabana.search.SearchResultsItem(); item.setRestaurant(results[j]); item.startup(); this.resultsNode.appendChild(item.domNode); } dojo.parser.parse(this.domNode); } } });
/** * Configuration for head elements added during the creation of index.html. * * All href attributes are added the publicPath (if exists) by default. * You can explicitly hint to prefix a publicPath by setting a boolean value to a key that has * the same name as the attribute you want to operate on, but prefix with = * * Example: * { name: 'msapplication-TileImage', content: '/assets/icon/ms-icon-144x144.png', '=content': true }, * Will prefix the publicPath to content. * * { rel: 'apple-touch-icon', sizes: '57x57', href: '/assets/icon/apple-icon-57x57.png', '=href': false }, * Will not prefix the publicPath on href (href attributes are added by default * */ module.exports = { link: [ /** <link> tags for 'apple-touch-icon' (AKA Web Clips). **/ { rel: 'apple-touch-icon', sizes: '57x57', href: '/admin/assets/icon/apple-icon-57x57.png' }, { rel: 'apple-touch-icon', sizes: '60x60', href: '/admin/assets/icon/apple-icon-60x60.png' }, { rel: 'apple-touch-icon', sizes: '72x72', href: '/admin/assets/icon/apple-icon-72x72.png' }, { rel: 'apple-touch-icon', sizes: '76x76', href: '/admin/assets/icon/apple-icon-76x76.png' }, { rel: 'apple-touch-icon', sizes: '114x114', href: '/admin/assets/icon/apple-icon-114x114.png' }, { rel: 'apple-touch-icon', sizes: '120x120', href: '/admin/assets/icon/apple-icon-120x120.png' }, { rel: 'apple-touch-icon', sizes: '144x144', href: '/admin/assets/icon/apple-icon-144x144.png' }, { rel: 'apple-touch-icon', sizes: '152x152', href: '/admin/assets/icon/apple-icon-152x152.png' }, { rel: 'apple-touch-icon', sizes: '180x180', href: '/admin/assets/icon/apple-icon-180x180.png' }, /** <link> tags for android web app icons **/ { rel: 'icon', type: 'image/png', sizes: '192x192', href: '/admin/assets/icon/android-icon-192x192.png' }, /** <link> tags for favicons **/ { rel: 'icon', type: 'image/png', sizes: '32x32', href: '/admin/assets/icon/favicon-32x32.png' }, { rel: 'icon', type: 'image/png', sizes: '96x96', href: '/admin/assets/icon/favicon-96x96.png' }, { rel: 'icon', type: 'image/png', sizes: '16x16', href: '/admin/assets/icon/favicon-16x16.png' }, /** <link> tags for a Web App Manifest **/ { rel: 'manifest', href: '/admin/assets/manifest.json' } ], meta: [ { name: 'msapplication-TileColor', content: '#00bcd4' }, { name: 'msapplication-TileImage', content: '/admin/assets/icon/ms-icon-144x144.png', '=content': true }, { name: 'theme-color', content: '#00bcd4' } ] };
addI18n({ toc: { doc:'Dokumentation', intro:'Einführung', about:'Über APPUDO', inst:'Einen Node installieren', steps:'Erste Schritte - TBD', ndash:'Der Node Dash', hub:'Der APPUDO Hub - TBD', edit:'APPUDO Edit - TBD', sat:'Send Mail on CPU Saturation - TBD', seg:'Send Mail on SEGFAULT - TBD', exmpl:'Beispiele - TBD', exmpl_appudo:'APPUDO Hub - TBD', exmpl_blog:'Blog - TBD', exmpl_stream:'Video Streaming - TBD', exmpl_file:'File Manager - TBD', bench:'Benchmarking - TBD', faq:'FAQ (alt)', open:'Open Source Danksagungen', apis:'API Schnipsel - TBD', api_pdf:'PDFs erstellen und signieren - TBD', api_http:'HTTP Client - TBD', api_mail:'Mails senden - TBD', run:'Runs - TBD', run_msg:'Nachrichten zwischen Runs - TBD', ws:'WebSocket - TBD', ws_data:'Mit GET-Paramtetern verbinden - TBD', ws_intercon:'Unmaskierte Serververbindung - TBD', ws_bc:'Daten(Dateien) broadcasten - TBD', page:'Page - TBD', page_tmpl:'Templating with views and code - TBD', page_skin:'Skinning pages - TBD', proc_watch:'Proc files and Watching - TBD', proc_stats:'The Proc "stats" file - TBD', proc_rotate:'The Proc "log_roate" file - TBD', async:'Asynchrone Abarbeitung', zones:'Isolationszonen - TBD', esp:'Einstiegspunkt Bereiche - TBD', nodmn:'Zugriff ohne Domain - TBD', refs:'Referenzen - TBD', statf:'Static Files - TBD', uperm:'User Permissions - TBD', datab:'Database Tables - TBD', pkg:'Paketierung - TBD' }, menu: { back:'Zurück', bmenu:'Menü' } });
/* * Copyright 2014 TWO SIGMA OPEN SOURCE, LLC * * 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. */ var BeakerPageObject = require('./beaker.po.js'); var path = require('path'); describe('notebook', function() { function activateLanguage(language) { beakerPO.activateLanguageInManager(language); beakerPO.waitForPlugin(language); beakerPO.languageManagerCloseButton.click(); }; function insertCellOfType(language) { beakerPO.cellEvaluatorMenu.click(); beakerPO.cellEvaluatorMenuItem(language).click(); } function evalInLanguage(language, code, expected, done) { activateLanguage(language); insertCellOfType(language); beakerPO.setCellInput(code); beakerPO.evaluateCell(); beakerPO.waitForCellOutput(); return beakerPO.getCellOutput().getText() .then(function(output) { expect(output).toEqual(expected); done(); }); } beforeEach(function() { beakerPO = new BeakerPageObject(); browser.get(beakerPO.baseURL); browser.waitForAngular(); }); describe('graphs', function() { beforeEach(function() { beakerPO.newEmptyNotebook.click(); beakerPO.insertCellButton.click(); beakerPO.notebookMenu.click(); beakerPO.languageManagerMenuItem.click(); activateLanguage('Groovy'); insertCellOfType('Groovy'); beakerPO.setCellInput('new Plot()') beakerPO.evaluateCell(); }); afterEach(function(done) { beakerPO.closeNotebook() .then(done); }); it('can output graphs', function(done) { beakerPO.waitUntilGraphOutputPresent() .then(function(present) { expect(present).toEqual(true); done(); }); }); it('can output graphs when minimized', function(done) { beakerPO.toggleOutputCellExpansion() beakerPO.evaluateCell(); beakerPO.toggleOutputCellExpansion() beakerPO.waitUntilGraphOutputPresent() .then(function(present) { expect(present).toEqual(true); done(); }); }); }); it('can load', function() { beakerPO.newEmptyNotebook.click(); expect(browser.getTitle()).toEqual('New Notebook'); beakerPO.closeNotebook(); }); it('can add a cell', function() { beakerPO.newEmptyNotebook.click(); beakerPO.insertCellButton.click(); expect(beakerPO.getEvaluateButton().isDisplayed()).toBe(true); beakerPO.closeNotebook(); }); describe('evaluating JS', function() { beforeEach(function() { beakerPO.newEmptyNotebook.click(); beakerPO.insertCellButton.click(); beakerPO.cellEvaluatorMenu.click(); beakerPO.cellEvaluatorMenuItem('JavaScript').click(); }); it('displays syntax errors correctly', function(done) { beakerPO.setCellInput(','); beakerPO.evaluateCell(); beakerPO.waitForCellOutput(); beakerPO.getCellOutput().getText().then(function(txt) { expect(txt).toEqual('Unexpected token (1:0)', txt); done(); }); }); afterEach(function() { beakerPO.closeNotebook(); }); }); describe('evaluating languages', function() { beforeEach(function() { beakerPO.newEmptyNotebook.click(); beakerPO.insertCellButton.click(); beakerPO.notebookMenu.click(); beakerPO.languageManagerMenuItem.click(); }); afterEach(function() { beakerPO.closeNotebook(); }); it('HTML', function(done) { evalInLanguage('HTML', '1+1', '1+1', done); }); /* it('R', function(done) { evalInLanguage('R', '1+1', '[1] 2', done); }); */ it('JavaScript', function(done) { evalInLanguage('JavaScript', '1+1', '2', done); }); it('Groovy', function(done) { evalInLanguage('Groovy', '1+1', '2', done); }); }); });
/* @flow */ import { Component } from 'react'; import Button from '../../../../../../library/Button'; import ButtonGroup from '../../../../../../library/ButtonGroup'; import Box from '../../../../../../library/Box'; import Table from '../../../../../../library/Table'; import { columns2, columns4, columns100, rows100x100, rows100x4, rows2x2 } from '../../common/largeData'; export default { id: 'large-data-sets', title: 'Large Data Sets', description: `You should open this in a [chromeless standalone](/components/table/large-data-sets?chromeless) before clicking those buttons. 😬`, hideFromProd: true, scope: { Box, Button, ButtonGroup, Component, Table, columns2, columns4, columns100, rows100x100, rows100x4, rows2x2 }, source: ` () => { class MyTable extends Component { constructor(props) { super(props); this.state = { columns: columns2, data: rows2x2 }; this.populate2x2 = this.populate2x2.bind(this); this.populate4x100 = this.populate4x100.bind(this); this.populate100x100 = this.populate100x100.bind(this); } populate2x2() { this.setState({ columns: columns2, data: rows2x2 }) } populate4x100() { this.setState({ columns: columns4, data: rows100x4 }) } populate100x100() { this.setState({ columns: columns100, data: rows100x100 }) } render() { return ( <div> <Box marginBottom="md"> <ButtonGroup aria-label="Data options" mode="radio" size="medium"> <Button onClick={this.populate2x2} defaultChecked>2 &times; 2</Button> <Button onClick={this.populate4x100}>4 &times; 100</Button> <Button onClick={this.populate100x100}>100 &times; 100</Button> </ButtonGroup> </Box> <Table columns={this.state.columns} data={this.state.data} rowKey="aa" selectable title="Example data" hideTitle /> </div> ); } } return <MyTable />; } ` };
"use strict"; var path = require("path"); var browserSync = require(path.resolve("./")); var pkg = require(path.resolve("package.json")); var sinon = require("sinon"); var assert = require("chai").assert; var cli = require(path.resolve(pkg.bin)); describe("E2E CLI `reload` with no files arg", function () { it("should make a http request to the protocol with no files arg", function (done) { browserSync.reset(); browserSync .create() .init({server: "test/fixtures", open: false}, function (err, bs) { var spy = sinon.spy(bs.events, "emit"); cli({ cli: { input: ["reload"], flags: { port: bs.options.get("port") } }, cb: function () { sinon.assert.calledWithExactly(spy, "browser:reload"); bs.cleanup(); done(); } }); }); }); it("should make a http request with files arg", function (done) { browserSync.reset(); browserSync .create() .init({server: "test/fixtures", open: false}, function (err, bs) { var spy = sinon.spy(bs.events, "emit"); cli({ cli: { input: ["reload"], flags: { port: bs.options.get("port"), files: "core.css" } }, cb: function () { sinon.assert.calledWithExactly(spy, "file:changed", { path: "core.css", basename: "core.css", log: true, namespace: "core", event: "change", ext: "css" }); bs.cleanup(); done(); } }); }); }); it("should make a http request with files arg over HTTPS", function (done) { browserSync.reset(); browserSync .create() .init({server: "test/fixtures", open: false, https: true}, function (err, bs) { var spy = sinon.spy(bs.events, "emit"); cli({ cli: { input: ["reload"], flags: { url: bs.options.getIn(["urls", "local"]), files: "core.css" } }, cb: function () { sinon.assert.calledWithExactly(spy, "file:changed", { path: "core.css", basename: "core.css", ext: "css", log: true, namespace: "core", event: "change" }); bs.cleanup(); done(); } }); }); }); it("should handle ECONNREFUSED errors nicely", function (done) { cli({ cli: { input: ["reload"], flags: {} }, cb: function (err) { assert.equal(err.code, "ECONNREFUSED"); assert.equal(err.message, "Browsersync not running at http://localhost:3000"); done(); } }); }); it("should handle non 200 code results", function (done) { cli({ cli: { input: ["reload"], flags: {} }, cb: function (err) { assert.equal(err.code, "ECONNREFUSED"); assert.equal(err.message, "Browsersync not running at http://localhost:3000"); done(); } }); }); });
/** * Created by abbe on 2015-03-06. */ toggleClassHidden = function(elem) { $(elem).parent().find('.operations').toggleClass("hidden"); }; $(document).ready(function() { $('.speciality').click(function() { toggleClassHidden(this); }); });
var express = require('express'); var session = require('express-session'); var bodyParser = require('body-parser'); var path = require('path'); var static = require('serve-static') var Promise = require("bluebird"); var moment = require('moment'); var exports = module.exports = {}; var encodings = [ 'ascii', 'utf8', 'utf16le', 'ucs2', 'base64', 'latin1', 'binary', 'hex' ]; var config = { port: process.env.LISTEN_PORT || 8080, host: process.env.LISTEN_HOST || '0.0.0.0' }; // Check if encoding is defined and set to default if not var getEncoding = function(enc) { if (typeof enc === 'undefined' || enc === '') { return 'utf8'; } else { return enc; } } // Check if encoding is in list of supported encodings var isEncSupported = function(encoding) { var e = encodings.indexOf(encoding); if(e < 0) { return false; } else { return true; } } var encode = function(str, enc) { var encoding = getEncoding(enc); return new Promise(function(resolve, reject) { if(!isEncSupported(encoding)) { reject({'error': '\''+encoding+'\' is not a supported encoding.'}); } else { resolve(Buffer.from(str, encoding).toString('base64')); } }); } var decode = function(str, enc) { var encoding = getEncoding(enc); return new Promise(function(resolve, reject) { if(!isEncSupported(encoding)) { reject({'error': '\''+encoding+'\' is not a supported encoding.'}); } else { resolve(Buffer.from(str, 'base64').toString(encoding)) } }); } var encodeParamData = function(req, res) { encode(req.params.data, req.query.encoding).then(function(d) { res.json({ input: req.params.data, output: d, encoding: getEncoding(req.query.encoding), timestamp: moment() }); }).catch(function(error) { res.status(500).send(error); }); } var encodePostData = function(req, res) { encode(req.body.data, req.query.encoding).then(function(d) { res.json({ input: req.body.data, output: d, encoding: getEncoding(req.query.encoding), timestamp: moment() }); }).catch(function(error) { res.status(500).send(error); }); } var decodeParamData = function(req, res) { decode(req.params.data, req.query.encoding).then(function(d) { res.json({ input: req.params.data, output: d, encoding: getEncoding(req.query.encoding), timestamp: moment() }); }).catch(function(error) { res.status(500).send(error); }); }; var decodePostData = function(req, res) { decode(req.body.data, req.query.encoding).then(function(d) { res.json({ input: req.body.data, output: d, encoding: getEncoding(req.query.encoding), timestamp: moment() }); }).catch(function(error) { res.status(500).send(error); }); } var app = express(); var router = express.Router(); // Configure our app to use body-parser. This will let us get the data from POST requests app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // Middleware to use for all requests router.use(function(req, res, next) { // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', '*'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Set to true if you need the website to include cookies in the requests sent // to the API (e.g. in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', false); next(); }); // Routes router.route('/encode/:data') .get(encodeParamData); router.route('/encode') .post(encodePostData); router.route('/decode/:data') .get(decodeParamData); router.route('/decode') .post(decodePostData); // Register our routes app.use('/api', router); // Serve static content app.use('/', static(path.join(__dirname, 'build'), {'index': ['index.html']})); app.use('/node_modules', static(path.join(__dirname, '../../node_modules'))); app.listen(config.port, config.host); console.log(`Listening on http://${config.host}:${config.port}/`);
/** * @namespace cli */ module.exports = { CliLogger: require('./CliLogger.js').CliLogger };
var express = require('express'); var router = express.Router(); var crypto = require('crypto'); var User = require('../models/user.js'); var Post = require('../models/post.js'); var sys = require('sys'); var exec = require('child_process').exec; var util = require('util'); var spawn = require('child_process').spawn; function output(error, stdout, stderr){ sys.puts(stdout); var result = error; result += stdout; result += stderr; console.log(result); if (error !== null) { console.log('' + error); } } function render_result(req, res, result){ res.render('admin', { title: 'Deploy', deploy_msg:'Deploy the new code from github:\n' + result, user: req.session.user, success: req.flash('success').toString(), error: req.flash('error').toString() }); } router.get('/deploy', function(req, res) { //result = exec('sh `pwd`/tools/deploy.sh', output); console.log('Get deploy request ' + new Date()); res.write('Get deploy request ' + new Date() + '\n'); var result = spawn('sh', ['tools/deploy.sh']); var resultString = ""; result.stdout.on('data', function (data) { // register one or more handlers console.log('stdout: ' + data); res.write(data); resultString += data; // render_result(req, res, data); }); result.stderr.on('data', function (data) { resultString += data; console.log('stderr: ' + data); //render_result(req, res, data); res.write(data); }); result.on('exit', function (code) { console.log('child process exited with code ' + code); resultString += 'child process exited with code ' + code; // render_result(req, res,resultString); // res.write(resultString); res.end(); }); }); router.get('/', function(req, res) { res.render('post', { title: 'Post' , user: req.session.user, success: req.flash('success').toString(), error: req.flash('error').toString() }); }); router.post('/', function(req, res) { var username = req.session.user.name; var title = req.body.title; var post = req.body.post; var date = new Date(); var newPost = new Post({ username:username, time:date, title:title, post:post }); newPost.save(function(err, post){ if(err){ req.flash('error', err); return res.redirect('/'); } req.flash('success', 'Congratulations, your post saved success'); res.redirect('/'); }); }); module.exports = router;
(function () { 'use strict'; var title = 'Change Popup Template'; angular.module('mappifyApp.sidebar.popups', [ 'mappifyApp.sidebar.configService' ]) .config(function (configServiceProvider) { var description = { id: 'popup', order: 90, title: title, fileName: 'popups', icon: 'share-square-o', ctrl: PopupCtrl }; // @notice the template modal is currently disabled //configServiceProvider.registerConfig(description); }); /*@ngInject*/ function PopupCtrl($modalInstance, mapService) { var modal = this; modal.title = title; modal.popups = ''; modal.cancel = function () { $modalInstance.dismiss(); }; // modalInstance resolves the promise modal.close = function () { $modalInstance.close(modal.popups); mapService.triggerAutoRefreshConfig(); }; } })();
view.ar = ( function() { var api = {}; api.createARWindow = function() { var win1 = Titanium.UI.createWindow({ navBarHidden : true }); win1.add(createHead('St.Pauli-Rundblick')); var rows = []; var stations = []; var currLocation; rows[0] = Ti.UI.createTableViewRow({ height : 130 }); var toptitle = Ti.UI.createLabel({ color : 'white', top : 5, left : 180, height : 'auto', font : { fontSize : 20, fontFamily : 'MoondogZero' }, text : 'Eigener Standort' }); rows[0].add(toptitle); var map = Titanium.Map.createView({ height : 600, width : 800, top : 3, left : 3, anchorPoint : { x : 0, y : 0 }, borderRadius : 10, borderWidth : 1, transform : Titanium.UI.create2DMatrix().scale(.2), userLocation : true, mapType : Titanium.Map.STANDARD_TYPE, region : { latitude : 53.5526999, longitude : 9.9607801, latitudeDelta : 0.0005, longitudeDelta : 0.0005 }, }); var office = Titanium.Map.createAnnotation({ latitude : 53.5526999, longitude : 9.9607801, }); rows[0].add(map); var skull = Ti.UI.createImageView({ image : '/assets/skull.png', right : 2, width : 25, height : 20 }); rows[0].add(skull); var tv = Ti.UI.createTableView({ height : '100%', top : 60, backgroundColor : 'black' }); win1.add(tv); tv.addEventListener('click', function(e) { var arwindow = Ti.UI.createWindow({ navBarHidden : true, url : '/ar/camera.js', locations : stations, currLocation : currLocation }); tabGroup.activeTab.open(arwindow); }); ctrl.stations.getStations(true, function(e) { stations = e.stations; var colors = ['#ff7777', '#6666ff', '#ff66ff']; currLocation = e.myposition; map.setLocation({ latitude : currLocation.lat, longitude : currLocation.lng }); map.animate(Ti.UI.createAnimation({ left : 3, duration : 800 })); for(var i = 0; i < e.stations.length; i++) { var station = e.stations[i]; rows[i + 1] = Ti.UI.createTableViewRow({ latlng : station.latlng, height : 60 }); var skull = Ti.UI.createImageView({ image : '/assets/skull.png', right : 2, width : 25, height : 20 }); var logo = Ti.UI.createImageView({ image : '/assets/logos/' + station.id + '.png', left : 0, defaultImage : '', borderWidth : 1, borderRadius : 5, top : 3, width : 90, height : 30 }); var dist = Ti.UI.createLabel({ color : '#ccc', left : 5, bottom : 5, height : 'auto', font : { fontSize : 10, fontFamily : 'MoondogZero' }, text : station.dist + ' m' }); rows[i + 1].add(dist); rows[i + 1].add(logo); var title = Ti.UI.createLabel({ color : colors[station.kategorie - 1], left : 100, right : 25, top : 5, bottom : 10, height : 'auto', font : { fontSize : 15, fontWeight : 'bold', fontFamily : 'MoondogZero' }, text : station.title }); rows[i + 1].add(title); rows[i + 1].add(skull); } tv.setData(rows); }); return win1; } return api; }());
var dashboard = document.getElementById("dashboard"); var bookShelfDB; function openDB() { indexedDB.deleteDatabase("bookShelf"); var openResult = window.indexedDB.open("bookShelf", 1); openResult.addEventListener("success", function() { bookShelfDB = this.result; initData(); }); openResult.addEventListener("upgradeneeded", function() { bookShelfDB = this.result; if (bookShelfDB.objectStoreNames.contains("books")) { bookShelfDB.deleteObjectStore("books"); } var objStore = bookShelfDB.createObjectStore("books", { keyPath : "isbn", autoIncrement : true }); }); } openDB(); function initData() { var tx = bookShelfDB.transaction([ "books" ], "readwrite"); var objStore = tx.objectStore("books"); objStore.put({ title : "HTML5", year : 2016, category : "기술" }); objStore.put({ title : "CSS35", year : 2015, category : "기술" }); objStore.put({ title : "JavaScript", year : 2014, category : "기술" }); objStore.put({ title : "Java", year : 2013, category : "기술" }); objStore.put({ title : "Servlet/JSP", year : 2012, category : "기술" }); objStore.put({ title : "JQuery", year : 2011, category : "기술" }); objStore.put({ title : "SQL", year : 2010, category : "기술" }); objStore.put({ title : "Spring", year : 2009, category : "기술" }); objStore.put({ title : "MyBatis", year : 2008, category : "기술" }); objStore.put({ title : "XML", year : 2007, category : "기술" }); } document.getElementById("getAllB").addEventListener("click", function() { dashboard.innerHTML = ""; var tx = bookShelfDB.transaction([ "books" ], "readonly"); var objStore = tx.objectStore("books"); var request = objStore.getAll(); request.addEventListener("success", function() { dashboard.innerHTML = ""; for (var i = 0; i < request.result.length; i++) { dashboard.innerHTML += JSON.stringify(request.result[i]) + "<br>"; } }); }); var lowerIsbn = document.getElementById("lowerISBN"); var upperIsbn = document.getElementById("upperISBN"); document.getElementById("getByIsbnRangeB").addEventListener( "click", function() { var keyRange; var lowerValue = Number.parseInt(lowerIsbn.value); var upperValue = Number.parseInt(upperIsbn.value); if (!(lowerValue || upperValue)) { dashboard.innerHTML = "최소값과 최대값이 필요합니다."; return; } else { keyRange = IDBKeyRange.bound(lowerValue, upperValue, false, false); } var tx = bookShelfDB.transaction([ "books" ], "readonly"); var objStore = tx.objectStore("books"); var request = objStore.getAll(keyRange); request.addEventListener("success", function() { dashboard.innerHTML = ""; for (var i = 0; i < request.result.length; i++) { dashboard.innerHTML += JSON.stringify(request.result[i]) + "<br>"; } }); });
$(document).ready(function () { $(window).on('scroll',function () { var bottom = $(document).height() - $('.module-share').offset().top; if (bottom <= 185) { if (parseInt($('.module-share').css('bottom')) == 100) return; $('.module-share').css('bottom', 100) } else if(bottom >= 400){ if (parseInt($('.module-share').css('bottom')) == 0) return; $('.module-share').css('bottom', 0) } }); $(window).trigger('scroll'); });
var assert = require('assert'); var utils = require('util'); module.exports = { 'AdserverTargeting Test Case 1' : function (browser) { browser .url('http://localhost:9999/test/spec/e2e/gpt-examples/gpt_default.html') .waitForElementVisible('body', 3000) .pause(3000) .execute(function(){ if(typeof window.pbjs.bidderSettings == "undefined") { var pbjsBidderSettingsObject = [ "hb_bidder", "hb_adid", "hb_pb", "hb_size" ]; } else { var pbjsBidderSettings = window.pbjs.bidderSettings; var pbjsBidderSettingsObject = {}; Object.keys(pbjsBidderSettings).forEach(function (prop) { //if(prop == 'standard') return; var value = pbjsBidderSettings[prop]; var bs = value.adserverTargeting.map(function(item){ return item.key; }); pbjsBidderSettings.standard.adserverTargeting.map(function(value){ if(bs.indexOf(value.key) == -1 ) { bs.push(value.key) } }); pbjsBidderSettingsObject[prop] = bs; }); } var adserverTargetingObject = {}; var adserverTargeting = window.pbjs.getAdserverTargeting(); Object.keys(adserverTargeting).forEach(function(value){ if(Object.keys(adserverTargeting[value]).length == 0) return; adserverTargetingObject[adserverTargeting[value].hb_bidder] = Object.keys(adserverTargeting[value]) }); return [pbjsBidderSettingsObject, adserverTargetingObject]; }, [], function(result) { Object.keys(result.value[1]).forEach(function(key) { if(utils.isArray(result.value[0])) { assert.deepEqual(result.value[0].sort(), result.value[1][key].sort()); } else { if(result.value[0].hasOwnProperty(key)) { var obj1 = result.value[0][key].sort(); } else { var obj1 = result.value[0]['standard'].sort(); } assert.deepEqual(obj1, result.value[1][key].sort()); } }); }); }, after : function(browser) { browser.end(); } };
/*! * ${copyright} */ // Provides the Design Time Metadata for the sap.m.DatePicker control sap.ui.define([], function() { "use strict"; return { actions: { remove: { changeType: "hideControl" }, reveal: { changeType: "unhideControl" } }, name: { singular: "DATEPICKER_NAME", plural: "DATEPICKER_NAME_PLURAL" } }; }, /* bExport= */ false);
var chai = require('chai'); var expect = chai.expect; describe('operations/shape.js', function() { var source = require('../../fixtures/source.json'); var shape; beforeEach(function() { shape = require('../../../operations/shape'); }); it('should shape an object', function() { var result = shape({ type: 'shape', shape: { qix: { qux: '/foo/bar' } } }, source); expect(result).to.deep.equal({ qix: { qux: 1 } }); }); it('should shape an object with defaults', function() { var result = shape({ type: 'shape', shape: { qix: { qux: ['/foo/bar/baz', 2] } } }, source); expect(result).to.deep.equal({ qix: { qux: 2 } }); }); it('should shape an object with defaults with single token', function() { var result = shape({ type: 'shape', shape: { qix: { qux: ['/foo/bar/baz', '<%/foo/bar%>'] } } }, source); expect(result).to.deep.equal({ qix: { qux: '1' } }); }); it('should shape an object with defaults with multiple tokens', function() { var result = shape({ type: 'shape', shape: { qix: { qux1: ['/foo/bar/baz', 'test:<%/foo/bar%>:<%/foo/baz%>'], qux2: ['/foo/bar/baz', '<%/foo/bar%>:<%/foo/baz%>'] } } }, source); expect(result).to.deep.equal({ qix: { qux1: 'test:1:2', qux2: '1:2' } }); }); it('should shape an object with source value reference', function() { var result = shape({ type: 'shape', shape: { qix: { qux: '@' } } }, source); expect(result).to.deep.equal({ qix: { qux: source } }); }); it('should shape an object with a dynamic path', function() { var result = shape({ type: 'shape', shape: { qix: { qux: '/foo/@' } } }, source); expect(result).to.deep.equal({ qix: { qux: [1, 2, [3, 4]] } }); }); it('should shape an object with virtuals', function() { var result = shape({ type: 'shape', virtual: { virtualTest: [{ target: { path: '/virtualTest' }, source: { path: '/hello/world' } }] }, shape: { qix: { qux: '$virtualTest' } } }, source); expect(result).to.deep.equal({ qix: { qux: 'lorem' } }); }); it('should shape an object with virtuals and defaults', function() { var result = shape({ type: 'shape', virtual: { virtualTest: [{ target: { path: '/virtualTest' }, source: { path: '/hello/world/foo' } }] }, shape: { qix: { qux: ['$virtualTest', 'virtual-default'] } } }, source); expect(result).to.deep.equal({ qix: { qux: 'virtual-default' } }); }); });
(function(window, google, maperizer) { maperizer.MAP_OPTIONS = { geolocation: true, center: { lat: 0, lng: 0 }, zoom: 7, searchbox: true, cluster: true, geocoder: true } }(window, google, window.Maperizer || (window.Maperizer = {})));
/** * Contians utility functions for calculating values on geometries * @module geomutils **/ //File for geom utils if (!Number.prototype.toRad) { Number.prototype.toRad = function() { return this * Math.PI / 180; }; } var greatCircleRadius = { miles: 3956, km: 6367 }; /** * Calculates the distance between the two points using the haversine method. * @param {number} lat1 The latitude of the first point. * @param {number} lon1 The longtitude of the first point. * @param {number} lat2 The latitude of the first point. * @param {number} lon2 The longtitude of the first point. * @returns {number} The distance in miles between the two points. **/ exports.calculateDistance = function(lat1, lon1, lat2, lon2) { var dLat = (lat2 - lat1).toRad(), dLon = (lon2 - lon1).toRad(); lat1 = lat1.toRad(); lat2 = lat2.toRad(); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return greatCircleRadius.km * c; }; /** * Calcuates the midpoint between the two points passed in. * @param {number} lat1 The latitude of the first point. * @param {number} lon1 The longtitude of the first point. * @param {number} lat2 The latitude of the first point. * @param {number} lon2 The longtitude of the first point. */ exports.calculateMidpoint = function(lat1, lon1, lat2, lon2) { var dLat = (lat2 - lat1).toRad(), dLon = (lon2 - lon1).toRad(); lat1 = lat1.toRad(); lat2 = lat2.toRad(); var Bx = Math.cos(lat2) * Math.cos(dLon); var By = Math.cos(lat2) * Math.sin(dLon); var lat3 = Math.atan2(Math.sin(lat1) + Math.sin(lat2), Math.sqrt((Math.cos(lat1) + Bx) * (Math.cos(lat1) + Bx) + By * By)); var lon3 = lon1 + Math.atan2(By, Math.cos(lat1) + Bx); };
var gulp = require('gulp'); var webpack = require('webpack'); var gutil = require('gulp-util'); var webpackConfig = require('./webpack.config'); var watch = require('gulp-watch'); var build = function () { return webpack(webpackConfig, function (err, stats) { if (err) throw new gutil.PluginError('webpack', err); gutil.log('[webpack]', stats.toString({ colors: true, progress: true })); var date = new Date(); console.log('LAST COMPILATION : ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()); }); }; gulp.task('watch', function () { return watch('./public/src/**/*.js', function () { build(); }); }); gulp.task('build', function () { build(); });
(function(){ 'use strict'; angular .module('SyntheaApp') .factory('SynMixer', SynMixer); SynMixer.$inject = ['SynSubgroup','SynProject','$interval']; function SynMixer(SynSubgroup,SynProject,$interval) { /** * A pointer to the current SynMixer instance, so we can * stop any playback/timers when instantiating a new one * * @private */ var mixer; var Howler = require('howler').Howler; /** * Creates an instance of **SynMixer**, which is the Mixer singleton, the * master controller of all Subgroups and Channels in the Project. * * The Mixer manages the queuing, fading, and replacing * of cues according to global and cue-specific configs. * For each Subgroup, the Mixer maintains an array of Channels * that handle individual cues. Each Channel can be assigned * only one cue at a time. * * @property {array} channels An array of *every* Channel that * exists in the Mixer * @property {number} fadeInDuration The global default for * fade-in time on new cues (used only when fade-in is active) * @property {number} fadeOutDuration The global default for fade-out * time on new cue (used in all cases of pausing/stopping playback) * @property {boolean} isCloudProject A flag to identify whether * the current Project is stored locally or in the cloud, which * has ramifications on how playback is handled. * @property {object} subgroups A mapping of all * the available Subgroups in the Mixer. This is * populated on-demand as cues are loaded. */ function Mixer() { this.$interval_ = $interval; this.channels = []; this.subgroups = {}; window.channels = this.channels; // Global settings from the project var p = SynProject.getProject(); var d = SynProject.getProjectDef(); // Set our global Howler options Howler.autoSuspend = false; // Fail? So far, only on debug refresh of render window if (!p.config || !d.documentRoot) { console.warn('Unable to load Mixer, missing project or config'); return; } this.fadeInDuration = p.config.fadeInDuration || 2000; this.fadeOutDuration = p.config.fadeOutDuration || 2000; this.isCloudProject = !!d.documentRoot.match('https?://'); return this; } Mixer.prototype._buildAnalyser = function() { // Create a analyser/visualization node and splice it in between the // Howler masterGain and destination nodes this.analyser = Howler.ctx.createAnalyser(); Howler.masterGain.connect(this.analyser); this.analyser.connect(Howler.ctx.destination); }; /** * Universal method to play a cue, really just a convenience method to call * `Mixer.queue` with `opts.autoplay = true`. * * @param {Cue} cue - the Cue object to be played * @param {object} [opts] options to define playback * @return {Channel} */ Mixer.prototype.play = function(cue, opts) { // Accept any incoming options, and add autoplay var options = angular.merge({autoplay: true}, opts); // Return the channel on which it plays return this.queue(cue, options); }; /** * Universal method to queue a cue for playback (which essentially passes * the command down the line to Subgroup to Channel to Player) * * @param {Cue} cue - the Cue object to be queued * @param {object} [opts] - options for the cue playback * @return {Channel} */ Mixer.prototype.queue = function(cue,opts) { var subname; // Is there a subgroup for this button? // If not, use the common subgroup subname = cue.subgroup || '__COMMON__'; // Does this subgroup need to be created? if (!this.subgroups.hasOwnProperty(subname)) { this.subgroups[subname] = new SynSubgroup(subname,this); } // Should we make an analyser? if (!this.analyser) { // Keep an eye out for our howler context // TODO: use a callback rather than interval var contextInterval = this.$interval_(function() { if (Howler.ctx) { this._buildAnalyser(); this.$interval_.cancel(contextInterval); } }.bind(this)); } // Return the channel on which it plays return this.subgroups[subname].queue(cue,opts); }; /** * Global method to stop playback on all Channels. * * @param {boolean} fullstop Force all channels (including queued) to stop & flush */ Mixer.prototype.stop = function(fullstop, hardstop) { // Iterate through the Subgroups and stop them all angular.forEach(this.subgroups, function(subgroup) { // If fullstop, clear ALL channels including queue if (fullstop) { subgroup.stopFull(hardstop); } // If regular stop, only stop current/active channels else { subgroup.stopExcept(); } }); }; /** * Flush the queue and playback all cues that are queued */ Mixer.prototype.toggleLock = function() { // Iterate through the Channels and play any that are queued angular.forEach(this.channels, function(ch) { if (ch.is_queued) { ch.play(); } }); }; return { createMixer: function() { // Clear out an existing mixer, if need be if (mixer) { mixer.stop(); } mixer = new Mixer(); return mixer; }, getMixer: function() { return mixer; } }; } // IIFE })();
'use strict' var React = require('react') var LayerUtils = require('./LayerUtils') var Surface = React.createClass({ displayName: 'Surface', layer: null, ctx: null, getDefaultProps: function() { return { scale: window.devicePixelRatio || 1 } }, render: function() { let children = this.props.children let h = React.createElement return h('canvas', { id:'canvas', ref:this.handleRef, tabIndex:1, width:this.props.width, height:this.props.height, style:this.props.style, onKeyDown: this.handleKeyDown, onKeyUp: this.handleKeyUp, onKeyPress: this.handleKeyPress, onTouchBegin: this.handleTouchBegin, onTouchMove: this.handleTouchMove, onTouchEnd: this.handleTouchEnd, onTouchCancel: this.handleTouchCancel, onClick: this.handleClick, onDoubleClick: this.handleDoubleClick, onWheel: this.handleWheel }, children) }, componentDidMount: function() { if (this.layer) this.batchedTick() this.context2d().scale(this.props.scale, this.props.scale) }, componentDidUpdate: function(prevProps, prevState) { if (this.layer) this.batchedTick() //this.context2d().scale(this.props.scale, this.props.scale) }, handleKeyDown: function(e) { let target = LayerUtils.focusTest(e, this.layer, this) //console.log(target) if (target && target.onKeyDown) target.onKeyDown(e) }, handleKeyUp: function(e) { let target = LayerUtils.focusTest(e, this.layer, this) if (target && target.onKeyUp) target.onKeyUp(e) }, handleKeyPress: function(e) { let target = LayerUtils.focusTest(e, this.layer, this) if (target && target.onKeyPress) target.onKeyPress(e) }, handleClick: function(e) { let target = LayerUtils.hitTest(e, this.layer, 'onClick') }, handleDoubleClick: function(e) { let target = LayerUtils.hitTest(e, this.layer, 'onDoubleClick') }, handleWheel: function(e) { let target = LayerUtils.hitTest(e, this.layer, 'onWheel') }, handleTouchBegin: function(e) { let target = LayerUtils.hitTest(e, this.layer, 'onTouchBeing') }, handleTouchMove: function(e) { let target = LayerUtils.hitTest(e, this.layer, 'onTouchMove') }, handleTouchEnd: function(e) { let target = LayerUtils.hitTest(e, this.layer, 'onTouchEnd') }, handleTouchCancel: function(e) { let target = LayerUtils.hitTest(e, this.layer, 'onTouchCancel') }, handleRef: function(ref) { if (this.layer !== ref) { console.log('canvas: ref='+ref+' focus='+(document.activeElement)) ref.focus() console.log('canvas: focus1='+(document.activeElement)) //document.getElementById('surface').focus(); //console.log('canvas: focus2='+(document.activeElement)+' c1='+document.getElementById('surface')) this.layer = ref this.layer.repaint = this.batchedTick } //console.log(this.layer) }, context2d: function() { return this.layer.getContext('2d') }, batchedTick: function() { if (this._frameReady === false) { this._pendingTick = true return } this.doTick() }, doTick: function () { // Block updates until next animation frame. this._frameReady = false LayerUtils.drawLayer(this.layer, this.context2d()) requestAnimationFrame(this.afterTick) }, afterTick: function () { // Execute pending draw that may have been scheduled during previous frame this._frameReady = true if (this._pendingTick) { this._pendingTick = false this.batchedTick() } }, }) module.exports = Surface /* let CanvasProxy = React.createClass({ render: function() { console.log("proxyctx: "+this.props.context.repainter) return this.props.children && this.props.children[0] || null }, getChildContext: function() { return this.props.context }, childContextTypes: { repainter: React.PropTypes.object } }) let Canvas = React.createClass({ componentDidMount() { return //this.draw(this, 2) let h = React.createElement ReactDOM.render(h(CanvasProxy, { context:{repainter:this.state.repainter}, width:this.props.width, height:this.props.height, style:this.props.style }, this.props.children), document.createElement("section")) }, }) //img = 'https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Sorted_binary_tree_inorder.svg/336px-Sorted_binary_tree_inorder.svg.png' */
require("../www/discography/js/lib/ajax.js"); require("../www/discography/js/lib/promise.js"); describe("Ajax interface", function() { it("has a get method", function() { expect(Ajax.get).toBeDefined(); }); it("get method should resolve promise", function(done) { XMLHttpRequest.withResponse(function(response) { response.responseText = JSON.stringify([1, 2, 3]); var promise = Ajax.get("/foo"); expect(promise).toBeDefined(); expect(promise.then).toBeDefined(); promise.then(function(array) { expect(response.requestMethod).toEqual("GET"); expect(response.requestURL).toEqual("/foo"); expect(array.length).toEqual(3); // Tell Jasmine we were called. MUST call the `done' function // *after* all expectations or the tests will silently pass :( done(); }); }); }); });
import request from 'supertest'; import {expect} from 'chai'; import {Vote} from 'lib/models'; import {Poll} from 'lib/models'; import {Types} from 'mongoose'; describe('Votes', () => { let votes = [], poll, agent; before( done => { agent = request.agent(server); Poll.create({ dashboard: 'dash1', title: 'poll 1', owner: users[0]._id }, (err, _poll) => { poll = _poll; Vote.create([{ projectId: Types.ObjectId().toString(), poll: poll._id, fingerprints: ['a'] }, { projectId: Types.ObjectId().toString(), poll: poll._id, fingerprints: ['a', 'b'] }, { projectId: Types.ObjectId().toString(), poll: poll._id, fingerprints: ['a', 'b', 'c'] }], (err, _votes) => { votes = _votes; done(err); }); }); }); after( done => { Vote.remove({}, () => { Poll.remove(done); }); }); it ('must not allow to request without a fingerprint', done => { agent.get('/api/polls/' + poll.token + '/votes') .expect(400) .end(done); }); it ('must allow to fetch all project votes', done => { let fingerprint = 'b'; agent.get('/api/polls/' + poll.token + '/votes') .set('fingerprint', fingerprint) .expect(200) .end((err, res) => { let pvotes = res.body; expect(pvotes).to.be.an('array'); expect(pvotes.length).to.be.equal(3); pvotes.forEach( (p, i) => { expect(p.projectId).to.be.ok; expect(p.votes).to.be.a('number'); expect(p.votes).to.be.equal(votes[i].fingerprints.length); if (votes[i].fingerprints.indexOf(fingerprint) > -1){ expect(p.voted).to.be.equal(true); } else { expect(p.voted).to.be.equal(false); } }); done(); }); }); it ('must allow to vote a project', done => { let v = votes[0]; let fingerprint = 'b'; agent.post('/api/polls/' + poll.token + '/votes/' + v.projectId) .set('fingerprint', fingerprint) .expect(200) .end((err, res) => { let _v = res.body; expect(_v.projectId).to.be.equal(v.projectId); expect(_v.votes).to.be.equal(v.fingerprints.length + 1); expect(_v.voted).to.be.equal(true); v.fingerprints.push(fingerprint); done(); }); }); it ('must allow to vote a project which has no votes yet', done => { let fingerprint = 'b'; let newId = Types.ObjectId().toString(); agent.post('/api/polls/' + poll.token + '/votes/' + newId) .set('fingerprint', fingerprint) .expect(200) .end((err, res) => { let _v = res.body; expect(_v.projectId).to.be.equal(newId); expect(_v.votes).to.be.equal(1); expect(_v.voted).to.be.equal(true); done(); }); }); it ('must VALIDATE ProjectID is a valid Mongo ObjectId', done => { let fingerprint = 'd'; agent.post('/api/polls/' + poll.token + '/votes/XYZ') .set('fingerprint', fingerprint) .expect(400) .end(done); }); it ('must allow to unvote a project', done => { let v = votes[0]; let fingerprint = 'b'; agent.delete('/api/polls/' + poll.token + '/votes/' + v.projectId) .set('fingerprint', fingerprint) .expect(200) .end((err, res) => { let _v = res.body; expect(_v.projectId).to.be.equal(v.projectId); expect(_v.votes).to.be.equal(v.fingerprints.length - 1); expect(_v.voted).to.be.equal(false); v.fingerprints.push(fingerprint); done(); }); }); it ('must NOT allow to vote or unvote a project if is not an open poll', done => { let fingerprint = 'k'; let newId = Types.ObjectId().toString(); poll.open = false; poll.save( (err, _poll) => { expect(_poll.open).to.be.equal(false); agent.post('/api/polls/' + poll.token + '/votes/' + newId) .set('fingerprint', fingerprint) .expect(403) .end((err, res) => { agent.delete('/api/polls/' + poll.token + '/votes/' + newId) .set('fingerprint', fingerprint) .expect(403) .end(done); }); }); }); });
// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-id-init-fn-name-cover.case // - src/dstr-binding/default/cls-expr-gen-meth-static-dflt.template /*--- description: SingleNameBinding assigns `name` to "anonymous" functions "through" cover grammar (static class expression generator method (default parameter)) esid: sec-class-definitions-runtime-semantics-evaluation es6id: 14.5.16 features: [generators, destructuring-binding, default-parameters] flags: [generated] info: | ClassExpression : class BindingIdentifieropt ClassTail 1. If BindingIdentifieropt is not present, let className be undefined. 2. Else, let className be StringValue of BindingIdentifier. 3. Let value be the result of ClassDefinitionEvaluation of ClassTail with argument className. [...] 14.5.14 Runtime Semantics: ClassDefinitionEvaluation 21. For each ClassElement m in order from methods a. If IsStatic of m is false, then b. Else, Let status be the result of performing PropertyDefinitionEvaluation for m with arguments F and false. [...] 14.4.13 Runtime Semantics: PropertyDefinitionEvaluation GeneratorMethod : * PropertyName ( StrictFormalParameters ) { GeneratorBody } 1. Let propKey be the result of evaluating PropertyName. 2. ReturnIfAbrupt(propKey). 3. If the function code for this GeneratorMethod is strict mode code, let strict be true. Otherwise let strict be false. 4. Let scope be the running execution context's LexicalEnvironment. 5. Let closure be GeneratorFunctionCreate(Method, StrictFormalParameters, GeneratorBody, scope, strict). 9.2.1 [[Call]] ( thisArgument, argumentsList) [...] 7. Let result be OrdinaryCallEvaluateBody(F, argumentsList). [...] 9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList ) 1. Let status be FunctionDeclarationInstantiation(F, argumentsList). [...] 9.2.12 FunctionDeclarationInstantiation(func, argumentsList) [...] 23. Let iteratorRecord be Record {[[iterator]]: CreateListIterator(argumentsList), [[done]]: false}. 24. If hasDuplicates is true, then [...] 25. Else, b. Let formalStatus be IteratorBindingInitialization for formals with iteratorRecord and env as arguments. [...] 13.3.3.7 Runtime Semantics: KeyedBindingInitialization SingleNameBinding : BindingIdentifier Initializeropt [...] 6. If Initializer is present and v is undefined, then [...] d. If IsAnonymousFunctionDefinition(Initializer) is true, then i. Let hasNameProperty be HasOwnProperty(v, "name"). ii. ReturnIfAbrupt(hasNameProperty). iii. If hasNameProperty is false, perform SetFunctionName(v, bindingId). ---*/ var callCount = 0; var C = class { static *method({ cover = (function () {}), xCover = (0, function() {}) } = {}) { assert.sameValue(cover.name, 'cover'); assert.notSameValue(xCover.name, 'xCover'); callCount = callCount + 1; } }; C.method().next(); assert.sameValue(callCount, 1, 'method invoked exactly once');
module.exports = decorate var ErrorPage = require("error-page") , domain = require("domain") , Cookies = require("cookies") , RedSess = require("redsess") , csrf = require('csrf-lite') , path = require('path') , sanitizer = require('sanitizer') , Templar = require("templar") , ejs = require('ejs') , tplDir = path.resolve(__dirname, 'templates') , templateOptions = { engine: ejs, folder: tplDir } , url = require('url') , bunyan = require('bunyan') , crypto = require('crypto') , logger , CouchLogin = require('couch-login') // TODO: Error page configs , errorPageConf = {} , MC = require('./models.js') , http = require('http') function errorHandler (req, res, data) { if (!req.profile) { req.model.load('profile', req) req.model.end(thenShow) } else { thenShow() } function thenShow () { data.profile = req.profile data.title = data.message data.statusMessage = http.STATUS_CODES[data.statusCode] var tpl = 'error.ejs' var tplSpecial = 'error-' + data.statusCode + '.ejs' if (res.template.has(tplSpecial)) tpl = tplSpecial data.headers = Object.keys(data.headers || {}).filter(function (h) { return h !== 'cookie' }).reduce(function (set, h) { set[h] = data.headers[h] return set }, {}) delete data.options res.template(tpl, data, data.statusCode || 500) } } var env = process.env.NODE_ENV function decorate (req, res, config) { // production https can only be https ever. if (config.https && env === 'production') { res.setHeader('strict-transport-security', 1000 * 60 * 60 * 24 * 30 + '') } res.setHeader = function (orig) { return function () { if (res._header) return return orig.apply(this, arguments) }}(res.setHeader) req.model = res.model = new MC templateOptions.debug = config.debug templateOptions.stamp = config.stamp if (config.errorPage) errorPageConf = config.errorPage errorPageConf['*'] = errorHandler if (!logger) { var logOpts = config.log || { name: 'npm-www', level: 'trace' } logger = bunyan.createLogger(logOpts) } // handle unexpected errors relating to this request. // TODO: make this a separate module. var d = domain.create() d.add(req) d.add(res) d.on("error", function (er) { if (er.domainEmitter) { var c = er.domainEmitter.constructor if (c) c = c.name er.domainEmitter = c || '[unknown]' } delete er.domain_emitter delete er.domain logger.error({ error: er }, er.stack) try { if (res.error) res.error(er) else { res.statusCode = 500 res.setHeader('content-type', 'text/plain') res.end('Server Error\n' + er.message) } // don't destroy before sending the error res.on("finish", function () { d.dispose() }) // don't wait forever, though. setTimeout(function () { d.dispose() }, 1000) // disconnect after errors so that a fresh worker can come up. req.client.server.close() } catch (er) { d.dispose() } }) // set up various decorations // TODO: Move some/all of this into a separate module. req.cookies = res.cookies = new Cookies(req, res, config.keys) req.session = res.session = new RedSess(req, res, { keys: config.keys, cookies: req.cookies }) // set up the CouchLogin to automatically save the token in the // session, and log in on demand. req.couch = CouchLogin(config.registryCouch).decorate(req, res) req.couch.strictSSL = false res.template = Templar(req, res, templateOptions) res.template.locals.sanitize = sanitizer.sanitize res.template.locals.canonicalHref = url.resolve( config.canonicalHost, url.parse(req.url).path) // use session token as the csrf protection bit var csrfToken = csrf(req.session.token) res.template.locals.csrfToken = csrfToken res.template.locals.csrf = csrf.html(csrfToken) req.log = res.log = logger.child( { serializers: bunyan.stdSerializers , req_id: crypto.randomBytes(4).toString('hex') , session: req.sessionToken }) res.on('finish', function () { req.log.info({ res: res }) }) // more debugging info. var remoteAddr = req.socket.remoteAddress + ':' + req.socket.remotePort , address = req.socket.address() address = address.address + ':' + address.port req.log.info({req: req, remote: remoteAddr, address: address}) // allow stuff like "req.pathname", etc. var u = url.parse(req.url, true) delete u.auth Object.keys(u).forEach(function (k) { req[k] = u[k] }) res.error = ErrorPage(req, res, errorPageConf) res.redirect = function (target, code) { res.statusCode = code || 302 // strip out \n etc. target = url.format(target) res.setHeader('location', target) var avail = ['text/html', 'application/json'] res.html( '<html><body><h1>Moved' + (code === 302 ? ' Permanently' : '') + '</h1>' + '<a href="' + target + '">' + target + '</a>') } res.send = function (data, status, headers) { res.statusCode = res.statusCode || status if (headers) Object.keys(headers).forEach(function (h) { res.setHeader(h, headers[h]) }) if (!Buffer.isBuffer(data)) data = new Buffer(data) res.setHeader('content-length', data.length) res.end(data) } res.json = res.sendJSON = function (obj, status) { res.send(JSON.stringify(obj), status, {'content-type':'application/json'}) } res.html = res.sendHTML = function (data, status) { res.send(data, status, {'content-type':'text/html'}) } }
// This file was procedurally generated from the following sources: // - src/spread/sngl-err-unresolvable.case // - src/spread/error/member-expr.template /*--- description: Spread operator applied to the only argument when reference is unresolvable (`new` operator) esid: sec-new-operator-runtime-semantics-evaluation es6id: 12.3.3.1 flags: [generated] info: | MemberExpression : new MemberExpression Arguments 1. Return EvaluateNew(MemberExpression, Arguments). 12.3.3.1.1 Runtime Semantics: EvaluateNew 6. If arguments is empty, let argList be an empty List. 7. Else, a. Let argList be ArgumentListEvaluation of arguments. [...] 12.3.6.1 Runtime Semantics: ArgumentListEvaluation ArgumentList : ... AssignmentExpression 1. Let list be an empty List. 2. Let spreadRef be the result of evaluating AssignmentExpression. 3. Let spreadObj be GetValue(spreadRef). 4. Let iterator be GetIterator(spreadObj). 5. ReturnIfAbrupt(iterator). 6.2.3.1 GetValue (V) 1. ReturnIfAbrupt(V). 2. If Type(V) is not Reference, return V. 3. Let base be GetBase(V). 4. If IsUnresolvableReference(V), throw a ReferenceError exception. ---*/ assert.throws(ReferenceError, function() { new function() {}(...unresolvableReference); });
/* * jQuery File Upload Processing Plugin 1.2.2 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2012, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint nomen: true, unparam: true */ /*global define, window */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ '/jquery', './jquery.fileupload' ], factory); } else { // Browser globals: factory( window.jQuery ); } }(function ($) { 'use strict'; var originalAdd = $.blueimp.fileupload.prototype.options.add; // The File Upload Processing plugin extends the fileupload widget // with file processing functionality: $.widget('blueimp.fileupload', $.blueimp.fileupload, { options: { // The list of processing actions: processQueue: [ /* { action: 'log', type: 'debug' } */ ], add: function (e, data) { var $this = $(this); data.process(function () { return $this.fileupload('process', data); }); originalAdd.call(this, e, data); } }, processActions: { /* log: function (data, options) { console[options.type]( 'Processing "' + data.files[data.index].name + '"' ); } */ }, _processFile: function (data) { var that = this, dfd = $.Deferred().resolveWith(that, [data]), chain = dfd.promise(); this._trigger('process', null, data); $.each(data.processQueue, function (i, settings) { var func = function (data) { return that.processActions[settings.action].call( that, data, settings ); }; chain = chain.pipe(func, settings.always && func); }); chain .done(function () { that._trigger('processdone', null, data); that._trigger('processalways', null, data); }) .fail(function () { that._trigger('processfail', null, data); that._trigger('processalways', null, data); }); return chain; }, // Replaces the settings of each processQueue item that // are strings starting with an "@", using the remaining // substring as key for the option map, // e.g. "@autoUpload" is replaced with options.autoUpload: _transformProcessQueue: function (options) { var processQueue = []; $.each(options.processQueue, function () { var settings = {}, action = this.action, prefix = this.prefix === true ? action : this.prefix; $.each(this, function (key, value) { if ($.type(value) === 'string' && value.charAt(0) === '@') { settings[key] = options[ value.slice(1) || (prefix ? prefix + key.charAt(0).toUpperCase() + key.slice(1) : key) ]; } else { settings[key] = value; } }); processQueue.push(settings); }); options.processQueue = processQueue; }, // Returns the number of files currently in the processsing queue: processing: function () { return this._processing; }, // Processes the files given as files property of the data parameter, // returns a Promise object that allows to bind callbacks: process: function (data) { var that = this, options = $.extend({}, this.options, data); if (options.processQueue && options.processQueue.length) { this._transformProcessQueue(options); if (this._processing === 0) { this._trigger('processstart'); } $.each(data.files, function (index) { var opts = index ? $.extend({}, options) : options, func = function () { return that._processFile(opts); }; opts.index = index; that._processing += 1; that._processingQueue = that._processingQueue.pipe(func, func) .always(function () { that._processing -= 1; if (that._processing === 0) { that._trigger('processstop'); } }); }); } return this._processingQueue; }, _create: function () { this._super(); this._processing = 0; this._processingQueue = $.Deferred().resolveWith(this) .promise(); } }); }));
// This file was procedurally generated from the following sources: // - src/accessor-names/literal-string-double-quote.case // - src/accessor-names/default/cls-expr-inst.template /*--- description: Computed values as accessor property names (string literal using double quotes) (Class expression, instance method) esid: sec-runtime-semantics-classdefinitionevaluation es6id: 14.5.14 flags: [generated] info: | [...] 21. For each ClassElement m in order from methods a. If IsStatic of m is false, then i. Let status be the result of performing PropertyDefinitionEvaluation for m with arguments proto and false. 12.2.6.7 Runtime Semantics: Evaluation [...] ComputedPropertyName : [ AssignmentExpression ] 1. Let exprValue be the result of evaluating AssignmentExpression. 2. Let propName be ? GetValue(exprValue). 3. Return ? ToPropertyKey(propName). ---*/ var stringSet; var C = class { get "doubleQuote"() { return 'get string'; } set "doubleQuote"(param) { stringSet = param; } }; assert.sameValue(C.prototype["doubleQuote"], 'get string'); C.prototype["doubleQuote"] = 'set string'; assert.sameValue(stringSet, 'set string');
var CreateServer = require('./create_server'); var SnapshotServer = require('./snapshot_server'); var DestroyServer = require('./destroy_server'); module.exports = function(clientConfig) { var client = require('./client')(clientConfig) return { createServer: CreateServer(client), destroyServer: DestroyServer(client), snapshotServer: SnapshotServer(client) } }
// This file was procedurally generated from the following sources: // - src/annex-b-fns/eval-global-skip-early-err-for.case // - src/annex-b-fns/eval-global/direct-if-stmt-else-decl.template /*--- description: Extension not observed when creation of variable binding would produce an early error (for statement) (IfStatement with a declaration in the second statement position in eval code) esid: sec-functiondeclarations-in-ifstatement-statement-clauses es6id: B.3.4 flags: [generated, noStrict] info: | The following rules for IfStatement augment those in 13.6: IfStatement[Yield, Return]: if ( Expression[In, ?Yield] ) FunctionDeclaration[?Yield] else Statement[?Yield, ?Return] if ( Expression[In, ?Yield] ) Statement[?Yield, ?Return] else FunctionDeclaration[?Yield] if ( Expression[In, ?Yield] ) FunctionDeclaration[?Yield] else FunctionDeclaration[?Yield] if ( Expression[In, ?Yield] ) FunctionDeclaration[?Yield] B.3.3.3 Changes to EvalDeclarationInstantiation [...] ii. If replacing the FunctionDeclaration f with a VariableStatement that has F as a BindingIdentifier would not produce any Early Errors for body, then [...] ---*/ assert.throws(ReferenceError, function() { f; }, 'An initialized binding is not created prior to evaluation'); assert.sameValue( typeof f, 'undefined', 'An uninitialized binding is not created prior to evaluation' ); eval( 'for (let f; ; ) {if (false) ; else function f() { }break;\ }' ); assert.throws(ReferenceError, function() { f; }, 'An initialized binding is not created following evaluation'); assert.sameValue( typeof f, 'undefined', 'An uninitialized binding is not created following evaluation' );
cordova.define('cordova/plugin_list', function(require, exports, module) { module.exports = [ { "file": "plugins/cordova-plugin-splashscreen/www/splashscreen.js", "id": "cordova-plugin-splashscreen.SplashScreen", "clobbers": [ "navigator.splashscreen" ] }, { "file": "plugins/cordova-plugin-inappbrowser/www/inappbrowser.js", "id": "cordova-plugin-inappbrowser.inappbrowser", "clobbers": [ "cordova.InAppBrowser.open", "window.open" ] } ]; module.exports.metadata = // TOP OF METADATA { "cordova-plugin-whitelist": "1.2.2", "cordova-plugin-splashscreen": "3.1.0", "cordova-plugin-inappbrowser": "1.2.1" }; // BOTTOM OF METADATA });
import DoubleEndedQueue from '../../src/queue/DoubleEndedQueue'; import Node from '../../src/Node'; describe('DoubleEndedQueue', () => { let queue = null; beforeEach(() => { queue = new DoubleEndedQueue(); }); describe('dequeueBack()', () => { it('should return null if empty', () => { expect(queue.dequeueBack()).toBeNull(); }); it('should reduce the index, size, and items', () => { queue.enqueueAll([1, 2, 3, 4, 5]); expect(queue.index).toBe(5); expect(queue.size).toBe(5); expect(queue.items).toEqual([ new Node(1), new Node(2), new Node(3), new Node(4), new Node(5) ]); let value = queue.dequeueBack(); expect(value).toBe(5); expect(queue.index).toBe(4); expect(queue.size).toBe(4); expect(queue.items).toEqual([ new Node(1), new Node(2), new Node(3), new Node(4) ]); queue.dequeue(); value = queue.dequeueBack(); expect(value).toBe(4); expect(queue.index).toBe(2); expect(queue.size).toBe(2); expect(queue.items).toEqual([ new Node(2), new Node(3) ]); }); }); describe('dequeueBackAll()', () => { it('should return an array of all values', () => { queue.enqueueAll([1, 2, 3]); expect(queue.size).toBe(3); let values = queue.dequeueBackAll(); expect(queue.size).toBe(0); expect(queue.items).toEqual([]); expect(values).toEqual([3, 2, 1]); }); }); describe('enqueueFront()', () => { it('should add values to the front of the queue', () => { expect(queue.size).toBe(0); expect(queue.items).toEqual([]); queue.enqueueFront(1); expect(queue.size).toBe(1); expect(queue.items).toEqual([ new Node(1) ]); queue.enqueueFront(2); expect(queue.size).toBe(2); expect(queue.items).toEqual([ new Node(2), new Node(1) ]); queue.enqueue(3); expect(queue.size).toBe(3); expect(queue.items).toEqual([ new Node(2), new Node(1), new Node(3) ]); }); it('should error if the capacity is met', () => { queue.capacity = 1; // Testing only queue.enqueueFront(1); expect(queue.size).toBe(1); expect(() => { queue.enqueueFront(2); }).toThrowError('DoubleEndedQueue is full'); }); }); describe('enqueueFrontAll()', () => { it('should add multiple values', () => { expect(queue.size).toBe(0); expect(queue.items).toEqual([]); queue.enqueueFrontAll([1, 2, 3]); expect(queue.size).toBe(3); expect(queue.items).toEqual([ new Node(3), new Node(2), new Node(1) ]); }); }); it('should be usable with strings', () => { queue.enqueueAll(['foo', 'bar', 'baz']); expect(queue.contains('foo')).toBe(true); expect(queue.indexOf('bar')).toBe(1); let value = queue.dequeueBack(); expect(value).toBe('baz'); expect(queue.front()).toBe('foo'); expect(queue.back()).toBe('bar'); }); it('should be usable with objects', () => { let foo = { key: 1, name: 'foo' }, bar = { key: 2, name: 'bar' }, baz = { key: 3, name: 'baz' }, value = null; queue.enqueueFrontAll([foo, bar, baz]); expect(queue.contains(foo)).toBe(true); expect(queue.indexOf(bar)).toBe(1); value = queue.dequeueBack(); expect(value).toBe(foo); expect(queue.front()).toBe(baz); expect(queue.back()).toBe(bar); }); });
// @flow import { createAction } from "redux-actions" export const TOGGLE_EMAIL_PATCH_IN_FLIGHT = "TOGGLE_EMAIL_PATCH_IN_FLIGHT" export const toggleEmailPatchInFlight = createAction( TOGGLE_EMAIL_PATCH_IN_FLIGHT )
var DOCUMENTATION_OPTIONS = { URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), VERSION: '2021.11.31', LANGUAGE: 'None', COLLAPSE_INDEX: false, BUILDER: 'html', FILE_SUFFIX: '.html', LINK_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt', NAVIGATION_WITH_KEYS: true };
/** * @license * Copyright 2019 Google LLC. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * Code distributed by Google as part of this project is also * subject to an additional IP rights grant found at * http://polymer.github.io/PATENTS.txt */ /** * An ordered set of elements. Backed by an Array and a Set. Lookups are backed * by the Set so they are quick, and order is maintained by the Array. Elements * can be added to the OrderedSet multiple times. */ export class OrderedSet { constructor() { this.set = new Set(); this.array = []; } add(element) { this.set.add(element); this.array.push(element); } addAll(other) { other.set.forEach(e => this.set.add(e)); this.array.push(...other.array); } has(element) { return this.set.has(element); } copy() { const copy = new OrderedSet(); copy.addAll(this); return copy; } get length() { return this.array.length; } asSet() { return this.set; } asArray() { return this.array; } } //# sourceMappingURL=ordered-set.js.map
define([ './WeakMap' ], function (WeakMap) { 'use strict'; var callbacks = new WeakMap(), noop = function () {}; function CallbackQueue() { callbacks.set(this, []); } CallbackQueue.prototype = { add: function (callback) { var _callback = { active: true, callback: callback }; callbacks.get(this).push(_callback); callback = null; return { remove: function () { this.remove = noop; _callback.active = false; callback = null; } }; }, drain: function () { var args = Array.prototype.slice.call(arguments), _callbacks = callbacks.get(this), item; callbacks.set(this, []); for (var i = 0, l = _callbacks.length; i < l; i++) { item = _callbacks[i]; if (item && item.active) { item.callback.apply(null, args); } } } }; return CallbackQueue; });
jQuery(function($){ var slider = window.slider = new Slider($('#sliderContainer')); slider.setSize(800, 500); slider.fetchJson('json?count=15'); slider.setTransitionFunction(SliderTransitionFunctions.circles); });
(function() { angular.module('gnucash-reports-view.reports') .directive('gnucashIncomeVsExpense', IncomeVsExpenseDirectiveGenerator); IncomeVsExpenseDirectiveGenerator.$inject = ['colorDefinitions', 'formatters']; function IncomeVsExpenseDirectiveGenerator(colorDefinitions, formatters) { return { restrict: 'E', scope: { reportData: '&' }, templateUrl: 'core/reports/income_vs_expense/income_vs_expenseDirective.html', link: link }; function link($scope) { var data = $scope.reportData(); $scope.options = { chart: { type: 'multiBarChart', height: 450, margin : { top: 20, right: 20, bottom: 100, left: 100 }, x: function(d){return d[0];}, y: function(d){return d[1];}, showControls: false, showValues: true, valueFormat: formatters.currency, stacked: true, transitionDuration: 0, xAxis: { axisLabel: 'Date', tickFormat: formatters.date, rotateLabels: 35, showMaxMin: false }, yAxis: { axisLabel: 'USD', axisLabelDistance: 35, tickFormat: formatters.currencyNoParts } } }; data.expenses.forEach(function(dataValue) { if (dataValue[1] === 0) { // TODO: Figure out how to do this so that it doesn't display as -0.0001 in the graph. dataValue[1] = -0.00001; } }); $scope.data = [ { key : 'Income', bar: true, color: colorDefinitions.credit, values : data.income }, { key : "Expenses" , bar: true, color: colorDefinitions.debit, values : data.expenses } ]; $scope.tableData = data; } } })();
// eslint-disable-next-line import/no-extraneous-dependencies import { action } from '@storybook/addon-actions'; /** * Reduce an array of function names to an object of action that can pass to a component. * @param accumulator Current list of action * @param actionName Name of the new action to add. * @returns {[actionName]: function} */ const actionMaker = (accumulator, actionName) => { const fn = action(actionName); fn.toString = () => actionName; return { ...accumulator, [actionName]: fn }; }; /** * Create a list of story book actions. * @param string[] ...actionNames List of actions * @returns {[actionName]: function} */ const actionListMaker = (...actionNames) => (actionNames.reduce(actionMaker, {})); export default actionListMaker;
(function () { var DD_docs = {}; DD_docs.metricsGuidePage = function () { $('.lang-tab').click(function (e) { var el = $(this); var lang = el.attr('lang'); $('.' + lang + '-lang-tab').tab('show'); }); }; DD_docs.apiPage = function () { // When language buttons are clicked, show all the code snippets // from that language. $('.lang-btn').click(function (e) { var el = $(this); // Find the element currently in the view port var scrollElement; $('div.int-anchor').each( function() { if ($(this).offset().top >= window.scrollY) { scrollElement = $(this); return false; } }); // Highlight the active button. $('.lang-btn').removeClass('active'); el.addClass('active'); // Show this language's code blocks and language-specific elements var lang = el.attr('lang'); $('.code-block').hide(); $('.code-block-' + lang).fadeIn(); $('.lang-specific').hide(); $('.lang-specific-' + lang).fadeIn(); // Scroll to the element that was in the viewport (ie retain location). $('html, body').scrollTop(scrollElement.offset().top); // Add the language selection to the current URL. if (history.pushState) { url = window.location.href.replace(window.location.hash, '').replace(window.location.search, ''); history.pushState(null, null, url + '?lang=' + lang + window.location.hash) } }); }; // Export to global scope. window.DD_docs = DD_docs; // var language = navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage) // var noOverride = window.location.href.indexOf("overridelang") == -1; // if (noOverride) { // if (language.indexOf('ja') > -1 && window.location.pathname.indexOf('/ja/') != 0) { // document.location.href = '/ja' + window.location.pathname; // } else if (language.indexOf('ja') == -1 && window.location.pathname.indexOf('/ja/') == 0) { // document.location.href = window.location.pathname.substring(3); // } // } })(); $(document).ready(function() { $('#tipue_search_input').tipuesearch(); }); // Allow language selection via URL GET parameter. $(window).load(function() { if (s = window.location.search.match(/lang=[^&]+/gi)) { lang = s[0].replace(/lang=/gi, ''); $('div[lang="' + lang + '"]').click(); } });
// @flow /* global SETTINGS */ import { assert } from "chai" import sinon from "sinon" import { getHLSEncodedUrl, videoIsProcessing, videoHasError, saveToDropbox } from "./video" import { makeVideo } from "../factories/video" import { makeVideoFileName } from "./urls" import { VIDEO_STATUS_CREATED, VIDEO_STATUS_UPLOADING, VIDEO_STATUS_UPLOAD_FAILED, VIDEO_STATUS_TRANSCODING, VIDEO_STATUS_TRANSCODE_FAILED_INTERNAL, VIDEO_STATUS_TRANSCODE_FAILED_VIDEO, VIDEO_STATUS_COMPLETE, VIDEO_STATUS_ERROR, ENCODING_HLS } from "../constants" describe("video library functions", () => { let video beforeEach(() => { video = makeVideo() }) describe("getHLSEncodedUrl", () => { it("finds an HLS encoded video", () => { assert.equal( getHLSEncodedUrl(video), // $FlowFixMe: Flow thinks this is undefined. Go home Flow, you're drunk, this is a test. video.videofile_set.find( videofile => videofile.encoding === ENCODING_HLS ).cloudfront_url ) }) it("returns null if there is not an HLS encoded video", () => { video.videofile_set.forEach(file => { file.encoding = "original" }) assert.isNull(getHLSEncodedUrl(video)) }) }) describe("videoIsProcessing", () => { [ [VIDEO_STATUS_CREATED, true], [VIDEO_STATUS_UPLOADING, true], [VIDEO_STATUS_UPLOAD_FAILED, false], [VIDEO_STATUS_TRANSCODING, true], [VIDEO_STATUS_TRANSCODE_FAILED_INTERNAL, false], [VIDEO_STATUS_TRANSCODE_FAILED_VIDEO, false], [VIDEO_STATUS_COMPLETE, false], [VIDEO_STATUS_ERROR, false] ].forEach(([status, bool]) => { it(`should return ${String(bool)} for ${status}`, () => { video.status = status assert.equal(videoIsProcessing(video), bool) }) }) }) describe("videoHasError", () => { [ [VIDEO_STATUS_CREATED, false], [VIDEO_STATUS_UPLOADING, false], [VIDEO_STATUS_UPLOAD_FAILED, true], [VIDEO_STATUS_TRANSCODING, false], [VIDEO_STATUS_TRANSCODE_FAILED_INTERNAL, true], [VIDEO_STATUS_TRANSCODE_FAILED_VIDEO, true], [VIDEO_STATUS_COMPLETE, false], [VIDEO_STATUS_ERROR, true] ].forEach(([status, bool]) => { it(`should return ${String(bool)} for ${status}`, () => { video.status = status assert.equal(videoHasError(video), bool) }) }) }) describe("uploadToDropbox", () => { it("calls the Dropbox API with correct arguments", () => { SETTINGS.cloudfront_base_url = "http://asdasldk.cloudfront.net/" const sandbox = sinon.createSandbox() window.Dropbox = { save: () => {} } const dropboxStub = sandbox.stub(window.Dropbox, "save") saveToDropbox(video) sinon.assert.calledWith( dropboxStub, `${SETTINGS.cloudfront_base_url}${video.key}/video.mp4`, makeVideoFileName(video, "mp4") ) }) }) })
define([ '../node!fs-extra', '../node!mkdirp', 'dojo/Deferred'], function (fs, mkdirp, Deferred) { /* * Code in this module is forked from https://github.com/kitsonk/setten */ var asDeferred = function (fn, self, noError) { // summary: // Converts a function that utilises a callback and converts it into a dojo/Deferred that resolves with // either a single argument or an array of arguments that would have been passed to the callback. // fn: Function // The function to convert into a function that returns a dojo/Deferred. // self: Object // The object to use as scope when invoking the function. Typically the object which the function // belongs to. Defaults to `this` if not passed. // noError: Boolean // If the callback does not have an err value as the first argument passed to the callback. // returns: dojo/promise/Promise self = self || this; return noError ? function () { var dfd = new Deferred(), args = Array.prototype.slice.call(arguments); args.push(function () { var a = Array.prototype.slice.call(arguments); dfd.resolve(a.length > 1 ? a : a.length ? a[0] : null); }); fn.apply(self, args); return dfd.promise; } : function () { var dfd = new Deferred(), args = Array.prototype.slice.call(arguments); args.push(function () { var a = Array.prototype.slice.call(arguments), err = a.shift(); if (err) { dfd.reject(err); } else { dfd.resolve(a.length > 1 ? a : a.length ? a[0] : null); } }); fn.apply(self, args); return dfd.promise; }; }; var dfs = {}, singleArgFunctions = ['exists']; // Iterate through each property of the module for (var f in fs) { if (typeof fs[f] === 'function' && !/(^[_A-Z]|^create|^(un)?watch|Sync$)/.test(f)) { // It is something we want to convert dfs[f] = asDeferred(fs[f], fs, ~singleArgFunctions.indexOf(f)); // Create a deferred } else { dfs[f] = fs[f]; // Leave alone } } dfs['mkdirp'] = asDeferred(mkdirp, mkdirp); dfs['mkdirpSync'] = mkdirp.sync; return dfs; });
var classwblut_1_1geom_1_1_w_b___binary_grid3_d = [ [ "WB_BinaryGrid3D", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#a6586e47f046c00cb93d0e5c9b0bf59bf", null ], [ "clear", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#a9c2b252e4fab4765a56570a35f417552", null ], [ "createGrid", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#ae8ab605bf137a84ea6b38e0a626177b8", null ], [ "get", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#ac2bbadf4616ae09e9361ffb4de4925f5", null ], [ "getCenter", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#a99c8decfd9f313cb8906ed06d9f5e772", null ], [ "getDX", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#a6b148b95ece9d4a7001b221675123906", null ], [ "getDY", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#af8a9c22c177d10e8290341c6a7bb3736", null ], [ "getDZ", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#a4a06d0469e70d5b21c9d2c4f6fa21e0b", null ], [ "getMin", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#ade3670ffac3a32415a2d84be20ee94b1", null ], [ "getSizeX", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#a7cb0f67dda0288d40f0386b54aed73bf", null ], [ "getSizeY", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#ad2521aabb4bfdbf23ab97735b12fef44", null ], [ "getSizeZ", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#afb31720fd2db1fea6739f30db546bf7a", null ], [ "set", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#a11bda7cf56b5b93f5c8e5015cf035550", null ], [ "setCenter", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#a6e1e34d17e9d927dace9236a5f6206f1", null ], [ "setDX", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#ae87a1b88ae05574d5db9d12372018673", null ], [ "setDY", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#a8c0440dcf2f0939200e074a4fa66d5ab", null ], [ "setDZ", "classwblut_1_1geom_1_1_w_b___binary_grid3_d.html#ac8688253e235773add0c258e59f2a8e1", null ] ];
/** * @copyright 2010-2017, The Titon Project * @license http://opensource.org/licenses/BSD-3-Clause * @link http://titon.io * @flow */ import React from 'react'; import Input from './Input'; import style from '../../styler'; import { INPUT_CLASSES } from './types'; import type { InputProps } from './types'; export function ToolkitTextarea(props: InputProps) { return ( <Input {...props} type="textarea" /> ); } export default style({ ...INPUT_CLASSES, input: 'input input-textarea', })(ToolkitTextarea);
'use strict' const http = require('http') const https = require('https') const request = require('./request') const url = require('url') class Client { constructor (options = {}) { if (typeof options === 'string') { options = url.parse(options) } options.path = options.path || '/' if (options.agent == null) { if (options.protocol === 'https:') { options.agent = new https.Agent({ // Enable keep-alive connections keepAlive: true, // Pass through the TLS options pfx: options.pfx, key: options.key, passphrase: options.passphrase, cert: options.cert, ca: options.ca, ciphers: options.ciphers, rejectUnauthorized: !(options.rejectUnauthorized === false), secureProtocol: options.secureProtocol, servername: options.servername }) } else { options.agent = new http.Agent({keepAlive: true}) } } this._options = options } close () { this._options.agent.destroy() } create (resource, override, callback) { if (typeof override === 'function') { callback = override override = null } const options = Object.assign({}, this._options, override) options.method = 'POST' options.path = url.resolve(options.path, resource.resourceType) request(options, resource, callback) } update (resource, override, callback) { if (typeof override === 'function') { callback = override override = null } const options = Object.assign({}, this._options, override) options.method = 'PUT' options.path = url.resolve(options.path, `${resource.resourceType}/${resource.id}`) request(options, resource, callback) } read (resourceType, id, override, callback) { if (typeof override === 'function') { callback = override override = null } const options = Object.assign({}, this._options, override) options.method = 'GET' options.path = url.resolve(options.path, `${resourceType}/${id}`) request(options, callback) } vread (resourceType, id, versionId, override, callback) { if (typeof override === 'function') { callback = override override = null } const options = Object.assign({}, this._options, override) options.method = 'GET' options.path = url.resolve(options.path, `${resourceType}/${id}/_history/${versionId}`) request(options, callback) } delete (resourceType, id, override, callback) { if (typeof override === 'function') { callback = override override = null } const options = Object.assign({}, this._options, override) options.method = 'DELETE' options.path = url.resolve(options.path, `${resourceType}/${id}`) request(options, callback) } transaction (bundle, override, callback) { if (typeof override === 'function') { callback = override override = null } const options = Object.assign({}, this._options, override) options.method = 'POST' request(options, bundle, callback) } search (resourceType, query, override, callback) { if (typeof override === 'function') { callback = override override = null } const options = Object.assign({}, this._options, override) options.method = 'GET' options.path = url.format({ pathname: url.resolve(options.path, resourceType), query }) request(options, callback) } } module.exports = exports = Client
/*global beforeEach, describe, it, assert, expect */ 'use strict'; describe('Modal View', function () { beforeEach(function () { this.ModalView = new Air.Views.Modal(); }); });
var Settings = { timeout: null, /** * Loads the settings */ registerSettings : function() { // Nanoscroller this.nanoscroller(); // Tracks input change event this.inputChange(); }, flushCache : function() { $("#flush_cache").click(function(e) { e.preventDefault(); // Self var self = this, ciims = CiiMSDashboard.getAuthData(); $.ajax({ url: Settings.getRoute() + "/flushcache", type: 'GET', headers: CiiMSDashboard.getRequestHeaders(), beforeSend: function() { $("#nav-icon").removeClass("fa-ellipsis-v"); if ($("#nav-icon").find("span").length == 0) { var element = $("<span>").addClass("fa fa-spinner fa-spin active"); $("#nav-icon").append($(element)); } $("legend").parent().find(".alert").remove(); }, complete: function() { setTimeout(function() { $("#nav-icon").addClass("fa-ellipsis-v"); $("#nav-icon").find("span").remove(); }, 1000); } }); return false; }); }, /** * Tests email connection settings */ testEmailSettings : function() { $("a#testEmailSettings").click(function(e) { e.preventDefault(); // Self var self = this, ciims = CiiMSDashboard.getAuthData(); $.ajax({ url: Settings.getRoute() + "test", type: 'GET', headers: CiiMSDashboard.getRequestHeaders(), beforeSend: function() { $("#nav-icon").removeClass("fa-ellipsis-v"); if ($("#nav-icon").find("span").length == 0) { var element = $("<span>").addClass("fa fa-spinner fa-spin active"); $("#nav-icon").append($(element)); } $("legend").parent().find(".alert").remove(); }, error: function(data) { var json = $.parseJSON(data.responseText), message = json.message, alert = $("<div>").addClass("alert alert-error"); alert.html(message); $("legend").after($(alert)); }, success: function(json, textStatus, jqXHR) { var message = json.message, alert = $("<div>").addClass("alert alert-success"); alert.html(message); $("legend").after($(alert)); }, complete: function() { setTimeout(function() { $("#nav-icon").addClass("fa-ellipsis-v"); $("#nav-icon").find("span").remove(); }, 1000); } }); return false; }); }, /** * Change event tracking */ inputChange : function() { var self = this; $("form :input").change(function() { self.changeEvent(); }); $("form :input").keyup(function() { self.changeEvent(); }); }, changeEvent : function() { // Self var self = this, ciims = CiiMSDashboard.getAuthData(); // Clears the previously set timeout clearTimeout(this.timeout); // Sets the timeout this.timeout = setTimeout(function() { $.ajax({ url: self.getRoute(), data: self.getAttributes(), type: 'POST', headers: CiiMSDashboard.getRequestHeaders(), beforeSend: function() { $("#nav-icon").removeClass("fa-ellipsis-v"); if ($("#nav-icon").find("span").length == 0) { var element = $("<span>").addClass("fa fa-spinner fa-spin active"); $("#nav-icon").append($(element)); } }, complete: function() { setTimeout(function() { $("#nav-icon").addClass("fa-ellipsis-v"); $("#nav-icon").find("span").remove(); }, 1000); } }); }, 500); }, /** * Retrieves the appropriate route * @return string */ getRoute : function() { var origin = window.location.origin, uri = window.location.pathname, path = uri.split('/'), controller = path[2].singularize(); path[1] = 'api'; path[2] = controller; return path.join("/"); }, /** * Triggers the nanoscroller * @return nanoScroller */ nanoscroller : function() { return $(".nano").nanoScroller({ iOSNativeScrolling: true }); }, /** * Retrieves the settings form attributes * @return Object */ getAttributes : function() { var inputs = $("form :input"), values = {}; $(inputs).each(function() { if ($(this).attr("type") == "checkbox") values[this.name] = $(this).prop('checked') == true ? 1 : 0; else values[this.name] = $(this).val(); }); return values; } };
// Generated by CoffeeScript 1.9.3 (function() { "use strict"; var Dict, Handlebars, _, marked; Handlebars = require('handlebars'); _ = require('./util'); marked = require('marked'); Dict = require('collections/dict'); module.exports = { _template_cache: new Dict(), compile_template: function(content, _imports) { var template; _imports = _imports || { _: _ }; template = Handlebars.compile(content); return function(context) { var _tmpl, result; result = template(context); _tmpl = _.template(result, { imports: _imports }); return _tmpl(context); }; }, get_compiled_template: function(template) { var render; if (_.isFunction(template)) { render = template; } else { if (this._template_cache.has(template)) { render = When(_template_cache.get(template)); } else { render = this.compile_template(template); } } return render; }, render_template: function(template, context) { var render; render = this.get_compiled_template(template); return render(context); }, convert_markdown_to_html: function(text) { return marked(text); } }; }).call(this); //# sourceMappingURL=templates.js.map
(function(){ /** * Object Bubble() * Defines a plugin that takes the responsibility to manage bubble * @param {Object} config */ JenScript.Bubble = function(config) { this.init(config); }; JenScript.Model.inheritPrototype(JenScript.Bubble, JenScript.Plugin); JenScript.Model.addMethods(JenScript.Bubble, { /** * Initialize Bubble * Defines bubble * @param {Object} config */ init : function(config){ config = config || {}; config.priority = 100; this.Id = 'bubble'+JenScript.sequenceId++; this.center = (config.center !== undefined)?config.center : new JenScript.Point2D(0,0); this.radius = (config.radius !== undefined)?config.radius : 50; this.fillColor = (config.fillColor !== undefined)?config.fillColor : 'black'; this.fillOpacity = (config.fillOpacity !== undefined)?config.fillOpacity : 1; this.strokeColor = config.strokeColor; this.strokeWidth = (config.strokeWidth !== undefined)?config.strokeWidth : 1; this.strokeOpacity = (config.strokeOpacity !== undefined)?config.strokeOpacity : 1; }, /** * get bubble center in user coordiante * @returns bubble center */ getCenter : function(){ return this.center; }, /** * set bubble center in user coordinate * @param {Object} bubble center */ setCenter : function(center){ this.center = center; }, /** * get bubble radius in pixel * @returns bubble radius */ getRadius : function(){ return this.radius; }, /** * set bubble radius in pixel * @param {Number} bubble radius */ setRadius : function(radius){ this.radius = radius; }, /** * equals bubble if this bubble id match with the given bubble o * @param {Object} o */ equals : function(o){ if(!(o instanceof JenScript.Bubble)) return false; if(o.Id === this.Id) return true; } }); })();
console.log('Launching app..') import React from 'react' import ReactDOM from 'react-dom' import {Route, Router} from 'react-router' import {Provider} from 'react-redux' import store from 'lib/store/store' import Homepage from 'lib/home' import 'css/main.less!less' import { useRouterHistory } from 'react-router' import { createHashHistory } from 'history' const appHistory = useRouterHistory(createHashHistory)({ queryKey: false }) ReactDOM.render( <Provider store={store}> <Router history={appHistory}> <Route path='/' component={Homepage}/> </Router> </Provider>, document.getElementById('react-div'))
var MoonCalc = require('./mooncalc'), t = require('tape'); t.test('test data for day', function (t) { var date = new Date('2014-04-29'); t.equal( JSON.stringify(MoonCalc.datasForDay(date)), JSON.stringify({ 'date' : { 'year' : 2014, 'month' : 4, 'day' : 29 }, 'age' : 29.5157733025988, 'distance' : 382220.74996379716, 'ecliptic' : { 'latitude' : -0.7738569272648606, 'longitude': 41.595918875627774 }, 'phase' : 'NEW', 'trajectory' : 'ascendent', 'constellation' : 'Aries' }) ); t.end(); });
/** * Test stubs to mirror available global variables. * Those variables usually come from the back-end via templates. * See /wagtailadmin/templates/wagtailadmin/admin_base.html. */ import 'element-closest'; global.wagtailConfig = { ADMIN_API: { DOCUMENTS: '/admin/api/main/documents/', IMAGES: '/admin/api/main/images/', PAGES: '/admin/api/main/pages/', EXTRA_CHILDREN_PARAMETERS: '', }, ADMIN_URLS: { PAGES: '/admin/pages/', }, DATE_FORMATTING: { DATE_FORMAT: 'MMM. D, YYYY', SHORT_DATE_FORMAT: 'DD/MM/YYYY', }, STRINGS: { DELETE: 'Delete', EDIT: 'Edit', PAGE: 'Page', PAGES: 'Pages', LOADING: 'Loading…', NO_RESULTS: 'No results', SERVER_ERROR: 'Server Error', SEE_ALL: 'See all', CLOSE_EXPLORER: 'Close explorer', ALT_TEXT: 'Alt text', DECORATIVE_IMAGE: 'Decorative image', WRITE_HERE: 'Write here…', HORIZONTAL_LINE: 'Horizontal line', LINE_BREAK: 'Line break', UNDO: 'Undo', REDO: 'Redo', RELOAD_PAGE: 'Reload the page', RELOAD_EDITOR: 'Reload saved content', SHOW_LATEST_CONTENT: 'Show latest content', SHOW_ERROR: 'Show error', EDITOR_CRASH: 'The editor just crashed. Content has been reset to the last saved version.', BROKEN_LINK: 'Broken link', MISSING_DOCUMENT: 'Missing document', CLOSE: 'Close', EDIT_PAGE: 'Edit \'{title}\'', VIEW_CHILD_PAGES_OF_PAGE: 'View child pages of \'{title}\'', PAGE_EXPLORER: 'Page explorer', SAVE: 'Save', SAVING: 'Saving...', CANCEL: 'Cancel', DELETING: 'Deleting...', ADD_A_COMMENT: 'Add a comment', SHOW_COMMENTS: 'Show comments', REPLY: 'Reply', RESOLVE: 'Resolve', RETRY: 'Retry', DELETE_ERROR: 'Delete error', CONFIRM_DELETE_COMMENT: 'Are you sure?', SAVE_ERROR: 'Save error', SAVE_COMMENT_WARNING: 'This will be saved when the page is saved', FOCUS_COMMENT: 'Focus comment', UNFOCUS_COMMENT: 'Unfocus comment', SAVE_PAGE_TO_ADD_COMMENT: 'Save the page to add this comment', SAVE_PAGE_TO_SAVE_COMMENT_CHANGES: 'Save the page to save this comment', SAVE_PAGE_TO_SAVE_REPLY: 'Save the page to save this reply', TOGGLE_SIDEBAR: 'Toggle sidebar', MAIN_MENU: 'Main menu', }, WAGTAIL_I18N_ENABLED: true, LOCALES: [ { code: 'en', display_name: 'English' }, { code: 'fr', display_nam: 'French' } ], ACTIVE_LOCALE: 'en' }; global.wagtailVersion = '1.6a1'; global.wagtail = {}; global.chooserUrls = { documentChooser: '/admin/documents/chooser/', emailLinkChooser: '/admin/choose-email-link/', anchorLinkChooser: '/admin/choose-anchor-link', embedsChooser: '/admin/embeds/chooser/', externalLinkChooser: '/admin/choose-external-link/', imageChooser: '/admin/images/chooser/', pageChooser: '/admin/choose-page/', }; /* use dummy content for onload handlers just so that we can verify that we've chosen the right one */ global.IMAGE_CHOOSER_MODAL_ONLOAD_HANDLERS = { type: 'image' }; global.PAGE_CHOOSER_MODAL_ONLOAD_HANDLERS = { type: 'page' }; global.EMBED_CHOOSER_MODAL_ONLOAD_HANDLERS = { type: 'embed' }; global.DOCUMENT_CHOOSER_MODAL_ONLOAD_HANDLERS = { type: 'document' };
import { EOrientation } from '../interfaces'; import { ALayoutContainer } from './ALayoutContainer'; import { ASequentialLayoutContainer } from './ASequentialLayoutContainer'; export class LineUpLayoutContainer extends ASequentialLayoutContainer { constructor(document, options, ...children) { super(document, options); this.minChildCount = 1; this.type = 'lineup'; this.node.dataset.layout = 'lineup'; if (this.options.stackLayout) { this.node.dataset.mode = 'stacked'; } children.forEach((d) => this.push(d)); } place(child, reference, area) { console.assert(area !== 'center'); const index = this._children.indexOf(reference) + (area === 'right' || area === 'bottom' ? 1 : 0); return this.push(child, index); } addedChild(child, index) { super.addedChild(child, index); if (index < 0 || index >= (this._children.length - 1)) { //+1 since we already chanded the children this.node.appendChild(ASequentialLayoutContainer.wrap(child)); } else { this.node.insertBefore(ASequentialLayoutContainer.wrap(child), this.node.children[index]); } if (this.options.stackLayout) { if (this.options.orientation === EOrientation.HORIZONTAL) { child.node.parentElement.style.minWidth = child.minSize[0] > 0 ? `${child.minSize[0]}px` : null; // set minSize if available or delete CSS property } else { child.node.parentElement.style.minHeight = child.minSize[1] > 0 ? `${child.minSize[1]}px` : null; } } child.visible = this.visible; } takeDownChild(child) { this.node.removeChild(child.node.parentElement); this.node.dataset.mode = ''; super.takeDownChild(child); } persist() { return Object.assign(super.persist(), { type: 'lineup', stackLayout: this.options.stackLayout }); } static restore(dump, restore, doc) { const options = Object.assign(ALayoutContainer.restoreOptions(dump), { orientation: EOrientation[dump.orientation], stackLayout: dump.stackLayout }); const r = new LineUpLayoutContainer(doc, options); dump.children.forEach((d) => r.push(restore(d))); return r; } static derive(node, derive) { const children = Array.from(node.children); console.assert(children.length >= 1); const deriveOrientation = () => { if (node.dataset.layout.startsWith('v') || (node.dataset.orientation && node.dataset.orientation.startsWith('v'))) { return EOrientation.VERTICAL; } return EOrientation.HORIZONTAL; }; const options = Object.assign(ALayoutContainer.deriveOptions(node), { orientation: deriveOrientation(), stackLayout: node.dataset.mode === 'stacked' || node.dataset.layout.endsWith('stack') }); const r = new LineUpLayoutContainer(node.ownerDocument, options); children.forEach((c) => r.push(derive(c))); return r; } defaultOptions() { return Object.assign(super.defaultOptions(), { stackLayout: false }); } } //# sourceMappingURL=LineUpLayoutContainer.js.map
var app = require('./example'); var req = require('supertest'); exports['express-alias'] = { // verify the root route works by itself: before: function (next) { req(app) .get('/') .expect(200, 'hello world') .end(next); }, 'should redirect, using Express’s default of 302': function (next) { req(app) .get('/alias') .expect(302) .expect('Location', '/') .end(next); }, 'should redirect, allowing other status codes': function (next) { req(app) .get('/alias/301') .expect(301) .expect('Location', '/') .end(next); } };
import React from 'react'; import ReactDOM from 'react-dom'; import Note from './index.js'; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<Note />, div); ReactDOM.unmountComponentAtNode(div); });
var View = require ('ampersand-view'); var templates = require ('../templates'); var mapview = require ('../views/map-view'); var Collection = require ('../collections/map-collection.js'); var data = new Collection (); module.exports = View.extend ({ initialize: function () { console.log ('In map.intialize'); data.fetch (); }, template: templates.pages.map, render: function () { this.renderWithTemplate (this); console.log ('In map.render'); var myMapview = new mapview ({ collection:data }); myMapview.render (); } });
exports.up = async (knex) => { await knex.schema.createTableIfNotExists("transitions", (table) => { table.increments(); table.string("name").notNullable(); table.integer("time"); table.integer("x"); table.integer("y"); table.integer('user_id').unsigned(); table.foreign('user_id').references('users.id'); table.timestamps(true, true); }); await knex("transitions").insert([ { name: "IT 1", time: 3, x: 300, y: 100, user_id: 1 }, { name: "IT 2", time: 12, x: 300, y: 200, user_id: 1 }, { name: "IT 3", time: 66, x: 300, y: 300, user_id: 1 }, { name: "IT 4", time: 22, x: 300, y: 400, user_id: 1 }, { name: "IT 5", time: 77, x: 300, y: 500, user_id: 1 }, { name: "IT 6", time: 10, x: 300, y: 600, user_id: 1 }, { name: "CT 1", time: 13, x: 700, y: 200, user_id: 1 }, { name: "CT 2", time: 13, x: 700, y: 350, user_id: 1 }, { name: "CT 3", time: 8, x: 700, y: 500, user_id: 1 }, { name: "PT 1", time: 4, x: 1050, y: 200, user_id: 1 }, { name: "PT 2", time: 5, x: 1050, y: 350, user_id: 1 }, { name: "PT 3", time: 6, x: 1050, y: 500, user_id: 1 }, { name: "ST 1", time: 26, x: 1450, y: 100, user_id: 1 }, { name: "ST 2", time: 20, x: 1450, y: 250, user_id: 1 }, { name: "ST 3", time: 22, x: 1450, y: 400, user_id: 1 }, { name: "ST 4", time: 35, x: 1450, y: 550, user_id: 1 }, { name: "RT 1", time: 35, x: 1450, y: 700, user_id: 1 }, { name: "RT 2", time: 35, x: 1450, y: 850, user_id: 1 }, { name: "RT 3", time: 35, x: 1450, y: 1000, user_id: 1 } ]); }; exports.down = async (knex) => { await knex.schema.dropTableIfExists("transitions"); };
/* eslint-env node */ module.exports = function(/*env*/) { return { port: 3000, host: 'localhost', historyApiFallback: true, compress: true, debug: true, disableHostCheck: true, stats: { colors: true } }; };
import React from 'react'; const ToCCOPPA = () =>{ return ( <li> <h3><a href="#coppa">Children Online Privacy Protection Act (COPPA)</a></h3> <ul> <li><a href="#child-information">Child information</a></li> <li><a href="#child-information-deletion">Removing your child's information</a></li> </ul> </li> ) }; export default ToCCOPPA;
/* TL.Media.SoundCloud ================================================== */ TL.Media.SoundCloud = TL.Media.extend({ includes: [TL.Events], /* Load the media ================================================== */ _loadMedia: function() { var api_url, self = this; // Create Dom element this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-iframe tl-media-soundcloud tl-media-shadow", this._el.content); // Get Media ID this.media_id = this.data.url; // API URL api_url = "https://soundcloud.com/oembed?url=" + this.media_id + "&format=js&callback=?" // API Call TL.getJSON(api_url, function(d) { self.createMedia(d); }); }, createMedia: function(d) { this._el.content_item.innerHTML = d.html; // After Loaded this.onLoaded(); } });
16 gid=32753351 18 uid=1520560311 20 ctime=1321817496 20 atime=1321817504 38 LIBARCHIVE.creationtime=1321815762 24 SCHILY.dev=234881029 23 SCHILY.ino=16405104 18 SCHILY.nlink=1
/** * Decide what support block app should show * */ module.exports = cdb.core.View.extend({ initialize: function() { this.user = this.options.user; this.template = cdb.templates.getTemplate('common/views/support_banner'); }, render: function() { this.$el.html( this.template({ userType: this._getUserType() }) ) return this; }, _getUserType: function() { var accountType = this.user.get('account_type').toLowerCase(); // Get user type if (this.user.isInsideOrg()) { return 'org'; } else if (accountType === "internal" || accountType === "partner" || accountType === "ambassador") { return 'internal' } else if (accountType !== "free") { return 'client'; } else { return 'regular' } } });
import path from 'path'; import webpack from 'webpack'; import MiniCssExtractPlugin from 'mini-css-extract-plugin'; export default class Compile { constructor(cliPath, appPath, target, env) { const envDefines = env.defines ? env.defines : {}; const nodeModules = env.nodeModules ? env.nodeModules : 'node_modules'; const es6Modules = env.es6Modules ? env.es6Modules : {}; const es6ModulesRegex = Object.keys(es6Modules).map(e => { return new RegExp(e, 'i'); }); // this is used to hack around the fact that there is no 'mainDir' support // for npm packages, thus it is hard to compile es6 only modules without // explictly providing a src folder, which in fact the client can provide us. // reference: https://github.com/nodejs/node/issues/14970 const es6ModuleAliases = {}; for (const es6Module in es6Modules) { const relPath = es6Modules[es6Module] === '/' ? '' : es6Modules[es6Module]; es6ModuleAliases[es6Module] = `${es6Module}${relPath}`; } const exclude = modulePath => { return ( /node_modules/.test(modulePath) && !es6ModulesRegex.some(e => e.test(modulePath)) ); }; const defines = { 'process.env': { NODE_ENV: JSON.stringify(target), }, }; for (const envDefine in envDefines) { defines[envDefine] = JSON.stringify(envDefines[envDefine]); } this.config = { mode: target, context: appPath, // used to resolve webpack's loader packages. of course the // modules folder should be the path of the cliPath. also support // installation via yarn in which the node_modules of this package // are installed into the parent folder resolveLoader: { modules: [ path.resolve(cliPath, 'node_modules'), path.resolve(cliPath, '../'), ], extensions: ['.js', '.json'], mainFields: ['loader', 'main'], }, // needed in the case of, for example, external modules which // are not bundled, and therefore have to have their modules // resolved somehow... resolve: { extensions: ['*', '.js'], modules: [ path.resolve(cliPath, 'node_modules'), path.resolve(cliPath, '../'), path.resolve(appPath, 'node_modules'), path.resolve(appPath, nodeModules), ], alias: es6ModuleAliases, }, module: { rules: [ { test: /\.js(x)?$/, exclude, use: { loader: 'babel-loader', options: this.getBabelLoaderOptions(env), }, }, { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, 'css-loader?importLoaders=true&localIdentName=[name]_[local]_[hash:base64:3]', 'postcss-loader', 'sass-loader', ], }, { test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=10000', }, { test: /\.(ttf|eot)(\?[\s\S]+)?$/, loader: 'file-loader', }, { test: /\.svg$/, loader: 'url-loader?limit=10000', }, { test: /\.png$/, loader: 'url-loader?limit=10000', query: { mimetype: 'image/png' }, }, { test: /favicon.ico$/, loader: 'file-loader', options: { name: '[name].[ext]', publicPath: '/', }, }, { test: /\.(jpg)$/, loaders: ['url-loader?limit=10000'], }, ], }, plugins: [ new MiniCssExtractPlugin({ filename: '[name].css', chunkFilename: '[id].css', }), new webpack.DefinePlugin(defines), ], }; } getConfig() { return this.config; } getBabelLoaderOptions(env) { const plugins = [ require.resolve('@babel/plugin-syntax-export-default-from'), require.resolve('@babel/plugin-transform-react-display-name'), require.resolve('@babel/plugin-proposal-class-properties'), [ require.resolve('babel-plugin-styled-components'), { ssr: true, displayName: true, }, ], ]; // only add react hot loading if we are building an isomorphic app // which implies there is a client/server combination present if (env.entry.client && env.entry.server) { plugins.push(require.resolve('react-hot-loader/babel')); } return { presets: [], plugins, cacheDirectory: true, }; } run() { return new Promise((resolve, reject) => { const compileInstance = webpack(this.config); compileInstance.run((err, stats) => { if (err) reject(err); resolve(stats); }); }); } }
import uniqueId from 'lodash/uniqueId' import is from 'utils/is' import { TabStateScope } from 'commons/Tab' import config from 'config' const { Tab: BaseTab, TabGroup: BaseTabGroup, state } = TabStateScope() state.keepOne = config.isLib class Tab extends BaseTab { constructor (props = {}) { super() this.id = is.undefined(props.id) ? uniqueId('tab_') : props.id state.tabs.set(this.id, this) } } class TabGroup extends BaseTabGroup { constructor (props = {}) { super() this.id = is.undefined(props.id) ? uniqueId('tab_group_') : props.id state.tabGroups.set(this.id, this) } } export default state export { Tab, TabGroup, state }
/* * grunt-readme * https://github.com/phadej/grunt-readme * * Copyright (c) 2013 Oleg Grenrus * Licensed under the BSD3 license. */ "use strict"; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ "Gruntfile.js", "tasks/*.js", ], options: { jshintrc: ".jshintrc", }, }, // Configuration to be run (and then tested). literate: { "README.md": "tasks/literate.js", "demo1": { src: "tasks/literate.js", dest: "tasks-literate-js.md", options: { code: true, }, }, }, bfdocs: { documentation: { options: { title: "Grunt literate", manifest: { files: [ "README.md" ], }, dest: "documentation/", theme: "default", } } }, }); // Actually load this plugin's task(s). grunt.loadTasks("tasks"); // These plugins provide necessary tasks. grunt.loadNpmTasks("grunt-contrib-jshint"); grunt.loadNpmTasks("grunt-beautiful-docs"); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. // grunt.registerTask('test', ['clean', 'readme', 'nodeunit']); // Docs task grunt.registerTask("docs", ["literate", "bfdocs"]); // By default, lint and run all tests. grunt.registerTask("default", ["jshint"]); };
var Backbone = require('backbone'); var UserTablesModel = require('dashboard/data/user-tables-model'); describe('dashboard/data/user-tables-model', function () { var model; beforeEach(function () { spyOn(UserTablesModel.prototype, 'fetch'); var userModel = new Backbone.Model({ base_url: 'http://wadus.com' }); model = new UserTablesModel(null, { userModel: userModel }); }); it('throws an error when base_url is missing', function () { model = function () { return new UserTablesModel(null, {}); }; expect(model).toThrowError('userModel is required'); }); describe('._initBinds', function () { it('sets stateModel to fetched on sync', function () { expect(model.stateModel.get('status')).toEqual('fetching'); model.trigger('sync'); expect(model.stateModel.get('status')).toEqual('fetched'); }); it('sets stateModel to errored on error', function () { expect(model.stateModel.get('status')).toEqual('fetching'); model.trigger('error'); expect(model.stateModel.get('status')).toEqual('errored'); }); describe('when paramsModel change:q', function () { it('sets stateModel to fetching', function () { model.paramsModel.set({ q: 'wubalubadubdub' }); expect(model.stateModel.get('status')).toEqual('fetching'); }); it('calls .fetch', function () { model.paramsModel.set({ q: 'wubalubadubdub' }); expect(model.fetch).toHaveBeenCalled(); }); }); }); describe('.url', function () { it('sets the default params in the url', function () { var defaultUrl = 'http://wadus.com/api/v1/viz?tag_name=&q=&page=1&type=&exclude_shared=true&tags=&shared=no&only_liked=false&order=updated_at&types=table&deepInsights=false&load_do_totals=true'; expect(model.url()).toEqual(defaultUrl); }); }); describe('.generateParams', function () { it('returns the paramsModel attributes encoded', function () { var encodedParams = 'tag_name=&q=&page=1&type=&exclude_shared=true&tags=&shared=no&only_liked=false&order=updated_at&types=table&deepInsights=false&load_do_totals=true'; expect(model.generateParams()).toEqual(encodedParams); }); }); describe('.parse', function () { it('transforms a tables array into an object', function () { var response = { visualizations: [ { name: 'rick' }, { name: 'morty' }, { name: 'jerry' } ] }; var values = model.parse(response); expect(values.rick).toBeDefined(); }); it('adds the default permissions to the table', function () { var response = { visualizations: [ { name: 'jerry' } ] }; var values = model.parse(response); expect(values.jerry.permissions).toEqual({ select: false, update: false, insert: false, delete: false }); }); }); describe('.setQuery', function () { it('sets the query in paramsModel', function () { expect(model.paramsModel.get('q')).toEqual(''); model.setQuery('morty'); expect(model.paramsModel.get('q')).toEqual('morty'); }); }); describe('.getStateModel', function () { it('returns the stateModel', function () { expect(model.getStateModel()).toEqual(model.stateModel); }); }); describe('.isFetched', function () { it('returns true if stateModel:status is fetched', function () { model.stateModel.set({ status: 'fetched' }); expect(model.isFetched()).toBe(true); }); }); describe('.hasQuery', function () { it('returns true if paramsModel has q', function () { expect(model.hasQuery()).toBe(false); model.paramsModel.set({ q: 'morty' }); expect(model.hasQuery()).toBe(true); }); }); describe('.isEmpty', function () { it('returns true if model has no attributes', function () { expect(model.isEmpty()).toBe(true); model.set({ rick: 'morty' }); expect(model.isEmpty()).toBe(false); }); }); });
import { gql, graphql } from 'react-apollo'; const commentInsert = gql` mutation commentInsert($comment: CommentInputType!) { commentInsert(comment: $comment) { _id } } `; const commentsInsertMutation = graphql(commentInsert, { props: (params) => ({ commentInsert: (comment) => params.commentInsertMutation({variables: {comment}}), }), name: 'commentInsertMutation', options: { refetchQueries: ['commentsQuery'] } }); export default commentsInsertMutation;
/* * * When the validation fails, create the items user submitted in the previous request * */ function recreateItems() { dojo.forEach (returnedItems, function(items) { moreWidgets(items.productName, items.quantity, items.unitPrice, items.taxTypeName, items.taxPercentage); } ); } dojo.addOnLoad(function() { recreateItems() })
/* eslint-env mocha */ 'use strict' const Logger = require('logplease') const assert = require('chai').assert const UP2P = require('../src/index') const MockMetadataHandler = require('./mockMetadataHandler') Logger.setLogLevel(Logger.LogLevels.ERROR) describe('Config storage', () => { it('check persistent config storage', (done) => { let peer1, peer2 let config1, config2 peer1 = new UP2P(new MockMetadataHandler()) peer1.start() .then(() => peer1._db.getConfig()) .then((config) => { config1 = config }) .then(() => { peer2 = new UP2P(new MockMetadataHandler()) }) .then(() => peer2.start()) .then(() => peer2._db.getConfig()) .then((config) => { config2 = config }) .then(() => assert.deepEqual(config1, config2)) .then(done) .catch((err) => console.error(err.stack)) }) })
/* @flow */ import DispatcherInstance from '../dispatcher/DispatcherInstance.js'; import {isDispatcher} from '../dispatcher/DispatcherInterface.js'; import invariant from '../invariant.js'; import StoreFacade from './StoreFacade.js'; function emptyGetter() { return null; } var HINT_LINK = 'Learn more about defining stores:' + ' https://github.com/HubSpot/general-store#create-a-store'; export default class StoreDefinition { _facade: ?StoreFacade; _getter: ?Function; _responses: {[key: string]: (data: any) => void}; constructor() { this._facade = null; this._getter = null; this._responses = {}; } defineGet( getter: () => any ): StoreDefinition { invariant( !this.isRegistered(), 'StoreDefinition.defineGet: this store definition cannot be modified' + ' because is has already been registered with a dispatcher. %s', HINT_LINK ); invariant( typeof getter === 'function', 'StoreDefinition.defineGet: expected getter to be a function but got' + ' "%s" instead. %s', getter, HINT_LINK ); this._getter = getter; return this; } defineResponseTo( actionTypes: Array<string> | string, response: (data: any) => void ): StoreDefinition { invariant( !this.isRegistered(), 'StoreDefinition.defineResponseTo: this store definition cannot be' + ' modified because is has already been registered with a dispatcher. %s', HINT_LINK ); [].concat(actionTypes).forEach(actionType => { return this._setResponse(actionType, response); }); return this; } isRegistered(): bool { return this._facade instanceof StoreFacade; } register(dispatcher: ?Dispatcher): StoreFacade { dispatcher = dispatcher || DispatcherInstance.get(); invariant( dispatcher !== null && typeof dispatcher === 'object', 'StoreDefinition.register: you haven\'t provide a dispatcher instance.' + ' You can pass an instance to' + ' GeneralStore.define().register(dispatcher) or use' + ' GeneralStore.DispatcherInstance.set(dispatcher) to set a global' + ' instance.' + ' https://github.com/HubSpot/general-store#default-dispatcher-instance' ); invariant( isDispatcher(dispatcher), 'StoreDefinition.register: Expected dispatcher to be an object' + ' with a register method, and an unregister method but got "%s".' + ' Learn more about the dispatcher interface:' + ' https://github.com/HubSpot/general-store#dispatcher-interface', dispatcher ); invariant( typeof this._getter === 'function', 'StoreDefinition.register: a store cannot be registered without a' + ' getter. Use GeneralStore.define().defineGet(getter) to define a' + ' getter. %s', HINT_LINK ); var facade = this._facade || new StoreFacade( this._getter || emptyGetter, this._responses, dispatcher ); if (this._facade === null) { this._facade = facade; } return facade; } _setResponse( actionType: string, response: (data: any) => void ): void { invariant( typeof actionType === 'string', 'StoreDefinition.defineResponseTo: expected actionType to be a string' + ' but got "%s" instead. %s', actionType, HINT_LINK ); invariant( !this._responses.hasOwnProperty(actionType), 'StoreDefinition.defineResponseTo: conflicting resposes for actionType' + ' "%s". Only one response can be defined per actionType per Store. %s', actionType, HINT_LINK ); invariant( typeof response === 'function', 'StoreDefinition.defineResponseTo: expected response to be a function' + ' but got "%s" instead. %s', response ); this._responses[actionType] = response; } }
import React from 'react' import Icon from 'react-icon-base' const IoSocialTumblr = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m25.1 30.9c1.6 0 3.3-0.4 4.9-1.5v5.1c-1.4 0.6-2.7 1.1-3.7 1.4s-2.2 0.3-3.6 0.3c-1.4 0-2.7-0.1-3.9-0.5-1.1-0.4-2.2-0.9-2.9-1.6s-1.4-1.4-1.7-2.2-0.5-2-0.5-3.5v-10.9h-3.7v-4.5c1.3-0.4 2.3-1.1 3.3-1.9s1.5-1.6 2-2.7 0.9-2.9 1.1-4.7h4.9v8.8h7.5v5h-7.5v7.9c0 1.9 0 3.1 0.3 3.7 0.1 0.5 0.5 0.9 1.1 1.2 0.7 0.5 1.4 0.6 2.4 0.6z"/></g> </Icon> ) export default IoSocialTumblr
import { spawn } from 'child_process'; import { promisify } from 'util'; import { readdir as readdirRaw, readFileSync } from 'fs'; import { join } from 'path'; import { getDeployables } from './utils/list-examples'; import { filterDataForCurrentCircleCINode } from './utils/concurrency'; const readdir = promisify(readdirRaw); const p = (l) => join(__dirname, '..', ...l); const logger = console; const exec = async (command, args = [], options = {}) => new Promise((resolve, reject) => { const child = spawn(command, args, { ...options, stdio: 'inherit', shell: true }); child .on('close', (code) => { if (code) { reject(); } else { resolve(); } }) .on('error', (e) => { logger.error(e); reject(); }); }); const hasChromaticAppCode = (l) => { const text = readFileSync(l, 'utf8'); const json = JSON.parse(text); return !!( json && json.storybook && json.storybook.chromatic && json.storybook.chromatic.projectToken ); }; const handleExamples = async (deployables) => { await deployables.reduce(async (acc, d) => { await acc; const out = p(['built-storybooks', d]); const cwd = p([]); const { storybook: { chromatic: { projectToken }, }, } = JSON.parse(readFileSync(p(['examples', d, 'package.json']))); if (projectToken) { await exec( `yarn`, [ 'chromatic', `--storybook-build-dir="${out}"`, '--exit-zero-on-changes', `--project-token="${projectToken}"`, ], { cwd } ); logger.log('-------'); logger.log(`✅ ${d} ran`); logger.log('-------'); } else { logger.log('-------'); logger.log(`❌ ${d} skipped`); logger.log('-------'); } }, Promise.resolve()); }; const run = async () => { const examples = await readdir(p(['examples'])); const list = filterDataForCurrentCircleCINode(examples); const deployables = getDeployables(list, hasChromaticAppCode); if (deployables.length) { logger.log(`🖼 Will run chromatics for: ${deployables.join(', ')}`); await handleExamples(deployables); } }; run().catch((e) => { logger.error(e); process.exit(1); });
import DS from 'ember-data' export default DS.Model.extend({ 'first-name': DS.attr('string'), 'lastName': DS.attr('string'), 'zipCode': DS.attr('string'), 'email': DS.attr('string') })
const path = require('path') const express = require('express') const app = express() app.use(express.static('dist')) app.get('/*', (req, res) => { res.sendFile(path.resolve('dist/index.html')) }) const PORT = process.env.PORT || 8080 const HOST = process.env.HOST || '0.0.0.0' app.listen(PORT, HOST, () => { console.log(`App listening on http://${HOST}:${PORT}/`) })
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M12 6.5c-2.49 0-4 2.02-4 4.5v6h8v-6c0-2.48-1.51-4.5-4-4.5zm2.5 3.3-2.8 3.4h2.8V15h-5v-1.8l2.8-3.4H9.5V8h5v1.8z", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M9.5 9.8h2.8l-2.8 3.4V15h5v-1.8h-2.8l2.8-3.4V8h-5zM18 16v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2zm-2 1H8v-6c0-2.48 1.51-4.5 4-4.5s4 2.02 4 4.5v6zm-4 5c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2z" }, "1")], 'NotificationsPausedTwoTone'); exports.default = _default;
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M7 3v9c0 .55.45 1 1 1h2v7.15c0 .51.67.69.93.25l5.19-8.9c.39-.67-.09-1.5-.86-1.5H13l2.49-6.65c.25-.65-.23-1.35-.93-1.35H8c-.55 0-1 .45-1 1z" }), 'FlashOnRounded');
'use strict'; module.exports = function (t, a) { var report = t('foo = \'raz\';'); a(report.length, 1, "Report length"); a.deep(report[0], { line: 1, character: 1, message: '\'foo\' was used before it was defined.' }); };
var WebSocketServer = require('ws').Server; var events = require('events'); var _ = require('lodash'); var util = require('util'); var PINGPONG = 25 * 1000; function Peertc() { var that = this; this.sockets = []; this.mapping = {}; that.on('__pong', function(data, socket) { socket.pingSent = 0; }); that.on('__init', function(data, socket) { var id = data.id; socket.id = id; that.mapping[id] = socket; socket.send(JSON.stringify({ event: '_init' })); }); that.on('__ice_candidate', function(data, socket) { var soc = that.get(data.to); if (soc) { soc.send(JSON.stringify({ "event": "_ice_candidate", "data": { "label": data.label, "candidate": data.candidate, "from": data.from, "to": data.to } })); } }); that.on('__offer', function(data, socket) { var soc = that.get(data.to); if (soc) { soc.send(JSON.stringify({ "event": "_offer", "data": { "sdp": data.sdp, "from": data.from, "to": data.to } })); } }); that.on('__answer', function(data, socket) { var soc = that.get(data.to); if (soc) { soc.send(JSON.stringify({ "event": "_answer", "data": { "sdp": data.sdp, "from": data.from, "to": data.to } })); } }); } util.inherits(Peertc, events.EventEmitter); _.mixin(Peertc.prototype, { init: function(socket) { var that = this; that.add(socket); socket.on('message', function(data) { var json = JSON.parse(data); var event; if ((event = json.event)) { that.emit(event, json.data, socket); } else { that.emit("message", data, socket); } }); var pingpong = setInterval(function() { if (socket.pingSent >= 2) { socket.close(); } else { socket.send(JSON.stringify({ "event": "_ping", "data": { time: +new Date } })); socket.pingSent++; } }, PINGPONG); socket.on('close', function() { clearInterval(pingpong); that.remove(socket); }); }, add: function(socket) { var that = this; that.sockets.push(socket); }, remove: function(socket) { var that = this; var i = that.sockets.indexOf(socket); that.sockets.splice(i, 1); delete that.mapping[socket.id]; }, get: function(id) { var that = this; return that.mapping[id]; } }); module.exports.listen = function(port) { var server; var peertc = new Peertc(); server = typeof port === 'number' ? new WebSocketServer({ port: port }) : new WebSocketServer({ server: port }); server.on('connection', function(socket) { peertc.init(socket); }); return server; };
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _get = function get(_x2, _x3, _x4) { var _again = true; _function: while (_again) { var object = _x2, property = _x3, receiver = _x4; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x2 = parent; _x3 = property; _x4 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _alt = require('alt'); var _alt2 = _interopRequireDefault(_alt); var _form_actions = require('./form_actions'); var _form_actions2 = _interopRequireDefault(_form_actions); var _form_store = require('./form_store'); var _form_store2 = _interopRequireDefault(_form_store); var FormFlux = (function (_Alt) { _inherits(FormFlux, _Alt); function FormFlux() { var config = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; _classCallCheck(this, FormFlux); _get(Object.getPrototypeOf(FormFlux.prototype), 'constructor', this).call(this, config); this.addActions('formActions', _form_actions2['default']); this.addStore('formStore', _form_store2['default'], this.actions.formActions); } return FormFlux; })(_alt2['default']); exports['default'] = FormFlux; module.exports = exports['default'];
var searchData= [ ['data_5fbits',['DATA_BITS',['../class_r_f_i_d_attribute_types.html#aa5d728f9661d83970eb05afe3bfa3da8',1,'RFIDAttributeTypes']]], ['date_5ftime',['DATE_TIME',['../class_r_f_i_d_attribute_types.html#a4217e575e55a000642024dcea29706de',1,'RFIDAttributeTypes']]], ['deallocate_5fchannel',['DEALLOCATE_CHANNEL',['../class_r_f_i_d_commands_codes.html#a6dea4184f7648b65c1fd85eec94927b2',1,'RFIDCommandsCodes']]], ['deallocate_5ftrigger',['DEALLOCATE_TRIGGER',['../class_r_f_i_d_commands_codes.html#acae6a5c459eba5e0b225b306b787a207',1,'RFIDCommandsCodes']]], ['desb_5fenable',['DESB_ENABLE',['../class_r_f_i_d_attribute_types.html#a89494a023e5bef3ca581425f4947d20e',1,'RFIDAttributeTypes']]], ['desb_5fstatus',['DESB_STATUS',['../class_r_f_i_d_attribute_types.html#a5d87504f95846574d7320ba00a95477e',1,'RFIDAttributeTypes']]] ];
var searchData= [ ['jointable',['JoinTable',['../a00018.html#a530a83353adc1152ebd8df8491199d9d',1,'tpc.c']]] ];
//子页面不用iframe,用div展示 var closableTab = { tabList:[], //添加tab addTab:function(tabItem){ //tabItem = {id,name,url,closable} var id = "tab_seed_" + tabItem.id; var container ="tab_container_" + tabItem.id; $("li[id^=tab_seed_]").removeClass("active"); $("div[id^=tab_container_]").removeClass("active"); if(!$('#'+id)[0]){ var li_tab = '<li class="nav-item" id="'+id+'"><a class="nav-link" data-toggle="tab" href="#'+container+'" >'+tabItem.name; if(tabItem.closable){ li_tab = li_tab + '<i class="glyphicon glyphicon-remove small" id="x'+id+'" tabclose="'+id+'" style="position: relative;right:-6px;top: -6px;" onclick="closableTab.closeTab(this)">×</i></a></li> '; closableTab.tabList.push('x'+id); }else{ li_tab = li_tab + '</a></li>'; } var tabpanel = '<div role="tabpanel" class="container tab-pane" id="'+container+'" style="width: 100%;">'+ '正在加载...'+ '</div>'; $('.nav-tabs').append(li_tab); $('.tab-content').append(tabpanel); $('#'+container).load(tabItem.url,function(response,status,xhr){ if(status=='error'){//status的值为success和error,如果error则显示一个错误页面 $(this).html(response); } }); } $("#"+id).addClass("active"); $("#"+container).addClass("active"); }, //关闭tab closeTab:function(item){ var val = $(item).attr('tabclose'); var containerId = "tab_container_"+val.substring(9); if($('#'+containerId).hasClass('active')){ $('#'+val).prev().addClass('active'); console.log(val) console.log(containerId) $('#'+containerId).prev().addClass('active'); } $("#"+val).remove(); $("#"+containerId).remove(); closableTab.tabList.splice(closableTab.tabList.indexOf('x'+val),1); }, closeAllTab:function(){ var i=0; for(i=closableTab.tabList.length-1;i>=0;i--){ closableTab.closeTab(document.getElementById(''+closableTab.tabList[i])); } }, slide:function(flag){ var curTabHead=$('.nav-link.active'); var curTabBody=$('.tab-pane.active'); if(flag==1){ var leftTabHead=curTabHead.parent().prev().find('.nav-link'); var leftTabBody=curTabBody.prev(); if(leftTabHead.length>0){ curTabHead.removeClass('active'); leftTabHead.addClass('active'); leftTabHead.addClass('show'); curTabBody.removeClass('active'); leftTabBody.addClass('active'); leftTabBody.addClass('show'); } }else{ var rightTabHead=curTabHead.parent().next().find('.nav-link'); var rightTabBody=curTabBody.next(); if(rightTabHead.length>0){ curTabHead.removeClass('active'); rightTabHead.addClass('active'); rightTabHead.addClass('active'); curTabBody.removeClass('active'); rightTabBody.addClass('active'); rightTabBody.addClass('show'); } } }, slideLeft:function(){ closableTab.slide(1); }, slideRight:function(){ closableTab.slide(2); } }
/** * Module dependencies */ var EventEmitter = require('events'); var loadAPI = require('./lib/load-api'); var prepareEmbed = require('./lib/prepare-embed'); var sdk; /** * Expose `SoundCloud` */ module.exports = SoundCloud; /** * Create new `SoundCloud` controller * * @param {String} id of embedded widget */ function SoundCloud(id) { sdk = loadAPI(); prepareEmbed(id); this.attachToEmbed(id); } /** * Mixin events */ SoundCloud.prototype = new EventEmitter(); /** * Play the track. * * @api public */ SoundCloud.prototype.play = function() { this.player.play(); }; /** * Pause the track. * * @api public */ SoundCloud.prototype.pause = function() { this.player.pause(); }; /** * Remove all event handlers and free up internal player for * garbage collection. * * @api public */ SoundCloud.prototype.destroy = function() { this.unbindEvents(); delete this.player; }; /** * Attach a controller to the embedded widget * * @param {String} id of embedded widget * @api private */ SoundCloud.prototype.attachToEmbed = function(id) { var self = this; sdk(function(err, SC) { self.player = new window.SC.Widget(id); self.bindEvents(); }); }; /** * Bind player events * * @api private */ SoundCloud.prototype.bindEvents = function() { var self = this; self.player.bind(window.SC.Widget.Events.READY, function(event) { self.emit('ready', event); }); self.player.bind(window.SC.Widget.Events.PLAY, function(event) { self.emit('play', event); }); self.player.bind(window.SC.Widget.Events.PAUSE, function(event) { self.emit('pause', event); }); self.player.bind(window.SC.Widget.Events.FINISH, function(event) { self.emit('end', event); }); self.player.bind(window.SC.Widget.Events.PLAY_PROGRESS, function(event) { self.emit('playProgress', event); }); self.player.bind(window.SC.Widget.Events.LOAD_PROGRESS, function(event) { self.emit('loadProgress', event); }); }; /** * Unbind all player events * * @api private */ SoundCloud.prototype.unbindEvents = function() { this.player.unbind(window.SC.Widget.Events.READY); this.player.unbind(window.SC.Widget.Events.PLAY); this.player.unbind(window.SC.Widget.Events.PAUSE); this.player.unbind(window.SC.Widget.Events.FINISH); this.player.unbind(window.SC.Widget.Events.PLAY_PROGRESS); this.player.unbind(window.SC.Widget.Events.LOAD_PROGRESS); };