code
stringlengths
2
1.05M
define(["backbone", "underscore", "text!homeTemplate.html"], function (Backbone, _, homeTemplate) { return Backbone.View.extend({ className: "home", tagName: "section", template: _.template(homeTemplate), render: function () { this.$el.html(this.template()); return this; } }); });
/** * System configuration for Angular 2 samples * Adjust as necessary for your application needs. */ (function(global) { // map tells the System loader where to look for things var map = { 'app': 'app', // 'dist', 'odm': 'odm', // 'dist', '@angular': 'node_modules/@angular', 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', 'rxjs': 'node_modules/rxjs' }; // packages tells the System loader how to load when no filename and/or no extension var packages = { 'app': { main: 'main.js', defaultExtension: 'js' }, 'odm': { main: 'main.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' }, 'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' }, }; var ngPackageNames = [ 'common', 'compiler', 'core', 'forms', 'http', 'platform-browser', 'platform-browser-dynamic', 'router', 'router-deprecated', 'upgrade', ]; // Individual files (~300 requests): function packIndex(pkgName) { packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' }; } // Bundled (~40 requests): function packUmd(pkgName) { packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' }; } // Most environments should use UMD; some (Karma) need the individual index files var setPackageConfig = System.packageWithIndex ? packIndex : packUmd; // Add package entries for angular packages ngPackageNames.forEach(setPackageConfig); var config = { map: map, packages: packages }; System.config(config); })(this);
import _ from 'underscore'; const LOAD = 'redux-example/suppliers/LOAD'; const LOAD_SUCCESS = 'redux-example/suppliers/LOAD_SUCCESS'; const LOAD_FAIL = 'redux-example/suppliers/LOAD_FAIL'; const LOAD_SUPPLIER = 'redux-example/suppliers/LOAD_SUPPLIER'; const LOAD_SUPPLIER_SUCCESS = 'redux-example/suppliers/LOAD_SUPPLIER_SUCCESS'; const LOAD_SUPPLIER_FAIL = 'redux-example/suppliers/LOAD_SUPPLIER_FAIL'; const CREATE_SUPPLIER = 'redux-example/suppliers/CREATE_SUPPLIER'; const CREATE_SUPPLIER_SUCCESS = 'redux-example/suppliers/CREATE_SUPPLIER_SUCCESS'; const CREATE_SUPPLIER_FAIL = 'redux-example/suppliers/CREATE_SUPPLIER_FAIL'; const DELETE_SUPPLIER = 'redux-example/suppliers/DELETE_SUPPLIER'; const DELETE_SUPPLIER_SUCCESS = 'redux-example/suppliers/DELETE_SUPPLIER_SUCCESS'; const DELETE_SUPPLIER_FAIL = 'redux-example/suppliers/DELETE_SUPPLIER_FAIL'; const initialState = { suppliers: { entities: [], byId: {}, byGroupId: {} }, loading: false, errors: null, }; export default function suppliersReducer(state = initialState, action = {}) { let entities; switch (action.type) { case LOAD: return { ...state, loading: true, }; case LOAD_SUCCESS: entities = action.result; return { ...state, loading: false, suppliers: { entities: entities, byId: _.indexBy(entities, 'id'), byGroupId: _.groupBy(entities, 'group_id'), }, }; case LOAD_FAIL: return { ...state, loading: false, error: action.error, }; case LOAD_SUPPLIER: return { ...state, loading: true, }; case LOAD_SUPPLIER_SUCCESS: entities = [...state.suppliers.entities, action.result]; return { ...state, loading: false, suppliers: { entities: entities, byId: _.indexBy(entities, 'id'), byGroupId: _.groupBy(entities, 'group_id'), }, }; case LOAD_SUPPLIER_FAIL: return { ...state, loading: false, error: action.error, }; case CREATE_SUPPLIER: return { ...state, errors: null, }; case CREATE_SUPPLIER_SUCCESS: entities = [...state.suppliers.entities, action.result]; return { ...state, suppliers: { entities, byId: _.indexBy(entities, 'id'), byGroupId: _.groupBy(entities, 'group_id'), }, errors: null, }; case CREATE_SUPPLIER_FAIL: return { ...state, errors: action.error, }; case DELETE_SUPPLIER_SUCCESS: entities = _.reject(state.suppliers.entities, (supplier) => { return supplier.id === action.requestData.id; }); return { ...state, suppliers: { entities, byId: _.indexBy(entities, 'id'), byGroupId: _.groupBy(entities, 'group_id'), }, }; case DELETE_SUPPLIER: case DELETE_SUPPLIER_FAIL: default: return state; } } /** * Load suppliers scoped by group * * @param {Number} groupId */ export function load(groupId) { return { types: [LOAD, LOAD_SUCCESS, LOAD_FAIL], promise: (client) => client.get(`/suppliers?group_id=${groupId}`) }; } export function loadEntity(id) { return { types: [LOAD_SUPPLIER, LOAD_SUPPLIER_SUCCESS, LOAD_SUPPLIER_FAIL], promise: (client) => client.get(`/suppliers/${id}`) }; } /** * Create api call on suppliers * * @param {Object} data */ export function create(data) { return { types: [CREATE_SUPPLIER, CREATE_SUPPLIER_SUCCESS, CREATE_SUPPLIER_FAIL], promise: (client) => client.post('/suppliers', { data }), }; } /** * Delete supplier * * @param {Number} id */ export function destroy(id) { return { types: [DELETE_SUPPLIER, DELETE_SUPPLIER_SUCCESS, DELETE_SUPPLIER_FAIL], promise: (client) => client.delete(`/suppliers/${id}`, { data: { id }}), requestData: { id } }; }
// For an introduction to the Page Control template, see the following documentation: // http://go.microsoft.com/fwlink/?LinkId=232511 (function () { "use strict"; /****************************/ /* GAMES HUB PAGE CONTROL */ /****************************/ WinJS.UI.Pages.define("/pages/statsHub/statsHub.html", { /* Responds to navigations to this page */ ready: function (element, options) { // TODO: make sure this doesn't crash when starting on this page RC.assert(typeof (RC.HighScores.dictionary) === "object", "High scores dictionary should already be defined"); RC.assert(typeof (RC.Achievements.dictionary) === "object", "Achievements dictionary should already be defined"); // Initialize the stats hub list event listeners initializeStatsHubEventListeners(); // Create the stats list view data sources var highScoresDataSource = WinJS.Class.derive(WinJS.UI.VirtualizedDataSource, function () { this._baseDataSourceConstructor(new highScoresDataAdapter()); }); //var statsDataSource = WinJS.Class.derive(WinJS.UI.VirtualizedDataSource, function () { // this._baseDataSourceConstructor(new statsDataAdapter()); //}); // Populate the achievements data populateAchievementsData(); // Add the stats list view data sources to the RC.Stats namespace WinJS.Namespace.defineWithParent(RC, "Stats", { highScoresDataSource: new highScoresDataSource, //statsDataSource: new statsDataSource }); }, /* Responds to navigations away from this page */ unload: function () { disposeStatsHubEventListeners(); }, /* Responds to changes in the view state */ updateLayout: function (element) { } }); /*********************/ /* EVENT LISTENERS */ /*********************/ /* Initializes the stats hub event listeners */ function initializeStatsHubEventListeners() { // Get the stats hub var statsHub = $(".statsHub .hub")[0]; // Navigate to the high scores page when the high scores header is invoked statsHub.addEventListener("headerinvoked", navigateToStatsHubSubpage); }; /* Disposes of the stats hub event listeners */ function disposeStatsHubEventListeners() { // Get the stats hub var statsHub = $(".statsHub .hub")[0]; // Navigate to the high scores page when the high scores header is invoked statsHub.removeEventListener("headerinvoked", navigateToStatsHubSubpage); }; function navigateToStatsHubSubpage(event) { switch (event.detail.index) { case 0: WinJS.Navigation.navigate("/pages/highScores/highScores.html"); break; case 1: WinJS.Navigation.navigate("/pages/achievements/achievements.html"); break } }; /*******************/ /* DATA ADAPTERS */ /*******************/ /* Retrieves the logged-in user's high scores */ var highScoresDataAdapter = WinJS.Class.define( // Constructor function () { this._maxNumHighScoresToShow = 10; this._numHighScores = undefined; }, // IListDataAdapter methods { // Retrieve the item at the requested index (and possibly some items before and after it) itemsFromIndex: function (requestIndex, countBefore, countAfter) { RC.assert(typeof(RC.HighScores.dictionary) === "object", "High scores dictionary should already be defined"); RC.assert(typeof(this._numHighScores) === "number", "Number of high scores should be defined in getCount()"); var _this = this; return new WinJS.Promise(function (complete, error) { // TODO: remove or accept the Firebase way of doing this /*RC.firebaseRoot.child("users/" + RC.loggedInUserId + "/games/singlePlayer/completed").once("value", function (dataSnapshot) { var completedSinglePlayerGames = dataSnapshot.val(); var numCompletedSinglePlayerGames = completedSinglePlayerGames.length; var results = []; for (var i = requestIndex - countBefore; i < requestIndex + countAfter, i < numCompletedSinglePlayerGames; ++i) { var game = completedSinglePlayerGames[i]; game.isPlaceholder = false; results.push({ key: i.toString(), data: game }); if (results.length == maxNumItems) { break; } } return complete({ items: results, offset: countBefore, totalCount: Math.min(numCompletedSinglePlayerGames, maxNumItems) }); });*/ var highScoresDictionary = RC.HighScores.dictionary; var highScoresList = []; for (var key in highScoresDictionary) { highScoresList = highScoresList.concat(highScoresDictionary[key]); } highScoresList.sort(function (a, b) { return b.score - a.score }); highScoresList = highScoresList.slice(0, _this._maxNumHighScoresToShow); var results = []; for (var i = requestIndex - countBefore; i < requestIndex + countAfter, i < highScoresList.length; ++i) { var game = highScoresList[i]; game.isPlaceholder = false; results.push({ key: i.toString(), data: game }); } return complete({ items: results, offset: countBefore, totalCount: results.length }); }); }, // Returns the number of items in the result list getCount: function () { RC.assert(typeof (RC.HighScores.dictionary) === "object", "High scores dictionary should already be defined"); var _this = this; // TODO: remove or accept the Firebase way of doing this /*return new WinJS.Promise(function (complete, error) { RC.firebaseRoot.child("users/" + RC.loggedInUserId + "/games/singlePlayer/completed").once("value", function (dataSnapshot) { complete(Math.min(dataSnapshot.numChildren(), _this._maxNumItems)); }); });*/ return new WinJS.Promise(function (complete, error) { var highScoresDictionary = RC.HighScores.dictionary; _this._numHighScores = 0; for (var key in highScoresDictionary) { _this._numHighScores += highScoresDictionary[key].length; } complete(Math.min(_this._numHighScores, _this._maxNumHighScoresToShow)); }); } } ); /***********************/ /* ACHIEVEMENTS DATA */ /***********************/ function populateAchievementsData() { RC.assert(typeof (RC.Achievements) == "object", "Achievements namespace should already be defined"); RC.assert(typeof (RC.Achievements.dictionary) === "object", "Achievements dictionary should be undefined"); // Get the completion ratio and percentage for each achievement type var completionDictionary = {}; for (var key in RC.Achievements.dictionary) { // Get the current achievements list var achievementsList = RC.Achievements.dictionary[key]; var numAchievements = achievementsList.length; // Determine how many of achievements in the current list are complete var numAchievementsCompleted = 0; for (var i = 0; i < numAchievements; ++i) { if (achievementsList[i].isComplete) { numAchievementsCompleted += 1; } } // Determine the completion percentage var completionPercentage = (numAchievementsCompleted / numAchievements * 100).toFixed(1); if (completionPercentage == "100.0") { completionPercentage = "100"; } // Add the current key to the completion dictionary completionDictionary[key] = { numAchievements: numAchievements, numAchievementsCompleted: numAchievementsCompleted, ratio: numAchievementsCompleted + "/" + numAchievements, percentage: completionPercentage + "%" } } // Populate the achievements data $("#fiveLetterAchievementsGrid > .ratio").text(completionDictionary["5"].ratio); $("#fiveLetterAchievementsGrid > .percentage").text(completionDictionary["5"].percentage); $("#sixLetterAchievementsGrid > .ratio").text(completionDictionary["6"].ratio); $("#sixLetterAchievementsGrid > .percentage").text(completionDictionary["6"].percentage); $("#sevenLetterAchievementsGrid > .ratio").text(completionDictionary["7"].ratio); $("#sevenLetterAchievementsGrid > .percentage").text(completionDictionary["7"].percentage); $("#miscellaneousAchievementsGrid > .ratio").text(completionDictionary["Miscellaneous"].ratio); $("#miscellaneousAchievementsGrid > .percentage").text(completionDictionary["Miscellaneous"].percentage); // Calculate and populate the all achievements data var numAllAchievements = completionDictionary["5"].numAchievements + completionDictionary["6"].numAchievements + completionDictionary["7"].numAchievements + completionDictionary["Miscellaneous"].numAchievements; var numAllAchievementsCompleted = completionDictionary["5"].numAchievementsCompleted + completionDictionary["6"].numAchievementsCompleted + completionDictionary["7"].numAchievementsCompleted + completionDictionary["Miscellaneous"].numAchievementsCompleted; var completionPercentage = (numAllAchievementsCompleted / numAllAchievements * 100).toFixed(1); if (completionPercentage == "100.0") { completionPercentage = "100"; } $("#allAchievementsGrid > .ratio").text(numAllAchievementsCompleted + "/" + numAllAchievements); $("#allAchievementsGrid > .percentage").text(completionPercentage + "%"); }; })();
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { return 5; } global.ng.common.locales['ceb'] = [ 'ceb', [['a', 'p'], ['AM', 'PM'], u], [['AM', 'PM'], u, u], [ ['D', 'L', 'M', 'M', 'H', 'B', 'S'], ['Dom', 'Lun', 'Mar', 'Mks', 'Hu', 'Bi', 'Sa'], ['Domingo', 'Lunes', 'Martes', 'Miyerkules', 'Huwebes', 'Biyernes', 'Sabado'], ['Dom', 'Lun', 'Mar', 'Miy', 'Huw', 'Biy', 'Sab'] ], u, [ ['E', 'P', 'M', 'A', 'M', 'H', 'H', 'A', 'S', 'O', 'N', 'D'], ['En', 'Peb', 'Mar', 'Apr', 'May', 'Hun', 'Hul', 'Ag', 'Set', 'Okt', 'Nob', 'Dis'], [ 'Enero', 'Pebrero', 'Marso', 'Abril', 'Mayo', 'Hunyo', 'Hulyo', 'Agosto', 'Setyembre', 'Oktubre', 'Nobyembre', 'Disyembre' ] ], u, [['WK', 'KP'], u, u], 0, [6, 0], ['M/d/yy', 'MMM d, y', 'MMMM d, y', 'EEEE, MMMM d, y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1}, {0}', u, '{1} \'sa\' {0}', u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,#0%', '¤#,##0.00', '#E0'], '₱', 'Philippine Piso', {'JPY': ['JP¥', '¥'], 'PHP': ['₱'], 'USD': ['US $', '$']}, 'ltr', plural, [] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
version https://git-lfs.github.com/spec/v1 oid sha256:b7b090942eb1b5faa026ad6a48d57357bea293624bc96b4a55a72d98cdceb6ce size 75251
version https://git-lfs.github.com/spec/v1 oid sha256:88a4c468392ef3e2c81c47d0a31c5ccf94a1da5f91f9ee6464b53142279c15ba size 3800
/*jslint node: true */ 'use strict'; /*********************** * Logging and Analytics */ var hendrix = require('../../../lib/hendrix'), connectionDb = hendrix.getConnectionDb(), log = hendrix.log, winston = require('winston'), momentTimeZone = require('moment-timezone'); var t = 0; var ipDay = momentTimeZone().tz("Asia/Jerusalem").date(); log("Initialize ipDay to: " + ipDay); /******************************** * DayStat * pages - score page counter by country * users - users counter by country, not counting crawlers * */ // render log page exports.logRender = function(req,res,next) { var options = { // number of results limit: 1024, start: 0, order: 'desc' }; winston.query(options, function (err, results) { if (err) { return next(err); } var pars = { username: req.user.username, message: req.message, messageType: req.messageType }; if ( results.hasOwnProperty('file')) { results.file.forEach(function(entry){ if (entry.level === 'error') { entry.level = 'danger'; } entry.timestamp = convertTime(entry.timestamp); }); pars.log = results.file; } else { return next(new Error('Working on console errors only')); } res.render('admin/logs/log.jade', pars); }); }; // convert unix string date to log display function convertTime(date){ var d = momentTimeZone(date).tz("Asia/Jerusalem"), str = d.format('D/M - hh:mm:ss'); return str; } // render log page exports.logTest = function(req,res,next) { log("testing message" + t); t++; res.send('OK'); }; // render log page exports.logTestCritical = function(req,res,next) { log("testing critical message" + t); t++; t.info.stam = 10; res.send('OK'); };
'use strict'; let ParentNode = require("./parentNode.js"); module.exports = class FunctionCall extends ParentNode { constructor(_opNode) { super(); this.name = "FUNCTION_CALL"; this.opNode = _opNode; // this.children are arguments this.description += this.opNode.getToken().data; } getOpNode() { return this.opNode; } }
import { expect } from 'chai'; import detectDefaultLocale from '.'; describe('detectDefaultLocale', () => { it('should be a function', () => { expect(detectDefaultLocale).to.be.a('function'); }); it('should return default locale of en-US in node', () => { delete global.navigator; expect(detectDefaultLocale()).to.equal('en-US'); }); it('should accept defaultLocale parameter and use that as default', () => { delete global.navigator; expect(detectDefaultLocale('fo-BA')).to.equal('fo-BA'); }); it('should use navigator.languages[0] as default if available', () => { global.navigator = { languages: ['fo-Ba'], }; expect(detectDefaultLocale()).to.equal('fo-BA'); delete global.navigator; }); it('should try to check navigator.language if navigator.languages is not availble', () => { global.navigator = { languages: [], language: 'te-ST', }; expect(detectDefaultLocale()).to.equal('te-ST'); global.navigator = { language: 'te-ST', }; expect(detectDefaultLocale()).to.equal('te-ST'); delete global.navigator; }); it('should fall back to default if navigator does not have language info', () => { global.navigator = {}; expect(detectDefaultLocale('ro-GE')).to.equal('ro-GE'); delete global.navigator; }); });
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("circle", { cx: "12", cy: "19", r: "2" }), h("path", { d: "M10 3h4v12h-4z" })), 'PriorityHigh');
// #TODO this does not work yet async function /*example:*/simpleWait/*{"id":"dd1a_bbbc_9d7d","name":{"mode":"input","value":"wait"},"color":"hsl(300, 30%, 70%)","values":{},"instanceId":{"mode":"input","value":""},"prescript":"","postscript":""}*/() { var /*probe:*/a/*{}*/ = 3 await lively.sleep(100) var b = a + 4 var /*probe:*/msg/*{}*/ = "result " + b console.log(b) } async function /*example:*//*example:*/asyncIteration/*{"id":"61ae_f3c6_b32e","name":{"mode":"input","value":"by1"},"color":"hsl(350, 30%, 70%)","values":{"inc":{"mode":"input","value":"1"}},"instanceId":{"mode":"input","value":""},"prescript":"","postscript":""}*//*{"id":"ce23_5029_999d","name":{"mode":"input","value":"by2"},"color":"hsl(120, 30%, 70%)","values":{"inc":{"mode":"input","value":"2"}},"instanceId":{"mode":"input","value":""},"prescript":"","postscript":""}*/(inc) { let n = 0 for(let i=0; i < 10; i++) { /*probe:*/n/*{}*/ += inc await lively.sleep(10) } /*probe:*/return/*{}*/ n } /* Context: {"context":{"prescript":"","postscript":""},"customInstances":[]} */
/* jshint -W069 */ var map; var toner; var tonerLite; var osmMapnik; var markers = { 'en': [], 'it': [] }; var coords = []; var english; var englishLayer; var italian; var italianLayer; var icon; var icons; var iconURLs; var englishSearch = []; var italianSearch = []; var englishLabels = {}; var italianLabels = {}; var featureList; var markerClusters; var permaLink = { id: undefined, lang: 'en' }; $(window).resize(function() { sizeLayerControl(); }); $(document).on('click', '.feature-row', function(e) { var id = $(this).data('id'); var lang = $(this).data('lang'); sidebarClick(id, lang); }); icon = new L.Icon({ iconUrl: 'assets/img/signpost-icon.png', iconSize: [32, 37] }); iconURLs = { en: 'assets/img/United-Kingdom32.png', it: 'assets/img/Italy32.png' }; var PlaceIcon = L.Icon.extend({ options: { iconSize: [32, 32], iconAnchor: [16, 32], popupAnchor: [0, -32] } }); icons = { en: new PlaceIcon({ iconUrl: iconURLs.en }), it: new PlaceIcon({ iconUrl: iconURLs.it }) }; markerClusters = new L.MarkerClusterGroup({ spiderfyOnMaxZoom: false, showCoverageOnHover: false, zoomToBoundsOnClick: true, disableClusteringAtZoom: 16 }); englishLayer = L.geoJson(null); english = L.geoJson(null, { pointToLayer: function(feature, latlng) { var marker = new L.Marker(latlng, { icon: icons.en }); marker.id = feature.properties.id; coords.push(latlng); markers['en'][feature.properties.id] = marker; return marker; }, onEachFeature: function(feature, layer) { if (feature.properties && feature.properties.label) { var permalink = window.location.pathname + '?id=' + feature.properties.id + '&lang=en'; var popup = '<div class="rude-place-popup">'; popup += '<p>' + feature.properties.label + '</p>'; popup += '<p><a href="' + permalink + '">Permalink to this place ...</a></p>'; popup += '</div>'; layer.bindPopup(popup); englishLabels[feature.properties.id] = { lang: 'en', id: feature.properties.id, feature: feature }; englishSearch.push({ lang: 'en', id: feature.properties.id, source: 'English', label: feature.properties.label }); } } }); $.getJSON('assets/data/geojson/rude-en.geojson', function(data) { english.addData(data); map.addLayer(englishLayer); }); italianLayer = L.geoJson(null); italian = L.geoJson(null, { pointToLayer: function(feature, latlng) { var marker = new L.Marker(latlng, { icon: icons.it }); coords.push(latlng); markers['it'][feature.properties.id] = marker; return marker; }, onEachFeature: function(feature, layer) { if (feature.properties && feature.properties.label) { var permalink = window.location.pathname + '?id=' + feature.properties.id + '&lang=it'; var popup = '<div class="rude-place-popup">'; popup += '<p>' + feature.properties.label + '</p>'; popup += '<p><a href="' + permalink + '">Permalink to this place ...</a></p>'; popup += '</div>'; layer.bindPopup(popup); italianLabels[feature.properties.id] = { lang: 'it', id: feature.properties.id, feature: feature }; italianSearch.push({ lang: 'it', id: feature.properties.id, source: 'Italian', label: feature.properties.label }); } } }); $.getJSON('assets/data/geojson/rude-it.geojson', function(data) { italian.addData(data); }); $(document).one('ajaxStop', function() { $('#loading').hide(); rebuildFeatureList(englishLabels); var englishBH = new Bloodhound({ name: 'English', datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.label); }, queryTokenizer: Bloodhound.tokenizers.whitespace, local: englishSearch, limit: 10 }); var italianBH = new Bloodhound({ name: 'Italian', datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.label); }, queryTokenizer: Bloodhound.tokenizers.whitespace, local: italianSearch, limit: 10 }); englishBH.initialize(); italianBH.initialize(); $("#searchbox").typeahead({ minLength: 3, highlight: true, hint: false }, { name: "English", displayKey: "label", source: englishBH.ttAdapter(), templates: { header: '<h4 class="typeahead-header"><img src="' + iconURLs.en + '" width="24" height="28">&nbsp;English</h4>' } }, { name: 'Italian', displayKey: 'label', source: italianBH.ttAdapter(), templates: { header: '<h4 class="typeahead-header"><img src="' + iconURLs.it + '" width="24" height="28">&nbsp;Italian</h4>' } }).on("typeahead:selected", function (obj, datum) { var target; if (datum.source === 'English') { if (!map.hasLayer(englishLayer)) { map.addLayer(englishLayer); } if (map.hasLayer(italianLayer)) { map.removeLayer(italianLayer); } target = markers['en'][datum.id]; zoomAndPopup(target); } if (datum.source === 'Italian') { if (!map.hasLayer(italianLayer)) { map.addLayer(italianLayer); } if (map.hasLayer(englishLayer)) { map.removeLayer(englishLayer); } target = markers['it'][datum.id]; zoomAndPopup(target); } if ($(".navbar-collapse").height() > 50) { $(".navbar-collapse").collapse("hide"); } }).on("typeahead:opened", function () { $(".navbar-collapse.in").css("max-height", $(document).height() - $(".navbar-header").height()); $(".navbar-collapse.in").css("height", $(document).height() - $(".navbar-header").height()); }).on("typeahead:closed", function () { $(".navbar-collapse.in").css("max-height", ""); $(".navbar-collapse.in").css("height", ""); }); $(".twitter-typeahead").css("position", "static"); $(".twitter-typeahead").css("display", "block"); rebuildFeatureList(englishLabels); if (permaLink.id && permaLink.lang) { var datum; if (permaLink.lang === 'en' && englishLabels.hasOwnProperty(permaLink.id)) { if (!map.hasLayer(englishLayer)) { map.addLayer(englishLayer); } if (map.hasLayer(italianLayer)) { map.removeLayer(italianLayer); } datum = markers['en'][permaLink.id]; zoomAndPopup(datum); } if (permaLink.lang === 'it' && italianLabels.hasOwnProperty(permaLink.id)) { if (!map.hasLayer(italianLayer)) { map.addLayer(italianLayer); } if (map.hasLayer(englishLayer)) { map.removeLayer(englishLayer); } datum = markers['it'][permaLink.id]; zoomAndPopup(datum); } } }); $("#list-btn").click(function() { $('#sidebar').toggle(); map.invalidateSize(); return false; }); $('#credits-btn').click(function() { $('#attributionModal').modal('show'); return false; }); $("#nav-btn").click(function() { $(".navbar-collapse").collapse("toggle"); }); $("#sidebar-toggle-btn").click(function() { $("#sidebar").toggle(); map.invalidateSize(); return false; }); $("#sidebar-hide-btn").click(function() { $('#sidebar').hide(); map.invalidateSize(); }); /* Highlight search box text on click */ $("#searchbox").click(function () { $(this).select(); }); /* Prevent hitting enter from refreshing the page */ $("#searchbox").keypress(function (e) { if (e.which == 13) { e.preventDefault(); } }); $("#about-btn").click(function() { $("#aboutModal").modal("show"); $(".navbar-collapse.in").collapse("hide"); return false; }); $("#full-extent-btn").click(function() { var layer; if (map.hasLayer(englishLayer)) { layer = english; } else if (map.hasLayer(italianLayer)) { layer = italian; } if (layer) { map.fitBounds(layer.getBounds()); $(".navbar-collapse.in").collapse("hide"); } return false; }); function sidebarClick(id, lang) { var layer = markers[lang][id]; zoomAndPopup(layer); if (document.body.clientWidth <= 767) { $("#sidebar").hide(); map.invalidateSize(); } } function syncSidebar() { /* Empty sidebar features */ $("#feature-list tbody").empty(); if (map.hasLayer(englishLayer)) { $.each(englishLabels, function(index, obj) { var stamp = obj.stamp; var feature = obj.feature; $("#feature-list tbody").append('<tr class="feature-row" data-id="' + obj.id + '" data-permalink="' + feature.properties.id + '" data-lang="en"><td style="vertical-align: middle;"><img width="16" height="18" src="' + iconURLs.en + '"></td><td class="feature-name">' + feature.properties.label + '</td><td style="vertical-align: middle;"><i class="fa fa-chevron-right pull-right"></i></td></tr>'); }); rebuildFeatureList(englishLabels); } if (map.hasLayer(italianLayer)) { $.each(italianLabels, function(index, obj) { var stamp = obj.stamp; var feature = obj.feature; $("#feature-list tbody").append('<tr class="feature-row" id="' + stamp + '" permalink="' + feature.properties.id + '" lang="it" lat="' + feature.geometry.coordinates[1] + '" lng="' + feature.geometry.coordinates[0] + '"><td style="vertical-align: middle;"><img width="16" height="18" src="' + iconURLs.it + '"></td><td class="feature-name">' + feature.properties.label + '</td><td style="vertical-align: middle;"><i class="fa fa-chevron-right pull-right"></i></td></tr>'); }); rebuildFeatureList(italianLabels); } } function sortLabels(labels) { labels = $.grep(labels,function(n){ return(n); }); labels.sort(function(a, b) { if (a.feature.properties.label < b.feature.properties.label) { return -1; } if (a.feature.properties.label > b.feature.properties.label) { return 1; } return 0; }); return labels; } function rebuildFeatureList(list) { /* Update list.js featureList */ featureList = new List("features", { valueNames: ["feature-name"], page: Object.keys(list).length }); featureList.sort("feature-name", { order: "asc" }); } function sizeLayerControl() { $(".leaflet-control-layers").css("max-height", $("#map").height() - 50); } // Map Base Layers toner = L.tileLayer.provider('Stamen.Toner'); tonerLite = L.tileLayer.provider('Stamen.TonerLite'); osmMapnik = L.tileLayer.provider('OpenStreetMap.Mapnik'); map = L.map('map', { zoom: 3, center: [0,0], layers: [tonerLite, markerClusters], zoomControl: false, attributionControl: false }); /* Layer control listeners that allow for a single markerClusters layer */ map.on("overlayadd", function(e) { if (e.layer === englishLayer) { markerClusters.addLayer(english); syncSidebar(); } if (e.layer === italianLayer) { markerClusters.addLayer(italian); syncSidebar(); } }); map.on("overlayremove", function(e) { if (e.layer === englishLayer) { markerClusters.removeLayer(english); syncSidebar(); } if (e.layer === italianLayer) { markerClusters.removeLayer(italian); syncSidebar(); } }); /* Larger screens get expanded layer control and visible sidebar */ var isCollapsed = false; if (document.body.clientWidth <= 767) { var isCollapsed = true; } var baseLayers = { "Toner Lite": tonerLite, "Toner": toner, "OSM": osmMapnik }; var groupedOverlays = { "Languages": { '<img src="assets/img/Italy32.png" width="24" height="28">&nbsp;Italian': italianLayer, '<img src="assets/img/United-Kingdom32.png" width="24" height="28">&nbsp;English': englishLayer } }; var layerControl = L.control.groupedLayers(baseLayers, groupedOverlays, { exclusiveGroups: ["Languages"], collapsed: isCollapsed }).addTo(map); function updateAttribution(e) { $.each(map._layers, function(index, layer) { if (layer.getAttribution) { $('#attribution').html(layer.getAttribution()); } }); } map.on('layeradd', updateAttribution); map.on('layerremove', updateAttribution); var attributionControl = L.control({ position: 'bottomright' }); attributionControl.onAdd = function(map) { var div = L.DomUtil.create('div', 'leaflet-control-attribution'); div.innerHTML = '<span class="hidden-hs">Hosting courtesy of <a href="https://opencagedata.com/" target="_blank">OpenCage</a> | This is a thing by <a href="http://www.garygale.com">Gary Gale</a> | </span><a href="#" onclick="$(\'#attributionModal\').modal(\'show\'); return false;">Credits &amp; Attribution</a>'; return div; }; map.addControl(attributionControl); var zoomControl = L.control.zoom({ position: "bottomright" }).addTo(map); var locateControl = L.control.locate({ position: "bottomright", drawCircle: true, follow: true, setView: true, keepCurrentZoomLevel: false, markerStyle: { weight: 1, opacity: 0.8, fillOpacity: 0.8 }, circleStyle: { weight: 1, clickable: false }, icon: 'fa fa-location-arrow', metric: false, strings: { title: "My location", popup: "You are within {distance} {unit} from this point", outsideMapBoundsMsg: "You seem located outside the boundaries of the map" }, locateOptions: { maxZoom: 9, watch: true, enableHighAccuracy: true, maximumAge: 10000, timeout: 10000 } }).addTo(map); function parsePermaLink(parser) { var url = window.location.search.substr(1); if (!url) { url = window.location.hash.substr(1); } if (url !== '') { nvps = url.split('&'); $.each(nvps, function(index, value) { var nvp = value.split('='); parser(nvp[0], nvp[1]); }); } } function paramParser(key, value) { switch (key) { case 'id': permaLink.id = parseInt(value); break; case 'lang': permaLink.lang = value; break; default: break; } } function zoomAndPopup(marker) { markerClusters.zoomToShowLayer(marker, function() { marker.fire('click'); }); } $(document).ready(function() { parsePermaLink(paramParser); });
import React from 'react'; import { mount } from 'enzyme'; import Errors from '../Errors'; import { errors } from './fixtures'; function setup() { let component = mount(<Errors errors={errors} />); return { component, errorItems: component.find('.error-messages > div'), }; } describe('Components::Errors', () => { it('should render errors correctly', () => { const { errorItems } = setup(); expect(errorItems.length).toEqual(errors.length); }); });
var express = require('express'); var app = express(); app.use(express.static(__dirname + '/')); app.get('/', function (req, res) { res.sendFile(__dirname + '/index.html'); }); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); });
/* host_checker.js https://atmospherejs.com/particle4dev/meteor-cron2 */ // appEE = new (Npm.require('events').EventEmitter); // var checkHost = function( args ){ }; // var i = 0; var c = CRON.createNewCronJob('5 * * * * *', function () { // i++; // console.log('You will see this message ' + i + ' second'); appEE.emit('checkCronEvent', {"dt": moment().format('YYYY-MM-DD HH:mm:ss') }); // collNodes.find({}).forEach(function(host){ Meteor._debug("Sending "+host.host+" to check:"); host.services.forEach(function(service){ if (service.enable && service .type!=='icmp' ){ Meteor._debug("---> service type: "+service.type); appEE.emit("checkHostService", {"host":host.host, "type":service.type}); }; }); }); // }, 'America/Los_Angeles'); // on stop c.onStop(function () { console.log('stop'); }); c.run(); // appEE.on("checkCronEvent", function(event){ Meteor._debug("checkCronEvent received at "+event.dt); }); // appEE.on("checkHostService", Meteor.bindEnvironment(function(event) { Meteor._debug("checkHostService received "+EJSON.stringify(event) ); var url; var res = {statusCode: 666}; var ret = 'unknown'; // if (event.type === 'http'){ url = "http://"+event.host; try { res = HTTP.get(url); } catch (exc){ Meteor._debug("checkHostService HTTP exception: "+exc); }; } else if (event.type === 'https'){ url = "https://"+event.host; try { res = HTTP.get(url); } catch (exc){ Meteor._debug("checkHostService HTTPS exception: "+exc); }; } else { res.statusCode = 666; }; // // Meteor._debug("checkHostService res:", res.statusCode); // if (res.statusCode === 200 ){ ret = 'OK'; } else { ret = 'ERROR'; }; Meteor._debug("checkHostService ret:", ret); // appEE.emit("updateHostService", {host: event.host, type:event.type, res: ret}); // }, function(exc){ Meteor._debug("Exception from checkHostService:", exc); }) ); // appEE.on("updateHostService", Meteor.bindEnvironment(function(event) { Meteor._debug("updateHostService received "+EJSON.stringify(event) ); collNodes.update( {host: event.host, "services.type": event.type}, {$set:{ "services.$.last_check_dt": moment().format('YYYY-MM-DD HH:mm:ss'), "services.$.last_check_res": event.res }} ); // appEE.emit("updateGlobalStats", {"host":event.host, "res":event.res}); // }, function(exc){ Meteor._debug("Exception from checkHostUpdate:", exc); }) ); // appEE.on("updateGlobalStats", Meteor.bindEnvironment(function(event) { Meteor._debug("updateGlobalStats:", event); // var incOk = 0; var incError = 0; if (event.res=="OK") incOk = 1; if (event.res=="ERROR") incError = 1; // collGlobalStats.update( {}, { $set:{"run_last_dt": moment().format('YYYY-MM-DD HH:mm:ss'), "run_last_ts":moment().valueOf() }, $inc:{"tests.total":1, "tests.ok":incOk, "tests.error":incError} } ); // }, function(exc){ Meteor._debug("Exception from updateGlobalStats: ", exc); }) ); //
var mongo = require('mongodb').MongoClient; var url = process.env.MONGODB_URL; mongo.connect(url, function(err, db) { global.db = db; });
define( [ 'jsorrery/NameSpace', 'jsorrery/algorithm/MoveAlgorithm', 'jsorrery/algorithm/Gravity' ], function(ns, MoveAlgorithm, Gravity) { 'use strict'; var beginPos = new THREE.Vector3(); var workVect = new THREE.Vector3(); var moveBody = function(body, deltaT, deltaTSq, i){ if(body.previousPosition){ beginPos.copy(body.position); body.force.multiplyScalar(body.invMass);//force is in newtons, need to divide it by the mass to get number of m/s*s of accel body.force.multiplyScalar(deltaTSq); workVect.copy(body.position).sub(body.previousPosition); body.position.add(workVect); body.position.add(body.force);/**/ body.previousPosition.copy(beginPos); } else {//initialisation (with Euler algorithm) body.previousPosition = body.position.clone(); workVect = new THREE.Vector3(); body.force.multiplyScalar(body.invMass);//force is in newtons, need to divide it by the mass to get number of m/s*s of accel body.force.multiplyScalar(deltaT); body.velocity.add(body.force); var correctedVel = body.getVelocity(); correctedVel.multiplyScalar(deltaT);//speed needs to take deltaT into account body.position.add(correctedVel); } body.force.x = body.force.y = body.force.z = 0;//reset force }; var Verlet = Object.create(MoveAlgorithm); Verlet.name = 'Verlet'; Verlet.moveBodies = function(epochTime, deltaT) { this.computeDeltaT(deltaT); Gravity.calculateGForces(this.bodies); for(var i=0; i<this.bodies.length; i++){ this.bodies[i].beforeMove(deltaT); if(this.bodies[i].calculateFromElements){ this.bodies[i].setPositionFromDate(epochTime + deltaT, false); } else if(!this.bodies[i].isStill){ moveBody(this.bodies[i], deltaT, this.deltaTSq, i); } this.bodies[i].afterMove(deltaT); } }; return Verlet; } );
// Simulate config options from your production environment by // customising the .env file in your project's root folder. require('dotenv').load(); // Require keystone var keystone = require('keystone'), pkg = require('./package.json'); // Initialise Keystone with your project's configuration. // See http://keystonejs.com/guide/config for available options // and documentation. keystone.init({ 'name': 'Evilcome', 'brand': 'Evilcome', 'less': 'public', 'static': 'public', 'favicon': 'public/favicon.ico', 'views': 'templates/views', 'view engine': 'jade', 'view cache': process.env.NODE_ENV === 'production' ? true : false, 'auto update': true, 'mongo': process.env.MONGO_URI || 'mongodb://localhost/' + pkg.name, 'session': true, 'auth': true, 'user model': 'User', 'cookie secret': process.env.COOKIE_SECRET || 'evilcome.com', 'ga property': process.env.GA_PROPERTY, 'ga domain': process.env.GA_DOMAIN, 'basedir': __dirname }); // Load your project's Models keystone.import('models'); keystone.set('locals', { _: require('underscore'), moment: require('moment'), env: keystone.get('env'), utils: keystone.utils, plural: keystone.utils.plural, editable: keystone.content.editable, ga_property: keystone.get('ga property'), ga_domain: keystone.get('ga domain') }); keystone.set('routes', require('./routes')); // Setup common locals for your emails. The following are required by Keystone's // default email templates, you may remove them if you're using your own. // Configure the navigation bar in Keystone's Admin UI keystone.set('nav', { 'posts': ['posts', 'post-categories', 'post-comments'], 'users': 'users', 'games': 'games', 'links': ['links', 'link-tags', 'link-comments'] }); // Start Keystone to connect to your database and initialise the web server keystone.start();
const React = require('react'); const { render } = require('react-dom'); const { default: ReactTether } = require('../../../lib/react-tether'); function App() { return ( <div> <h1>CommonJS example</h1> <ReactTether attachment="top left" renderTarget={ref => ( <span ref={ref} id="child-1"> Child 1 </span> )} renderElement={ref => ( <span ref={ref} id="child-2"> Child 2 </span> )} /> </div> ); } render(<App />, document.querySelector('#app'));
define([ 'jquery', 'underscore', 'backbone', 'views/main/box', 'views/employees/employee', ], function($, _, Backbone, BoxView, EmployeesView){ var EmployeesPageView = Backbone.View.extend({ initialize: function(options){ this.employees = new EmployeesView(options); }, render: function() { var boxView = new BoxView(); boxView.render({ el: '#box', context: { title: 'Сотрудник', body: this.employees.$el, footer: null } }); } }); return EmployeesPageView; });
/** * System configuration for Angular samples * Adjust as necessary for your application needs. */ (function (global) { System.config({ paths: { // paths serve as alias 'npm:': 'node_modules/' }, // map tells the System loader where to look for things map: { // our app is within the app folder 'app': 'app', // angular bundles '@angular/core': 'npm:@angular/core/bundles/core.umd.js', '@angular/common': 'npm:@angular/common/bundles/common.umd.js', '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', '@angular/http': 'npm:@angular/http/bundles/http.umd.js', '@angular/router': 'npm:@angular/router/bundles/router.umd.js', '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', 'angular2-datatable': 'npm:angular2-datatable', 'lodash': 'npm:lodash/lodash.js', "ng2-accordion": "npm:ng2-accordion", // other libraries 'rxjs': 'npm:rxjs', 'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js' }, // packages tells the System loader how to load when no filename and/or no extension packages: { app: { defaultExtension: 'js', meta: { './*.js': { loader: 'systemjs-angular-loader.js' } } }, 'lodash': { defaultExtension: 'js' }, rxjs: { defaultExtension: 'js', main: 'Rx.js' }, 'angular2-datatable': { main: 'index.js', defaultExtension: 'js' }, "ng2-accordion": { main: "index.js", defaultExtension: "js" } } }); })(this);
'use strict'; console.log("Environment: " + '/* @echo NODE_ENV */' + " | Version: " + '/* @echo VERSION */'); angular.module('<%= appname %>.service', []); angular.module('<%= appname %>.directive', []); angular.module('<%= appname %>.filter', []); angular.module('<%= appname %>', [ '<%= appname %>.service' ,'<%= appname %>.directive' ,'<%= appname %>.filter' // module:block // endblock ]);
(function($){$.fn.letitflow=function(userParams){var defaults={maxWidth:"",maxHeight:"",themeColor:"dark",colorText:"light",colorBar:"#777",color2:"",datesBelow:false,flat:false,firstDay:"",lastDay:"",steps:[],stepsLabel:true,lastStepName:""};var params=$.extend(defaults,userParams);return this.each(function(){var $t=$(this);$t.append('<div class="letItFlow"><div class="lif-progress"><div class="lif-bar"><span></span></div></div></div>');var global={init:function(){views.initViews()}};var model={totalLength:0, totalProgression:null,nSteps:0,nStepsName:0,dates:[],labWidth:[],progression:function(){var toDay=$.now();this.totalLength=params.lastDay-params.firstDay;if(toDay>params.firstDay)this.totalProgression=Math.abs((toDay-params.firstDay)/this.totalLength)*100;else this.totalProgression=0;this.totalPercents=this.totalProgression.toFixed(0);views.barUpdateViews()},getSteps:function(obj){this.nSteps=params.steps.length;for(var i=0;i<this.nSteps;i++){if(obj[i]){if(obj[i].stepName){stepName=obj[i].stepName; this.nStepsName++}else stepName="";stepDate=new Date(obj[i].stepDate)}this.dates.push({sName:stepName,sDate:stepDate,sPerc:"",sWidth:""})}},createSteps:function(){this.dates=[{sName:params.firstDayName,sDate:params.firstDay,sPerc:"0",sWidth:"0"},{sName:params.lastStepName,sDate:params.lastDay,sPerc:"100",sWidth:"100"}];model.getSteps(params.steps);this.dates.sort(function(x,y){return x.sDate-y.sDate});$(".lif-progress .lif-bar",$t).before('<div class="cuts"></div>');for(var i=1;i<this.dates.length;i++){this.dates[i].sPerc= Math.abs((this.dates[i].sDate-params.firstDay)/this.totalLength)*100;this.dates[i].sWidth=(this.dates[i].sPerc-this.dates[i-1].sPerc).toFixed(4);$(".cuts",$t).append('<span title="'+this.dates[i].sName+'" style="width:'+this.dates[i].sWidth+'%;"> </span>')}if(this.nStepsName){$(".endsDates",$t).after('<div class="stepTooltip"></div>');var delayID;$(".cuts span",$t).css("cursor","pointer");$(".cuts span, .tt",$t).on("click",function(){thisName=$(this).attr("title");$(".stepTooltip",$t).html("<span>"+ thisName+"</span>").fadeIn("fast");clearTimeout(delayID);delayID=setTimeout(function(){$(".stepTooltip span",$t).fadeOut("slow")},1800)})}},addLabels:function(){$(".lif-progress",$t).before('<div class="lif-steps"></div>');for(var i=1;i<this.dates.length;i++){$pWidth=this.dates[i].sWidth;$(".lif-steps",$t).append('<p class="step'+[i]+'" style="width:'+$pWidth+'%;"><span>'+this.dates[i].sName+"</span></p>");this.labWidth[i]=$(".lif-steps .step"+[i]+" span").width()}views.labelHighlight();views.labelWidth()}, formatEndsDates:function(mydate){newDD=("0"+mydate.getDate()).slice(-2);newMM=("0"+(mydate.getMonth()+1)).slice(-2);newYY=mydate.getFullYear();newDate='<span class="dateday">'+newDD+"</span>";newDate+='<span class="datemonth">'+newMM+"</span>";newDate+='<span class="dateyear">'+newYY+"</span>";return newDate}};var colorBar={layoutColor:function(){$(".letItFlow",$t).removeClass("light");if(params.themeColor=="light")$(".letItFlow",$t).addClass("light")},bColor:function(){$(".lif-bar",$t).css("background-color", params.colorBar)},textColor:function(){switch(params.colorText){case "dark":$(".lif-bar",$t).css({"color":"#333","text-shadow":"0px 1px 0 rgba(255,255,255,0.7)"});break;case "light":$(".lif-bar",$t).css({"color":"#FFF","text-shadow":"0px 1px 0 rgba(0,0,0,0.7)"});break;default:break}},bGradient:function(){$(".lif-bar",$t).css({"background":params.colorBar,"background":"-moz-linear-gradient(left, "+params.colorBar+" 0%, "+params.color2+" 100%)","background":"-webkit-gradient(linear, left top, right top, color-stop(0%,"+ params.colorBar+"), color-stop(100%,"+params.color2+"))","background":"-webkit-linear-gradient(left, "+params.colorBar+" 0%,"+params.color2+" 100%)"});$(".lif-bar",$t).css({"background":"-o-linear-gradient(left, "+params.colorBar+" 0%,"+params.color2+" 100%)","background":"-ms-linear-gradient(left, "+params.colorBar+" 0%,"+params.color2+")","background":"linear-gradient(to right, "+params.colorBar+" 0%,"+params.color2+" 100%)","filter":"progid:DXImageTransform.Microsoft.gradient( startColorstr='"+ params.colorBar+"', endColorstr='"+params.color2+"',GradientType=1 )","-ms-filter":"progid:DXImageTransform.Microsoft.gradient(startColorstr='"+params.colorBar+"', endColorstr='"+params.color2+"')"})}};var views={initViews:function(){model.progression();this.barInitViews();if(params.steps.length){model.createSteps();if(params.stepsLabel){model.addLabels();$(".letItFlow",$t).removeClass("no-labels")}else $(".letItFlow",$t).addClass("no-labels")}this.windowResize()},barInitViews:function(){colorBar.layoutColor(); startDate='<div class="start">'+model.formatEndsDates(params.firstDay)+"</div>";endDate='<div class="end">'+model.formatEndsDates(params.lastDay)+"</div>";$(".lif-progress",$t).after('<div class="endsDates">'+startDate+endDate+"</div>");colorBar.textColor();if(params.color2)colorBar.bGradient();else colorBar.bColor();if(params.maxWidth)$(".letItFlow",$t).css("max-width",params.maxWidth);if(params.maxHeight){heightVal=params.maxHeight.replace(/[^-\d\.]/g,"");if(heightVal<21){$(".letItFlow",$t).addClass("small"); if(heightVal<11){$(".letItFlow",$t).removeClass("small");$(".letItFlow",$t).addClass("xsmall")}}$(".lif-progress",$t).css("height",params.maxHeight);newLineH=heightVal-2+"px";$(".lif-progress .lif-bar span",$t).css("line-height",newLineH)}if(params.datesBelow)$(".letItFlow",$t).addClass("below");if(params.flat)$(".letItFlow",$t).addClass("flat")},barUpdateViews:function(){if(model.totalProgression<100){$(".lif-bar",$t).width(model.totalProgression+"%");$(".lif-bar span",$t).html(model.totalPercents+ " %")}else{$(".lif-bar",$t).width("100%");$(".lif-bar span",$t).html("100 %")}if(model.totalPercents<8){$(".hoverinfo",$t).remove();$(".lif-bar",$t).before('<span class="hoverinfo">'+model.totalPercents+" %</span>")}else $(".hoverinfo",$t).remove();this.labelHighlight()},labelHighlight:function(){for(var i=1;i<model.dates.length;i++)if(model.dates[i].sPerc-model.dates[i].sWidth<model.totalProgression)$(".lif-steps .step"+[i],$t).css("opacity","1")},labelWidth:function(){for(var i=1;i<model.dates.length;i++){stepOuter= $(".step"+[i],$t);stepOuterWid=stepOuter.width();stepInner=$(".step"+[i]+" span",$t);stepInnerWid=model.labWidth[i];getName=model.dates[i].sName;if(stepOuterWid<stepInnerWid)stepInner.html('<a class="tt" title="'+getName+'">\u25a0</a>');else stepInner.html(getName)}},windowResize:function(){$(window).resize(function(){views.labelWidth()})}};global.init();setInterval(function(){model.progression()},3600)})}})(jQuery);
/** * A hash table key value storage * Use it to quickly and resource efficiently find values bound to large object or large string keys in a very large collection. It uses CRC32 algorythm to convert supplied values into integer hashes and * * @author Nikola Stamatovic Stamat < stamat@ivartech.com > * @copyright ivartech < http://ivartech.com > * @version 1.0 * @date 2013-11-17 * @namespace ivar.data */ ivar.namespace('ivar.data'); /** * @example * a = {'a':1, 'b':{'c':[1,2,[3,45],4,5], 'd':{'q':1, 'b':{q':1, 'b':8},'c':4}, 'u':'lol'}, 'e':2}; b = {'a':1, 'b':{'c':[2,3,[1]], 'd':{'q':3,'b':{'b':3}}}, 'e':2}; c = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." var hc = new HashMap(); hc.put({a:1, b:1}); hc.put({b:1, a:1}); hc.put(true); hc.put('true'); hc.put(a) console.log(hc.exists(b)) console.log(hc.exists(a)) console.log(hc.get(a)) console.log(hc.exists(c)) hc.remove(a) console.log(hc.exists(a)) hc.put(c) console.log(hc.exists(c)) console.log(hc.get(c)) * @class * @param {array} a An array of objects {key: key, value: value} to store on init */ ivar.data.HashMap = function(a) { /** * Keeps values in arrays labeled under typewise crc32 hashes * * @this HashMap * @protected */ var storage = {}; this.getStorage = function() { return storage; } /** * Produces an integer hash of a given value * If the object is passed, before JSON stringification the properties are ordered. Note that because crc32 hashes strings, then boolean true would be the same as string 'true' or a sting '123' would be the same as integer 123, etc... We could add some modifier to solve this but a chance of using this with a set of values different by type is low in common use. * * @this HashCache * @protected * @param {any} value Any value to be hashed * @return {integer} Integer hash * * @see ivar.orderedStringify * @see ivar.whatis * @see ivar.types */ var hashFn = function(value) { var type = ivar.types[ivar.whatis(value)]; if (type === 5 || type === 6) { value = ivar.orderedStringify(value); } else { value = value.toString(); } return ivar.crc32(value); }; /** * Gets value stored under the submited key * * @this HashMap * * @param {any} key Submited key * @return {any} Value stored under the key * * @see HashMap.storage * @see ivar.equal */ this.get = function(key) { var hash = hashFn(key); var bucket = storage[hash]; if (bucket && bucket.length > 0) { for (var i = 0; i < bucket.length; i++) { if(ivar.equal(bucket[i].key, key)) return bucket[i].value; } } }; /** * Gets bucket id if the key is already stored under the hash in the bucket * Only for this.put * * @this HashMap * * @param {any} key Submited key * @return {integer} If the key exists in bucket returns positive integer, otherwise -1 * * @see HashMap.storage * @see ivar.equal */ var getBucketId = function(hash, key) { var bucket = storage[hash]; if (bucket && bucket.length > 0) { for (var i = 0; i < bucket.length; i++) { if(ivar.equal(bucket[i].key, key)) return i; } } return -1; }; /** * Hashes the value and stores it in the hash table where the generated hash is a key * * @this HashMap * @public * @param {any} key Any value to be stored * @param {any} value Any value to be stored * * @see HashMap.hashFn * @see HashMap.storage * @see HashMap.getBucketId */ this.put = function(key, value) { var hash = hashFn(key); var bucket_id = getBucketId(hash, key); if(bucket_id === -1) { if (storage.hasOwnProperty(hash)) { storage[hash].push({key: key, value: value}); } else { storage[hash] = [{key: key, value: value}]; } } else { storage[hash][bucket_id] = {key: key, value: value}; } } /** * Checks if the value is listed in HashCache instance * * @this HashMap * @public * @param {any} key Any key to be checked for existance * @return {boolean} If the value is listed * * @see HashMap.hashFn * @see HashMap.hashHoldsKey */ this.exists = function(key) { var hash = hashFn(key); return getBucketId(hash, key) > -1 ? true : false; } /** * Finds the value listed and removes it from the HashCache instance * * @this HashMap * @public * @param {any} value Any value to be removed * @return {boolean} If the value existed and was removed * * @see HashMap.hashFn * @see HashMap.storage * @see ivar.equal */ this.remove = function(key) { var hash = hashFn(key); var bucket_id = getBucketId(hash, key); var res = false; if(bucket_id > -1) { bucket_id > 0 ? storage[hash].splice(bucket_id, 1) : delete storage[hash]; return true; } return res; } //INIT if (a !== undefined && ivar.whatis(a) === 'array') { for (var i = 0; i < a.length; i++) { this.put(a[i].key, a[i].value); } } };
var Scraper = require('./Scraper'); class scraper extends Scraper.HTMLScraper { constructor(company) { super(company); this.jobs_url = 'https://www.specialized.com/us/en/careers'; this.listscraper = { urls: { listItem: ".open li", data: { url: { selector: "a", attr: "href" } } } }; this.relativelinks = false; this.jobscraper = { title: { selector: ".app-title" }, description: { selector: "#content", how: "html" }, location: { selector: ".location", how: "text" } }; } } module.exports = scraper;
/** * Altair's Event/Emitter is a little twist on the original NodeJs EventEmitter implementation. The event system has been * augmented with a query engine to allow for much more sophisticated listening. Take a look at the ReadMe.md or someshit. */ define(['altair/facades/declare', './Event', 'altair/facades/hitch', 'altair/events/Deferred', 'altair/Deferred', './QueryAgent', 'dojo/promise/all', 'altair/facades/when', 'altair/facades/series', 'lodash' ], function (declare, Event, hitch, Deferred, BaseDeferred, QueryAgent, all, when, series, _) { var agent = new QueryAgent(); return declare(null, { _eventListenerQueryAgent: agent, _listeners: null, constructor: function () { this._listeners = {}; }, /** * Alias for "on()" * * @param event * @param callback * @param query * @param options * @returns {dojo.Deferred} */ addEventListener: function (event, callback, query, options) { return this.on(event, callback, query, options); }, /** * Add a listener with optional query * * @param event * @param callback * @param query * @param options * @returns {dojo.Deferred} */ on: function (event, callback, query, options) { //get _listeners ready if (!this._listeners[event]) { this._listeners[event] = []; } //if they passed a query as the 2nd argument if(callback && !_.isFunction(callback)) { query = callback; callback = null; } //create deferred & listener var deferred = new Deferred(), listener = { callback: callback, query: query, deferred: deferred }; //add listener to array this._listeners[event].push(listener); return deferred; }, /** * Remove a listener by its deferred * * @param event string, name of the event * @param deferred, the deferred that was returned from "on" * @returns {null} */ removeEventListener: function (event, deferred) { if(this._listeners[event]) { this._listeners[event] = _.filter(this._listeners[event], function (listener) { return listener.deferred !== deferred; }); } return this; }, /** * Emit an event by name passing along data. Customize it with options. * * @param event * @param data * @param callback * @param options */ emit: function (event, data, options) { event = this.coerceEvent(event, data); //build a list of results all listeners... var list = [], _agent; if(this._listeners[event.name]) { _agent = (options && options.agent) ? options.agent : this._eventListenerQueryAgent; _.each(this._listeners[event.name], hitch(this, function (listener) { if(_agent.matches(event, listener.query)) { var dfd, results; //if the listener was passed as the callback, or 2nd param, of on() if(listener.callback) { results = hitch(listener, 'callback', event); list.push(results); } if(listener.deferred.hasWaiting()) { list.push(function (listener, event) { return function () { var dfd = new BaseDeferred() listener.deferred.resolve(event).then(function (results) { results = results[0]; if(results !== undefined && (!results.isInstanceOf || !results.isInstanceOf(Event))) { return when(results).then(hitch(dfd, 'resolve')).otherwise(hitch(dfd, 'reject')); } dfd.resolve(); }).otherwise(function (err) { dfd.reject(err); }); return dfd; }; }(listener, event)); } } })); } return series(list).then(function (results) { event.setResults(results); return event; }); }, /** * Pass an event name (string) or event object and get back an event object. Very handy way to normalize data * for event related logic. * * @param eventName * @param data * @returns {altair.io.core.lib.altair.events.Event} * @private */ coerceEvent: function (eventName, data) { return (typeof eventName === 'string') ? new Event(eventName, data, this) : eventName; } }); });
/** * Created by shawn on 1/10/17. */ describe('Logging', function () { var log = LogManager.DefaultLogger /** * This function is used by tests - simply returns whatever is passed to it (identity function) * @param i * @returns {*} */ EC.foo = function (i) { return i; }; beforeEach(function () { // override the NetSuite native logging call for each test with a fresh spy so we can track calls // to this underlying method in test assertions. global.nlapiLogExecution = sinon.spy(); }); it('test Debug has correct event type', function () { log.debug('hello world') global.nlapiLogExecution.should.have.been.calledOnce global.nlapiLogExecution.should.have.been.calledWith('debug') }); it('test Error has correct event type', function () { log.error('hello world') global.nlapiLogExecution.should.have.been.calledOnce; // errors on the logger map to emergency (highest level) in NS global.nlapiLogExecution.should.have.been.calledWith('emergency'); }); it('test Audit has correct event type', function () { log.info('hello world'); global.nlapiLogExecution.should.have.been.calledOnce; global.nlapiLogExecution.should.have.been.calledWith('audit'); }); it('test Warning has correct event type', function () { log.warn('hello world'); global.nlapiLogExecution.should.have.been.calledOnce; global.nlapiLogExecution.should.have.been.calledWith('error'); }); it("test logging details as an object", function () { var anObject = {foo: "bar", baz: 3}; log.info('hello world', anObject); // to show the call details on console: // console.log(global.nlapiLogExecution.getCall(0)); global.nlapiLogExecution.should.have.been.calledOnce; global.nlapiLogExecution.should.have.been.calledWith('audit', "hello world", '{"foo":"bar","baz":3}'); }); it("test logging details as a string", function () { log.info('hello world', "surely a string"); // to show the call details on console: // console.log(global.nlapiLogExecution.getCall(0)); global.nlapiLogExecution.should.have.been.calledOnce; global.nlapiLogExecution.should.have.been.calledWith('audit', "hello world", "surely a string"); }); /** * Our Auto-Logging feature, which uses AOP (aspect oriented programming) to achieve codeless logging */ describe("auto-logging", function () { afterEach(function () { // forcibly remove any AOP applied to our foo method - presence of the unweave() method // is the hint that it's an aop-ized function. while (EC.foo.unweave) EC.foo.unweave(); }); it("test autologging without args", function () { // create an object to spy on. var foo = { a: function (p) { } }; LogManager.autoLogMethodEntryExit({target: foo, method: 'a'}, { withArgs: false }); foo.a("an argument"); // this argument should not be logged // get the 3rd argument ('details') of the first invocation of nlapiLogExecution() var detailsArgument = global.nlapiLogExecution.args[0][2]; assert.isNull(detailsArgument); }); it("autologging with all defaults", function () { LogManager.autoLogMethodEntryExit() EC.foo("hi"); var methodEntry = global.nlapiLogExecution.args[0]; var methodExit = global.nlapiLogExecution.args[1]; // get the 3rd argument ('details') of the first invocation of nlapiLogExecution() var detailsArgument = methodEntry[2]; // by default, arguments are logged on method entry assert.ok(detailsArgument); // and return values also logged methodExit[2].should.equal('returned: "hi"'); }); it("test autologging with args by default", function () { global.nlapiLogExecution.reset(); // create an object to spy on. var foo = { a: function (p) { } }; LogManager.autoLogMethodEntryExit({target: foo, method: 'a'}); foo.a("an argument"); // get the 3rd argument of the first invocation of nlapiLogExecution() var detailsArgument = global.nlapiLogExecution.args[0][2]; detailsArgument.should.contain("an argument"); }); it("test autologging with return value", function () { global.nlapiLogExecution.reset(); // object with a function that returns something var foo = { a: function () { return 'a return value'; } }; LogManager.autoLogMethodEntryExit({target: foo, method: 'a'}); foo.a('an argument'); // nlapiLogExecution() 'details' argument should include the return value on the second invocation var detailsArgument = global.nlapiLogExecution.args[1][2]; detailsArgument.should.contain('a return value'); }); it("test autologging function that returns nothing", function () { global.nlapiLogExecution.reset(); // object with a function that returns nothing var foo = { a: function (p) { } }; LogManager.autoLogMethodEntryExit({target: foo, method: 'a'}); foo.a("an argument"); // nlapiLogExecution() 'details' argument should include the return value on the second invocation var detailsArgument = global.nlapiLogExecution.args[1][2]; // method that returns nothing should be undefined detailsArgument.should.contain('undefined'); }); it("test autologging without return value", function () { global.nlapiLogExecution.reset(); // object with a function that returns something var foo = { a: function () { return "a return value"; } }; // last boolean argument turns off return value logging LogManager.autoLogMethodEntryExit({target: foo, method: 'a'}, {withReturnValue: false}); foo.a("an argument"); // nlapiLogExecution() 'details' argument should include the return value on the second invocation var detailsArgument = global.nlapiLogExecution.args[1][2]; assert.isNull(detailsArgument); }); it("test autologging with profiling option", function () { global.nlapiLogExecution.reset(); // object with a function that returns something var foo = { a: function () { return "a return value"; } }; // last boolean argument turns off return value logging LogManager.autoLogMethodEntryExit({target: foo, method: 'a'}, {withProfiling: true}); var retval = foo.a("an argument"); retval.should.equal("a return value"); // called once before method, once after global.nlapiLogExecution.should.have.been.calledTwice; console.log("nlapiLogExecution 1:" + JSON.stringify(global.nlapiLogExecution.getCall(0).args)); console.log("nlapiLogExecution 2:" + JSON.stringify(global.nlapiLogExecution.getCall(1).args)); // nlapiLogExecution() 'title' argument should include method elapsed time var titleArgument = global.nlapiLogExecution.args[1][1]; // this assertion assumes your computer is fast enough for this call to return 0 milliseconds :) titleArgument.should.contain('Exit a() 0ms = 0.00 minutes'); }); it("test autologging without profiling option", function () { global.nlapiLogExecution.reset(); // object with a function that returns something var foo = { a: function () { return "a return value"; } }; // last boolean argument turns off return value logging LogManager.autoLogMethodEntryExit({target: foo, method: 'a'}, {withProfiling: false}); var retval = foo.a("an argument"); retval.should.equal("a return value"); // called once before method, once after global.nlapiLogExecution.should.have.been.calledTwice; console.log('nlapiLogExecution 1:' + JSON.stringify(global.nlapiLogExecution.getCall(0).args)); console.log('nlapiLogExecution 2:' + JSON.stringify(global.nlapiLogExecution.getCall(1).args)); // nlapiLogExecution() 'title' argument should include method elapsed time var titleArgument = global.nlapiLogExecution.args[1][1]; titleArgument.should.equal('Exit a()'); }); it("logs at 'DEBUG' level by default", function () { LogManager.autoLogMethodEntryExit(); EC.foo(); // get the log type argument from the first invocation of nlapiLogExecution global.nlapiLogExecution.args[0][0].should.equal('debug'); // and the second invocatin (method Exit()) global.nlapiLogExecution.args[1][0].should.equal('debug'); }); it("log with different logLevel", function () { LogManager.autoLogMethodEntryExit({target: EC, method: 'foo'}, { logLevel:LogManager.logLevel.info}) EC.foo(); // get the log type argument from the first invocation of nlapiLogExecution global.nlapiLogExecution.args[0][0].should.equal('audit'); // and the second invocatin (method Exit()) global.nlapiLogExecution.args[1][0].should.equal('audit'); }); describe("governance auto-logging", function () { beforeEach(function () { }); afterEach(function () { }); it("logs number of units remaining on function exit", function () { LogManager.autoLogMethodEntryExit({target: EC, methods: /\w/}, { withGovernance:true }); var result = EC.foo("bar"); result.should.equal('bar'); // should auto log twice, once before method entry, once after global.nlapiLogExecution.should.have.been.calledTwice; // second call, function exit autologging var title = global.nlapiLogExecution.args[1][1]; title.should.contain('governance: 1000'); }); }); }); // Logger can be configured with optional correlation id logged as part of the message title describe("Correlation IDs", function () { afterEach(function () { // reset Correlation ID so other tests won't see it (Log is a global singleton) LogManager.includeCorrelationId = false; }); it('logs without correlation id by default', function () { log.debug('hello world'); global.nlapiLogExecution.should.have.been.calledOnce; global.nlapiLogExecution.firstCall.args[1].should.not.contain(">"); }); it('logs with random correlation id when requested', function () { LogManager.includeCorrelationId = true; dump('correlation id: ' + LogManager.correlationId); log.debug('hello world'); global.nlapiLogExecution.should.have.been.calledOnce; global.nlapiLogExecution.firstCall.args[1].should.contain(LogManager.correlationId + '>'); dump(global.nlapiLogExecution.firstCall.args[1]); }); it('maintains the same correlation id across multiple log calls', function () { LogManager.includeCorrelationId = true; dump('correlation id: ' + LogManager.correlationId); // make several calls to the logger, all should have the same correlation id log.debug('hello world'); log.info('here I am'); log.warn('again!'); global.nlapiLogExecution.should.have.been.calledThrice; dump(global.nlapiLogExecution.firstCall.args); dump(global.nlapiLogExecution.secondCall.args); dump(global.nlapiLogExecution.thirdCall.args); var detailsShouldMatch = new RegExp(LogManager.correlationId + '>'); assert(global.nlapiLogExecution.alwaysCalledWithMatch(sinon.match.any, detailsShouldMatch)); }); it('can use a custom correlation id', function () { LogManager.includeCorrelationId = true; // set custom correlation id LogManager.correlationId = "myid"; dump('correlation id: ' + LogManager.correlationId); log.debug('hello world'); global.nlapiLogExecution.should.have.been.calledOnce; global.nlapiLogExecution.firstCall.args[1].should.contain('myid>'); dump(global.nlapiLogExecution.firstCall.args[1]); }); }); // Multiple loggers can be used and configured with different log levels describe("Multiple loggers", function () { afterEach(function () { }); it('basic logging', function () { // default logger is named 'log' with logger name 'default' with loglevel 'debug' log.debug('hello world'); global.nlapiLogExecution.should.have.been.calledOnce; }); it('can define multiple independent named loggers', function () { // get a logger with the name 'foo' var fooLogger = LogManager.getLogger('foo') // get another logger with the name 'bar' var barLogger = LogManager.getLogger('bar') fooLogger.setLevel(LogManager.logLevel.warn) barLogger.setLevel(LogManager.logLevel.info) // no NS log methods should have been invoked at this point global.nlapiLogExecution.should.not.have.been.called; // the loggers should have different logging levels fooLogger.level.should.be.equal(LogManager.logLevel.warn) barLogger.level.should.be.equal(LogManager.logLevel.info) }); it('separate loggers have different log levels', function () { // get a logger with the name 'foo' var fooLogger = LogManager.getLogger('foo') // get another logger with the name 'bar' var barLogger = LogManager.getLogger('bar') fooLogger.setLevel(LogManager.logLevel.warn) barLogger.setLevel(LogManager.logLevel.info) // invoke foo logger with level > warning so it should log fooLogger.error('an error!') // invoke barLogger with a level < info so it should NOT log anything barLogger.debug('debugging!') global.nlapiLogExecution.should.have.been.calledOnce; // log title global.nlapiLogExecution.firstCall.args[1].should.contain('[foo]'); }); it('logs with random correlation id when requested', function () { LogManager.includeCorrelationId = true; dump('correlation id: ' + LogManager.correlationId); log.debug('hello world'); global.nlapiLogExecution.should.have.been.calledOnce; global.nlapiLogExecution.firstCall.args[1].should.contain(LogManager.correlationId + '>'); dump(global.nlapiLogExecution.firstCall.args[1]); }); it('maintains the same correlation id across multiple log calls', function () { LogManager.includeCorrelationId = true; dump('correlation id: ' + LogManager.correlationId); // make several calls to the logger, all should have the same correlation id log.debug('hello world'); log.info('here I am'); log.warn('again!'); global.nlapiLogExecution.should.have.been.calledThrice; dump(global.nlapiLogExecution.firstCall.args); dump(global.nlapiLogExecution.secondCall.args); dump(global.nlapiLogExecution.thirdCall.args); var detailsShouldMatch = new RegExp(LogManager.correlationId + '>'); assert(global.nlapiLogExecution.alwaysCalledWithMatch(sinon.match.any, detailsShouldMatch)); }); it('can use a custom correlation id', function () { LogManager.includeCorrelationId = true; // set custom correlation id LogManager.correlationId = "myid"; dump('correlation id: ' + LogManager.correlationId); log.debug('hello world'); global.nlapiLogExecution.should.have.been.calledOnce; global.nlapiLogExecution.firstCall.args[1].should.contain('myid>'); dump(global.nlapiLogExecution.firstCall.args[1]); }); }); });
var tasks = [ {"startDate":new Date("1981"),"endDate":new Date("1985"),"taskName":"6-5","status":"RUNNING"}, {"startDate":new Date("1986"),"endDate":new Date("1990"),"taskName":"7-5","status":"SUCCEEDED"}, {"startDate":new Date("1991"),"endDate":new Date("1995"),"taskName":"8-5","status":"FAILED"}, {"startDate":new Date("1996"),"endDate":new Date("2000"),"taskName":"9-5","status":"KILLED"}, {"startDate":new Date("2001"),"endDate":new Date("2005"),"taskName":"10-5","status":"RUNNING"}, {"startDate":new Date("2006"),"endDate":new Date("2010"),"taskName":"11-5","status":"SUCCEEDED"}, {"startDate":new Date("2011"),"endDate":new Date("2015"),"taskName":"12-5","status":"FAILED"} ]; var taskStatus = { "SUCCEEDED" : "bar", "FAILED" : "bar-failed", "RUNNING" : "bar-running", "KILLED" : "bar-killed" }; var taskNames = [ "6-5", "7-5", "8-5", "9-5", "10-5", "11-5", "12-5" ]; tasks.sort(function(a, b) { return a.endDate - b.endDate; }); var maxDate = tasks[tasks.length - 1].endDate; tasks.sort(function(a, b) { return a.startDate - b.startDate; }); var minDate = tasks[0].startDate; //var format = "%H:%M"; var format = "%Y"; var gantt = d3.gantt().taskTypes(taskNames).taskStatus(taskStatus).tickFormat(format); gantt(tasks);
function getNow() { return new Date().getTime(); } function getYearsSince(epoch) { var now = getNow(); var then = new Date(epoch); var years = Math.floor((now - then) / 31536000000); return years; } function addMinutes(epoch, m) { var da = epoch + (m * 60000); return da; } function addSeconds(epoch, m) { var da = epoch + (m * 1000); return da; } function subtractMinutes(epoch, m) { var da = epoch - (m * 60000); return da; } function subtractDays(epoch, _d) { // 1 day = 1440 mins as per google :) var da = subtractMinutes(epoch, (_d * 1440)); return da; } function addDays(epoch, _d) { // 1 day = 1440 mins as per google :) var da = addMinutes(epoch, (_d * 1440)); return da; } function addYears(epoch, m) { var da = epoch + (m * 31536000000); return da; } function isInFuture(epoch) { var now = getNow(); if (now < epoch) { return true; } else { return false; } } function isInPast(epoch) { var now = getNow(); if (now >= epoch) { return true; } else { return false; } } function getMillisecondsSince(epoch) { var now = getNow(); var then = new Date(epoch); var seconds = now - then; return seconds; } function getSecondsSince(epoch) { var now = getNow(); var then = new Date(epoch); var seconds = Math.floor((now - then) / 1000); return seconds; } function getMinutesSince(epoch) { var now = getNow(); var then = new Date(epoch); var minutes = Math.floor((now - then) / 60000); return minutes; } function getHoursSince(utcDate) { var now = getNow(); var then = new Date(utcDate); var hours = Math.floor((now - then) / 3600000); return hours; } function getDaysSince(utcDate) { var now = getNow(); var then = new Date(utcDate); var days = Math.floor((now - then) / 86400000); return days; } function getMinDate() { var now = getNow(); var then = now - (10 * 31536000000); return then; } function getMaxDate() { var now = getNow(); var then = now + (10 * 31536000000); return then; } function fromEpoch(epoch) { return epoch * 1000; } function toEpoch(hammerTime) { return Math.floor(hammerTime / 1000); } function getEpochBeforeMinutes(minutes){ var now = getNow(); var then = subtractMinutes(now, minutes); // addMinutes(minutes); //then = toEpoch(then); return then; } exports.now = getNow; exports.addSeconds = addSeconds; exports.addMinutes = addMinutes; exports.addDays = addDays; exports.subtractDays = subtractDays; exports.subtractMinutes = subtractMinutes; exports.addYears = addYears; exports.isInFuture = isInFuture; exports.isInPast = isInPast; exports.getMillisecondsSince = getMillisecondsSince; exports.getSecondsSince = getSecondsSince; exports.getMinutesSince = getMinutesSince; exports.getHoursSince = getHoursSince; exports.getDaysSince = getDaysSince; exports.getYearsSince = getYearsSince; exports.getMinDate = getMinDate; exports.getMaxDate = getMaxDate; exports.fromEpoch = fromEpoch; exports.toEpoch = toEpoch; exports.getEpochBeforeMinutes = getEpochBeforeMinutes;
this.NesDb = this.NesDb || {}; NesDb[ 'A7F135CF49F92E0FD9D03B6F48C1BD65CE8BCC77' ] = { "$": { "name": "Tetris", "altname": "テトリス", "class": "Licensed", "catalog": "BPS-T0", "publisher": "Bullet-Proof Software", "developer": "Bullet-Proof Software", "region": "Japan", "players": "1", "date": "1988-12-22" }, "cartridge": [ { "$": { "system": "Famicom", "revision": "A", "crc": "D074653D", "sha1": "A7F135CF49F92E0FD9D03B6F48C1BD65CE8BCC77", "dump": "ok", "dumper": "bootgod", "datedumped": "2009-03-17" }, "board": [ { "$": { "type": "HVC-CNROM", "pcb": "CN-04B", "mapper": "3" }, "prg": [ { "$": { "size": "32k", "crc": "B5B29375", "sha1": "615706A0AAA9D2E2F6D57182890EE9DBEC711159" } } ], "chr": [ { "$": { "size": "16k", "crc": "A4896EEF", "sha1": "B99BC30C45E28BFF443B8C7DD5B56809EA2BFB04" } } ], "chip": [ { "$": { "type": "74xx161" } } ], "pad": [ { "$": { "h": "1", "v": "0" } } ] } ] }, { "$": { "system": "Famicom", "revision": "A", "crc": "D074653D", "sha1": "A7F135CF49F92E0FD9D03B6F48C1BD65CE8BCC77", "dump": "ok", "dumper": "bootgod", "datedumped": "2007-06-24" }, "board": [ { "$": { "type": "HVC-CNROM", "pcb": "UNK-BPS-T0", "mapper": "3" }, "prg": [ { "$": { "name": "BPS-T0-1 PRG", "size": "32k", "crc": "B5B29375", "sha1": "615706A0AAA9D2E2F6D57182890EE9DBEC711159" } } ], "chr": [ { "$": { "name": "BPS-T0-1 CHR", "size": "16k", "crc": "A4896EEF", "sha1": "B99BC30C45E28BFF443B8C7DD5B56809EA2BFB04" } } ], "chip": [ { "$": { "type": "74xx161" } } ], "pad": [ { "$": { "h": "1", "v": "0" } } ] } ] } ], "gameGenieCodes": [ { "name": "Two-player interactive game!", "codes": [ [ "ENEALYNN" ] ] }, { "name": "Need only complete 10 lines in game B", "codes": [ [ "APSEGYIZ" ] ] }, { "name": "Must complete 50 lines in game B", "codes": [ [ "AISEGYIZ" ] ] }, { "name": "Must complete 80 lines in game B", "codes": [ [ "EASEGYIZ" ] ] }, { "name": "Faster 'forced' fall rate", "codes": [ [ "PASAUPPE" ] ] } ] };
var async = require('async') , request = require('request') ; var providers = [ 'http://localhost/test/list.one', 'http://localhost/test/list.two' ]; async.each( providers, // 1st param is the collection function(provider, callbackOuter) { // 2nd param is the function that each item is passed to console.log('requesting provider', provider); request( provider, function(err, response, contents) { if (err) { console.error(err); } if (!contents) { return callbackOuter(); // skip this outer loop } console.log('list:', contents); var list = contents.split('\n'); async.each( list, // 1st param is the array of items function(element, callbackInner) { // 2nd param is the function that each item is passed to console.log('leaf url:', element); request( element, function(err, response, contents) { if (err) { console.error(err); } console.log('leaf contents:', contents); callbackInner(); // signal this inner cicle is done } ); }, function(err) { // 3th param is the function to call when everything's done (inner callback) if (err) { return console.error('Error in the final inner async callback:', err, '\n', 'One of the iterations produced an error.\n', 'Skipping this iteration.' ); } callbackOuter(); // signal this inner loop is done console.log('inner loop done'); } ); } ); }, function(err) { // 3rd param is the function to call when everything's done (outer callback) console.log('outer loop done!'); if (err) { console.error('Error in the final outer async callback:', err, '\n', 'One of the iterations produced an error.\n', 'All processing will now stop.' ); } } ); /* function (sets, waterfallCallback) { async.eachSeries(sets, function (set, seriesCallback) { console.log('SET ' + set.code.toUpperCase()); request(baseurl + set.path, function (err, response, body) { var $ = cheerio.load(body); $('body > a[href^="/' + set.code + '/"]').each(function () { console.log(' %s (%s)', $(this).text(), $(this).attr('href')); }); seriesCallback(null); /* 1 * / }); }, waterfallCallback /* 2 * /); } */
/** * Using Rails-like standard naming convention for endpoints. * GET /citizenpedia/api/tags -> index * POST /citizenpedia/api/tags -> create * GET /citizenpedia/api/tags/:id -> show * PUT /citizenpedia/api/tags/:id -> upsert * PATCH /citizenpedia/api/tags/:id -> patch * DELETE /citizenpedia/api/tags/:id -> destroy */ 'use strict'; //import jsonpatch from 'fast-json-patch'; import Tag from './tag.model'; import Question from '../question/question.model'; function respondWithResult(res, statusCode) { statusCode = statusCode || 200; return function(entity) { if(entity) { return res.status(statusCode).json(entity); } return null; }; } function patchUpdates(patches) { return function(entity) { try { jsonpatch.apply(entity, patches, /*validate*/ true); } catch(err) { return Promise.reject(err); } return entity.save(); }; } function removeEntity(res) { return function(entity) { if(entity) { return entity.remove() .then(() => { res.status(204).end(); }); } }; } function handleEntityNotFound(res) { return function(entity) { if(!entity) { res.status(404).end(); return null; } return entity; }; } function handleError(res, statusCode) { statusCode = statusCode || 500; return function(err) { res.status(statusCode).send(err); }; } // Gets a list of Tags export function index(req, res) { return Tag.find().exec() .then(respondWithResult(res)) .catch(handleError(res)); } // Gets a single Tag from the DB export function show(req, res) { console.log("Search by tag"); var query = req.params.id; console.log(query); Question.find({"tags.text": query}).sort({createdAt: -1}).limit(20).execAsync() .then(respondWithResult(res)) .catch(handleError(res)); } // Creates a new Tag in the DB export function create(req, res) { return Tag.create(req.body) .then(respondWithResult(res, 201)) .catch(handleError(res)); } // Upserts the given Tag in the DB at the specified ID export function upsert(req, res) { if(req.body._id) { delete req.body._id; } return Tag.findOneAndUpdate({_id: req.params.id}, req.body, {new: true, upsert: true, setDefaultsOnInsert: true, runValidators: true}).exec() .then(respondWithResult(res)) .catch(handleError(res)); } // Updates an existing Tag in the DB export function patch(req, res) { if(req.body._id) { delete req.body._id; } return Tag.findById(req.params.id).exec() .then(handleEntityNotFound(res)) .then(patchUpdates(req.body)) .then(respondWithResult(res)) .catch(handleError(res)); } // Deletes a Tag from the DB export function destroy(req, res) { return Tag.findById(req.params.id).exec() .then(handleEntityNotFound(res)) .then(removeEntity(res)) .catch(handleError(res)); }
var webpage = require('webpage'), fs = require('fs'), system = require('system'), margin = system.args[5] || '0cm', orientation = system.args[6] || 'portrait', cookie_file = system.args[7], render_time = system.args[8] || 10000 , time_out = system.args[9] || 90000 , viewport_width = system.args[10] || 600, viewport_height = system.args[11] || 600, redirects_num = system.args[12] || 0, cookies = {}, address, output, size; function error(msg) { msg = msg || 'Unknown error'; console.log(msg); phantom.exit(1); throw msg; } function print_usage() { console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom] [margin] [orientation] [cookie_file] [render_time] [time_out] [viewport_width] [viewport_height] [max_redirects_count]'); console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"'); } window.setTimeout(function () { error("Shit's being weird no result within: " + time_out + "ms"); }, time_out); function renderUrl(url, output, options) { options = options || {}; var statusCode, page = webpage.create(); if (system.args[15]) { page.customHeaders = { "Accept-Language": system.args[15] }; }; for (var k in options) { if (options.hasOwnProperty(k)) { page[k] = options[k]; } } // determine the statusCode page.onResourceReceived = function (resource) { if (resource.url == url) { statusCode = resource.status; } }; page.onResourceError = function (resourceError) { error(resourceError.errorString + ' (URL: ' + resourceError.url + ')'); }; page.onNavigationRequested = function (redirect_url, type, willNavigate, main) { if (main) { if (redirect_url !== url) { page.close(); if (redirects_num-- >= 0) { renderUrl(redirect_url, output, options); } else { error(url + ' redirects to ' + redirect_url + ' after maximum number of redirects reached'); } } } }; page.open(url, function (status) { if (status !== 'success' || (statusCode != 200 && statusCode != null)) { if (fs.exists(output)) { fs.remove(output); } try { fs.touch(output); } catch (e) { console.log(e); } error('Unable to load the URL: ' + url + ' (HTTP ' + statusCode + ')'); } else { window.setTimeout(function () { page.render(output + '_tmp.pdf'); if (fs.exists(output)) { fs.remove(output); } try { fs.move(output + '_tmp.pdf', output); } catch (e) { error(e); } console.log('Rendered to: ' + output, new Date().getTime()); phantom.exit(0); }, render_time); } }); } if (cookie_file) { try { f = fs.open(cookie_file, "r"); cookies = JSON.parse(f.read()); fs.remove(cookie_file); } catch (e) { console.log(e); } phantom.cookiesEnabled = true; phantom.cookies = cookies; } if (system.args.length < 3 || system.args.length > 16) { console.log('i see',system.args.length,'args -> ',system.args); print_usage() && phantom.exit(2); } else { address = system.args[1]; output = system.args[2]; page_options = { viewportSize: { width: viewport_width, height: viewport_height } }; if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") { size = system.args[3].split('*'); page_options.paperSize = size.length === 2 ? { width:size[0], height:size[1], margin:'0px' } : { format:system.args[3], orientation:orientation, margin:margin }; } if (system.args[13] && system.args[14]) { page_options.paperSize = { format: 'A4', margin: "1cm", header: { height: "3cm", contents: phantom.callback(function(pageNum, numPages) { return system.args[13]; }) }, footer: { height: "1cm", contents: phantom.callback(function(pageNum, numPages) { if (pageNum == numPages) { return ""; } return "<center>"+ pageNum + " / " + numPages + "</center>"+system.args[14]; }) } }; } if (system.args.length > 4) { page_options.zoomFactor = system.args[4]; } renderUrl(address, output, page_options); }
const htmlSafe = require('./html_safe'); module.exports = { input(action, csrfToken, code, charset) { const attributes = charset === 'digits' ? 'pattern="[0-9]*" inputmode="numeric" ' : ''; return `<form id="op.deviceInputForm" novalidate method="post" action="${action}"> <input type="hidden" name="xsrf" value="${csrfToken}"/> <input ${code ? `value="${htmlSafe(code)}" ` : ''}${attributes}type="text" name="user_code" placeholder="Enter code" onfocus="this.select(); this.onfocus = undefined;" autofocus autocomplete="off"></input> </form>`; }, confirm(action, csrfToken, code) { return `<form id="op.deviceConfirmForm" method="post" action="${action}"> <input type="hidden" name="xsrf" value="${csrfToken}"/> <input type="hidden" name="user_code" value="${htmlSafe(code)}"/> <input type="hidden" name="confirm" value="yes"/> </form>`; }, };
export default class Car { constructor(name) { this._name = name; } set name(value) { console.log("set name from " + this._name + " to: " , value); this._name = value; } get name() { console.log("get name" + this._name); return this._name; } } module.exports = Car
/*jslint browser: true*/ /*global $, jQuery, console, XPathResult, chrome */ (function () { 'use strict'; var ext = { init: "init", initVidState: "initVidState", clearall: "clearall", capture: "capture", loadCapture: "loadCapture", toggleState: "toggleState", toggleVidState: "toggleVidState", updateState: "updateState" }; // ========================== function communicate(method, data, callback) { chrome.tabs.getSelected(null, function (tab) { chrome.tabs.sendMessage(tab.id, { method: method, data: data }, callback); }); } function getCroppedImage(img, x, y, w, h) { var c = $("<canvas>").attr({ width: w, height: h }); c[0].getContext("2d").drawImage(img[0], -x, -y); return c[0].toDataURL("image/png"); } function capture(d, cb) { chrome.tabs.captureVisibleTab(chrome.windows.WINDOW_ID_CURRENT, function (image) { image = getCroppedImage($("<img>").attr("src", image), d.x, d.y, d.w, d.h); //$("#main").html($("<img>").attr("src",image)); //cb($("<img>").attr("src",image)); //cb({sdsd:"sdfdsfdsf"}); //console.log("Capture Done"); communicate(ext.loadCapture, { image: image }, function () {}); //chrome.tabs.create({url:"temp.html"}); // console.log("ddd", cb); }); cb("Capture Started"); } function setIcon(state) { var ico = { path: state ? "icon_active.png" : "icon.png" }; chrome.browserAction.setIcon(ico, function () {}); } function msgHandler(msg, sender, callback) { var res = null; switch (msg.method) { case ext.capture: res = capture(msg.data, callback); break; case ext.updateState: res = setIcon(msg.data); break; } if (callback) { callback(msg); } } chrome.runtime.onMessage.addListener(msgHandler); chrome.commands.onCommand.addListener(function (command) { communicate(command, null, function () { }); }); }());
8.0-alpha3:1093a7b08fe7be7482a21cc4d38cf0bdfe5437345496a2cf1bdf3d561ea4e28d 8.0-alpha4:1093a7b08fe7be7482a21cc4d38cf0bdfe5437345496a2cf1bdf3d561ea4e28d 8.0-alpha5:1093a7b08fe7be7482a21cc4d38cf0bdfe5437345496a2cf1bdf3d561ea4e28d 8.0-alpha6:1093a7b08fe7be7482a21cc4d38cf0bdfe5437345496a2cf1bdf3d561ea4e28d 8.0-alpha7:1093a7b08fe7be7482a21cc4d38cf0bdfe5437345496a2cf1bdf3d561ea4e28d 8.0-alpha8:1093a7b08fe7be7482a21cc4d38cf0bdfe5437345496a2cf1bdf3d561ea4e28d 8.0-alpha9:1093a7b08fe7be7482a21cc4d38cf0bdfe5437345496a2cf1bdf3d561ea4e28d 8.0-alpha10:1093a7b08fe7be7482a21cc4d38cf0bdfe5437345496a2cf1bdf3d561ea4e28d 8.0-alpha11:1093a7b08fe7be7482a21cc4d38cf0bdfe5437345496a2cf1bdf3d561ea4e28d 8.0-alpha12:83d10a14fb8b19a2a240ef0cac5d42feaf00fd2e60ba05f5eeb9db4fbba9910f 8.0-alpha13:83d10a14fb8b19a2a240ef0cac5d42feaf00fd2e60ba05f5eeb9db4fbba9910f 8.0.0-alpha14:83d10a14fb8b19a2a240ef0cac5d42feaf00fd2e60ba05f5eeb9db4fbba9910f 8.0.0-alpha15:83d10a14fb8b19a2a240ef0cac5d42feaf00fd2e60ba05f5eeb9db4fbba9910f 8.0.0-beta1:c36371f511daffdeaff2a892e6d89cd2bf3e895ec70ab1d89baa5f68b3b40486 8.0.0-beta2:c36371f511daffdeaff2a892e6d89cd2bf3e895ec70ab1d89baa5f68b3b40486 8.0.0-beta3:c36371f511daffdeaff2a892e6d89cd2bf3e895ec70ab1d89baa5f68b3b40486 8.0.0-beta4:c36371f511daffdeaff2a892e6d89cd2bf3e895ec70ab1d89baa5f68b3b40486 8.0.0-beta6:c36371f511daffdeaff2a892e6d89cd2bf3e895ec70ab1d89baa5f68b3b40486 8.0.0-beta7:b86f32a8fd0d7285c47e18b282f484cd922f823e46e681e268efbb6404b6acf2 8.0.0-beta9:b86f32a8fd0d7285c47e18b282f484cd922f823e46e681e268efbb6404b6acf2 8.0.0-beta10:b86f32a8fd0d7285c47e18b282f484cd922f823e46e681e268efbb6404b6acf2 8.0.0-beta11:b86f32a8fd0d7285c47e18b282f484cd922f823e46e681e268efbb6404b6acf2 8.0.0-beta12:b86f32a8fd0d7285c47e18b282f484cd922f823e46e681e268efbb6404b6acf2 8.0.0-beta13:b86f32a8fd0d7285c47e18b282f484cd922f823e46e681e268efbb6404b6acf2 8.0.0-beta14:b86f32a8fd0d7285c47e18b282f484cd922f823e46e681e268efbb6404b6acf2 8.0.0-beta15:b86f32a8fd0d7285c47e18b282f484cd922f823e46e681e268efbb6404b6acf2 8.0.0-beta16:dda91d19aff240943ce8eebec7c9c8c5855e2df644ae824f6865329df680fc6a 8.0.0-rc1:dda91d19aff240943ce8eebec7c9c8c5855e2df644ae824f6865329df680fc6a 8.0.0-rc2:dda91d19aff240943ce8eebec7c9c8c5855e2df644ae824f6865329df680fc6a 8.0.0-rc3:dda91d19aff240943ce8eebec7c9c8c5855e2df644ae824f6865329df680fc6a 8.0.0-rc4:dda91d19aff240943ce8eebec7c9c8c5855e2df644ae824f6865329df680fc6a 8.0.1:dda91d19aff240943ce8eebec7c9c8c5855e2df644ae824f6865329df680fc6a 8.0.2:dda91d19aff240943ce8eebec7c9c8c5855e2df644ae824f6865329df680fc6a 8.0.3:dda91d19aff240943ce8eebec7c9c8c5855e2df644ae824f6865329df680fc6a 8.0.4:dda91d19aff240943ce8eebec7c9c8c5855e2df644ae824f6865329df680fc6a 8.0.5:dda91d19aff240943ce8eebec7c9c8c5855e2df644ae824f6865329df680fc6a 8.0.6:dda91d19aff240943ce8eebec7c9c8c5855e2df644ae824f6865329df680fc6a 8.1.0-beta1:dda91d19aff240943ce8eebec7c9c8c5855e2df644ae824f6865329df680fc6a 8.1.0-beta2:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.1.0-rc1:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.1.1:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.1.2:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.1.3:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.1.4:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.1.5:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.1.6:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.1.7:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.1.8:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.1.9:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.1.10:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.2.0-beta1:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.2.0-beta2:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.2.0-beta3:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.2.0-rc1:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.2.0-rc2:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.2.1:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.2.2:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.2.3:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.2.4:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.2.5:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.2.6:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.3.0-alpha1:bc982181bae77fa1c1b5dc2a6fa79c4e3b2ab34f15c7d8efe0a984d37d487327 8.3.0-beta1:bfa782ce278ad97f39e815ed2aea9e756526c995ebfae4526bad4ab4e8f9af95 8.3.0-rc1:bfa782ce278ad97f39e815ed2aea9e756526c995ebfae4526bad4ab4e8f9af95 8.2.7:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.3.0-rc2:bfa782ce278ad97f39e815ed2aea9e756526c995ebfae4526bad4ab4e8f9af95 8.0.0:dda91d19aff240943ce8eebec7c9c8c5855e2df644ae824f6865329df680fc6a 8.1.0:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.2.0:1edfccf551bb8fba78f96bfe46b859da92736b52cdc0166f3121cc5958e0d3f4 8.3.0:bfa782ce278ad97f39e815ed2aea9e756526c995ebfae4526bad4ab4e8f9af95
/** * View engine * https://github.com/koajs/koa-hbs/blob/master/index.js * https://github.com/dominicbarnes/koa-handlebars/blob/master/index.js */ const path = require('path') const fs = require('mz/fs') const fm = require('front-matter') const hbs = require('handlebars') const helpers = require('../helpers') module.exports = app => { const templateCache = {} const viewDir = path.join(__dirname, '../views/') const extname = '.html' // register helpers hbs.registerHelper(helpers) /** * get template from cache * @param {String} filename template file name * @return {[type]} [description] */ const getTemplate = async filename => { if (templateCache[filename] && app.env !== 'development') { // from cache return templateCache[filename] } const { body, attributes } = fm(await fs.readFile(filename, 'utf-8')) const template = hbs.compile(body, { strict: false }) template.meta = attributes // cached template templateCache[filename] = template return template } // recursive render template const renderTemplate = async (filename, data, result) => { if (result) { data.body = new hbs.SafeString(result) data.placeholder = data.body } const template = await getTemplate(filename) result = template(data, {}) // try to find layout if (template.meta.layout) { const currentDir = path.dirname(filename) const layoutFilename = path.resolve(currentDir, template.meta.layout + extname) result = await renderTemplate(layoutFilename, data, result) } return result } app.context.render = async function (name, data, output = true) { const filename = path.join(viewDir, name + extname) // template data data = Object.assign({}, this.state, data) // render template const result = await renderTemplate(filename, data) // response if (output) { this.type = 'text/html' this.body = result } return result } return (ctx, next) => next() } // data: // { // context: this, // request: this.request, // response: this.response, // cookie: this.cookie, // session: this.session, // config: this.config // }
var fs = require ('fs'); var EventEmitter = require("events").EventEmitter; var ee = new EventEmitter(); var _ = require ('underscore'); var s = require("underscore.string"); var attributes = {}; attributes.fullname = "FN:"; attributes.email = "EMAIL;"; attributes.phone = "TEL;"; attributes.bday = "BDAY:"; attributes.note = "NOTE:"; attributes.addr = "ADR;"; var addressPrefix = /ADR;.*:/ function parse(data) { var dataStr = data.toString("utf-8") var lines = s(dataStr).lines(); var all_contacts = []; var contact; _.each(lines, function(lineContent) { if (s(lineContent).trim().startsWith("BEGIN:VCARD")) { contact = {}; contact.fullname = "empty"; contact.bday = ""; contact.note = ""; contact.addr = []; contact.phone = []; contact.email = []; } if (s(lineContent).trim().startsWith("END:VCARD")) { all_contacts.push(contact); } _.each(attributes, function(attribute){ // each line can have a group prefix: [group "."] name *(";" param) // https://tools.ietf.org/html/rfc6350 if (s(lineContent).contains(attribute)) { ee.emit("attributeMatched", attribute, lineContent, contact); } }); }); // end _.each return all_contacts; } function parseVcardString(vcardString, callback) { var all_contacts = parse(vcardString); callback(null, all_contacts); } function parseVcardStringSync(vcardString) { return parse(vcardString); } function parseVcardFile(pathToFile, callback) { fs.readFile(pathToFile, function(err, data) { if (err) { callback(err); } else { var all_contacts = parse(data); callback(null, all_contacts); } }); // end fs.readFile } function attributeMatched(attribute, line, contact) { switch (attribute) { case "FN:": contact.fullname = s(line.slice(3)).clean().value(); break; case "EMAIL;": var email_obj = {}; email_obj.value = s(line.substring(line.indexOf(":") + 1)).clean().value(); email_obj.default = false; if (s(line).contains("type=pref")) { email_obj.default = true; } contact.email.push(email_obj); break; case "TEL;": var phone_obj = {}; phone_obj.value = s(line.substring(line.indexOf(":") + 1)).clean().value(); phone_obj.default = false; if (s(line).contains("type=pref")) { phone_obj.default = true; } contact.phone.push(phone_obj); break; case "BDAY:": contact.bday = s(line.slice(5)).clean().value(); break; case "NOTE:": contact.note = s(line.slice(5)).clean().value(); break; case "ADR;": var addr_obj = {}; var prefix = line.match(addressPrefix); if (prefix && prefix.length == 1) { prefix = prefix[0]; var addressContent = s(line.substring(prefix.length)).clean().value(); var addressItems = addressContent.split(';'); var numItems = addressItems.length; addr_obj.poBox = numItems > 0? addressItems[0] : ""; addr_obj.extAddress = numItems > 1? addressItems[1] : ""; addr_obj.street = numItems > 2? addressItems[2] : ""; addr_obj.city = numItems > 3? addressItems[3] : ""; addr_obj.locality = numItems > 3? addressItems[3] : ""; addr_obj.state = numItems > 4? addressItems[4] : ""; addr_obj.region = numItems > 4? addressItems[4] : ""; addr_obj.zip = numItems > 5? addressItems[5] : ""; addr_obj.country = numItems > 6? addressItems[6] : ""; addr_obj.default = s(line).contains("type=pref"); contact.addr.push(addr_obj); } else { console.log ('unable to match address format for:\n'+ address); } break; } } ee.on("attributeMatched", attributeMatched); exports.parseVcardString = parseVcardString; exports.parseVcardStringSync = parseVcardStringSync; exports.parseVcardFile = parseVcardFile;
'use strict'; var request = require('request'); module.exports = function (grunt) { // show elapsed time at the end require('time-grunt')(grunt); // load all grunt tasks require('load-grunt-tasks')(grunt); grunt.loadNpmTasks('grunt-contrib-less'); var reloadPort = 35729, files; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), develop: { server: { file: 'app.js' } }, watch: { options: { nospawn: true, livereload: reloadPort }, server: { files: [ 'app.js', 'routes/*.js' ], tasks: ['develop', 'delayed-livereload'] }, js: { files: ['ui/app/{,*/}*.js'], tasks: ['jshint', 'browserify'], options: { livereload: reloadPort } }, less: { files: ['less/*.less'], tasks: ["less"], options: { livereload: reloadPort } }, html: { files: ['ui/{,*/}*.html'], options: { livereload: reloadPort } } }, less: { development: { options: { paths: ["less"] }, files: { "public/css/app.css": "less/app.less" } }, production: { options: { paths: ["less"], cleancss: true }, files: { "public/css/app.css": "less/app.less" } } }, browserify: { development: { src: ['ui/app/{,*/}*.js'], options: { }, dest: 'public/js/app.js' } }, jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: [ 'Gruntfile.js', 'public/js/src/{,*/}*.js' ] }, }); grunt.config.requires('watch.server.files'); files = grunt.config('watch.server.files'); files = grunt.file.expand(files); grunt.registerTask('delayed-livereload', 'Live reload after the node server has restarted.', function () { var done = this.async(); setTimeout(function () { request.get('http://localhost:' + reloadPort + '/changed?files=' + files.join(','), function (err, res) { var reloaded = !err && res.statusCode === 200; if (reloaded) { grunt.log.ok('Delayed live reload successful.'); } else { grunt.log.error('Unable to make a delayed live reload.'); } done(reloaded); }); }, 500); }); grunt.registerTask('default', ['develop', 'watch']); };
var brightWhite = [230,230,230], white = [200,200,200], silver = [150,150,155], black = [060,060,060], darkBlack = [040,040,040], justRed = [255, 0, 0], lightRed = [235, 60, 54], red = [210, 50, 44], darkRed = [186, 26, 26], burgundy = [123, 22, 33], gold = [200,150, 30], darkGold = [175,140, 0], iceWhite = [215,238,228], iceBlue = [180,234,255], lightBlue = [ 51,151,197], blue = [ 59, 54,182], navyBlue = [ 0, 51,102], lightYellow = [219,220, 47], yellow = [255,190, 20], orange = [255,144, 47], darkOrange = [197, 83, 0], skinPink = [240,194,170], lightPink = [255,122,204], violet = [153,153,255], elodeamelonPink = [255, 50,100], pink = [206, 51,145], purple = [113, 52,165], darkPurple = [ 79, 47, 79], cyan = [ 93,242,255], darkCyan = [ 0,139,149], mintGreen = [180,255,180], limeGreen = [110,225, 10], oliveGreen = [105,120, 0], lightGreen = [ 50,220,110], green = [ 83,159, 48], darkGreen = [ 0, 70, 0], fluorescentJacket = [209,255, 56], slate = [ 47, 79, 79], bone = [255,250,205], tan = [210,180,140], brown = [142,107, 68], giraffeBrown = [130, 80, 10]; exports.data = [ { primary: black, secondary: [ red, pink, lightBlue, green, orange, gold, silver ] }, { primary: silver, secondary: [ red, darkBlack, lightBlue, limeGreen ] }, { primary: slate, secondary: [ darkPurple, orange, brown ] }, { primary: navyBlue, secondary: [ limeGreen, elodeamelonPink, tan ] }, { primary: brown, secondary: [ tan, purple, pink, mintGreen ] }, { primary: purple, secondary: [ lightBlue, gold, white ] }, { primary: blue, secondary: [ yellow, orange, iceWhite ] }, { primary: darkGreen, secondary: [ lightYellow, white, pink ] }, { primary: darkRed, secondary: [ gold, white, purple, black ] }, { primary: red, secondary: [ lightBlue, green, yellow ] }, { primary: burgundy, secondary: [ cyan, bone, limeGreen ] }, { primary: elodeamelonPink, secondary: [ lightGreen, justRed, purple ] }, { primary: pink, secondary: [ orange, lightBlue, yellow ] }, { primary: lightPink, secondary: [ black, burgundy, brightWhite ] }, { primary: cyan, secondary: [ purple, navyBlue, yellow ] }, { primary: bone, secondary: [ darkGreen, darkRed, purple ] }, { primary: yellow, secondary: [ giraffeBrown, darkBlack, burgundy, slate ] }, { primary: orange, secondary: [ black, slate, lightBlue ] }, { primary: white, secondary: [ red, lightBlue, green, orange, black ] }, { primary: limeGreen, secondary: [ darkRed, darkGreen, navyBlue ] }, { primary: tan, secondary: [ oliveGreen, blue, purple ] }, { primary: iceBlue, secondary: [ brightWhite, darkRed, orange ] }, { primary: lightBlue, secondary: [ gold, red, elodeamelonPink ] }, { primary: violet, secondary: [ lightPink, lightRed, purple ] }, { primary: green, secondary: [ yellow, pink, purple ] }, { primary: oliveGreen, secondary: [ purple, bone, violet ] }, { primary: mintGreen, secondary: [ brown, navyBlue, violet ] }, { primary: darkGold, secondary: [ purple, lightBlue, silver ] }, { primary: darkCyan, secondary: [ black, brightWhite ] }, { primary: skinPink, secondary: [ darkRed, purple, darkCyan ] }, { primary: darkOrange, secondary: [ darkGreen, purple, darkCyan ] }, { primary: fluorescentJacket, secondary: [ black, lightBlue, purple, silver ] } ];
import 'whatwg-fetch' import { Promise } from 'es6-promise' import alt from '../alt' import TeamServiceStateModel from '../models/team-service-state-model' import { List } from 'immutable' class TeamServiceStateActions { static fetchPromise() { return new Promise((resolve, reject) => { fetch('/api/team/services') .then((response) => { if (response.status >= 200 && response.status < 300) { return response.json() } else { let err = new Error(response.statusText) err.response = response throw err } }) .then((data) => { let teamServiceStates = data.map((props) => { return new TeamServiceStateModel(props) }) resolve(new List(teamServiceStates)) }) .catch((err) => { reject(err) }) }) } update(teamServiceStates) { this.dispatch(teamServiceStates) } updateSingle(teamServiceState) { this.dispatch(teamServiceState) } fetch() { this.dispatch() TeamServiceStateActions .fetchPromise() .then((teamServiceStates) => { this.actions.update(teamServiceStates) }) .catch((err) => { this.actions.failed(err) }) } failed(err) { this.dispatch(err) } } export default alt.createActions(TeamServiceStateActions)
import React from 'react'; import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card'; import { Grid, Row, Col, Clearfix } from 'react-bootstrap'; import {Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle} from 'material-ui/Toolbar'; import IconMenu from 'material-ui/IconMenu'; import IconButton from 'material-ui/IconButton'; import FontIcon from 'material-ui/FontIcon'; import NavigationExpandMoreIcon from 'material-ui/svg-icons/navigation/expand-more'; import NavigationMenu from 'material-ui/svg-icons/navigation/menu'; import MenuItem from 'material-ui/MenuItem'; import DropDownMenu from 'material-ui/DropDownMenu'; import RaisedButton from 'material-ui/RaisedButton'; class MainComponent extends React.Component { constructor(props){ super(props); var userDataObj = JSON.parse(localStorage.getItem('userData')); var userName = userDataObj.name; this.state = { userData : localStorage.getItem('userData'), userName : userName, userNameTry : JSON.parse(localStorage.getItem('userData')).name } this.responseFacebook = this.responseFacebook.bind(this); } responseFacebook(response){ } render(){ return (<div> <Toolbar> <ToolbarGroup firstChild={true}> <IconMenu iconButtonElement={ <IconButton touch={true}> <NavigationMenu /> </IconButton> } /> <ToolbarTitle text={this.state.userNameTry} /> </ToolbarGroup> <ToolbarGroup> <ToolbarSeparator /> <ToolbarTitle text={this.state.userData}/> <IconMenu iconButtonElement={ <IconButton touch={true}> <NavigationExpandMoreIcon /> </IconButton> } > <MenuItem primaryText="Download" /> <MenuItem primaryText="More Info" /> </IconMenu> </ToolbarGroup> </Toolbar> <Col xs={12} sm ={10} smOffset = {1} md={8} mdOffset={2} lg = {6} lgOffset={3}> <Card> <CardHeader title="TheCookBot" subtitle="Recipe by ingredients and more.." avatar="http://lorempixel.com/100/100/food/" /> <CardActions> </CardActions> <CardText> <div id="status"></div> </CardText> } </Card> </Col></div>); } } export default MainComponent;
'use strict'; var _ = require('lodash'); var Recipe = require('./recipe.model'); // Get list of recipes exports.index = function(req, res) { Recipe.find(function (err, recipes) { if(err) { return handleError(res, err); } return res.json(200, recipes); }); }; // Get a single recipe exports.show = function(req, res) { Recipe.findById(req.params.id, function (err, recipe) { if(err) { return handleError(res, err); } if(!recipe) { return res.send(404); } return res.json(recipe); }); }; // Creates a new recipe in the DB. exports.create = function(req, res) { Recipe.create(req.body, function(err, recipe) { if(err) { return handleError(res, err); } return res.json(201, recipe); }); }; // Updates an existing recipe in the DB. exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } Recipe.findById(req.params.id, function (err, recipe) { console.log("hello1234"); if (err) { return handleError(res, err); } if(!recipe) { return res.send(404); } var updated = _.merge(recipe, req.body); console.log(req.body); console.log(req.params); console.log(updated); updated.save(function (err) { if (err) { return handleError(res, err); } console.log("4321 created"); console.log(recipe); return res.json(200, recipe); }); }); }; // Deletes a recipe from the DB. exports.destroy = function(req, res) { Recipe.findById(req.params.id, function (err, recipe) { if(err) { return handleError(res, err); } if(!recipe) { return res.send(404); } recipe.remove(function(err) { if(err) { return handleError(res, err); } return res.send(204); }); }); }; function handleError(res, err) { return res.send(500, err); }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M8.17 17c.51 0 .98-.29 1.2-.74l1.42-2.84c.14-.28.21-.58.21-.89V8c0-1.1-.9-2-2-2H5.34C4.6 6 4 6.6 4 7.34v4.32C4 12.4 4.6 13 5.34 13H8l-1.03 2.06c-.45.89.2 1.94 1.2 1.94zm9 0c.51 0 .98-.29 1.2-.74l1.42-2.84c.14-.28.21-.58.21-.89V7.34C20 6.6 19.4 6 18.66 6h-4.32C13.6 6 13 6.6 13 7.34v4.32c0 .74.6 1.34 1.34 1.34H17l-1.03 2.06c-.45.89.2 1.94 1.2 1.94z" /> , 'FormatQuoteRounded');
var async =require('async'), pkgcloud = require('pkgcloud'), fs = require('fs'), logging = require('../common/logging'), config = require('../common/config'), _ = require('underscore'); var log = logging.getLogger(process.env.PKGCLOUD_LOG_LEVEL || 'debug'); var provider = process.argv[2]; var client = pkgcloud.storage.createClient(config.getConfig(provider, 1)); client.on('log::*', logging.logFunction); client.getFiles(process.argv[3], { limit: 1000000 }, function (err, files) { if (err) { log.error(err); return; } async.forEachLimit(files, 20, function(file, next) { client.removeFile(process.argv[3], file, function(err) { if (err && err.statusCode !== 404) { next(err); return; } next(); }); }, function(err) { log.info(err); }); });
function wrapper() { var recursive = function(n) { if (n <= 2) { return 1; } else { return recursive(n - 1) + recursive(n - 2); } }; var iterations = [23, 24, 25, 26, 27, 28, 29, 30, 31, 32]; var start = null, end = null, time = null, times = []; for (var i = 0; i < iterations.length; i++) { start = new Date().getTime(); recursive(iterations[i]); end = new Date().getTime(); time = end - start; times.push(time); } return times.join('\t'); }
var keyMirror = require('keymirror'); module.exports = keyMirror({ ERROR_MESSAGE: null, CLEAR_ERROR: null })
const inquirer = require('inquirer'); const send = require('./send'); const promptToSend = (transport, from, to, template) => { inquirer.prompt([{ type: 'confirm', name: 'send', default: true, message: 'Send test email', }]) .then((sendResponse) => { if (sendResponse.send) { send(template, from, to, transport, () => { promptToSend(transport, from, to, template); }); } }); }; module.exports = promptToSend;
(function() { 'use strict'; angular .module('simpleWebrtcServerApp') .controller('UserManagementDeleteController', UserManagementDeleteController); UserManagementDeleteController.$inject = ['$uibModalInstance', 'entity', 'User']; function UserManagementDeleteController ($uibModalInstance, entity, User) { var vm = this; vm.user = entity; vm.clear = clear; vm.confirmDelete = confirmDelete; function clear () { $uibModalInstance.dismiss('cancel'); } function confirmDelete (login) { User.delete({login: login}, function () { $uibModalInstance.close(true); }); } } })();
import { NotSupportedError } from '../not_supported_error' class PlainString { constructor() { this.string = '' } get value() { return this.string } push(string) { this.string += string } add_bind() { throw new NotSupportedError(this.constructor, 'add_bind') } } export { PlainString }
import React, { Component } from 'react' import { Segment } from 'stardust' export default class SegmentEmphasisExample extends Component { render() { return ( <div> <Segment> I'm here to tell you something, and you will probably read me first. </Segment> <Segment className='secondary'> I am pretty noticeable but you might check out other content before you look at me. </Segment> <Segment className='tertiary'> If you notice me you must be looking very hard. </Segment> </div> ) } }
"use strict"; define("ace/mode/julia_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function (require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JuliaHighlightRules = function JuliaHighlightRules() { this.$rules = { start: [{ include: '#function_decl' }, { include: '#function_call' }, { include: '#type_decl' }, { include: '#keyword' }, { include: '#operator' }, { include: '#number' }, { include: '#string' }, { include: '#comment' }], '#bracket': [{ token: 'keyword.bracket.julia', regex: '\\(|\\)|\\[|\\]|\\{|\\}|,' }], '#comment': [{ token: ['punctuation.definition.comment.julia', 'comment.line.number-sign.julia'], regex: '(#)(?!\\{)(.*$)' }], '#function_call': [{ token: ['support.function.julia', 'text'], regex: "([a-zA-Z0-9_]+!?)([\\w\\xff-\\u218e\\u2455-\\uffff]*\\()" }], '#function_decl': [{ token: ['keyword.other.julia', 'meta.function.julia', 'entity.name.function.julia', 'meta.function.julia', 'text'], regex: "(function|macro)(\\s*)([a-zA-Z0-9_\\{]+!?)([\\w\\xff-\\u218e\\u2455-\\uffff]*)([(\\\\{])" }], '#keyword': [{ token: 'keyword.other.julia', regex: '\\b(?:function|type|immutable|macro|quote|abstract|bitstype|typealias|module|baremodule|new)\\b' }, { token: 'keyword.control.julia', regex: '\\b(?:if|else|elseif|while|for|in|begin|let|end|do|try|catch|finally|return|break|continue)\\b' }, { token: 'storage.modifier.variable.julia', regex: '\\b(?:global|local|const|export|import|importall|using)\\b' }, { token: 'variable.macro.julia', regex: "@[\\w\\xff-\\u218e\\u2455-\\uffff]+\\b" }], '#number': [{ token: 'constant.numeric.julia', regex: '\\b0(?:x|X)[0-9a-fA-F]*|(?:\\b[0-9]+\\.?[0-9]*|\\.[0-9]+)(?:(?:e|E)(?:\\+|-)?[0-9]*)?(?:im)?|\\bInf(?:32)?\\b|\\bNaN(?:32)?\\b|\\btrue\\b|\\bfalse\\b' }], '#operator': [{ token: 'keyword.operator.update.julia', regex: '=|:=|\\+=|-=|\\*=|/=|//=|\\.//=|\\.\\*=|\\\\=|\\.\\\\=|^=|\\.^=|%=|\\|=|&=|\\$=|<<=|>>=' }, { token: 'keyword.operator.ternary.julia', regex: '\\?|:' }, { token: 'keyword.operator.boolean.julia', regex: '\\|\\||&&|!' }, { token: 'keyword.operator.arrow.julia', regex: '->|<-|-->' }, { token: 'keyword.operator.relation.julia', regex: '>|<|>=|<=|==|!=|\\.>|\\.<|\\.>=|\\.>=|\\.==|\\.!=|\\.=|\\.!|<:|:>' }, { token: 'keyword.operator.range.julia', regex: ':' }, { token: 'keyword.operator.shift.julia', regex: '<<|>>' }, { token: 'keyword.operator.bitwise.julia', regex: '\\||\\&|~' }, { token: 'keyword.operator.arithmetic.julia', regex: '\\+|-|\\*|\\.\\*|/|\\./|//|\\.//|%|\\.%|\\\\|\\.\\\\|\\^|\\.\\^' }, { token: 'keyword.operator.isa.julia', regex: '::' }, { token: 'keyword.operator.dots.julia', regex: '\\.(?=[a-zA-Z])|\\.\\.+' }, { token: 'keyword.operator.interpolation.julia', regex: '\\$#?(?=.)' }, { token: ['variable', 'keyword.operator.transposed-variable.julia'], regex: "([\\w\\xff-\\u218e\\u2455-\\uffff]+)((?:'|\\.')*\\.?')" }, { token: 'text', regex: '\\[|\\(' }, { token: ['text', 'keyword.operator.transposed-matrix.julia'], regex: "([\\]\\)])((?:'|\\.')*\\.?')" }], '#string': [{ token: 'punctuation.definition.string.begin.julia', regex: '\'', push: [{ token: 'punctuation.definition.string.end.julia', regex: '\'', next: 'pop' }, { include: '#string_escaped_char' }, { defaultToken: 'string.quoted.single.julia' }] }, { token: 'punctuation.definition.string.begin.julia', regex: '"', push: [{ token: 'punctuation.definition.string.end.julia', regex: '"', next: 'pop' }, { include: '#string_escaped_char' }, { defaultToken: 'string.quoted.double.julia' }] }, { token: 'punctuation.definition.string.begin.julia', regex: "\\b[\\w\\xff-\\u218e\\u2455-\\uffff]+\"", push: [{ token: 'punctuation.definition.string.end.julia', regex: "\"[\\w\\xff-\\u218e\\u2455-\\uffff]*", next: 'pop' }, { include: '#string_custom_escaped_char' }, { defaultToken: 'string.quoted.custom-double.julia' }] }, { token: 'punctuation.definition.string.begin.julia', regex: '`', push: [{ token: 'punctuation.definition.string.end.julia', regex: '`', next: 'pop' }, { include: '#string_escaped_char' }, { defaultToken: 'string.quoted.backtick.julia' }] }], '#string_custom_escaped_char': [{ token: 'constant.character.escape.julia', regex: '\\\\"' }], '#string_escaped_char': [{ token: 'constant.character.escape.julia', regex: '\\\\(?:\\\\|[0-3]\\d{,2}|[4-7]\\d?|x[a-fA-F0-9]{,2}|u[a-fA-F0-9]{,4}|U[a-fA-F0-9]{,8}|.)' }], '#type_decl': [{ token: ['keyword.control.type.julia', 'meta.type.julia', 'entity.name.type.julia', 'entity.other.inherited-class.julia', 'punctuation.separator.inheritance.julia', 'entity.other.inherited-class.julia'], regex: '(type|immutable)(\\s+)([a-zA-Z0-9_]+)(?:(\\s*)(<:)(\\s*[.a-zA-Z0-9_:]+))?' }, { token: ['other.typed-variable.julia', 'support.type.julia'], regex: '([a-zA-Z0-9_]+)(::[a-zA-Z0-9_{}]+)' }] }; this.normalizeRules(); }; JuliaHighlightRules.metaData = { fileTypes: ['jl'], firstLineMatch: '^#!.*\\bjulia\\s*$', foldingStartMarker: '^\\s*(?:if|while|for|begin|function|macro|module|baremodule|type|immutable|let)\\b(?!.*\\bend\\b).*$', foldingStopMarker: '^\\s*(?:end)\\b.*$', name: 'Julia', scopeName: 'source.julia' }; oop.inherits(JuliaHighlightRules, TextHighlightRules); exports.JuliaHighlightRules = JuliaHighlightRules; }); define("ace/mode/folding/cstyle", ["require", "exports", "module", "ace/lib/oop", "ace/range", "ace/mode/folding/fold_mode"], function (require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function (commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)); this.foldingStopMarker = new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)); } }; oop.inherits(FoldMode, BaseFoldMode); (function () { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function (session, foldStyle, row, forceMultiline) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function (session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; }).call(FoldMode.prototype); }); define("ace/mode/julia", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/mode/julia_highlight_rules", "ace/mode/folding/cstyle"], function (require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JuliaHighlightRules = require("./julia_highlight_rules").JuliaHighlightRules; var FoldMode = require("./folding/cstyle").FoldMode; var Mode = function Mode() { this.HighlightRules = JuliaHighlightRules; this.foldingRules = new FoldMode(); }; oop.inherits(Mode, TextMode); (function () { this.lineCommentStart = "#"; this.blockComment = ""; this.$id = "ace/mode/julia"; }).call(Mode.prototype); exports.Mode = Mode; });
/** * Вьюха ответа * Намеренно не использую никакой шаблонизатор. Такой вариант полюбомы быстрее. * Если онадобится шаблонизатор - прикрутим ect, pug или чтото своё. */ export default function views(data) { const {component, state} = data; return ` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="application/javascript" href="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"> <script type="application/javascript" href="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"> <title>Hello React</title> <link rel="stylesheet" href="/assets/styles.css"> <script type="application/javascript"> window.INITIAL_STATE = ${JSON.stringify(state)}; </script> </head> <body> <div id="react-view">${component}</div> <div id="dev-tools"></div> <script type="application/javascript" src="/assets/bundle.js"></script> </body> </html> `; }
import Modifier from './Modifier'; export default Modifier;
// Write a function that returns the index of the first element in array that is larger than its neighbours or -1, if there’s no such element. // Use the function from the previous exercise. var arr = [2, 3, 4, 5, 6, 5, 3, 2], //change array elements for different cases :) i = 0, // [2,1,3] will return index 0 firstIndex; // [2,2,3] will return last index // [2,2,2] will return no such element :) firstIndex = check(arr); if (firstIndex >= 0) { console.log('First element in array that is larger than its neighbours is at position: ' + firstIndex); } else { console.log('There’s no such element!'); } function check(arr) { var position; for (position = 0; position < arr.length; position += 1) { if (arr[position] > arr[position + 1] && arr[position] > arr[position - 1]) { return position; } else if (!position && arr[0] > arr[1]) { return 0; } else if (position === arr.length - 1 && arr[arr.length - 1] > arr[arr.length - 2]) { return arr.length - 1; } } return -1; }
App.JobsNewController = Ember.ObjectController.extend({ save: function () { var job = App.Job.createRecord(this.get('content')); job.save(); this.transitionToRoute('jobs'); }, cancel: function () { this.transitionToRoute('jobs'); } });
require('jsdom-global')() const assert = require('assert') const { $ } = require('./') const body = document.body describe('Bianco', function() { beforeEach(function() { const div = document.createElement('div') div.innerHTML = ` <h1>bianco!!!</h1> ` body.appendChild(div) }) // all the bianco helpers are already tested in their own repos it('Silence is golden', function() { const h1 = $('h1')[0] assert.equal(h1.innerHTML, 'bianco!!!') }) })
import "webgltexture-loader-expo-camera"; import App from "./src/App"; export default App;
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ /* * This module only exports 'compile' which compiles a JSON language definition * into a typed and checked ILexer definition. */ import * as monarchCommon from './monarchCommon'; /* * Type helpers * * Note: this is just for sanity checks on the JSON description which is * helpful for the programmer. No checks are done anymore once the lexer is * already 'compiled and checked'. * */ function isArrayOf(elemType, obj) { if (!obj) { return false; } if (!(Array.isArray(obj))) { return false; } for (var _i = 0, obj_1 = obj; _i < obj_1.length; _i++) { var el = obj_1[_i]; if (!(elemType(el))) { return false; } } return true; } function bool(prop, defValue) { if (typeof prop === 'boolean') { return prop; } return defValue; } function string(prop, defValue) { if (typeof (prop) === 'string') { return prop; } return defValue; } function arrayToHash(array) { var result = {}; for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var e = array_1[_i]; result[e] = true; } return result; } function createKeywordMatcher(arr, caseInsensitive) { if (caseInsensitive === void 0) { caseInsensitive = false; } if (caseInsensitive) { arr = arr.map(function (x) { return x.toLowerCase(); }); } var hash = arrayToHash(arr); if (caseInsensitive) { return function (word) { return hash[word.toLowerCase()] !== undefined && hash.hasOwnProperty(word.toLowerCase()); }; } else { return function (word) { return hash[word] !== undefined && hash.hasOwnProperty(word); }; } } // Lexer helpers /** * Compiles a regular expression string, adding the 'i' flag if 'ignoreCase' is set. * Also replaces @\w+ or sequences with the content of the specified attribute */ function compileRegExp(lexer, str) { var n = 0; while (str.indexOf('@') >= 0 && n < 5) { // at most 5 expansions n++; str = str.replace(/@(\w+)/g, function (s, attr) { var sub = ''; if (typeof (lexer[attr]) === 'string') { sub = lexer[attr]; } else if (lexer[attr] && lexer[attr] instanceof RegExp) { sub = lexer[attr].source; } else { if (lexer[attr] === undefined) { throw monarchCommon.createError(lexer, 'language definition does not contain attribute \'' + attr + '\', used at: ' + str); } else { throw monarchCommon.createError(lexer, 'attribute reference \'' + attr + '\' must be a string, used at: ' + str); } } return (monarchCommon.empty(sub) ? '' : '(?:' + sub + ')'); }); } return new RegExp(str, (lexer.ignoreCase ? 'i' : '')); } /** * Compiles guard functions for case matches. * This compiles 'cases' attributes into efficient match functions. * */ function selectScrutinee(id, matches, state, num) { if (num < 0) { return id; } if (num < matches.length) { return matches[num]; } if (num >= 100) { num = num - 100; var parts = state.split('.'); parts.unshift(state); if (num < parts.length) { return parts[num]; } } return null; } function createGuard(lexer, ruleName, tkey, val) { // get the scrutinee and pattern var scrut = -1; // -1: $!, 0-99: $n, 100+n: $Sn var oppat = tkey; var matches = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/); if (matches) { if (matches[3]) { // if digits scrut = parseInt(matches[3]); if (matches[2]) { scrut = scrut + 100; // if [sS] present } } oppat = matches[4]; } // get operator var op = '~'; var pat = oppat; if (!oppat || oppat.length === 0) { op = '!='; pat = ''; } else if (/^\w*$/.test(pat)) { // just a word op = '=='; } else { matches = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/); if (matches) { op = matches[1]; pat = matches[2]; } } // set the tester function var tester; // special case a regexp that matches just words if ((op === '~' || op === '!~') && /^(\w|\|)*$/.test(pat)) { var inWords_1 = createKeywordMatcher(pat.split('|'), lexer.ignoreCase); tester = function (s) { return (op === '~' ? inWords_1(s) : !inWords_1(s)); }; } else if (op === '@' || op === '!@') { var words = lexer[pat]; if (!words) { throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' is not defined, in rule: ' + ruleName); } if (!(isArrayOf(function (elem) { return (typeof (elem) === 'string'); }, words))) { throw monarchCommon.createError(lexer, 'the @ match target \'' + pat + '\' must be an array of strings, in rule: ' + ruleName); } var inWords_2 = createKeywordMatcher(words, lexer.ignoreCase); tester = function (s) { return (op === '@' ? inWords_2(s) : !inWords_2(s)); }; } else if (op === '~' || op === '!~') { if (pat.indexOf('$') < 0) { // precompile regular expression var re_1 = compileRegExp(lexer, '^' + pat + '$'); tester = function (s) { return (op === '~' ? re_1.test(s) : !re_1.test(s)); }; } else { tester = function (s, id, matches, state) { var re = compileRegExp(lexer, '^' + monarchCommon.substituteMatches(lexer, pat, id, matches, state) + '$'); return re.test(s); }; } } else { // if (op==='==' || op==='!=') { if (pat.indexOf('$') < 0) { var patx_1 = monarchCommon.fixCase(lexer, pat); tester = function (s) { return (op === '==' ? s === patx_1 : s !== patx_1); }; } else { var patx_2 = monarchCommon.fixCase(lexer, pat); tester = function (s, id, matches, state, eos) { var patexp = monarchCommon.substituteMatches(lexer, patx_2, id, matches, state); return (op === '==' ? s === patexp : s !== patexp); }; } } // return the branch object if (scrut === -1) { return { name: tkey, value: val, test: function (id, matches, state, eos) { return tester(id, id, matches, state, eos); } }; } else { return { name: tkey, value: val, test: function (id, matches, state, eos) { var scrutinee = selectScrutinee(id, matches, state, scrut); return tester(!scrutinee ? '' : scrutinee, id, matches, state, eos); } }; } } /** * Compiles an action: i.e. optimize regular expressions and case matches * and do many sanity checks. * * This is called only during compilation but if the lexer definition * contains user functions as actions (which is usually not allowed), then this * may be called during lexing. It is important therefore to compile common cases efficiently */ function compileAction(lexer, ruleName, action) { if (!action) { return { token: '' }; } else if (typeof (action) === 'string') { return action; // { token: action }; } else if (action.token || action.token === '') { if (typeof (action.token) !== 'string') { throw monarchCommon.createError(lexer, 'a \'token\' attribute must be of type string, in rule: ' + ruleName); } else { // only copy specific typed fields (only happens once during compile Lexer) var newAction = { token: action.token }; if (action.token.indexOf('$') >= 0) { newAction.tokenSubst = true; } if (typeof (action.bracket) === 'string') { if (action.bracket === '@open') { newAction.bracket = 1 /* Open */; } else if (action.bracket === '@close') { newAction.bracket = -1 /* Close */; } else { throw monarchCommon.createError(lexer, 'a \'bracket\' attribute must be either \'@open\' or \'@close\', in rule: ' + ruleName); } } if (action.next) { if (typeof (action.next) !== 'string') { throw monarchCommon.createError(lexer, 'the next state must be a string value in rule: ' + ruleName); } else { var next = action.next; if (!/^(@pop|@push|@popall)$/.test(next)) { if (next[0] === '@') { next = next.substr(1); // peel off starting @ sign } if (next.indexOf('$') < 0) { // no dollar substitution, we can check if the state exists if (!monarchCommon.stateExists(lexer, monarchCommon.substituteMatches(lexer, next, '', [], ''))) { throw monarchCommon.createError(lexer, 'the next state \'' + action.next + '\' is not defined in rule: ' + ruleName); } } } newAction.next = next; } } if (typeof (action.goBack) === 'number') { newAction.goBack = action.goBack; } if (typeof (action.switchTo) === 'string') { newAction.switchTo = action.switchTo; } if (typeof (action.log) === 'string') { newAction.log = action.log; } if (typeof (action.nextEmbedded) === 'string') { newAction.nextEmbedded = action.nextEmbedded; lexer.usesEmbedded = true; } return newAction; } } else if (Array.isArray(action)) { var results = []; for (var i = 0, len = action.length; i < len; i++) { results[i] = compileAction(lexer, ruleName, action[i]); } return { group: results }; } else if (action.cases) { // build an array of test cases var cases_1 = []; // for each case, push a test function and result value for (var tkey in action.cases) { if (action.cases.hasOwnProperty(tkey)) { var val = compileAction(lexer, ruleName, action.cases[tkey]); // what kind of case if (tkey === '@default' || tkey === '@' || tkey === '') { cases_1.push({ test: undefined, value: val, name: tkey }); } else if (tkey === '@eos') { cases_1.push({ test: function (id, matches, state, eos) { return eos; }, value: val, name: tkey }); } else { cases_1.push(createGuard(lexer, ruleName, tkey, val)); // call separate function to avoid local variable capture } } } // create a matching function var def_1 = lexer.defaultToken; return { test: function (id, matches, state, eos) { for (var _i = 0, cases_2 = cases_1; _i < cases_2.length; _i++) { var _case = cases_2[_i]; var didmatch = (!_case.test || _case.test(id, matches, state, eos)); if (didmatch) { return _case.value; } } return def_1; } }; } else { throw monarchCommon.createError(lexer, 'an action must be a string, an object with a \'token\' or \'cases\' attribute, or an array of actions; in rule: ' + ruleName); } } /** * Helper class for creating matching rules */ var Rule = /** @class */ (function () { function Rule(name) { this.regex = new RegExp(''); this.action = { token: '' }; this.matchOnlyAtLineStart = false; this.name = ''; this.name = name; } Rule.prototype.setRegex = function (lexer, re) { var sregex; if (typeof (re) === 'string') { sregex = re; } else if (re instanceof RegExp) { sregex = re.source; } else { throw monarchCommon.createError(lexer, 'rules must start with a match string or regular expression: ' + this.name); } this.matchOnlyAtLineStart = (sregex.length > 0 && sregex[0] === '^'); this.name = this.name + ': ' + sregex; this.regex = compileRegExp(lexer, '^(?:' + (this.matchOnlyAtLineStart ? sregex.substr(1) : sregex) + ')'); }; Rule.prototype.setAction = function (lexer, act) { this.action = compileAction(lexer, this.name, act); }; return Rule; }()); /** * Compiles a json description function into json where all regular expressions, * case matches etc, are compiled and all include rules are expanded. * We also compile the bracket definitions, supply defaults, and do many sanity checks. * If the 'jsonStrict' parameter is 'false', we allow at certain locations * regular expression objects and functions that get called during lexing. * (Currently we have no samples that need this so perhaps we should always have * jsonStrict to true). */ export function compile(languageId, json) { if (!json || typeof (json) !== 'object') { throw new Error('Monarch: expecting a language definition object'); } // Create our lexer var lexer = {}; lexer.languageId = languageId; lexer.noThrow = false; // raise exceptions during compilation lexer.maxStack = 100; // Set standard fields: be defensive about types lexer.start = (typeof json.start === 'string' ? json.start : null); lexer.ignoreCase = bool(json.ignoreCase, false); lexer.tokenPostfix = string(json.tokenPostfix, '.' + lexer.languageId); lexer.defaultToken = string(json.defaultToken, 'source'); lexer.usesEmbedded = false; // becomes true if we find a nextEmbedded action // For calling compileAction later on var lexerMin = json; lexerMin.languageId = languageId; lexerMin.ignoreCase = lexer.ignoreCase; lexerMin.noThrow = lexer.noThrow; lexerMin.usesEmbedded = lexer.usesEmbedded; lexerMin.stateNames = json.tokenizer; lexerMin.defaultToken = lexer.defaultToken; // Compile an array of rules into newrules where RegExp objects are created. function addRules(state, newrules, rules) { for (var _i = 0, rules_1 = rules; _i < rules_1.length; _i++) { var rule = rules_1[_i]; var include = rule.include; if (include) { if (typeof (include) !== 'string') { throw monarchCommon.createError(lexer, 'an \'include\' attribute must be a string at: ' + state); } if (include[0] === '@') { include = include.substr(1); // peel off starting @ } if (!json.tokenizer[include]) { throw monarchCommon.createError(lexer, 'include target \'' + include + '\' is not defined at: ' + state); } addRules(state + '.' + include, newrules, json.tokenizer[include]); } else { var newrule = new Rule(state); // Set up new rule attributes if (Array.isArray(rule) && rule.length >= 1 && rule.length <= 3) { newrule.setRegex(lexerMin, rule[0]); if (rule.length >= 3) { if (typeof (rule[1]) === 'string') { newrule.setAction(lexerMin, { token: rule[1], next: rule[2] }); } else if (typeof (rule[1]) === 'object') { var rule1 = rule[1]; rule1.next = rule[2]; newrule.setAction(lexerMin, rule1); } else { throw monarchCommon.createError(lexer, 'a next state as the last element of a rule can only be given if the action is either an object or a string, at: ' + state); } } else { newrule.setAction(lexerMin, rule[1]); } } else { if (!rule.regex) { throw monarchCommon.createError(lexer, 'a rule must either be an array, or an object with a \'regex\' or \'include\' field at: ' + state); } if (rule.name) { if (typeof rule.name === 'string') { newrule.name = rule.name; } } if (rule.matchOnlyAtStart) { newrule.matchOnlyAtLineStart = bool(rule.matchOnlyAtLineStart, false); } newrule.setRegex(lexerMin, rule.regex); newrule.setAction(lexerMin, rule.action); } newrules.push(newrule); } } } // compile the tokenizer rules if (!json.tokenizer || typeof (json.tokenizer) !== 'object') { throw monarchCommon.createError(lexer, 'a language definition must define the \'tokenizer\' attribute as an object'); } lexer.tokenizer = []; for (var key in json.tokenizer) { if (json.tokenizer.hasOwnProperty(key)) { if (!lexer.start) { lexer.start = key; } var rules = json.tokenizer[key]; lexer.tokenizer[key] = new Array(); addRules('tokenizer.' + key, lexer.tokenizer[key], rules); } } lexer.usesEmbedded = lexerMin.usesEmbedded; // can be set during compileAction // Set simple brackets if (json.brackets) { if (!(Array.isArray(json.brackets))) { throw monarchCommon.createError(lexer, 'the \'brackets\' attribute must be defined as an array'); } } else { json.brackets = [ { open: '{', close: '}', token: 'delimiter.curly' }, { open: '[', close: ']', token: 'delimiter.square' }, { open: '(', close: ')', token: 'delimiter.parenthesis' }, { open: '<', close: '>', token: 'delimiter.angle' } ]; } var brackets = []; for (var _i = 0, _a = json.brackets; _i < _a.length; _i++) { var el = _a[_i]; var desc = el; if (desc && Array.isArray(desc) && desc.length === 3) { desc = { token: desc[2], open: desc[0], close: desc[1] }; } if (desc.open === desc.close) { throw monarchCommon.createError(lexer, 'open and close brackets in a \'brackets\' attribute must be different: ' + desc.open + '\n hint: use the \'bracket\' attribute if matching on equal brackets is required.'); } if (typeof desc.open === 'string' && typeof desc.token === 'string' && typeof desc.close === 'string') { brackets.push({ token: desc.token + lexer.tokenPostfix, open: monarchCommon.fixCase(lexer, desc.open), close: monarchCommon.fixCase(lexer, desc.close) }); } else { throw monarchCommon.createError(lexer, 'every element in the \'brackets\' array must be a \'{open,close,token}\' object or array'); } } lexer.brackets = brackets; // Disable throw so the syntax highlighter goes, no matter what lexer.noThrow = true; return lexer; }
angular.module("jaws.home", [ "ui.state", "audio", "audio.metronome", "jaws.home.audiometer" ]) .config(function config($stateProvider) { $stateProvider.state("home", { url: "/home", views: { "main": { controller: "HomeCtrl", templateUrl: "home/home.tpl.html" } } }); }) .controller("HomeCtrl", function HomeController($scope, audio, metronome) { var recording = false, input; audio.getAudioStream(function(node) { console.log("input stream available"); input = node; }, function(error) { console.log(error); }); $scope.metronomeOn = false; $scope.tracks = []; $scope.toggleArmed = function(track) { track.armed = !track.armed; }; $scope.addTrack = function() { if (!input) { return; } $scope.tracks.push(new Track(audio, input)); }; $scope.deleteTrack = function(track) { var index = $scope.tracks.indexOf(track); if (index != -1) { $scope.tracks.splice(index, 1); } }; $scope.toggleRecording = function() { recording = !recording; $scope.tracks.forEach(function(track) { track.setRecording(recording); }); }; $scope.play = function() { if (recording) { return; } // HACK to hopefully get all the tracks to play in time var playStart = audio.currentTime() + 1; $scope.tracks.forEach(function(track) { track.play(playStart); }); if ($scope.metronomeOn) { metronome.start(); // HOW TO STOP THE METRONOME? } }; $scope.recordingLabel = function() { return recording ? "Stop Recording" : "Start Recording"; }; $scope.trackArmedLabel = function(track) { return track && track.armed ? "Disarm" : "Arm"; }; }) ;
/** * @fileoverview DOM driver mock * @author Frederik Krautwald */ function makeEvents() { return () => { return {} } } function makeSelect() { return () => { return { select: makeSelect(), events: makeEvents(), } } } function mockDomDriver() { return { select: makeSelect(), } } export default mockDomDriver
import * as lamb from "../.."; import { nonStrings, nonStringsAsStrings, wannabeEmptyObjects } from "../../__tests__/commons"; import "../../__tests__/custom_matchers"; describe("setPath / setPathIn", function () { var obj = { a: 2, b: { a: { g: 10, h: 11 }, b: [4, 5], c: "foo" }, "c.d": { "e.f": 6 } }; var sparseArr = Object.freeze([, 55, ,]); // eslint-disable-line comma-spacing, no-sparse-arrays obj.b.d = sparseArr; Object.defineProperty(obj.b, "w", { value: { x: 22, y: { z: 33 } } }); var objCopy = JSON.parse(JSON.stringify(obj)); objCopy.b.d = sparseArr; afterEach(function () { expect(obj).toEqual(objCopy); expect(obj.b.d).toStrictArrayEqual(objCopy.b.d); }); it("should allow to set a nested property in a copy of the given object", function () { var r1 = lamb.setPath("a", 99, ".")(obj); var r2 = lamb.setPathIn(obj, "a", 99, "."); expect(r1).toEqual({ a: 99, b: { a: { g: 10, h: 11 }, b: [4, 5], c: "foo", d: sparseArr }, "c.d": { "e.f": 6 } }); expect(r1.b).toBe(obj.b); expect(r1["c.d"]).toBe(obj["c.d"]); expect(r1.b.d).toStrictArrayEqual(sparseArr); expect(r2).toEqual(r1); expect(r2.b.d).toStrictArrayEqual(sparseArr); var r3 = lamb.setPath("b.c", "bar", ".")(obj); var r4 = lamb.setPathIn(obj, "b.c", "bar", "."); expect(r3).toEqual({ a: 2, b: { a: { g: 10, h: 11 }, b: [4, 5], c: "bar", d: sparseArr }, "c.d": { "e.f": 6 } }); expect(r3.b.a).toBe(obj.b.a); expect(r3.b.b).toBe(obj.b.b); expect(r3["c.d"]).toBe(obj["c.d"]); expect(r3.b.d).toStrictArrayEqual(sparseArr); expect(r4).toEqual(r3); expect(r4.b.d).toStrictArrayEqual(sparseArr); }); it("should use the dot as the default separator", function () { var r = lamb.setPath("b.a.g", 99)(obj); expect(r).toEqual({ a: 2, b: { a: { g: 99, h: 11 }, b: [4, 5], c: "foo", d: sparseArr }, "c.d": { "e.f": 6 } }); expect(r.b.b).toBe(obj.b.b); expect(r["c.d"]).toBe(obj["c.d"]); expect(lamb.setPathIn(obj, "b.a.g", 99)).toEqual(r); }); it("should ignore extra arguments passed to the built function in its partially applied form", function () { var r = lamb.setPath("b.c", "bar")(obj, {}); expect(r).toEqual({ a: 2, b: { a: { g: 10, h: 11 }, b: [4, 5], c: "bar", d: sparseArr }, "c.d": { "e.f": 6 } }); }); it("should allow custom separators", function () { var r = lamb.setPath("c.d->e.f", 99, "->")(obj); expect(r).toEqual({ a: 2, b: { a: { g: 10, h: 11 }, b: [4, 5], c: "foo", d: [, 55, , ] // eslint-disable-line comma-spacing, no-sparse-arrays }, "c.d": { "e.f": 99 } }); expect(r.b).toBe(obj.b); expect(lamb.setPathIn(obj, "c.d->e.f", 99, "->")).toEqual(r); }); it("should add non-existent properties to existing objects", function () { var r1 = { a: 2, b: { a: { g: 10, h: 11 }, b: [4, 5], c: "foo", d: [, 55, , ], // eslint-disable-line comma-spacing, no-sparse-arrays z: 99 }, "c.d": { "e.f": 6 } }; var r2 = { a: 2, b: { a: { g: 10, h: 11 }, b: [4, 5], c: "foo", d: [, 55, , ] // eslint-disable-line comma-spacing, no-sparse-arrays }, "c.d": { "e.f": 6 }, z: { a: 99 } }; var r3 = { a: 2, b: { a: { g: 10, h: 11 }, b: [4, 5], c: "foo", d: [, 55, , ] // eslint-disable-line comma-spacing, no-sparse-arrays }, "c.d": { "e.f": 6 }, z: { a: { b: 99 } } }; expect(lamb.setPath("b.z", 99)(obj)).toEqual(r1); expect(lamb.setPathIn(obj, "b.z", 99)).toEqual(r1); expect(lamb.setPath("z.a", 99)(obj)).toEqual(r2); expect(lamb.setPathIn(obj, "z.a", 99)).toEqual(r2); expect(lamb.setPath("z.a.b", 99)(obj)).toEqual(r3); expect(lamb.setPathIn(obj, "z.a.b", 99)).toEqual(r3); var o = { a: null }; var r4 = { a: { b: { c: 99 } } }; expect(lamb.setPath("a.b.c", 99)(o)).toEqual(r4); expect(lamb.setPathIn(o, "a.b.c", 99)).toEqual(r4); }); it("should treat non-enumerable properties encountered in a path as non-existent properties", function () { var r1 = { a: 2, b: { a: { g: 10, h: 11 }, b: [4, 5], c: "foo", d: [, 55, , ], // eslint-disable-line comma-spacing, no-sparse-arrays w: { z: 99 } }, "c.d": { "e.f": 6 } }; var r2 = { a: 2, b: { a: { g: 10, h: 11 }, b: [4, 5], c: "foo", d: [, 55, , ], // eslint-disable-line comma-spacing, no-sparse-arrays w: { y: { z: 99 } } }, "c.d": { "e.f": 6 } }; expect(lamb.setPathIn(obj, "b.w.z", 99)).toEqual(r1); expect(lamb.setPath("b.w.z", 99)(obj)).toEqual(r1); expect(lamb.setPathIn(obj, "b.w.y.z", 99)).toEqual(r2); expect(lamb.setPath("b.w.y.z", 99)(obj)).toEqual(r2); }); it("should replace indexes when an array is found and the key is a string containing an integer", function () { var r = { a: 2, b: { a: { g: 10, h: 11 }, b: [4, 99], c: "foo", d: [, 55, , ] // eslint-disable-line comma-spacing, no-sparse-arrays }, "c.d": { "e.f": 6 } }; expect(lamb.setPath("b.b.1", 99)(obj)).toEqual(r); expect(lamb.setPathIn(obj, "b.b.1", 99)).toEqual(r); expect(lamb.setPath("1", 99)([1, 2, 3])).toEqual([1, 99, 3]); expect(lamb.setPathIn([1, 2, 3], "1", 99)).toEqual([1, 99, 3]); }); it("should allow using negative array indexes in path parts", function () { var r = { a: 2, b: { a: { g: 10, h: 11 }, b: [99, 5], c: "foo", d: [, 55, , ] // eslint-disable-line comma-spacing, no-sparse-arrays }, "c.d": { "e.f": 6 } }; expect(lamb.setPath("b.b.-2", 99)(obj)).toEqual(r); expect(lamb.setPathIn(obj, "b.b.-2", 99)).toEqual(r); expect(lamb.setPath("-2", 99)([1, 2, 3])).toEqual([1, 99, 3]); expect(lamb.setPathIn([1, 2, 3], "-2", 99)).toEqual([1, 99, 3]); }); it("should build dense arrays when the path target is a sparse array index", function () { var expected1 = { a: 2, b: { a: { g: 10, h: 11 }, b: [4, 5], c: "foo", d: [void 0, 99, void 0] }, "c.d": { "e.f": 6 } }; var expected2 = { a: 2, b: { a: { g: 10, h: 11 }, b: [4, 5], c: "foo", d: [void 0, 55, 99] }, "c.d": { "e.f": 6 } }; ["b.d.1", "b.d.-2", "b.d.-1", "b.d.2"].forEach(function (path, idx) { var r1 = lamb.setPathIn(obj, path, 99); var r2 = lamb.setPath(path, 99)(obj); var expected = idx < 2 ? expected1 : expected2; expect(r1).toEqual(expected); expect(r1.b.d).toStrictArrayEqual(expected.b.d); expect(r2).toEqual(expected); expect(r2.b.d).toStrictArrayEqual(expected.b.d); }); }); it("should not add new elements to an array and behave like `setAt` which returns a copy of the array", function () { var r1 = lamb.setPath("b.b.2", 99)(obj); var r2 = lamb.setPathIn(obj, "b.b.2", 99); var r3 = { a: 2, b: { a: { g: 10, h: 11 }, b: [4, 5], c: "foo", d: [void 0, 55, void 0] }, "c.d": { "e.f": 6 } }; expect(r1).toEqual(obj); expect(r2).toEqual(obj); expect(r1.b.b).not.toBe(obj.b.b); expect(r2.b.b).not.toBe(obj.b.b); expect(lamb.setPathIn(obj, "b.d.11", 99)).toEqual(r3); expect(lamb.setPath("b.d.11", 99)(obj)).toEqual(r3); }); it("should allow to change values nested in an array", function () { var o = { data: [ { id: 1, value: 10 }, { id: 2, value: 20 }, { id: 3, value: 30 } ] }; var r = { data: [ { id: 1, value: 10 }, { id: 2, value: 99 }, { id: 3, value: 30 } ] }; expect(lamb.setPath("data.1.value", 99)(o)).toEqual(r); expect(lamb.setPathIn(o, "data.1.value", 99)).toEqual(r); expect(lamb.setPath("data.-2.value", 99)(o)).toEqual(r); expect(lamb.setPathIn(o, "data.-2.value", 99)).toEqual(r); }); it("should build an object with numbered keys when an array-like object is found", function () { var r = { a: 2, b: { a: { g: 10, h: 11 }, b: [4, 5], c: { 0: "m", 1: "o", 2: "o" }, d: sparseArr }, "c.d": { "e.f": 6 } }; expect(lamb.setPath("b.c.0", "m")(obj)).toEqual(r); expect(lamb.setPathIn(obj, "b.c.0", "m")).toEqual(r); }); it("should build an object with numbered keys when an array is found and the key is not a string containing an integer", function () { var r = { a: 2, b: { a: { g: 10, h: 11 }, b: { 0: 4, 1: 5, z: 99 }, c: "foo", d: sparseArr }, "c.d": { "e.f": 6 } }; expect(lamb.setPath("b.b.z", 99)(obj)).toEqual(r); expect(lamb.setPathIn(obj, "b.b.z", 99)).toEqual(r); }); it("should accept integers as paths containing a single key", function () { expect(lamb.setPath(1, 99)([1, 2, 3])).toEqual([1, 99, 3]); expect(lamb.setPathIn([1, 2, 3], -1, 99)).toEqual([1, 2, 99]); expect(lamb.setPath(2, 99)([1, 2])).toEqual([1, 2]); expect(lamb.setPathIn({ a: 1 }, 1, 99)).toEqual({ a: 1, 1: 99 }); }); it("should give priority to object keys over array indexes when a negative index is encountered", function () { var o = { a: ["abc", "def", "ghi"] }; o.a["-1"] = "foo"; var r = { a: { 0: "abc", 1: "def", 2: "ghi", "-1": 99 } }; expect(lamb.setPath("a.-1", 99)(o)).toEqual(r); expect(lamb.setPathIn(o, "a.-1", 99)).toEqual(r); }); it("should consider a negative integer to be an index if the property exists but it's not enumerable", function () { var o = { a: ["abc", "def", "ghi"] }; Object.defineProperty(o.a, "-1", { value: 99 }); var r = { a: ["abc", "def", "foo"] }; expect(lamb.setPath("a.-1", "foo")(o)).toEqual(r); expect(lamb.setPathIn(o, "a.-1", "foo")).toEqual(r); }); it("should convert other values for the `path` parameter to string", function () { var values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; var testObj = lamb.make(nonStringsAsStrings, values); nonStrings.forEach(function (key) { var expected = lamb.merge({}, testObj); expected[String(key)] = 99; expect(lamb.setPathIn(testObj, key, 99, "_")).toEqual(expected); expect(lamb.setPath(key, 99, "_")(testObj)).toEqual(expected); }); expect(lamb.setPathIn({ a: 2 }, 1.5, 99)).toEqual({ a: 2, 1: { 5: 99 } }); expect(lamb.setPath(1.5, 99)({ a: 2 })).toEqual({ a: 2, 1: { 5: 99 } }); expect(lamb.setPathIn({ a: 2 })).toEqual({ a: 2, undefined: void 0 }); expect(lamb.setPath()({ a: 2 })).toEqual({ a: 2, undefined: void 0 }); }); it("should throw an exception if called without arguments", function () { expect(lamb.setPathIn).toThrow(); expect(lamb.setPath()).toThrow(); }); it("should throw an exception if supplied with `null` or `undefined` instead of an object", function () { expect(function () { lamb.setPathIn(null, "a", 99); }).toThrow(); expect(function () { lamb.setPathIn(void 0, "a", 99); }).toThrow(); expect(function () { lamb.setPath("a", 99)(null); }).toThrow(); expect(function () { lamb.setPath("a", 99)(void 0); }).toThrow(); }); it("should convert to object every other value", function () { wannabeEmptyObjects.forEach(function (value) { expect(lamb.setPathIn(value, "a", 99)).toEqual({ a: 99 }); expect(lamb.setPath("a", 99)(value)).toEqual({ a: 99 }); }); }); });
/* SHJS - Syntax Highlighting in JavaScript Copyright (C) 2007, 2008 gnombat@users.sourceforge.net License: http://shjs.sourceforge.net/doc/gplv3.html */ if (! this.sh_languages) { this.sh_languages = {}; } var sh_requests = {}; function sh_isEmailAddress(url) { if (/^mailto:/.test(url)) { return false; } return url.indexOf('@') !== -1; } function sh_setHref(tags, numTags, inputString) { var url = inputString.substring(tags[numTags - 2].pos, tags[numTags - 1].pos); if (url.length >= 2 && url.charAt(0) === '<' && url.charAt(url.length - 1) === '>') { url = url.substr(1, url.length - 2); } if (sh_isEmailAddress(url)) { url = 'mailto:' + url; } tags[numTags - 2].node.href = url; } /* Konqueror has a bug where the regular expression /$/g will not match at the end of a line more than once: var regex = /$/g; var match; var line = '1234567890'; regex.lastIndex = 10; match = regex.exec(line); var line2 = 'abcde'; regex.lastIndex = 5; match = regex.exec(line2); // fails */ function sh_konquerorExec(s) { var result = ['']; result.index = s.length; result.input = s; return result; } /** Highlights all elements containing source code in a text string. The return value is an array of objects, each representing an HTML start or end tag. Each object has a property named pos, which is an integer representing the text offset of the tag. Every start tag also has a property named node, which is the DOM element started by the tag. End tags do not have this property. @param inputString a text string @param language a language definition object @return an array of tag objects */ function sh_highlightString(inputString, language) { if (/Konqueror/.test(navigator.userAgent)) { if (! language.konquered) { for (var s = 0; s < language.length; s++) { for (var p = 0; p < language[s].length; p++) { var r = language[s][p][0]; if (r.source === '$') { r.exec = sh_konquerorExec; } } } language.konquered = true; } } var a = document.createElement('a'); var span = document.createElement('span'); // the result var tags = []; var numTags = 0; // each element is a pattern object from language var patternStack = []; // the current position within inputString var pos = 0; // the name of the current style, or null if there is no current style var currentStyle = null; var output = function(s, style) { var length = s.length; // this is more than just an optimization - we don't want to output empty <span></span> elements if (length === 0) { return; } if (! style) { var stackLength = patternStack.length; if (stackLength !== 0) { var pattern = patternStack[stackLength - 1]; // check whether this is a state or an environment if (! pattern[3]) { // it's not a state - it's an environment; use the style for this environment style = pattern[1]; } } } if (currentStyle !== style) { if (currentStyle) { tags[numTags++] = {pos: pos}; if (currentStyle === 'sh_url') { sh_setHref(tags, numTags, inputString); } } if (style) { var clone; if (style === 'sh_url') { clone = a.cloneNode(false); } else { clone = span.cloneNode(false); } clone.className = style; tags[numTags++] = {node: clone, pos: pos}; } } pos += length; currentStyle = style; }; var endOfLinePattern = /\r\n|\r|\n/g; endOfLinePattern.lastIndex = 0; var inputStringLength = inputString.length; while (pos < inputStringLength) { var start = pos; var end; var startOfNextLine; var endOfLineMatch = endOfLinePattern.exec(inputString); if (endOfLineMatch === null) { end = inputStringLength; startOfNextLine = inputStringLength; } else { end = endOfLineMatch.index; startOfNextLine = endOfLinePattern.lastIndex; } var line = inputString.substring(start, end); var matchCache = []; for (;;) { var posWithinLine = pos - start; var stateIndex; var stackLength = patternStack.length; if (stackLength === 0) { stateIndex = 0; } else { // get the next state stateIndex = patternStack[stackLength - 1][2]; } var state = language[stateIndex]; var numPatterns = state.length; var mc = matchCache[stateIndex]; if (! mc) { mc = matchCache[stateIndex] = []; } var bestMatch = null; var bestPatternIndex = -1; for (var i = 0; i < numPatterns; i++) { var match; if (i < mc.length && (mc[i] === null || posWithinLine <= mc[i].index)) { match = mc[i]; } else { var regex = state[i][0]; regex.lastIndex = posWithinLine; match = regex.exec(line); mc[i] = match; } if (match !== null && (bestMatch === null || match.index < bestMatch.index)) { bestMatch = match; bestPatternIndex = i; if (match.index === posWithinLine) { break; } } } if (bestMatch === null) { output(line.substring(posWithinLine), null); break; } else { // got a match if (bestMatch.index > posWithinLine) { output(line.substring(posWithinLine, bestMatch.index), null); } var pattern = state[bestPatternIndex]; var newStyle = pattern[1]; var matchedString; if (newStyle instanceof Array) { for (var subexpression = 0; subexpression < newStyle.length; subexpression++) { matchedString = bestMatch[subexpression + 1]; output(matchedString, newStyle[subexpression]); } } else { matchedString = bestMatch[0]; output(matchedString, newStyle); } switch (pattern[2]) { case -1: // do nothing break; case -2: // exit patternStack.pop(); break; case -3: // exitall patternStack.length = 0; break; default: // this was the start of a delimited pattern or a state/environment patternStack.push(pattern); break; } } } // end of the line if (currentStyle) { tags[numTags++] = {pos: pos}; if (currentStyle === 'sh_url') { sh_setHref(tags, numTags, inputString); } currentStyle = null; } pos = startOfNextLine; } return tags; } //////////////////////////////////////////////////////////////////////////////// // DOM-dependent functions function sh_getClasses(element) { var result = []; var htmlClass = element.className; if (htmlClass && htmlClass.length > 0) { var htmlClasses = htmlClass.split(' '); for (var i = 0; i < htmlClasses.length; i++) { if (htmlClasses[i].length > 0) { result.push(htmlClasses[i]); } } } return result; } function sh_addClass(element, name) { var htmlClasses = sh_getClasses(element); for (var i = 0; i < htmlClasses.length; i++) { if (name.toLowerCase() === htmlClasses[i].toLowerCase()) { return; } } htmlClasses.push(name); element.className = htmlClasses.join(' '); } /** Extracts the tags from an HTML DOM NodeList. @param nodeList a DOM NodeList @param result an object with text, tags and pos properties */ function sh_extractTagsFromNodeList(nodeList, result) { var length = nodeList.length; for (var i = 0; i < length; i++) { var node = nodeList.item(i); switch (node.nodeType) { case 1: if (node.nodeName.toLowerCase() === 'br') { var terminator; if (/MSIE/.test(navigator.userAgent)) { terminator = '\r'; } else { terminator = '\n'; } result.text.push(terminator); result.pos++; } else { result.tags.push({node: node.cloneNode(false), pos: result.pos}); sh_extractTagsFromNodeList(node.childNodes, result); result.tags.push({pos: result.pos}); } break; case 3: case 4: result.text.push(node.data); result.pos += node.length; break; } } } /** Extracts the tags from the text of an HTML element. The extracted tags will be returned as an array of tag objects. See sh_highlightString for the format of the tag objects. @param element a DOM element @param tags an empty array; the extracted tag objects will be returned in it @return the text of the element @see sh_highlightString */ function sh_extractTags(element, tags) { var result = {}; result.text = []; result.tags = tags; result.pos = 0; sh_extractTagsFromNodeList(element.childNodes, result); return result.text.join(''); } /** Merges the original tags from an element with the tags produced by highlighting. @param originalTags an array containing the original tags @param highlightTags an array containing the highlighting tags - these must not overlap @result an array containing the merged tags */ function sh_mergeTags(originalTags, highlightTags) { var numOriginalTags = originalTags.length; if (numOriginalTags === 0) { return highlightTags; } var numHighlightTags = highlightTags.length; if (numHighlightTags === 0) { return originalTags; } var result = []; var originalIndex = 0; var highlightIndex = 0; while (originalIndex < numOriginalTags && highlightIndex < numHighlightTags) { var originalTag = originalTags[originalIndex]; var highlightTag = highlightTags[highlightIndex]; if (originalTag.pos <= highlightTag.pos) { result.push(originalTag); originalIndex++; } else { result.push(highlightTag); if (highlightTags[highlightIndex + 1].pos <= originalTag.pos) { highlightIndex++; result.push(highlightTags[highlightIndex]); highlightIndex++; } else { // new end tag result.push({pos: originalTag.pos}); // new start tag highlightTags[highlightIndex] = {node: highlightTag.node.cloneNode(false), pos: originalTag.pos}; } } } while (originalIndex < numOriginalTags) { result.push(originalTags[originalIndex]); originalIndex++; } while (highlightIndex < numHighlightTags) { result.push(highlightTags[highlightIndex]); highlightIndex++; } return result; } /** Inserts tags into text. @param tags an array of tag objects @param text a string representing the text @return a DOM DocumentFragment representing the resulting HTML */ function sh_insertTags(tags, text) { var doc = document; var result = document.createDocumentFragment(); var tagIndex = 0; var numTags = tags.length; var textPos = 0; var textLength = text.length; var currentNode = result; // output one tag or text node every iteration while (textPos < textLength || tagIndex < numTags) { var tag; var tagPos; if (tagIndex < numTags) { tag = tags[tagIndex]; tagPos = tag.pos; } else { tagPos = textLength; } if (tagPos <= textPos) { // output the tag if (tag.node) { // start tag var newNode = tag.node; currentNode.appendChild(newNode); currentNode = newNode; } else { // end tag currentNode = currentNode.parentNode; } tagIndex++; } else { // output text currentNode.appendChild(doc.createTextNode(text.substring(textPos, tagPos))); textPos = tagPos; } } return result; } /** Highlights an element containing source code. Upon completion of this function, the element will have been placed in the "sh_sourceCode" class. @param element a DOM <pre> element containing the source code to be highlighted @param language a language definition object */ function sh_highlightElement(element, language) { sh_addClass(element, 'sh_sourceCode'); var originalTags = []; var inputString = sh_extractTags(element, originalTags); var highlightTags = sh_highlightString(inputString, language); var tags = sh_mergeTags(originalTags, highlightTags); var documentFragment = sh_insertTags(tags, inputString); while (element.hasChildNodes()) { element.removeChild(element.firstChild); } element.appendChild(documentFragment); } function sh_getXMLHttpRequest() { if (window.ActiveXObject) { return new ActiveXObject('Msxml2.XMLHTTP'); } else if (window.XMLHttpRequest) { return new XMLHttpRequest(); } throw 'No XMLHttpRequest implementation available'; } function sh_load(language, element, prefix, suffix) { if (language in sh_requests) { sh_requests[language].push(element); return; } sh_requests[language] = [element]; var request = sh_getXMLHttpRequest(); var url = prefix + 'sh_' + language + suffix; request.open('GET', url, true); request.onreadystatechange = function () { if (request.readyState === 4) { try { if (! request.status || request.status === 200) { eval(request.responseText); var elements = sh_requests[language]; for (var i = 0; i < elements.length; i++) { sh_highlightElement(elements[i], sh_languages[language]); } } else { throw 'HTTP error: status ' + request.status; } } finally { request = null; } } }; request.send(null); } /** Highlights all elements containing source code on the current page. Elements containing source code must be "pre" elements with a "class" attribute of "sh_LANGUAGE", where LANGUAGE is a valid language identifier; e.g., "sh_java" identifies the element as containing "java" language source code. */ function sh_highlightDocument(prefix, suffix) { var nodeList = document.getElementsByTagName('pre'); for (var i = 0; i < nodeList.length; i++) { var element = nodeList.item(i); var htmlClasses = sh_getClasses(element); for (var j = 0; j < htmlClasses.length; j++) { var htmlClass = htmlClasses[j].toLowerCase(); if (htmlClass === 'sh_sourcecode') { continue; } if (htmlClass.substr(0, 3) === 'sh_') { var language = htmlClass.substring(3); if (language in sh_languages) { sh_highlightElement(element, sh_languages[language]); } else if (typeof(prefix) === 'string' && typeof(suffix) === 'string') { sh_load(language, element, prefix, suffix); } else { throw 'Found <pre> element with class="' + htmlClass + '", but no such language exists'; } break; } } } }
/** * SensorController * * @description :: Server-side logic for managing Sensors * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ module.exports = { };
/** * access/scope.js * * @author Denis Luchkin-Zhou <denis@ricepo.com> * @license MIT */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.getScope = getScope; exports['default'] = scope; // istanbul ignore next function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _bluebird = require('bluebird'); var _bluebird2 = _interopRequireDefault(_bluebird); var _authorized = require('authorized'); var _authorized2 = _interopRequireDefault(_authorized); var _ignisUtil = require('ignis-util'); /*! * Symbols used by scope.js */ var __scopes = (0, _ignisUtil.symbol)('Ignis::access::scopes'); exports.__scopes = __scopes; /** * getScope(2) * * @description Creates a function that retrieves the scope. * @param {ignis} The Ignis app instance. * @param {name} Name of the scope to retrieve. * @return {Function} Function that retrieves the scope. */ function getScope(ignis, name) { return (0, _ignisUtil.unpromisify)(function (req) { var callbacks = ignis[__scopes].get(name); /* Deny if there are no scope callbacks */ if (!callbacks || callbacks.length === 0) { return _bluebird2['default'].resolve(null); } /* Start trying */ return callbacks.reduce(function (last, next) { return last.then(function (data) { if (data) { return data; } if (req.params[next.param]) { return next.callback(req.params[next.param]); } return null; }); }, _bluebird2['default'].resolve(null)).then(function (data) { return data || null; }); }); } /** * scope(3) * * @description Specifies the callback to retrieve an entity. * @param {name} Name of the entity. * @param {param} URL param that contains ID used for the search. * @param {callback} Promise-generating callback to retrieve the * entity using the specified ID. * @return {this} Namespace for further chaining. */ function scope(name, param, callback) { // istanbul ignore next var _this = this; var store = this[__scopes]; /* Create a scope if it is not already present */ if (!store.has(name)) { store.set(name, []); _authorized2['default'].entity(name, function (req, done) { getScope(_this, name)(req, done); }); } store.get(name).push({ param: param, callback: callback }); } //# sourceMappingURL=scope.js.map
import * as types from '../constant/actiontype'; export default function (state = {}, action) { const { payload, meta = {}, type } = action; switch (type) { case types.FETCH_UPDATE_INFO: return { ...state, ...payload }; default: return state; } }
(function ($) { $.fn.bootstrapModalManager = function (options) { // Define html templates var headTemplate = '<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title">{{title}}</h4></div>', bodyTemplate = '<div class="modal-body"><p>{{body}}</p></div>', footerTemplate = ' <div class="modal-footer">{{footerButtons}}</div>', containerTemplate = '<div class="modal fade" tabindex="-1" role="dialog"><div class="modal-dialog"><div class="modal-content"></div></div></div>', buttonTemplate = '<button type="button" class="btn {{classes}}">{{text}}</button>', settings = { head: { text: 'Test title' }, body: { text: 'A body of text.' }, footer: { buttons: [] } } // data-dismiss="modal" // Extend the passed in options object. $.extend(true, settings, options); // Validate the values. validateSettings(); // Create the modal var $modal = $(containerTemplate); $modal.find('.modal-content') .append(headTemplate.replace('{{title}}', settings.head.text)) .append(bodyTemplate.replace('{{body}}', settings.body.text)) .append(footerTemplate.replace('{{footerButtons}}', constructButtons(settings.footer.buttons))); // Add modal to the page and show. this.append($modal); $modal.find('.modal-footer') .find('button') .each(function (i, obj) { if (settings.footer.buttons[i].action != null) { $(this).on('click', settings.footer.buttons[i].action); } else { // If button doesn't have an action it will close the $(this).on('click', function () { closeModal(this); }) } }); $modal.modal(); /** Construct the buttons from the supplyed array. */ function constructButtons(buttonList) { var buttons = ''; for (var i = 0; i < buttonList.length; i++) { buttons += buttonTemplate .replace('{{classes}}', buttonList[i].classes.join(' ')) .replace('{{text}}', buttonList[i].text); } return buttons; } /** Check the values in settings are valid. */ function validateSettings() { if (typeof settings.head != 'object') { throw "Head section is not an object."; } if (typeof settings.head.text != 'string') { throw "Head section should have a text property string."; } if (typeof settings.body != 'object') { throw "Body section is not an object."; } if (typeof settings.body.text != 'string') { throw "Body section should have a text property string."; } if (typeof settings.footer != 'object') { throw "Footer section is not an object."; } if (!settings.footer.buttons instanceof Array) { throw "Footer should have a buttons array. If you don't want any buttons this should be an empty array."; } } /** * Close and then remove the modal. */ function closeModal() { setTransitionEndEvent(); $modal.modal('hide'); } /** * Capture the end of the transition so the modal can be removed. */ function setTransitionEndEvent() { var transitionEvent = getTransitionEndEvent(); $modal[0].addEventListener(transitionEvent, function () { console.log('Transition end event!'); setTimeout(function () { $modal.remove(); }, 200); }); } function getTransitionEndEvent() { var t; var el = document.createElement('fakeelement'); var transitions = { 'transition': 'transitionend', 'OTransition': 'oTransitionEnd', 'MozTransition': 'transitionend', 'WebkitTransition': 'webkitTransitionEnd' } for (t in transitions) { if (el.style[t] !== undefined) { return transitions[t]; } } } return $modal; } })($)
import React from 'react' export default { "welcome": { title: "Get started", content: ( <div> </div> ) }, "what-is-pcr": { title: "What is PCR", content: ( <div> We have two primers which anneal to a target sequence. Polymerase can then attach to the double stranded (annealed) regions and extend the primer sequence in the 5’ to 3’ direction. This means for the forward primer we are moving towards the end (direction right) of the sequence along the leading strand. For the reverse primer we are moving from the end of the sequence to be cloned towards the start of the leading sequence (direction left). However, the polymerase moves along the complementary strand. This means for the reverse primer, the polymerase is moving 3’ to 5’ according to the coding strand but 5’ to 3’ for the complementary strand. This uses free dNTPs. </div> ) }, "what-is-plasmid-cloning": { title: "What is PCR plasmid cloning", content: ( <div> <p>The theory of PCR cloning builds upon the ideas behind PCR. In addition to matching our gene of interest, we also at the same time add restriction sites to the ends of the PCR product so that it can be easily cloned into a plasmid of interest.</p> <p>We add these restriction sites to the 5’ ends of each primer. That means the restriction site on the coding strand will be upstream of the gene. Whilst the restriction site on the complementary strand will be downstream of the gene.</p> <p>By having matching restriction sites between the vector and gene, annealing of hanging ends results in the gene being inserted into the vector.</p> </div> ) }, "approaching-primer-design-questions": { title: "Approaching primer design questions", content: ( <div> <p>If you haven’t yet read “What is PCR” and “What is PCR cloning”, do so before moving onto the exercises. It’s always best to do the forward primer first, as its easiest, then our reverse primer.</p> <p>Splitting our primers up into two parts makes it easier for us to understand what each part does. Underneath each pair of inputs for a single primer, you will be shown a preview of the combined sequence. The segments are coloured slightly differently too so you can check your inputs against the exercise.</p> <ul> <li>A way to think about our primers is that the 5’ end of each primer is on the ‘outside’ of the gene, whilst the 3’ ends match the gene itself.</li> <li>Our 5’ segment always matches the vector, for both forward and reverse primers. Use this part to pick restriction sites and to add 5’ Caps and add bases to get the haystack in frame.</li> <li>Our 3’ segment matches the GOI only. </li> <li>For the forward primer this exactly matches the first 18-24 bases of the coding strand in the 5’ to 3’ direction.</li> <li>For the reverse primer, we want it to match exactly the last 18-24 bases of the complementary strand (as we’re moving leftwards).</li> <li>We present both primers in the 5’ to 3’ direction. This is already the case for the Forward Primer, but for the Reverse Primer we must reverse our 3’ to 5’ sequence to get a 5’ to 3’ sequence. </li> </ul> </div> ) }, "selecting-a-restriction-site": { title: "Selecting a restriction site", content: ( <div> For both forward and reverse primers, pick a restriction site that is unique in the vector. If a restriction site is contained multiple times, then you will have different copies of your sequence of interest after PCR. Only pick site which result in hanging ends. These are restriction sites where after cutting at different base positions results in ends that can anneal together. </div> ) }, "selecting-forward-primer-vector": { title: "Forward primer: matching the vector", content: ( <div> <p>Looking at the first half of our forward primer (the side with 5’), we need to include a restriction site that is contained within the vector. This must follow a few simple rules. </p> <ul> <li>The first being that the restriction site must be contained in, and unique to the vector.</li> <li>It cannot be inside our gene of interest that we wish to clone. </li> <li>It must also not appear more than once. </li> <li>It will also be after our promoter and before another unique restriction site that will be later used for our reverse primer.</li> </ul> <p>But which strand of our restriction site should we include in our primer? For our forward primer we choose the strand that runs in the same direction of our gene: the top 5’ to 3’ strand.</p> </div> ) }, "hanging-ends-vs-blunt-ends": { title: "Hanging ends vs blunt ends", content: ( <div> <p>In these exercises, you should always use restriction enzymes that will produce hanging ends rather than blunt ends. Blunt ends do not anneal complementary strands, instead being ligated by DNA ligase. This lack of complementarity means the direction of the inserted gene cannot be ensured.</p> </div> ) }, "selecting-reverse-primer-vector": { title: "Reverse primer: matching the vector", content: ( <div> <p>We follow similar rules for our forward primer. </p> <ul> <li>Our restriction site must be after the restriction site of the forward primer.</li> <li>The restriction site must be read 5’ to 3’ on the complementary strand (outwards to inwards remember!). Thankfully, since restriction sites are palindromic we can just copy the 5’ to 3’ direction of either strand.</li> </ul> </div> ) }, "preventing-vector-conflicts": { title: "Preventing restriction site conflicts within the vector", content: ( <div> <p>To ensure that the gene is correctly inserted, we must ensure that our two chosen restriction sites do not conflict. But how do we ensure this? </p> <p>We first check that both restriction sites are not the same. If we have our forward and reverse primers with the same RE site, then the gene could be inserted in either direction.</p> <p>In the same line of thought, we want to ensure our restriction sites do not overlap. That is, our forward primer’s restriction site comes before our reverse primer’s restriction site.</p> </div> ) }, "fusion-protein-vector-considerations": { title: "Additional considerations for fusion protein RE sites", content: ( <div> <p>If our vector contains a promoter, we should also ensure that our forward primer is after the promoter.</p> <p>If we are creating a fusion protein with a N-terminal tag, we should also ensure that our forward primer is after the tag. <strong>Otherwise, our tag would be lost and/or our protein wont be synthesised at all!</strong></p> <p>If we are creating a fusion protein with a C-terminal tag, we should ensure our reverse primer is before the tag and to not include any stop codons <strong>to prevent protein truncations</strong></p> </div> ) }, "preventing-sequence-of-interest-conflicts": { title: "Preventing restriction site conflicts within the sequence of interest", content: ( <div> <p>Our chosen restriction site enzymes must not cut within our sequence of interest in any way. If this were to happen, then when running your PCR your sequence of interest would be cut into smaller (and likely unusable) fragments of DNA upon addition of the restriction enzymes that you would need to create your hanging ends.</p> <p>Other restriction sites which you choose not to include in your primers do not matter, as their corresponding enzymes will not be in your PCR experiment.</p> </div> ) }, "forward-primer-annealing-sequence-of-interest": { title: "Forward Primer hybridisation sequence: annealing the sequence of interest", content: ( <div> <strong>FILL ME IN!</strong> </div> ) }, "reverse-primer-annealing-sequence-of-interest": { title: "Reverse Primer hybridisation sequence: annealing the sequence of interest", content: ( <div> <strong>FILL ME IN</strong> </div> ) }, "start-codons-when-and-how": { title: "When and where to add a start codon", content: ( <div> <strong>FILL ME IN</strong> </div> ) }, "forward-primer-frame": { title: "Getting the protein in frame: forward primer", content: ( <div> <strong>FILL ME IN</strong> </div> ) }, "stop-codons-when-and-how": { title: "When to add a stop codon", content: ( <div> <strong>FILL ME IN</strong> </div> ) }, "reverse-primer-frame": { title: "Getting in frame: reverse primer", content: ( <div> <strong>FILL ME IN</strong> </div> ) }, "other-considerations": { title: "Other considerations after annealing", content: ( <div> <strong>FILL ME IN</strong> </div> ) }, "5-prime-cap": { title: "Making the 5’ cap (‘leader sequence’)", content: ( <div> <p>Adding extra bases (2-10) at the 5’ end assists restriction enzymes in recognising and/or binding to their restriction.</p> </div> ) }, "GC-clamp": { title: "Making the 3’ GC Clamp", content: ( <div> <p>Fill me in</p> </div> ) }, "GC-content": { title: "Choosing and determining GC content", content: ( <div> <p>FIL ME IN</p> </div> ) }, "melting-temperatures": { title: "Determining melting and annealing temperatures", content: ( <div> <p>Fill me in</p> </div> ) } } // {/* <TutorialLink /* tutorialNumber="0.1" */ to="/tutorials/welcome">Get started</TutorialLink> // <TutorialLink /* tutorialNumber="1.1" */ to="/tutorials/what-is-pcr">What is PCR</TutorialLink> // <TutorialLink /* tutorialNumber="1.2" */ to="/tutorials/what-is-plasmid-cloning">What is PCR plasmid cloning</TutorialLink> // <TutorialLink /* tutorialNumber="1.3" */ to="/tutorials/approaching-questions">Approaching primer design questions</TutorialLink> // <TutorialLink /* tutorialNumber="2.1" */ to="/tutorials/selecting-a-re-site">Selecting a restriction site</TutorialLink> // <TutorialLink /* tutorialNumber="2.2" */ to="/tutorials/forward-primer-matching-vector">Forward primer: matching the vector</TutorialLink> // <TutorialLink /* tutorialNumber="2.3" */ to="/tutorials/blunt-vs-hanging-ends">Hanging ends vs blunt ends</TutorialLink> // <TutorialLink /* tutorialNumber="2.4" */ to="/tutorials/prevent-vector-conflicts">Preventing restriction site conflicts within the vector</TutorialLink> // <TutorialLink /* tutorialNumber="2.5" */ to="/tutorials/what-is-pcr">Preventing restriction site conflicts within the sequence of interest</TutorialLink> // <TutorialLink /* tutorialNumber="2.6" */ to="/tutorials/forward-primer-hybridisation">Forward primer hybridisation sequence: annealing the sequence of interest</TutorialLink> // <TutorialLink /* tutorialNumber="3.1" */ to="/tutorials/reverse-primer-matching-vector">Reverse primer: matching the vector</TutorialLink> // <TutorialLink /* tutorialNumber="3.2" */ to="/tutorials/forward-primer-matching-vector">Reverse primer: preventing conflicts with the forward primer</TutorialLink> // <TutorialLink /* tutorialNumber="3.3" */ to="/tutorials/reverse-primer-hybridisation">Reverse primer hybridisation sequence: annealing the sequence of interest</TutorialLink> // <TutorialLink /* tutorialNumber="3.3" */ to="/tutorials/reverse-primer-hybridisation">Reverse primer hybridisation sequence: annealing the sequence of interest</TutorialLink> */}
const cwd = process.cwd() const env = require('./env') const path = require('path') const webpack = require('webpack') const postcssConfig = require('./postcss') const srcJSDir = path.join(cwd, 'src') const nodeModulesDir = path.join(cwd, 'node_modules') module.exports = function (options = {}) { // vue config const vue = { postcss: [ require('postcss-import'), require('precss'), require('postcss-calc'), require('postcss-sprites')(postcssConfig['postcss-sprites']), require('autoprefixer')(postcssConfig.autoprefixer) ] } // eslint config const eslint = { configFile: path.join(cwd, '.eslintrc.yaml'), // Loader will always return warnings emitWarning: true // do not enable cache, it will not work properly } // babel config const babelPlugins = [ 'add-module-exports', 'transform-es3-property-literals', 'transform-es3-member-expression-literals' ] // the 'transform-runtime' plugin tells babel // - Removes the inline babel helpers and uses the module babel-runtime/helpers instead. // - Automatically requires babel-runtime/regenerator when you use generators/async functions. // - Automatically requires babel-runtime/core-js and maps ES6 static methods (Object.assign) and built-ins (Promise). // set polyfill to false to avoid runtime to polyfill, otherwise it will insert `import` to the generated code, which will not be recoginized by browser unless you webpack it. if (options.transformRuntime) { babelPlugins.unshift(['transform-runtime', {polyfill: false}]) } const babel = { presets: [ ['stage-2'], ['es2015', {'loose': true, 'modules': 'commonjs'}] ], cacheDirectory: true, plugins: babelPlugins } // pre loaders const preLoaders = [ {test: /\.(?:js)$/, loader: 'source-map', include: nodeModulesDir} ] if (options.eslint) { const eslintJSDirs = [srcJSDir, ...(options.eslintJSDirs || [])] preLoaders.push({ test: /\.(?:js|vue)$/, loader: 'eslint', include: eslintJSDirs }) } const includeJSDirs = [srcJSDir, ...(options.includeJSDirs || [])] const excludeJSDirs = [...(options.excludeJSDirs || [])] // loaders const loaders = [ {test: /\.txt$/, loader: 'raw'}, {test: /\.html$/, loader: 'raw'}, {test: /\.pug/, loader: 'pug'}, {test: /\.json$/, loader: 'json'}, {test: /\.yaml$/, loader: 'json!yaml'}, {test: /\.css$/, loader: 'style!css!postcss'}, {test: /\.vue$/, loader: 'vue'}, {test: /\.js$/, include: includeJSDirs, exclude: excludeJSDirs, loader: 'babel'}, { test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'url', query: { // limit for base64 inlining in bytes limit: 10000, // custom naming format if file is larger than // the threshold name: '[name].[ext]?[hash]' } } ] const config = { output: {}, vue, eslint, // when used with vue, the babel config should be placed here // http://vue-loader.vuejs.org/en/features/es2015.html babel, module: { preLoaders, loaders, noParse: [] }, resolve: { root: [], alias: { 'data': path.join(cwd, 'data'), // the main file of vue 2.0 is ok, so no need to redefine // 'vuejs': path.join(cwd, 'node_modules/vue/dist/vue.min.js'), 'axios': path.join(cwd, 'node_modules/axios/dist/axios.min'), 'regularjs': path.join(cwd, 'node_modules/regularjs/dist/regular.min'), 'restate': path.join(cwd, 'node_modules/regular-state/restate-full'), 'stateman': path.join(cwd, 'node_modules/stateman/stateman.min') }, extensions: ['', '.js', '.vue', '.json', '.yaml'] }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: `"${env.getNodeEnv()}"` } }), new webpack.ProvidePlugin({ Vue: 'vue', VueRouter: 'vue-router', Vuex: 'vuex', syncVuexRouter: 'vuex-router-sync', Regular: 'regularjs', restate: 'restate', RegularStrap: 'regular-strap', VueStrap: 'zoro-vue-strap', _: 'lodash' }) ], node: { fs: 'empty' } } config.optimizePlugins = [ new webpack.optimize.OccurrenceOrderPlugin(), // https://github.com/mishoo/UglifyJS2/issues/1246#issuecomment-237535244 new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, screw_ie8: false, drop_console: true }, mangle: { screw_ie8: false }, output: { screw_ie8: false } }), new webpack.optimize.DedupePlugin(), new webpack.optimize.LimitChunkCountPlugin({maxChunks: 15}), // in chars (a char is a byte) new webpack.optimize.MinChunkSizePlugin({minChunkSize: 10000}) ] const isDevelopment = env.isDevelopment() if (isDevelopment) { // sourceMap 相关 config.output.pathinfo = true if (!process.env.NO_SOURCE_MAP) { // config.devtool = '#eval-source-map' // config.devtool = 'inline-module-source-map' config.devtool = 'eval' } } else { config.devtool = '#source-map' } return config }
import React from 'react'; export default class AbsolutePosition extends React.Component { // eslint-disable-line render() { const style = { position: 'absolute', top: this.props.top, left: this.props.left, width: this.props.width, border: '1px solid gray', background: '#fff', margin: 10, padding: 10, }; return ( <div style={style}> <p> This portal is opened manually and given an absolute position using:{' '} the opening element's <i>onClick</i> prop, and the portal's <i>isOpened</i> prop. </p> <p>Click anywhere outside to close it.</p> </div> ); } } AbsolutePosition.propTypes = { top: React.PropTypes.number, left: React.PropTypes.number, width: React.PropTypes.number, closePortal: React.PropTypes.func, };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = registerBuiltinTypeHandlers; var _invariant = require('./invariant'); var _invariant2 = _interopRequireDefault(_invariant); var _types = require('./types'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function registerBuiltinTypeHandlers(t) { // Notes from: http://sitr.us/2015/05/31/advanced-features-in-flow.html // and the flow source code. // Type of the class whose instances are of type T. // This lets you pass around classes as first-class values. t.declareTypeHandler({ name: 'Class', typeName: 'ClassType', accepts(input, instanceType) { if (typeof input !== 'function') { return false; } const expectedType = instanceType.resolve(); if (input === expectedType) { return true; } if (typeof expectedType === 'function') { if (expectedType.prototype.isPrototypeOf(input.prototype)) { return true; } else { return false; } } const annotation = t.getAnnotation(input); if (annotation) { return expectedType.acceptsType(annotation); } // we're dealing with a type switch (input.typeName) { case 'NumberType': case 'NumericLiteralType': return input === Number; case 'BooleanType': case 'BooleanLiteralType': return input === Boolean; case 'StringType': case 'StringLiteralType': return input === String; case 'ArrayType': case 'TupleType': return input === Array; default: return false; } }, inferTypeParameters(input) { return []; } }); // If A and B are object types, $Diff<A,B> is the type of objects that have // properties defined in A, but not in B. // Properties that are defined in both A and B are allowed too. t.declareTypeHandler({ name: '$Diff', typeName: '$DiffType', accepts(input, aType, bType) { if (input === null || typeof input !== "object" && typeof input !== "function") { return false; } aType = aType.resolve(); bType = bType.resolve(); (0, _invariant2.default)(aType instanceof _types.ObjectType && bType instanceof _types.ObjectType, "Can only $Diff object types."); const properties = aType.properties; for (let i = 0; i < properties.length; i++) { const property = properties[i]; if (bType.hasProperty(property.key)) { continue; } if (!property.accepts(input)) { return false; } } return true; }, inferTypeParameters(input) { return []; } }); // An object of type $Shape<T> does not have to have all of the properties // that type T defines. But the types of the properties that it does have // must accepts the types of the same properties in T. t.declareTypeHandler({ name: '$Shape', typeName: '$ShapeType', accepts(input, shapeType) { if (input === null || typeof input !== "object" && typeof input !== "function") { return false; } shapeType = shapeType.resolve(); (0, _invariant2.default)(shapeType instanceof _types.ObjectType, "Can only $Shape<T> object types."); for (const key in input) { const property = shapeType.getProperty(key); if (!property || !property.accepts(input)) { return false; } } return true; }, inferTypeParameters(input) { return []; } }); // Any, but at least T. t.declareTypeHandler({ name: '$SuperType', typeName: '$SuperType', accepts(input, superType) { return superType.accepts(input); }, inferTypeParameters(input) { return []; } }); // object with larger key set than X's t.declareTypeHandler({ name: '$SubType', typeName: '$SubType', accepts(input, subType) { return subType.accepts(input); }, inferTypeParameters(input) { return []; } }); // The set of keys of T. t.declareTypeHandler({ name: '$Keys', typeName: '$KeysType', accepts(input, subject) { subject = subject.resolve(); (0, _invariant2.default)(subject instanceof _types.ObjectType, '$Keys<T> - T must be an ObjectType.'); const properties = subject.properties; for (let i = 0; i < properties.length; i++) { const property = properties[i]; if (input === property.key) { return true; } } return false; }, inferTypeParameters(input) { return []; } }); t.declareTypeHandler({ name: 'Date', impl: Date, typeName: 'DateType', accepts(input) { return input instanceof Date && !isNaN(input.getTime()); }, inferTypeParameters(input) { return []; } }); t.declareTypeHandler({ name: 'Iterable', typeName: 'IterableType', accepts(input, keyType) { if (!input || typeof input[Symbol.iterator] !== 'function') { return false; } return true; }, inferTypeParameters(input) { return []; } }); t.declareTypeHandler({ name: 'Promise', impl: Promise, typeName: 'PromiseType', accepts(input) { return input && typeof input.then === 'function' && input.then.length > 1; }, inferTypeParameters(input) { return []; } }); t.declareTypeHandler({ name: 'Map', impl: Map, typeName: 'MapType', accepts(input, keyType, valueType) { if (!(input instanceof Map)) { return false; } for (const [key, value] of input) { if (!keyType.accepts(key) || !valueType.accepts(value)) { return false; } } return true; }, inferTypeParameters(input) { const keyTypes = []; const valueTypes = []; loop: for (const [key, value] of input) { findKey: { for (let i = 0; i < keyTypes.length; i++) { const type = keyTypes[i]; if (type.accepts(key)) { break findKey; } } keyTypes.push(t.typeOf(key)); } for (let i = 0; i < valueTypes.length; i++) { const type = valueTypes[i]; if (type.accepts(value)) { continue loop; } } valueTypes.push(t.typeOf(value)); } const typeInstances = []; if (keyTypes.length === 0) { typeInstances.push(t.existential()); } else if (keyTypes.length === 1) { typeInstances.push(keyTypes[0]); } else { typeInstances.push(t.union(...keyTypes)); } if (valueTypes.length === 0) { typeInstances.push(t.existential()); } else if (valueTypes.length === 1) { typeInstances.push(valueTypes[0]); } else { typeInstances.push(t.union(...valueTypes)); } return typeInstances; } }); t.declareTypeHandler({ name: 'Set', impl: Set, typeName: 'SetType', accepts(input, valueType) { if (!(input instanceof Set)) { return false; } for (const value of input) { if (!valueType.accepts(value)) { return false; } } return true; }, inferTypeParameters(input) { const valueTypes = []; loop: for (const value of input) { for (let i = 0; i < valueTypes.length; i++) { const type = valueTypes[i]; if (type.accepts(value)) { continue loop; } } valueTypes.push(t.typeOf(value)); } if (valueTypes.length === 0) { return [t.existential()]; } else if (valueTypes.length === 1) { return [valueTypes[0]]; } else { return [t.union(...valueTypes)]; } } }); return t; }
/** * Running Server */ exports.start = function () { var vhost = __vhost; for (var port in vhost) { start(port); } } function start(port) { var vhost = __vhost; var ssl = __ssl; if (ssl[port]) { var https = require('https').createServer({ key: require('fs').readFileSync(ssl[port].key, 'utf8'), cert: require('fs').readFileSync(ssl[port].cert, 'utf8') }, function (request, response) { serverHandler(request, response, vhost[port], port); }); https.listen(port, function () { runningMsg(port); }); } else { var http = require('http').createServer(function (request, response) { serverHandler(request, response, vhost[port], port); }); http.listen(port, function () { runningMsg(port); }) } } /** * Request and Response Handler * @param request: web server request * @param response: web server response * @param vhost: virtual host information * @param port: server port */ function serverHandler(request, response, vhost, port) { var server = {}; // Local Variable about Request Information server.port = port; // requested port server.vhost = vhost; server.request = request; // web server request server.response = response; // web server response // Conntection Controller require('./connection.js').connect(server); } // Server Running Message function runningMsg(port) { var date = new Date(); console.log('# Server Running : ' + port + ' (' + date + ')'); } global.__response_status_code = { 100: "Continue", 101: "Switching Protocols", 200: "OK", 201: "Created", 202: "Accepted", 203: "Non-Authoritative Information", 204: "No Content", 205: "Reset Content", 206: "Partial Content", 300: "Multiple Choices", 301: "Moved Permanently", 302: "Found", 303: "See Other", 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", 308: "Permanent Redirect", 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 406: "Not Acceptable", 407: "Proxy Authentication Required", 408: "Request Timeout", 409: "Conflict", 410: "Gone", 411: "Length Required", 412: "Precondition Failed", 413: "Request Entity Too Large", 414: "Request-URI Too Long", 415: "Unsupported Media Type", 416: "Requested Range Not Satisfiable", 417: "Expectation Failed", 426: "Upgrade Required", 428: "Precondition Required", 429: "Too Many Requests", 431: "Request Header Fields Too Large", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout", 505: "HTTP Version Not Supported", 506: "Variant Also Negotiates", 511: "Network Authentication Required", 0: null };
const DrawCard = require('../../drawcard.js'); const { Locations, CardTypes } = require('../../Constants'); class ForceOfTheRiver extends DrawCard { setupCardAbilities(ability) { this.action({ title: 'Create spirits from facedown dynasty cards', condition: () => this.game.isDuringConflict(), effect: 'summon {1}!', effectArgs: { id: 'spirit-of-the-river', label: 'Sprits of the River', name: 'Sprits of the River', facedown: false, type: CardTypes.Character }, gameAction: ability.actions.createToken(context => ({ target: [Locations.ProvinceOne, Locations.ProvinceTwo, Locations.ProvinceThree, Locations.ProvinceFour].map( location => context.player.getDynastyCardInProvince(location) ).filter(card => card.facedown) })) }); } canAttach(card, context) { if(!card.hasTrait('shugenja') || card.controller !== context.player) { return false; } return super.canAttach(card, context); } } ForceOfTheRiver.id = 'force-of-the-river'; module.exports = ForceOfTheRiver;
jQuery(function($) { $(".pinion-nivoSlider").nivoSlider(); });
(function() { ProtoCalendar.LangFile['it'] = { HOUR_MINUTE_ERROR: 'The time is not valid.', NO_DATE_ERROR: 'No day has been selected.', OK_LABEL: 'OK', DEFAULT_FORMAT: 'mm/dd/yyyy', LABEL_FORMAT: 'dddi mmm dd yyyy', MONTH_ABBRS: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'], WEEKDAY_ABBRS: ['Do','Lu','Ma','Me','Gio','Ve','Sa'], WEEKDAY_NAMES: ['Do','Lu','Ma','Me','Gio','Ve','Sa'], YEAR_LABEL: ' ', MONTH_LABEL: ' ', YEAR_AND_MONTH: false }; })();
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseAria = parseAria; /** * Support aria- and role in ReactTooltip * * @params props {Object} * @return {Object} */ function parseAria(props) { var ariaObj = {}; Object.keys(props).filter(function (prop) { // aria-xxx and role is acceptable return (/(^aria-\w+$|^role$)/.test(prop) ); }).forEach(function (prop) { ariaObj[prop] = props[prop]; }); return ariaObj; }
/* eslint-disable no-underscore-dangle */ import { Provider } from 'cerebral'; import { state } from 'cerebral'; import form from './src/form'; import rules from './src/rules'; import resetForm from './src/helpers/resetForm'; import formToJSON from './src/helpers/formToJSON'; export { default as form } from './src/form'; export { default as rules } from './src/rules'; export { computedField as field } from './src/form'; function FormsProvider(options = {}) { if (options.rules) { Object.assign(rules, options.rules); } if (options.errorMessages) { rules._errorMessages = options.errorMessages; } return Provider({ get(path) { return this.context.resolve.value(form(state`${path}`)); }, reset(path) { this.context.state.set(path, resetForm(this.context.state.get(path))); }, toJSON(path) { return formToJSON(this.context.state.get(path)); }, updateRules(newRules) { Object.assign(rules, newRules); }, updateErrorMessages(errorMessages) { Object.assign(rules._errorMessages, errorMessages); }, }); } export default FormsProvider;
(function(app){ app.controller('homeCtrl', function($scope, service, $templateRequest, $compile, $http){ var carouselHighlightData; var foodMenu; var mapLoc; var instaContent; //https://api.instagram.com/v1/users/search?q=juliosgarbi&client_id=ee1008e3dad0433eb962cbf6a8b5f17a&access_token=32268563.ee1008e.5b3a8945f92d4402a31912ce4fbfccbb&callback=jQuery21102631924652949065_1465078545962&_=1465078546204 var insta = { init:function(){ angular.forEach(instaContent, function(obj, index){ var li = document.createElement('li'); li.className = 'item'; var img = document.createElement('img'); img.src = obj.images.standard_resolution.url; li.appendChild(img); if(index < 10) document.querySelector('.insta-list._first').appendChild(li); else document.querySelector('.insta-list._sec').appendChild(li); }); this.createInteration(); }, createInteration:function(){ document.querySelector('.insta-list._first').addEventListener('mousemove', this.onMoveMouse.bind(this)); document.querySelector('.insta-list._sec').addEventListener('mousemove', this.onMoveMouse.bind(this)); }, onMoveMouse:function(e){ var x = (e.currentTarget.offsetWidth - window.innerWidth) * (e.screenX / (window.innerWidth - 40)) ; e.currentTarget.style.transform = "translate("+-x+"px, 0)"; } }; var mapLocale = { init:function(){ Maps.init(mapLoc, document.querySelector(".where-we-work .map")); } }; var menuCarousel = { actual:2, init:function(){ this.createFirstScreen(); }, createFirstScreen:function(){ this.createTemplate(0, 'before-out').then(function(){ this.createTemplate(1, 'before').then(function(){ this.createTemplate(2, 'actual').then(function(){ this.createTemplate(3, 'after').then(function(){ this.createTemplate(4, 'after-out').then(function(){ this.startEvent(); }.bind(this)); }.bind(this)); }.bind(this)); }.bind(this)); }.bind(this)); }, goNext:function(){ this.disposeEvent(); angular.element(document.querySelector('.before-out')).remove(); angular.element(document.querySelector('.after')).addClass('actual').removeClass('after'); angular.element(document.querySelector('.after-out')).addClass("after").removeClass('after-out'); angular.element(document.querySelector('.actual')).addClass("before").removeClass('actual'); angular.element(document.querySelector('.before')).addClass("before-out").removeClass('before'); if(this.actual == foodMenu.length - 1){ this.actual = 0; }else{ this.actual++; } this.createTemplate(this.actual, 'after-out').then(function(){ this.startEvent(); }.bind(this)); }, goBack:function(){ this.disposeEvent(); angular.element(document.querySelector('.after-out')).remove(); angular.element(document.querySelector('.after')).addClass('after-out').removeClass('after'); angular.element(document.querySelector('.actual')).addClass("after").removeClass('actual'); angular.element(document.querySelector('.before')).addClass("actual").removeClass('before'); angular.element(document.querySelector('.before-out')).addClass("before").removeClass('before-out'); if(this.actual == 0){ this.actual = foodMenu.length - 1; }else{ this.actual--; } this.createTemplate(this.actual, 'before-out').then(function(){ this.startEvent(); }.bind(this)); }, createTemplate:function(index, loc){ return $templateRequest("views/templates/menu-card.html").then(function(html){ var scope = $scope.$new(true); var template = angular.element(html); template.addClass(loc); scope.title = foodMenu[index].title; scope.desc = foodMenu[index].description; scope.price = foodMenu[index].price; angular.element(document.querySelector('.carousel-menu')).append($compile(template)(scope)); document.querySelector('.'+loc + " .image").style.background = "url("+foodMenu[index].image+") no-repeat center center"; document.querySelector('.'+loc + " .image").style.backgroundSize = "cover"; }); }, startEvent:function(){ this.a = document.querySelector('.after').eventListener('click', this.goNext.bind(this), false); //to add this.b = document.querySelector('.before').eventListener('click', this.goBack.bind(this), false); //to add }, disposeEvent:function(){ document.querySelector('.after').eventListener(this.a); document.querySelector('.before').eventListener(this.b); } }; var headerCarousel = { init:function(){ this.createFirstScreen(); this.alignImage(); this.createBullets(); window.addEventListener('resize', this.alignImage); }, blockScreen:function(){ document.querySelector('.header').style.height = "808px"; document.querySelector('.header .image').style.top = "inherit"; document.querySelector('.header .image').style.transform = "inherit"; document.querySelector('.header .image').style.bottom = "0"; }, alignImage:function(){ document.querySelector('.header .image').style.left = window.innerWidth / 2 + "px"; if(document.querySelector('.header .image').getBoundingClientRect().top < 103){ document.querySelector('.header .image').style.transform = "inherit"; document.querySelector('.header .image').style.top = 103 + "px"; } }, createFirstScreen:function(){ this.changeCarousel(0) }, createBullets:function(){ var bullets = ''; for(var i = 0; i < carouselHighlightData.length; i ++){ bullets += '<li class="bullet">'; bullets += ' <div class="ball"></div>'; bullets += ' <div class="line"></div>'; bullets += '</li>'; } document.querySelector('.header .bullets').innerHTML = bullets; document.querySelector('.header .bullets .bullet').classList.add('active'); var bulletList = document.querySelectorAll('.header .bullets .bullet'); for(var j = 0; j < bulletList.length; j++){ bulletList[j].addEventListener('click', this.handleClickBullet.bind(this)); } }, handleClickBullet:function(e){ var node = e.currentTarget; var childs = node.parentNode.childNodes; for (i = 0; i < childs.length; i++) { if (node == childs[i]) break; } document.querySelector('.header .bullets .active').classList.remove('active'); document.querySelectorAll('.header .bullets .bullet')[i].classList.add('active'); this.changeCarousel(i); }, changeCarousel:function(index){ document.querySelector('.header .background').style.background = "url("+carouselHighlightData[index].image+") no-repeat center center"; document.querySelector('.header .background').style.backgroundSize = "cover"; document.querySelector('.header .image').style.background = "url("+carouselHighlightData[index].image+") no-repeat center center"; document.querySelector('.header .image').style.backgroundSize = "cover"; document.querySelector('.header .title').innerHTML = carouselHighlightData[index].title; document.querySelector('.header .desc').innerHTML = carouselHighlightData[index].description; document.querySelector('.header .more').setAttribute("href", carouselHighlightData[index].link); } }; if(window.innerHeight < 808) { headerCarousel.blockScreen(); }else { document.querySelector('.header').style.height = window.innerHeight + "px"; } service.getHeaderHighlights().then(function(data){ carouselHighlightData = data; headerCarousel.init(); }); service.getMenuKits().then(function(data){ foodMenu = data; menuCarousel.init(); }); service.getMapLocation().then(function(data){ mapLoc = data; mapLocale.init(); }); service.getInstagram().then(function(data){ instaContent = data.data.data; insta.init(); }); HTMLElement.prototype.eventListener= function(type, func, capture){ if(typeof arguments[0]=="object"&&(!arguments[0].nodeType)){ return this.removeEventListener.apply(this,arguments[0]); } this.addEventListener(type, func, capture); return arguments; } }); })(angular.module('personalModule'));
/*global define*/ define([ 'jquery', 'underscore', 'backbone', 'tpl!templates/<%= name %>.html' ], function ($, _, Backbone, Tpl) { 'use strict'; var <%= _.classify(name) %>View = Backbone.View.extend({ template: Tpl, bindings: {}, events: {}, initialize: function () { } }); return <%= _.classify(name) %>View; });
var express = require('express'), json = require('express-json'), bodyParser = require('body-parser'), app = express(), http = require("http"), port = process.env.PORT || 3000; app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(express.static(__dirname + '/public')); http.createServer(app).listen(port, function () { console.log('Master I am here to serve you on port ', port); });
var restify = require('restify'); var bunyan = require('bunyan'); var util = require("util"); var allConfig = require('./config/param.json'); var logger = bunyan.createLogger({ name: "mantisbt-sync-jira", level: "debug" }); var server = restify.createServer({ name: "mantisbt-sync-jira", log: logger }); function createSubTasks(config, jiraClient, parentKey) { if (config.subTasks && parentKey) { logger.info("Creating subtask for Jira issue %s", parentKey); for (var i = 0; i < config.subTasks.length; i++) { var subtask = config.subTasks[i]; var jiraSubtask = { "fields": { "project": { "key": config.target.project.key }, "issuetype": { "id": subtask.issueType.id }, parent: { "key": parentKey }, "summary": subtask.summary, "description": subtask.description, "reporter": config.source.username } }; logger.info("Creating subtask for Jira issue %s - %s", parentKey, subtask.summary); jiraClient.post('/jira2/rest/api/2/issue', jiraSubtask, function (err, req, res, obj) { if (err) { logger.error(err); } }); } } logger.info("End creating subtask for Jira issue %s", parentKey); } function pushToJira(config, jiraClient, issue) { var jql = util.format('"cf[10017]" ~ "%s"', issue.id); var query = { "jql": jql, "startAt": 0, "maxResults": 1, "fields": [ "key" ] }; logger.debug("Searching existing issue in Jira with id %s", issue.id); jiraClient.post('/jira2/rest/api/2/search', query, function (err, req, res, obj) { if (err) { logger.error(err); } else { if (!obj.issues || !obj.issues.length) { var jiraIssue = { "fields": { "project": { "key": config.target.project.key }, "issuetype": { "id": config.convert.issueType.id } } }; var mapping = config.convert.mapping; for (var i = 0; i < mapping.length; i++) { var mappedField = mapping[i]; if (mappedField['jiraName']) { var jiraFieldName = mappedField['jiraName']; if (mappedField['mantisName']) { var mantisFieldName = mappedField['mantisName']; var value = issue[mantisFieldName]; if (!(typeof value === 'string')) { value = JSON.stringify(value); } jiraIssue['fields'][jiraFieldName] = value; } else if (mappedField['defaultValue']) { jiraIssue['fields'][jiraFieldName] = mappedField['defaultValue']; } else { logger.error("Can't find fieldValue in mapping", JSON.stringify(mappedField)); } } else { logger.error("Can't find jira field name in mapping", JSON.stringify(mappedField)); } } logger.info("Creating Jira issue for Mantis %d", issue.id); logger.debug("Pushing issue data : %s", JSON.stringify(jiraIssue)); jiraClient.post('/jira2/rest/api/2/issue', jiraIssue, function (err, req, res, obj) { if (err) { logger.error(err); } else if (obj.key) { logger.info("Jira issue created : %s", obj.key); createSubTasks(config, jiraClient, obj.key); } }); } } }); } // Function to retrieve the configuration for a given project function getConfigForProject(projectId) { var allProjects = allConfig.projects; for (var i = 0; i < allProjects.length; i++) { var project = allProjects[i]; if (project.id == projectId) { return project; } } logger.error("No project found for id %d", projectId); } // Function to fetch all active issues in Mantis function getSourceIssues(config, mantisClient, jiraClient) { logger.debug("Retrieving open issues in Mantis"); var uri = util.format('/bugs/search/findByProjectIdAndStatusIdNotIn?project=%s&status=%d&projection=%s', config.source.project.id, 90, "bugDetails"); mantisClient.get(uri, function (err, req, res, obj) { if (err) { logger.error(err); } else { var issues = obj._embedded.bugs; for (var i = 0; i < issues.length; i++) { var task = issues[i]; pushToJira(config, jiraClient, task); } } }); } function synForConfig(config) { logger.debug("Creating Mantis REST client for endpoint %s", config['source']['url']); var mantisClient = restify.createJsonClient({ url: config['source']['url'], version: '*', log: logger }); if (config.source.username) { mantisClient.basicAuth(config.source.username, config.source.password); } logger.debug("Creating Jira REST client for endpoint %s", config.target.url); var jiraClient = restify.createJsonClient({ url: config.target.url, version: '*', log: logger }); if (config.target.username) { jiraClient.basicAuth(config.target.username, config.target.password); } getSourceIssues(config, mantisClient, jiraClient); } server.get('/launch/:projectId', function create(req, res, next) { logger.info("Starting sync for project %s", req.params.projectId); var config = getConfigForProject(req.params.projectId); if (config) { synForConfig(config); res.send(200); } else { res.send(500); } return next(); }); server.get('/launchAll', function create(req, res, next) { var allProjects = allConfig.projects; for (var i = 0; i < allProjects.length; i++) { var project = allProjects[i]; logger.info("Starting sync for project %s", project.id); synForConfig(project); } res.send(200); return next(); }); server.listen(8080, function () { console.log('%s listening at %s', server.name, server.url); });
$('#save-battery-button').on('click', function(e) { e.preventDefault(); if ($(".combobox-menu-visible").length) { return; } var jsonData = $('#battery-form').serializeJSON(); Grocy.FrontendHelpers.BeginUiBusy("battery-form"); if (Grocy.EditMode === 'create') { Grocy.Api.Post('objects/batteries', jsonData, function(result) { Grocy.EditObjectId = result.created_object_id; Grocy.Components.UserfieldsForm.Save(function() { if (GetUriParam("embedded") !== undefined) { window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl); } else { window.location.href = U('/batteries'); } }); }, function(xhr) { Grocy.FrontendHelpers.EndUiBusy("battery-form"); Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response) } ); } else { Grocy.Api.Put('objects/batteries/' + Grocy.EditObjectId, jsonData, function(result) { Grocy.Components.UserfieldsForm.Save(function() { if (GetUriParam("embedded") !== undefined) { window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl); } else { window.location.href = U('/batteries'); } }); }, function(xhr) { Grocy.FrontendHelpers.EndUiBusy("battery-form"); Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response) } ); } }); $('#battery-form input').keyup(function(event) { Grocy.FrontendHelpers.ValidateForm('battery-form'); }); $('#battery-form input').keydown(function(event) { if (event.keyCode === 13) //Enter { event.preventDefault(); if (document.getElementById('battery-form').checkValidity() === false) //There is at least one validation error { return false; } else { $('#save-battery-button').click(); } } }); $(document).on('click', '.battery-grocycode-label-print', function(e) { e.preventDefault(); document.activeElement.blur(); var batteryId = $(e.currentTarget).attr('data-chore-id'); Grocy.Api.Get('batteries/' + batteryId + '/printlabel', function(labelData) { if (Grocy.Webhooks.labelprinter !== undefined) { Grocy.FrontendHelpers.RunWebhook(Grocy.Webhooks.labelprinter, labelData); } }); }); Grocy.Components.UserfieldsForm.Load(); setTimeout(function() { $('#name').focus(); }, 250); Grocy.FrontendHelpers.ValidateForm('battery-form');
Ext.define('CF.view.Tree', { extend: 'GeoExt.tree.Panel', alias : 'widget.cf_tree', requires: [ 'Ext.tree.plugin.TreeViewDragDrop', 'GeoExt.panel.Map', 'GeoExt.tree.OverlayLayerContainer', 'GeoExt.tree.BaseLayerContainer', 'GeoExt.data.LayerTreeModel', 'GeoExt.tree.View', 'GeoExt.tree.Column' ], initComponent: function() { var store = Ext.create('Ext.data.TreeStore', { model: 'GeoExt.data.LayerTreeModel', root: { expanded: true, children: [ { plugins: ['gx_baselayercontainer'], expanded: true, text: "Base Maps" }, { plugins: ['gx_overlaylayercontainer'], expanded: true } ] } }); Ext.apply(this, { border: true, region: "west", title: "Layers", width: 180, minWidth: 150, maxWidth: 400, split: true, collapsible: true, collapseMode: "mini", autoScroll: true, store: store, rootVisible: false, lines: false }); this.callParent(arguments); } });
import AppContainer from './AppContainer' import HomeContainer from './HomeContainer' import MemoContainer from './MemoContainer' import LoginContainer from './LoginContainer' import RegisterContainer from './RegisterContainer' import NoMatchContainer from './NoMatchContainer' import WallContainer from './WallContainer' export { AppContainer, HomeContainer, MemoContainer, LoginContainer, RegisterContainer, NoMatchContainer, WallContainer }
import { expect } from "../test_helper"; import youtubeReducer, { _nullState } from "../../reducers/youtube_reducer"; import { RECEIVE_YOUTUBE_FOLLOWS } from "../../actions/youtube_actions"; describe("Youtube Reducer", () => { it("handles action with unknown type", () => { expect(youtubeReducer(undefined, {})).to.eql(_nullState); }); it("handles action with type RECEIVE_YOUTUBE_FOLLOWS", () => { const channels = ["channel1", "channel2"]; const action = { type: RECEIVE_YOUTUBE_FOLLOWS, channels, }; expect(youtubeReducer(undefined, action).channels).to.eql(channels); }); });
module.exports = function rootHandler (request, reply) { reply.view('index', { title: 'Workflow Viewer' }); };
module.exports = ` <path id="retina" fill="none" stroke="black" stroke-width="1" d="M 222.61,74.10 C 227.04,79.29 226.26,85.87 219.00,87.69 214.22,88.88 207.73,87.24 204.21,83.78 197.76,77.43 197.35,70.85 207.00,68.47 212.97,67.77 218.58,69.39 222.61,74.10 Z M 273.89,72.22 C 276.90,78.15 268.25,86.19 263.00,87.47 257.31,88.85 246.84,87.21 248.71,79.00 250.03,73.19 255.80,70.08 261.00,68.53 264.83,67.99 271.82,68.17 273.89,72.22 Z" /> `;
var webpack = require('webpack'); var path = require("path"); module.exports = { entry: './entry.js', output: { path: path.join(__dirname, "dist"), filename: 'bundle.js', publicPath:"dist/", //给require.ensure用 chunkFilename: "[name].chunk.js"//给require.ensure用 }, module: { loaders: [ {test: /\.css$/, loader: 'style!css'} ] }, plugins: [ new webpack.BannerPlugin('This file is created by lufeng') ], devtool: "source-map" }
/*! * Stylus - RGBA * Copyright(c) 2010 LearnBoost <dev@learnboost.com> * MIT Licensed */ /** * Module dependencies. */ var Node = require('./node') , HSLA = require('./hsla') , functions = require('../functions') , adjust = functions.adjust , nodes = require('./'); /** * Initialize a new `RGBA` with the given r,g,b,a component values. * * @param {Number} r * @param {Number} g * @param {Number} b * @param {Number} a * @api public */ var RGBA = exports = module.exports = function RGBA(r,g,b,a){ Node.call(this); this.r = clamp(r); this.g = clamp(g); this.b = clamp(b); this.a = clampAlpha(a); this.rgba = this; }; /** * Inherit from `Node.prototype`. */ RGBA.prototype.__proto__ = Node.prototype; /** * Return an `RGBA` without clamping values. * * @param {Number} r * @param {Number} g * @param {Number} b * @param {Number} a * @return {RGBA} * @api public */ RGBA.withoutClamping = function(r,g,b,a){ var rgba = new RGBA(0,0,0,0); rgba.r = r; rgba.g = g; rgba.b = b; rgba.a = a; return rgba; }; /** * Return a clone of this node. * * @return {Node} * @api public */ RGBA.prototype.clone = function(){ var clone = new RGBA( this.r , this.g , this.b , this.a); clone.raw = this.raw; clone.lineno = this.lineno; clone.column = this.column; clone.filename = this.filename; return clone; }; /** * Return a JSON representation of this node. * * @return {Object} * @api public */ RGBA.prototype.toJSON = function(){ return { __type: 'RGBA', r: this.r, g: this.g, b: this.b, a: this.a, raw: this.raw, lineno: this.lineno, column: this.column, filename: this.filename }; }; /** * Return true. * * @return {Boolean} * @api public */ RGBA.prototype.toBoolean = function(){ return nodes.true; }; /** * Return `HSLA` representation. * * @return {HSLA} * @api public */ RGBA.prototype.__defineGetter__('hsla', function(){ return HSLA.fromRGBA(this); }); /** * Return hash. * * @return {String} * @api public */ RGBA.prototype.__defineGetter__('hash', function(){ return this.toString(); }); /** * Add r,g,b,a to the current component values. * * @param {Number} r * @param {Number} g * @param {Number} b * @param {Number} a * @return {RGBA} new node * @api public */ RGBA.prototype.add = function(r,g,b,a){ return new RGBA( this.r + r , this.g + g , this.b + b , this.a + a); }; /** * Subtract r,g,b,a from the current component values. * * @param {Number} r * @param {Number} g * @param {Number} b * @param {Number} a * @return {RGBA} new node * @api public */ RGBA.prototype.sub = function(r,g,b,a){ return new RGBA( this.r - r , this.g - g , this.b - b , a == 1 ? this.a : this.a - a); }; /** * Multiply rgb components by `n`. * * @param {String} n * @return {RGBA} new node * @api public */ RGBA.prototype.multiply = function(n){ return new RGBA( this.r * n , this.g * n , this.b * n , this.a); }; /** * Divide rgb components by `n`. * * @param {String} n * @return {RGBA} new node * @api public */ RGBA.prototype.divide = function(n){ return new RGBA( this.r / n , this.g / n , this.b / n , this.a); }; /** * Operate on `right` with the given `op`. * * @param {String} op * @param {Node} right * @return {Node} * @api public */ RGBA.prototype.operate = function(op, right){ if ('in' != op) right = right.first switch (op) { case 'is a': if ('string' == right.nodeName && 'color' == right.string) { return nodes.true; } break; case '+': switch (right.nodeName) { case 'unit': var n = right.val; switch (right.type) { case '%': return adjust(this, new nodes.String('lightness'), right); case 'deg': return this.hsla.adjustHue(n).rgba; default: return this.add(n,n,n,0); } case 'rgba': return this.add(right.r, right.g, right.b, right.a); case 'hsla': return this.hsla.add(right.h, right.s, right.l); } break; case '-': switch (right.nodeName) { case 'unit': var n = right.val; switch (right.type) { case '%': return adjust(this, new nodes.String('lightness'), new nodes.Unit(-n, '%')); case 'deg': return this.hsla.adjustHue(-n).rgba; default: return this.sub(n,n,n,0); } case 'rgba': return this.sub(right.r, right.g, right.b, right.a); case 'hsla': return this.hsla.sub(right.h, right.s, right.l); } break; case '*': switch (right.nodeName) { case 'unit': return this.multiply(right.val); } break; case '/': switch (right.nodeName) { case 'unit': return this.divide(right.val); } break; } return Node.prototype.operate.call(this, op, right); }; /** * Return #nnnnnn, #nnn, or rgba(n,n,n,n) string representation of the color. * * @return {String} * @api public */ RGBA.prototype.toString = function(){ function pad(n) { return n < 16 ? '0' + n.toString(16) : n.toString(16); } if (1 == this.a) { var r = pad(this.r) , g = pad(this.g) , b = pad(this.b); // Compress if (r[0] == r[1] && g[0] == g[1] && b[0] == b[1]) { return '#' + r[0] + g[0] + b[0]; } else { return '#' + r + g + b; } } else { return 'rgba(' + this.r + ',' + this.g + ',' + this.b + ',' + (+this.a.toFixed(3)) + ')'; } }; /** * Return a `RGBA` from the given `hsla`. * * @param {HSLA} hsla * @return {RGBA} * @api public */ exports.fromHSLA = function(hsla){ var h = hsla.h / 360 , s = hsla.s / 100 , l = hsla.l / 100 , a = hsla.a; var m2 = l <= .5 ? l * (s + 1) : l + s - l * s , m1 = l * 2 - m2; var r = hue(h + 1/3) * 0xff , g = hue(h) * 0xff , b = hue(h - 1/3) * 0xff; function hue(h) { if (h < 0) ++h; if (h > 1) --h; if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; if (h * 2 < 1) return m2; if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6; return m1; } return new RGBA(r,g,b,a); }; /** * Clamp `n` >= 0 and <= 255. * * @param {Number} n * @return {Number} * @api private */ function clamp(n) { return Math.max(0, Math.min(n.toFixed(0), 255)); } /** * Clamp alpha `n` >= 0 and <= 1. * * @param {Number} n * @return {Number} * @api private */ function clampAlpha(n) { return Math.max(0, Math.min(n, 1)); }
var express = require('express'); var path = require('path'); var httpProxy = require('http-proxy'); //创建express实例 var app = express(); app.use(express.static(path.resolve('.'))); //index page app.get('/', function(req, res) { res.redirect('./demos.html'); }); app.listen(process.env.PORT || 3330); console.log('服务器已启动,http://localhost:' + (process.env.PORT || 3330));
'use strict'; const should = require('chai').should(); // eslint-disable-line const Hexo = require('hexo'); describe('Index generator', () => { const hexo = new Hexo(__dirname, {silent: true}); const Post = hexo.model('Post'); const generator = require('../lib/generator').bind(hexo); let posts, locals; // Default config hexo.config.index_generator = { per_page: 10, order_by: '-date' }; before(() => hexo.init().then(() => Post.insert([ {source: 'foo', slug: 'foo', date: 1e8, order: 0}, {source: 'bar', slug: 'bar', date: 1e8 + 1, order: 10}, {source: 'baz', slug: 'baz', date: 1e8 - 1, order: 1} ])).then(data => { posts = Post.sort('-date'); locals = hexo.locals.toObject(); })); it('pagination enabled', () => { hexo.config.index_generator.per_page = 2; const result = generator(locals); result.length.should.eql(2); for (let i = 0, len = result.length; i < len; i++) { result[i].layout.should.eql(['index', 'archive']); result[i].data.current.should.eql(i + 1); result[i].data.base.should.eql(''); result[i].data.total.should.eql(2); } result[0].path.should.eql(''); result[0].data.current_url.should.eql(''); result[0].data.posts.should.eql(posts.limit(2)); result[0].data.prev.should.eql(0); result[0].data.prev_link.should.eql(''); result[0].data.next.should.eql(2); result[0].data.next_link.should.eql('page/2/'); result[0].data.__index.should.be.true; result[1].path.should.eql('page/2/'); result[1].data.current_url.should.eql('page/2/'); result[1].data.posts.should.eql(posts.skip(2)); result[1].data.prev.should.eql(1); result[1].data.prev_link.should.eql(''); result[1].data.next.should.eql(0); result[1].data.next_link.should.eql(''); result[1].data.__index.should.be.true; // Restore config hexo.config.index_generator.per_page = 10; }); it('pagination disabled', () => { hexo.config.index_generator.per_page = 0; const result = generator(locals); result.length.should.eql(1); result[0].path.should.eql(''); result[0].layout.should.eql(['index', 'archive']); result[0].data.base.should.eql(''); result[0].data.total.should.eql(1); result[0].data.current.should.eql(1); result[0].data.current_url.should.eql(''); result[0].data.posts.should.eql(posts); result[0].data.prev.should.eql(0); result[0].data.prev_link.should.eql(''); result[0].data.next.should.eql(0); result[0].data.next_link.should.eql(''); result[0].data.__index.should.be.true; // Restore config hexo.config.index_generator.per_page = 10; }); describe('order', () => { it('default order', () => { const result = generator(locals); result[0].data.posts.should.eql(posts); }); it('custom order', () => { hexo.config.index_generator.order_by = '-order'; let result = generator(locals); result[0].data.posts.eq(0).source.should.eql('bar'); result[0].data.posts.eq(1).source.should.eql('baz'); result[0].data.posts.eq(2).source.should.eql('foo'); hexo.config.index_generator.order_by = 'order'; result = generator(locals); result[0].data.posts.eq(0).source.should.eql('foo'); result[0].data.posts.eq(1).source.should.eql('baz'); result[0].data.posts.eq(2).source.should.eql('bar'); // Restore config delete hexo.config.index_generator.order_by; }); it('custom order - invalid order key', () => { hexo.config.index_generator.order_by = '-something'; const result = generator(locals); result[0].data.posts.eq(0).source.should.eql('foo'); result[0].data.posts.eq(1).source.should.eql('bar'); result[0].data.posts.eq(2).source.should.eql('baz'); // Restore config delete hexo.config.index_generator.order_by; }); }); it('custom pagination_dir', () => { hexo.config.index_generator.per_page = 1; hexo.config.pagination_dir = 'yo'; const result = generator(locals); result[0].path.should.eql(''); result[1].path.should.eql('yo/2/'); result[2].path.should.eql('yo/3/'); // Restore config hexo.config.index_generator.per_page = 10; hexo.config.pagination_dir = 'page'; }); });
import cache from 'memory-cache'; import debug from 'debug'; const error = debug('memory-cache-proxy:error'); const info = debug('memory-cache-proxy:info'); export default async (func, cacheOptions, args) => { info(`${func.name} Cache Proxy`); // 检查cacheOptions是否正确 if (!cacheOptions || !cacheOptions.key || !cacheOptions.expire) { error('cacheOptions must be provided.'); throw new Error('cacheOptions must be provided.'); } // 检查args参数是否是数组 if (!Array.isArray(args)) { error('parameter args must be a array'); throw new Error('parameter args must be a array'); } try { let data = cache.get(cacheOptions.key); // 缓存中没有数据,从func获取 if (!data) { info(`${func.name} get data from cache failed. cacheKey:`, cacheOptions.key); data = await func(...args); cache.put(cacheOptions.key, data, cacheOptions.expire); info('putted data to cache. cacheOptions=', cacheOptions); } else { info('retrived data from cache. cacheKey=', cacheOptions.key); } return data; } catch (e) { error(e.message); error(e.stack); throw e; } };
import Ember from 'ember'; export default Ember.Route.extend({ model(params) { return this.store.find('post', params['post_id']); } });
// connect.rdns_access plugin exports.register = function() { var i; var config = this.config.get('connect.rdns_access.ini'); this.wl = this.config.get('connect.rdns_access.whitelist', 'list'); this.bl = this.config.get('connect.rdns_access.blacklist', 'list'); this.deny_msg = config.general && (config.general['deny_msg'] || 'Connection rejected.'); var white_regex = this.config.get('connect.rdns_access.whitelist_regex', 'list'); var black_regex = this.config.get('connect.rdns_access.blacklist_regex', 'list'); if (white_regex.length) { this.wlregex = new RegExp('^(?:' + white_regex.join('|') + ')$', 'i'); } if (black_regex.length) { this.blregex = new RegExp('^(?:' + black_regex.join('|') + ')$', 'i'); } this.register_hook('connect', 'rdns_access'); } exports.rdns_access = function(next, connection) { var plugin = this; // IP whitelist checks if (connection.remote_ip) { plugin.logdebug('checking ' + connection.remote_ip + ' against connect.rdns_access.whitelist'); if (_in_whitelist(plugin, connection.remote_ip)) { plugin.logdebug("Allowing " + connection.remote_ip); return next(); } } // hostname whitelist checks if (connection.remote_host) { plugin.logdebug('checking ' + connection.remote_host + ' against connect.rdns_access.whitelist'); if (_in_whitelist(plugin, connection.remote_host.toLowerCase())) { plugin.logdebug("Allowing " + connection.remote_host); return next(); } } // IP blacklist checks if (connection.remote_ip) { plugin.logdebug('checking ' + connection.remote_ip + ' against connect.rdns_access.blacklist'); if (_in_blacklist(plugin, connection.remote_ip)) { plugin.logdebug("Rejecting, matched: " + connection.remote_ip); return next(DENY, connection.remote_host.toLowerCase() + ' [' + connection.remote_ip + '] ' + plugin.deny_msg); } } // hostname blacklist checks if (connection.remote_host) { plugin.logdebug('checking ' + connection.remote_host + ' against connect.rdns_access.blacklist'); if (_in_blacklist(plugin, connection.remote_host.toLowerCase())) { plugin.logdebug("Rejecting, matched: " + connection.remote_host); return next(DENY, connection.remote_host.toLowerCase() + ' [' + connection.remote_ip + '] ' + plugin.deny_msg); } } return next(); } function _in_whitelist(plugin, host) { var i; for (i in plugin.wl) { plugin.logdebug('checking ' + host + ' against ' + plugin.wl[i]); if (plugin.wl[i].toLowerCase() === host) { return 1; } } if (plugin.wlregex) { plugin.logdebug('checking ' + host + ' against ' + plugin.wlregex.source); if (host.match(plugin.wlregex)) { return 1; } } return 0; } function _in_blacklist(plugin, host) { var i; for (i in plugin.bl) { plugin.logdebug('checking ' + host + ' against ' + plugin.bl[i]); if (plugin.bl[i].toLowerCase() === host) { return 1; } } if (plugin.blregex) { plugin.logdebug('checking ' + host + ' against ' + plugin.blregex.source); if (host.match(plugin.blregex)) { return 1; } } return 0; }
var width = 100, height = 100, radius = Math.min(width, height) / 2; var vals = d3.select("body").selectAll("td"); var values = []; for( var i = 0; i < vals[0].length; i+=2 ) { d = { value: parseInt(vals[0][i].innerText), color: vals[0][i+1].innerText }; values.push(d); } var arc = d3.svg.arc() .outerRadius(radius - 10) .innerRadius(radius - 30); var pie = d3.layout.pie() .sort(null) .value(function(d) { return d.value; }); var root = d3.select("#chart") .append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")") var g = root.selectAll(".arc") .data(pie(values)) .enter().append("g") .attr("class", "arc"); g.append("path") .attr("d", arc) .attr("class", function(d) { return d.data.color; });
var searchData= [ ['libversion',['libVersion',['../class_d_s___config.html#a97f429aeadc08838cc61ac87606cc09f',1,'DS_Config']]], ['libversionchanged',['libVersionChanged',['../class_d_s___base.html#a97874971cbbc6970bd3a76d3166617cb',1,'DS_Base']]], ['logdocument',['logDocument',['../class_driver_station.html#acedd717f2eb38fb95ffa835f8aa376ce',1,'DriverStation']]], ['logger',['Logger',['../class_logger.html',1,'Logger'],['../class_d_s___config.html#ac058fd98e1cf514dd47b1b08a7401a4f',1,'DS_Config::logger()'],['../class_driver_station.html#ace6de99545caa8c38aaa3303c9b490b5',1,'DriverStation::logger()']]], ['logspath',['logsPath',['../class_logger.html#a3798367a4d16fe35669b45adc368a71c',1,'Logger::logsPath()'],['../class_driver_station.html#a37d6ffc0c15706c329213c05ed01f97f',1,'DriverStation::logsPath()']]], ['logvariant',['logVariant',['../class_driver_station.html#a0e835c3fdce9c14138553d1fc6cc2e35',1,'DriverStation']]], ['lookup',['Lookup',['../class_lookup.html',1,'Lookup'],['../class_lookup.html#af67ea2ada6f6d15c1d1f4b7d8ca62d5b',1,'Lookup::lookup()']]] ];
//定义异步请求对象 var httpRequest=false; //创建异步请求对象 function createXMLHttp(){ //判断为ie浏览器 if(window.ActiveXObject){ try{ httpRequest=new ActiveXObject("msxml2.XMLHTTP"); }catch(e1){ try{ httpRequest=new ActiveXObject("Microsoft.XMLHTTP"); }catch(e2){ httpRequest=false; alert("在ie浏览器中创建异步请求对象失败!"); } } //判断为非ie浏览器 }else if(window.XMLHTTPRequest){ try{ httpRequest=new XMLHTTPRequest(); }catch(e3){ httpRequest=false; alert("在非ie浏览器中创建异步请求对象失败!"); } } } //准备并向服务器发送异步请求(请求路径:url,请求方式:get:null,post:提交数据;回调方法名称:method) function doCommandAjax(url,postData,mothed){ //创建异步请求对象 createXMLHttp(); if(!postData){ //get方式提交 httpRequest.open("get",url,true); }else{ //post方式提交 httpRequest.open("post",url,true); } //注册事件 httpRequest.onreadystatechange=callBack(httpRequest,mothed); //不管是get还是post请求都要设置请求头 httpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //发送请求 httpRequest.send(postData); } //回调的启动方法 function callBack(httpRequest,mothed){ return function(){ //表示请求服务器完成 try{ if(httpRequest.readyState==4){ //alert(httpRequest.status); if(httpRequest.status==200){ eval(mothed+"();"); } } }catch(e4){ //alert("请求失败"); } } } //获取post提交数据 function getData(element){ //encodeURIComponet()对表单数据进行编码 //有多个元素的时候 //alert("是否为数字:"+isNaN(element.length)); if(!isNaN(element.length)&&element.length>1){ for(var i=0;i<element.length;i++){ //alert("是否选择:"+element[i].checked); if(element[i].checked){ getData(element[i]); //break; } } } if(isNaN(element.length)){ var sug=encodeURIComponent(element.name); sug+="="; sug+=encodeURIComponent(element.value); sug+="&"; postData+=sug; //alert(postData+" :888"); } }
/*global rootDir*/ const rp = require("request-promise"); const utils = require(rootDir + "/scripts/utils.js"); module.exports = function(api) { api.getStats = function (worldId) { return rp("https://api.guildwars2.com/v2/wvw/matches/stats?world=" + worldId); }; api.getScores = function (worldId) { return rp("https://api.guildwars2.com/v2/wvw/matches/scores?world=" + worldId); }; };