text
stringlengths
2
6.14k
var qunit = require("qunit"); homebridge = require("../../node_modules/homebridge/lib/api.js"); qunit.options.coverage = { dir: "/tmp/" }; qunit.run({ code : "index.js", tests : [ 'switchBinary', 'issue-48.js', 'issue-69.js', 'issue-72.js', 'issue-70.js', 'update-without-change.js' ].map(function (v) { return './tests/js/' + v; }) });
var HashTree = require('../../lib/hash-tree'), path = require('path'); describe('Hash Tree', function() { it('computes hashes', function( done ) { HashTree(path.resolve(__dirname, '../')).computeHashes(function( err, nodes ) { if (err) { return done(err); } assert.property(nodes, 'unit'); assert.property(nodes.unit, 'hash-tree.js'); assert.match(nodes.unit['hash-tree.js'], /[a-f0-9]{24}/i); done(err); }); }); it('includes paths', function( done ) { HashTree(path.resolve(__dirname, '../'), { include: [ '**/*.opts' ] }).computeHashes(function( err, nodes ) { if (err) { return done(err); } assert.deepEqual(nodes, { 'mocha.opts': '807f8a5b99ece3cb0352d14953fe260a', unit: {} }); done(err); }); }); it('excludes paths', function( done ) { HashTree(path.resolve(__dirname, '../'), { exclude: [ '**/*.opts' ] }).computeHashes(function( err, nodes ) { if (err) { return done(err); } assert.notProperty(nodes, 'mocha.opts'); done(err); }); }); describe('File Diffs', function() { beforeEach(function( done ) { var hashTree = this.unitTree = new HashTree(path.resolve(__dirname, '../')); hashTree.computeHashes(done); }); beforeEach(function( done ) { var hashTree = this.libTree = new HashTree(path.resolve(__dirname, '../../lib')); hashTree.computeHashes(done); }); it("lists paths that don't match", function() { var diffList = this.unitTree.computeDiff(this.libTree.nodes); assert.include(diffList, 'unit/hash-tree.js'); }); it("doesn't false positive", function() { var diffList = this.unitTree.computeDiff(this.unitTree.nodes); assert.lengthOf(diffList, 0); }); }); });
/// <reference path="typings/tsd.d.ts"/> var through = require('through'); var DependencyResolver = require('dependency-resolver'); var path = require('path'); function getFileReferences(contents) { var regex = 'reference path="(.+)"'; var matches = contents.match(new RegExp(regex, 'g')); if (!matches) { return []; } return matches.map(function (m) { return m.match(new RegExp(regex))[1]; }); } function tsOrder() { var res = new DependencyResolver(); var files = {}; function onFile(file) { files[file.path] = file; res.add(file.path); getFileReferences(file.contents.toString()).forEach(function (p) { var depPath = path.resolve(path.dirname(file.path), p); res.setDependency(file.path, depPath); }); } function onEnd() { var _this = this; res.sort().forEach(function (serv) { _this.emit('data', files[serv]); }); return this.emit('end'); } return through(onFile, onEnd); } module.exports = tsOrder;
const os = require("os") module.exports = { args: [ {name: "name", message: "The source file's name"}, ], files: ({name}) => [ { name: `${name}.c`, content: `` }, { name: `${name}.h`, content: ` #ifndef ${name.constCase()}_H #define ${name.constCase()}_H #endif ` } ] }
'use strict'; module.exports = function(config) { config.set({ files: [ 'https://code.jquery.com/jquery-3.1.1.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.14/angular-filter.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-mocks.js', './google.js', './bin/app.js', './test.js', {pattern: './bin/templates/*.html', included: false, served: true} ], frameworks: ['mocha', 'chai'], port: 9876, browsers: ['Chrome'], proxies: { '/templates/': 'http://localhost:9876/base/bin/templates/' } }); };
import parent from '../render/dom/parent' import { property } from '../render/static' const injectable = {} export default injectable if (typeof window === 'undefined') { Object.defineProperty(global.Element.prototype, 'value', { configurable: true, get () { return this.getAttribute('value') }, set (val) { this.setAttribute('value', val) } }) } /* element.setAttributeNS( namespace, name, value) element.removeAttributeNS( namespace, attrName); */ if (typeof window === 'undefined') { global.Element.prototype.setAttributeNS = function (ns, key, value) { this.setAttribute(key, value) } global.Element.prototype.getAttributeNS = function (ns, key) { this.getAttribute(key) } global.Element.prototype.removeAttributeNS = function (ns, key) { this.removeAttribute(key) } } injectable.props = { attr: { type: 'property', render: { static: property, state (t, state, type, subs, tree, id, pid) { const pnode = parent(tree, pid) if (pnode && !pnode._propsStaticParsed) { property(t, pnode) pnode._propsStaticParsed = true } } }, props: { type: null, // default to wrong one --- it defaults to element.... default: { props: { name: true }, render: { static (t, pnode) { const val = t.compute() const key = t.name || t.key if (~key.indexOf(':')) { const namespace = 'http://www.w3.org/1999/xlink' if (val === t || val === void 0) { pnode.removeAttributeNS(namespace, key) } else { pnode.setAttributeNS(namespace, key, val) } } else { if (val === t || val === void 0) { pnode.removeAttribute(key) } else { pnode.setAttribute(key, val) } } }, state (t, state, type, subs, tree, id, pid) { const pnode = parent(tree, pid) const key = t.name || t.key if (~key.indexOf(':')) { const namespace = 'http://www.w3.org/1999/xlink' if (type === 'remove') { if (pnode) { pnode.removeAttributeNS(namespace, key) } } else { let val = t.compute(state, state) const type = typeof val if (type === 'boolean') { val = val + '' } if (val && (type === 'object' && val.inherits) || val === void 0) { if (pnode.getAttributeNS(namespace, key)) { pnode.removeAttribute(namespace, key) // missing } } else { if (!val && type === 'object') { if (pnode) pnode.removeAttribute(key) } else if (pnode.getAttributeNS(namespace, key) != val) { // eslint-disable-line pnode.setAttributeNS(namespace, key, val) } } } } else { if (type === 'remove') { if (pnode) { pnode.removeAttribute(key) } } else { let val = t.compute(state, state) const type = typeof val if (type === 'boolean') { val = val + '' } if ((type === 'object' && (!val || val.inherits)) || val === void 0) { if (pnode.getAttribute(key)) { pnode.removeAttribute(key) // missing } } else { if (pnode.getAttribute(key) != val) { // eslint-disable-line pnode.setAttribute(key, val) } } } } } } }, value: { render: { static (t, pnode) { const val = t.compute() // missing pnode.value = val // missing (needs a way on server this does not work) }, state (t, state, type, subs, tree, id, pid) { const pnode = parent(tree, pid) if (type === 'remove') { if (pnode) { pnode.value = '' } // missing } else { const val = t.compute(state, state) if (val != pnode.value) { // eslint-disable-line pnode.value = val === t ? '' : val } } } } } } } }
import { ipcRenderer } from 'electron' import { ADD_REQUEST, ADD_RESPONSE, UPDATE_FILTER, GET_HTTP_MESSAGE_DETAILS_SUCCESS, TOGGLE_FILTER_INPUT } from '../../constants/actionTypes' import { REQUEST_HTTP_MESSAGE_DETAILS, HTTP_MESSAGE_DETAILS, HTTP_MESSAGE_REQUEST, REQUEST_HTTP_MESSAGE_REQUEST } from '../../constants/ipcMessages' import { sendToProxyWindow } from '../../windows' import http from 'http' import { load as loadConfig } from '../../lib/config' const config = loadConfig() export function addRequest (request) { return {type: ADD_REQUEST, payload: request} } export function addResponse (response) { return {type: ADD_RESPONSE, payload: response} } export function getHttpMessageDetailsSuccess (data) { return {type: GET_HTTP_MESSAGE_DETAILS_SUCCESS, payload: data} } export function getHttpMessageDetails (requestId) { return (dispatch) => { sendToProxyWindow(REQUEST_HTTP_MESSAGE_DETAILS, requestId) ipcRenderer.on(HTTP_MESSAGE_DETAILS, (e, details) => { dispatch(getHttpMessageDetailsSuccess(details)) }) } } export function replayRequest (requestId) { return (dispatch) => { sendToProxyWindow(REQUEST_HTTP_MESSAGE_REQUEST, requestId) ipcRenderer.once(HTTP_MESSAGE_REQUEST, (e, request) => { const options = { port: config.port, hostname: 'localhost', method: request.method, path: `${request.protocol}//${request.host}${request.path}`, headers: request.headers } const req = http.request(options) req.write(Buffer.from(request.body.data)) req.end() }) } } export function updateFilter (filter) { return {type: UPDATE_FILTER, payload: filter} } export function toggleFilterInput () { return {type: TOGGLE_FILTER_INPUT} }
var glob = require('glob') module.exports = function globTests() { return glob.sync('./test/spec/**/*.spec.{js,jsx}') }
'use strict' var _url = document.createElement('a') module.exports = function (url) { _url.href = url return { hash: _url.hash, href: _url.href, urlpath: _url.pathname, search: _url.search, host: _url.hostname, port: _url.port } }
var eos = require('end-of-stream') module.exports = each function each (stream, fn, cb) { var waiting = false var error = null var ended = false stream.on('readable', onreadable) read(null) if (cb) eos(stream, {readable: true, writable: false}, done) return stream function done (err) { error = err ended = true if (waiting) return cb(error) } function onreadable () { if (waiting) read(null) } function read (err) { if (err) { waiting = true stream.destroy(err) return } var data = stream.read() waiting = !data if (waiting && ended) return cb(error) if (data) fn(data, read) } }
const readline = require('readline'); const Spinner = function (text = '%s') { if ('string' == typeof text) { text = { text }; } this._text = text.text || ''; this._list = text.spinners || function ( spin = (t) => ['|', '/', '-', '\\'][t % 4], list = [] ) { for (let n = 0; n < 19; n++) list.push( `[${"█".repeat(n)}${".".repeat(18 - n)}] ${spin(n)}` ); for (let n = 19; n < 36; n++) list.push( `[${".".repeat(n - 18)}${"█".repeat(36 - n)}] ${spin(n)}` ); return list; }(); this._second = text.delay || 60; this._output = text.stream || process.stdout; this.onTick = text.onTick || function (t) { this.clear(this._output); this._output.write(t); }; }; Spinner.prototype.start = function (index = 0) { this._id = setInterval(() => { this.onTick(this._text.indexOf('%s') > -1 ? this._text.replace('%s', this._list[index]) : this._list[index] + ' ' + this._text); index = ++index % this._list.length; }, this._second); }; Spinner.prototype.stop = function (clear) { clearInterval(this._id); this._id = undefined; clear && this.clear(); }; Spinner.prototype.clear = function () { readline.clearLine(this._output, 0); readline.cursorTo(this._output, 0); }; module.exports = Spinner;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Tiles = void 0; var tile_size_1 = require("./tile-size"); var tile_sizes_1 = require("./tile-sizes"); var Tiles = /** @class */ (function () { function Tiles() { // #region Properties this.showTiles = true; this.tiles = new Array(); this.isTilesLoaded = false; this.hideTileIfOnlyOne = true; // not yet evaluated in HTML, but this is the standard behavior this.tileSizes = tile_size_1.TileSize.getTileSizes(); this.nextLeft = 0; this.nextTop = 0; this.columnHeightMax = 0; // #endregion } // #endregion // #region Methods Tiles.prototype.addTile = function (tile) { this.isTilesLoaded = true; var tileSize = this.tileSizes[tile.tileSize]; tile.size = tile_sizes_1.TileSizes[tile.tileSize]; // Get CSS Name tile.top = this.nextTop + 'px'; tile.left = this.nextLeft + 'px'; this.nextLeft += tileSize.width; if (tileSize.height > this.columnHeightMax) { this.columnHeightMax = tileSize.height; } if (this.nextLeft > 540) { this.nextLeft = 0; this.nextTop += this.columnHeightMax; this.columnHeightMax = 0; } this.tiles.push(tile); return tile; }; return Tiles; }()); exports.Tiles = Tiles; //# sourceMappingURL=tiles.js.map
function getTypes (types) { return function (raw) { return types[raw.type] } } module.exports = getTypes
'use strict' let gulp = require("gulp"); let sourcemaps = require("gulp-sourcemaps"); let babel = require("gulp-babel"); let watch = require('gulp-watch'); let changed = require('gulp-changed'); let nodemon = require('gulp-nodemon'); let plumber = require('gulp-plumber'); let path = require('path'); let demon; gulp.task("default", ['es6']); gulp.task("sourcemaps", function() { return gulp.src("src/**/*.js") .pipe(sourcemaps.init()) .pipe(babel()) .pipe(sourcemaps.write("./maps")) .pipe(gulp.dest("build")); }); gulp.task("es6-js", function() { return gulp.src(["src/**/*.js", "tests/**/*.js"]) .pipe(changed("build")) .pipe(plumber({ errorHandler: function(e) { console.log('error', e); } })) .pipe(babel()) .pipe(gulp.dest("build")) .on('end', function() { console.log('end build'); }); }); gulp.task("json", function() { return gulp.src(["src/**/*.json", "tests/**/*.json"]) .pipe(gulp.dest("build")); }); gulp.task('es6', ['es6-js', 'json']); gulp.task('upd', ['es6'], function() { return gulp.src(["build/**/*.js"]) .pipe(gulp.dest("../iris-v2/node_modules/iris-service-sound-conjunct/build")); }); gulp.task('test-upd', ['start-test'], function() { gulp.watch(["src/**/*.js", "tests/**/*.js"], ['upd']); }); gulp.task('test', ['start-test'], function() { gulp.watch(["src/**/*.js", "tests/**/*.js"], ['es6']); }); gulp.task('serve', ['start-serve'], function() { gulp.watch(["src/**/*.js", "tests/**/*.js"], ['es6']); }); gulp.task('start-test', function() { demon = nodemon({ script: 'build/run.js', watch: ['build/'], execMap: { "js": "node --harmony " }, env: { 'NODE_ENV': 'development' } }); }); gulp.task('start-serve', function() { demon = nodemon({ script: 'build/index.js', watch: ['build/'], execMap: { "js": "node --harmony " }, env: { 'NODE_ENV': 'development' } }); });
'use strict'; /** * Returns the result of applying concat to the result of applying a function to values. * * @param {array} vals - an array of values * @param {function} fn * @param {object} ctx * * @return {array} */ module.exports = function mapconcat(vals, fn, ctx) { return Array.prototype.concat.apply([], vals.map(fn, ctx)); };
export const ADD_REQUEST = 'ADD_REQUEST' export const ADD_RESPONSE = 'ADD_RESPONSE' export const GET_HTTP_MESSAGE_DETAILS_SUCCESS = 'GET_HTTP_MESSAGE_DETAILS_SUCCESS' export const UPDATE_FILTER = 'UPDATE_FILTER' export const TOGGLE_FILTER_INPUT = 'TOGGLE_FILTER_INPUT'
// We need to import the CSS so that webpack will load it. // The MiniCssExtractPlugin is used to separate it out into // its own CSS file. import "../css/app.css" // webpack automatically bundles all modules in your // entry points. Those entry points can be configured // in "webpack.config.js". // // Import deps with the dep name or local files with a relative path, for example: // // import {Socket} from "phoenix" // import socket from "./socket" // import "phoenix_html" import {Socket} from "phoenix" import NProgress from "nprogress" import {LiveSocket} from "phoenix_live_view" import hooks from "./hooks" window.addEventListener('phx:hook:svelte', (e) => { Object.values(liveSocket.main.viewHooks) .filter(x => x.el.id == e.detail.svelteID)[0]._instance.serverEvent(e.detail) }) let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content") let liveSocket = new LiveSocket("/live", Socket, { hooks, params: {_csrf_token: csrfToken}, /* metadata: { click: (e, el) => { return { svelteID: el.closest('[phx-hook="svelte-component"]').id } } } */ }) // Show progress bar on live navigation and form submits window.addEventListener("phx:page-loading-start", info => NProgress.start()) window.addEventListener("phx:page-loading-stop", info => NProgress.done()) // connect if there are any LiveViews on the page liveSocket.connect() // expose liveSocket on window for web console debug logs and latency simulation: liveSocket.enableDebug() // >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session // >> liveSocket.disableLatencySim()
var gulp = require('gulp'); var mocha = require('gulp-mocha'); var eslint = require('gulp-eslint'); var istanbul = require('gulp-istanbul'); var formatter = require('eslint-friendly-formatter'); var lint = ['gulpfile.js', 'index.js', 'utils.js']; gulp.task('coverage', function() { return gulp.src(lint.concat(['!gulpfile.js'])) .pipe(istanbul({ includeUntested: true })) .pipe(istanbul.hookRequire()); }); gulp.task('test', ['coverage'], function() { return gulp.src('test.js') .pipe(mocha({ reporter: 'spec' })) .pipe(istanbul.writeReports()) .pipe(istanbul.writeReports({ reporters: [ 'text' ], reportOpts: {dir: 'coverage', file: 'summary.txt'} })); }); gulp.task('lint', function() { return gulp.src(lint.concat(['test.js'])) .pipe(eslint()) .pipe(eslint.format(formatter)); }); gulp.task('default', ['test']);
/** * 分类栏条目 */ import React, { Component, PropTypes } from 'react'; import classnames from 'classnames'; import { Link } from 'react-router'; export default class CategoryBar extends Component { render(){ const { text , active , link ,...other } = this.props; return ( <li {...other}> <Link to={link} className={classnames({active})} > {text} </Link> </li> ); } }
/* Project architecture can be changed if the project grows - instead of using 'type' oriented * architecture, i.e. to have directories such as 'controllers', 'services' etc., * we can use 'feature' oriented structure, where each feature has its own * directory with all the needed components, e.g. feature for 'login' form can * have its controller, service, directive and etc in one folder called 'login' * which can be placed under a common folder in /scripts/ called for example * 'modules' or 'components'. * */ var abApp = angular.module('address-book', ['LocalStorageModule', 'ngRoute', 'ngAnimate', 'addressBookServices', 'addressBookFactories', 'addressBookControllers']); abApp.config(['localStorageServiceProvider', '$routeProvider', function (localStorageServiceProvider, $routeProvider) { localStorageServiceProvider.setPrefix('address-book'); $routeProvider .when('/', { templateUrl: 'views/address-list/address-list.html', controller: 'AddressListController', resolve: { addresses: ['AddressEntryFactory', function (AddressEntryFactory) { return AddressEntryFactory.getAllEntries(); }] } }) .otherwise({redirectTo: '/'}); }]).constant('_', window._) .run(['CountryListFactory', function (CountryListFactory) { // Get the counties data var cl = require('country-list')(); CountryListFactory.setCountryListService(cl); }]);
version https://git-lfs.github.com/spec/v1 oid sha256:8e85cd0bba914ed57ac03ce72804dbe6e83dbef37296bdcacb969c811c7aeecd size 1568
//getter methods console.log("Syntax: "); console.log("The get syntax binds an object property \n to a function that will be called when that property is looked up."); console.log("{get prop() { ... } }"); console.log("{get [expression]() { ... } }"); // prop: The name of the property to bind to the given function. // expression: Starting with ECMAScript 6, you can also use expressions for a computed property name to bind to the given function. /* Description Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want reflect the status of an internal variable without requiring the use of explicit method calls. In JavaScript, this can be accomplished with the use of a getter. It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property. - It can have an identifier which is either a number or a string; -It must have exactly zero parameters (see Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments for more information); -It must not appear in an object literal with another get or with a data entry for the same property ({ get x() { }, get x() { } } and { x: ..., get x() { } } are forbidden). A getter can be removed using the delete operator */ console.log("Example"); var log = ['test']; var obj ={ get latest(){ if (log.length == 0) return undefined; return log[log.length -1] } } console.log(obj.latest); console.log("If you want to remove the getter, you can just delete it: delete obj.latest;");
const AstNode = require('./ast-node'); class ForLoopBodyWithValue extends AstNode { type() { return 'for_loop_body_with_value'; } /** * @param {ParseContext} context * @return {AstNodeParseResult} */ parse(context) { const tm = context.sourceTextManager(); tm.whitespace(); const v = context.parse('temp_var').expr; tm.whitespaceRequired(); tm.next('in'); tm.whitespaceRequired(); const keys = context.parse('var').keys; return { type: this.type(), tmp_k: null, tmp_v: v, keys: keys, }; } } module.exports = ForLoopBodyWithValue;
// task browserSync const gulp = require('gulp'); const config = require('../gulp.config'); const path = require('path'); const browserSync = require('browser-sync').create(); const browserSyncTask = () => { browserSync.init(config.tasks.browserSync); let watchableTasks = [ 'scripts', 'html', 'styles' ]; watchableTasks.forEach((taskName) => { let files = path.join( config.root, config.tasks[taskName].src, `/**/*.{${config.tasks[taskName].extensions}}` ); if (taskName === 'scripts') { files = [ path.join( config.root, config.tasks[taskName].src, `/**/*.{${config.tasks[taskName].extensions}}` ), path.join( config.root, config.tasks.vueify.src, `/**/*.{${config.tasks.vueify.extensions}}` ) ]; } let watchTaskName = `watch${taskName[0] .toUpperCase() .concat(taskName.slice(1))}`; gulp.task(watchTaskName, [taskName], (done) => { browserSync.reload(); done(); } ); gulp.watch(files, [watchTaskName]); }); }; gulp.task('browserSync', browserSyncTask); module.exports = browserSyncTask;
var hoverZoomPlugins = hoverZoomPlugins || []; hoverZoomPlugins.push({ name:'YouTube', prepareImgLinks:function (callback) { var res = [], repl = 'http://i1.ytimg.com/vi/$1/0.jpg'; function decodeQueryString(queryString) { var keyValPairs = queryString.split("&"), params = {}; for (var i = 0; i < keyValPairs.length; i++) { var key = decodeURIComponent(keyValPairs[i].split("=")[0]); params[key] = decodeURIComponent(keyValPairs[i].split("=")[1] || ""); } return params; } function decodeStreamMap(url_encoded_fmt_stream_map) { var streams = url_encoded_fmt_stream_map.split(","), sources = {}; for (var i = 0; i < streams.length; i++) { var stream = decodeQueryString(streams[i]); var type = stream.type.split(";")[0]; var quality = stream.quality.split(",")[0]; stream.original_url = stream.url; stream.url = "" + stream.url + "&signature=" + stream.sig; sources["" + type + " " + quality] = stream; } return sources; } function getSource(sources, type, quality) { var lowest = null, exact = null; for (var key in sources) { var source = sources[key]; if (source.type.match(type)) { if (source.quality.match(quality)) { exact = source; } else { lowest = source; } } } return exact || lowest; } function prepareVideoPreview(link, id) { if (link.hasClass('hoverZoomLoading') || link.hasClass('hoverZoomLink') || link.hasClass('ytp-title-link')) return; link.addClass('hoverZoomLoading'); var match = link.attr('href').match(/[\?&]t=([\dhm]+)/); var start = match && match.length >= 2 ? match[1] : null; if (start && start.indexOf('m') !== -1) { var parts = start.split('m'); if (parts.length == 2) { var parts2 = start.split('h'); if (parts2.length == 2) parts[0] = parseInt(parts2[0]) * 60 + parseInt(parts2[1]); start = parseInt(parts[0]) * 60 + parseInt(parts[1] || 0); } } chrome.runtime.sendMessage({action: 'ajaxGet', url: location.protocol + "//www.youtube.com/get_video_info?video_id=" + id, method: 'GET'}, function (video_info) { link.removeClass('hoverZoomLoading'); var video = decodeQueryString(video_info); if (video.status === "fail") { cLog(video.reason); return; } var sources = decodeStreamMap(video.url_encoded_fmt_stream_map); var src = getSource(sources, "webm", "hd720") || getSource(sources, "mp4", "hd720"); if (src) { link.data().hoverZoomSrc = [start ? src.url + '#t=' + start : src.url]; link.addClass('hoverZoomLink'); hoverZoom.displayPicFromElement(link); } }); } $('a[href*="youtu.be/"]').one('mouseenter', function () { var link = $(this), match = this.href.match(/^.*youtu.be\/([\w-]+).*$/); if (!match || match.length < 2) return; prepareVideoPreview(link, match[1]); }); $('a[href*="youtube.com/watch"]').one('mouseenter', function () { var link = $(this), match = this.href.match(/^.*v=([\w-]+).*$/); if (!match || match.length < 2) return; prepareVideoPreview(link, match[1]); }); // $('a[href*="youtu.be/"] img').each(function () { // var link = $(parentNodeName(this, 'a')), // img = $(this); // img.data().hoverZoomSrc = [link.attr('href').replace(/^.*youtu.be\/([\w-]+).*$/, repl)]; // res.push(img); // }); // $('a[href*="youtube.com/watch"] img').each(function () { // var link = $(parentNodeName(this, 'a')), // img = $(this); // img.data().hoverZoomSrc = [link.attr('href').replace(/^.*v=([\w-]+).*$/, repl)]; // res.push(img); // }); hoverZoom.urlReplace(res, 'img[src*="ytimg.com/vi/"], img[src*="ytimg.com/vi_webp/"]', /\/([1-9]|default|hqdefault|mqdefault)\.(jpg|webp)/, '/0.$2' ); $('a img[data-thumb*="ytimg.com/vi/"]').each(function () { var img = $(this); img.data().hoverZoomSrc = [this.getAttribute('data-thumb').replace(/\/([1-9]|default|hqdefault|mqdefault)\.jpg/, '/0.jpg')]; res.push(img); }); callback($(res)); } });
import _ from 'lodash' export const composite = (commands) => { if (!Array.isArray(commands)) { return commands; } if (commands.length === 1) { return commands[0]; } return { 'composite': _.chain(commands).reduce((o, v, idx) => { o[idx] = v; return o; }, {}).value() }; }; export const addElement = (json) => ({ 'add-element' : json }); export const addConnector = (json) => ({ 'add-connector' : json }); export const addRelationship = (json) => ({ 'add-relationship' : json }); export const modViewObject = (viewId, voId, payload) => ({ 'mod-view-object': { viewId: viewId, id: voId, ...payload } }); export const modConcept = (id, payload) => ({ 'mod-concept': { id: id, ...payload } }); export const deleteViewObject = (viewId, voId) => ({ 'del-view-object': { viewId: viewId, id: voId } }); export const moveViewNode = (viewId, voId, pos, size) => ({ 'mov-view-node': { viewId: viewId, id: voId, pos: { x:pos.x, y:pos.y }, size: { width: size.width, height: size.height } } }); export const moveViewEdge = (viewId, voId, points) => ({ 'mov-view-edge': { viewId: viewId, id: voId, points: _.chain(points).map((p) => ({ x:p.x, y:p.y })).value() } }); export const addViewNodeConcept = (viewId, concept, pos, size) => ({ 'add-view-node-concept': { viewId: viewId, concept: concept, pos: { x:pos.x, y:pos.y }, size: { width: size.width, height: size.height } } }); export const addViewRelationship = (viewId, concept, src, dst) => ({ 'add-view-relationship': { viewId: viewId, concept: concept, src, dst } }); export const addViewNotes = (viewId, pos, size) => ({ 'add-view-notes': { viewId: viewId, pos: { x:pos.x, y:pos.y }, size: { width: size.width, height: size.height } } }); export const addViewConnection = (viewId, src, dst) => ({ 'add-view-connection': { viewId: viewId, src, dst } }); export const addView = (viewpoint, name, payload={}) => ({ 'add-view': { viewpoint: viewpoint, name: name, ...payload } }); export const modView = (id, name, payload={}) => ({ 'mod-view': { id: id, name: name, ...payload } });
const Program = require('../models/Program'), Campus = require('../models/Campus'), fixtures = require('node-mongoose-fixtures'); /** * GET / * Home page. */ exports.index = (req, res) => { //load programs Program.find({}, (err, programs) => { if(err) return console.error(err); res.render('home', {title: 'Home', programs: programs}) }); };
var relationsMapper = require('./map_relations'); var Promise = require('bluebird'); var DEFAULT_LIST_RELATIONS = require('./constants').LIST_RELATIONS; var DEFAULT_ITEM_LIST = require('./constants').ITEM_TYPE_LIST; var SAMPLE_DATA = require('./data-demo'); var CLOUD_TOPIC_PREFIX = require('./topics_constants').CLOUD_TOPIC_PREFIX; /** * Returns build data function singleton * @param {Object} mediator - mediator object used for communication * @returns {Function} - buildData function */ function getBuildDataFunction(mediator) { /** * Synchronously publishes 'wfm:cloud:{itemType}:create topic for each item type. * @param {Object} mediator - mediator object used for communication * @returns {Promise} Promise, resolved if all items are successfully created. */ return function buildData() { var relationsMap = []; /** * Iterator function for mapSeries, creates all sample items for given item type * @param itemType * @returns {Promise} */ function createDataForType(itemType) { return createItemsForType(mediator, itemType, relationsMap) .then(function(mappingsForType) { relationsMap[itemType] = mappingsForType; }); } return Promise.mapSeries(DEFAULT_ITEM_LIST, createDataForType).return(); }; } /** * Creates all items of a given type * @param {Object} mediator - mediator object used for communication * @param {String} itemType - type of the item to remove e.g. result, workorder * @param {Array} relationsMap - An array mapping out relations between seed and newly created data-reset * @returns {Promise} with mappings for given type. */ function createItemsForType(mediator, itemType, relationsMap) { var topic = CLOUD_TOPIC_PREFIX + itemType + ':create'; function createForType(dataItem) { var mapping = { seedId: dataItem.id, newId: '' }; dataItem = relationsMapper.mapRelations(itemType, dataItem, relationsMap[DEFAULT_LIST_RELATIONS[itemType]]); return mediator.request(topic, [dataItem, dataItem.id], {uid: dataItem.id}) .then(function(createdItem) { mapping.newId = createdItem.id; return mapping; }); } //map series resolves to an array of results returned by its iterator func. i.e. an array of mappings for a type return Promise.mapSeries(SAMPLE_DATA[itemType](), createForType); } module.exports = { getBuildDataFunction: getBuildDataFunction, createItemsForType: createItemsForType };
'use strict'; var fs = require('fs'), request = require('request'), wikiParser = require('./wikiparser'), _ = require('lodash'); var fns = { getSlugNameFor: function(str) { var slug = str.replace(/\s+/g, '-').toLowerCase(); return slug; }, extendWithJSONs: function(series) { for (var ser in series) { var fileName = './cache/' + fns.getSlugNameFor(ser) + '.json'; if (!fs.existsSync(fileName)) { console.error('json for "', ser, '" not exists. Filename should be: ', fileName); continue; } series[ser].jsonData = require('./.' + fileName); } }, writeJSON: function(fileName, jsonData) { return new Promise(function (fulfill, reject) { fs.writeFile(fileName, JSON.stringify(jsonData, null, 2), function(err) { if (err) { reject() } else { fulfill(); } }); }); }, findSeriesByTitle: function(title, series) { var hit = _.find(series, function(value, key, fullObj) { return key === title; }); if (!hit) { console.error('Couldn\'t find this show in the db:', title); return ''; } return hit; }, loadUrl: function(url) { return new Promise(function (fulfill, reject) { request(url, function (error, response, body) { if (error || response.statusCode != 200) { throw new Error(error); } fulfill(body); }); }); }, updateCacheFromWiki: function(seriesData) { return fns.loadUrl(seriesData.wikiUrl) .then(function(body) { return wikiParser.extractDataFromWikiPage(seriesData, body); }); }, populateEpisodes: function(series, date, beforeDays, afterDays) { var showsBefore = [], showsAfter = [], beforeDate = date.getTime() - beforeDays * 1000 * 24 * 60 * 60, afterDate = date.getTime() + afterDays * 1000 * 24 * 60 * 60, nowDate = date.getTime(); _.each(series, function(data, key) { if (data.jsonData) { _.each(data.jsonData, function(season) { _.each(season.episodes, function(episode) { episode.dateObj = new Date(episode.date); if (episode.dateObj.getTime() > beforeDate && episode.dateObj.getTime() < nowDate) { showsBefore.push({ series: key, season: season.season, episode: episode}); } else if (episode.dateObj.getTime() > nowDate && episode.dateObj.getTime() < afterDate) { showsAfter.push({ series: key, season: season.season, episode: episode}); } }); }); } }); return { showsBefore: _.sortBy(showsBefore, function(n) { return n.episode.dateObj.getTime(); }), showsAfter: _.sortBy(showsAfter, function(n) { return n.episode.dateObj.getTime(); }) }; }, formatDate: function(date) { var month = date.getMonth() + 1, day = date.getDay(), dayText = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][day]; return date.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' (' + dayText + ')'; } } module.exports = fns;
/* * The MIT License (MIT) * Copyright (c) 2016 Jim Liu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ xdescribe('uiMask', function () { var inputHtml = "<input ui-mask=\"'(9)9'\" ng-model='x'>"; var $compile, $rootScope, element; beforeEach(module('ui.directives')); beforeEach(inject(function (_$rootScope_, _$compile_) { $rootScope = _$rootScope_; $compile = _$compile_; })); describe('ui changes on model changes', function () { it('should update ui valid model value', function () { $rootScope.x = undefined; element = $compile(inputHtml)($rootScope); $rootScope.$digest(); expect(element.val()).toBe(''); $rootScope.$apply(function () { $rootScope.x = 12; }); expect(element.val()).toBe('(1)2'); }); it('should wipe out ui on invalid model value', function () { $rootScope.x = 12; element = $compile(inputHtml)($rootScope); $rootScope.$digest(); expect(element.val()).toBe('(1)2'); $rootScope.$apply(function () { $rootScope.x = 1; }); expect(element.val()).toBe(''); }); }); describe('model binding on ui change', function () { //TODO: was having har time writing those tests, will open a separate issue for those }); describe('should fail', function() { it('errors on missing quotes', function() { $rootScope.x = 42; var errorInputHtml = "<input ui-mask=\"(9)9\" ng-model='x'>"; element = $compile(errorInputHtml)($rootScope); expect($rootScope.$digest).toThrow('The Mask widget is not correctly set up'); }); }); });
var log = console.log , Alice = require( '../' ) , ed = Alice() , path = null ; // same edge ed.add( 1, 2 ); ed.add( 2, 1, true ); ed.add( 1, 2, true ); // vertex loop ed.add( 2, 2 ); ed.cut( 2, 2 ); // same edge ed.add( 2, 1, true ); ed.cut( 1, 2 ); ed.add( 1, 2 ); ed.cut( 2, 1 ); // add some edges ed.add( 5, 4 ); ed.add( 4, 3 ); ed.add( 4, 1 ); ed.add( 2, 5 ); // add a cycle ed.add( 2, 1 ); log(); log( '- 2-partite graph edges:', ed.e ); log(); log( '- 2-partite graph vertices:', ed.v ); log(); log( '- pruning edges to find cycles..' ); path = ed.prune( true ); log(); log( '- pruning results:', path ); log(); log( '- edge set is %sempty! (%d edges found)', ed.edges ? 'not ' : '', ed.edges ); log(); if ( ed.edges ) log( '- cycle found:', ed.e ); else log( '- no cycle found!' ); log();
(function () { 'use strict'; var $$compile = null, $$rootScope = null, scope = null; describe('minItems validation directive', function () { beforeEach(function () { module('dynamic-forms'); inject(function ($compile, $rootScope) { $$rootScope = $rootScope; $$compile = $compile; }); }); function createDynamicList(minItems, items) { scope = $$rootScope.$new(); scope.model = items; var element = angular.element('<div ng-model="model"></div>'); element.attr('data-min-items', minItems); element = $$compile(element)(scope); scope.$digest(); return element; } it('passes validation when the minItems is not a number', function() { var element = createDynamicList('string', [1, 2, 3]); expect(element.hasClass('ng-valid')).toBeTruthy(); expect(element.hasClass('ng-invalid')).not.toBeTruthy(); }); it('fails validation when the array length is less than the value', function () { var element = createDynamicList(2, [1]); expect(element.hasClass('ng-valid')).not.toBeTruthy(); expect(element.hasClass('ng-invalid')).toBeTruthy(); }); it('passes validation when the array length is equal to the value', function () { var element = createDynamicList(3, [1, 2, 3]); expect(element.hasClass('ng-invalid')).not.toBeTruthy(); expect(element.hasClass('ng-valid')).toBeTruthy(); }); it('fails validation when an item is removed and causes array length to be less than the min value', function () { var element = createDynamicList(2, [1, 2]); expect(element.hasClass('ng-invalid')).not.toBeTruthy(); expect(element.hasClass('ng-valid')).toBeTruthy(); scope.model.splice(0, 1); scope.$digest(); expect(element.hasClass('ng-valid')).not.toBeTruthy(); expect(element.hasClass('ng-invalid')).toBeTruthy(); }); it('passes validation when min items is less than min value and then an item is added to be equal to the minItems', function () { var element = createDynamicList(2, [1]); expect(element.hasClass('ng-invalid')).toBeTruthy(); expect(element.hasClass('ng-valid')).not.toBeTruthy(); scope.model.push(2); scope.$digest(); expect(element.hasClass('ng-valid')).toBeTruthy(); expect(element.hasClass('ng-invalid')).not.toBeTruthy(); }); }); }());
'use strict'; /** * Scales an image or video to fill the screen in one dimension, preserving its * aspect ratio. * * Serves as a polyfill for the CSS object-fit: contain property if it is not * supported (mostly for IE). * * Should be applied to an <img> or <video> tag or a <div ng-bind-html> that * will load content with either an <img> or <video> tag. */ function MediaContainDirective($timeout) { return { // Must be a class since this depends on CSS classes. ("-directive" is in // the classname to differentiate a class-based directive from normal CSS). restrict: 'C', // Execute last. priority: -1, link: function ($scope, $element, $attrs) { // If object-fit is supported, no need for rest of the directive. // TODO(dbow): Make sure this is actually a viable feature detect... // Could use Modernizr with non-core detect added. if ('objectFit' in document.documentElement.style) { return; } // Add polyfill class to override default object-fit styles. $element.addClass('media-contain-directive-polyfill'); /** * The IMG or VIDEO element found within $element. * @type {Element} */ var mediaElement; /** * The angular.element version of mediaElement. * @type {Object} */ var $mediaElement; // Check if directive is applied directly to IMG or VIDEO element. if ($element[0].tagName === 'IMG' || $element[0].tagName === 'VIDEO') { $mediaElement = $element; mediaElement = $element[0]; } /** * Checks an image or video to see if it needs to be adjusted to fill the * screen. Media defaults to 100% width with no limit on height. This * function checks to see if the image or video's aspect ratio is less * than the window's. If so, adds a class that will make it 100% height * with no limit on width. If an image or video with height and width * cannot be found returns false so we can check again. * * @return {boolean} Whether a media element with width and height was * found. */ function checkMedia() { // If we haven't found the mediaElement yet, try to find an IMG or // VIDEO in the $element's children. var child; if (!mediaElement) { child = $element.find('IMG')[0] || $element.find('VIDEO')[0]; if (child) { mediaElement = child; $mediaElement = angular.element(mediaElement); } } // If we've found the mediaElement and it has dimensions, adjust the // class applied based on aspect ratio of the window and that of the // mediaElement. if (mediaElement) { var mediaHeight = mediaElement.height || mediaElement.videoHeight; var mediaWidth = mediaElement.width || mediaElement.videoWidth; if (mediaHeight && mediaWidth) { var windowAspectRatio = window.innerWidth / window.innerHeight; $mediaElement.toggleClass('media-contain-directive-y', mediaWidth / mediaHeight < windowAspectRatio); // Remove listeners. if (mediaElement.tagName === 'IMG') { $mediaElement.off('load', checkMedia); } else { $mediaElement.off('loadedmetadata', checkMedia); } return true; } } return false; } /** * Checks if a mediaElement has been found yet, and if so, attaches * the appropriate load listener ('load' for IMG, 'loadedmetadata' for * VIDEO) based on tagName. * * @return {boolean} Whether a listener was set up. */ function listenForMediaLoad() { if (mediaElement) { if (mediaElement.tagName === 'IMG') { $mediaElement.on('load', checkMedia); } else { $mediaElement.on('loadedmetadata', checkMedia); } return true; } return false; } /** * Initialize the directive. * * Calls checkMedia to determine if the mediaElement has been found and * its media has loaded. If not, tries to set up media load listeners to * check again. * * @return {boolean} Whether either checkMedia or listenForMediaLoad * was successful and the directive was initialized. */ function init() { return checkMedia() || listenForMediaLoad(); } // Try to inititalize the directive. if (!init() && $attrs.ngBindHtml) { // If we can't init yet and there is an ng-bind-html tag, wait for that // to populate and then init again. $scope.$watch('ngBindHtml', function() { $timeout(init, 50); // Give HTML a chance to load. }); } // Update on resize (debounced). angular.element(window).on('resize', _.debounce(checkMedia, 150)); } }; } angular .module('angular-multimedia') .directive('mediaContainDirective', ['$timeout', MediaContainDirective]);
(function(module){ 'use strict'; //this comment set up here to turn off eslint warnings about unused vars /*global issues issueView helpers d3Chart:true*/ //set up constructor for easier use of data function RepoIssue (opts){ this.repoOwner = opts.html_url.split('/')[3]; this.repoName = opts.html_url.split('/')[4]; this.issueUser = opts.user.login; this.issueUserAvatarURL = opts.user.avatar_url; this.issueUserAcctURL = opts.user.html_url; this.dateCreated = helpers.parseGitHubDate(opts.created_at), this.daysAgo = helpers.numberOfDaysAgo(this.dateCreated); this.daysAgoString = this.daysAgo; if(this.daysAgo !== 'today' && this.daysAgo !== 1) this.daysAgoString = `${this.daysAgo} days ago`; if(this.daysAgo === 1) this.daysAgoString = `${this.daysAgo} day ago`; this.repoURL = helpers.parseRepoURL(opts.html_url), this.issueURL = opts.html_url, this.labels = opts.labels, this.title = opts.title, this.body = opts.body; if (this.body === '') this.body = 'This user did not enter any text for this issue.'; this.id = opts.id; } let issues = {}; module.issues = issues; issues.data = []; issues.owner; issues.repo; issues.pageNumber = 1; issues.perPage = 100; issues.getIt = function(num, callback){ return $.ajax({ type: 'GET', url: `/github/repos/${issues.owner}/${issues.repo}/issues?page=${num}&per_page=100`, success: function(data){ issueView.noIssuesAlert(data, num); data.forEach((element) => { let issue = new RepoIssue(element); issues.data.push(issue); }); callback(issues.data); }, error: function () { issueView.badRequest(); }, }); }; issues.fetchData = function(num){ $.when( $.get(`/github/repos/Automattic/mongoose/issues?page=${num}&per_page=100`) .done((data) => { if(data.length){ data.forEach((element) => { let issue = new RepoIssue(element); issues.data.push(issue); }); num++; issues.fetchData(num); console.log(num, issues.data); } else { console.log('no more data'); } }) .fail(() => { issues.success = false; }) ); }; })(window);
import { combineReducers } from 'redux'; import graph from './graph'; export default combineReducers({ graph });
const PlotCard = require('../../plotcard'); const GameActions = require('../../GameActions'); class ThePrinceWhoCameTooLate extends PlotCard { setupCardAbilities(ability) { this.action({ title: 'Search your deck', phase: 'standing', handler: context => { this.game.resolveGameAction( GameActions.search({ title: 'Select a character', match: { type: 'character' }, message: '{player} uses {source} to search their deck and put {searchTarget} into play', cancelMessage: '{player} uses {source} to search their deck but does not find a card', gameAction: GameActions.putIntoPlay(context => ({ player: context.player, card: context.searchTarget })) }), context ); }, limit: ability.limit.perRound(1) }); } } ThePrinceWhoCameTooLate.code = '15052'; module.exports = ThePrinceWhoCameTooLate;
/** * A simple styled li element */ import styled from 'styled-components'; const Li = styled.li` `; export default Li;
var gulp = require('gulp'); var phpspec = require('gulp-phpspec'); var run = require('gulp-run'); var plumber = require('gulp-plumber'); var notify = require('gulp-notify'); gulp.task('test', function() { gulp.src('spec/**/*.php') .pipe(run('clear')) .pipe(phpspec('', { 'verbose': 'v', notify: true })) .on('error', notify.onError({ title: "Crap", message: "The tests failed.", icon: __dirname + '/fail.png' })) .pipe(notify({ title: "Success", message: "All tests have returned green!" })); }); gulp.task('watch', function() { gulp.watch(['spec/**/*.php', 'src/**/*.php'], ['test']); }); gulp.task('default', ['test', 'watch']);
export const selectGallery = (gallery) => ({ type: 'SELECT_GALLERY', gallery })
// moment.js locale configuration // locale : tibetan (bo) // author : Thupten N. Chakrishar : https://github.com/vajradog (function (factory) { if (typeof define === 'function' && define.amd) { define(['../moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var symbolMap = { '1': '༡', '2': '༢', '3': '༣', '4': '༤', '5': '༥', '6': '༦', '7': '༧', '8': '༨', '9': '༩', '0': '༠' }, numberMap = { '༡': '1', '༢': '2', '༣': '3', '༤': '4', '༥': '5', '༦': '6', '༧': '7', '༨': '8', '༩': '9', '༠': '0' }; return moment.defineLocale('bo', { months : 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split("_"), monthsShort : 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split("_"), weekdays : 'གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་'.split("_"), weekdaysShort : 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split("_"), weekdaysMin : 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split("_"), longDateFormat : { LT : "A h:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[དི་རིང] LT', nextDay : '[སང་ཉིན] LT', nextWeek : '[བདུན་ཕྲག་རྗེས་མ], LT', lastDay : '[ཁ་སང] LT', lastWeek : '[བདུན་ཕྲག་མཐའ་མ] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s ལ་", past : "%s སྔན་ལ", s : "ལམ་སང", m : "སྐར་མ་གཅིག", mm : "%d སྐར་མ", h : "ཆུ་ཚོད་གཅིག", hh : "%d ཆུ་ཚོད", d : "ཉིན་གཅིག", dd : "%d ཉིན་", M : "ཟླ་བ་གཅིག", MM : "%d ཟླ་བ", y : "ལོ་གཅིག", yy : "%d ལོ" }, preparse: function (string) { return string.replace(/[༡༢༣༤༥༦༧༨༩༠]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return "མཚན་མོ"; } else if (hour < 10) { return "ཞོགས་ཀས"; } else if (hour < 17) { return "ཉིན་གུང"; } else if (hour < 20) { return "དགོང་དག"; } else { return "མཚན་མོ"; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); }));
/** * Created by JinWYP on 7/27/16. */ var expect = require('chai').expect; var colorConverter = require('../../../business-libs/colorConverter'); describe('Color Code Converter', function() { describe('RGB to Hex conversion', function() { it('converts the basic colors', function() { var redHex = colorConverter.rgbToHex(255, 0, 0); var greenHex = colorConverter.rgbToHex(0, 255, 0); var blueHex = colorConverter.rgbToHex(0, 0, 255); expect(redHex).to.equal('ff0000'); expect(greenHex).to.equal('00ff00'); expect(blueHex).to.equal('0000ff'); }); }); describe('Hex to RGB conversion', function() { it('converts the basic colors', function() { var red = colorConverter.hexToRgb('ff0000'); var green = colorConverter.hexToRgb('00ff00'); var blue = colorConverter.hexToRgb('0000ff'); expect(red).to.deep.equal([255, 0, 0]); expect(green).to.deep.equal([0, 255, 0]); expect(blue).to.deep.equal([0, 0, 255]); }); }); });
/*jslint node: true*/ /*jslint nomen: true*/ "use strict"; var React = require('react'), ActionBindingMixin = require('../mixins/ActionBindingMixin'), serialize = require('form-serialize'); module.exports = React.createClass({ mixins: [ActionBindingMixin], render: function () { return React.createElement("form", React.__spread({}, this.props, {onSubmit: this.onSubmit}), this.props.children); }, onSubmit: function (event) { event.preventDefault(); this.callAction(serialize(event.target, { hash: !this.props.urlEncoding })); } });
var Easel = require('easel'); var app = new Easel(); app.server.start();
/* eslint-env mocha, jest */ import getActualComponentFactory from '../../lib/testUtils'; import Task from '../Task'; const defaultProps = { index: 0, color: 'red', text: 'a cool task', estimation: '60', due: '', repeat: '', done: false, onRequestDo() {}, onRequestDelete() {}, onRequestSnackbar() {}, onRequestEditTaskOpen() {}, }; const getActualTask = getActualComponentFactory(Task, defaultProps); jest.useFakeTimers(); it('should render', () => { getActualTask(); }); it('should be a div', () => { const wrapper = getActualTask(); expect(wrapper.is('div.Task')).toBe(true); }); it('should have 1 text div', () => { const wrapper = getActualTask(); expect(wrapper.find('div.text').length).toBe(1); }); it('should have 1 Estimation', () => { const wrapper = getActualTask(); expect(wrapper.find('Estimation').length).toBe(1); }); it('should have 1 DueDate', () => { const wrapper = getActualTask(); expect(wrapper.find('DueDate').length).toBe(1); }); it('should have 1 Repeat', () => { const wrapper = getActualTask(); expect(wrapper.find('Repeat').length).toBe(1); }); it('should have 1 Actions', () => { const wrapper = getActualTask(); expect(wrapper.find('Actions').length).toBe(1); }); it('should set Circle color based on props', () => { const wrapper = getActualTask({ color: 'blue' }); expect(wrapper.find('Circle').prop('color')).toBe('blue'); }); it('should set Circle signal based on props', () => { const wrapper = getActualTask({ signal: true }); expect(wrapper.find('Circle').prop('signal')).toBe(true); }); it('should set text div text based on props', () => { const wrapper = getActualTask({ text: 'a cooler idea' }); expect(wrapper.find('div.text').text()).toBe('a cooler idea'); }); it('should set Estimation estimation based on props', () => { const wrapper = getActualTask({ estimation: '30' }); expect(wrapper.find('Estimation').prop('estimation')).toBe('30'); }); it('should set DueDate due based on props', () => { const wrapper = getActualTask({ due: 'tomorrow' }); expect(wrapper.find('DueDate').prop('due')).toBe('tomorrow'); }); it('should set Repeat repeat based on props', () => { const wrapper = getActualTask({ repeat: '5' }); expect(wrapper.find('Repeat').prop('repeat')).toBe('5'); }); it('should set Actions done based on props', () => { const wrapper = getActualTask({ done: true }); expect(wrapper.find('Actions').prop('done')).toBe(true); }); it('should call onRequestDelete inside Actions onRequestDelete', () => { const wrapper = getActualTask({ index: 3, onRequestDelete(index) { expect(index).toBe(3); }, }); wrapper.find('Actions').props().onRequestDelete(); jest.runAllTimers(); }); it('should call onRequestSnackbar inside Actions onRequestDelete', () => { const wrapper = getActualTask({ onRequestSnackbar(message) { expect(message).toBe('Task deleted'); }, }); wrapper.find('Actions').props().onRequestDelete(); jest.runAllTimers(); }); it('should call onRequestDo inside Actions onRequestDo', () => { const wrapper = getActualTask({ index: 3, onRequestDo(index) { expect(index).toBe(3); }, }); wrapper.find('Actions').props().onRequestDo(); jest.runAllTimers(); }); it('should call onRequestSnackbar inside Actions onRequestDo', () => { const wrapper = getActualTask({ onRequestSnackbar(message) { expect(message).toBe('Task done'); }, }); wrapper.find('Actions').props().onRequestDo(); jest.runAllTimers(); }); it('should call onRequestEditTaskOpen inside Actions onRequestEditDialogOpen', () => { const wrapper = getActualTask({ index: 3, onRequestEditTaskOpen(index) { expect(index).toBe(3); }, }); wrapper.find('Actions').props().onRequestEditDialogOpen(); jest.runAllTimers(); }); it('should remove its done class based on state', () => { const wrapper = getActualTask({ repeat: '5', }); wrapper.find('Actions').props().onRequestDo(); wrapper.update(); jest.runAllTimers(); expect(wrapper.props().className.includes('done')).toBe(false); });
import React from 'react' import { ScrollView, StyleSheet, View } from 'react-native' import { Video as ExpoVideo } from 'expo' import VideoPlayer from '@expo/videoplayer' import { Ionicons } from '@expo/vector-icons' import PropTypes from 'prop-types' import { Colors } from 'constants' const styles = StyleSheet.create( { container: { flex: 1, backgroundColor: Colors.baseWhite, }, } ) const Video = ( { uri, shouldPlay } ) => { const icon = ( name, size = 36 ) => () => ( <Ionicons name={name} size={size} color={Colors.tintColor} style={{ textAlign: 'center' }} /> ) return ( <View style={styles.container}> <ScrollView style={styles.container}> <VideoPlayer videoProps={{ isLooping: true, isMuted: true, repeat: true, shouldPlay: shouldPlay, resizeMode: ExpoVideo.RESIZE_MODE_CONTAIN, source: { uri, }, }} textStyle={{ color: Colors.tintColor, fontSize: 12, }} playIcon={icon( 'ios-play-outline' )} pauseIcon={icon( 'ios-pause-outline' )} fullscreenEnterIcon={icon( 'ios-expand-outline', 0 )} fullscreenExitIcon={icon( 'ios-contract-outline', 0 )} switchToLandscape={e => console.log( e )} switchToPortrait={e => console.log( e )} playFromPositionMillis={0} /> </ScrollView> </View> ) } Video.propTypes = { shouldPlay: PropTypes.bool.isRequired, uri: PropTypes.string.isRequired, } Video.defaultProps = { shouldPlay: false, } export default Video
import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import page from '../../../pages/components/kinetic-form/radios'; import sinon from 'sinon'; const { run, set, get } = Ember; moduleForComponent('kinetic-form/radios', 'Integration | Component | kinetic form/radios', { integration: true, beforeEach() { page.setContext(this); set(this, 'updateSpy', sinon.spy()); }, afterEach() { page.removeContext(); } }); test('displays field.title', function(assert) { set(this, 'testField', {title: 'test-title'}); page.render(hbs`{{kinetic-form/radios field=testField update=(action updateSpy)}}`); assert.ok(page.hasInTitle('test-title'), 'expected field.title to be displayed'); }); test('highlights as required when field.required is true', function(assert) { set(this, 'testField', {required: false}); page.render(hbs`{{kinetic-form/radios field=testField update=(action updateSpy)}}`); assert.notOk(page.isRequired, 'expected component to not be highlighted as required'); run(() => set(this, 'testField.required', true)); assert.ok(page.isRequired, 'expected component to be highlighted as required'); }); test('shows the current value', function(assert) { set(this, 'testValue', true); page.render(hbs`{{kinetic-form/radios value=testValue update=(action updateSpy)}}`); assert.ok(page.isOn, 'expected on button to be active'); assert.notOk(page.isOff, 'expected off button to not be active'); run(() => set(this, 'testValue', false)); assert.notOk(page.isOn, 'expected on button to not be active'); assert.ok(page.isOff, 'expected off button to be active'); }); test('calls update action when user enters text', function() { page.render(hbs`{{kinetic-form/radios update=(action updateSpy)}}`); run(() => page.turnOn()); sinon.assert.calledWith(get(this, 'updateSpy'), true); run(() => page.turnOff()); sinon.assert.calledWith(get(this, 'updateSpy'), false); }); test('highlights as an error when error is truthy', function(assert) { set(this, 'testError', null); page.render(hbs`{{kinetic-form/radios error=testError update=(action updateSpy)}}`); assert.notOk(page.hasError, 'expected to not have error highlight'); run(() => set(this, 'testError', {message: 'test-error'})); assert.ok(page.hasError, 'expected to have error highlight'); });
// Copyright 2012 Ofir Picazo. All Rights Reserved. /** * @fileoverview Foundation object, fill one per suit to complete the game. * * @author ofirpicazo@gmail.com (Ofir Picazo) */ goog.provide('solitario.game.Foundation'); goog.require('goog.dom.dataset'); goog.require('solitario.game.Card'); goog.require('solitario.game.Pile'); /** * Class to represent a foundation in the game. * * @param {!Element} el DOM element representing the foundation. * @constructor * @extends {solitario.game.Pile} */ solitario.game.Foundation = function(el) { goog.base(this, el); /** * Type of pile, workaround to avoid using instanceof. * @type {solitario.game.constants.PileTypes} */ this.pileType = solitario.game.constants.PileTypes.FOUNDATION; /** * Suit this foundation contains. * @type {?solitario.game.constants.SUIT} */ this.suit = null; }; goog.inherits(solitario.game.Foundation, solitario.game.Pile); /** * Return true if this foundation can accept the passed card given the game * rules. * * @param {solitario.game.Card} card The card to be evaluated. * @return {boolean} true if the card can be pushed to the tableu, false if not. * @override */ solitario.game.Foundation.prototype.canAcceptCard = function(card) { // If the super class says no, we cannot say yes. if (!solitario.game.Foundation.superClass_.canAcceptCard.call(this, card)) { return false; } // Check that card is a Ace when the foundation is empty, otherwise it must be // the next card for the suit of the pile. if (this.isEmpty()) { return (card.number == solitario.game.constants.CardNumber.ACE); } else { var topCard = this.getTopCard(); return (card.suit == this.suit && (card.value - topCard.value == 1)); } }; /** * Pop a card off of the foundation. * * @return {?solitario.game.Card} The card popped from the pile. * @override */ solitario.game.Foundation.prototype.pop = function() { var card = solitario.game.Foundation.superClass_.pop.call(this); if (this.isEmpty()) { this.suit = null; } return card; }; /** * Adds a new card to the foundation. Sets the foundation's suit if it's not yet * set. * * @param {solitario.game.Card} card Card to be pushed. * @override */ solitario.game.Foundation.prototype.push = function(card) { solitario.game.Foundation.superClass_.push.call(this, card); if (!this.suit) { this.suit = card.suit; } };
(function() { "use strict"; define( function() { var interactiveToolConfig = new function() { var self = this; //This is the default value for the textbox that holds the value of the number of units to buffer in the buffering tool self.defaultBufferValue = 1; //his is a configurable list of units that can be used to buffer search areas. self.bufferUnits = [{ text: "Mile", value: esri.tasks.GeometryService.UNIT_NAUTICAL_MILE }, { text: "Kilometer", value: esri.tasks.GeometryService.UNIT_KILOMETER }, { text: "Feet", value: esri.tasks.GeometryService.UNIT_FOOT }, { text: "Meter", value: esri.tasks.GeometryService.UNIT_METER }]; //This is the default selected index in the unit selector for the buffering tool self.selectedBufferUnitIndex = 0; //This is the URl to the geometry service that performs the buffering for the buffering tool. self.geometryServiceURL = "http://geo.azmag.gov/gismag/rest/services/Utilities/Geometry/GeometryServer"; //This is the spatial reference specified for the buffered area. self.bufferSpatialReference = { wkid: 26949 }; // JSON respresentation of an ESRI Simple Fill Symbol // http://resources.arcgis.com/en/help/arcgis-rest-api/#/Symbol_Objects/02r3000000n5000000/ self.selectionPointSymbol = { type: "simplemarkersymbol", style: "esriSFSNull", color: [255, 0, 255, 191] }; self.selectionSymbol = { type: "esriSFS", style: "esriSFSNull", color: [0, 0, 0, 0], outline: { type: "esriSLS", style: "esriSLSDash", color: [255, 0, 255, 191], width: 3 } }; self.bufferSymbol = { type: "esriSFS", style: "esriSFSNull", color: [0, 0, 0, 0], outline: { type: "esriSLS", style: "esriSLSDash", color: [255, 0, 0, 191], width: 3 } }; }; return interactiveToolConfig; } ); }());
module.exports.generator = function () { // This should return a new bite code in the form of a String }
export const encodeArrayForUrl = (values) => { const encodedValues = values.map(encodeURIComponent) return encodedValues.join(',') } export const getArrayFromUrlParam = (urlParam) => { const encodedValues = urlParam.split(',') return encodedValues.map(decodeURIComponent) } export const buildQueryForUrl = (filterParams) => { const query = [] if (filterParams) { for (let fieldName in filterParams) { const fieldValue = filterParams[fieldName] if (fieldValue !== undefined && fieldValue !== null && fieldValue !== '') { const param = `${fieldName}=${encodeURIComponent(fieldValue.toString())}` query.push(param) } } } if (query.length) { const urlParams = `?${query.join('&')}` return urlParams } return '' } export const buildUrl = (basePath, filterParams) => { const urlParams = buildQueryForUrl(filterParams) return basePath + urlParams }
import defaultCardConfig from '../defaultCardConfig'; /** * Maps room to limited set of properties for export (room as file download). * * @param room * @return {undefined|{stories: *, exportedAt: number, roomId}} */ export function mapRoomExportDto(room) { if (!room) { return undefined; } return { roomId: room.id, exportedAt: Date.now(), stories: room.stories .filter((story) => !story.trashed) .map((story) => mapStoryExportDto(story, room.users)) }; } function mapStoryExportDto(story, users) { const usernamesMap = users.reduce((total, currentUser) => { total[currentUser.id] = currentUser.username || currentUser.id; return total; }, {}); return { title: story.title, description: story.description, consensus: story.consensus, estimations: Object.entries(story.estimations).map((entry) => { const matchingUser = usernamesMap[entry[0]]; const mappedEstm = { username: matchingUser ? matchingUser : entry[0], value: entry[1] }; if (matchingUser) { mappedEstm.userId = entry[0]; } if (story.estimationsConfidence && story.estimationsConfidence[entry[0]]) { mappedEstm.confidence = story.estimationsConfidence[entry[0]]; } return mappedEstm; }) }; } /** * Maps to extensive set of properties. This is used to re-sync client state with backend state and should return the same information as contained in the "joinedRoom" event. * * @param room * @return {undefined|{selectedStory, stories, autoReveal, id, cardConfig: *, users}} */ export function mapRoomStateDto(room) { if (!room) { return undefined; } const { id, autoReveal, withConfidence, issueTrackingUrl, selectedStory, stories, users, cardConfig } = room; return { id, autoReveal, withConfidence, issueTrackingUrl, selectedStory, stories, users, passwordProtected: !!room.password, cardConfig: cardConfig ? cardConfig : defaultCardConfig }; } /** * * @param {object[]} allRooms List of all rooms from the store * @param {string} storeType * @return {{roomCount: number, rooms: {userCount: *, created: number|*, userCountDisconnected: *, lastActivity: number|*, markedForDeletion: boolean|[]|*, storyCount: *}[], storeInfo: (string|*), uptime: number}} */ export function mapAppStatusDto(allRooms, storeType) { const rooms = Object.values(allRooms).map((room) => ({ storyCount: room.stories.length, userCount: room.users.length, userCountDisconnected: room.users.filter((user) => user.disconnected).length, lastActivity: room.lastActivity, markedForDeletion: room.markedForDeletion, created: room.created })); return { rooms, roomCount: rooms.length, uptime: Math.floor(process.uptime()), storeInfo: storeType }; }
//9.2.1 //Pseudocode ------------------------------------------- //create function to make a new list, // that takes a string and split it and create a object with the splited words //go through each element inside the object //display the list //create a function that adds an item with quantity to the list. //if the item is not on the list, give it a value otherwise add to qty. //create a function that removes an item. //if the item is in the list, delete the item. //create a function that displays the list. //the list should list "You have QUANTITY ITEM in your list." //initial solution------------------------------------- function newList(stuff){ var list = {}; var items = stuff.split(" "); for (var x = 0; x < items.length; x++){ list[items[x]] = 1; } return list } function addQuanity(list_name, item, qty){ if (list_name[item] === undefined){ list_name[item] = qty } else { list_name[item] += qty } } function removeItem(list_name, item) { delete list_name[item] } function updateQuanity(list_name, item, qty){ list_name[item] = qty } function printList(list_name) { for(var item in list_name) { console.log('You have ' + list_name[item] + " " + [item] + ' in your list.' ) } } //Driver code var something = new newList("apple bread coffee chocolate"); // console.log(something) addQuanity(something, "herbs", 1) // console.log(something) removeItem(something, "apple"); // console.log(something) updateQuanity(something, "bread", 30) console.log(something) printList(something) //Refactor -------------------------------------- function newList(stuff){ var list = {}; var items = stuff.split(" "); for (var x = 0; x < items.length; x++){ list[items[x]] = 1; } return list } function changeQuanity(list_name, item, qty){ if (list_name[item] === undefined){ list_name[item] = qty } else { list_name[item] += qty } } function removeItem(list_name, item) { delete list_name[item] } function printList(list_name) { for(var item in list_name) { console.log('You have ' + list_name[item] + " " + [item] + ' in your list.' ) } } //Reflection ------------------------------------- /* What concepts did you solidify in working on this challenge? (reviewing the passing of information, objects, constructors, etc.) This challenge solidified my understanding of arguments in functions. It is nice to be able to pass as many arguments we want. I also had more practice with accessing objects and manipulating them to do what I want of them. And as I was trying to figure out how to do string intrapolation, I realized that they were just variables, so why not concat variables into my strings? What was the most difficult part of this challenge? The most difficult part for me was how to find a way to access my list outside the function. Then I realized that I could just create a new list and manipulate them that way. Did an array or object make more sense to use and why? Yes it did, when I worked on the tallyvotes challenge I was getting really confused with what I was accessing from the object, even after giving them variables. With more practice I was able to easily see what I was accessing and control the object the way I wanted. */ //9.2.2 //Pseudocode ------------------------------------------- //input: array from 1 to 10 //output: //multiples of 3 display RETURN fizz //multiples of 5 display RETURN buzz //multiples of 15 display RETURN fizbuzz //make a function that takes an array as an input //iterate the array through each element of the array as the array iterates each element we need to return the elements into "fizzbuzzed"(maybe) //if the element is divisible by 15 RETURN "FizzBuzz" //if the element is divisible by 5 RETURN "Buzz" //if the element is divisible by 3 RETURN "Fizz" var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] function super_fizz_buzz(input){ for(var x = 0;x<=input.length;x++) { if (input[x] % 15 == 0) console.log("FizzBuzz"); else if (input[x] % 3 == 0) console.log("Fizz"); else if (input[x] % 5 == 0) console.log("Buzz"); else console.log(input[x]); }; }; //Driver code console.log(super_fizz_buzz(array)); //Refactor -------------------------------------- function super_fizz_buzz(input){ for(var x = 0;x<=input.length;x++) { var fizz = input[x] % 3 == 0, buzz = input[x] % 5 == 0; console.log(fizz ? buzz ? "FizzBuzz" : "Fizz" : buzz ? "Buzz" : x); }; }; //Reflection ------------------------------------- /* What concepts did you solidify in working on this challenge? It was good practice with loops, if/else statements and functions. What was the most difficult part of this challenge? The most difficult part was the refactoring. I found a way to use tiernary operator similar to one of ruby to refactor the if/else conditions into one line. Did you solve the problem in a new way this time? No, I just translated how I had in ruby. The only difference is instead of using the map enumerable, I used a FOR loop to iterate through the array. Was your pseudocode different from the Ruby version? What was the same and what was different? My pseudocode was the same as my ruby version. The only differnce was my syntax which I ended using a FOR loop and counted from each index in the array. */
import chalk from 'chalk' import moment from 'moment' import Table from 'cli-table' import bugger from 'debug' const debug = bugger('todo:util') /** * Format console.log calls for readability and structure * @param {String} data message to be logged */ function log(data) { let time = moment().format('MM/DD hh:mm:ss:SS') let prefix = chalk.cyan(`[ ${time} ] - `) let content = chalk.red(data) debug('Logging out content %o', data) console.log(content) } /** * A collection of utility functions for formatting * logged output. * @type {Object} */ const format = { task: function(group, source) { return source.map(item => { return `@${group} - ${item.task}` }).join('\n') } } /** * A collection of error templates * @type {Object} */ const err = { group: function(group, exists) { let output = group == '_' ? 'general group' : group let message = exists ? `No tasks found in ${output}` : `Group "${output}" doesn't exist` return message } } export { log, format, err }
import React from 'react' import { filter, get } from 'lodash' import utils from '~/utils' import Filter from '~/components/filter/Filter' import InfiniteScroll from '~/components/infinite-scroll/InfiniteScroll' import RepositoryCard from '~/components/repository-list/repository-card/RepositoryCard' /** * The RepositoryList object class. */ class RepositoryList extends React.Component { // Initial state. state = { repos: this.props.repos, filteredRepos: this.props.repos, } // Default props. static defaultProps = { repos: [], } /** * Update the internal state when this component receive new repos prop. * @param {Object} nextProps */ componentWillReceiveProps(nextProps) { const currRepos = get(this.props, 'repos', []) const nextRepos = get(nextProps, 'repos', []) if (currRepos.length !== nextRepos.length) { this.setState({ repos: nextRepos, filteredRepos: nextRepos, }) } } /** * Render this component. */ render() { const { filteredRepos } = this.state return ( <div> <Filter placeholder="Filter repositories by name or author..." onChange={ (value) => this.filterChanged(value) } /> <InfiniteScroll items={ filteredRepos } render={ (repo) => ( <RepositoryCard key={ repo.id } repo={ repo } /> ) } /> </div> ) } /** * Handle filter value changes. * @param {String} value The new filter value. */ filterChanged(value) { const { repos } = this.state // Filter repos. const query = utils.unicodeNormalize(value) const matcher = new RegExp(utils.escapeRegExp(query), 'i') const filteredRepos = filter(repos, (repo) => { return matcher.test(repo.normalizedName) || matcher.test(repo.normalizedDescription) || matcher.test(repo.user.normalizedName) }) // Update the state. this.setState((state) => ({ filteredRepos, })) } } export default RepositoryList
module.exports = { push: { options: { recursive: true, src: '<%= vars.wplocal %>', dest: '<%= vars.wpremote %>', host: 'n72f3258732714@p3nlpaas001.shr.prod.phx3.secureserver.net', delete: true, exclude: [ 'node_modules', '.gitignore', 'grunt', '.git', 'gruntfile.js', '.DS_Store', '_design' ], ssh: true, args: ['--verbose'] } } };
exports.seed = function(knex, Promise) { return knex('users') .del() .then(function() { // Inserts seed entries return knex('users').insert([ { id: 1, first_name: 'Steve', last_name: 'Morse', email: 'steve@gmail.com', hashed_password: '$2a$10$Sc1JH2uOZ1Cv0t3hoWoc1OyWCdy6Q6BP07b8zWqjT2A2bBbZr6Ab6' }, { id: 2, first_name: 'Steve', last_name: 'Vaughan', email: 'steve2@gmail.com', hashed_password: '$2a$10$ha5HzJWYkRcwQLhT9kHb.eZJ0sT26edJnHAcbpPrF5tMqo3w26Ux2' } ]); }) .then(() => knex.raw("SELECT setval('users_id_seq', (SELECT MAX(id) FROM users))") ); };
"use strict"; let ImageVol = require('./ImageVol'); const DEFAULTS = { // declare size of input // output Vol is of size 128x128x4 here input: { type: 'input', out_sx: 128, out_sy: 128, out_depth: 4 }, conv: [ // the first layer will perform convolution with 16 kernels, each of size 5x5. // the input will be padded with 2 pixels on all sides to make the output Vol of the same size // output Vol will thus be 128x128x16 at this point W2 = (W1 - sx + pad*2)/stride + 1 { type: 'conv', sx: 5, // width is (128 - 5 + 4) + 1 = 128 filters: 16, stride: 1, pad: 2, activation:'relu' }, // output Vol is of size 128x128x20 here { type: 'conv', sx: 5, filters: 20, stride: 1, pad: 2, activation:'relu' } ], // output Vol is of size 16x16x16 here pool: { type: 'pool', sx: 8, stride: 2 }, // output Vol is of size 1x1x10 here softmax: { type: 'softmax', num_classes: 10 }, // tweak this trainer: { method: 'adadelta', l2_decay: 0.001, batch_size: 10 } }; var ConvNetJS = require("ConvNetJS"); class DigitReader { constructor(options) { if (!options) options = {}; this.net = new ConvNetJS.Net(); if (options.net) { console.log('Using previously saved neural network'); this.net.fromJSON(options.net); } else { console.log('Creating fresh neural network'); let layerDefinitions = []; layerDefinitions.push(DigitReader.mergeDefaults(options, 'input')); layerDefinitions.push(DigitReader.mergeDefaults(options, 'conv', 0)); layerDefinitions.push(DigitReader.mergeDefaults(options, 'pool')); layerDefinitions.push(DigitReader.mergeDefaults(options, 'conv', 1)); layerDefinitions.push(DigitReader.mergeDefaults(options, 'pool')); // experiment here with adding more from the defaults. // layerDefinitions.push(DigitReader.mergeDefaults(options, 'conv', 1)); // layerDefinitions.push(DigitReader.mergeDefaults(options, 'pool')); // layerDefinitions.push(DigitReader.mergeDefaults(options, 'conv', 1)); // layerDefinitions.push(DigitReader.mergeDefaults(options, 'pool')); layerDefinitions.push(DigitReader.mergeDefaults(options, 'softmax')); this.net.makeLayers(layerDefinitions); } this.length = 10; this.trainer = new ConvNetJS.SGDTrainer(this.net, DigitReader.mergeDefaults(options, 'trainer')); } train(image, fact) { if (!image) throw new Error({message: "Missing Image"}); if (typeof fact === 'undefined') throw new Error({message: "Missing fact"}); if(typeof fact !== 'number') throw new Error({ message: "Expected fact to be a number, not a " + fact.class.name, context: fact }); if (fact < 0 || fact >= this.length) throw new Error({ message: "Fact must be between 0 and " + (this.length - 1), context: fact }); let imageVol = new ImageVol(image); imageVol.toVol(function(vol) { this.trainer.train(vol, fact); }.bind(this)); } predict(image, callback) { let imageVol = new ImageVol(image); imageVol.toVol(function(vol) { let probabilities = this.net.forward(vol); let guess = null; let bestGuess = null; for (let i = 0, l = this.length; i < l; i++) { if (guess === null || probabilities.w[i] > guess) { guess = probabilities.w[i]; bestGuess = i; } } callback(bestGuess, probabilities.w[bestGuess]); }.bind(this)); } static option(key, options, label, iteration) { if (!options || !options[label]) return null; if (typeof iteration === 'number') { return options[label][iteration][key]; } return options[label][key]; } static validate(label, iteration) { if (!label || !DEFAULTS[label]) throw new Error({message: "Invalid label", context: label}); if (typeof iteration !== 'undefined') { if (typeof iteration !== 'number') throw new Error({message: "Iteration must be a number", context: iteration}); if (!DEFAULTS[label][iteration]) throw new Error({message: "Invalid iteration for " + label, context: iteration}); } } static cleanOptions(options, label, iteration) { DigitReader.validate(label, iteration); let newOptions = {}; let allowedKeys = Object.keys((typeof iteration === 'number') ? DEFAULTS[label][iteration] : DEFAULTS[label]); allowedKeys.forEach(function(key) { let opt = DigitReader.option(key, options, label, iteration); if (opt) newOptions[key] = opt; }); return newOptions; } static mergeDefaults(options, label, iteration) { let newOptions = DigitReader.cleanOptions(options, label, iteration); if (typeof iteration === 'number') { Object.assign(newOptions, DEFAULTS[label][iteration], newOptions); } else { Object.assign(newOptions, DEFAULTS[label], newOptions); } return newOptions; } } module.exports = DigitReader;
function StrUtils(stdlib, ffi, heap){ "use asm"; var buffer = new stdlib.Uint16Array(heap); var log = ffi.log; function strlen(){ var i = 0; var length = 0; while(buffer[i << 1 >> 1] | 0 != 0){ log((i | 0) >> 0); log((buffer[i << 1 >> 1] | 0) >> 0 ); i = ((i + 1) | 0); length = (length + 1) | 0; } return length | 0; } return { strlen: strlen }; } function AsmText(){ this.initialize.apply(this, arguments); } AsmText.prototype = { initialize: function(text){ this.text = text; console.log(this.buffer); this.util = StrUtils(window, {log: text => { console.log(text); }}, this.buffer); }, get buffer(){ if(this._buffer == null){ this._buffer = new Uint16Array(new ArrayBuffer(0x10000)); this.text.split("").forEach((char, index) => { this._buffer[index] = char.charCodeAt(0); }); } return this._buffer.buffer; }, get uint16(){ return this._buffer; }, get length(){ return this.util.strlen(); } }; (function(){ function App(){ this.initialize.apply(this, arguments); }; App.prototype = { initialize: function(){ this.el = null; }, render: function(){ if(this.el == null){ this._render(); } return this.el; }, _render: function(){ this.el = document.createElement("div"); const input = document.createElement("textarea"); const output = document.createElement("p"); const button = document.createElement("button"); button.textContent = "strlen"; this.el.appendChild(button); this.el.appendChild(input); this.el.appendChild(output); button.addEventListener("click", event => { const t = new AsmText(input.value); console.log(t.text); output.textContent = "length = " + t.length; }); } }; window.addEventListener("load", event =>{ const app = new App(); document.querySelector("#strutils").appendChild(app.render()); }); })();
import { merge, omit } from 'lodash' export { account } from './account' export { files } from './files' export { projects } from './projects' // Updates an entity cache in response to any action with response.entities. export function entities (state = { users: {}, projects: {} }, action) { if (action.response && action.response.entities) { return merge({}, state, action.response.entities) } if (action.method === 'remove') { console.debug('****************** state before:', state) if (!state.entities[action.model.toLowerCase()]) throw new Error('Entity does not exist') const stateWithoutEntity = omit(state[action.model.toLowerCase()], `${action.modelData[1]}/${action.modelData[0]}`) console.debug('returning state:', stateWithoutEntity) return stateWithoutEntity } return state }
function editCustomer(router,connection){ var self=this; self.handleRoutes(router,connection); } editCustomer.prototype.handleRoutes = function(router,connection){ router.post('/editCustomer',function(req,res){ var sessionCode = req.body.sessionCode; var idCustomer = req.body.idCustomer; var name = req.body.name; var phone = req.body.phone; var email = req.body.email; var birthdate = req.body.birthdate; var membershipId = req.body.membershipId; if(sessionCode == null || sessionCode == undefined || sessionCode == ''){ res.json({"message":"err.. no param s_c received"}); }else{ if(idCustomer == null || idCustomer == undefined || idCustomer == ''){ res.json({"message":"err.. no param s_c received"}); }else{ if(name == null || name == undefined || name == ''){ res.json({"message":"err.. no param name received"}); }else{ if(phone == null || phone == undefined || phone == ''){ res.json({"message":"err.. no param name received"}); }else{ var q0 = "update `customer` set name='"+name+"',phone='"+phone+"'where id="+idCustomer; connection.query(q0,function(err,rows){ if(err){ res.json({"message":"err.. error on updating cust 1st query"}); }else{ if(membershipId == null || membershipId == undefined || membershipId == '' ){ if(birthdate == null || birthdate == undefined || birthdate == ''){ if(email == null || email == undefined || email == ''){ res.json({"message":"success update customer non-member"}); }else{ var q1 = "update `customer` set email='"+email+"' where id="+idCustomer; connection.query(q1,function(err,rows){ if(err){ res.json({"message":"err.. error on updating customer","q1":q1}); }else{ res.json({"message":"success updating customer"}); } }); } }else{ if(email == null || email == undefined || email == ''){ var q2 = "update `customer` set birthdate='"+birthdate+"' where id="+idCustomer; connection.query(q2,function(err,rows){ if(err){ res.json({"message":"err.. error on updating customer","q2":q2}); }else{ res.json({"message":"success updating customer"}); } }); }else{ var q3 = "update `customer` set email='"+email+"',birthdate='"+birthdate+"' where id="+idCustomer; connection.query(q3,function(err,rows){ if(err){ res.json({"message":"err.. error on updating customer","q3":q3}); }else{ res.json({"message":"success updating customer"}); } }); } } }else{ if(birthdate == null || birthdate == undefined || birthdate == ''){ if(email == null || email == undefined || email == ''){ var q4 = "update `customer` set membershipId="+membershipId+" where id="+idCustomer; connection.query(q4,function(err,rows){ if(err){ res.json({"message":"err.. error on updating customer","q4":q4}); }else{ res.json({"message":"success updating customer"}); } }); }else{ var q5 = "update `customer` set membershipId="+membershipId+",email='"+email+"' where id="+idCustomer; connection.query(q5,function(err,rows){ if(err){ res.json({"message":"err.. error on updating customer","q5":q5}); }else{ res.json({"message":"success updating customer"}); } }); } }else{ if(email == null || email == undefined || email == ''){ var q6 = "update `customer` set membershipId="+membershipId+",birthdate='"+birthdate+"' where id="+idCustomer; connection.query(q6,function(err,rows){ if(err){ res.json({"message":"err.. error on updating customer","q6":q6}); }else{ res.json({"message":"success updating customer"}); } }); }else{ var q7 = "update `customer` set membershipId="+membershipId+",birthdate='"+birthdate+"',email='"+email+"' where id="+idCustomer; connection.query(q7,function(err,rows){ if(err){ res.json({"message":"err.. error on updating customer","q7":q7}); }else{ res.json({"message":"success updating customer"}); } }); } } } } }); } } } } }); } module.exports = editCustomer;
const array = [1, 42, 7, 9, 13, 10, 20, 35, 45, -7, -3, 0, 4, -1, 15]; Array.prototype.find = function(isOk) { const len = this.length; for(let i = 0; i < len; i += 1) { if(isOk(this[i], i, this)) { return this[i]; } } } Array.prototype.findIndex = function(isOk) { const len = this.length; for(let i = 0; i < len; i += 1) { if(isOk(this[i], i, this)) { return i; } } return -1; } console.log(array.find(x => x % 2 === 0)); console.log(array.find(x => x % 2 === 1)); console.log(array.find(x => x > 10 && x < 20)); console.log(array.find(x => x === 45)); console.log(array.find(x => x === 46)); console.log(array.findIndex(x => x % 2 === 0)); console.log(array.findIndex(x => x % 2 === 1)); console.log(array.findIndex(x => x > 10 && x < 20)); console.log(array.findIndex(x => x === 45)); console.log(array.findIndex(x => x === 46));
module.exports = function resolve(vector) { if (Array.isArray(vector.direction)) { var dimensions = vector.direction.length + 1 var result = new Array(dimensions) for (var dimension = 1; dimension <= dimensions; dimension++) { var axis = vector.magnitude for (var i = 1; i <= dimension; i++) { if (i !== dimensions) { if (i === dimension) { axis *= Math.cos(vector.direction[i - 1]) } else { axis *= Math.sin(vector.direction[i - 1]) } } } result[dimension - 1] = axis } return result } else { return [ vector.magnitude * Math.cos(vector.direction), vector.magnitude * Math.sin(vector.direction) ] } }
'use strict'; const reactions = require('./reactions.js'); class Rule { constructor(expression, reaction) { this.expression = expression; this.reaction = reaction; } } class Rules { constructor() { this.rules = []; } add(rule) { this.rules.push(rule); } length() { return this.rules.length; } } function rulesFromJson(json) { if (!json || !json.rules || json.rules.length <= 0) { throw new Error('No rules found'); } const rules = new Rules(); json.rules.map((entry) => { if (entry.term && entry.reaction) { rules.add( new Rule( new RegExp(entry.term, 'i'), new reactions.ReactionDirectMessage(entry.reaction) ) ); } return entry; }); if (rules.length() <= 0) { throw new Error('No rules found'); } return rules; } module.exports = { rulesFromJson, Rules, Rule, };
/* @flow */ import React from 'react' export function withDOM<T>(cb: (el: Element) => T): T { var div = document.createElement('div') document.body.appendChild(div) var result = cb(div) document.body.removeChild(div) return result } export function cleanHtml(html: string): string { return html.replace(/ data\-reactid=".*?"/g, '') } export function renderToHtml(tree: ReactElement): string { return withDOM(el => { React.render(tree, el) return cleanHtml(el.innerHTML) }) } type map = {[key: string]: any} // Converts Object({...}) to null({...}) export function removeProto(source: map): map { var result = Object.create(null) var keys = Object.keys(source) var i for (i = 0; i < keys.length; i++) { result[keys[i]] = source[keys[i]] } return result }
var path = require('path'); var EventEmitterPrototype = require('events').EventEmitter.prototype; var colors = require('colors'); var utils = require('./utils'); var extend = utils.extend; var dateFormat = utils.dateFormat; var pagerun = {}; pagerun.mode = 'product'; // default mode: product (product | test | debug) pagerun.package = require('../package.json'); pagerun.version = pagerun.package.version; var runConfigs ={}; var arrFilters = []; var arrLogs = []; var arrMessages = []; var arrNpmPlugins = []; // request map var mapRequests = {}; // copy event function pagerun.on = EventEmitterPrototype.on; pagerun.emit = EventEmitterPrototype.emit; // load plugin from core var mapLoadedPlugins = {}; pagerun.loadPlugin = function(pluginName, bNpm){ if(mapLoadedPlugins[pluginName] !== true){ mapLoadedPlugins[pluginName] = true; var modulesRoot = pagerun.modulesRoot || path.resolve('node_modules'); var plugin = bNpm ? require(path.resolve(modulesRoot, 'pagerun-'+pluginName)) : require('./plugins/'+pluginName); var pluginEnv = {}; pluginEnv.config = function(defConfig){ return pagerun.getConfig(pluginName, defConfig); }; pluginEnv.log = function(type, message){ return pagerun.log(pluginName, type, message); }; pluginEnv.error = function(message){ return pagerun.message(pluginName, 'error', message); }; pluginEnv.warn = function(message){ return pagerun.message(pluginName, 'warn', message); }; pluginEnv.info = function(message){ return pagerun.message(pluginName, 'info', message); }; plugin.call(pluginEnv, pagerun); pagerun.log('pagerun', 'loadPlugin', pluginName + ' ('+(bNpm?'npm':'core')+')'); } } // load plugin from npm pagerun.loadNpmPlugin = function(pluginName){ arrNpmPlugins.push(pluginName); }; // set run config pagerun.setConfig = function(configs){ var newConfig; var oldConfig; for(var name in configs){ oldConfig = runConfigs[name]; newConfig = configs[name]; if(typeof newConfig === 'object'){ newConfig = extend(oldConfig?oldConfig:{}, newConfig); } runConfigs[name] = newConfig; } }; // get filter config pagerun.getConfig = function(name, defConfig){ var config = runConfigs[name]; if(typeof config === 'object'){ config = extend(defConfig?defConfig:{}, config?config:{}); } else if(config === undefined){ config = defConfig?defConfig:''; } return config; } // add request map pagerun.addRequestMap = function(path, data){ mapRequests[path] = data; } // check url matched pagerun.isMatchUrl = function(url, arrChecks){ if(arrChecks !== undefined){ for(var i=0,c=arrChecks.length;i<c;i++){ if(isMatchUrl(url, arrChecks[i])){ return true; } } } else{ return true; } return false; } function isMatchUrl(url, check){ var bMatch = false, regCheck = str2Reg(check); if(regCheck !== undefined){ if(regCheck.test(url) === true){ bMatch = true; } } else if(check.substr(0,1) === '!' && url === check.substr(1)){ bMatch = true; } else if(url.indexOf(check) === 0){ bMatch = true; } return bMatch; } function str2Reg(str){ var match = str.match(/^\/(.+)\/([i])?$/); if(match !== null){ var reg; try { reg = RegExp(match[1], match[2]); } catch(ex) {} if(reg !== undefined){ return reg; } } } // save log pagerun.log = function(module, type, message){ message = message?message:''; var dateString = dateFormat('yyyy-MM-dd hh:mm:ss'); arrLogs.push({ module: module, type: type, message: message, time: new Date().getTime() }); if(pagerun.mode !== 'product'){ console.log('[' + dateString.green + ']: ',module,type,message); } }; // save result pagerun.message = function(module, type, message){ arrMessages.push({ type: type, module: module, message: message, time: new Date().getTime() }); } // run pagerun.run = function(done){ // load core plugins pagerun.loadPlugin('pageproxy'); pagerun.loadPlugin('hosts'); pagerun.loadPlugin('webdriver'); pagerun.loadPlugin('inject'); pagerun.loadPlugin('bridge'); // load npm plugins arrNpmPlugins.forEach(function(pluginName){ pagerun.loadPlugin(pluginName, true); }); var runState = false; pagerun.on('webdriverEnd', function(bSuccess){ runState = bSuccess }); pagerun.on('proxyStart', function(msg){ var proxy = msg.proxy; proxy.addFilter(function(httpData, next, end){ if(httpData.type === 'request' && httpData.hostname === 'pagerun'){ var responseData = mapRequests[httpData.hostname + httpData.path]; if(responseData !== undefined){ httpData.responseCode = responseData.responseCode; httpData.responseHeaders = responseData.responseHeaders; httpData.responseData = responseData.responseData; return end(); } } next(); }); }); pagerun.on('proxyEnd', function(){ pagerun.log('pagerun','end'); pagerun.emit('runEnd'); done({ success: runState, messages: arrMessages, logs: arrLogs }); }); pagerun.log('pagerun','start'); pagerun.emit('runStart'); }; pagerun.localIp = utils.localIp(); module.exports = pagerun;
var test = require('tape'); var sinon = require('sinon'); var consts = require('../src/constants'); var playerSync = require('../src/playerSync/controller'); var THREE = require('three'); var testId = 'id1'; var testId2 = 'id2'; var initialPosition = consts.playerSync.AVATAR_INITIAL_POSITION; var initialPositionVector = new THREE.Vector3(); initialPositionVector.set(initialPosition[0], initialPosition[1], initialPosition[2]); var slightlyMovedVector = new THREE.Vector3(); slightlyMovedVector.set(initialPosition[0] + consts.playerSync.ROUGH_MOVEMENT_THRESHOLD / 10, initialPosition[1], initialPosition[2]); var brutallyMovedVector = new THREE.Vector3(); brutallyMovedVector.set(initialPosition[0], initialPosition[1] + consts.playerSync.ROUGH_MOVEMENT_THRESHOLD * 1000, initialPosition[2]); var initialRotationXY = { x: 0, y: 0 }; var setup = function() { playerSync.onLeave(testId, function() {}); playerSync.onLeave(testId2, function() {}); }; test('PlayerSyncController::onJoin', function(t) { setup(); var broadcast = sinon.spy(); playerSync.onJoin(testId, broadcast); t.ok(broadcast.calledWith(testId), 'should call broadcast with id passed'); playerSync.sendUpdates(function(update) { var playerInfo = update.positions[testId]; t.deepEqual(playerInfo.position, initialPositionVector, 'position should be equal to initial as defined in consts'); t.deepEqual(playerInfo.rotation, initialRotationXY, 'rotation should be equal to zero'); t.end(); }); }); test('PlayerSyncController::onLeave', function(t) { setup(); var broadcast = sinon.spy(); playerSync.onJoin(testId, function() {}); playerSync.onJoin(testId2, function() {}); playerSync.onLeave(testId, broadcast); t.ok(broadcast.calledWith(testId), 'should call broadcast with id passed'); playerSync.sendUpdates(function(update) { var playerInfo = update.positions[testId]; t.ok(!playerInfo, 'there should be no info for a player that left'); t.end(); }); }); test('PlayerSyncController::sendUpdates', function(t) { setup(); var broadcast = sinon.spy(); playerSync.sendUpdates(broadcast); t.ok(!broadcast.called, 'doesnt call callback if there are no logged users'); playerSync.onJoin(testId, function() {}); playerSync.onJoin(testId2, function() {}); var now = new Date(); playerSync.sendUpdates(function(update) { t.pass('calls callback if there is at least one logged user'); t.equal(Object.keys(update.positions).length, 2, 'contains information of all logged users'); t.deepEqual(update.date, now, 'date should be now'); t.end(); }); }); test('PlayerSyncController::onState when movement is normal', function(t) { setup(); playerSync.onJoin(testId, function() {}); var state = { position: slightlyMovedVector, rotation: new THREE.Vector3(1, 2) }; playerSync.onState(testId, state); playerSync.sendUpdates(function(update) { var playerInfo = update.positions[testId]; t.deepEqual(playerInfo.rotation, {x: 1, y: 2}, 'should alter rotation'); t.deepEqual(playerInfo.position, state.position, 'should alter position if the movement is not too rough'); t.end(); }); }); test('PlayerSyncController::onState when movement is rough', function(t) { setup(); playerSync.onJoin(testId, function() {}); var state = { position: brutallyMovedVector, rotation: new THREE.Vector3() }; playerSync.onState(testId, state); playerSync.sendUpdates(function(update) { var lerpedYPosition = initialPosition[1] + (consts.playerSync.ROUGH_MOVEMENT_THRESHOLD * 1000 * consts.playerSync.LERP_PERCENT); var playerInfo = update.positions[testId]; t.deepEqual(playerInfo.rotation, {x: 0, y: 0}, 'should alter rotation'); t.deepEqual(playerInfo.position, {x: state.position.x, y: lerpedYPosition, z: state.position.z}, 'should lerp position vector'); t.end(); }); });
import React from "react" import Header from "../components/Header" import Button from "../components/Button" import { Div, P, Span } from "../components/Base" import Img from "../images/Hangout" import Layout from "../components/Layout" export default function Meetings() { return ( <Layout pageTitle="Meetings" description="Want to come join in on the fun at our next meetup? Visit the link below to find out when we will be having our next event." > <Div maxWidth="1200px" flexd flexWrap="wrap" mt={12} mx="auto" mb={24} jc="space-around" ai="center" > <Span p={[4]} width={[1, 1, 1 / 2]} maxWidth="400px"> <Img /> </Span> <Div p={[8, 8, 4]} pb={[4, 0]} width={[1, 1, 1 / 2]} ff="sans.0"> <Header type={1} fs={["2xl", "3xl"]} color="grey8"> Next Meetup Event </Header> <P fs="lg" color="grey8" lh="normal"> Want to come join in on the fun at our next meetup? Visit the link below to find out when we will be having our next event. </P> <Span> <Button as="a" href="https://www.meetup.com/TulsaJS/" target="_blank" rel="nofollow" type="primary" small > Meetup Page </Button> </Span> </Div> </Div> </Layout> ) }
import React from 'react' export default React.createClass ({ render() { return ( <span> <h2> {this.props.name} </h2> </span> ) } })
"use strict"; const mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = new Schema({ /* * The UTC datetime that the user account was created on Twitter. * * Example: "created_at": "Mon Nov 29 21:18:15 +0000 2010" */ created_at: String, /* * When true, indicates that the user has not altered the theme or background of their user profile. */ default_profile: Boolean, /* * When true, indicates that the user has not uploaded their own avatar and * a default egg avatar is used instead. */ default_profile_image: Boolean, /* * Nullable. The user-defined UTF-8 string describing their account */ description: String, /* * The number of tweets this user has favorited in the account’s lifetime. * British spelling used in the field name for historical reasons. */ favourites_count: Number, /* * The number of followers this account currently has. * Under certain conditions of duress, this field will temporarily indicate “0.” */ followers_count: Number, /* * The number of users this account is following (AKA their “followings”). * Under certain conditions of duress, this field will temporarily indicate “0.” */ friends_count: Number, /* * The string representation of the unique identifier for this User. * Implementations should use this rather than the large, possibly un-consumable integer in id. */ id_str: { type: String, index: { unique: true, sparse: true }, lowercase: true, trim: true, default: '' }, /* * The BCP 47 code for the user’s self-declared user interface language. * May or may not have anything to do with the content of their Tweets. */ lang: String, /* * The number of public lists that this user is a member of. */ listed_count: Number, /* * Nullable. The user-defined location for this account’s profile. * Not necessarily a location nor parseable. * This field will occasionally be fuzzily interpreted by the Search service. * * Example: "location": "San Francisco, CA" */ location: String, /* * The name of the user, as they’ve defined it. Not necessarily a person’s name. * Typically capped at 20 characters, but subject to change. */ name: String, /* * A HTTPS-based URL pointing to the background image the user has uploaded for their profile. */ profile_background_image_url_https: String, /* * The HTTPS-based URL pointing to the standard web representation of the user’s uploaded profile banner. * By adding a final path element of the URL, you can obtain different image sizes optimized * for specific displays. In the future, an API method will be provided to serve these URLs * so that you need not modify the original URL. For size variations, please see User Profile Images * and Banners. * * Example: "profile_banner_url": "https://si0.twimg.com/profile_banners/819797/1348102824" */ profile_banner_url: String, /* * A HTTPS-based URL pointing to the user’s avatar image. */ profile_image_url_https: String, /* * The screen name, handle, or alias that this user identifies themselves with. * screen_names are unique but subject to change. Use id_str as a user identifier whenever possible. * Typically a maximum of 15 characters long, but some historical accounts may exist with longer names. */ screen_name: String, /* * The number of tweets (including retweets) issued by the user. */ statuses_count: Number, /* * Nullable. A string describing the Time Zone this user declares themselves within. * * Example: "time_zone":"Pacific Time (US & Canada)" */ time_zone: String, /* * Nullable. A URL provided by the user in association with their profile. */ url: String, /* * When true, indicates that the user has a verified account. See Verified Accounts. */ verified: Boolean, /* * When present, indicates a textual representation of the two-letter country codes this user is withheld from. */ withheld_in_countries: String }); module.exports = mongoose.model('User', userSchema);
'use strict'; module.exports = { app: { title: 'FrogBan', description: 'A KanBan system for FogBugz using MeanJS', keywords: 'KanBan, FogBugz, MeanJS' }, port: process.env.PORT || 3000, templateEngine: 'swig', sessionSecret: 'MEAN', sessionCollection: 'sessions', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.css', ], js: [ 'public/lib/angular/angular.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.js', 'public/lib/angular-ui-utils/ui-utils.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.js' ] }, css: [ 'public/modules/**/css/*.css' ], js: [ 'public/config.js', 'public/application.js', 'public/modules/*/*.js', 'public/modules/*/*[!tests]*/*.js' ], tests: [ 'public/lib/angular-mocks/angular-mocks.js', 'public/modules/*/tests/*.js' ] } };
(function (ang) { var app = ang.module('app'); app.config(function ($resourcesProvider, $stateProvider, $urlRouterProvider) { // Resources $resourcesProvider.init({ resources: { Users: { route: '/api/v1/users/:userId?:query' }, Logout: { route: '/auth/v1/logout' } } }); // Router $urlRouterProvider.otherwise("/"); $stateProvider .state('users', { url: '/users', template: '<div class="cover" ui-view></div>' }) .state('users.registered', { url: '/registered', templateUrl: '/front/modules/console-seed/dev/users/registered.html', controller: 'usersRegisteredController' }) }); })(angular);
import React, { Component } from 'react'; import './App.css'; import Articles from './components/Articles'; class App extends Component { constructor(props) { super(props) this.state = {sortOrder: "VOTES"} } handleTopClick = () => { this.setState({sortOrder: "VOTES"}) } handleNewestClick = () => { this.setState({sortOrder: "DATE"}) } render() { const { articles } = this.props; const { sortOrder } = this.state; return ( <div className="App"> <div className="navigation"> <button data-testid="top-link" onClick={this.handleTopClick}>Top</button> <button data-testid="newest-link" onClick={this.handleNewestClick}>Newest</button> </div> <Articles articles={articles} sortOrder={sortOrder} /> </div> ); } } export default App;
'use strict'; const SwiftTransformStream = require('swift-transform').Transform; const pTry = require('p-try'); class IteratorCallerStream extends SwiftTransformStream { constructor(iterator, concurrency) { super({ objectMode: true, concurrency }); this._iterator = iterator; this._count = 0; } getCount() { return this._count; } // ------------------------------------------------- _transform(data, encoding, callback) { data.index = this._count++; // eslint-disable-line no-plusplus // Execute the iterator // Note that the iterator can throw synchronously as well as return non-promise values pTry(() => this._iterator(data)) // Invoke callback asyncronously so that errors are not swalled by the promise // This also guarantees that the promise chain is broken so that they don't stack (avoiding possible leaks) .then( () => setImmediate(() => callback(null, data)), (err) => setImmediate(() => callback(err)) ); } } module.exports = function (iterator, concurrency) { return new IteratorCallerStream(iterator, concurrency); };
// preview and play in JSBin - http://jsbin.com/aviyuf/edit#source //loggging for JSBin var log = function(msg){ if (document.getElementById('log')) { document.getElementById('log').innerHTML = document.getElementById('log').innerHTML + "<br/>" + msg; } }; /* helper functions */ var getProp = function(property){ log(property + " - " + this[property]); }; var setProp = function(property, value){ this[property] = value; } /* Function calls */ Sugarless({name: "Tom"})( getProp, "name" , setProp, "name", "Tommy" , getProp, "name" ); Sugarless({name: "Jerry"})( getProp, "name" , setProp, "age", 10 , getProp, "age" );
ActiveNavigation = { bootstrap: function() { this.create_main_menu(); this.create_sub_menus(); this.attach_events(); }, create_main_menu: function() { chrome.contextMenus.removeAll(); chrome.contextMenus.create({ id: 'active_navigation_content_menu', title: 'Active Navigation', contexts: ['page'] }); return this; }, create_sub_menus: function() { chrome.tabs.query({}, function(tabs) { var tabs_length = tabs.length; for (var i = 0; i < tabs_length; i++) { var tab = tabs[i]; var context_menu_item = { id: "" + tab.id, title: tab.title, parentId: "active_navigation_content_menu", } if (tab.highlighted && tab.selected && tab.active) { context_menu_item.type = "checkbox"; context_menu_item.checked = true; } chrome.contextMenus.create(context_menu_item); } }); return this; }, attach_events: function() { this.attach_context_menu_item_clicked(); this.attach_tab_highlighted(); }, attach_context_menu_item_clicked: function() { chrome.contextMenus.onClicked.addListener(function(info, tab) { chrome.tabs.update(parseInt(info.menuItemId), {highlighted: true}); }); }, attach_tab_highlighted: function() { chrome.tabs.onHighlighted.addListener(function(tab) { ActiveNavigation.create_main_menu().create_sub_menus(); }); } } ActiveNavigation.bootstrap();
/** * @file Option * * @author Leo Wang(leowang721@gmail.com) */ var _ = require('lodash'); var React = require('react-native'); var { PickerIOS, View, Text, TouchableOpacity, } = React; var FormElement = require('./FormElement'); var ICON = { checkbox: '□▣', radio: '○◉' }; var styles = require('./styles/option'); /** * Option * when setting props.value, watch out Float Number < 1, the comparation would have problem * @class Option * @extends FormElement * @requires FormElement */ class Option extends FormElement { /** * @constructor * * @param {Object} props properties * * @param {string} props.id element's id, setting id will set props.ref with the same value * @param {?Object} props.style style * @param {string=} props.type type of the current form element, will try to set styles[type] * * @param {string|number} value value, watch out Float Number < 1, the comparation would have problem * @param {?string} label label for this option * @param {?(Object} props.labelStyle styles for label * @param {?(string|Component)} props.icon icon for option, you can use either unicode characters or a Component * @param {?(Object} props.iconStyle styles for icon * * @param {?Object} context context */ constructor(props, context) { super(props, context); } render() { var optionStyles = this.getStyles(styles); var icon; var selectedIcon; var iconProp = this.props.icon || ICON[this.props.type]; if (iconProp) { if (typeof iconProp === 'string') { if (iconProp.length === 1) { icon = selectedIcon = (<Text style={[optionStyles.icon, this.props.iconStyle]}>{iconProp}</Text>); } else { icon = (<Text style={[optionStyles.icon, this.props.iconStyle]}>{iconProp[0]}</Text>); selectedIcon = (<Text style={[optionStyles.icon, this.props.iconStyle]}>{iconProp[1]}</Text>); } } else if (iconProp.isReactElement) { icon = selectedIcon = (<View style={[optionStyles.icon, this.props.iconStyle]}>{iconProp}</View>); } else if (_.isArray(iconProp)) { icon = (<View style={[optionStyles.icon, this.props.iconStyle]}>{iconProp[0]}</View>); selectedIcon = (<View style={[optionStyles.icon, this.props.iconStyle]}>{iconProp[1]}</View>); } } return ( <TouchableOpacity onPress={this.onPress.bind(this)} style={[ ...optionStyles.container, this.props.style, this.props.selected ? optionStyles.selected : [], ]} {..._.omit(this.props, ['children', 'style', 'onPress'])}> <View style={optionStyles.labelContainer}> {this.props.selected ? selectedIcon : icon} <Text style={[...optionStyles.label, this.props.labelStyle]}> {this.props.label || this.props.value} </Text> </View> </TouchableOpacity> ); } onPress() { if (this.props.onPress) { this.props.onPress(this.props.value); } } } Option.propTypes = FormElement.assignPropTypes(PickerIOS.propTypes, { label: React.PropTypes.string, icon: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.element]), labelStyle: React.PropTypes.object, iconStyle: React.PropTypes.object, onPress: React.PropTypes.func, }); Option.defaultProps = {}; module.exports = Option;
class ehstorshell_ehstorfolder_1 { constructor() { } // System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) CreateObjRef() { } // bool Equals(System.Object obj) Equals() { } // int GetHashCode() GetHashCode() { } // System.Object GetLifetimeService() GetLifetimeService() { } // type GetType() GetType() { } // System.Object InitializeLifetimeService() InitializeLifetimeService() { } // string ToString() ToString() { } } module.exports = ehstorshell_ehstorfolder_1;
IonicBBS.controller("LoginCtrl",function($scope,$rootScope){ console.log("app.."); //表单部分 $scope.fm = { // userName : "", // passWord : "" } $scope.login = function(){ console.log("login..."); } });
/** * meta 配置 * hidden=true表示在导航上默认不展示 * requiresAuth=true 表示需要身份验证即需要登录 * scrollTop=true 切换路由时,页面滚动到顶部,默认是true * type: resource/node 对应的侧边栏 */ import Vue from 'vue' import Router from 'vue-router' import Views from '@/views/index' import store from '../store' import nodeRoute from './node' import resourceRoute from './resource' import {gotoLogin} from "../lib/utils"; Vue.use(Router) const scrollBehavior = (to, from, savedPosition) => { if (savedPosition) { return savedPosition } const position = {} if (to.hash) { position.selector = to.hash } if (to.meta.scrollToTop !== false) { position.x = 0 position.y = 0 } return position } const router = new Router({ mode: 'history', scrollBehavior, routes: [ { path: '/', meta: {title: '资源市场'}, component: Views.layout, children: [resourceRoute, nodeRoute, { path: 'about', hidden: true, meta: { requiresAuth: false, title: '关于freelog' }, component: Views.aboutView }, { path: 'setting', hidden: true, meta: { requiresAuth: true, title: '账号设置' }, component: Views.userView }, { path: 'help', hidden: true, meta: { requiresAuth: false, title: '帮助中心' }, component: Views.helpView }, { path: '/', hidden: true, meta: { requiresAuth: false, title: '资源市场', theme: 'gray' }, component: Views.mainView }] }, { path: '*', meta: { requiresAuth: false, title: 'not found' }, component: Views.layout, children: [{ name: '404', path: '', meta: { requiresAuth: false, title: '404' }, component: Views.error }] } ] }) function listenWindowVisibility() { let hidden = 'hidden' const doc = document if (hidden in doc) { doc.addEventListener('visibilitychange', onchange) } else if ('mozHidden' in doc) { hidden = 'mozHidden' doc.addEventListener('mozvisibilitychange', onchange) } else if ('webkitHidden' in doc) { hidden = 'webkitHidden' doc.addEventListener('webkitvisibilitychange', onchange) } else if ('msHidden' in doc) { hidden = 'msHidden' doc.addEventListener('msvisibilitychange', onchange) } else { const events = ['onpageshow', 'onpagehide', 'onfocus', 'onblur'] events.forEach((name) => { window[name] = onchange() }) } function onchange(evt) { const v = 'visible' const h = 'hidden' const evtMap = { focus: v, focusin: v, pageshow: v, blur: h, focusout: h, pagehide: h } let type evt = evt || window.event if (evt.type in evtMap) { type = evtMap[evt.type] } else { type = this[hidden] ? 'hidden' : 'visible' } if (type === 'visible') { isChecked = false } } } //避免每次跳转都判断登录态的判断,只有切换tab后回来再重新判断 var isChecked = false listenWindowVisibility() router.beforeEach((to, from, next) => { if (isChecked) { return next() } store.dispatch('checkUserSession') .then(isSameSession => { isChecked = true if (isSameSession) { next() } else { store.dispatch('getCurrentUserInfo') .then(user => { if (user) { window.location = to.fullPath } else { gotoLogin() } }) } }) }) export default router
export const api_key = "dc6zaTOxFJmzC";
import {expect} from 'chai'; import formatCurrency from '../../../frontend/src/lib/format_currency'; describe('formatCurrency', () => { it('should return $12.34', () => { expect(formatCurrency(12.34)).to.equal('$12.34'); }); it('should return $12,345.67', () => { expect(formatCurrency(12345.67)).to.equal('$12,345.67'); }); it('should return £12.34', () => { expect(formatCurrency(12.34, 'GBP')).to.equal('£12.34'); }); it('should return 12.34', () => { expect(formatCurrency(12.34, 'SEK')).to.equal('kr12,34'); }); it('should return €12.34', () => { expect(formatCurrency(12.34,'EUR')).to.equal('€12,34'); }); it('should return €12 345.67', () => { expect(formatCurrency(12345.67,'EUR')).to.equal('€12 345,67'); }); it('should return -€12.34', () => { expect(formatCurrency(-12.34,'EUR')).to.equal('-€12,34'); }); it('should return MXN$10', () => { expect(formatCurrency(10,'MXN',{precision: 0, compact: false})).to.equal('MXN $10'); }) });
const MongoClient = require('mongodb').MongoClient; const config = require('./../config'); const dbName = config.DB_NAME; let currentConnection = null; async function connect() { if (currentConnection === null) { currentConnection = await MongoClient.connect(config.DB_URL, { useNewUrlParser: true, useUnifiedTopology: true, }); } return currentConnection; } async function close() { if (currentConnection !== null) { currentConnection.close(); currentConnection = null; } } async function insertMany(collectionName, items) { const collection = currentConnection.db(dbName).collection(collectionName); const queryResult = await collection.insertMany(items); return queryResult; } async function findAll(collectionName) { const collections = await currentConnection.db(dbName).collections(); const queryResult = new Map(); for (collection of collections) { const collectionName = collection.collectionName; if (!queryResult.has(collectionName)) { queryResult.set(collectionName, []); } const collectionResults = await collection.find().toArray(); queryResult.get(collectionName).push(...collectionResults); } return queryResult; } async function dropIfExists(collectionName) { let queryResult = null; if (await isCollectionExists(collectionName)) { const collection = currentConnection.db(dbName).collection(collectionName); queryResult = await collection.drop(); } return queryResult; } async function isCollectionExists(collectionName) { const collections = await currentConnection.db(dbName).listCollections().toArray(); return collections.some((collection) => collection.name === collectionName); } module.exports = { isCollectionExists, dropIfExists, findAll, insertMany, close, connect, }
ScalaJS.modules.org_littlewings_scalajs_ScalaJsGettingStarted().main();
/* eslint-env es5,node */ require('babel-register'); let config; if (process.env.NODE_ENV === 'production') config = require('./webpack.production').default; else config = require('./webpack.development').default; module.exports = config;
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* jshint maxlen: false */ 'use strict'; var createAPIRequest = require('../../lib/apirequest'); /** * Google Cloud Vision API * * Integrates Google Vision features, including image labeling, face, logo, and landmark detection, optical character recognition (OCR), and detection of explicit content, into applications. * * @example * var google = require('googleapis'); * var vision = google.vision('v1'); * * @namespace vision * @type {Function} * @version v1 * @variation v1 * @param {object=} options Options for Vision */ function Vision(options) { // eslint-disable-line var self = this; self._options = options || {}; self.images = { /** * vision.images.annotate * * @desc Run image detection and annotation for a batch of images. * * @example * // PRE-REQUISITES: * // --------------- * // 1. If not already done, enable the Google Cloud Vision API * // and check the quota for your project at * // https://console.developers.google.com/apis/api/vision * // 2. This sample uses Application Default Credentials for Auth. * // If not already done, install the gcloud CLI from * // https://cloud.google.com/sdk/ and run 'gcloud auth application-default login' * // 3. To install the client library and Application Default Credentials library, run: * // 'npm install googleapis --save' * var google = require('googleapis'); * var vision = google.vision('v1'); * * google.auth.getApplicationDefault(function(err, authClient) { * if (err) { * console.log('Authentication failed because of ', err); * return; * } * if (authClient.createScopedRequired && authClient.createScopedRequired()) { * var scopes = ['https://www.googleapis.com/auth/cloud-platform']; * authClient = authClient.createScoped(scopes); * } * * var request = { * // TODO: Change placeholders below to appropriate parameter values for the 'annotate' method: * * resource: {}, * // Auth client * auth: authClient * }; * * vision.images.annotate(request, function(err, result) { * if (err) { * console.log(err); * } else { * console.log(result); * } * }); * }); * * @alias vision.images.annotate * @memberOf! vision(v1) * * @param {object} params Parameters for request * @param {object} params.resource Request body data * @param {callback} callback The callback that handles the response. * @return {object} Request object */ annotate: function (params, callback) { var parameters = { options: { url: 'https://vision.googleapis.com/v1/images:annotate', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); } }; } module.exports = Vision;
/** * Author jmorrison * Date: 8/29/11 * Time: 12:20 PM */ function isArray(obj) { return (obj.constructor.toString().indexOf(”Array”) != -1); }
'use strict'; angular.module('mean').config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider .state('users', { url: '/admin/users', templateUrl: 'mean-admin/views/users.html' }).state('themes', { url: '/admin/themes', templateUrl: 'mean-admin/views/themes.html' }).state('settings', { url: '/admin/settings', templateUrl: 'mean-admin/views/settings.html' }).state('modules', { url: '/admin/modules', templateUrl: 'mean-admin/views/modules.html' }).state('administration', { url: '/admin/administration', templateUrl: 'mean-admin/views/administration.html' }); } ]);
var utils = require('./utils') var config = require('../config') var isProduction = process.env.NODE_ENV === 'production' module.exports = { loaders: utils.cssLoaders({ sourceMap: isProduction ? config.build.productionSourceMap : config.dev.cssSourceMap, extract: isProduction }), preLoaders: { pug: 'pug-html-loader' } }
import { LOAD_DATA_INITIATION, LOAD_DATA_SUCCESS, LOAD_DATA_FAILURE, CLEAR_DATA_ERROR, } from './constants'; const initialState = { isLoading: false, data: {}, error: {}, }; /** * @function featureComponent * @description A redux reducer function * Takes state and an action and returns next state. * @param {state} - the state tree of the application * @param {action} - the dispatched redux action */ const featureComponent = (state = initialState, action) => { switch (action.type) { case LOAD_DATA_INITIATION: return Object.assign({}, state, { isLoading: true, }); case LOAD_DATA_SUCCESS: return Object.assign({}, state, { isLoading: false, data: action.data, }); case LOAD_DATA_FAILURE: return Object.assign({}, state, { isLoading: false, error: action.error, }); case CLEAR_DATA_ERROR: return Object.assign({}, state, { error: {}, }); default: return state; } }; export default featureComponent;
'use strict'; const gulp = require('gulp'); const autoprefixer = require('gulp-autoprefixer'); const browserSync = require('browser-sync').create(); const sass = require('gulp-sass'); const sassGlob = require('gulp-sass-glob'); const scssLint = require('gulp-scss-lint'); const webpack = require('webpack-stream'); const publicDir = './public/'; const scriptsDir = './assets/scripts/'; const stylesDir = './assets/styles/'; const scripts = [scriptsDir + '**/*.js', scriptsDir + '**/*.vue']; const styles = stylesDir + '**/*.scss'; const webpackConfig = require('./webpack.config.js'); function webpackError() { this.emit('end'); } gulp.task('js', () => { gulp.src(scriptsDir + 'main.js') .pipe(webpack(webpackConfig)) .on('error', webpackError) .pipe(gulp.dest(publicDir)) .pipe(browserSync.stream()); }); gulp.task('scssLint', () => { gulp.src(styles) .pipe(scssLint({ 'config': 'config/scss-lint.yml' })); }); gulp.task('sass', ['scssLint'], () => { gulp.src(stylesDir + 'main.scss') .pipe(sassGlob()) .pipe(sass({outputStyle: 'compressed'}) .on('error', sass.logError) ) .pipe(autoprefixer()) .pipe(gulp.dest(publicDir)) .pipe(browserSync.stream()); }); gulp.task('reload', () => { browserSync.reload(); }); gulp.task('default', ['sass'], () => { browserSync.init({ server: publicDir, }); gulp.watch(scripts, ['js']); gulp.watch(styles, ['scssLint', 'sass']); gulp.watch(publicDir + '**/*.html', ['reload']); });
// Deprecated /* istanbul ignore file */ import styled from 'styled-components' export const config = { borderWidth: '2px', } const AvatarStackUI = styled('div')` display: flex; position: relative; &.is-withLayerStack { padding-left: calc(${config.borderWidth} * 3); } ` export const AvatarStackLayeringUI = styled(AvatarStackUI)` align-items: center; justify-content: center; margin: auto; max-width: 230px; min-height: 64px; width: 100%; min-width: 0; ` export const ItemUI = styled('div')` position: relative; &.is-withLayerStack { margin-left: 0; } `
// For authoring Nightwatch tests, see // http://nightwatchjs.org/guide#usage module.exports = { 'default e2e tests': function test(browser) { // automatically uses dev Server port from /config.index.js // default: http://localhost:8080 // see nightwatch.conf.js const devServer = browser.globals.devServerURL; browser .url(devServer) .waitForElementVisible('#app', 5000) .assert.containsText('p', 'App') .end(); }, };
import React, { useState, useCallback } from 'react'; // component import MaintenaceBanner from './component'; // utils import { getMaintenanceBannerAccepted, setMaintenanceBannerAccepted } from './helpers'; const MaintenaceBannerContainer = () => { const [maintenanceBannerAccepted, setMaintenanceBannerAcceptance] = useState(getMaintenanceBannerAccepted()); const memoizedCallback = useCallback( () => { setMaintenanceBannerAccepted(); }, [], ); const handleMaintenanceBanner = () => { setMaintenanceBannerAcceptance(true); memoizedCallback(); }; return !maintenanceBannerAccepted ? ( <MaintenaceBanner handleMaintenanceBanner={handleMaintenanceBanner} timeText="Monday 27th April 2020 (10:00 to 16:00 CET)" /> ) : null; }; export default MaintenaceBannerContainer;
'use strict'; module.exports = function (stamp, flags) { if (stamp.p === 'win32' && flags.ci) { return { allow: false, note: 'headless windows CI seems to fail' }; } return { deployFilesFrom: [ 'opn' ] }; };
'use strict'; const mongoose = require('mongoose'); module.exports = mongoose.model('buys', mongoose.Schema({ name: String, symbol: String, quantity: String, price: String }) );
/* @noflow */ import React from 'react'; import Redirect from '../'; import {shallow, mount} from 'enzyme'; describe('<Redirect>', () => { var context, navigate, serverResult; beforeEach(() => { serverResult = {}; navigate = jest.fn(); context = { router: { linkMiddleware: [], location: {}, urls: { makeLocation({urlName, params}) { expect(urlName).toEqual('user:profile'); expect(params).toEqual({username: 'x'}); return {pathname: "/u/x/", search: '?a=b'}; }, match() { return {}; } }, navigate, history: { createHref(location) { expect(location).toEqual({pathname: "/u/x/", search: "?a=b"}); return "/u/x/?a=b"; } }, listen: () => () => {}, serverResult } }; }); it('should redirect on mount', () => { mount(<Redirect urlName="user:profile" params={{username: 'x'}} state={{statevar: 1}} />, {context}); expect(navigate).toBeCalledWith(jasmine.objectContaining({urlName: "user:profile", params: {username: 'x'}, state: {statevar: 1}}), false); }); it('should replace if instructed', () => { mount(<Redirect urlName="user:profile" params={{username: 'x'}} state={{statevar: 1}} replace={true} />, {context}); expect(navigate).toBeCalledWith(jasmine.objectContaining({urlName: "user:profile", params: {username: 'x'}, state: {statevar: 1}}), true); }); it('should update serverResult if provided', () => { const wrapper = shallow(<Redirect urlName="user:profile" params={{username: 'x'}} query={{a: 'b'}} state={{statevar: 1}} />, {context}); // Shallow again because of withRouter decorator shallow(wrapper.node, {context}); expect(navigate).not.toBeCalled(); expect(serverResult.redirect).toEqual('/u/x/?a=b'); }); });
'use strict'; var _Promise = require('babel-runtime/core-js/promise')['default']; Object.defineProperty(exports, '__esModule', { value: true }); var utils = {}; utils.formatSectionsIntoPage = function (mapData) { mapData.html = mapData.html.replace('</body>', '<script>' + mapData.js + '</script></body>'); mapData.html = mapData.html.replace('</head>', '<style>' + mapData.css + '</style></head>'); return _Promise.resolve(mapData.html); }; exports['default'] = utils; module.exports = exports['default'];
var mongoose = require('mongoose') , Truck = mongoose.model('Truck') , Feed = mongoose.model('Feed') exports.get = function (req, res) { Truck .find({}) .exec(function (err, trucks) { if (err) throw err if (trucks) res.json(trucks) }) } function populateTruck (params, truck, user) { console.log(user) //if (!user) return null //Populate the trucks truck.date=Date.now() if (params.temporality) truck.temporality = params.temporality if (params.location) truck.location = params.location if (params.validity) truck.validity = params.validity truck.version++ Feed .findOne({}) .exec(function (err, tweets) { if (err) throw err if (tweets) { tweets = tweets.tweets for (i in tweets) { var tweet = tweets[i] if (tweet._id==params.id) { var twt = { username : user, version: truck.version, screen_name: tweet.screen_name, content: tweet.content, geo: tweet.geo, datePosted: tweet.datePosted, avatar: tweet.avatar } if (twt.geo && !truck.location) truck.location = twt.geo tweet.username = user tweet.version = truck.version truck.tweets.push(twt) console.log(truck) } } } truck.save() }) } exports.del = function (req, res) { var now = new Date() //just for testing, to avoid using mocha Truck .find({date: {$lt: now.setDate(now.getDate()-1)}, temporality:"today"}) .exec(function(err, trucks){ if (err) throw err console.log(trucks) }) Truck .remove({}) .exec(function(err,slt) { res.send("Removed") }) } exports.post = function (req, res) { var params = null if (req.params) params = req.params if (req.body) params = req.body if (!params) return null Truck .findOne({truckName: params.truckname}) .exec(function (err, truck) { if (err) throw err if (!truck) { console.log("New truck created...") var truck = new Truck() truck.truckName=params.truckname } console.log(truck) populateTruck(params, truck, req.user) }) Truck .remove({date: {$lt: now.setDate(now.getDate()-1)}, temporality:"today"}) .exec(function(err, trucks){ if (err) throw err console.log(trucks) }) res.send("ok") return null }
var nano = require('nano'); var Q = require('q'); var exp = { setup : setup, nano : nano } function setup(config){ var d = Q.defer(); nano = nano(config.couchdbUrl); function fin(){ design(config) .then(function (cfg) { var theDb = nano.db.use('liblib') var dbq = { view : function(view, params){ var d = Q.defer(); var design; if(/\//.test(view)){ design = view.split('/')[0]; view = view.split('/')[1]; } else { design = designDocName; } theDb.view(design, view, params, function(err, data){ if(err){ d.reject(err); } else { d.resolve(data); } }); return d.promise; }, fetch : Q.nbind(theDb.fetch, theDb), insert : Q.nbind(theDb.insert, theDb), list : Q.nbind(theDb.list, theDb), get : Q.nbind(theDb.get, theDb), destroy : Q.nbind(theDb.destroy, theDb) } var ret = { config : cfg, q : dbq } d.resolve(ret) }) } nano.db.get('liblib', function(err, body){ if(err){ nano.db.create('liblib', function(err, body){ if(err){ d.reject(new Error("couchDB problem: " + err)); } else { fin(); } }); } else { fin(); } }); return d.promise; } function design(config){ var d = Q.defer(); nano.db.use(config.dbName).insert({ views : { all : { map : function(doc){ emit(doc.id); } } }, lists : { ul : function (head, req) { provides('html', function(){ html = "<html><body><ul>\n"; while (row = getRow()) { html += "<li>" + row.key + ":" + row.value + "</li>\n"; } html += "</ul></body></head>"; return html; }); } } }, '_design/liblib', function (err, res) { d.resolve(config); }); return d.promise; } module.exports = exp
//vendors let modules = []; if(process.env.npm_lifecycle_event === 'server') { require('bootstrap-sass/eyeglass-exports'); require('./styles/bootstrap.scss'); require('angular'); require('angular-vs-repeat/src/angular-vs-repeat.min.js'); modules.push(require('angular-animate')); modules.push('vs-repeat'); var _ = require('lodash'); var moment = require('moment/moment.js'); } if(process.env.npm_lifecycle_event === 'server' || process.env.npm_lifecycle_event === 'build') { //eonasdan-bootstrap-datetimepicker require('eonasdan-bootstrap-datetimepicker/build/css/bootstrap-datetimepicker.min.css'); require('eonasdan-bootstrap-datetimepicker/src/js/bootstrap-datetimepicker.js'); require('./styles/calendar.scss'); require('./styles/datetimepicker.scss'); } //controllers import CalendarCtrl from './controllers/calendar-ctrl.js'; import TimepickerCtrl from './controllers/timepicker-ctrl.js'; import CheckDatesCtrl from './controllers/check-dates-ctrl.js'; import CalendarTestCtrl from './controllers/calendar-test-ctrl.js'; import DateTimePickerCtrl from './controllers/date-time-picker-ctrl.js'; //services import CalendarService from './services/calendar.service.js'; //directives import availabilityCalendar from './directives/availablity-calendar.js'; import calendarInfiniteScroll from './directives/calendar-infinite-scroll.js'; import cellTimepicker from './directives/cell-timepicker.js'; import mouseOver from './directives/mouse-over.js'; import showPicker from './directives/show-picker.js'; import cellDatepicker from './directives/cell-datepicker.js'; import checkerDates from './directives/check-dates.js'; import dateTimePicker from './directives/datetimepicker.js'; const MODULE_NAME = 'availabilityCalendar'; angular .module(MODULE_NAME, modules) //services .service('CalendarService', CalendarService) //controllers .controller('CalendarCtrl', CalendarCtrl) .controller('TimepickerCtrl', TimepickerCtrl) .controller('CheckDatesCtrl', CheckDatesCtrl) .controller('CalendarTestCtrl', CalendarTestCtrl) .controller('DateTimePickerCtrl', DateTimePickerCtrl) //directives .directive('availabilityCalendar', availabilityCalendar) .directive('calendarInfiniteScroll', calendarInfiniteScroll) .directive('cellTimepicker', cellTimepicker) .directive('mouseOver', mouseOver) .directive('showPicker', showPicker) .directive('cellDatepicker', cellDatepicker) .directive('checkerDates', checkerDates) .directive('dateTimePicker', dateTimePicker) ; export default MODULE_NAME;