text
stringlengths
2
6.14k
module.exports = { name: 'segony', version: '0.0.1', php: { 'minimum-stability': 'dev', 'require': { 'godmodelabs/segony-kernel': '*' } }, js: [ { path: 'jquery', origin: { type: 'bower', name: 'jquery', version: '2.1.1' }, modules: { 'jquery': { source: 'dist/jquery.min', shim: { exports: 'jQuery' }, global: true } } } ] };
function mediaEditController($scope, $routeParams, mediaResource, notificationsService) { if ($routeParams.create) { mediaResource.getScaffold($routeParams.id, $routeParams.doctype) .then(function (data) { $scope.contentLoaded = true; $scope.content = data; }); } else { mediaResource.getById($routeParams.id) .then(function (data) { $scope.contentLoaded = true; $scope.content = data; }); } $scope.files = []; $scope.addFiles = function (propertyId, files) { //this will clear the files for the current property and then add the new ones for the current property $scope.files = _.reject($scope.files, function (item) { return item.id == propertyId; }); for (var i = 0; i < files.length; i++) { //save the file object to the scope's files collection $scope.files.push({ id: propertyId, file: files[i] }); } }; //TODO: Clean this up and share this code with the content editor $scope.saveAndPublish = function (cnt) { mediaResource.saveMedia(cnt, $routeParams.create, $scope.files) .then(function (data) { $scope.content = data; notificationsService.success("Published", "Media has been saved and published"); }); }; //TODO: Clean this up and share this code with the content editor $scope.save = function (cnt) { mediaResource.saveMedia(cnt, $routeParams.create, $scope.files) .then(function (data) { $scope.content = data; notificationsService.success("Saved", "Media has been saved"); }); }; } angular.module("umbraco") .controller("Umbraco.Editors.MediaEditController", mediaEditController);
import * as note from 'audio/notes'; const ch1 = [[note.A3, note.F3], 1], ch2 = [note.C5, 0.5], ch3 = [note.B4, 0.5], ch4 = [note.G4, 0.5], ch5 = [[note.F4, note.A3, note.F3], [0.5, 1, 1]], ch6 = [note.E4, 0.25], ch7 = [note.G4, 0.25], ch8 = [note.A4, 0.25], ch9 = [note.F4, 0.25], ch10 = [note.F3, 0.25], ch11 = [note.E4, 0.5]; const canond = [ // Staff 1. [[note.E4, note.C4], 1], [[note.D4, note.G3], 1], [[note.C4, note.A3], 1], [[note.B3, note.E3], 1], ch1, [[note.G3, note.C3], 1], ch1, [[note.B3, note.G3], 1], // Staff 2. [[note.E6, note.G5, note.C5], 1], [[note.D6, note.B5, note.G4], 1], [[note.C6, note.A4], 1], [[note.B5, note.G5, note.E4], 1], [[note.A5, note.C5, note.F4], 1], [[note.G5, note.E5, note.C4], 1], [[note.A5, note.F5, note.F4], 1], [[note.B5, note.D5, note.G4], 1], // Staff 3. [[note.C5, note.C4, note.E4], [0.5, 1, 1]], ch2, [[note.D5, note.D4, note.G3], [0.5, 1, 1]], ch3, [[note.C5, note.E4, note.A4], [0.5, 1, 1]], [note.E5, 0.5], [[note.G5, note.E3], [0.5, 1, 1]], ch4, [[note.A4, note.A3, note.F3], [0.5, 1, 1]], [note.F4, 0.5], [[note.E4, note.C3], [0.5, 1, 1]], ch4, ch5, ch2, [[note.B4, note.B3, note.G3], [0.5, 1, 1]], ch4, // Staff 4. [[note.C4, note.E3, note.C3], [0.5, 1, 1]], ch6, ch7, [[note.G4, note.G2], [0.25, 1, 1]], ch8, ch7, ch9, [[note.E4, note.A2, note.C3], [0.75, 1, 1]], ch6, [[note.E4, note.G2, note.E2], [0.25, 1, 1]], ch9, ch6, [note.D4, 0.25], [[note.C4, note.A2, note.F2], [0.25, 1, 1]], [note.Bb3, 0.25], [note.A3, 0.25], [note.B3, 0.25], [[note.G3, note.E2, note.C2], [0.5, 1, 1]], [note.E3, 0.5], [[note.C3, note.A2, note.F2], [0.5, 1, 1]], ch10, [note.E3, 0.25], [[note.D3, note.B2, note.G2], [0.5, 1, 1]], [note.G3, 0.25], ch10, // Staff 5. [[``, note.E4, note.C4], [0.5, 1, 1]], ch2, [[note.D5, note.G3], [0.5, 1, 1]], ch3, [[note.C5, note.C4, note.A3], [0.5, 1, 1]], ch11, [[note.G4, note.B3, note.E3], [0.75, 1, 1]], ch8, ch5, [note.C4, 0.5], [[note.E4, note.G3, note.C3], [0.5, 1, 1]], ch4, ch5, ch11, [[note.D4, note.B3, note.G3], [0.5, 1, 1]], ch4, [[note.E4, note.C4, note.C3], [2, 2, 2]], ]; export default canond;
'use strict'; let _ = require('lodash'), moment = require('moment'), AgentManager = require('../../../../app/services').AgentManager; describe('GET /agent/clusters/:token', () => { db.sync(); db.create(['cluster', 'node']); let cluster, node, manager; beforeEach(() => { cluster = factory.buildSync('cluster'); return cluster.save().then(() => { node = factory.buildSync('runningNode', { cluster_id: cluster.id }); return node.save(); }).then(() => { manager = new AgentManager(node); }); }); context('when node is master', () => { beforeEach(() => { return node.update({ master: true }); }); it('returns running nodes addresses of its cluster', done => { api.agent(node).fetch().expect(200, (err, res) => { if (err) { return done(err); } manager.fetch().then(addresses => { expect(res.body).to.deep.equal(addresses); done(); }).catch(done); }); }); it('updates the cluster last_seen', done => { api.agent(node).fetch().expect(200, (err, res) => { if (err) { return done(err); } cluster.reload().then(() => { expect(moment(cluster.last_seen).fromNow()) .to.equal('a few seconds ago'); done(); }).catch(done); }); }); }); context('when node is slave', () => { beforeEach(() => { return node.update({ master: false }); }); it('returns a forbidden error', done => { api.agent(node).fetch().expect(403, done); }); }); context('when node no longer exists', () => { beforeEach(() => { return node.destroy(); }); it('returns a 404 not found', done => { api.agent(node).fetch().expect(404, done); }); }); context('when token is invalid', () => { it('returns a 401 unauthorized', done => { api.agent().fetch().expect(401, done); }); }) });
var app = {}; $(function() { app.picFilter = ""; /** * The basic Pic Model represents an image that can be * favorited or deleted as needed. */ var Pic = Backbone.Model.extend({ defaults: function() { return { title: "Untitled Photo", deleted: false, favorited: false, picId: Pics.nextPicId(), }; }, toggleFavorited: function() { this.save({favorited: !this.get("favorited")}); }, toggleDeleted: function() { this.save({deleted: !this.get("deleted")}); }, }); /** * A Collection of pictures: */ var PicSet = Backbone.Collection.extend({ model: Pic, localStorage: new Backbone.LocalStorage("picpik-backbone"), deleted: function() { return this.where({deleted: true}); }, favorited: function() { return this.where({favorited: true}); }, nextPicId: function() { if (!this.length) return 1; return (this.last().get('picId') % 4) + 1; }, comparator: 'order' }); var Pics = new PicSet; /** * The View object for a Picture in the grid. * The view object is a div */ var PicView = Backbone.View.extend({ tagName: "div", template: _.template($("#pic-template").html()), events: { "click .favorite" : "toggleFavorited", "click .delete" : "toggleDeleted", }, initialize: function() { this.listenTo(this.model, 'change', this.render); this.listenTo(this.model, 'destroy', this.remove); this.listenTo(this.model, 'visible', this.toggleVisible); }, render: function() { this.$el.html(this.template(this.model.toJSON())); this.$el.toggleClass('favorited', this.model.get('favorited')); this.toggleVisible(); return this; }, toggleFavorited: function() { this.model.toggleFavorited(); }, toggleDeleted: function() { this.$el.fadeOut(400, (function() { this.model.toggleDeleted(); }).bind(this)); }, toggleVisible: function() { if (this.isHidden()) { this.$el.hide(); } else { this.$el.show(); } }, isHidden: function() { console.log('Check isHidden'); var isDeleted = this.model.get('deleted'); var isFavorited = this.model.get('favorited'); console.log(isFavorited); return ( (!isFavorited && app.picFilter === "favorited") || (isDeleted && app.picFilter != "deleted") || (!isDeleted && app.picFilter === "deleted") ); }, }); /** * The top-level piece of UI for the App. */ var AppView = Backbone.View.extend({ el: $("#picpikapp"), statsTemplate: _.template($('#stats-template').html()), events: { "click #add-pic": "createPic" }, initialize: function() { this.listenTo(Pics, 'add', this.addOne); this.listenTo(Pics, 'reset', this.addAll); this.listenTo(Pics, 'all', this.render); this.listenTo(Pics, 'change:completed', this.filterOne); this.listenTo(Pics, 'filter', this.filterAll); this.$main = $('#main'); this.$footer = $('#footer-stats'); Pics.fetch(); }, render: function() { var deleted = Pics.deleted().length; var favorited = Pics.favorited().length; this.$footer.html(this.statsTemplate({ num_favorited: favorited, num_deleted: deleted })); this.$('#filters a').removeClass('selected') .filter('[href="#/' + (app.picFilter || '') + '"]') .addClass('selected'); }, addOne: function(pic) { var view = new PicView({model: pic}); this.$('#pic-grid').append(view.render().el); }, addAll: function() { Pics.each(this.addOne, this); }, filterOne: function (pic) { pic.trigger('visible'); }, filterAll: function() { Pics.each(this.filterOne, this); }, createPic: function(e) { console.log('create pic!'); Pics.create({title: "New Pic"}); }, }); var App = new AppView; var PicsRouter = Backbone.Router.extend({ routes: { '*filter': 'setFilter' }, setFilter: function (param) { app.picFilter = param || ''; Pics.trigger('filter'); } }); var PicPikRouter = new PicsRouter(); Backbone.history.start(); });
const webpack = require('webpack') const config = require('./webpack.base.config') config.plugins = [ ...config.plugins, new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }), new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.OccurrenceOrderPlugin() ] module.exports = config
$(".button-collapse").sideNav(); $(document).ready(function(){ $('select').material_select(); $('.datepicker').pickadate({ selectMonths: true, // Creates a dropdown to control month selectYears: 15, // Creates a dropdown of 15 years to control year format: "dd-mm-yyyy", onStart: function() { var date = new Date(); this.set('select', [date.getFullYear(), date.getMonth(), date.getDate()]); } }); }); function difficultySearchFilter(settings, data, dataIndex, obj) { if(difffield.length === 0) return true; var difficulty_id = obj[2]["@data-filter"]; var res = difffield.includes(difficulty_id); return res; }; function viewRoute(route_id) { $("#loading").show(); $.get("/Route/Details/" + route_id, function (data) { $(".modal-content").html(data); $("#loading").hide(); }).done(function () { history.pushState({ url: window.URL + "", modalclose:true }, "Details", "/Route/Details/" + route_id); setupReply(); $('#modal1').openModal({ complete: function () { history.back(-1); } }); }).fail(function() { $("#loading").hide(); Materialize.toast('Loading error!', 4500); }); } // Necessary for manual calls, as static loading will not call viewroute() function setupReply() { $(".show_reply_field a:link").click(function () { //This function is added to all comment-buttons. $(".show_reply_field").css("display", "inline"); $(".reply_field").css("display", "none"); $(this).parent().parent().children(".reply_field").css("display", "block"); }); } function togglemore() { var element = $('#long_content'); var size = element.css("max-height"); if (size === "300px") { element.css('max-height', "3000px"); $("#long_content button").html("Show Less"); } else { $("#long_content button").html("Show More"); element.css('max-height', "300px"); } } function langUpdate(id) { $("#lang_id").val(id); $("#lang_id").closest('form').submit(); } function initRouteTable() { table = $('.table').DataTable({ info: false, searching: true, lengthChange: false, pageLength: 50, paging: false, responsive: true, columnDefs: [ { "searchable": false, "targets": 2}, { "searchable": false, "targets": 3} ] }); } function initDefaultTable() { table = $('.table').DataTable({ info: false, searching: false, lengthChange: false, pageLength: 50, paging: false, responsive: true, ordering: false }); }
'use strict' const Rx = require('rx'); const R = require('ramda'); const uuid = require('uuid'); const config = require('./config'); const subjects = { order: new Rx.ReplaySubject(config.replayBufferSize, config.replayWindowSize), system: new Rx.ReplaySubject(config.replayBufferSize, config.replayWindowSize) } subjects.system.onNextError = function(error, payload = {}) { subjects.system.onNext(R.merge({ error, id: uuid.v4(), level: 'error', result: 'error', time: new Date() }, payload)); } subjects.system.onNextSuccess = function(payload = {}) { subjects.system.onNext(R.merge({ id: uuid.v4(), level: 'info', result: 'success', time: new Date() }, payload)); } //todo: create onNextError and onNextSuccess for systemSubject module.exports.orderSubject = subjects.order;//new Rx.ReplaySubject(config.replayBufferSize, config.replayWindowSize); module.exports.systemSubject = subjects.system;//new Rx.ReplaySubject(config.replayBufferSize, config.replayWindowSize);
var R = require('ramda'); var assert = require('assert'); var types = require('./types'); var jsv = require('jsverify'); var Maybe = require('..').Maybe; var MaybeGen = R.curry(function(a, n) { return n % 2 === 0 ? Maybe.Just(a.generator(n)) : Maybe.Nothing(); }); var MaybeShow = R.curry(function(a, m) { return (Maybe.isJust(m)) ? 'Just(' + a.show(m.value) + ')' : 'Nothing'; }); var MaybeShrink = R.curry(function(a, m) { return (Maybe.isJust(m)) ? [Maybe.Nothing()].concat(a.shrink(m.value).map(Maybe.Just)) : []; }); var MaybeArb = function(a) { return { generator: jsv.generator.bless(MaybeGen(a)), show: MaybeShow(a), shrink: jsv.shrink.bless(MaybeShrink(a)) }; }; describe('Maybe', function() { var m = MaybeArb(jsv.nat); var env = {Maybe: MaybeArb}; var appF = 'Maybe (nat -> nat)'; var appN = 'Maybe nat'; it('has an arbitrary', function() { var arb = jsv.forall(m, function(m) { return m instanceof Maybe; }); jsv.assert(arb); }); it('is a Functor', function() { var fTest = types.functor; jsv.assert(jsv.forall(m, fTest.iface)); jsv.assert(jsv.forall(m, fTest.id)); jsv.assert(jsv.forall(m, 'nat -> nat', 'nat -> nat', fTest.compose)); }); it('is an Apply', function() { var aTest = types.apply; jsv.assert(jsv.forall(m, aTest.iface)); jsv.assert(jsv.forall(appF, appF, appN, env, aTest.compose)); }); it('is an Applicative', function() { var aTest = types.applicative; jsv.assert(jsv.forall(m, aTest.iface)); jsv.assert(jsv.forall(appN, appN, env, aTest.id)); jsv.assert(jsv.forall(appN, 'nat -> nat', 'nat', env, aTest.homomorphic)); jsv.assert(jsv.forall(appN, appF, 'nat', env, aTest.interchange)); }); it('is a Chain', function() { var cTest = types.chain; var f = 'nat -> Maybe nat'; jsv.assert(jsv.forall(m, cTest.iface)); jsv.assert(jsv.forall(m, f, f, env, cTest.associative)); }); it('is a Monad', function() { var mTest = types.monad; jsv.assert(jsv.forall(m, mTest.iface)); }); }); describe('Maybe usage', function() { describe('checking for Just | Nothing', function() { it('should allow the user to check if the instance is a Nothing', function() { assert.equal(true, Maybe(null).isNothing()); assert.equal(false, Maybe(42).isNothing()); }); it('should allow the user to check if the instance is a Just', function() { assert.equal(true, Maybe(42).isJust()); assert.equal(false, Maybe(null).isJust()); }); it('can check the type statically', function() { var nada = Maybe.Nothing(); var just1 = Maybe.Just(1); assert.equal(Maybe.isJust(nada), false); assert.equal(Maybe.isNothing(nada), true); assert.equal(Maybe.isJust(just1), true); assert.equal(Maybe.isNothing(just1), false); }); }); describe('#getOrElse', function() { it('should return the contained value for if the instance is a Just', function() { assert.equal(42, Maybe(42).getOrElse(24)); }); it('should return the input value if the instance is a Nothing', function() { assert.equal(24, Maybe(null).getOrElse(24)); }); }); describe('#toString', function() { it('returns the string representation of a Just', function() { assert.strictEqual(Maybe.Just([1, 2, 3]).toString(), 'Maybe.Just([1, 2, 3])'); }); it('returns the string representation of a Nothing', function() { assert.strictEqual(Maybe.Nothing().toString(), 'Maybe.Nothing()'); }); }); });
$j.ready(function() { var text = "Thank you for downloading jCombo. For more info on how to get started, please visit <a href=\"http://jcombo.com/\">http://jcombo.com/</a>."; $(document.body).html('<div style="padding:20px;">' + text + '</div>'); });
angular.module('app').controller('GameCtrl', ['$location', '$scope', '$ocModal', 'Fight', 'Monster', 'GameData', '$log', function GameCtrl($location, $scope, $ocModal, Fight, Monster, GameData, $log) { // Set controllerAs var game = this; game.$log = $log; // Setup resources game.fight = new Fight(); game.monster = new Monster(); // Export functions game.loadFight = loadFight; // Setup empty error game.errorShow = false; game.errorMessage = ''; // Init data and watch for changes game.user = GameData.getUserData(); $scope.$watch(function () {return GameData.getUserData(); }, function (newValue, oldValue) { if (newValue !== oldValue) { game.user = newValue; } }, true); // Gets a fight with a random monster, sets the data, and sends to fight function loadFight() { Fight.get(game.fight, function success(fight){ GameData.setFightData(fight); Monster.get({monsterId: fight.monsterId}, function(monster) { GameData.setMonsterData(monster); $location.path('fight'); }); }, function error (err) { game.errorShow = true; game.errorMessage = err.data; }); } }]); //Setup resource for signing up for an account angular.module('app').factory('Fight', ['APIDOMAIN', '$resource', function(APIDOMAIN, $resource) { return $resource(APIDOMAIN + '/fights/random'); }]); //Setup resource for signing up for an account angular.module('app').factory('Monster', ['APIDOMAIN', '$resource', function(APIDOMAIN, $resource) { return $resource(APIDOMAIN + '/monsters/:monsterId', {monsterId: '@id'}); }]);
module.exports = { AcceptedValues: require('./accepted_values'), Attribute: require('./attribute'), Manual: require('./manual'), RegularExpression: require('./regular_expression'), Require: require('./require') }
function getDirective() { return { restrict: 'E', transclude: true, template: '<a class="tabs-link" ui-sref="tabs.tab({label: item.label })" ui-sref-active="active-tab"><ng-transclude></ng-transclude></a>' } } export default angular.module('directives.tabsDirective', []) .directive('directive', getDirective)
/* global describe, it */ const expect = require('chai').expect const label = require('../../src/validators/label') describe('LABEL validator', () => { it('should accept single line LABEl directives', () => { const state = label('"com.example.vendor"="ACME Incorporated"') expect(state).to.have.an('object') expect(state).to.have.deep.property('valid', true) }) it('should accept single line with multiple LABEL directives', () => { const state = label('multi.label1="value1" multi.label2="value2" other="value3"') expect(state).to.have.an('object') expect(state).to.have.deep.property('valid', true) }) it('should accept multiple line LABEL directives', () => { const state = label('["multi.label1=\'value1\'", "multi.label2=\'value2\'", "other=\'value3\'"]') expect(state).to.have.an('object') expect(state).to.have.deep.property('valid', true) }) })
'use strict'; angular.module('myApp.view2', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/view2', { templateUrl: 'view2/view2.html', controller: 'ItemCont' }) .when('/allItems2',{ templateUrl: 'view2/allItems2.html', controller: 'ItemCont' }) .when('/item2/:number',{ templateUrl: 'view2/itemDet2.html', controller: 'ItemCont' }) .when('/addItem2',{ templateUrl: 'view2/addItem2.html', controller: 'ItemCont' }) .when('/addItem2/:number',{ templateUrl: 'view2/addItem2.html', controller: 'ItemCont' }) .when('/printViewBasTwo',{ templateUrl: 'view2/printViewBasketTwo.html', controller: 'ItemCont' }); }]) //controller passes the methods/functions to to frontend for access via $scope //parameters to the routes are also given functionality .controller('ItemCont',['$scope','$routeParams',"ItemsFactory", function($scope, $routeParams, ItemsFactory){ //two baskets are hardcoded as follows var items2 = [ {name: "Item1",value : 20,qty:3}, {name: "Item2",value: 5,qty:2}, {name: "Item3",value : 10,qty:4} ]; $scope.itemList2=ItemsFactory.getItems2; $scope.delItems2=ItemsFactory.delItems2; $scope.addEditItem2=ItemsFactory.addEditItem2; $scope.getSerialValueA=ItemsFactory.getSerialValueA; $scope.getSubTotalA=ItemsFactory.getSubTotalA; $scope.getTotalA=ItemsFactory.getTotalA; if(angular.isDefined($routeParams.number)){ var ida = $routeParams.number; var list1=$scope.itemList2(); for (var j=0;j<list1.length;j++) { if(ida === list1[j].name){ $scope.foundItem2=list1[j]; break;} } } }]);
import { baseUniDriverFactory } from 'wix-ui-test-utils/base-driver'; export const dividerDriverFactory = base => { return { ...baseUniDriverFactory(base), }; };
/*global describe, expect, fallback, it*/ describe('tests.unit.core.isFunction', function() { it('should be a Function', function() { var test = fallback.isFunction; expect(test).to.be.a('function'); }); it('to always return a Boolean', function() { var test = fallback.isFunction(); expect(typeof test).to.equal('boolean'); }); it('null should return false.', function() { expect(fallback.isFunction(null)).to.equal(false); }); it('undefined should return false.', function() { expect(fallback.isFunction(undefined)).to.equal(false); }); it('Array should return false.', function() { expect(fallback.isFunction([])).to.equal(false); }); it('String should return false.', function() { expect(fallback.isFunction('String')).to.equal(false); }); it('Number should return false.', function() { expect(fallback.isFunction(0)).to.equal(false); }); it('Object should return false.', function() { expect(fallback.isFunction({})).to.equal(false); }); it('Boolean of false should return false.', function() { expect(fallback.isFunction(false)).to.equal(false); }); it('Boolean of true should return false.', function() { expect(fallback.isFunction(true)).to.equal(false); }); it('Function should return true.', function() { expect(fallback.isFunction(function() {})).to.equal(true); }); });
import React from 'react' import { connect } from 'react-redux' import styled from 'styled-components' import { Sequence } from '../../components/Sequence' const Container = styled.div` text-align: center; ` const PrimerPreviewSmall = ({ strand, plasmidSegment, geneSegment, animatingPreview }) => { const displayBases = (bases = '') => bases.split('').map((l,i) => <span className="l" key={i}>{l}</span> ) const activeClass = animatingPreview ? 'active' : '' if(strand === 'reverse') { return ( <Container className={`primer-preview primer-preview-reverse ` + activeClass}> <Sequence className='RV'> <span className='prime-5 l'>5</span> <span className='prime-5 l'>-</span> {displayBases(plasmidSegment)} </Sequence> <Sequence className='RG'> {displayBases(geneSegment)} <span className='prime-3 l'>-</span> <span className='prime-3 l'>3</span> </Sequence> </Container> ) } if(strand === 'forward') { // doing a double if because I dont like silent errors. return ( <Container> <Sequence className='FV'> <span className='prime-5'>5</span> <span className='prime-5'>-</span> {displayBases(plasmidSegment)} </Sequence> <Sequence className='FG'> {displayBases(geneSegment)} <span className='prime-3'>-</span> <span className='prime-3'>3</span> </Sequence> </Container> ) } } const mapStateToProps = ({formInputs, animatingPreview }, ownProps) => { const plasmidSegment = ownProps.strand === 'forward' ? 'FV' : 'RV' const geneSegment = ownProps.strand === 'forward' ? 'FG' : 'RG' return { strand: ownProps.strand, plasmidSegment: formInputs[plasmidSegment], geneSegment: formInputs[geneSegment], animatingPreview } } export default connect(mapStateToProps)(PrimerPreviewSmall)
var searchData= [ ['woeidfromcordi',['woeidfromcordi',['../namespacewoeidfromcordi.html',1,'']]], ['woeidfromcordi_2epy',['woeidfromcordi.py',['../woeidfromcordi_8py.html',1,'']]], ['woeidfromquery',['woeidfromquery',['../namespacewoeidfromquery.html',1,'']]], ['woeidfromquery_2epy',['woeidfromquery.py',['../woeidfromquery_8py.html',1,'']]], ['writefutureweather',['writefutureweather',['../namespacewritefutureweather.html',1,'']]], ['writefutureweather_2epy',['writefutureweather.py',['../writefutureweather_8py.html',1,'']]], ['writepastweather',['writepastweather',['../namespacewritepastweather.html',1,'']]], ['writepastweather_2epy',['writepastweather.py',['../writepastweather_8py.html',1,'']]] ];
import React from 'react' import "react-image-gallery/styles/css/image-gallery.css"; import ImageGallery from 'react-image-gallery'; /** * */ export default class PhotoComponent extends React.Component{ /** * render * @return {ReactElement} markup */ render(){ if (this.props===undefined || this.props.items===undefined) { return null; } return ( <div> <div style={{"margin":"5px"}}> <input placeholder="Search photos" onKeyPress={(e)=>{if (e.key==='Enter') this.props.handleSearch(e.target.value);}}/> </div> <div> <ImageGallery items={this.props.items} slideInterval={2000} onImageLoad={this.handleImageLoad} lazyLoad={true} autoPlay={true}/> </div> </div> ); } }
/** * This file/module contains all configuration for the build process. */ module.exports = { /** * The `build_dir` folder is where our projects are compiled during * development and the `compile_dir` folder is where our app resides once it's * completely built. */ build_dir: 'build', compile_dir: 'bin', /** * This is a collection of file patterns that refer to our app code (the * stuff in `src/`). These file paths are used in the configuration of * build tasks. `js` is all project javascript, less tests. `ctpl` contains * our reusable components' (`src/common`) template HTML files, while * `atpl` contains the same, but for our app's code. `html` is just our * main HTML file, `less` is our main stylesheet, and `unit` contains our * app's unit tests. */ app_files: { js: [ 'src/**/*.js', '!src/**/*.spec.js', '!src/assets/**/*.js' ], jsunit: [ 'src/**/*.spec.js' ], coffee: [ 'src/**/*.coffee', '!src/**/*.spec.coffee' ], coffeeunit: [ 'src/**/*.spec.coffee' ], atpl: [ 'src/app/**/*.tpl.html' ], ctpl: [ 'src/common/**/*.tpl.html' ], html: [ 'src/index.html' ], less: 'src/less/main.less' }, /** * This is a collection of files used during testing only. */ test_files: { js: [ 'vendor/angular-mocks/angular-mocks.js' ] }, /** * This is the same as `app_files`, except it contains patterns that * reference vendor code (`vendor/`) that we need to place into the build * process somewhere. While the `app_files` property ensures all * standardized files are collected for compilation, it is the user's job * to ensure non-standardized (i.e. vendor-related) files are handled * appropriately in `vendor_files.js`. * * The `vendor_files.js` property holds files to be automatically * concatenated and minified with our project source files. * * The `vendor_files.css` property holds any CSS files to be automatically * included in our app. * * The `vendor_files.assets` property holds any assets to be copied along * with our app's assets. This structure is flattened, so it is not * recommended that you use wildcards. */ vendor_files: { js: [ 'vendor/angular/angular.js', 'vendor/angular-bootstrap/ui-bootstrap-tpls.min.js', 'vendor/jquery/jquery.js', 'vendor/bootstrap/dist/js/bootstrap.js', 'vendor/placeholders/angular-placeholders-0.0.1-SNAPSHOT.min.js', 'vendor/angular-ui-router/release/angular-ui-router.js', // 'vendor/angular-ui-utils/modules/route/route.js' 'vendor/angular-resource/angular-resource.min.js', 'vendor/angular-cookies/angular-cookies.min.js' ], css: [ ], assets: [ ] }, };
'use strict'; const HttpStatus = require('http-status-codes'); const morgan = require('morgan'); const winston = require('winston'); const OPTIONS = { skip, stream: {write: loggging} }; module.exports = app => { app.use(morgan('common', OPTIONS)); }; function loggging(message) { return winston.warn(message); } function skip(req, res) { return res.statusCode < HttpStatus.BAD_REQUEST; }
/* * bucketdb * * Copyright(c) 2015 André König <andre.koenig@posteo.de> * MIT Licensed * */ /** * @author André König <andre.koenig@posteo.de> * */ 'use strict'; var debug = require('debug')('bucketdb:database'); var levelup = require('levelup'); var leveldown = require('leveldown'); var mandatory = require('mandatory'); var sublevel = require('level-sublevel'); var VError = require('verror'); var INSTANCE = null; var DB_PATH = null; function database () { if (!INSTANCE && DB_PATH) { debug('Create new LevelDB instance.'); INSTANCE = levelup(DB_PATH, { valueEncoding: 'json' }); } return INSTANCE; } var wrapper = module.exports = function wrapper (type) { mandatory(type).is('string', 'Please define a storage entity type.'); // // Create a sublevel of the LevelDB instance and pass it to // the storage service. With this approach it is possible to abstract the // whole sublevel aspects away. // // TODO: The `sublevel` activation can be moved to `database.getInstance` when // https://github.com/dominictarr/level-sublevel/issues/78 has been closed. // return sublevel(database()).sublevel(type); }; wrapper.setDatabasePath = function setDatabasePath (dbPath) { DB_PATH = dbPath; }; /** * Function for destroying the whole storage layer. * * @param {function} callback * Will be executed when the storage layer and the respective database has * been destroyed. Executed as `callback(err)`. * */ wrapper.destroy = function destroy (callback) { var db = null; mandatory(callback).is('function', 'Please provide a proper callback function.'); function onDestroy (err) { if (err) { return callback(new VError(err, 'failed to destroy the storage layer.')); } callback(null); } function onClose () { leveldown.destroy(DB_PATH, onDestroy); } db = database(); if (db) { return db.once('closed', onClose).close(); } onClose(); };
import Vue from 'vue' import Vuex from 'vuex' import actions from './actions' import mutations from './mutations' import getters from './getters' Vue.use(Vuex) export function createStore () { return new Vuex.Store({ state: { activeType: null, activePage: {/* [id: number]: Number */}, scrollPosition: {/* [id: string]: Number */}, itemsPerPage: 20, items: {/* [id: number]: Item */}, users: {/* [id: string]: User */}, lists: { top: [/* number */], new: [], show: [], ask: [], job: [] } }, actions, mutations, getters }) }
var domain = require(__dirname + "/src/wires-domain.js").domain; var a = [0, 1]; domain.each(a, function(item) { console.log(item); }).catch(function(e) { console.log(e.stack) })
class ClassExpression { constructor (options) { this.type = 'ClassExpression' Object.assign(this, options) } } module.exports = ClassExpression
'use strict'; import { Actions } from 'flummox'; import ApiUtils from '../utils/ApiUtils'; class WidgetActions extends Actions { getFile() { return ApiUtils.get('api/file'); } getTranscript() { return ApiUtils.get('api/fileTranscript'); } updateTime(time) { return time; } } export default WidgetActions;
var Twitter = require('passport-twitter').Strategy , User = require('./users') , tokens = require('./tokens') , config = { consumerKey: tokens.twitter_consumer_key, consumerSecret: tokens.twitter_consumer_secret, callbackURL: "/login" } function callback(token, tokenSecret, profile, done) { User.findOne({profile_id: profile.id}, function (err, user) { if (err) { throw err; } else if (user != null) { // User exists in database. return done(null, user) } else { // User doesn't exist in database, // so it will create a new one. var pic = profile.photos[0].value.replace(/_normal/, '') , usr = { profile_id: profile.id, name: profile.displayName, photo: pic } , register = new User(usr); register.save(function (err, user) { if (err) throw err; done(null, user) }) } }); } function passport(passport) { // Passport session setup. // To support persistent login sessions, Passport needs to be able to // serialize users into and deserialize users out of the session. Typically, // this will be as simple as storing the user ID when serializing, and finding // the user by ID when deserializing. However, since this example does not // have a database of user records, the complete Twitter profile is serialized // and deserialized. passport.serializeUser(function(user, done) { done(null, user); }); passport.deserializeUser(function(obj, done) { done(null, obj); }); passport.use(new Twitter(config, callback)); } module.exports = passport;
import { get } from 'ember-metal/property_get'; import run from 'ember-metal/run_loop'; import EmberView from 'ember-views/views/view'; import { compile } from 'ember-template-compiler'; import { registerHelper } from 'ember-htmlbars/helpers'; import buildOwner from 'container/tests/test-helpers/build-owner'; import { OWNER } from 'container/owner'; var owner, view; QUnit.module('EmberView - Layout Functionality', { setup() { owner = buildOwner(); owner.registerOptionsForType('template', { instantiate: false }); }, teardown() { run(function() { view.destroy(); owner.destroy(); }); owner = view = null; } }); QUnit.test('Layout views return throw if their layout cannot be found', function() { view = EmberView.create({ [OWNER]: { lookup() { } }, layoutName: 'cantBeFound' }); expectAssertion(function() { get(view, 'layout'); }, /cantBeFound/); }); import { test } from 'ember-glimmer/tests/utils/skip-if-glimmer'; test('should use the template of the associated layout', function() { var templateCalled = 0; var layoutCalled = 0; registerHelper('call-template', function() { templateCalled++; }); registerHelper('call-layout', function() { layoutCalled++; }); owner.register('template:template', compile('{{call-template}}')); owner.register('template:layout', compile('{{call-layout}}')); view = EmberView.create({ [OWNER]: owner, layoutName: 'layout', templateName: 'template' }); run(function() { view.createElement(); }); equal(templateCalled, 0, 'template is not called when layout is present'); equal(layoutCalled, 1, 'layout is called when layout is present'); }); test('should use the associated template with itself as the context', function() { owner.register('template:testTemplate', compile( '<h1 id=\'twas-called\'>template was called for {{personName}}</h1>' )); view = EmberView.create({ [OWNER]: owner, layoutName: 'testTemplate', context: { personName: 'Tom DAAAALE' } }); run(function() { view.createElement(); }); equal('template was called for Tom DAAAALE', view.$('#twas-called').text(), 'the named template was called with the view as the data source'); }); test('should fall back to defaultLayout if neither template nor templateName are provided', function() { var View = EmberView.extend({ defaultLayout: compile('used default layout') }); view = View.create(); run(function() { view.createElement(); }); equal('used default layout', view.$().text(), 'the named template was called with the view as the data source'); }); test('should not use defaultLayout if layout is provided', function() { var View = EmberView.extend({ layout: compile('used layout'), defaultLayout: compile('used default layout') }); view = View.create(); run(function() { view.createElement(); }); equal('used layout', view.$().text(), 'default layout was not printed'); });
/* * grunt-multisync * https://github.com/jaetask/multisync * * Copyright (c) 2013 Jae Task * Licensed under the MIT license. */ var utils = require('./utils.js'), _ = require('underscore'); 'use strict'; module.exports = { buildRsyncOptions: function(grunt, data) { var options = {}; var taskList = []; grunt.verbose.writeln('Generating '+ data.folders.length +' rsync tasks for multisync:' + data.taskName); for (var i = 0; i < data.folders.length; i++) { var counter = i+1; var folder = data.folders[i]; var dynamic = folder; // clone? var dynamicTaskName = data.taskName+'_'+counter; grunt.verbose.writeln('Folder pair ('+dynamicTaskName+')'); dynamic.src = data.drives.src+folder.src; dynamic.dest = data.drives.dest+folder.dest; grunt.verbose.writeln('- src: '+dynamic.src); grunt.verbose.writeln('- dest: '+dynamic.dest); // inject global options _.extend(dynamic,data.options || {}); options[dynamicTaskName] = {options: dynamic}; taskList.push("rsync:"+dynamicTaskName); } grunt.verbose.writeln('- rsync config set to:'); grunt.verbose.writeln(utils.jsonify(options)); grunt.verbose.writeln('- registered task with task list:'); grunt.verbose.writeln(utils.jsonify(taskList)); grunt.config.set('rsync', options); grunt.registerTask(data.taskName, taskList); grunt.task.run(data.taskName) } };
import isEmpty from 'lodash/isEmpty'; export function defaultTo(defaultValue) { return (v) => ( ! v) ? defaultValue : v; } export function toString(value) { if (value === undefined || value === null) { return ''; } return value.toString ? value.toString() : String(value); } export function toNumber(value) { if (isNaN(value)) { throw new Error(`Cannot transform ${value} into a number.`); } return Number(value); } export function toInteger(value) { if (isNaN(value)) { throw new Error(`Cannot transform ${value} into an integer.`); } return parseInt(value); } export function toFloat(value) { if (isNaN(value)) { throw new Error(`Cannot transform ${value} into a float.`); } return parseFloat(value); } export function toBoolean(value) { if (value !== true && value !== 'true' && value !== 'false' && value !== false) { throw new Error(`Cannot transform ${value} into a boolean.`) } return value === true || value === 'true'; } export function mapFrom(mapping) { if ( ! mapping) { throw new Error('The mapping cannot be null.'); } return (value) => { if ( ! mapping[value]) { throw new Error(`Cannot find value for ${value} in mapping.`); } return mapping[value]; }; } export function using(fn) { if ( ! fn) { throw new Error('The function to use cannot be null.'); } return (value) => fn(value); }
 // ********* TODO ********* // * Nothing :) var twit = require('twit'), fs = require('fs'), global_config = require('./config'), logger = require('./logger'), utils = require('./utils'), agg_twitter = require('./aggregators/aggregator-twitter'), url = require("url"); var email = require("emailjs/email"); var Tumblr = require('tumblrwks'); var aggregators = [agg_twitter]; var tumblr = null; function processInstagramPost(request, response) { /*if (response.statusCode == 200) { var keywordList = request.post.map(function (message, index, array) { return message.object_id; }); agg_instagram_new.pushNewKeywords(keywordList); } response.writeHead(200, "OK", { 'Content-Type': 'text/plain' }); response.end();*/ } RegExp.escape = function (str) { var specials = /[.*+?|()\[\]{}\\$^]/g; // .*+?|()[]{}\$^ return str.replace(specials, "\\$&"); } var pushMessage = function(message) { var keywords = require('./keywords'); var cleanedMessageText = message.Text keywords.list.forEach(function (element, index) { var regex = new RegExp("(" + RegExp.escape(element) + ")", "gi"); // replace case insensitive cleanedMessageText = cleanedMessageText.replace(regex, ''); }); // extract steam id var sid = cleanedMessageText.match(/sid(\d*)/g); if (sid && sid.length > 0 && sid[0].length > 3) { cleanedMessageText = cleanedMessageText.replace(/sid(\d*)/g, ""); sid = sid[0].substring(3, sid[0].length); } var tweetText = cleanedMessageText; var maxCharsToTweet = 111; // tweet functionality of tumblr only allows 111 characters.... var refundNotesUrl = "http://refundnotes.com"; var refundNotesTweetSuffix = " " + refundNotesUrl; var caractersToRemove = (tweetText.length + refundNotesTweetSuffix.length) - maxCharsToTweet; if (caractersToRemove > 0) { tweetText = tweetText.substring(0, tweetText.length - caractersToRemove - 3) + "..."; } tweetText += refundNotesTweetSuffix; // remove media after tweet text creation because to keep the media in the autotweet var mediaTag = ""; if (message.Media && message.Media.length > 0) { // if media is available remove the automatically added tweet link cleanedMessageText = cleanedMessageText.replace(/http.?:\/\/t\.co\/[A-Za-z0-9]*/g, ""); mediaTag = "<img src='" + message.Media + "'>"; } cleanedMessageText = cleanedMessageText.trim(); var body = ""; if (cleanedMessageText.length > 0) { body += cleanedMessageText; } body += mediaTag; var source = "<a href='http://twitter.com/" + message.UserName + "' ><img style='vertical-align:middle;margin:0px' src='" + message.UserImageURL + "'>&nbsp;<span style=''>" + message.UserName + "</span></a>"; var addSteamWidget = sid && sid.length > 0; if (addSteamWidget) { source += "<iframe src='http://store.steampowered.com/widget/" + sid + "/' style='margin-top:5px;' frameborder=0 width=646 height=190 ></iframe>"; } tumblr.post('/post', { type: 'quote', quote: body, source: source, tweet: tweetText, state: 'draft' }, function (err, json) { console.log(json); /*tumblr.post('/post/delete', { id: json.id }, function (err, json) { console.log(json); });*/ }); if (!global_config.debug || true) { var server = email.server.connect({ user: "refundnotes@hemofektik.de", password: "{0a8404F9-55B6}", host: "smtp.hemofektik.de", tls: true }); // send the message and get a callback with an error or details of the message that was sent server.send({ text: message.Text, from: "#RefundNotes Bot <refundnotes@hemofektik.de>", to: "drafts@refundnotes.com", subject: "New RefundNote Draft" }, function (err, message) { console.log(err || message); }); } } var init = function () { logger.logInfo('[SERVER] Configuration:'); var tmblrOptions = { consumerKey: global_config.tmblr_consumer_key, consumerSecret: global_config.tmblr_consumer_secret, accessToken: global_config.tmblr_access_token, accessSecret: global_config.tmblr_access_secret, hostname: global_config.tmblr_hostname }; tumblr = new Tumblr( tmblrOptions, tmblrOptions.hostname ); // Initialize aggregators logger.logInfo('[SERVER] Initializing aggregators'); aggregators.forEach(function (agg, index, array) { logger.logInfo(agg.logName + 'initializing'); agg.init(pushMessage); }); } exports.init = init; exports.processInstagramPost = processInstagramPost;
import React, { PropTypes } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './ZPersonalInfo.css'; class ZPersonalInfo extends React.Component { constructor (props) { super(); this.state = { name: props.name, email: props.email, phone: props.phone }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange (e) { this.setState({ [e.target.name] : e.target.value }); } async handleSubmit () { console.log(this.state); } render() { return ( <div> <h3>Profile</h3> <form> <label>Name </label> <input type="text" value={this.state.name} name="name" onChange={this.handleChange} /> <label>Email </label> <input type="text" value={this.state.email} name="email" onChange={this.handleChange} /> <label>Phone </label> <input type="text" value={this.state.phone} name="phone" onChange={this.handleChange} /> <input type="submit" value="Save" onClick={this.handleSubmit}/> </form> </div> ); }; }; ZPersonalInfo.propTypes = { name: PropTypes.string, email: PropTypes.string, phone: PropTypes.string }; export default withStyles(s)(ZPersonalInfo);
import {Component} from './Component'; import {attributes, copy} from './prototype/attributes'; import {CompositionError} from './errors'; @attributes( copy('position', 'rotation', 'quaternion', 'target') ) /** * @class CameraComponent * @category core * @param {Object} [params] - The parameters object. * @param {Object} [instructions] - The instructions object. * @extends module:core.Component * @memberof module:core */ class CameraComponent extends Component { /** * Default values for parameters * @member {Object} module:core.CameraComponent#defaults * @static * @default * { * build: true, * * position: {x: 0, y: 0, z: 0}, * rotation: {x: 0, y: 0, z: 0} * } */ static defaults = { ...Component.defaults, build: true, position: {x: 0, y: 0, z: 0}, rotation: {x: 0, y: 0, z: 0} }; /** * Static instructions * @member {Object} module:core.CameraComponent#instructions * @static * @default * { * position: ['x', 'y', 'z'], * rotation: ['x', 'y', 'z'], * scale: ['x', 'y', 'z'] * } */ static instructions = { position: ['x', 'y', 'z'], rotation: ['x', 'y', 'z'], scale: ['x', 'y', 'z'] }; static from(camera, params = {}) { params.build = false; const component = new CameraComponent(params); component.native = camera; component.wrap(); return component; } constructor(params, defaults = CameraComponent.defaults, instructions = CameraComponent.instructions) { super(params, defaults, instructions); if (this.params.build) { const build = this.build(this.params); if (!build) { throw new CompositionError( 'CameraComponent', '.build() method should return a THREE.Object3D or a Promise resolved with THREE.Object3D.', this ); } if (build instanceof Promise) { build.then(native => { this.native = native; }); } else this.native = build; this.wait(this.wrap()); } this.applyCommand('postIntegrate'); } // BUILDING & WRAPPING /** * @method build * @instance * @description Build livecycle should return a native object. * @throws {CompositionError} * @memberof module:core.CameraComponent */ build() { throw new CompositionError( 'CameraComponent', 'Instance should have it\'s own .build().', this ); } /** * @method wrap * @instance * @description Wraps transforms (`position` & `rotation`) * @return {Promise} Resolved when action is completed * @memberof module:core.CameraComponent */ wrap() { return new Promise(resolve => { this.defer(() => { this.position.set(this.params.position.x, this.params.position.y, this.params.position.z); this.rotation.set(this.params.rotation.x, this.params.rotation.y, this.params.rotation.z); this.applyBridge({onWrap: 1}); resolve(this); }); }); } /** * @method copy * @instance * @description Copy source transforms & execute `Component.copy()` * @param {CameraComponent} source - The camera component to copy * @return {this} CameraComponent * @memberof module:core.CameraComponent */ copy(source) { return super.copy(source, () => { if (this.target) this.target.copy(source.target()); this.position.copy(source.position); this.rotation.copy(source.rotation); this.quaternion.copy(source.quaternion); }); } /** * @method clone * @instance * @description Make a clone of this CameraComponent using `.copy()` * @return {CameraComponent} clone of this object * @memberof module:core.CameraComponent */ clone() { return new this.constructor({build: false}).copy(this); } } export { CameraComponent };
/** * Defines an operation yielding a value incremented by steps across a range. * * @typedef {object} Phaser.GameObjects.Particles.Types.EmitterOpSteppedConfig * @since 3.0.0 * * @property {number} start - The starting value. * @property {number} end - The ending value. * @property {number} steps - The number of steps between start and end. */
import sinon from 'sinon' import { accomodationListFetch } from '../../actions' import getSagaTester from '../../../../mock/sagaTester' import sagas from '..' describe('Accomodation sagas', () => { beforeEach(() => { sinon.stub(accomodationListFetch, 'resource') }) afterEach(() => { accomodationListFetch.resource.restore() }) it('fetch accomodation from API', () => { const sagaTester = getSagaTester({ years: { list: { data: [ { id: 200, year: '2017', current: true } ] } } }) accomodationListFetch.resource.returns({ ok: true, status: 200, json: () => ([ { id: 20, name: 'DK Milevsko' } ]) }) sagaTester.runAll(sagas) sagaTester.dispatch(accomodationListFetch()) expect(sagaTester.numCalled(accomodationListFetch.REQUEST)).toBe(1) expect(sagaTester.numCalled(accomodationListFetch.SUCCESS)).toBe(1) expect(sagaTester.getState().accomodation.list.data).toEqual([ { id: 20, name: 'DK Milevsko' } ]) }) it('dispatch capacity poll on accomodation required', () => { const sagaTester = getSagaTester({ years: { list: { data: [ { id: 200, year: '2017', current: true } ] } } }) accomodationListFetch.resource.returns({ ok: true, status: 200, json: () => ([ { id: 20, name: 'DK Milevsko' } ]) }) sagaTester.runAll(sagas) sagaTester.dispatch(accomodationListFetch.subscribe()) expect(sagaTester.numCalled('YEAR_CAPACITY_POLL_REQUIRED')).toBe(1) }) it('dispatch capacity poll on accomdation exit', () => { const sagaTester = getSagaTester({}) sagaTester.runAll(sagas) sagaTester.dispatch(accomodationListFetch.unsubscribe()) expect(sagaTester.numCalled('YEAR_CAPACITY_POLL_STOP')).toBe(1) }) })
import gulp from 'gulp'; import imageMin from 'gulp-imagemin'; import {path, tasks} from './const'; const IMAGES = path.DIST + '**/*.{png,jpg,jpeg,svg,gif}'; gulp.task(tasks.CLIENT_IMAGE_DIST, () => { return gulp.src(IMAGES, {base: path.DIST}) .pipe(imageMin()) .pipe(gulp.dest(path.DIST)); });
/** * A specialized version of `bue.some` for arrays without support for callback * shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, else `false`. */ function arraySome(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } module.exports = arraySome;
var util = require('./util') var getMsg = util.stringTemplate( 'Expected property `{name}` of type {expType}, got {gotType} for spec: {spec}') /** * @param {ErrorSpec} value * @throws {TypeError} */ module.exports.enforceErrorSpec = function (spec) { var msg if (util.getName(spec) !== 'Object') { throw new TypeError('spec must be an Object') } if (util.getName(spec.name) !== 'String') { msg = getMsg({ name: 'name', expType: 'String', gotType: util.getName(spec.name), spec: JSON.stringify(spec) }) throw new TypeError(msg) } if (spec.name === '') { msg = 'Expect "name" not empty string (spec: ' + JSON.stringify(spec) + ')' throw new TypeError(msg) } if (['String', 'Function'].indexOf(util.getName(spec.message)) === -1) { msg = getMsg({ name: 'message', expType: 'String or Function', gotType: util.getName(spec.message), spec: JSON.stringify(spec) }) throw new TypeError(msg) } if (spec.errors !== undefined) { if (util.getName(spec.errors) !== 'Array') { msg = getMsg({ name: 'errors', expType: 'Array', gotType: util.getName(spec.errors), spec: JSON.stringify(spec) }) throw new TypeError(msg) } spec.errors.forEach(module.exports.enforceErrorSpec) } }
import Ember from 'ember'; export default Ember.ArrayController.extend({ currentTitle: null });
'use strict'; const chai = require('chai'); const expect = chai.expect; const Support = require('../../support'); const dialect = Support.getTestDialect(); const DataTypes = require('@sequelize/core/lib/data-types'); if (dialect === 'mysql') { describe('[MYSQL Specific] DAOFactory', () => { describe('constructor', () => { it('handles extended attributes (unique)', function () { const User = this.sequelize.define(`User${Support.rand()}`, { username: { type: DataTypes.STRING, unique: true }, }, { timestamps: false }); expect(this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(User.rawAttributes)).to.deep.equal({ username: 'VARCHAR(255) UNIQUE', id: 'INTEGER NOT NULL auto_increment PRIMARY KEY' }); }); it('handles extended attributes (default)', function () { const User = this.sequelize.define(`User${Support.rand()}`, { username: { type: DataTypes.STRING, defaultValue: 'foo' }, }, { timestamps: false }); expect(this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(User.rawAttributes)).to.deep.equal({ username: 'VARCHAR(255) DEFAULT \'foo\'', id: 'INTEGER NOT NULL auto_increment PRIMARY KEY' }); }); it('handles extended attributes (null)', function () { const User = this.sequelize.define(`User${Support.rand()}`, { username: { type: DataTypes.STRING, allowNull: false }, }, { timestamps: false }); expect(this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(User.rawAttributes)).to.deep.equal({ username: 'VARCHAR(255) NOT NULL', id: 'INTEGER NOT NULL auto_increment PRIMARY KEY' }); }); it('handles extended attributes (primaryKey)', function () { const User = this.sequelize.define(`User${Support.rand()}`, { username: { type: DataTypes.STRING, primaryKey: true }, }, { timestamps: false }); expect(this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(User.rawAttributes)).to.deep.equal({ username: 'VARCHAR(255) PRIMARY KEY' }); }); it('adds timestamps', function () { const User1 = this.sequelize.define(`User${Support.rand()}`, {}); const User2 = this.sequelize.define(`User${Support.rand()}`, {}, { timestamps: true }); expect(this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(User1.rawAttributes)).to.deep.equal({ id: 'INTEGER NOT NULL auto_increment PRIMARY KEY', updatedAt: 'DATETIME NOT NULL', createdAt: 'DATETIME NOT NULL' }); expect(this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(User2.rawAttributes)).to.deep.equal({ id: 'INTEGER NOT NULL auto_increment PRIMARY KEY', updatedAt: 'DATETIME NOT NULL', createdAt: 'DATETIME NOT NULL' }); }); it('adds deletedAt if paranoid', function () { const User = this.sequelize.define(`User${Support.rand()}`, {}, { paranoid: true }); expect(this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(User.rawAttributes)).to.deep.equal({ id: 'INTEGER NOT NULL auto_increment PRIMARY KEY', deletedAt: 'DATETIME', updatedAt: 'DATETIME NOT NULL', createdAt: 'DATETIME NOT NULL' }); }); it('underscores timestamps if underscored', function () { const User = this.sequelize.define(`User${Support.rand()}`, {}, { paranoid: true, underscored: true }); expect(this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(User.rawAttributes)).to.deep.equal({ id: 'INTEGER NOT NULL auto_increment PRIMARY KEY', deleted_at: 'DATETIME', updated_at: 'DATETIME NOT NULL', created_at: 'DATETIME NOT NULL' }); }); it('omits text fields with defaultValues', function () { const User = this.sequelize.define(`User${Support.rand()}`, { name: { type: DataTypes.TEXT, defaultValue: 'helloworld' } }); expect(User.rawAttributes.name.type.toString()).to.equal('TEXT'); }); it('omits blobs fields with defaultValues', function () { const User = this.sequelize.define(`User${Support.rand()}`, { name: { type: DataTypes.STRING.BINARY, defaultValue: 'helloworld' } }); expect(User.rawAttributes.name.type.toString()).to.equal('VARCHAR(255) BINARY'); }); }); describe('primaryKeys', () => { it('determines the correct primaryKeys', function () { const User = this.sequelize.define(`User${Support.rand()}`, { foo: { type: DataTypes.STRING, primaryKey: true }, bar: DataTypes.STRING, }); expect(this.sequelize.getQueryInterface().queryGenerator.attributesToSQL(User.primaryKeys)).to.deep.equal({ foo: 'VARCHAR(255) PRIMARY KEY' }); }); }); }); }
// Any copyright is dedicated to the Public Domain. // http://creativecommons.org/publicdomain/zero/1.0/ // null input. checkPublicSuffix(null, null); // Mixed case. checkPublicSuffix('COM', null); checkPublicSuffix('example.COM', 'example.com'); checkPublicSuffix('WwW.example.COM', 'example.com'); // Leading dot. checkPublicSuffix('.com', null); checkPublicSuffix('.example', null); checkPublicSuffix('.example.com', null); checkPublicSuffix('.example.example', null); // Unlisted TLD. checkPublicSuffix('example', null); checkPublicSuffix('example.example', 'example.example'); checkPublicSuffix('b.example.example', 'example.example'); checkPublicSuffix('a.b.example.example', 'example.example'); // Listed, but non-Internet, TLD. //checkPublicSuffix('local', null); //checkPublicSuffix('example.local', null); //checkPublicSuffix('b.example.local', null); //checkPublicSuffix('a.b.example.local', null); // TLD with only 1 rule. checkPublicSuffix('biz', null); checkPublicSuffix('domain.biz', 'domain.biz'); checkPublicSuffix('b.domain.biz', 'domain.biz'); checkPublicSuffix('a.b.domain.biz', 'domain.biz'); // TLD with some 2-level rules. checkPublicSuffix('com', null); checkPublicSuffix('example.com', 'example.com'); checkPublicSuffix('b.example.com', 'example.com'); checkPublicSuffix('a.b.example.com', 'example.com'); checkPublicSuffix('uk.com', null); checkPublicSuffix('example.uk.com', 'example.uk.com'); checkPublicSuffix('b.example.uk.com', 'example.uk.com'); checkPublicSuffix('a.b.example.uk.com', 'example.uk.com'); checkPublicSuffix('test.ac', 'test.ac'); // TLD with only 1 (wildcard) rule. checkPublicSuffix('cy', null); checkPublicSuffix('c.cy', null); checkPublicSuffix('b.c.cy', 'b.c.cy'); checkPublicSuffix('a.b.c.cy', 'b.c.cy'); // More complex TLD. checkPublicSuffix('jp', null); checkPublicSuffix('test.jp', 'test.jp'); checkPublicSuffix('www.test.jp', 'test.jp'); checkPublicSuffix('ac.jp', null); checkPublicSuffix('test.ac.jp', 'test.ac.jp'); checkPublicSuffix('www.test.ac.jp', 'test.ac.jp'); checkPublicSuffix('kyoto.jp', null); checkPublicSuffix('test.kyoto.jp', 'test.kyoto.jp'); checkPublicSuffix('ide.kyoto.jp', null); checkPublicSuffix('b.ide.kyoto.jp', 'b.ide.kyoto.jp'); checkPublicSuffix('a.b.ide.kyoto.jp', 'b.ide.kyoto.jp'); checkPublicSuffix('c.kobe.jp', null); checkPublicSuffix('b.c.kobe.jp', 'b.c.kobe.jp'); checkPublicSuffix('a.b.c.kobe.jp', 'b.c.kobe.jp'); checkPublicSuffix('city.kobe.jp', 'city.kobe.jp'); checkPublicSuffix('www.city.kobe.jp', 'city.kobe.jp'); // TLD with a wildcard rule and exceptions. checkPublicSuffix('ck', null); checkPublicSuffix('test.ck', null); checkPublicSuffix('b.test.ck', 'b.test.ck'); checkPublicSuffix('a.b.test.ck', 'b.test.ck'); checkPublicSuffix('www.ck', 'www.ck'); checkPublicSuffix('www.www.ck', 'www.ck'); // US K12. checkPublicSuffix('us', null); checkPublicSuffix('test.us', 'test.us'); checkPublicSuffix('www.test.us', 'test.us'); checkPublicSuffix('ak.us', null); checkPublicSuffix('test.ak.us', 'test.ak.us'); checkPublicSuffix('www.test.ak.us', 'test.ak.us'); checkPublicSuffix('k12.ak.us', null); checkPublicSuffix('test.k12.ak.us', 'test.k12.ak.us'); checkPublicSuffix('www.test.k12.ak.us', 'test.k12.ak.us');
import path from 'path'; import http from 'http'; import express from 'express'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { Provider } from 'react-redux'; import exphbs from 'express-handlebars'; import Helmet from 'react-helmet'; import StaticRouter from 'react-router-dom/StaticRouter'; import { matchRoutes } from 'react-router-config'; import { createMemoryHistory } from 'history'; import configureStore from '../store'; import { routes, renderRoutes } from '../routes'; import config from '../config'; const app = express(); app.engine('hbs', exphbs({ extname: 'hbs' })); app.set('views', path.join(__dirname, '../template')); let port = config.port || 8080; if (process.env.NODE_ENV === 'development') { app.use(express.static(path.join(__dirname, '../', 'public'))); port = config.devPort || 3001; } else { app.use(express.static(path.join(__dirname, '../../', 'public'))); } app.set('view engine', 'hbs'); const server = new http.Server(app); app.use((req, res) => { /* eslint no-undef: 0 */ if (__DEVELOPMENT__) { webpackIsomorphicTools.refresh(); } const matchData = matchRoutes(routes, req.url); if (!matchData || matchData.length === 0) { res.status(404).end('Not found'); return; } const component = matchData[matchData.length - 1].route.component; const fetchData = (component && component.fetchData) || (() => Promise.resolve()); const match = matchData[matchData.length - 1].match; const history = createMemoryHistory({ initialEntries: [req.url] }); const store = configureStore({}, history); fetchData({ store, match }) .then(() => { const context = {}; const body = renderToString( <Provider store={store}> <StaticRouter location={req.url} context={context}> {renderRoutes(routes)} </StaticRouter> </Provider> ); if (context.url) { res.redirect(302, context.url); return; } const head = Helmet.rewind(); const state = store.getState(); const data = { title: head.title.toString(), meta: head.meta.toString(), link: head.link.toString(), script: head.script.toString(), body, state: JSON.stringify(state), assets: webpackIsomorphicTools.assets(), layout: false }; res.render('index', data); }) .catch(e => console.log(e)); }); if (port) { server.listen(port, (err) => { if (err) { console.error(err); } console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, port); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
'use strict'; var _ = require('lodash'); var Holodeck = require('../../../../../holodeck'); var Request = require('../../../../../../../lib/http/request'); var Response = require('../../../../../../../lib/http/response'); var Twilio = require('../../../../../../../lib'); var client; var holodeck; describe('Mobile', function() { beforeEach(function() { holodeck = new Holodeck(); client = new Twilio('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'AUTHTOKEN', holodeck); }); it('should generate valid list request', function() { holodeck.mock(new Response(500, '')); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .availablePhoneNumbers('US') .mobile.list(); promise = promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(Error.prototype.constructor); }); promise.done(); var solution = { accountSid: 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', countryCode: 'US' }; var url = _.template('https://api.twilio.com/2010-04-01/Accounts/<%= accountSid %>/AvailablePhoneNumbers/<%= countryCode %>/Mobile.json')(solution); holodeck.assertHasRequest(new Request({ method: 'GET', url: url })); } ); it('should generate valid read_full response', function() { var body = JSON.stringify({ 'available_phone_numbers': [ { 'address_requirements': 'none', 'beta': false, 'capabilities': { 'mms': false, 'sms': true, 'voice': false }, 'friendly_name': '+4759440374', 'iso_country': 'NO', 'lata': null, 'latitude': null, 'longitude': null, 'phone_number': '+4759440374', 'postal_code': null, 'rate_center': null, 'region': null } ], 'first_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Mobile.json?PageSize=50&Page=0', 'last_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Mobile.json?PageSize=50&Page=0', 'next_page_uri': null, 'num_pages': 1, 'page': 0, 'page_size': 50, 'previous_page_uri': null, 'start': 0, 'total': 1, 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Mobile.json?PageSize=1' }); holodeck.mock(new Response(200, body)); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .availablePhoneNumbers('US') .mobile.list(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); it('should generate valid read_empty response', function() { var body = JSON.stringify({ 'available_phone_numbers': [], 'first_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Mobile.json?PageSize=50&Page=0', 'last_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Mobile.json?PageSize=50&Page=0', 'next_page_uri': null, 'num_pages': 1, 'page': 0, 'page_size': 50, 'previous_page_uri': null, 'start': 0, 'total': 1, 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/AvailablePhoneNumbers/US/Mobile.json?PageSize=1' }); holodeck.mock(new Response(200, body)); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .availablePhoneNumbers('US') .mobile.list(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); });
define([ 'views/chart', 'views/map', 'text!../../html/results.html' ], function(ChartView, MapView, temp){ return Backbone.View.extend({ el: '#results', events: { 'click .toggle img': 'toggle' }, initialize: function() { this.template = Handlebars.compile(temp); this.lawyer_chart = new ChartView(); this.pleas_chart = new ChartView(); }, render: function() { $(this.el).html(this.template(this.data.data)); }, populate: function(data) { this.data = data; this.render(); }, toggle: function(e) { var rel = $(e.target).parent('span').attr('rel'); var li = $(e.target).parents('#' + rel); if ($(li).hasClass('open')) { $(li).children('.dropdown').hide(); $(li).removeClass('open'); } else { $('#results li').children('.dropdown').hide(); $('#results li').removeClass('open'); $(li).children('.dropdown').slideToggle(100); $(li).addClass('open'); $(li).find('.chart').html(''); $(li).find('div[id^=map-container]').html(''); // Dummy data var stats = [ {chart: 'lawyer', caption: 'Percentage of people who hired a lawyer', data: [ { title: 'Yes', value : 75, color: "#23a3e8" }, { title: 'No', value: 25, color: "#e75b51" }, ]}, {chart: 'pleas', caption: 'Percentage of pleas in court', data: [ { title: 'Guilty', value : 50, color: "#23a3e8" }, { title: 'Not Guilty', value: 25, color: "#e07732" }, { title: 'No Contest', value: 25, color: "#e75b51" }, ]} ] _.each(stats, function(stat) { var chart_id = '#' + stat.chart + '-' + rel; var options = {chart: chart_id, caption: stat.caption, data: stat.data} if (stat.chart == 'lawyer') this.lawyer_chart.render(options); else this.pleas_chart.render(options); var map = new MapView({id:rel}); }.bind(this)); } } }); });
const rescuetime = require('../'); rescuetime.start('this is a test'); setTimeout(()=>{ rescuetime.end('this is a test', delta => { console.log(delta); }); }, 3000);
'use strict'; angular.module('hano.translator', []) .factory('parseLinks', function(text) { var result = ''; result = text.replace(/\[art:([^\]]+)\]/, '<a href="/articles/$1">$1</a>'); result = result.replace(/\[dic:([^\]]+)\]/, '<a href="/dictionary/$1">$1</a>'); return result; }) .factory('parseWutopian', function(text) { return text.replace(/\[wut:([^\]]+)\]/, function(str, p1) { if (p1) { p1 = p1.replace(/rr\b/g, '-'); return '<span class="wutopian">' + p1 + '</span>'; } }); }) .factory('parseNardanskh', function(text) { return text.replace(/\[nar:([^\]]+)\]/, '<span class="nardanskh">$1</span>'); }) .factory('parseCalendar', function(text) { return text.replace(/\[ic:([^\]]+)\]/, '<a href="/calendar/$1">IC $1</a>'); }) .factory('parse', function(text) { // TODO: deal // var result = module.exports.parseLinks(text); // result = module.exports.parseWutopian(result); // result = module.exports.parseNardanskh(result); // result = module.exports.parseCalendar(result); // return result; return text; });
function appStart() { console.log('Todo loco!'); } $(document).on('ready', appStart);
Parties = new Mongo.Collection("parties"); Parties.allow({ insert: function (userId, party) { return userId && party.owner === userId; }, update: function (userId, party, fields, modifier) { if (userId !== party.owner) return false; return true; }, remove: function (userId, party) { if (userId !== party.owner) return false; return true; } }); // Meteor.methods({ // invite: function (partyId, userId) { // check(partyId, String); // check(userId, String); // var party = Parties.findOne(partyId); // if (!party) // throw new Meteor.Error(404, "No such party"); // if (party.owner !== this.userId) // throw new Meteor.Error(404, "No such party"); // if (party.public) // throw new Meteor.Error(400, // "That party is public. No need to invite people."); // if (userId !== party.owner && ! _.contains(party.invited, userId)) { // Parties.update(partyId, { $addToSet: { invited: userId } }); // var from = contactEmail(Meteor.users.findOne(this.userId)); // var to = contactEmail(Meteor.users.findOne(userId)); // if (Meteor.isServer && to) { // // This code only runs on the server. If you didn't want clients // // to be able to see it, you could move it to a separate file. // Email.send({ // from: "noreply@socially.com", // to: to, // replyTo: from || undefined, // subject: "PARTY: " + party.title, // text: // "Hey, I just invited you to '" + party.title + "' on Socially." + // "\n\nCome check it out: " + Meteor.absoluteUrl() + "\n" // }); // } // } // }, // rsvp: function (partyId, rsvp) { // check(partyId, String); // check(rsvp, String); // if (! this.userId) // throw new Meteor.Error(403, "You must be logged in to RSVP"); // if (! _.contains(['yes', 'no', 'maybe'], rsvp)) // throw new Meteor.Error(400, "Invalid RSVP"); // var party = Parties.findOne(partyId); // if (! party) // throw new Meteor.Error(404, "No such party"); // if (! party.public && party.owner !== this.userId && // !_.contains(party.invited, this.userId)) // // private, but let's not tell this to the user // throw new Meteor.Error(403, "No such party"); // var rsvpIndex = _.indexOf(_.pluck(party.rsvps, 'user'), this.userId); // if (rsvpIndex !== -1) { // // update existing rsvp entry // if (Meteor.isServer) { // // update the appropriate rsvp entry with $ // Parties.update( // {_id: partyId, "rsvps.user": this.userId}, // {$set: {"rsvps.$.rsvp": rsvp}}); // } else { // // minimongo doesn't yet support $ in modifier. as a temporary // // workaround, make a modifier that uses an index. this is // // safe on the client since there's only one thread. // var modifier = {$set: {}}; // modifier.$set["rsvps." + rsvpIndex + ".rsvp"] = rsvp; // Parties.update(partyId, modifier); // } // // Possible improvement: send email to the other people that are // // coming to the party. // } else { // // add new rsvp entry // Parties.update(partyId, // {$push: {rsvps: {user: this.userId, rsvp: rsvp}}}); // } // } // }); // var contactEmail = function (user) { // if (user.emails && user.emails.length) // return user.emails[0].address; // if (user.services && user.services.facebook && user.services.facebook.email) // return user.services.facebook.email; // return null; // };
/**! * nodeclub - config/index.js * MIT Licensed */ 'use strict'; /** * Module dependencies. */ var path = require('path'); var fs = require('fs'); var mkdirp = require('mkdirp'); fs.existsSync = fs.existsSync || path.existsSync; var pkg = require('../package.json'); var root = path.dirname(__dirname); var config = { version: pkg.version, webPort: 7001, enableCluster: false, debug: true, // if debug logdir: path.join(root, '.tmp', 'logs'), viewCache: false, cookieKeys: ['nodeclub secret', 'haha other key'], mysql: { servers: [ { host: 'keydiary.mysql.rds.aliyuncs.com', // 'db4free.net' port: 3306, user: 'nodeclub_dev', password: 'nodeclub_dev' } ], database: 'nodeclub_dev', maxConnections: 4, queryTimeout: 5000, }, }; // load config/config.js, everything in config.js will cover the same key in index.js var customConfig = path.join(root, 'config/config.js'); if (fs.existsSync(customConfig)) { var options = require(customConfig); for (var k in options) { config[k] = options[k]; } } mkdirp.sync(config.logdir); module.exports = config;
var app = angular.module('supportApplication', ['ngMessages', 'glue.directives']); app.controller('ChatController', function ($scope, $http, $timeout, $log) { $scope.configuration; $scope.channel; $scope.messages = []; $scope.session = { token: null, identity: null, isInitialized: false, isLoading: false, expired: false }; $scope.init = function () { $http.get('/api/setup') .then(function onSuccess (response) { $scope.configuration = response.data; }, function onError (response) { $log.error('error loading configuration'); $log.error(response); }); }; $scope.initChat = function () { /* clean up */ $scope.channel = null; $scope.messages = []; $scope.session = { token: null, identity: null, isInitialized: false, isLoading: false, expired: false }; $scope.session.isLoading = true; var user = { identity: $scope.user.identity, endpoint: navigator.userAgent.toLowerCase() + Math.floor((Math.random() * 1000) + 1) }; $http.post('/api/tasks/chat', user) .then(function onSuccess (response) { $scope.session.token = response.data.token; $scope.session.identity = response.data.identity; $scope.setupClient(response.data.channel.sid); }, function onError (response) { $scope.session.isLoading = false; $log.error('server returned error'); $log.error(response); }); }; $scope.setupClient = function (channelSid) { $log.log('setup channel: ' + channelSid); var accessManager = new Twilio.AccessManager($scope.session.token); /** * you'll want to be sure to listen to the tokenExpired event either update * the token via accessManager.updateToken(<token>) or let your page tell the user * the chat is not active anymore **/ accessManager.on('tokenExpired', function () { $log.warn('token expired'); $scope.session.expired = true; $scope.$apply(); }); accessManager.on('error', function (err) { $log.error('An error occurred'); $log.error(err); }); var messagingClient = new Twilio.IPMessaging.Client(accessManager); var promise = messagingClient.getChannelBySid(channelSid); promise.then(function (channel) { $log.log('channel is: ' + channel.uniqueName); $scope.setupChannel(channel); }, function (reason) { /* client could not access the channel */ $log.error('could not access channel'); $log.error(reason); }); }; $scope.setupChannel = function (channel) { channel.join().then(function (member) { $scope.messages.push({ body: 'An agent will be available shortly', author: 'System' }); /* use now joined the channel, display canvas */ $scope.session.isInitialized = true; $scope.session.isLoading = false; $scope.$apply(); }); channel.on('messageAdded', function (message) { $scope.messages.push(message); $scope.$apply(); }); channel.on('memberJoined', function (member) { $log.log(member.identity + ' has joined the channel.'); $scope.messages.push({ body: member.identity + ' has joined the channel.', author: 'System' }); $scope.$apply(); }); channel.on('memberLeft', function (member) { $scope.messages.push({ body: member.identity + ' has left the channel.', author: 'System' }); $scope.$apply(); }); channel.on('typingStarted', function (member) { $log.log(member.identity + ' started typing'); $scope.typingNotification = member.identity + ' is typing ...'; $scope.$apply(); }); channel.on('typingEnded', function (member) { $log.log(member.identity + ' stopped typing'); $scope.typingNotification = ''; $scope.$apply(); }); $scope.channel = channel; }; $scope.$watch('message', function (newValue, oldValue) { if ($scope.channel) { $log.log('send typing notification to channel'); $scope.channel.typing(); } }); $scope.send = function () { $scope.channel.sendMessage($scope.message); $scope.message = ''; }; }); app.filter('time', function () { return function (value) { return moment(value).format('HH:mm'); }; });
'use strict'; /** * @module code-project/task/create-taiga-boards */ const request = require('request'); /** * Promise wrapper for request, abstracts the http api * @private * @param {Object} data - request object * @returns {Promise.<String>} promise will resolve to response body or reject with error code */ function requestPromise (data) { return new Promise((resolve, reject) => { request(data, (error, headers, body) => { if (error) { reject(error); } else { resolve(body); } }); }); } /** * TaigaBoard is meta data for creating a single board. * @typedef {Object} TaigaBoard * @property {String} name - name of the board * @property {Array} members - {Array} of {String} with emails */ /** * TaigaOptions is meta data that can be used on all boards. * @typedef {Object} TaigaOptions * @property {String} description - description of the board * @property {Boolean} isPrivate - choose whether repo is public or private * @property {Boolean} isBacklogActived - choose whether or not to have a backlog * @property {Boolean} isIssuesActived - choose whether or not to have issues * @property {Boolean} isKanbanActivated - choose whether or not to use Kanban * @property {Boolean} isWikiActivated - choose whether or not to have a project wiki */ /** * Takes in Taiga meta data and create boards for each * @param {String} taigaUsername - Taiga admin username * @param {String} taigaPassword - Taiga admin password * @param {Array} taigaBoards - an {Array} of {TaigaBoard} * @param {TaigaOptions} taigaOptions - shared options for all boards * @returns {Promise} resolves when boards have been created */ function createTiagaBoards (taigaUsername, taigaPassword, taigaBoards, taigaOptions) { let authorizationToken = null; // Login to Taiga requestPromise({ body: { password: taigaPassword, type: 'normal', username: taigaUsername }, json: true, method: 'POST', uri: 'https://api.taiga.io/api/v1/auth' }) .then((data) => { // Store authorization token for later authorizationToken = data.auth_token; // Setup shared meta for boards const boardMetaData = { description: taigaOptions.description, is_backlog_activated: taigaOptions.isBacklogActived, is_issues_activated: taigaOptions.isIssuesActived, is_kanban_activated: taigaOptions.isKanbanActivated, is_private: taigaOptions.isPrivate, is_wiki_activated: taigaOptions.isWikiActivated }; // Collect promises for all boards const promises = []; // Create each board for (const index in taigaBoards) { // Set the name boardMetaData.name = taigaBoards[index].name; // Create board promises.push( requestPromise({ body: boardMetaData, headers: {Authorization: `Bearer ${authorizationToken}`}, json: true, method: 'POST', uri: 'https://api.taiga.io/api/v1/projects' }) ); } // Wait for all boards to be created return Promise.all(promises); }) .then((data) => { const promises = []; // For each person in each project for (const boardIndex in taigaBoards) { for (const userIndex in taigaBoards[boardIndex].emails) { const taigaRoles = data[boardIndex].roles; // Setup the members permissions const userMetadata = { email: taigaBoards[boardIndex].emails[userIndex], project: data[boardIndex].id, role: taigaRoles .find((element) => element.name === 'Back') .id }; // Add them to the taiga board promises.push( requestPromise({ body: userMetadata, headers: {Authorization: `Bearer ${authorizationToken}`}, json: true, method: 'POST', uri: 'https://api.taiga.io/api/v1/memberships' }) ); } } return Promise.all(promises); }); } module.exports = createTiagaBoards;
import Ember from 'ember'; import config from './config/environment'; var Router = Ember.Router.extend({ location: config.locationType }); export default Router.map(function() { this.resource("index", {path: "/"}); this.route("redirector"); this.route("login"); this.route("user", {path: "/user/:user_id"}, function() { this.route("activity"); this.route("proposals"); }); this.route("auth", function() { this.route("setup", {path: "/:provider/setup/:token"}); this.route("oauth_login", {path: "/:provider/login"}); this.route("manual", {path: "/do/:username/:auth_key"}); }); this.route("users", {}, function() { this.route("index"); this.route("forgot-password"); this.route("reset-password"); this.route("new"); this.route("login"); }); this.resource("words", {path: "/words/:lang"}, function() { this.route("new"); this.route("random"); }); this.resource("posts"); this.resource("post", {path: "/post/:post_id"}); this.resource("proposals", function() { }); this.resource("proposal", {path: "/proposal/:proposal_id"}, function() { this.route("new-word"); this.route("new-meaning"); this.route("meaning-change"); }); this.route("project", {path: "/project/:project_id"}, function() { this.route("random"); this.route("propose", {path: "/propose/:meaning_id"}); }); this.route("info", function() { this.route("goals"); this.route("faqs"); this.route("guidelines"); this.route("get-started"); this.route("legal"); }); this.route('legacy-word', {path: "/word/:seq"}); this.route("quizzes"); this.route("quiz", {path: "/quiz/:id"}); this.resource("seq", {path: "/:lang/:seq"}, function() { this.route("wordset", {path: "/"}, function() { this.route("proposals"); }); }); this.route('not-found', { path: '/*path' }); });
// avoid fs IO on every request with simple caching // see logs from second request var http = require('http'); var path = require('path'); var fs = require('fs'); var mimeTypes = { '.js' : 'text/javascript', '.html' : 'text/html', '.css' : 'text/css' }; var cache = {}; function cacheAndDeliver(f, cb){ fs.stat(f, function(err, stats){ var lastChanged = Date.parse(stats.ctime), isUpdated = (cache[f]) && lastChanged > cache[f].timestamp; if(!cache[f] || isUpdated){ fs.readFile(f, function(err, data){ if(!err){ cache[f] = { content: data, timestamp: Date.now() // store unix timestamp }; } cb(err, data); }); return; } console.log('loading ' + f + ' from cache'); cb(null, cache[f].content); }); // end fs.stat } // end cacheAndDeliver http.createServer(function (request, response){ var lookup = path.basename(decodeURI(request.url)) || 'index.html', f = 'static/' + lookup; if(request.url == '/favicon.ico'){ // pretty harsh handling // dont want the requests in this example response.end(); return; } fs.exists(f, function(exists){ if(exists){ cacheAndDeliver(f, function(err, data){ var headers = {'Content-type': mimeTypes[path. extname(lookup)]}; response.writeHead(200, headers); response.end(data); if(err){ response.writeHead(500); response.end('Server error'); return; } }); return; } else{ response.writeHead(404); response.end('404 - Item not found'); } }); }).listen(1337);
this.NesDb = this.NesDb || {}; NesDb[ '4912EBB244888B9680BD2A044CB157BD67475818' ] = { "$": { "name": "Jack Nicklaus' Greatest 18 Holes of Major Championship Golf", "class": "Licensed", "catalog": "NES-JC-USA", "publisher": "Konami", "developer": "Sculptured Software", "portdeveloper": "Konami", "region": "USA", "players": "4", "date": "1990-03" }, "cartridge": [ { "$": { "system": "NES-NTSC", "crc": "C313EF54", "sha1": "4912EBB244888B9680BD2A044CB157BD67475818", "dump": "ok", "dumper": "bootgod", "datedumped": "2006-12-24" }, "board": [ { "$": { "type": "KONAMI-UNROM", "pcb": "351320", "mapper": "2" }, "prg": [ { "$": { "name": "RD025N02P", "size": "128k", "crc": "C313EF54", "sha1": "4912EBB244888B9680BD2A044CB157BD67475818" } } ], "vram": [ { "$": { "size": "8k" } } ], "chip": [ { "$": { "type": "74xx161" } }, { "$": { "type": "74xx32" } } ], "cic": [ { "$": { "type": "6113B1" } } ], "pad": [ { "$": { "h": "1", "v": "0" } } ] } ] }, { "$": { "system": "NES-NTSC", "crc": "C313EF54", "sha1": "4912EBB244888B9680BD2A044CB157BD67475818", "dump": "ok", "dumper": "bootgod", "datedumped": "2006-03-09" }, "board": [ { "$": { "type": "KONAMI-UNROM", "pcb": "351320", "mapper": "2" }, "prg": [ { "$": { "name": "RD025N0.2P", "size": "128k", "crc": "C313EF54", "sha1": "4912EBB244888B9680BD2A044CB157BD67475818" } } ], "vram": [ { "$": { "size": "8k" } } ], "chip": [ { "$": { "type": "74xx161" } }, { "$": { "type": "74xx32" } } ], "cic": [ { "$": { "type": "6113B1" } } ], "pad": [ { "$": { "h": "1", "v": "0" } } ] } ] } ] };
$(function() { if(jQuery().jqm){ $('#report-form').jqm(); } }); var ls = ls || {}; ls.commentreport =( function ($) { this.open = function (iId,user) { $('#report-comment-id').val(iId); $('#reportspan').html(iId); $('#reportuserspan').html(user); $('#report-url').val( 'http://' + window.location.hostname + window.location.pathname + '#comment' + iId ); $('#reporturlspan').html( 'http://' + window.location.hostname + window.location.pathname + '#comment' + iId ); $('#report-reason').focus() $('#report-form').jqmShow(); } this.send = function (form) { ls.ajaxSubmit(aRouter['ajax']+'commentreport', form, function(data) { if (!data.bStateError) { ls.msg.notice(data.sMsgTitle,data.sMsg); $('#report-form').jqmHide(); } else { ls.msg.error(data.sMsgTitle,data.sMsg); } }); } return this; }).call(ls.commentreport || {},jQuery);
var utils = require('../utils.js'); describe('This is example for wait a non-protractor promise', function () { beforeEach(function() { browser.get('http://juliemr.github.io/protractor-demo/'); }); it('then result should be I am very slow', function () { var promise = utils.getPromise(); promise.then(function (result) { expect(result).toBe('I am diferent'); }); }); });
var classHelix_1_1Logic_1_1util_1_1LRTask = [ [ "LRTask", "classHelix_1_1Logic_1_1util_1_1LRTask.html#af0a9f16ae381e863037d64fafb43c32a", null ], [ "LRTask", "classHelix_1_1Logic_1_1util_1_1LRTask.html#aefa6467a13eca3588cc3d200a10554e6", null ], [ "~LRTask", "classHelix_1_1Logic_1_1util_1_1LRTask.html#aede6626ab516bb97b63e255dc1523d3a", null ], [ "LRTask", "classHelix_1_1Logic_1_1util_1_1LRTask.html#af5bea84d2601fc82cf7956341898bd61", null ], [ "checkSize", "classHelix_1_1Logic_1_1util_1_1LRTask.html#ab4b592bb89568f587d2b6ed3601d82a6", null ], [ "createXmlChildren", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a54a1f416e6b29636bae600a5d50ef13b", null ], [ "createXmlDoc", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a98aa16126302213dd67a5352473edaaa", null ], [ "createXmlNode", "classHelix_1_1Logic_1_1util_1_1LRTask.html#aacc251847428a616ab2b43e0db005377", null ], [ "deleteVector", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a31272405222640a14e3cfbd29f7ab0ac", null ], [ "init", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a37e38bca66a80680b64d186668590184", null ], [ "Name", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a323a0852dde474db9cc32f679a150f16", null ], [ "operator=", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a159e043597a28a2c524d2762ee222065", null ], [ "readXmlChildren", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a2ce66a8d10624e83b90c926928d80a5d", null ], [ "readXmlNode", "classHelix_1_1Logic_1_1util_1_1LRTask.html#aa86a323e515e9e39309412eec12750fc", null ], [ "unusedSqlStmt", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a08a2ee346d612dcc49fa93ba39ccf64c", null ], [ "unusedSqlStmt", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a980173bafda95313aa5089aaee940042", null ], [ "unusedSqlStmt_getSQL", "classHelix_1_1Logic_1_1util_1_1LRTask.html#aa6edd2df9bce57e2079db2de99bda587", null ], [ "unusedSqlStmt_prepSQL", "classHelix_1_1Logic_1_1util_1_1LRTask.html#af4ff783070adb7a391edf7ca5d33f3a2", null ], [ "TaskCurrent", "classHelix_1_1Logic_1_1util_1_1LRTask.html#aee4fa01402bc8fbcafc82550ae1bb20d", null ], [ "TaskFinish", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a8b6771ffc700b885763e2f2ee3d9fd04", null ], [ "TaskID", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a254d7bfcab48db9ddda4b12c0a6a7b46", null ], [ "TaskMsg", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a7fa360c8b5cc97727a571cd32ab8dfc7", null ], [ "TaskName", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a39fa8f756276341b0f18063bd64c3e71", null ], [ "TaskResponse", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a2387f0e454b7464cce9229423b80c1a6", null ], [ "TaskStart", "classHelix_1_1Logic_1_1util_1_1LRTask.html#a511d14f50ba2eb5be2f1359449a18ccd", null ] ];
/** @babel */ export default { config: require('./config.coffee').config, consumeStatusBar (statusBar) { const EventWatchElement = require('./event-watch-element') this.element = new EventWatchElement({ configSpec: this.config, statusBar: statusBar }) }, deactivate () { if (this.element) { this.element.destroy() this.element = null } } }
/* * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development"). * This devtool is neither made for production nor for readable output files. * It uses "eval()" calls to create a separate source file in the browser devtools. * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/) * or disable the default devtool with "devtool: false". * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/). */ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ "./entry1.ts": /*!*******************!*\ !*** ./entry1.ts ***! \*******************/ /***/ (() => { eval("console.log('banana');\n\n\n//# sourceURL=webpack:///./entry1.ts?"); /***/ }) /******/ }); /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module can't be inlined because the eval devtool is used. /******/ var __webpack_exports__ = {}; /******/ __webpack_modules__["./entry1.ts"](); /******/ /******/ })() ;
'use strict'; var array = require('../array.js'); var generator = require('./generator.js'); generator('array', array, { valid: [ ['[]'], ['[[[[[]]]]]'], ['[1, 2, 3]'], ['[1, \'two\', 3.0, [\'four\']]'] ], invalid: [ [''], [' =>'], ['=> '], ['==>'], [' []'], ['[] '], ['[,]'], ['[,,]'], ['[1,]'], ['[,1]'], ['[[]'], ['[]]'] ] });
(function () { 'use strict'; angular .module('blog') .factory('PostsService', PostsService); PostsService.$inject = ['$resource']; function PostsService($resource) { var PostsService = $resource('https://jsonplaceholder.typicode.com/posts/:id/:comments/', { id: '@id', _start: '@start', _limit: '@limit' }, { getComments: { params: { comments: 'comments' }, method: 'GET', isArray: true } }); return PostsService; } })();
module.exports = function (req, res) { if (!req.schema.definition()) return res.json({ error: "Definition not found" }); res.json(req.schema.definition()); };
/*! * Language-Manager-JS v1.0.0 (http://usermyadmin.net/Language-Manager-JS) * Copyright 2015 EdificApps. * Licensed under MIT (https://github.com/edificapps/Language-Manager-JS/blob/master/LICENSE) * * Plug-in for jQuery 1.11.2 - 2.1.3 : Full testing. * */ $.fn.extend({ lang: function (e) { this.each(function(i, e) { h = $(e).html(); var c = h; while(true){ var p = c.match(/[\_]{2,2}@([\w-]{2,}):([\w-]{2,})+[\_]{2,2}/); if(p){ c = c.substring(p.index+p[0].length, h.length); h = h.replace(p[0], $.language[p[1].toUpperCase()][p[2].toLowerCase()]); }else break; } $(e).html(h); }); } });
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M18.29 15.71l-4.58 4.58c-.39.39-1.03.39-1.42 0-.39-.39-.39-1.03 0-1.42L15.17 16H5c-.55 0-1-.45-1-1V5c0-.55.45-1 1-1s1 .45 1 1v9h9.17l-2.88-2.87c-.39-.39-.39-1.03 0-1.42.39-.39 1.03-.39 1.42 0l4.58 4.58c.39.39.39 1.03 0 1.42z" /> , 'SubdirectoryArrowRightRounded');
import './tags.scss' export class Tags { constructor() { this.log = LogManager.getLogger(`Saeris.io/${this.constructor.name}`) } attached() { } }
// serialize obj {"key": "value", "another": "value"} to gql {key: "value", another: "value"} // -- quotes around keys (normal JSON stringify) are rejected in gql args export const toGqlObjectArg = (obj) => typeof(obj)!=='object' ? JSON.stringify(obj) : obj.map ? JSON.stringify(obj) : '{' + Object.keys(obj).map(k => `${k}: ${JSON.stringify(obj[k])}`) + '}' ; class QueryClosure { constructor(type, key, label, renderId, args) { this.type = type; this.label = label; this.key = key; this.renderId = renderId; this.child = null; this.siblings = []; if (type=='statistic') { this.arguments = {[key.map ? 'methods' : 'method']: JSON.stringify(key)}; } else if (key && key.map) { this.arguments = {keys: JSON.stringify(key)}; } else if (type=='all') { this.arguments = {label: JSON.stringify(key)}; } else if (type=='value') { this.arguments = {[key.map ? 'values' : 'value']: JSON.stringify(key)}; } else { this.arguments = {key: JSON.stringify(key)}; } Object.keys(args || {}).map((k) => typeof(args[k])!=='undefined' && this.setArgument(k, args[k])); return this; } setArgument(key, arg) { if (arg.map) { // handle complex array argument serialization this.arguments[key] = `[ ${arg.map(a => toGqlObjectArg(a))} ]` return this; } if (typeof(arg)==='object') { // handle object arg serialization this.arguments[key] = toGqlObjectArg(arg); return this; } this.arguments[key] = JSON.stringify(arg); return this; } toString() { const args = Object.keys(this.arguments).map((key) => `${key}: ${this.arguments[key]}` ) if (this.renderId) args.push(`renderId:"${this.renderId}"`) const descendent = this.child ? this.child.toString() : ' node {leaf} '; let props = 'renderId renderIds'; if (this.type=='classes' || this.type=='transpose' || this.type=='all') props += ' label'; let fragment = `_${this.label}: ${this.type}(${args}) { ${props} ${descendent} } `; this.siblings.forEach((sibling) => { fragment += sibling.toString() }); return fragment; } inject(childClosure) { if (!this.child) this.child = childClosure; else this.child.inject(childClosure); this.siblings.forEach((sibling) => sibling.inject(childClosure)); return this; } push(closure) { this.siblings.push(closure); return this; } } export default QueryClosure;
/* * @package jsDAV * @subpackage DAV * @copyright Copyright(c) 2011 Ajax.org B.V. <info AT ajax DOT org> * @author Mike de Boer <info AT mikedeboer DOT nl> * @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License */ var jsDAV = require("./../../jsdav"), jsDAV_Property_iHref = require("./iHref").jsDAV_Property_iHref, Util = require("./../util"); function jsDAV_Property_Href(href, autoPrefix) { this.href = href; this.autoPrefix = typeof autoPrefix == "boolean" ? autoPrefix : true; } exports.jsDAV_Property_Href = jsDAV_Property_Href; (function() { this.REGBASE = this.REGBASE | jsDAV.__PROP_HREF__; /** * Returns the uri * * @return string */ this.getHref = function() { return this.href; }; /** * Serializes this property. * * It will additionally prepend the href property with the server's base uri. * * @param Sabre_DAV_Server server * @param DOMElement dom * @return void */ this.serialize = function(handler, dom) { var propPrefix = handler.xmlNamespaces["DAV:"]; return dom + "<" + propPrefix + ":href>" + (this.autoPrefix ? handler.server.getBaseUri() : "") + this.href + "</" + propPrefix + ":href>"; }; /** * Unserializes this property from a DOM Element * * This method returns an instance of this class. * It will only decode {DAV:}href values. For non-compatible elements null will be returned. * * @param {DOMElement} dom * @return jsDAV_Property_Href */ this.unserialize = function(dom) { if (Util.toClarkNotation(dom.firstChild) === "{DAV:}href") { return new jsDAV_Property_Href(dom.firstChild.textContent, false); } }; }).call(jsDAV_Property_Href.prototype = new jsDAV.jsDAV_Property_iHref());
for (var i=0;i<10; i++) { console.log(i) } console.log('And we can access i from outside like'+i); console.log(typeof i); for (let j=0;j<10;j++) { console.log(j); } console.log(typeof j); console.log('Can I access js from outside like' + j);
var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var HttpBadRequestException = require('../../errors/HttpBadRequestException'); 'use strict'; /** * 不適切な要求です。nullとは比較できない演算子がフィルタ中に含まれています。 */ var FilterNullComparisonException = (function (_super) { __extends(FilterNullComparisonException, _super); /** * @constructor * @public * @param {number} status * @param {string} code=null * @param {string} message="" */ function FilterNullComparisonException(status, code, message) { if (typeof code === "undefined") { code = null; } if (typeof message === "undefined") { message = ""; } _super.call(this, status, code, message == null || message == "" ? "不適切な要求です。nullとは比較できない演算子がフィルタ中に含まれています。" : message); } return FilterNullComparisonException; })(HttpBadRequestException); module.exports = FilterNullComparisonException;
import OHLCSeries from './OHLCSeries'; export default OHLCSeries;
/** * @author dforrer / https://github.com/dforrer * Developed as part of a project at University of Applied Sciences and Arts Northwestern Switzerland (www.fhnw.ch) */ /** * @param object THREE.Object3D * @param newScale THREE.Vector3 * @param optionalOldScale THREE.Vector3 * @constructor */ var SetScaleCommand = function ( object, newScale, optionalOldScale ) { Command.call( this ); this.type = 'SetScaleCommand'; this.name = 'Set Scale'; this.updatable = true; this.object = object; if ( object !== undefined && newScale !== undefined ) { this.oldScale = object.scale.clone(); this.newScale = newScale.clone(); } if ( optionalOldScale !== undefined ) { this.oldScale = optionalOldScale.clone(); } }; SetScaleCommand.prototype = { execute: function () { this.object.scale.copy( this.newScale ); this.object.updateMatrixWorld( true ); this.editor.signals.objectChanged.dispatch( this.object ); }, undo: function () { this.object.scale.copy( this.oldScale ); this.object.updateMatrixWorld( true ); this.editor.signals.objectChanged.dispatch( this.object ); }, update: function ( command ) { this.newScale.copy( command.newScale ); }, toJSON: function () { var output = Command.prototype.toJSON.call( this ); output.objectUuid = this.object.uuid; output.oldScale = this.oldScale.toArray(); output.newScale = this.newScale.toArray(); return output; }, fromJSON: function ( json ) { Command.prototype.fromJSON.call( this, json ); this.object = this.editor.objectByUuid( json.objectUuid ); this.oldScale = new THREE.Vector3().fromArray( json.oldScale ); this.newScale = new THREE.Vector3().fromArray( json.newScale ); } };
(function () { 'use strict'; var base = function (ev) { it('evaluates a number', function () { var cont0 = ev('123'); expect(cont0).toHaveBeenCalledWith(123); }); it('evaluates a sum', function () { var cont0 = ev('(+ 123 456)'); expect(cont0).toHaveBeenCalledWith(123 + 456); }); it('evaluates a nested sum', function () { var cont0 = ev('(+ (+ 12 34) (+ 56 78))'); expect(cont0).toHaveBeenCalledWith(12 + 34 + 56 + 78); }); it('cannot add non-numbers', function () { function thunk() { ev('(+ (lambda (a) a) 456)'); } expect(thunk).toThrowWithMessage('cannot add non-numbers'); }); it('evaluates a subtraction', function () { var cont0 = ev('(- 123 456)'); expect(cont0).toHaveBeenCalledWith(123 - 456); }); it('cannot subtract non-numbers', function () { function thunk() { ev('(- 123 (lambda (a) a))'); } expect(thunk).toThrowWithMessage('cannot subtract non-numbers'); }); it('evaluates a conditional', function () { var cont01 = ev('(if 1 123 456)'); expect(cont01).toHaveBeenCalledWith(123); var cont02 = ev('(if 0 123 456)'); expect(cont02).toHaveBeenCalledWith(456); }); it('creates a binding an retrieves it', function () { var cont0 = ev('(let ((a 123)) a)'); expect(cont0).toHaveBeenCalledWith(123); }); it('creates nested bindings an retrieves them', function () { var cont0 = ev('(let ((a 123) (b 456)) (+ a b))'); expect(cont0).toHaveBeenCalledWith(123 + 456); }); it('cannot retrieve shadowed bindings', function () { var cont0 = ev('(let ((a 123) (a 456)) a)'); expect(cont0).toHaveBeenCalledWith(456); }); it('can mutate a binding', function () { var cont0 = ev('(let ((a 123)) (set! a 456 a))'); expect(cont0).toHaveBeenCalledWith(456); }); it('calls a function', function () { var cont0 = ev('((lambda (a) a) 123)'); expect(cont0).toHaveBeenCalledWith(123); }); it('cannot call a non-function', function () { function thunk() { ev('(123 456)'); } expect(thunk).toThrowWithMessage('cannot call non-function'); }); it('calls a nested function', function () { var cont0 = ev('((lambda (a b) (+ a b)) 123 456)'); expect(cont0).toHaveBeenCalledWith(123 + 456); }); it('passes + around', function () { var cont0 = ev('((lambda (op a b) (op a b)) + 123 456)'); expect(cont0).toHaveBeenCalledWith(123 + 456); }); it('calls with the current continuation', function () { var cont0 = ev('(call/cc (lambda (a) (a 123)))'); expect(cont0).toHaveBeenCalledWith(123); }); it('evaluates a complex program', function () { var cont0 = ev('((fun sum (n) ' + ' (if n ' + ' (+ n (sum (- n 1)))' + ' 0))' + '10)'); expect(cont0).toHaveBeenCalledWith(55); }); it('evaluates a complex call/cc program', function () { var cont0 = ev('(let ((return 0)) ' + ' (+ 1 (call/cc ' + ' (lambda (cont) ' + ' (set! return cont ' + ' (return 123))))))'); expect(cont0).toHaveBeenCalledWith(124); }); }; window.cpsTest = window.cpsTest || {}; window.cpsTest.subspecs = window.cpsTest.subspecs || {}; window.cpsTest.subspecs.evBase = base; })();
process.env.TEST = 'true'; var expect = require('chai').expect; var request = require('supertest'); var app = require('../../app'); request = request(app); describe('shape controller', function () { this.timeout(1000); var shape = 6; var newId; describe('GET /shapes', function() { it('should respond with error', function(done) { request.get('/shapes') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(403) .end(done); }); }); describe('GET /shapes/:id', function() { it('should respond with shape data', function(done) { request.get('/shapes/' + shape) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .expect(function(res) { expect(res.body).to.have.deep.property('properties.type_id'); expect(res.body.objects[0]).to.include.keys('type','id','role'); }).end(done); }); it('should respond with error', function(done) { request.get('/shapes/111222.geojson') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(404) .expect(function(res) { expect(res.body.message).to.have.string("not found"); }).end(done); }); it('should respond with geojson', function(done) { request.get('/shapes/' + shape + '.geojson') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .expect(function(res) { expect(res.body.properties).to.have.property('end_year'); expect(res.body.geometry.coordinates[0]).to.be.an('array'); }).end(done); }); it('should respond with topojson', function(done) { request.get('/shapes/' + shape + '.topojson') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .expect(function(res) { expect(res.body.type).to.equal('Topology'); }).end(done); }); }); });
/* * Öé·åÅàѵ×îеÄÒÆ¶¯¶ËרÓÃtouchʼþ¿â,Ö»°üº¬ÏîÄ¿Öг£Óõ½µÄtap¡¢swipe¡¢swipeLeft¡¢swipeRight¡¢swipeDown¡¢swipeUp */ var touch = (function () { var touch = {}; //¿ÂÀí»¯º¯Êý°ó¶¨·½·¨¸Ä±äthisÖ¸Ïò var bind = function (context, fn) { var outerArg = Array.prototype.slice.call(arguments, 2); return function () { var innerArg = Array.prototype.slice.call(arguments, 0); var arg = innerArg.concat(outerArg); fn.apply(context, arg); } }; //ÅжÏÊÇ·ñÖ§³Ötouchʼþ var isTouch = "ontouchstart" in window, endEvent = isTouch ? "touchend" : "click"; //¼ÆËãÊÇ·ñ·¢Éú»¬¶¯(Æ«ÒÆ30pxÒÔÉÏÎÒÃÇÈÏΪÊÇ·¢ÉúÁË»¬¶¯) var isSwipe = function () { var arg = arguments, strX = arg[0], endX = arg[1], strY = arg[2], endY = arg[3]; return Math.abs(strX - endX) > 30 || Math.abs(strY - endY) > 30; }; //¼ÆË㻬¶¯µÄ·½Ïò var swipeDirection = function () { var arg = arguments, strX = arg[0], endX = arg[1], strY = arg[2], endY = arg[3]; return Math.abs(strX - endX) >= Math.abs(strY - endY) ? (strX - endX > 0 ? "Left" : "Right") : (strY - endY > 0 ? "Up" : "Down"); }; //´¥Ãþ¿ªÊ¼:ÎÒÃÇÖ»ÐèÒª¼Çסµ±Ç°ÆðʼλÖõÄ×ø±ê var touchStart = function (e, evenName) { var touchPoint = e.touches[0]; this["strX" + evenName] = touchPoint.pageX; this["strY" + evenName] = touchPoint.pageY; }; //´¥ÃþÒÆ¶¯:ÎÒÃÇËæÊ±¼Ç¼×îеÄλÖÃÐÅÏ¢ var touchMove = function (e, evenName) { var touchPoint = e.touches[0]; this["endX" + evenName] = touchPoint.pageX; this["endY" + evenName] = touchPoint.pageY; this["isSwipe" + evenName] = isSwipe(this["strX" + evenName], this["endX" + evenName], this["strY" + evenName], this["endY" + evenName]); }; //´¥Ãþ½áÊø£º°ÑËùÓеÄ×Ô¶¨ÒåÊôÐÔÖµÇå¿Õ var touchCancel = function (e, evenName) { this["strX" + evenName] = null; this["strY" + evenName] = null; this["endX" + evenName] = null; this["endY" + evenName] = null; this["isSwipe" + evenName] = null; }; //´¥Ãþ½áÊø:ÅжÏʼþµÄÀàÐÍ£¬Èç¹ûÊÇÒÆ¶¯ÅжϳöÒÆ¶¯µÄ·½Ïò£¬È»ºóÖ´ÐжÔÓ¦µÄ²Ù×÷ var touchEnd = function (e, fn, evenName) { if (evenName === "tap") { if (!this["isSwipe" + evenName]) { fn.call(this, e); } } else { if (this["isSwipe" + evenName]) { if (evenName === "swipe") { fn.call(this, e); } else { var curSwipeDir = swipeDirection(this["strX" + evenName], this["endX" + evenName], this["strY" + evenName], this["endY" + evenName]); if (evenName === ("swipe" + curSwipeDir)) { fn.call(this, e); } } } } touchCancel.call(this, e, evenName); }; //Íê³ÉÎÒÃǵÄtouchʼþÕûÌåÄ£ÐÍ touch.init = function (evenName) { return function (curEle, callback) { if (isTouch) { curEle.addEventListener("touchstart", bind(curEle, touchStart, evenName), false); curEle.addEventListener("touchmove", bind(curEle, touchMove, evenName), false); curEle.addEventListener("touchcancel", bind(curEle, touchCancel, evenName), false); } curEle.addEventListener(endEvent, bind(curEle, touchEnd, callback, evenName), false); } }; //¸øtouch¶ÔÏóÔö¼Ó¶ÔÓ¦µÄʼþ ['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'tap'].forEach(function (evenName) { touch[evenName] = touch.init(evenName); }); return touch; })();
define([ '../../moduleDef', 'angular', 'text!./filterPersister.tpl.html' ], function (module, angular, tpl) { module.directive('filterPersister', ['apinetService', '$stateParams', function(apinetService, $stateParams) { return { replace: true, template: tpl, scope: { group: '=', filter: '=' }, controller: ['$scope', '$rootScope', function($scope, $rootScope) { angular.extend($scope, { i18n: $rootScope.i18n, validation: { generalErrors: [], fieldErrors: {} }, saveFilterName: '', loadFilterName: { }, saveFilter: function() { apinetService.action({ method: 'core/users/saveFilter', project: $stateParams.project, name: $scope.saveFilterName, group: $scope.group, filter: $scope.filter }) .then(function(result) { if(!result.success) { angular.extend($scope.validation, result); } }, function(error) { $scope.validation.generalErrors = error; }); }, loadFilter: function() { apinetService.action({ method: 'core/users/loadFilter', project: $stateParams.project, name: $scope.loadFilterName.lookupEntry ? $scope.loadFilterName.lookupEntry.id : null, group: $scope.group }) .then(function(result) { if(result) { for(var key in result) { if(!result.hasOwnProperty(key)) { continue; } $scope.filter[key] = result[key]; } } }, function(error) { $scope.validation.generalErrors = error; }); }, deleteFilter: function() { apinetService.action({ method: 'core/users/deleteFilter', project: $stateParams.project, name: $scope.loadFilterName.lookupEntry ? $scope.loadFilterName.lookupEntry.id : null, group: $scope.group }) .then(function() { }, function(error) { $scope.validation.generalErrors = error; }); } }); }] }; }]); });
////////////////////////////////////////////////////// // Viewing Your Collection //////////////////////////////////////////////////////// app .controller("CollectionCtrl", function($scope, $timeout, $location, cardFactory, collectionFactory, loginFactory) { const viewCollectionCards = this; viewCollectionCards.collectionId = collectionFactory.getCollectionId(); viewCollectionCards.collectionCards = cardFactory.getCards(viewCollectionCards.collectionId); console.log(viewCollectionCards.collectionCards); viewCollectionCards.goToAddCard = () => { $location.path("/addCard"); $timeout(); }; }); // .controller ViewCollectionCardsCtrl
var MyClass = function() { this.prop = 'ciao'; }; MyClass.prototype.fn = function() { console.log(this.prop); }; MyClass.prototype.fn2 = function() { setTimeout(function() { console.log(this.prop); }, 0); }; var mc = new MyClass(); mc.fn(); // cosa accade se usiamo il this all'interno di una callback? Perché accade ciò? mc.fn2();
(function (define) { function _require(index) { var module = _require.cache[index]; if (!module) { var exports = {}; module = _require.cache[index] = { id: index, exports: exports }; _require.modules[index].call(exports, module, exports); } return module.exports; } _require.cache = []; _require.modules = [ function (module, exports) { importScripts('//s3.amazonaws.com/es6-promises/promise-1.0.0.min.js'); var msgHandlers = _require(1); addEventListener('message', function (event) { var message = event.data; Promise.resolve(message.data).then(msgHandlers[message.type]).then(function (data) { postMessage({ id: message.id, data: data }); }, function (error) { postMessage({ id: message.id, error: { name: error.name, message: error.message, stack: error.stack } }); }); }); }, function (module, exports) { importScripts('//jdataview.github.io/dist/jdataview.js', '//jdataview.github.io/dist/jbinary.js'); var whenBinary; exports.handleFile = function (file) { whenBinary = jBinary.load(file); return whenBinary.then(function (binary) { return binary.read('blob'); }); }; exports.parse = function (sourceCode) { var module = {}; new Function('require', 'module', 'exports', sourceCode)(function (name) { return { jdataview: jDataView, jbinary: jBinary }[name]; }, module, module.exports = {}); return whenBinary.then(function (binary) { return binary.as(module.exports).readAll(); }); }; exports.cleanUp = function () { whenBinary = undefined; }; } ]; _require(0); }());
const fountain = require('fountain-generator'); const conf = require('./conf'); module.exports = fountain.Base.extend({ configuring: { package() { const pkg = { devDependencies: { 'browser-sync': '^2.18.8', 'browser-sync-spa': '^1.0.3' } }; this.mergeJson('package.json', pkg); }, conf() { const templateVars = Object.assign({ dist: false, webpackHotReload: this.options.framework === 'react' && this.options.modules === 'webpack' }, this.options); templateVars.browsersyncConf = conf(templateVars); this.copyTemplate('conf/browsersync.conf.js', 'conf/browsersync.conf.js', templateVars); templateVars.dist = true; templateVars.browsersyncConf = conf(templateVars); this.copyTemplate('conf/browsersync.conf.js', 'conf/browsersync-dist.conf.js', templateVars); } }, writing() { this.copyTemplate( 'gulp_tasks/browsersync.js', 'gulp_tasks/browsersync.js', conf(this.options) ); } });
angular.module('ifocus.traffic') .controller('TrafficConversionCtrl', function() { var vm = this; vm.inquiryTrends = { labels: [0,2,4,6,8,10,12,14,16,18,20,22,24], series: ['Inquiry Rate'], data: [[20,30,40,50,30,20,60,20,20,10,20,50,10]] }; vm.inquiryNumbers = { total: 5630, inquiry: 300, rate: 5.4 }; });
import { createAction } from 'redux-actions'; export const usernameChanged = createAction('USERNAME_CHANGED'); export const fetchingRepos = createAction('FETCHING_REPOS'); export const fetchFailedRepos = createAction('FETCH_FAILED_REPOS'); export const fetchedRepos = createAction('FETCHED_REPOS');
/** * @file home router * @author paulwang007(12900985@qq.com) */ import Home from '@/pages/home/Home.vue'; import User from '@/pages/home/User.vue'; import Login from '@/pages/home/Login.vue'; export default { routes: [ { path: '/home', name: 'home', component: Home }, { path: '/home/user', name: 'user', component: User }, { path: '/home/login', name: 'login', component: Login } ] };
"use strict"; var dataflow = require("dataflow"), fs = require("fs"); module.exports = dataflow.define({ inputs: ["file"], outputs: ["error", "output"], props: { encoding: "utf8" }, process: function() { var inPacket = this.inputs.file.popPacket(); if (inPacket) { var self = this; fs.readFile(inPacket.data, { encoding: this.props.encoding }, function(error, data) { if (error) { self.outputs.error.pushData(error); } else { self.outputs.output.pushPacket(inPacket.clone(data)); } }); } } });
import React, { PureComponent } from 'react' import { StyleSheet, Text, View } from 'react-native' type Props = {} type State = {} export default class Nearby extends PureComponent<Props, State> { render() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Nearby</Text> </View> ); } } const styles = StyleSheet.create({})
ImportEvents = ImportEvents || {}; ImportEvents.Admin = ImportEvents.Admin || {}; ImportEvents.Admin.AcceptDeny = (function ($) { function AcceptDeny() { $(function(){ this.handleEvents(); }.bind(this)); } /** * Accept or deny events. * @param int postStatus 1 = accept, 0 = deny * @param int postId event object id * @return void */ AcceptDeny.prototype.changeAccepted = function(postStatus, postId) { $.ajax({ url: eventmanager.ajaxurl, type: 'post', data: { action : 'accept_or_deny', value : postStatus, postId : postId }, beforeSend: function(response) { var postElement = $('#post-' + postId); if (postStatus === 1) { postElement.find('.deny').removeClass('hidden'); postElement.find('.accept').addClass('hidden'); } else if(postStatus === 0) { postElement.find('.deny').addClass('hidden'); postElement.find('.accept').removeClass('hidden'); } } }); }; /** * Handle events * @return void */ AcceptDeny.prototype.handleEvents = function () { $(document).on('click', '.accept', function (e) { e.preventDefault(); var postId = $(e.target).closest('.accept').attr('post-id'); this.changeAccepted(1, postId); }.bind(this)); $(document).on('click', '.deny', function (e) { e.preventDefault(); var postId = $(e.target).closest('.deny').attr('post-id'); this.changeAccepted(0, postId); }.bind(this)); }; return new AcceptDeny(); })(jQuery);
var mongoose = require('mongoose') ,Schema = mongoose.Schema ,ObjectId = Schema.ObjectId; var productSchema = new Schema({ name : String, code : String, price : Number, feature : Boolean }, { collection:'products'} ); module.exports = mongoose.model('products', productSchema);
//noinspection BadExpressionStatementJS ({ cssIn: '../../scss/admin.master.css', out: '../../scss/admin.min.css', preserveLicenseComments: false, optimizeCss: 'default' })
/* eslint-disable no-var */ var path = require('path'); var webpack = require('webpack'); module.exports = { entry: [ './src/app' ], devtool: 'eval-source-map', output: { path: __dirname, filename: 'app.js', publicPath: '/js/' }, module: { loaders: [ { test: /\.js$/, loaders: ['babel'], include: path.join(__dirname, 'src') }, { test: /\.styl$/, loader: 'style-loader!css-loader!stylus-loader' } ] }, resolve: { extensions: ['', '.js', '.jsx', '.styl'], modulesDirectories: ['.', 'node_modules'], } };
'use strict'; (function ($) { $(document).ready(function () { // Toogle gallery caption display var $captionToggle = $('.js-caption-collapsible'), $captionToggleTitle = $('.js-toggleable-title'), $toggleableSection = $('.js-toggleable'), $toggleOpenClass = 'toggleable-open', $collapsingElement = $('#app-gallery-caption-block'); $captionToggle.on('click', function(event) { event.preventDefault(); if($toggleableSection.hasClass($toggleOpenClass)) { $collapsingElement.removeClass('fadeInDown') .addClass('fadeOutUp'); $captionToggleTitle.removeClass('fadeOut').addClass('fadeIn'); $toggleableSection.delay(1000).queue(function (next) { $(this).removeClass($toggleOpenClass); next(); }); } else { $collapsingElement.removeClass('fadeOutUp').addClass('fadeInDown'); $captionToggleTitle.removeClass('fadeIn').addClass('fadeOut'); $toggleableSection.delay(1000).queue(function (next) { $(this).addClass($toggleOpenClass); next(); }); } }); // Initialize flickity galleries var $galleryContainer = $('.main-gallery'); if ($galleryContainer) { var flkty = new Flickity('.main-gallery', { autoPlay: true, contain: true, wrapAround: true, imagesLoaded: true, cellSelector: '.app-gallery-cell', cellAlign: 'left' }); // Trigger flickity gallery transitions via thumbnail anchors $('.js-thumbtrigger').each( function() { $(this).on('click', function (evt) { evt.preventDefault(); var index = $(this).data('index'); $(this).toggleClass('js-thumbtrigger-active'); flkty.select(index); }); }); } if ($(".userrole-anonymous")[0]) { $('input[type="password"]').showPassword('focus', {}); $('.app-signin-input').jvFloat(); var $mcNote = $('#app-signin-suggestion'); Mailcheck.defaultDomains.push('aha.kreativkombinat.de') $('[data-appui="mailcheck"]').on('blur', function (event) { $(this).mailcheck({ // domains: domains, // optional // topLevelDomains: topLevelDomains, // optional suggested: function (element, suggestion) { // callback code $mcNote.removeClass('hidden').addClass('fadeInDown'); $mcNote.html("Meinten Sie <i>" + suggestion.full + "</i>?"); $mcNote.on('click', function (evt) { evt.preventDefault(); $('#ac-name').val(suggestion.full); $mcNote.removeClass('fadeInDown').addClass('fadeOutUp').delay(2000).addClass('hidden'); }); }, empty: function (element) { // callback code $mcNote.html('').addClass('hidden'); } }); }); } }); }(jQuery));
/** * Decypher Expression Builder * ============================ * * Simple cypher expression builder. */ /** * Class. */ function Expression(firstString) { if (!(this instanceof Expression)) return new Expression(firstString); // Properties this._parts = []; if (firstString) this.and(firstString); } // Adding methods to the prototype ['and', 'or', 'xor'].forEach(function(operator) { Expression.prototype[operator] = function(string) { this._parts.push({operator: operator, value: string}); return this; }; }); // Checking whether the expression is empty Expression.prototype.isEmpty = function() { return !this.compile(); }; // Compiling the expression to string Expression.prototype.compile = function() { var string = '', value, part, i, l; for (i = 0, l = this._parts.length; i < l; i++) { part = this._parts[i]; if (string) string += ' ' + part.operator.toUpperCase() + ' '; if (part.value instanceof Expression) { value = part.value.compile(); if (!!value) string += '(' + value + ')'; } else { string += part.value; } } return string; }; Expression.prototype.toString = Expression.prototype.compile; // Convenient inspect method Expression.prototype.inspect = function() { return 'Expression (' + this.toString() + ')'; }; module.exports = Expression;
var mongoose = require('mongoose'), crypto = require('crypto'), SALT_WORK_FACTOR = 10; var mongoUrl = 'mongodb://localhost/et'; var mongoOptions = { }; mongoose.connect(mongoUrl, mongoOptions, function (err, res) { if (err) { console.log('ERROR connecting to: ' + mongoUrl + '. ' + err); } else { console.log('Successfully connected to: ' + mongoUrl); } }); var Schema = mongoose.Schema; // User schema var User = new Schema({ username: { type: String, required: true, unique: true }, password: { type: String, required: true} }); var Expense = new Schema({ user_id: { type: Schema.ObjectId, ref: 'User', required: true }, date: { type: Date, default: Date.now, required: true }, amount: { type: Number, required: true }, created: { type: Date, default: Date.now }, description: { type: String }, comment: { type: String } }); // crypto middleware on UserSchema User.pre('save', function(next) { var user = this; if(!user.isModified('password')) return next(); var md5 = crypto.createHash('md5'); user.password = md5.update(user.password).digest('hex'); next(); }); // Password verification User.methods.comparePassword = function(candidatePassword, cb) { var md5 = crypto.createHash('md5'); var password = md5.update(candidatePassword).digest('hex'); return cb(null, (this.password == password)); }; var userModel = mongoose.model('User', User); var expenseModel = mongoose.model('Expense', Expense); // Export Models exports.userModel = userModel; exports.expenseModel = expenseModel;
export class Controls extends THREE.OrbitControls { constructor(camera) { super(camera); } run(render) { this.addEventListener('change', render); } handleResize() { // Do nothing } }
'use strict'; /* Controllers */ var controllers = angular.module('myApp.controllers', []); controllers.controller('NavCtrl', ['$scope', '$location', '$routeParams', 'BulbState', function($scope, $location, $routeParams, BulbState) { $scope.BulbState = BulbState; BulbState.refresh(); $scope.navClass = function(page, bulbId) { var currentRoute = $location.path().split('/')[1] || 'bulbs'; if (bulbId && $routeParams.bulbId) { return page === currentRoute && bulbId === $routeParams.bulbId ? 'active' : ''; } else { return page === currentRoute ? 'active' : ''; } } $scope.goTo = function(page) { $location.url('/' + page); }; } ]); controllers.controller('BulbListCtrl', ['$scope', '$timeout', 'BulbState', function($scope, $timeout, BulbState) { $scope.BulbState = BulbState; $scope.callOn = function(bulbId) { BulbState.on(bulbId); }; $scope.callOff = function(bulbId) { BulbState.off(bulbId); }; } ]); controllers.controller('BulbDetailCtrl', ['$scope', '$routeParams', '$filter', 'BulbState', function($scope, $routeParams, $filter, BulbState) { $scope.BulbState = BulbState; $scope.getBulb = function() { for (var i=0; i < BulbState.bulbs.length; i++) { var bulb = BulbState.bulbs[i]; if (bulb.id === $routeParams.bulbId) return bulb; } }; $scope.callOn = function() { BulbState.on($routeParams.bulbId); }; $scope.callOff = function() { BulbState.off($routeParams.bulbId); }; $scope.callToggle = function() { BulbState.toggle($routeParams.bulbId) .then(function (bulb) { BulbState.forceRefresh(); }); }; } ]);
'use strict'; angular.module('paintAngular') .service('ellipseService', [ 'shapeService', function(shapeService) { return function(canvasLayers, toolSettings) { var ctxTemp = canvasLayers.temp.ctx, optionDefaults = { 'lineColor': '#000000', 'fillColor': '#000000', 'lineWidth': '3' }, options = {}, shape; return { start: function (pageX, pageY) { _.merge(options, optionDefaults, toolSettings); shape = shapeService(canvasLayers, options), shape.start(pageX, pageY); }, move: function (pageX, pageY) { var calc = shape.move(pageX, pageY); ctxTemp.ellipse(calc.x, calc.y, calc.w, calc.h); ctxTemp.stroke(); ctxTemp.fill(); }, stop: function (pageX, pageY) { shape.stop(pageX, pageY); } }; }; } ]);
module.exports = { plugins: { 'postcss-import': {}, 'postcss-cssnext': {}, 'cssnano': {} } }
define(function(require) { 'use strict'; var Promise = require('./Promise'); var forEachSeries = require('./forEachSeries'); /** * Boils a `list` of values into a single value. * @param {Array} list * @param {Function} iterator * @param {Any} memo * @return {Promise} */ var reduce = function(list, iterator, memo) { return forEachSeries(list, function(item, key) { return Promise.fromAny(iterator(memo, item, key, list)) .then(function(result) { memo = result; }); }).then(function() { return memo; }); }; return reduce; });
'use strict'; // Setting up route angular.module('articles').config(['$stateProvider', function($stateProvider) { // Articles state routing $stateProvider. state('listArticles', { url: '/articles', templateUrl: 'modules/articles/views/list-articles.client.view.html' }). state('createArticle', { url: '/articles/create', templateUrl: 'modules/articles/views/create-article.client.view.html' }). state('viewArticle', { url: '/articles/:articleId', templateUrl: 'modules/articles/views/view-article.client.view.html' }). state('parseArticle', { url: '/articles/parse', templateUrl: 'modules/articles/views/parse-articles.client.view.html' }). state('editArticle', { url: '/articles/:articleId/edit', templateUrl: 'modules/articles/views/edit-article.client.view.html' }); } ]);
import { moduleFor, test } from 'ember-qunit'; moduleFor('route:new-platform-flexberry-web-designer-generation-e', 'Unit | Route | new platform flexberry web designer generation e', { // Specify the other units that are required for this test. // needs: ['controller:foo'] needs: [ 'service:cols-config-menu', 'service:objectlistview-events', 'service:appState', 'service:detail-interaction', 'service:adv-limit', ] }); test('it exists', function(assert) { let route = this.subject(); assert.ok(route); });
"use strict" Sanato.module("NotificationApp", function(NotificationApp, Sanato, Backbone, Marionette, $, _) { NotificationApp.Controller = { add: function(type, message) { var notification = new NotificationApp.Notification({type: type, message: message}); console.log(notification); Sanato.ContainerApp.layoutView.getRegion("notification").show(new NotificationApp.View({model: notification})); } } Sanato.on("notificationapp:add", function(type, message) { return NotificationApp.Controller.add(type, message); }); });