text
stringlengths
2
6.14k
version https://git-lfs.github.com/spec/v1 oid sha256:5a4f668a21f7ea9a0b8ab69c0e5fec6461ab0f73f7836acd640fe43ea9919fcf size 89408
import * as types from '@/store/mutation-types'; export default { namespaced: true, state: { type: 0, catId: 0 }, getters: { [types.STATE_INFO]: state => { return state.type + 3; } } }
document.observe('click', function(e, el) { if (el = e.findElement('form a.add_nested_fields')) { // Setup var assoc = el.readAttribute('data-association'); // Name of child var target = el.readAttribute('data-target'); var blueprint = $(el.readAttribute('data-blueprint-id')); var content = blueprint.readAttribute('data-blueprint'); // Fields template // Make the context correct by replacing <parents> with the generated ID // of each of the parent objects var context = (el.getOffsetParent('.fields').firstDescendant().readAttribute('name') || '').replace(/\[[a-z_]+\]$/, ''); // If the parent has no inputs we need to strip off the last pair var current = content.match(new RegExp('\\[([a-z_]+)\\]\\[new_' + assoc + '\\]')); if (current) { context = context.replace(new RegExp('\\[' + current[1] + '\\]\\[(new_)?\\d+\\]$'), ''); } // context will be something like this for a brand new form: // project[tasks_attributes][1255929127459][assignments_attributes][1255929128105] // or for an edit form: // project[tasks_attributes][0][assignments_attributes][1] if(context) { var parent_names = context.match(/[a-z_]+_attributes(?=\]\[(new_)?\d+\])/g) || []; var parent_ids = context.match(/[0-9]+/g) || []; for(i = 0; i < parent_names.length; i++) { if(parent_ids[i]) { content = content.replace( new RegExp('(_' + parent_names[i] + ')_.+?_', 'g'), '$1_' + parent_ids[i] + '_'); content = content.replace( new RegExp('(\\[' + parent_names[i] + '\\])\\[.+?\\]', 'g'), '$1[' + parent_ids[i] + ']'); } } } // Make a unique ID for the new child var regexp = new RegExp('new_' + assoc, 'g'); var new_id = new Date().getTime(); content = content.replace(regexp, new_id); var field; if (target) { field = $$(target)[0].insert(content); } else { field = el.insert({ before: content }); } field.fire('nested:fieldAdded', {field: field, association: assoc}); field.fire('nested:fieldAdded:' + assoc, {field: field, association: assoc}); return false; } }); document.observe('click', function(e, el) { if (el = e.findElement('form a.remove_nested_fields')) { var hidden_field = el.previous(0), assoc = el.readAttribute('data-association'); // Name of child to be removed if(hidden_field) { hidden_field.value = '1'; } var field = el.up('.fields').hide(); field.fire('nested:fieldRemoved', {field: field, association: assoc}); field.fire('nested:fieldRemoved:' + assoc, {field: field, association: assoc}); return false; } });
import { Component } from 'vidom'; import { DocComponent, DocTabs, DocTab, DocAttrs, DocAttr, DocExample, DocChildren, DocText, DocInlineCode } from '../../Doc'; import SimpleExample from './examples/SimpleExample'; import simpleExampleCode from '!raw!./examples/SimpleExample.js'; export default function ModalDoc({ tab, onTabChange }) { return ( <DocComponent title="Modal"> <DocTabs value={ tab } onTabChange={ onTabChange }> <DocTab title="Examples" value="Examples"> <DocExample title="Simple" code={ simpleExampleCode }> <SimpleExample/> </DocExample> </DocTab> <DocTab title="API" value="api"> <DocAttrs> <DocAttr name="autoclosable" type="Boolean" def="false"> Enables the modal to be hidden on pressing "Esc" or clicking somewhere outside its content. </DocAttr> <DocAttr name="onHide" type="Function"> The callback to handle hide event. </DocAttr> <DocAttr name="theme" type="String" required> Sets the modal theme. </DocAttr> <DocAttr name="visible" type="Boolean" def="false"> Sets the visibility of the modal. </DocAttr> </DocAttrs> <DocChildren> <DocText> Children with any valid type are allowed. </DocText> </DocChildren> </DocTab> </DocTabs> </DocComponent> ); }
"use strict"; /** * Broadcast updates to client when the model changes */ Object.defineProperty(exports, "__esModule", { value: true }); var product_events_1 = require("./product.events"); // Model events to emit var events = ['save', 'remove']; function register(socket) { // Bind model events to socket events for (var i = 0, eventsLength = events.length; i < eventsLength; i++) { var event = events[i]; var listener = createListener('product:' + event, socket); product_events_1.default.on(event, listener); socket.on('disconnect', removeListener(event, listener)); } } exports.register = register; function createListener(event, socket) { return function (doc) { socket.emit(event, doc); }; } function removeListener(event, listener) { return function () { product_events_1.default.removeListener(event, listener); }; } //# sourceMappingURL=product.socket.js.map
/** * vuex-mapstate-modelvalue-instrict- v0.0.4 * (c) 2017 fsy0718 * @license MIT */ 'use strict'; var push = Array.prototype.push; var pop = Array.prototype.pop; var _mapStateModelValueInStrict = function (modelValue, stateName, type, opts, setWithPayload, copts) { if ( opts === void 0 ) opts = {}; if ( copts === void 0 ) copts = {}; if (process.env.NODE_ENV === 'development' && (!modelValue || !stateName || !type)) { throw new Error(("vuex-mapstate-modelvalue-instrict: the " + modelValue + " at least 3 parameters are required")) } var getFn = opts.getFn || copts.getFn; var modulePath = opts.modulePath || copts.modulePath; return { get: function get () { if (getFn) { return getFn(this.$store.state, modelValue, stateName, modulePath) } if (modulePath) { var paths = modulePath.split('/') || []; var result; try { result = paths.reduce(function (r, c) { return r[c] }, this.$store.state); result = result[stateName]; } catch (e) { if (process.env.NODE_ENV === 'development') { throw e } result = undefined; } return result } return this.$store.state[stateName] }, set: function set (value) { var mutation = setWithPayload ? ( obj = {}, obj[stateName] = value, obj ) : value; var obj; var _type = modulePath ? (modulePath + "/" + type) : type; this.$store.commit(_type, mutation, modulePath ? opts.param || copts.param : undefined); } } }; var _mapStateModelValuesInStrict = function () { var args = arguments; var setWithPayload = pop.call(args); var result = {}; if (Array.isArray(args[0])) { var opts = args[1]; args[0].forEach(function (item) { result[item[0]] = _mapStateModelValueInStrict(item[0], item[1], item[2], item[3], setWithPayload, opts); }); } else { result[args[0]] = _mapStateModelValueInStrict(args[0], args[1], args[2], args[3], setWithPayload); } return result }; // mapStateModelValuesInStrict(modelValue, stateName, type, {getFn, setWithPayload, modulePath}}) // mapStateModelValuesInStrict([[modelValue, stateName, type, {getFn1}], [modelValue, stateName, type]], {getFn, setWithPayload}) var mapStateModelValuesInStrictWithPayload = function () { var args = arguments; push.call(arguments, true); return _mapStateModelValuesInStrict.apply(null, args) }; var mapStateModelValuesInStrict = function () { var args = arguments; push.call(arguments, false); return _mapStateModelValuesInStrict.apply(null, args) }; var index = { mapStateModelValuesInStrict: mapStateModelValuesInStrict, mapStateModelValuesInStrictWithPayload: mapStateModelValuesInStrictWithPayload, version: '0.0.4' }; module.exports = index;
// The file contents for the current environment will overwrite these during build. // The build system defaults to the dev environment which uses `environment.ts`, but if you do // `ng build --env=prod` then `environment.prod.ts` will be used instead. // The list of which env maps to which file can be found in `angular-cli.json`. // The file contents for the current environment will overwrite these during build. export var environment = { production: false }; //# sourceMappingURL=C:/Old/Hadron/HadronClient/src/environments/environment.js.map
var namespace_pathfinder_1_1_internal_1_1_g_u_i = [ [ "ModExtensionsUI", "class_pathfinder_1_1_internal_1_1_g_u_i_1_1_mod_extensions_u_i.html", "class_pathfinder_1_1_internal_1_1_g_u_i_1_1_mod_extensions_u_i" ], [ "ModList", "class_pathfinder_1_1_internal_1_1_g_u_i_1_1_mod_list.html", "class_pathfinder_1_1_internal_1_1_g_u_i_1_1_mod_list" ] ];
// Karma configuration // Generated on Wed Jun 01 2016 16:04:37 GMT-0400 (EDT) module.exports = function (config) { config.set({ basePath: '', // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'browserify'], // include only tests here; browserify will find the rest files: [ 'test/**/*-spec.+(js|jsx)' ], exclude: [], // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'test/**/*-spec.+(js|jsx)': ['browserify'] }, browserify: { debug: true, transform: ['babelify'], extensions: ['.js', '.jsx'], // needed for enzyme configure: function (bundle) { bundle.on('prebundle', function () { bundle.external('react/addons'); bundle.external('react/lib/ReactContext'); bundle.external('react/lib/ExecutionEnvironment'); }); } }, // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['mocha'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: false, // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // if true, Karma captures browsers, runs the tests and exits singleRun: true, // how many browser should be started simultaneous concurrency: Infinity }) };
import 'babel-polyfill'; import EdgeGrid from 'edgegrid'; import dotenv from 'dotenv'; import inquirer from 'inquirer'; import formatJson from 'format-json'; import fs from 'fs'; (async function() { // load .env vars dotenv.config(); let papiResponses = new Map(); const edgegrid = new EdgeGrid({ path: process.env.AKA_EDGERC, section: 'default' }); let contractId = await papiChoice( 'Select Akamai contract:', '/papi/v1/contracts', 'contracts', 'contractId', 'contractTypeName' ); let groupId = await papiChoice( 'Select Akamai property group:', '/papi/v1/groups/?contractId=' + contractId, 'groups', 'groupId', 'groupName' ); let propertyId = await papiChoice( 'Select Akamai property:', '/papi/v1/properties/?contractId=' + contractId + '&groupId=' + groupId, 'properties', 'propertyId', 'propertyName' ); let latestVersion = papiResponses.get('properties').properties.items.filter((property) => { return property.propertyId === propertyId; })[0].latestVersion; // request property version let version = await inquirer.prompt([ { type: 'input', name: 'version', message: 'The latest property verions is ' + latestVersion + ', which would you like?', default: latestVersion, validate: (version) => { if (parseInt(version) > 0 && parseInt(version) <= latestVersion) { return true; } else { return 'Please enter a valid version number.'; } } } ]).then(function (answers) { console.log('selected version = ' + answers.version); return answers.version; }); let propertyJson = await callPapi('property', '/papi/v1/properties/' + propertyId + '/versions/' + version + '/rules?contractId=' + contractId + '&groupId=' + groupId).then((data) => { return data; }); let propertyName = papiResponses.get('properties').properties.items.filter((property) => { return property.propertyId === propertyId; })[0].propertyName; await inquirer.prompt([ { type: 'confirm', name: 'outputToFile', message: 'Output property ' + propertyName + ' v' + version + ' json to file now?', default: true, } ]).then(function (answers) { console.log('selected outputToFile = ' + answers.outputToFile); if (answers.outputToFile) { let outputDir = __dirname + '/../papiJson'; if (!fs.existsSync(outputDir)) { fs.mkdirSync(outputDir); } fs.writeFileSync( outputDir + '/' + propertyName + '-v' + version + '.papi.json', formatJson.plain(propertyJson), 'utf8' ); console.log('\npapi json written to: ./papiJson/' + propertyName + '-v' + version + '.papi.json'); } }); console.log( '\n# ---------------------------------------------------------\n' + '# place the following in .env or set as shell/node env vars\n' + '# if you would like to use these parameters to configure nginx directly\n' + '# from api calls - otherwise point at the generated papi json.\n' + '# refer to start.js and start-local.js\n' + 'AKA_CONTRACT_ID=' + contractId + '\n' + 'AKA_GROUP_ID=' + groupId + '\n' + 'AKA_PROPERTY_ID=' + propertyId + '\n' + 'AKA_PROPERTY_VERSION=' + version + '\n' ); async function papiChoice(message, papiUrl, containerField, valueField, nameField) { let choices = await callPapi(containerField, papiUrl).then((data) => { return data[containerField].items.map((item) => { let choice = {}; choice.name = item[valueField] + ' ' + item[nameField]; choice.value = item[valueField]; return choice; }); }); return await inquirer.prompt([ { type: 'list', name: valueField, message: message, paginated: true, choices: choices } ]).then(function (answers) { console.log('selected ' + valueField + ' = ' + answers[valueField]); return answers[valueField]; }); } async function callPapi(type, papiUrl) { return new Promise( (resolve, reject) => { console.log('calling papi url: ' + papiUrl + '\n'); edgegrid.auth({ path: papiUrl, method: 'GET' }).send((error, response, body) => { if (error) { return reject(error); } let jsonResult = JSON.parse(body); papiResponses.set(type, jsonResult); return resolve(jsonResult); }); }); } })();
export default { Control : require('./Control'), Delete : require('./Delete'), Detail : require('./Detail'), Head : require('./Head'), Quit : require('./Quit'), };
import Game from '../models/game' class Store { constructor() { const game = new Game({ onTick: () => { this.ui.game.update() } }) const { snake, map } = game this.snake = snake this.map = map this.game = game game.start() this.ui = {} this.data = { map, paused: false } } turnUp = () => { this.snake.turnUp() } turnRight = () => { this.snake.turnRight() } turnDown = () => { this.snake.turnDown() } turnLeft = () => { this.snake.turnLeft() } pauseOrPlay = () => { if (this.game.paused) { this.game.play() this.data.paused = false } else { this.game.pause() this.data.paused = true } this.ui.index.updateSelf() } reset = () => { this.game.reset() } toggleSpeed = () => { this.game.toggleSpeed() } } export default new Store
(function () { 'use strict'; angular.module('app.layout', ['app.core', 'ui.bootstrap.collapse']); })();
'use strict'; // eslint-disable-line const { default: ImageminPlugin } = require('imagemin-webpack-plugin'); const imageminMozjpeg = require('imagemin-mozjpeg'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin') const config = require('./config'); module.exports = { plugins: [ new ImageminPlugin({ optipng: { optimizationLevel: 7 }, gifsicle: { optimizationLevel: 3 }, pngquant: { quality: '65-90', speed: 4 }, svgo: { plugins: [ { removeUnknownsAndDefaults: false }, { cleanupIDs: false }, { removeViewBox: false }, ], }, plugins: [imageminMozjpeg({ quality: 75 })], disable: (config.enabled.watcher), }), new UglifyJsPlugin({ uglifyOptions: { ecma: 8, compress: { warnings: true, drop_console: true, }, }, }), ], };
var _ = require('lodash'), fs = require('fs'), path = require('path'), through = require('through'), filesize = require('file-size'); function browserify(file, options) { var source = []; function write(data) { source.push(data); }; function end(file, options) { var renderTemplate = function(options, stats) { var si = options.size.representation === 'si', computedSize = filesize(stats.size, { fixed: options.size.decimals, spacer: options.size.spacer }), jsonOptions = JSON.stringify(options), jsonStats = JSON.stringify(stats), prettySize = (options.size.unit === 'human') ? computedSize.human({ si: si }) : computedSize.to(options.size.unit, si), template = options.output.file.template; return template.replace('%file%', path.basename(file)) .replace('%fullname%', file) .replace('%size%', prettySize) .replace('%stats%', jsonStats) .replace('%atime%', stats.atime) .replace('%mtime%', stats.mtime) .replace('%unit%', options.size.unit) .replace('%decimals%', options.size.decimals) .replace('%options%', jsonOptions); }; var fileStat = function(err, stats) { if (err) { console.error('Failure to extract file stats', file, err); return; } if (options.output.file) { var result = '', prependHeader = renderTemplate(options, stats); try { result = [prependHeader, source.join('')].join(''); } catch (error) { error.message += ' in "' + file + '"'; this.emit('error', error); } this.queue(result); this.queue(null); } }.bind(this); fs.stat(file, fileStat); } return (function transform(file, options) { var options = _.extend({ size: { unit: 'human', decimals: '2', spacer: ' ', representation: 'si' }, output: { file: { template: [ '', '/* =========================== ', ' * > File: %file%', ' * > Size: %size%', ' * > Modified: %mtime%', ' * =========================== */', '' ].join('\n') } } }, options); return through(_.partial(write), _.partial(end, file, options)); })(file, options); }; module.exports = { browserify: browserify };
var Models = {}; module.exports = Models; /** * Creates a new instance of the Model class * @constructor */ Models.Model = function(id, name, status, type, normalValue, wierdValue) { /** @type {string} */ this._id = id || ''; /** @type {string} */ this.name = name || ''; /** @type {string} */ this.status = status || 'disable'; /** @type {string} */ this.type = type || 'normal'; /** @type {number} */ this.normalValue = normalValue || 0; /** @type {number} */ this.wierdValue = wierdValue || 0; }; /** * Creates a new instance of a PublicModel * @constructor */ Models.PublicModel = function(name, value) { /** @type {string} */ this.name = name || ''; /** @type {number} */ this.value = value || 0; };
/* ============================================================= * bootstrap-collapse.js v2.3.2 * http://getbootstrap.com/2.3.2/javascript.html#collapse * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* COLLAPSE PUBLIC CLASS DEFINITION * ================================ */ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.collapse.defaults, options) if (this.options.parent) { this.$parent = $(this.options.parent) } this.options.toggle && this.toggle() } Collapse.prototype = { constructor: Collapse , dimension: function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } , show: function () { var dimension , scroll , actives , hasData if (this.transitioning || this.$element.hasClass('in')) return dimension = this.dimension() scroll = $.camelCase(['scroll', dimension].join('-')) actives = this.$parent && this.$parent.find('> .accordion-group > .in') if (actives && actives.length) { hasData = actives.data('collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('collapse', null) } this.$element[dimension](0) this.transition('addClass', $.Event('show'), 'shown') $.support.transition && this.$element[dimension](this.$element[0][scroll]) } , hide: function () { var dimension if (this.transitioning || !this.$element.hasClass('in')) return dimension = this.dimension() this.reset(this.$element[dimension]()) this.transition('removeClass', $.Event('hide'), 'hidden') this.$element[dimension](0) } , reset: function (size) { var dimension = this.dimension() this.$element .removeClass('collapse') [dimension](size || 'auto') [0].offsetWidth this.$element[size !== null ? 'addClass' : 'removeClass']('collapse') return this } , transition: function (method, startEvent, completeEvent) { var that = this , complete = function () { if (startEvent.type == 'show') that.reset() that.transitioning = 0 that.$element.trigger(completeEvent) } this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return this.transitioning = 1 this.$element[method]('in') $.support.transition && this.$element.hasClass('collapse') ? this.$element.one($.support.transition.end, complete) : complete() } , toggle: function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } } /* COLLAPSE PLUGIN DEFINITION * ========================== */ var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('collapse') , options = $.extend({}, $.fn.collapse.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.defaults = { toggle: true } $.fn.collapse.Constructor = Collapse /* COLLAPSE NO CONFLICT * ==================== */ $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } /* COLLAPSE DATA-API * ================= */ $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) { var $this = $(this), href , target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 , option = $(target).data('collapse') ? 'toggle' : $this.data() $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed') $(target).collapse(option) }) }(window.jQuery);
angular.module('Eintrag').service('editarService', ['$http', function ($http) { this.editarUsuario = function (data) { return $http.post('http://localhost/Eintrag/www/server.php/editarUsuario', $.param(data)); }; }]);
appService.factory('Chats', function() { // Might use a resource here that returns a JSON array // Some fake testing data var chats = [{ id: 0, name: 'Ben Sparrow', lastText: 'You on your way?', face: 'app/view/common/img/ben.png' }, { id: 1, name: 'Max Lynx', lastText: 'Hey, it\'s me', face: 'app/view/common/img/max.png' }, { id: 2, name: 'Adam Bradleyson', lastText: 'I should buy a boat', face: 'app/view/common/img/adam.jpg' }, { id: 3, name: 'Perry Governor', lastText: 'Look at my mukluks!', face: 'app/view/common/img/perry.png' }, { id: 4, name: 'Mike Harrington', lastText: 'This is wicked good ice cream.', face: 'app/view/common/img/mike.png' }]; return { all: function() { return chats; }, remove: function(chat) { chats.splice(chats.indexOf(chat), 1); }, get: function(chatId) { for (var i = 0; i < chats.length; i++) { if (chats[i].id === parseInt(chatId)) { return chats[i]; } } return null; } }; });
import { AppRegistry } from "react-native"; import App from "./App"; AppRegistry.registerComponent("KeepTheBallGame", () => App);
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import AppBar from 'material-ui/AppBar'; import Tabs, { Tab } from 'material-ui/Tabs'; import PhoneIcon from '@material-ui/icons/Phone'; import FavoriteIcon from '@material-ui/icons/Favorite'; import PersonPinIcon from '@material-ui/icons/PersonPin'; import HelpIcon from '@material-ui/icons/Help'; import ShoppingBasket from '@material-ui/icons/ShoppingBasket'; import ThumbDown from '@material-ui/icons/ThumbDown'; import ThumbUp from '@material-ui/icons/ThumbUp'; import Typography from 'material-ui/Typography'; function TabContainer(props) { return ( <Typography component="div" style={{ padding: 8 * 3 }}> {props.children} </Typography> ); } TabContainer.propTypes = { children: PropTypes.node.isRequired, }; const styles = theme => ({ root: { flexGrow: 1, width: '100%', backgroundColor: theme.palette.background.paper, }, }); class ScrollableTabsButtonPrevent extends React.Component { state = { value: 0, }; handleChange = (event, value) => { this.setState({ value }); }; render() { const { classes } = this.props; const { value } = this.state; return ( <div className={classes.root}> <AppBar position="static"> <Tabs value={value} onChange={this.handleChange} scrollable scrollButtons="off"> <Tab icon={<PhoneIcon />} /> <Tab icon={<FavoriteIcon />} /> <Tab icon={<PersonPinIcon />} /> <Tab icon={<HelpIcon />} /> <Tab icon={<ShoppingBasket />} /> <Tab icon={<ThumbDown />} /> <Tab icon={<ThumbUp />} /> </Tabs> </AppBar> {value === 0 && <TabContainer>Item One</TabContainer>} {value === 1 && <TabContainer>Item Two</TabContainer>} {value === 2 && <TabContainer>Item Three</TabContainer>} {value === 3 && <TabContainer>Item Four</TabContainer>} {value === 4 && <TabContainer>Item Five</TabContainer>} {value === 5 && <TabContainer>Item Six</TabContainer>} {value === 6 && <TabContainer>Item Seven</TabContainer>} </div> ); } } ScrollableTabsButtonPrevent.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(ScrollableTabsButtonPrevent);
// Actions export const ADD_NOTIFICATION = 'notifications/ADD_NOTIFICATION' export const DISMISS_NOTIFICATION = 'notifications/DISMISS_NOTIFICATION' export const CLEAR_NOTIFICATIONS = 'notifications/CLEAR_NOTIFICATIONS' // Reducer export const initialState = [] export default function reducer(state = initialState, action) { const { payload, type } = action switch (type) { case ADD_NOTIFICATION: return [...state, payload] case DISMISS_NOTIFICATION: return state.filter(notification => notification.id !== payload) case CLEAR_NOTIFICATIONS: return [state] default: return state } } // Action Creators export function addNotification(notification) { const { id, dismissAfter } = notification if (!id) { notification.id = new Date().getTime() } return (dispatch, getState) => { dispatch({ type: ADD_NOTIFICATION, payload: notification }) if (dismissAfter) { setTimeout(() => { const { notifications } = getState() const found = notifications.find(lookup => { return lookup.id === notification.id }) if (found) { dispatch({ type: DISMISS_NOTIFICATION, payload: notification.id }) } }, dismissAfter) } } } export function dismissNotification(id) { return { type: DISMISS_NOTIFICATION, payload: id } } export function clearNotifications(id) { return { type: CLEAR_NOTIFICATIONS, payload: id } }
var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js'); var ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3'); let fs = require('fs'); let path = require('path'); const directoryName = path.dirname(__filename); const creds = { tone: { "username": "redacted", "password": "redacted" }, nlu: { "username": "redacted", "password": "redacted" } }; let toneAnalyzer = new ToneAnalyzerV3({ username: creds.tone.username, password: creds.tone.password, version: 'v3', version_date: '2017-03-15' }); var nlu = new NaturalLanguageUnderstandingV1({ username: creds.nlu.username, password: creds.nlu.password, version_date: NaturalLanguageUnderstandingV1.VERSION_DATE_2017_02_27 }); function generateToneAnalysis(title, poem) { let toneParams = { 'text': poem, 'isHTML': false, 'sentences': false }; let nluParams = { 'text': poem, 'features': { 'keywords': { 'emotion': true, 'sentiment': true, 'limit': 10 }, 'sentiment': {} } } toneAnalyzer.tone(toneParams, function(err, res1){ if (err) { console.log(err); } else { nlu.analyze(nluParams, function(err, res2){ if (err) { console.log(err); } else { var result = Object.assign({"title": title}, res1, res2); prettyJson = JSON.stringify(result, null, 2); fs.appendFileSync('./sentiments.json', prettyJson, {encoding: 'utf8'}); console.log(`Retrieved Watson Analysis for ${title}`); } }); } }); } function readFiles(dirname, onFileContent, onError) { fs.readdir(dirname, function(err, filenames) { if (err) { onError(err); return; } var index = filenames.indexOf(".DS_Store"); if (index >= 0) { filenames.splice(index, 1 ); } filenames.forEach(function(filename) { fs.readFile(path.join(dirname,filename), 'utf8', function(err, content) { if (err) { onError(err); return; } onFileContent(filename.substring(0, filename.length-4), content); }); }); }); } // fs.writeFileSync('./s.json', '', 'utf8'); // fs.readdir('./missing', function(err, files) { // var index = files.indexOf(".DS_Store"); // if (index >= 0) { // files.splice(index, 1 ); // } // for (var i = 0; i<files.length; i++) { // console.log(files[i]); // file = fs.readFileSync(path.join(directoryName+'/missing', files[i]), {encoding: 'utf8'}); // generateToneAnalysis(files[i], file); // } // }); fs.readdir('./poems', function(err, folders){ if (err) { console.log(err); return; } var index = folders.indexOf(".DS_Store"); if (index >= 0) { folders.splice(index, 1 ); } for (var i = 0; i < folders.length; i++) { let dirname = path.join('./poems', folders[i]); readFiles(dirname, generateToneAnalysis, function(err) { console.log(err); }); } });
var encodeDecode = function() { var randomNum = function (min, max) { // helper function for random numbers return Math.random() * (max - min) + min; }; var insertBreak = function (counter) { //helper function to break lines @ 100 char if (counter % 100 === 0) { $('body').append("<br>"); } }; var encode = function (s) { //encodes a string var spl = s.split(""); var lineCounter = 0; for (var i=0; i < spl.length; i++) { $('body').append("<span class='encoded' hidden>" + spl[i] + "</span>"); var r = randomNum(20,30); for (var j=0; j < r; j++) { insertBreak(lineCounter); lineCounter++; var q = randomNum(33,126); $('body').append("<span>" + String.fromCharCode(q) + "</span>"); } } }; var decode = function () { //decodes the page var decodeString = ""; $('[hidden]').each(function() { decodeString += $(this).text(); $(this).remove(); }); $('span, br').remove(); $('body').append("<span class='decoded'>" + decodeString + "</span>"); }; if ($('body').children('span.encoded').length > 0) { decode(); } else if ($('body').children('span.decoded').length > 0) { var s = $('span.decoded').text(); $('span.decoded').remove(); encode(s); } else { encode("The challenge was found by running: $('body').children().toggle(); Note that even the line breaks from the challenege were included in my script. We should grab lunch, don't you think? "); //starter string to encode / decode } }; $( document ).ready(function() { encodeDecode(); });
import React, { Fragment, Children, cloneElement, useRef, useEffect } from 'react'; import { createPortal } from 'react-dom'; import PropTypes from 'prop-types'; import cx from 'classnames'; import idgen from './idgen'; import Button from './Button'; import { safeJSONStringify } from './utils'; const Modal = ({ actions, bottomSheet, children, fixedFooter, header, className, trigger, options, open, root, ...props }) => { const _modalRoot = useRef(null); const _modalInstance = useRef(null); const _modalRef = useRef(null); if (root === null) { console.warn( 'React Materialize: root should be a valid node element to render a Modal' ); } useEffect(() => { const modalRoot = _modalRoot.current; if (!_modalInstance.current) { _modalInstance.current = M.Modal.init(_modalRef.current, options); } return () => { if (root.contains(modalRoot)) { root.removeChild(modalRoot); } _modalInstance.current.destroy(); }; // deep comparing options object // eslint-disable-next-line react-hooks/exhaustive-deps }, [safeJSONStringify(options), root]); useEffect(() => { if (open) { showModal(); } else { hideModal(); } }, [open]); const showModal = e => { e && e.preventDefault(); _modalInstance.current && _modalInstance.current.open(); }; const hideModal = e => { e && e.preventDefault(); _modalInstance.current && _modalInstance.current.close(); }; const classes = cx( 'modal', { 'modal-fixed-footer': fixedFooter, 'bottom-sheet': bottomSheet }, className ); const renderModalPortal = () => { if (!_modalRoot.current) { _modalRoot.current = document.createElement('div'); root.appendChild(_modalRoot.current); } return createPortal( <div className={classes} ref={_modalRef} {...props}> <div className="modal-content"> <h4>{header}</h4> {children} </div> <div className="modal-footer">{Children.toArray(actions)}</div> </div>, _modalRoot.current ); }; return ( <Fragment> {trigger && cloneElement(trigger, { onClick: showModal })} {renderModalPortal()} </Fragment> ); }; Modal.propTypes = { /** * Options * Object with options for modal */ options: PropTypes.shape({ /** * Opacity of the modal overlay. */ opacity: PropTypes.number, /** * Transition in duration in milliseconds. */ inDuration: PropTypes.number, /** * Transition out duration in milliseconds. */ outDuration: PropTypes.number, /** * Callback function called before modal is opened. */ onOpenStart: PropTypes.func, /** * Callback function called after modal is opened. */ onOpenEnd: PropTypes.func, /** * Callback function called before modal is closed. */ onCloseStart: PropTypes.func, /** * Callback function called after modal is closed. */ onCloseEnd: PropTypes.func, /** * Prevent page from scrolling while modal is open. */ preventScrolling: PropTypes.bool, /** * Allow modal to be dismissed by keyboard or overlay click. */ dismissible: PropTypes.bool, /** * Starting top offset */ startingTop: PropTypes.string, /** * Ending top offset */ endingTop: PropTypes.string }), /** * Extra class to added to the Modal */ className: PropTypes.string, /** * Modal is opened on mount * @default false */ open: PropTypes.bool, /** * BottomSheet styled modal * @default false */ bottomSheet: PropTypes.bool, /** * Component children */ children: PropTypes.node, /** * FixedFooter styled modal * @default false */ fixedFooter: PropTypes.bool, /** * Text to shown in the header of the modal */ header: PropTypes.string, /** * The button to trigger the display of the modal */ trigger: PropTypes.node, /** * The buttons to show in the footer of the modal * @default <Button>Close</Button> */ actions: PropTypes.node, /** * The ID to trigger the modal opening/closing */ id: PropTypes.string, /** * Root node where modal should be injected * @default document.body */ root: PropTypes.any }; Modal.defaultProps = { get id() { return `Modal-${idgen()}`; }, root: typeof window !== 'undefined' ? document.body : null, open: false, options: { opacity: 0.5, inDuration: 250, outDuration: 250, onOpenStart: null, onOpenEnd: null, onCloseStart: null, onCloseEnd: null, preventScrolling: true, dismissible: true, startingTop: '4%', endingTop: '10%' }, fixedFooter: false, bottomSheet: false, actions: [ <Button waves="green" modal="close" flat> Close </Button> ] }; export default Modal;
class KonamiCodeManager { constructor() { this._pattern = "38384040373937396665"; this._keyCodeCache = ''; this._callback = () => {}; this._boundCheckKeyCodePattern = this._checkKeyCodePattern.bind(this); } attach(root, callback) { if (root instanceof Element) { root.removeEventListener('keydown', this._boundCheckKeyCodePattern); root.addEventListener('keydown', this._boundCheckKeyCodePattern); this._callback = callback; } } _checkKeyCodePattern(e) { if (e) { this._keyCodeCache += e.keyCode; if (this._keyCodeCache.length === this._pattern.length) { if (this._keyCodeCache === this._pattern) { console.log('KonamiCode passed, let\'s show some easter eggs :)'); this._callback(); } this._keyCodeCache = ''; } else if (!this._pattern.match(this._keyCodeCache)) { this._keyCodeCache = ''; } } } } module.exports = new KonamiCodeManager();
'use strict'; describe('test search controller', function() { beforeEach(module('mapTweetInfoApp')); beforeEach(module('twitterSearchServices')); beforeEach(module('latLngServices')); describe('searchCtrl', function(){ var scope, ctrl, $httpBackend, $browser, $location; beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) { // $httpBackend = _$httpBackend_; // $httpBackend.expectGET('phones/phones.json'). // respond([{name: 'Nexus S'}, {name: 'Motorola DROID'}]); scope = $rootScope.$new(); $location = scope.$service('$location'); $browser = scope.$service('$browser'); ctrl = $controller('searchCtrl', {$scope: scope}); })); it('should have default variables set', function() { // expect(scope.phones).toEqualData([]); // $httpBackend.flush(); expect(scope.counts).toEqualData( [{label: '25 Tweets', value: '25'},{label: '50 Tweets', value: '50'},{label: '75 Tweets', value: '75'},{label: '150 Tweets', value: '150'}] ); }); // it('should set the default value of orderProp model', function() { // expect(scope.orderProp).toBe('age'); // }); }); });
/** * * Trailing Zeroes * * @author: Corey Hart <http://www.codenothing.com> * @description: Removes unecessary trailing zeroes from values * * @before: * .example { * width: 5.0px; * } * * @after: * .example { * width: 5px; * } * */ var CSSCompressor = global.CSSCompressor, rdecimal = /^(\+|\-)?(\d*\.[1-9]*0*)(\%|[a-z]{2})$/i, rleadzero = /^\-?0/; CSSCompressor.rule({ name: 'Trailing Zeroes', type: CSSCompressor.RULE_TYPE_VALUE, group: 'Numeric', description: "Removes unecessary trailing zeroes from values", callback: function( value, position, compressor ) { var m = rdecimal.exec( value ), before = value, n; if ( m ) { // Remove possible leading zero that comes from parseFloat n = parseFloat( m[ 2 ] ); if ( ( n > 0 && n < 1 ) || ( n > -1 && n < 0 ) ) { n = ( n + '' ).replace( rleadzero, '' ); } value = ( m[ 1 ] ? m[ 1 ] : '' ) + n + ( m[ 3 ] ? m[ 3 ] : '' ); compressor.log( "Removing unecesary trailing zeroes '" + before + "' => '" + value + "'", position ); return value; } } });
// 文件上传 jQuery(function() { var $ = jQuery, $list = $('#thelist'), $btn = $('#ctlBtn'), state = 'pending', // 优化retina, 在retina下这个值是2 ratio = window.devicePixelRatio || 1, // 缩略图大小 thumbnailWidth = 100 * ratio, thumbnailHeight = 100 * ratio, uploader; uploader = WebUploader.create({ // 单文件上传 multiple: false, // 不压缩image resize: false, // swf文件路径 swf: '/webuploader/Uploader.swf', // 文件接收服务端。 server: '/upload', // 选择文件的按钮。可选。 // 内部根据当前运行是创建,可能是input元素,也可能是flash. pick: '#picker', // 只允许选择图片文件。 accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' } }); // 当有文件添加进来的时候 uploader.on( 'fileQueued', function( file ) { var $li = $( '<div id="' + file.id + '" class="file-item thumbnail">' + '<img>' + '<div class="info">' + file.name + '</div>' + '</div>' ), $img = $li.find('img'); $list.append( $li ); // 创建缩略图 uploader.makeThumb( file, function( error, src ) { if ( error ) { $img.replaceWith('<span>不能预览</span>'); return; } $img.attr( 'src', src ); }, thumbnailWidth, thumbnailHeight ); }); // 文件上传过程中创建进度条实时显示。 uploader.on( 'uploadProgress', function( file, percentage ) { var $li = $( '#'+file.id ), $percent = $li.find('.progress .progress-bar'); // 避免重复创建 if ( !$percent.length ) { $percent = $('<div class="progress progress-striped active">' + '<div class="progress-bar" role="progressbar" style="width: 0%">' + '</div>' + '</div>').appendTo( $li ).find('.progress-bar'); } $li.find('p.state').text('上传中'); $percent.css( 'width', percentage * 100 + '%' ); }); uploader.on( 'uploadSuccess', function( file , data) { $( '#'+file.id ).find('p.state').text('已上传'); $('#user_avatar').val(data.imageurl) $('#avatar').attr("src",data.imageurl) }); uploader.on( 'uploadError', function( file ) { $( '#'+file.id ).find('p.state').text('上传出错'); }); uploader.on( 'uploadComplete', function( file ) { $( '#'+file.id ).find('.progress').fadeOut(); }); uploader.on( 'all', function( type ) { if ( type === 'startUpload' ) { state = 'uploading'; } else if ( type === 'stopUpload' ) { state = 'paused'; } else if ( type === 'uploadFinished' ) { state = 'done'; } if ( state === 'uploading' ) { $btn.text('暂停上传'); } else { $btn.text('开始上传'); } }); $btn.on( 'click', function() { if ( state === 'uploading' ) { uploader.stop(); } else { uploader.upload(); } }); });
(function (w) { var $ = w.$, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], my = w.ilm, contid = 0; function fixCharts(width, fn) { $(fn).css("width", width); $(d).ready(function () { var inner = $(fn).width(); setTimeout(function () { $.each(w.ilm.charts, function (i, obj) { obj.setSize($(fn).width() - 6, obj.containerHeight, false); }); }, 500); }); } function setWidth() { console.log(w.ilm.getWidth()); var inner = ((w.ilm.getWidth() < 1024) ? "100" : "50") + "%"; $('.float').each(function () { fixCharts(inner, this); }); } w.ilm.popup=""; w.ilm.Options = function(state){ var t = this, f = $("#lingid"), g = $("#sl"); g.html("Seaded (klikk varjamiseks)"); my.settingTemplate(f); return false; }; w.ilm.Lingid = function (state) { var t = this, f = $("#lingid"), g = $("#sl"); g.html("Lingid (klikk varjamiseks)"); f.html(w.ilm.lingid.process(w.ilm.lingid.JSON)); return false; }; w.ilm.Popup = function(name, cb) { var v = $("#popup"); if(!v) return false; var b = $("#bghide"), hh = $('.navbar').height(), y = w.innerHeight || e.clientHeight || g.clientHeight, act = v.attr("name"),swp = 0; if (act) $("#ilm-" + act).parent().removeClass("active"); if(name && (!act || (act && act !== name))) { b.css({height : $(d).height(), position : 'absolute', left : 0, top : 0}).show(); v.attr("name", name); $("#ilm-" + name).parent().addClass("active"); if(cb) cb.call(this, name); swp = ((y/2) - (v.height()/2)) + $(w).scrollTop(); v.css({top : (swp > 0 ? swp : hh)}).show(); } else if(v.is(":visible")) { v.hide(); b.hide(); v.attr("name", ""); } return false; }; $(d).ready(function () { $("#pagelogo").html(ilm.logo); //setWidth(); $("#ilm-viited").click(function(e){ //ilm.showLinks(); var b = $(e.target); if(w.ilm.linksasmenu) { b.attr({"data-toggle":"dropdown"}); b.addClass("dropdown-toggle"); var a = $(".ilm-viited-dropdown"); a.html(w.ilm.lingid.process(w.ilm.lingid.JSON)); a.height(w.innerHeight-(w.innerHeight/3)); } else { b.removeClass("dropdown-toggle"); b.removeAttr("data-toggle"); w.ilm.Popup("viited",w.ilm.Lingid); } //return false; }); $("#ilm-seaded").click(function(e){ my.settingTemplate("#ilm-seaded-dropdown"); //w.ilm.Popup("seaded",w.ilm.Options); //return false; }); $("#fctitle").on("click",function(){ w.ilm.setEstPlace(w.ilm.nextPlace()); //w.ilm.reloadest(); return false; }); $("#datepicker").datepicker({ dateFormat: 'yy-mm-dd', timezone: "+0"+(((my.addDst)?1:0)+2)+"00", onSelect: function(dateText, inst) { w.ilm.setDate(dateText); //w.ilm.reload(); } }); $("#curtime").on("click",function(){ $("#datepicker").datepicker('show'); }); $("#curplace").on("click",function(){ w.ilm.setCurPlace(w.ilm.nextCurPlace()); //w.ilm.reload(); return false; }); w.ilm.loadBase(); w.ilm.loadInt(1000 * 60); // 1min w.ilm.loadEstInt(1000 * 60 * 10); // 10min $('#backgr').css({"display" : "block"}); $(w).on("keydown", function (e) { //w.console.log("pressed" + e.keyCode); var obj = $("#popup"); if(!obj) return; if (e.keyCode === 27 || e.keyCode === 13 ) { w.ilm.Popup("lingid", w.ilm.Lingid); } /*if (e.keyCode === 27 && obj.style.display === "block") { w.ilm.showLinks(); } else if (e.keyCode === 13 && obj.style.display === "none") { w.ilm.showLinks(); }*/ }); $(w).on('hashchange', function() { console.log("hash changed " + w.location.hash); w.ilm.hash_data(); }); }); })(window);
import setupStore from 'dummy/tests/helpers/store'; import Ember from 'ember'; import {module, test} from 'qunit'; import DS from 'ember-data'; var env, store; var attr = DS.attr; var hasMany = DS.hasMany; var belongsTo = DS.belongsTo; var run = Ember.run; var Post, Tag; module("unit/many_array - DS.ManyArray", { beforeEach() { Post = DS.Model.extend({ title: attr('string'), tags: hasMany('tag', { async: false }) }); Tag = DS.Model.extend({ name: attr('string'), post: belongsTo('post', { async: false }) }); env = setupStore({ post: Post, tag: Tag }); store = env.store; }, afterEach() { run(function() { store.destroy(); }); } }); test("manyArray.save() calls save() on all records", function(assert) { assert.expect(3); run(function() { Tag.reopen({ save() { assert.ok(true, 'record.save() was called'); return Ember.RSVP.resolve(); } }); store.push({ data: [{ type: 'tag', id: '1', attributes: { name: 'Ember.js' } }, { type: 'tag', id: '2', attributes: { name: 'Tomster' } }, { type: 'post', id: '3', attributes: { title: 'A framework for creating ambitious web applications' }, relationships: { tags: { data: [ { type: 'tag', id: '1' }, { type: 'tag', id: '2' } ] } } }] }); var post = store.peekRecord('post', 3); post.get('tags').save().then(function() { assert.ok(true, 'manyArray.save() promise resolved'); }); }); }); test("manyArray trigger arrayContentChange functions with the correct values", function(assert) { assert.expect(12); var willChangeStartIdx; var willChangeRemoveAmt; var willChangeAddAmt; var originalArrayContentWillChange = DS.ManyArray.prototype.arrayContentWillChange; var originalArrayContentDidChange = DS.ManyArray.prototype.arrayContentDidChange; DS.ManyArray.reopen({ arrayContentWillChange(startIdx, removeAmt, addAmt) { willChangeStartIdx = startIdx; willChangeRemoveAmt = removeAmt; willChangeAddAmt = addAmt; return this._super.apply(this, arguments); }, arrayContentDidChange(startIdx, removeAmt, addAmt) { assert.equal(startIdx, willChangeStartIdx, 'WillChange and DidChange startIdx should match'); assert.equal(removeAmt, willChangeRemoveAmt, 'WillChange and DidChange removeAmt should match'); assert.equal(addAmt, willChangeAddAmt, 'WillChange and DidChange addAmt should match'); return this._super.apply(this, arguments); } }); run(function() { store.push({ data: [{ type: 'tag', id: '1', attributes: { name: 'Ember.js' } }, { type: 'tag', id: '2', attributes: { name: 'Tomster' } }, { type: 'post', id: '3', attributes: { title: 'A framework for creating ambitious web applications' }, relationships: { tags: { data: [ { type: 'tag', id: '1' } ] } } }] }); store.peekRecord('post', 3); store.push({ data: { type: 'post', id: '3', attributes: { title: 'A framework for creating ambitious web applications' }, relationships: { tags: { data: [ { type: 'tag', id: '1' }, { type: 'tag', id: '2' } ] } } } }); store.peekRecord('post', 3); }); DS.ManyArray.reopen({ arrayContentWillChange: originalArrayContentWillChange, arrayContentDidChange: originalArrayContentDidChange }); });
'use strict'; /* Controllers */ angular.module('myApp.controllers') .controller('DatepickerDemoCtrl', ['$scope','$timeout',function($scope, $timeout) { $scope.today = function() { $scope.dt = new Date(); }; $scope.today(); $scope.showWeeks = true; $scope.toggleWeeks = function () { $scope.showWeeks = ! $scope.showWeeks; }; $scope.clear = function () { $scope.dt = null; }; // Disable weekend selection $scope.disabled = function(date, mode) { return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) ); }; $scope.toggleMin = function() { $scope.minDate = ( $scope.minDate ) ? null : new Date(); }; $scope.toggleMin(); $scope.open = function() { $timeout(function() { $scope.opened = true; }); }; $scope.dateOptions = { 'year-format': "'yy'", 'starting-day': 1 }; }])
import {Manager} from './manager' export {Filterer} from './filter'; export {Logger} from './logger'; export {Manager}; var logging = new Manager(); export default logging;
/** * Created by larry on 2017/1/6. */ import React from 'react'; import Todo from './Todo'; //圆括号里面要写大括号 const TodoList = ({todos, onTodoClick}) => { return ( <ul> { todos.map ( todo => <Todo key={todo.id} {...todo} onClick={() => onTodoClick(todo.id)} /> ) } </ul> ) }; export default TodoList;
requirejs.config({ // baseUrl: '/', paths: { lodash: '//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash', jquery: '//code.jquery.com/jquery-1.11.0.min', react: '//cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react-with-addons' }, shim: { lodash: {exports: '_'}, jquery: {exports: '$'}, react: {exports: 'React'} } }) requirejs(['jquery', 'react', 'ImageSearch'], function ($, React, ImageSearch) { 'use strict' React.renderComponent(ImageSearch(), $('#main').get(0)) //eslint-disable-line new-cap })
export { default } from 'ember-fhir/serializers/timing-repeat';
/* * Globalize Culture co * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to be fixed in the generator * Portions (c) Corporate Web Solutions Ltd. */ (function( window, undefined ) { var Globalize; if ( typeof require !== "undefined" && typeof exports !== "undefined" && typeof module !== "undefined" ) { // Assume CommonJS Globalize = require( "globalize" ); } else { // Global variable Globalize = window.Globalize; } Globalize.addCultureInfo( "co", "default", { name: "co", englishName: "Corsican", nativeName: "Corsu", language: "co", numberFormat: { ",": " ", ".": ",", "NaN": "Mica numericu", negativeInfinity: "-Infinitu", positiveInfinity: "+Infinitu", percent: { ",": " ", ".": "," }, currency: { pattern: ["-n $","n $"], ",": " ", ".": ",", symbol: "€" } }, calendars: { standard: { firstDay: 1, days: { names: ["dumenica","luni","marti","mercuri","ghjovi","venderi","sabbatu"], namesAbbr: ["dum.","lun.","mar.","mer.","ghj.","ven.","sab."], namesShort: ["du","lu","ma","me","gh","ve","sa"] }, months: { names: ["ghjennaghju","ferraghju","marzu","aprile","maghju","ghjunghju","lugliu","aostu","settembre","ottobre","nuvembre","dicembre",""], namesAbbr: ["ghje","ferr","marz","apri","magh","ghju","lugl","aost","sett","otto","nuve","dice",""] }, AM: null, PM: null, eras: [{"name":"dopu J-C","start":null,"offset":0}], patterns: { d: "dd/MM/yyyy", D: "dddd d MMMM yyyy", t: "HH:mm", T: "HH:mm:ss", f: "dddd d MMMM yyyy HH:mm", F: "dddd d MMMM yyyy HH:mm:ss", M: "d MMMM", Y: "MMMM yyyy" } } } }); }( this ));
(function () { 'use strict'; angular.module('customers') .controller('OneCustomerCtrl', function ($scope, customers, $stateParams) { var cid = $stateParams.cid; $scope.customer=_.find(customers, function (customer) { return customer.profile.userName===cid; }); console.log($scope.customer); }); })();
var exptemplate = require('../prepublic/javascripts/exptemplate'); module.exports = exptemplate;
/** * Created by jsturtevant on 1/18/14 */ var DEFAULT_SHORTCUT_KEY = 'ctrl+shift+k'; var LOCAL_STORAGE_KEY = 'optionsStore' var defaultOptions = { shortcuts: [ {key: "", value:""} ], cssSelectors: [{value:""}], shortcutKey: DEFAULT_SHORTCUT_KEY, includeIFrames: true }; var optionsApp = angular.module('optionsApp', []); optionsApp.factory('OptionsData', function() { var optionsJSON = localStorage[LOCAL_STORAGE_KEY]; if (!optionsJSON){ return defaultOptions; } else{ return JSON.parse(optionsJSON); } }); optionsApp.directive("showhide", function() { return function(scope, element, attrs) { var bodyelement =angular.element(document.getElementById(attrs.showhide)); element.bind("mouseover", function() { element.css("cursor", "pointer"); element.css('color', attrs.togglecolor); }) element.bind("mouseleave", function() { if (bodyelement.hasClass('hidden')){ element.css('color', ""); } }); element.bind("click", function() { angular.element(bodyelement).toggleClass('hidden'); element.css('color', attrs.togglecolor); }); }; }); function OptionsCtrl($scope, OptionsData, $timeout){ $scope.options = OptionsData; $scope.AddShortcut = function(){ $scope.options.shortcuts.push({key: "", value:""}) }; $scope.AddSelector = function(){ if (!$scope.options.cssSelectors){ $scope.options.cssSelectors = defaultOptions.cssSelectors; } $scope.options.cssSelectors.push({value: ""}) }; $scope.Save = function(){ localStorage[LOCAL_STORAGE_KEY] = JSON.stringify($scope.options); $scope.message = 'Changes saved!'; $timeout(function() { $scope.message = null; }, 5 * 1000); }; $scope.Delete = function (index){ $scope.options.shortcuts.splice(index,1); }; $scope.DeleteSelector = function (index){ $scope.options.cssSelectors.splice(index,1); }; };
import { fromJS, OrderedMap } from 'immutable'; const vaccines = fromJS([ { name: 'AVA (BioThrax)', id: '8b013618-439e-4829-b88f-98a44b420ee8', diseases: ['Anthrax'], }, { name: 'VAR (Varivax)', id: 'f3e08a56-003c-4b46-9dea-216298401ca0', diseases: ['Varicella (Chickenpox)'], }, { name: 'MMRV (ProQuad)', id: '3373721d-3d14-490c-9fa9-69a223888322', diseases: [ 'Varicella (Chickenpox)', 'Measles', 'Mumps', 'Rubella (German Measles)', ], }, { name: 'HepA (Havrix, Vaqta)', id: 'a9144edf-13a2-4ce5-b6af-14eb38fd848c', diseases: ['Hepatitis A'], }, { name: 'HepA-HepB (Twinrix)', id: '6888fd1a-af4f-4f33-946d-40d4c473c9cc', diseases: ['Hepatitis A', 'Hepatitis B'], }, { name: 'HepB (Engerix-B, Recombivax HB)', id: 'ca079856-a561-4bc9-9bef-e62429ed3a38', diseases: ['Hepatitis B'], }, { name: 'Hib-HepB (Comvax)', id: '7305d769-0d1e-4bef-bd09-6998dc839825', diseases: ['Hepatitis B', 'Haemophilus influenzae type b (Hib)'], }, { name: 'Hib (ActHIB, PedvaxHIB, Hiberix)', id: 'd241f0c7-9920-4bc6-8f34-288a13e03f4d', diseases: ['Haemophilus influenzae type b (Hib)'], }, { name: 'HPV4 (Gardasil)', id: 'c2fef03c-db7f-483b-af70-50560712b189', diseases: ['Human Papillomavirus (HPV)'], }, { name: 'HPV2 (Cervarix)', id: '286f55e4-e727-4fc4-86b0-5a08ea712a77', diseases: ['Human Papillomavirus (HPV)'], }, { name: 'TIV (Afluria, Agriflu, FluLaval, Fluarix, Fluvirin, Fluzone, Fluzone High-Dose, Fluzone Intradermal)', // eslint-disable-line max-len id: '60e85a31-6a54-48e1-b0b7-deb28120675b', diseases: ['Seasonal Influenza (Flu)'], }, { name: 'LAIV (FluMist)', id: '9e67e321-9a7f-426f-ba9b-28885f93f9b9', diseases: ['Seasonal Influenza (Flu)'], }, { name: 'JE (Ixiaro)', id: '5ce00584-3350-442d-ac6c-7f19567eff8a', diseases: ['Japanese Encephalitis'], }, { name: 'MMR (M-M-R II)', id: 'd10b7bf0-d51e-4117-a6a4-08bdb5cb682a', diseases: ['Measles', 'Mumps', 'Rubella (German Measles)'], }, { name: 'MCV4 (Menactra)', id: '6295fe11-f0ce-4967-952c-f271416cc300', diseases: ['Meningococcal'], }, { name: 'MPSV4 (Menomune)', id: '65f6d6d0-6dd8-49c9-95da-ed9fa403ae96', diseases: ['Meningococcal'], }, { name: 'MODC (Menveo)', id: 'be10b480-7934-46be-a488-66540aac2881', diseases: ['Meningococcal'], }, { name: 'Tdap (Adacel, Boostrix)', id: '0c6c33fb-f4dc-44c6-8684-625099f6fa21', diseases: ['Pertussis (Whooping Cough)', 'Tetanus (Lockjaw)', 'Diphtheria'], }, { name: 'PCV13 (Prevnar13)', id: 'd8c5a723-21e2-49a6-a921-705da16563e1', diseases: ['Pneumococcal'], }, { name: 'PPSV23 (Pneumovax 23)', id: '4005de2f-8e6d-40ae-bb5f-068ac56885b8', diseases: ['Pneumococcal'], }, { name: 'Polio (Ipol)', id: '9c1582f2-8a7b-4bae-8ba5-656efe33fb29', diseases: ['Polio'], }, { name: 'Rabies (Imovax Rabies, RabAvert)', id: '2bfeeb1f-b7a7-4ce6-aae1-72e840a93e2e', diseases: ['Rabies'], }, { name: 'RV1 (Rotarix)', id: '8ddfa840-7558-469a-a53b-19a40d016518', diseases: ['Rotavirus'], }, { name: 'RV5 (RotaTeq)', id: '9281ddcb-5ef3-47e6-a249-6b2b8bee1e7f', diseases: ['Rotavirus'], }, { name: 'ZOS (Zostavax)', id: '2921b034-8a4c-46f5-9753-70a112dfec3f', diseases: ['Shingles (Herpes Zoster)'], }, { name: 'Vaccinia (ACAM2000)', id: 'e26378f4-5d07-4b5f-9c93-53816c0faf9f', diseases: ['Smallpox'], }, { name: 'DTaP (Daptacel, Infanrix)', id: 'b23e765e-a05b-4a24-8095-03d79e47a8aa', diseases: [ 'Tetanus (Lockjaw)', 'Pertussis (Whooping Cough)', 'Diphtheria', ], }, { name: 'Td (Decavac, generic)', id: '1af45230-cb2a-4242-81ac-2430cd64f8ce', diseases: ['Tetanus (Lockjaw)', 'Diphtheria'], }, { name: 'DT (-generic-)', id: '6eb77e28-aaa1-4e29-b124-5793a4bd6f1f', diseases: ['Tetanus (Lockjaw)', 'Diphtheria'], }, { name: 'TT (-generic-)', id: 'd6cf7277-831c-43c6-a1fa-7109d3325168', diseases: ['Tetanus (Lockjaw)'], }, { name: 'DTaP-IPV (Kinrix)', id: 'a8ecfef5-5f09-442c-84c3-4dfbcd99b3b8', diseases: [ 'Tetanus (Lockjaw)', 'Polio', 'Pertussis (Whooping Cough)', 'Diphtheria', ], }, { name: 'DTaP-HepB-IPV (Pediarix)', id: '10bc0626-7b0a-4a42-b1bf-2742f0435c37', diseases: [ 'Tetanus (Lockjaw)', 'Polio', 'Hepatitis B', 'Pertussis (Whooping Cough)', 'Diphtheria', ], }, { name: 'DTaP-IPV/Hib (Pentacel)', id: 'dcbb9691-1544-44fc-a9ca-351946010876', diseases: [ 'Tetanus (Lockjaw)', 'Polio', 'Haemophilus influenzae type b (Hib)', 'Pertussis (Whooping Cough)', 'Diphtheria', ], }, { name: 'DTaP/Hib', id: 'e817c55d-e3db-4963-9fec-04d5823f6915', diseases: [ 'Tetanus (Lockjaw)', 'Diphtheria', 'Haemophilus influenzae type b (Hib)', 'Pertussis (Whooping Cough)', ], }, { name: 'BCG (TICE BCG, Mycobax)', id: '8f2049a1-a1e3-44e1-947e-debbf3cafecc', diseases: ['Tuberculosis (TB)'], }, { name: 'Typhoid Oral (Vivotif)', id: '060f44be-e1e7-4575-ba0f-62611f03384b', diseases: ['Typhoid Fever'], }, { name: 'Typhoid Polysaccharide (Typhim Vi)', id: '87009829-1a48-4330-91e1-6bcd7ab04ee1', diseases: ['Typhoid Fever'], }, { name: 'YF (YF-Vax)', id: '24d5bfc4-d69a-4311-bb10-8980dddafa20', diseases: ['Yellow Fever'], }, ]); const keyedVaccines = vaccines.reduce((result, item) => ( result.set(item.get('id'), item) ), OrderedMap()); export default keyedVaccines.sortBy(vaccine => vaccine.get('name').toLowerCase());
/** * 页面管理 * @author: SimonHao * @date: 2015-12-19 14:24:08 */ 'use strict'; var path = require('path'); var fs = require('fs'); var extend = require('extend'); var mid = require('made-id'); var file = require('./file'); var config = require('./config'); var page_list = {}; var comm_option = config.get('comm'); var server = comm_option.server; var base_path = comm_option.path.base; var dist_path = comm_option.path.dist; var page_path = path.join(dist_path, 'page'); var view_option = extend({ basedir: base_path }, comm_option.view); var style_option = extend({ basedir: base_path }, comm_option.style); var script_option = extend({ basedir: base_path }, comm_option.script); exports.get = function(src){ if(exports.has(src)){ return page_list[src]; } }; exports.has = function(src){ return src in page_list; }; exports.set = function(src){ if(exports.has(src)){ return exports.get(src); }else{ return page_list[src] = new PageInfo(src); } }; function PageInfo(src){ this.info = new ModuleInfo(src); this.deps = []; this.external_style = {}; this.external_script = {}; this.page_style = path.dirname(this.info.view) + '.css'; this.page_script = path.dirname(this.info.view) + '.js'; this._dist = null; this._url = null; } PageInfo.prototype.link_style = function(pack_name){ this.external_style[pack_name] = path.join(base_path, pack_name + '.css'); }; PageInfo.prototype.link_script = function(pack_name){ this.external_script[pack_name] = path.join(base_path, pack_name + '.js'); }; PageInfo.prototype.script_module = function(){ var script_module = []; this.deps.forEach(function(module_info){ if(module_info.script){ script_module.push(module_info.script); } }); if(this.info.script){ script_module.push(this.info.script); } return script_module; }; PageInfo.prototype.style_module = function(){ var style_module = []; this.deps.forEach(function(module_info){ if(module_info.style){ style_module.push(module_info.style); } }); if(this.info.style){ style_module.push(this.info.style); } return style_module; }; PageInfo.prototype.add_deps = function(deps){ var self = this; deps.forEach(function(dep_info){ self.deps.push(new ModuleInfo(dep_info.filename, dep_info)); }); }; PageInfo.prototype.entry = function(){ var entry_list = []; this.deps.filter(function(module_info){ return module_info.script; }).forEach(function(module_info){ entry_list.push({ id: module_info.id, options: module_info.info.options || {}, instance: module_info.info.instance }); }); if(this.info.script){ entry_list.push({ id: this.info.id, options: {}, instance: null }); } return entry_list; }; PageInfo.prototype.dist = function(){ if(this._dist) return this._dist; var path_dir = path.normalize(this.info.id).split(path.sep); path_dir.splice(1,1); return this._dist = path.join(page_path, path_dir.join(path.sep) + '.html'); }; PageInfo.prototype.url = function(){ if(this._url) return this._url var relative_path = path.relative(page_path, this.dist()); var url = server.web_domain + server.web_path + relative_path.split(path.sep).join('/'); this._url = url; return url; }; /** * Include Module Info * @param {string} filename view filename */ function ModuleInfo(filename, info){ this.info = info || {}; this.view = filename; this.id = mid.id(filename, view_option); this.script = mid.path(this.id, script_option); this.style = mid.path(this.id, style_option); }
export { default } from 'ember-flexberry-gis/components/flexberry-wfs-filter';
lychee.define('Font').exports(function(lychee) { var Class = function(spriteOrImages, settings) { this.settings = lychee.extend({}, this.defaults, settings); if (this.settings.kerning > this.settings.spacing) { this.settings.kerning = this.settings.spacing; } this.__cache = {}; this.__images = null; this.__sprite = null; if (Object.prototype.toString.call(spriteOrImages) === '[object Array]') { this.__images = spriteOrImages; } else { this.__sprite = spriteOrImages; } this.__init(); }; Class.prototype = { defaults: { // default charset from 32-126 charset: ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~', baseline: 0, spacing: 0, kerning: 0, map: null }, __init: function() { // Single Image Mode if (this.__images !== null) { this.__initImages(); // Sprite Image Mode } else if (this.__sprite !== null) { if (Object.prototype.toString.call(this.settings.map) === '[object Array]') { var test = this.settings.map[0]; if (Object.prototype.toString.call(test) === '[object Object]') { this.__initSpriteXY(); } else if (typeof test === 'number') { this.__initSpriteX(); } } } }, __initImages: function() { for (var c = 0, l = this.settings.charset.length; c < l; c++) { var image = this.__images[c] || null; if (image === null) continue; var chr = { id: this.settings.charset[c], image: image, width: image.width, height: image.height, x: 0, y: 0 }; this.__cache[chr.id] = chr; } }, __initSpriteX: function() { var offset = this.settings.spacing; for (var c = 0, l = this.settings.charset.length; c < l; c++) { var chr = { id: this.settings.charset[c], width: this.settings.map[c] + this.settings.spacing * 2, height: this.__sprite.height, real: this.settings.map[c], x: offset - this.settings.spacing, y: 0 }; offset += chr.width; this.__cache[chr.id] = chr; } }, __initSpriteXY: function() { for (var c = 0, l = this.settings.charset.length; c < l; c++) { var frame = this.settings.map[c]; var chr = { id: this.settings.charset[c], width: frame.width + this.settings.spacing * 2, height: frame.height, real: frame.width, x: frame.x - this.settings.spacing, y: frame.y }; this.__cache[chr.id] = chr; } }, get: function(id) { if (this.__cache[id] !== undefined) { return this.__cache[id]; } return null; }, getSettings: function() { return this.settings; }, getSprite: function() { return this.__sprite; } }; return Class; });
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M8 9v1.5h2.25V15h1.5v-4.5H14V9H8zM6 9H3c-.55 0-1 .45-1 1v5h1.5v-1.5h2V15H7v-5c0-.55-.45-1-1-1zm-.5 3h-2v-1.5h2V12zM21 9h-4.5c-.55 0-1 .45-1 1v5H17v-4.5h1V14h1.5v-3.51h1V15H22v-5c0-.55-.45-1-1-1z" }), 'AtmOutlined');
// bundles everything except TS files which will be built by rollup. // webpack stuff var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var failPlugin = require('webpack-fail-plugin'); var helpers = require('./helpers'); const basePlugins = [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }), new webpack.optimize.CommonsChunkPlugin('globals'), new HtmlWebpackPlugin({ template: 'index.template.html', favicon: 'favicon.ico' }), new ExtractTextPlugin("styles.css"), failPlugin ]; const devPlugins = [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ]; const plugins = basePlugins .concat((process.env.NODE_ENV === 'development') ? devPlugins: []); module.exports = { entry: { globals: [ 'core-js', 'zone.js', 'reflect-metadata' ] }, output: { path: helpers.root(''), publicPath: '', filename: '[name].js', chunkFilename: '[id].chunk.js' }, resolve: { extensions: [ '.webpack.js', '.web.js', '.js', '.html' ] }, module: { loaders: [ { test: /\.json$/, loader: 'json-loader' }, { test: /\.html$/, loader: 'raw' }, { test: /\.(ico)$/, loader: 'file' }, { test: /\.(png|jpe?g|gif)$/, loader: 'file', query: {name: 'assets/[name].[hash].[ext]'} }, { test: /\.css$/, exclude: helpers.root('src', 'app'), loader: ExtractTextPlugin.extract({ fallbackLoader: "style-loader", loader: "css-loader" }) }, { test: /\.css$/, include: helpers.root('src', 'app'), loader: 'raw' }, { test: /\.woff(2)?(\?v=\d+\.\d+\.\d+)?$/, loader: 'url', query: {limit: '10000', mimetype: 'application/font-woff'} }, { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url', query: {limit: '10000', mimetype: 'application/octet-stream'} }, { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file' }, { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url', query: {limit: '10000', mimetype: 'image/svg+xml'} } ] }, plugins: plugins }; // gulp tasks var gulp = require('gulp'); var watch = require('gulp-watch'); var batch = require('gulp-batch'); gulp.task('build', function () { console.log('build Working!'); }); gulp.task('watch', function () { watch('**/*.ts', batch(function (events, done) { gulp.start('build', done); })); });
exports.up = function (knex, Promise) { return Promise.all([ knex.schema.createTable('locations', function (table) { table.uuid('id').notNullable().primary() table.string('title').notNullable().unique() table.text('description') table.string('address_1') table.string('address_2') table.string('town') table.string('county') table.string('zipcode') table.string('country') }), knex.schema.createTable('conferences', function (table) { table.uuid('id').notNullable().primary() table.string('title').notNullable().unique() table.text('description') table.string('organiser').notNullable().unique() table.dateTime('startTime') table.dateTime('endTime') table.uuid('location').references('locations.id') }) ]) } exports.down = function (knex, Promise) { return Promise.all([ knex.schema.dropTable('conferences'), knex.schema.dropTable('locations') ]) }
#!/usr/bin/env node var _ = require('lodash'); var async = require('async-chainable'); var asyncFlush = require('async-chainable-flush'); var colors = require('chalk'); var doop = require('.'); var glob = require('glob'); var fs = require('fs'); var fspath = require('path'); var program = require('commander'); var sha1 = require('node-sha1'); program .version(require('./package.json').version) .description('List units installed for the current project') .option('-b, --basic', 'Display a simple list, do not attempt to hash file differences') .option('-v, --verbose', 'Be verbose. Specify multiple times for increasing verbosity', function(i, v) { return v + 1 }, 0) .parse(process.argv); async() .use(asyncFlush) .then(doop.chProjectRoot) .then(doop.getUserSettings) // Get the list of units {{{ .then('units', function(next) { doop.getUnits(function(err, units) { if (err) return next(err); next(null, units.map(u => { return { id: u, path: fspath.join(doop.settings.paths.units, u), files: {}, } })); }); }) // }}} // Hash file comparisons unless program.basic {{{ // Get repo {{{ .then('repo', function(next) { if (program.basic) return next(); doop.getDoopPath(next, program.repo); }) .then(function(next) { if (program.basic) return next(); if (program.verbose) console.log('Using Doop source:', colors.cyan(this.repo)); next(); }) // }}} // Scan project + Doop file list and hash all files (unless !program.basic) {{{ .then(function(next) { if (program.basic) return next(); // Make a list of all files in both this project and in the doop repo // For each file create an object with a `local` sha1 hash and `doop` sha1 hash var hashQueue = async(); // Hash tasks to perform async() .forEach(this.units, function(next, unit) { async() .parallel([ // Hash all project files {{{ function(next) { glob(fspath.join(unit.path, '**'), {nodir: true}, function(err, files) { if (files.length) { unit.existsInProject = true; files.forEach(function(file) { hashQueue.defer(file, function(next) { if (program.verbose) console.log('Hash file (Proj)', colors.cyan(file)); sha1(fs.createReadStream(file), function(err, hash) { if (!unit.files[file]) unit.files[file] = {path: file}; unit.files[file].project = hash; next(); }); }); }); } else { unit.existsInProject = false; } next(); }); }, // }}} // Hash all Doop files {{{ function(next) { glob(fspath.join(doop.settings.paths.doop, unit.path, '**'), {nodir: true}, function(err, files) { if (files.length) { unit.existsInDoop = true; files.forEach(function(rawFile) { var croppedPath = rawFile.substr(doop.settings.paths.doop.length + 1); var file = fspath.join(doop.settings.paths.doop, croppedPath); hashQueue.defer(file, function(next) { if (program.verbose) console.log('Hash file (Doop)', colors.cyan(croppedPath)); sha1(fs.createReadStream(file), function(err, hash) { if (!unit.files[croppedPath]) unit.files[croppedPath] = {path: file}; unit.files[croppedPath].doop = hash; next(); }); }); }); } else { unit.existsInDoop = false; } next(); }); }, // }}} ]) .end(next) }) .end(function(err) { if (err) return next(err); // Wait for hashing queue to finish hashQueue.await().end(next); }); }) // }}} // }}} // Present the list {{{ .then(function(next) { var task = this; if (program.verbose > 1) console.log(); this.units.forEach(function(unit) { if (unit.existsInProject && !unit.existsInDoop) { console.log(colors.grey(' -', unit.id)); } else if (!unit.existsInProject && unit.existsInDoop) { console.log(colors.red(' -', unit.id)); } else { // In both Doop + Project - examine file differences var changes = []; // Edited {{{ var items = _.filter(unit.files, f => f.project && f.doop && f.project != f.doop); if (_.get(doop.settings, 'list.changes.maxEdited') && items.length > doop.settings.list.changes.maxEdited) { changes.push(colors.yellow.bold('~' + items.length + ' items')); } else { items.forEach(f => changes.push(colors.yellow.bold('~') + f.path.substr(unit.path.length+1))); } // }}} // Created {{{ var items = _.filter(unit.files, f => f.project && !f.doop); if (_.get(doop.settings, 'list.changes.maxCreated') && items.length > doop.settings.list.changes.maxCreated) { changes.push(colors.green.bold('+' + items.length + ' items')); } else { items.forEach(f => changes.push(colors.green.bold('+') + f.path.substr(unit.path.length+1))); } // }}} // Deleted {{{ var items = _.filter(unit.files, f => f.doop && !f.project); if (_.get(doop.settings, 'list.changes.maxDeleted') && items.length > doop.settings.list.changes.maxDeleted) { changes.push(colors.red.bold('-' + items.length + ' items')); } else { items.forEach(f => changes.push(colors.red.bold('-') + f.path.substr(doop.settings.paths.doop.length+unit.path.length+2))); } // }}} if (changes.length) { console.log(' -', unit.id, colors.blue('('), changes.join(', '), colors.blue(')')); } else { console.log(' -', unit.id); } } }); next(); }) // }}} // End {{{ .flush() .end(function(err) { if (err) { console.log(colors.red('Doop Error'), err.toString()); process.exit(1); } else { process.exit(0); } }); // }}}
if(!Hummingbird) { var Hummingbird = {}; } Hummingbird.Base = function() {}; Hummingbird.Base.prototype = { validMessageCount: 0, messageRate: 20, initialize: function() { this.averageLog = []; this.setFilter(); this.registerHandler(); }, registerHandler: function() { this.socket.registerHandler(this.onData, this); }, onMessage: function(message) { console.log("Base class says: " + JSON.stringify(message)); }, onData: function(fullData) { var average; var message = this.extract(fullData); if(typeof(message) != "undefined") { this.validMessageCount += 1; // Calculate the average over N seconds if the averageOver option is set if(this.options.averageOver) { average = this.addToAverage(message); } if((!this.options.every) || (this.validMessageCount % this.options.every == 0)) { this.onMessage(message, this.average()); } } }, extract: function(data) { if(typeof(data) == "undefined") { return; } var obj = data; for(var i = 0, len = this.filter.length; i < len; i++) { obj = obj[this.filter[i]]; if(typeof(obj) == "undefined") { return; } } return obj; }, setFilter: function() { // TODO: extend this (and extract) to support multiple filters var obj = this.options.data; this.filter = []; while(typeof(obj) == "object") { for(var i in obj) { this.filter.push(i); obj = obj[i]; break; } } }, addToAverage: function(newValue) { var averageCount = this.options.averageOver * this.messageRate; this.averageLog.push(newValue); if(this.averageLog.length > averageCount) { this.averageLog.shift(); } }, average: function() { if(this.averageLog.length == 0) { return 0; } return this.averageLog.sum() * 1.0 / this.averageLog.length * this.messageRate; } };
define([ 'knockout' ],function( ko ){ ko.bindingHandlers.withfirst = { 'init' : function(element, valueAccessor, allBindings, viewModel, bindingContext) { var savedNodes; ko.computed(function() { var dataValue = ko.utils.unwrapObservable(valueAccessor()); var shouldDisplay = typeof dataValue.length == "number" && dataValue.length; var isFirstRender = !savedNodes; // Save a copy of the inner nodes on the initial update, // but only if we have dependencies. if (isFirstRender && ko.computedContext.getDependenciesCount()) { savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */); } if (shouldDisplay) { if (!isFirstRender) { ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes)); } ko.applyBindingsToDescendants( bindingContext['createChildContext'](dataValue && dataValue[0]), element); } else { ko.virtualElements.emptyNode(element); } }, null).extend({ rateLimit: 50 }); return { 'controlsDescendantBindings': true }; } } });
var bunyanConfig = require('../index'); var bunyan = require('bunyan'); var path = require('path'); describe('bunyan-config', function () { it('should not convert things it does not understand', function () { bunyanConfig({ name: 'test', streams: [{ path: '/tmp/log.log' }, { type: 'raw', stream: 'unknown' }], serializers: 5 }).should.deep.equal({ name: 'test', streams: [{ path: '/tmp/log.log' }, { type: 'raw', stream: 'unknown' }], serializers: 5 }); }); describe('streams', function () { it('should convert stdout and stderr', function () { bunyanConfig({ streams: [{ level: 'info', stream: 'stdout' }, { stream: {name: 'stderr'} }] }).should.deep.equal({ streams: [{ level: 'info', stream: process.stdout }, { stream: process.stderr }] }); }); it('should convert bunyan-logstash', function () { bunyanConfig({ streams: [{ level: 'error', type: 'raw', stream: { name: 'bunyan-logstash', params: { host: 'example.com', port: 1234 } } }] }).should.deep.equal({ streams: [{ level: 'error', type: 'raw', stream: require('bunyan-logstash').createStream({ host: 'example.com', port: 1234 }) }] }); }); it('should convert bunyan-redis stream', function () { var config = bunyanConfig({ streams: [{ type: 'raw', stream: { name: 'bunyan-redis', params: { host: 'example.com', port: 1234 } } }] }); config.streams[0].stream.should.be.an.instanceof(require('events').EventEmitter); config.streams[0].stream._client.host.should.equal('example.com'); config.streams[0].stream._client.port.should.equal(1234); config.streams[0].stream._client.end(); }); }); describe('serializers', function () { it('should convert serializers property, if it is a string', function () { bunyanConfig({ serializers: 'bunyan:stdSerializers' }).should.deep.equal({ serializers: bunyan.stdSerializers }); }); it('should not convert serializers, if it is an empty string', function () { bunyanConfig({ serializers: '' }).should.deep.equal({ serializers: '' }); }); it('should convert serializers object', function () { var absolutePathWithProps = path.resolve(__dirname, './fixtures/dummySerializerWithProps'); var relativePathWithProps = './' + path.relative(process.cwd(), absolutePathWithProps); var absolutePathWithoutProps = path.resolve(__dirname, './fixtures/dummySerializerWithoutProps'); var relativePathWithoutProps = './' + path.relative(process.cwd(), absolutePathWithoutProps); bunyanConfig({ serializers: { moduleWithProps: 'bunyan:stdSerializers.req', moduleWithoutProps: 'bunyan', absoluteWithProps: relativePathWithProps + ':c', relativeWithProps: relativePathWithProps + ':a.b', absoluteWithoutProps: absolutePathWithoutProps, relativeWithoutProps: relativePathWithoutProps, empty: '', noModuleId: ':abc' } }).should.deep.equal({ serializers: { moduleWithProps: bunyan.stdSerializers.req, moduleWithoutProps: bunyan, absoluteWithProps: require('./fixtures/dummySerializerWithProps').c, relativeWithProps: require('./fixtures/dummySerializerWithProps').a.b, absoluteWithoutProps: require('./fixtures/dummySerializerWithoutProps'), relativeWithoutProps: require('./fixtures/dummySerializerWithoutProps'), empty: '', noModuleId: ':abc' } }); }); }); });
'use strict'; var http = require('http'); var Logger = require('bunyan'); var log = new Logger({ name: 'test-server', level: 'debug' }); var server = http.createServer(function (request) { var data = ''; log.info({ url: request.url }, 'Incoming Request'); request.on('data', function (chunk) { data += chunk; }); throw new Error('expected error'); }); var port = 3000; server.listen(port); log.info({ port: port }, 'listening');
import React from 'react'; import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import EmailField from '../EmailField'; // EmailField // props: inputId // behavior: renders a <Field /> component // test: renders a <Field /> component describe('<EmailField />', () => { it('should render a Field component', () => { let wrapper = shallow(<EmailField inputId='testField'/>); expect(toJson(wrapper)).toMatchSnapshot(); }); });
import Ember from 'ember'; export default Ember.Component.extend({ actions: { addFavorite() { this.sendAction('addFavorite', this.get('newFavorite')); } } });
(function ($) { 'use strict'; // Device check for limiting resize handling. var IS_DEVICE = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); function FullHeight(el, options) { this.el = $(el); var data = {}; $.each(this.el.data(), function (attr, value) { if (/^fullheight/.test(attr)) { var key = attr.replace('fullheight', '').toLowerCase(); data[key] = value; } }); options = $.extend({}, FullHeight.defaults, options, data); this.debug = options.debug; this.container = $(options.container); this.property = options.property; this.propertyBefore = this.el.css(this.property); // Chrome for Android resizes the browser a lot when scrolling due to the address bar collapsing. // This causes a lot of arbitrary layout jumps and slow image resize operations with this plugin. // So for device UA where height should not change, we only update if the width changes as well (f.ex. // orientation changes). this.allowDeviceHeightResize = !( options.allowDeviceHeightResize === null || options.allowDeviceHeightResize === false || options.allowDeviceHeightResize === 'false' ); this.lastWidth = this.container.innerWidth(); this.timerResize = 0; this.container.on('resize.yrkup3.fullheight', $.proxy(this, '_onResize')); this.update(); } FullHeight.defaults = { debug: false, allowDeviceHeightResize: false, container: window, property: 'min-height' }; FullHeight.prototype._onResize = function () { var newWidth = this.container.innerWidth(); var allowResize = !IS_DEVICE || this.allowDeviceHeightResize || newWidth !== this.lastWidth; // Do the update if expected. if (allowResize) { var root = this; clearTimeout(this.timerResize); this.timerResize = setTimeout(function () { root.update(); }, 200); } this.lastWidth = newWidth; }; FullHeight.prototype.update = function () { if (this.debug) { console.log('update', this.el); } var newHeight; var offset = this.container.offset(); if (typeof offset == 'undefined') { newHeight = $(window).innerHeight(); } else { newHeight = this.container.innerHeight() - (this.el.offset().top - offset.top); } if (newHeight !== this.lastHeight) { if (this.debug) { console.log('set `' + this.property + '` to ' + newHeight); } this.el.css(this.property, newHeight); this.lastHeight = newHeight; } }; FullHeight.prototype.dispose = function () { if (this.debug) { console.log('dispose'); } this.container.off('.yrkup3.fullheight'); this.el.css(this.property, this.propertyBefore); }; $.fn.fullheight = function (options) { this.each(function () { var el = $(this); // Store data var data = el.data('yrkup3.fullheight'); if (!data) { el.data('yrkup3.fullheight', (data = new FullHeight(el, options))); } // Run command if (typeof options == 'string') { data[options](); } }); return this; }; })(jQuery);
var _ = require('lodash'), restify = require('restify'), async = require('async'); module.exports = function(settings, server, db){ var globalLogger = require(settings.path.root('logger')); var auth = require(settings.path.lib('auth'))(settings, db); var api = require(settings.path.lib('api'))(settings, db); var vAlpha = function(path){ return {path: path, version: settings.get("versions:alpha")} }; function context(req){ return {logger: req.log}; } server.get(vAlpha('/ping'), function(req, res, next){ res.json(); next(); }); /** * API to create or update an email template. If a template exists (accountId + Name pair), it will be updated. Otherwise a new one will be created */ server.post(vAlpha('/email/:name'), auth, function(req, res, next){ var logger = req.log || globalLogger; var params = req.params; if (!params || !params.name || !params.htmlData || !params.htmlType || !params.cssData || !params.cssType){ var err = new restify.BadRequestError("Invalid arguments"); logger.info(err, params); return res.send(err); } api.email.createOrUpdate.call(context(req), params.accountId, params.name, params.htmlData, params.htmlType, params.cssData, params.cssType, function(err){ if (err) { logger.error(err); res.send(new restify.InternalServerError("Something went wrong")); } else { res.json(); } next(); }); }); server.put(vAlpha('/trigger/:name/on/event'), auth, function(req, res, next){ var logger = req.log || globalLogger; var params = req.params; if (!params.accountId || !params.name || !params.actionId || !params.eventName) { var err = new restify.BadRequestError("Invalid arguments"); logger.info(err, params); return res.send(err); } var eventCondition = { name: params.eventName, attrs: params.eventAttrs }; api.trigger.create.call(context(req), params.accountId, params.name, eventCondition, null, params.actionId, function(err, triggerDoc){ if (err){ logger.error(err); res.send(new restify.InternalServerError("Something went wrong")); } else { res.json({id: triggerDoc.id}) } next(); }) }); server.put(vAlpha('/trigger/:name/on/time'), auth, function(req, res, next){ var logger = req.log || globalLogger; var params = req.params; if (!params.accountId || !params.name || !params.actionId || (!params.next && !params.every)) { var err = new restify.BadRequestError("Invalid arguments"); logger.info(err, params); return res.send(err); } var timeCondition = { next: params.next, every: params.every }; api.trigger.create.call(context(req), params.accountId, params.name, null, timeCondition, params.actionId, function(err, triggerDoc){ if (err){ logger.error(err); res.send(new restify.InternalServerError("Something went wrong")); } else { res.json({id: triggerDoc.id}) } next(); }) }); server.post(vAlpha('/event/:name'), auth, function(req, res, next){ var logger = req.log || globalLogger; var params = req.params; if (!params.accountId || !params.name || !params.userId){ var err = restify.BadRequestError("Invalid Arguments"); logger.info(err, params); return res.send(err); } api.event.add.call(context(req), params.accountId, params.name, params.userId, params.attrs, function(err){ if (err){ logger.error(err); res.send(new restify.InternalServerError("Something went wrong")); } else { res.send(); } next(); }); }); };
// Description: // There are two lists of different length. The first one consists of keys, // the second one consists of values. Write a function //createDict(keys, values) that returns a dictionary created from keys and // values. If there are not enough values, the rest of keys should have a //None (JS null)value. If there not enough keys, just ignore the rest of values. // Example 1: // keys = ['a', 'b', 'c', 'd'] // values = [1, 2, 3] // createDict(keys, values) // returns {'a': 1, 'b': 2, 'c': 3, 'd': null} // Example 2: // keys = ['a', 'b', 'c'] // values = [1, 2, 3, 4] // createDict(keys, values) // returns {'a': 1, 'b': 2, 'c': 3} function createDict(keys, values){ var result = {}; for(var i = 0;i<keys.length;i++){ result[keys[i]] = values[i]!=undefined ? values[i] : null; } return result; }
"use strict"; const { ParserError } = require("../util/errors"); const yaml = require("js-yaml"); module.exports = { /** * The order that this parser will run, in relation to other parsers. * * @type {number} */ order: 200, /** * Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects. * * @type {boolean} */ allowEmpty: true, /** * Determines whether this parser can parse a given file reference. * Parsers that match will be tried, in order, until one successfully parses the file. * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case * every parser will be tried. * * @type {RegExp|string[]|function} */ canParse: [".yaml", ".yml", ".json"], // JSON is valid YAML /** * Parses the given file as YAML * * @param {object} file - An object containing information about the referenced file * @param {string} file.url - The full URL of the referenced file * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver * @returns {Promise} */ async parse (file) { // eslint-disable-line require-await let data = file.data; if (Buffer.isBuffer(data)) { data = data.toString(); } if (typeof data === "string") { try { return yaml.load(data); } catch (e) { throw new ParserError(e.message, file.url); } } else { // data is already a JavaScript value (object, array, number, null, NaN, etc.) return data; } } };
define([ 'jquery', 'underscore', 'backbone', 'collections/users/students', 'collections/users/classes', 'collections/users/streams', 'text!templates/students/studentnew.html', 'text!templates/students/classes.html', 'text!templates/students/streams.html', 'jqueryui', 'bootstrap' ], function($, _, Backbone, Students, Classes, Streams, StudentTpl, classesTpl, streamsTpl){ var NewStudent = Backbone.View.extend({ tagName: 'div', title: "New Student - Student Information System", events: { 'submit form#new-student' : 'addStudent', 'change #class_id' : 'getStreams' }, template: _.template(StudentTpl), classesTpl: _.template(classesTpl), streamsTpl: _.template(streamsTpl), initialize: function(){ $("title").html(this.title); //fetch list of all classes for this class from the database var self = this; Classes.fetch({ data: $.param({ token: tokenString }), success: function(data){ self.setClasses(); } }); //fetch list of all streams for this client from the database Streams.fetch({ data: $.param({ token: tokenString }) }); }, render: function(){ this.$el.html(this.template()); this.$classes = this.$("#classes-list"); this.$streams = this.$("#streams-list"); return this; }, addStudent: function(evt){ evt.preventDefault(); var student = { reg_number: $("#reg_number").val(), first_name: $("#first_name").val(), middle_name: $("#middle_name").val(), last_name: $("#last_name").val(), dob: $("#dob").val(), pob: $("#pob").val(), bcn: $("#bcn").val(), sex: $("#sex").val(), nationality: $("#nationality").val(), doa: $("#doa").val(), class_id: $("#class_id").val(), stream_id: ($("#stream_id").val()) ? $("#stream_id").val() : '', address: $("#address").val(), code: $("#code").val(), town: $("#town").val(), pg_f_name: $("#pg_f_name").val(), pg_l_name: $("#pg_l_name").val(), pg_email: $("#pg_email").val(), pg_phone: $("#pg_phone").val() }; $(".submit-button").html("Please wait..."); $(".error-message").hide(200); $(".success-message").hide(200); Students.create(student, { url: baseURL + 'students/students?token=' + tokenString, success: function(){ $(".success-message").html("Student added successfully!").show(400); $(".submit-button").html('<i class="fa fa-fw fa-check"></i>Save'); //empty the form $("#reg_number").val(''), $("#first_name").val(''), $("#middle_name").val(''), $("#last_name").val(''), $("#dob").val(''), $("#pob").val(''), $("#bcn").val(''), $("#sex").val(''), $("#nationality").val(''), $("#doa").val(''), $("#class_id").val(''), $("#stream_id").val(''), $("#address").val(''), $("#code").val(''), $("#town").val(''), $("#pg_f_name").val(''), $("#pg_l_name").val(''), $("#pg_email").val(''), $("#pg_phone").val('') }, error : function(jqXHR, textStatus, errorThrown) { if(textStatus.status != 401 && textStatus.status != 403) { $(".error-message").html("Please check the errors below!").show(400); $(".submit-button").html('<i class="fa fa-fw fa-check"></i>Save'); } } }); }, setClasses: function(){ this.$classes.empty(); var regClasses = []; Classes.each(function(oneClass){ regClasses.push(oneClass.toJSON()); }, this); this.$classes.html(this.classesTpl({ regClasses: regClasses })); }, getStreams: function(){ var classID = $("#class_id").val(); var regStreams = []; var streams = Streams.where({ class_id: classID }); $.each(streams, function(key, oneStream){ regStreams.push(oneStream.toJSON()); }); this.$streams.html(this.streamsTpl({ regStreams: regStreams })); } }); return NewStudent; });
var express = require('express'); var user = require('../model/user'); var jsonReturn = require('../common/jsonReturn'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res, next) { user.getUsers(function(err, rows, fields){ res.render('users', { users : rows } ); }) }); router.post('/getUsers', function (req, res, next) { if(req.body.username){ user.getUsers(function(err, rows, fields){ res.json(jsonReturn({ users : rows } )); }) } }); module.exports = router;
import { createAction } from 'redux-actions'; import { APP_LAYOUT_CHANGE, APP_LAYOUT_INIT } from './constants'; // 选中菜单列表项 const appLayoutInit = createAction(APP_LAYOUT_INIT); export const onAppLayoutInit = (key) => { return (dispatch) => { dispatch(appLayoutInit(key)); }; }; const appLayoutChange = createAction(APP_LAYOUT_CHANGE); export const onAppLayoutChange = (key) => { return (dispatch) => { dispatch(appLayoutChange(key)); }; };
// Init express server var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var server = require('http').Server(app); server.listen(3000); console.log("started listenning on port 3000"); // Subscribe to lexa's router stream and update the LED accordingly // var onoff = require('onoff'); // var Gpio = onoff.Gpio; // var led = new Gpio(18, 'out'); var sio = require('socket.io-client'); var socket = sio.connect('http://lexa.tuscale.ro'); // socket.on('message', function(msg) { // console.log('Got a new message from the router:', msg); // var jMsg = JSON.parse(msg); // var newLedState = jMsg.led; // led.writeSync(newLedState); // }); // Init firebase var firebase = require('firebase'); var io = require('socket.io')(server); var firebase_app = firebase.initializeApp({ apiKey: "AIzaSyB3ZvJDuZ2HD-UppgPvY2by-GI0KnessXw", authDomain: "rlexa-9f1ca.firebaseapp.com", databaseURL: "https://rlexa-9f1ca.firebaseio.com", projectId: "rlexa-9f1ca", storageBucket: "rlexa-9f1ca.appspot.com", messagingSenderId: "161670508523" }); var db = firebase.database(); app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // Init NFC serial link // var SerialPort = require('serialport'); // SerialPort.list(function (err, ports) { // ports.forEach(function (port) { // console.log(port.comName); // }); // }); // var port = new SerialPort('/dev/ttyACM0', { // baudRate: 9600, // parser: SerialPort.parsers.readline("\r\n") // }); // port.on('open', function () { // console.log('open'); // }); // // Monitor NFC activity // port.on('data', function (data) { // var tagID = data.split(' ').join(''); // console.log(data.split(' ')); // tagID = tagID.substring(0, tagID.length - 1); // console.log(tagID + " scanned ..."); // db.ref("card/" + tagID).once("value", function(cardOwnerSnap) { // var cardOwnerName = cardOwnerSnap.child('name').val(); // if (cardOwnerName) { // db.ref('authed').set(cardOwnerName); // } // }); // // Notify our web-clients that a tag was scanned // io.sockets.emit('idscanned', { cardid: tagID }); // }); io.on('connection', function (socket) { console.log('Web client connected.'); }); // Define web-facing endpoints for managing the users app.post('/add_user', function (req, res) { var currentUser = { name: req.body.name, led: req.body.led, id: req.body.id }; var updates = {}; updates['card/' + currentUser.id] = { name: currentUser.name, led: currentUser.led }; updates['users/' + currentUser.name] = currentUser; return firebase.database().ref().update(updates); }); app.get('/get_users', function (req, res) { firebase.database().ref().once('value', function (snap) { var dataUsers = snap.child("users"); res.send(dataUsers); }); }); app.get('/get_authed', function (req, res) { db.ref().once('value', function (snap) { var isUserLogged = snap.child("authed/Mike").val(); console.log(isUserLogged); if (isUserLogged) { var userData = snap.child("users/Mike/led") console.log(parseInt(userData.val())); } }) var name = "BLAH"; name = name.toLowerCase(); name = name.charAt(0).toUpperCase() + name.slice(1); res.send(name); }); // Monitor process termination and do cleanups // process.on('SIGINT', function () { // led.writeSync(0); // led.unexport(); // process.exit(); // }); // db.ref('authed').once('value', function (snap) { // var lastScannedTagOwner = snap.val(); // if (lastScannedTagOwner) { // // Valid tag present // request({ // url: 'http://lexa.tuscale.ro/publish', // method: 'POST', // json: { led: (stateName === "on" ? 1 : 0) } // }, // function (error, response, body) { // if (error) { // return console.error('upload failed:', error); // } // // Delete scanned tag and notify user of successfull op // db.ref('authed').remove(); // that.emit(':tell', 'Hi ' + lastScannedTagOwner + '! Turning ' + stateName + ' the LED!'); // console.log('Upload successful! Server responded with:', body) // } // ); // } else { // that.emit(':tell', 'Please scan your tag and try again.'); // } // });
// fetch() polyfill for making API calls. import 'whatwg-fetch'; // Object.assign() is commonly used with React. // It will use the native implementation if it's present and isn't buggy. import objectAssign from 'object-assign'; Object.assign = objectAssign;
// getPostsParameters gives an object containing the appropriate find and options arguments for the subscriptions's Posts.find() getPostsParameters = function (terms) { var maxLimit = 200; // console.log(terms) // note: using jquery's extend() with "deep" parameter set to true instead of shallow _.extend() // see: http://api.jquery.com/jQuery.extend/ // initialize parameters by extending baseParameters object, to avoid passing it by reference var parameters = deepExtend(true, {}, viewParameters.baseParameters); // if view is not defined, default to "top" var view = !!terms.view ? dashToCamel(terms.view) : 'top'; // get query parameters according to current view if (typeof viewParameters[view] !== 'undefined') parameters = deepExtend(true, parameters, viewParameters[view](terms)); // extend sort to sort posts by _id to break ties deepExtend(true, parameters, {options: {sort: {_id: -1}}}); // if a limit was provided with the terms, add it too (note: limit=0 means "no limit") if (typeof terms.limit !== 'undefined') _.extend(parameters.options, {limit: parseInt(terms.limit)}); // limit to "maxLimit" posts at most when limit is undefined, equal to 0, or superior to maxLimit if(!parameters.options.limit || parameters.options.limit == 0 || parameters.options.limit > maxLimit) { parameters.options.limit = maxLimit; } // hide future scheduled posts unless "showFuture" is set to true or postedAt is already defined if (!parameters.showFuture && !parameters.find.postedAt) parameters.find.postedAt = {$lte: new Date()}; // console.log(parameters); return parameters; }; getUsersParameters = function(filterBy, sortBy, limit) { var find = {}, sort = {createdAt: -1}; switch(filterBy){ case 'invited': // consider admins as invited find = {$or: [{isInvited: true}, adminMongoQuery]}; break; case 'uninvited': find = {$and: [{isInvited: false}, notAdminMongoQuery]}; break; case 'admin': find = adminMongoQuery; break; } switch(sortBy){ case 'username': sort = {username: 1}; break; case 'karma': sort = {karma: -1}; break; case 'postCount': sort = {postCount: -1}; break; case 'commentCount': sort = {commentCount: -1}; case 'invitedCount': sort = {invitedCount: -1}; } return { find: find, options: {sort: sort, limit: limit} }; };
// ==UserScript== // @name Kiss Simple Infobox hider // @description Hides the infobox on kissanime.com, kisscartoon.me and kissasian.com player sites // @include https://kissanime.ru/Anime/*/* // @include https://kimcartoon.to/Cartoon/*/* // @include https://kissasian.sh/Drama/*/* // @author Playacem // @updateURL https://raw.githubusercontent.com/Playacem/KissScripts/master/kiss-simple-infobox-hider/kiss-simple-infobox-hider.user.js // @downloadURL https://raw.githubusercontent.com/Playacem/KissScripts/master/kiss-simple-infobox-hider/kiss-simple-infobox-hider.user.js // @require https://code.jquery.com/jquery-latest.js // @grant none // @run-at document-end // @version 0.0.11 // ==/UserScript== // do not change var JQ = jQuery; function hideInfobox() { var selector = JQ('#centerDivVideo') /* the div with the video */ .prev() /*a clear2 div*/ .prev() /*dropdown*/ .prev() /*a clear2 div*/ .prev(); /*the actual div*/ selector.remove(); } // load after 2 seconds setTimeout(hideInfobox, 2000);
'use strict'; const fs = require('fs'); const Q = require('q'); const exec = require('child_process').exec; const searchpaths = ["/bin/xset"]; class XSetDriver { constructor(props) { this.name = "Backlight Control"; this.devicePath = "xset"; this.description = "Screensaver control via Xwindows xset command"; this.devices = []; this.driver = {}; //this.depends = []; } probe(props) { searchpaths.forEach(function(p) { if(fs.existsSync(p)) { let stat = fs.lstatSync(p); if (stat.isFile()) { console.log("found xset control at "+p); this.devices.push(new XSetDriver.Channel(this, p, props)); } } }.bind(this)); return this.devices.length>0; } } class XSetChannel { constructor(driver, path, props) { this.value = 1; this.setCommand = path; this.enabled = true; this.display = ":0.0"; this.error = 0; // internal variables this.lastReset = new Date(); } enable() { this.set("on"); } disable() { this.set("off"); } activate() { this.set("activate"); } blank() { this.set("blank"); } reset() { this.set("reset"); this.lastReset=new Date(); } setTimeout(secs) { this.set(""+secs); } set(action) { if(!this.enabled) return false; var ss = this; exec("DISPLAY="+this.display+" "+this.setCommand+" s "+action, function(error,stdout, stderr) { if(error) { if(ss.error++ >10) { ss.enabled=false; } console.log("xset error "+error); console.log(stdout); console.log("errors:"); console.log(stderr); } }.bind(this)); } } XSetDriver.Channel = XSetChannel; module.exports = XSetDriver; /* Treadmill.prototype.init_screensaver = function(action) { this.screensaver = { // config/settings enabled: !simulate, display: ":0.0", error: 0, // internal variables lastReset: new Date(), // screensaver functions enable: function() { this.set("on"); }, disable: function() { this.set("off"); }, activate: function() { this.set("activate"); }, blank: function() { this.set("blank"); }, reset: function() { this.set("reset"); this.lastReset=new Date(); }, timeout: function(secs) { this.set(""+secs); }, // main set() function calls command "xset s <action>" set: function(action) { if(!this.enabled) return false; var ss = this; exec("DISPLAY="+this.display+" xset s "+action, function(error,stdout, stderr) { if(error) { if(ss.error++ >10) { ss.enabled=false; } console.log("xset error "+error); console.log(stdout); console.log("errors:"); console.log(stderr); } }); } }; if(simulate) return false; // initialize the screensaver var ss = this.screensaver; exec("./screensaver.conf "+this.screensaver.display, function(error,stdout, stderr) { if(error) { ss.enabled = false; console.log("screensaver.conf error "+error); console.log(stdout); console.log("errors:"); console.log(stderr); } }); this.screensaver.enable(); } */
var fs = require("fs"); var longStr = (new Array(10000)).join("welefen"); while(true){ fs.writeFileSync("1.txt", longStr); }
/** * Copyright (c) 2011 Bruno Jouhier <bruno.jouhier@sage.com> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ "use strict"; var fs = require("fs"); var path = require("path"); var compile = require("./compile"); var registered = false; var _options = {}; /// !doc /// /// # streamline/lib/compiler/register /// /// Streamline `require` handler registration /// /// * `register.register(options)` /// Registers `require` handlers for streamline. /// `options` is a set of default options passed to the `transform` function. exports.register = function(setoptions) { if (registered) return; _options = setoptions || {}; registered = true; var pModule = require('module').prototype; var orig = pModule._compile; pModule._compile = function(content, filename) { content = compile.transformModule(content, filename, _options); return orig.call(this, content, filename); } }; var dirMode = parseInt('777', 8); exports.trackModule = function(m, options) { if (registered) throw new Error("invalid call to require('streamline/module')"); m.filename = m.filename.replace(/\\/g, '/'); var tmp = m.filename.substring(0, m.filename.lastIndexOf('/')); tmp += '/tmp--' + Math.round(Math.random() * 1e9) + path.extname(m.filename); //console.error("WARNING: streamline not registered, re-loading module " + m.filename + " as " + tmp); exports.register({}); fs.writeFileSync(tmp, fs.readFileSync(m.filename, "utf8"), "utf8"); process.on('exit', function() { try { fs.unlinkSync(tmp); } catch (ex) {} }) m.exports = require(tmp); return false; } Object.defineProperty(exports, "options", { enumerable: true, get: function() { return _options; } });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DropdownMenuItemType; (function (DropdownMenuItemType) { DropdownMenuItemType[DropdownMenuItemType["Normal"] = 0] = "Normal"; DropdownMenuItemType[DropdownMenuItemType["Divider"] = 1] = "Divider"; DropdownMenuItemType[DropdownMenuItemType["Header"] = 2] = "Header"; })(DropdownMenuItemType = exports.DropdownMenuItemType || (exports.DropdownMenuItemType = {})); //# sourceMappingURL=Dropdown.Props.js.map
/** * Export exceptions * @type {Object} */ module.exports = { Schema: require('./Schema'), Value: require('./Value') }
var express = require('express'); var userRouter = express.Router(); var passport = require('passport'); var Model = require('../models/user'); var authenticate = require('./auth'); /* GET all the users */ exports.getAll = function(req, res, next) { Model.Users.forge() .fetch({ columns: ['_id', 'username', 'admin'] }) .then(function(user) { res.json(user); }).catch(function(err) { console.log(err); }); }; /* GET a user given its id */ exports.getUser = function(req, res, next) { var userID = req.params.userID; Model.User.forge({'_id':userID}) .fetch({columns:['_id', 'username', 'admin']}) .then(function (user) { res.json(user); }); }; /* PUT update a user given its id */ exports.updateUser = function(req, res, next) { var userID = req.params.userID; Model.User.forge({'_id':userID}) .fetch({columns:['_id', 'username', 'admin']}) .then(function (user) { res.json(user); }); }; /* GET logout */ exports.signOut = function(req, res){ req.logout(); res.status(200).json({message: 'Login user out'}); }; /* POST login. */ exports.signIn = function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err) { return next(err); } if (!user) { return res.status(401).json({ err: info }); } return req.logIn(user, function(err) { if (err) { console.log(err); return res.status(500).json({ error: 'Could not log in user' }); } var token = authenticate.getToken(user); res.status(200).json({ status: 'Login successful', succes: true, token: token }); }); })(req, res, next); }; /* POST Register. */ exports.signUp = function(req, res, next) { var userData = req.body; Model.User.forge({ username: userData.username }).fetch() //see if user already exists .then(function(user) { if (user) { return res.status(400).json({ title: 'signup', errorMessage: 'That username already exists' }); } else { //User does not existe, lets add it var signUpUser = Model.User.forge({ username: userData.username, password: userData.password, admin: false }); signUpUser.save() .then(function(user) { var result = 'User ' + user.get('username') + ' created.'; return res.status(200).json({ message: result, user: { id: user.get('id'), username: user.get('username'), } }); }); } }); };
import Float from 'ember-advanced-form/components/float'; export default Float;
document.getElementsByTagName('body')[0].style.overflow = 'hidden'; window.scrollTo(70, 95);
var url = args.url; var limit = args.limitl; var defaultWaitTime = Number(args.wait_time_for_polling) uuid = executeCommand('urlscan-submit-url-command', {'url': url})[0].Contents; uri = executeCommand('urlscan-get-result-page', {'uuid': uuid})[0].Contents; var resStatusCode = 404 var waitedTime = 0 while(resStatusCode == 404 && waitedTime < Number(args.timeout)) { var resStatusCode = executeCommand('urlscan-poll-uri', {'uri': uri})[0].Contents; if (resStatusCode == 200) { break; } wait(defaultWaitTime); waitedTime = waitedTime + defaultWaitTime; } if(resStatusCode == 200) { return executeCommand('urlscan-get-http-transaction-list', {'uuid': uuid, 'url': url, 'limit': limit}); } else { if(waitedTime >= Number(args.timeout)){ return 'Could not get result from UrlScan, please try to increase the timeout.' } else { return 'Could not get result from UrlScan, possible rate-limit issues.' } }
define(function (require) { require('plugins/timelion/directives/expression_directive'); const module = require('ui/modules').get('kibana/timelion_vis', ['kibana']); module.controller('TimelionVisParamsController', function ($scope, $rootScope) { $scope.vis.params.expression = $scope.vis.params.expression || '.es(*)'; $scope.vis.params.interval = $scope.vis.params.interval || '1m'; $scope.search = function () { $rootScope.$broadcast('courier:searchRefresh'); }; }); });
(function() { 'use strict'; angular.module('newApp') .controller('newAppCtrl', newAppCtrl); function newAppCtrl() { } })();
let upath = require('upath'), through2 = require('through2'), paths = require('../../project.conf.js').paths, RegexUtil = require('../util/RegexUtil'); module.exports = class StreamReplacer { constructor(replacements = {}) { this.replacements = replacements; } /** * Add a transform to the replacer. A transform is a function that takes a vinyl file from the stream as a * parameter and returns the path to be used as a replacement for that file. * * This function is called for each file present in the stream. * * @param transformFn(file) * * @returns {through2} */ push(transformFn) { let that = this; return through2.obj(function (file, enc, flush) { let dir = upath.dirname(upath.relative(paths.src(), file.path)), ext = upath.extname(file.path), name = upath.basename(file.path, ext); that.replacements[transformFn(file)] = new RegExp(RegexUtil.escape(upath.join(dir, name + ext)).replace(/ /g, '(?: |%20)'), 'g'); this.push(file); flush(); }); } /** * Search and replace all files in the stream with values according to the transforms configured via `push()`. * * @returns {through2} */ replace() { let that = this; return through2.obj(function (file, enc, flush) { Object.keys(that.replacements).forEach((replacement) => { file.contents = new Buffer(String(file.contents).replace(that.replacements[replacement], replacement)); }); this.push(file); flush(); }); } };
"use strict"; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), interval: 200, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: false, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, node: true, es5: true, strict: true, globalstrict: true }, files: { src: ['Gruntfile.js', 'package.json', 'lib/*.js', 'lib/controllers/**/*.js', 'lib/models/**/*.js', 'lib/utils/**/*.js', 'demo/*.js'] } }, watch: { files: ['<%= jshint.files.src %>'], tasks: ['default'] } }); // npm tasks grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-jshint'); // Default task. grunt.registerTask('default', ['jshint']); };
//borrowed from stefanocudini bootstrap-list-filter (function($) { $.fn.btsListFilterContacts = function(inputEl, options) { var searchlist = this, searchlist$ = $(this), inputEl$ = $(inputEl), items$ = searchlist$, callData, callReq; //last callData execution function tmpl(str, data) { return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) { return data[key] || ''; }); } function debouncer(func, timeout) { var timeoutID; timeout = timeout || 300; return function () { var scope = this , args = arguments; clearTimeout( timeoutID ); timeoutID = setTimeout( function () { func.apply( scope , Array.prototype.slice.call( args ) ); }, timeout); }; } options = $.extend({ delay: 300, minLength: 1, initial: true, eventKey: 'keyup', resetOnBlur: true, sourceData: null, sourceTmpl: '<a class="list-group-item" href="#"><tr><h3><span>{title}</span></h3></tr></a>', sourceNode: function(data) { return tmpl(options.sourceTmpl, data); }, emptyNode: function(data) { return '<a class="list-group-item well" href="#"><span>No Results</span></a>'; }, itemEl: '.list-group-item', itemChild: null, itemFilter: function(item, val) { //val = val.replace(new RegExp("^[.]$|[\[\]|()*]",'g'),''); //val = val.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); val = val && val.replace(new RegExp("[({[^.$*+?\\\]})]","g"),''); var text = $.trim($(item).text()), i = options.initial ? '^' : '', regSearch = new RegExp(i + val,'i'); return regSearch.test( text ); } }, options); inputEl$.on(options.eventKey, debouncer(function(e) { var val = $(this).val(); console.log(val); if(options.itemEl) items$ = searchlist$.find(options.itemEl); if(options.itemChild) items$ = items$.find(options.itemChild); var contains = items$.filter(function(){ return options.itemFilter.call(searchlist, this, val); }), containsNot = items$.not(contains); if (options.itemChild){ contains = contains.parents(options.itemEl); containsNot = containsNot.parents(options.itemEl).hide(); } if(val!=='' && val.length >= options.minLength) { contains.show(); containsNot.hide(); if($.type(options.sourceData)==='function') { contains.hide(); containsNot.hide(); if(callReq) { if($.isFunction(callReq.abort)) callReq.abort(); else if($.isFunction(callReq.stop)) callReq.stop(); } callReq = options.sourceData.call(searchlist, val, function(data) { callReq = null; contains.hide(); containsNot.hide(); searchlist$.find('.bts-dynamic-item').remove(); if(!data || data.length===0) $( options.emptyNode.call(searchlist) ).addClass('bts-dynamic-item').appendTo(searchlist$); else for(var i in data) $( options.sourceNode.call(searchlist, data[i]) ).addClass('bts-dynamic-item').appendTo(searchlist$); }); } else if(contains.length===0) { $( options.emptyNode.call(searchlist) ).addClass('bts-dynamic-item').appendTo(searchlist$); } } else { contains.show(); containsNot.show(); searchlist$.find('.bts-dynamic-item').remove(); } }, options.delay)); if(options.resetOnBlur) inputEl$.on('blur', function(e) { $(this).val('').trigger(options.eventKey); }); return searchlist$; }; })(jQuery);
/*! * jquery.initialize. An basic element initializer plugin for jQuery. * * Copyright (c) 2014 Barış Güler * http://hwclass.github.io * * Licensed under MIT * http://www.opensource.org/licenses/mit-license.php * * http://docs.jquery.com/Plugins/Authoring * jQuery authoring guidelines * * Launch : July 2014 * Version : 0.1.0 * Released: July 29th, 2014 * * * makes an element initialize for defined events with their names */ (function ($) { $.fn.initialize = function (options) { var currentElement = $(this), opts = options; var getSize = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; var setEvents = function () { for (var countForEventsObj = 0, len = getSize(opts.events); countForEventsObj < len; countForEventsObj++) { $(this).on(opts.events[countForEventsObj].name, opts.events[countForEventsObj].funcBody) } } if (opts.init) { setEvents(); } return this; } })(jQuery);
/** * utility library */ var basicAuth = require('basic-auth'); var fs = require('fs'); /** * Simple basic auth middleware for use with Express 4.x. * * @example * app.use('/api-requiring-auth', utils.basicAuth('username', 'password')); * * @param {string} username Expected username * @param {string} password Expected password * @returns {function} Express 4 middleware requiring the given credentials */ exports.basicAuth = function(username, password) { return function(req, res, next) { var user = basicAuth(req); if (!user || user.name !== username || user.pass !== password) { res.set('WWW-Authenticate', 'Basic realm=Authorization Required'); return res.sendStatus(401); } next(); }; }; exports.cpuTemp = function() { var cputemp = Math.round(((parseFloat(fs.readFileSync("/sys/class/thermal/thermal_zone0/temp"))/1000) * (9/5) + 32)*100)/100; return cputemp; }; exports.w1Temp = function(serial) { var temp; var re=/t=(\d+)/; try { var text=fs.readFileSync('/sys/bus/w1/devices/' + serial + '/w1_slave','utf8'); if (typeof(text) != "undefined") { if (text.indexOf("YES") > -1) { var temptext=text.match(re); if (typeof(temptext) != "undefined") { temp = Math.round(((parseFloat(temptext[1])/1000) * (9/5) + 32)*100)/100; } } } } catch (e) { console.log(e); } return temp; };
version https://git-lfs.github.com/spec/v1 oid sha256:5f5740cfcc24e2a730f7ea590ae0dc07d66d256fd183c46facf3fdfeb0bd69d2 size 3654
version https://git-lfs.github.com/spec/v1 oid sha256:467bccdb74ef62e6611ba27f338a0ba0c49ba9a90ef1facb394c14de676318cf size 1150464
version https://git-lfs.github.com/spec/v1 oid sha256:4f8b1998d2048d6a6cabacdfb3689eba7c9cb669d6f81dbbd18156bdb0dbe18f size 1880
import React from 'react' import { FormControl } from 'react-bootstrap' import './@FilterListInput.css' const FilterListInput = ({onFilter, searchValue}) => { let handleFilter = e => { onFilter(e.target.value) } return (<FormControl className='FilterListInput' type='text' defaultValue={searchValue} placeholder='Search within this list...' onChange={handleFilter.bind(this)} />) } export default FilterListInput
/*! * ear-pipe * Pipe audio streams to your ears * Dan Motzenbecker <dan@oxism.com> * MIT Licensed */ "use strict"; var spawn = require('child_process').spawn, util = require('util'), Duplex = require('stream').Duplex, apply = function(obj, method, args) { return obj[method].apply(obj, args); } var EarPipe = function(type, bits, transcode) { var params; if (!(this instanceof EarPipe)) { return new EarPipe(type, bits, transcode); } Duplex.apply(this); params = ['-q', '-b', bits || 16, '-t', type || 'mp3', '-']; if (transcode) { this.process = spawn('sox', params.concat(['-t', typeof transcode === 'string' ? transcode : 'wav', '-'])); } else { this.process = spawn('play', params); } } util.inherits(EarPipe, Duplex); EarPipe.prototype._read = function() { return apply(this.process.stdout, 'read', arguments); } EarPipe.prototype._write = function() { return apply(this.process.stdin, 'write', arguments); } EarPipe.prototype.pipe = function() { return apply(this.process.stdout, 'pipe', arguments); } EarPipe.prototype.end = function() { return apply(this.process.stdin, 'end', arguments); } EarPipe.prototype.kill = function() { return apply(this.process, 'kill', arguments); } module.exports = EarPipe;
/** * @description - The purpose of this model is to lookup various Drinking activities for a user */ var baseModel = require('./base'); var Drink; Drink = baseModel.Model.extend({ tableName: 'drink' }); module.exports = baseModel.model('Drink', Drink);
module.exports = { root: true, parser: 'babel-eslint', parserOptions: { sourceType: 'module', ecmaFeatures: { 'jsx': true }, }, globals: { enz: true, xhr_calls: true, }, plugins: [ 'react' ], extends: 'react-app', rules: { 'semi': [2, 'never'], // allow paren-less arrow functions 'arrow-parens': 0, // allow async-await 'generator-star-spacing': 2, // allow debugger during development 'no-debugger': 2, 'comma-danglcd e': 0, 'camelcase': 0, 'no-alert': 2, 'space-before-function-paren': 2, 'react/jsx-uses-react': 2, 'react/jsx-uses-vars': 2, } }
define(['jquery'], function ($) { if (!Array.prototype.reduce) { /** * Array.prototype.reduce polyfill * * @param {Function} callback * @param {Value} [initialValue] * @return {Value} * * @see http://goo.gl/WNriQD */ Array.prototype.reduce = function (callback) { var t = Object(this), len = t.length >>> 0, k = 0, value; if (arguments.length === 2) { value = arguments[1]; } else { while (k < len && !(k in t)) { k++; } if (k >= len) { throw new TypeError('Reduce of empty array with no initial value'); } value = t[k++]; } for (; k < len; k++) { if (k in t) { value = callback(value, t[k], k, t); } } return value; }; } if ('function' !== typeof Array.prototype.filter) { /** * Array.prototype.filter polyfill * * @param {Function} func * @return {Array} * * @see http://goo.gl/T1KFnq */ Array.prototype.filter = function (func) { var t = Object(this), len = t.length >>> 0; var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; if (func.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } var isSupportAmd = typeof define === 'function' && define.amd; /** * @class core.agent * * Object which check platform and agent * * @singleton * @alternateClassName agent */ var agent = { /** @property {Boolean} [isMac=false] true if this agent is Mac */ isMac: navigator.appVersion.indexOf('Mac') > -1, /** @property {Boolean} [isMSIE=false] true if this agent is a Internet Explorer */ isMSIE: navigator.userAgent.indexOf('MSIE') > -1 || navigator.userAgent.indexOf('Trident') > -1, /** @property {Boolean} [isFF=false] true if this agent is a Firefox */ isFF: navigator.userAgent.indexOf('Firefox') > -1, /** @property {String} jqueryVersion current jQuery version string */ jqueryVersion: parseFloat($.fn.jquery), isSupportAmd: isSupportAmd, isW3CRangeSupport: !!document.createRange }; return agent; });
ml.module('three.scenes.Fog') .requires('three.Three', 'three.core.Color') .defines(function(){ /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ THREE.Fog = function ( hex, near, far ) { this.color = new THREE.Color( hex ); this.near = ( near !== undefined ) ? near : 1; this.far = ( far !== undefined ) ? far : 1000; }; });
/** * @file Generate ico image files. * @memberof module:ci/tasks * @function icoTask * @param grunt * @param {object} config - Task configuration. * @param {function} callback - Callback when done. * */ "use strict"; var ico = require('../../lib/commands/ico'); module.exports = function (grunt, config, callback) { ico(config.src, config.dest, {}, function (err) { if (!err) { grunt.log.writeln('ICO file created: %s', config.dest); callback(err); } }); };
'use strict'; const path = require('path') const webpack = require('webpack') const pkg = require('./package.json') const HtmlWebpackPlugin = require('html-webpack-plugin') const WebpackNotifierPlugin = require('webpack-notifier') var paths = { dist: path.join(__dirname, 'dist'), src: path.join(__dirname, 'src') } const baseAppEntries = [ './src/index.jsx' ]; const devAppEntries = [ 'webpack-dev-server/client', 'webpack/hot/only-dev-server' ]; const appEntries = baseAppEntries .concat(process.env.NODE_ENV === 'development' ? devAppEntries : []); const basePlugins = [ new webpack.DefinePlugin({ __DEV__: process.env.NODE_ENV !== 'production', 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }), new webpack.optimize.CommonsChunkPlugin('vendor', '[name].[hash].js'), new HtmlWebpackPlugin({ template: './src/index.html', inject: 'body' }) ]; const devPlugins = [ new webpack.NoErrorsPlugin(), new WebpackNotifierPlugin({ title: pkg.name }) ]; const prodPlugins = [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ]; const plugins = basePlugins .concat(process.env.NODE_ENV === 'production' ? prodPlugins : []) .concat(process.env.NODE_ENV === 'development' ? devPlugins : []); module.exports = { entry: { app: appEntries, vendor: [ 'es5-shim', 'es6-shim', 'es6-promise', 'react', 'react-dom', 'react-redux', 'redux', 'redux-thunk' ] }, output: { path: paths.dist, filename: '[name].[hash].js', publicPath: '/', sourceMapFilename: '[name].[hash].js.map', chunkFilename: '[id].chunk.js' }, devtool: 'eval-source-map', resolve: { extensions: ['', '.jsx', '.js', '.css'] }, plugins: plugins, // devServer: { // historyApiFallback: { index: '/' }, // proxy: proxy(), // }, module: { preLoaders: [ { test: /\.js$/, loader: "eslint", exclude: /node_modules/ } ], loaders: [{ test: /\.(jsx|js)?$/, loader: 'react-hot!babel', include: paths.src, exclude: /(\.test\.js$)/ }, { test: /\.css$/, loaders: ['style', 'css?modules&localIdentName=[local]---[hash:base64:5]', 'postcss'], include: paths.src }, { test: /\.html$/, loader: 'raw', exclude: /node_modules/ } ] }, postcss: function (webpack) { return [ require("postcss-import")({ addDependencyTo: webpack }), require("postcss-url")(), require("postcss-custom-properties")(), require("postcss-nesting")(), require("postcss-cssnext")(), require("postcss-browser-reporter")(), require("postcss-reporter")() ] } };
var dotBeautify = require('../index.js'); var fs = require('fs'); var chai = require('chai'); var assert = chai.assert; var expect = chai.expect; var setup = 'function start (resp)\ {\ resp.writeHead(200, {"Content-Type": "text/html"\ });\ fs.readFile(filename, "utf8", function(err, data) {\ if (err) throw err;\ resp.write(data);resp.end ();});\ }'; describe('dotbeautify', function() { before(function() { fs.writeFileSync(__dirname + '/data/badFormat.js', setup, 'utf8'); }); it('Beautify the horribly formatted code without a config', function() { dotBeautify.beautify([__dirname + '/data/']); var properFormat = fs.readFileSync(__dirname + '/data/goodFormat.js', 'utf8'); var badFormat = fs.readFileSync(__dirname + '/data/badFormat.js', 'utf8'); if(properFormat == badFormat) { return true; } }); it('Beautify the horribly formatted code with a given config', function() { dotBeautify.beautify([__dirname + '/data/'], { indent_size: 8 }); var properFormat = fs.readFileSync(__dirname + '/data/goodFormat.js', 'utf8'); var badFormat = fs.readFileSync(__dirname + '/data/badFormat.js', 'utf8'); if(properFormat == badFormat) { return true; } }); it('Should throw an error upon not passing any directories in', function() { expect(function() { dotBeautify.beautify([],{}); }).to.throw(Error); }); });
import Ember from 'ember'; export default Ember.Component.extend({ colorMap: { running: 'green', waiting: 'orange', terminated: 'red' }, getStatusByName(name) { let retval = null; Ember.$.each(this.get('containerStatuses'), (i, containerStatus) => { if (name === containerStatus.name) { retval = containerStatus; return; } }); return retval; }, items: Ember.computed('containers', 'containerStatuses', function() { let items = []; this.get('containers').map((container) => { let status = this.getStatusByName(container.name); let state = Object.keys(status.state)[0], stateLabel = state.capitalize(), stateColor = this.colorMap[state], readyLabel = status.ready ? 'Ready' : 'Not ready', readyColor = status.ready ? 'green': 'orange'; items.push({ container, status, stateLabel, stateColor, readyLabel, readyColor }); }); return items; }) });
define(function() { var TramoView = Backbone.View.extend({ tagName: 'tr', template: _.template($('#tramo-tmpl').html()), events: {}, initialize: function() {}, render: function(index) { $(this.el).html(this.template(this.model.toJSON())) .addClass((index % 2 === 0) ? 'row1' : 'row2'); return this; } }); return TramoView; });
module.exports = { moduleFileExtensions: ['js', 'jsx', 'json', 'vue', 'ts', 'tsx'], transform: { '^.+\\.vue$': 'vue-jest', '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub', '^.+\\.tsx?$': 'ts-jest' }, transformIgnorePatterns: ['/node_modules/'], moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1' }, snapshotSerializers: ['jest-serializer-vue'], testMatch: ['**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'], testURL: 'http://localhost/', watchPlugins: ['jest-watch-typeahead/filename', 'jest-watch-typeahead/testname'], globals: { 'ts-jest': { babelConfig: true } } }
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.bitcoin = { messagePrefix: '\x18Bitcoin Signed Message:\n', bech32: 'bc', bip32: { public: 0x0488b21e, private: 0x0488ade4, }, pubKeyHash: 0x00, scriptHash: 0x05, wif: 0x80, }; exports.regtest = { messagePrefix: '\x18Bitcoin Signed Message:\n', bech32: 'bcrt', bip32: { public: 0x043587cf, private: 0x04358394, }, pubKeyHash: 0x6f, scriptHash: 0xc4, wif: 0xef, }; exports.testnet = { messagePrefix: '\x18Bitcoin Signed Message:\n', bech32: 'tb', bip32: { public: 0x043587cf, private: 0x04358394, }, pubKeyHash: 0x6f, scriptHash: 0xc4, wif: 0xef, };
import React from 'react'; import PropTypes from 'prop-types'; import './index.css'; const TemplateWrapper = ({children}) => <div>{children()}</div>; TemplateWrapper.propTypes = { children: PropTypes.func, }; export default TemplateWrapper;
'use strict'; describe('Purchases E2E Tests:', function () { describe('Test purchases page', function () { it('Should report missing credentials', function () { browser.get('http://localhost:3000/purchases'); expect(element.all(by.repeater('purchase in purchases')).count()).toEqual(0); }); }); });
(function(){ function render (context, points) { console.log ('render called'); var angle = 0, center = new Point3D (400,400,400); return function () { context.clearRect(0,0,800,600); if (points.length < 1000) { points.push (randomPoint()); } if (angle > 360) {angle = 0;} points.map ( function (pt) { return pt.subtract (center); } ).map ( function (pt) { return y_rotate(pt, angle); } )/*.map ( function (pt) { return x_rotate(pt, angle); } )//.map ( function (pt) { return z_rotate(pt,angle); } )/**/.map ( function (pt) { return project (pt,700); } ).map ( function (pt) { return { x: pt['x'] + center.x, y: pt['y'] + center.y, scale: pt['scale'] } } ).forEach ( function (pt) { if (pt.scale < 0) {return;} context.fillStyle = 'rgba(255,255,255,' + pt.scale + ')'; context.beginPath(); context.arc(pt.x, pt.y, 4*pt.scale, 0, Math.PI * 2, true); context.closePath(); context.fill(); } ); angle = angle + 1; } } function randomInt (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function randomPoint () { return new Point3D ( randomInt (-100,900), randomInt (-100,900), randomInt (-100,900), 1, randomInt (1,10) ); } function init() { console.log ('inited'); var viewport = document.getElementById('viewport'), context = viewport.getContext ('2d'), points = []; context.strokeStyle = '#aaa'; context.lineWidth = 1; setInterval (render (context, points), 50); } document.body.onload = init; }());