text
stringlengths
2
6.14k
import React from 'react'; import { compose, mapProps } from 'recompose'; import { withRouter } from '@ui/NativeWebRouter'; import BackgroundView from '@ui/BackgroundView'; import SavedPaymentReviewForm from '@ui/forms/SavedPaymentReviewForm'; import PaddedView from '@ui/PaddedView'; import { Title, Row, TinyButton, TinyButtonText } from '../styles'; const enhance = compose( withRouter, mapProps(props => ({ onPressEdit() { props.history.push('address'); }, })), ); const PaymentMethodConfirmation = enhance(({ onPressEdit }) => ( <BackgroundView> <PaddedView> <Row> <Title>Review</Title> <TinyButton onPress={onPressEdit}> <TinyButtonText>Edit</TinyButtonText> </TinyButton> </Row> </PaddedView> <SavedPaymentReviewForm navigateToOnComplete="done" /> </BackgroundView> )); export default PaymentMethodConfirmation;
import { combineReducers } from 'redux'; import todoReducer from './todoReducer'; import userReducer from './userReducer'; const rootReducer = combineReducers({ todos: todoReducer, user: userReducer }); export default rootReducer;
import BmiCalculator from './scripts/components/BmiCalculator.jsx'; export default BmiCalculator;
'use strict'; var _ = require('lodash'); var Page = require('./form-field-page'); var FormFieldResultsPage = Page.extend({ url: 'http://127.0.0.1:3000/form-fields-results', els: _.extend(Page.prototype.els, { 'radio-field': by.id('radio-field'), results: by.id('results') }) }); module.exports = FormFieldResultsPage;
const toUpper = (str) => { let newString = "" for (var letter of str) { var num = letter.charCodeAt() if ( num > 96 && num < 123 ) { num -= 32 newString += String.fromCharCode(num) } else { newString += letter } } return newString } export default toUpper
// MIT © 2017 azu "use strict"; const TextLintTester = require("textlint-tester"); const tester = new TextLintTester(); // rule const rule = require("../src/textlint-rule-google-possessives"); const defaultMessage = require("../src/textlint-rule-google-possessives").defaultMessage; // ruleName, rule, { valid, invalid } tester.run("textlint-rule-google-possessives", rule, { valid: [ "Each component has its own set of traits.", "This is business's book.", "alias's", "application's", "business's", "class's", "customer's", "Elvis's", "Liz's", "user's ", // singular "users'", // plural, "Elise Williams's", "the Williamses'", "women's" // < ], invalid: [ { text: "businesses's", errors: [ { index: 0 } ] }, { text: "Buzz'", errors: [ { index: 0 } ] }, { text: "Carlos'", errors: [ { index: 0, message: defaultMessage } ] }, { text: "class'", errors: [ { index: 0, message: defaultMessage } ] }, { text: "examples's", errors: [ { index: 0, message: defaultMessage } ] }, { text: "users's", errors: [ { index: 0, message: defaultMessage } ] }, { text: "values's", errors: [ { index: 0, message: defaultMessage } ] } ] });
'use strict'; var mongoose = require('mongoose'), Announcements = mongoose.model('Announcements'), Users = mongoose.model('User'), _ = require('lodash'); exports.create = function (req, res) { //create a new announcement var announcement = new Announcements(req.body); announcement.save(function(err) { if (err) { console.log(err); res.status(400).send(err); } else { res.json(announcement); } }); }; exports.listAll = function(req,res){ Announcements.find().exec(function(err,Announcements){ if(err){ return res.status(400).send(err); } else{ res.json(Announcements); } }); }; exports.listOne = function(req,res){ var announcement = req.announcement; res.json(announcement); }; exports.announcementByID = function(req,res,next,id){ if(!mongoose.Types.ObjectId.isValid(id)){ return res.status(400).send({ message:'AnnouncmentID is invalid' }); } Announcements.findById(id).populate('user','displayName').exec(function(err,announcement){ if(err){ return next(err); } else if(!announcement){ return res.status(404).send({ message:'No announcement with that id was found' }); } req.announcement = announcement; next(); }); }; exports.update = function(req,res){ var annoucement = req.announcement; annoucement.title = req.body.title; annoucement.message = req.body.message; annoucement.save(function(err){ if(err){ console.log(err); res.status(400).send(err); } else{ res.json(annoucement); } }); }; exports.delete = function (req, res) { var announcement = req.announcement; announcement.remove(function(err) { if(err){ res.status(400).send(err); } else { res.end(); } }); };
import fixture from 'can-fixture'; const store = fixture.store([{ id: 0, description: 'First item' }, { id: 1, description: 'Second item' }]); fixture({ 'GET /roomplan': store.findAll, 'GET /roomplan/{id}': store.findOne, 'POST /roomplan': store.create, 'PUT /roomplan/{id}': store.update, 'DELETE /roomplan/{id}': store.destroy }); export default store;
export {default as transform} from "./src/d3-transform"
'use strict'; var chai = require("chai"), sinon = require("sinon"), sinonChai = require("sinon-chai"), async = require('async'), _ = require('lodash'), request = require('supertest'); var expect = chai.expect; chai.use(sinonChai); /************************************************************************** * Begin of tests *************************************************************************/ var app = require('../../app'); var User = require('../../lib/models/user/user.model'); var UserMocks = require('../../lib/models/user/user.mocks'); var jwt = require('../../lib/jwt'); var jsonwebtoken = require('jsonwebtoken'); var config = require('../../config'); describe('api.auth.login', function() { describe('POST /api/auth/login', function () { var user; beforeEach(function (done) { User.remove({}, done); }); beforeEach(function (done) { user = new User(UserMocks.localDummy1); user.save(done); }); it('should return a new identity, access and refresh token for a valid login', function (done) { request(app) .post('/api/auth/login') .send({ email: UserMocks.localDummy1.identities.local.email, password: UserMocks.localDummy1.identities.local.secret }) .expect(200) .expect('Content-Type', 'application/json; charset=utf-8') .end(function (err, res) { expect(err).to.not.exist; expect(Object.keys(res.body)).to.have.length(3); expect(res.body).to.contain.keys('it', 'at', 'rt'); async.series([ function (done) { var data = jsonwebtoken.verify(res.body.it, config.jwt.tokenSecret, { issuer: config.jwt.issuer, audience: config.jwt.audience, algorithm: config.jwt.algorithm }); expect(data).to.contain.keys('sub', 'iat', 'exp', 'iss', 'aud', 'identities'); expect(Object.keys(data)).to.have.length(6); done(); }, function (done) { var data = jsonwebtoken.verify(res.body.at, config.jwt.tokenSecret, { issuer: config.jwt.issuer, audience: config.jwt.audience, algorithm: config.jwt.algorithm }); expect(data).to.contain.keys('sub', 'iat', 'exp', 'iss', 'aud'); expect(Object.keys(data)).to.have.length(5); done(); }, function (done) { jwt.verifyRefreshToken(res.body.rt, function (err, data) { expect(err).to.not.exist; expect(data).to.contain.keys('sub', 'iat', 'exp', 'iss', 'aud'); done(err); }); } ], done); }); }); it('should send 401 when invalid credentials are sent', function (done) { request(app) .post('/api/auth/login') .send({ email: UserMocks.localDummy1.identities.local.email, password: 'wrongpassword' }) .expect(401) .expect('Content-Type', 'application/json; charset=utf-8') .end(function (err, res) { expect(err).to.not.exist; expect(res.body).to.have.a.property('name', 'InvalidCredentialsError'); expect(res.body).to.have.a.property('message', 'Invalid credentials'); done() }) }); it('should handle weird requests', function (done) { request(app) .post('/api/auth/login') .send({ email: {'$or': [{1: 1}]}, password: {} }) .expect(422) .expect('Content-Type', 'application/json; charset=utf-8') .end(function (err, res) { expect(err).to.not.exist; expect(res.body).to.have.a.property('name', 'ValidationError'); expect(res.body).to.have.a.property('message', 'Validation failed'); expect(res.body).to.have.a.deep.property('errors.email.kind', 'string.base'); expect(res.body).to.have.a.deep.property('errors.password.kind', 'string.base'); done() }) }); }); });
window.jQuery = window.$ = require("jquery"); require('foundation-sites/dist/js/foundation'); $(document).ready(function() { $(document).foundation(); /* $(document).foundation({ orbit: { animation: 'slide', timer_speed: 1000, pause_on_hover: true, animation_speed: 500, navigation_arrows: true, bullets: false } });*/ }); require('highlight.js/styles/railscasts.css'); require(['highlight.js/lib/highlight'], function(hljs) { hljs.registerLanguage('bash', require('highlight.js/lib/languages/bash')); hljs.registerLanguage('cpp', require('highlight.js/lib/languages/cpp')); hljs.registerLanguage('cmake', require('highlight.js/lib/languages/cmake')); hljs.registerLanguage('java', require('highlight.js/lib/languages/java')); hljs.registerLanguage('javascript', require('highlight.js/lib/languages/javascript')); hljs.registerLanguage('json', require('highlight.js/lib/languages/json')); hljs.registerLanguage('python', require('highlight.js/lib/languages/python')); hljs.initHighlightingOnLoad(); }); require('react-tagsinput/react-tagsinput.css'); require('fixed-data-table/dist/fixed-data-table.css');
version https://git-lfs.github.com/spec/v1 oid sha256:9a4c3800bcc1ce9138f70f63505cbb97b03c59b9441071aadf6fed8976be5df4 size 3696
var Type = require("@kaoscript/runtime").Type; module.exports = function() { function foobar() { } function quxbaz() { let x, __ks_0; if(Type.isValue(__ks_0 = foobar()) ? (x = __ks_0, false) : true) { throw new Error(); } return x.y; } };
define( [ "ui/loading/loading" ], function() { "use strict"; /** * example: * <s-loading class="global"></s-loading> * */ angular.module( "$ui.loading", [] ) .directive( "sLoading", function() { function link( $scope, $element, $attrs ) { var loading; $scope.controller = loading = $( $element ).loading(); if ( [ "1", "true" ].indexOf( $attrs.autoShow ) !== -1 ) { loading.show(); } } return { scope : { controller : "=", autoShow : "@" }, template : "<div class='ui loading'></div>", replace : true, restric : "E", link : link }; } ); } );
import { getOrFetchEvents, getOrFetchEventsSuccess, getOrFetchEventsError } from 'actions/events'; import api from 'services/api'; import {eventsNormalizr} from 'utils/normalize'; export function getOrFetchEventsFlow(){ return function (dispatch){ dispatch(getOrFetchEvents()); api.fetchEvents() .then(({data}={})=>{ data = eventsNormalizr(data); dispatch(getOrFetchEventsSuccess(data)); }).catch(function (error) { dispatch(getOrFetchEventsError(error)); }); }; }
(function ($) { $.fn.pBar = function (params) { var params = $.extend({ min: 0, max: 60, val: 50, tooltip: "Restan % días" }, params); var objs = $(this); var o = null; var wdt = 0; $.each(objs, function () { o = $(this); min = (typeof (o.data("min")) != "undefined") ? o.data("min") : min; max = (typeof (o.data("max")) != "undefined") ? o.data("max") : max; val = (typeof (o.data("val")) != "undefined") ? o.data("val") : val; var gray = $("<span />"); var label = $("<label />"); wdt = (((val * 100) / max)); gray.css({ width: wdt + "%" }); gray.addClass((wdt == 100) ? "empty" : (wdt >= 90 && wdt < 100) ? "full" : (wdt >= 70 && wdt < 90) ? "warning" : "ok"); label.text(max - val); if (params.tooltip != null) label.attr("title", params.tooltip.replace("%", max - val)); gray.appendTo(o); label.appendTo(o); }); return objs; } }(jQuery));
version https://git-lfs.github.com/spec/v1 oid sha256:8f3e6bee10adea1a6e17ff0bd1731d10c39f8907652b5148e7c3cc57eac6c88c size 25804
/** * @module Build * @submodule Build.Config * @class Build.Config.RequireJS * @static */ module.exports = function(config) { return { 'global': { 'options': { 'name': 'main', 'baseUrl': config.javascripts +'/app/', 'mainConfigFile': config.javascripts +'/app/main.js', // Exclusions from minconcat use empty: 'paths': { 'facebook': 'empty:', 'google-analytics': 'empty:', 'settings': 'empty:' }, 'has': { 'debugMode': false }, 'out': config.jsmin +'/app.min.js' } } }; };
!(function (factory) { if (typeof define === 'function') { define(['zepto'], factory); } else { factory(Zepto); } })(function ($) { return $; });
const React = require('react'); const { Bar } = require('react-chartjs'); export default class BarChart extends React.Component { constructor(props) { super(props); const colors = new Array(this.props.scores.length).fill('rgba(178,225,102,0.5)'); const teamIdx = this.props.names.findIndex((name) => name === props.username); if (teamIdx !== -1) { colors[teamIdx] = 'rgba(54, 162, 235, 0.2)'; } this.state = { datasets: [ { label: 'Problems solved', fillColor: colors, data: this.props.numSolved, }, ], labels: this.props.names, }; } render() { const that = this; const options = { responsive: true, showTooltips: true, tooltipTemplate: (v) => { const teamIdx = that.props.names.findIndex((name) => name === v.label); const time = that.props.scores[teamIdx]; return `Time: ${time} minutes`; }, }; return ( <div className='chart-wrapper'> <Bar type='bar' data={this.state} options={options} width='1000px' height='500px' /> </div> ); } } BarChart.propTypes = { names: React.PropTypes.array, numSolved: React.PropTypes.array, scores: React.PropTypes.array, username: React.PropTypes.string.isRequired, };
import URIjs from 'urijs'; export const parseSearchString = (string) => URIjs.parseQuery(string); export const calcSearchString = (params) => URIjs.buildQuery(params, true);
'use strict'; /*! * Collection * https://github.com/kobezzza/Collection * * Released under the MIT license * https://github.com/kobezzza/Collection/blob/master/LICENSE */ var _core = require("../core"); var _types = require("../helpers/types"); var _gcc = require("../helpers/gcc"); /** * Returns true if in the collection exists at least one element which matches by the specified condition * * @see Collection.prototype.forEach * @param {($$CollectionFilter|$$CollectionSingleBase)=} [opt_filter] - function filter or an array of functions * @param {?$$CollectionSingleBase=} [opt_params] - additional parameters * @return {(boolean|!Promise<boolean>)} */ _core.Collection.prototype.some = function (opt_filter, opt_params) { let p = opt_params || {}; if (!(0, _types.isArray)(opt_filter) && !(0, _types.isFunction)(opt_filter)) { p = opt_filter || p; opt_filter = null; } this._initParams(p, opt_filter); p = (0, _gcc.any)(Object.assign(Object.create(this.p), p, { mult: false, result: false })); const returnVal = (0, _gcc.any)(this.forEach(() => p.result = true, p)); if (returnVal !== this) { return returnVal; } return p.result; };
/** * @file UserAccount/actions.js * @fileoverview - Exports redux action creation methods for modifying the * application scope state from the UserAccount component. */ import { REQUEST_SAVE_PROFILE, RECEIVED_SAVE_PROFILE, FAILED_SAVE_PROFILE, REQUEST_LOAD_PROFILE, RECEIVED_LOAD_PROFILE, FAILED_LOAD_PROFILE, UPDATE_PROFILE } from '../../actionTypes'; import ReduxThunk from 'redux-thunk'; import {Actions} from 'react-native-router-flux'; import DeviceStorageService from '../../services/deviceStorage/DeviceStorageService'; import { dispatch } from 'react-redux'; /* ========================================================================== * * Async Action Creators * ========================================================================== */ export const saveProfile = (user) => { return (dispatch) => { const svc = new AsyncStorageService(); // Dispatch notification that a save is taking place. dispatch(requestSaveProfile); // Write the updated profile to the service. const wrPromise = svc.write(['profile', stuent]); // Handle Promise resolve and fails. wrPromise.then((res) => { dispatch(recievedSaveProfile(user)); }, (error) => { dispatch(failedSaveProfile(error)); }); } }; /* ========================================================================== * * Synchronous Action Creators * ========================================================================== */ export const requestSaveProfile = (user) => { return { type: REQUEST_SAVE_PROFILE, user: user } } export const updateProfile = () => { return { type: UPDATE_PROFILE } }; export const recievedSaveProfile = (user) => { } export const failedSaveProfile = (user) => { }
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import uniqueId from 'lodash/uniqueId'; import WixComponent from '../BaseComponents/WixComponent'; import styles from './ToggleSwitch.scss'; /** * Controlled switch */ class ToggleSwitch extends WixComponent { constructor(params) { super(params); this.id = uniqueId(); } render() { const {checked, onChange, size, disabled} = this.props; const id = this.id; const rootClassName = classnames(styles.toggleSwitch, { [styles.toggleSwitchSmall]: size === 'small', [styles.toggleSwitchXSmall]: size === 'x-small', [styles.disabled]: disabled }); const outerLabel = classnames(styles.outerLabel, { [styles.disabled]: disabled }); const innerLabel = classnames(styles.innerLabel, { [styles.disabled]: disabled }); const toggleActive = classnames(styles.toggleActive, { [styles.disabled]: disabled }); const toggleInactive = classnames(styles.toggleInactive, { [styles.disabled]: disabled }); return ( <div className={rootClassName}> <input type="checkbox" id={id} checked={checked} onChange={onChange}/> <label htmlFor={id} className={outerLabel}> <label htmlFor={id} className={innerLabel}> <svg className={toggleActive} viewBox="0 0 41 32"> <path d="M0.169 17.815c0.169 1.098 0.76 2.111 1.689 2.871l14.269 10.385c1.942 1.435 4.644 1.013 6.079-0.844l18.069-23.303c1.435-1.858 1.098-4.559-0.844-5.995s-4.644-1.098-6.164 0.844l-15.367 19.842-10.723-7.852c-1.942-1.435-4.644-1.013-6.164 0.844-0.76 0.929-1.013 2.111-0.844 3.208z"/> </svg> <svg className={toggleInactive} viewBox="0 0 143 32"> <path d="M0 0h142.545v32h-142.545v-32z"/> </svg> </label> </label> </div> ); } } ToggleSwitch.displayName = 'ToggleSwitch'; ToggleSwitch.propTypes = { checked: PropTypes.bool.isRequired, /** Callback function when user changes the value of the component */ onChange: PropTypes.func.isRequired, disabled: PropTypes.bool, /** Specifies toggle size */ size: PropTypes.oneOf(['x-small', 'small', 'large']) }; ToggleSwitch.defaultProps = { checked: false, onChange: () => {}, disabled: false, size: 'large' }; export default ToggleSwitch;
/** * @author Vladimir Kozhin <affka@affka.ru> * @license MIT */ 'use strict'; const Jii = require('../../BaseJii'); const InvalidConfigException = require('../../exceptions/InvalidConfigException'); const Collection = require('../../base/Collection'); const _clone = require('lodash/clone'); const INeatContextProfiles = require('../INeatContextProfiles'); class NeatContextProfiles extends INeatContextProfiles { preInit() { /** * @type {object} */ this.data = {}; /** * @type {NeatClient} */ this.neat = 'neat'; super.preInit(...arguments); } init() { super.init(); this.neat = Jii.app.get(this.neat); } /** * * @param {string} profileName * @param {string} collectionName * @param {object} [params] * @returns {Promise.<T>} */ getCollection(profileName, collectionName, params) { params = params || {}; /** @typedef {NeatComet.bindings.BindingServer} bingind */ /*var binding = this.neat.engine.profilesDefinition[profileName] && this.neat.engine.profilesDefinition[profileName][name] || null; if (!binding) { throw new InvalidConfigException('Not found collection for profile id `' + name + '`'); }*/ return Promise.resolve().then(() => { // @todo Temporary code var opened = this.neat.engine._openedProfilesByProfileId; var profile = opened && opened[profileName] && opened[profileName][0] || this.neat.openProfile(profileName, params); var collection = profile.getCollection(collectionName); if (this.data[collectionName]) { collection.set(this.data[collectionName]); this.data[collectionName] = null; // Mark as exists record (not isNew) collection.each(model => { model.setOldAttributes(_clone(model.getAttributes())); }); /*return new Collection(this.data[collectionName], { modelClass: binding.serverModel || binding.clientModel })*/ } return collection; }); } } module.exports = NeatContextProfiles;
it("update for, init with empty data", function (done) { // [inject] init var lis = wrap.getElementsByTagName('li'); expect(lis.length).toBe(2); myComponent.data.push('persons', {name: 'otakustay', email: 'otakustay@gmail.com'} ); san.nextTick(function () { var lis = wrap.getElementsByTagName('li'); expect(lis.length).toBe(3); expect(lis[1].getAttribute('title')).toBe('otakustay'); expect(lis[1].innerHTML.indexOf('otakustay - otakustay@gmail.com')).toBe(0); myComponent.dispose(); document.body.removeChild(wrap); done(); }); });
var data = require("../data.json"); exports.view = function(req, res){ console.log("---------- Inside of previous contribution -------- "); res.render('previouscontribution', { answers: data.user.contributions, questions: data.user.personalquestions }); };
// DOM Ready $(function() { // SVG fallback // toddmotto.com/mastering-svg-use-for-a-retina-web-fallbacks-with-png-script#update if (!Modernizr.svg) { var imgs = document.getElementsByTagName('img'); var dotSVG = /.*\.svg$/; for (var i = 0; i != imgs.length; ++i) { if(imgs[i].src.match(dotSVG)) { imgs[i].src = imgs[i].src.slice(0, -3) + "png"; } } } // Check if an object or array is empty function is_empty(obj) { if (obj === null) return true; if (obj.length && obj.length > 0) return false; if (obj.length === 0) return true; for (var key in obj) { if (hasOwnProperty.call(obj, key)) return false; } return true; } // Remove some attribution $(".leaflet-control-attribution").css('display', 'none'); /** * This loops al the listitems and ul's in the filtering nav from the elm plugin and adds images to all of them if there * exists an iimage/icon with a name that is {slug}.png of each list item (layer) */ $(".easy-layer-map-navigation-list-item").each(function() { var layer_slug = this.getAttribute('data-slug'); // that = the anchor tag var that = $(this).children(':first'); url = theme_url + '/img/icons/' + layer_slug + '.png'; url_transparent = theme_url + '/img/icons/transparent.png'; var checkbox = '<img class=\'arkipelag-sthlm-layer-checkbox checked\' src=\'' + theme_url +'/img/icons/cb_checked.png\' />'; $.ajax({ url: url, async: false, success: function() { $(that).prepend('<img class=\'arkipelag-sthlm-layer-icon\' src=\'' + url + '\' />'); $(that).append(checkbox); }, error: function() { $(that).prepend('<img class=\'arkipelag-sthlm-layer-icon\' src=\'' + url_transparent + '\' />'); $(that).append(checkbox); } }); }); // Add the site logo to the top of the navigation var url = theme_url + '/img/logo.png'; $("#easy-layer-map-navigation-container").prepend('<div class=""><img class="arkipelag-sthlm-nav-logo" src="' + url + '" /></div>'); // Add hide/show functionality for the navigationmenu $('.easy-layer-map-navigation-header-link').click(function(e) { e.preventDefault(); $(this).next('ul').children('li').slideToggle(); }); // check of uncheck the checkboxes in the navigation/filtering $(".easy-layer-map-navigation-link").click(function() { var checked_url = theme_url +'/img/icons/cb_checked.png'; var unchecked_url = theme_url +'/img/icons/cb_unchecked.png'; var element = $(this).children('.arkipelag-sthlm-layer-checkbox.checked'); if(element.length > 0) { $(element).attr('src', unchecked_url).removeClass('checked'); } else { element = $(this).children('.arkipelag-sthlm-layer-checkbox'); $(element).attr('src', checked_url).addClass('checked'); } }); // Add the searchfieldfunctionality var first_search = true; $('.elm-search-field').on('focus', function() { if(first_search === true) { $(this).val(''); first_search = false; } }).on('change', function() { $('.elm-result-body').html(''); // If the searchfield isnt empty we search the spots and adds them to the searchresult div if($(this).val() !== '') { var pattern = new RegExp($(this).val().toLowerCase(), 'i'); search_results = []; for(var i in elm_spots_list) { console.log(elm_spots_list); var added = false; var title = elm_spots_list[i].title.toLowerCase(); var layers = elm_spots_list[i].layers; var plats = elm_spots_list[i].plats.toLowerCase(); var omrade = elm_spots_list[i].omrade.toLowerCase(); if(pattern.test(title) || pattern.test(plats) || pattern.test(omrade)) { search_results.push(elm_spots_list[i]); added = true; } if(!added) { for(var p in layers) { if(pattern.test(layers[p].title)) { search_results.push(elm_spots_list[i]); break; } } } } } function sortResult(result, index) { return array.sort((function(index){ return function(a, b){ return (a[index] === b[index] ? 0 : (a[index] < b[index] ? -1 : 1)); }; })(index)); } var result_array = []; for(var o in search_results) { result_array[o] = []; result_array[o]['url'] = search_results[o].url; result_array[o]['id'] = search_results[o].spotid; result_array[o]['title'] = search_results[o].title; result_array[o]['omrade'] = search_results[o].omrade; result_array[o]['plats'] = search_results[o].plats; result_array[o]['layers'] = ''; for(var t in search_results[o].layers) { if(t > 0) { result_array[o]['layers'] += ", " + search_results[o]['layers'][t].title; } else { result_array[o]['layers'] += search_results[o]['layers'][t].title; } } } function render(spots) { var html = ''; for(var i in spots) { console.log(spots); html += "<tr class='elm-result-row' id='" + spots[i].url + "'>"; html += "<td class='elm-result-cell'>" + spots[i].title + "</td>"; html += "<td class='elm-result-cell'>" + spots[i].layers + "</td>"; html += "<td class='elm-result-cell'>" + spots[i].omrade + "</td>"; html += "<td class='elm-result-cell'>" + spots[i].plats + "</td>"; html += "</tr>"; } $('.elm-result-body').append(html); $('.elm-result-row').click(function() { console.log(this.id); }); } if(!is_empty(search_results)) { render(result_array); search_results = []; } else { } }).on('empty', function() { $('.elm-result-body').html(''); }); });
//= require ./sweetalert2.all.min
import Ember from 'ember'; const assign = Ember.assign || Ember.merge; export default Ember.ArrayProxy.extend({ content: Ember.A(), defaultClearDuration: 3200, defaultAutoClear: false, addNotification(options) { // If no message is set, throw an error if (!options.message) { throw new Error("No notification message set"); } const notification = Ember.Object.create({ message: options.message, type: options.type || 'info', // info, success, warning, error autoClear: (Ember.isEmpty(options.autoClear) ? this.get('defaultAutoClear') : options.autoClear), clearDuration: options.clearDuration || this.get('defaultClearDuration'), onClick: options.onClick, htmlContent: options.htmlContent || false }); this.pushObject(notification); if (notification.autoClear) { notification.set('remaining', notification.get('clearDuration')); this.setupAutoClear(notification); } return notification; }, // Helper methods for each type of notification error(message, options) { this.addNotification(assign({ message: message, type: 'error' }, options)); }, success(message, options) { this.addNotification(assign({ message: message, type: 'success' }, options)); }, info(message, options) { this.addNotification(assign({ message: message, type: 'info' }, options)); }, warning(message, options) { this.addNotification(assign({ message: message, type: 'warning' }, options)); }, removeNotification(notification) { if (!notification) { return; } notification.set('dismiss', true); // Delay removal from DOM for dismissal animation Ember.run.later(this, () => { this.removeObject(notification); }, 500); }, setupAutoClear(notification) { notification.set('startTime', Date.now()); const timer = Ember.run.later(this, () => { // Hasn't been closed manually if (this.indexOf(notification) >= 0) { this.removeNotification(notification); } }, notification.get('remaining')); notification.set('timer', timer); }, pauseAutoClear(notification) { Ember.run.cancel(notification.get('timer')); const elapsed = Date.now() - notification.get('startTime'); const remaining = notification.get('clearDuration') - elapsed; notification.set('remaining', remaining); }, clearAll() { this.set('content', Ember.A()); }, setDefaultAutoClear(autoClear) { if (Ember.typeOf(autoClear) !== 'boolean') { throw new Error('Default auto clear preference must be a boolean'); } this.set('defaultAutoClear', autoClear); }, setDefaultClearNotification(clearDuration) { if (Ember.typeOf(clearDuration) !== 'number') { throw new Error('Clear duration must be a number'); } this.set('defaultClearDuration', clearDuration); } });
import React from 'react'; import PropTypes from 'prop-types'; import { View, Text, } from 'react-native'; const propTypes = { bottom: PropTypes.number.isRequired, displayText: PropTypes.string, color: PropTypes.string, opacity: PropTypes.number, width: PropTypes.number.isRequired }; const defaultProps = { color: 'gray', opacity: .7 }; class HorizontalLine extends React.Component { render() { const { color, opacity, bottom, displayText, width } = this.props; return ( <View style={{ opacity: opacity, backgroundColor: 'transparent', width: width, borderStyle: 'dashed', borderColor: color, borderWidth: .5, height: 1, bottom: bottom, position: 'absolute' }} > <Text style={{ position: 'absolute', bottom: 0, fontSize: 8 }} > {displayText} </Text> </View> ); } } HorizontalLine.propTypes = propTypes; HorizontalLine.defaultProps = defaultProps; export default HorizontalLine;
const RouteRecognizer = require('route-recognizer'); const glob = require('glob'); const router = new RouteRecognizer(); class Router { constructor(paths = []) { this.multiAdd(paths); } add(paths) { paths = Array.isArray(paths) ? paths : [ paths ]; router.add(paths); } multiAdd(paths) { paths = Array.isArray(paths) ? paths : [ paths ]; paths.forEach(path => router.add([ path ])); } async install(ctx, next) { const assemblyLine = router.recognize(ctx.path) || []; for (let i = 0; i < assemblyLine.length; i++) { const { handler, params } = assemblyLine[i]; delete params['']; Object.assign(ctx.request.query, params); await handler.apply(ctx, [ ctx ]); } await next(); } } const pages = glob.sync('./server/pages/*'); const paths = pages.reduce((paths, each) => { const path = each.replace(/^\.\/server\/pages|\.js$/g, ''); const handler = require(each.replace(/^\.\/server/, '..')); paths.push({ path, handler }); if (path === '/auto') { paths.push({ path: '/auto/', handler }); } return paths; }, [ { path: '/', handler: require('../pages/index.js') }, { path: '/static/*', handler: require('../pages/static.js') }, { path: '/demos/*', handler: require('../pages/demos.js') }, { path: '/manifest.json', handler: require('../pages/demos.js') }, { path: '/auto/manifest.json', handler: require('../pages/demos.js') }, { path: '/auto/*', handler: require('../pages/auto.js') }, { path: '/sw.js', handler: require('../pages/sw.js') }, { path: '/googleb2d01223dfd5850d.html', handler: require('../pages/googleb2d01223dfd5850d.js') }, { path: '/whoareyou.json', handler: require('../pages/whoareyou.js') }, ]); module.exports = new Router(paths);
(function(module) { var contactController = {}; contactController.index = function() { $('.containing-landing').hide(); $('#contact').show().siblings().hide(); }; module.contactController = contactController; })(window);
import React, { Component } from 'react'; import Sticky from '../components/Sticky'; import MovieNav from '../components/MovieNav'; import MovieCards from '../components/MovieCards'; import PropTypes from 'prop-types'; import Loader from '../components/Loader'; const propTypes = { sticky: PropTypes.bool.isRequired, navigation: PropTypes.object.isRequired, loadingMovies: PropTypes.bool.isRequired }; class MovieContent extends Component { componentWillMount() {} paginationOnChange = (page) => { this.props.setPage(page); } render() { const { dispatch, height, sticky, movies, navigation, loadingMovies } = this.props; return ( <div className={`movies ${(sticky ? 'sticky' : '')}`}> <MovieNav {...this.props} /> { (loadingMovies) ? <Loader /> : <MovieCards {...this.props} data={movies.data} /> } {/* { this.props.loading ? <Loader /> : null } */} </div> ); } } MovieContent.propTypes = propTypes; export default Sticky(MovieContent, 50);
(function() { 'use strict'; angular .module('core') .run(run); run.$inject = ['$rootScope']; /* @ngInject */ function run($rootScope) { var _ = $rootScope, methods = {}; methods.chunk = function(array, n) { return _.transform(array, function(result, el, i, arr) { return i % n === 0 ? result.push(arr.slice(i, i + n)) : null; }); }; methods.stripBase64 = function(str) { return str.replace(/^data:image\/png;base64,/, ''); }; //methods.recursive = function(obj, opt, iterator) { // function recurse(obj, property) { // iterator(obj, property); // _.each(_.keys(obj), function(prop) { // recurse(obj[prop]); // }); // //_.each(obj[opt], recurse); // } // recurse(obj); //}; _.each(methods, function(method, methodName) { _[methodName] = _.bind(method, _); }); } })();
this.manifest = { "name": "Visual Site Alert", "icon": "icon.png", "settings": [ { "tab": "Site List", "group": "Add New Alert", "name": "myDescription", "type": "description", "text": "Site URL specifies the URL you want to match. You can use <strong>*</strong> as a wild card. \ For example, <strong>http*://*.ca</strong> will match all sites in .ca domain. \ Alert text specifies the text that will appear atop of the bar.\ Similarly, use a regular expression in the Page Content field, to show the notification bar only \ when certain content is present." }, { "tab": "Site List", "group": "Add New Alert", "name": "site_url", "type": "text", "label": "Site URL", "text": "Example: http://google.*" }, { "tab": "Site List", "group": "Add New Alert", "name": "site_contents", "type": "text", "label": "Page Contents" }, { "tab": "Site List", "group": "Add New Alert", "name": "site_alert", "type": "text", "label": "Alert Text", "text": "Example: Warning! You are now on google!" }, { "tab": "Site List", "group": "Add New Alert", "name": "addAlert", "type": "button", "text": "Add Alert" }, { "tab": "Site List", "group": "Existing Alerts", "name": "existingAlerts", "type": "description", "text": "Existing alerts." } ], "alignment": [ [ "site_url", "site_alert", "site_contents" ] ] };
/* * purge.js * * CVS/SVN Keywords *------------------------------ * $Author: cnobile $ * $Date: 2011-11-10 20:29:49 -0500 (Thu, 10 Nov 2011) $ * $Revision: 54 $ *------------------------------ */ var Purge = function() { this._setupSubmit(); this._CONFIRM_REQUEST = null; this._DELETE_REQUEST = null; }; Purge.prototype = { _CONTACT_SERVER_TXT: "Wait while contacting the server...", _setupSubmit: function() { this._CONFIRM_REQUEST = this._confirmationRequest.bind(this); this._DELETE_REQUEST = this._deleteRequest.bind(this); $('form#form').submit(this._CONFIRM_REQUEST); $('input#search').click(function() { window.location = "/maintenance/purge/"; }); $('input#reset').click(function () { this._setMessage(""); }.bind(this)); }, _confirmationRequest: function() { this._setMessage(this._CONTACT_SERVER_TXT); this._callAjax("post", this._assembleURI("/maintenance/confirm/"), this._createJSON(), this._confirmationCB); }, _confirmationCB: function(json, status) { this._setMessage(json['message']); if(json['valid']) { $('form#form').unbind('submit', this._CONFIRM_REQUEST); $('form#form').bind('submit', this._DELETE_REQUEST); } }, _deleteRequest: function() { this._callAjax("post", this._assembleURI("/maintenance/delete/"), this._createJSON(), this._deleteCB); }, _deleteCB: function(json, status) { this._setMessage(json["message"]); if(json['valid']) { $('td input[type=checkbox]').each(function() { if(this.checked) { $(this).parent().parent().remove(); } }); } $('form#form').unbind('submit', this._DELETE_REQUEST); $('form#form').bind('submit', this._CONFIRM_REQUEST); this._setMessage(true); }, _createJSON: function() { var checkboxes = $('td > input[type=checkbox]'); var pks = []; for(var i = 0; i < checkboxes.length; i++) { var box = checkboxes[i]; if(box.checked) { var node = $(box).parent().parent().find("td > input[type=hidden]"); pks[i] = node[0].value; } } var json = {pks: pks}; return json; } }; $(document).ready(function() { extend(Purge, AjaxBase); new Purge(); });
/* The MIT License (MIT) Copyright (c) 2014 Charles Bryan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ !function(t){t.fn.activeScroll=function(n){var o=t.extend({animation:200,"class":"active",nav:"nav",navItem:"li",navLink:"a",sections:"section",sectionIdAttr:"id",threshold:-10},n),i=o.nav+" "+o.navItem,s=i+" "+o.navLink,a=!1,e=t(this).find(o.sections).filter(function(){var n=t(this),i=n.attr(o.sectionIdAttr);if(!i)return!1;var e="#"+i,r=t(s+"[href='"+e+"']");return r?(r.click(function(i){if(i.preventDefault(),window.history.pushState){var s=window.location.hash.replace(window.location.hash,e);a?window.history.replaceState({},"",s):window.history.pushState({},"",s),a=!0}t("html, body").animate({scrollTop:n.offset().top+(o.threshold+1)})}),t(this).prop("$link",r),!0):!1});t(window).scroll(function(){var n=t(window).scrollTop();e.each(function(){t(this).offset().top<=n-o.threshold&&(t(i+"."+o.class).removeClass(o.class),t(this).prop("$link").closest(i).addClass(o.class))})}).scroll()}}(jQuery);
(function(testacular, requirejs, require) { // monkey patch requirejs, to use append timestamps to sources // to take advantage of testacular's heavy caching // it would work even without this hack, but with reloading all the files all the time var normalizePath = function(path) { var normalized = []; var parts = path.split('/'); for (var i = 0; i < parts.length; i++) { if (parts[i] === '.') { continue; } if (parts[i] === '..' && normalized.length && normalized[normalized.length - 1] !== '..') { normalized.pop(); continue; } normalized.push(parts[i]); } return normalized.join('/'); }; var createPatchedLoad = function(files, originalLoadFn) { return function (context, moduleName, url) { url = normalizePath(url); if (files.hasOwnProperty(url)) { url = url + '?' + files[url]; } else { console.error('There is no timestamp for ' + url + '!'); } return originalLoadFn.call(this, context, moduleName, url); }; }; // config base path require.config({ baseUrl: '/base' }); // make it async testacular.loaded = function() {}; // patch require.js requirejs.load = createPatchedLoad(testacular.files, requirejs.load); })(window.__testacular__, window.requirejs, window.require);
import SVG from './SVG'; import Radium from 'radium'; import { layout, svg } from 'd3'; import { Spring } from 'react-motion'; import { Component, PropTypes } from 'react'; export default class PieChart extends Component { static defaultProps = { data: PropTypes.array.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, outerRadius: PropTypes.number.isRequired, innerRadius: PropTypes.number.isRequired } state = { ...[...Array(this.props.data.length)].map(() => false) } onMouseOver = (i) => () => this.setState({ [i]: true }) onMouseOut = (i) => () => this.setState({ [i]: false }) render() { const { innerRadius, outerRadius, width, height } = this.props; const pie = layout.pie().padAngle(.02); const arc = svg.arc().padRadius(outerRadius).innerRadius(innerRadius); return ( <SVG width={width} height={height}> <g transform={`translate(${width / 2}, ${height / 2})`}> { pie(this.props.data).map( (dataPoint, i) => <Spring key={i} endValue={{ val: this.state[i] ? outerRadius : outerRadius - 20 }}> { ({ val }) => <Path d={arc({ ...dataPoint, outerRadius: val })} onMouseOver={this.onMouseOver(i)} onMouseOut={this.onMouseOut(i)} /> } </Spring>) } </g> </SVG> ); } } @Radium class Path extends Component { render() { return ( <path style={{ fill: '#CCCCCC', stroke: '#333333', strokeWidth: 1.5, transition: 'fill 250ms linear', cursor: 'pointer', ':hover': { fill: '#999999', stroke: '#000000' } }} d={this.props.d} onMouseOver={this.props.onMouseOver} onMouseOut={this.props.onMouseOut} /> ); } }
/*jslint node:true, vars:true, bitwise:true, unparam:true */ /*jshint unused:true */ /*global */ var ledController = require("./ledController.js"); ledController.clear(); ledController.smile(); var motorController = require("./motorController.js") motorController.go(); motorController.stop(); //motorController.demo(); var headControler = require("./headcontroller.js"); headControler.lookMiddle(); var theThingsAPI = require('thethingsio-api'); var motionKEY = 'motion'; //create Client var client = theThingsAPI.createClient(); var lastAction = "@@@"; function readMotions() { //read latest write var req1 = client.thingReadLatest(motionKEY); //event fired when the response arrives req1.on('response',function(res){ if (res.statusCode == 200 && res.payload !== undefined) { var payload = JSON.parse(res.payload); var newAction = payload.data[0].value; if (newAction !== lastAction) { lastAction = newAction; motorController.doAction(newAction); } } }); req1.end(); } readMotions(); motorController.stop(); var loopCounter = 0; setInterval(function() { readMotions(); }, 200);
module.exports = { accepted: ':attribute må være akseptert.', alpha: ':attribute feltet kan kun inneholde alfabetiske tegn.', alpha_dash: ':attribute feltet kan kun inneholde alfanumeriske tegn, i tillegg til bindestreker og understreker.', alpha_num: ':attribute feltet må være alfanumerisk.', between: ':attribute feltet må være mellom :min og :max.', confirmed: ':attribute feltet stemmer ikke overens med bekreftelsen.', email: ':attribute formatet er ugyldig.', date: ':attribute er et ugyldig datoformat.', def: ':attribute attributtet har feil.', digits: ':attribute må være på :digits siffer.', different: ':attribute og :different må være forskjellige.', 'in': 'Den oppgitte verdien for :attribute er ugyldig.', integer: ':attribute må være et heltall.', hex: 'The :attribute should have hexadecimal format', min: { numeric: ':attribute må minst være :min.', string: ':attribute må være på minst :min tegn.' }, max: { numeric: ':attribute kan ikke være større enn :max.', string: ':attribute kan maks ha :max tegn.' }, 'not_in': 'Den oppgitte verdien for :attribute er ugyldig.', numeric: ':attribute må være et tall.', present: 'The :attribute field must be present (but can be empty).', required: ':attribute feltet er påkrevd.', required_if: ':attribute er påkrevd når :other er :value.', same: ':attribute og :same må være like.', size: { numeric: ':attribute må ha størrelsen :size.', string: ':attribute må ha :size tegn.' }, string: ':attribute må være tekst.', url: ':attribute formatet er ugyldig.', regex: ':attribute formatet er ugyldig.', attributes: {} };
$(function(){ var from = MUDSLIDE.from, to = MUDSLIDE.to, label = MUDSLIDE.label, cloneAppend = MUDSLIDE.cloneAppend, copyProperties = MUDSLIDE.copyProperties, deepClone = MUDSLIDE.deepClone, tokenize = MUDSLIDE.tokenize, tokenizeChars = MUDSLIDE.tokenizeChars, mediaPlay = MUDSLIDE.mediaPlay, mediaVolume = MUDSLIDE.mediaVolume, mediaStop = MUDSLIDE.mediaStop, killTweens = MUDSLIDE.killTweens, record = MUDSLIDE.record, revert = MUDSLIDE.revert, delay = MUDSLIDE.delay, pause = MUDSLIDE.pause, wrapInner = MUDSLIDE.wrapInner; /** These are the tween generation rules, with an order which can be used to determine their priority within * a scene. Keys are selectors, and values are either... * - SchedulerFactories * - objects (further selector keys in the heirarchy) * - arrays (further sequences of factories and objects) * */ var gantZoomGs0 = {position:"absolute",fontSize:"12pt",top:"0%",left:"0%",width:"100%",height:"33%",zIndex:2,autoAlpha:1,repeat:1,yoyo:true}; var gantZoomGs1 = copyProperties({top:"33.6%"},deepClone(gantZoomGs0)); var gantZoomGs2 = copyProperties({top:"66.6%"},deepClone(gantZoomGs0)); var gantZoomMs = {duration:1,outerOffset:"-=2"}; var gantLiZoomGs = {display:"none",position:"relative",left:"500px",repeat:1,yoyo:true}; var gantLiZoomMs = {duration:1,innerOffset:"-=2"}; var rules = [ {".scene":[ //reveals in order of preferred appearance {".scene":from({},{duration:1.0,outerOffset:"-=0.9"})}, {".scene .gantt":pause()}, {".gantt td":record()}, //records position of all divs without disturbing layout {".gantt td":revert()}, //applies recorded positions to all, recreating layout in absolute terms? //animate transcription tasks {".gantt .method li":from(gantLiZoomGs,gantLiZoomMs)}, {".gantt .method .transcription.phase0": to(gantZoomGs0,gantZoomMs)}, {".gantt .method .transcription.phase1":to(gantZoomGs1,gantZoomMs)}, {".gantt .method .transcription.phase2":to(gantZoomGs2,gantZoomMs)}, {".gantt":[pause("-=1"), pause()]}, //animate workshop tasks {".gantt .workshop li":from(gantLiZoomGs,gantLiZoomMs)}, {".gantt .phase0 .workshop": to(gantZoomGs0,gantZoomMs)}, {".gantt .phase1 .workshop":to(gantZoomGs1,gantZoomMs)}, {".gantt .phase2 .workshop":to(gantZoomGs2,gantZoomMs)}, {".gantt":[pause("-=1"), pause()]}, //animate publication tasks {".gantt .publication li":from(gantLiZoomGs,gantLiZoomMs)}, {".gantt .phase0 .publication": to(gantZoomGs0,gantZoomMs)}, {".gantt .phase1 .publication":to(gantZoomGs1,gantZoomMs)}, {".gantt .phase2 .publication":to(gantZoomGs2,gantZoomMs)}, {".gantt":[pause("-=1"), pause()]}, {".scene.console li.tokenize":[ cloneAppend("<audio class='typing' preload='auto' ><source src='audio/teletype_beep.wav' /> </audio>"), //creates an audio sample cloneAppend("<span class='cursor'>_</span>"), //copies a cursor in place at build time {">span.cursor":from({repeat:-1,yoyo:true},{duration:0.25,parallel:true})}, {"li.tokenize:not(.auto)":pause()}, {"audio.typing":[from({duration:0.05},{}), mediaVolume(0.15), mediaPlay()]}, //plays the audio sample tokenizeChars( from({display:"none",delay:0.05},{duration:0}) ), {">span.cursor":to({},{parallel:true})}, {"audio.typing":mediaStop()}, //stops the audio sample ]}, {".grow":from({width:0},{})}, {"h2":from({},{duration:2,innerOffset:"-=1.5"})}, {"blockquote":from({},{duration:2,innerOffset:"-=1.5"})}, {".left,.wide": from({position:"relative",top:"25px",left:"-25px",ease:Power1.easeIn},{})}, {".right": from({position:"relative",top:"25px",left:"25px",ease:Power1.easeIn},{outerOffset:"-=" + MUDSLIDE.configuration.defaultMsProps.from.duration})}, label("scene"), {".scene:not(.intro)":pause()}, //{".scene:not(.intro)":delay(2)}, //conceals in order of preferred appearance {".right": to({position:"relative",top:"25px",left:"25px"})}, {".left,.wide": to({position:"relative",top:"25px",left:"-25px"})}, {"blockquote":to({},{innerOffset:"-=" + (MUDSLIDE.configuration.defaultMsProps.to.duration * 0.75)})}, {"h2":to({},{innerOffset:"-=" + (MUDSLIDE.configuration.defaultMsProps.to.duration * 0.75)})}, {".grow":to({width:0})}, {".scene:not(.intro)":to({delay:0.1}, {duration:1.0})}, {".scene.intro":to({}, {autoDelay:0.075})}, ]} ]; //CH TODO - figure out how to activate this on a per-slide basis - triggering only when shown to save CPU var translateMax = 50; var scaleMax = 1.2; var translateX = Math.round(-translateMax + (Math.random() * translateMax * 2)); var translateY = Math.round(-translateMax + (Math.random() * translateMax * 2)); TweenMax.to(".background", 60, { transform:"translateX(" + translateX + "px) translateY(" + translateY + "px) scaleX(" + scaleMax + ") scaleY(" + scaleMax + ")", ease:Linear.easeNone, repeat:-1, yoyo:true }); //CH TODO - find a neat representation for this within the macro language var washTl = new TimelineMax({repeat:-1,yoyo:true}); washTl.append(TweenMax.to(".wash", 30, {backgroundColor:"hsl(0,50%,50%)"})); washTl.append(TweenMax.to(".wash", 30, {backgroundColor:"hsl(120,50%,50%)"})); washTl.append(TweenMax.to(".wash", 30, {backgroundColor:"hsl(240,50%,50%)"})); washTl.play(); MUDSLIDE.initDeck(rules); MUDSLIDE.timeline.pause(); /* var matchMaker = function(string){ return function(item){ return item.name.indexOf(string) != -1; }; }; TweenLite.fromTo(MUDSLIDE.timeline, 120, {time:0}, {time:300}); MUDSLIDE.timeline.tweenTo(MUDSLIDE.getPauseLabel(3), {onComplete:function(){MUDSLIDE.timeline.timeScale=1;}}); */ /* //switch this for a media tween factory ASAP var audio = $.media("#theme"); $("#theme").bind("canplaythrough", function () { //audio.seek(38); audio.play(); }); */ });
import assert from 'assert'; import sinon from 'sinon'; import githubSearch from '../../lib/resolver/github-search.js'; describe('github-search', () => { const sandbox = sinon.sandbox.create(); const fetchStub = sinon.stub(window, 'fetch'); const path = '/octo/foo.txt'; const target = 'bar.txt'; afterEach(() => { fetchStub.reset(); sandbox.reset(); }); after(() => { sandbox.restore(); }); it('returns a function', () => { assert.deepEqual( typeof githubSearch({ path, target }), 'function', ); }); it('calls the github search api', () => { githubSearch({ path, target })(); assert.deepEqual( fetchStub.args[0][0], 'https://api.github.com/search/code?q=bar.txt+in:path+filename:bar.txt+repo:octo/foo.txt+extension:.txt', ); }); it('does not append query param "extension" when target does not have a file extension', () => { githubSearch({ path, target: 'bar' })(); assert.deepEqual( fetchStub.args[0][0], 'https://api.github.com/search/code?q=bar+in:path+filename:bar+repo:octo/foo.txt', ); }); });
module.exports = { name: "part", ns: "irc", description: "Part Message", phrases: { active: "Client parting" }, ports: { input: { bot: { title: "IRC Client", type: "Client", required: true } }, output: { channel: { title: "Channel", type: "string" }, who: { title: "Who", type: "string" }, reason: { title: "Reason", type: "string" } } }, fn: function part(input, $, output, state, done, cb, on) { var r = function() { $.bot.part('part', function partCallback(channel, who, reason) { cb({ channel: channel, who: who, reason: reason }); }); }.call(this); return { output: output, state: state, on: on, return: r }; } }
import React from 'react'; import userEvent from '@testing-library/user-event'; import { render, screen } from '@testing-library/react'; import TextInput from './TextInput'; let clearErrorsCallback, setDataCallback; beforeEach(() => { clearErrorsCallback = jest.fn(); setDataCallback = jest.fn(); }); describe('TextInput component', () => { /** @test */ test('renders a text input element', () => { render( <TextInput clearErrors={clearErrorsCallback} id="text_input_test" setData={setDataCallback} value="sample text" />, ); const textInputElement = screen.getByTestId('text-input-element'); expect(textInputElement).toHaveAttribute('type', 'text'); }); /** @test */ test('will trigger clearErrors and setData methods on input change event', () => { render( <TextInput clearErrors={clearErrorsCallback} id="text_input_test" setData={setDataCallback} value="" />, ); const textInputElement = screen.getByTestId('text-input-element'); userEvent.type(textInputElement, 'hi'); const calls = setDataCallback.mock.calls; expect(clearErrorsCallback).toHaveBeenCalledTimes(2); expect(setDataCallback).toHaveBeenCalledTimes(2); expect(calls[0]).toEqual(['text_input_test', 'h']); expect(calls[1]).toEqual(['text_input_test', 'i']); }); });
var controllersModule = angular.module('controllers', ['services']);//create a module with name 'controllers' and 'services' as dependency to it //create controller under this module 'controllers' and inject 'searchService' to it. controllersModule.controller('searchController', ['$scope', 'searchService', function($scope, searchService) { $scope.welcomeMsg = 'Search PB Site'; $scope.search = function() { //use the injected searchService to make actual search searchService.search($scope.searchTerm).then(function(result) { $scope.result = result.data;//response from searchService is set in $scope.result to render it in UI. }); } } ]);
/** * 缓存图片 * * @author liuwencheng * @date 2012-12-20 * * @update by liuwencheng 2013-6-2 重新处理已加载的图片缓存 * @update by z 2013-6-15 添加参数处理图片附加数据 * @update by liuwencheng 2013-8-28 包装成Class以实现多个实例加载, 增加loaded */ define(function(require,exports){ var $ = require('jquery') , objs = require('zz/utils/objs') , Class = require('zz/core/Class') var defaultOpts = { imgs: [], infos: [], done: null, sync: false, loaded: null } var ImgsLoader = Class() .init(function (opts) { this._opts = objs.extend({},defaultOpts, opts) //配置 this._leftNum = this._opts.imgs.length //剩余加载的数量 this._start() }) .method({ /** * 开始加载图片 */ _start: function () { var len = this._opts.imgs.length //异步加载 if (! this._opts.sync) { while (len--) { this.loadImg(len) } } //同步加载 else { this.loadImg(0) //加载第一张 } }, /** * 加载单个图片 * @param index {Number} img在数组中的位置 */ loadImg: function (index) { var img = new Image , that = this , _opts = this._opts , info //超出数组大小 if(index >= _opts.imgs.length) return //获取信息 info = _opts.infos && _opts.infos[index] //加载成功 img.onload = function(){ _opts.done && _opts.done(img,index,info) //数量-1 that._leftNum = that._leftNum - 1 //全部加载完 if (that._leftNum === 0) { _opts.loaded && _opts.loaded() that.destroy() //销毁 return } // 顺序加载时加载下一个图片 _opts.sync && that.loadImg(index+1) } //加载失败 img.onerror = function(){ _opts.sync && that.loadImg(index+1) } img.src = _opts.imgs[index] } }) /* * opts = { * imgs: {Array} * infos:{Array} 图片附加信息,和图片对应 * done: {Function} ( {Object} ImgObj 图片对象, {Number} index, {*} info )回调函数,加载完图片后执行 * loaded {Function} 图片全部加载完成的回调 * sync: {Boolean} 顺序加载图片, 默认false * } */ return function(opts){ return new ImgsLoader(opts) } });
var express = require('express'); var router = express.Router(); var cb_handler = require('../handlers/cb_handler.js'); var db_handler = require('../handlers/db_handler.js'); //Listar categorias router.get('/', function(req, res) { var my_cb_handler = cb_handler(req, res, null, db_handler.getCategories); db_handler.atenderQuery(req,res,my_cb_handler); }); //Agregar nueva categoria router.post('/', function (req, res) { var my_cb_handler = cb_handler(req,res,null, db_handler.addCategory); db_handler.atenderQuery(req,res,my_cb_handler); }); module.exports = router;
/* --- Day 11: Corporate Policy --- Santa's previous password expired, and he needs help choosing a new one. To help him remember his new password after the old one expires, Santa has devised a method of coming up with a password based on the previous one. Corporate policy dictates that passwords must be exactly eight lowercase letters (for security reasons), so he finds his new password by incrementing his old password string repeatedly until it is valid. Incrementing is just like counting with numbers: xx, xy, xz, ya, yb, and so on. Increase the rightmost letter one step; if it was z, it wraps around to a, and repeat with the next letter to the left until one doesn't wrap around. Unfortunately for Santa, a new Security-Elf recently started, and he has imposed some additional password requirements: Passwords must include one increasing straight of at least three letters, like abc, bcd, cde, and so on, up to xyz. They cannot skip letters; abd doesn't count. Passwords may not contain the letters i, o, or l, as these letters can be mistaken for other characters and are therefore confusing. Passwords must contain at least two different, non-overlapping pairs of letters, like aa, bb, or zz. For example: hijklmmn meets the first requirement (because it contains the straight hij) but fails the second requirement requirement (because it contains i and l). abbceffg meets the third requirement (because it repeats bb and ff) but fails the first requirement. abbcegjk fails the third requirement, because it only has one double letter (bb). The next password after abcdefgh is abcdffaa. The next password after ghijklmn is ghjaabcc, because you eventually skip all the passwords that start with ghi..., since i is not allowed. Given Santa's current password (your puzzle input), what should his next password be? --- Part Two --- Santa's password expired again. What's the next one? */ var corporatePolicy = require('./app/corporate_policy'); console.log(corporatePolicy.day11()); console.log(corporatePolicy.part2());
var app = require('http').createServer(handler) , fs = require('fs') , path = require('path') , url = require('url') ,mime=require('mime') app.listen(80); function handler (req, res) { var uri = url.parse(req.url).pathname; if(uri=='/'){ uri='/index.html' } uri=uri.replace(/%20/g,' ') console.log(uri) var filename = path.join(process.cwd(), uri); fs.readFile(filename, function (err, data) { if (err) { res.writeHead(404); return res.end('Error loading file...'); } res.setHeader('Content-type',mime.lookup(uri)); res.writeHead(200); res.end(data); }) }
/** * * @providesModule ReactNativeHeading * @flow */ 'use strict'; var React = require('react-native'); var ReactNativeHeading = React.NativeModules.ReactNativeHeading; module.exports = ReactNativeHeading;
export default class AttributeLocalization { /** * AttributeLocalization constructor. * * @param {string} formLabel */ constructor(formLabel) { this.formLabel = formLabel; } }
/* * Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) * * openAUSIAS: The stunning micro-library that helps you to develop easily * AJAX web applications by using Java and jQuery * openAUSIAS is distributed under the MIT License (MIT) * Sources at https://github.com/rafaelaznar/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ 'use strict'; moduloUsuario.controller('UsuarioNewController', ['$scope', '$routeParams', '$location', 'serverService', 'sharedSpaceService', function ($scope, $routeParams, $location, serverService, sharedSpaceService) { $scope.id = $routeParams.id; $scope.ob = 'usuario'; $scope.result = null; $scope.title = "Crear un nuevo usuario"; $scope.icon = "fa-user"; if (sharedSpaceService.getFase() == 0) { $scope.obj = { id: 0, login: "", password: "", id_estado: 0, obj_estado: { id: 0 }, id_tipousuario: 0, obj_tipousuario: { id: 0 }, ciudad: "", firma: "", skin: "" }; } else { $scope.obj = sharedSpaceService.getObject(); sharedSpaceService.setFase(0); } $scope.chooseOne = function (foreignObjectName) { sharedSpaceService.setObject($scope.obj); sharedSpaceService.setReturnLink('/' + $scope.ob + '/new'); sharedSpaceService.setFase(1); $location.path('/' + foreignObjectName + '/selection/1/10'); } $scope.save = function () { console.log("save"); console.log({json: JSON.stringify(serverService.array_identificarArray($scope.obj))}); //strValues = serverService.array_identificarArray(thisObject.form_getFormValues(strClass)); serverService.getDataFromPromise(serverService.promise_setOne($scope.ob, {json: JSON.stringify(serverService.array_identificarArray($scope.obj))})).then(function (data) { $scope.result = data; }); }; $scope.$watch('obj.obj_estado.id', function () { serverService.getDataFromPromise(serverService.promise_getOne('estado', $scope.obj.obj_estado.id)).then(function (data2) { $scope.obj.obj_estado = data2.message; }); }); $scope.$watch('obj.obj_tipousuario.id', function () { serverService.getDataFromPromise(serverService.promise_getOne('usuario', $scope.obj.obj_tipousuario.id)).then(function (data2) { $scope.obj.obj_tipousuario = data2.message; }); }); $scope.back = function () { window.history.back(); }; $scope.close = function () { $location.path('/home'); }; $scope.plist = function () { $location.path('/usuario/plist'); }; $("#alta_group").datetimepicker({format: "DD/MM/YYYY", locale: "es"}); $("#cambio_group").datetimepicker({format: "DD/MM/YYYY", locale: "es"}); }]);
/*globals describe, it, beforeEach, afterEach */ var assert = require("assert"), fs = require('fs'), _ = require('underscore'), path = require("path"), Html = require("../lib/html.js"), describeReporting = require("../../../test/helpers.js").describeReporting; describeReporting(path.join(__dirname, "../../"), ["html"], function(reporter) { describe('html', function() { beforeEach(function() { this.html = new Html(reporter); }); it('should be rendered', function(done) { var request = { options: { type: "html", timeout: 5000 }, reporter: reporter, template: { content: "Hey" }, data: null }; var response = { headers: {}}; _.findWhere(reporter.extensionsManager.recipes, { name: "html" }).execute(request, response).then(function () { assert.equal("Hey", response.result); done(); }); }); }); });
'use babel'; const {CompositeDisposable} = require('atom'); const validUrl = require('valid-url'); const addMarker = (editor, marker) => { // abort early if (!editor.replaceSelectedText) { return ''; } return editor.replaceSelectedText(null, text => { return (text === '') ? '' : `${marker}$selection${marker}`.replace('$selection', text); }); }; class mdwrap { constructor() { this.subscriptions = new CompositeDisposable(); this.subscriptions.add( atom.commands.add('atom-workspace', { 'atom-markdown-wrapper:paste': this.paste, 'atom-markdown-wrapper:image': this.image, 'atom-markdown-wrapper:bold': this.bold, 'atom-markdown-wrapper:italic': this.italic, 'atom-markdown-wrapper:strikethrough': this.strikethrough }) ); } destroy() { this.subscriptions.dispose(); } paste(editor, selection, clipboard) { // abort early if (!editor.insertText || !clipboard) { return; } let insert; if (editor && selection && clipboard) { insert = '[$selection]($href)' .replace('$selection', selection) .replace('$href', clipboard); } if (!validUrl.isWebUri(clipboard) && !clipboard.match(/^#/)) { throw new Error('Not a valid URL or #anchor'); } editor.insertText(insert); return insert; } image(editor, selection, clipboard) { // abort early if (!editor.insertText || !clipboard) { return; } let insert; if (editor && clipboard) { insert = '![$selection]($href)' .replace('$selection', selection || '') .replace('$href', clipboard); } if (!validUrl.isWebUri(clipboard)) { throw new Error('Not a valid image URL'); } editor.insertText(insert); return insert; } bold(editor) { return addMarker(editor, '**'); } italic(editor) { return addMarker(editor, '_'); } strikethrough(editor) { return addMarker(editor, '~~'); } } module.exports = mdwrap;
define("ghost/routes/mobile-index-route", ["ghost/utils/mobile","exports"], function(__dependency1__, __exports__) { "use strict"; var mobileQuery = __dependency1__["default"]; // Routes that extend MobileIndexRoute need to implement // desktopTransition, a function which is called when // the user resizes to desktop levels. var MobileIndexRoute = Ember.Route.extend({ desktopTransition: Ember.K, activate: function attachDesktopTransition() { this._super(); mobileQuery.addListener(this.desktopTransitionMQ); }, deactivate: function removeDesktopTransition() { this._super(); mobileQuery.removeListener(this.desktopTransitionMQ); }, setDesktopTransitionMQ: function () { var self = this; this.set('desktopTransitionMQ', function desktopTransitionMQ() { if (!mobileQuery.matches) { self.desktopTransition(); } }); }.on('init') }); __exports__["default"] = MobileIndexRoute; });
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Callback // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ function tellMeWhenItIsDone(Callback) { setTimeout(function() { Callback(); }, (3*1000)); } tellMeWhenItIsDone( function() { console.log('google Foobar'); })
import { createStore, applyMiddleware, compose } from 'redux'; import reduxLogger from 'redux-logger'; import thunk from 'redux-thunk'; import reducers from 'reducers'; const logger = reduxLogger({ predicate: () => process.env.NODE_ENV === 'development', collapsed: true, duration: true, }); const middlewares = []; middlewares.push(applyMiddleware(...[thunk, logger])); export default createStore(reducers, {}, compose(...middlewares));
/** * @class Oskari.mapframework.service.base.Bundle * */ Oskari.clazz.define("Oskari.mapframework.service.base.Bundle", /** * @constructor * * Bundle's constructor is called when bundle is created. At * this stage bundle sources have been loaded, if bundle is * loaded dynamically. * */ function() { /* * Any bundle specific classes may be declared within * constructor to enable stealth mode * * When running within map application framework - Bundle * may refer classes declared with Oskari.clazz.define() - * Bundle may refer classes declared with Ext.define - * Bundle may refer classes declared within OpenLayers * libary * * */ }, { /* * @method create * * called when a bundle instance will be created * */ "create" : function() { return null; }, /** * @method update * * Called by Bundle Manager to provide state information to * bundle * */ "update" : function(manager, bundle, bi, info) { } }, /** * metadata */ { "protocol" : ["Oskari.bundle.Bundle"], "source" : { "scripts" : [{ "type" : "text/javascript", "src" : "../../../../sources/framework/service/service.js" } /*, { "type" : "text/javascript", "src" : "../../../../sources/framework/service/language-service.js" }*/], "resources" : [] }, "bundle" : { "manifest" : { "Bundle-Identifier" : "service-base", "Bundle-Name" : "mapframework.service.base.Bundle", "Bundle-Tag" : { "mapframework" : true }, "Bundle-Author" : [{ "Name" : "jjk", "Organisation" : "nls.fi", "Temporal" : { "Start" : "2009", "End" : "2011" }, "Copyleft" : { "License" : { "License-Name" : "EUPL", "License-Online-Resource" : "http://www.paikkatietoikkuna.fi/license" } } }], "Bundle-Name-Locale" : { "fi" : { "Name" : " mapframework.service.Bundle", "Title" : " mapframework.service.Bundle" }, "en" : {} }, "Bundle-Version" : "1.0.0", "Import-Namespace" : ["Oskari"], "Import-Bundle" : {} } } }); /** * Install this bundle by instantating the Bundle Class * */ Oskari.bundle_manager.installBundleClass("service-base", "Oskari.mapframework.service.base.Bundle");
// // Set up a collection to contain player information. On the server, // // it is backed by a MongoDB collection named "players". // Players = new Meteor.Collection("players"); // if (Meteor.isClient) { // Template.leaderboard.players = function () { // return Players.find({}, {sort: {score: -1, name: 1}}); // }; // Template.leaderboard.selected_name = function () { // var player = Players.findOne(Session.get("selected_player")); // return player && player.name; // }; // Template.player.selected = function () { // return Session.equals("selected_player", this._id) ? "selected" : ''; // }; // Template.leaderboard.events({ // 'click input.inc': function () { // Players.update(Session.get("selected_player"), {$inc: {score: 5}}); // } // }); // Template.player.events({ // 'click': function () { // Session.set("selected_player", this._id); // } // }); // } // // On server startup, create some players if the database is empty. // if (Meteor.isServer) { // Meteor.startup(function () { // if (Players.find().count() === 0) { // var names = ["Ada Lovelace", // "Grace Hopper", // "Marie Curie", // "Carl Friedrich Gauss", // "Nikola Tesla", // "Claude Shannon"]; // for (var i = 0; i < names.length; i++) // Players.insert({name: names[i], score: Math.floor(Math.random()*10)*5}); // } // }); // }
define(['antispammail'], function(antiSpamMail) { /** * Crypt given mail * * @method encrypt * @param {String} emailToEncrypt email address to encrypt * @returns {String} encrypted email address */ antiSpamMail.encrypt = function(emailToEncrypt) { return this.encryptDecrypt('mailto:' + emailToEncrypt, 1); }; /** * Initiate the form to encrypt * * @method encryptForm * @param {String} formName the name of the form * @param {String} fieldName name of email field * @returns void */ antiSpamMail.encryptForm = function(formName, fieldName) { var cryptform, email, emailHtml, encryptedMail, fieldShowEncryptedHtml, fieldShowEncryptedMail, i, radioObj, radioValue; formName = formName || 'antiSpamMail'; fieldName = fieldName || 'cryptmail_email'; fieldShowEncryptedMail = 'cryptmail_cryptedmail'; fieldShowEncryptedHtml = 'cryptmail_html'; cryptform = document.forms[formName]; email = cryptform[fieldName].value; if (cryptform.cryptmail_email.value.length < 4) { return false; } radioObj = cryptform.cryptmail_radio; if (radioObj.length > 0) { i = 0; while (i < radioObj.length) { radioValue = parseInt(radioObj[i].checked ? radioObj[i].value : void 0, 10); i++; } } else { radioValue = 0; } if (radioValue === 1) { emailHtml = email.replace(/\./g, '<span class="crypt" aria-hidden="true">.</span>.<span class="crypt" aria-hidden="true">.</span>'); emailHtml = emailHtml.replace(/@/, '<span class="crypt" aria-hidden="true">.</span>@<span class="crypt" aria-hidden="true">.</span>'); } else { emailHtml = email.replace(/\./g, ' [dot] '); emailHtml = emailHtml.replace(/@/, ' [at] '); } encryptedMail = this.encrypt(email); cryptform[fieldShowEncryptedMail].value = encryptedMail; cryptform[fieldShowEncryptedHtml].value = '<a href="javascript:' + this.encryptFn + '(\'' + encryptedMail + '\');">' + emailHtml + '</a>'; }; });
var Settings = Brumobile.Model.define( "SETTINGS", { name: "string", value: "string" } ); Settings.get = function(name, callback) { Settings.findOne({name:name}, function(setting) { if(setting) callback(setting.value); else callback(null); }); } Settings.save = function(name, value) { Settings.findOne({name:name}, function(setting) { if(setting) { setting.value = value; setting.save(); } else { var setting = new Settings({name:name, value:value}); setting.save(); } }); } Settings.remove = function(name) { Settings.findOne({name:name}, function(setting) { if(setting) { setting.destroy(); } }); }
// Regular expression that matches all symbols in the Miscellaneous Mathematical Symbols-A block as per Unicode v5.1.0: /[\u27C0-\u27EF]/;
version https://git-lfs.github.com/spec/v1 oid sha256:3bcf67b7cec3082efb04ef523044585dc1497641c27abaeaebb18be49aaeddaf size 85842
const addWater = () => image => image.addBandsReplace(water(image)) const water = image => image .selfExpression('i.water or (!i.snow and (i.blue/i.swir1 > 4.0 or i.ndwi > 0.15))') .rename('water') module.exports = addWater
var gplay = require('google-play-scraper'); var fs = require('fs'); var appSet = new Set(); var lineReader = require('readline').createInterface({ input: fs.createReadStream('teste') }); var wStream = fs.createWriteStream("handledApps.csv", { flags : 'w' }); lineReader.on('line', function (line){ if(line.indexOf("value") > -1){ var vals = line.split(":"); var pattern = /[\"\\\[\]]/g; var apps = vals[1].replace(pattern, "").split(","); console.log("********************"); console.log(vals[1]); console.log(vals[1].replace(pattern, "")); console.log(apps); apps.forEach(function(collectedApp){ appSet.add(collectedApp); }); } }); lineReader.on('close', function(){ console.log("Total of apps: " + appSet.size); appSet.forEach(function(collectedApp){ gplay.app({appId: collectedApp}) .then(function(app){ wStream.write(collectedApp + " " + app.genreId + "\n"); //console.log(collectedApp + " " + app.genreId); }) .catch(function(e){ console.log(collectedApp + ' = There was an error fetching the application!'); }); }); });
import chromedriver from'chromedriver'; export function testStart(webdriver) { chromedriver.start(); const driver = new webdriver.Builder() .forBrowser('chrome') .build(); return driver; } export function testStop(driver, done) { driver.quit().then(() => { chromedriver.stop(); done(); }); }
import { createStore, applyMiddleware, combineReducers, compose } from 'redux'; import * as reducers from './reducers'; import middleware from './middleware'; const reducer = combineReducers(reducers); // create a store that has redux-thunk middleware enabled const finalCreateStore = compose.apply(this, middleware.map(md => applyMiddleware(md)).concat([createStore])); export const store = finalCreateStore(reducer);
// For now we introduce the API but use the full underscore and backbone libs module.exports = require('./src/BevRealLibs.js');
import { GET_NEW_MUSIC_LIST_ID } from '../actions/index.js'; import { RESET_GAME } from '../actions/index.js'; export default function(state = null, action) { switch(action.type) { case GET_NEW_MUSIC_LIST_ID: return action.payload; case RESET_GAME: return null; } return state; }
'use strict'; angular.module('main') .service('Dialog', function ($cordovaDialogs, $q) { return { alert: function (message, title) { var defer = $q.defer(); if (window.cordova) { $cordovaDialogs.alert(message, title) .then(function () { defer.resolve(); }); } else { defer.reject('Unsupported platform'); } return defer.promise; }, confirm: function (message, title, buttonsText) { var defer = $q.defer(); if (window.cordova) { $cordovaDialogs.confirm(message, title, buttonsText) .then(function (result) { if (result === 2) { defer.resolve(true); } defer.reject(false); }); } else { defer.reject('Unsupported platform'); } return defer.promise; } }; });
window._ = require('lodash'); /** * We'll load jQuery and the Bootstrap jQuery plugin which provides support * for JavaScript based Bootstrap features such as modals and tabs. This * code may be modified to fit the specific needs of your application. */ window.$ = window.jQuery = require('jquery'); /** * Vue is a modern JavaScript library for building interactive web interfaces * using reactive data binding and reusable components. Vue's API is clean * and simple, leaving you to focus on building your next great project. */ window.Vue = require('vue'); /** * We'll register a HTTP interceptor to attach the "CSRF" header to each of * the outgoing requests issued by this application. The CSRF middleware * included with Laravel will automatically verify the header's value. */ //Vue.http.interceptors.push((request, next) => { // request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken); // // next(); //}); /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from "laravel-echo" // window.Echo = new Echo({ // broadcaster: 'pusher', // key: 'your-pusher-key' // });
/* Smoothly scroll element to the given target (element.scrollTop) for the given duration Returns a promise that's fulfilled when done, or rejected if interrupted Taken from https://coderwall.com/p/hujlhg/smooth-scrolling-without-jquery */ var smoothScrollTo = function(element, target, duration) { target = Math.round(target); duration = Math.round(duration); if (duration < 0) { return Promise.reject("bad duration"); } if (duration === 0) { element.scrollTop = target; return Promise.resolve(); } var start_time = Date.now(); var end_time = start_time + duration; var start_top = element.scrollTop; var distance = target - start_top; // based on http://en.wikipedia.org/wiki/Smoothstep var smooth_step = function(start, end, point) { if(point <= start) { return 0; } if(point >= end) { return 1; } var x = (point - start) / (end - start); // interpolation return x*x*(3 - 2*x); } return new Promise(function(resolve, reject) { // This is to keep track of where the element's scrollTop is // supposed to be, based on what we're doing var previous_top = element.scrollTop; // This is like a think function from a game loop var scroll_frame = function() { if(element.scrollTop != previous_top) { reject("interrupted"); return; } // set the scrollTop for this frame var now = Date.now(); var point = smooth_step(start_time, end_time, now); var frameTop = Math.round(start_top + (distance * point)); element.scrollTop = frameTop; // check if we're done! if(now >= end_time) { resolve(); return; } // If we were supposed to scroll but didn't, then we // probably hit the limit, so consider it done; not // interrupted. if(element.scrollTop === previous_top && element.scrollTop !== frameTop) { resolve(); return; } previous_top = element.scrollTop; // schedule next frame for execution setTimeout(scroll_frame, 0); } // boostrap the animation process setTimeout(scroll_frame, 0); }); }
import React from 'react'; import { createDevTools } from 'redux-devtools'; import DockMonitor from 'redux-devtools-dock-monitor'; import SliderMonitor from 'redux-slider-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q' defaultPosition='bottom' defaultSize={0.15} > <SliderMonitor keyboardEnabled /> </DockMonitor> );
// Derived and adapted from // https://github.com/rwldrn/duino/blob/development/lib/ping.js var Board = require("../lib/board.js"), events = require("events"), util = require("util"); function Sonar( opts ) { if ( !(this instanceof Sonar) ) { return new Sonar( opts ); } var last, samples, median; last = null; samples = []; opts = Board.options( opts ); // Hardware instance properties this.board = Board.mount( opts ); this.firmata = this.board.firmata; this.mode = this.firmata.MODES.ANALOG; this.pin = opts.pin || 0; // Sonar instance properties this.freq = opts.freq || 100; this.voltage = null; // Set the pin to ANALOG mode this.firmata.pinMode( this.pin, this.mode ); this.firmata.analogRead( this.pin, function( data ) { this.voltage = data; samples.push( data ); }.bind(this)); // Throttle setInterval(function() { var err; err = null; median = samples.sort()[ Math.floor( samples.length / 2 ) ]; // Emit throttled event this.emit( "read", err, median ); // If the median value for this interval is not the same as the // median value in the last interval, fire a "change" event. if ( median !== last ) { this.emit( "change", err, median ); } // Store this media value for comparison // in next interval last = median; // Reset samples; samples.length = 0; }.bind(this), this.freq ); Object.defineProperties( this, { // Based on the voltage, // Calculate the distance in inches and centimeters inches: { get: function() { return ( 254 / 1024 ) * 2 * median; } }, cm: { get: function() { return ( median / 2 ) * 2.54; } } }); } util.inherits( Sonar, events.EventEmitter ); module.exports = Sonar; // Reference // // http://www.maxbotix.com/tutorials.htm#Code_example_for_the_BasicX_BX24p // http://www.electrojoystick.com/tutorial/?page_id=285 // Tutorials // // http://www.sensorpedia.com/blog/how-to-interface-an-ultrasonic-rangefinder-with-sensorpedia-via-twitter-guide-2/
define([ "dojo/_base/array", // array.indexOf, array.map "dojo/_base/declare", // declare "dojo/dom-geometry", // domGeometry.setMarginBox "dojo/has", "dojo/query", // query "./_FormValueWidget", "dojo/touch" // not used directly, but allows me to set dojoClick flag on node and get responsive click handling ], function(array, declare, domGeometry, has, query, _FormValueWidget){ // module: // dijit/form/MultiSelect var MultiSelect = declare("dijit.form.MultiSelect" + (has("dojo-bidi") ? "_NoBidi" : ""), _FormValueWidget, { // summary: // Widget version of a `<select multiple=true>` element, // for selecting multiple options. // size: Number // Number of elements to display on a page // NOTE: may be removed in version 2.0, since elements may have variable height; // set the size via style="..." or CSS class names instead. size: 7, baseClass: "dijitMultiSelect", templateString: "<select multiple='true' ${!nameAttrSetting} data-dojo-attach-point='containerNode,focusNode' data-dojo-attach-event='onchange: _onChange'></select>", buildRendering: function(){ this.inherited(arguments); // get responsive click handling, see dojo/touch this.domNode.dojoClick = true; }, addSelected: function(/*dijit/form/MultiSelect*/ select){ // summary: // Move the selected nodes of a passed Select widget // instance to this Select widget. // // example: // | // move all the selected values from "bar" to "foo" // | dijit.byId("foo").addSelected(dijit.byId("bar")); select.getSelected().forEach(function(n){ this.containerNode.appendChild(n); // scroll to bottom to see item // cannot use scrollIntoView since <option> tags don't support all attributes // does not work on IE due to a bug where <select> always shows scrollTop = 0 this.domNode.scrollTop = this.domNode.offsetHeight; // overshoot will be ignored // scrolling the source select is trickier esp. on safari who forgets to change the scrollbar size var oldscroll = select.domNode.scrollTop; select.domNode.scrollTop = 0; select.domNode.scrollTop = oldscroll; }, this); this._set('value', this.get('value')); }, getSelected: function(){ // summary: // Access the NodeList of the selected options directly return query("option", this.containerNode).filter(function(n){ return n.selected; // Boolean }); // dojo/NodeList }, _getValueAttr: function(){ // summary: // Hook so get('value') works. // description: // Returns an array of the selected options' values. // Don't call getSelect.map() because it doesn't return a real array, // and that messes up dojo.toJson() calls like in the Form.html test return array.map(this.getSelected(), function(n){ return n.value; }); }, multiple: true, // for Form _setValueAttr: function(/*Array*/ values, /*Boolean?*/ priorityChange){ // summary: // Hook so set('value', values) works. // description: // Set the value(s) of this Select based on passed values query("option", this.containerNode).forEach(function(n){ n.selected = (array.indexOf(values, n.value) != -1); }); this.inherited(arguments); }, invertSelection: function(/*Boolean?*/ onChange){ // summary: // Invert the selection // onChange: Boolean // If false, onChange is not fired. var val = []; query("option", this.containerNode).forEach(function(n){ if(!n.selected){ val.push(n.value); } }); this._setValueAttr(val, !(onChange === false || onChange == null)); }, _onChange: function(/*Event*/){ this._handleOnChange(this.get('value'), true); }, // for layout widgets: resize: function(/*Object*/ size){ if(size){ domGeometry.setMarginBox(this.domNode, size); } }, postCreate: function(){ this._set('value', this.get('value')); this.inherited(arguments); } }); if(has("dojo-bidi")){ MultiSelect = declare("dijit.form.MultiSelect", MultiSelect, { addSelected: function(/*dijit/form/MultiSelect*/ select){ select.getSelected().forEach(function(n){ n.text = this.enforceTextDirWithUcc(this.restoreOriginalText(n), n.text); }, this); this.inherited(arguments); }, _setTextDirAttr: function(textDir){ // to insure the code executed only when _BidiSupport loaded, and only // when there was a change in textDir if((this.textDir != textDir || !this._created) && this.enforceTextDirWithUcc){ this._set("textDir", textDir); query("option", this.containerNode).forEach(function(option){ // If the value wasn't defined explicitly, it the same object as // option.text. Since the option.text will be modified (by wrapping of UCC) // we want to save the original option.value for form submission. if(!this._created && option.value === option.text){ option.value = option.text; } // apply the bidi support option.text = this.enforceTextDirWithUcc(option, option.originalText || option.text); }, this); } } }); } return MultiSelect; });
import { put, takeLatest, call, select } from 'redux-saga/effects'; import { push } from 'react-router-redux'; import { LOGIN, RESOLVE_APP_STAGE, GET_PROFILE, SIGN_OUT } from '../../constants/user'; import { ROUTES } from '../../constants/routes'; import { setUser, destroyUser, setProfile } from '../../actions/user'; import { setAuthToken, removeAuthToken } from '../../utils/auth'; import { convertProfileResponse } from '../../utils/converters/api/response'; import routes from '../../utils/network/api'; export function* resolveAppStageSaga({ payload: { user } }) { if (user.token && user.profile) { if (!user.profile.registered) { yield put(push(ROUTES.USER.REGISTRATION)); } else { yield put(push(ROUTES.APP.HOME)); } } } export function* loginUserSaga({ payload: { user } }) { const { token } = user; setAuthToken(token); yield put(setUser(user)); } export function* signOutSaga() { removeAuthToken(); yield put(destroyUser()); yield put(push(ROUTES.USER.LOGIN)); } export function* getUserProfile() { const response = yield call(routes.user.profile); let profile = null; if (!response.err) { profile = response.data; } return profile; } export function* updateUserProfile() { const profile = yield getUserProfile(); if (profile) { yield put(setProfile(convertProfileResponse(profile))); } } export function* getUser() { let user = yield select((state) => state.get('user')); if (!user.toJS().profile) { const profile = yield getUserProfile(); if (profile) { yield put(setProfile(convertProfileResponse(profile))); const stateUser = yield select((state) => state.get('user')); user = stateUser.toJS(); } else { user = null; } } else { user = user.toJS(); } return user; } function* userFlow() { yield takeLatest(LOGIN, loginUserSaga); yield takeLatest(RESOLVE_APP_STAGE, resolveAppStageSaga); yield takeLatest(GET_PROFILE, getUserProfile); yield takeLatest(SIGN_OUT, signOutSaga); } export default [ userFlow, ];
var express = require('express'); var glob = require('glob'); var config = require('./config'); var dir = config.MEDIA_DIRECTORY + '/**/*.+(' + config.MEDIA_FILE_TYPES.join('|') + ')'; var data = []; var hashData = {}; glob(dir, {}, function(err,files) { for(var i = 0; i < files.length; i++) { var video = {name:files[i], id:i}; data.push(video); hashData[i] = video; } }); exports.getFromDirectory = function() { return data; } exports.getHashedVideos = function() { return hashData; }
var config = require('../dist/config/config'); var DynamoDb = require('./DynamoDb'); var fs = require('fs'); var data = JSON.parse(fs.readFileSync(__dirname + '/data.json', 'utf8')); var type = "init"; // create, delete, sample, reset, init var table = "all"; // all, Message, User if(typeof process.argv[4] !== "undefined") { type = process.argv[4]; } if(typeof process.argv[3] !== "undefined") { table = process.argv[3]; } if(table !== "all") { data.forEach((t,i) => { if(t.name !== table) { delete data[i]; } }); } var db = new DynamoDb(); data.forEach((t) => { if(type == "init") { // create table db.create(t, function (err, data) { if(err == null) { // db.addItems(t, function (err, data) { // }); } }); } else if(type == "reset") { // create table db.delete(t.name, function (err, data) { // create table db.create(t, function (err, data) { db.addItems(t, function (err, data) { }); }); }); } else if(type == "create") { db.create(t, function (err, data) { }); } else if(type == "delete") { db.delete(t.name, function (err, data) { }); } else if(type == "sample") { db.addItems(t, function (err, data) { }); } });
'use strict'; const passport = require('passport'); //capitalize constructors as convention const LocalStrategy = require('passport-local').Strategy; const User = require('./user.model'); const SUCCESSFUL_LOGIN_MSG = 'Success!'; const INCORRECT_USERNAME_MSG = 'Incorrect Username or password'; const INCORRECT_PASSWORD_MSG = 'Incorrect Username or password'; passport.serializeUser((user, done) => { done(null, user._id); }); passport.deserializeUser(function(id, done) { User.findById(id, done); }); passport.use(new LocalStrategy ({ usernameField: 'email' }, (email, password, done) => { User.findOne({ email: email }, (err, user) => { if (err) throw err; if (user) { user.authenticate(password, (err, valid) => { if (err) throw err; if (valid) { done(null, user); } else { done(); } }); } else { done(); } }); }) );
/** * @author v.lugovksy * created on 16.12.2015 */ (function () { 'use strict'; angular.module('GasNinjasAdmin.pages.dashboard') .directive('trafficChart', trafficChart); /** @ngInject */ function trafficChart() { return { restrict: 'E', controller: 'TrafficChartCtrl', templateUrl: 'app/pages/dashboard/trafficChart/trafficChart.html' }; } })();
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], "MONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "SHORTDAY": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "SHORTMONTH": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], "fullDate": "EEEE dd MMMM y", "longDate": "dd MMMM y", "medium": "dd MMM,y h:mm:ss a", "mediumDate": "dd MMM,y", "mediumTime": "h:mm:ss a", "short": "d/M/yyyy h:mm a", "shortDate": "d/M/yyyy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "$", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "(\u00a4", "negSuf": ")", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "en-zw", "pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
$(document).ready(function(){ Mobify.Capture.init(function(capture){ var capturedDoc = capture.capturedDoc; var images = capturedDoc.querySelectorAll('img, picture'); Mobify.ResizeImages.resize(images, capturedDoc) capture.renderCapturedDoc(); }); });
'use strict' var auth = require('./lib/authenticate') var repos = require('./lib/repos') var events = require('./lib/events') var eventsReport = require('./lib/events-report') var pullRequests = require('./lib/pull-requests') module.exports = function githubStatusReport(user, callback) { var options = { github: auth(), user: user, per_page: 100 } var data = {} repos(options, function(err, repos) { data.repos = repos pullRequests(repos, options, function(err, pullRequests) { data.pullRequests = pullRequests events(options, function(err, events) { data.events = events.all data.eventsReport = eventsReport(events.all) callback(err, data) }) }) }) }
var rework = require('rework'), path = require('path'), validator = require('validator'); module.exports = function rebaseUrls(args) { args = args || {}; args.contentsBuffer; args.filepath; args.destpath; var css = args.contentsBuffer.toString(); var foldersToGoUp = args.destpath.split(path.sep).length - 1; var myArray = []; for (var i = 0; i < foldersToGoUp; i++) { myArray.push('..'); } var prefix = myArray.join(path.sep); return rework(css) .use(rework.url(function (url) { if (validator.isURL(url)) { return url; } if (/^(data:.*;.*,)/.test(url)) { return url; } if (/^(\/)/.test(url)) { //url is absolute return url; } var p = path.join(prefix, path.dirname(args.filepath), url); // console.log('before:', url); // console.log('after:', p); if (process.platform === 'win32') { p = p.replace(/\\/g, '/'); } return p; })) .toString(); };
version https://git-lfs.github.com/spec/v1 oid sha256:4a7ac474b309c38ff06bfda7c928b8b864f6f8da9b489ab5eb9f5fb44edcb2e7 size 28041
//Author: Sam var parkIds = []; $(document).ready(function() { $('#toMap').on('click', function() { if (typeof map == 'undefined') { initialize(); } }); $('.park').on('click', '.select', function(e) { e.preventDefault(); var parkId = $(this).attr('data-id'); if ($(this).hasClass('btn-success')) { unselectPark(parkId); } else { if (parkIds.length != 2) { $(this).addClass('btn-success'); $(this).text('Selected'); $('#compare-parks-body').append('<button data-park="' + parkId + '" id="compare-park-' + parkId +'" class="btn btn-warning selected-park" aria-label="Right Align">' + $(this).data('name') + '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>' + '</button>') parkIds.push(parkId); } } handleCompareButton(); }); $('#compare-parks-body').on('click', '.selected-park', function() { var parkId = $(this).data('park'); unselectPark(parkId, this); handleCompareButton(); }); }); function handleCompareButton() { if (parkIds.length == 2) { $('#compare').attr('disabled', false); var url = '../compare?park1=' + parkIds[0] + '&park2=' + parkIds[1]; $('#compare').attr('href', url); } else { $('#compare').attr('disabled', true); } } function unselectPark(parkId) { $('#park-' + parkId).find('.select').removeClass('btn-success').text('compare'); parkIds.splice(parkIds.indexOf(parkId), 1); $('#compare-park-' + parkId).remove(); }
({ ["__proto__"]: 0, ["__proto__"]: 0 });
'use strict'; module.exports = function htmlescape(html) { if (!html) { return ''; } return html.replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/'/g, '&#039;') .replace(/>/g, '&gt;') .replace(/</g, '&lt;'); };
function Enemy() {} Enemy.prototype = new Actor(); // tick method Enemy.prototype.onTick = function() { if (this.dead) { if (this.currentFrame == this.deadFrame) game.enemies.removeChild(this); return; } if (this.top() > game.canvas.height) this.die(); this.move(); return this; }; // take damage when hit Enemy.prototype.takeDamage = function() { this.health--; game.playSound('hit'); if(this.health < 1) { this.die(); game.score += this.points.kill; } else { this.gotoAndPlay(this.health_animations[this.health]); game.score += this.points.hit; } }; // die method Enemy.prototype.die = function() { game.playSound('explosion'); this.gotoAndPlay('dead'); this.dead = true; };
module.exports = function (NodeTeaparty) { NodeTeaparty.Status = function(widgetKey) { var UP = 'up', DOWN = 'down'; this.send = function(status, callback) { if (typeof status === 'undefined') status = DOWN; else if (typeof status !== 'string') status = !!status ? UP : DOWN; else status = status.toLowerCase() === UP ? UP : DOWN; NodeTeaparty.send(widgetKey, {status: status}, callback); } }; };
/** * @private * @param {Node} node Node. * @param {Array.<*>} objectStack Object stack. * @return {ol.Extent|undefined} Bounding box object. */ ol.format.WMSCapabilities.readLatLonBoundingBox_ = function (node, objectStack) { goog.asserts.assert(node.nodeType == Node.ELEMENT_NODE, 'node.nodeType should be ELEMENT'); goog.asserts.assert(node.localName == 'LatLonBoundingBox', 'localName should be LatLonBoundingBox'); return [ ol.format.XSD.readDecimalString(node.getAttribute('minx')), ol.format.XSD.readDecimalString(node.getAttribute('miny')), ol.format.XSD.readDecimalString(node.getAttribute('maxx')), ol.format.XSD.readDecimalString(node.getAttribute('maxy')) ]; }; for(var a in ol.xml.makeStructureNS( ol.format.WMSCapabilities.NAMESPACE_URIS_, { 'SRS': ol.xml.makeObjectPropertyPusher(ol.format.XSD.readString), 'LatLonBoundingBox': ol.xml.makeObjectPropertySetter( ol.format.WMSCapabilities.readLatLonBoundingBox_), })){ goog.object.extend(ol.format.WMSCapabilities.LAYER_PARSERS_[a],{ 'SRS': ol.xml.makeObjectPropertyPusher(ol.format.XSD.readString), 'LatLonBoundingBox': ol.xml.makeObjectPropertySetter( ol.format.WMSCapabilities.readLatLonBoundingBox_), }) }
import FizzBuzzPopCalculator from '../src/index.js'; import { expect } from 'chai'; describe('fizz-buzz-pop-js tests', () => { let results = []; beforeEach(() => { let calculator = new FizzBuzzPopCalculator(); results = calculator.generateValues(); }); describe('When is not multiple 1 and 7', () => it('should be 1 and 7', () => { expect(results[0]).to.equal("1"); expect(results[6]).to.equal("7"); }) ); describe('When multiple of 3 and 5', () => it('should be FizzBuzz', () => expect(results[14]).to.equal("FizzBuzz")) ); describe('When multiple of 3', () => it('should be Fizz', function () { expect(results[2]).to.equal("Fizz"); expect(results[8]).to.equal("Fizz"); }) ); describe('When multiple of 5', () => it('should be Buzz', () => expect(results[4]).to.equal("Buzz")) ); describe('When multiple of 2 and 3', () => it('should be Pop', function () { expect(results[1]).to.equal("Pop"); expect(results[3]).to.equal("Pop"); }) ); describe('When multiple of 9', () => it('should be BuzzPop', () => expect(results[9]).to.equal("BuzzPop")) ); describe('When multiple of 2, 3 and 5', () => it('should be FizzBuzzPop', () => expect(results[29]).to.equal("FizzBuzzPop")) ); describe('When multiple of 2 and 3', () => it('should be FizzPop', () => expect(results[5]).to.equal("FizzPop")) ); });
module.exports = function(grunt) { grunt.initConfig({ elm: { compile: { files: { "bingo.js": ["Bingo.elm"] } } }, watch: { elm: { files: ["Bingo.elm", "BingoUtils.elm"], tasks: ["elm"] } }, clean: ["elm-stuff/build-artifacts"] }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-elm'); grunt.registerTask('default', ['elm']); };
import Vue from 'vue' import Vuelidate from 'vuelidate' import { shallowMount } from '@vue/test-utils' import useI18nGlobally from '../../__utils__/i18n' import ModalExportWallets from '@/components/Modal/ModalExportWallets' import StringMixin from '@/mixins/strings' import WalletMixin from '@/mixins/wallet' Vue.use(Vuelidate) const i18n = useI18nGlobally() describe('ModalExportWallets', () => { const mountComponent = () => { const wallets = [ { address: 'A1', name: null, balance: 0 }, { address: 'A2', name: '', balance: 1 }, { address: 'A3', name: 'wallet_a3', balance: 0 }, { address: 'A4', name: 'wallet_a4', balance: 1 } ] const ledgerWallets = [ { address: 'A5', name: null, balance: 0 }, { address: 'A6', name: 'ledger_a6', balance: 1 } ] return shallowMount(ModalExportWallets, { i18n, mixins: [StringMixin, WalletMixin], mocks: { session_network: { knownWallets: {} }, $store: { getters: { 'delegate/byAddress': jest.fn(), 'wallet/contactsByProfileId': () => [], 'wallet/byProfileId': () => wallets, 'ledger/wallets': () => ledgerWallets } } } }) } it('should render modal', () => { const wrapper = mountComponent() expect(wrapper.isVueInstance()).toBeTrue() }) describe('toggleOption', () => { it('should exclude empty wallets', () => { const wrapper = mountComponent() wrapper.vm.toggleOption('excludeEmpty') const walletsWithBalance = [ { address: 'A2', name: '', balance: 1 }, { address: 'A4', name: 'wallet_a4', balance: 1 } ] expect(wrapper.vm.wallets).toEqual(walletsWithBalance) }) it('should exclude wallets with no name', () => { const wrapper = mountComponent() wrapper.vm.toggleOption('excludeUnnamed') const walletsWithName = [ { address: 'A3', name: 'wallet_a3', balance: 0 }, { address: 'A4', name: 'wallet_a4', balance: 1 } ] expect(wrapper.vm.wallets).toEqual(walletsWithName) }) }) })
let result = (() => { let Suits = { CLUBS: "\u2663", // ♣ DIAMONDS: "\u2666", // ♦ HEARTS: "\u2665", // ♥ SPADES: "\u2660" // ♠ }; let Faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']; class Card { constructor(face, suit) { this.face = face; this.suit = suit; } get face() { return this._face; } set face(face) { if (!Faces.includes(face)) { throw new Error('Invalid card face: ' + face); } this._face = face; } get suit() { return this._suit; } set suit(suit) { if (!Object.keys(Suits).map(k => Suits[k]).includes(suit)) { throw new Error('Invalid suit'); } this._suit = suit; } toString() { return `${this.face}${this.suit}`; } } return {Suits, Card } })(); let Suits = result.Suits; let Card = result.Card; let card = new Card("2",Suits.SPADES); console.log(card); card = new Card("2",Suits.CLUBS); console.log(card); card = new Card("2",Suits.DIAMONDS); console.log(card); card = new Card("2",Suits.HEARTS); console.log(card);
var led_8h = [ [ "Led_Init", "led_8h.html#af1aee968a5ceeb7915921aa6d78aca23", null ], [ "Led_Off", "led_8h.html#a274dbef77287444be852fe96969b3c55", null ], [ "Led_On", "led_8h.html#a39675df62ae72fa5af35fc7ec2e8c950", null ], [ "Led_Toggle", "led_8h.html#a5ebbd778fb3444fbfbded2130e08b33d", null ] ];
import {sleepUntilReactAvailable} from "test/e2e/utils/index.js"; const {maxTimeout, originUrl} = browser.params; // Private variables const dom = Symbol("dom"); class HelmetPageObject { static location = `${originUrl}/helmet-example`; _dom = { container: $("#helmet"), link: $("#helmet-link") }; get [dom]() { return this._dom; } getLocation() { return browser.get(HelmetPageObject.location); } getNavigationLink() { return this[dom].link; } sleepUntilPageAvailable() { return Promise.all([ sleepUntilReactAvailable(), browser.wait( protractor.ExpectedConditions.visibilityOf(this[dom].container), maxTimeout ) ]); } } export default HelmetPageObject;
function login(e) { e.preventDefault(); var email = document.getElementById("email").value; var password = document.getElementById("password").value; var data = {}; data.email = email; data.password = password; var xhttp = new XMLHttpRequest(); xhttp.open("POST", "/skinstore/loginuser", true); xhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { // console.log(xhttp.responseText); // alert(xhttp.responseText); var textnode = document.createTextNode(xhttp.responseText); // var node = document.getElementById("loginform"); // node.appendChild(textnode); document.getElementById("loginform").appendChild(textnode); alert(textnode); } }; //JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string. //JSON.parse turns a string of JSON text into a Javascript object. xhttp.send(JSON.stringify(data)); }