text
stringlengths
2
6.14k
#!/usr/bin/env node require("./bin/npm-cli.js")
var vows = require("vows"), _ = require("../../"), load = require("../load"), assert = require("../assert"); var suite = vows.describe("d3.max"); suite.addBatch({ "max": { topic: load("arrays/max").expression("d3.max"), "returns the greatest numeric value for numbers": function(max) { assert.equal(max([1]), 1); assert.equal(max([5, 1, 2, 3, 4]), 5); assert.equal(max([20, 3]), 20); assert.equal(max([3, 20]), 20); }, "returns the greatest lexicographic value for strings": function(max) { assert.equal(max(["c", "a", "b"]), "c"); assert.equal(max(["20", "3"]), "3"); assert.equal(max(["3", "20"]), "3"); }, "ignores null, undefined and NaN": function(max) { var o = {valueOf: function() { return NaN; }}; assert.equal(max([NaN, 1, 2, 3, 4, 5]), 5); assert.equal(max([o, 1, 2, 3, 4, 5]), 5); assert.equal(max([1, 2, 3, 4, 5, NaN]), 5); assert.equal(max([1, 2, 3, 4, 5, o]), 5); assert.equal(max([10, null, 3, undefined, 5, NaN]), 10); assert.equal(max([-1, null, -3, undefined, -5, NaN]), -1); }, "compares heterogenous types as numbers": function(max) { assert.strictEqual(max([20, "3"]), 20); assert.strictEqual(max(["20", 3]), "20"); assert.strictEqual(max([3, "20"]), "20"); assert.strictEqual(max(["3", 20]), 20); }, "returns undefined for empty array": function(max) { assert.isUndefined(max([])); assert.isUndefined(max([null])); assert.isUndefined(max([undefined])); assert.isUndefined(max([NaN])); assert.isUndefined(max([NaN, NaN])); }, "applies the optional accessor function": function(max) { assert.equal(max([[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]], function(d) { return _.min(d); }), 2); assert.equal(max([1, 2, 3, 4, 5], function(d, i) { return i; }), 4); } } }); suite.export(module);
var name; switch (name) { case "Kamol": doSomething(); default: doSomethingElse(); } switch (name) { default: doSomethingElse(); break; case "Kamol": doSomething(); }
(function() { "use strict"; var WORD = /[\w$]+/, RANGE = 500; CodeMirror.registerHelper("hint", "anyword", function(editor, options) { var word = options && options.word || WORD; var range = options && options.range || RANGE; var cur = editor.getCursor(), curLine = editor.getLine(cur.line); var start = cur.ch, end = start; while (end < curLine.length && word.test(curLine.charAt(end))) ++end; while (start && word.test(curLine.charAt(start - 1))) --start; var curWord = start != end && curLine.slice(start, end); var list = [], seen = {}; var re = new RegExp(word.source, "g"); for (var dir = -1; dir <= 1; dir += 2) { var line = cur.line, end = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir; for (; line != end; line += dir) { var text = editor.getLine(line), m; while (m = re.exec(text)) { if (line == cur.line && m[0] === curWord) continue; if ((!curWord || m[0].lastIndexOf(curWord, 0) == 0) && !Object.prototype.hasOwnProperty.call(seen, m[0])) { seen[m[0]] = true; list.push(m[0]); } } } } return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)}; }); })();
//! moment.js locale configuration //! locale : Chinese (Hong Kong) [zh-hk] //! author : Ben : https://github.com/ben-lin //! author : Chris Lam : https://github.com/hehachris //! author : Konstantin : https://github.com/skfd ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.moment) }(this, (function (moment) { 'use strict'; var zhHk = moment.defineLocale('zh-hk', { months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), weekdaysShort : '週日_週一_週二_週三_週四_週五_週六'.split('_'), weekdaysMin : '日_一_二_三_四_五_六'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'YYYY年MMMD日', LL : 'YYYY年MMMD日', LLL : 'YYYY年MMMD日 HH:mm', LLLL : 'YYYY年MMMD日dddd HH:mm', l : 'YYYY年MMMD日', ll : 'YYYY年MMMD日', lll : 'YYYY年MMMD日 HH:mm', llll : 'YYYY年MMMD日dddd HH:mm' }, meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { return hour; } else if (meridiem === '中午') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === '下午' || meridiem === '晚上') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 600) { return '凌晨'; } else if (hm < 900) { return '早上'; } else if (hm < 1130) { return '上午'; } else if (hm < 1230) { return '中午'; } else if (hm < 1800) { return '下午'; } else { return '晚上'; } }, calendar : { sameDay : '[今天]LT', nextDay : '[明天]LT', nextWeek : '[下]ddddLT', lastDay : '[昨天]LT', lastWeek : '[上]ddddLT', sameElse : 'L' }, dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/, ordinal : function (number, period) { switch (period) { case 'd' : case 'D' : case 'DDD' : return number + '日'; case 'M' : return number + '月'; case 'w' : case 'W' : return number + '週'; default : return number; } }, relativeTime : { future : '%s內', past : '%s前', s : '幾秒', m : '1 分鐘', mm : '%d 分鐘', h : '1 小時', hh : '%d 小時', d : '1 天', dd : '%d 天', M : '1 個月', MM : '%d 個月', y : '1 年', yy : '%d 年' } }); return zhHk; })));
var assert = require('assert'); var cookie = require('..'); suite('parse'); test('basic', function() { assert.deepEqual({ foo: 'bar' }, cookie.parse('foo=bar')); assert.deepEqual({ foo: '123' }, cookie.parse('foo=123')); }); test('ignore spaces', function() { assert.deepEqual({ FOO: 'bar', baz: 'raz' }, cookie.parse('FOO = bar; baz = raz')); }); test('escaping', function() { assert.deepEqual({ foo: 'bar=123456789&name=Magic+Mouse' }, cookie.parse('foo="bar=123456789&name=Magic+Mouse"')); assert.deepEqual({ email: ' ",;/' }, cookie.parse('email=%20%22%2c%3b%2f')); }); test('ignore escaping error and return original value', function() { assert.deepEqual({ foo: '%1', bar: 'bar' }, cookie.parse('foo=%1;bar=bar')); });
var gulp = require('gulp'); var paths = require('../paths'); var del = require('del'); var vinylPaths = require('vinyl-paths'); // deletes all files in the output path gulp.task('clean', function() { return gulp.src([paths.output]) .pipe(vinylPaths(del)); });
var test = require('tap').test var server = require('./lib/server.js') var common = require('./lib/common.js') var client = common.freshClient() function nop () {} var URI = 'http://localhost:1337/rewrite' var TOKEN = 'b00b00feed' var PARAMS = { auth: { token: TOKEN } } test('logout call contract', function (t) { t.throws(function () { client.logout(undefined, PARAMS, nop) }, 'requires a URI') t.throws(function () { client.logout([], PARAMS, nop) }, 'requires URI to be a string') t.throws(function () { client.logout(URI, undefined, nop) }, 'requires params object') t.throws(function () { client.logout(URI, '', nop) }, 'params must be object') t.throws(function () { client.logout(URI, PARAMS, undefined) }, 'requires callback') t.throws(function () { client.logout(URI, PARAMS, 'callback') }, 'callback must be function') t.throws( function () { var params = { auth: {} } client.logout(URI, params, nop) }, { name: 'AssertionError', message: 'can only log out for token auth' }, 'auth must include token' ) t.end() }) test('log out from a token-based registry', function (t) { server.expect('DELETE', '/-/user/token/' + TOKEN, function (req, res) { t.equal(req.method, 'DELETE') t.equal(req.headers.authorization, 'Bearer ' + TOKEN, 'request is authed') res.json({message: 'ok'}) }) client.logout(URI, PARAMS, function (er) { t.ifError(er, 'no errors') t.end() }) }) test('cleanup', function (t) { server.close() t.end() })
/* Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ //>>built define("dojo/store/JsonRest",["../_base/xhr","../_base/lang","../json","../_base/declare","./util/QueryResults"],function(_1,_2,_3,_4,_5){ var _6=null; return _4("dojo.store.JsonRest",_6,{constructor:function(_7){ this.headers={}; _4.safeMixin(this,_7); },headers:{},target:"",idProperty:"id",ascendingPrefix:"+",descendingPrefix:"-",_getTarget:function(id){ var _8=this.target; if(typeof id!="undefined"){ if(_8.charAt(_8.length-1)=="/"){ _8+=id; }else{ _8+="/"+id; } } return _8; },get:function(id,_9){ _9=_9||{}; var _a=_2.mixin({Accept:this.accepts},this.headers,_9.headers||_9); return _1("GET",{url:this._getTarget(id),handleAs:"json",headers:_a}); },accepts:"application/javascript, application/json",getIdentity:function(_b){ return _b[this.idProperty]; },put:function(_c,_d){ _d=_d||{}; var id=("id" in _d)?_d.id:this.getIdentity(_c); var _e=typeof id!="undefined"; return _1(_e&&!_d.incremental?"PUT":"POST",{url:this._getTarget(id),postData:_3.stringify(_c),handleAs:"json",headers:_2.mixin({"Content-Type":"application/json",Accept:this.accepts,"If-Match":_d.overwrite===true?"*":null,"If-None-Match":_d.overwrite===false?"*":null},this.headers,_d.headers)}); },add:function(_f,_10){ _10=_10||{}; _10.overwrite=false; return this.put(_f,_10); },remove:function(id,_11){ _11=_11||{}; return _1("DELETE",{url:this._getTarget(id),headers:_2.mixin({},this.headers,_11.headers)}); },query:function(_12,_13){ _13=_13||{}; var _14=_2.mixin({Accept:this.accepts},this.headers,_13.headers); var _15=this.target.indexOf("?")>-1; if(_12&&typeof _12=="object"){ _12=_1.objectToQuery(_12); _12=_12?(_15?"&":"?")+_12:""; } if(_13.start>=0||_13.count>=0){ _14["X-Range"]="items="+(_13.start||"0")+"-"+(("count" in _13&&_13.count!=Infinity)?(_13.count+(_13.start||0)-1):""); if(this.rangeParam){ _12+=(_12||_15?"&":"?")+this.rangeParam+"="+_14["X-Range"]; _15=true; }else{ _14.Range=_14["X-Range"]; } } if(_13&&_13.sort){ var _16=this.sortParam; _12+=(_12||_15?"&":"?")+(_16?_16+"=":"sort("); for(var i=0;i<_13.sort.length;i++){ var _17=_13.sort[i]; _12+=(i>0?",":"")+(_17.descending?this.descendingPrefix:this.ascendingPrefix)+encodeURIComponent(_17.attribute); } if(!_16){ _12+=")"; } } var _18=_1("GET",{url:this.target+(_12||""),handleAs:"json",headers:_14}); _18.total=_18.then(function(){ var _19=_18.ioArgs.xhr.getResponseHeader("Content-Range"); if(!_19){ _19=_18.ioArgs.xhr.getResponseHeader("X-Content-Range"); } return _19&&(_19=_19.match(/\/(.*)/))&&+_19[1]; }); return _5(_18); }}); });
var cx = require('classnames'); var blacklist = require('blacklist'); var React = require('react'); module.exports = React.createClass({ displayName: 'Field', getDefaultProps() { return { d: null, t: null, m: null, label: '' } }, renderError() { if(!this.props.error) return null; return <span className="error">{this.props.error}</span>; }, renderLabel() { var cn = cx('label', this.props.d ? `g-${this.props.d}` : null); if(!this.props.label) { return ( <label className={cn}>&nbsp;</label> ); } return ( <label className={cn}> {this.props.label} </label> ); }, render() { var props = blacklist(this.props, 'label', 'error', 'children', 'd', 't', 'm'); props.className = cx('u-field', { 'g-row': this.props.d, 'u-field-row': this.props.d, 'u-field-err': this.props.error }); return ( <div {... props}> {this.renderLabel()} {this.props.d ? ( <div className={`g-${24 - this.props.d}`}> {this.props.children} </div> ) : this.props.children} {this.renderError()} </div> ); } });
/* @flow */ import { PropTypes } from 'react' export default PropTypes.oneOfType([ // [Number, Number] PropTypes.arrayOf(PropTypes.number), // {lat: Number, lng: Number} PropTypes.shape({ lat: PropTypes.number, lng: PropTypes.number, }), // {lat: Number, lon: Number} PropTypes.shape({ lat: PropTypes.number, lon: PropTypes.number, }), ])
import { modulo } from './Math.js' export function random(x) { return modulo(Math.sin(x) * 43758.5453123, 1) }
'use strict'; var main = { expand:true, cwd: './build/styles/', src:['*.css'], dest: './build/styles/' }; module.exports = { main:main };
import AddLearningToStoryDescription from '../../../../src/content_scripts/pivotal_tracker/use_cases/add_learning_to_story_description' import WWLTWRepository from '../../../../src/content_scripts/repositories/wwltw_repository'; import StoryTitleProvider from '../../../../src/content_scripts/utilities/story_title_provider'; import ProjectIdProvider from '../../../../src/content_scripts/utilities/project_id_provider'; describe('AddLearningToStoryDescription', function () { let wwltwRepositorySpy; let foundStory; let execute; const projectId = 'some project id'; const storyTitle = 'some story title'; beforeEach(function () { wwltwRepositorySpy = new WWLTWRepository(); foundStory = {id: '1234'}; spyOn(chrome.runtime, 'sendMessage'); spyOn(wwltwRepositorySpy, 'findByTitle').and.returnValue(Promise.resolve([foundStory])); spyOn(wwltwRepositorySpy, 'update').and.returnValue(Promise.resolve()); spyOn(StoryTitleProvider, 'currentStoryTitle').and.returnValue(storyTitle); spyOn(ProjectIdProvider, 'getProjectId').and.returnValue(projectId); const useCase = new AddLearningToStoryDescription(wwltwRepositorySpy); execute = useCase.execute; }); describe('execute', function () { describe('when called outside of AddLearningToStoryDescription instance', function () { it('finds the story', function () { execute('some tag, some other tag', 'some body'); expect(wwltwRepositorySpy.findByTitle).toHaveBeenCalledWith( projectId, storyTitle ); }); it('sends analytics data', function () { execute(); expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ eventType: 'submit' }); }); it('updates the found story', function (done) { const body = 'some body'; const tags = 'some tag, some other tag'; execute(tags, body).then(function () { expect(wwltwRepositorySpy.update).toHaveBeenCalledWith( projectId, foundStory, tags, body ); done(); }); }); }); }); });
"use strict"; var Template = function (options) { this._pageTitle = ''; this._titleSeparator = options.title_separator; this._siteTitle = options.site_title; this._req = null; this._res = null; }; Template.prototype.bindMiddleware = function(req, res) { this._req = req; this._res = res; }; Template.prototype.setPageTitle = function(pageTitle) { this._pageTitle = pageTitle; }; Template.prototype.setSiteTitle = function(siteTitle) { this._siteTitle = siteTitle; }; Template.prototype.setTitleSeparator = function(separator) { this._titleSeparator = separator; }; Template.prototype.getTitle = function() { if (this._pageTitle !== '') { return this._pageTitle + ' ' + this._titleSeparator + ' ' + this._siteTitle; } else { return this._siteTitle; } }; Template.prototype.getPageTitle = function() { return this._pageTitle; }; Template.prototype.getSiteTitle = function() { return this._siteTitle; }; Template.prototype.render = function(path, params) { this._res.render('partials/' + path, params); }; module.exports = Template;
/* eslint-env mocha */ const mockBot = require('../mockBot') const assert = require('assert') const mockery = require('mockery') const sinon = require('sinon') const json = JSON.stringify({ state: 'normal', nowTitle: 'Midnight News', nowInfo: '20/03/2019', nextStart: '2019-03-20T00:30:00Z', nextTitle: 'Book of the Week' }) describe('radio module', function () { let sandbox before(function () { // mockery mocks the entire require() mockery.enable() mockery.registerMock('request-promise', { get: () => Promise.resolve(json) }) // sinon stubs individual functions sandbox = sinon.sandbox.create() mockBot.loadModule('radio') }) it('should parse the API correctly', async function () { sandbox.useFakeTimers({ now: 1553040900000 }) // 2019-03-20T00:15:00Z const promise = await mockBot.runCommand('!r4') assert.strictEqual(promise, 'Now: \u000300Midnight News\u000f \u000315(20/03/2019)\u000f followed by Book of the Week in 15 minutes (12:30 am)') }) after(function (done) { mockery.disable() mockery.deregisterAll() done() }) })
var DND_START_EVENT = 'dnd-start', DND_END_EVENT = 'dnd-end', DND_DRAG_EVENT = 'dnd-drag'; angular .module( 'app' ) .config( [ 'iScrollServiceProvider', function(iScrollServiceProvider){ iScrollServiceProvider.configureDefaults({ iScroll: { momentum: false, mouseWheel: true, disableMouse: false, useTransform: true, scrollbars: true, interactiveScrollbars: true, resizeScrollbars: false, probeType: 2, preventDefault: false // preventDefaultException: { // tagName: /^.*$/ // } }, directive: { asyncRefreshDelay: 0, refreshInterval: false } }); } ] ) .controller( 'main', function( $scope, draggingIndicator, iScrollService ){ 'use strict'; this.iScrollState = iScrollService.state; var DND_SCROLL_IGNORED_HEIGHT = 20, // ignoring 20px touch-scroll, // TODO: this might be stored somewhere in browser env DND_ACTIVATION_TIMEOUT = 500, // milliseconds needed to touch-activate d-n-d MOUSE_OVER_EVENT = 'mousemove'; var self = this, items = [], touchTimerId; $scope.dragging = draggingIndicator; for( var i = 0; i< 25; i++ ){ items.push( i ); } $scope.items = items; this.disable = function ( ){ $scope.iScrollInstance.disable(); }; this.log = function ( msg ){ console.log( 'got msg', msg ); }; } );
'use strict' let _ = require('lodash') let HttpClient = require('./http-client') /** * Server configuration and environment information * @extends {HttpClient} */ class Config extends HttpClient { /** * @constructs Config * @param {Object} options General configuration options * @param {Object} options.http configurations for HttpClient */ constructor (options) { super(options.http) } /** * Return the whole server information * @return {Promise} A promise that resolves to the server information */ server () { return this._httpRequest('GET') .then((response) => response.metadata) } /** * Retrieve the server configuration * @return {Promise} A promise that resolves to the server configuration */ get () { return this.server() .then((server) => server.config) } /** * Unset parameters from server configuration * @param {...String} arguments A list parameters that you want to unset * @return {Promise} A promise that resolves when the config has been unset */ unset () { return this.get() .then((config) => _.omit(config, _.flatten(Array.from(arguments)))) .then((config) => this.update(config)) } /** * Set one or more configurations in the server * @param {Object} data A plain object containing the configuration you want * to insert or update in the server * @return {Pomise} A promise that resolves when the config has been set */ set (data) { return this.get() .then((config) => _.merge(config, data)) .then((config) => this.update(config)) } /** * Replaces the whole server configuration for the one provided * @param {Object} data The new server configuration * @return {Promise} A promise that resolves when the configuration has been * replaces */ update (data) { return this._httpRequest('PUT', { config: data }) } } module.exports = Config
import $ from 'jquery'; import { router } from 'src/router'; import './header.scss'; export default class Header { static selectors = { button: '.header__enter', search: '.header__search' }; constructor($root) { this.elements = { $root, $window: $(window) }; this.attachEvents(); } attachEvents() { this.elements.$root.on('click', Header.selectors.button, this.handleClick) } handleClick = () => { const search = $(Header.selectors.search).val(); if (search) { router.navigate(`/search?query=${search}`); } } }
"use strict"; describe("This package", function(){ it("rubs the lotion on its skin, or else", function(){ 2..should.equal(2); // In this universe, it'd damn well better }); it("gets the hose again", function(){ this.should.be.extensible.and.ok; // Eventually }); it("should not fail", function(){ NaN.should.not.equal(NaN); // NaH global.foo = "Foo"; }); it("might be written later"); // Nah it("should fail", function(){ const A = { alpha: "A", beta: "B", gamma: "E", delta: "D", }; const B = { Alpha: "A", beta: "B", gamma: "E", delta: "d", }; A.should.equal(B); }); describe("Suite nesting", function(){ it("does something useful eventually", function(done){ setTimeout(() => done(), 40); }); it("cleans anonymous async functions", async function(){ if(true){ true.should.be.true; } }); it("cleans anonymous generators", function * (){ if(true){ true.should.be.true; } }); it("cleans named async functions", async function foo() { if(true){ true.should.be.true; } }); it("cleans named generators", function * foo (){ if(true){ true.should.be.true; } }); it("cleans async arrow functions", async () => { if(true){ true.should.be.true; } }); }); }); describe("Second suite at top-level", function(){ it("shows another block", function(){ Chai.expect(Date).to.be.an.instanceOf(Function); }); it("breaks something", function(){ something(); }); it("loads locally-required files", () => { expect(global.someGlobalThing).to.equal("fooXYZ"); }); unlessOnWindows.it("enjoys real symbolic links", () => { "Any Unix-like system".should.be.ok; }); }); describe("Aborted tests", () => { before(() => {throw new Error("Nah, not really")}); it("won't reach this", () => true.should.not.be.false); it.skip("won't reach this either", () => true.should.be.true); });
'use strict'; var yeoman = require('yeoman-generator'), chalk = require('chalk'), yosay = require('yosay'), bakery = require('../../lib/bakery'), feedback = require('../../lib/feedback'), debug = require('debug')('bakery:generators:cm-bash:index'), glob = require('glob'), path = require('path'), _ = require('lodash'); // placeholder for CM implementaiton delivering a BASH-based project. var BakeryCM = yeoman.Base.extend({ constructor: function () { yeoman.Base.apply(this, arguments); this._options.help.desc = 'Show this help'; this.argument('projectname', { type: String, required: this.config.get('projectname') == undefined }); }, // generators are invalid without at least one method to run during lifecycle default: function () { /* TAKE NOTE: these next two lines are fallout of having to include ALL sub-generators in .composeWith(...) at the top level. Essentially ALL SUBGENERATORS RUN ALL THE TIME. So we have to escape from generators we don't want running within EVERY lifecycle method. (ugh) */ let cmInfo = this.config.get('cm'); if (cmInfo.generatorName != 'cm-bash') { return; } } }); module.exports = BakeryCM;
/*\ |*| |*| :: cookies.js :: |*| |*| A complete cookies reader/writer framework with full unicode support. |*| |*| Revision #1 - September 4, 2014 |*| |*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie |*| https://developer.mozilla.org/User:fusionchess |*| |*| This framework is released under the GNU Public License, version 3 or later. |*| http://www.gnu.org/licenses/gpl-3.0-standalone.html |*| |*| Syntaxes: |*| |*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]]) |*| * docCookies.getItem(name) |*| * docCookies.removeItem(name[, path[, domain]]) |*| * docCookies.hasItem(name) |*| * docCookies.keys() |*| \*/ export default { getItem: function (sKey) { if (!sKey) { return null; } return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null; }, setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) { if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; } var sExpires = ""; if (vEnd) { switch (vEnd.constructor) { case Number: sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd; break; case String: sExpires = "; expires=" + vEnd; break; case Date: sExpires = "; expires=" + vEnd.toUTCString(); break; } } document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : ""); return true; }, removeItem: function (sKey, sPath, sDomain) { if (!this.hasItem(sKey)) { return false; } document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : ""); return true; }, hasItem: function (sKey) { if (!sKey) { return false; } return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }, keys: function () { var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/); for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); } return aKeys; } };
'use strict'; // Proxy URL (optional) const proxyUrl = 'drupal.dev'; // API keys const TINYPNG_KEY = ''; // fonts const fontList = []; // vendors const jsVendorList = []; const cssVendorList = []; // paths to relevant directories const dirs = { src: './src', dest: './dist' }; // paths to file sources const sources = { js: `${dirs.src}/**/*.js`, scss: `${dirs.src}/**/*.scss`, coreScss: `${dirs.src}/scss/main.scss`, img: `./img/**/*.{png,jpg}`, font: fontList, jsVendor: jsVendorList, cssVendor: cssVendorList }; // paths to file destinations const dests = { js: `${dirs.dest}/js`, css: `${dirs.dest}/css`, img: `${dirs.dest}/img`, sigFile: `./img/.tinypng-sigs`, font: `${dirs.dest}/fonts`, vendor: `${dirs.dest}/vendors` }; // plugins import gulp from 'gulp'; import browserSync from 'browser-sync'; import gulpLoadPlugins from 'gulp-load-plugins'; // auto-load plugins const $ = gulpLoadPlugins(); /**************************************** Gulp Tasks *****************************************/ // launch browser sync as a standalone local server gulp.task('browser-sync-local', browserSyncLocal()); // browser-sync task for starting the server by proxying a local url gulp.task('browser-sync-proxy', browserSyncProxy()); // copy vendor CSS gulp.task('css-vendors', cssVendors()); // copy fonts gulp.task('fonts', fonts()); // Lint Javascript Task gulp.task('js-lint', javascriptLint()); // Concatenate and Minify Vendor JS gulp.task('js-vendors', javascriptVendors()); // lint sass task gulp.task('sass-lint', sassLint()); // Concatenate & Minify JS gulp.task('scripts', ['js-lint'], scripts()); // compile, prefix, and minify the sass gulp.task('styles', styles()); // compress and combine svg icons gulp.task('svg', svg()); // Unit testing gulp.task('test', test()); // compress png and jpg images via tinypng API gulp.task('tinypng', tinypng()); // Watch Files For Changes gulp.task('watch', watch()); // default task builds src, opens up a standalone server, and watches for changes gulp.task('default', [ 'fonts', 'styles', 'scripts', 'browser-sync-local', 'watch' ]); // local task builds src, opens up a standalone server, and watches for changes gulp.task('local', [ 'fonts', 'styles', 'scripts', 'browser-sync-local', 'watch' ]); // proxy task builds src, opens up a proxy server, and watches for changes gulp.task('proxy', [ 'fonts', 'styles', 'scripts', 'browser-sync-proxy', 'watch' ]); // builds everything gulp.task('build', [ 'fonts', 'styles', 'scripts', 'css-vendors', 'js-vendors' ]); // builds the vendor files gulp.task('vendors', [ 'css-vendors', 'js-vendors' ]); // compresses imagery gulp.task('images', [ 'svg', 'tinypng' ]); /**************************************** Task Logic *****************************************/ function browserSyncLocal () { return () => { browserSync.init({ server: '../../../../' }); }; } function browserSyncProxy () { return () => { browserSync.init({ proxy: proxyUrl }); }; } function cssVendors () { return () => { return gulp.src(sources.cssVendor) .pipe(gulp.dest(dests.vendor)); }; } function fonts () { return () => { gulp.src(sources.font) .pipe(gulp.dest(dests.font)); }; } function javascriptLint () { return () => { return gulp.src(sources.js) .pipe($.jshint({esversion: 6})) .pipe($.jshint.reporter('jshint-stylish')); }; } function javascriptVendors () { return () => { return gulp.src(sources.jsVendor) .pipe($.plumber()) .pipe($.concat('vendors.min.js')) .pipe($.uglify()) .pipe(gulp.dest(dests.vendor)); }; } function sassLint () { return () => { return gulp.src(sources.scss) .pipe($.sassLint()) .pipe($.sassLint.format()) .pipe($.sassLint.failOnError()); }; } function scripts () { return () => { return gulp.src(sources.js) .pipe($.plumber()) .pipe($.sourcemaps.init()) .pipe($.concat('main.js')) .pipe($.babel()) .pipe(gulp.dest(dests.js)) .pipe($.rename({suffix: '.min'})) .pipe($.uglify()) .pipe($.sourcemaps.write('.')) .pipe(gulp.dest(dests.js)) .pipe(browserSync.stream()); }; } function styles () { return () => { return gulp.src(sources.coreScss) .pipe($.sourcemaps.init()) .pipe($.sass().on('error', $.sass.logError)) .pipe($.autoprefixer(["> 1%", "last 2 versions"], { cascade: true })) .pipe(gulp.dest(dests.css)) .pipe($.rename({suffix: '.min'})) .pipe($.cleanCss()) .pipe($.sourcemaps.write('.')) .pipe(gulp.dest(dests.css)) .pipe(browserSync.stream()); }; } function svg () { return () => { return gulp.src('./img/icons/*.svg') .pipe($.svgmin()) .pipe($.svgstore()) .pipe(gulp.dest('./img/icons')); }; } function test (done) { return () => { let server = new karma.Server('./karma.conf.js', done); server.start(); }; } function tinypng () { return () => { return gulp.src(sources.img) .pipe($.tinypngCompress({ key: TINYPNG_KEY, sigFile: dests.sigFile })) .pipe(gulp.dest(dests.img)); }; } function watch () { return () => { gulp.watch(sources.js, ['scripts']); gulp.watch(sources.scss, ['styles']); gulp.watch('**/*.php', browserSync.reload); }; }
// get the languange parameter in the URL (i for case insensitive; //exec for test for a match in a string and return thr first match) function getURLParameter(key) { var result = new RegExp(key + '=([^&]*)', 'i').exec(window.location.search); return result && result[1] || ''; } // function toggleLang(lang) { var lang = lang || 'de'; document.location = document.location.pathname + '?lang=' + lang; } // set UR var lang = getURLParameter('lang') || 'de'; $('#lang').ready(function() { $('#lang li').each(function() { var li = $(this)[0]; if (li.id == lang) $(this).addClass('selected'); }); });
'use strict'; var _get = require('babel-runtime/helpers/get')['default']; var _inherits = require('babel-runtime/helpers/inherits')['default']; var _createClass = require('babel-runtime/helpers/create-class')['default']; var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default']; var _extends = require('babel-runtime/helpers/extends')['default']; var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default']; Object.defineProperty(exports, '__esModule', { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _EnhancedSwitch = require('./EnhancedSwitch'); var _EnhancedSwitch2 = _interopRequireDefault(_EnhancedSwitch); var Radio = (function (_React$Component) { _inherits(Radio, _React$Component); function Radio() { _classCallCheck(this, Radio); _get(Object.getPrototypeOf(Radio.prototype), 'constructor', this).apply(this, arguments); } _createClass(Radio, [{ key: 'getValue', value: function getValue() { return this.refs.enhancedSwitch.getValue(); } }, { key: 'setChecked', value: function setChecked(newCheckedValue) { this.refs.enhancedSwitch.setSwitched(newCheckedValue); } }, { key: 'isChecked', value: function isChecked() { return this.refs.enhancedSwitch.isSwitched(); } }, { key: 'render', value: function render() { var enhancedSwitchProps = { ref: 'enhancedSwitch', inputType: 'radio' }; // labelClassName return _react2['default'].createElement(_EnhancedSwitch2['default'], _extends({}, this.props, enhancedSwitchProps)); } }]); return Radio; })(_react2['default'].Component); exports['default'] = Radio; module.exports = exports['default'];
class Foo { [prop1]: string; }
(function () { "use strict"; angular.module('projectManagerSPA').controller('userLoginController', ['authenticationService', '$scope', '$state',function (authenticationService, $scope, $state) { $scope.logIn = function () { authenticationService.logIn($scope.username, $scope.password, function () { $state.go('organizationList'); }); }; $scope.logOut = function () { $state.go('userLogout'); }; }]); })();
var map; var infoWindow; // A variável markersData guarda a informação necessária a cada marcador // Para utilizar este código basta alterar a informação contida nesta variável var markersData = [ { lat: -3.741262, lng: -38.539389, nome: "Campus do Pici - Universidade Federal do Ceará", endereco:"Av. Mister Hull, s/n", telefone: "(85) 3366-9500" // não colocar virgula no último item de cada maracdor }, { lat: -3.780833, lng: -38.469656, nome: "Colosso Lake Lounge", endereco:"Rua Hermenegildo Sá Cavalcante, s/n", telefone: "(85) 98160-0088" // não colocar virgula no último item de cada maracdor } // não colocar vírgula no último marcador ]; function initialize() { var mapOptions = { center: new google.maps.LatLng(40.601203,-8.668173), zoom: 9, mapTypeId: 'roadmap', }; map = new google.maps.Map(document.getElementById('map-slackline'), mapOptions); // cria a nova Info Window com referência à variável infowindow // o conteúdo da Info Window será atribuído mais tarde infoWindow = new google.maps.InfoWindow(); // evento que fecha a infoWindow com click no mapa google.maps.event.addListener(map, 'click', function() { infoWindow.close(); }); // Chamada para a função que vai percorrer a informação // contida na variável markersData e criar os marcadores a mostrar no mapa displayMarkers(); } google.maps.event.addDomListener(window, 'load', initialize); // Esta função vai percorrer a informação contida na variável markersData // e cria os marcadores através da função createMarker function displayMarkers(){ // esta variável vai definir a área de mapa a abranger e o nível do zoom // de acordo com as posições dos marcadores var bounds = new google.maps.LatLngBounds(); // Loop que vai estruturar a informação contida em markersData // para que a função createMarker possa criar os marcadores for (var i = 0; i < markersData.length; i++){ var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng); var nome = markersData[i].nome; var endereco = markersData[i].endereco; var telefone = markersData[i].telefone; createMarker(latlng, nome, endereco, telefone); // Os valores de latitude e longitude do marcador são adicionados à // variável bounds bounds.extend(latlng); } // Depois de criados todos os marcadores // a API através da sua função fitBounds vai redefinir o nível do zoom // e consequentemente a área do mapa abrangida. map.fitBounds(bounds); } // Função que cria os marcadores e define o conteúdo de cada Info Window. function createMarker(latlng, nome, endereco, telefone){ var marker = new google.maps.Marker({ map: map, position: latlng, title: nome }); // Evento que dá instrução à API para estar alerta ao click no marcador. // Define o conteúdo e abre a Info Window. google.maps.event.addListener(marker, 'click', function() { // Variável que define a estrutura do HTML a inserir na Info Window. var iwContent = '<div id="iw_container">' + '<div class="iw_title">' + nome + '</div>' + '<div class="iw_content">' + endereco + '<br />' + telefone + '<br />'; // O conteúdo da variável iwContent é inserido na Info Window. infoWindow.setContent(iwContent); // A Info Window é aberta. infoWindow.open(map, marker); }); }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; function _default() { return function ({ addUtilities, variants }) { addUtilities({ '.bg-clip-border': { 'background-clip': 'border-box' }, '.bg-clip-padding': { 'background-clip': 'padding-box' }, '.bg-clip-content': { 'background-clip': 'content-box' }, '.bg-clip-text': { 'background-clip': 'text' } }, variants('backgroundClip')); }; }
var gulp = require('gulp'); var karma = require('karma').server; var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var path = require('path'); var plumber = require('gulp-plumber'); var runSequence = require('run-sequence'); var jshint = require('gulp-jshint'); /** * File patterns **/ // Root directory var rootDirectory = path.resolve('./'); // Source directory for build process var sourceDirectory = path.join(rootDirectory, './src'); var sourceFiles = [ // Make sure module files are handled first path.join(sourceDirectory, '/**/*.module.js'), // Then add all JavaScript files path.join(sourceDirectory, '/**/*.js') ]; var lintFiles = [ 'gulpfile.js', // Karma configuration 'karma-*.conf.js' ].concat(sourceFiles); gulp.task('build', function() { gulp.src(sourceFiles) .pipe(plumber()) .pipe(concat('df-validator.js')) .pipe(gulp.dest('./dist/')) .pipe(uglify()) .pipe(rename('df-validator.min.js')) .pipe(gulp.dest('./dist')); }); /** * Process */ gulp.task('process-all', function (done) { runSequence(/*'jshint',*/ 'test-src', 'build', done); }); /** * Watch task */ gulp.task('watch', function () { // Watch JavaScript files gulp.watch(sourceFiles, ['process-all']); }); /** * Validate source JavaScript */ gulp.task('jshint', function () { return gulp.src(lintFiles) .pipe(plumber()) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); }); /** * Run test once and exit */ gulp.task('test-src', function (done) { karma.start({ configFile: __dirname + '/karma-src.conf.js', singleRun: true }, done); }); /** * Run test once and exit */ gulp.task('test-dist-concatenated', function (done) { karma.start({ configFile: __dirname + '/karma-dist-concatenated.conf.js', singleRun: true }, done); }); /** * Run test once and exit */ gulp.task('test-dist-minified', function (done) { karma.start({ configFile: __dirname + '/karma-dist-minified.conf.js', singleRun: true }, done); }); gulp.task('default', function () { runSequence('process-all', 'watch'); });
/** * Created by quanpower on 14-8-20. */ var config = require('./../config'); var redis = require('./redis'); var _ = require('lodash'); function cacheDevice(device){ if(device){ var cloned = _.clone(device); redis.set('DEVICE_' + device.uuid, JSON.stringify(cloned),function(){ //console.log('cached', uuid); }); } } function noop(){} if(config.redis){ module.exports = cacheDevice; } else{ module.exports = noop; }
/** * morningstar-base-charts * * Copyright © 2016 . All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import defaultClasses from "../config/classes.js"; import ChartBase from "./chartBase.js"; import { ChartUtils } from "../utils/utils.js"; /** * Horizontal Bar Chart Implementation * * @extends {ChartBase} */ class HorizontalBarChart extends ChartBase{ /** * Creates an instance of HorizontalBarChart. * * @param {any} options */ constructor(options) { super(options); } /** * @override */ render(options) { var axes = this.axes, yScale = axes.axis("y").scale(), xScale = axes.axis("x").scale(), data = this.data[0].values, chartArea = this.layer, barHeight = yScale.rangeBand(), barPadding = 6, hasNegative = ChartUtils.hasNegative(data), animation = (options && !options.animation) ? false : true;; var getClass = d => { if(hasNegative){ return d >= 0 ? "h-bar-positive" : "h-bar-negative"; } return "h-bar"; }; var draw = selection => { selection.attr("class", getClass) .attr("x", (d) => xScale(Math.min(0, d))) .attr("y", 6) .attr("transform", (d, i) => "translate(0," + i * barHeight + ")") .attr("width", d => animation ? 0 : Math.abs(xScale(d) - xScale(0)) ) .attr("height", barHeight - barPadding); return selection; }; var bar = chartArea.selectAll("rect").data(data); bar.call(draw) .enter().append("rect").call(draw); bar.exit().remove(); if (animation) { bar.transition().duration(300) .attr("width", d => Math.abs(xScale(d) - xScale(0))); } } /** * * * @param {any} index */ onMouseover(index) { this.canvas.svg.selectAll(`.${defaultClasses.CHART_GROUP}.${defaultClasses.FOCUS}-${index}`) .transition() .style("opacity", 0.5); } /** * * * @param {any} index */ onMouseout(index) { this.canvas.svg.selectAll(`.${defaultClasses.CHART_GROUP}.${defaultClasses.FOCUS}-${index}`) .transition() .style("opacity", 1); } /** * * * @param {any} data */ _formatData(data) { var xDomain = this.axes.axis("x").scale().domain(); this._categories = data.map(value => value.name); this.data = xDomain.map(function (series, i) { var item = { series }; item.values = data.map(value => { return { series: series, category: value.name, value: value.values[i], index: value.index }; }); return item; }); } } export default HorizontalBarChart;
/** * Copyright (c) 2014-2015, CKSource - Frederico Knabben. All rights reserved. * Licensed under the terms of the MIT License (see LICENSE.md). */ ( function( QUnit, bender ) { var total = 0, failed = 0, passed = 0, ignored = 0, errors = 0, result = { success: true, errors: [] }; // prevent QUnit from starting QUnit.config.autostart = false; bender.removeListener( window, 'load', QUnit.load ); function start() { QUnit.testStart( function() { total++; } ); QUnit.testDone( function( details ) { details.success = result.success; details.error = result.errors.length ? result.errors.join( '\n' ) : undefined; details.duration = details.runtime; details.fullName = details.module + ' ' + details.name; bender.result( details ); if ( details.success ) { if ( details.ignored ) { ignored++; } else { passed++; } } else { failed++; errors++; } result.success = true; result.errors = []; } ); QUnit.done( function( details ) { details.duration = details.runtime; bender.next( { coverage: window.__coverage__, duration: details.runtime, passed: passed, failed: failed, errors: errors, ignored: ignored, total: total } ); } ); QUnit.log( function( details ) { // add detailed error message to test result if ( !details.result ) { result.success = false; result.errors.push( [ details.message, 'Expected: ' + details.expected, 'Actual: ' + details.actual, details.source ].join( '\n' ) ); } } ); // manually start the runner QUnit.load(); QUnit.start(); } function stopRunner() { QUnit.stop(); } function isSingle( name ) { return name === decodeURIComponent( window.location.hash.substr( 1 ) ); } var oldTest = QUnit.test; QUnit.test = function( name ) { var module = this.config.currentModule, fullName = module ? module + ' ' + name : name; if ( window.location.hash && window.location.hash !== '#child' && !isSingle( fullName ) ) { return; } oldTest.apply( this, arguments ); }; window.assert = bender.assert = QUnit.assert; bender.runner = QUnit; bender.start = start; bender.stopRunner = stopRunner; } )( window.QUnit || {}, bender );
/** * This is a "mini-app" that encapsulates router definitions. See more * at: http://expressjs.com/guide/routing.html (search for "express.Router") * */ var router = require('express').Router({ mergeParams: true }); module.exports = router; // Don't just use, but also export in case another module needs to use these as well. router.callbacks = require('./controllers/hello'); router.models = require('./models'); //-- For increased module encapsulation, you could also serve templates with module-local //-- paths, but using shared layouts and partials may become tricky / impossible //var hbs = require('hbs'); //app.set('views', __dirname + '/views'); //app.set('view engine', 'handlebars'); //app.engine('handlebars', hbs.__express); // Module's Routes. Please note this is actually under /hello, because module is attached under /hello router.get('/', router.callbacks.sayHello);
import WebhookNotification, { LinkClick, LinkClickCount, MessageTrackingData, WebhookDelta, WebhookObjectAttributes, WebhookObjectData, } from '../src/models/webhook-notification'; import { WebhookTriggers } from '../src/models/webhook'; describe('Webhook Notification', () => { test('Should deserialize from JSON properly', done => { const webhookNotificationJSON = { deltas: [ { date: 1602623196, object: 'message', type: 'message.created', object_data: { namespace_id: 'aaz875kwuvxik6ku7pwkqp3ah', account_id: 'aaz875kwuvxik6ku7pwkqp3ah', object: 'message', attributes: { action: 'save_draft', job_status_id: 'abc1234', thread_id: '2u152dt4tnq9j61j8seg26ni6', received_date: 1602623166, }, id: '93mgpjynqqu5fohl2dvv6ray7', metadata: { sender_app_id: 64280, link_data: [ { url: 'https://nylas.com/', count: 1, }, ], timestamp: 1602623966, recents: [ { ip: '24.243.155.85', link_index: 0, id: 0, user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36', timestamp: 1602623980, }, ], message_id: '4utnziee7bu2ohak56wfxe39p', payload: 'Tracking enabled', }, }, }, ], }; const webhookNotification = new WebhookNotification().fromJSON( webhookNotificationJSON ); expect(webhookNotification.deltas.length).toBe(1); const webhookDelta = webhookNotification.deltas[0]; expect(webhookDelta instanceof WebhookDelta).toBe(true); expect(webhookDelta.date).toEqual(new Date(1602623196 * 1000)); expect(webhookDelta.object).toEqual('message'); expect(webhookDelta.type).toEqual(WebhookTriggers.MessageCreated); const webhookDeltaObjectData = webhookDelta.objectData; expect(webhookDeltaObjectData instanceof WebhookObjectData).toBe(true); expect(webhookDeltaObjectData.id).toEqual('93mgpjynqqu5fohl2dvv6ray7'); expect(webhookDeltaObjectData.accountId).toEqual( 'aaz875kwuvxik6ku7pwkqp3ah' ); expect(webhookDeltaObjectData.namespaceId).toEqual( 'aaz875kwuvxik6ku7pwkqp3ah' ); expect(webhookDeltaObjectData.object).toEqual('message'); const webhookDeltaObjectAttributes = webhookDeltaObjectData.objectAttributes; expect( webhookDeltaObjectAttributes instanceof WebhookObjectAttributes ).toBe(true); expect(webhookDeltaObjectAttributes.action).toEqual('save_draft'); expect(webhookDeltaObjectAttributes.jobStatusId).toEqual('abc1234'); expect(webhookDeltaObjectAttributes.threadId).toEqual( '2u152dt4tnq9j61j8seg26ni6' ); expect(webhookDeltaObjectAttributes.receivedDate).toEqual( new Date(1602623166 * 1000) ); const webhookMessageTrackingData = webhookDeltaObjectData.metadata; expect(webhookMessageTrackingData instanceof MessageTrackingData).toBe( true ); expect(webhookMessageTrackingData.messageId).toEqual( '4utnziee7bu2ohak56wfxe39p' ); expect(webhookMessageTrackingData.payload).toEqual('Tracking enabled'); expect(webhookMessageTrackingData.timestamp).toEqual( new Date(1602623966 * 1000) ); expect(webhookMessageTrackingData.senderAppId).toBe(64280); expect(webhookMessageTrackingData.linkData.length).toBe(1); expect(webhookMessageTrackingData.recents.length).toBe(1); const linkData = webhookMessageTrackingData.linkData[0]; expect(linkData instanceof LinkClickCount).toBe(true); expect(linkData.url).toEqual('https://nylas.com/'); expect(linkData.count).toBe(1); const recents = webhookMessageTrackingData.recents[0]; expect(recents instanceof LinkClick).toBe(true); expect(recents.id).toBe(0); expect(recents.ip).toEqual('24.243.155.85'); expect(recents.userAgent).toEqual( 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36' ); expect(recents.timestamp).toEqual(new Date(1602623980 * 1000)); expect(recents.linkIndex).toBe(0); done(); }); });
import deepFreeze from 'deep-freeze'; import { arrayToMap, mapKeysToArray } from './mapUtils'; describe('arrayToMap', () => { it('should create map from 2D array', () => { const a = [ ['key1', 'value1'], ['key2', 'value2'] ]; deepFreeze(a); const result = arrayToMap(a); expect(result.size).toBe(2); expect(result.get('key1')).toBe('value1'); expect(result.get('key2')).toBe('value2'); }); it('should create empty map from empty array', () => { const result = arrayToMap([]); expect(result.size).toBe(0); }); }); describe('mapKeysToArray', () => { it('should create array from map keys in order', () => { const map = new Map(); map.set('a', 'value1'); map.set('c', 'value2'); map.set('1', 'value3'); map.set('b', 'value4'); map.set('2', 'value5'); const result = mapKeysToArray(map); expect(result).toEqual(['a', 'c', '1', 'b', '2']); }); it('should create empty array from new map', () => { const map = new Map(); const result = mapKeysToArray(map); expect(result).toEqual([]); }); });
require('./node') require('./console')
/* * Author: Brendan Le Foll <brendan.le.foll@intel.com> * Copyright (c) 2014 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var m = require("mraa") console.log("mraa version: " + m.getVersion()); var x = new m.Gpio(8) x.dir(m.DIR_OUT) x.write(1)
class upnp_soaprequest { constructor() { } // System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) CreateObjRef() { } // bool Equals(System.Object obj) Equals() { } // int GetHashCode() GetHashCode() { } // System.Object GetLifetimeService() GetLifetimeService() { } // type GetType() GetType() { } // System.Object InitializeLifetimeService() InitializeLifetimeService() { } // string ToString() ToString() { } } module.exports = upnp_soaprequest;
module.exports = { schedule_inputError: "Not all required inputs are present in the request", reminder_newscheduleSuccess: "A new mail has been successfully saved and scheduled", schedule_ShdlError: "The scheduleAt should be a timestamp (like : 1411820580000) and should be in the future", gbl_oops: "Oops something went wrong", gbl_success: "success" };
/** * create edit language file link */ export default (lang) => { return `https://github.com/electerm/electerm-locales/edit/master/locales/${lang}.js` }
/** * @author Ultimo <von.ultimo@gmail.com> * @license http://www.opensource.org/licenses/mit-license.html MIT License * @version 0.1 (25-06-2017) * * Hier schreiben wir die JavaScript Funktionen. * */ src="jquery-3.2.1.min"; $(document).ready(function(){ $("td:contains('-')").filter(":contains('€')").addClass('neg'); $(".betrag").filter(":contains('-')").addClass('neg'); }); function goBack() { window.history.back(); }
var compare = require('typewiselite') var search = require('binary-search') function compareKeys (a, b) { return compare(a.key, b.key) } module.exports = function (_compare) { var ary = [], kv _compare = _compare || compare function cmp (a, b) { return _compare(a.key, b.key) } return kv = { getIndex: function (key) { return search(ary, {key: key}, cmp, 0, ary.length - 1) }, get: function (key) { var i = this.getIndex(key) return i >= 0 ? ary[i].value : undefined }, has: function (key) { return this.getIndex(key) >= 0 }, //update a key set: function (key, value) { return kv.add({key: key, value: value}) }, add: function (o) { var i = search(ary, o, cmp) //overwrite a key, or insert a key if(i < 0) ary.splice(~i, 0, o) else ary[i] = o return i }, toJSON: function () { return ary.slice() }, store: ary } } module.exports.search = search module.exports.compareKeys = compareKeys
define( [ 'jquery', 'angular', 'json!nuke/data/dummy_model.json', 'json!nuke/data/dummy_layout.json', 'text!nuke/demo.html' ], function( $, ng, dummyModel, dummyLayout, htmlDemoTemplate ) { 'use strict'; var module = ng.module( 'NukeDemoApp', [ 'nbe' ] ) .run( [ '$templateCache', function( $templateCache ) { $templateCache.put( 'lib/demo.html', htmlDemoTemplate ); } ] ); /////////////////////////////////////////////////////////////////////////////////////////////////////////// function NukeDemoController( $scope, $timeout ) { $scope.model = dummyModel; $scope.layout = dummyLayout; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// module.controller( 'NukeDemoController', [ '$scope', '$timeout', NukeDemoController ] ); /////////////////////////////////////////////////////////////////////////////////////////////////////////// return module; } );
/*global module:false*/ module.exports = function(grunt) { // Project configuration. grunt.initConfig({ meta: { version: '2.0.0', banner: '/*! Ebla - v<%= meta.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '* Copyright (c) <%= grunt.template.today("yyyy") %> ' + 'Monospaced */' }, concat: { dist: { src: ['<banner:meta.banner>', 'javascripts/libs/jquery.cookie.js', 'javascripts/ebla/ebla.js', 'javascripts/ebla/debug.js', 'javascripts/ebla/flash-message.js', 'javascripts/ebla/compatibility.js', 'javascripts/ebla/elements.js', 'javascripts/ebla/controls.js', 'javascripts/ebla/data.js', 'javascripts/ebla/images.js', 'javascripts/ebla/layout.js', 'javascripts/ebla/loader.js', 'javascripts/ebla/navigation.js', 'javascripts/ebla/navigation.event.js', 'javascripts/ebla/navigation.keyboard.js', 'javascripts/ebla/placesaver.js', 'javascripts/ebla/progress.js', 'javascripts/ebla/resize.js', 'javascripts/ebla/toc.js', 'javascripts/ebla/init.js', 'javascripts/ebla/book.js'], dest: 'javascripts/ebla.js' } }, uglify: { dist: { src: ['<banner:meta.banner>', 'javascripts/ebla.js'], dest: 'javascripts/ebla.min.js' } }, sass: { dist: { options: { style: 'compressed' }, files: { 'stylesheets/ebla.css': 'stylesheets/ebla.scss', 'stylesheets/book.css': 'stylesheets/book.scss' } } }, watch: { files: ['javascripts/ebla/*.js', 'stylesheets/*.scss'], tasks: ['sass', 'concat', 'uglify'] }, jshint: { files: ['Gruntfile.js', 'javascripts/ebla.js'], options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, browser: true, jquery: true, devel: true, globals: { Modernizr: true, debug: true, bookData: true, bookJson: true } }, } }); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-sass'); // Default task. grunt.registerTask('default', ['sass', 'concat', 'jshint', 'uglify']); };
import {Chart} from 'react-google-charts'; import React, {Component, PropTypes} from 'react'; import DataFormatter from '../../utils/DataFormatter'; class EnvyBarChart extends Component { constructor(props) { super(props); this.state={ options:{ hAxis: {title: 'Event Type'}, vAxis: {title: 'Envy Events'}, legend: 'none', }, }; } generateGraph(events) { var formatter = new DataFormatter(); var result = formatter.generateEnvyGraph(events); return result; } render() { var data = this.generateGraph(this.props.events); return ( <Chart chartType="ColumnChart" data={data} options={this.state.options} graph_id="EnvyBarChart" width='40vw' height='50vh' /> ); } }; EnvyBarChart.propTypes = { events: PropTypes.array.isRequired } export default EnvyBarChart;
"use strict"; let mongoose = require('mongoose'), Schema = mongoose.Schema, EmailValidator = require('./emailValidator'); class User { constructor(explicitConnection) { this.explicitConnection = explicitConnection; this.schema = new Schema({ email: { type: 'string', trim: true, required: true }, organization: { type: 'string', trim: true, required: true }, password: {type: 'string', required: true}, isVisibleAccount: {type: 'boolean'}, userApiKey: {type: 'string'}, userApiSecret: {type: 'string'}, linkedApps: {}, avatarProto: {type: 'string'}, gmailAccount: {type: 'string'}, facebookAccount: {type: 'string'}, twitterAccount: {type: 'string'}, fullname: {type: 'string'}, loginHistories: [], changeProfileHistories: [], changeAuthorizationHistories: [], sparqlQuestions: [], blockingHistories: [], authorizations: {}, tripleUsage: {type: 'number', default: 0}, tripleUsageHistory: [], isBlocked: { type: 'boolean', required: true }, blockedCause: { type: 'string', } }).index({ email: 1, organization: 1 }, { unique: true }); } getModel() { if (this.explicitConnection === undefined) { return mongoose.model('User', this.schema); } else { return this.explicitConnection.model('User', this.schema); } } } module.exports = User;
module.export = { };
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import moment from 'moment'; import { toggleSelect } from '../actions/users'; import { createLink } from '../../utils'; class User extends Component { render() { const profile_image_url_https = this.props.user.profile_image_url_https ? this.props.user.profile_image_url_https.replace('normal', 'bigger') : ''; const small_profile_image_url_https = this.props.user.profile_image_url_https ? this.props.user.profile_image_url_https.replace('normal', 'mini') : ''; var description = this.props.user.description; if(description) { description = description.replace(/@[A-Za-z_0-9]+/g, id => createLink(`https://twitter.com/${id.substring(1)}`, id)); this.props.user.entities.description.urls.forEach(url => description = description.replace(new RegExp(url.url, 'g'), createLink(url.expanded_url, url.expanded_url))); } return this.props.settings.showMode === 'card' ? ( <li className={'responsive-card ' + (this.props.user.select ? 'responsive-card--selected' : '')}> <input type="checkbox" checked={this.props.user.select} className="user__select" onChange={this.props.toggleSelect} /> <div alt="" className="card-img-top" style={{ backgroundImage: this.props.user.profile_banner_url ? `url(${this.props.user.profile_banner_url + '/600x200'})` : 'none', backgroundColor: !this.props.user.profile_banner_url ? `#${this.props.user.profile_link_color}` : 'transparent' }} onClick={this.props.toggleSelect}></div> <div className="card-block"> <div className="media"> <div className="media-left"> <img src={profile_image_url_https} width="73" height="73" className="media-left__icon" /> </div> <div className="media-body"> <div className="card-title"> <div className="card-title__name"> {this.props.user.name} </div> <div className="card-title__screen-name"> <small> <a href={`https://twitter.com/${this.props.user.screen_name}`} target="_new" title={this.props.user.id_str}>@{this.props.user.screen_name}</a> {this.props.user.protected ? ( <span> &nbsp;<i className="fa fa-lock"></i> </span> ) : null} </small> </div> </div> </div> </div> </div> <ul className="list-group list-group-flush"> { this.props.user.entities && this.props.user.entities.url ? ( <li className="list-group-item"> <a href={this.props.user.entities.url.urls[0].url} target="_new"> <i className="fa fa-link fa-fw"></i> {this.props.user.entities.url.urls[0].expanded_url ? this.props.user.entities.url.urls[0].expanded_url : this.props.user.entities.url.urls[0].url}</a> </li> ) : null } { this.props.user.location ? ( <li className="list-group-item"> <i className="fa fa-map-marker fa-fw"></i> {this.props.user.location} </li> ) : null } </ul> {this.props.user.entities && !this.props.user.entities.url && !this.props.user.location ? <hr /> : null} <div className="card-block"> <p className="card-text" dangerouslySetInnerHTML={{__html: description}}> </p> </div> </li> ) : ( <tr onClick={e => { if(['A', 'INPUT'].includes(e.target.tagName)) { e.stopPropagation(); } else { this.props.toggleSelect(); } }}> <td className="user-list-table__checkbox user-list-table__checkbox--row"> <input type="checkbox" checked={this.props.user.select} onChange={this.props.toggleSelect} /> </td> <td className="user-list-table__name user-list-table__name--row"><img src={small_profile_image_url_https} width="24" height="24" /> {this.props.user.name}</td> <td> <a href={`https://twitter.com/${this.props.user.screen_name}`} target="_new">{this.props.user.screen_name}</a> {this.props.user.protected ? ( <span> &nbsp;<i className="fa fa-lock"></i> </span> ) : null} </td> <td>{this.props.user.friends_count}</td> <td>{this.props.user.followers_count}</td> <td>{this.props.user.status ? moment(new Date(this.props.user.status.created_at)).format('YYYY/MM/DD HH:mm:ss') : null}</td> </tr> ); } } User.propTypes = { userId: PropTypes.string.isRequired, user: PropTypes.object.isRequired, settings: PropTypes.object.isRequired }; User.defaultProps = { userId: '0', user: {}, settings: {} }; function mapStateToProps(state, ownProps) { return { user: state.users.users.allUserInfo[ownProps.userId], settings: state.settings }; } function mapDispatchToProps(dispatch, ownProps) { return { toggleSelect() { dispatch(toggleSelect(ownProps.userId)); } }; } export default connect(mapStateToProps, mapDispatchToProps)(User);
/*! Copyright 2011, Ben Lin (http://dreamerslab.com/) * Licensed under the MIT License (LICENSE.txt). * * Version: 1.0.0 * * Requires: jQuery 1.2.3+ */ $.preload = function(){ var tmp = [], i = arguments.length; // reverse loop run faster for( ; i-- ; ) tmp.push( $( '<img />' ).attr( 'src', arguments[ i ] )); };
/*jshint indent: 4, browser:true*/ /*global L*/ /* * L.TimeDimension.Player */ //'use strict'; L.TimeDimension.Player = (L.Layer || L.Class).extend({ includes: (L.Evented || L.Mixin.Events), initialize: function(options, timeDimension) { L.setOptions(this, options); this._timeDimension = timeDimension; this._paused = false; this._buffer = this.options.buffer || 5; this._minBufferReady = this.options.minBufferReady || 1; this._waitingForBuffer = false; this._loop = this.options.loop || false; this._steps = 1; this._timeDimension.on('timeload', (function(data) { this.release(); // free clock this._waitingForBuffer = false; // reset buffer }).bind(this)); this.setTransitionTime(this.options.transitionTime || 1000); this._timeDimension.on('limitschanged availabletimeschanged timeload', (function(data) { this._timeDimension.prepareNextTimes(this._steps, this._minBufferReady, this._loop); }).bind(this)); }, _tick: function() { var maxIndex = this._getMaxIndex(); var maxForward = (this._timeDimension.getCurrentTimeIndex() >= maxIndex) && (this._steps > 0); var maxBackward = (this._timeDimension.getCurrentTimeIndex() == 0) && (this._steps < 0); if (maxForward || maxBackward) { // we reached the last step if (!this._loop) { this.pause(); this.stop(); this.fire('animationfinished'); return; } } if (this._paused) { return; } var numberNextTimesReady = 0, buffer = this._bufferSize; if (this._minBufferReady > 0) { numberNextTimesReady = this._timeDimension.getNumberNextTimesReady(this._steps, buffer, this._loop); // If the player was waiting, check if all times are loaded if (this._waitingForBuffer) { if (numberNextTimesReady < buffer) { console.log('Waiting until buffer is loaded. ' + numberNextTimesReady + ' of ' + buffer + ' loaded'); this.fire('waiting', { buffer: buffer, available: numberNextTimesReady }); return; } else { // all times loaded console.log('Buffer is fully loaded!'); this.fire('running'); this._waitingForBuffer = false; } } else { // check if player has to stop to wait and force to full all the buffer if (numberNextTimesReady < this._minBufferReady) { console.log('Force wait for load buffer. ' + numberNextTimesReady + ' of ' + buffer + ' loaded'); this._waitingForBuffer = true; this._timeDimension.prepareNextTimes(this._steps, buffer, this._loop); this.fire('waiting', { buffer: buffer, available: numberNextTimesReady }); return; } } } this.pause(); this._timeDimension.nextTime(this._steps, this._loop); if (buffer > 0) { this._timeDimension.prepareNextTimes(this._steps, buffer, this._loop); } }, _getMaxIndex: function(){ return Math.min(this._timeDimension.getAvailableTimes().length - 1, this._timeDimension.getUpperLimitIndex() || Infinity); }, start: function(numSteps) { if (this._intervalID) return; this._steps = numSteps || 1; this._waitingForBuffer = false; var startedOver = false; if (this.options.startOver){ if (this._timeDimension.getCurrentTimeIndex() === this._getMaxIndex()){ this._timeDimension.setCurrentTimeIndex(this._timeDimension.getLowerLimitIndex() || 0); startedOver = true; } } this.release(); this._intervalID = window.setInterval( L.bind(this._tick, this), this._transitionTime); if (!startedOver) this._tick(); this.fire('play'); this.fire('running'); }, stop: function() { if (!this._intervalID) return; clearInterval(this._intervalID); this._intervalID = null; this._waitingForBuffer = false; this.fire('stop'); }, pause: function() { this._paused = true; }, release: function () { this._paused = false; }, getTransitionTime: function() { return this._transitionTime; }, isPlaying: function() { return this._intervalID ? true : false; }, isWaiting: function() { return this._waitingForBuffer; }, isLooped: function() { return this._loop; }, setLooped: function(looped) { this._loop = looped; this.fire('loopchange', { loop: looped }); }, setTransitionTime: function(transitionTime) { this._transitionTime = transitionTime; if (typeof this._buffer === 'function') { this._bufferSize = this._buffer.call(this, this._transitionTime, this._minBufferReady, this._loop); console.log('Buffer size changed to ' + this._bufferSize); } else { this._bufferSize = this._buffer; } if (this._intervalID) { this.stop(); this.start(this._steps); } this.fire('speedchange', { transitionTime: transitionTime, buffer: this._bufferSize }); }, getSteps: function() { return this._steps; } });
'use strict'; angular.module('mean.settings').config(['$stateProvider', function($stateProvider) { var checkLoggedin = function($q, $timeout, $http, $location) { // Initialize a new promise var deferred = $q.defer(); // Make an AJAX call to check if the user is logged in $http.get('/loggedin').success(function(user) { // Authenticated if (user !== '0') $timeout(deferred.resolve); // Not Authenticated else { $timeout(deferred.reject); $location.url('/'); } }); return deferred.promise; }; $stateProvider.state('settings', { url: '/settings', templateUrl: 'settings/views/index.html', resolve: { loggedin: checkLoggedin } }); } ]);
import PropTypes from 'prop-types' import React from 'react' import block from 'bem-cn-lite' import { Field, reduxForm } from 'redux-form' import { compose } from 'underscore' import { connect } from 'react-redux' import { renderTextInput } from '../text_input' import { renderCheckboxInput } from '../checkbox_input' import { signUp, updateAuthFormStateAndClearError } from '../../client/actions' import { GDPRMessage } from 'desktop/components/react/gdpr/GDPRCheckbox' function validate(values) { const { accepted_terms_of_service, email, name, password } = values const errors = {} if (!name) errors.name = 'Required' if (!email) errors.email = 'Required' if (!password) errors.password = 'Required' if (!accepted_terms_of_service) errors.accepted_terms_of_service = 'Please agree to our terms to continue' return errors } function SignUp(props) { const { error, handleSubmit, isLoading, signUpAction, updateAuthFormStateAndClearErrorAction, } = props const b = block('consignments-submission-sign-up') return ( <div className={b()}> <div className={b('title')}>Create an Account</div> <div className={b('subtitle')}> Already have an account?{' '} <span className={b('clickable')} onClick={() => updateAuthFormStateAndClearErrorAction('logIn')} > Log in </span>. </div> <form className={b('form')} onSubmit={handleSubmit(signUpAction)}> <div className={b('row')}> <div className={b('row-item')}> <Field name="name" component={renderTextInput} item={'name'} label={'Full Name'} autofocus /> </div> </div> <div className={b('row')}> <div className={b('row-item')}> <Field name="email" component={renderTextInput} item={'email'} label={'Email'} type={'email'} /> </div> </div> <div className={b('row')}> <div className={b('row-item')}> <Field name="password" component={renderTextInput} item={'password'} label={'Password'} type={'password'} /> </div> </div> <div className={b('row')}> <div className={b('row-item')}> <Field name="accepted_terms_of_service" component={renderCheckboxInput} item={'accepted_terms_of_service'} label={<GDPRMessage />} value={false} /> </div> </div> <button className={b .builder()('sign-up-button') .mix('avant-garde-button-black')()} type="submit" > {isLoading ? <div className="loading-spinner-white" /> : 'Submit'} </button> {error && <div className={b('error')}>{error}</div>} </form> </div> ) } const mapStateToProps = state => { return { error: state.submissionFlow.error, isLoading: state.submissionFlow.isLoading, } } const mapDispatchToProps = { signUpAction: signUp, updateAuthFormStateAndClearErrorAction: updateAuthFormStateAndClearError, } SignUp.propTypes = { error: PropTypes.string, handleSubmit: PropTypes.func.isRequired, isLoading: PropTypes.bool.isRequired, signUpAction: PropTypes.func.isRequired, updateAuthFormStateAndClearErrorAction: PropTypes.func.isRequired, } export default compose( reduxForm({ form: 'signUp', // a unique identifier for this form validate, }), connect(mapStateToProps, mapDispatchToProps) )(SignUp)
TF.listen();
$(document).ready(function() { $(document).on('submit', '.status-button', function(e) { e.preventDefault(); var joinButton = e.target $.ajax(joinButton.action, { method: 'PATCH', data: $(this).serialize() }) .done(function(data) { gameDiv = $(joinButton).parent(); gameDiv.replaceWith(data); }) .fail(function() { alert("Failure!"); }); }); });
function OrganizationController() { // injetando dependência 'ngInject'; // ViewModel const vm = this; console.log('OrganizationController'); } export default { name: 'OrganizationController', fn: OrganizationController };
import React, { Component } from 'react'; import Header from './Header'; import MainSection from './MainSection'; export default class App extends Component { render() { return ( <div> <Header/> <MainSection/> </div> ); } }
version https://git-lfs.github.com/spec/v1 oid sha256:641860132ccb9772e708b19feb3d59bb6291f6c40eebbfcfa0982a4e8eeda219 size 69639
(function(global) { var vwl = {}; var receivePoster; var receiveEntry; var receiveLoadedList; // vwl.init - advertise VWL info and register for VWL messages // // Parameters: // left - (optional) url of this world's initial left entry image // right - (optional) url of this world's initial right entry image // receivePosterFunc - (optional) function to handle poster images from other // worlds // receiveEntryFunc - (optional) function to handle entry images from other // worlds // recevieLoadedListFunc - (optional) function to handle list of loaded worlds vwl.init = function(left, right, receivePosterFunc, receiveEntryFunc, receiveLoadedListFunc) { receivePoster = receivePosterFunc; receiveEntry = receiveEntryFunc; receiveLoadedList = receiveLoadedListFunc; receiveEntry && window.addEventListener('message', function(message) { if (message.source != window || message.origin != window.location.origin) return; if (message.data.tabInfo) { var left = null; var right = null; if (message.data.tabInfo.info && message.data.tabInfo.info.entry_image) { left = message.data.tabInfo.info.entry_image.left_src; right = message.data.tabInfo.info.entry_image.right_src; } receiveEntry(message.data.tabInfo.url, message.data.tabInfo.loaded, left, right); } if (message.data.loadedList !== undefined) { receiveLoadedList(message.data.loadedList); } }, false); window.postMessage({info:{entry_image:{ left_src:left, right_src:right}}}, '*'); } // vwl.getInfo - get info (entry image and poster image) on a specific world // // Parameters: // url - url of worlds to get info on // getPoster - (optional) if true get the poster image vwl.getInfo = function(url, getPoster) { if (receivePoster && getPoster) { var request = new XMLHttpRequest(); var dir = url.substr(0, url.lastIndexOf('/') + 1); request.open('GET', dir + 'vwl_info.json'); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { var poster = JSON.parse(request.responseText).poster_image; receivePoster(url, poster.left_src ? dir + poster.left_src : null, poster.right_src ? dir + poster.right_src : null, poster._2d_src ? dir + poster._2d_src : null); } else { receivePoster(url); } } request.send(null); } receiveEntry && window.postMessage({getInfo:url}, '*'); } // vwl.getLoadedList - get the list of loaded worlds vwl.getLoadedList = function() { window.postMessage({getLoadedList:true}, '*'); } // vwl.open - load world // // Parameters: // url - url of world to open vwl.open = function(url) { window.postMessage({open:url}, '*'); } // vwl.navigate - navigate to a world // // Parameters: // left - (optional) new left entry image for current world // right - (optional) new right entry image for current world // url - url of world to navigate to vwl.navigate = function(left, right, url) { var message = {navigate:url}; if (left && right) { message.info = {entry_image:{left_src:left, right_src:right}}; } window.postMessage(message, '*'); } global.vwl = vwl; }) (window);
// These two object contain information about the state of Ebl var GlobalState = Base.extend({ constructor: function() { this.isAdmin = false; this.authToken = null; this.docTitle = null; this.container = null; // default config this.config = { template: 'default', language: 'en', postsPerPage: 5, pageTitleFormat: "{ebl_title} | {doc_title}", // callbacks onBlogLoaded: null, onPostOpened: null, onPageChanged: null }; } }); var LocalState = Base.extend({ constructor: function() { this.page = 0; this.post = null; this.editors = null; } }); var PostStatus = { NEW: 0, DRAFT: 1, PUBLISHED: 2, parse: function (s) { if (s.toLowerCase() == "new") return 0; if (s.toLowerCase() == "draft") return 1; if (s.toLowerCase() == "published") return 2; return null; } }; var gState = new GlobalState(); // state shared among the entire session var lState = new LocalState(); // state of the current view
import React from 'react' import { Container, Group, TabBar, Icon, Badge, amStyles, } from 'amazeui-touch' import {Link} from 'react-router' class App extends React.Component{ propsType ={ children:React.PropTypes.node } render(){ let { location, params, children, ...props } = this.props; let transition = children.props.transition || 'sfr' return ( <Container direction="column"> <Container transition={transition} > {children} </Container> <TabBar > <TabBar.Item component={Link} eventKey = 'home' active = {location.pathname === '/'} icon = 'home' title = '首页' to='/' /> <TabBar.Item component={Link} active={location.pathname === '/class'} eventKey="class" icon="list" title="课程" to='/class' /> <TabBar.Item active={location.pathname === '/search'} eventKey="search" icon="search" title="发现" /> <TabBar.Item component={Link} active={location.pathname === '/me'} eventKey="person" icon="person" title="我" to='/me' /> </TabBar> </Container> ) } } export default App
/* * unstrap v1.1.3 * https://unstrap.org * 2015-2020 * MIT license */ const version = '1.1.3', collection = {}; function extendUnstrap (v) { var list; if (!collection[v].selectors) { collection[v].selectors = ['.' + collection[v].name]; } collection[v].selectors.forEach(function (sel) { list = document.querySelectorAll(sel); for (var i = 0; i < list.length; i++) { collection[v].extend && collection[v].extend(list.item(i)); } }) } function init () { var observer = new MutationObserver(function (mut) { mut.forEach(function (m) { var n = m.addedNodes, f; for (var i=0; i<n.length; i++) { var c = n.item(i).classList; if (c) { for (var j = 0; j < c.length; j++) { if (f = collection[c.item(j)]) { f.extend && f.extend(n.item(i)); } } } } }); }); Object.keys(collection).forEach(function (v) { extendUnstrap(v); }) observer.observe(document.body, {childList: true, subtree: true}); } function register (...components) { components.forEach((component) => { if (component.name) { collection[component.name] = component; } }) } function unregister (...components) { components.forEach((component) => { delete collection[component.name]; }) } function list () { return Object.keys(collection).sort(); } window.onload = init; export default { version, register, unregister, list }
let fs = require("fs"); let path = require("path"); let cp = require("child_process"); function runCommand(folder, args) { cp.spawn("npm", args, { env: process.env, cwd: folder, stdio: "inherit" }); } function getPackages(category) { let folder = path.join(__dirname, category); return fs .readdirSync(folder) .map(function(dir) { let fullPath = path.join(folder, dir); // check for a package.json file if (!fs.existsSync(path.join(fullPath, "package.json"))) { return; } return fullPath; }) .filter(function(pkg) { return pkg !== undefined; }); } function runCommandInCategory(category, args) { let pkgs = getPackages(category); pkgs.forEach(function(pkg) { runCommand(pkg, args); }); } let CATEGORIES = ["react", "vue", "svelte", "misc"]; let category = process.argv[2]; let args = process.argv.slice(3); if (category === "all") { CATEGORIES.forEach(function(c) { runCommandInCategory(c, args); }); } else { runCommandInCategory(category, args); }
var models=require('../models/models.js'); // Autoload :id de comentarios exports.load=function (req,res,next,commentId) { models.Comment.find({ where:{ id:Number(commentId) } }).then(function (comment) { if(comment){ req.comment=comment; next(); }else{ next(new Error('No existe commentId=' +commentId)) } }).catch(function (error) { next(error); }); }; //GET /quizes/:quizId/comments/new exports.new=function (req,res) { res.render('comments/new.ejs',{quizid:req.params.quizId, errors:[]}); }; //POST /quizes/:quizId/comments exports.create=function (req,res) { var comment =models.Comment.build( { texto:req.body.comment.texto, QuizId:req.params.quizId, }); comment .validate() .then( function (err) { if(err){ res.render('comments/new.ejs', {comment:comment,quizid:req.params.quizId,errors:err.errors}); }else{ comment //save :guarda en DB campo texto .save() .then(function () { res.redirect('/quizes/'+req.params.quizId); }); } } ).catch(function (error) { next(error); }); }; //GET /quizes/:quizId/comments/:commentId/publish exports.publish=function (req,res) { req.comment.publicado=true; req.comment.save({fields:["publicado"]}).then( function () { res.redirect('/quizes/'+req.params.quizId); }).catch(function (error) { next(error); }); };
import React, { PropTypes } from 'react'; import TodoItem from './TodoItem'; const TodoList = ({todos}) => ( <ul className="todo-list"> {todos.map(todo => <TodoItem key={todo.id} {...todo} /> )} </ul> ); TodoList.propTypes = { todos: PropTypes.array.isRequired } export default TodoList;
// Video: https://www.youtube.com/watch?v=WH5BrkzGgQY const daggy = require('daggy') const compose = (f, g) => x => f(g(x)) const id = x => x //===============Define Coyoneda========= // create constructor with props 'x' and 'f' // 'x' is our value, 'f' is a function const Coyoneda = daggy.tagged('x', 'f') // map composes the function Coyoneda.prototype.map = function(f) { return Coyoneda(this.x, compose(f, this.f)) } Coyoneda.prototype.lower = function() { return this.x.map(this.f) } // lift starts off Coyoneda with the 'id' function Coyoneda.lift = x => Coyoneda(x, id) //===============Map over a non-Functor - Set ========= // Set does not have a 'map' method const set = new Set([1, 1, 2, 3, 3, 4]) console.log("Set([1, 1, 2, 3, 3, 4]) : ", set) // Wrap set into Coyoneda with 'id' function const coyoResult = Coyoneda.lift(set) .map(x => x + 1) .map(x => `${x}!`) console.log( "Coyoneda.lift(set).map(x => x + 1).map(x => `${x}!`): ", coyoResult ) // equivalent to buildUpFn = coyoResult.f, ourSet = coyoResult.x const {f: builtUpFn, x: ourSet} = coyoResult console.log("builtUpFn is: ", builtUpFn, "; ourSet is: ", ourSet) ourSet .forEach(n => console.log(builtUpFn(n))) // 2! // 3! // 4! // 5! //===============Lift a functor in (Array) and achieve Loop fusion========= console.log( `Coyoneda.lift([1,2,3]).map(x => x * 2).map(x => x - 1).lower() : `, Coyoneda.lift([1,2,3]) .map(x => x * 2) .map(x => x - 1) .lower() ) // [ 1, 3, 5 ] //===============Make Any Type a Functor========= // Any object becomes a functor when placed in Coyoneda const Container = daggy.tagged('x') const tunacan = Container("tuna") const res = Coyoneda.lift(tunacan) .map(x => x.toUpperCase()) .map(x => x + '!') const {f: fn, x: can} = res console.log(fn(can.x)) // TUNA!
var map, boroughSearch = [], theaterSearch = [], museumSearch = []; /* Basemap Layers */ var mapquestOSM = L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0po4e8k/{z}/{x}/{y}.png"); var mbTerrainSat = L.tileLayer("https://{s}.tiles.mapbox.com/v3/matt.hd0b27jd/{z}/{x}/{y}.png"); var mbTerrainReg = L.tileLayer("https://{s}.tiles.mapbox.com/v3/aj.um7z9lus/{z}/{x}/{y}.png"); var mapquestOAM = L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0pml9h7/{z}/{x}/{y}.png", { maxZoom: 19, }); var mapquestHYB = L.layerGroup([L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0pml9h7/{z}/{x}/{y}.png", { maxZoom: 19, }), L.tileLayer("http://{s}.mqcdn.com/tiles/1.0.0/hyb/{z}/{x}/{y}.png", { maxZoom: 19, subdomains: ["oatile1", "oatile2", "oatile3", "oatile4"], })]); map = L.map("map", { zoom: 5, center: [39, -95], layers: [mapquestOSM] }); /* Larger screens get expanded layer control */ if (document.body.clientWidth <= 767) { var isCollapsed = true; } else { var isCollapsed = false; } var baseLayers = { "Street Map": mapquestOSM, "Aerial Imagery": mapquestOAM, "Imagery with Streets": mapquestHYB }; var overlays = {}; var layerControl = L.control.layers(baseLayers, {}, { collapsed: isCollapsed }).addTo(map); /* Add overlay layers to map after defining layer control to preserver order */ var sidebar = L.control.sidebar("sidebar", { closeButton: true, position: "left" }).addTo(map); sidebar.toggle(); /* Highlight search box text on click */ $("#searchbox").click(function () { $(this).select(); }); /* Placeholder hack for IE */ if (navigator.appName == "Microsoft Internet Explorer") { $("input").each(function () { if ($(this).val() === "" && $(this).attr("placeholder") !== "") { $(this).val($(this).attr("placeholder")); $(this).focus(function () { if ($(this).val() === $(this).attr("placeholder")) $(this).val(""); }); $(this).blur(function () { if ($(this).val() === "") $(this).val($(this).attr("placeholder")); }); } }); } $(function(){ var popup = { init : function() { // position popup windowW = $(window).width(); $("#map").on("mousemove", function(e) { var x = e.pageX + 20; var y = e.pageY; var windowH = $(window).height(); if (y > (windowH - 100)) { var y = e.pageY - 100; } else { var y = e.pageY - 20; } $("#info").css({ "left": x, "top": y }); }); } }; popup.init(); })
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('commentator', 'Unit | Model | commentator', { // Specify the other units that are required for this test. needs: [] }); test('it exists', function(assert) { let model = this.subject(); // let store = this.store(); assert.ok(!!model); });
const fs = require('fs') const { normalize, resolve, join, sep } = require('path') function getAppDir () { let dir = process.cwd() while (dir.length && dir[dir.length - 1] !== sep) { if (fs.existsSync(join(dir, 'quasar.conf.js'))) { return dir } dir = normalize(join(dir, '..')) } const { fatal } = require('./helpers/logger') fatal(`Error. This command must be executed inside a Quasar v1+ project folder.`) } const appDir = getAppDir() const cliDir = resolve(__dirname, '..') const srcDir = resolve(appDir, 'src') const pwaDir = resolve(appDir, 'src-pwa') const ssrDir = resolve(appDir, 'src-ssr') const cordovaDir = resolve(appDir, 'src-cordova') const capacitorDir = resolve(appDir, 'src-capacitor') const electronDir = resolve(appDir, 'src-electron') const bexDir = resolve(appDir, 'src-bex') module.exports = { cliDir, appDir, srcDir, pwaDir, ssrDir, cordovaDir, capacitorDir, electronDir, bexDir, resolve: { cli: dir => join(cliDir, dir), app: dir => join(appDir, dir), src: dir => join(srcDir, dir), pwa: dir => join(pwaDir, dir), ssr: dir => join(ssrDir, dir), cordova: dir => join(cordovaDir, dir), capacitor: dir => join(capacitorDir, dir), electron: dir => join(electronDir, dir), bex: dir => join(bexDir, dir) } }
module.exports = { testClient: 'http://localhost:8089/dist/', mochaTimeout: 10000, testLayerIds: [0], seleniumTimeouts: { script: 5000, implicit: 1000, pageLoad: 5000 } }
'use strict'; import Maths from './maths.js' import FSM from './fsm.js' import { Animation, Interpolation } from './animation.js' export { Maths, FSM, Interpolation, Animation }
// Runs the wiki on port 80 var server = require('./server'); server.run(80);
var Type = require("@kaoscript/runtime").Type; module.exports = function(expect) { class Shape { constructor() { this.__ks_init(); this.__ks_cons(arguments); } __ks_init_0() { this._color = ""; } __ks_init() { Shape.prototype.__ks_init_0.call(this); } __ks_cons_0(color) { if(arguments.length < 1) { throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)"); } if(color === void 0 || color === null) { throw new TypeError("'color' is not nullable"); } else if(!Type.isString(color)) { throw new TypeError("'color' is not of type 'String'"); } this._color = color; } __ks_cons(args) { if(args.length === 1) { Shape.prototype.__ks_cons_0.apply(this, args); } else { throw new SyntaxError("Wrong number of arguments"); } } __ks_func_color_0() { return this._color; } color() { if(arguments.length === 0) { return Shape.prototype.__ks_func_color_0.apply(this); } throw new SyntaxError("Wrong number of arguments"); } __ks_func_draw_0() { return "I'm drawing a " + this._color + " rectangle."; } draw() { if(arguments.length === 0) { return Shape.prototype.__ks_func_draw_0.apply(this); } throw new SyntaxError("Wrong number of arguments"); } } Shape.prototype.__ks_cons_1 = function() { this._color = "red"; }; Shape.prototype.__ks_cons = function(args) { if(args.length === 0) { Shape.prototype.__ks_cons_1.apply(this); } else if(args.length === 1) { Shape.prototype.__ks_cons_0.apply(this, args); } else { throw new SyntaxError("Wrong number of arguments"); } } let shape = new Shape(); expect(shape.draw()).to.equals("I'm drawing a red rectangle."); };
'use strict' angular .module('softvApp') .controller('ModalAddhubCtrl', function (clusterFactory, tapFactory, $rootScope, areaTecnicaFactory, $uibModalInstance, opcion, ngNotify, $state) { function init() { if (opcion.opcion === 1) { vm.blockForm2 = true; muestraColonias(); muestrarelaciones(); vm.Titulo = 'Nuevo HUB'; } else if (opcion.opcion === 2) { areaTecnicaFactory.GetConHub(opcion.id, '', '', 3).then(function (data) { console.log(); vm.blockForm2 = false; var hub = data.GetConHubResult[0]; vm.Clv_Txt = hub.Clv_txt; vm.Titulo = 'Editar HUB - '+hub.Clv_txt; vm.Descripcion = hub.Descripcion; vm.clv_hub = hub.Clv_Sector; muestraColonias(); muestrarelaciones(); }); } else if (opcion.opcion === 3) { areaTecnicaFactory.GetConHub(opcion.id, '', '', 3).then(function (data) { vm.blockForm2 = true; vm.blocksave = true; var hub = data.GetConHubResult[0]; vm.Clv_Txt = hub.Clv_txt; vm.Titulo = 'Consultar HUB - '+hub.Clv_txt; vm.Descripcion = hub.Descripcion; vm.clv_hub = hub.Clv_Sector; muestraColonias(); muestrarelaciones(); }); } } function muestraColonias() { areaTecnicaFactory.GetMuestraColoniaHub(0, 0, 0) .then(function (data) { vm.colonias = data.GetMuestraColoniaHubResult; }); } function AddSector() { if (opcion.opcion === 1) { areaTecnicaFactory.GetNueHub(0, vm.Clv_Txt, vm.Descripcion).then(function (data) { if (data.GetNueHubResult > 0) { vm.clv_hub = data.GetNueHubResult; ngNotify.set('El HUB se ha registrado correctamente ,ahora puedes agregar la relación con las colonias', 'success'); $rootScope.$broadcast('reloadlista'); vm.blockForm2 = false; vm.blocksave = true; } else { ngNotify.set('La clave del HUB ya existe', 'error'); } }); } else if (opcion.opcion === 2) { areaTecnicaFactory.GetModHub(vm.clv_hub, vm.Clv_Txt, vm.Descripcion).then(function (data) { console.log(data); ngNotify.set('El HUB se ha editado correctamente', 'success'); $rootScope.$broadcast('reloadlista'); $uibModalInstance.dismiss('cancel'); }); } } function cancel() { $uibModalInstance.dismiss('cancel'); } function validaRelacion(clv) { var count = 0; vm.RelColonias.forEach(function (item) { count += (item.IdColonia === clv) ? 1 : 0; }); return (count > 0) ? true : false; } function NuevaRelacionSecColonia() { if (validaRelacion(vm.Colonia.IdColonia) === true) { ngNotify.set('La relación HUB-COLONIA ya esta establecida', 'warn'); return; } areaTecnicaFactory.GetNueRelHubColonia(vm.clv_hub, vm.Colonia.IdColonia) .then(function (data) { muestrarelaciones(); ngNotify.set('se agrego la relación correctamente', 'success'); }); } function muestrarelaciones() { areaTecnicaFactory.GetConRelHubColonia(vm.clv_hub) .then(function (rel) { console.log(rel); vm.RelColonias = rel.GetConRelHubColoniaResult; }); } function deleterelacion(clv) { clusterFactory.GetQuitarEliminarRelClusterSector(2, vm.clv_cluster, clv).then(function (data) { ngNotify.set('Se eliminó la relación correctamente', 'success'); muestrarelaciones(); }); } var vm = this; init(); vm.cancel = cancel; vm.clv_hub = 0; vm.RelColonias = []; vm.AddSector = AddSector; vm.NuevaRelacionSecColonia = NuevaRelacionSecColonia; });
'use strict'; var path = require('path'); var fs = require('fs'); module.exports = function(gen,cb) { var sections; if (gen.config.get('framework')==='bigwheel') { var model = require(path.join(process.cwd(),'src/model/index.js')); sections = ['Preloader']; Object.keys(model).forEach(function(key) { if (key.charAt(0)==="/") sections.push(key.substr(1) || 'Landing'); }); } else { sections = ['Landing']; } nextSection(sections,gen,cb); }; function nextSection(arr,gen,cb) { if (arr.length>0) { createSection(arr.shift(),gen,function() { nextSection(arr,gen,cb); }); } else { if (cb) cb(); } } function createSection(cur,gen,cb) { var name = gen.config.get('sectionNames') ? '{{section}}.js' : 'index.js'; var style = gen.config.get('sectionNames') ? '{{section}}.{{css}}' : 'style.{{css}}'; var count = 0; var total = 0; var done = function() { count++; if (count>=total) cb(); }; fs.stat('src/sections/'+cur+'/',function(err,stat) { if (err) { gen.config.set('section',cur); if (gen.config.get('framework')==='bigwheel') { var type = cur==='Preloader' ? 'preloader' : 'normal'; gen.copy('templates/sections/{{framework}}/'+type+'/index.js','src/sections/{{section}}/'+name,done); gen.copy('templates/sections/{{framework}}/'+type+'/style.css','src/sections/{{section}}/'+style,done); gen.copy('templates/sections/{{framework}}/'+type+'/template.hbs','src/sections/{{section}}/template.hbs',done); gen.copy('templates/.gitkeep','src/ui/{{section}}/.gitkeep',done); total += 4; } else if (gen.config.get('framework')==='react') { gen.copy('templates/sections/{{framework}}/index.js','src/sections/{{section}}/'+name,done); gen.copy('templates/sections/{{framework}}/style.css','src/sections/{{section}}/'+style,done); total += 2; } } else { done(); } }); };
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('pillzApp')); var MainCtrl, scope, $httpBackend; // Initialize the controller and a mock scope beforeEach(inject(function (_$httpBackend_, $controller, $rootScope) { $httpBackend = _$httpBackend_; $httpBackend.expectGET('/api/awesomeThings') .respond(['HTML5 Boilerplate', 'AngularJS', 'Karma', 'Express']); scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings).toBeUndefined(); $httpBackend.flush(); expect(scope.awesomeThings.length).toBe(4); }); });
'use strict'; var assert = require('power-assert'); var resetStorage = require('./'); var dbName = 'test-item'; describe('#localStorage', function () { beforeEach(function (done) { localStorage.clear(); done(); }); it('should save value', function () { var expected = { foo: 'bar', goo: 'nuu' }; localStorage.setItem('item', JSON.stringify(expected)); assert.deepEqual(expected, JSON.parse(localStorage.getItem('item'))); }); it('should clear value', function (done) { var input = { foo: 'bar', goo: 'nuu' }; localStorage.setItem('item', JSON.stringify(input)); resetStorage .localStorage() .then(function () { assert.equal(null, localStorage.getItem('item')); done(); }); }); }); describe('#indexedDB', function () { var db; beforeEach(function (done) { var req = indexedDB.deleteDatabase('test-item'); req.onsuccess = function() { done(); }; }); // http://dev.classmethod.jp/ria/html5/html5-indexed-database-api/ it('should save value', function (done) { if (!indexedDB) { throw new Error('Your browser doesn\'t support a stable version of IndexedDB.'); } var openRequest = indexedDB.open(dbName, 2); var key = 'foo'; var value = 'bar'; var expected = {}; expected[key] = value; openRequest.onerror = function(event) { throw new Error(event.toString); }; openRequest.onupgradeneeded = function(event) { db = event.target.result; var store = db.createObjectStore('mystore', { keyPath: 'mykey'}); store.createIndex('myvalueIndex', 'myvalue'); }; openRequest.onsuccess = function() { db = openRequest.result; var transaction = db.transaction(['mystore'], 'readwrite'); var store = transaction.objectStore('mystore'); var request = store.put({ mykey: key, myvalue: value }); request.onsuccess = function () { var transaction = db.transaction(['mystore'], 'readwrite'); var store = transaction.objectStore('mystore'); var request = store.get(key); request.onsuccess = function (event) { assert.equal(value, event.target.result.myvalue); db.close(); done(); }; request.onerror = function (event) { db.close(); throw new Error(event.toString); }; }; request.onerror = function(event) { db.close(); throw new Error(event.toString); }; }; }); it.skip('should clear value. Writing this test is too hard for me.', function (done) { if (true) {// eslint-disable-line no-constant-condition throw new Error(); } if (!indexedDB) { throw new Error('Your browser doesn\'t support a stable version of IndexedDB.'); } var openRequest = indexedDB.open(dbName, 2); var key = 'foo'; var value = 'bar'; var expected = {}; expected[key] = value; openRequest.onerror = function(event) { throw new Error(event.toString); }; openRequest.onupgradeneeded = function(event) { db = event.target.result; var store = db.createObjectStore('mystore', { keyPath: 'mykey'}); store.createIndex('myvalueIndex', 'myvalue'); }; openRequest.onsuccess = function() { db = openRequest.result; var transaction = db.transaction(['mystore'], 'readwrite'); var store = transaction.objectStore('mystore'); var request = store.put({ mykey: key, myvalue: value }); request.onsuccess = function () { db.close(); var openRequest = indexedDB.open(dbName, 2); openRequest.onerror = function(event) { throw new Error(event.toString); }; openRequest.onsuccess = function() { var db = openRequest.result; var transaction = db.transaction(['mystore'], 'readwrite'); var store = transaction.objectStore('mystore'); var request = store.get(key); request.onsuccess = function (event) { assert.equal(value, event.target.result.myvalue); db.close(); done(); }; request.onerror = function (event) { db.close(); throw new Error(event.toString); }; }; }; request.onerror = function(event) { db.close(); throw new Error(event.toString); }; }; }); });
import React from 'react' import DocumentTitle from 'react-document-title' import ReactHeight from 'react-height' import Header from './header/header' import Content from './content/content' import Footer from './footer/footer' import { APP_NAME } from '../constants' class Layout extends React.Component { render() { const hfStyle = { flex: 'none' } const contentStyle = { flex: 1 } const containerStyle = { display: 'flex', minHeight: window.innerHeight, flexDirection: 'column' } return ( <div style={containerStyle}> <DocumentTitle title={APP_NAME}/> <Header style={hfStyle}/> <Content style={contentStyle}/> <Footer style={hfStyle}/> </div> ) } } export default Layout
var i18n = require('i18n'); var _ = require('lodash'); exports.register = function (plugin, options, next) { i18n.configure(options); plugin.ext('onPreResponse', function (request, extNext) { // If is an error message if(request.response.isBoom) { i18n.setLocale(getLocale(request, options)); request.response.output.payload.message = i18n.__(request.response.output.payload.message); return extNext(request.response); } extNext(); }); next(); }; var getLocale = function(request, options) { i18n.init(request.raw.req); if(_.contains(_.keys(i18n.getCatalog()), request.raw.req.language)) { return request.raw.req.language; } else { return options.defaultLocale; } };
import expect from 'expect'; import createStore from './createStore'; describe('createStore()', () => { let store; beforeEach(() => { store = createStore(); }); it('should write data and return its key when write() is called', () => { const hash = store.write({ hello: 'world' }); expect(hash).toBe(store.keys()[0]); }); it('should return data when read() is called with a valid key', () => { const hash = store.write({ hello: 'world' }); expect(store.read(hash)).toEqual({ hello: 'world' }); }); it('should throw an error when read() is called with an invalid key', () => { store.write({ hello: 'world' }); expect(() => store.read('wrong')).toThrow(/Entry wrong not found/); }); it('should return all keys when keys() is called', () => { const hash1 = store.write({ hello: 'world' }); const hash2 = store.write({ hello2: 'world2' }); expect(store.keys()).toEqual([ hash1, hash2, ]); }); it('should return all store content when toJSON() is called', () => { const hash1 = store.write({ hello: 'world' }); const hash2 = store.write({ hello2: 'world2' }); expect(store.toJSON()).toEqual({ [hash1]: { hello: 'world', }, [hash2]: { hello2: 'world2', }, }); }); it('should init the store if a snapshot is given', () => { const localStore = createStore({ ae3: { hello: 'world', }, }); expect(localStore.read('ae3')).toEqual({ hello: 'world', }); }); it('should write data with the given hash if provided', () => { const hash = store.write({ hello: 'world' }, 'forcedHash'); expect(hash).toBe('forcedHash'); expect(store.keys()[0]).toBe('forcedHash'); expect(store.read('forcedHash')).toEqual({ hello: 'world' }); }); it('should notify any subscriber when something is written into the store', () => { const subscriber1 = expect.createSpy(); store.subscribe(subscriber1); const subscriber2 = expect.createSpy(); store.subscribe(subscriber2); const hash = store.write({ hello: 'world' }); expect(subscriber1).toHaveBeenCalledWith(hash); expect(subscriber2).toHaveBeenCalledWith(hash); store.unsubscribe(subscriber1); const hash2 = store.write({ hello: 'earth' }); expect(subscriber1.calls.length).toBe(1); expect(subscriber2).toHaveBeenCalledWith(hash2); expect(subscriber2.calls.length).toBe(2); }); });
var xml = require('xmlbuilder'); var fs = require('fs'); /** * Function is used to create plis file which is required for downloading ios app. * @param {string} name app name * @param {string} path path to application * @param {string} title title for alert * @param {Function} callback function which will be called when plist file is created */ function creatPlist(name, path, title, callback){ var d = xml.create('plist', {'version':'1.0'}) .ele('dict') .ele('key','items').up() .ele('array') .ele('dict') .ele('key','assets').up() .ele('array') .ele('dict') .ele('key','kind').up() .ele('string','software-package').up() .ele('key','url').up() .ele('string',path).up() .up() .up() .ele('key','metadata').up() .ele('dict') .ele('key','bundle-identifier').up() .ele('string', name).up() .ele('key', 'kind').up() .ele('string','software').up() .ele('key','title').up() .ele('string', title) .up() .up() .up() .up() .up() .end({ pretty: true}); //generate unique file path:) use this for now. var filePath = './processing/file' + new Date().getMilliseconds() + '.plist'; fs.writeFile(filePath, d, function(err){ callback(err,filePath); }); console.log(xml); } //--------------EXPORTS---------------// exports.creatPlist = creatPlist;
'use strict'; define([], function($) { var Util = class { static charToLineCh(string, char) { var stringUpToChar = string.substr(0, char); var lines = stringUpToChar.split("\n"); return { line: lines.length - 1, ch: lines[lines.length - 1].length }; } }; return Util; });
'use strict'; angular.module('articles').controller('ChangeHeaderImageController', ['$scope', '$timeout', '$stateParams', '$window', 'Authentication', 'FileUploader', 'Articles', function ($scope, $timeout, $stateParams, $window, Authentication, FileUploader, Articles) { $scope.user = Authentication.user; $scope.article = Articles.get({ articleId: $stateParams.articleId }); $scope.imageURL = $scope.article.headerMedia || null; // Create file uploader instance $scope.uploader = new FileUploader({ url: 'api/articles/' + $stateParams.articleId + '/headerimage', alias: 'newHeaderImage' }); // Set file uploader image filter $scope.uploader.filters.push({ name: 'imageFilter', fn: function (item, options) { var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|'; return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; } }); // Called after the user selected a new picture file $scope.uploader.onAfterAddingFile = function (fileItem) { if ($window.FileReader) { var fileReader = new FileReader(); fileReader.readAsDataURL(fileItem._file); fileReader.onload = function (fileReaderEvent) { $timeout(function () { $scope.imageURL = fileReaderEvent.target.result; }, 0); }; } }; // Called after the article has been assigned a new header image $scope.uploader.onSuccessItem = function (fileItem, response, status, headers) { // Show success message $scope.success = true; // Populate user object $scope.user = Authentication.user = response; // Clear upload buttons $scope.cancelUpload(); }; // Called after the user has failed to upload a new picture $scope.uploader.onErrorItem = function (fileItem, response, status, headers) { // Clear upload buttons $scope.cancelUpload(); // Show error message $scope.error = response.message; }; // Change article header image $scope.uploadHeaderImage = function () { console.log($scope); // Clear messages $scope.success = $scope.error = null; // Start upload $scope.uploader.uploadAll(); }; // Cancel the upload process $scope.cancelUpload = function () { $scope.uploader.clearQueue(); //$scope.imageURL = $scope.article.profileImageURL; }; } ]);
/** @jsx h */ import h from '../../../helpers/h' import { Mark } from '../../../..' export default function(change) { change.addMark( Mark.create({ type: 'bold', data: { thing: 'value' }, }) ) } export const input = ( <value> <document> <paragraph> <anchor />w<focus />ord </paragraph> </document> </value> ) export const output = ( <value> <document> <paragraph> <anchor /> <b thing="value">w</b> <focus />ord </paragraph> </document> </value> )
import { Category } from '../../../stories/storiesHierarchy'; export const storySettings = { category: Category.COMPONENTS, storyName: 'ColorPicker', dataHook: 'storybook-colorpicker', };
process.env.NODE_ENV = 'test'; var chai = require('chai'); var chaihttp = require('chai-http'); chai.use(chaihttp); var expect = chai.expect; require(__dirname + '/../app.js'); describe('the error handler function', function() { it('should return a status of 500', function(done) { chai.request('localhost:3000') .get('/products/fish') .end(function(err, res) { expect(res).to.have.status(500); expect(JSON.stringify(res.body)).to.eql('{"msg":"ERROR!!"}'); done(); }); }); });
// "node scripts/create-package-app-test.js && node packages/app-test/synchronize.js && node packages/react-boilerplate-app-scripts/scripts/link-react-boilerplates.js && lerna bootstrap", 'use strict'; require('./create-package-app-test.js'); require('../packages/app-test/synchronize.js'); require('../packages/react-boilerplate-app-scripts/scripts/link-react-boilerplates.js'); const fs = require('fs-extra'); const path = require('path'); const execSync = require('child_process').execSync; try { //begin----加上packages/app-test const lernaJson = require('../lerna.json'); const packagesFolderName = 'packages/app-test'; if (lernaJson.packages.indexOf(packagesFolderName) === -1) { //可能中途ctr+c,导致包名没被删除 lernaJson.packages.push(packagesFolderName); } fs.writeFileSync( path.resolve(__dirname, '../lerna.json'), JSON.stringify(lernaJson, null, 2) ); //end----加上packages/app-test execSync('npm run lerna-bootstrap', { stdio: 'inherit' }); //begin----移除packages/app-test,发布的时候不会发布这个的,只是用来测试 if (lernaJson.packages.indexOf(packagesFolderName) !== -1) { lernaJson.packages.splice( lernaJson.packages.indexOf(packagesFolderName), 1 ); } fs.writeFileSync( path.resolve(__dirname, '../lerna.json'), JSON.stringify(lernaJson, null, 2) ); //end----移除packages/app-test,发布的时候不会发布这个的,只是用来测试 } catch (e) { console.log(e); }
'use strict'; var mongoose = require('mongoose'); var bcrypt = require('bcrypt'); var eat = require('eat'); var userSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true, trim: true }, username: { type: String, required: true, unique: true, trim: true }, biography: { type: String }, location: { type: String }, auth: { basic: { username: String, password: String } } }); userSchema.methods.hashPassword = function(password) { var hash = this.auth.basic.password = bcrypt.hashSync(password, 8); return hash; }; userSchema.methods.checkPassword = function(password) { return bcrypt.compareSync(password, this.auth.basic.password); }; userSchema.methods.generateToken = function(callback) { var id = this._id; eat.encode({id: id}, process.env.APP_SECRET, callback); }; module.exports = mongoose.model('User', userSchema);
version https://git-lfs.github.com/spec/v1 oid sha256:bf2580cc3dbb5c69564e5338a736b949ba7f1c7d567f37e58589d9f573c7abbb size 481
version https://git-lfs.github.com/spec/v1 oid sha256:e7cf7648766782e7940410a3abb8126a98b94e57bd61bfc7c1523679e8ce7ed6 size 26807
const UrlPathValidator = require('../../../services/validators/url-path-validator') const referenceIdHelper = require('../../helpers/reference-id-helper') const BenefitOwner = require('../../../services/domain/benefit-owner') const ValidationError = require('../../../services/errors/validation-error') const insertBenefitOwner = require('../../../services/data/insert-benefit-owner') const SessionHandler = require('../../../services/validators/session-handler') module.exports = function (router) { router.get('/apply/:claimType/new-eligibility/benefit-owner', function (req, res) { UrlPathValidator(req.params) const isValidSession = SessionHandler.validateSession(req.session, req.url) if (!isValidSession) { return res.redirect(SessionHandler.getErrorPath(req.session, req.url)) } return res.render('apply/new-eligibility/benefit-owner', { claimType: req.session.claimType, dob: req.session.dobEncoded, relationship: req.session.relationship, benefit: req.session.benefit, referenceId: req.session.referenceId }) }) router.post('/apply/:claimType/new-eligibility/benefit-owner', function (req, res, next) { UrlPathValidator(req.params) const isValidSession = SessionHandler.validateSession(req.session, req.url) if (!isValidSession) { return res.redirect(SessionHandler.getErrorPath(req.session, req.url)) } const benefitOwnerBody = req.body try { const benefitOwner = new BenefitOwner( req.body.FirstName, req.body.LastName, req.body['dob-day'], req.body['dob-month'], req.body['dob-year'], req.body.NationalInsuranceNumber) const referenceAndEligibilityId = referenceIdHelper.extractReferenceId(req.session.referenceId) return insertBenefitOwner(referenceAndEligibilityId.reference, referenceAndEligibilityId.id, benefitOwner) .then(function () { return res.redirect(`/apply/${req.params.claimType}/new-eligibility/about-you`) }) .catch(function (error) { next(error) }) } catch (error) { if (error instanceof ValidationError) { return renderValidationError(req, res, benefitOwnerBody, error.validationErrors, false) } else { throw error } } }) } function renderValidationError (req, res, benefitOwnerBody, validationErrors, isDuplicateClaim) { return res.status(400).render('apply/new-eligibility/benefit-owner', { errors: validationErrors, isDuplicateClaim: isDuplicateClaim, claimType: req.session.claimType, dob: req.session.dobEncoded, relationship: req.session.relationship, benefit: req.session.benefit, referenceId: req.session.referenceId, benefitOwner: benefitOwnerBody }) }
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('memo-card', 'Integration | Component | memo card', { integration: true }); test('it renders', function(assert) { assert.expect(2); // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{memo-card}}`); assert.equal(this.$().text().trim(), ''); // Template block usage: this.render(hbs` {{#memo-card}} template block text {{/memo-card}} `); assert.equal(this.$().text().trim(), 'template block text'); });
module.exports = function (grunt) { grunt.initConfig({ less: { test: { src: 'test/test.less', dest: 'test/test.css' } } }) grunt.loadNpmTasks('grunt-contrib-less') grunt.registerTask('default', ['less']) }
(function () { 'use strict'; // Setting up route angular .module('app.users') .run(appRun); // appRun.$inject = ['$stateProvider']; /* @ngInject */ function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return [ { state: 'profile', config: { url: '/settings/profile', controller: 'SettingsController', controllerAs: 'vm', templateUrl: 'modules/users/views/settings/edit-profile.client.view.html' } }, { state: 'password', config: { url: '/settings/password', controller: 'SettingsController', controllerAs: 'vm', templateUrl: 'modules/users/views/settings/change-password.client.view.html' } }, { state: 'accounts', config: { url: '/settings/accounts', controller: 'SettingsController', controllerAs: 'vm', templateUrl: 'modules/users/views/settings/social-accounts.client.view.html' } }, { state: 'signup', config: { url: '/signup', controller: 'AuthenticationController', controllerAs: 'vm', templateUrl: 'modules/users/views/authentication/signup.client.view.html' } }, { state: 'signin', config: { url: '/signin', controller: 'AuthenticationController', controllerAs: 'vm', templateUrl: 'modules/users/views/authentication/signin.client.view.html' } }, { state: 'forgot', config: { url: '/password/forgot', controller: 'PasswordController', controllerAs: 'vm', templateUrl: 'modules/users/views/password/forgot-password.client.view.html' } }, { state: 'reset-invalid', config: { url: '/password/reset/invalid', controller: 'PasswordController', controllerAs: 'vm', templateUrl: 'modules/users/views/password/reset-password-invalid.client.view.html' } }, { state: 'reset-success', config: { url: '/password/reset/success', controller: 'PasswordController', controllerAs: 'vm', templateUrl: 'modules/users/views/password/reset-password-success.client.view.html' } }, { state: 'reset', config: { url: '/password/reset/:token', controller: 'PasswordController', controllerAs: 'vm', templateUrl: 'modules/users/views/password/reset-password.client.view.html' } } ]; } })();
'use strict'; const {app} = require('electron'); const appName = app.getName(); module.exports = { label: appName, submenu: [{ label: 'About ' + appName, role: 'about', params: { version: '1.0.0' } }, { type: 'separator' }, { label: 'Preferences', event: 'prefer', params: 'optional params' }, { type: 'separator' }, { label: 'Hide ' + appName, accelerator: 'Command+H', role: 'hide' }, { label: 'Hide Others', accelerator: 'Command+Shift+H', role: 'hideothers' }, { label: 'Show All', role: 'unhide' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click: () => app.quit() }] };
// Get all of our fake login data //var login = require('../login.json'); exports.view = function(req, res){ var goalname =req.params.goalname; res.render('add-milestone', {'time' : req.cookies.startTime, 'goalname': goalname}); }; exports.timePost = function(req,res){ var startTime = req.params.startTime; res.cookie('time', startTime, { maxAge: 900000 }); }
Template.index.onCreated( () => { let template = Template.instance(); template.autorun(()=> { template.subscribe('wishList'); }); }); Template.index.helpers({ contentReady() { return Template.instance().subscriptionsReady(); }, wishItems() { return Wish.find().fetch(); } });
jQuery(document).ready(function($){$(".slide8").remove();});
var throttle = require( "../throttle" ); // Fire callback at end of detection period var func = throttle(function() { // Do stuff here console.log( "throttled" ); }, 200 ); func();
version https://git-lfs.github.com/spec/v1 oid sha256:e1af4eb3952e50a1690c1d45f20c988b688e49f11938afc9f62e5384f71aaebb size 7470