text
stringlengths
2
6.14k
module.exports = function (grunt) { // load all grunt tasks matching the `grunt-*` pattern require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), broccoli: { release: { dest: 'release', env: 'production' }, dev: { dest: 'build' } }, karma: { unit: { singleRun: true, configFile: 'test/karma.conf.js' } }, 'gh-pages': { options: { base: 'release', repo: 'https://github.com/astrifex/astrifex.github.io.git', branch: 'master' }, src: ['**'] }, clean: { dev: ['build'], release: ['release'], tmp: ['tmp/**/*'] } }); // Default task(s). grunt.registerTask('default', ["broccoli:dev:serve"]); };
'use babel'; import MarkdownToAsciidocView from '../lib/markdown-to-asciidoc-view'; describe('MarkdownToAsciidocView', () => { it('has one valid test', () => { expect('life').toBe('easy'); }); });
module.exports = (api) => { api.cache(false) return { presets: [ "@babel/preset-env" ] } }
//Ctrl-$X keys for controling hipster itself. module.exports = function (doc, keys, render) { var saved = false var rc = this.config var fs = require('fs') var cp = require('child_process') function send (args, write, cb) { var cmd = args.shift() var output = '' var c = cp.spawn(cmd, args) if(cb) { c.stdout.on('data', function (b) { output += b }) c.stdout.on('end', function () { cb(null, output) }) } c.on('error', function () {}) c.stdin.write(write || '') c.stdin.end() } function clipIn () { if(process.platform === 'darwin') { send(['pbcopy'], doc.getMarked()) } else if(process.platform === 'linux') { send(['xclip', '-i', '-selection', 'clipboard'], doc.getMarked()) } } function clipOut () { function cb (_, paste) { doc.insert(paste) } if(process.platform === 'darwin') { send(['pbpaste'], '', cb) } else if(process.platform === 'linux') { send(['xclip', '-o', '-selection', 'clipboard'], '', cb) } } keys.on('keypress', function (ch, key) { console.error(ch, key) if(key.ctrl) { if(key.name == 's' && !rc.noSave) { saved = true fs.writeFileSync(rc.file, doc.lines.join('').replace(/\n+$/g,'\n'), 'utf-8') return } if(key.name == 'c') { clipIn() } if(key.name == 'x') { clipIn() doc.clearMarked() } if(key.name == 'p' || key.name == 'v') { doc.clearMarked() clipOut() } if(key.name == 'r') return render.redraw(), doc.move() //delete current line if(key.name == 'd') return doc.start().deleteLines(doc.row, 1).move() //select current line if(key.name == 'l') doc.start().mark().down().mark().move() if(key.name == 'q') { process.stdin.pause() //exit error if not saved, so you can cancel editing //git commit messages process.exit(saved ? 0 : 1) } } }) }
var testapi = require('./testapi.js'); var util = require('util'); var request = require('request'); describe('Passing of parameters', function() { before(function() { var config = {options: {port: 3001, webworker: false} }; testapi.server(config); }) it('should accept parameters in REST style', function(done) { request('http://localhost:3001/api/test/multipleParams/param1/param1value/param2/param2value', function (error, res, body) { res.statusCode.should.equal(200); var result = JSON.parse(res.body); result.should.have.property('param1', 'param1value'); result.should.have.property('param2', 'param2value'); result.options.should.have.property('option1', 'bla'); done(); }) }) it('should accept parameters in the querystring', function(done) { request('http://localhost:3001/api/test/multipleParams?param1=param1value&param2=param2value', function (error, res, body) { res.statusCode.should.equal(200); var result = JSON.parse(res.body); result.should.have.property('param1', 'param1value'); result.should.have.property('param2', 'param2value'); result.options.should.have.property('option1', 'bla'); done(); }) }) it('should accept parameters in the querystring as a single config', function(done) { var config = {param1: "param1value", param2: "param2value"}; var configInUrl = encodeURI(JSON.stringify(config)); request('http://localhost:3001/api/test/multipleParams?config=' + configInUrl, function (error, res, body) { res.statusCode.should.equal(200); var result = JSON.parse(res.body); result.should.not.have.property('err'); result.should.have.property('param1', 'param1value'); result.should.have.property('param2', 'param2value'); result.options.should.have.property('option1', 'bla'); done(); }) }) it('should accept config in the body of a POST x-www-form-urlencoded', function(done) { var config = {param1: "param1value", param2: "param2value"}; request({method: 'POST', url: 'http://localhost:3001/api/test/multipleParamsPosted', form: config}, function (error, res, body) { res.statusCode.should.equal(200); var result = JSON.parse(res.body); result.should.have.property('param1', 'param1value'); result.should.have.property('param2', 'param2value'); result.options.should.have.property('option1', 'bla'); done(); }) }) it('should accept config in the body of a POST as single config param', function(done) { var config = {param1: "param1value", param2: "param2value", options: {'option1': 'bar'} }; request({method: 'POST', url: 'http://localhost:3001/api/test/multipleParamsPosted', json: config}, function (error, res, body) { res.statusCode.should.equal(200); var result = res.body; result.should.have.property('param1', 'param1value'); result.should.have.property('param2', 'param2value'); result.options.should.have.property('option1', 'bar'); done(); }) }) it('should not remember config from last time', function(done) { var config = {param1: "param1value"}; request({method: 'POST', url: 'http://localhost:3001/api/test/multipleParamsPosted', json: config}, function (error, res, body) { res.statusCode.should.equal(200); var result = res.body; result.should.have.property('err'); done(); }) }) after(function() { var config = {command: 'stop', options: {webworker: false} }; testapi.server(config, function() { //should stop the server }) }) })
// function diabloApi($scope, $http) { // var url = 'https://eu.api.battle.net/d3/profile/mac-2679/?callback=JSON_CALLBACK'; // $http.jsonp(url).success(function(data) { // $scope.diablo = data; // }); // } // function Hello($scope, $http) { // $http.jsonp('https://eu.api.battle.net/d3/profile/mac-2679/'). // success(function(data) { // $scope.greeting = data; // }); // } // $(function () { // var apiKey = 'mgqy8nb6nfktdw39q5mm7de2jwjpqcc7'; // $.getJSON('https://eu.api.battle.net/d3/profile/mac-2679/?locale=en_GB&apikey=mgqy8nb6nfktdw39q5mm7de2jwjpqcc7') // }); // var apikey = "mgqy8nb6nfktdw39q5mm7de2jwjpqcc7"; // var baseUrl = "https://eu.api.battle.net/d3/profile/mac-2679/?locale=en_GB&apikey="; // // construct the uri with our apikey // var moviesSearchUrl = baseUrl + apikey; // var query = "battleTag"; // $(document).ready(function() { // // send off the query // $.ajax({ // url: moviesSearchUrl, // dataType: "jsonp", // success: searchCallback // }); // }); // // callback for when we get back the results // function searchCallback(data) { // $(document.body).append('Found ' + data.total + ' results for ' + query); // var movies = data.movies; // $.each(movies, function(index, movie) { // $(document.body).append('<h1>' + movie.title + '</h1>'); // $(document.body).append('<img src="' + movie.posters.thumbnail + '" />'); // }); // }
/* eslint-disable react/prop-types */ const React = require('react'); function Footer(props) { const { config, language } = props; const { baseUrl, docsUrl } = config; const docUrl = (doc) => { const docsPart = `${docsUrl ? `${docsUrl}/` : ''}`; return `${baseUrl}${docsPart}${doc}`; }; const pageUrl = (doc) => baseUrl + (language ? `${language}/` : '') + doc; return ( <footer className="nav-footer" id="footer"> <section className="sitemap"> <a href={baseUrl} className="nav-home"> {config.footerIcon && ( <img src={baseUrl + config.footerIcon} alt={config.title} width="52" height="52" /> )} </a> <div> <h5>Docs</h5> <a href={docUrl('getting-started.html')}>Getting Started</a> <a href={docUrl('configuration.html')}>API Reference</a> <a href={docUrl('continuous-integration.html')}>Guides</a> </div> <div> <h5>Community</h5> <a href={pageUrl('users.html')}>User Showcase</a> </div> <div> <h5>More</h5> <a href="https://github.com/oblador/loki">GitHub</a> <a className="github-button" href={config.repoUrl} data-icon="octicon-star" data-count-href="/oblador/loki/stargazers" data-show-count="true" data-count-aria-label="# stargazers on GitHub" aria-label="Star this project on GitHub" > Star </a> {config.twitterUsername && ( <div className="social"> <a href={`https://twitter.com/${config.twitterUsername}`} className="twitter-follow-button" > Follow @{config.twitterUsername} </a> </div> )} {config.facebookAppId && ( <div className="social"> <div className="fb-like" data-href={config.url} data-colorscheme="dark" data-layout="standard" data-share="true" data-width="225" data-show-faces="false" /> </div> )} </div> </section> <section className="copyright">{config.copyright}</section> </footer> ); } module.exports = Footer;
;(function() { function inventaris(id) { // URL of the Search API this.API_URL = '/gressus/data/bomeninventaris.json'; // The results within the JSON-object // Initialize App this.init = function() { console.log('1. Initialize the app'); this.loadData(); } // Load the data from the API (iTunes) this.loadData = function() { // Hack --> Closure var that = this; console.log('2. Load the Data'); // Define a XMLHttpRequest object in order to load data var xhr = new XMLHttpRequest(); // 2.1. Open a connection to the API // get verb: Get the information from the end-point (READ execution) // Third option means asynchronous action or not xhr.open('get', this.API_URL, true); // 2.2. Settings xhr.responseType = 'json'; // 2.3. Listeners // 2.3.1. onload: i received something that's not an error xhr.onload = function() { if (xhr.status == 200){ // Get the loaded data var data = (!xhr.responseType)?JSON.parse(xhr.response):xhr.response; // Get the real results from iTunes that.results = data.query.results.json.results; // Call the updateUI() function that.updateUI(); }; } // 2.3.2. onload: i received an error xhr.onerror = function() { console.log('Error'); }; // 2.4. Send the request xhr.send(); }; // Update the User Interface (UI) this.updateUI = function() { console.log('3. Update UI'); this.generateTableUI(); }; // Generate the albums as a table with rows this.generateTableUI = function() { console.log('4. Generate UI with table-element'); }; }; // Make an instance of the ITunesApp var app = new inventaris(); // Initialize the app app.init(); })();
// @flow import { call, takeLeading } from 'redux-saga/effects'; import testSaga from 'testSaga'; function identity(value) { return value; } function* otherBackgroundSaga(value) { yield call(identity, value + 1); } function* backgroundSaga(value) { yield call(identity, value); } function* otherSaga() { yield call(identity, 42); } function* mainSaga() { yield takeLeading('FOO', backgroundSaga, 42); } test('handles takeLeading effect', () => { testSaga(mainSaga) .next() .takeLeading('FOO', backgroundSaga, 42); }); test('throws if wrong pattern', () => { expect(_ => { testSaga(mainSaga) .next() .takeLeading('BAR', backgroundSaga, 42); }).toThrow(); }); test('throws if wrong saga', () => { expect(_ => { testSaga(mainSaga) .next() .takeLeading('FOO', otherBackgroundSaga, 42); }).toThrow(); }); test('throws if args are wrong', () => { expect(_ => { testSaga(mainSaga) .next() .takeLeading('FOO', backgroundSaga, 43); }).toThrow(); }); test('throws if different effect', () => { expect(_ => { testSaga(otherSaga) .next() .takeLeading('FOO', backgroundSaga, 42); }).toThrow(); });
import React, { PropTypes } from "react"; import shallowCompare from "react-addons-shallow-compare"; import classNames from "classnames"; import StatsSubscription from "../../subscriptions/subscription/stats"; import { Link, Icon, SiteIcon, Time } from "../common"; import StatsList from "./stats-list"; import StatsChartList from "./stats-chart-list"; import LinkList from "./link-list"; export default class StatsSubscriptionItem extends React.Component { static propTypes = { subscription: PropTypes.instanceOf(StatsSubscription).isRequired, item: PropTypes.object.isRequired, }; constructor(props) { super(props); this.state = { expanded: false }; this.handleExpand = this.handleExpand.bind(this); } shouldComponentUpdate(nextProps, nextState) { return shallowCompare(this, nextProps, nextState); } handleExpand() { this.setState({ expanded: !this.state.expanded }); } render() { const { subscription, item } = this.props; const { expanded } = this.state; const statsLog = subscription.statsLogs[item.id]; const cls = "stats-subscription-item"; // Prefix for className return ( <article className={classNames({ [cls]: true, [`${cls}--expandable`]: statsLog.timestamps.length > 1, [`${cls}--collapsed`]: !expanded, [`${cls}--expanded`]: expanded, })} onClick={this.handleExpand} > <header className={`${cls}__header`}> <h1 className={`${cls}__title`}> <SiteIcon name={subscription.siteId} /> {" "} <Link href={item.url} title={item.title} /> </h1> </header> {statsLog && <div className={`${cls}__body`}> {expanded && <div className={`${cls}__chart`}> <StatsChartList stats={item.stats} statsLog={statsLog} /> </div> } <StatsList stats={item.stats} statsLog={statsLog} /> </div> } <footer className={`${cls}__footer`}> <ul className={`${cls}__footer-right`}> {subscription.lastUpdatedAt && <li className={`${cls}__time`}> <Icon name="clock-o" /> <Time value={subscription.lastUpdatedAt} /> </li> } </ul> <div className={`${cls}__footer-left`}> {item.links && <LinkList links={item.links} /> } </div> </footer> </article> ); } }
const webdriver = require('selenium-webdriver'); const chrome = require('selenium-webdriver/chrome'); const firefox = require('selenium-webdriver/firefox'); const CHROMEDRIVER = 'chromedriver'; const BROWSERSTACK = 'browserstack'; const FIREFOXDRIVER = 'geckodriver'; function baseDriver(capabilities) { const builtDriver = new webdriver.Builder(); if (capabilities && capabilities.browserName) { builtDriver.forBrowser(capabilities.browserName); } builtDriver.withCapabilities(capabilities || webdriver.Capabilities.chrome()); if (capabilities && capabilities.args) { if (capabilities.browserName === 'chrome') { builtDriver.setChromeOptions(new chrome.Options().addArguments(capabilities.args)); } else if (capabilities.browserName === 'firefox') { builtDriver.setFirefoxOptions(new firefox.Options().addArguments(capabilities.alwaysMatch['moz:firefoxOptions'].args)); } } return builtDriver.build(); } function buildLocalMobile(framework) { delete framework.useMobile; const driver = new webdriver.Builder() .usingServer('http://localhost:4723/wd/hub') .withCapabilities(framework.capabilities) .build() return driver; } function defaultDriver(capabilities) { const driver = baseDriver(capabilities); return driver; } function buildRemoteHost(framework) { const driver = new webdriver.Builder() .usingServer(framework.server) .withCapabilities(framework.capabilities) .build(); driver.framework = BROWSERSTACK; return driver; } function buildSimple(framework) { const capabilities = framework && framework.capabilities; const baseDriverBuilt = defaultDriver(capabilities); baseDriverBuilt.framework = framework || CHROMEDRIVER; return baseDriverBuilt; } const frameworks = { get(framework) { return buildSimple(framework); }, getLocalMobile(framework) { return buildLocalMobile(framework); }, getRemoteHost(framework) { return framework.size ? buildSimple(framework) : buildRemoteHost(framework); }, }; module.exports = frameworks;
angular.module('hslApp') .directive('createRecipeDirective', function() { return { restrict: 'E', templateUrl: 'js/directives/create-recipe/create-recipe.tpl.html', scope:{ title: "=", recipe: "=" }, controller: function($scope, $rootScope, $location, ingredientFactory, recipeFactory, tagFactory, unitService, cacheService) { $scope.ingredients = []; $scope.selectedIngredient; $scope.units = unitService.getUnits(); $scope.fileUploadMethod = 'button'; $scope.severities = [ {name: "Lätt", id: 1}, {name: "Medel", id: 2}, {name: "Svår", id: 3} ]; $scope.getMatchingTags = function(searchText){ return tagFactory.query({search: searchText}).$promise; } $scope.formSubmit = function(){ if($scope.form.$valid){ if($scope.recipe.id){ $scope.recipe.$update().then(function(data){ if(data){ $scope.recipe = data; cacheService.update(null, $scope.recipe); $rootScope.globalInfo = { message: "Recept uppdaterat!", show: true, code: 'info' }; } else{ $rootScope.globalInfo = { message: "Det gick inte att uppdatera receptet", show: true, code: 'warning' }; } }); return; } $scope.recipe.CreatedBy = $rootScope.user.id; $scope.recipe.$save().then(function(){ $rootScope.globalInfo = { message: "Sparat!", show: true, code: 'info' }; $location.path('/admin/recipes'); cacheService.update('all', $scope.recipe); }); } } $scope.delete = function(){ recipeFactory.delete({'Id': $scope.recipe.id}).$promise.then(function(){ $rootScope.globalInfo = { message: "Recept borttaget", show: true, code: 'info' }; $location.path('/admin/recipes'); }); } $scope.getIngredientsMatch = function(searchText){ $scope.loading = true; return ingredientFactory.query({search: searchText}).$promise.then(function(data){ $scope.loading = false; return data; }); }; $scope.setIngredient = function(ingredient){ $scope.selectedIngredient = ingredient; }; $scope.removeIngredient = function(ingredient){ var index = $scope.recipe.ingredients.indexOf(ingredient) $scope.recipe.ingredients.splice(ingredient, 1); } $scope.addIngredientToList = function(){ if(!$scope.recipe.ingredients){ $scope.recipe.ingredients = []; } if($scope.selectedIngredient != null){ if($scope.recipe.ingredients.indexOf($scope.selectedIngredient) > -1){ $rootScope.globalInfo = { message: "Det går inta att ha samma ingrediens två gånger", show: true, code: 'warning' }; return; } $scope.recipe.ingredients.unshift($scope.selectedIngredient); $scope.selectedIngredient = null; $scope.ingredientObject = null; return } if($scope.ingredientObject){ $scope.recipe.ingredients.unshift({name: $scope.ingredientObject, id: "00000000-0000-0000-0000-000000000000"}); $scope.ingredientObject = null; } } } }; });
define([ "Phase" ], function(Phase) { "use strict"; var Store = {}; Store.InitialState = function() { return ( { round: 0, phaseKey: Phase.SETUP, // cardInstance IDs. questDeckIds: [], questDiscardIds: [], // cardInstance IDs. encounterDeckIds: [], encounterDiscardIds: [], // cardInstance ID. activeLocationId: undefined, // cardInstance ID. activeQuestId: undefined, // cardInstance IDs. stagingAreaIds: [], // agent IDs. agentIds: [], // agent ID. activeAgentId: undefined, // agent ID. firstAgentId: undefined, // //////////////////////////////////////////////////////////////// // Dictionaries. agents: { // id: agent }, cardInstances: { // id: cardInstance }, }); }; return Store; });
import mappings from '../lib/map'; import getData from '../../../../util/getData'; import { usePostCSSPlugin, processCSSFactory, } from '../../../../util/testHelpers'; import plugin from '..'; const { processCSS, passthroughCSS } = processCSSFactory(plugin); const data = getData(mappings); test( 'should pass through two value syntax', passthroughCSS('background:space round') ); function suite(fixture, expected) { return () => Promise.all([ processCSS( `background:#000 url(cat.jpg) ${fixture} 50%`, `background:#000 url(cat.jpg) ${expected} 50%` ), processCSS( `background-repeat:${fixture}`, `background-repeat:${expected}` ), processCSS( `background-repeat:#000 url(cat.jpg) ${fixture} 50%,#000 url(cat.jpg) ${fixture} 50%`, `background-repeat:#000 url(cat.jpg) ${expected} 50%,#000 url(cat.jpg) ${expected} 50%` ), processCSS( `background-repeat:${fixture},${fixture}`, `background-repeat:${expected},${expected}` ), processCSS(`mask-repeat:${fixture}`, `mask-repeat:${expected}`), ]); } Object.keys(data).forEach((conversion) => { const fixture = data[conversion]; test(fixture, suite(fixture, conversion)); }); test( 'should normalize uppercase property and value', processCSS( 'BACKGROUND:#000 url(cat.jpg) REPEAT NO-REPEAT 50%', 'BACKGROUND:#000 url(cat.jpg) repeat-x 50%' ) ); test( 'should pass through when there are no repeat values', passthroughCSS('background:url(cat.jpg)') ); test( 'should pass through when there are no repeat values (2)', passthroughCSS('background:#000 url(cat.jpg)') ); test( 'should pass through the single value syntax', passthroughCSS('background:#000 url(cat.jpg) repeat') ); test( 'should pass through with var', passthroughCSS('background-repeat: var(--foo)') ); test( 'should pass through with var #1', passthroughCSS('background-repeat: center var(--foo)') ); test( 'should pass through with var #2', passthroughCSS('background-repeat: right 100px var(--test)') ); test( 'should pass through with var #3', passthroughCSS('background: var(--foo)') ); test( 'should pass through with var #4', passthroughCSS( 'background: url("../../media/examples/star.png") center var(--foo);' ) ); test( 'should pass through with env', passthroughCSS('background-position: env(--foo)') ); test( 'should normalize background position with var and multiple background', processCSS( 'background: url("/media/examples/lizard.png") repeat no-repeat, url("/media/examples/lizard.png") var(--foo)', 'background: url("/media/examples/lizard.png") repeat-x, url("/media/examples/lizard.png") var(--foo)' ) ); test( 'should normalize background position with var and multiple background #1', processCSS( 'background: url("/media/examples/lizard.png") var(--foo), url("/media/examples/lizard.png") repeat no-repeat', 'background: url("/media/examples/lizard.png") var(--foo), url("/media/examples/lizard.png") repeat-x' ) ); test( 'should normalize background position with var and multiple background #2', processCSS( 'background: url("/media/examples/lizard.png") repeat no-repeat, url("/media/examples/lizard.png") repeat var(--foo)', 'background: url("/media/examples/lizard.png") repeat-x, url("/media/examples/lizard.png") repeat var(--foo)' ) ); test( 'should normalize background position with var and multiple background #3', processCSS( 'background: url("/media/examples/lizard.png") repeat var(--foo), url("/media/examples/lizard.png") repeat no-repeat', 'background: url("/media/examples/lizard.png") repeat var(--foo), url("/media/examples/lizard.png") repeat-x' ) ); test('should use the postcss plugin api', usePostCSSPlugin(plugin()));
var webpack = require('webpack'); var ejs = require('ejs'); var MIN = process.argv.indexOf('-p') > -1; function getBanner() { var pkg = require('./bower.json'); var banner = ['/**', ' * <%= pkg.name %> - <%= pkg.description %>', ' * @version v<%= pkg.version %>', ' * @link <%= pkg.homepage %>', ' * @license <%= pkg.license %>', ' */', ''].join('\n'); return ejs.render(banner, {pkg: pkg}); } module.exports = { entry: __dirname + '/src/angular-bootstrap-confirm.js', output: { path: __dirname + '/dist', filename: MIN ? 'angular-bootstrap-confirm.min.js' : 'angular-bootstrap-confirm.js', libraryTarget: 'umd' }, externals: { angular: 'angular', 'angular-sanitize': 'angular-sanitize', './ui-bootstrap-position': 'angular' }, devtool: MIN ? 'source-map' : null, module: { preLoaders: [{ test: /.*\.js$/, loaders: ['eslint'], exclude: /node_modules/ }], loaders: [{ test: /.*\.js$/, loaders: ['ng-annotate'], exclude: /node_modules/ }] }, plugins: [ new webpack.NoErrorsPlugin(), new webpack.BannerPlugin(getBanner(), { raw: true, entryOnly: true }) ] };
'use strict' let usuarios = [] let sesiones = [] module.exports = { usarSeguridad: usarSeguridad, existeUsuario: existeUsuario, crearUsuario: crearUsuario, esUsuarioValido: esUsuarioValido, esSesionValida: esSesionValida, getSesion: getSesion, nuevaSesion: nuevaSesion } function usarSeguridad(app, ruta) { app.use(ruta, (req, res, next) => { let sessionId = req.get('sessionId') let sesion = getSesion(sessionId) if (sesion) { if (esSesionValida(sesion)) { sesion.timeStamp = new Date() req.usuario = sesion.email next() } else { console.log(`Sesión caducada: ${JSON.stringify(sesion)}`) // Sintaxis mejorada de envío de códigos de estado http res.status(419).send('Sesión caducada') } } else { res.status(401).send('Credencial inválida') } }) } function existeUsuario(usuario) { return usuarios.some(u => u.email == usuario.email) } function crearUsuario(usuario) { usuarios.push(usuario) } function esUsuarioValido(usuario) { return usuarios.filter(u => u.email == usuario.email && u.password == usuario.password)[0] } function getSesion(sessionId) { return sesiones.filter(s => s.sessionId == sessionId)[0] } function esSesionValida(sesion) { return (new Date() - sesion.timeStamp) < 20 * 60 * 1000 } function nuevaSesion(email) { let sessionId = Math.random() * (88888) + 11111 let timeStamp = new Date() sesiones.push({ sessionId: sessionId, email: email, timeStamp: timeStamp }) return sessionId }
export function toNumber( numeric, fallback ) { return isNaN( numeric ) ? ( fallback || 0 ) : Number( numeric ); } export function translate( data ) { return ' translate3d(' + toNumber(data.x) + 'px, ' + toNumber(data.y) + 'px, ' + toNumber(data.z) + 'px)'; } export function rotate( data, revert ) { let rX = " rotateX(" + toNumber(data.rotateX) + "deg) ", rY = " rotateY(" + toNumber(data.rotateY) + "deg) ", rZ = " rotateZ(" + toNumber(data.rotateZ) + "deg) "; return revert ? rZ + rY + rX : rX + rY + rZ; } export function scale( data ) { return ' scale(' + toNumber(data, 1) + ')' ; } export function perspective( p ) { return " perspective(" + p + "px) "; } export function computeWindowScale( config ) { let hScale = window.innerHeight / config.height, wScale = window.innerWidth / config.width, scale = hScale > wScale ? wScale : hScale; if ( config.maxScale && scale > config.maxScale ) { scale = config.maxScale; } if ( config.minScale && scale < config.minScale ) { scale = config.minScale; } return scale; } export const pfx = ( () => { let style = document.createElement( "dummy" ).style, prefixes = "Webkit Moz O ms Khtml".split( " " ), memory = {}; return ( prop ) => { if ( typeof memory[ prop ] === "undefined" ) { let ucProp = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ), props = ( prop + " " + prefixes.join( ucProp + " " ) + ucProp ).split( " " ); memory[ prop ] = null; for ( let i in props ) { if ( style[ props[ i ] ] !== undefined ) { memory[ prop ] = props[ i ]; break; } } } return memory[ prop ]; }; })(); export function css( el, props ) { for ( let key in props ) { if ( props.hasOwnProperty( key ) ) { let pkey = pfx( key ); if ( pkey !== null ) { el.style[ pkey ] = props[ key ]; } } } return el; } export function throttle( fn, delay ) { let timer = null; return function() { let context = this, args = arguments; clearTimeout( timer ); timer = setTimeout( function() { fn.apply( context, args ); }, delay ); }; } export function getElementFromHash( stepsData ) { let id = window.location.hash.replace( /^#\/?/, "" ); return stepsData[ id ]; }
/** * Created by BK on 06.06.17. */ export default class Fartometer extends Phaser.Graphics { constructor(game, fartometer, x, y, width, height, player) { super(game, x, y); this.game = game; this.fartometerFactor = 2.5; this.fartometerHeight = height; this.lineWidth = 2; this.player = player; this.draw(fartometer); } draw(fartometer, fartometerMax) { const fartometerWidth = fartometerMax * this.fartometerFactor; const progressX = fartometerWidth * (fartometer / fartometerMax); this.lineStyle(this.lineWidth, 0xFFFFFF); this.drawRect(0, 0, fartometerWidth, this.fartometerHeight); this.lineStyle(0); this.beginFill(0x44cc44); this.drawRect(0, 0, progressX, this.fartometerHeight); this.endFill(); this.beginFill(0xCCCCCC); this.drawRect(progressX, 0, fartometerWidth - progressX, this.fartometerHeight); this.endFill(); } }
const initialState = {}; const dashboard = (state = initialState, action) => { switch (action.type) { default: return state; } }; export default dashboard;
(function(N) { N.Map = function(opts) { self = this; self.directionsService = new google.maps.DirectionsService(); self.directionsDisplay = new google.maps.DirectionsRenderer(); var mapOptions = { center: new google.maps.LatLng(39.875, -75.238), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map"),mapOptions), traffic = new google.maps.TrafficLayer(); traffic.setMap(map); self.directionsDisplay.setMap(map); // Update the travel times every minute // TODO: Make a factor of time-until (less frequent early) setInterval($.proxy(self.calculateRoute,self), 60 * 3 * 1000); }; N.Map.prototype.calculateRoute = function() { var self = this, start = $('#addr').val(), end = "Philadelphia International Airport", request = { origin: start, destination: end, travelMode: google.maps.TravelMode.DRIVING }; self.directionsService.route(request, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { self.directionsDisplay.setDirections(result); self.trigger('route-time-update', result.routes[0].legs[0]); } }); }; _.extend(N.Map.prototype, Backbone.Events); }(this));
/** * Created with IntelliJ IDEA. * User: Atlas * Date: 10/7/14 * Time: 4:05 AM */ // Code that doesn't need data can go here var WIDTH = 700, HEIGHT = 500; var margin = {top: 20, right: 20, bottom: 20, left: 80 }; var W = WIDTH - margin.left - margin.right; var H = HEIGHT - margin.top - margin.bottom; var svg = d3.select("#svgcanvas").append("svg") .attr("width", WIDTH) .attr("height", HEIGHT); //This function is called when the data is loaded var dataReady = function(error, data) { console.log("Data: "+JSON.stringify(data)); console.log("Max: "+ d3.max(data, function(d) { return d.sales; }) ); // Set the ranges (including the margins) - the domain is set once we have the data var x = d3.time.scale() .domain([new Date(2014,0,1), new Date(2014,11,31)]) .range([margin.left, W]); var y = d3.scale.linear() .domain([0,d3.max(data, function(d) { return d.sales; })]) .range([H, margin.top]); //The rects for bars - note that these are drawn from the top to the bottom svg.selectAll("rect") .data(data) .enter() .append("rect") .attr("x",function(d,i) {return x(new Date(2014,i,1));}) .attr("y", function(d) {return y(d.sales);}) //the top of the bar .attr("width", 20) .attr("height", function(d) {return H - y(d.sales);}) //the length of the bar .style("fill","navy"); //Circle to mark the actual data points svg.selectAll("circle") .data(data) .enter() .append("circle") .attr("cx", function(d,i) {return x(new Date(2014,i,1));}) .attr("cy", function(d) {return y(d.sales);}) .attr("r", 4) .style("fill","orange"); // Create the axes var xAxis = d3.svg.axis() .scale(x) .orient("bottom") .ticks(d3.time.months) .tickSize(16,0) .tickFormat(d3.time.format("%b")); var yAxis = d3.svg.axis() .scale(y) .orient("left") .ticks(7) .tickSize(16,0); // Add the axes svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + H + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .attr("transform", "translate(" + margin.left + ",0)") .call(yAxis); // Add a title svg.append("text") .attr("class","chartTitle") .attr("x", W/2) .attr("y", margin.top) .attr("text-anchor","middle") .text("Sales by Month"); } //Load the data - the anon function ensure the type for sales is a number d3.csv("data/myData.csv", function(d) { return {month: d.month, sales: +d.sales};}, dataReady);
// @flow import React from 'react' import {Text} from 'react-native' import TabbarIcon from './components/TabbarIcon' export default class MeScreen extends React.Component { static navigationOptions = { tabBar: { label: 'Me', icon: ({tintColor}) => <TabbarIcon name="user" color={tintColor} /> } } render () { return (<Text>MeScreen</Text>) } }
var path = require('path') var config = require('../config') var ExtractTextPlugin = require('extract-text-webpack-plugin') exports.assetsPath = function (_path) { var assetsSubDirectory = process.env.NODE_ENV === 'production' ? config.build.assetsSubDirectory : config.dev.assetsSubDirectory return path.posix.join(assetsSubDirectory, _path) } exports.cssLoaders = function(options) { options = options || {} // generate loader string to be used with extract text plugin function generateLoaders(loaders) { var sourceLoader = loaders.map(function(loader) { var tempLoader, loaderName var loaderOptions = loader.split('?') loaderName = loaderOptions[0] if (!/-loader/.test(loaderName)) loaderName += '-loader' tempLoader = { loader: loaderName, options: { sourceMap: options.sourceMap } } if (loaderOptions.length > 1) { tempLoader.options[loaderOptions.pop()] = true } return tempLoader }) // Extract CSS when that option is specified // (which is the case during production build) if (options.extract) { var extractLoader = sourceLoader.map(function(loader) { return loader.loader }) return ExtractTextPlugin.extract({ fallback: 'vue-style-loader', use: extractLoader }) } else { return [{ loader: 'vue-style-loader' }].concat(sourceLoader) } } // http://vuejs.github.io/vue-loader/en/configurations/extract-css.html return { css: generateLoaders(['css']), postcss: generateLoaders(['css', 'postcss']), less: generateLoaders(['css', 'less']), sass: generateLoaders(['css', 'sass?indentedSyntax']), scss: generateLoaders(['css', 'sass']), stylus: generateLoaders(['css', 'stylus']), styl: generateLoaders(['css', 'stylus']) } } // Generate loaders for standalone style files (outside of .vue) exports.styleLoaders = function(options) { var output = [] var loaders = exports.cssLoaders(options) for (var extension in loaders) { var loader = loaders[extension] var tempLoader = {} tempLoader.test = new RegExp('\\.' + extension + '$') options.extract ? (tempLoader.use = loader) : (tempLoader.loader = loader) output.push(tempLoader) } return output }
import { CALL_API, Schemas } from '../middleware/api.mdw'; export const USER_REQUEST = 'USER_REQUEST'; export const USER_SUCCESS = 'USER_SUCCESS'; export const USER_FAILURE = 'USER_FAILURE'; function getActionState(getState) { return getState().github; } // Fetches a single user from Github API. // Relies on the custom API middleware in ../middleware/api.js. function fetchUser(login) { return { [CALL_API]: { types: [ USER_REQUEST, USER_SUCCESS, USER_FAILURE ], endpoint: 'users/' + login, schema: Schemas.USER } } } export function loadUser(login, requiredFields = []) { return (dispatch, getState) => { const user = getActionState(getState).entities.users[login]; if (user && requiredFields.every( key => user.hasOwnProperty(key) )) { return null; } return dispatch(fetchUser(login)); } } export const REPO_REQUEST = 'REPO_REQUEST'; export const REPO_SUCCESS = 'REPO_SUCCESS'; export const REPO_FAILURE = 'REPO_FAILURE'; function fetchRepo(fullName) { return { [CALL_API]: { types: [ 'REPO_REQUEST', 'REPO_SUCCESS', 'REPO_FAILURE' ], endpoint: 'repos/' + fullName, schema: Schemas.REPO } } } export function loadRepo(fullName, requiredFields = []) { return (dispatch, getState) => { const repo = getActionState(getState).entities.repos[fullName]; if (repo && requiredFields.every( key => repo.hasOwnProperty(key) )) { return null; } return dispatch(fetchRepo(fullName)); } } export const STARRED_REQUEST = 'STARRED_REQUEST'; export const STARRED_SUCCESS = 'STARRED_SUCCESS'; export const STARRED_FAILURE = 'STARRED_REQUEST'; function fetchStarred(login, nextPageUrl) { return { login, [CALL_API]: { types: [ STARRED_REQUEST, STARRED_SUCCESS, STARRED_FAILURE ], endpoint: nextPageUrl, schema: Schemas.REPO_ARRAY } } } export function loadStarred(login, nextPage) { return (dispatch, getState) => { const { nextPageUrl = `users/${login}/starred`, pageCount = 0 } = getActionState(getState).pagination.starredByUser[login] || {}; if (pageCount > 0 && !nextPage) { return null; } return dispatch(fetchStarred(login, nextPageUrl)); } } export const STARGAZERS_REQUEST = 'STARGAZERS_REQUEST'; export const STARGAZERS_SUCCESS = 'STARGAZERS_SUCCESS'; export const STARGAZERS_FAILURE = 'STARGAZERS_FAILURE'; function fetchStargazers(fullName, nextPageUrl) { return { fullName, [CALL_API]: { types: [ STARGAZERS_REQUEST, STARGAZERS_SUCCESS, STARGAZERS_SUCCESS ], endpoint: nextPageUrl, schema: Schemas.USER_ARRAY } } } export function loadStargazers(fullName, nextPage) { return (dispatch, getState) => { const { nextPageUrl = `repos/${fullName}/stargazers`, pageCount = 0 } = getActionState(getState).pagination.stargazersByRepo[fullName] || {}; if (pageCount > 0 && !nextPage) { return null; } return dispatch(fetchStargazers(fullName, nextPageUrl)); } } export const RESET_ERROR_MESSAGE = 'RESET_ERROR_MESSAGE'; export function resetErrorMessage() { return { type: RESET_ERROR_MESSAGE } }
'use strict' // prevent passport from monkey patching const connect = require('passport/lib/framework/connect') connect.__monkeypatchNode = function() {} // load passport and add the koa framework const passport = require('passport') const Passport = require('passport').Passport const framework = require('./framework/koa')() passport.framework(framework) class KoaPassport extends Passport { constructor() { super() this.framework(framework) } } // Export default singleton. module.exports = passport // Expose constructor module.exports.KoaPassport = KoaPassport
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Autodesk, Inc. All rights reserved // Written by Philippe Leefsma 2014 - ADN/Developer Technical Services // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. /////////////////////////////////////////////////////////////////////////////// AutodeskNamespace("Autodesk.ADN.Viewing.Extension"); Autodesk.ADN.Viewing.Extension.MongoDbPanel = function (viewer) { _self = this; this.viewer = viewer; Autodesk.Viewing.Extensions.ViewerPropertyPanel.call( this, this.viewer); _self.setNodeProperties = function (nodeId) { Autodesk.Viewing.Extensions.ViewerPropertyPanel.prototype.setNodeProperties.call( _self, nodeId); _self.selectedNodeId = nodeId; }; _self.setProperties = function (properties) { Autodesk.Viewing.Extensions.ViewerPropertyPanel.prototype.setProperties.call( _self, properties); this.viewer.getPropertyValue(_self.selectedNodeId, "ProductId", function (productId) { if (productId !== 'undefined') { var url = 'http://' + window.location.host + '/node/mongo/api/product/' + productId; $.getJSON(url, function (data) { var product = data.product; var category = "MongoDb Data"; _self.addProperty("Product Name", product.Name, category); _self.addProperty("Supplier Name", product.SupplierName, category); _self.addProperty("Price", product.Price, category); _self.addProperty("Currency", product.Currency, category); //_self.addProperty("Description", product.Description, category); }); } }); }; }; Autodesk.ADN.Viewing.Extension.MongoDbPanel.prototype = Object.create(Autodesk.Viewing.Extensions.ViewerPropertyPanel.prototype); Autodesk.ADN.Viewing.Extension.MongoDbPanel.prototype.constructor = Autodesk.ADN.Viewing.Extension.MongoDbPanel; Autodesk.ADN.Viewing.Extension.MongoDbPanelExtension = function (viewer, options) { // base constructor Autodesk.Viewing.Extension.call(this, viewer, options); var _viewer = viewer; var _self = this; /////////////////////////////////////////////////////////////////////////// // load callback // /////////////////////////////////////////////////////////////////////////// _self.load = function () { console.log('Autodesk.ADN.Viewing.Extension.MongoDbPanelExtension loaded'); var panel = new Autodesk.ADN.Viewing.Extension.MongoDbPanel(_viewer); _viewer.setPropertyPanel(panel); viewer.refreshPropertyPanel = function () { panel.setVisible(false, true); panel.setVisible(true, true); } return true; }; /////////////////////////////////////////////////////////////////////////// // unload callback // /////////////////////////////////////////////////////////////////////////// _self.unload = function () { var panel = new Autodesk.Viewing.Extensions.ViewerPropertyPanel( _viewer); _viewer.setPropertyPanel(panel); return true; }; }; Autodesk.ADN.Viewing.Extension.MongoDbPanelExtension.prototype = Object.create(Autodesk.Viewing.Extension.prototype); Autodesk.ADN.Viewing.Extension.MongoDbPanelExtension.prototype.constructor = Autodesk.ADN.Viewing.Extension.MongoDbPanelExtension; Autodesk.Viewing.theExtensionManager.registerExtension( 'Autodesk.ADN.Viewing.Extension.MongoDbPanelExtension', Autodesk.ADN.Viewing.Extension.MongoDbPanelExtension);
import Parse from 'parse'; let reduxStore = null; export function logout () { Parse.User.logOut(); } export function initializeParseToRedux(_store) { if( !reduxStore ){ reduxStore = _store; } const cookieStoredUser = Parse.User.current(); if( cookieStoredUser ){ console.log( cookieStoredUser ) let query = new Parse.Query(Parse.Role); query.find().then(data=>{ console.log('roles ==> ', data.getUsers() ); }) const loginUser = cookieStoredUser.toJSON(); reduxStore.dispatch({ type: 'UPDATE_LOGIN_USER', user: loginUser }); } } export function requestPasswordReset(email, cb) { if (!reduxStore) { throw new Error('Parse-Redux Connector is not initialized!') } Parse.User.requestPasswordReset(email, { success: () => { console.log('Success!!') }, error: (err) => { console.log('error', err) } }); } export function saveUserInfoToParse(email, password, info, cb) { if( !reduxStore ) { throw new Error('Parse-Redux Connector is not initialized!') } Parse.User.logIn(email, password, { success: user => { user.set('nickname', info.nickname); user.set('baby', info.baby); user.save(null, { success: userAgain => { reduxStore.dispatch({ type: 'UPDATE_LOGIN_USER', user: userAgain.toJSON() }); cb && cb({ success: { message: '수정되었습니다' } }); }, error: (userAgain, error ) => { cb && cb({ error: error, message: '정보 수정에 실패했습니다.' }); } }) }, error: ( user, error) => { cb && cb({ error: error, message: '인증된 사용자가 아닙니다. 잘못된 접근입니다.' }); } }) }
const { test } = require('ava'); const envConfig = require('../'); const ENV = { CONFIG_mongo_db: 'mongo.db1', CONFIG__mongo__db: 'mongo.db2', ACONFIG_mongo_db: 'mongo.db3', BCONFIG_mongo_port__number: '3434', CCONFIG_mongo_port__num: '3435', DCONFIG_mongo_flag__boolean: '1', ECONFIG_mongo_flag__bool: '', }; test.before(() => { Object.assign(process.env, ENV); }); test('should load mongo db', (t) => { const config = envConfig(); t.deepEqual(config, { mongo: { db: 'mongo.db1', }, }); }); test('should load mongo db with another separator', (t) => { const config = envConfig({ separator: '__' }); t.deepEqual(config, { mongo: { db: 'mongo.db2', }, }); }); test('should load mongo db with another prefix', (t) => { const config = envConfig({ prefix: 'ACONFIG' }); t.deepEqual(config, { mongo: { db: 'mongo.db3', }, }); }); test('should load mongo port with type number', (t) => { const config = envConfig({ prefix: 'BCONFIG' }); t.deepEqual(config, { mongo: { port: 3434, }, }); }); test('should load mongo db with type num', (t) => { const config = envConfig({ prefix: 'CCONFIG' }); t.deepEqual(config, { mongo: { port: 3435, }, }); }); test('should load mongo db with type bool', (t) => { const config = envConfig({ prefix: 'DCONFIG' }); t.deepEqual(config, { mongo: { flag: true, }, }); }); test('should load mongo db with type boolean', (t) => { const config = envConfig({ prefix: 'ECONFIG' }); t.deepEqual(config, { mongo: { flag: false, }, }); });
/*jslint node: true */ /*global module, require*/ 'use strict'; var ExecutionError = require('../error/execution'); module.exports = function fail(name, value, callback) { if (typeof value === 'function') { callback = value; value = undefined; } if (!this.hasBegun(name)) { return callback && callback(new ExecutionError( 'An item with this name has not yet started.')); } if (this.hasFinished(name)) { return callback && callback(new ExecutionError( 'An item with this name has already completed.')); } this.state.completed[name] = true; this.state.completed[name] = { error: value }; return callback && callback(null); };
/* * James D. Zoll * * 4/22/2013 * * Lens of Truth jQuery plugin. * * This is a simple plugin that overrides the jQuery .data() function * to actually write values out to the DOM when setting them. jQuery by * default stores the values in an internal cache for speed and compatibility * reasons, but this makes it tedious to debug data-attribute related * behavior, particularly on browsers without mature developer tools, since * it can be difficult to grab expando properties on nodes. * * This plugin is very minimal, but should still only be run when debugging. * Data properties will have the string "data-lot" prepended to their name * to prevent jQuery from re-fetching them from the DOM, and to remove * possible DEBUG only behavior. * * Non-string literals passed in will be converted to JSON values before * being added to the DOM, if the browser supports it. In the interest of * being lightweight, browsers that don't have native JSON object will just * print the [object Object] or similar, since jQuery doesn't have a built * in toJson(). */ (function( $ ){ // Prefix for all attributes written to the DOM var attrPrefix = 'data-lot-'; // Store a handle for the old data function. var _oldData = $.fn.data; // We define a function to write out attributes. It will be aware // of both the attrPrefix value and of the reserved names for // data objects that jQuery uses, which will not be written // to the dom. var writeAttr = function(obj, k, v) { if (!(k[0] === '_' || k === 'events' || k === 'handle')) { if (typeof v === 'object' && window.JSON && window.JSON.stringify) { obj.attr(attrPrefix + k, window.JSON.stringify(v)); return; } obj.attr(attrPrefix + k, v); } }; $.fn.data = function(key, value) { // Call the jQuery data function and store the result. // Do this first so that if it raises an exception, we // don't modify the DOM. var result = _oldData.apply(this, arguments); // Now depending on whether we have a key, a key and a value, // or an object, update the DOM appropriately. if (key === undefined) { // Nothing to write, since this was a fetch. return result; } if (typeof key === 'object') { // Multiple values were set, so iterate and // write them all. var elems = this; $.each(key, function(k, v) { writeAttr(elems, k, v); }); return result; } if (value === undefined) { // Nothing to write, since this was a fetch. return result; } // Write the single attribute to the DOM. writeAttr(this, key, value); return result; }; })( jQuery );
$(document).ready(function () { // toggle skin select $("#skin-select #toggle").click(function () { if ($(this).hasClass('active')) { $(this).removeClass('active') $('#skin-select').css({ "width": "260px" }); $('.wrap-fluid').css({ "width": "auto" , "margin-left": "260px" , }); $('#skin-select li').css({ "text-align": "left" }); $('#skin-select li span, .devider-title h3, ul.topnav h4, .side-dash, .noft-blue, .noft-purple-number, .noft-blue-number').css({ "display": "inline-block" , "float": "none" }); $('.ul.topnav h4, .hide-min-toggle').css({ "display": "none" }); $('.tooltip-tip2').addClass('tooltipster-disable'); $('.tooltip-tip').addClass('tooltipster-disable'); $('.datepicker-wrap').css({ "position": "absolute" , "right": "300px" }); $('.skin-part').css({ "visibility": "visible" }); $('#menu-showhide').css({ "height": "auto" , "margin": "-13px 0 0" }); $('#skin-select li i').css({ "top": "0" , "left": "-15px" , "padding": "8px 0" }); $('ul.topnav ul').css({ "border-radius": "0" , "padding": "15px 25px" }); $('img.admin-pic.img-circle').css({ "margin": "20px 0 0 20px" }); $('.profile span, .profile i, .bottom-list-menu li, .chat-list-menu li').css({ "display": "block" }); $(".profile h3").css({ 'display': 'block' }); $(".profile img").css({ 'width': '45px' , 'height': '45px' , 'top': '15px' , 'left': '4px' }); $(".profile").css({ 'top': '-10px' }); $('#menuwrapper').removeAttr('id').addClass(); } else { $(this).addClass('active') $('#skin-select').css({ "width": "50px" }); $('.wrap-fluid').css({ "width": "auto" , "margin-left": "50px" }); $('#skin-select li').css({ "text-align": "right" }); $('#skin-select li span, .devider-title h3, ul.topnav h4, .side-dash, .noft-blue, .noft-purple-number, .noft-blue-number').css({ "display": "none" }); $('.datepicker-wrap').css({ "position": "absolute" , "right": "84px" }); $('.skin-part').css({ "visibility": "visible" }); $('.hide-min-toggle').css({ "display": "block" }); $('#menu-showhide').css({ "margin": "-10px 0px 0px" }); $('#skin-select li i').css({ "top": "0" , "left": "-30px" , "padding": "8px 0" }); $('ul.topnav ul').css({ "border-radius": "0" , "padding": "5px 10px" }); $('ul.topnav ul').removeAttr('style'); $('#menuwrapper ul li ul').css({ "display": "inline-grid!important" }); $('.profile span, .profile i, .bottom-list-menu li, .chat-list-menu li').css({ "display": "none" }); $('img.admin-pic.img-circle').css({ "margin": "18px 0 0 4px" }); $('.accordion-nav').removeAttr('class').addClass('topnav'); $(".side-bar").attr("id", "menuwrapper"); $(".profile h3").css({ 'display': 'none' }); $(".profile img").css({ 'width': '45px' , 'height': '45px' , 'top': '15px' , 'left': '-10px' }); $(".profile").css({ 'top': '-10px' }); } return false; }); // show skin select for a second setTimeout(function () { $("#skin-select #toggle").addClass('active').trigger('click'); }, 10) }); // end doc.ready
'use strict'; var fidemRequestSigner = {}; // Inspiration and documentation // http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html // https://github.com/mhart/aws4 function hmac(key, string, encoding) { return AWS.util.crypto.hmac(key, string, encoding); } function hash(string, encoding) { return AWS.util.crypto.sha256(string, encoding); } function RequestSigner(request, credentials) { if (typeof request === 'string') { request = url.parse(request); } this.request = request; this.request.body = request.data ? JSON.stringify(request.data) : ''; this.credentials = credentials; this.service = request.service || ''; this.region = request.region || ''; } RequestSigner.prototype.sign = function () { var request = this.request; var headers = request.headers || {}; var date = new Date(headers.Date || new Date()); this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, ''); this.date = this.datetime.substr(0, 8); if (!request.method && request.body) request.method = 'POST'; if (!headers.Host && !headers.host) headers.Host = request.hostname || request.host; if (!request.hostname && !request.host) request.hostname = headers.Host || headers.host; if (request.body && !headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'; if (request.body && !headers['Content-Length'] && !headers['content-length']) headers['Content-Length'] = request.body.length; headers['X-Fidem-Date'] = this.datetime; if (this.credentials.sessionToken) { headers['X-Fidem-Security-Token'] = this.credentials.sessionToken; } if (headers.Authorization) { delete headers.Authorization; } headers.Authorization = this.authHeader(); return request; }; RequestSigner.prototype.generateSignature = function () { var request = this.request; var headers = request.headers || {}; var date = new Date(headers.Date || new Date()); this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, ''); this.date = this.datetime.substr(0, 8); if (!request.method && request.body) request.method = 'POST'; if (!headers.Host && !headers.host) headers.Host = request.hostname || request.host; if (!request.hostname && !request.host) request.hostname = headers.Host || headers.host; if (request.body && !headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'; if (request.body && !headers['Content-Length'] && !headers['content-length']) headers['Content-Length'] = Buffer.byteLength(request.body); headers['X-Fidem-Date'] = this.datetime; if (this.credentials.sessionToken) { headers['X-Fidem-Security-Token'] = this.credentials.sessionToken; } if (headers.Authorization) { delete headers.Authorization; } return this.signature(); }; RequestSigner.prototype.authHeader = function () { return [ 'FIDEM4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), 'SignedHeaders=' + this.signedHeaders(), 'Signature=' + this.signature() ].join(', '); }; RequestSigner.prototype.signature = function () { var kDate = hmac('FIDEM4' + this.credentials.secretAccessKey, this.date, 'buffer'); var kRegion = hmac(kDate, this.region, 'buffer'); var kService = hmac(kRegion, this.service, 'buffer'); var kCredentials = hmac(kService, 'fidem4_request', 'buffer'); return hmac(kCredentials, this.stringToSign(), 'hex'); }; RequestSigner.prototype.stringToSign = function () { return [ 'FIDEM4-HMAC-SHA256', this.datetime, this.credentialString(), hash(this.canonicalString(), 'hex') ].join('\n'); }; RequestSigner.prototype.canonicalString = function () { var pathParts = (this.request.path || '/').split('?', 2); return [ this.request.method || 'GET', pathParts[0] || '/', pathParts[1] || '', this.canonicalHeaders() + '\n', this.signedHeaders(), hash(this.request.body || '', 'hex') ].join('\n'); }; RequestSigner.prototype.canonicalHeaders = function () { var headers = this.request.headers; function trimAll(header) { return header.toString().trim().replace(/\s+/g, ' '); } return Object.keys(headers) .sort(function (a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1; }) .map(function (key) { return key.toLowerCase() + ':' + trimAll(headers[key]); }) .join('\n'); }; RequestSigner.prototype.signedHeaders = function () { return Object.keys(this.request.headers) .map(function (key) { return key.toLowerCase(); }) .sort() .join(';'); }; RequestSigner.prototype.credentialString = function () { return [ this.date, this.region, this.service, 'fidem4_request' ].join('/'); }; fidemRequestSigner.RequestSigner = RequestSigner; fidemRequestSigner.sign = function (request, credentials) { return new RequestSigner(request, credentials).sign(); }; fidemRequestSigner.generateSignature = function (request, credentials) { return new RequestSigner(request, credentials).generateSignature(); };
import { CustomEvent } from 'global'; import { LitElement, html, css } from 'lit-element'; const demoWcCardStyle = css` :host { display: block; position: relative; width: 250px; height: 200px; border-radius: 10px; transform-style: preserve-3d; transition: all 0.8s ease; } .header { font-weight: bold; font-size: var(--demo-wc-card-header-font-size, 16px); text-align: center; } .content { padding: 20px 10px 0 10px; flex-grow: 1; } .footer { display: flex; } dl { margin: 0; text-align: left; } dd { margin-left: 15px; } button { border-radius: 15px; width: 30px; height: 30px; background: #fff; border: 1px solid #ccc; color: #000; font-size: 21px; line-height: 27px; font-weight: bold; cursor: pointer; margin: 5px; } .note { flex-grow: 1; color: #666; font-size: 16px; font-weight: bold; text-align: left; padding-top: 15px; } :host([back-side]) { transform: rotateY(180deg); } #front, #back { position: absolute; width: 250px; box-sizing: border-box; box-shadow: #ccc 3px 3px 2px 1px; padding: 10px; display: flex; flex-flow: column; top: 0; left: 0; height: 100%; border-radius: 10px; backface-visibility: hidden; overflow: hidden; } #front { background: linear-gradient(141deg, #aaa 25%, #eee 40%, #ddd 55%); color: var(--demo-wc-card-front-color, #000); } #back { background: linear-gradient(141deg, #333 25%, #aaa 40%, #666 55%); color: var(--demo-wc-card-back-color, #fff); text-align: center; transform: rotateY(180deg) translate3d(0px, 0, 1px); } #back .note { color: #fff; } `; /** * This is a container looking like a card with a back and front side you can switch * * @slot - This is an unnamed slot (the default slot) * @fires side-changed - Fires whenever it switches between front/back * @cssprop --demo-wc-card-header-font-size - Header font size * @cssprop --demo-wc-card-front-color - Font color for front * @cssprop --demo-wc-card-back-color - Font color for back * @csspart front - Front of the card * @csspart back - Back of the card */ export class DemoWcCard extends LitElement { static get properties() { return { backSide: { type: Boolean, reflect: true, attribute: 'back-side', }, header: { type: String }, rows: { type: Object }, }; } static get styles() { return demoWcCardStyle; } constructor() { super(); /** * Indicates that the back of the card is shown */ this.backSide = false; /** * Header message */ this.header = 'Your Message'; /** * Data rows */ this.rows = []; } toggle() { this.backSide = !this.backSide; } render() { return html` <div id="front" part="front"> <div class="header">${this.header}</div> <div class="content"> <slot></slot> </div> <div class="footer"> <div class="note">A</div> <button @click=${this.toggle}>></button> </div> </div> <div id="back" part="back"> <div class="header">${this.header}</div> <div class="content"> ${this.rows.length === 0 ? html`` : html` <dl> ${this.rows.map( (row) => html` <dt>${row.header}</dt> <dd>${row.value}</dd> ` )} </dl> `} </div> <div class="footer"> <div class="note">B</div> <button @click=${this.toggle}>></button> </div> </div> `; } updated(changedProperties) { if (changedProperties.has('backSide') && changedProperties.get('backSide') !== undefined) { this.dispatchEvent(new CustomEvent('side-changed')); } } } // eslint-disable-next-line no-undef customElements.define('input', DemoWcCard);
'use strict'; /* ============================================== NavLinks Collection ============================================== */ APP.NavLinks = Backbone.Collection.extend({ model: APP.NavLink });
$(document).ready(function() { $("input[name=color]").spectrum({ // The color-picker allowEmpty: true, preferredFormat: "hex" }); $(".loginregistertoggle").click(function() { // Switch between login and signup $("#login, #signup").toggle(); }); $("#updateprofile").submit(function() { // Sanitize HTML in about section var clean = $("<div>").text($("textarea[name=about]").val()).html(); $("textarea[name=about]").val(clean); }); });
import { createAsyncIterable, createIterable } from '../helpers/helpers'; import { STRICT_THIS } from '../helpers/constants'; import Promise from 'core-js-pure/es/promise'; import fromAsync from 'core-js-pure/features/array/from-async'; QUnit.test('Array.fromAsync', assert => { assert.expect(25); const async = assert.async(); assert.isFunction(fromAsync); assert.arity(fromAsync, 1); assert.name(fromAsync, 'fromAsync'); function C() { /* empty */ } fromAsync(createAsyncIterable([1, 2, 3]), it => it ** 2).then(it => { assert.arrayEqual(it, [1, 4, 9], 'async iterable and mapfn'); return fromAsync(createAsyncIterable([1]), function (arg, index) { assert.same(this, STRICT_THIS, 'this'); assert.same(arguments.length, 2, 'arguments length'); assert.same(arg, 1, 'argument'); assert.same(index, 0, 'index'); }); }).then(() => { return fromAsync(createAsyncIterable([1, 2, 3])); }).then(it => { assert.arrayEqual(it, [1, 2, 3], 'async iterable without mapfn'); return fromAsync(createIterable([1, 2, 3]), arg => arg ** 2); }).then(it => { assert.arrayEqual(it, [1, 4, 9], 'iterable and mapfn'); return fromAsync(createIterable([1, 2, 3]), arg => Promise.resolve(arg ** 2)); }).then(it => { assert.arrayEqual(it, [1, 4, 9], 'iterable and async mapfn'); return fromAsync(createIterable([1]), function (arg, index) { assert.same(this, STRICT_THIS, 'this'); assert.same(arguments.length, 2, 'arguments length'); assert.same(arg, 1, 'argument'); assert.same(index, 0, 'index'); }); }).then(() => { return fromAsync(createIterable([1, 2, 3])); }).then(it => { assert.arrayEqual(it, [1, 2, 3], 'iterable and without mapfn'); return fromAsync([1, Promise.resolve(2), 3]); }).then(it => { assert.arrayEqual(it, [1, 2, 3], 'array'); return fromAsync('123'); }).then(it => { assert.arrayEqual(it, ['1', '2', '3'], 'string'); return fromAsync.call(C, [1]); }).then(it => { assert.true(it instanceof C, 'subclassable'); return fromAsync({ length: 1, 0: 1 }); }).then(it => { assert.arrayEqual(it, [1], 'non-iterable'); return fromAsync(createIterable([1]), () => { throw 42; }); }).catch(error => { assert.same(error, 42, 'rejection on a callback error'); return fromAsync(undefined, () => { /* empty */ }); }).catch(error => { assert.true(error instanceof TypeError); return fromAsync(null, () => { /* empty */ }); }).catch(error => { assert.true(error instanceof TypeError); return fromAsync([1], null); }).catch(error => { assert.true(error instanceof TypeError); return fromAsync([1], {}); }).catch(error => { assert.true(error instanceof TypeError); async(); }); });
import Ember from 'ember'; export let Serializer = Ember.Mixin.create({ attrs: { suggestion: { serialize: 'odata-id', deserialize: 'records' } }, /** * Field name where object identifier is kept. */ primaryKey: '__PrimaryKey' });
/* global describe, it */ import {expect} from 'chai' import {generateToken} from './token' import {staRHsListOperation} from '../../src/operations/starhs-list' import Promise from 'bluebird' import {StaRHsAPIClient} from '../../src/apiclient' import {URIValue} from 'rheactor-value-objects' import {StaRH} from 'starhs-models' import {ListType} from 'rheactor-models' import {itShouldHaveLinkTo} from './helper' const mountURL = new URIValue('https://api.example.com') describe('/staRHs/{user}/received', () => { it('should return the received staRHs', () => { const mockClient = new StaRHsAPIClient('myapikey', 'apiuser', 'apipass') mockClient.getStaRHsReceived = (sessionToken, opts) => { expect(sessionToken).to.equal('some-session-token') return Promise.resolve([ { 'From': 'Peter Gamelkoorn', 'FromID': '1a1d56af-a34e-47e9-b590-309da51f60cc', 'FromURLPicture': 'https://starhs.net/profileimgs/20c67c72-7c45-4de0-91e3-c2ac11c40b95.jpg', 'No': 2, 'Reason': 'staRH message 1', 'Date': '2016-12-13T15:16:00' }, { 'From': 'Angela Maus', 'FromID': '1d70ff1a-d5c9-4edf-b383-35a0074462c3', 'FromURLPicture': 'https://starhs.net/profileimgs/05a08e72-eaa0-4ab3-8b52-61ca02860f2d.jpg', 'No': 2, 'Reason': 'staRH message 2', 'Date': '2016-12-12T23:50:00' }, { 'From': 'Heiko Fischer', 'FromID': '1b71e7a5-122b-489a-9def-e43cfba32adf', 'FromURLPicture': 'https://starhs.net/profileimgs/8651161a-ac33-4837-9c33-87997ce7bdc1.jpg', 'No': 2, 'Reason': 'staRH message 3', 'Date': '2016-12-12T19:57:00' } ]) } mockClient.getProfile = sessionToken => { expect(sessionToken).to.equal('some-session-token') return Promise.resolve({ 'PKUser': 'profile-id-antarctica', 'Forename': '', 'Name': 'Antarctica', 'EMail': 'antartica@example.com', 'URLPicture': 'http://starhs.net/profileimgs/' }) } mockClient.getStaRHsStatus = sessionToken => { expect(sessionToken).to.equal('some-session-token') return Promise.resolve({ 'CycleStaRHsToShare': 10, 'YouHaveShared': 1, 'YouHaveReceived': 2, 'YouHaveLeft': 8, 'TotalShared': 19, 'TotalReceived': 11 }) } const list = staRHsListOperation(mountURL, mockClient) return generateToken() .then(token => list.post({}, ['some-user-name', 'received'], token) .then( /** * @param {List} list */ list => { ListType(list) itShouldHaveLinkTo(list, StaRH, true, 'next') expect(list.total).to.equal(11) expect(list.itemsPerPage).to.equal(10) expect(list.hasNext).to.equal(true) expect(list.hasPrev).to.equal(false) expect(list.items.length).to.equal(3) expect(list.items[0]).to.be.instanceof(StaRH) expect(list.items[0].amount).to.equal(2) expect(list.items[0].message).to.equal('staRH message 1') expect(list.items[0].$createdAt.toISOString()).to.equal(new Date('2016-12-13T15:16:00').toISOString()) expect(list.items[0].to.$id.equals(new URIValue(`${mountURL}/profile/profile-id-antarctica`))).to.equal(true) expect(list.items[0].to.name).to.equal('Antarctica') expect(list.items[0].to.avatar.equals(new URIValue('http://starhs.net/profileimgs/'))).to.equal(true) expect(list.items[0].from.$id.equals(new URIValue(`${mountURL}/profile/1a1d56af-a34e-47e9-b590-309da51f60cc`))).to.equal(true) expect(list.items[0].from.name).to.equal('Peter Gamelkoorn') expect(list.items[0].from.avatar.equals(new URIValue('https://starhs.net/profileimgs/20c67c72-7c45-4de0-91e3-c2ac11c40b95.jpg'))).to.equal(true) } ) ) }) })
/** * A simple transform stream that just passes on data as it comes in. */ 'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; } var stream = require('stream'); var ThroughStream = (function (_stream$Transform) { _inherits(ThroughStream, _stream$Transform); function ThroughStream() { _classCallCheck(this, ThroughStream); _get(Object.getPrototypeOf(ThroughStream.prototype), 'constructor', this).call(this); } _createClass(ThroughStream, [{ key: '_transform', value: function _transform(chunk, encoding, next) { this.push(chunk, encoding); next(); } }]); return ThroughStream; })(stream.Transform); module.exports = ThroughStream; //# sourceMappingURL=../lib/ThroughStream.js.map
'use strict' exports.find = function(req, res, next){ req.query.name = req.query.name ? req.query.name : ''; req.query.limit = req.query.limit ? parseInt(req.query.limit, null) : 20; req.query.page = req.query.page ? parseInt(req.query.page, null) : 1; req.query.sort = req.query.sort ? req.query.sort : '_id'; var filters = {}; if (req.query.username) { filters.username = new RegExp('^.*?'+ req.query.username +'.*$', 'i'); } req.app.db.models.Event.pagedFind({ filters: filters, keys: 'name username description', limit: req.query.limit, page: req.query.page, sort: req.query.sort }, function(err, results) { if (err) { return next(err); } if (req.xhr) { res.header("Cache-Control", "no-cache, no-store, must-revalidate"); results.filters = req.query; res.send(results); } else { // results.data is everything that we are searching for results.filters = req.query; res.render('events/index', { data: results.data }); } }); }; exports.read = function(req, res, next){ req.app.db.models.Event.findById(req.params.id).exec(function(err, event){ if(err){ return next(err) } if (req.xhr){ res.send(event) } else { res.render('events/details', { event: event }) } }) }; exports.add = function(req, res){ if (!req.isAuthenticated()) { req.flash("error", "You are not logged in"); res.location('/events'); res.redirect("/events"); } res.render('events/add'); }; // exports.create = function(req, res, next){ // var workflow = // }
'use strict'; var daap = {}; var session = {}; /* Actions functions */ exports.get_volume = function (callback) { daap.getProperty(session.id, ['dmcp.volume'], function (error, response) { if (error) { return callback(error); } callback(null, response['dmcp.getpropertyresponse']['dmcp.volume']); }); }; exports.set_volume = function (volume, callback) { if (volume < 0) { volume = 0; } else if (volume > 100) { volume = 100; } daap.setProperty(session.id, {'dmcp.volume': volume}, function (error, response) { if (error) { return callback(error, false); } callback(null, true); }); }; exports.action_play = function (callback, args) { daap.playStatusUpdate(session.id, 1, function (error, response) { if (error) { return callback(error, false); } if ('dmcp.playstatus' in response && 'dacp.playerstate' in response['dmcp.playstatus']) { if (response['dmcp.playstatus']['dacp.playerstate'] != 4) { daap.playPause(session.id, function (error, response) { if (error) { return callback(error, false); } callback(null, true); }); } else { return callback(null, true); } } else { return callback('undefined properties', false); } }); }; exports.action_pause = function (callback, args) { daap.playStatusUpdate(session.id, 1, function (error, response) { if (error) { return callback(error, false); } if ('dmcp.playstatus' in response && 'dacp.playerstate' in response['dmcp.playstatus']) { if (response['dmcp.playstatus']['dacp.playerstate'] == 4) { daap.playPause(session.id, function (error, response) { if (error) { return callback(error, false); } callback(null, true); }); } else { return callback(null, true); } } else { return callback('undefined properties', false); } }); }; exports.action_playpause = function (callback, args) { daap.playPause(session.id, function (error, response) { if (error) { return callback(error, false); } callback(null, true); }); }; exports.action_previous = function (callback, args) { daap.previous(session.id, function (error, response) { if (error) { return callback(error, false); } callback(null, true); }); }; exports.action_next = function (callback, args) { daap.next(session.id, function (error, response) { if (error) { return callback(error, false); } callback(null, true); }); }; exports.action_volume = function (callback, args) { exports.set_volume(args.volume_percent, callback); }; exports.action_volume_down = function (callback, args) { exports.get_volume(function (error, volume) { if (error) { return callback(error, false); } volume -= args.volume_down; exports.set_volume(volume, callback); }); }; exports.action_volume_up = function (callback, args) { exports.get_volume(function (error, volume) { if (error) { return callback(error, false); } volume += args.volume_up; exports.set_volume(volume, callback); }); }; exports.action_repeat = function (callback, args) { daap.setProperty(session.id, {'dacp.repeatstate': parseInt(args.repeat)}, function (error, response) { if (error) { return callback(error, false); } callback(null, true); }); }; exports.action_shuffle = function (callback, args) { daap.setProperty(session.id, {'dacp.shufflestate': parseInt(args.shuffle)}, function (error, response) { if (error) { return callback(error, false); } callback(null, true); }); }; /* Init */ exports.init = function (_daap, _session) { daap = _daap; session = _session; };
/** * @author weism * copyright 2015 Qcplay All Rights Reserved. */ /** * 动物信息 */ var Animal = qc.defineBehaviour('qc.demo.Animal', qc.Behaviour, function() { var self = this; self.type = 0; self.index = 0; self.explode = null; }, { // 需要序列化的字段 icon: qc.Serializer.NODE, explode: qc.Serializer.NODE }); // 设置动物的数据 Animal.prototype.setData = function(data) { var self = this; self.icon.frame = data.icon; self.type = data.type; self.index = data.index; self.name = '' + self.index; }; /** * 播放消失爆炸的效果 * @param cb */ Animal.prototype.disappear = function(cb) { var self = this; self.icon.visible = false; // 播放爆炸特效 self.explode.visible = true; self.explode.onFinished.addOnce(function() { self.explode.visible = false; cb(); }); self.explode.playAnimation('explode'); }; /** * 从fromIndex往下掉落 * @param icon * @param fromIndex */ Animal.prototype.drop = function(type, icon, fromIndex, cb) { var self = this; self.icon.frame = icon; self.type = type; self.icon.visible = true; var c = self.getScript('qc.TweenPosition'); c.from = new qc.Point(((fromIndex + 64) % 8) * 76, self.game.math.floorTo(fromIndex / 8) * 72); c.to = new qc.Point(((self.index) % 8) * 76, self.game.math.floorTo(self.index / 8) * 72); c.duration = (c.to.y - c.from.y) / 72 * 0.13; c.resetToBeginning(); c.onFinished.addOnce(function() { cb(); }); c.playForward(); }
var crypto = require("crypto"); Q = require("q"), _ = require("underscore"); module.exports = { permissions: function(){ if (this.session && this.session._id == this.value) return ["remove"] else return ["create"]; }, actions: { "create": function(req,res){ var md5 = crypto.createHash("md5"); var dfd = Q.defer(); var _this = this; _this.app.models.user.find({or: [ {nick: _this.data.login, password: _this.data.password}, {email: _this.data.login, password: _this.data.password} ]}).run(function(e,docs){ console.log(e,docs); if (e) return dfd.reject([500,e]); if (docs.length == 0) dfd.reject([403,{message: "Wrong user or password"}]); else if (obj.length > 1){ console.log("Error: You have to many users in database with this credentials!") dfd.reject({message: "Too many users with this credentials!"}); } else { try{ new _this.model({ "user": obj[0], "created": new Date(), "last_view": new Date(), "session_id": md5.update(obj[0]+new Date().toISOString()).digest("hex"), "expires": req.body.remember?new Date(Date.now() + 1000*3600*24*365*10):new Date(Date.now() + 1000*3600*6) }).save().then(function(a){ res.cookie( _this.cookieName, a.get("session_id"), req.body.remember?{expires: new Date(Date.now() + 1000000000000)}:{}); dfd.resolve(a) },dfd.reject); } catch(e){ m.log(e.message); } } }); return dfd.promise; }, "remove": m.ResourceController.actions.remove } };
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import './Header.css'; class Header extends Component { render() { return ( <header> <h1><Link to="/">Beavers Gamification!!</Link></h1> <span>Login</span> </header> ); } } export default Header;
import NProgress from 'nprogress' import { message, notification } from 'antd' import { getBsnListAction, getStrategyAction, getStrategyListAction, setRelationAction } from './request/strategy' const GET_BSN_LIST = 'GET_BSN_LIST' const SET_STRATEGY = 'SET_STRATEGY' export const getBsnList = selectOpt => (dispatch, getState) => { NProgress.start() dispatch(getBsnListAction(selectOpt)).then(action => { const dataBody = action.data.body if (dataBody.errorCode == '0') { dispatch({ type: GET_BSN_LIST, data: { bsnList: dataBody.bsnList, bsnListTotalNum: dataBody.turnPageTotalNum, bsnSelectOpt: selectOpt } }) } else { message.error('获取列表失败!') } NProgress.done() }) } export const getStrategy = (authId, success, fail) => (dispatch, getState) => { dispatch(getStrategyAction(authId)).then(action => { const dataBody = action.data.body if (dataBody.errorCode == '0') { const authDefine = dataBody.authDefine const authDefArr = authDefine.split('') dispatch({ type: SET_STRATEGY, data: { alias: dataBody.alias, authId: dataBody.authId, authType: dataBody.authType, areaNo: dataBody.areaNo, authDefine: authDefine, add1: authDefArr[0], add2: authDefArr[1], add3: authDefArr[2], add4: authDefArr[3], add5: authDefArr[4] } }) if (success) success() } else { message.error('数据获取失败!') if (fail) fail() } }) } export const setRelation = params => (dispatch, getState) => { dispatch(setRelationAction(params)).then(action => { const dataBody = action.data.body if (dataBody.errorCode == '0') { dispatch(getBsnList(getState().reviewSettings.bsnSelectOpt)) notification.success({ message: '成功', description: '关联成功!' }) } else { notification.warning({ message: '失败', description: '关联失败!' }) } }) } const initialState = { bsnList: [], bsnListTotalNum: 0, bsnSelectOpt: {}, strategyDetail: {} } export default (state = initialState, action) => { switch (action.type) { case GET_BSN_LIST: return { ...state, ...action.data } case SET_STRATEGY: return { ...state, strategyDetail: action.data } default: return state } }
'use strict'; var Lab = require('lab'), Hapi = require('hapi'), Plugin = require('../../../lib/plugins/anarcastanho'); var describe = Lab.experiment; var it = Lab.test; var expect = Lab.expect; var before = Lab.before; var after = Lab.after; describe('anarcastanho', function() { var server = new Hapi.Server(); it('Plugin successfully loads', function(done) { server.pack.register(Plugin, function(err) { expect(err).to.not.exist; done(); }); }); it('Plugin registers routes', function(done) { var table = server.table(); expect(table).to.have.length(1); expect(table[0].path).to.equal('/anarcastanho'); done(); }); it('Plugin route responses', function(done) { var table = server.table(); expect(table).to.have.length(1); expect(table[0].path).to.equal('/anarcastanho'); var request = { method: 'GET', url: '/anarcastanho' }; server.inject(request, function(res) { expect(res.statusCode).to.equal(200); expect(res.result).to.equal('don\'t worry, be hapi!'); done(); }); }); });
import { log } from '../../logger'; import { generateId } from '../../utils'; import mermaidAPI from '../../mermaidAPI'; import * as configApi from '../../config'; const clone = o => JSON.parse(JSON.stringify(o)); let rootDoc = []; export const parseDirective = function(statement, context, type) { mermaidAPI.parseDirective(this, statement, context, type); }; const setRootDoc = o => { log.info('Setting root doc', o); // rootDoc = { id: 'root', doc: o }; rootDoc = o; }; const getRootDoc = () => rootDoc; const docTranslator = (parent, node, first) => { if (node.stmt === 'relation') { docTranslator(parent, node.state1, true); docTranslator(parent, node.state2, false); } else { if (node.stmt === 'state') { if (node.id === '[*]') { node.id = first ? parent.id + '_start' : parent.id + '_end'; node.start = first; } } if (node.doc) { const doc = []; // Check for concurrency let i = 0; let currentDoc = []; for (i = 0; i < node.doc.length; i++) { if (node.doc[i].type === 'divider') { // debugger; const newNode = clone(node.doc[i]); newNode.doc = clone(currentDoc); doc.push(newNode); currentDoc = []; } else { currentDoc.push(node.doc[i]); } } // If any divider was encountered if (doc.length > 0 && currentDoc.length > 0) { const newNode = { stmt: 'state', id: generateId(), type: 'divider', doc: clone(currentDoc) }; doc.push(clone(newNode)); node.doc = doc; } node.doc.forEach(docNode => docTranslator(node, docNode, true)); } } }; const getRootDocV2 = () => { docTranslator({ id: 'root' }, { id: 'root', doc: rootDoc }, true); return { id: 'root', doc: rootDoc }; }; const extract = _doc => { // const res = { states: [], relations: [] }; let doc; if (_doc.doc) { doc = _doc.doc; } else { doc = _doc; } // let doc = root.doc; // if (!doc) { // doc = root; // } log.info(doc); clear(); log.info('Extract', doc); doc.forEach(item => { if (item.stmt === 'state') { addState(item.id, item.type, item.doc, item.description, item.note); } if (item.stmt === 'relation') { addRelation(item.state1.id, item.state2.id, item.description); } }); }; const newDoc = () => { return { relations: [], states: {}, documents: {} }; }; let documents = { root: newDoc() }; let currentDocument = documents.root; let startCnt = 0; let endCnt = 0; // eslint-disable-line // let stateCnt = 0; /** * Function called by parser when a node definition has been found. * @param id * @param text * @param type * @param style */ export const addState = function(id, type, doc, descr, note) { if (typeof currentDocument.states[id] === 'undefined') { currentDocument.states[id] = { id: id, descriptions: [], type, doc, note }; } else { if (!currentDocument.states[id].doc) { currentDocument.states[id].doc = doc; } if (!currentDocument.states[id].type) { currentDocument.states[id].type = type; } } if (descr) { log.info('Adding state ', id, descr); if (typeof descr === 'string') addDescription(id, descr.trim()); if (typeof descr === 'object') { descr.forEach(des => addDescription(id, des.trim())); } } if (note) currentDocument.states[id].note = note; }; export const clear = function() { documents = { root: newDoc() }; currentDocument = documents.root; currentDocument = documents.root; startCnt = 0; endCnt = 0; // eslint-disable-line classes = []; }; export const getState = function(id) { return currentDocument.states[id]; }; export const getStates = function() { return currentDocument.states; }; export const logDocuments = function() { log.info('Documents = ', documents); }; export const getRelations = function() { return currentDocument.relations; }; export const addRelation = function(_id1, _id2, title) { let id1 = _id1; let id2 = _id2; let type1 = 'default'; let type2 = 'default'; if (_id1 === '[*]') { startCnt++; id1 = 'start' + startCnt; type1 = 'start'; } if (_id2 === '[*]') { endCnt++; id2 = 'end' + startCnt; type2 = 'end'; } addState(id1, type1); addState(id2, type2); currentDocument.relations.push({ id1, id2, title }); }; const addDescription = function(id, _descr) { const theState = currentDocument.states[id]; let descr = _descr; if (descr[0] === ':') { descr = descr.substr(1).trim(); } theState.descriptions.push(descr); }; export const cleanupLabel = function(label) { if (label.substring(0, 1) === ':') { return label.substr(2).trim(); } else { return label.trim(); } }; export const lineType = { LINE: 0, DOTTED_LINE: 1 }; let dividerCnt = 0; const getDividerId = () => { dividerCnt++; return 'divider-id-' + dividerCnt; }; let classes = []; const getClasses = () => classes; const getDirection = () => 'TB'; export const relationType = { AGGREGATION: 0, EXTENSION: 1, COMPOSITION: 2, DEPENDENCY: 3 }; const trimColon = str => (str && str[0] === ':' ? str.substr(1).trim() : str.trim()); export default { parseDirective, getConfig: () => configApi.getConfig().state, addState, clear, getState, getStates, getRelations, getClasses, getDirection, addRelation, getDividerId, // addDescription, cleanupLabel, lineType, relationType, logDocuments, getRootDoc, setRootDoc, getRootDocV2, extract, trimColon };
module.exports = { singleQuote: true, };
var APP = { init: function() { loopChangeWord = setInterval(function(){ var $change = $('#change'); var iteration = ['quick', 'efficiently', 'well', 'together']; var current = $change.html(); for (var i = 0; i < iteration.length; i++) { if (iteration[i] == current) { if (i+1 > iteration.length-1) var nw = iteration[0]; else nw = iteration[i+1]; $change.fadeOut(500, function(){ $change.html(nw).fadeIn(500); }); } } }, 4000); return this; }, begin: function() { $sliders = $('.slideonload'); $avatar = $('#me'); $me = $('#me_container'); //fade in avatar then transition to left. $avatar.fadeIn(1000, function(){ $sliders.css({'width':'0'});//animation. }); //binding, loading in the first box data. $sliders.bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ $me.css({'float':'left'}); $sliders.css({'width':''}); displayDataBox1 = setTimeout(function(){ $db1 = $('#databox-1'); $db1.fadeIn(250); }, 1000); }); } };
"use strict"; var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); }; var Test = (function () { function Test() {} _prototypeProperties(Test, null, { test: { value: function test() { return 5 + 5; }, writable: true, enumerable: true, configurable: true } }); return Test; })();
/* * Jot - A quick note writing and sharing app. * custom.js - All custom js/jquery code * * Author: Alf http://alfg.co * * Licensed under the MIT License: * http://www.opensource.org/licenses/mit-license.php */ //JsLInt /*global $, document, location, Base64*/ $(document).ready(function () { "use strict"; // Autosize textarea $('#write-text').autosize(); // Decode and load data if hash url exists if (location.hash !== '') { var encType = location.hash.substr(1,1); //encryption type [b = blowfish, e = base64 encoding] if (encType === 'e') { // If base64 encoding var getHash = location.hash.substr(2); // Get hash after 2nd char $('#write-text').val(Base64.decode(getHash)); // Decode base64 hash $('#share-url').val(location.href); // Load URL into share-url box $('#share').show(); // Show share div $('#write-text').trigger('autosize'); // Dynamically sizes the textarea } else if (encType === 'b') { // Else if Blowfish cipher var getHash = location.hash.substr(2); // Get hash after 2nd char $('#write-text').val("This message is encrypted. Enter key to decrypt message."); // Requires key note // Show/hide relevant buttons $('#key-required').show(); $('#decrypt-button').show(); $('#save-button').hide(); $('#add-key-button').hide(); } } // Add encoded hash to url on save button $('#save-button').click(function (e) { var text = $('#write-text').val(), // Message encoded = Base64.encode(text), // Message encoded key = $('#key-gen').val(); // Get key value if (text === '') { $('.alert').show().text("Jot something first!").delay(3000).fadeOut('slow'); e.preventDefault(); } else if (key.length === 0) { // If key is empty, use encoding method // Add encoded to url and show share input location.hash = 'e' + encoded; $('#share-url').val(location.href); $('#share').slideDown('fast'); } else { // Else, use blowfish encryption // Encrypt text with blowfish var bf = new Blowfish({ key: key, }); var encrypted = bf.encrypt64(text); // Load blowfish cipher into url path and show share input location.hash = 'b' + encrypted; $('#share-url').val(location.href); $('#share').slideDown('fast'); } }); // Clear value of textarea element $('#clear-button').click(function () { // Resets all buttons/inputs location.hash = ''; $('#share').slideUp('fast'); $('#key').slideUp('fast'); $('#key-required').slideUp('fast'); $('#write-text').val(''); $('#key-gen').val(''); // Reset buttons $('#decrypt-button').hide(); $('#save-button').show(); $('#add-key-button').show(); }); // Add key input $('#add-key-button').click(function () { $('#key').slideDown('fast'); }); $('#decrypt-button').click(function () { // Run blowfish and output to write-text box. var getHash = location.hash.substr(2); // Gets hash value after 2nd char var key = $('#key-decrypt').val(); // Grabs inputted key var bf = new Blowfish({ // Run blowfish against key key: key, }); var decrypted = bf.decrypt64(getHash); //Decrypted message (if key is correct) $('#write-text').val(decrypted); // Output to write-text $('#write-text').trigger('autosize'); // Dynamically sizes the textarea }); }); $("#share-url").focus(function () { // Select all text on #share-url focus "use strict"; var $this = $(this); $this.select(); // Work around Chrome's little problem $this.mouseup(function () { // Prevent further mouseup intervention $this.unbind("mouseup"); return false; }); });
/** * Created by admin on 2/9/17. */ import React from 'react'; import { StyleSheet, Text, TextInput, View, LayoutAnimation, TouchableHighlight, Image } from 'react-native'; export default class Calling extends React.Component { render() { return ( <View style={styles.container}> <View style={styles.callDetails}> <Image style={{height:60,width:60}} source={require('./assets/avatar.jpeg')}/> <View style={{marginTop: 20, marginBottom: 20}}/> <Text style={styles.name}>Call Request</Text> <TouchableHighlight onPress={() => { }} underlayColor={'transparent'}> <Text>Ringing...</Text> </TouchableHighlight> </View> <View style={styles.callButtonContainer}> <TouchableHighlight onPress={() => { }} underlayColor={'transparent'}> <View style={styles.buttonContainer}> <View style={[styles.iconContainer, {backgroundColor: 'red'}]}> <Image style={styles.icon} source={require('./assets/decline_call_icon.png')}/> </View> <Text style={styles.iconTitle}>Decline</Text> </View> </TouchableHighlight> </View> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', padding: 20, }, callDetails: { flex: 3, justifyContent: 'center', alignItems: 'center', }, avatarContainer: { height: 100, width: 100, borderRadius: 50, marginBottom: 20 }, avatar: { height: 100, width: 100, borderRadius: 50, }, name: { fontSize: 18 }, callButtonContainer: { flex: 1, justifyContent: 'space-around', alignItems: 'center', flexDirection: 'row' }, iconContainer: { height: 60, width: 60, borderRadius: 30, justifyContent: 'center', alignItems: 'center', marginBottom: 10 }, buttonContainer: { alignItems: 'center', }, icon: { height: 30, width: 30 }, iconTitle: { alignItems: 'center', fontSize: 15, alignSelf: 'center' } });
window.$ = window.jQuery = require('jquery'); require('select2'); require('bootstrap-sass/assets/javascripts/bootstrap/dropdown.js'); require('bootstrap-sass/assets/javascripts/bootstrap/affix.js'); require('bootstrap-sass/assets/javascripts/bootstrap/modal.js'); require('bootstrap-sass/assets/javascripts/bootstrap/transition.js'); require('bootstrap-sass/assets/javascripts/bootstrap/collapse.js'); require('bootstrap-sass/assets/javascripts/bootstrap/carousel.js'); require('bootstrap-sass/assets/javascripts/bootstrap/tooltip.js'); require('bootstrap-sass/assets/javascripts/bootstrap/popover.js'); require('./monoboot.popovers.js'); require('../../core/js/index'); require('highcharts'); require('./monoboot.highcharts.theme.js'); require('./monoboot.highcharts.js');
var _DeviceEventEmitter=require('../plugins/DeviceEventEmitter');var _DeviceEventEmitter2=_interopRequireDefault(_DeviceEventEmitter); var _DeviceEventManager=require('../NativeModules/DeviceEventManager');var _DeviceEventManager2=_interopRequireDefault(_DeviceEventManager);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};} var DEVICE_BACK_EVENT='hardwareBackPress'; var _backPressSubscriptions=new Set(); /** * Detect hardware back button presses, and programmatically invoke the default back button * functionality to exit the app if there are no listeners or if none of the listeners return true. * * Example: * * ```js * BackAndroid.addEventListener('hardwareBackPress', function() { * if (!this.onMainScreen()) { * this.goBack(); * return true; * } * return false; * }); * ``` */ var BackAndroid={ exitApp:function(){function exitApp(){ _DeviceEventManager2['default'].invokeDefaultBackPressHandler(); }return exitApp;}(), addEventListener:function(){function addEventListener(eventName,handler){ _backPressSubscriptions.add(handler); return{ remove:function(){function remove(){return BackAndroid.removeEventListener(eventName,handler);}return remove;}()}; }return addEventListener;}(), removeEventListener:function(){function removeEventListener(eventName,handler){ _backPressSubscriptions['delete'](handler); }return removeEventListener;}()}; _DeviceEventEmitter2['default'].addListener(DEVICE_BACK_EVENT,function(){ var invokeDefault=true; _backPressSubscriptions.forEach(function(subscription){ if(subscription()){ invokeDefault=false; } }); if(invokeDefault){ BackAndroid.exitApp(); } }); module.exports=BackAndroid;
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M3 11c0 2.45 1.76 4.47 4.08 4.91l-1.49-1.49L7 13l4 4.01L7 21l-1.41-1.41 1.58-1.58v-.06C3.7 17.54 1 14.58 1 11c0-3.87 3.13-7 7-7h3v2H8c-2.76 0-5 2.24-5 5zm19 0V4h-9v7h9zm-2-2h-5V6h5v3zm-7 4h9v7h-9z" }), 'MoveDownOutlined');
import spreadAttributes from "../js/spreadAttributes.js"; class Anchor extends HTMLElement { connectedCallback() { const shadowRoot = this.attachShadow({ mode: "open" }); const styles = ` a { color: var(--white); text-decoration: none; } a:hover { color: var(--primary-color); } :host([active]) a { color: var(--primary-color); } `; shadowRoot.innerHTML = ` <style>${styles}</style> <a ${spreadAttributes(this.attributes)}><slot></slot></a> `; } } customElements.define("bp-anchor", Anchor);
define({ "_widgetLabel": "Filtre", "toggleTip": "Filtre ayarlarını göstermek/gizlemek için tıklayın", "toggleOn": "Geçerli filtreyi etkinleştirmek için geçiş düğmesine basın", "toggleOff": "Geçerli filtreyi kapatmak için geçiş düğmesine basın", "filterActions": "Filtre işlemleri", "resetAll": "Filtreleri sıfırla (özel olanlar hariç)", "turnOffAll": "Filtreleri kapat (özel olanlar hariç)", "createCustomFilter": "Özel bir filtre oluştur", "customFilter": "Özel filtre", "toggleCustomFilter": "Tüm filtreleri aç veya kapat", "toggleCustomFilters": "Tüm filtreleri aç veya kapat" });
var React = require('react'); module.exports = React.createClass({ render: require('./profile.chtmlx') });
define('ivy/directive/TypeStr', [ 'ivy/DirectiveInterpreter', 'ivy/utils', 'ivy/Consts' ], function(DirectiveInterpreter, iu, Consts) { var IvyDataType = Consts.IvyDataType, DirAttrKind = Consts.DirAttrKind; return FirClass( function TypeStrDirInterpreter() { this._name = 'typestr'; this._attrBlocks = [{ 'kind': DirAttrKind.ExprAttr, 'exprAttrs': [{ 'name': 'value', 'typeName': 'any' }] }, { 'kind': DirAttrKind.BodyAttr, 'bodyAttr': {} }] }, DirectiveInterpreter, { interpret: function(interp) { var valueType = iu.getDataNodeType(interp.getValue("value")); if( valueType >= Consts.IvyDataTypeItems.length ) { interp.rtError('Unable to get type-string for value'); } interp._stack.push(Consts.IvyDataTypeItems[valueType]); } }); });
import AbstractTracker from "./abstract"; export default class Nyaa extends AbstractTracker { static get id() { return "nyaa"; } static get hosts() { return [ "www.nyaa.se", ]; } static get tags() { return [ "anime", "books", "games", "japanese", "live_action", "music", "software", ].sort().join(" "); } static get scheme() { return "https"; } static get params() { return { ...super.params, itemSelector: "tr.tlistrow", searchPageDetector: ["table.tlist", ".viewtable"], lastPageDetector: ".pages b ~ a", itemsPerPage: 105, categoriesPageDetector: "select[name='cats']", categoriesListSelector: "select[name='cats']", // Nyaa singleResultPageDetector: ".viewtable", }; } static parsePage() { const categoryNames = $.map($("td.viewcategory a"), node => $(node).text()); return { name: $("td.viewtorrentname").text(), uid: (/(\d+)$/).exec(document.URL)[1], pageUrl: document.URL, torrentUrl: $("div.viewdownloadbutton a").prop("href"), size: this.parseSizeStr($("td.vtop").eq(4).text()), categoryNames, categoryName: categoryNames::this.last(), }; } static parseCategories(body) { const result = []; let lastTopCat; body.find(`${this.params.categoriesListSelector} > option`).each((index, node) => { const option = $(node); const valId = option.val(); const subNum = option.val().match(/(\d+)_(\d+)/)[2]; if (subNum === "0") { const cat = { id: valId, label: option.text(), selectable: true, }; result.push(cat); lastTopCat = cat; } else { const subcat = { id: valId, label: option.text().replace(/^.+\s-\s/, ""), selectable: true, }; if (!lastTopCat.childNodes) { lastTopCat.childNodes = []; } lastTopCat.childNodes.push(subcat); } }); return result; } static isSingleResultPage(body) { return !!body.find(this.params.singleResultPageDetector).length; } static parseSearchPage(body) { const rows = body.find(this.params.itemSelector); if ((rows.length === 0) && this.isSingleResultPage(body)) { const torrentLink = body.find(".viewdownloadbutton > a"); const uid = torrentLink.prop("href").match(/\d+$/)[0]; const categoryLink = body.find(".viewcategory > a:last-child"); return [{ name: body.find(".viewtorrentname").text(), uid, torrentUrl: torrentLink.prop("href"), pageUrl: `${this.scheme}://${this.hosts[0]}/?page=view&tid=${uid}`, category: categoryLink.prop("href").match(/\d+_\d+$/)[0], categoryName: categoryLink.text(), size: this.parseSizeStr(body.find("tr:nth-child(6) td:last-child").text()), seeders: parseInt(body.find(".viewsn").text(), 10), leechers: parseInt(body.find(".viewln").text(), 10), dateAdded: this.moment(body.find("tr:nth-child(2) td:last-child").text()).unix(), }]; } return $.map(rows, (node) => { const row = $(node); const titleLink = row.find(".tlistname > a"); return { name: titleLink.text(), uid: titleLink.prop("href").match(/\d+$/)[0], pageUrl: this.stripHostPrefix(titleLink.prop("href")), torrentUrl: this.stripHostPrefix(row.find(".tlistdownload > a").prop("href")), category: row.find(".tlisticon a").prop("href").match(/\d+_\d+$/)[0], categoryName: row.find(".tlisticon img").prop("alt"), size: this.parseSizeStr(row.find(".tlistsize").text()), seeders: parseInt(row.find(".tlistsn").text(), 10), leechers: parseInt(row.find(".tlistln").text(), 10), timesDownloaded: parseInt(row.find(".tlistdn").text(), 10), }; }); } static formRequest(str, options, referer, address, currentPage) { const sortByTable = { name: 6, size: 5, seeders: 2, leechers: 3, dateAdded: undefined, // Default }; const sortDescTable = { false: 2, true: undefined, // Default }; const sortBy = sortByTable[options.sortBy] || sortByTable.dateAdded; const sortDesc = sortDescTable[!!options.sortDesc] || sortDescTable.true; address.setSearch({ page: "search", sort: sortBy, order: sortDesc, term: str, }); if (currentPage > 0) { address.setSearch({ offset: currentPage + 1, }); } } }
/** * @method localStorageInit * @param {String} arg0 */ ca.localStorageInit = function ( fullpath ) { }; /** * @method localStorageGetItem */ ca.localStorageFree = function ( ) { }; /** * @method localStorageGetItem * @param {String} arg0 * @param {String} arg1 */ ca.localStorageSetItem = function ( key, value ) { }; /** * @method localStorageGetItem * @param {String} arg0 * @return {String} */ ca.localStorageGetItem = function ( key ) { return ""; }; /** * @method localStorageGetItem * @param {String} arg0 */ ca.localStorageRemoveItem = function ( key ) { }; /** * @class CAMotionManager */ ca.CAMotionManager = { /** * @method stopGyroscope */ startGyroscope : function ( func ) { }, }; /** * @class CADatePickerView */ ca.CADatePickerView = { /** * @method stopGyroscope */ onSelectRow : function ( func ) { }, }; /** * @class CADatePickerView */ ca.CADownloadManager = { /** * @method stopGyroscope */ setDownloadManagerDelegate : function ( delegate ) { }, }; /** * @class CANotificationCenter */ ca.CANotificationCenter = { /** * @method removeObserver * @param {func} arg0 * @param {ca.CAObject} arg1 * @param {String} arg2 */ addObserver : function ( func, caobject, str ) { }, };
import { Constants } from "expo"; import { Platform } from "react-native"; export default { getUniqueID() { return Constants.deviceId; } };
/* eslint-env browser */ /* global process */ import React from 'react'; import { Router } from 'react-router'; import { Provider } from 'react-redux'; import cookie from './utils/cookie'; // ルートとコンポーネントの紐付けを定義 import routes from './routes'; import { routerStateChange } from './actions/router'; import { createRedux } from './utils/redux'; // process.env.NODE_ENV === 'production'ならwindow.__INITIAL_STATE__をセット const store = createRedux((process.env.NODE_ENV === 'production') ? window.__INITIAL_STATE__ : { auth: { token: cookie.get('token') || '' } }); export default class Root extends React.Component { static propTypes = { // propsにhistoryがある history: React.PropTypes.object.isRequired } render() { return ( <Provider store={store}>{() => ( <Router history={this.props.history} routes={routes(store, true)} onUpdate={function() { // app/actions/router.jsを使用 // stateのアップデートを検知して更新 store.dispatch(routerStateChange(this.state)); }} /> )}</Provider> ); } }
var present="aboutmebutt"; function rightclickfunc() { if(present=="aboutmebutt") present="personalbutt"; else if(present=="personalbutt") present="academicbutt"; else if(present=="academicbutt") present="interestbutt"; else if(present=="interestbutt") present="otheractbutt"; clickfunction(present); } function leftclickfunc() { if(present=="personalbutt") present="aboutmebutt"; if(present=="academicbutt") present="personalbutt"; if(present=="interestbutt") present="academicbutt"; if(present=="otheractbutt") present="interestbutt"; clickfunction(present); } function previousstate() { var but; but=document.getElementById("aboutmebutt"); but.className="normalbutt"; but=document.getElementById("personalbutt"); but.className="normalbutt"; but=document.getElementById("academicbutt"); but.className="normalbutt"; but=document.getElementById("interestbutt"); but.className="normalbutt"; but=document.getElementById("otheractbutt"); but.className="normalbutt"; but=document.getElementById(present); but.className="selectedbutt"; clearheads(); var str=present.replace("butt","head"); var headpointer=document.getElementById(str); headpointer.className="show"; } function clickfunction(id) { present=id; previousstate(); var f1,a1,a2; a1=document.getElementById("leftarrow"); a1.className="show"; a2=document.getElementById("rightarrow"); a2.className="show"; if(id=="aboutmebutt") a1.className="hide"; if(id=="otheractbutt") a2.className="hide"; f1=document.getElementById("footer"); f1.className="hide"; f1=document.getElementById("footer2"); f1.className="hide"; var but; but=document.getElementById("aboutmebutt"); but.className="normalbutt"; but=document.getElementById("personalbutt"); but.className="normalbutt"; but=document.getElementById("academicbutt"); but.className="normalbutt"; but=document.getElementById("interestbutt"); but.className="normalbutt"; but=document.getElementById("otheractbutt"); but.className="normalbutt"; but=document.getElementById(id); but.className="selectedbutt"; sidebox=document.getElementById("favourites"); if(!(id=="aboutmebutt")) { sidebox.className="show"; f1=document.getElementById("footer2"); f1.className="show"; } else { sidebox.className="hide"; f1=document.getElementById("footer"); f1.className="show"; } var str=document.getElementById("aboutmecont"); str.className="hide"; str=document.getElementById("personalcont"); str.className="hide"; str=document.getElementById("academiccont"); str.className="hide"; str=document.getElementById("interestcont"); str.className="hide"; str=document.getElementById("otheractcont"); str.className="hide"; var main=id.replace("butt","cont"); var str1=document.getElementById(main); str1.className="show"; } function clearheads() { var str=document.getElementById("aboutmehead"); str.className="hide"; var str=document.getElementById("personalhead"); str.className="hide"; var str=document.getElementById("academichead"); str.className="hide"; var str=document.getElementById("interesthead"); str.className="hide"; var str=document.getElementById("otheracthead"); str.className="hide"; } function hoverfunction(id) { var but; but=document.getElementById("aboutmebutt"); but.className="normalbutt"; but=document.getElementById("personalbutt"); but.className="normalbutt"; but=document.getElementById("academicbutt"); but.className="normalbutt"; but=document.getElementById("interestbutt"); but.className="normalbutt"; but=document.getElementById("otheractbutt"); but.className="normalbutt"; but=document.getElementById(id); but.className="hoverbutt"; but=document.getElementById(present); but.className="selectedbutt"; var str=id.replace("butt","head"); var headpointer=document.getElementById(str); clearheads(); headpointer.className="show"; }
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @file Preview plugin. */ (function() { var previewCmd = { modes : { wysiwyg:1, source:1 }, canUndo : false, readOnly : 1, exec : function( editor ) { var sHTML, config = editor.config, baseTag = config.baseHref ? '<base href="' + config.baseHref + '"/>' : '', isCustomDomain = CKEDITOR.env.isCustomDomain(); if ( config.fullPage ) { sHTML = editor.getData() .replace( /<head>/, '$&' + baseTag ) .replace( /[^>]*(?=<\/title>)/, '$& &mdash; ' + editor.lang.preview ); } else { var bodyHtml = '<body ', body = editor.document && editor.document.getBody(); if ( body ) { if ( body.getAttribute( 'id' ) ) bodyHtml += 'id="' + body.getAttribute( 'id' ) + '" '; if ( body.getAttribute( 'class' ) ) bodyHtml += 'class="' + body.getAttribute( 'class' ) + '" '; } bodyHtml += '>'; sHTML = editor.config.docType + '<html dir="' + editor.config.contentsLangDirection + '">' + '<head>' + baseTag + '<title>' + editor.lang.preview + '</title>' + CKEDITOR.tools.buildStyleHtml( editor.config.contentsCss ) + '</head>' + bodyHtml + editor.getData() + '</body></html>'; } var iWidth = 640, // 800 * 0.8, iHeight = 420, // 600 * 0.7, iLeft = 80; // (800 - 0.8 * 800) /2 = 800 * 0.1. try { var screen = window.screen; iWidth = Math.round( screen.width * 0.8 ); iHeight = Math.round( screen.height * 0.7 ); iLeft = Math.round( screen.width * 0.1 ); } catch ( e ){} var sOpenUrl = ''; if ( isCustomDomain ) { window._cke_htmlToLoad = sHTML; sOpenUrl = 'javascript:void( (function(){' + 'document.open();' + 'document.domain="' + document.domain + '";' + 'document.write( window.opener._cke_htmlToLoad );' + 'document.close();' + 'window.opener._cke_htmlToLoad = null;' + '})() )'; } var oWindow = window.open( sOpenUrl, null, 'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=' + iWidth + ',height=' + iHeight + ',left=' + iLeft ); if ( !isCustomDomain ) { var doc = oWindow.document; doc.open(); doc.write( sHTML ); doc.close(); // Chrome will need this to show the embedded. (#8016) CKEDITOR.env.webkit && setTimeout( function() { doc.body.innerHTML += ''; }, 0 ); } } }; var pluginName = 'preview'; // Register a plugin named "preview". CKEDITOR.plugins.add( pluginName, { init : function( editor ) { editor.addCommand( pluginName, previewCmd ); editor.ui.addButton( 'Preview', { label : editor.lang.preview, command : pluginName }); } }); })();
/** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var hovertemplateAttrs = require('../../plots/template_attributes').hovertemplateAttrs; var texttemplateAttrs = require('../../plots/template_attributes').texttemplateAttrs; var scatterGeoAttrs = require('../scattergeo/attributes'); var scatterAttrs = require('../scatter/attributes'); var mapboxAttrs = require('../../plots/mapbox/layout_attributes'); var baseAttrs = require('../../plots/attributes'); var colorScaleAttrs = require('../../components/colorscale/attributes'); var extendFlat = require('../../lib/extend').extendFlat; var overrideAll = require('../../plot_api/edit_types').overrideAll; var lineAttrs = scatterGeoAttrs.line; var markerAttrs = scatterGeoAttrs.marker; module.exports = overrideAll({ lon: scatterGeoAttrs.lon, lat: scatterGeoAttrs.lat, // locations // locationmode mode: extendFlat({}, scatterAttrs.mode, { dflt: 'markers', description: [ 'Determines the drawing mode for this scatter trace.', 'If the provided `mode` includes *text* then the `text` elements', 'appear at the coordinates. Otherwise, the `text` elements', 'appear on hover.' ].join(' ') }), text: extendFlat({}, scatterAttrs.text, { description: [ 'Sets text elements associated with each (lon,lat) pair', 'If a single string, the same string appears over', 'all the data points.', 'If an array of string, the items are mapped in order to the', 'this trace\'s (lon,lat) coordinates.', 'If trace `hoverinfo` contains a *text* flag and *hovertext* is not set,', 'these elements will be seen in the hover labels.' ].join(' ') }), texttemplate: texttemplateAttrs({editType: 'plot'}, { keys: ['lat', 'lon', 'text'] }), hovertext: extendFlat({}, scatterAttrs.hovertext, { description: [ 'Sets hover text elements associated with each (lon,lat) pair', 'If a single string, the same string appears over', 'all the data points.', 'If an array of string, the items are mapped in order to the', 'this trace\'s (lon,lat) coordinates.', 'To be seen, trace `hoverinfo` must contain a *text* flag.' ].join(' ') }), line: { color: lineAttrs.color, width: lineAttrs.width // TODO // dash: dash }, connectgaps: scatterAttrs.connectgaps, marker: extendFlat({ symbol: { valType: 'string', dflt: 'circle', role: 'style', arrayOk: true, description: [ 'Sets the marker symbol.', 'Full list: https://www.mapbox.com/maki-icons/', 'Note that the array `marker.color` and `marker.size`', 'are only available for *circle* symbols.' ].join(' ') }, angle: { valType: 'number', dflt: 'auto', role: 'style', arrayOk: true, description: [ 'Sets the marker orientation from true North, in degrees clockwise.', 'When using the *auto* default, no rotation would be applied', 'in perspective views which is different from using a zero angle.' ].join(' ') }, allowoverlap: { valType: 'boolean', dflt: false, role: 'style', description: [ 'Flag to draw all symbols, even if they overlap.' ].join(' ') }, opacity: markerAttrs.opacity, size: markerAttrs.size, sizeref: markerAttrs.sizeref, sizemin: markerAttrs.sizemin, sizemode: markerAttrs.sizemode }, colorScaleAttrs('marker') // line ), fill: scatterGeoAttrs.fill, fillcolor: scatterAttrs.fillcolor, textfont: mapboxAttrs.layers.symbol.textfont, textposition: mapboxAttrs.layers.symbol.textposition, below: { valType: 'string', role: 'info', description: [ 'Determines if this scattermapbox trace\'s layers are to be inserted', 'before the layer with the specified ID.', 'By default, scattermapbox layers are inserted', 'above all the base layers.', 'To place the scattermapbox layers above every other layer, set `below` to *\'\'*.' ].join(' ') }, selected: { marker: scatterAttrs.selected.marker }, unselected: { marker: scatterAttrs.unselected.marker }, hoverinfo: extendFlat({}, baseAttrs.hoverinfo, { flags: ['lon', 'lat', 'text', 'name'] }), hovertemplate: hovertemplateAttrs(), }, 'calc', 'nested');
/* globals _wpCustomizeHeader, _ */ (function( $, wp ) { var api = wp.customize; api.HeaderTool = {}; /** * wp.customize.HeaderTool.ImageModel * * A header image. This is where saves via the Customizer API are * abstracted away, plus our own AJAX calls to add images to and remove * images from the user's recently uploaded images setting on the server. * These calls are made regardless of whether the user actually saves new * Customizer settings. * * @constructor * @augments Backbone.Model */ api.HeaderTool.ImageModel = Backbone.Model.extend({ defaults: function() { return { header: { attachment_id: 0, url: '', timestamp: _.now(), thumbnail_url: '' }, choice: '', selected: false, random: false }; }, initialize: function() { this.on('hide', this.hide, this); }, hide: function() { this.set('choice', ''); api('header_image').set('remove-header'); api('header_image_data').set('remove-header'); }, destroy: function() { var data = this.get('header'), curr = api.HeaderTool.currentHeader.get('header').attachment_id; // If the image we're removing is also the current header, unset // the latter if (curr && data.attachment_id === curr) { api.HeaderTool.currentHeader.trigger('hide'); } wp.ajax.post( 'custom-header-remove', { nonce: _wpCustomizeHeader.nonces.remove, wp_customize: 'on', theme: api.settings.theme.stylesheet, attachment_id: data.attachment_id }); this.trigger('destroy', this, this.collection); }, save: function() { if (this.get('random')) { api('header_image').set(this.get('header').random); api('header_image_data').set(this.get('header').random); } else { if (this.get('header').defaultName) { api('header_image').set(this.get('header').url); api('header_image_data').set(this.get('header').defaultName); } else { api('header_image').set(this.get('header').url); api('header_image_data').set(this.get('header')); } } api.HeaderTool.combinedList.trigger('control:setImage', this); }, importImage: function() { var data = this.get('header'); if (data.attachment_id === undefined) { return; } wp.ajax.post( 'custom-header-add', { nonce: _wpCustomizeHeader.nonces.add, wp_customize: 'on', theme: api.settings.theme.stylesheet, attachment_id: data.attachment_id } ); }, shouldBeCropped: function() { if (this.get('themeFlexWidth') === true && this.get('themeFlexHeight') === true) { return false; } if (this.get('themeFlexWidth') === true && this.get('themeHeight') === this.get('imageHeight')) { return false; } if (this.get('themeFlexHeight') === true && this.get('themeWidth') === this.get('imageWidth')) { return false; } if (this.get('themeWidth') === this.get('imageWidth') && this.get('themeHeight') === this.get('imageHeight')) { return false; } return true; } }); /** * wp.customize.HeaderTool.ChoiceList * * @constructor * @augments Backbone.Collection */ api.HeaderTool.ChoiceList = Backbone.Collection.extend({ model: api.HeaderTool.ImageModel, // Ordered from most recently used to least comparator: function(model) { return -model.get('header').timestamp; }, initialize: function() { var current = api.HeaderTool.currentHeader.get('choice').replace(/^https?:\/\//, ''), isRandom = this.isRandomChoice(api.get().header_image); // Overridable by an extending class if (!this.type) { this.type = 'uploaded'; } // Overridable by an extending class if (typeof this.data === 'undefined') { this.data = _wpCustomizeHeader.uploads; } if (isRandom) { // So that when adding data we don't hide regular images current = api.get().header_image; } this.on('control:setImage', this.setImage, this); this.on('control:removeImage', this.removeImage, this); this.on('add', this.maybeAddRandomChoice, this); _.each(this.data, function(elt, index) { if (!elt.attachment_id) { elt.defaultName = index; } if (typeof elt.timestamp === 'undefined') { elt.timestamp = 0; } this.add({ header: elt, choice: elt.url.split('/').pop(), selected: current === elt.url.replace(/^https?:\/\//, '') }, { silent: true }); }, this); if (this.size() > 0) { this.addRandomChoice(current); } }, maybeAddRandomChoice: function() { if (this.size() === 1) { this.addRandomChoice(); } }, addRandomChoice: function(initialChoice) { var isRandomSameType = RegExp(this.type).test(initialChoice), randomChoice = 'random-' + this.type + '-image'; this.add({ header: { timestamp: 0, random: randomChoice, width: 245, height: 41 }, choice: randomChoice, random: true, selected: isRandomSameType }); }, isRandomChoice: function(choice) { return (/^random-(uploaded|default)-image$/).test(choice); }, shouldHideTitle: function() { return this.size() < 2; }, setImage: function(model) { this.each(function(m) { m.set('selected', false); }); if (model) { model.set('selected', true); } }, removeImage: function() { this.each(function(m) { m.set('selected', false); }); } }); /** * wp.customize.HeaderTool.DefaultsList * * @constructor * @augments wp.customize.HeaderTool.ChoiceList * @augments Backbone.Collection */ api.HeaderTool.DefaultsList = api.HeaderTool.ChoiceList.extend({ initialize: function() { this.type = 'default'; this.data = _wpCustomizeHeader.defaults; api.HeaderTool.ChoiceList.prototype.initialize.apply(this); } }); })( jQuery, window.wp );
'use strict'; var devConfig = { production: false, server: { port: 8080 }, src: { js: ['./*.js', './client/**/*.js', './tasks/**/*.js', './test/**/*.js'], scripts: './client/**/*.js', tests: './test/**/*.js', testConfig: './karma.conf.js', styles: 'client/**/*.scss', main: 'app.js' }, dest: { root: './build' } }; module.exports = devConfig;
/** * Created by lingfengliang on 2017/4/7. */ import React from 'react'; import { TouchableHighlight, Image, TouchableOpacity, StyleSheet, Text, View, } from 'react-native'; export default class ViewUtils { /** * 获取设置页的Item * @param callBack 单击item的回调 * @param icon 左侧图标 * @param text 显示的文本 * @param tintStyle 图标着色 * @param expandableIco 右侧图标 * @return {XML} */ static getSettingItem(callBack, icon, text, tintStyle, expandableIco) { return ( <TouchableHighlight onPress={callBack}> <View style={[styles.setting_item_container]}> <View style={{alignItems: 'center', flexDirection: 'row'}}> {icon ? <Image source={icon} resizeMode='stretch' style={[{opacity: 1, width: 16, height: 16, marginRight: 10,}, tintStyle]}/> : <View style={{opacity: 1, width: 16, height: 16, marginRight: 10,}}/> } <Text>{text}</Text> </View> <Image source={expandableIco ? expandableIco : require('../../res/images/ic_tiaozhuan.png')} style={[{ marginRight: 10, height: 22, width: 22, alignSelf: 'center', opacity: 1 }, tintStyle]}/> </View> </TouchableHighlight> ) } static getLeftButton(callBack) { return <TouchableOpacity style={{padding: 8}} onPress={callBack}> <Image style={{width: 26, height: 26,}} source={require('../../res/images/ic_arrow_back_white_36pt.png')}/> </TouchableOpacity> } static getRightButton(title, callBack) { return <TouchableOpacity style={{alignItems: 'center',}} onPress={callBack}> <View style={{marginRight: 10}}> <Text style={{fontSize: 20, color: '#FFFFFF',}}>{title}</Text> </View> </TouchableOpacity> } /** * 获取更多按钮 * @param callBack * @returns {XML} */ static getMoreButton(callBack) { return <TouchableHighlight underlayColor={'transparent'} ref="moreMenuButton" style={{padding: 5}} onPress={callBack} > <View style={{paddingRight: 8}}> <Image style={{width: 24, height: 24,}} source={require('../../res/images/ic_more_vert_white_48pt.png')} /> </View> </TouchableHighlight> } /** * 获取分享按钮 * @param callBack * @returns {XML} */ static getShareButton(callBack) { return <TouchableHighlight underlayColor={'transparent'} onPress={callBack} > <Image style={{width: 20, height: 20,opacity:0.9,marginRight:10,tintColor:'white'}} source={require('../../res/images/ic_share.png')}/> </TouchableHighlight> } } const styles = StyleSheet.create({ setting_item_container: { backgroundColor: 'white', padding: 10, height: 60, alignItems: 'center', justifyContent: 'space-between', flexDirection: 'row' }, })
'use strict'; const Api = require('./Api'); module.exports = class Plans extends Api { constructor(api_key, api_secret) { super(api_key, api_secret); } getPlans(data, cb) { return this.get({ path: '/plans', body: data }, cb); } getPlan(plan_id, cb) { return this.get({ path: '/plan/' + plan_id }, cb); } createPlan(data, cb) { return this.post({ path: '/create/plan/', body: data }, cb); } updatePlan(data, cb) { return this.post({ path: '/update/plan/', body: data }, cb); } };
const hasDOM = typeof document !== 'undefined'; const defaultWormhole = 'paper-wormhole'; export default function initialize() { if (!hasDOM) { return; } let application = arguments[1] || arguments[0]; let rootElementSelector = application.rootElement || 'body'; let rootElement = document.querySelector(rootElementSelector); let wormhole = document.createElement('div'); wormhole.id = defaultWormhole; rootElement.appendChild(wormhole); }
// 'Red México Abierto' webapp var app = angular.module('redMxAbiertoApp', ['ngCookies']); app.controller('stagesCtrl', function(){ var self = this; self.names = []; self.openModal = function(id) { var modalId = "#stageModal" + id; angular.element(modalId).modal('show'); }; }); app.controller('stepsCtrl', function(){ var self = this; self.names = []; self.openModal = function(id) { var modalId = "#stepModal" + id; angular.element(modalId).modal('show'); }; }); app.controller('activitiesCtrl', [ '$http', '$cookies', function($http, $cookies){ var self = this; self.initialize = function() { // initialize variables self.names = []; self.user_activities = []; self.user_activities_in_step = {}; self.hideWelcomeMessage = !!$cookies["_hide_first_log_in_message"]; // active tab variables self.currentStage = null; self.currentStep = null; }; self.newUserActivity = function(activity){ // add self to user activities and in corresponding // step activities container if( angular.isDefined(activity) ){ var userActivityId = activity['userActivityId']; var stepKey = activity['stepId']; var done = activity['done']; self.user_activities[userActivityId] = done; if( angular.isUndefined(self.user_activities_in_step[stepKey]) ){ self.user_activities_in_step[stepKey] = []; } self.user_activities_in_step[stepKey].push(userActivityId); } }; self.activityChecked = function(activityId, currentStepId, nextTabs) { // Get token var csrfToken = angular.element('meta[name=csrf-token]')[0].content; // Checkbox id and state to change var data = { authenticity_token: csrfToken, user_activity: { id: activityId, checked: self.user_activities[activityId] } }; // Let's submit the checkbox info $http.post('/user_activities', data) .success(function(data, status, headers, config){ // do something when the checkbox has beeen successfully submitted ... // let's change tabs if all activities for a step have // been masrked as completed. var nextStep = true; angular.forEach(self.user_activities_in_step[currentStepId], function(userActivityId){ if (self.user_activities[userActivityId] == false){ nextStep = false; } }); if( nextStep && angular.isDefined(nextTabs) ){ self.setTabs( nextTabs['stageId'], nextTabs['stepId'] ); } }); }; self.openModal = function(id) { var modalId = "#activityModal" + id; angular.element(modalId).modal('show'); }; self.hideFirstTimeUserMessage = function() { // Let's set a cookie so that the message doesn't appear again self.hideWelcomeMessage = true; $cookies["_hide_first_log_in_message"] = true; }; // let's add some code for the active tabs // stages_path self.setTabs = function(stageId, stepId) { self.setStageTab(stageId); self.setStepTab(stepId); }; self.setStageTab = function(id) { self.currentStage = id; }; self.setStepTab = function(id) { self.currentStep = id; }; self.initialize(); }]);
'use strict'; describe('service', function() { beforeEach(module('mysterysolver.services')); describe('navigation service', function() { var $location, navigation; beforeEach(inject(['$location', 'navigation', function (location, mn) { $location = location; navigation = mn; }])); it('should throw when getting data without navigation', function() { expect(function () { navigation.getNavigationData(); }).toThrow(); }); describe("after navigating", function() { beforeEach(function() { navigation.navigate('/dest', 1); }); it('should set the path on $location', function() { expect($location.path()).toBe('/dest'); }); it('should return the data', function() { expect(navigation.getNavigationData()).toBe(1); }); it('should throw when fetching data from a different location', function() { $location.path('destination2'); expect(function () { navigation.getNavigationData(); }).toThrow(); }); }); }); });
// Load modules var Lab = require('lab'); var Joi = require('../lib'); var Validate = require('./helper'); // Declare internals var internals = {}; // Test shortcuts var expect = Lab.expect; var before = Lab.before; var after = Lab.after; var describe = Lab.experiment; var it = Lab.test; describe('date', function () { it('matches specific date', function (done) { var now = Date.now(); expect(Joi.validate(new Date(now), Joi.date().valid(new Date(now)))).to.not.exist; done(); }); describe('#validate', function () { it('validates min', function (done) { Validate(Joi.date().min('1-1-2012'), [ ['1-1-2013', true], ['1-1-2012', true], [0, false], ['1-1-2000', false] ]); done(); }); it('validates max', function (done) { Validate(Joi.date().max('1-1-2013'), [ ['1-1-2013', true], ['1-1-2012', true], [0, true], ['1-1-2014', false] ]); done(); }); }); });
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'gatsby'; import Dropdown from './Dropdown'; import { getPages } from '../../api'; import { handlePreviousPage, handleNextPage } from '../../api/url'; const PageItem = ({ number, content }) => ( <li className={`page-item${number < 0 ? ' disabled' : ''}`}> <Link className="page-link" to={`${number}`} href={number}> {content || number} </Link> </li> ); const getPageNumber = pathname => pathname.split('/')[2]; const Pagination = ({ pathname, pageCount }) => { const currentPageNumber = getPageNumber(pathname); return ( <nav aria-label="Page navigation example"> <ul className="pagination justify-content-center"> <PageItem number={handlePreviousPage(currentPageNumber)} content="Previous" /> <li className="page-item"> <Dropdown pages={getPages(pageCount)} text={currentPageNumber} /> </li> <PageItem number={handleNextPage(currentPageNumber, pageCount)} content="Next" /> </ul> </nav> ); }; PageItem.propTypes = { number: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, content: PropTypes.string.isRequired, }; Pagination.propTypes = { pathname: PropTypes.string.isRequired, pageCount: PropTypes.number.isRequired, }; export default Pagination;
({ "clearFilterDialogTitle": "Netejar el filtre", "filterDefDialogTitle": "Filtre", "ruleTitleTemplate": "Regla ${0}", "conditionEqual": "igual que", "conditionNotEqual": "no és igual que", "conditionLess": "és menys que", "conditionLessEqual": "és menys o igual que", "conditionLarger": "és més que", "conditionLargerEqual": "és més o igual que", "conditionContains": "conté", "conditionIs": "és", "conditionStartsWith": "comença per", "conditionEndWith": "acaba per", "conditionNotContain": "no conté", "conditionIsNot": "no és", "conditionNotStartWith": "no comença per", "conditionNotEndWith": "no acaba per", "conditionBefore": "abans", "conditionAfter": "després", "conditionRange": "interval", "conditionIsEmpty": "és buit", "all": "tot", "any": "qualsevol", "relationAll": "totes les regles", "waiRelAll": "Fes coincidir totes les regles següents:", "relationAny": "qualsevol regla", "waiRelAny": "Fes coincidir qualsevol de les regles següents:", "relationMsgFront": "Coincidència", "relationMsgTail": "", "and": "i", "or": "o", "addRuleButton": "Afegeix regla", "waiAddRuleButton": "Afegeix una regla nova", "removeRuleButton": "Elimina regla", "waiRemoveRuleButtonTemplate": "Elimina la regla ${0}", "cancelButton": "Cancel·la", "waiCancelButton": "Cancel·la aquest diàleg", "clearButton": "Esborra", "waiClearButton": "Neteja el filtre", "filterButton": "Filtre", "waiFilterButton": "Envia el filtre", "columnSelectLabel": "Columna", "waiColumnSelectTemplate": "Columna per a la regla ${0}", "conditionSelectLabel": "Condició", "waiConditionSelectTemplate": "Condició per a la regla ${0}", "valueBoxLabel": "Valor", "waiValueBoxTemplate": "Especifiqueu el valor de filtre per a la regla ${0}", "rangeTo": "a", "rangeTemplate": "de ${0} a ${1}", "statusTipHeaderColumn": "Columna", "statusTipHeaderCondition": "Regles", "statusTipTitle": "Barra de filtre", "statusTipMsg": "Feu clic aquí a la barra de filtre per filtrar els valors a ${0}.", "anycolumn": "qualsevol columna", "statusTipTitleNoFilter": "Barra de filtre", "statusTipTitleHasFilter": "Filtre", "statusTipRelPre": "Coincidència", "statusTipRelPost": "regles.", "defaultItemsName": "elements", "filterBarMsgHasFilterTemplate": "Es mostren ${0} de ${1} ${2}.", "filterBarMsgNoFilterTemplate": "No s'ha aplicat cap filtre", "filterBarDefButton": "Defineix filtre", "waiFilterBarDefButton": "Filtra la taula", "a11yFilterBarDefButton": "Filtre...", "filterBarClearButton": "Netejar filtre", "waiFilterBarClearButton": "Neteja el filtre", "closeFilterBarBtn": "Tancar la barra de filtre", "clearFilterMsg": "Això eliminarà el filtre i mostrarà tots els registres disponibles.", "anyColumnOption": "Qualsevol columna", "trueLabel": "Cert", "falseLabel": "Fals" })
/** * @module abe-protractor * * @requires {@link https://www.npmjs.org/package/protractor|protractor} * @requires {@link https://www.npmjs.org/package/glob|glob} * @requires {@link http://nodejs.org/api/fs.html|fs} * @requires {@link http://nodejs.org/api/path.html|path} * @requires {@link http://nodejs.org/api/util.html|util} * * * @description * Using ABE-spec as a base, allow for automatic creating of stubs using * ngMockE2E $httpBackend. * * @example * var abeProtractor = require('abe-protractor'); * * abeProtractor.setupServiceStubs({ * mocksLocation: 'myApp/mocks/**\/*\/' * stubsLocation: 'myApp/mockStubs/', * log: true * }); * // This will then setup stubs you have manually created and some default * // mocks */ var glob = require('glob'), path = require('path'), util = require('util'), fs = require('fs'), errors = { 'NO_FOLDER': 'not a folder', 'NO_JSON': 'no JSON files in folder' }, setupStub, setupServiceStubs; /** * @private * @description * Setup a stub and add to the browser. * * @param {string} match Location of mock * @param {object} options Options to be passed to the setupServiceStubs * @property {string} options.mocksLocation This is your location of your ABE * mocks * @property {string} options.stubsLocation This is base location of your * Angular custom Stubs * @property {boolean} options.log Whether or not to log out the stubs setup * */ setupStub = function (match, options) { // Return early if this isn't a folder if (match.slice(1 * -1) !== path.sep) { return errors['NO_FOLDER']; } var jsonFiles = glob.sync(match + '*.json'); // Return early if there are no JSON files in this folder if (jsonFiles.length === 0) { return errors['NO_JSON']; } var folder = path.basename(match), moduleName = util.format('app.stubs.%s', folder), filename = util.format('%s.stub.js', folder), stubPath = path.join(process.cwd(), options.stubsLocation, filename), stub, data = {}, methods = []; if (fs.existsSync(stubPath)) { stub = require(stubPath); } else { stub = require('./generate-stub.js').generateStub; data = { 'stub-options': { 'module_name': moduleName } }; } // Require each of the JSON files in the folder into a object hash // keyed by filename sans file extention, yielding an object with // a structure similar to, // // { // query: {mock-data}, // get: {mock-data}, // post: {mock-data}, // put: {mock-data} // } jsonFiles.forEach(function (jsonPath) { var name = path.basename(jsonPath, '.json'); data[name] = require(path.relative(__dirname, jsonPath)); methods.push(name); }); if (options.log) { console.log(util.format('Adding %s module (%s)', moduleName, methods)); } // Tell Protractor to add the stubbed resource module to the app at // runtime. The mock data object is passed through to the stub. browser.addMockModule(moduleName, stub, data); }; /** * Setup Service Stubs * * @param {object} options Options to be passed to the setupServiceStubs * @property {string} options.mocksLocation This is your location of your ABE * mocks * @property {string} options.stubsLocation This is base location of your * Angular custom Stubs * @property {boolean} options.log Whether or not to log out the stubs setup */ setupServiceStubs = function (options) { // Loop over all JSON mock data folders pased to the setupServiceStubs glob .sync(options.mocksLocation, { mark: true }) .forEach(function (match) { setupStub(match, options); }); }; module.exports.setupServiceStubs = setupServiceStubs;
import React from 'react'; import BigCalendar from 'react-big-calendar'; import events from '../events'; class Timeslots extends React.Component { render() { return ( <BigCalendar {...this.props} events={events} step={15} timeslots={8} defaultView='week' defaultDate={new Date(2015, 3, 12)} /> ) } } export default Timeslots;
import log from 'npmlog' import { resolve as optimize } from 'knapsack-js' export default function knapsackForAlbums (albums, capacity, blockSize) { log.verbose('knapsackForAlbums', 'capacity', capacity, 'blockSize', blockSize) const albumList = [...albums] // used for displaying report const al = albumList.reduce((c, a) => c.set(a.path, a), new Map()) // used for difference calculation later const paths = new Set(al.keys()) // knapsack-js wants a list of object literals, which is hard to get directly // from a map const sizes = albumList.map((a) => ({ [a.path]: a.getSize(blockSize) })) log.verbose('knapsackForAlbums', 'sizes', sizes) const optimized = optimize(capacity, sizes) log.verbose('knapsackForAlbums', 'optimized', optimized) const keepers = new Set(optimized.map((i) => Object.keys(i)[0])) log.silly('knapsackForAlbums', 'keepers', keepers) const leftovers = [...paths].filter((p) => !keepers.has(p)) log.silly('knapsackForAlbums', 'leftovers', leftovers) return { included: [...keepers].map((p) => al.get(p)), discarded: leftovers.map((p) => al.get(p)) } }
/* jshint strict: true, undef: true, browser: true, jquery: true */ /* global moment */ (function () { 'use strict'; $.ajax({ type: 'get', url: '/challenges', success: function (msg) { var dones = 0; var ids = Object.keys(msg); ids.forEach(function (id) { $.ajax({ type: 'get', url: '/challenges/' + id + '/tokens', success: function (tokens) { dones++; msg[id].tokens = tokens; if (dones === ids.length) { console.log(msg); render(msg); } } }); }); } }); function makeid () { var text = ''; var possible = 'abcdefghijklmnopqrstuvwxyz'; var i = 7; while(i--) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; } // Render links function render (challenges) { var $list = $('#list').empty(); Object.keys(challenges).forEach(function (challenge) { var $li = $('<li/>'); var $span = $('<span/>'); var $a = $('<a href="#">Supprimer</a>'); $a.attr('data-tournament', challenge); var tooltip = ''; var tokens = challenges[challenge].tokens; tokens.forEach(function (token) { tooltip += token.name + ' : ' + token.value + '<br/>'; }); $span.text(challenges[challenge].title + ' - ') .attr('data-toggle', 'popover') .attr('data-tigger', 'focus') .off('mouseenter').mouseenter(function () { $(this).popover('show'); }) .off('mouseleave').mouseleave(function () { $(this).popover('hide'); }); $li.append($span) .append($a); $list.append($li); $span.popover({ content: tooltip, html: true, title: 'Tokens' }); }); $('[data-tournament]').off('click').click(function (e) { e.preventDefault(); if (!window.confirm('Supprimer le challenge ?')) { return; } $.ajax({ type: 'delete', url: '/challenges/' + $(this).attr('data-tournament'), success: function () { location.reload(); } }); }); } render({}); /** * Checks if the number is a integer * @param {Number} a The number * @returns {Boolean} True if the number is an integer */ function isInt (a) { return Math.floor(a) === a; } // Tokens input generator var $submit = $('#submit'); var $nbTokens = $('#nbTokens'); var $tokensList = $('#tokensList'); $nbTokens.on('keyup blur', function () { $tokensList.html(''); var val = parseFloat($nbTokens.val(), 10); if (!val || val < 0 || !isInt(val)) { $nbTokens.next().text('La valeur doit être numérique positive entière'); $submit.addClass('btn-disabled').attr('disabled', ''); return; } $submit.removeClass('btn-disabled').removeAttr('disabled'); $nbTokens.next().text(''); for (var i = 0; i < val; ++i) { var $li = $('<li/>'); var $input = $('<input/>') .attr('type', 'number') .attr('name', 'tokensPrices[]') .addClass('form-control') .addClass('input-sm') .addClass('tokens') .attr('placeholder', '10') .attr('required', ''); $li.html('Token ' + (i + 1) + ' (<span class="tokenVal">' + makeid() + '</span>) :'); $li.append($input); $tokensList.append($li); } }); $submit.off('click').click(function (e) { e.preventDefault(); var $title = $('#title'); var $descr = $('#description'); var vals = []; var tokens = $('.tokens').each(function () { var token = $(this).parent().children('.tokenVal').text(); var value = parseInt($(this).val(), 10); vals.push({ name: token, value: value }); }); $.ajax({ type: 'post', url: '/challenges', data: JSON.stringify({ title: $title.val(), description: $descr.val() }), success: function (msg) { var id = msg.id; var dones = 0; vals.forEach(function (val) { $.ajax({ type: 'patch', url: '/challenges/' + id, data: JSON.stringify(val), success: function () { dones++; if (dones === vals.length) { location.reload(); } } }); }); } }); }); }());
function format(flat) { var map = {}; flat.forEach(function(a) { map[a["@id"]] = a; }); var ontology = {}; (function(a) { ontology.version = a["http://www.w3.org/2002/07/owl#versionInfo"][0]["@value"]; ontology.label = a["http://www.w3.org/2000/01/rdf-schema#label"].find(function(a) { return a["@language"] === "ja"; })["@value"]; ontology.comment = a["http://www.w3.org/2000/01/rdf-schema#comment"].find(function(a) { return a["@language"] === "ja"; })["@value"]; })(map["http://imi.go.jp/ns/core/rdf"]); var dig = function(id) { var a = map[id]; var json = { id: id, label: a["http://www.w3.org/2000/01/rdf-schema#label"].find(function(a) { return a["@language"] === "ja"; })["@value"], comment: a["http://www.w3.org/2000/01/rdf-schema#comment"].find(function(a) { return a["@language"] === "ja"; })["@value"] }; json.children = flat.filter(function(a) { return (a["http://www.w3.org/2000/01/rdf-schema#subClassOf"] || []).find(function(b) { return b["@id"] === id; }); }).map(function(a) { return dig(a["@id"]); }); json.properties = (a["http://www.w3.org/2000/01/rdf-schema#subClassOf"] || []).filter(function(b) { return b["@id"].indexOf("_:") === 0; }).map(function(b) { return map[b["@id"]]; }).map(function(b) { var id = b["http://www.w3.org/2002/07/owl#onProperty"][0]["@id"]; var prop = { id: id, min: 0, range: map[id]["http://www.w3.org/2000/01/rdf-schema#range"][0]["@id"] }; if (b["http://www.w3.org/2002/07/owl#maxQualifiedCardinality"]) prop.max = 1; if (b["http://www.w3.org/2002/07/owl#maxCardinality"]) prop.max = 1; return prop; }); return json; }; ontology.root = dig("http://imi.go.jp/ns/core/rdf#概念型"); return ontology; } var defaultInstance = { "http://www.w3.org/2001/XMLSchema#string": "文字列", "http://www.w3.org/2002/07/owl#Thing": "http://example.org/", "http://www.w3.org/2001/XMLSchema#integer": 1234567890, "http://www.w3.org/2001/XMLSchema#nonNegativeInteger": 1234567890, "http://www.w3.org/2001/XMLSchema#date": "2017-05-11", "http://www.w3.org/2001/XMLSchema#time": "00:00:00", "http://www.w3.org/2001/XMLSchema#dateTime": "2017-05-11T00:00:00", "http://www.w3.org/2001/XMLSchema#decimal": 1234.56789, "http://www.w3.org/2001/XMLSchema#double": 10.0e25, "urn:un:unece:uncefact:codelist:standard:ISO:ISO3AlphaCurrencyCode:2012-08-31#ISO3AlphaCurrencyCodeContentType": "YEN" }; fetch("https://imi.go.jp/ns/core/rdf.jsonld").then(function(a) { return a.json(); }).then(function(json) { return new Promise(function(resolve, reject) { jsonld.flatten(json, function(err, flat) { resolve(format(flat)); }); }); }).then(function(ontology) { console.log(ontology); $("#version").text(ontology.version); var render = function(anc) { var a = anc[anc.length - 1]; var div = $("<div class='clazz'/>"); div.attr("id", a.label); $("#menu>ul").append($("<li/>").css("text-indent", (anc.length - 1) + "em").append( $("<a/>").attr("href", "#" + a.label).text(a.label))); var ul = $("<ul/>").appendTo(div); anc.forEach(function(v, i) { var a = $("<a/>").attr("href", "#" + v.label).text(v.label); if (i === anc.length - 1) a = $("<b/>").text(v.label); ul.append($("<li/>").append(a)); }); div.append($("<p/>").text(a.comment)); var compact = function(v) { return v.replace(/.*#/, ""); }; var instance1 = { "@context": "https://imi.go.jp/ns/core/context.jsonld" }; var instance2 = { "@context": "https://imi.go.jp/ns/core/context.jsonld" }; anc.forEach(function(v) { instance1["@type"] = compact(v.id); instance2["@type"] = compact(v.id); v.properties.forEach(function(w) { var val = defaultInstance[w.range] || { "@type": compact(w.range) }; instance1[compact(w.id)] = w.max === 1 ? val : [val]; instance2[compact(w.id)] = val; }); }); div.append($("<button>配列あり</button>").attr("value", JSON.stringify(instance1, null, " "))); div.append($("<button>配列なし</button>").attr("value", JSON.stringify(instance2, null, " "))); div.append($("<pre contentEditable='true'/>").text(JSON.stringify(instance2, null, " "))); $("#container").append(div); a.children.forEach(function(v) { render(anc.concat(v)); }); }; render([ontology.root]); $("button").click(function() { $(this).parent().find("pre").text($(this).val()); }); });
import Http from 'helper/Http'; import { BackendUrl } from 'Config'; // ------------------------------------ // Constants // ------------------------------------ export const LOAD_QUEUE_REQUEST = 'REQUEST_QUEUE' export const LOAD_QUEUE_SUCCESS = 'RECEIVE_QUEUE' export const LOAD_QUEUE_FAILURE = 'LOAD_QUEUE_FAILURE' // ------------------------------------ // Actions // ------------------------------------ export function loadQueue() { return (dispatch) => dispatch({ types: [LOAD_QUEUE_REQUEST, LOAD_QUEUE_SUCCESS, LOAD_QUEUE_FAILURE], shouldCallAPI: (state) => !state.queues, callAPI: () => Http.get(`${BackendUrl}/roles`), payload: {} }) } // ------------------------------------ // Action Handlers // ------------------------------------ const QUEUE_ACTION_HANDLERS = { [LOAD_QUEUE_REQUEST]: (state) => { return ({ ...state, fetching: true }) }, [LOAD_QUEUE_SUCCESS]: (state, action) => { return ({ ...state, queues: action.payload, fetching: false }) }, [LOAD_QUEUE_FAILURE]: (state, action) => { return ({ ...state, fetching: false, error: action.error}) } } // ------------------------------------ // Reducers // ------------------------------------ const initialState = { fetching: false, queues: [], error: undefined} export default function queueReducer (state = initialState, action) { const handler = QUEUE_ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state }
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var Model = Client = require('../../models/Client'); var ClientsEngine = require('../../public/javascripts/climan/services/ClientsEngineService'); router.get('/:cpf?', function(req, res, next) { var cpf = req.params.cpf; if (!ClientsEngine.validateCPF(cpf)) { res.status(404).end(); } Client.findOne({ cpf: cpf }, function(err, result) { if (err) throw err; if (result) { res.json(result); } else { res.status(404).end(); } }); }); router.delete('/:cpf', function(req, res, next) { var cpf = req.params.cpf; if (!ClientsEngine.validateCPF(cpf)) { res.status(404).end(); } var chain = [ function() { Client.findOne({ cpf: cpf }, chain.shift()); }, function(err, result) { if (err) throw err; if (result === null) { res.status(404).end(); } chain.shift()(); }, function() { Client.remove({ cpf: cpf }, chain.shift()); }, function(err, result) { if (err) throw err; res.status(204).end(); } ]; chain.shift()(); }); router.post('/', function(req, res, next) { var client = req.body.client; var i = 0; if (!ClientsEngine.validateCPF(client.cpf)) { res.status(400).end(); } var chain = [ function() { Client.findOne({ cpf: client.cpf }, chain.shift()); }, function(err, result) { if (result) { for(var i in client) { result[i] = client[i]; } client = result; client.save(function (err) { if (err) throw err; res.status(200).end(); }); } else { chain.shift()(); } }, function() { client = new Client(client); client.save(function (err) { console.log(err); if (err) throw err; res.status(201).end(); }); } ]; chain.shift()(); }); module.exports = router;
/*jslint plusplus: true, devel: true, nomen: true, vars: true, node: true, indent: 4, maxerr: 50 */ "use strict"; /** * Module dependencies. */ var Strategy = require('./strategy'), login = require("./login"); /** * Expose `Strategy` directly from package. */ exports = module.exports = Strategy; /** * Export constructors. */ exports.Strategy = Strategy; /** * Expose login middle-ware */ exports.login = login;
/** * @Author: Alcwyn Parker <alcwynparker> * @Date: 2017-07-13T23:01:09+01:00 * @Email: alcwynparker@gmail.com * @Project: Unlocking Potential * @Filename: * @Last modified by: alcwynparker * @Last modified time: 2017-07-14T11:28:17+01:00 */ const express = require('express'); const Resource = require('./../models/ResourceModel'); var routes = function(){ /* TODO: Paste the code into a function */ // create a router to handle all end points for the API let resourceRouter = express.Router(); // here is where you add all the endpoints for the resources API resourceRouter.route('/Resources') .post((req, res) => { var resource = new Resource(req.body); resource.save(); res.status(201).send(resource); }) .get((req, res) => { // create an empty object let query = {}; // santize the querys so that just anything can't be thrown in the mix if (req.query.type){ query.type = req.query.type; } if (req.query.author){ query.author = req.query.author; } if (req.query.read){ query.read = req.query.read; } // get all resources Resource.find(query, function(err, resources) { if(err){ res.json(err); }else{ res.json(resources); } }); }); // same as the previoud route but with a param of id resourceRouter.route('/Resources/:id') .get((req, res) => { // new method to findbyId Resource.findById(req.params.id, (err, resources) => { if(err){ res.status(500).send(err); // Send an error code }else{ res.json(resources); } }); }) .put((req, res) => { /* TODO: */ // new method to findbyId Resource.findById(req.params.id, (err, resources) => { if(err){ res.status(500).send(err); // Send an error code }else{ // update the values resources.title = req.body.title; resources.author = req.body.author; resources.type = req.body.type; resources.read = req.body.req; // save the changes resources.save(); // return the results res.json(resources); } }); }); return resourceRouter; }; module.exports = routes;
var utils = require('./build-utils'); module.exports = function (grunt) { var pkg = grunt.file.readJSON('package.json'), srcDir = './src', buildDir = './build', version = pkg.version; // Forçamos concat e outros plugins a usarem LF sempre grunt.util.linefeed = '\n'; grunt.initConfig({ pkg: pkg, buildDir: buildDir, srcDir: srcDir, clean: { build: [buildDir] }, // Duplicate source for following building tasks // Copiamos o código fonte para trabalharmos em cima dele copy: { build: { files: [ {expand: true, cwd: '<%= srcDir %>/', src: ['**'], dest: '<%= buildDir %>/'} ] } }, rename: { htaccess: { src: '<%= buildDir %>/build.htaccess', dest: '<%= buildDir %>/.htaccess' } }, // Pré-processamento de strings (substituições) replace: { build: { src: [ '<%= buildDir %>/*.js' ], overwrite: true, replacements: [ { from: "$PROJECT_NAME$", to: "<%= pkg.name %>" }, { from: "$PROJECT_HOMEPAGE$", to: "<%= pkg.homepage %>" },{ from: "$PROJECT_VERSION$", to: version },{ from: "$PROJECT_BUILD_TIME$", to: (new Date()).toUTCString() },{ from: "$PROJECT_LICENSE$", to: "<%= pkg.license %>" } ] } }, // Javascript compresion uglify: { options: { mangle: true, compress: true, preserveComments: 'some' }, build: { options: { report: 'gzip' }, files : [{ expand : true, cwd : '<%= buildDir %>', dest : '<%= buildDir %>', src : ['**/*.js'] }] } } }); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-rename'); grunt.loadNpmTasks('grunt-text-replace'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.registerTask('build', [ 'clean:build', 'copy:build', 'ppem:build', 'sass:build', 'clean:postBuild', 'replace:build', 'uglify:build', 'clean:htaccess', 'rename' ]); grunt.registerTask('default', 'build'); };
//Processamento de parâmentros via URL //Foi solicitada mudança de mapa por URL? if (URLSetBaseLayer!=null){ switch(URLSetBaseLayer) { case 'satelite' : URLSetBaseLayer = 'lMBT'; break; } if(BaselayersValidas.match(URLSetBaseLayer)){ $('#map-select-layer').val(URLSetBaseLayer); $('#map-select-layer').change(); } } //Se foi solicitado marcador no mapa if (MarkerLatLonByURL !=null){ if (!MapPreventNewUserMakers){ MapPreventNewUserMakers = true; UserTempMarker.setLatLng(MarkerLatLonByURL); map.setView(MarkerLatLonByURL, 18); var Msg = TempMarkerMsg(MarkerLatLonByURL[0],MarkerLatLonByURL[1]); UserTempMarker.bindPopup(Msg).addTo(map); UserTempMarker.openPopup(); }else{ MapPreventNewUserMakers = false; map.removeLayer(UserTempMarker); } } if (CamadaDeDados !=null){ var OK = true; switch( CamadaDeDados ) { case 'hospedagem' : AddDataOverlay('hospedagem','Hospedagem',HotelIcon,'map'); break; case 'barrest' : AddDataOverlay('bares-restaurantes','Bares e Restaurantes',AlimentIcon,'map'); break; case 'taxi' : AddDataOverlay('taxi','Táxi',TaxiIcon,'car'); break; case 'ribeiraorun5k2017' : AddDataOverlay('ribeiraorun5k2017','Ribeirao Run 5k',null,'walk'); break; default : OK = false; } if(OK){ ControleListDadosGeoJSON.addTo(map); } } $(".btnMapSatSwitcher").click(function(e) { e.preventDefault(); if(MapCompareActive){ MapCompareActiveStop(); }else{ if( IsSatelliteLayer()){ $('#map-select-layer').val('lMNK'); }else{ $('#map-select-layer').val('lMBT'); } $('#map-select-layer').change(); } }); $(".btnListDadosGeoJSON").click(function(e) { e.preventDefault(); var URL = 'dados/?d='+CamadaDeDados; window.location.href = URL; });
/** * Module dependencies */ const Algorithm = require ('../algorithms/Algorithm') const crypto = require('crypto') const KeyAlgorithm = require('../dictionaries/KeyAlgorithm') const ShaKeyAlgorithm = require('../dictionaries/ShaKeyAlgorithm') const {OperationError} = require('../errors') /** * SHA */ class SHA extends Algorithm { /** * dictionaries */ static get dictionaries () { return [ KeyAlgorithm, ShaKeyAlgorithm ] } /** * members */ static get members () { return {} } /** * digest * * @description * * @param {AlgorithmIdentifier} algorithm * @param {BufferSource} data * * @returns {Uint8Array} */ digest (algorithm, data) { let result let {name} = algorithm data = Buffer.from(data) if (name === 'SHA-1') { let hash = crypto.createHash('sha1') hash.update(data) result = hash.digest() } else if (name === 'SHA-256') { let hash = crypto.createHash('sha256') hash.update(data) result = hash.digest() } else if (name === 'SHA-384') { let hash = crypto.createHash('sha384') hash.update(data) result = hash.digest() } else if (name === 'SHA-512') { let hash = crypto.createHash('sha512') hash.update(data) result = hash.digest() } else { throw new OperationError(`${name} is not a supported algorithm`) } return Uint8Array.from(result).buffer } } /** * Export */ module.exports = SHA
/*globals angular:false*/ (function (angular) { 'use strict'; var app; app = angular.module('dacos'); app.config(function ($routeProvider) { $routeProvider.when('/entrar', {'templateUrl' : 'auth/login.html'}); }); app.controller('AuthLoginController', function ($location, User) { this.user = new User(); this.login = function () { this.user.$login(function () { $location.path('/'); }, function () { this.message = 'nao autorizado.'; }); }; }); })(angular);
var webpack = require('webpack'); var path = require('path'); module.exports = { entry: './src/public/main.js', output: { path: path.join(__dirname, 'public'), filename: 'app.js' } };
this.NesDb = this.NesDb || {}; NesDb[ '7D84A12D6394A4721E40B9934D60545738973D4D' ] = { "$": { "name": "Power Blade 2", "class": "Licensed", "catalog": "NES-PB-USA", "publisher": "Taito", "developer": "Natsume", "region": "USA", "players": "1", "date": "1992-10" }, "cartridge": [ { "$": { "system": "NES-NTSC", "crc": "D273B409", "sha1": "7D84A12D6394A4721E40B9934D60545738973D4D", "dump": "ok", "dumper": "polarz", "datedumped": "2006-03-11" }, "board": [ { "$": { "type": "NES-TLROM", "pcb": "NES-TLROM-03", "mapper": "4" }, "prg": [ { "$": { "name": "NES-PB-0 PRG", "size": "128k", "crc": "1BEBF407", "sha1": "D75FE3C10666AECC40539D136478F65B116CA99D" } } ], "chr": [ { "$": { "name": "NES-PB-0 CHR", "size": "128k", "crc": "96ADC4A9", "sha1": "479B29022E06A2C7AA1E37DC5361D2CAC4022144" } } ], "chip": [ { "$": { "type": "MMC3C" } } ], "cic": [ { "$": { "type": "6113B1" } } ] } ] } ], "gameGenieCodes": [ { "name": "Start with 1 life", "codes": [ [ "AEKEPTZA" ] ] }, { "name": "Start with 6 lives", "codes": [ [ "IEKEPTZA" ] ] }, { "name": "Start with 9 lives", "codes": [ [ "AEKEPTZE" ] ] }, { "name": "Infinite lives", "codes": [ [ "GZSILAVG" ] ] }, { "name": "Infinite energy--except for spikes", "codes": [ [ "OVSLZLSV" ] ] }, { "name": "Stop timer", "codes": [ [ "ATKKXZSZ" ] ] }, { "name": "Speed up timer", "codes": [ [ "YPKGNXYU" ] ] }, { "name": "Slow down timer", "codes": [ [ "YYKGNXYU" ] ] }, { "name": "Infinite life tanks", "codes": [ [ "GXEVXTVG" ] ] }, { "name": "Infinite energy tanks", "codes": [ [ "GZEIPLVG" ] ] }, { "name": "Throw meter doesn't decrease when boomerang is thrown", "codes": [ [ "SAKSZZSZ" ] ] }, { "name": "Take minimal damage", "codes": [ [ "OVSLZLSV", "PESLLLAA" ] ] }, { "name": "Maximum throwing ability on pick-up", "codes": [ [ "OZVULSOK", "SANLZIVT" ] ] } ] };
angular .module('tippkick-planer-app') .component('tournamentHeader', { templateUrl: '/js/components/tournament-header.html', controller: ['firebase', function (firebase) { var that = this; firebase.auth().onAuthStateChanged(function(user) { that.user = user; }); } ] } );
import Element from './Element'; import ListItemElement from './ListItemElement'; /** * constructs a ListElement instance * @class ListElement * @classdesc the ListElement class allows to create a list of any type of elements * @extend Element * @public * @param {Object} options the options to be merged with defaults settings * @type {ListElement} */ export default class ListElement extends Element { /** * Initialize default settings for List Element * @memberOf ListElement * @method initDefaults * @instance * @override */ initDefaults() { super.initDefaults({ items: [], item: { // options for a ListItemElement to use as default listItem options minWidth: '100%', color: '#fff', }, itemEvents: { // event handlers to use as default listItem event handlers click: () => { }, }, indicator: false, // options for an ImageElement to use as default listItem indicator stroke: { size: 0, radius: 0, color: 'transparent', }, }); } /** * initializes data object for the ListElement instance * @memberOf ListElement * @method initData * @instance * @override */ initData() { this.items = []; } /** * compute bounds before drawing all graphic elements of ListElement instance * @memberOf ListElement * @method computeBounds * @instance * @override */ computeBounds() { if(!!this.settings.minWidth) { if(this.settings.minWidth.isPercentage() && !!this.parent) { this.settings.minWidth = this.parent.getComputedBounds().width * this.settings.minWidth.parsePercentage(); } if(this.settings.size.width < this.settings.minWidth) { this.settings.size.width = this.settings.minWidth; } } } preDrawElement() { this.computeBounds(); super.preDrawElement(); } /** * draws all graphic elements of the ListElement instance, cycles the items, draw them and computes positions * @memberOf ListElement * @method drawElements * @instance * @override */ drawElements() { super.drawElements(); this.settings.path('items', []).each((item, i) => { const listItem = new ListItemElement(this.settings.item.inherit(true, { indicator: this.settings.indicator, events: this.settings.itemEvents, }, item, { parent: this, align: 'left top', })); this.items.push(listItem); if(i > 0) { listItem.setPosition({ y: this.items[i - 1].getComputedBounds().bottom, }); } }); } }
import './Node.css' import React, { Component } from 'react'; import { DragSource } from 'react-dnd'; const nodeSource = { beginDrag(props) { return {id: props.node.id}; } }; function collect(connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging() } } class Node extends Component { render() { const { node, windowSize, connectDragSource, isDragging } = this.props; const style = { transform: `translate(${(windowSize.width * node.location.x) / 100}px, ${(windowSize.height * node.location.y) / 100}px)` + (isDragging ? 'rotate(20deg)' : 'rotate(0)') , } return connectDragSource( <div key={node.id} className="node_container" style={style} style={style}> {this.props.children} </div> ); } } export default DragSource('NODE', nodeSource, collect)(Node);
var circulo=require("./Ejem_Modulos_libreria.js"); console.log("Area(radio 4): " + circulo.area(4));
/** * VERSION: 0.1.0 * DATE: 2013-02-22 * UPDATES AND DOCS AT: http://www.greensock.com * * @license Copyright (c) 2008-2013, GreenSock. All rights reserved. * This work is subject to the terms at http://www.greensock.com/terms_of_use.html or for * Club GreenSock members, the software agreement that was issued with your membership. * * @author: Jack Doyle, jack@greensock.com */ (window._gsQueue || (window._gsQueue = [])).push( function() { "use strict"; window._gsDefine.plugin({ propName: "attr", API: 2, //called when the tween renders for the first time. This is where initial values should be recorded and any setup routines should run. init: function(target, value, tween) { var p; if (typeof(target.setAttribute) !== "function") { return false; } this._target = target; this._proxy = {}; for (p in value) { this._addTween(this._proxy, p, parseFloat(target.getAttribute(p)), value[p], p); this._overwriteProps.push(p); } return true; }, //called each time the values should be updated, and the ratio gets passed as the only parameter (typically it's a value between 0 and 1, but it can exceed those when using an ease like Elastic.easeOut or Back.easeOut, etc.) set: function(ratio) { this._super.setRatio.call(this, ratio); var props = this._overwriteProps, i = props.length, p; while (--i > -1) { p = props[i]; this._target.setAttribute(p, this._proxy[p] + ""); } } }); }); if (window._gsDefine) { window._gsQueue.pop()(); }
(function(coinswap) { coinswap.Transaction = Backbone.Model.extend({}); coinswap.TransactionCollection = Backbone.Collection.extend({ model: coinswap.Transaction, comparator: 'date' }); })(coinswap);
// For an introduction to the Blank template, see the following documentation: // http://go.microsoft.com/fwlink/?LinkId=232509 (function () { "use strict"; var app = WinJS.Application; var activation = Windows.ApplicationModel.Activation; app.onactivated = function (args) { if (args.detail.kind === activation.ActivationKind.launch) { if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) { // TODO: This application has been newly launched. Initialize // your application here. } else { // TODO: This application has been reactivated from suspension. // Restore application state here. } args.setPromise(WinJS.UI.processAll().then(function () { //__DEBUG__("started"); ko.applyBindings(null); })); } }; app.oncheckpoint = function (args) { // TODO: This application is about to be suspended. Save any state // that needs to persist across suspensions here. You might use the // WinJS.Application.sessionState object, which is automatically // saved and restored across suspension. If you need to complete an // asynchronous operation before your application is suspended, call // args.setPromise(). }; app.start(); })();
$.fn.timer = function(timerLimit){ var timeoutId; var timer = getTimer(); var self = this; var timerLimit = timerLimit || 3600; function startTimer(){ displayTimer(); }; function stopTimer(){ clearTimeout(timeoutId); timer = 0; } function displayTimer(){ if (timer >= timerLimit || self.hasClass('stopped')) { stopTimer(); if (timer >= timerLimit) { alert('Time is out'); } return; } timeoutId = setTimeout(displayTimer, 100); timer++; self.html(((timerLimit - timer) / 10).toFixed(1)); } function saveTimer(){ var date = new Date(); date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); document.cookie = "timer=" + timer + expires + "; path=/"; } function getTimer(){ return document.cookie.match(/timer=([^;]+);*/) ? document.cookie.match(/timer=([^;]+);*/)[1] : 0; } $(window).unload(function() { saveTimer(); }); startTimer(); }
import { mount } from '@vue/test-utils' import BColAsync from './col' // Vue test utils doesnt currently support mounting Async Components // So we have to resolve the component ourselves // https://github.com/vuejs/vue-test-utils/issues/1012 let BCol if (typeof BColAsync === 'function') { // is async, so call resolve BColAsync(cmp => { BCol = cmp }) } else { // Not async function BCol = BColAsync } describe('layout > col', () => { it('should have default expected structure', async () => { const wrapper = mount(BCol) expect(wrapper.is('div')).toBe(true) expect(wrapper.classes()).toContain('col') expect(wrapper.classes().length).toBe(1) expect(wrapper.findAll('.col > *').length).toBe(0) expect(wrapper.text()).toEqual('') }) it('renders custom root element when tag prop set', async () => { const wrapper = mount(BCol, { propsData: { tag: 'span' } }) expect(wrapper.is('span')).toBe(true) expect(wrapper.classes()).toContain('col') expect(wrapper.classes().length).toBe(1) expect(wrapper.findAll('.col > *').length).toBe(0) expect(wrapper.text()).toEqual('') }) it('should apply breakpoint specific col-{bp}-{#} classes', async () => { const wrapper = mount(BCol, { propsData: { cols: 6, sm: 5, md: 4, lg: 3, xl: 2 } }) expect(wrapper.is('div')).toBe(true) expect(wrapper.classes()).toContain('col-6') expect(wrapper.classes()).toContain('col-sm-5') expect(wrapper.classes()).toContain('col-md-4') expect(wrapper.classes()).toContain('col-lg-3') expect(wrapper.classes()).toContain('col-xl-2') expect(wrapper.classes().length).toBe(5) }) it('should not have class "col" when only single breakpoint prop specified', async () => { const wrapper = mount(BCol, { propsData: { sm: 5 } }) expect(wrapper.is('div')).toBe(true) expect(wrapper.classes()).toContain('col-sm-5') expect(wrapper.classes().length).toBe(1) }) it('should apply ".offset-*" classes with "offset-{bp}-{#}" props', async () => { const wrapper = mount(BCol, { propsData: { offset: 6, offsetSm: 5, offsetMd: 4, offsetLg: 3, offsetXl: 2 } }) expect(wrapper.is('div')).toBe(true) expect(wrapper.classes()).toContain('col') expect(wrapper.classes()).toContain('offset-6') expect(wrapper.classes()).toContain('offset-sm-5') expect(wrapper.classes()).toContain('offset-md-4') expect(wrapper.classes()).toContain('offset-lg-3') expect(wrapper.classes()).toContain('offset-xl-2') expect(wrapper.classes().length).toBe(6) }) it('should apply ".order-*" classes with "order-{bp}-{#}" props', async () => { const wrapper = mount(BCol, { propsData: { order: 6, orderSm: 5, orderMd: 4, orderLg: 3, orderXl: 2 } }) expect(wrapper.is('div')).toBe(true) expect(wrapper.classes()).toContain('col') expect(wrapper.classes()).toContain('order-6') expect(wrapper.classes()).toContain('order-sm-5') expect(wrapper.classes()).toContain('order-md-4') expect(wrapper.classes()).toContain('order-lg-3') expect(wrapper.classes()).toContain('order-xl-2') expect(wrapper.classes().length).toBe(6) }) it("should apply boolean breakpoint classes for 'sm', 'md', 'lg', 'xl' prop", async () => { const wrapper = mount(BCol, { propsData: { col: true, sm: true, md: true, lg: true, xl: true } }) expect(wrapper.is('div')).toBe(true) expect(wrapper.classes()).toContain('col') expect(wrapper.classes()).toContain('col-sm') expect(wrapper.classes()).toContain('col-md') expect(wrapper.classes()).toContain('col-lg') expect(wrapper.classes()).toContain('col-xl') expect(wrapper.classes().length).toBe(5) }) it("should apply boolean breakpoint classes for 'sm', 'md', 'lg', 'xl' prop set to empty string", async () => { const wrapper = mount(BCol, { propsData: { sm: '', md: '', lg: '', xl: '' } }) expect(wrapper.is('div')).toBe(true) expect(wrapper.classes()).toContain('col-sm') expect(wrapper.classes()).toContain('col-md') expect(wrapper.classes()).toContain('col-lg') expect(wrapper.classes()).toContain('col-xl') expect(wrapper.classes().length).toBe(4) }) it('should apply ".align-self-*" class with "align-self" prop', async () => { const wrapper = mount(BCol, { propsData: { alignSelf: 'center' } }) expect(wrapper.is('div')).toBe(true) expect(wrapper.classes()).toContain('col') expect(wrapper.classes()).toContain('align-self-center') expect(wrapper.classes().length).toBe(2) }) // it('computeBkPtClass helper should compute boolean classes', async () => { // expect(computeBkPtClass('col', 'sm', true)).toBe('col-sm') // expect(computeBkPtClass('col', 'md', true)).toBe('col-md') // expect(computeBkPtClass('col', 'lg', true)).toBe('col-lg') // expect(computeBkPtClass('col', 'xl', true)).toBe('col-xl') // }) // // it('computeBkPtClass helper should compute boolean classes when given empty string', async () => { // expect(computeBkPtClass('col', 'sm', '')).toBe('col-sm') // expect(computeBkPtClass('col', 'md', '')).toBe('col-md') // expect(computeBkPtClass('col', 'lg', '')).toBe('col-lg') // expect(computeBkPtClass('col', 'xl', '')).toBe('col-xl') // }) // // it("computeBkPtClass helper should NOT compute boolean classes when value 'false' (return 'undefined')", async () => { // expect(computeBkPtClass('col', 'sm', false)).toBe(undefined) // expect(computeBkPtClass('col', 'md', false)).toBe(undefined) // expect(computeBkPtClass('col', 'lg', false)).toBe(undefined) // expect(computeBkPtClass('col', 'xl', false)).toBe(undefined) // }) })