text
stringlengths
2
6.14k
const addMention = (editorState, data) => { console.log('addMention ...') } const findMentionEntities = (contentBlock, callback, contentState) => { const text = contentBlock.getText(); const MENTION_REGEX = /[@][\w]+/g; let match, start; // eslint-disable-next-line while ((match = MENTION_REGEX.exec(text)) !== null) { start = match.index; callback(start, start + match[0].length); } /* contentBlock.findEntityRanges( (character) => { const entityKey = character.getEntity(); return ( entityKey !== null && contentState.getEntity(entityKey).getType() === 'mention' ); }, callback ); */ } export { findMentionEntities, addMention }
'use strict'; var matrix = require( 'dstructs-matrix' ), erf = require( './../lib' ); var data, mat, out, tmp, i; // ---- // Plain arrays... data = new Array( 10 ); for ( i = 0; i < data.length; i++ ) { data[ i ] = Math.random()*20 - 10; } out = erf( data ); console.log( 'Arrays: %s\n', out ); // ---- // Object arrays (accessors)... function getValue( d ) { return d.x; } for ( i = 0; i < data.length; i++ ) { data[ i ] = { 'x': data[ i ] }; } out = erf( data, { 'accessor': getValue }); console.log( 'Accessors: %s\n', out ); // ---- // Deep set arrays... for ( i = 0; i < data.length; i++ ) { data[ i ] = { 'x': [ i, data[ i ].x ] }; } out = erf( data, { 'path': 'x/1', 'sep': '/' }); console.log( 'Deepset:' ); console.dir( out ); console.log( '\n' ); // ---- // Typed arrays... data = new Int32Array( 10 ); for ( i = 0; i < data.length; i++ ) { data[ i ] = Math.random() * 100; } tmp = erf( data ); out = ''; for ( i = 0; i < data.length; i++ ) { out += tmp[ i ]; if ( i < data.length-1 ) { out += ','; } } console.log( 'Typed arrays: %s\n', out ); // ---- // Matrices... mat = matrix( data, [5,2], 'int32' ); out = erf( mat ); console.log( 'Matrix: %s\n', out.toString() ); // ---- // Matrices (custom output data type)... out = erf( mat, { 'dtype': 'uint8' }); console.log( 'Matrix (%s): %s\n', out.dtype, out.toString() );
define([ 'kb_lib/html'], function ( html ) { 'use strict'; const t = html.tag, div = t('div'); class Widget { constructor({ runtime, node }) { if (!runtime) { throw new Error('A widget requires the "runtime" argument'); } this.runtime = runtime; // TODO: make this required... // if (!node) { // throw new Error('A widget requires the "node" argument'); // } this.mount = null; this.container = null; if (node) { this.createContainer(node); } } createContainer(node) { if (this.container) { throw new Error('Container already created already set for this widget'); } this.mount = node; this.container = document.createElement('div'); this.container.setAttribute('data-widget-type', 'plain'); this.mount.appendChild(this.container); } wrapPanel(content) { return div({ class: 'container-fluid' }, [div({ class: 'row' }, [div({ class: 'col-md-12' }, [content])])]); } // API attach(node) { this.createContainer(node); } setHTML(html) { this.container.innerHTML = html; } detach() { if (this.container) { this.container.innerHTML = ''; if (this.mount) { this.mount.removeChild(this.container); } this.container = null; } } } return Widget; });
"use strict" const process = require(`process`) const fs = require(`fs`) const createVerge1VspConverter = require(`../converter/createVerge1VspConverter`) const asset = require(`../asset`) const vspFilename = process.argv[2] const vsp = asset.fromDisk(vspFilename, asset.v1vsp) const converter = createVerge1VspConverter(vsp) const png = converter.convertToPng() const targetFilename = vspFilename + `.png` png.pack().pipe(fs.createWriteStream(targetFilename)) console.log(`converted`, vspFilename, `to`, targetFilename)
var CollapsableMixin = require('./transpiled/CollapsableMixin')['default']; module.exports = CollapsableMixin
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; import { Injectable, Optional } from "@angular/core"; import { Level } from "./level"; export class Options { } const CONSOLE_DEBUG_METHOD = console["debug"] ? "debug" : "log"; const DEFAULT_OPTIONS = { level: Level.WARN, global: true, globalAs: "logger", store: false, storeAs: "angular2.logger.level" }; let Logger = class Logger { constructor(options) { this.Level = Level; this._loadLevel = () => Number(localStorage.getItem(this._storeAs)); this.global = () => window[this._globalAs] = this; this.isErrorEnabled = () => this.level >= Level.ERROR; this.isWarnEnabled = () => this.level >= Level.WARN; this.isInfoEnabled = () => this.level >= Level.INFO; this.isDebugEnabled = () => this.level >= Level.DEBUG; this.isLogEnabled = () => this.level >= Level.LOG; let { level, global, globalAs, store, storeAs } = Object.assign({}, DEFAULT_OPTIONS, options); this._level = level; this._globalAs = globalAs; this._storeAs = storeAs; global && this.global(); if (store || this._loadLevel()) this.store(); } _storeLevel(level) { localStorage[this._storeAs] = level; } error(message, ...optionalParams) { this.isErrorEnabled() && console.error.apply(console, arguments); } warn(message, ...optionalParams) { this.isWarnEnabled() && console.warn.apply(console, arguments); } info(message, ...optionalParams) { this.isInfoEnabled() && console.info.apply(console, arguments); } debug(message, ...optionalParams) { this.isDebugEnabled() && console[CONSOLE_DEBUG_METHOD].apply(console, arguments); } log(message, ...optionalParams) { this.isLogEnabled() && console.log.apply(console, arguments); } store() { this._store = true; let storedLevel = this._loadLevel(); if (storedLevel) { this._level = storedLevel; } else { this._storeLevel(this.level); } return this; } unstore() { this._store = false; localStorage.removeItem(this._storeAs); return this; } get level() { return this._level; } set level(level) { this._store && this._storeLevel(level); this._level = level; } }; Logger = __decorate([ Injectable(), __param(0, Optional()), __metadata("design:paramtypes", [Options]) ], Logger); export { Logger }; //# sourceMappingURL=logger.js.map
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var saleSchema = new mongoose.Schema({ offerId: { type: Schema.ObjectId, ref: 'Offer', required: true }, sellerId: { type: Schema.ObjectId, ref: 'User', required: true }, buyerId: { type: Schema.ObjectId, ref: 'User', required: true }, saleDate: { type: Date, required: true } }); var SaleData = mongoose.model('Sale', saleSchema); module.exports = SaleData;
// For development purposes module.exports = { apps: [ { name: "insta-slackbot", script: "./bin/www", watch: true, ignore_watch: [".git/"] } ] }
var bull, cow, count, win, chance, placeno; var word; var used = new Array(); function guess(txt) { var result = document.getElementById("indicate" + (count-1)); var gword = txt.value.toLowerCase(); bull = 0; cow = 0; var i,j,k; var next = count + 1; var appendText = '<tr id="row' + (count+1) + '"><td> <input id="txtGuess' + (count+1) + '" type="text" maxlength="5" placeholder="Chance ' + placeno + '" onblur="guess(this);" onkeypress="return runScript(event,this)" disabled/> </td><td id="indicate' + (count+1) + '"> </td></tr>' if(gword.length == 5) { if(spellcheck(gword)) { displayContent(result.id,"Enter a proper word",0,"shake"); txt.focus(); } else if ((used.indexOf(gword))>-1){ displayContent(result.id,"This word is already used!",0,"shake"); txt.focus(); } else { //------------------------ CORRECT GUESS --------------------------- if(gword == word) { win = 1; displayWin(result,txt,chance) } //----------------------------------------------------------------- else { if(document.getElementById("txtGuess"+count)!=null) { document.getElementById("txtGuess"+count).disabled = false; document.getElementById("txtGuess"+count).focus(); } count++; var val=bullcow(gword,word); bull = val[0]; cow = val[1]; //------------------ ENABLING NEXT CHANCE ------------------------- if(next<chance) { displayContent("gameHeart",appendText,1); effect("row"+(count),"fadeInDown"); placeno++; } used.push(gword); //----------------------------------------------------------------- //---------------------- DISPLAY RESULT --------------------------- txt.disabled = true; var inner = bull + " Bull, " + cow + " Cow"; displayContent(result.id,inner,0,"bounceInLeft"); displayContent("spanChance",(chance-(count-1)),0,"fadeIn"); //----------------------------------------------------------------- //---------------------- COLORING CODES --------------------------- colorLetters(gword,bull,cow); //----------------------------------------------------------------- //------------------- FINAL WRONG GUESS RESULT -------------------- if(((count)==(chance+1)) && (gword.length==5)) { lastchance(); } //----------------------------------------------------------------- } } } else if((txt.value.length == 0) && (result!=null) && (win==0)) { displayContent(result.id,"Enter a 5 letter word",0,"shake"); txt.focus(); } else { txt.focus(); if((document.getElementById("txtGuess" + (next-1))!=null) && (win==0)) { displayContent(result.id,"Enter a 5 letter word",0,"shake"); } } } function setmoreChance() { chance = chance+6; $("#divFail").css("display","none"); var appendText = '<tr><td> <input id="txtGuess' + (count) + '" type="text" maxlength="5" placeholder="Chance ' + placeno + '" onblur="guess(this);" onkeypress="return runScript(event,this)"/> </td><td id="indicate' + (count) + '"> </td></tr>'; appendText += '<tr><td> <input id="txtGuess' + (count+1) + '" type="text" maxlength="5" placeholder="Chance ' + (placeno+1) + '" onblur="guess(this);" onkeypress="return runScript(event,this)" disabled/> </td><td id="indicate' + (count+1) + '"> </td></tr>'; displayContent("gameHeart",appendText,1); $("#txtGuess" + count).trigger("focus"); count++; placeno+=2; runTimer(); runAddTime(0); displayContent("spanChance",(chance-(count-1)),0,"fadeIn"); } function setinitialValues(newWord) { count = 1; chance = 10; win = 0; word = newWord; placeno = 3; used.length = 0; } function getwin() { return win; }
var negate = require('amp-negate'); negate(function() { return true; }); //=> false negate(function() { return false; }); //=> true
import React, { useState } from 'react' import Input from '@mui/material/Input' import { useTheme } from '@mui/material/styles' import Fab from '@mui/material/Fab' import Mic from '@mui/icons-material/Mic' import MyLocation from '@mui/icons-material/MyLocation' import CameraAlt from '@mui/icons-material/CameraAlt' import Send from '@mui/icons-material/Send' import { useIntl } from 'react-intl' import IconButton from '@mui/material/IconButton' import { useAuth } from 'base-shell/lib/providers/Auth' import { getLocation } from '../../utils/location' import { CircularProgress } from '@mui/material' import { getDatabase, ref, set, push, serverTimestamp } from 'firebase/database' import { getStorage, ref as storageRef, uploadString, getDownloadURL, } from 'firebase/storage' import { getApp } from 'firebase/app' export default function ({ path }) { const theme = useTheme() const intl = useIntl() const { auth } = useAuth() const [value, setValue] = useState('') const [isUploading, setUploading] = useState(false) const db = getDatabase() const uploadSelectedFile = (file) => { if (file === null) { return } if ((file.size / 1024 / 1024).toFixed(4) > 20) { //file larger than 10mb alert(intl.formatMessage({ id: 'max_file_size' })) return } setUploading(true) let reader = new FileReader() const r = push(ref(db, '/user_chat_messages/')) reader.onload = async (fileData) => { const snap = await uploadString( storageRef( getStorage(getApp()), `/user_chats/${auth.uid}/${r.key}.jpg` ), fileData.target.result, 'data_url' ) const downloadURL = await getDownloadURL(snap.ref) sendMessage({ type: 'image', message: '', image: downloadURL, key: r.key, }) setUploading(false) } reader.readAsDataURL(file) } const sendMessage = async (props) => { let newMessage = { created: serverTimestamp(), authorName: auth.displayName, authorUid: auth.uid, authorPhotoUrl: auth.photoURL, languageCode: intl.formatMessage({ id: 'current_locale', defaultMessage: 'en-US', }), ...props, } await set(push(ref(db, `${path}`)), newMessage) setValue('') } return ( <div style={{ display: 'flex', padding: 4, paddingBottom: 8, alignItems: 'center', }} > <div style={{ margin: 0, marginLeft: 8, marginRight: 8, paddingRight: 8, backgroundColor: theme.palette.grey[300], borderRadius: 22, height: '100%', flex: 1, display: 'flex', }} > <Input style={{ height: 50, left: 15, color: 'black', }} multiline rowsMax="2" disableUnderline={true} fullWidth={true} autoFocus value={value} autoComplete="off" placeholder={intl.formatMessage({ id: 'write_message_hint', defaultMessage: 'Write message', })} onChange={(e) => setValue(e.target.value)} onKeyDown={(e) => { if (e.keyCode === 13 && value.trim() !== '') { e.preventDefault() sendMessage({ type: 'text', message: value }) } }} type="Text" /> <input style={{ display: 'none' }} accept="image/*" id="icon-button-file" type="file" onChange={(e) => { uploadSelectedFile(e.target.files[0]) }} /> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', }} > <div> <label htmlFor="icon-button-file"> <IconButton disabled={isUploading} color="primary" aria-label="upload picture" component="span" size="small" edge={false} > {isUploading && ( <CircularProgress color="secondary" style={{ width: 20, height: 20, }} /> )} {!isUploading && <CameraAlt />} </IconButton> </label> </div> </div> <IconButton color="primary" size="small" onClick={async () => { try { const { coords } = await getLocation() const lat = coords?.latitude const long = coords?.longitude sendMessage({ type: 'location', message: '', location: `https://www.google.com/maps/place/${lat}+${long}/@${lat},${long}`, location_lat: lat, location_lng: long, }) } catch (error) {} }} > <MyLocation /> </IconButton> </div> <Fab onClick={ value !== '' ? () => sendMessage({ type: 'text', message: value }) : undefined } color="secondary" size="medium" > {value === '' && <Mic />} {value !== '' && <Send />} </Fab> </div> ) }
import React from 'react'; import {isBootstrapComplete, getBootstrapStatusMsg} from './state'; import {featureRoute, PRIORITY} from 'feature-router'; import SplashScreen from '../../../util/comp/SplashScreen'; // *** // *** The routes for this feature. // *** export default featureRoute({ priority: PRIORITY.HIGH+10, content({fassets, appState}) { // promote a simple SplashScreen (with status) until the bootstrap process is complete // NOTE: Errors from bootstrap hooks are promoted through independent user notifications (toasts) if (!isBootstrapComplete(appState)) { // console.log(`xx bootstrap feature router ... NOT COMPLETE: route -> SplashScreen with msg: ${getBootstrapStatusMsg(appState)}`); return <SplashScreen msg={getBootstrapStatusMsg(appState)}/>; } return null; }, });
/*jslint node: true */ /*jslint es6 */ 'use strict'; const Transform = require('stream').Transform; const CRC8 = require('./CRC8'); const BUFFER_LENGTH = 6 + 65536; class esp3parser extends Transform { constructor() { super(); this.position = 0; this.buffer = Buffer.alloc(BUFFER_LENGTH); // to be enhanced to have a variable length buffer this.payloadLength = 0; // length of payload } _transform(chunk, _, cb) { let cursor = 0; while (cursor < chunk.length) { if ( (0x55 === chunk[cursor]) || (this.position > 0)) { this.buffer[this.position] = chunk[cursor]; if (this.position === 5) { if (CRC8.getCRC8(this.buffer,1, 4) !== this.buffer[this.position]) { this.position = 0; // wrong CRC } else { this.position++; this.payloadLength = (this.buffer[1] * 256) + this.buffer[2] + this.buffer[3]; } } else if (this.position === ( 5 + this.payloadLength + 1)) { // end of message + CRC if (CRC8.getCRC8(this.buffer,6, this.payloadLength) === this.buffer[this.position]) { // CRC this.push(Buffer.from(this.buffer.slice(0, this.position))); } this.position = 0; this.payloadLength = 0; } else { this.position++; } } cursor++; } cb(); } } module.exports = esp3parser;
Package.describe({ name: 'std:accounts-basic', version: '1.1.12', summary: 'Basic – Accounts UI for React in Meteor 1.3', git: 'https://github.com/studiointeract/accounts-basic', documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.3'); api.use('ecmascript'); api.use('underscore'); api.use('fourseven:scss@3.4.1'); api.use('std:accounts-ui@1.1.20'); api.addFiles([ 'styles.scss' ], 'client'); api.mainModule('main.jsx'); });
var _ = require('lodash'); var crel = require('crel'); var fastClickAttach = require('fastclick'); var colorSets = require('./color-sets'); var util = require('./util'); fastClickAttach(document.body); document.ontouchmove = function (e) { e.preventDefault(); }; if (util.isStandalone()) { document.body.className += ' standalone'; } var app = {}; app.el = crel('section', {id: 'app', class: 'app'}); document.body.appendChild(app.el); // Add nav & toggle var nav = require('./nav')(document); var allColorsEnabled = false; var numAttempted = 0; var numCorrect = 0; var currentColorSet = 'tech-brands'; var requestedSet = location.search && location.search.substr(1).split('=')[0]; if (colorSets['' + requestedSet]) { currentColorSet = requestedSet; } var choicesFilter = function (set) { return function (name) { return allColorsEnabled ? true : util.isBlue(set[name]); }; }; function getChoices(set) { var correctNameCandidtes, correctName, incorrectNameCandidates, incorrectName; correctNameCandidtes = _.filter(_.keys(set), choicesFilter(set)); if (correctNameCandidtes.length < 2) { throw new Error('Color set is too small to play with'); } correctName = util.pick(correctNameCandidtes); incorrectNameCandidates = _.filter(correctNameCandidtes, function (name) { return name !== correctName && set[name] !== set[correctName] && util.hexesInSameColorGroup(set[name], set[correctName]); }); if (incorrectNameCandidates.length < 1) { throw new Error('Color group is too small to play with: ' + JSON.stringify({ correctName: correctName, incorrectNameCandidates: incorrectNameCandidates })); } incorrectName = util.pick(incorrectNameCandidates); return { correct: { name: correctName, color: set[correctName] }, incorrect: { name: incorrectName, color: set[incorrectName] } }; } function nextRound() { var coin = Math.random() > 0.5; var choices = getChoices(colorSets[currentColorSet]); var choiceA = coin ? choices.correct : choices.incorrect; var choiceB = coin ? choices.incorrect : choices.correct; var choiceAEl = crel('a', choiceA.name); var choiceBEl = crel('a', choiceB.name); var orEl = crel('p', 'or'); var enableAllColorsEl = crel('a', {'class': 'enable-all-colors'}, 'Want more than blues?'); var onChoose = function () { var isCorrect = (this.textContent || this.innerText) === choices.correct.name; if (isCorrect) { numCorrect++; } numAttempted++; app.el.innerHTML = ""; var result = isCorrect ? 'Correct!' : 'Nope, it\'s ' + choices.correct.name; var resultEl = crel('a', {'class': 'result'}, result); app.el.appendChild(resultEl); var numEl = crel('p', '' + numCorrect + ' / ' + numAttempted + ' correct'); app.el.appendChild(numEl); setTimeout(nextRound, 2000); }; var onEnableAllColors = function () { allColorsEnabled = true; app.el.innerHTML = ""; var resultEl = crel('a', {'class': 'result'}, 'You asked for it...'); app.el.appendChild(resultEl); setTimeout(nextRound, 2000); }; choiceAEl.onclick = onChoose; choiceBEl.onclick = onChoose; enableAllColorsEl.onclick = onEnableAllColors; app.el.innerHTML = ""; document.body.style.backgroundColor = '#' + choices.correct.color; setTimeout(function () { app.el.appendChild(choiceAEl); app.el.appendChild(orEl); app.el.appendChild(choiceBEl); if (!allColorsEnabled && numAttempted > 4) { app.el.appendChild(enableAllColorsEl); } }, 250); } nextRound();
import { Dimensions, Platform } from 'react-native'; const { width, height } = Dimensions.get('window'); // Used via Metrics.baseMargin const metrics = { marginHorizontal: 10, marginVertical: 10, section: 25, baseMargin: 10, doubleBaseMargin: 20, smallMargin: 5, doubleSection: 50, horizontalLineHeight: 1, searchBarHeight: 30, screenWidth: width < height ? width : height, screenHeight: width < height ? height : width, navBarHeight: (Platform.OS === 'ios') ? 64 : 54, buttonRadius: 4, icons: { tiny: 15, small: 20, medium: 30, large: 45, xl: 50, }, images: { small: 20, medium: 40, large: 60, logo: 200, }, }; export default metrics;
jQuery(function($) { /* * Liste du nombre de films par page */ $('#movies_per_page_form select').on('change',function(){ $('#movies_per_page_form').submit(); return false; }); $('.movie_delete').confirmDelete('Supprimer le film sélectionné ?'); });
/* * 参考: http://2inc.org/blog/2015/05/13/4818/ */ /* * modules load */ var gulp = require('gulp'); var browserSync = require('browser-sync'); var reload = browserSync.reload; var watchify = require('watchify'); /* * paths */ var jsSrcPath = './src/'; var jsSrcFile = 'app.js'; var jsDestPath = './dist/'; /* * tasks */ /** * browserify */ gulp.task( 'browserify', function() { return jscompile( false ); }); /** * watchify */ gulp.task( 'watchify', function() { return jscompile( true ); }); /** * jscompile function */ function jscompile( is_watch ) { var bundler; var props = { entries: jsSrcPath + jsSrcFile, debug: true, cache: {}, packageCache: {}, fullPaths: true }; if ( is_watch ) { bundler = watchify( browserify( props ) ); } else { bundler = browserify( props ); } function rebundle() { console.log("rebundle"); return bundler .pipe( source( jsSrcFile ) ) .pipe(gulp.dest( jsDestPath ) ) .on('end', function() { reload(); }); } bundler.on( 'update', function() { rebundle(); } ); bundler.on( 'log', function( message ) { console.log( message ); } ); return rebundle(); } gulp.task('srccopy', function() { return gulp .pipe( source( jsSrcFile ) ) .pipe(gulp.dest( jsDestPath ) ) .on('end', function() { reload(); }); }); /* * 実行時に必要なファイルをコピー */ gulp.task('plugins', function() { gulp.src('./node_modules/bootstrap/dist/css/bootstrap*.min.css') .pipe(gulp.dest('dist/css')); gulp.src('./node_modules/bootstrap/dist/js/bootstrap.min.js') .pipe(gulp.dest('dist/plugins')); gulp.src('./node_modules/bootstrap/dist/fonts/*') .pipe(gulp.dest('dist/fonts')); gulp.src('./node_modules/jquery/dist/jquery.min.js') .pipe(gulp.dest('dist/plugins')); gulp.src('./node_modules/encoding-japanese/encoding.min.js') .pipe(gulp.dest('dist/plugins')); }); // 監視タスクを作成 gulp.task('watch', ['plugins'], function() { browserSync({ notify: false, logPrefix: 'BS', server: ['./dist/'] }); gulp.watch(jsDestPath+'index.html', reload); gulp.watch(jsSrcPath+jsSrcFile, ['srccopy']); }); gulp.task('buildBundle', ['plugins','browserify'], function(){ }); gulp.task('default', ['buildBundle']);
'use strict'; /* Services */ // Demonstrate how to register services // In this case it is a simple value service. angular.module('WP.services', ['chieffancypants.loadingBar']).value('version', '0.1'); WP.factory('UserService', function($resource) { return $resource(WPUtil.ctx('/data/rest/user/:action'), {}, { authenticate: { method: 'POST', params: { 'action': 'authenticate' }, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }, }); }); WP.factory('Paper', ['$resource', function($resource) { return $resource(WPUtil.ctx('/data/rest/papers/:id'), {}, { 'paged': { method: 'GET', url: WPUtil.ctx('/data/rest/papers/paged') } }); }]); WP.factory('Author', ['$resource', function($resource) { return $resource(WPUtil.ctx('/data/rest/authors/:id'), {}); }]); WP.factory('Conference', ['$resource', function($resource) { return $resource(WPUtil.ctx('/data/rest/conferences/:id'), {}); }]); WP.factory('PaperType', ['$resource', function($resource) { return $resource(WPUtil.ctx('/data/rest/paperTypes/:id'), {}); }]); WP.factory('PaperAuthor', ['$resource', function($resource) { return $resource(WPUtil.ctx('/data/rest/paperAuthors/:id'), {}, { 'getByPaperId': { method: 'GET', isArray: true, url: WPUtil.ctx('/data/rest/paperAuthors/by_paper/:id') } }); }]); WP.factory('ConferenceMeta', ['$resource', function($resource) { return $resource(WPUtil.ctx('/data/rest/conference_meta/:id'), {}, { 'getByConferenceId': { method: 'GET', url: WPUtil.ctx('/data/rest/conference_meta/by_conference/:id') } }); }]); WP.factory('Attachment', ['$resource', function($resource) { return $resource(WPUtil.ctx('/object/:id'), {}, { 'getAttachmentsByObjectId': { method: 'GET', isArray: true, url: WPUtil.ctx("/data/rest/attachments/:bean/:id") }, 'deleteAttachment': { method: 'DELETE', url: WPUtil.ctx("/data/rest/attachments/:id") } }); }]);
'use strict' const { allTags, regexWindowsPaths, stringPosixPaths, nonPathRegex } = require('../util/type-edge-cases.js') const { evalSafeString, evalSafeRegexDef } = require('../util/ensure-eval-safe.js') const doFunc = require('./μИاκهよΞ/unicode-in-path.js') const debounce = require('debounce') function appOuterFunc () { const regexStringTarget = `${allTags} ${regexWindowsPaths} ${stringPosixPaths}` const evalCode = ` function evalInnerFunc () { const regex = new RegExp(${evalSafeRegexDef(`"${regexWindowsPaths}"`)}) return ${evalSafeString(`"${regexStringTarget}"`)}.repeat(100).replace(regex, ${evalSafeString(`"${stringPosixPaths}"`)}) } evalInnerFunc() ` // Long enough for consistent output, not so long test is slow or may time out const reps = 120 const obj = { // Method names defined from a variable show up as (anonymous) // but crazy method names written in as strings still show up in output // 'method: \\μИاκهよΞ\\ [CODE:RegExp] / native / [SHARED_LIB]': function () { 'method: [CODE:RegExp] / native / [SHARED_LIB]': function () { global.eval(evalCode) // eslint-disable-line regexStringTarget.repeat(reps).replace(new RegExp(nonPathRegex), stringPosixPaths) } } const doEval = function () { // obj['method: \\μИاκهよΞ\\ [CODE:RegExp] / native / [SHARED_LIB]']() obj['method: [CODE:RegExp] / native / [SHARED_LIB]']() } for (let i = 0; i < reps; i++) { doFunc(doEval) } } // This debounce wrapper is purely to get a simple stable 'deps' frame in the output const debounceWrapper = debounce(appOuterFunc, 0, true) debounceWrapper()
var inputs = { template: ` <div> <input type="text" placeholder="msg" v-model="msg" @keyup.enter="addMessage"> <button v-on:click="death">End session</button> </div> `, data: function() { return { msg: '' } }, methods: { addMessage: function(e) { this.$emit('addMessage', e.target.value); this.msg = ''; }, death: function(e) { this.$emit('death'); } } }; var users = { props: ['userlist'], template: ` <div> <p class="text-bold">users {{userlist.length}}</p> <ul> <li v-for="user in userlist">{{user}}</li> </ul> </div> ` }; var msgs = { props: ['messages'], template: ` <div> <p class="text-bold">msgs</p> <ul> <li v-for="msg in messages">{{msg.user}}: {{msg.msg}}</li> </ul> </div> ` }; var app = new Vue({ el: '#app', template: `<div> <h1>/chat</h1> <p class="robotext">status: {{ status }}</p> <p class="robotext">name: {{ username }}</p> <inputs @addMessage="addMessage" @death="death"></inputs> <users :userlist="userlist"></users> <msgs :messages="messages"></msgs> </div>`, components: { inputs: inputs, users: users, msgs: msgs }, data: function(){ return { status: '', username: '', userlist: [], messages: [] } }, methods: { addMessage: function(msg) { this.ws.emit('addMessage', {msg: msg}); }, death: function() { this.ws.die(); } }, created: function() { this.status = 'connecting'; this.ws = new wsClient('ws://localhost:3000'); this.ws .on('ready', () => app.status = 'connected') // built-in .on('reconnecting', () => app.status = 'reconnecting') // built-in .on('reconnectionFail', () => app.status = 'failed') // built-in .on('initialData', onInitialData) // custom .on('messageAdded', onMessageAdded) // custom .on('userlist', onUserList) // built-in event from server } }); function onInitialData(data) { app.username = data.username; } function onMessageAdded(data) { app.messages.push(data); } function onUserList(data) { app.userlist = data.userlist; }
'use strict'; import EventEmitter from 'events'; import config from 'config'; import request from 'request'; import logger from './logger'; const Camera = function () { EventEmitter.call(this); const { url, time } = config.get('camera'); let running = false; let timeout = null; const requestImage = (options) => new Promise((resolve, reject) => { request(options) .on('response', (response) => { const length = +response.headers['content-length']; const image = new Buffer(length); let size = 0; response.on('data', (data) => { image.write(data.toString('binary'), size, data.length, 'binary'); size += data.length; }); response.on('end', () => resolve(image)); }) .on('error', error => reject(error)); }); const worker = () => { const options = { method: 'get', encoding: null, url }; requestImage(options) .then(image => { if (running) { logger.info('received image from camera'); this.emit('image', image); } }) .catch(error => logger.error(error)) .then(() => timeout = setTimeout(worker, time)); }; this.start = () => { if (!running) { setTimeout(worker); } running = true; return this; }; this.stop = () => { clearTimeout(timeout); running = false; return this; }; }; Camera.prototype = Object.create(EventEmitter.prototype); Camera.prototype.constructor = Camera; export default Camera;
//var WebSocketEmitter = require('./lib/web-socket-emitter'); var http = require('http'); var WebSocket = require('ws'); var Server = require('./lib/server'); var chunkStore = require('./lib/chunk-stores/file'); var chunkGenerator = require('./lib/generators/server-terraced'); var stats = require('./lib/voxel-stats'); var config = require('../config'); var debug = false; // This only gets filled by require if config.mysql isn't empty var mysqlPool; var clientSettings = { initialPosition: config.initialPosition }; /* var chunkStore = new chunkStore( new chunkGenerator(config.chunkSize), config.chunkFolder ); */ // Use mysql chunk storage if the mysql module is installed var useMysql = false; try { require.resolve('mysql'); useMysql = true; } catch(e){} if (useMysql) { if (!('mysql' in config)) { throw new Error('Attempted to use mysql for chunk storage, but no mysql params found in config'); } mysqlPool = require('mysql').createPool(config.mysql); var chunkStore = new chunkStore( new chunkGenerator(config.chunkSize), config.mysql ); } else { var chunkStore = new chunkStore( new chunkGenerator(config.chunkSize), config.chunkFolder ); } var serverSettings = { // test with memory chunk store for now worldRadius: config.worldRadius || 10, maxPlayers: config.maxPlayers || 10 }; function clientUsernames() { var usernames = []; for (var clientId in server.clients) { var client = server.clients[clientId]; usernames.push( client.username ); } console.log('Usernames:', usernames.join(',')); } // SERVER SETUP // Create WebSocket and HTTP Servers separately so you can customize... // maybe you want WebSocket on a different port? // WEBSOCKET SETUP var connectionLimit = config.maxPlayers; var connections = 0; var httpServer = new http.Server(); httpServer.listen(config.websocketBindPort, config.websocketBindAddress); var wsServer = new WebSocket.Server({ server: httpServer }); wsServer.on('error', function(error) { console.log(error); }); wsServer.on('connection', function(connection) { stats.count('connections.incoming'); // Have we reached our player max? var ts = new Date(); console.log(ts.toUTCString(), 'Incoming client connection'); connections++; console.log('Connections: ' + connections); connection.on('close', function() { connections--; var ts = new Date(); console.log(ts.toUTCString(), 'Connections: ' + connections); }); if (connections > connectionLimit) { console.log('Denying connection, at our limit'); connection.close(); return; } //server.connectClient(connection); }); var server = new Server(config, clientSettings, chunkStore, wsServer, httpServer); /* server.on('client.join', function(client) { }); server.on('client.leave', function(client) { }); server.on('client.state', function(state) { }); */ server.on('chat', function(message) { stats.count('chat.messages.sent'); if (mysqlPool) { var row = { created_ms: Date.now(), username: message.user, message: message.text }; mysqlPool.query('insert into chat SET ?', row); } }); server.on('error', function(error) { console.log(error); });
/* Il existe maintenant 2 méthodes permettant d'accéder aux éléments de manière plus simple. */ var bodyElement = document.querySelector('body'); console.log(bodyElement); /* La méthode `querySelectorAll` retourne une liste. */ var bodyElement = document.querySelectorAll('body'); console.log(bodyElement); /* Il est possible de passer des `id` ou `class` à ces méthodes. */ var bodyElement = document.querySelector('#main'); console.log(bodyElement); var bodyElement = document.querySelectorAll('.site'); console.log(bodyElement); /* Il est possible d'utiliser les sélecteurs CSS classiques (comme jQuery). */ var pElements = document.querySelectorAll('#main p'); console.log(pElements); /* Il est possible d'utiliser des sélecteurs plus complexes comme `nth-child`. */ document.querySelector('p:nth-child(1)'); /* Essayez d'accéder au paragraphe en utilisant sa `class`. Son `id`. Pourquoi vaut-il mieux utiliser `getElementById` ? */
// Copyright (c) 2015 Uber Technologies, Inc. // // 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. 'use strict'; var BaseTransportAdapter = require('../../lib/transport/base-transport-adapter'); var BaseMessage = require('../../lib/message/base-message'); var Constants = require('../../lib/constants'); var ReplyMessage = require('../../lib/message/reply-message'); var Transport = require('../../lib/transport/transport'); var sinon = require('sinon'); var test = require('tape'); var util = require('util'); function TestMessage() { BaseMessage.apply(this, arguments); } TestMessage.type = 'Test'; util.inherits(TestMessage, BaseMessage); function TestReplyMessage() { ReplyMessage.apply(this, arguments); } TestReplyMessage.type = 'TestReply'; util.inherits(TestReplyMessage, ReplyMessage); test('Transport', function(suite) { var it = suite.test; it('should throw if instantiated without an adapter', function(t) { t.throws(function() { new Transport(); }); t.end(); }); it('should bind listeners on its adapter', function(t) { var adapterStub = sinon.createStubInstance(BaseTransportAdapter); new Transport({ adapter: adapterStub }); t.ok(adapterStub.on.calledWith(Constants.Event.TRANSPORT_ADAPTER_MESSAGE)); t.ok(adapterStub.on.calledWith(Constants.Event.TRANSPORT_ADAPTER_STATUS_CHANGED)); t.end(); }); }); test('Transport.prototype.sendMessage', function(suite) { var it = suite.test; it('should save the callback and call sendMessage on its adapter', function(t) { var adapterStub = sinon.createStubInstance(BaseTransportAdapter); var spy = sinon.spy(); var transport = new Transport({ adapter: adapterStub }); var index = 0; var message = new TestMessage({ index: index }); transport.sendMessage(message, spy); t.equal(transport._callbacks[index], spy); t.ok(adapterStub.sendMessage.calledWith(message)); t.end(); }); }); test('Transport.prototype._onAdapterMessage', function(suite) { var it = suite.test; it('should emit "message" when a message is received', function(t) { var adapterStub = sinon.createStubInstance(BaseTransportAdapter); var transport = new Transport({ adapter: adapterStub }); var index = 0; var message = new TestMessage({ index: index }); transport.on(Constants.Event.TRANSPORT_MESSAGE, function(msg) { t.equal(msg.index, index); t.end(); }); transport._onAdapterMessage(message); }); it('should call and remove the saved callback', function(t) { var adapterStub = sinon.createStubInstance(BaseTransportAdapter); var spy = sinon.spy(); var transport = new Transport({ adapter: adapterStub }); var index = 0; var message = new TestMessage({ index: index }); var replyMessage = new TestReplyMessage({ index: index, replyTo: index }); transport.sendMessage(message, spy); transport._onAdapterMessage(replyMessage); t.ok(spy.calledWith(replyMessage)); t.error(transport._callbacks[index]); t.end(); }); });
PDRClient.controller('AssessmentReportCtrl', [ '$scope', '$http', '$timeout', '$anchorScroll', '$location', '$stateParams', 'SessionService', 'Assessment', 'Report', 'Consensus', function($scope, $http, $timeout, $anchorScroll, $location, $stateParams, SessionService, Assessment, Report, Consensus) { $scope.currentUser = SessionService.getCurrentUser(); $scope.id = $stateParams.id; $scope.assessment = Assessment.get({id: $scope.id}); $scope.report = Report.get({assessment_id: $scope.id}); $scope.isFacilitator = function() { return $scope.assessment.owner; }; $scope.canEditPriorities = function() { return $scope.isFacilitator(); }; } ]);
'use strict' const test = require('tape') const isNumberLike = require('..') const testCases = [ // ['number', expectedResult] [0, true], ['0', true], [1.1, true], ['1.1', true], [-1.1, true], ['-1.1', true], ['1.1.1', false], [1.1e2, true], ['1.1e2', true], ['1e2e3', false], ['-', false], [null, false], ['22221.2.e.34442', false], [ '111a111', false ], [[], false], [Number.EPSILON, true], [Number.MAX_SAFE_INTEGER, true], [Number.MAX_VALUE, true], [Number.MIN_SAFE_INTEGER, true], [Number.MIN_VALUE, true], [Number.NaN, false], [Number.NEGATIVE_INFINITY, false], [Number.POSITIVE_INFINITY, false] ] test('isNumberLike', function (t) { t.plan(testCases.length) testCases.forEach(function (item) { t.equals(isNumberLike(item[0]), item[1], 'isNumberLike(' + JSON.stringify(item[0]) + ') === ' + item[1]) }) })
var TestServer = require("./test-server"); const { timeout } = require("../../extensions"); require("../test-finished"); describe("Server using database", () => { var testServer; var database; beforeEach(async () => { testServer = new TestServer(); database = testServer.database; }); it("waits for database connection before starting server", async () => { var establishConnection = null; database.connectionPromise = new Promise((resolve, reject) => { establishConnection = resolve; }) var isServerStarted = false; testServer.start().then(() => isServerStarted = true); await timeout(100); expect(isServerStarted).toBe(false); establishConnection(); await timeout(100); expect(isServerStarted).toBe(true); await testServer.stop(); }); it("aborts server start if connection to database cannot be established", async () => { var failedConnection = null; database.connectionPromise = new Promise((resolve, reject) => { failedConnection = reject; }) var threwError = false; testServer.start().catch(() => threwError = true); await timeout(20); failedConnection(); await timeout(20); expect(threwError).toBe(true); await testServer.stop(); }); it("upgrades database at start", async () => { await testServer.start(); expect(database.created).toBe(true); await testServer.stop(); }); });
const fs = require('fs'); const gulp = require('gulp'); const connect = require('gulp-connect'); const open = require('gulp-open'); const rename = require('gulp-rename'); const header = require('gulp-header'); const uglify = require('gulp-uglify'); const sourcemaps = require('gulp-sourcemaps'); const rollup = require('rollup'); const buble = require('rollup-plugin-buble'); const pkg = require('./package.json'); const paths = { root: './', build: 'build/', dist: 'dist/', demo: 'demo/', source: 'src/', }; const date = { year: new Date().getFullYear(), month: ('January February March April May June July August September October November December').split(' ')[new Date().getMonth()], day: new Date().getDate(), }; const t7 = { filename: 'template7', pkg, banner: [ '/**', ` * Template7 ${pkg.version}`, ` * ${pkg.description}`, ' * ', ` * ${pkg.homepage}`, ' * ', ` * Copyright ${date.year}, ${pkg.author}`, ' * The iDangero.us', ' * http://www.idangero.us/', ' * ', ` * Licensed under ${pkg.license}`, ' * ', ` * Released on: ${date.month} ${date.day}, ${date.year}`, ' */', ''].join('\n'), }; // Build gulp.task('build', (cb) => { fs.copyFileSync('./src/template7.d.ts', './build/template7.d.ts'); rollup.rollup({ input: './src/template7.js', plugins: [buble()], }).then((bundle) => { // eslint-disable-line return bundle.write({ strict: true, file: './build/template7.js', format: 'umd', name: 'Template7', sourcemap: true, sourcemapFile: './build/template7.js.map', }); }).then(() => { cb(); }); }); function umd(cb) { rollup.rollup({ input: './src/template7.js', plugins: [buble()], }).then((bundle) => { // eslint-disable-line return bundle.write({ strict: true, file: './dist/template7.js', format: 'umd', name: 'Template7', sourcemap: true, sourcemapFile: './dist/template7.js.map', banner: t7.banner, }); }).then(() => { gulp.src('./dist/template7.js') .pipe(sourcemaps.init()) .pipe(uglify()) .pipe(header(t7.banner)) .pipe(rename('template7.min.js')) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./dist/')) .on('end', () => { if (cb) cb(); }); }); } function es(cb) { rollup.rollup({ input: './src/template7.js', }).then((bundle) => { // eslint-disable-line return bundle.write({ strict: true, file: './dist/template7.esm.js', format: 'es', name: 'Template7', banner: t7.banner, }); }).then(() => { cb(); }); } // Dist gulp.task('dist', (cb) => { let cbs = 0; fs.copyFileSync('./src/template7.d.ts', './dist/template7.d.ts'); umd(() => { cbs += 1; if (cbs === 2) cb(); }); es(() => { cbs += 1; if (cbs === 2) cb(); }); }); gulp.task('watch', () => { gulp.watch('./src/*.js', gulp.series(['build'])); }); gulp.task('connect', () => connect.server({ root: [paths.root], livereload: true, port: '3000', })); gulp.task('open', () => gulp.src(`${paths.demo}index.html`).pipe(open({ uri: `http://localhost:3000/${paths.demo}index.html` }))); gulp.task('server', gulp.parallel(['watch', 'connect', 'open'])); gulp.task('default', gulp.series(['server']));
import * as math from './code-listing-114'; console.log('2 pi = ' + math.sum(math.pi, math.pi));
(function(){ 'use strict'; var HEAP = new ArrayBuffer(196 + 96 + 64) , HEAP_N = new Uint8Array(HEAP, 0, 196) , HEAP_O = new Uint8Array(HEAP, 196, 96) , HEAP_KEY = new Uint8Array(HEAP, 292, 64); var sha256 = this.sha256; if (!sha256 && (typeof require !== 'undefined')) var sha256 = require('./sha256'); var hmacsha256 = function(key, inout) { var hkey = HEAP_KEY , o = HEAP_O , n = HEAP_N , iol = inout.length , i; // This test isn't necessary for scrypt // if (key.length > 64) sha256(key, 80, hkey); // Clear to zeroes for (i = 32; i < 64; i++) { hkey[i] = 0; } // Start the process i = 64; while (i--) { o[i] = 0x5c ^ hkey[i]; n[i] = 0x36 ^ hkey[i]; } // Replaces n.concat(inout) i = iol; while (i--) { n[64 + i] = inout[i]; } sha256(n, 64 + iol, hkey); // Replaces o.concat(sha256(n)) i = 32; while (i--) { o[64 + i] = hkey[i]; } sha256(o, 96, inout); }; if (typeof exports !== 'undefined') { module.exports = hmacsha256; } else { this.hmacsha256 = hmacsha256; } }).call(this);
var color = $(".selected").css("background-color"); //Variable to store canvas element var $canvas = $("canvas"); var context = $canvas[0].getContext("2d"); var lastEvent; var mouseDown = false; //When clicking on control list items $(".controls").on("click", "li", function(){ //Deselect sibling elements $(this).siblings().removeClass("selected"); //Select clicked element $(this).addClass("selected"); //Cache current color color = $(this).css("background-color"); }); //When new color is pressed $("#revealColorSelect").click(function(){ //Run changeColor method so new color span is updated changeColor(); //Show color select if hidden or hide the color select if visible $("#colorSelect").toggle() }); // Update new color span function changeColor() { var r = $("#red").val(); var g = $("#green").val(); var b = $("#blue").val(); $("#newColor").css("background-color", "rgb(" + r + "," + g + "," + b + ")"); } function clearCanvas() { context.clearRect(0, 0, context.canvas.width, context.canvas.height); } //When color sliders change fill span with color $("input[type=range]").change(changeColor); //When "Add Color" is clicked $("#addNewColor").click(function(){ //Append the color to the controls ul var $newColor = $("<li></li>"); //create list item //Alter newColor CSS to be the newColor CSS background color, sets color selected as background color of the newColor $newColor.css("background-color", $("#newColor").css("background-color")); //Append to color list $(".controls ul").append($newColor); //Select the new color $newColor.click(); }); //When Clear Button is clicked $('#clearCanvas').click(function(e){ clearCanvas(); }); //On mouse events on canvas $canvas.mousedown(function(e){ lastEvent = e; mouseDown = true; }).mousemove(function(e){ //Draw line if(mouseDown){ context.beginPath(); //start path within canvas context.moveTo(lastEvent.offsetX, lastEvent.offsetY); context.lineTo(e.offsetX, e.offsetY); context.strokeStyle = color; context.stroke(); //draws the line lastEvent = e; //update lastEvent to be new value from e } }).mouseup(function() { mouseDown = false; }).mouseleave(function() { //bind mouseleave event to mouseup so when cursor leaves canvas, user must click to return to drawing inside canvas $canvas.mouseup(); });
import runloop from 'global/runloop'; import defineProperty from 'utils/defineProperty'; import getSpliceEquivalent from 'shared/getSpliceEquivalent'; import summariseSpliceOperation from 'shared/summariseSpliceOperation'; import processWrapper from 'viewmodel/prototype/get/arrayAdaptor/processWrapper'; var patchedArrayProto = [], mutatorMethods = [ 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift' ], testObj, patchArrayMethods, unpatchArrayMethods; mutatorMethods.forEach( function ( methodName ) { var method = function () { var spliceEquivalent, spliceSummary, result, wrapper, i; // push, pop, shift and unshift can all be represented as a splice operation. // this makes life easier later spliceEquivalent = getSpliceEquivalent( this, methodName, Array.prototype.slice.call( arguments ) ); spliceSummary = summariseSpliceOperation( this, spliceEquivalent ); // apply the underlying method result = Array.prototype[ methodName ].apply( this, arguments ); // trigger changes this._ractive.setting = true; i = this._ractive.wrappers.length; while ( i-- ) { wrapper = this._ractive.wrappers[i]; runloop.start( wrapper.root ); processWrapper( wrapper, this, methodName, spliceSummary ); runloop.end(); } this._ractive.setting = false; return result; }; defineProperty( patchedArrayProto, methodName, { value: method }); }); // can we use prototype chain injection? // http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/#wrappers_prototype_chain_injection testObj = {}; if ( testObj.__proto__ ) { // yes, we can patchArrayMethods = function ( array ) { array.__proto__ = patchedArrayProto; }; unpatchArrayMethods = function ( array ) { array.__proto__ = Array.prototype; }; } else { // no, we can't patchArrayMethods = function ( array ) { var i, methodName; i = mutatorMethods.length; while ( i-- ) { methodName = mutatorMethods[i]; defineProperty( array, methodName, { value: patchedArrayProto[ methodName ], configurable: true }); } }; unpatchArrayMethods = function ( array ) { var i; i = mutatorMethods.length; while ( i-- ) { delete array[ mutatorMethods[i] ]; } }; } patchArrayMethods.unpatch = unpatchArrayMethods; export default patchArrayMethods;
import { s__ } from '~/locale'; export const SUCCESS = 'success'; export const WARNING = 'warning'; export const DANGER = 'danger'; export const INFO = 'info'; export const WARNING_MESSAGE_CLASS = 'warning_message'; export const DANGER_MESSAGE_CLASS = 'danger_message'; export const MWPS_MERGE_STRATEGY = 'merge_when_pipeline_succeeds'; export const MTWPS_MERGE_STRATEGY = 'add_to_merge_train_when_pipeline_succeeds'; export const MT_MERGE_STRATEGY = 'merge_train'; export const AUTO_MERGE_STRATEGIES = [MWPS_MERGE_STRATEGY, MTWPS_MERGE_STRATEGY, MT_MERGE_STRATEGY]; // SP - "Suggest Pipelines" export const SP_TRACK_LABEL = 'no_pipeline_noticed'; export const SP_LINK_TRACK_EVENT = 'click_link'; export const SP_SHOW_TRACK_EVENT = 'click_button'; export const SP_LINK_TRACK_VALUE = 30; export const SP_SHOW_TRACK_VALUE = 10; export const SP_HELP_CONTENT = s__( `mrWidget|Use %{linkStart}CI pipelines to test your code%{linkEnd} by simply adding a GitLab CI configuration file to your project. It only takes a minute to make your code more secure and robust.`, ); export const SP_HELP_URL = 'https://about.gitlab.com/blog/2019/07/12/guide-to-ci-cd-pipelines/'; export const SP_ICON_NAME = 'status_notfound';
import _ from 'lodash'; import Emitter from '../../utils/mixins/emitter'; import Clickoutside from '../../utils/clickoutside'; import DropdownMenu from './DropdownMenu'; let dropdownTemplate = ` <div :class="classes" v-clickoutside="handleClose" > <template v-if="label"> <div class="dropdown__label" ref="reference" > {{ label }} </div> </template> <template v-else> <div class="dropdown__label" :class="iconClass" ref="reference" > </div> </template> <dropdown-menu @show="handleOpen" @hide="handleClose" v-show="visible" :trigger="trigger" :visible-arrow="visibleArrow" :arrow-class="arrowClass" :boundaries-selector="boundariesSelector" :options="popperOptions" > <div v-if="showHeader" class="dropdown__menu-header"> <slot name="header"> Header </slot> </div> <ul class="dropdown__menu-list"> <slot></slot> </ul> <div v-if="showFooter" class="dropdown__menu-footer"> <slot name="footer"> Footer </slot> </div> </dropdown-menu> </div> `; export default { mixins: [Emitter], name: 'Dropdown', template: dropdownTemplate, componentName: 'Dropdown', directives: { Clickoutside }, components: { 'dropdown-menu': DropdownMenu }, props: { trigger: { type: String, default: 'click', validator: value => ['click', 'hover'].indexOf(value) > -1 }, triggerReferenceOnly: { type: Boolean, default: true }, visibleArrow: { type: Boolean, default: true }, arrowClass: { type: String, default: 'dropdown__menu-arrow' }, boundariesSelector: String, popperOptions: { type: Object, default: function () { return {}; } }, label: { type: String, default: null }, showHeader: { type: Boolean, default: true }, showFooter: { type: Boolean, default: true }, modifierStyles: { type: Array, default: function () { return []; } }, variationClass: { type: String, default: "dropdown" }, iconClass: { type: String, default: "pe-icon-dropdown-arrow" } }, data() { return { visible: false }; }, computed: { classes: function () { let result; // If there is a label provided put the iconClass on classes if (this.label) { result = [this.variationClass, this.iconClass]; return _.concat(result, this.modifierStyles); } else { // Otherwise put iconClass on the dropdown__label element; result = [this.variationClass]; return _.concat(result, this.modifierStyles); } } }, watch: { visible(val) { // If visible is set to false if (!val) { // Destroy Popper // this.broadcast('DropdownMenu', 'destroyPopper'); } // If is visible else { // Broadcast updatePopper event // this.broadcast('DropdownMenu', 'updatePopper'); } // this.$emit('visible-change', val); } }, methods: { handleClose() { // console.log("CALLED Clickoutside"); >> WORKED this.visible = false; }, handleOpen() { this.visible = true; } }, mounted() { }, beforeDestroy() { if (this.$el) { this.broadcast('DropdownMenu', 'destroyPopper'); } } }; /* PLAN: Dropdown - Parent component - Contains "reference" ---> DONE - Uses the Dropdown menu ---> DONE - Determines variationClass and modifierStyles ---> DONE - Determines iconClass ---> DONE - Determines trigger click, hover, or use reference as trigger --- DONE - Determines dropdown label text - Dynamically loads component into menu <slot> Dropdown Menu - Child - Make each dropdown menu-item be similar to form-item where each item can be a different class of component. - Should be able to have a custom header and footer as well - Make slots for header and footer that can be passed in. Dropdown Menu Item - Child - <li> wrapper - Default slot will be where content is passed into - Check to see if it is destroyed when parent menu is destroyed. --> DONE Destroyed successfully - Generally Only have to manually destroy if you are manually mounting the component. Otherwise Vue will handle it. - Ok if neither are destroyed - Not Ok if menu is destroyed but items aren't <dropdown> <dropdown-menu-item> <some-component></some-component> </dropdown-menu-item> </dropdown> */
function *dropWhile(xs, iteratee, thisArg) { let drop = true; let fn = thisArg ? iteratee.bind(thisArg) : iteratee; let i = 0; for (let x of xs) { if (drop) { drop = fn(x, i, xs); } if (!drop) { yield x; } i += 1; } } export default dropWhile;
eid_data = [ { key: 'Viruses and prions', color: '#d62728', values: [ { "label" : "Ungulates" , "value" : 43 } , { "label" : "Carnivores" , "value" : 16 } , { "label" : "Rodents" , "value" : 50 } , { "label" : "Non-mammals" , "value" : 35 } , { "label" : "Primates" , "value" : 35 } , { "label" : "Other mammals" , "value" : 13 } , { "label" : "Bats" , "value" : 16 } ] }, { key: 'Bacteria and rickettsiae', color: '#1f77b4', values: [ { "label" : "Ungulates" , "value" : 112 } , { "label" : "Carnivores" , "value" : 64 } , { "label" : "Rodents" , "value" : 51 } , { "label" : "Non-mammals" , "value" : 41 } , { "label" : "Primates" , "value" : 30 } , { "label" : "Other mammals" , "value" : 11 } , { "label" : "Bats" , "value" : 4 } ] }, { key: 'Fungi', color: '#d62728', values: [ { "label" : "Ungulates" , "value" : 36 } , { "label" : "Carnivores" , "value" : 46 } , { "label" : "Rodents" , "value" : 9 } , { "label" : "Non-mammals" , "value" : 22 } , { "label" : "Primates" , "value" : 9 } , { "label" : "Other mammals" , "value" : 3 } , { "label" : "Bats" , "value" : 1 } ] }, { key: 'Protozoa', color: '#d62728', values: [ { "label" : "Ungulates" , "value" : 11 } , { "label" : "Carnivores" , "value" : 15 } , { "label" : "Rodents" , "value" : 17 } , { "label" : "Non-mammals" , "value" : 5 } , { "label" : "Primates" , "value" : 13 } , { "label" : "Other mammals" , "value" : 8 } , { "label" : "Bats" , "value" : 0 } ] }, { key: 'Helminths', color: '#d62728', values: [ { "label" : "Ungulates" , "value" : 61 } , { "label" : "Carnivores" , "value" : 105 } , { "label" : "Rodents" , "value" : 59 } , { "label" : "Non-mammals" , "value" : 70 } , { "label" : "Primates" , "value" : 33 } , { "label" : "Other mammals" , "value" : 12 } , { "label" : "Bats" , "value" : 3 } ] } ]; var mbchart; nv.addGraph(function() { mbchart = nv.models.multiBarChart() .x(function(d) { return d.label }) .y(function(d) { return d.value }) .margin({top: 40, right: 20, bottom: 80, left: 20}) .barColor(d3.scale.category20().range()) .showControls(true); mbchart.multibar .hideable(true); /*var xTicks = d3.select('.nv-x.nv-axis > g').selectAll('g'); xTicks .selectAll('text') .attr('transform', function(d,i,j) { return 'translate (-10, 25) rotate(-90 0,0)' }) ; */ mbchart.yAxis .tickFormat(d3.format(',.0f')); d3.select('#eidfig .chart').append("svg") .attr("width", 800) .attr("height", 600) .datum(eid_data) .transition().duration(500) .call(mbchart); nv.utils.windowResize(mbchart.update); mbchart.dispatch.on('stateChange', function(e) { nv.log('New State:', JSON.stringify(e)); }); return mbchart; });
import * as O from "most" import {h} from "@cycle/dom" export default function main({DOM, Store}) { const {dispatch, props} = model(Store) const vdom = view(props) const actions = intent(DOM) return { DOM: vdom, Store: dispatch(actions) } function model({actions, value}) { const dispatch = actions.reduce((state, action) => { switch (action.type) { case "INC": return {...state, num: state.num + 1} case "DEC": return {...state, num: state.num - 1} default: return state } }) return { dispatch, props: { num: value.map(v => v.num) } } } function view({num}) { return num.map(num => h("div", [ h("h1", [`Counter: ${num}`]), h("div", [ h("button.inc", "Increment"), h("button.dec", "Decrement") ]) ])) } function intent(DOM) { const incrementActions = DOM.select(".inc") .events("click") .map(() => ({type: "INC"})) const decrementActions = DOM.select(".dec") .events("click") .map(() => ({type: "DEC"})) return O.merge(incrementActions, decrementActions) } }
//TODO: //* password resets. //* delete users. //* change password. //* injectable hash function //* publish as a module. var _hash = require('sha1sum') function hash(str) { for(var i = 0; i < 1000; i++) str = _hash(str) return str } var auth = module.exports = function (db) { var authDb = db.sublevel('auth') return { auth: function (user, cb) { if(user.signup) { console.log('SIGNUP') if(!user.name || !user.email || !user.password) return cb(new Error('require name, email, password')) authDb.get(user.name, function (err, val) { console.log(err, val) if(!err) return cb(new Error('user already exists')) var salt = hash(Math.random()) db.batch([{ key: user.name, value: { password: hash(user.password + salt), salt: salt, name: user.name }, type:'put', prefix: authDb }, { key: user.name, value: { realname: '', user: user.name, bio: '', type: 'user' }, prefix: db.sublevel('user'), type: 'put', }] , function (err) { if(err) cb(err) else cb(null, { name: user.name, email: user.email, auth: true, signedIn: new Date }) }) }) } else { console.log('SIGNIN') if(!user.name || !user.password) return cb(new Error('require name, password')) authDb.get(user.name, function (err, val) { //console.log(val) //console.log(val.password, hash(user.password + val.salt)) if(err) cb(new Error('user does not exist')) else if(val.password === hash(user.password + val.salt)) { console.log('AUTHORIZED', {name: val.name, auth: true, signedIn: new Date}) cb(null, {name: val.name, auth: true, signedIn: new Date}) } else cb(new Error('password and username do not match')) }) } }, //this is coupled to the twitter example. //remove before publishing. access: function (user, db, method, args) { console.log('access?', user, method) if(!user && /put|del|batch|write/.test(method)) throw new Error('login to get write access') //validate that args is valid, and for this user. } } } if(!module.parent) { var levelup = require('levelup') var sublevel = require('level-sublevel') var opts = require('optimist').argv var db = sublevel(levelup('/tmp/test-level-auth', {encoding: 'json'})) var a = auth(db) a.auth(opts, function (err, user) { if(err) throw err console.log(user) }) }
--- layout: --- (function () { function getQueryVariable(variable) { var query = window.location.search.substring(1), vars = query.split("&"); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); if (pair[0] === variable) { return pair[1]; } } } function getPreview(query, content, previewLength) { previewLength = previewLength || (content.length * 2); var parts = query.split(" "), match = content.toLowerCase().indexOf(query.toLowerCase()), matchLength = query.length, preview; // Find a relevant location in content for (var i = 0; i < parts.length; i++) { if (match >= 0) { break; } match = content.toLowerCase().indexOf(parts[i].toLowerCase()); matchLength = parts[i].length; } // Create preview if (match >= 0) { var start = match - (previewLength / 2), end = start > 0 ? match + matchLength + (previewLength / 2) : previewLength; preview = content.substring(start, end).trim(); if (start > 0) { preview = "..." + preview; } if (end < content.length) { preview = preview + "..."; } // Highlight query parts preview = preview.replace(new RegExp("(" + parts.join("|") + ")", "gi"), "<strong>$1</strong>"); } else { // Use start of content if no match found preview = content.substring(0, previewLength).trim() + (content.length > previewLength ? "..." : ""); } return preview; } function displaySearchResults(results, query) { var searchResultsEl = document.getElementById("search-results"), searchProcessEl = document.getElementById("search-process"); if (results.length) { var resultsHTML = ""; results.forEach(function (result) { var item = window.data[result.ref], contentPreview = getPreview(query, item.content, 170), titlePreview = getPreview(query, item.title); resultsHTML += "<li><h4><a href='" + item.url + "'>" + titlePreview + "</a></h4><p><small>" + contentPreview + "</small></p></li>"; }); searchResultsEl.innerHTML = resultsHTML; searchProcessEl.innerText = "Showing"; } else { searchResultsEl.style.display = "none"; searchProcessEl.innerText = "No"; } } window.index = lunr(function () { this.field("id"); this.field("title", {boost: 10}); this.field("category"); this.field("url"); this.field("content"); }); var query = decodeURIComponent((getQueryVariable("q") || "").replace(/\+/g, "%20")), searchQueryContainerEl = document.getElementById("search-query-container"), searchQueryEl = document.getElementById("search-query"), searchInputEl = document.getElementById("search-input"); searchInputEl.value = query; searchQueryEl.innerText = query; searchQueryContainerEl.style.display = "inline"; for (var key in window.data) { window.index.add(window.data[key]); } displaySearchResults(window.index.search(query), query); // Hand the results off to be displayed })();
import React from 'react'; import EventEmitter from 'events'; import AbstractRotor, {INITIAL_ROTOR_TYPE, INITIAL_RING_POSITION, INITIAL_WINDOW_POSITION} from '../Rotor'; import {RO_TYPE_I, RO_TYPE_II, RO_TYPE_III, RO_TYPE_IV, RO_TYPE_V, RO_TYPE_VI, RO_TYPE_VII, RO_TYPE_VIII} from '../../../../Constants'; export default class Rotor extends React.Component { renderChoices () { return [RO_TYPE_I, RO_TYPE_II, RO_TYPE_III, RO_TYPE_IV, RO_TYPE_V, RO_TYPE_VI, RO_TYPE_VII, RO_TYPE_VIII].map((rotor) => { let disabled = this.props.usedRotors.indexOf(rotor) > -1; return <option key={rotor} disabled={disabled} value={rotor}>{rotor}</option>; }); } render () { return ( <AbstractRotor {...this.props}> {this.renderChoices()} </AbstractRotor> ); } } Rotor.propTypes = { type: React.PropTypes.oneOf([RO_TYPE_I, RO_TYPE_II, RO_TYPE_III, RO_TYPE_IV, RO_TYPE_V, RO_TYPE_VI, RO_TYPE_VII, RO_TYPE_VIII, INITIAL_ROTOR_TYPE]).isRequired, position: React.PropTypes.string.isRequired, ringPosition: React.PropTypes.number.isRequired, windowLetter: React.PropTypes.string.isRequired, eventManager: React.PropTypes.instanceOf(EventEmitter).isRequired }; Rotor.defaultProps = { type: INITIAL_ROTOR_TYPE, ringPosition: INITIAL_RING_POSITION, windowLetter: INITIAL_WINDOW_POSITION };
import classic from 'ember-classic-decorator'; import { inject as service } from '@ember/service'; import RESTSerializer from '@ember-data/serializer/rest'; import { isEmpty } from '@ember/utils'; /* * extends DS.RESTSerializer to implement encryption * * By default every attribute hash is encrypted using SJCL. * This is configurable by options parameter of DS.attr(). * * Options: * - encrypted (boolean) * If false the attribute won't be encrypted. * - includePlainOnCreate (string) * If set the attribute will be included plain (not encrypted) when * recorde is created. Value is the attributes name used. */ @classic export default class ApplicationSerializer extends RESTSerializer { isNewSerializerAPI = true; @service encryption; /* * implement decryption */ normalize(modelClass, resourceHash, prop) { // run before serialization of attribute hash modelClass.eachAttribute(function(key, attributes) { if ( attributes.options.encrypted !== false ) { if (typeof resourceHash[key] !== 'undefined' && resourceHash[key] !== null) { resourceHash[key] = this.encryption.decrypt(resourceHash[key]); } } }, this); // run legacy support transformation specified in model serializer if (typeof this.legacySupport === 'function') { resourceHash = this.legacySupport(resourceHash); } return super.normalize(modelClass, resourceHash, prop); } /* * implement encryption */ serializeAttribute(snapshot, json, key, attribute) { super.serializeAttribute(snapshot, json, key, attribute); // map includePlainOnCreate after serialization of attribute hash // but before encryption so we can just use the serialized hash if ( !isEmpty(attribute.options.includePlainOnCreate) && typeof attribute.options.includePlainOnCreate === 'string' ) { json[attribute.options.includePlainOnCreate] = json[key]; } // encrypt after serialization of attribute hash if ( attribute.options.encrypted !== false ) { json[key] = this.encryption.encrypt(json[key]); } } }
var tap = require('tap'); var utils = require('../lib/utils'); var locate = utils.locate; // Locate values tap.test('Locate values', function(t) { var locateMap = { foo: "bar", bar: { baz: "qwop" } }; var res; // Single level res = locate('foo', locateMap); t.equal(res, 'bar', 'Single level locate'); // Second level res = locate('bar.baz', locateMap); t.equal(res, 'qwop', 'Second level locate'); // Locate Object res = locate('bar', locateMap); t.similar(res, { baz: 'qwop' }, 'Object locate'); // VALUE_NOT_FOUND res = locate('does.not.exist', locateMap); t.equal(res, locate.VALUE_NOT_FOUND, 'Value not found'); // All done t.end(); }); // Locate values with validator tap.test('Locate with validator', function(t) { var locateMap = { foo: "bar", bar: { baz: "qwop" } }; var res; // String validator res = locate('foo', locateMap, utils.isString); t.equal(res, 'bar', 'Single level validator'); res = locate('bar.baz', locateMap, utils.isString); t.equal(res, 'qwop', 'Multi level validator'); // Invalid value res = locate('foo', locateMap, utils.isFunction); t.equal(res, locate.VALUE_NOT_VALID, 'Invalid value found'); t.end(); });
'use strict'; !function(name, definition) { if (typeof module !== 'undefined' && module.exports) { module.exports = definition; } else { var global = this, old = global[name]; definition.noConflict = function () { global[name] = old; return definition; }; global[name] = definition; } }('module_name', function() { return {}; }());
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('ui-card-text', 'Integration | Component | ui card text', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... });" this.render(hbs`{{ui-card-text}}`); assert.equal(this.$().text().trim(), ''); // Template block usage:" this.render(hbs` {{#ui-card-text}} template block text {{/ui-card-text}} `); assert.equal(this.$().text().trim(), 'template block text'); });
"use strict" const {createStore} = require(`redux`) const expect = require(`expect`) const isMapLoading = require(`./isMapLoading`) const {setMapLoading} = require(`../actions/index`) { // can set loading state const store = createStore(isMapLoading) store.dispatch(setMapLoading(true)) expect(store.getState()).toBe(true) store.dispatch(setMapLoading(false)) expect(store.getState()).toBe(false) }
import { rows } from './pascals-triangle'; describe('Pascals Triangle', () => { describe("Given a count, return a collection of that many rows of pascal's triangle", () => { test('zero rows', () => { expect(rows(0)).toEqual([]); }); xtest('single row', () => { expect(rows(1)).toEqual([[1]]); }); xtest('two rows', () => { expect(rows(2)).toEqual([[1], [1, 1]]); }); xtest('three rows', () => { expect(rows(3)).toEqual([[1], [1, 1], [1, 2, 1]]); }); xtest('four rows', () => { expect(rows(4)).toEqual([[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]); }); xtest('five rows', () => { expect(rows(5)).toEqual([ [1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1] ]); }); xtest('six rows', () => { expect(rows(6)).toEqual([ [1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1] ]); }); xtest('ten rows', () => { expect(rows(10)).toEqual([ [1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 15, 6, 1], [1, 7, 21, 35, 35, 21, 7, 1], [1, 8, 28, 56, 70, 56, 28, 8, 1], [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] ]); }); }); });
(function (){ var boot = // zero to many scripts to load a configuration and/or loader. // i.e. path-to-util/qasht/runner.html?boots=path-to/config.js,path-to/require.js ["../dojo/dojo.js"], standardDojoBoot = boot, test = // zero to many AMD modules and/or URLs to load; provided by csv URL query parameter="test" // For example, the URL... // // path-to-util/qasht/runner.html?test=qasht/selfTest,my/path/test.js // // ...will load... // // * the AMD module qasht/selfTest // * the plain old Javascript resource my/path/test.js // ["dojo/tests/module"], paths = // zero to many path items to pass to the AMD loader; provided by semicolon separated values // for URL query parameter="paths"; each path item has the form <from-path>,<to-path> // i.e. path-to-util/qasht/runner.html?paths=my/from/path,my/to/path;my/from/path2,my/to/path2 {}, qashtPlugins = // Semicolon separated list of files to load before the tests. // Idea is to override aspects of qasht for reporting purposes. "", breakOnError = // boolean; instructs qasht to call the debugger upon a test failures; this can be helpful when // trying to isolate exactly where the test failed false, async = // boolean; config require.async==true before loading boot; this will have the effect of making // version 1.7+ dojo bootstrap/loader operating in async mode false, sandbox = // boolean; use a loader configuration that sandboxes the dojo and dojox objects used by qasht false, trim = function (text){ if (text instanceof Array){ for (var result = [], i = 0; i < text.length; i++){ result.push(trim(text[i])); } return result; } else{ return text.match(/[^\s]*/)[0]; } }; qstr = window.location.search.substr(1); if (qstr.length){ for (var qparts = qstr.split("&"), x = 0; x < qparts.length; x++){ var tp = qparts[x].split("="), name = tp[0], value = (tp[1] || "").replace(/[<>"':\(\)]/g, ""); // replace() to avoid XSS attack //Avoid URLs that use the same protocol but on other domains, for security reasons. if (value.indexOf("//") === 0 || value.indexOf("\\\\") === 0){ throw "Insupported URL"; } switch (name){ // Note: // * dojoUrl is deprecated, and is a synonym for boot // * testUrl is deprecated, and is a synonym for test // * testModule is deprecated, and is a synonym for test (dots are automatically replaced with slashes) // * registerModulePath is deprecated, and is a synonym for paths case "boot": case "dojoUrl": boot = trim(value.split(",")); break; case "test": test = trim(value.replace(/\./g, "/").split(",")); break; // registerModulePath is deprecated; use "paths" case "registerModulePath": case "paths": for (var path, modules = value.split(";"), i = 0; i < modules.length; i++){ path = modules[i].split(","); paths[trim(path[0])] = trim(path[1]); } break; case "breakOnError": breakOnError = true; break; case "sandbox": sandbox = true; break; case "async": async = true; break; case "qashtPlugins": qashtPlugins = value.split(";"); break; } } } var config = { paths : paths, deps : ["dojo/domReady", "qasht/main"], callback : function (domReady, qasht){ domReady(function (){ if (blanket){ blanket.setupCoverage(); qasht.on('end', function (){ blanket.onTestsDone(); }); qasht.on('suite', function (){ blanket.onModuleStart(); }); qasht.on('testStart', function (){ blanket.onTestStart(); }); qasht.on('testComplete', function (test){ blanket.onTestDone(qasht.totalTests, test.passed); }); blanket.customReporter = function (coverage_results){ console.log(coverage_results); }; } qasht.breakOnError = breakOnError; require(test, function (){ qasht.run(); }); }); }, async : async, isDebug : 1 }; // load all of the qashtPlugins if (qashtPlugins){ var i = 0; for (i = 0; i < qashtPlugins.length; i++){ config.deps.push(qashtPlugins[i]); } } require = config; // now script inject any boots for (var e, i = 0; i < boot.length; i++){ if (boot[i]){ e = document.createElement("script"); e.type = "text/javascript"; e.src = boot[i]; e.charset = "utf-8"; document.getElementsByTagName("head")[0].appendChild(e); } } })();
//~ name b490 alert(b490); //~ component b491.js
Package.describe({ name: 'herrhelms:meteor-vcard-dummy', version: '0.0.1', summary: 'Playground package to generate and download .vcf files within your meteor app', git: 'https://github.com/herrhelms/meteor-vcards-dummy.git', documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.1.0.2'); api.imply('iron:router@1.0.7'); api.use(['templating', 'spacebars', 'reactive-var'], 'client'); api.addFiles('meteor-vcard-dummy.js'); });
import { inherit } from '../../../src/utils' describe('Utils.inherit', function() { it('does not assign properties it does not own', function() { const a = inherit(function Child() {}, function Parent() {}) expect(a.constructor).toEqual(a.constructor) }) })
import React from 'react'; import Helmet from 'react-helmet'; import { Route } from '../../core/router'; import { Model as MethodType } from '../../entities/MethodType'; import { Deferred } from '../../util/utils'; import NavLink from '../../components/NavLink'; import Progress from 'react-progress-2'; import { PageHeader, Row, Col, Panel, Label } from 'react-bootstrap'; import radio from 'backbone.radio'; const router = radio.channel('router'); const session = radio.channel('session'); export default class MethodTypeShowRoute extends Route { breadcrumb({ params }) { const dfd = new Deferred; (new MethodType({ fid: params.fid })).fetch({ success: m => dfd.resolve(m.get('title')) }); return dfd.promise; } fetch({ params }) { this.methodType = new MethodType({ fid: params.fid }); return this.methodType.fetch(); } render() { const isAdmin = session.request('currentUser').get('role') === 'admin'; const methodType = this.methodType.toJSON(); return ( <div> <Helmet title={methodType.title} /> <PageHeader>{methodType.title}</PageHeader> <Row> <Col md={12}> <ul className="nav menu-nav-pills"> {!isAdmin ? '' : ( <li> <NavLink to={`/method-types/${methodType.fid}/edit`}> <i className="fa fa-pencil-square-o" /> Редактировать </NavLink> </li> )} {!isAdmin ? '' : ( <li> <a href="javascript:;" onClick={() => { Progress.show(); this.methodType.destroy({ success: () => { Progress.hide(); router.request('navigate', 'method-types'); }, }); }} > <i className="fa fa-ban" aria-hidden="true" /> Удалить </a> </li> )} </ul> </Col> </Row> <Row> <Col md={12}> <Panel> <h4><Label>Название</Label>{' '} {methodType.title} </h4> </Panel> </Col> </Row> </div> ); } }
(function($) { $.widget("ouvigna.indexify", { $source: null, $destination: null, mode: null, options: { source: null, destination: null, mode: null, classSelector: "" }, _create: function() { this._setOptions(); var items = this._findItems(), $html = this._buildHTML(items); this._setHTML($html); }, _setOptions: function() { this.$destination = this.element; this.$source = (this.options.source === null)? this.element: $(this.options.source); this.mode = (this.options.mode === null)? "html": this.options.mode; }, _findItems: function(level, $from) { var headers, _self = this, items = []; level = level === undefined?1:level; if (level == 1) { headers = $("h" + level, this.$source); } else { $limit = $($from.nextAll("h" + (level-1)).get(0)); headers = $from.nextUntil($limit, "h" + level); } if (this.options.classSelector) { headers = headers.filter("." + this.options.classSelector); } headers.each(function() { var $this = $(this); items.push({"$element": $this, "children": _self._findItems(level + 1, $this)}); }); return items; }, _buildHTML: function(items) { var $self = this, $listItems = $("<ul>"); $.each(items, function() { var $item = $("<li>"). html(this.$element.html()). appendTo($listItems); if ("children" in this && this.children.length) { $item.append($self._buildHTML(this.children)); } }); return $listItems; }, _setHTML: function($html) { if (typeof this.$destination[this.mode] === "function") { this.$destination[this.mode]($html); } } }); })(jQuery);
/** * Copyright (c) 2011 Sitelier Inc. * * 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. * * Author: Chris Osborn * Date: 1/20/12 */ var Q = require('q'); var mongodb = require('mongodb'); /** * Wrapper for a MongoDB server object. * * @param host * @param port * @param options */ function Server(host, port, options) { this.mserver = new mongodb.Server(host, port, options); } exports.Server = Server; Server.prototype.database = function(dbName) { var dbConnection = new mongodb.Db(dbName, this.mserver); return Q.ncall(dbConnection.open, dbConnection).then( function(mdb) { return new Database(mdb); } ); }; /** * Wrapper for a MongoDB database object. * * @param mdb mongodb-native database object to wrap */ function Database(mdb) { this.mdb = mdb; } exports.Database = Database; Database.prototype.collection = function(name) { return Q.ncall(this.mdb.collection, this.mdb, name).then( function(mcoll) { return new Collection(mcoll); } ); }; Database.prototype.collections = function() { return Q.ncall(this.mdb.collections, this.mdb).then( function(collections) { return collections.map(function(mcoll) { return new Collection(mcoll); }); } ); }; Database.prototype.close = function() { return Q.ncall(this.mdb.close, this.mdb); }; Database.prototype.getGridStoreHandle = function(name, mode, options) { var gs = new mongodb.GridStore(this.mdb, name, mode, options); return Q.ncall(gs.open, gs).then( function(gs) { return new GridStoreHandle(gs); } ); }; Database.prototype.unlink = function(name) { return Q.ncall(mongodb.GridStore.unlink, mongodb.GridStore, this.mdb, name); }; Database.prototype.exist = function(name) { return Q.ncall(mongodb.GridStore.exist, mongodb.GridStore, this.mdb, name); }; /** * Wrapper for a MongoDB collection object. * * @param mcoll mongodb-native collection object to wrap */ function Collection(mcoll) { this.mcoll = mcoll; Object.defineProperty(this, 'collectionName', { value: mcoll.collectionName }); } exports.Collection = Collection; Collection.prototype.save = function(data, options) { return Q.ncall(this.mcoll.save, this.mcoll, data, options); }; Collection.prototype.update = function(query, update, options) { return Q.ncall(this.mcoll.update, this.mcoll, query, update, options); }; Collection.prototype.remove = function(query) { return Q.ncall(this.mcoll.remove, this.mcoll, query); }; Collection.prototype.find = function(query) { return new Iterator(this.mcoll.find(query)); }; Collection.prototype.group = function(fields, query, initial, reducer) { return Q.ncall(this.mcoll.group, this.mcoll, fields, query, initial, reducer); }; Collection.prototype.ensureIndex = function(definition, options) { return Q.ncall(this.mcoll.ensureIndex, this.mcoll, definition, options); }; /** * Wrapper for a MongoDB iterator object. * * @param miterator mongodb-native iterator object to wrap */ function Iterator(miterator) { this.mit = miterator; } Iterator.prototype.nextObject = function() { return Q.ncall(this.mit.nextObject, this.mit); }; Iterator.prototype.toArray = function() { return Q.ncall(this.mit.toArray, this.mit); }; function GridStoreHandle(mgs) { this.mgs = mgs; } GridStoreHandle.prototype.getRaw = function() { return this.mgs; }; GridStoreHandle.prototype.write = function(data) { return Q.ncall(this.mgs.write, this.mgs, data).then( function(gs) {} // clear out the useless return value ); }; GridStoreHandle.prototype.read = function(size) { return Q.ncall(this.mgs.read, this.mgs, size); }; GridStoreHandle.prototype.close = function() { return Q.ncall(this.mgs.close, this.mgs); }; GridStoreHandle.prototype.stream = function(autoclose) { return this.mgs.stream(autoclose); };
import { connect } from 'react-redux' import HomeView from './component' import { handleBaseCostChange, removeEntry, handlePaymentMethod, handleDateChange, clearAll, exportAll, handleReasonChange, handleChangeForeign, sortByDate, } from './module' const mapStateToProps = state => ({ values: state.entries, }) const mapDispatchToProps = { handleBaseCostChange, removeEntry, handlePaymentMethod, handleDateChange, clearAll, exportAll, handleReasonChange, handleChangeForeign, sortByDate, } // Sync route definition export default { component: connect(mapStateToProps, mapDispatchToProps)(HomeView), }
// Copy Attributes Module // ====================== // addSelectBoxAttributes // ---------------------- // Add's all attributes (excluding id, class names, and the style attribute) from the default select box to the new drop down selectBoxIt._addSelectBoxAttributes = function() { // Stores the plugin context inside of the self variable var self = this; // Add's all attributes to the currently traversed drop down option self._addAttributes(self.selectBox.prop("attributes"), self.dropdown); // Add's all attributes to the drop down items list self.selectItems.each(function(iterator) { // Add's all attributes to the currently traversed drop down option self._addAttributes($(this).prop("attributes"), self.listItems.eq(iterator)); }); // Maintains chainability return self; }; // addAttributes // ------------- // Add's attributes to a DOM element selectBoxIt._addAttributes = function(arr, elem) { // Stores the plugin context inside of the self variable var self = this, whitelist = self.options["copyAttributes"], blacklist = self.options["dontCopyAttributes"]; // If there are array properties if(arr.length) { // Iterates over all of array properties $.each(arr, function(iterator, property) { // Get's the property name and property value of each property var propName = (property.name).toLowerCase(), propValue = property.value; // If the currently traversed property is in the blacklist if($.inArray(propName, blacklist) !== -1) { return; } // If the currently traversed property value is not "null", is on the whitelist, or is an HTML 5 data attribute if(propValue !== "null" && ($.inArray(propName, whitelist) !== -1 || propName.indexOf("data") !== -1)) { // Set's the currently traversed property on element elem.attr(propName, propValue); } }); } // Maintains chainability return self; };
var models = require('@bungalow/models'); exports2.requireUri = function (uri) { return new Promise(function (resolve, fail) { var parts = uri.split(/\:/g); var id = parts[4]; var username = parts[2]; models.Playlist.fromUserId(username, id).load().then(function (playlist) { console.log(playlist); playlist.icon = 'music'; console.log("Playlist resolved", playlist); resolve(playlist); }); }); };
'use strict'; const path = require('path'); const webpack = require('webpack'); const isWebpackDevServer = process.argv.some(a => path.basename(a) === 'webpack-dev-server'); const isWatch = process.argv.includes('--watch'); const plugins = isWebpackDevServer || !isWatch ? [] : [ function(){ this.plugin('done', function(stats){ process.stderr.write(stats.toString('errors-only')); }); } ] ; module.exports = { devtool: 'eval-source-map', devServer: { contentBase: '.', port: 4008, stats: 'errors-only' }, entry: './src/Example.purs', output: { path: __dirname, pathinfo: true, filename: 'bundle.js' }, module: { rules: [ { test: /\.purs$/, use: [ { loader: 'purs-loader', options: { src: [ // if spago = true // source paths reported by `spago sources` path.join('src', '**', '*.purs'), path.join('bower_components', 'purescript-*', 'src', '**', '*.purs') ], bundle: false, psc: 'psa', watch: isWebpackDevServer || isWatch, pscIde: false } } ] }, ] }, resolve: { modules: [ 'node_modules', 'bower_components' ], extensions: [ '.purs', '.js'] }, plugins: [ new webpack.LoaderOptionsPlugin({ debug: true }) ].concat(plugins) };
search_result['4109']=["topic_00000000000009D9.html","RecaptchaResponse Class",""];
function createItemExamineState(game){ return { "game":game, "preload":function(){ }, "setup":function(){ }, "itemName":"", "previousState":"", "draw":function(){ background(this.game.colors.ruby); var descriptor=this.game.itemDescriptors[this.itemName]; var plotX=0; var plotY=0; image( this.game.patternManager.getGraphic(descriptor.pattern(),"black","black"), plotX, plotY); image( this.game.patternManager.getGraphic(descriptor.pattern(),descriptor.foreground(),descriptor.background()), plotX, plotY); this.game.textManager.writeText(descriptor.name,plotX+game.constants.board.cellWidth(),plotY,"darksilver","silver"); plotY+=game.constants.board.cellHeight(); for(var index=0;index<descriptor.description.length;++index){ this.game.textManager.writeText(descriptor.description[index],plotX+32,plotY,"silver","transparent"); plotY+=game.constants.text.cellHeight(); } this.game.textManager.writeText("Esc: back",0,this.game.constants.screen.height()-game.constants.text.cellHeight(),"silver","transparent"); }, "keyPressed":function(){ if (keyCode==ESCAPE){ this.game.state=this.previousState; return false; } return true; }, "keyReleased":function(){ return true; } }; }
import metadata from './metadata.min.json' import parser from '../../../source/parse' function parse(...parameters) { parameters.push(metadata) return parser.apply(this, parameters) } describe('parse', () => { it('should not parse invalid phone numbers', function() { parse('+7 (800) 55-35-35').should.deep.equal({}) parse('+7 (800) 55-35-35', undefined).should.deep.equal({}) parse('+7 (800) 55-35-35', 'US').should.deep.equal({}) parse('(800) 55 35 35', { defaultCountry: 'RU' }).should.deep.equal({}) parse('+1 187 215 5230', 'US').should.deep.equal({}) parse('+1 1877 215 5230', 'US').should.deep.equal({ country: 'US', phone: '8772155230' }) }) it('should parse valid phone numbers', function() { // Instant loans // https://www.youtube.com/watch?v=6e1pMrYH5jI // // Restrict to RU parse('8 (800) 555 35 35', 'RU').should.deep.equal({ country: 'RU', phone: '8005553535' }) // International format parse('+7 (800) 555-35-35').should.deep.equal({ country: 'RU', phone: '8005553535' }) // // Restrict to US, but not a US country phone code supplied // parse('+7 (800) 555-35-35', 'US').should.deep.equal({}) // Restrict to RU parse('(800) 555 35 35', 'RU').should.deep.equal({ country: 'RU', phone: '8005553535' }) // Default to RU parse('8 (800) 555 35 35', { defaultCountry: 'RU' }).should.deep.equal({ country: 'RU', phone: '8005553535' }) // Gangster partyline parse('+1-213-373-4253').should.deep.equal({ country: 'US', phone: '2133734253' }) // Switzerland (just in case) parse('044 668 18 00', 'CH').should.deep.equal({ country: 'CH', phone: '446681800' }) // China, Beijing parse('010-852644821', 'CN').should.deep.equal({ country: 'CN', phone: '10852644821' }) // France parse('+33169454850').should.deep.equal({ country: 'FR', phone: '169454850' }) // UK (Jersey) parse('+44 7700 300000').should.deep.equal({ country: 'JE', phone: '7700300000' }) // KZ parse('+7 702 211 1111').should.deep.equal({ country: 'KZ', phone: '7022111111' }) // Brazil parse('11987654321', 'BR').should.deep.equal({ country: 'BR', phone: '11987654321' }) // Long country phone code. parse('+212659777777').should.deep.equal({ country: 'MA', phone: '659777777' }) // No country could be derived. // parse('+212569887076').should.deep.equal({ countryPhoneCode: '212', phone: '569887076' }) }) it('should parse non-European digits', function() { parse('+١٢١٢٢٣٢٣٢٣٢').should.deep.equal({ country: 'US', phone: '2122323232' }) }) it('should work in edge cases', function() { let thrower // No input parse('').should.deep.equal({}) // No country phone code parse('+').should.deep.equal({}) // No country at all (non international number and no explicit country code) parse('123').should.deep.equal({}) // No country metadata for this `require` country code thrower = () => parse('123', 'ZZ') thrower.should.throw('Unknown country') // No country metadata for this `default` country code thrower = () => parse('123', { defaultCountry: 'ZZ' }) thrower.should.throw('Unknown country') // Invalid country phone code parse('+210').should.deep.equal({}) // Country phone code beginning with a '0' parse('+0123').should.deep.equal({}) // Barbados NANPA phone number parse('+12460000000').should.deep.equal({ country: 'BB', phone: '2460000000' }) // // A case when country (restricted to) is not equal // // to the one parsed out of an international number. // parse('+1-213-373-4253', 'RU').should.deep.equal({}) // National (significant) number too short parse('2', 'US').should.deep.equal({}) // National (significant) number too long parse('222222222222222222', 'US').should.deep.equal({}) // No `national_prefix_for_parsing` parse('41111', 'AC').should.deep.equal({ country: 'AC', phone: '41111'}) // National prefix transform rule (Mexico). // Local cell phone from a land line: 044 -> 1. parse('0445511111111', 'MX').should.deep.equal({ country: 'MX', phone: '15511111111' }) // No metadata thrower = () => parser('') thrower.should.throw('`metadata` argument not passed') // Numerical `value` thrower = () => parse(2141111111, 'US') thrower.should.throw('A text for parsing must be a string.') }) it('should parse phone number extensions', function() { // "ext" parse('2134567890 ext 123', 'US').should.deep.equal ({ country : 'US', phone : '2134567890', ext : '123' }) // "ext." parse('+12134567890 ext. 12345', 'US').should.deep.equal ({ country : 'US', phone : '2134567890', ext : '12345' }) // "#" parse('+12134567890#1234').should.deep.equal ({ country : 'US', phone : '2134567890', ext : '1234' }) // "x" parse('+78005553535 x1234').should.deep.equal ({ country : 'RU', phone : '8005553535', ext : '1234' }) // Not a valid extension parse('2134567890 ext. abc', 'US').should.deep.equal({ country : 'US', phone : '2134567890' }) }) })
// Async tests asyncTest("An async test", function () { start(); }); asyncTest("A test", function () { stop(); stop(); start(); start(); }); asyncTest("A test", function () { stop(); start(); });
$(function () { 'use strict'; var $formFilter = $('form.repository-filter'), $formFilterBtn = $('a.repository-filter'); $formFilter .find('select, input').change(function () { $formFilter.hide(0, function () { $formFilter.submit(); }) }) .end() .find('label').click(function () { var $prev = $(this).prev(); if ($prev.prop('checked')) { $prev.prop('checked', false).trigger('change'); return false; } }) .end() .find('a.button').click(function () { $formFilter .find('select').val('All').end() .find('input:checkbox, input:radio').prop('checked', false).trigger('change'); return false; }); $formFilterBtn.click(function () { var $elem = $(this); $formFilter.find('div.' + $elem.data('section')).toggle(0, function () { if ($(this).is(':visible')) { $elem.removeClass('secondary').addClass('info'); return; } $elem.removeClass('info').addClass('secondary'); }); $formFilter.find('input[autofocus]:visible').focus(); return false; }); $('a.attitude').click(function () { if (!$(this).hasClass('secondary')) { return false; } var elem = $(this); $.get(elem.attr('href'), function () { elem.siblings().each(function () { $(this).removeClass('success info alert').addClass('secondary'); }); elem.addClass(elem.removeClass('secondary').data('activeClass')); }); return false; }); });
'use strict'; var express = require('express'); var controller = require('./status.controller'); var router = express.Router(); router.get('/', controller.index); module.exports = router;
/* eslint-env browser */ /** * JWTs as access tokens are long enough that they have a significant impact on * test duration when using browser.setValue. Instead, this function let's us * inject them into the browser context and assign them in one shot. * * @param {string} selector * @param {string} token * @returns {undefined} */ export default function setValue(selector, token) { document.querySelector(selector).value = token; }
/** * Provides a single function for parsing an expression using a Parser * TODO(emily): Remove this */ var Parser = require("./Parser"); /** * Parses an expression using a Parser, then returns the parsed result. */ var parseTree = function(toParse, settings) { if (!(typeof toParse === 'string' || toParse instanceof String)) { throw new TypeError('KaTeX can only parse string typed expression'); } var parser = new Parser(toParse, settings); return parser.parse(); }; module.exports = parseTree;
function foo(name) { var x = 5 function goo() { console.log('name:', name, ', x =', x) x = 7 } return goo } var bar = 'bar' var g = foo(bar) g() var tar = 'tar' var f = foo(tar) f() /* === Output ==== name: bar , x = 5 name: tar , x = 5 */
jsonp({"cep":"62460000","cidade":"Uruoca","uf":"CE","estado":"Cear\u00e1"});
///HEAD TRACKING var videoInput = document.getElementById('vid'); var canvasInput = document.getElementById('compare'); var canvasOverlay = document.getElementById('overlay') var debugOverlay = document.getElementById('debug'); var overlayContext = canvasOverlay.getContext('2d'); canvasOverlay.style.position = "absolute"; canvasOverlay.style.top = '1000px'; canvasOverlay.style.left = '1600px'; canvasOverlay.style.zIndex = '0'; canvasOverlay.style.display = 'block'; var htracker = new headtrackr.Tracker({altVideo : {ogv : "./media/capture5.ogv", mp4 : "./media/capture5.mp4"}, calcAngles : true, ui : false, headPosition : false}); htracker.init(videoInput, canvasInput); htracker.start(); ///STREETVIEW LOCATIONS var json = {"locations": [ {"lat": "21.275807", "lng": "-157.826042", "heading": 270, "pitch": -5, "zoom": .5} , //honolulu // {"lat": "50.9273", "lng": "-1.6546", "heading": 180, "pitch": -5, "zoom": .5} , //british countryside // {"lat": "40.60763", "lng": "140.45995", "heading": 100, "pitch": -5, "zoom": .5} , //cherry blossoms {"lat": "26.625983", "lng": "-111.814436", "heading": 60, "pitch": -5, "zoom": .5} , //mexican seaside // {"lat": "36.2529989", "lng": "136.9005", "heading": 90, "pitch": -5, "zoom": .5} , //japanese countryside // {"lat": "40.742327", "lng": "-73.989007", "heading": 200, "pitch": -5, "zoom": .5} , //flatiron {"lat": "35.659543", "lng": "139.700691", "heading": 270, "pitch": -5, "zoom": .5} , //tokyo // {"lat": "45.435469", "lng": "12.324016", "heading": 140, "pitch": -5, "zoom": .5} , //venice // {"lat": "51.179429", "lng": "-1.825911", "heading": 180, "pitch": -5, "zoom": .5} , //stonehenge {"lat": "36.098205", "lng": "-112.092658", "heading": 0, "pitch": -5, "zoom": .5} //grand canyon ] }; //MATH FUNCTIONS function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function convertToRange(value, srcRange, dstRange){ // value is outside source range return if (value < srcRange[0] || value > srcRange[1]){ return NaN; } var srcMax = srcRange[1] - srcRange[0], dstMax = dstRange[1] - dstRange[0], adjValue = value - srcRange[0]; return (adjValue * dstMax / srcMax) + dstRange[0]; } var prevIndex; //STREETVIEW INITIALIZE function initialize() { while (index == prevIndex){ var index = getRandomInt(0,json.locations.length-1); } prevIndex = index; var mLoc = json.locations[index]; prevLoc = mLoc; var location = new google.maps.LatLng(mLoc.lat, mLoc.lng); var panoramaOptions = { position: location, pov: { heading : mLoc.heading, pitch : mLoc.pitch, zoom : mLoc.zoom }, disableDefaultUI: true }; var panorama = new google.maps.StreetViewPanorama(document.getElementById('panorama_img'), panoramaOptions); var curHead = mLoc.heading; var curPitch = mLoc.pitch; //WEBSOCKET SETUP var ws = new WebSocket('ws://localhost:8000'); ws.onopen = function(){ }; ws.onmessage = function(msg){ var c = msg.data; if (msg.data == 0){ while (index == prevIndex){ index = getRandomInt(0,json.locations.length-1); } prevIndex = index; var mLoc = json.locations[index]; var location = new google.maps.LatLng(mLoc.lat, mLoc.lng); panorama.setPosition(location); panorama.setPov({ heading: mLoc.heading, pitch: mLoc.pitch }); }; }; //ADD FACETRACKING EVENT TO PAN STREETVIEW document.addEventListener("facetrackingEvent", function( event ) { if (event.detection == "CS") { overlayContext.clearRect(0,0,320,240); overlayContext.translate(event.x, event.y) overlayContext.rotate(event.angle-(Math.PI/2)); overlayContext.strokeStyle = "#00CC00"; overlayContext.strokeRect((-(event.width/2)) >> 0, (-(event.height/2)) >> 0, event.width, event.height); overlayContext.rotate((Math.PI/2)-event.angle); overlayContext.translate(-event.x, -event.y); if (event.x>20 && event.x<300){ xVel = convertToRange(event.x,[20,300],[-20,20]); yVel = convertToRange(event.y,[50,250],[-20,20]); console.log(event.y); var newHead = curHead + xVel; var newPitch = curPitch + yVel; panorama.setPov({ heading: newHead, pitch: curPitch //change curPitch to newPitch if you want to change Y axis rotation }); } } }); } google.maps.event.addDomListener(window, 'load', initialize); //PROJECTION SETUP var container = $("#container"); var img = $(".img"); var pts = $(".pt"); var IMG_WIDTH = 1920; var IMG_HEIGHT = 1080; var transform = new PerspectiveTransform(img[0], IMG_WIDTH, IMG_HEIGHT, true); var tl = pts.filter(".tl").css({ left : transform.topLeft.x, top : transform.topLeft.y }); var tr = pts.filter(".tr").css({ left : transform.topRight.x, top : transform.topRight.y }); var bl = pts.filter(".bl").css({ left : transform.bottomLeft.x, top : transform.bottomLeft.y }); var br = pts.filter(".br").css({ left : transform.bottomRight.x, top : transform.bottomRight.y }); var target; var targetPoint; function onMouseMove(e) { targetPoint.x = e.pageX - container.offset().left - 20; targetPoint.y = e.pageY - container.offset().top - 20; target.css({ left : targetPoint.x, top : targetPoint.y }); // check the polygon error, if it's 0, which mean there is no error if(transform.checkError()==0){ transform.update(); img.show(); }else{ img.hide(); } } pts.mousedown(function(e) { target = $(this); targetPoint = target.hasClass("tl") ? transform.topLeft : target.hasClass("tr") ? transform.topRight : target.hasClass("bl") ? transform.bottomLeft : transform.bottomRight; onMouseMove.apply(this, Array.prototype.slice.call(arguments)); $(window).mousemove(onMouseMove); $(window).mouseup(function() { $(window).unbind('mousemove', onMouseMove); }) });
jsonp({"cep":"85823700","cidade":"Bom Retiro","uf":"PR","estado":"Paran\u00e1"});
/** * First we will load all of this project's JavaScript dependencies which * includes Vue and other libraries. It is a great starting point when * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); window.mobile_menu = require('./mobile-menu'); window.image_expander = require('./image-expander'); image_expander.boot(); window.reader = require('./reader'); window.Vue = require('vue'); /** * Next, we will create a fresh Vue application instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ Vue.component('search-component', require('./components/SearchComponent.vue')); Vue.component('guide-component', require('./components/GuideComponent.vue')); Vue.component('guide-shelf-component', require('./components/GuideShelfComponent.vue')); Vue.component('guide-map-component', require('./components/GuideMapComponent.vue')); Vue.component('reader-component', require('./components/ReaderComponent.vue')); const app = new Vue({ el: '#app', mounted: function () { }, data: { }, methods: { openGuide(id) { console.log('RootComponent openGuide'); this.$refs.reader.load(id); this.$refs.reader.activate(); }, createShelf (guides, shelfIndex = false) { console.log('RootComponent createShelf'); this.$refs.map.createShelf(guides, shelfIndex); }, } }); $(document).ready(function(){ mobile_menu.boot(); });
jsonp({"cep":"47320000","cidade":"Pau a Pique","uf":"BA","estado":"Bahia"});
/** * Copyright (c) 2015 Guyon Roche * * 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. * */ 'use strict'; var fs = require('fs'); var events = require('events'); var utils = require('../../../utils/utils'); var BaseXform = require('../base-xform'); var TemplateXform = require('../template-xform'); // AppXform - used to write the app.xml // Not used for parsing var AppXform = module.exports = function() { }; utils.inherits(AppXform, BaseXform, { STATIC_XFORMS: { doc: new TemplateXform(fs.readFileSync(__dirname + '/app.xml').toString()) } },{ render: function(xmlStream, model) { AppXform.STATIC_XFORMS.doc.render(xmlStream, model); }, parseOpen: function() { return false; }, parseText: function() { }, parseClose: function() { return false; } });
$('#place_interest_tokens').tokenInput('/interests.json', { preventDuplicates: true}, {prePopulate: $('#place_interest_tokens').data('load')} ); $('#trip_place_tokens').tokenInput('/places.json', { preventDuplicates: true}, {prePopulate: $('#trip_place_tokens').data('load')} ); $('#trip_from_tokens').tokenInput('/places.json', { preventDuplicates: true, prePopulate: $('#trip_from_tokens').data('load'), onAdd: function(item) { if ($("#trip_from_tokens").tokenInput("get").length > 1) { $("#trip_from_tokens").tokenInput("clear"); } $("#trip_from_tokens").tokenInput("add", item); } }); $('#user_location_tokens').tokenInput('/locations.json',{token_limit:1, hintText: "Locations", preventDuplicates: true,onAdd: function(item) { if ($("#user_location_tokens").tokenInput("get").length > 1) { $("#user_location_tokens").tokenInput("clear"); } $("#user_location_tokens").tokenInput("add", item); }});
/******************************************************************************* * Copyright (c) 2015-2018 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation *******************************************************************************/ 'use strict'; let path = require('path'); let gulp = require('gulp'); let conf = require('./conf'); let $ = require('gulp-load-plugins')(); // Downloads the selenium webdriver gulp.task('webdriver-update', $.protractor.webdriver_update); gulp.task('webdriver-standalone', $.protractor.webdriver_standalone); function runProtractor (done) { let params = process.argv; let args = params.length > 3 ? params.slice(3) : []; gulp.src(path.join(conf.paths.e2e, '/**/*.ts')) .pipe($.protractor.protractor({ configFile: 'protractor.conf.js', args: args })) .on('error', function (err) { // Make sure failed tests cause gulp to exit non-zero throw err; }) .on('end', function () { done(); }); } gulp.task('protractor', ['protractor:src']); gulp.task('protractor:src', ['serve:e2e', 'webdriver-update'], runProtractor); gulp.task('protractor:dist', ['serve:e2e-dist', 'webdriver-update'], runProtractor);
function ajaxObject(layer, url) { // This is the object constructor var that=this; // A workaround for some javascript idiosyncrocies var updating = false; // Set to true if this object is already working on a request this.callback = function() {} // A post-processing call -- a stub you overwrite. this.update = function(passData) { // Initiates the server call. if (updating==true) { return false; } // Abort if we're already processing a call. updating=true; // Set the updating flag. var AJAX = null; // Initialize the AJAX variable. if (window.XMLHttpRequest) { // Are we working with mozilla? AJAX=new XMLHttpRequest(); // Yes -- this is mozilla. } else { // Not Mozilla, must be IE AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again? } // End setup Ajax. if (AJAX==null) { // If we couldn't initialize Ajax... alert("Your browser doesn't support AJAX."); // Sorry msg. return false // Return false (WARNING - SAME AS ALREADY PROCESSING!) } else { AJAX.onreadystatechange = function() { // When the browser has the request info.. if (AJAX.readyState==4 || AJAX.readyState=="complete") { // see if the complete flag is set. LayerID.innerHTML=AJAX.responseText; // It is, so put the new data in the object's layer delete AJAX; // delete the AJAX object since it's done. updating=false; // Set the updating flag to false so we can do a new request that.callback(); // Call the post-processing function. } // End Ajax readystate check. } // End create post-process fucntion block. var timestamp = new Date(); // Get a new date (this will make the url unique) var uri=urlCall+'?'+passData+'&timestamp='+(timestamp*1); // Append date to url (so the browser doesn't cache the call) AJAX.open("GET", uri, true); // Open the url this object was set-up with. AJAX.send(null); // Send the request. return true; // Everything went a-ok. } // End Ajax setup aok if/else block } // This area set up on constructor calls. var LayerID = document.getElementById(layer); // Remember the layer associated with this object. var urlCall = url; // Remember the url associated with this object. } // End AjaxObject
USETEXTLINKS = 1 STARTALLOPEN = 0 WRAPTEXT = 1 PRESERVESTATE = 0 HIGHLIGHT = 1 ICONPATH = 'file:////Users/eric/github/popgenDB/sims_for_structure_paper/2PopDNAnorec_0.5_1000/' //change if the gif's folder is a subfolder, for example: 'images/' foldersTree = gFld("<i>ARLEQUIN RESULTS (2PopDNAnorec_1_818.arp)</i>", "") insDoc(foldersTree, gLnk("R", "Arlequin log file", "Arlequin_log.txt")) aux1 = insFld(foldersTree, gFld("Run of 31/07/18 at 17:02:37", "2PopDNAnorec_1_818.xml#31_07_18at17_02_37")) insDoc(aux1, gLnk("R", "Settings", "2PopDNAnorec_1_818.xml#31_07_18at17_02_37_run_information")) aux2 = insFld(aux1, gFld("Genetic structure (samp=pop)", "2PopDNAnorec_1_818.xml#31_07_18at17_02_37_pop_gen_struct")) insDoc(aux2, gLnk("R", "AMOVA", "2PopDNAnorec_1_818.xml#31_07_18at17_02_37_pop_amova")) insDoc(aux2, gLnk("R", "Pairwise distances", "2PopDNAnorec_1_818.xml#31_07_18at17_02_37_pop_pairw_diff"))
var redisAdapter = require('sails-redis'); function config (redisConfig) { var redisPort = redisConfig.port, redisHost = redisConfig.host, db = redisConfig.db ; console.log('Waterline Redis config:', redisHost, ':', redisPort, '/', db); return { adapters: { redis: redisAdapter }, connections: { myLocalRedis: { adapter: 'redis', port: redisPort, host: redisHost, password: null, database: db, options: { parser: 'hiredis', return_buffers: false, detect_buffers: false, socket_nodelay: true, no_ready_check: true, enable_offline_queue: true } } }, defaults: { migrate: 'alter' } }; } module.exports = config;
var mongoose = require('mongoose'); require('../models/fieldModel'); var Field = mongoose.model('Field'); module.exports = { getFieldsByLocation: function(location) { var query = { "location": { $near: { $geometry: { type: "Point", coordinates:[-34.89,-56.18] }, $maxDistance : 20000 } } }; queryStr = JSON.stringify(query); var promise = Field.find(queryStr).exec() return promise; }, getFieldsByCity: function(city, radius) { return "TBD"; }, saveField: function(f) { var field = new Field(f); var promise = field.save(); } };
/** * @fileoverview Magic dependency loading. Taken from script.aculo.us * and modified to break it. * @author Stefan Strigler steve@zeank.in-berlin.de * @version $Revision: 1.1 $ */ var JSJaC = { Version: '$Rev: 456 $', require: function(libraryName) { // inserting via DOM fails in Safari 2.0, so brute force approach document.write('<script type="text/javascript" src="'+libraryName+'"></script>'); }, load: function() { var includes = ['xmlextras', 'jsextras', 'crypt', 'JSJaCConfig', 'JSJaCConstants', 'JSJaCCookie', 'JSJaCJSON', 'JSJaCJID', 'JSJaCBuilder', 'JSJaCPacket', 'JSJaCError', 'JSJaCKeys', 'JSJaCConnection', 'JSJaCHttpPollingConnection', 'JSJaCHttpBindingConnection', 'JSJaCConsoleLogger' ]; var scripts = document.getElementsByTagName("script"); var path = './'; for (var i=0; i<scripts.length; i++) { if (scripts.item(i).src && scripts.item(i).src.match(/JSJaC\.js$/)) { path = scripts.item(i).src.replace(/JSJaC.js$/,''); break; } } for (var i=0; i<includes.length; i++) this.require(path+includes[i]+'.js'); }, bind: function(fn, obj, arg) { return function() { if (arg) fn.apply(obj, arg); else fn.apply(obj); }; } }; if (typeof JSJaCConnection == 'undefined') JSJaC.load();
jQuery(document).ready( function($) { /* Mini Plugin */ $.fn.abManageOptions = function() { var $$ = this, obj = $$.parents('tr').nextAll('tr'); obj.toggle( 0, function() { obj.children().find(':input').attr('disabled', !$$.attr('checked')); } ); } /* Tabs steuern */ function abInitTabs() { $('#ab_main').tabs( { 'select': function(event, ui) { $('#ab_tab_index').val(ui.index); }, 'selected': parseInt($('#ab_tab_index').val()) } ); } /* Event abwickeln */ $('#ab_main .related tr:first-child :checkbox').click( function() { $(this).abManageOptions(); } ).filter(':checked').abManageOptions(); /* jQuery UI geladen? */ if ( jQuery.ui === undefined || jQuery.ui.tabs === undefined ) { $.getScript( 'http://code.jquery.com/ui/1.8.18/jquery-ui.min.js', abInitTabs ); } else { abInitTabs(); } /* Alert ausblenden */ if ( typeof $.fn.delay === 'function' ) { $('#setting-error-settings_updated').delay(5000).fadeOut(); } } );
var FPS = 60; var TPF = 1000/FPS; var isPlaying = 1; var now; var scene = {}; var n_stars = 1000; var sec_stars = 60; var canvas, ctx; var nKey = 21; $( window ).load(function(){ canvas = document.getElementById('pianoCanvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight/2; ctx = canvas.getContext('2d'); var scale = [7,50]; var y = 25; var x = 0; CH(x,y,scale[0],scale[1],4); x+=scale[0]*3; CH(x,y,scale[0],scale[1],3); x+=scale[0]; CH(x,y,scale[0],scale[1],2); x+=scale[0]*4; x = create12(scale, x,y); x = create12(scale, x,y); x = create12(scale, x,y); x = create12(scale, x,y); x = create12(scale, x,y); x = create12(scale, x,y); CH(x,y,scale[0],scale[1],0); x+=scale[0]*2; setInterval(function() { now = new Date(); for(var obj in scene){ scene[obj].update(TPF); } ctx.clearRect(0, 0, canvas.width, canvas.width); for(var obj in scene){ scene[obj].draw(ctx); } }, TPF); }); function create12(scale, x,y){ CH(x,y,scale[0],scale[1],0); x+=scale[0]*2; CH(x,y,scale[0],scale[1],3); x+=scale[0]*2; CH(x,y,scale[0],scale[1],1); x+=scale[0]*3; CH(x,y,scale[0],scale[1],3); x+=scale[0]; CH(x,y,scale[0],scale[1],2); x+=scale[0]*4; CH(x,y,scale[0],scale[1],0); x+=scale[0]*2; CH(x,y,scale[0],scale[1],3); x+=scale[0]*2; CH(x,y,scale[0],scale[1],4); x+=scale[0]*3; CH(x,y,scale[0],scale[1],3); x+=scale[0]; CH(x,y,scale[0],scale[1],4); x+=scale[0]*3; CH(x,y,scale[0],scale[1],3); x+=scale[0]; CH(x,y,scale[0],scale[1],2); x+=scale[0]*4; return x; } function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } var pcolors = ['rgba(80, 80, 80, 1)', 'rgba(200, 200, 200, 1)']; var pColorIdx = [1,1,1,0,1,1]; var pKeys = [ [[0,0],[0,2],[4,2],[4,1],[2,1],[2,0],[0,0]], [[1,0],[1,1],[0,1],[0,2],[4,2],[4,1],[3,1],[3,0],[1,0]], [[2,0],[2,1],[0,1],[0,2],[4,2],[4,0],[2,0]], [[0,0],[0,1],[3,1],[3,0],[0,0]], [[1,0],[1,1],[0,1],[0,2],[4,2],[4,1],[3,1],[3,0],[1,0]], [[1.5,0],[1.5,1],[0,1],[0,2],[4,2],[4,1],[3.5,1],[3.5,0],[1,0]], ]; function CH(x,y,scaleX,scaleY,type){ var nk = (nKey).toString(16).toUpperCase(); scene[nk] = { volume : "00", color : "#f90", n: nk, x: x, y: y, scaleX: scaleX, scaleY: scaleY, type: type, update: function(tpf){ }, draw : function(ctx){ if(this.volume != "00"){ ctx.fillStyle = this.color; } else{ ctx.fillStyle = pcolors[pColorIdx[this.type]]; } ctx.strokeStyle="#000"; ctx.lineWidth=1; drawKey(ctx, pKeys[this.type], this.x, this.y, this.scaleX, this.scaleY); ctx.fillStyle = "#f90"; ctx.font = "12px Arial"; ctx.fillText(""+this.n+"",this.x,this.y); ctx.stroke(); } }; nKey++; } function drawKey(ctx, arr, x, y, sx, sy) { ctx.beginPath(); ctx.moveTo(x+sx*arr[0][0],y+sy*arr[0][1]); for (var i = 1; i < arr.length; i++) { ctx.lineTo(x+sx*arr[i][0],y+sy*arr[i][1]); } ctx.fill(); ctx.stroke(); }
/** * */ Ext.define('MySQLink.ux.ProcedureEditor', { extend: 'Ext.form.Panel',//Ext.panel.Panel requires: [], xtype: 'procedure-editor', initComponent: function (config) { Ext.applyIf(this, { host: '', db: '', name: '' }); this.createFields(); config = Ext.apply(this, { layout: { type: 'vbox', align: 'stretch' }, fieldDefaults: { labelAlign: 'left' }, defaults: { padding: '5 5 0 5' }, items: [this.nameField, this.parameterField, this.definitionField], buttonAlign: 'center', buttons: [ { text: 'Save', scope: this, handler: function () { //this.up('form').getForm().isValid(); //var def = this.getDefinition(); this.save(); } }, { text: 'Cancel', scope: this, handler: function () { //this.up('form').getForm().reset(); } } ] }); this.callParent(); }, createFields: function () { this.nameField = Ext.create('Ext.form.field.Text', { fieldLabel: 'Name', padding: '5 5 0 5', allowBlank: false }); this.parameterField = Ext.create('MySQLink.ux.ParameterGrid', { title: 'Parameters', flex: 1, minHeight: 148, name: 'params' }); this.definitionField = Ext.create('MySQLink.CodeMirror', { //collapsible: true, title: 'Definition', xtype: 'codemirror', padding: '5 5 5 5', flex: 2, layout: 'fit' }); }, getDefinition: function () { var p = [], store = this.parameterField.store; for (var i = 0; i < store.getCount(); i++) { p.push(store.getAt(i).getData()); } var def = { name: this.nameField.getValue(), parameters: p, definition: this.definitionField.getQuery() } return def; }, save: function () { Ext.Ajax.request({ scope: this, url: this.baseURL + 'Procedure/Save', params: { host: this.host, db: this.db, definition: Ext.JSON.encode(this.getDefinition()) }, success: function (resp, opts) { }, failure: function () { } }); } });
/** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ define([ 'jquery', 'ko', 'Magento_Ui/js/form/form', 'Magento_Customer/js/action/login', 'Magento_Customer/js/customer-data', 'Magento_Customer/js/model/authentication-popup', 'mage/translate', 'mage/url', 'Magento_Ui/js/modal/alert', 'mage/validation' ], function ($, ko, Component, loginAction, customerData, authenticationPopup, $t, url, alert) { 'use strict'; return Component.extend({ registerUrl: window.authenticationPopup.customerRegisterUrl, forgotPasswordUrl: window.authenticationPopup.customerForgotPasswordUrl, autocomplete: window.authenticationPopup.autocomplete, modalWindow: null, isLoading: ko.observable(false), defaults: { template: 'Magento_Customer/authentication-popup' }, /** * Init */ initialize: function () { var self = this; this._super(); url.setBaseUrl(window.authenticationPopup.baseUrl); loginAction.registerLoginCallback(function () { self.isLoading(false); }); }, /** Init popup login window */ setModalElement: function (element) { if (authenticationPopup.modalWindow == null) { authenticationPopup.createPopUp(element); } }, /** Is login form enabled for current customer */ isActive: function () { var customer = customerData.get('customer'); return customer() == false; //eslint-disable-line eqeqeq }, /** Show login popup window */ showModal: function () { if (this.modalWindow) { $(this.modalWindow).modal('openModal'); } else { alert({ content: $t('Guest checkout is disabled.') }); } }, /** * Provide login action * * @return {Boolean} */ login: function (formUiElement, event) { var loginData = {}, formElement = $(event.currentTarget), formDataArray = formElement.serializeArray(); event.stopPropagation(); formDataArray.forEach(function (entry) { loginData[entry.name] = entry.value; }); if (formElement.validation() && formElement.validation('isValid') ) { this.isLoading(true); loginAction(loginData); } return false; } }); });
import { test, moduleFor } from 'ember-qunit'; moduleFor('route:sponsors/sponsor', 'SponsorsSponsorRoute', { // Specify the other units that are required for this test. // needs: ['controller:foo'] }); test('it exists', function() { var route = this.subject(); ok(route); });
'use strict'; var app = require('../..'); import Clan from './clanes.model'; import request from 'supertest'; describe('Clanes API:', function() { var nuevoClan; before(function() { return Clan.remove().then(function() { nuevoClan = new Clan({ info: { nombre: 'Elite España Test Integración', nick: 'EETC', nivel: '1', normas: 'Prueba de normas de **EE1**, con texto *en cursiva*. \nTambién añado un salto de línea' }, media: { color1: 'ff0048', color2: 'ff0000', logo: 'logo_1_claro_cuadrado.png', icono: '', telegram: '', telegramLogo: 'telegram_1.jpg', telegramLogoAdmins: 'telegram_admin_1.jpg' } }); return nuevoClan.save(); }); }); // Clear users after testing after(function() { return Clan.remove(); }); describe('GET /api/clanes', function() { var listaClanes; beforeEach(function(done) { request(app) .get('/api/clanes') .expect(200) .expect('Content-Type', /json/) .end((err, res) => { if (err) { return done(err); } listaClanes = res.body; done(); }); }); it('should respond with JSON array', function() { expect(listaClanes).to.be.instanceOf(Array); }); }); describe('GET /api/clanes/:id', function() { var listaClanes; beforeEach(function(done) { request(app) .get(`/api/clanes/${nuevoClan._id}`) .expect(200) .expect('Content-Type', /json/) .end((err, res) => { if (err) { return done(err); } listaClanes = res.body; done(); }); }); afterEach(function() { listaClanes = {}; }); it('should respond with the requested clanes', function() { expect(listaClanes.info.nombre).to.equal('Elite España Test Integración'); expect(listaClanes.info.nick).to.equal('EETC'); }); }); });
import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return this.store.find('session'); } });
/* * logic.js -- main logic * * Codes from Jack Works(zjwpeter@gmail.com) * And idea is from Scott Shen(scottshen0515@gmail.com) * * Vola Studio 2014. * * */ dom.game.source.click(function () { var $t = $(this).stop(true); var result = checkr($t.attr('r'), settings.tgr, settings.tolerance, true); if(result == "in range"){ win(); } else{ lose(); } }) function lose(){ Event.publish("result lose")("result",["lose"]); } function win(){ Event.publish("result win")("result",["win"]); ani(); } function ani(){ settings.tgr = random(70,150) dom.game.target.attr("r", settings.tgr); dom.game.source.css("fontSize",0).attr("r",10) .animate({"fontSize":150 + settings.tolerance}, { step: function(now) { var $t = $(this); $t.attr("r",now); if(checkr(now, settings.tgr, settings.tolerance, false) == "stop animation"){ $t.stop(true); lose(); } }, duration:Math.random()*1000 + settings.speed }, 'linear', function () { lose(); }) } function random(min,max){ return Math.floor(Math.random()*(max-min+1)+min); } function checkr(s,t,m,c){ /* * * Actions: * "too big" "continue animation" * "too big" "stop animation" * "too small" "continue animation" * "in range" "continue animation" * t-m t+m t+2m * too small in range stop animation too big */ if(t+m<s&&c) return "too big"; if(t+m+m<s){if(c)return "too big";else return ("stop animation")} if(!c&&(t+m<s||t-m>s||(t-m<s&&s<t+m)))return "continue animation" if(t-m>s&&c)return "too small" if(t-m<s&&s<t+m)return "in range" return "error" }
/*globals Backbone */ /** * gp.media.model.PostImage * * An instance of an image that's been embedded into a post. * * Used in the embedded image attachment display settings modal - @see gp.media.view.MediaFrame.ImageDetails. * * @class * @augments Backbone.Model * * @param {int} [attributes] Initial model attributes. * @param {int} [attributes.attachment_id] ID of the attachment. **/ var PostImage = Backbone.Model.extend({ initialize: function( attributes ) { var Attachment = gp.media.model.Attachment; this.attachment = false; if ( attributes.attachment_id ) { this.attachment = Attachment.get( attributes.attachment_id ); if ( this.attachment.get( 'url' ) ) { this.dfd = jQuery.Deferred(); this.dfd.resolve(); } else { this.dfd = this.attachment.fetch(); } this.bindAttachmentListeners(); } // keep url in sync with changes to the type of link this.on( 'change:link', this.updateLinkUrl, this ); this.on( 'change:size', this.updateSize, this ); this.setLinkTypeFromUrl(); this.setAspectRatio(); this.set( 'originalUrl', attributes.url ); }, bindAttachmentListeners: function() { this.listenTo( this.attachment, 'sync', this.setLinkTypeFromUrl ); this.listenTo( this.attachment, 'sync', this.setAspectRatio ); this.listenTo( this.attachment, 'change', this.updateSize ); }, changeAttachment: function( attachment, props ) { this.stopListening( this.attachment ); this.attachment = attachment; this.bindAttachmentListeners(); this.set( 'attachment_id', this.attachment.get( 'id' ) ); this.set( 'caption', this.attachment.get( 'caption' ) ); this.set( 'alt', this.attachment.get( 'alt' ) ); this.set( 'size', props.get( 'size' ) ); this.set( 'align', props.get( 'align' ) ); this.set( 'link', props.get( 'link' ) ); this.updateLinkUrl(); this.updateSize(); }, setLinkTypeFromUrl: function() { var linkUrl = this.get( 'linkUrl' ), type; if ( ! linkUrl ) { this.set( 'link', 'none' ); return; } // default to custom if there is a linkUrl type = 'custom'; if ( this.attachment ) { if ( this.attachment.get( 'url' ) === linkUrl ) { type = 'file'; } else if ( this.attachment.get( 'link' ) === linkUrl ) { type = 'post'; } } else { if ( this.get( 'url' ) === linkUrl ) { type = 'file'; } } this.set( 'link', type ); }, updateLinkUrl: function() { var link = this.get( 'link' ), url; switch( link ) { case 'file': if ( this.attachment ) { url = this.attachment.get( 'url' ); } else { url = this.get( 'url' ); } this.set( 'linkUrl', url ); break; case 'post': this.set( 'linkUrl', this.attachment.get( 'link' ) ); break; case 'none': this.set( 'linkUrl', '' ); break; } }, updateSize: function() { var size; if ( ! this.attachment ) { return; } if ( this.get( 'size' ) === 'custom' ) { this.set( 'width', this.get( 'customWidth' ) ); this.set( 'height', this.get( 'customHeight' ) ); this.set( 'url', this.get( 'originalUrl' ) ); return; } size = this.attachment.get( 'sizes' )[ this.get( 'size' ) ]; if ( ! size ) { return; } this.set( 'url', size.url ); this.set( 'width', size.width ); this.set( 'height', size.height ); }, setAspectRatio: function() { var full; if ( this.attachment && this.attachment.get( 'sizes' ) ) { full = this.attachment.get( 'sizes' ).full; if ( full ) { this.set( 'aspectRatio', full.width / full.height ); return; } } this.set( 'aspectRatio', this.get( 'customWidth' ) / this.get( 'customHeight' ) ); } }); module.exports = PostImage;
var gulp = require('gulp'); var jade = require('gulp-jade'); var sass = require('gulp-sass'); var prettify = require('gulp-prettify'); var rename = require('gulp-rename'); var minify = require('gulp-csso'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var shell = require('gulp-shell'); var browserSync = require('browser-sync'); var sourcemaps = require('gulp-sourcemaps'); var postcss = require('gulp-postcss'); var cssnext = require('postcss-cssnext'); var paths = { 'html': 'src/', 'scss': 'src/css/', 'img': 'src/images/', 'dist': 'dist/', 'css': 'dist/css/' } gulp.task('bs', function() { browserSync.init({ server: { baseDir: paths.dist, index: 'index.html' }, notify: true }); }); gulp.task('html', function() { return gulp.src([ paths.html + '**/*.jade', '!' + paths.html + '**/_*.jade' ]) .pipe(jade()) .pipe(gulp.dest(paths.dist)); }); gulp.task('prettify', ['html'], function() { return gulp.src(paths.dist + '**/*.html') .pipe(prettify({ brace_style: 'collapse', indent_size: 2, indent_char: ' ' })) .pipe(gulp.dest(paths.dist)) .pipe(browserSync.reload({ stream: true })); }); gulp.task('scss', function() { var processors = [ cssnext() ]; return gulp.src(paths.scss + '**/*.scss') .pipe(sourcemaps.init()) .pipe(sass({ outputStyle: 'expanded', includePaths: require('node-reset-scss').includePath })) .on('error', function(err) { console.log(err.message); }) .pipe(postcss(processors)) .pipe(sourcemaps.write()) .pipe(gulp.dest(paths.css)) .pipe(browserSync.reload({ stream: true })); }); gulp.task('watch', function() { gulp.watch([paths.html + '**/*.jade'], ['prettify']); gulp.watch([paths.scss + '**/*.scss'], ['scss']); }); gulp.task('default', ['bs', 'prettify', 'scss', 'watch']);
$(document).ready(function(){ mooxMarketplaceInitDropdowns(); });
/* global $ */ $(function() { $("select#id_groups").selectize({ plugins: ["remove_button"], placeholder: "Everyone" }); var reset = $("#id_expiration_date").val() !== "3000-01-01 00:00:00"; $("#id_expiration_date").datetimepicker({ lazyInit: true, format: "Y-m-d H:i:s" }); // for approval page $("select#id_teachers_requested").selectize({ plugins: ["remove_button"], maxItems: 2 }); $("form#announcement_form").bind("submit", function (e) { if($("#id_notify_email_all").prop("checked")) { if(!confirm("This will send an email to ALL users who can see this post. If you have not selected a group, this will email the entire school. Are you sure you want to do this?")) { e.preventDefault(); } } if($("#id_title").val().match(/\bION\b/) || editor.getData().match(/\bION\b/)) { // People frequently write "ION" instead of the correct spelling, "Ion." See https://github.com/tjcsl/ion/issues/805 Messenger().error('We have detected the use of "ION" in all caps in your announcement. Please correct it to use "Ion", <a href="/docs/terminology" style="color:#7F7FFF">the official name</a>.'); e.preventDefault(); return; } var button = $("button#submit_announcement"); button.click(function(ev) { ev.preventDefault(); }) button.append(" <i class=\"fas fa-spinner fa-spin\" aria-hidden=\"true\"></i>"); if ($("input#id_title").val() === "") { button.prop("disabled", false); } }); // name of <textarea> is content var editor = CKEDITOR.replace("content", { width: "600px" }); var end_index = 0; editor.on("instanceReady", function () { // TODO: Don't duplicate this function. Bad! var text = editor.getData(); dates = chrono.parse(text) .sort(function (a, b) { var a_date = a.end ? a.end.date() : a.start.date(); var b_date = b.end ? b.end.date() : b.start.date(); return b_date.getTime() - a_date.getTime(); }) .filter(function (val, ind, ary) { if (ind) { var a_date = val.end ? val.end.date() : val.start.date(); var b_date = ary[ind - 1].end ? ary[ind - 1].end.date() : ary[ind - 1].start.date(); return !ind || a_date.getTime() != b_date.getTime(); } else { return true; } }); $(".exp-list").empty(); if (dates.length > 0) $(".exp-header").css("display", "block"); else $(".exp-header").css("display", "none"); for (var i = 0; i < dates.length; i++) { var use_date = dates[i].end ? dates[i].end.date() : dates[i].start.date(); $(".exp-list").append(`<li><a class='exp-suggest-item' data-date='${use_date}'>"${dates[i].text}" - ${use_date}</a></li>`); } }); editor.on("change", function () { // TODO: Optimize by only parsing on new spaces var text = editor.getData(); dates = chrono.parse(text) .sort(function (a, b) { var a_date = a.end ? a.end.date() : a.start.date(); var b_date = b.end ? b.end.date() : b.start.date(); return b_date.getTime() - a_date.getTime(); }) .filter(function (val, ind, ary) { if (ind) { var a_date = val.end ? val.end.date() : val.start.date(); var b_date = ary[ind - 1].end ? ary[ind - 1].end.date() : ary[ind - 1].start.date(); return !ind || a_date.getTime() != b_date.getTime(); } else { return true; } }); $(".exp-list").empty(); if (dates.length > 0) $(".exp-header").css("display", "block"); else $(".exp-header").css("display", "none"); for (var i = 0; i < dates.length; i++) { var use_date = dates[i].end ? dates[i].end.date() : dates[i].start.date(); $(".exp-list").append(`<li><a class='exp-suggest-item' data-date='${use_date}'>"${dates[i].text}" - ${use_date}</a></li>`); } }); });
$(window).scroll(function () { if ($(window).scrollTop() + $(window).height() === $(document).height()) { $('.load-more-objects').click(); $('.load-more-activities').click(); } }); $(document).ready(function () { $('.column-object-description').children('span').each(function () { $(this).text(changeNameLength($(this).text(), 100)); }); $('.column-object-title').find('a').each(function () { $(this).text(changeNameLength($(this).text(), 42)); }); }); jsf.ajax.addOnEvent(function (data) { if ($(data.source).hasClass("load-more-objects") || $(data.source).hasClass("load-more-activities")) { $('.column-object-description').children('span').each(function () { $(this).text(changeNameLength($(this).text(), 100)); }); $('.column-object-title').find('a').each(function () { $(this).text(changeNameLength($(this).text(), 42)); }); } });
/* Hello */ /* This is the file */ function fitImg() { iWidth = (NS)?window.innerWidth:document.body.clientWidth; iHeight = (NS)?window.innerHeight:document.body.clientHeight; iWidth = document.images[0].width - iWidth; iHeight = document.images[0].height - iHeight; window.resizeBy(iWidth, iHeight); self.focus(); } function getImage() { var title = document.title+'_elogImg.png' var fImgUrl = 'elogImg/'+title $.ajax({ type: 'get', url: '/python/serverScript.py', cache: false, data: { samName: document.title }, async: true, success: function() { popupPic(fImgUrl); /*callback;*/}, }); }; function popupPic(sPicURL) { window.open( "popup.html?"+sPicURL, "","resizable=1,HEIGHT=200,WIDTH=200,CENTERSCREN=YES,scrollbars=no"); } function startDOE() { window.open( "popup.html?" ) } document.getElementById("xrd").onclick = getImage; document.getElementById("doe").onclick = startDOE;
import { expect } from 'chai'; import { HAPPYCHAT_GROUP_WPCOM, HAPPYCHAT_GROUP_JPOP, HAPPYCHAT_SKILL_PRODUCT, HAPPYCHAT_SKILL_LANGUAGE, } from 'calypso/state/happychat/constants'; import getSkills from 'calypso/state/happychat/selectors/get-skills'; describe( '#getSkills()', () => { const uiState = { ui: { section: { name: 'reader', }, }, }; test( 'should return default product for no sites', () => { const siteId = 1; const state = { ...uiState, currentUser: { id: 73705554, user: { ID: 73705554, login: 'testonesite2014', localeSlug: 'en' }, }, sites: { items: {}, }, }; expect( getSkills( state, siteId ) ).to.eql( { [ HAPPYCHAT_SKILL_PRODUCT ]: [ HAPPYCHAT_GROUP_WPCOM ], [ HAPPYCHAT_SKILL_LANGUAGE ]: [ 'en' ], } ); } ); test( 'should ignore language if not set', () => { const siteId = 1; const state = { ...uiState, currentUser: { id: 73705554, user: { ID: 73705554, login: 'testonesite2014' }, }, sites: { items: {}, }, }; expect( getSkills( state, siteId ) ).to.eql( { [ HAPPYCHAT_SKILL_PRODUCT ]: [ HAPPYCHAT_GROUP_WPCOM ], } ); } ); test( 'should return both product and language', () => { const siteId = 1; const state = { ...uiState, currentUser: { id: 1, user: { ID: 1, login: 'testonesite2014', localeSlug: 'fr' }, capabilities: { [ siteId ]: { manage_options: true, }, }, }, sites: { items: { [ siteId ]: { jetpack: true, plan: { product_id: 2005, product_slug: 'jetpack_personal', }, }, }, }, }; expect( getSkills( state, siteId ) ).to.eql( { [ HAPPYCHAT_SKILL_PRODUCT ]: [ HAPPYCHAT_GROUP_JPOP ], [ HAPPYCHAT_SKILL_LANGUAGE ]: [ 'fr' ], } ); } ); } );
$(function() { $('#help').click(function(){ console.log("here"); $('#overlay').fadeIn(200,function(){ $('#box').animate({'top':'20px'},200); }); return false; }); $('#boxclose').click(function(){ $('#box').animate({'top':'-1000px'},500,function(){ $('#overlay').fadeOut('fast'); }); }); }); $(document).keyup(function(e) { if (e.keyCode == 27) { $('#box').animate({'top':'-1000px'},500,function(){ $('#overlay').fadeOut('fast'); }); $( ".accordionclass" ).css({"opacity":1}).show(); $( ".dynamic" ).empty(); $( ".dynamic" ).offset({top:-1000}); } }); /* * hoverIntent | Copyright 2011 Brian Cherne * http://cherne.net/brian/resources/jquery.hoverIntent.html * modified by the jQuery UI team */ $.event.special.hoverintent = { setup: function() { $( this ).bind( "mouseover", jQuery.event.special.hoverintent.handler ); }, teardown: function() { $( this ).unbind( "mouseover", jQuery.event.special.hoverintent.handler ); }, handler: function( event ) { var currentX, currentY, timeout, args = arguments, target = $( event.target ), previousX = event.pageX, previousY = event.pageY; function track( event ) { currentX = event.pageX; currentY = event.pageY; }; function clear() { target .unbind( "mousemove", track ) .unbind( "mouseout", clear ); clearTimeout( timeout ); } function handler() { var prop, orig = event; if ( ( Math.abs( previousX - currentX ) + Math.abs( previousY - currentY ) ) < 7 ) { clear(); event = $.Event( "hoverintent" ); for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } // Prevent accessing the original event since the new event // is fired asynchronously and the old event is no longer // usable (#6028) delete event.originalEvent; target.trigger( event ); } else { previousX = currentX; previousY = currentY; timeout = setTimeout( handler, 100 ); } } timeout = setTimeout( handler, 100 ); target.bind({ mousemove: track, mouseout: clear }); } };
self.port.emit('openCxPanel', true);
/** * $Id: editor_plugin_src.js 201 2007-02-12 15:56:56Z spocke $ * * @author Moxiecode * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved. */ (function() { // Load plugin specific language pack tinymce.PluginManager.requireLangPack('clker'); tinymce.create('tinymce.plugins.clkerPlugin', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished it's initialization so use the onInit event * of the editor instance to intercept that event. * * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed, url) { // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample'); ed.addCommand('mceclker', function() { ed.windowManager.open({ file : url + '/dialog.php', width : 700 + parseInt(ed.getLang('clker.delta_width', 0)), height : 450 + parseInt(ed.getLang('clker.delta_height', 0)), inline : 1 }, { plugin_url : url, // Plugin absolute URL some_custom_arg : 'custom arg' // Custom argument }); }); // Register clker button ed.addButton('clker', { title : 'Clker ClipArt Gallery', cmd : 'mceclker', image : url + '/img/clker.gif' }); // Add a node change handler, selects the button in the UI when a image is selected ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('clker', n.nodeName == 'IMG'); }); }, /** * Creates control instances based in the incomming name. This method is normally not * needed since the addButton method of the tinymce.Editor class is a more easy way of adding buttons * but you sometimes need to create more complex controls like listboxes, split buttons etc then this * method can be used to create those. * * @param {String} n Name of the control to create. * @param {tinymce.ControlManager} cm Control manager to use inorder to create new control. * @return {tinymce.ui.Control} New control instance or null if no control was created. */ createControl : function(n, cm) { return null; }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'clker plugin', author : 'Mohamed Ibrahim', authorurl : 'http://www.clker.com', infourl : 'http://www.clker.com/clkerplugin', version : "1.0" }; } }); // Register plugin tinymce.PluginManager.add('clker', tinymce.plugins.clkerPlugin); })();
x = rnorm(1000, 5, 2); str(x); hist(x, "x", "normalized"); curve("dnorm(x, 5,2)", "N(5,2)", 0.2);
export default { type: 'array', items: { oneOf: [ { type: 'object', required: [ 'domain_name', 'product_name', 'product_slug', 'product_type', 'site_id', 'mailboxes', ], properties: { domain_name: { type: 'string' }, product_name: { type: 'string' }, product_slug: { type: 'string' }, product_type: { type: 'string' }, site_id: { type: 'integer' }, mailboxes: { type: 'array', items: { type: 'object', required: [ 'name', 'first_name', 'last_name', 'state' ], properties: { name: { type: 'string' }, first_name: { type: 'string' }, last_name: { type: 'string' }, state: { type: 'string', enum: [ 'active', 'suspended' ] }, meta: { type: 'object' }, }, }, }, }, }, { type: 'object', required: [ 'domain_name', 'error', 'product_slug', 'site_id' ], properties: { domain_name: { type: 'string' }, error: { type: 'string' }, product_slug: { type: 'string' }, site_id: { type: 'integer' }, }, }, ], }, };