code
stringlengths
2
1.05M
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _express = require('express'); var _express2 = _interopRequireDefault(_express); var _membershipController = require('../controllers/membershipController'); var _membershipController2 = _interopRequireDefault(_membershipController); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var membershipRouter = _express2.default.Router({ mergeParams: true }); /** * @description: Defines router for handling all 'membership' requests * @module */ var membershipController = new _membershipController2.default(); /** * @description: Add a user to a group * @param {Object} req The incoming request from the client * @param {Object} res The outgoing response from the server */ membershipRouter.post('/', function (req, res) { membershipController.addOtherMemberToGroup(req, res); }); /** * @description: Fetch all members in a group * @param {Object} req The incoming request from the client * @param {Object} res The outgoing response from the server */ membershipRouter.get('/', function (req, res) { membershipController.getMembersInGroup(req, res); }); /** * @description: Remove a member from a group * @param {Object} req The incoming request from the client * @param {Object} res The outgoing response from the server */ membershipRouter.delete('/:userId', function (req, res) { membershipController.deleteMemberFromGroup(req, res); }); exports.default = membershipRouter;
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import styles from './GroupDeleteConfirmationPanel.scss'; import { deleteGroup, toggleDeleteGroupOpen } from '../../../../redux/modules/groups'; import PanelWithActions from '../../../../components/ManagementPages/PanelWithActions/PanelWithActions.js'; const GroupDeleteConfirmationPanel = ({ id, name, deleteGroupAction, toggleDeleteAction }) => ( <PanelWithActions content={( <div className={styles.groupDeleteConfirmationPanel}> <p>Are you sure you want to delete group: "{name}"</p> <p>Deleting a group also delete all of its logs!</p> </div> )} primaryIcon="check" primaryAction={() => deleteGroupAction(id)} secondaryIcon="close" secondaryAction={() => toggleDeleteAction(id)} /> ); GroupDeleteConfirmationPanel.propTypes = { id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, deleteGroupAction: PropTypes.func.isRequired, toggleDeleteAction: PropTypes.func.isRequired }; export default connect((state, { id }) => ({ name: state.groups.data[id].name }), { deleteGroupAction: deleteGroup, toggleDeleteAction: toggleDeleteGroupOpen })(GroupDeleteConfirmationPanel);
var _ = require('lodash'), Bluebird = require('bluebird'), path = require('path'), debug = require('debug')('configurated-sample-generator'), fs = Bluebird.promisifyAll(require('fs')), packer = require('./packer'), util = require('util'); function PackerConfigurer(options) { options = options || {}; this.organization = options.organization; this.types = { noop: _.identity }; this.infoLoader = _.identity; } PackerConfigurer.prototype.addTypeProcesor = function(name, fn) { this.types[name] = fn; return this; } PackerConfigurer.prototype.setInformationLoader = function(fn) { this.infoLoader = fn; return this; } PackerConfigurer.prototype.getPacker = function() { return _.partial(packer, this); } PackerConfigurer.fileWriter = function(fn) { return function fileWriter(context) { var fileDesc = fn(context); return fs.writeFileAsync(path.join(context.configurationFilePath || context.examplePath, fileDesc.name), fileDesc.content, {flags: 'w'}).then(function() { debug("File created"); return context; }); }; }; PackerConfigurer.envFileCreator = function(fn) { return PackerConfigurer.fileWriter(function(context) { var env = _.map(fn(context), function(value, key) { return util.format('%s=%s', key, value); }).join(' \n'); return { name: '.env', content: env + '\n' }; }); }; PackerConfigurer.fileReplacer = function(fn) { return function searchAndReplaceConfig(context) { return fs.readFileAsync(context.configurationFilePath) .then(function(contents) { debug("Reading content of existing file to replace"); var finalContent = fn(context, contents.toString()); debug("Content replaced"); return fs.writeFileAsync(context.configurationFilePath, finalContent, {flags: 'w'}) .then(function() { debug("New content written"); return context; }); }); }; } module.exports = PackerConfigurer;
/* Waypoint: Iterate over Arrays with map The map method is a convenient way to iterate through arrays. Here's an example usage: var timesFour = oldArray.map(function(val){ return val * 4; }); The map method will iterate through every element of the array, creating a new array with values that have been modified by the callback function, and return it. In our example the callback only uses the value of the array element (the val argument) but your callback can also include arguments for the index and array being acted on. Use the map function to add 3 to every value in the variable oldArray. */ var oldArray = [1,2,3,4,5]; var addThree = oldArray.map(function(val){ return val + 3; });
/** * @providesModule RegisterPage */ import React, { Component } from 'react'; import { TouchableOpacity, ScrollView, StyleSheet, Dimensions, TextInput, Platform, Button, Alert, Image, Text, View } from 'react-native'; import Crypto from 'crypto-js'; import { requestState } from 'ReducerUtils'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import Actions from 'Actions'; export class RegisterPage extends Component { static navigationOptions = { title: '注册', headerStyle:{ backgroundColor:'#232323' }, headerTitleStyle:{ fontSize: 20, }, headerTintColor:'white' } constructor(props) { super(props); this.state = { username: '', password: '', } } componentWillReceiveProps(nextProps) { if (nextProps.registState != this.props.registState) { switch (nextProps.registState) { case requestState.LOADED: Alert.alert('注册成功'); break; case requestState.ERROR: Alert.alert('注册失败'); break; } } } render() { return ( <View style={{ flex: 1, backgroundColor: '#232323' }}> <View style={{ marginTop: 100 }}> <TextInput placeholderTextColor="#bfbfbf" underlineColorAndroid="transparent" style={styles.singleLine} placeholder="用户名" onChangeText={(text) => this.setState({ username: text })} /> <View></View> <TextInput placeholderTextColor="#bfbfbf" underlineColorAndroid="transparent" style={styles.singleLine} placeholder="密码" secureTextEntry={true} onChangeText={(text) => this.setState({ password: text })} /> </View> <TouchableOpacity style={[styles.button, { marginLeft: 20, marginRight: 20 }]} onPress={() => { this.props.dispatch(Actions.regist(this.state.username, Crypto.SHA256(this.state.password).toString(Crypto.enc.Hex))); }} > <Text style={styles.buttonText}>{'注册'}</Text> </TouchableOpacity> </View> ) } } var styles = StyleSheet.create({ button: { borderRadius: 4, marginTop: 10, height: 35, backgroundColor: '#6e6e6e', alignItems: 'center', }, buttonText: { color: '#FFFFFF', fontSize: 16, lineHeight: 30, }, singleLine: { borderRadius: 4, marginLeft: 10, marginRight: 10, marginBottom: 5, backgroundColor: '#3e3e3e', color: '#FFFFFF', fontSize: 16, padding: 0, paddingLeft: 15, height: 50, }, }); const getRegistState = state => state.user.registState; const getRegistErrorObj = state => state.user.registErrorObj; const RegisterPageSelector = createSelector([getRegistState,getRegistErrorObj], (registState,registErrorObj) => { return { registState, registErrorObj } }); export default connect(RegisterPageSelector)(RegisterPage);
'use strict'; var mongoose = require('mongoose'), Schema = mongoose.Schema; var hasValue = function(val){ return val && val.length; }; // Schema var UserSchema = new Schema({ name: { type: String, required: true, validate: [ hasValue, 'Name cannot be blank' ] }, email: { type: String, match: [ /.+\@.+\..+/, 'Please enter a valid email' ] }, accessToken : { type: String }, meetup : {} }); mongoose.model('User', UserSchema);
Ext.define("Com.GatotKaca.ERP.model.Language",{extend:"Ext.data.Model",fields:[{name:"language_id",type:"string"},{name:"language_name",type:"string"},{name:"language_status",type:"boolean"}]});
/** * History * @see https://github.com/ReactTraining/history */ import { createBrowserHistory, createMemoryHistory } from 'history'; export const historyConfig = { baseName: '', forceRefresh: false, }; export const createClientHistory = () => createBrowserHistory(historyConfig); export const createServerHistory = ({ path } = {}) => { const initialEntriesArgument = path ? { initialEntries: [path], } : {}; const history = createMemoryHistory({ ...historyConfig, ...initialEntriesArgument, }); return history; };
/*** * Contains core SlickGrid classes. * @module Core * @namespace Slick */ (function($) { // register namespace $.extend(true, window, { "Slick": { "Event": Event, "EventData": EventData, "Range": Range, "NonDataRow": NonDataItem, "Group": Group, "GroupTotals": GroupTotals, "EditorLock": EditorLock, /*** * A global singleton editor lock. * @class GlobalEditorLock * @static * @constructor */ "GlobalEditorLock": new EditorLock() } }); /*** * An event object for passing data to event handlers and letting them control propagation. * <p>This is pretty much identical to how W3C and jQuery implement events.</p> * @class EventData * @constructor */ function EventData() { var isPropagationStopped = false; var isImmediatePropagationStopped = false; /*** * Stops event from propagating up the DOM tree. * @method stopPropagation */ this.stopPropagation = function() { isPropagationStopped = true; }; /*** * Returns whether stopPropagation was called on this event object. * @method isPropagationStopped * @return {Boolean} */ this.isPropagationStopped = function() { return isPropagationStopped; }; /*** * Prevents the rest of the handlers from being executed. * @method stopImmediatePropagation */ this.stopImmediatePropagation = function() { isImmediatePropagationStopped = true; }; /*** * Returns whether stopImmediatePropagation was called on this event object.\ * @method isImmediatePropagationStopped * @return {Boolean} */ this.isImmediatePropagationStopped = function() { return isImmediatePropagationStopped; } } /*** * A simple publisher-subscriber implementation. * @class Event * @constructor */ function Event() { var handlers = []; /*** * Adds an event handler to be called when the event is fired. * <p>Event handler will receive two arguments - an <code>EventData</code> and the <code>data</code> * object the event was fired with.<p> * @method subscribe * @param fn {Function} Event handler. */ this.subscribe = function(fn) { handlers.push(fn); }; /*** * Removes an event handler added with <code>subscribe(fn)</code>. * @method unsubscribe * @param fn {Function} Event handler to be removed. */ this.unsubscribe = function(fn) { for (var i = handlers.length - 1; i >= 0; i--) { if (handlers[i] === fn) { handlers.splice(i, 1); } } }; /*** * Fires an event notifying all subscribers. * @method notify * @param args {Object} Additional data object to be passed to all handlers. * @param e {EventData} * Optional. * An <code>EventData</code> object to be passed to all handlers. * For DOM events, an existing W3C/jQuery event object can be passed in. * @param scope {Object} * Optional. * The scope ("this") within which the handler will be executed. * If not specified, the scope will be set to the <code>Event</code> instance. */ this.notify = function(args, e, scope) { e = e || new EventData(); scope = scope || this; var returnValue; for (var i = 0; i < handlers.length && !(e.isPropagationStopped() || e.isImmediatePropagationStopped()); i++) { returnValue = handlers[i].call(scope, e, args); } return returnValue; }; } /*** * A structure containing a range of cells. * @class Range * @constructor * @param fromRow {Integer} Starting row. * @param fromCell {Integer} Starting cell. * @param toRow {Integer} Optional. Ending row. Defaults to <code>fromRow</code>. * @param toCell {Integer} Optional. Ending cell. Defaults to <code>fromCell</code>. */ function Range(fromRow, fromCell, toRow, toCell) { if (toRow === undefined && toCell === undefined) { toRow = fromRow; toCell = fromCell; } /*** * @property fromRow * @type {Integer} */ this.fromRow = Math.min(fromRow, toRow); /*** * @property fromCell * @type {Integer} */ this.fromCell = Math.min(fromCell, toCell); /*** * @property toRow * @type {Integer} */ this.toRow = Math.max(fromRow, toRow); /*** * @property toCell * @type {Integer} */ this.toCell = Math.max(fromCell, toCell); /*** * Returns whether a range represents a single row. * @method isSingleRow * @return {Boolean} */ this.isSingleRow = function() { return this.fromRow == this.toRow; }; /*** * Returns whether a range represents a single cell. * @method isSingleCell * @return {Boolean} */ this.isSingleCell = function() { return this.fromRow == this.toRow && this.fromCell == this.toCell; }; /*** * Returns whether a range contains a given cell. * @method contains * @param row {Integer} * @param cell {Integer} * @return {Boolean} */ this.contains = function(row, cell) { return row >= this.fromRow && row <= this.toRow && cell >= this.fromCell && cell <= this.toCell; }; /*** * Returns a readable representation of a range. * @method toString * @return {String} */ this.toString = function() { if (this.isSingleCell()) { return "(" + this.fromRow + ":" + this.fromCell + ")"; } else { return "(" + this.fromRow + ":" + this.fromCell + " - " + this.toRow + ":" + this.toCell + ")"; } } } /*** * A base class that all special / non-data rows (like Group and GroupTotals) derive from. * @class NonDataItem * @constructor */ function NonDataItem() { this.__nonDataRow = true; } /*** * Information about a group of rows. * @class Group * @extends Slick.NonDataItem * @constructor */ function Group() { this.__group = true; this.__updated = false; /*** * Number of rows in the group. * @property count * @type {Integer} */ this.count = 0; /*** * Grouping value. * @property value * @type {Object} */ this.value = null; /*** * Formatted display value of the group. * @property title * @type {String} */ this.title = null; /*** * Whether a group is collapsed. * @property collapsed * @type {Boolean} */ this.collapsed = false; /*** * GroupTotals, if any. * @property totals * @type {GroupTotals} */ this.totals = null; } Group.prototype = new NonDataItem(); /*** * Compares two Group instances. * @method equals * @return {Boolean} * @param group {Group} Group instance to compare to. */ Group.prototype.equals = function(group) { return this.value === group.value && this.count === group.count && this.collapsed === group.collapsed; }; /*** * Information about group totals. * An instance of GroupTotals will be created for each totals row and passed to the aggregators * so that they can store arbitrary data in it. That data can later be accessed by group totals * formatters during the display. * @class GroupTotals * @extends Slick.NonDataItem * @constructor */ function GroupTotals() { this.__groupTotals = true; /*** * Parent Group. * @param group * @type {Group} */ this.group = null; } GroupTotals.prototype = new NonDataItem(); /*** * A locking helper to track the active edit controller and ensure that only a single controller * can be active at a time. This prevents a whole class of state and validation synchronization * issues. An edit controller (such as SlickGrid) can query if an active edit is in progress * and attempt a commit or cancel before proceeding. * @class EditorLock * @constructor */ function EditorLock() { var activeEditController = null; /*** * Returns true if a specified edit controller is active (has the edit lock). * If the parameter is not specified, returns true if any edit controller is active. * @method isActive * @param editController {EditController} * @return {Boolean} */ this.isActive = function(editController) { return (editController ? activeEditController === editController : activeEditController !== null); }; /*** * Sets the specified edit controller as the active edit controller (acquire edit lock). * If another edit controller is already active, and exception will be thrown. * @method activate * @param editController {EditController} edit controller acquiring the lock */ this.activate = function(editController) { if (editController === activeEditController) { // already activated? return; } if (activeEditController !== null) { throw "SlickGrid.EditorLock.activate: an editController is still active, can't activate another editController"; } if (!editController.commitCurrentEdit) { throw "SlickGrid.EditorLock.activate: editController must implement .commitCurrentEdit()"; } if (!editController.cancelCurrentEdit) { throw "SlickGrid.EditorLock.activate: editController must implement .cancelCurrentEdit()"; } activeEditController = editController; }; /*** * Unsets the specified edit controller as the active edit controller (release edit lock). * If the specified edit controller is not the active one, an exception will be thrown. * @method deactivate * @param editController {EditController} edit controller releasing the lock */ this.deactivate = function(editController) { if (activeEditController !== editController) { throw "SlickGrid.EditorLock.deactivate: specified editController is not the currently active one"; } activeEditController = null; }; /*** * Attempts to commit the current edit by calling "commitCurrentEdit" method on the active edit * controller and returns whether the commit attempt was successful (commit may fail due to validation * errors, etc.). Edit controller's "commitCurrentEdit" must return true if the commit has succeeded * and false otherwise. If no edit controller is active, returns true. * @method commitCurrentEdit * @return {Boolean} */ this.commitCurrentEdit = function() { return (activeEditController ? activeEditController.commitCurrentEdit() : true); }; /*** * Attempts to cancel the current edit by calling "cancelCurrentEdit" method on the active edit * controller and returns whether the edit was successfully cancelled. If no edit controller is * active, returns true. * @method cancelCurrentEdit * @return {Boolean} */ this.cancelCurrentEdit = function cancelCurrentEdit() { return (activeEditController ? activeEditController.cancelCurrentEdit() : true); }; } })(jQuery);
import React from 'react'; import PropTypes from 'prop-types'; import Bar from 'src/components/organisms/Bar'; import Results from 'src/components/organisms/Results'; import './Search.css'; class Search extends React.Component { static propTypes = { isLoading: PropTypes.bool, query: PropTypes.string, results: PropTypes.array.isRequired, onSearch: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, onClick: PropTypes.func.isRequired, }; static childContextTypes = { onClick: PropTypes.func.isRequired, }; getChildContext() { return { onClick: this.props.onClick, }; } render() { const { isLoading, query, onClose, onSearch, onClick, results, } = this.props; return ( <div className="sw-Search"> <div className="sw-Search-close" onClick={onClose}> <i className="material-icons">clear</i> </div> <Bar className="sw-Search-top" isLoading={isLoading} query={query} onSearch={onSearch} /> <Results className="sw-Search-bottom" onClick={onClick} results={results} /> </div> </div> ); } } export default Search;
'use strict'; const SqlConnectionManager = require('../lib/SqlConnectionManager.js'); describe('SqlConnectionManager tests', () => { test('open connection failed', () => { const connection = { connect: jest.fn((callback) => callback('connection error')), }; const connectionFactory = { createInstance: jest.fn(() => connection), }; const sqlConnectionManager = new SqlConnectionManager(connectionFactory); const sqlFuncPromise = ()=> Promise.resolve('hello'); return sqlConnectionManager.executeAsync(sqlFuncPromise) .then((result) => { expect(result).toBe(); }) .catch((err) => { expect(err).toBe('connection error'); }); }); test('close connection failed', () => { const connection = { connect: jest.fn((callback) => callback(undefined)), end: jest.fn((callback) => callback('connection error')), }; const connectionFactory = { createInstance: jest.fn(() => connection), }; const sqlConnectionManager = new SqlConnectionManager(connectionFactory); const sqlFuncPromise = ()=> Promise.resolve('hello'); return sqlConnectionManager.executeAsync(sqlFuncPromise) .then((result) => { expect(result).toBe(); }) .catch((err) => { expect(err).toBe('connection error'); }); }); test('query failed', () => { const connection = { connect: jest.fn((callback) => callback(undefined)), end: jest.fn((callback) => callback(undefined)), }; const connectionFactory = { createInstance: jest.fn(() => connection), }; const sqlConnectionManager = new SqlConnectionManager(connectionFactory); const sqlFuncPromise = ()=> Promise.reject('query error'); return sqlConnectionManager.executeAsync(sqlFuncPromise) .then((result) => { expect(result).toBe(); }) .catch((err) => { expect(err).toBe('query error'); }); }); test('query succeeded', () => { const connection = { connect: jest.fn((callback) => callback(undefined)), end: jest.fn((callback) => callback(undefined)), }; const connectionFactory = { createInstance: jest.fn(() => connection), }; const sqlConnectionManager = new SqlConnectionManager(connectionFactory); const sqlFuncPromise = ()=> Promise.resolve('query succeeded'); return sqlConnectionManager.executeAsync(sqlFuncPromise) .then((result) => { expect(result).toBe('query succeeded'); }) .catch((err) => { expect(err).toBe(); }); }); });
'use strict'; require('../src/verdoux'); var assert = require('assert'); var util = require('util'); var Experimental = require('../src/experimental'); describe('Experimental', function(){ var experimental; beforeEach(function() { experimental = Experimental.create(); }); it('should be able to be created', function(){ assert(existy(experimental)); }); describe('#fooExperimental', function(){ it('should be able to call fooExperimental', function(){ var result = Experimental.fooExperimental(); assert(existy(result)); }); }); describe('#bar', function(){ it('should be able to call bar', function(){ var result = experimental.bar(); assert(existy(result)); }); }); describe('#canAccessUnderscore', function(){ it('should have access to underscore framework', function(){ assert(experimental.canAccessUnderscore()); }); }); });
'use strict'; module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ jshint: { options: { jshintrc: '.jshintrc' }, files: [ 'Gruntfile.js', 'lib/**/*.js', 'test/**/*.js' ] }, watch: { files: ['<%= jshint.files %>'], tasks: ['jshint'] } }); grunt.registerTask('default', 'watch'); };
require.config({ baseUrl: './js', paths: { 'cm':'../../bower_components/codemirror' } });
jQuery(function($) { // QWERTY Text Input // The bottom of this file is where the autocomplete extension is added // ******************** $('#text').keyboard({ layout: 'qwerty' }); $('.version').html( '(v' + $('#text').getkeyboard().version + ')' ); // QWERTY Password // ******************** $('#password').keyboard({ openOn : null, stayOpen : true, layout : 'qwerty' }); $('#password-opener').click(function(){ var kb = $('#password').getkeyboard(); // close the keyboard if the keyboard is visible and the button is clicked a second time if ( kb.isOpen ) { kb.close(); } else { kb.reveal(); } }); // QWERTY (mod) Text Area // ******************** $('#qwerty-mod').keyboard({ lockInput: true, // prevent manual keyboard entry layout: 'custom', customLayout: { 'normal': [ '` 1 2 3 4 5 6 7 8 9 0 - = {bksp}', '{tab} q w e r t y u i o p [ ] \\', 'a s d f g h j k l ; \' {enter}', '{shift} z x c v b n m , . / {shift}', '{accept} {space} {left} {right}' ], 'shift': [ '~ ! @ # $ % ^ & * ( ) _ + {bksp}', '{tab} Q W E R T Y U I O P { } |', 'A S D F G H J K L : " {enter}', '{shift} Z X C V B N M < > ? {shift}', '{accept} {space} {left} {right}' ] } }) .addCaret(); // International Text Area // ******************** $('#inter').keyboard({ layout: 'international', css: { // input & preview // "label-default" for a darker background // "light" for white text input: 'form-control input-sm dark', // keyboard container container: 'center-block well', // default state buttonDefault: 'btn btn-default', // hovered button buttonHover: 'btn-primary', // Action keys (e.g. Accept, Cancel, Tab, etc); // this replaces "actionClass" option buttonAction: 'active', // used when disabling the decimal button {dec} // when a decimal exists in the input area buttonDisabled: 'disabled' } }); // Alphabetical Text Area // ******************** $('#alpha').keyboard({ layout: 'alpha' }); // Colemak Input // ******************** $('#colemak').keyboard({ layout: 'colemak' }); // Dvorak Text Area // ******************** $('#dvorak').keyboard({ layout: 'dvorak' }); // Num Pad Input // ******************** $('#num').keyboard({ layout: 'num', restrictInput : true, // Prevent keys not in the displayed keyboard from being typed in preventPaste : true, // prevent ctrl-v and right click autoAccept : true }); // Custom: Hex // ******************** $('#hex').keyboard({ layout: 'custom', customLayout: { 'default' : [ 'C D E F', '8 9 A B', '4 5 6 7', '0 1 2 3', '{bksp} {a} {c}' ] }, maxLength : 6, restrictInput : true, // Prevent keys not in the displayed keyboard from being typed in // include lower case characters (added v1.25.7) restrictInclude : 'a b c d e f', useCombos : false, // don't want A+E to become a ligature acceptValid: true, validate: function(keyboard, value, isClosing){ // only make valid if input is 6 characters in length return value.length === 6; } }); // Custom: Meta Sets // ******************** $('#meta').keyboard({ // keyboard will open showing last key set used resetDefault: false, autoAccept: true, // required for userClosed: true userClosed: true, layout : 'custom', display: { 'alt' : 'AltGr:It\'s all Greek to me', 'meta1' : '\u2666:end of alphabet', // Diamond with label that shows in the title (spaces are okay here) 'meta2' : '\u2665:Russian', // Heart 'meta3' : '\u2663:zodiac', // Club 'meta99' : '\u2660:numbers' // Spade }, customLayout: { 'default' : [ // Add labels using a ":" after the key's name and replace spaces with "_" // without the labels this line is just 'a b c d e f g' 'a:a_letter,_that_sounds_like_"ey" b:a_bug_that_makes_honey c:is_when_I_look_around d:a_grade,_I_never_got e:is_what_girls_say_when_they_run_away_from_me f:u,_is_what_I_say_to_those_screaming_girls! g:gee,_is_that_the_end_of_my_wittiness?', '{shift} {alt} {meta1} {meta2} {meta3} {meta99}', '{bksp} {sp:1} {accept} {cancel}' ], 'shift' : [ 'A B C D E F G', '{shift} {alt} {meta1} {meta2} {meta3} {meta99}', '{bksp} {sp:1} {accept} {cancel}' ], 'alt' : [ '\u03b1:alpha \u03b2:beta \u03B3:gamma \u03b4:delta \u03b5:epsilon \u03b6:zeta \u03b7:eta', // lower case Greek '{shift} {alt} {meta1} {meta2} {meta3} {meta99}', '{bksp} {sp:1} {accept} {cancel}' ], 'alt-shift' : [ '\u0391:alpha \u0392:beta \u0393:gamma \u0394:delta \u0395:epsilon \u03A6:zeta \u03A7:eta', // upper case Greek '{shift} {alt} {meta1} {meta2} {meta3} {meta99}', '{bksp} {sp:1} {accept} {cancel}' ], 'meta1' : [ 't u v w x y z', // lower case end of alphabet '{shift} {alt} {meta1} {meta2} {meta3} {meta99}', '{bksp} {sp:1} {accept} {cancel}' ], 'meta1-shift' : [ 'T U V W X Y Z', // upper case '{shift} {alt} {meta1} {meta2} {meta3} {meta99}', '{bksp} {sp:1} {accept} {cancel}' ], 'meta1-alt' : [ '0 9 8 7 6 5 4', // numbers '{shift} {alt} {meta1} {meta2} {meta3} {meta99}', '{bksp} {sp:1} {accept} {cancel}' ], 'meta1-alt-shift' : [ ') ( * & ^ % $', // shifted numbers '{shift} {alt} {meta1} {meta2} {meta3} {meta99}', '{bksp} {sp:1} {accept} {cancel}' ], 'meta2' : [ '\u0430 \u0431 \u0432 \u0433 \u0434 \u0435 \u0436', // lower case Russian '{shift} {alt} {meta1} {meta2} {meta3} {meta99}', '{bksp} {sp:1} {accept} {cancel}' ], 'meta2-shift' : [ '\u0410 \u0411 \u0412 \u0413 \u0414 \u0415 \u0416', // upper case Russian '{shift} {alt} {meta1} {meta2} {meta3} {meta99}', '{bksp} {sp:1} {accept} {cancel}' ], 'meta3' : [ '\u2648 \u2649 \u264A \u264B \u264C \u264D \u264E', // Zodiac '{shift} {alt} {meta1} {meta2} {meta3} {meta99}', '{bksp} {sp:1} {accept} {cancel}' ], 'meta99' : [ '1 2 3 4 5 6 7', // only because I ran out of ideas '{shift} {alt} {meta1} {meta2} {meta3} {meta99}', '{bksp} {sp:1} {accept} {cancel}' ] } }); /* example from readme, comment out the meta example above then uncomment this one to test it $('#meta').keyboard({ layout: 'custom', display: { 'meta1' : '\u2666', // Diamond 'meta2' : '\u2665' // Heart }, customLayout: { 'default' : [ 'd e f a u l t', '{meta1} {meta2} {accept} {cancel}' ], 'meta1' : [ 'm y m e t a 1', '{meta1} {meta2} {accept} {cancel}' ], 'meta2' : [ 'M Y M E T A 2', '{meta1} {meta2} {accept} {cancel}' ] } }) */ // Custom: Junk / Examples // ******************** $('#junk').keyboard({ layout: 'custom', customLayout: { 'default' : [ 'a e i o u y c', '` \' " ~ ^ {dec} {combo}', '{tab} {enter} {bksp}', '{space}', '{accept} {cancel} {shift}' ], 'shift' : [ 'A E I O U Y C', '` \' " ~ ^ {dec} {combo}', '{t} {sp:1} {e} {sp:1} {b}', '{space}', '{a} {sp:1} {c} {sp:1} {s}' ] }, // Added here as an example on how to add combos combos : { 'a' : { e: '\u00e6' }, 'A' : { E: '\u00c6' } }, // example callback function accepted : function(e, keyboard, el){ alert('The content "' + el.value + '" was accepted!'); } }); // Custom: Mapped keys // ******************** $('#map').keyboard({ layout : 'custom', customLayout: { 'default' : [ // "n(a):title/tooltip"; n = new key, (a) = actual key, ":label" = title/tooltip (use an underscore "_" in place of a space " ") '\u03b1(a):lower_case_alpha_(type_a) \u03b2(b):lower_case_beta_(type_b) \u03be(c):lower_case_xi_(type_c) \u03b4(d):lower_case_delta_(type_d) \u03b5(e):lower_case_epsilon_(type_e) \u03b6(f):lower_case_zeta_(type_f) \u03b3(g):lower_case_gamma_(type_g)', // lower case Greek '{shift} {accept} {cancel}' ], 'shift' : [ '\u0391(A):alpha \u0392(B):beta \u039e(C):xi \u0394(D):delta \u0395(E):epsilon \u03a6(F):phi \u0393(G):gamma', // upper case Greek '{shift} {accept} {cancel}' ] }, usePreview: false // no preveiw }); // Custom: Hidden Input // click on a link - add focus to hidden input // ******************** $('.hiddenInput').click(function(){ $('#hidden').data('keyboard').reveal(); return false; }); // Initialize keyboard script on hidden input // set "position.of" to the same link as above $('#hidden').keyboard({ layout: 'qwerty', position : { of : $('.hiddenInput'), my : 'center top', at : 'center top' } }); // Custom: Lockable // ******************** $('#lockable').keyboard({ layout: 'custom', customLayout: { 'normal': [ '` 1 2 3 4 5 6 7 8 9 0 - = {bksp}', '{tab} q w e r t y u i o p [ ] \\', 'a s d f g h j k l ; \' {enter}', '{shift} z x c v b n m , . / {shift}', '{accept} {space} {left} {right} {sp:.2} {del} {toggle}' ], 'shift': [ '~ ! @ # $ % ^ & * ( ) _ + {bksp}', '{tab} Q W E R T Y U I O P { } |', 'A S D F G H J K L : " {enter}', '{shift} Z X C V B N M < > ? {shift}', '{accept} {space} {left} {right} {sp:.2} {del} {toggle}' ] }, css: { // add dark themed class popup : 'ui-keyboard-dark-theme' } }); // Custom: iPad by gitaarik // ******************** $('#ipad').keyboard({ display: { 'bksp' : '\u2190', 'accept' : 'return', 'default' : 'ABC', 'shift' : '\u21d1', 'meta1' : '.?123', 'meta2' : '#+=' }, layout: 'custom', customLayout: { 'default': [ 'q w e r t y u i o p {bksp}', 'a s d f g h j k l {enter}', '{s} z x c v b n m , . {s}', '{meta1} {space} {meta1} {accept}' ], 'shift': [ 'Q W E R T Y U I O P {bksp}', 'A S D F G H J K L {enter}', '{s} Z X C V B N M ! ? {s}', '{meta1} {space} {meta1} {accept}' ], 'meta1': [ '1 2 3 4 5 6 7 8 9 0 {bksp}', '- / : ; ( ) \u20ac & @ {enter}', '{meta2} . , ? ! \' " {meta2}', '{default} {space} {default} {accept}' ], 'meta2': [ '[ ] { } # % ^ * + = {bksp}', '_ \\ | ~ < > $ \u00a3 \u00a5 {enter}', '{meta1} . , ? ! \' " {meta1}', '{default} {space} {default} {accept}' ] } }); // Custom: iPad email by gitaarik // ******************** $('#ipad-email').keyboard({ display: { 'bksp' : '\u2190', 'enter' : 'return', 'default' : 'ABC', 'meta1' : '.?123', 'meta2' : '#+=', 'accept' : '\u21d3' }, layout: 'custom', customLayout: { 'default': [ 'q w e r t y u i o p {bksp}', 'a s d f g h j k l {enter}', '{s} z x c v b n m @ . {s}', '{meta1} {space} _ - {accept}' ], 'shift': [ 'Q W E R T Y U I O P {bksp}', 'A S D F G H J K L {enter}', '{s} Z X C V B N M @ . {s}', '{meta1} {space} _ - {accept}' ], 'meta1': [ '1 2 3 4 5 6 7 8 9 0 {bksp}', '` | { } % ^ * / \' {enter}', '{meta2} $ & ~ # = + . {meta2}', '{default} {space} ! ? {accept}' ], 'meta2': [ '[ ] { } \u2039 \u203a ^ * " , {bksp}', '\\ | / < > $ \u00a3 \u00a5 \u2022 {enter}', '{meta1} \u20ac & ~ # = + . {meta1}', '{default} {space} ! ? {accept}' ] } }); // Console showing callback messages // ******************** $('.ui-keyboard-input').bind('visible hidden beforeClose accepted canceled restricted', function(e, keyboard, el, status){ var c = $('#console'), t = '<li><span class="keyboard">' + $(el).parent().find('h2 .tooltip-tipsy').text() + '</span>'; switch (e.type){ case 'visible' : t += ' keyboard is <span class="event">visible</span>'; break; case 'hidden' : t += ' keyboard is now <span class="event">hidden</span>'; break; case 'accepted' : t += ' content "<span class="content">' + el.value + '</span>" was <span class="event">accepted</span>' + ($(el).is('[type=password]') ? ', yeah... not so secure :(' : ''); break; case 'canceled' : t += ' content was <span class="event ignored">ignored</span>'; break; case 'restricted' : t += ' The "' + String.fromCharCode(e.keyCode) + '" key is <span class="event ignored">restricted</span>!'; break; case 'beforeClose' : t += ' keyboard is about to <span class="event">close</span>, contents were <span class="event ' + (status ? 'accepted">accepted' : 'ignored">ignored') + '</span>'; break; } t += '</li>'; c.append(t); if (c.find('li').length > 3) { c.find('li').eq(0).remove(); } }); // Show code // ******************** $('h2 span').click(function(){ var orig = 'Click, then scroll down to see this code', active = 'Scroll down to see the code for this example', t = '<h3>' + $(this).parent().text() + ' Code</h3>' + $(this).closest('.block').find('.code').html(); // add indicator & update tooltips $('h2 span') .attr({ title : orig, 'original-title': orig }) .parent() .filter('.active') .removeClass('active'); $(this) .attr({ title : active, 'original-title': active }) // hide, then show the tooltip to force updating & realignment .tipsy('hide') .tipsy('show') .parent().addClass('active'); $('#showcode').html(t).show(); }); // add tooltips // ******************** $('.tooltip-tipsy').tipsy({ gravity: 's' }); $('.navbar [title]').tipsy({ gravity: 'n' }); // ******************** // Extension demos // ******************** // Set up typing simulator extension on ALL keyboards $('.ui-keyboard-input').addTyping(); // simulate typing into the keyboard // \t or {t} = tab, \b or {b} = backspace, \r or \n or {e} = enter // added {l} = caret left, {r} = caret right & {d} = delete $('#inter-type').click(function(){ $('#inter').getkeyboard().reveal().typeIn("{t}Hal{l}{l}{d}e{r}{r}l'o{b}o {e}{t}World", 500); return false; }); $('#meta-type').click(function(){ var meta = $('#meta').getkeyboard(); meta.reveal().typeIn('aBcD1112389\u2648\u2649', 700, function(){ meta.accept(); alert('all done!'); }); return false; }); // Autocomplete demo var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $('#text') .autocomplete({ source: availableTags }) .addAutocomplete(); prettyPrint(); });
module.exports={A:{A:{"2":"H D G E A B HB"},B:{"1":"J L N I","2":"0 C p"},C:{"1":"1 2 4 6 7 8 9 W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y z AB BB","33":"0 3 cB F K H D G E A B C p J L N I O P Q R S T U V aB UB"},D:{"1":"IB FB JB KB LB MB","33":"0 1 2 4 6 7 8 9 F K H D G E A B C p J L N I O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x y z AB BB OB eB GB"},E:{"1":"B C b VB","33":"F K H D G E A NB EB PB QB RB SB TB"},F:{"1":"C y z bB DB","2":"E B WB XB YB ZB b CB","33":"2 J L N I O P Q R S T U V W X Y Z a c d e f g h i j k l m n o M q r s t u v w x"},G:{"2":"5 G C EB dB fB gB hB iB jB kB lB mB nB oB"},H:{"2":"pB"},I:{"1":"GB","2":"3 5 F qB rB sB tB uB vB"},J:{"33":"D A"},K:{"2":"A B C b CB DB","33":"M"},L:{"1":"FB"},M:{"2":"1"},N:{"2":"A B"},O:{"2":"wB"},P:{"2":"F K xB yB"},Q:{"33":"zB"},R:{"2":"0B"}},B:3,C:"CSS grab & grabbing cursors"};
(function (global) { System.config({ paths: { // paths serve as alias 'npm:': '/static/js/lib/' }, // map tells the System loader where to look for things map: { // our app is within the app folder app: '', // angular bundles '@angular/core': 'npm:@angular/core/bundles/core.umd.js', '@angular/common': 'npm:@angular/common/bundles/common.umd.js', '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', '@angular/http': 'npm:@angular/http/bundles/http.umd.js', '@angular/router': 'npm:@angular/router/bundles/router.umd.js', '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', '@angular/material': 'npm:@angular/material/material.umd.js', // other libraries 'rxjs': 'npm:rxjs' }, // packages tells the System loader how to load when no filename and/or no extension packages: { app: { main: '/static/build/main.js', defaultExtension: 'js' }, rxjs: { defaultExtension: 'js' } } }); })(this);
function range(a,b) { return a<b ? Array(b-a+1).fill(0).map(i=>a++) : Array(a-b+1).fill(0).map(i=>a--) }
export class Element { constructor(value) { this.value = value; this.next = null; } } export class List { constructor(arr) { this.head = null; if (arr) { arr.forEach((el) => { this.add(new Element(el)); }); } } get length() { return this.head ? this.countElements(1, this.head) : 0; } add(el) { const element = el; element.next = this.head; this.head = element; } countElements(count, element) { return element.next ? this.countElements(count + 1, element.next) : count; } toArray(arr = [], element = this.head) { arr.push(element.value); return element && element.next ? this.toArray(arr, element.next) : arr; } reverse(prev = null) { if (this.head.next) { const current = this.head; this.head = this.head.next; current.next = prev; return this.reverse(current); } this.head.next = prev; return this; } }
// @requires Tian.js //============================================================= // Namespace: Tian.Number // Contains convenience functions for number manipulation. //------------------------------------------------------------- Tian.Number = { /** * Property: dsep * Decimal separator to use when formatting numbers. */ dsep: ".", /** * Property: tsep * Thousands separator to use when formatting numbers. */ tsep: ",", /** * APIFunction: limitSigDigs * Limit the number of significant digits on a float. * * Parameters: * num - {Float} * sig - {Integer} * * Returns: * {Float} The number, rounded to the specified number of significant * digits. */ limitSigDigs: function(num, sig) { var fig = 0; if (sig > 0) { fig = parseFloat(num.toPrecision(sig)); } return fig; }, /** * APIFunction: limitFixDigs * Limit the number of fixed digits on a float. * * Parameters: * num - {Float} * sig - {Integer} * * Returns: * {Float} The number, rounded to the specified number of fixed * digits. */ limitFixDigs: function(num, fix) { var fig = 0; if (typeof fix === 'number') { fig = parseFloat(num.toFixed(fix)); } return fig; }, /** * APIFunction: format * Formats a number for output. * * Parameters: * num - {Float} * dec - {Integer} Number of decimal places to round to. * Defaults to 0. Set to null to leave decimal places unchanged. * tsep - {String} Thousands separator. * Default is ",". * dsep - {String} Decimal separator. * Default is ".". * * Returns: * {String} A string representing the formatted number. */ format: function(num, dec, tsep, dsep) { dec = (typeof dec != "undefined") ? dec : 0; tsep = (typeof tsep != "undefined") ? tsep : Tian.Number.tsep; dsep = (typeof dsep != "undefined") ? dsep : Tian.Number.dsep; if (dec != null) { num = parseFloat(num.toFixed(dec)); } var parts = num.toString().split("."); if (parts.length == 1 && dec == null) { // integer where we do not want to touch the decimals dec = 0; } var integer = parts[0]; if (tsep) { var thousands = /(-?[0-9]+)([0-9]{3})/; while(thousands.test(integer)) { integer = integer.replace(thousands, "$1" + tsep + "$2"); } } var str; if (dec == 0) { str = integer; } else { var rem = parts.length > 1 ? parts[1] : "0"; if (dec != null) { rem = rem + new Array(dec - rem.length + 1).join("0"); } str = integer + dsep + rem; } return str; }, // add zeros before number zeroize: function(value, length) { if (!length) length = 2; value = value + ''; for (var i = 0, zeros = ''; i < (length-value.length); i++) { zeros += '0'; } return zeros + value; } };
/* A morse code keyer, based on HTML5 audio. Gordon Good velo27 [at] yahoo [dot] com License: None; use as you wish Limitations: - Schedules all audio events up front. This means the speed cannot be changed after the send method is called. Usage: keyer = new Keyer(); keyer.init(context, sink); // where context is the window AudioContext, and sink is the // audio sink to send audio to. keyer.setSpeed(25); // words per minute keyer.setPitch(500); // in Hz keyer.setMonitorGain(0.8); // range 0.0 - 1.0 keyer.send("text to send") keyer.stop(); */ // Morse constants var INTER_CHARACTER = 2.5 // Time between letters var INTER_WORD = 3.5 // Time between words var RAMP = 0.010 function wpmToElementDuration(wpm) { // Convert a words-per-minute value to an element duration, expressed // in seconds. // Based on CODEX (60000 ms per minute / W * 60 dit values in CODEX) return 1.0 / wpm; }; var Keyer = function() { // Keyer configuration this.speed = 25; // in wpm this.elementDuration = wpmToElementDuration(this.speed); this.startTime = 0; this.completionCallback = null; this.completionCallbackId = null; this.voxDelay = 250; // Time from message end to unkey tx // Message sending state // Largest time at which we've scheduled an audio event this.latestScheduledEventTime = 0; }; Keyer.prototype.init = function(context, audioSink) { this.context = context; this.audioSink = audioSink; // Signal chain; oscillator -> gain (keying) -> gain (monitor volume) this.voiceOsc = context.createOscillator(); this.voiceOsc.type = 'sine'; //this.voiceOsc.frequency.value = 500; this.voiceOsc.frequency.setTargetAtTime(500, context.currentTime, 0.001); this.voiceOsc.start(); // envelopeGain control is used to generate keying envelope this.envelopeGain = context.createGain(); this.envelopeGain.gain.setValueAtTime(0.0, context.currentTime); this.monitorGain = context.createGain(); this.monitorGain.gain.setValueAtTime(1.0, context.currentTime); this.voiceOsc.connect(this.envelopeGain); this.envelopeGain.connect(this.monitorGain); this.monitorGain.connect(this.audioSink); }; Keyer.prototype.stop = function() { this.abortMessage(); // Just disconnecting the oscillator seems sufficient to cause // CPU usage to drop when the keyer is stoppped. Previously, // we did this.voiceOsc.stop(); this.voiceOsc.disconnect(); }; Keyer.prototype.setPitch = function(pitch) { // Schedule the frequency change in the future, otherwise // we will hear it sweep from the current to the new // frequency. var now = context.currentTime; this.voiceOsc.frequency.setValueAtTime(pitch, now); }; Keyer.prototype.setMonitorGain = function(gain) { var now = context.currentTime; this.monitorGain.gain.setValueAtTime(gain, now); }; Keyer.prototype.setSpeed = function(wpm) { this.speed = wpm; this.elementDuration = wpmToElementDuration(this.speed); }; Keyer.prototype.isSending = function() { return (this.latestScheduledEventTime > context.currentTime); }; Keyer.prototype.abortMessage = function() { this.envelopeGain.gain.cancelScheduledValues(this.startTime); this.envelopeGain.gain.linearRampToValueAtTime(0.0, context.currentTime + RAMP); this.latestScheduledEventTime = 0.0; if (this.completionCallbackId != null) { clearTimeout(this.completionCallbackId); setTimeout(this.completionCallback, 0); this.completionCallback = null; } }; /* Send the given text. */ Keyer.prototype.send = function(text, completionCallback) { var self = this; if (typeof completionCallback === "undefined") { this.completionCallback = null; } else { this.completionCallback = completionCallback; } // Send morse var timeOffset = context.currentTime; this.startTime = timeOffset; // Morse sending functions function dot(gainNode, elementDuration) { // Send a dot timeOffset += RAMP; gainNode.linearRampToValueAtTime(1.0, timeOffset); timeOffset += elementDuration; gainNode.linearRampToValueAtTime(1.0, timeOffset); // Inter-element space timeOffset += RAMP; gainNode.linearRampToValueAtTime(0.0, timeOffset); timeOffset += elementDuration; gainNode.linearRampToValueAtTime(0.0, timeOffset); // Remember this time self.latestScheduledEventTime = timeOffset; } function dash(gainNode, elementDuration) { // Send a dash timeOffset += RAMP; gainNode.linearRampToValueAtTime(1.0, timeOffset); timeOffset += 3 * elementDuration; gainNode.linearRampToValueAtTime(1.0, timeOffset); // Inter-element space timeOffset += RAMP; gainNode.linearRampToValueAtTime(0.0, timeOffset); timeOffset += elementDuration; gainNode.linearRampToValueAtTime(0.0, timeOffset); // Remember this time self.latestScheduledEventTime = timeOffset; } function letter_space(gainNode, elementDuration) { // Wait INTER_CHARACTER units timeOffset += RAMP; gainNode.linearRampToValueAtTime(0.0, timeOffset); timeOffset += INTER_CHARACTER * elementDuration; gainNode.linearRampToValueAtTime(0.0, timeOffset); // Remember this time self.latestScheduledEventTime = timeOffset; } function word_space(gainNode, elementDuration) { // Wait INTER_WORD units timeOffset += RAMP; gainNode.linearRampToValueAtTime(0.0, timeOffset); timeOffset += INTER_WORD * elementDuration; gainNode.linearRampToValueAtTime(0.0, timeOffset); // Remember this time self.latestScheduledEventTime = timeOffset; } // keyer send() implementation // Convert text to string representing morse dots and dashes var morseLetters = [] for (var i = 0, len = text.length; i < len; i++) { morseLetters.push(toMorse(text[i])); } morseString = morseLetters.join("S"); this.envelopeGain.gain.linearRampToValueAtTime(0, timeOffset); // TODO(ggood) instead of scheduling all of the events here, only // schedule up to, say, 500 milliseconds into the future, and schedule // a callback in which we will schedule another 500 ms, etc. for (var i = 0, len = morseString.length; i < len; i++) { switch (morseString[i]) { case ".": dot(this.envelopeGain.gain, this.elementDuration); break; case "-": dash(this.envelopeGain.gain, this.elementDuration); break; case "S": letter_space(this.envelopeGain.gain, this.elementDuration); break; case "W": word_space(this.envelopeGain.gain, this.elementDuration); break; default: break; } } if (this.completionCallback != null) { var fireTime = ((self.latestScheduledEventTime - context.currentTime) * 1000); this.completionCallbackId = setTimeout(this.completionCallback, fireTime + this.voxDelay); } function toMorse(char) { var morseMap = { "a": ".-", "b": "-...", "c": "-.-.", "d": "-..", "e": ".", "f": "..-.", "g": "--.", "h": "....", "i": "..", "j": ".---", "k": "-.-", "l": ".-..", "m": "--", "n": "-.", "o": "---", "p": ".--.", "q": "--.-", "r": ".-.", "s": "...", "t": "-", "u": "..-", "v": "...-", "w": ".--", "x": "-..-", "y": "-.--", "z": "--..", "0": "-----", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "?": "..--..", "/": "-..-.", ".": ".-.-.-", ",": "--..--", " ": "W", } char = char.toLowerCase() if (char in morseMap) { return morseMap[char]; } else { return ""; } } }
"use strict"; const path = require("path"); const webpack = require("webpack"); const paths = require("./paths"); const env = require("./env"); const outputPath = path.join(paths.app, "distdll"); const webpackConfig = { entry : { cesiumDll : ["cesium/Source/Cesium.js"], }, devtool : "#source-map", output : { path : outputPath, filename : "[name].js", library : "[name]_[hash]", sourcePrefix: "", }, plugins : [ new webpack.DllPlugin({ path : path.join(outputPath, "[name]-manifest.json"), name : "[name]_[hash]", context : paths.cesiumSourceFolder, }), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify("production") }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ], module : { unknownContextCritical : false, loaders : [ { test : /\.css$/, loader: "style!css" }, { test : /\.(png|gif|jpg|jpeg)$/, loader : "file-loader", }, ], }, }; module.exports = webpackConfig;
version https://git-lfs.github.com/spec/v1 oid sha256:c9b40ba5d11ec054f4c252d852ab147d85c1188c65ecd068c6c324930c4da26b size 529
'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface .addColumn('Orders', 'data', { type: Sequelize.JSON, }) .then(() => queryInterface.addColumn('OrderHistories', 'data', { type: Sequelize.JSON, }), ) .then(() => { console.log('>>> done'); }); }, down: (queryInterface, Sequelize) => { return queryInterface .removeColumn('Orders', 'data') .then(() => queryInterface.removeColumn('OrderHistories', 'data')) .then(() => { console.log('>>> done'); }); }, };
import React, { Component } from 'react'; // eslint-disable-next-line import ScrollBar from 'react-perfect-scrollbar'; // eslint-disable-next-line import 'react-perfect-scrollbar/styles.scss'; import './example.scss'; function logEvent(type) { console.log(`event '${type}' triggered!`); } const debounce = (fn, ms = 0) => { let timeoutId; return function wrapper(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => fn.apply(this, args), ms); }; }; class Example extends Component { constructor(props) { super(props); this.state = { className: undefined, onXReachEnd: null, items: Array.from(new Array(100).keys()), }; } componentDidMount() { setTimeout(() => { this.setState({ className: 'dummy', onXReachEnd: () => logEvent('onXReachEnd'), }); }, 5000); } handleYReachEnd = () => { logEvent('onYReachEnd'); } handleTrigger = () => { this.setState({ items: Array.from(new Array(100).keys()), }); } handleSync = debounce((ps) => { ps.update(); console.log('debounce sync ps container in 1000ms'); }, 1000) render() { const { className, onXReachEnd } = this.state; return ( <React.Fragment> <div className="example"> <ScrollBar className={className} onScrollY={() => logEvent('onScrollY')} onScrollX={() => logEvent('onScrollX')} onScrollUp={() => logEvent('onScrollUp')} onScrollDown={() => logEvent('onScrollDown')} onScrollLeft={() => logEvent('onScrollLeft')} onScrollRight={() => logEvent('onScrollRight')} onYReachStart={() => logEvent('onYReachStart')} onYReachEnd={this.handleYReachEnd} onXReachStart={() => logEvent('onXReachStart')} onXReachEnd={onXReachEnd} component="div" > <div className="content" /> </ScrollBar> </div> <div className="example"> <button onClick={this.handleTrigger}>Trigger</button> <ScrollBar onSync={this.handleSync}> {this.state.items.map(e => (<div key={e}>{e}</div>))} </ScrollBar> </div> </React.Fragment> ); } } export default Example;
import { setData } from '@progress/kendo-angular-intl'; setData({ name: "de-LU", likelySubtags: { de: "de-Latn-DE" }, identity: { language: "de", territory: "LU" }, territory: "LU", numbers: { symbols: { decimal: ",", group: ".", list: ";", percentSign: "%", plusSign: "+", minusSign: "-", exponential: "E", superscriptingExponent: "·", perMille: "‰", infinity: "∞", nan: "NaN", timeSeparator: ":" }, decimal: { patterns: [ "n" ], groupSize: [ 3 ] }, scientific: { patterns: [ "nEn" ], groupSize: [] }, percent: { patterns: [ "n %" ], groupSize: [ 3 ] }, currency: { patterns: [ "n $" ], groupSize: [ 3 ], "unitPattern-count-one": "n $", "unitPattern-count-other": "n $" }, accounting: { patterns: [ "n $" ], groupSize: [ 3 ] } } });
//# sourceMappingURL=http://localhost:8080/static/scripts/dist/app.js.map import React from 'react'; import ReactDOM from 'react-dom'; import PollForm from './createPoll.jsx'; import PollDisplay from './pollDisplay.jsx'; import Sidebar from './sidebar.jsx'; class MainDisplay extends React.Component { render () { return( <div className="col-xs-9"> {this.props.display} </div> ) } } class App extends React.Component { constructor () { super(); // calling universal super function on React.Component this.state = { polls : [], display : <PollForm />, } } // function executes once, after component is initialized componentDidMount() { this.fetchPolls(); } // AJAX call to server to fetch user's polls. Updates the state of poll. fetchPolls() { reqwest({ url : "/api/user/polls", method : "GET", success: (resp) => { // response will be JSON string of an array of Poll objects - look at Poll schema for reference var updatedPolls = JSON.parse(resp); this.setState({polls : updatedPolls}); }, error : function (err) { console.log(err); } }); } handlePollClick (pollId) { console.log(pollId); var pollCopy = this.state.polls.slice(); var idx = pollCopy.findIndex( function (poll) { return poll._id == pollId; }); // setting clicked poll to main display this.setState({ display : <PollDisplay poll={pollCopy[idx]} /> }); } handleCreateClick() { this.setState({ display : <PollForm /> // setting the "create form" display on click }); } render () { return( /* Sidebar with all the polls inside */ <div className="row"> <Sidebar polls={this.state.polls} onPollClick={(id) => this.handlePollClick(id)} onCreateClick={() => this.handleCreateClick()}/> <MainDisplay display={this.state.display}/> </div> ); } } ReactDOM.render( <App />, document.getElementById('app') );
define([ 'angular', 'angular-route', './controllers/index' ], function (ng) { 'use strict'; return ng.module('app', [ 'app.controllers', 'ngRoute' ]); });
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import { Link } from 'react-router-dom'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import Typography from '@material-ui/core/Typography'; const styles = { card: { minWidth: 75, width: 300, margin: 10 }, bullet: { display: 'inline-block', margin: '0 2px', transform: 'scale(0.8)' }, title: { marginBottom: 2, fontSize: 24 }, pos: { marginBottom: 12 } }; function DashboardContent(props) { const { classes } = props; return ( <div className="dashboard-card-container"> <Card className={classes.card}> <Link to="/search" className="link-formatting"> <CardContent> <Typography component="h1" className={`${classes.title} discover-card`} color="textPrimary" > Discover New Artists </Typography> {/* <Typography component="p"> Click below to search for artists in your area </Typography> */} </CardContent> </Link> </Card> <Card className={`${classes.card} coming-soon`}> <Link to="" className="link-formatting"> <CardContent> <Typography component="h1" className={`${classes.title} discover-card`} color="textPrimary" > Recomendations (coming soon...) </Typography> </CardContent> </Link> <div className="overlay" /> </Card> <Card className={`${classes.card} coming-soon`}> <Link to="" className="link-formatting"> <CardContent> <Typography component="h1" className={`${classes.title} discover-card`} color="textPrimary" > Previous Searches (coming soon...) </Typography> </CardContent> </Link> <div className="overlay" /> </Card> </div> ); } DashboardContent.propTypes = { classes: PropTypes.object.isRequired }; export default withStyles(styles)(DashboardContent);
module.exports = { name: 'user', properties: { fullName: { type: String, required: true } } }
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const HarmonyImportDependency = require("./HarmonyImportDependency"); class HarmonyAcceptImportDependency extends HarmonyImportDependency { constructor(request, originModule, parserScope) { super(request, originModule, NaN, parserScope); this.weak = true; } get type() { return "harmony accept"; } } HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemplate { apply(dep, source, runtime) {} }; module.exports = HarmonyAcceptImportDependency;
//Problem 3. Occurrences of word //Write a function that finds all the occurrences of word in a text. //The search can be case sensitive or case insensitive. //Use function overloading. function countWordOccurrences(text, word, caseSensitiv){ var i, len, caseSensitiv, currentWord, count = 0, textAsArray = []; caseSensitiv = caseSensitiv || false; if (!caseSensitiv) { word = word.toLowerCase(); text = text.toLowerCase(); } //May be there is a better regex, but I think here is enougth textAsArray = text.replace(/\.\s*/g, '|').replace(/\?/g, '|').replace(/\!/g, '|').replace(/\s+/g, '|').split("|"); for (i = 0, len = textAsArray.length; i < len; i += 1) { currentWord = textAsArray[i]; if (word === currentWord) { count += 1; } } return count; } //Test text = 'The BBC has updated its cookie policy. We use cookies to ensure that we give you the best experience on our website. This includes cookies from third party social media websites if you visit a page which contains embedded content from social media. Such third party cookies may track your use of the BBC website. We and our partners also use cookies to ensure we show you advertising that is relevant to you. If you continue without changing your settings, we will assume that you are happy to receive all cookies on the BBC website.However, you can change your Cookies settings at any time.'; console.log(text); console.log(); console.log('Serching for "Cookies" using case sensitive search:'); console.log('--> ' + countWordOccurrences(text, 'Cookies', true) + ' occurrences!'); console.log(); console.log('Serching for "Cookies" using case unsensitive search:'); console.log('--> ' + countWordOccurrences(text, 'Cookies') + ' occurrences!');
#!/usr/bin/env node import Backbeam from '../' var yargs = require('yargs').usage('Usage: $0').help('help') yargs.wrap(yargs.terminalWidth()) yargs.command('server', 'Start the development server', (yargs) => { var backbeam = new Backbeam(process.cwd()) backbeam.serverStart() console.log('Started server at port 3333') }) yargs.argv
var app; (function (app) { var common; (function (common) { var services; (function (services) { var ConstantService = (function () { function ConstantService() { this.apiAcertoURI = 'api/acerto/'; this.apiApostaURI = '/api/aposta/'; this.apiApostadorURI = '/api/apostador/'; this.apiSorteioURI = '/api/sorteio/'; this.apiStatusSorteioURI = '/api/statussorteio/'; this.apiTipoAcertoURI = '/api/tipoacerto/'; this.apiTipoSorteioURI = '/api/tiposorteio/'; } return ConstantService; }()); services.ConstantService = ConstantService; angular.module('loteriaApp') .service('constantService', ConstantService); })(services = common.services || (common.services = {})); })(common = app.common || (app.common = {})); })(app || (app = {}));
#!/usr/bin/env node var count = process.argv[ 2 ] || 10 ; process.stdout.write( 'Starting echo.js...' ) ; try { process.stdin.setRawMode( true ) ; } catch ( error ) { console.log( 'Not a TTY' ) ; } process.stdin.on( 'data' , function( data ) { console.log( 'Count #' , count , ':' , data ) ; if ( count <= 0 ) { process.stdout.write( 'Exiting...' ) ; process.exit() ; } process.stdout.write( data ) ; count -- ; } ) ;
var db = require("mongojs").connect("basketminderdb", ["reports"]); // "username:[email protected]/mydb" exports.getAllReports = function(callback) { db.reports.find(function(err, reports) { if(err) { console.log('No Reports'); console.log(err); } callback(reports, err); }); } exports.insertReport = function(report, callback) { db.reports.insert(report, function(error, report) { callback(report, error); }); }
angular.module('breeze') .controller('ProfileCtrl', function($scope, $auth, $alert, Account) { /** * Get user's profile information. */ $scope.getProfile = function() { Account.getProfile() .success(function(data) { $scope.user = data; }) .error(function(error) { $alert({ content: error.message, animation: 'fadeZoomFadeDown', type: 'info', duration: 3 }); }); }; /** * Update user's profile information. */ $scope.updateProfile = function() { Account.updateProfile({ displayName: $scope.user.displayName, email: $scope.user.email, phoneNum: $scope.user.phoneNum }).then(function() { $alert({ content: 'Profile has been updated', animation: 'fadeZoomFadeDown', type: 'info', duration: 3 }); }); }; /** * Link third-party provider. */ $scope.link = function(provider) { $auth.link(provider) .then(function() { $alert({ content: 'You have successfully linked ' + provider + ' account', animation: 'fadeZoomFadeDown', type: 'info', duration: 3 }); }) .then(function() { $scope.getProfile(); }) .catch(function(response) { $alert({ content: response.data.message, animation: 'fadeZoomFadeDown', type: 'info', duration: 3 }); }); }; $scope.getProfile(); });
'use strict'; const assert = require('assert'); const mockRequire = require('mock-require'); const mockBindings = require('./mocks/bindings'); const mockLinux = require('./mocks/linux'); const mockI2c = require('./mocks/i2c.node'); const sinon = require('sinon'); mockRequire('bindings', mockBindings); const i2c = require('../i2c-bus'); describe('scanSync', () => { let i2c1; beforeEach(() => { mockLinux.mockI2c1(); i2c1 = i2c.openSync(1); const setUpStubs = () => { let currentAddr; sinon.stub(mockI2c, 'setAddrSync').callsFake( (device, addr, forceAccess) => { currentAddr = addr; } ); sinon.stub(mockI2c, 'receiveByteSync').callsFake( (device) => { if (currentAddr >= 10 && currentAddr <= 20) { return 0x55; } throw new Error('No device at ' + currentAddr); } ); }; setUpStubs(); }); it('scans all addresses for devices', () => { const addresses = i2c1.scanSync(); assert.deepEqual(addresses, [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]); }); it('scans single address for device', () => { const addresses = i2c1.scanSync(15); assert.deepEqual(addresses, [15]); }); it('scans address range for devices', () => { const addresses = i2c1.scanSync(0, 15); assert.deepEqual(addresses, [10, 11, 12, 13, 14, 15]); }); it('scans another address range for devices', () => { const addresses = i2c1.scanSync(12, 17); assert.deepEqual(addresses, [12, 13, 14, 15, 16, 17]); }); afterEach(() => { mockI2c.setAddrSync.restore(); mockI2c.receiveByteSync.restore(); i2c1.closeSync(); mockLinux.restore(); }); });
if (typeof exports === 'object') { var assert = require('assert'); var alasql = require('..'); } else { __dirname = '.'; } if (false) { describe('Test 135 a la NoSQL', function () { var test135; it('1. Insert NoSQL', function (done) { var test135 = alasql.create('test135'); var one = test135.create('one'); one.insert({a: 1, b: 2}, function (res) { assert(res == 1); one.find({a: 1}, function (res) { assert.deepEqual(res, {a: 1, b: 2}); done(); }); }); }); it('99. Clear database', function (done) { test135.drop(); done(); }); }); }
Ext.define("Com.GatotKaca.ERP.model.Day",{extend:"Ext.data.Model",fields:[{name:"day_id",type:"number"},{name:"day_name",type:"string"}]});
define(['class'], function(Class){ var Datatypes = {}; var compareValues = function(v1, v2){ if (v1 == v2) { return 0; } else if (v2 > v1) { return 1; } else { return -1; } }; var compareDates = function(v1, v2){ var diff = v2 - v1; if (diff == 0) { return 0; } else if (diff > 0) { return 1; } else { return -1; } }; var boolToInt = function(bool){ var int; if (bool === true) { return 1; } else if (bool === false) { return 0; } else { return -1; } } var compareBooleans = function(v1, v2){ return compareValues(boolToInt(v1), boolToInt(v2)); }; _.extend(Datatypes, { 'String': { parse: function(v){ return v.toString(); }, compare: compareValues }, 'Boolean': { parse: function(v){ return v.toString().length == 0 ? null : ![false, 0, 'false', '0'].include(v); }, compare: compareBooleans }, 'Integer': { parse: function(v){ if (!_.isInteger(v)) return undefined; return parseInt(v); }, compare: compareValues }, 'Float': { parse: function(v){ if (!_.isFloat(v)) return undefined; return parseFloat(v); }, compare: compareValues }, 'Date': { parse: function(v){ if (_.isDate(v)) return v; return Date.create(v) || undefined; }, compare: compareDates }, 'Datetime': { parse: function(v){ if (_.isDate(v)) return v; return Date.create(v) || undefined; }, compare: compareDates }, 'Cardinality': { parse: function(v){ var separators = [',','..']; if (_.isArray(v)) { return v; } else { var s = separators .detect(function(separator){ return v.includes(separator); }); if (!s){ throw "Unable to parse Cardinality"; } return v.split(s).map(function(n){ return parseInt(n); }); } }, compare: function(v1, v2){ //NaN to ignore either min or max if ((isNaN(v1[0]) || v1[0] == v2[0]) && (isNaN(v1[1]) || v1[1] == v2[1])){ return 0; } if ((isNaN(v1[0]) || v1[0] > v2[0]) && (isNaN(v1[1]) || v1[1] > v2[1])){ return -1; } if ((isNaN(v1[0]) || v1[0] < v2[0]) && (isNaN(v1[1]) || v1[1] < v2[1])){ return 1; } return null; } } }); var ParserFactory = { get: function(datatype){ var parser = (Datatypes[datatype] || Datatypes.String).parse; return function(value){ try { return _.isNull(value) ? null : parser(value); } catch (err) { return undefined; //unparseable } } } }; var ComparerFactory = { get: function(datatype){ var comparer = (Datatypes[datatype] || Datatypes.String).compare; return function(v1, v2){ return _.isNull(v1) || _.isNull(v2) ? null : comparer(v1, v2); } } }; //TODO: test comparisons for various datatypes (e.g. dates, integers, etc.) //TODO: consider maintaining attribute datatypes in the models to avoid having to parse everything. var Matcher = Class.extend({ init: function(attribute, value, datatype){ this.attribute = attribute; this.datatype = datatype = datatype || 'String'; this.parse = ParserFactory.get(datatype); this.compare = ComparerFactory.get(datatype); this.value = this.parse(value); } }); var Matchers = { '=': Matcher.extend({ matches: function(model){ var value = model.value(this.attribute); var parsed = this.parse(value); var compared = this.compare(this.value, parsed); return !_.isNull(compared) && compared == 0; } }), '>': Matcher.extend({ matches: function(model){ var value = model.value(this.attribute); var parsed = this.parse(value); var compared = this.compare(this.value, parsed); return !_.isNull(compared) && compared > 0; } }), '<': Matcher.extend({ matches: function(model){ var value = model.value(this.attribute); var parsed = this.parse(value); var compared = this.compare(this.value, parsed); return !_.isNull(compared) && compared < 0; } }), '>=': Matcher.extend({ matches: function(model){ var value = model.value(this.attribute); var parsed = this.parse(value); var compared = this.compare(this.value, parsed); return !_.isNull(compared) && compared >= 0; } }), '<=': Matcher.extend({ matches: function(model){ var value = model.value(this.attribute); var parsed = this.parse(value); var compared = this.compare(this.value, parsed); return !_.isNull(compared) && compared <= 0; } }), TypeMatcher: Matcher.extend({ init: function(type){ this.type = type; }, matches: function(model){ return model.isa(this.type); } }), IdentityMatcher: Matcher.extend({ init: function(identity){ this.identity = identity; }, matches: function(model){ var identity = this.identity.toLowerCase(); //make case insensitive return model.names().any(function(name){ return name.value().toLowerCase() == identity; }) || model.iids().any(function(iid){ return iid.toLowerCase() == identity; }); } }) } var Filter = Class.extend({ init: function(criteria, datatyper){ var that = this; this.criteria = criteria; this.types = []; datatyper = datatyper || function(attribute){ return 'String'; }; var comparison = function(criterion, operator){ var parts = criterion.split(operator); if (parts.length === 2) { var matcher = Matchers[operator.trim()]; var attribute = parts[0].trim(); var value = parts[1].trim(); var datatype = datatyper(attribute); return new matcher(attribute, value, datatype); } else { return null; } } var identifier = function(value){ var typePrefix = '#'; if (value.startsWith(typePrefix)){ value = value.replace(typePrefix,''); that.types.push(value); //track types publicly return new Matchers.TypeMatcher(value); } else { return new Matchers.IdentityMatcher(value); } } //parse criteria based on potential operators this.filters = criteria.split('&').map(function(criterion){ criterion = criterion.trim(); return comparison(criterion, '<=') || comparison(criterion, '>=') || comparison(criterion, '=') || comparison(criterion, '<') || comparison(criterion, '>') || identifier(criterion); }); }, select: function(topics){ var filters = this.filters; return topics.select(function(topic){ return filters.all(function(filter){ return filter.matches(topic); }); }); } }); var Comparisons = {eq: [0], value: [0], gt: [1], gte: [0, 1], lt: [-1], lte: [-1, 0], 'in': [0]}; (function(c){ c['=' ] = c.eq; c['>' ] = c.gt; c['>='] = c.gte; c['<' ] = c.lt; c['<='] = c.lte; })(Comparisons); return { Datatypes: Datatypes, Comparisons: Comparisons, ParserFactory: ParserFactory, ComparerFactory: ComparerFactory, Filter: Filter //TODO: eliminate Filter and Matchers in favor of queries. }; });
/* civiz.js */ var CVIZ = { version: '0.12' } var COLORS = { red: '#ca0020', pink: '#f4a582', ltblue: '#92c5de', dkblue: '#0571b0', black: '#000000', white: '#ffffff', grey: '#dddddd', highlight: '#ffeb3b' } var GRAPHCOLORS = [ "#3366cc", "#dc3912", "#ff9900", "#109618", "#990099", "#0099c6", "#dd4477", "#66aa00", "#b82e2e", "#316395", "#994499", "#22aa99", "#aaaa11", "#6633cc", "#e67300", "#8b0707", "#651067", "#329262", "#5574a6", "#3b3eac" ]; // DOM var w = window; var d = document; var DOM = { d3svg: d3.select('svg'), svg: d.getElementById('svg'), cmd: d.getElementById('cmd'), out: d.getElementById('out'), inp: d.getElementById('inp'), load: d.getElementById('load'), loadbody: d.getElementById('loadbody'), ok: d.getElementById('ok'), cancel: d.getElementById('cancel') } // Shortcuts DOM.svg.ael = DOM.svg.addEventListener; DOM.svg.rel = DOM.svg.removeEventListener; DOM.svg.dim = DOM.svg.getBoundingClientRect(); DOM.cmd.ael = DOM.cmd.addEventListener; DOM.cmd.rel = DOM.cmd.removeEventListener; // Graph // adjustables var NODE = { RADIUS: 8.0, DISTANCE: 60 // other } var NODESDB = {} var EDGESDB = {} // Functions /////////////////////////////////////////////// var UTILS = { newLine: function() { var blinkers = DOM.inp.getElementsByTagName('i'); for (i = 0; i < blinkers.length; ++i) blinkers[i].remove(); var blinky = document.createElement('i'); blinky.innerHTML = '>'; DOM.inp.insertBefore(blinky, DOM.cmd); }, listen: function(cmd) { c = cmd.split(' '); switch(c[0]) { case 'help': cmdHelp(); break; case 'about': cmdAbout(); break; case 'clear': cmdClear(); break; case 'draw': cmdDraw(); break; case 'new': cmdNew(); break; case 'save': cmdSave(); break; case 'load': cmdLoad(cmd); break; case 'nodes': cmdNodes(cmd); break; case 'edges': cmdEdges(cmd); break; case 'info': cmdInfo(cmd); break; default: return 1; } }, print: function(msg, type) { msg = msg || ""; var clr; switch (type) { case 0: clr = COLORS.ltblue; break; case 1: clr = COLORS.dkblue; break; case 2: clr = COLORS.red; break; case 3: clr = COLORS.pink; break; default: clr = COLORS.white; } DOM.out.firstElementChild.innerHTML += ('<span style="color:'+clr+'">' + msg + '</span><br>'); DOM.cmd.value = ''; UTILS.newLine(); DOM.out.scrollTop = DOM.out.scrollHeight; Ps.update(DOM.out); // Update scrollbar DOM.cmd.focus(); }, edgeCount: function() { var nedges = 0; for (key in EDGESDB) nedges += EDGESDB[key].length; return nedges; }, highlightNode: function(id) { d3.selectAll('circle').attr('class', 'dim'); d3.selectAll('line').attr('class', 'dim'); var c = d.getElementById(id); if (c) { c.setAttribute('class', 'active'); // Get edges var edges = d.querySelectorAll( '[data-parent=\'' + id + '\'], ' + '[data-target=\'' + id + '\']'); for (i = 0; i < edges.length; ++i) edges[i].setAttribute('class', 'active'); // Get targets if (EDGESDB[id]) { for (i = 0; i < EDGESDB[id].length; ++i) d .getElementById(EDGESDB[id][i]) .setAttribute('class', 'target'); } // Get parents for (key in EDGESDB) { if (EDGESDB[key].indexOf(id) > -1) { var node = d.getElementById(key); var oldClass = node.getAttribute('class'); var newClass = (oldClass) ? oldClass + ' parent' : 'parent'; node.setAttribute('class', newClass); } } } } } // Commands //////////////////////////////////////////////// function cmdHelp() { UTILS.print("help", 1); UTILS.print("Commands: "); UTILS.print( "help<br>" + "about<br>" + "clear<br>" + "draw<br>" + "new<br>" + "save<br>" + "load [example]<br>" + "nodes list, add, remove<br>" + "edges list, add, remove<br>" + "info node-id" ); UTILS.print(); } function cmdAbout() { UTILS.print("about", 1); UTILS.print("cviz version " + CVIZ.version); UTILS.print("A network graph visualizer"); UTILS.print("by jamjpan"); UTILS.print(); } function cmdClear() { DOM.out.firstElementChild.innerHTML = ''; DOM.cmd.value = ''; UTILS.newLine(); Ps.update(DOM.out); // Update scrollbar } function cmdNodes(cmd) { var c = cmd.split(' '); var sub = c[1] || null; switch (sub) { case 'list': cmdNodesList(); break; case 'add': cmdNodesAdd(cmd); break; case 'remove': cmdNodesRemove(cmd); break; case null: UTILS.print( "No node command given. " + "Possible subcommands: " + "list, add, remove" , 2); break; default: UTILS.print("Unrecognized command: nodes " + sub, 2); } UTILS.print(); } function cmdEdges(cmd) { var c = cmd.split(' '); var sub = c[1] || null; switch (sub) { case 'list': cmdEdgesList(); break; case 'add': cmdEdgesAdd(cmd); break; case 'remove': cmdEdgesRemove(cmd); break; case null: UTILS.print( "No edge command given. " + "Possible subcommands: " + "list, add, remove" , 2); break; default: UTILS.print("Unrecognized command: edges " + sub, 2); } UTILS.print(); } function cmdDraw() { while(DOM.svg.lastChild) DOM.svg.removeChild(DOM.svg.lastChild); var color = d3.scaleOrdinal(GRAPHCOLORS); var sim = d3.forceSimulation(); var width = DOM.svg.dim.width; var height = DOM.svg.dim.bottom - DOM.svg.dim.top; var id = function(d) { return d.id; }; var dist = function() { return NODE.DISTANCE; }; sim .force('link', d3.forceLink() .id(id) .distance(dist)) .force('charge', d3.forceManyBody()) .force('center', d3.forceCenter(width/2, height/2)); var zoom = d3.zoom() .scaleExtent([-2, 40]) //.translateExtent([[-100, -100], [width+90, height+100]]) .on('zoom', zoomed); var nodes = []; var edges = []; for (key in NODESDB) { nodes.push({ 'id': key, 'group': NODESDB[key][0], 'desc': NODESDB[key][1] }); } for (key in EDGESDB) { for (i = 0; i < EDGESDB[key].length; ++i) { edges.push({ 'source': key, 'target': EDGESDB[key][i] }); } } var edge = DOM.d3svg.append('g') .attr('class', 'edge') .selectAll('line') .data(edges) .enter() .append('line') .attr('stroke-width', 1) .attr('data-parent', function(d) { return d.source; }) .attr('data-target', function(d) { return d.target; }); var node = DOM.d3svg.append('g') .attr('class', 'node') .selectAll('circle') .data(nodes) .enter() .append('circle') .attr('r', NODE.RADIUS) .attr('fill', function(d) { return color(d.group); }) .attr('stroke', function(d) { return color(d.group); }) .attr('id', function(d) { return d.id; }) .call(d3.drag() .on('start', dragstarted) .on('drag', dragged) .on('end', dragended) ); node .append('title') .text(function(d) { return (d.id + " [" + d.group + "] " + d.desc); }); sim.nodes(nodes).on('tick', ticked); sim.force('link').links(edges); DOM.d3svg.call(zoom); function ticked() { edge .attr('x1', function(d) { return d.source.x; }) .attr('y1', function(d) { return d.source.y; }) .attr('x2', function(d) { return d.target.x; }) .attr('y2', function(d) { return d.target.y; }); node .attr('cx', function(d) { return d.x; }) .attr('cy', function(d) { return d.y; }); } function dragstarted(d) { if (!d3.event.active) sim.alphaTarget(0.3).restart(); d.fx = d.x; d.fy = d.y; } function dragged(d) { d.fx = d3.event.x; d.fy = d3.event.y; } function dragended(d) { if (!d3.event.active) sim.alphaTarget(0); d.fx = null; d.fy = null; } function zoomed() { node.attr('transform', d3.event.transform); edge.attr('transform', d3.event.transform); } UTILS.print("draw", 1); UTILS.print(); } function cmdSave() { UTILS.print("save", 1); UTILS.print("Copy to file the following:"); UTILS.print("Nodes " + JSON.stringify(NODESDB), 0); UTILS.print("Edges " + JSON.stringify(EDGESDB), 0); UTILS.print(); } function cmdLoad(cmd) { var c = cmd.split(' '); var opt = c[1] || null; if (!opt) UTILS.print("load", 1); else UTILS.print("load " + opt, 1); if (!opt || opt != "example") { if (opt) UTILS.print("\"" + opt + "\" not recognized.", 2); else (DOM.load.hidden) ? DOM.load.hidden = false : UTILS.print("Already open."); } if (opt == "example") { NODESDB = { "Myriel": ["1", "character"], "Napoleon": ["1", "character"], "Mlle.Baptistine": ["1", "character"], "Mme.Magloire": ["1", "character"], "CountessdeLo": ["1", "character"], "Geborand": ["1", "character"], "Champtercier": ["1", "character"], "Cravatte": ["1", "character"], "Count": ["1", "character"], "OldMan": ["1", "character"], "Labarre": ["2", "character"], "Valjean": ["2", "character"], "Marguerite": ["3", "character"], "Mme.deR": ["2", "character"], "Isabeau": ["2", "character"], "Gervais": ["2", "character"], "Tholomyes": ["3", "character"], "Listolier": ["3", "character"], "Fameuil": ["3", "character"], "Blacheville": ["3", "character"], "Favourite": ["3", "character"], "Dahlia": ["3", "character"], "Zephine": ["3", "character"], "Fantine": ["3", "character"], "Mme.Thenardier": ["4", "character"], "Thenardier": ["4", "character"], "Cosette": ["5", "character"], "Javert": ["4", "character"], "Fauchelevent": ["0", "character"], "Bamatabois": ["2", "character"], "Perpetue": ["3", "character"], "Simplice": ["2", "character"], "Scaufflaire": ["2", "character"], "Woman1": ["2", "character"], "Judge": ["2", "character"], "Champmathieu": ["2", "character"], "Brevet": ["2", "character"], "Chenildieu": ["2", "character"], "Cochepaille": ["2", "character"], "Pontmercy": ["4", "character"], "Boulatruelle": ["6", "character"], "Eponine": ["4", "character"], "Anzelma": ["4", "character"], "Woman2": ["5", "character"], "MotherInnocent": ["0", "character"], "Gribier": ["0", "character"], "Jondrette": ["7", "character"], "Mme.Burgon": ["7", "character"], "Gavroche": ["8", "character"], "Gillenormand": ["5", "character"], "Magnon": ["5", "character"], "Mlle.Gillenormand": ["5", "character"], "Mme.Pontmercy": ["5", "character"], "Mlle.Vaubois": ["5", "character"], "Lt.Gillenormand": ["5", "character"], "Marius": ["8", "character"], "BaronessT": ["5", "character"], "Mabeuf": ["8", "character"], "Enjolras": ["8", "character"], "Combeferre": ["8", "character"], "Prouvaire": ["8", "character"], "Feuilly": ["8", "character"], "Courfeyrac": ["8", "character"], "Bahorel": ["8", "character"], "Bossuet": ["8", "character"], "Joly": ["8", "character"], "Grantaire": ["8", "character"], "MotherPlutarch": ["9", "character"], "Gueulemer": ["4", "character"], "Babet": ["4", "character"], "Claquesous": ["4", "character"], "Montparnasse": ["4", "character"], "Toussaint": ["5", "character"], "Child1": ["10", "character"], "Child2": ["10", "character"], "Brujon": ["4", "character"], "Mme.Hucheloup": ["8", "character"]}; EDGESDB = { "Napoleon": ["Myriel"], "Mlle.Baptistine": ["Myriel"], "Mme.Magloire": ["Myriel", "Mlle.Baptistine"], "CountessdeLo": ["Myriel"], "Geborand": ["Myriel"], "Champtercier": ["Myriel"], "Cravatte": ["Myriel"], "Count": ["Myriel"], "OldMan": ["Myriel"], "Valjean": ["Labarre", "Mme.Magloire", "Mlle.Baptistine", "Myriel"], "Marguerite": ["Valjean"], "Mme.deR": ["Valjean"], "Isabeau": ["Valjean"], "Gervais": ["Valjean"], "Listolier": ["Tholomyes"], "Fameuil": ["Tholomyes", "Listolier"], "Blacheville": ["Tholomyes", "Listolier", "Fameuil"], "Favourite": ["Tholomyes", "Listolier", "Fameuil", "Blacheville"], "Dahlia": ["Tholomyes", "Listolier", "Fameuil", "Blacheville", "Favourite"], "Zephine": ["Tholomyes", "Listolier", "Fameuil", "Blacheville", "Favourite", "Dahlia"], "Fantine": ["Tholomyes", "Listolier", "Fameuil", "Blacheville", "Favourite", "Dahlia", "Zephine", "Marguerite", "Valjean"], "Mme.Thenardier": ["Fantine", "Valjean"], "Thenardier": ["Mme.Thenardier", "Fantine", "Valjean"], "Cosette": ["Mme.Thenardier", "Valjean", "Tholomyes", "Thenardier"], "Javert": ["Valjean", "Fantine", "Thenardier", "Mme.Thenardier", "Cosette"], "Fauchelevent": ["Valjean", "Javert"], "Bamatabois": ["Fantine", "Javert", "Valjean"], "Perpetue": ["Fantine"], "Simplice": ["Perpetue", "Valjean", "Fantine", "Javert"], "Scaufflaire": ["Valjean"], "Woman1": ["Valjean", "Javert"], "Judge": ["Valjean", "Bamatabois"], "Champmathieu": ["Valjean", "Judge", "Bamatabois"], "Brevet": ["Judge", "Champmathieu", "Valjean", "Bamatabois"], "Chenildieu": ["Judge", "Champmathieu", "Brevet", "Valjean", "Bamatabois"], "Cochepaille": ["Judge", "Champmathieu", "Brevet", "Chenildieu", "Valjean", "Bamatabois"], "Pontmercy": ["Thenardier"], "Boulatruelle": ["Thenardier"], "Eponine": ["Mme.Thenardier", "Thenardier"], "Anzelma": ["Eponine", "Thenardier", "Mme.Thenardier"], "Woman2": ["Valjean", "Cosette", "Javert"], "MotherInnocent": ["Fauchelevent", "Valjean"], "Gribier": ["Fauchelevent"], "Mme.Burgon": ["Jondrette"], "Gavroche": ["Mme.Burgon", "Thenardier", "Javert", "Valjean"], "Gillenormand": ["Cosette", "Valjean"], "Magnon": ["Gillenormand", "Mme.Thenardier"], "Mlle.Gillenormand": ["Gillenormand", "Cosette", "Valjean"], "Mme.Pontmercy": ["Mlle.Gillenormand", "Pontmercy"], "Mlle.Vaubois": ["Mlle.Gillenormand"], "Lt.Gillenormand": ["Mlle.Gillenormand", "Gillenormand", "Cosette"], "Marius": ["Mlle.Gillenormand", "Gillenormand", "Pontmercy", "Lt.Gillenormand", "Cosette", "Valjean", "Tholomyes", "Thenardier", "Eponine", "Gavroche"], "BaronessT": ["Gillenormand", "Marius"], "Mabeuf": ["Marius", "Eponine", "Gavroche"], "Enjolras": ["Marius", "Gavroche", "Javert", "Mabeuf", "Valjean"], "Combeferre": ["Enjolras", "Marius", "Gavroche", "Mabeuf"], "Prouvaire": ["Gavroche", "Enjolras", "Combeferre"], "Feuilly": ["Gavroche", "Enjolras", "Prouvaire", "Combeferre", "Mabeuf", "Marius"], "Courfeyrac": ["Marius", "Enjolras", "Combeferre", "Gavroche", "Mabeuf", "Eponine", "Feuilly", "Prouvaire"], "Bahorel": ["Combeferre", "Gavroche", "Courfeyrac", "Mabeuf", "Enjolras", "Feuilly", "Prouvaire", "Marius"], "Bossuet": ["Marius", "Courfeyrac", "Gavroche", "Bahorel", "Enjolras", "Feuilly", "Prouvaire", "Combeferre", "Mabeuf", "Valjean"], "Joly": ["Bahorel", "Bossuet", "Gavroche", "Courfeyrac", "Enjolras", "Feuilly", "Prouvaire", "Combeferre", "Mabeuf", "Marius"], "Grantaire": ["Bossuet", "Enjolras", "Combeferre", "Courfeyrac", "Joly", "Gavroche", "Bahorel", "Feuilly", "Prouvaire"], "MotherPlutarch": ["Mabeuf"], "Gueulemer": ["Thenardier", "Valjean", "Mme.Thenardier", "Javert", "Gavroche", "Eponine"], "Babet": ["Thenardier", "Gueulemer", "Valjean", "Mme.Thenardier", "Javert", "Gavroche", "Eponine"], "Claquesous": ["Thenardier", "Babet", "Gueulemer", "Valjean", "Mme.Thenardier", "Javert", "Eponine", "Enjolras"], "Montparnasse": ["Javert", "Babet", "Gueulemer", "Claquesous", "Valjean", "Gavroche", "Eponine", "Thenardier"], "Toussaint": ["Cosette", "Javert", "Valjean"], "Child1": ["Gavroche"], "Child2": ["Gavroche", "Child1"], "Brujon": ["Babet", "Gueulemer", "Thenardier", "Gavroche", "Eponine", "Claquesous", "Montparnasse"], "Mme.Hucheloup": ["Bossuet", "Joly", "Grantaire", "Bahorel", "Courfeyrac", "Gavroche", "Enjolras"] }; UTILS.print(); UTILS.print("Loaded."); UTILS.print("Auto-draw."); cmdDraw(); } UTILS.print(); } function cmdNew() { NODESDB = {}; EDGESDB = {}; cmdDraw(); cmdClear(); } function cmdInfo(cmd) { var c = cmd.split(' '); var opt = c[1] || null; UTILS.print(cmd, 1); if (!opt) { UTILS.print("ID is required.", 2); UTILS.print("Usage: info node-id", 2); } else { var node = NODESDB[opt]; if (node) { UTILS.print("id: " + opt); UTILS.print("group: " + node[0]); UTILS.print("desc: " + node[1]); UTILS.print("targets: "); var targets = 'no targets'; if (EDGESDB[opt]) { targets = ''; for (i = 0; i < EDGESDB[opt].length; ++i) targets += (EDGESDB[opt][i] + ' '); } UTILS.print(targets, 0); UTILS.print("targeted by: "); var parents = ''; for (key in EDGESDB) { if (EDGESDB[key].indexOf(opt) > -1) parents += (key + ' '); } if (parents == '') parents = 'none'; UTILS.print(parents, 3); UTILS.highlightNode(opt); } else { UTILS.print("Node not found.", 2); } } UTILS.print(); } // Node commands /////////////////////////////////////////// function cmdNodesList() { UTILS.print("nodes list", 1); for (i in NODESDB) { UTILS.print( i + " [" + NODESDB[i][0] + "] " + NODESDB[i][1] ); } UTILS.print(); UTILS.print("Count: " + Object.keys(NODESDB).length); } function cmdNodesAdd(cmd) { var c = cmd.split('"'); var pre = c[0].split(' '); var id = pre[2] || null; var group = pre[3] || null; var desc = c[1] || null; UTILS.print("nodes add", 1); UTILS.print("id: " + id); UTILS.print("group: " + group); UTILS.print("desc: " + desc); if (id && desc && !NODESDB[id]) { NODESDB[id] = [group, desc]; UTILS.print(); UTILS.print("Count: " + Object.keys(NODESDB).length); } else { if (!id) UTILS.print("ID is required.", 2); if (!desc) UTILS.print("Description is required.", 2); if (NODESDB[id]) UTILS.print("ID already exists.", 2); UTILS.print("Fix errors and try again.", 2); UTILS.print("Usage: nodes add id [group] \"my desc\"", 2); } } function cmdNodesRemove(cmd) { var c = cmd.split(' '); var id = c[2] || null; UTILS.print("nodes remove", 1); UTILS.print("id: " + id); if (id) { if (NODESDB[id]) { delete NODESDB[id]; UTILS.print(); UTILS.print("Removed node " + id); UTILS.print("Edges destroyed: "); for (key in EDGESDB) { if (key == id || EDGESDB[key] == id) { UTILS.print("from " + key + " to " + EDGESDB[key]); delete EDGESDB[key]; } } } else { UTILS.print("Node " + id + " not found.", 2); } UTILS.print(); UTILS.print("Count: " + Object.keys(NODESDB).length); } else { UTILS.print("ID is required.", 2); UTILS.print("Fix errors and try again.", 2); UTILS.print("Usage: nodes remove id", 2); } } // Edges commands ////////////////////////////////////////// function cmdEdgesList() { UTILS.print("edges list", 1); var first = true; for (key in EDGESDB) { var targets = ''; for (i = 0; i < EDGESDB[key].length; ++i) targets += (EDGESDB[key][i] + ' '); // Don't print newline for first line if (first) first = false; else UTILS.print(); UTILS.print(key); UTILS.print(targets, 0); } UTILS.print(); UTILS.print("Count: " + UTILS.edgeCount()); } function cmdEdgesAdd(cmd) { var c = cmd.split(' '); var from = c[2] || null; var to = c[3] || null; UTILS.print("edges add", 1); UTILS.print("from: " + from); UTILS.print("to: " + to); var has = (EDGESDB[from]) ? EDGESDB[from].indexOf(to) : -1; if (from && to && NODESDB[from] && NODESDB[to] && from != to && has == -1) { (EDGESDB[from]) ? EDGESDB[from].push(to) : EDGESDB[from] = [to]; } else { if (!from) UTILS.print("From is required.", 2); if (!to) UTILS.print("To is required.", 2); if (!NODESDB[from]) UTILS.print("From does not exists.", 2); if (!NODESDB[to]) UTILS.print("To does not exists.", 2); if (from == to) UTILS.print("Cannot add edge to self.", 2); if (has > -1) UTILS.print("Exists.", 2); UTILS.print("Fix errors and try again.", 2); UTILS.print("Usage: edges add from to", 2); } } function cmdEdgesRemove(cmd) { var c = cmd.split(' '); var from = c[2] || null; var to = c[3] || null; UTILS.print("edges remove", 1); UTILS.print("from: " + from); UTILS.print("to: " + to); var has = (EDGESDB[from]) ? EDGESDB[from].indexOf(to) : -1; if (from && to && NODESDB[from] && NODESDB[to] && from != to && has > -1) { EDGESDB[from].splice(has, 1); if (EDGESDB[from].length == 0) delete EDGESDB[from]; } else { if (!from) UTILS.print("From is required.", 2); if (!to) UTILS.print("To is required.", 2); if (has == -1) UTILS.print("Edge does not exist.", 2); UTILS.print("Fix errors and try again.", 2); UTILS.print("Usage: edges remove from to", 2); } } //////////////////////////////////////////////////////////// w.addEventListener('resize', function() { // Recalculate this but leave it // up to the user to redraw DOM.svg.dim = DOM.svg.getBoundingClientRect(); }); DOM.cmd.ael('keyup', function(e) { if (e.keyCode == 13) { var cmd = DOM.cmd.value; var unrecognized = UTILS.listen(cmd); if (unrecognized) { UTILS.print("Unrecognized command: " + cmd, 2); UTILS.print(); } } }); DOM.ok.addEventListener('click', function() { try { var def = DOM.loadbody.value; def = def.replace('\r', ''); def = def.replace('\n', ''); def = def.split('Edges '); EDGESDB = JSON.parse(def[1]); def = def[0].split('Nodes '); NODESDB = JSON.parse(def[1]); UTILS.print("Loaded."); UTILS.print("Auto-draw."); cmdDraw(); } catch (e) { console.log(e); UTILS.print("Parse failure. Check definition.", 2); } DOM.load.hidden = true; UTILS.print(); }); DOM.cancel.addEventListener('click', function() { DOM.load.hidden = true; }); // Toggles highlight when a circle is clicked DOM.svg.addEventListener('click', function(e) { var nodeName = e.target.nodeName; var nodeClass = e.target.getAttribute('class'); var nodeId = e.target.getAttribute('id'); if (nodeName == 'circle' && nodeClass != 'active') UTILS.highlightNode(nodeId); else { d3.selectAll('circle').attr('class', ''); d3.selectAll('line').attr('class', ''); } }); Ps.initialize(DOM.out); // Perfect scrollbar UTILS.print("cviz version " + CVIZ.version, 3); UTILS.print("-----------------", 3); UTILS.print("Type \"help\" or \"about\" for more information.", 0); UTILS.print(); UTILS.newLine();
(function(){ dw.visualization.register('grouped-column-chart', 'raphael-chart', { // some config _showValueLabels: function() { return true; }, render: function(el) { this.setRoot(el); var me = this, c = me.initCanvas({}), dataset = me.dataset, chart_width = c.w - c.lpad - c.rpad, series_gap = 0.05, // pull from theme row_gap = 0.01; me.axesDef = me.axes(); if (!me.axesDef) return; if (!_.isUndefined(me.get('selected-row'))) { row = me.get('selected-row'); } me.checkData(); me._color_opts = {}; if (me.get('negative-color', false)) { me._color_opts.byValue = function(v) { return me.theme().colors[v < 0 ? 'negative' : 'positive']; }; } else { me._color_opts.varyLightness = true; } me.init(); // compute maximum x-label height var lh = 0, lhi = 0, lw = 0, lwi = 0; barColumns = me.getBarColumns(), n = barColumns.length; _.each(barColumns, function(column, s) { var lbl_w = me.labelWidth(column.title(), 'series'), lbl_h = me.labelHeight(column.title(), 'series'); if (lbl_w >= lw) { lw = lbl_w; lwi = s; } if (lbl_h >= lh) { lh = lbl_h; lhi = s; } }); var bw = (c.w * 0.9) / (me.axesDef.columns.length*1.5); if (bw < 20) { c.bpad += me.labelWidth(barColumns[lwi].title(), 'series smaller'); } else if (bw < 30) { c.bpad += lw; } else { c.bpad += lh; } me.initDimensions(); // store bar references for updates me.__bars = {}; me.__barLbls = {}; me.__gridlines = {}; me.__gridlabels = {}; me.__series_names = {}; if (!me.theme().columnChart.cutGridLines) me.horzGrid(); me.update(); // enable mouse events el.mousemove(_.bind(me.onMouseMove, me)); if (dataset.numRows() > 1) { var items = [], lblFmt = me.chart().columnFormatter(me.axes(true).labels); dataset.eachRow(function(r) { items.push({ label: lblFmt(me.axes(true).labels.val(r)), color: me.getColor(null, r, { varyLightness: true, key: me.axes(true).labels.val(r) }) }); }); me.addLegend(items, $('#header', c.root.parent())); } $('.showOnHover').hide(); if (me.theme().columnChart.cutGridLines) me.horzGrid(); me.post_render(); me.renderingComplete(); }, update: function() { var me = this, c = me.__canvas, n = me.axesDef.columns.length; // draw bars _.each(me.getBarColumns(me.get('sort-values'), me.get('reverse-order')), function(column, s) { column.each(function(val, r) { me._color_opts.key = me.axes(true).labels.val(r); var d = me.barDimensions(column, s, r), fill = me.getColor(column, r, me._color_opts), stroke = chroma.color(fill).darken(10).hex(), key = column.name()+'-'+r, bar_attrs = { x: d.x, y: d.y, width: d.w, height: d.h, stroke: stroke, fill: fill }; me.__bars[key] = me.__bars[key] || me.registerElement(c.paper.rect().attr(bar_attrs), column.name(), r); if (me.theme().columnChart.barAttrs) { me.__bars[key].attr(me.theme().columnChart.barAttrs); } me.__barLbls[key] = me.__barLbls[key] || me.registerLabel(me.label(0,0,'X', { align: 'center', cl: 'value' }), column.name()); me.__barLbls[key].animate({ x: d.x + d.w * 0.5, y: d.y + d.h * 0.5, txt: me.formatValue(column.val(r)) }, 1000, 'expoInOut'); me.__barLbls[key].data('row', r); me.__barLbls[key].hide(); me.__bars[key].animate(bar_attrs, me.theme().duration, me.theme().easing).data('strokeCol', stroke); var val_y = val >= 0 ? d.y - 10 : d.y + d.h + 10, lbl_y = val < 0 ? d.y - 10 : d.y + d.h + 5, lblcl = ['series'], lbl_w = c.w / (n+2), valign = val >= 0 ? 'top' : 'bottom', halign = 'center', alwaysShow = (me.chart().hasHighlight() && me.chart().isHighlighted(column.name())) || (d.w > 40); if (me.chart().hasHighlight() && me.chart().isHighlighted(column.name())) { lblcl.push('highlighted'); } if (d.bw < 30) { //lblcl.push('rotate90'); lbl_y += 5; lbl_w = 100; halign = 'right'; } if (d.bw < 20) { lblcl.push('smaller'); lbl_w = 90; } // add series label if (!/^X\.\d+$/.test(column.title()) && r === 0) { var la = { x: d.bx + d.bw * 0.5, y: lbl_y, w: lbl_w, align: halign, valign: valign, cl: lblcl.join(' '), rotate: d.bw < 30 ? -90 : 0 }, sl = me.__series_names[column.name()] = me.__series_names[column.name()] || me.registerLabel(me.label(la.x, la.y, column.title(), la), column.name()); sl.animate(la, me.theme().duration, me.theme().easing); } }); }); // draw baseline var y = c.h - me.__scales.y(0) - c.bpad; me.path([['M', c.lpad, y], ['L', c.w - c.rpad, y]], 'axis') .attr(me.theme().yAxis); }, getBarColumns: function(sortBars, reverse) { return this._getBarColumns(sortBars, reverse); }, // hack to be able to overload in stacked-column-charts.js _getBarColumns: function(sortBars, reverse) { var me = this, columns = _.map(me.axesDef.columns, function(i) { return me.dataset.column(i); }); if (sortBars) { columns.sort(function(a, b) { var aType = a.type(true); return aType.toNum ? aType.toNum(a.val(0)) - aType.toNum(b.val(0)) : a.val() > b.val() ? 1 : a.val() == b.val() ? 0 : -1; }); } if (reverse) columns.reverse(); return columns; }, initDimensions: function(r) { // var me = this, c = me.__canvas; me.__domain = dw.utils.minMax(me.getBarColumns()); if (me.__domain[0] > 0) me.__domain[0] = 0; if (me.__domain[1] < 0) me.__domain[1] = 0; me.__scales = { y: d3.scale.linear().domain(me.__domain) }; // v-- substract a few pixel to get space for the legend! me.__scales.y.rangeRound([0, c.h - c.bpad - c.tpad - 30]); }, /* * computes x,y,w,h for each bar */ barDimensions: function(column, s, r) { var me = this, sc = me.__scales, c = me.__canvas, n = me.axesDef.columns.length, w, h, x, y, i, cw, bw, pad = 0.35, vspace = 0.1, val = column.val(r); if (c.w / n < 30) vspace = 0.05; cw = (c.w - c.lpad - c.rpad) * (1 - vspace - vspace); bw = cw / (n + (n-1) * pad); h = sc.y(val) - sc.y(0); w = Math.round(bw / column.length); if (h >= 0) { y = c.h - c.bpad - sc.y(0) - h; } else { y = c.h - c.bpad - sc.y(0); h *= -1; } if (val !== 0) h = Math.max(0.5, h); x = Math.round((c.w - c.lpad - c.rpad) * vspace + c.lpad + s * (bw + bw * pad)); return { w: w, h: h, x: x + Math.floor((w+1)*r), y: y, bx: x, bw: bw }; }, getDataRowByPoint: function(x, y) { return 0; }, showTooltip: function() { }, hideTooltip: function() { }, /* * renders the horizontal grid */ horzGrid: function() { // draw tick marks and labels var me = this, yscale = me.__scales.y, c = me.__canvas, domain = me.__domain, styles = me.__styles, ticks = me.getYTicks(yscale, c.h, true); ticks = ticks.filter(function(val, t) { return val >= domain[0] && val <= domain[1]; }); _.each(ticks, function(val, t) { var y = c.h - c.bpad - yscale(val), x = c.lpad, ly = y-10, lbl, txt = me.formatValue(val, t == ticks.length-1, true); // c.paper.text(x, y, val).attr(styles.labels).attr({ 'text-anchor': 'end' }); if (me.theme().columnChart.cutGridLines) ly += 10; if (val !== 0) { lbl = me.__gridlabels[val] = me.__gridlabels[val] || me.label(x+2, ly, txt, { align: 'left', cl: 'axis', css: { opacity: 0 } }); lbl.animate({ x: x+2, y: ly, css: { opacity: 1 } }, me.theme().duration, me.theme().easing); } if (me.theme().yTicks) { me.path([['M', c.lpad-25, y], ['L', c.lpad-20,y]], 'tick'); } if (me.theme().horizontalGrid) { var p = 'M' + [c.lpad, y] + 'H' + c.w, l = me.__gridlines[val] = me.__gridlines[val] || me.path(p, 'grid').attr(me.theme().horizontalGrid).attr('opacity', 0); if (val === 0) l.attr(me.theme().xAxis); else if (me.theme().columnChart.cutGridLines) l.attr('stroke', me.theme().colors.background); l.animate({ path: p, opacity: 1 }, me.theme().duration, me.theme().easing); l.toBack(); } }); _.each(me.__gridlabels, function(lbl, val) { if (_.indexOf(ticks, +val) < 0) { lbl.animate({ css: { opacity: 0 } }, me.theme().duration, me.theme().easing); } }); _.each(me.__gridlines, function(line, val) { if (_.indexOf(ticks, +val) < 0) { line.animate({ opacity: 0 }, me.theme().duration, me.theme().easing); } }); }, /* * highlights hovered bars and displays value labels */ hover: function(hoveredSeries) { var me = this, whitishBg = chroma.color(me.theme().colors.background).lch()[0] > 60; // compute fill color, depending on hoveredSeries function getFill(col, el) { var fill = me.getColor(null, el.data('row'), { varyLightness: true, key: me.axes(true).labels.val(el.data('row')) }); if (hoveredSeries !== undefined && col.name() == dw.utils.name(hoveredSeries)) { fill = chroma.color(fill).darken(whitishBg ? 15 : -25).hex(); } return fill; } _.each(me.getBarColumns(), function(column) { var fill, stroke; // highlight/invert the column title _.each(me.__labels[column.name()], function(lbl) { if (hoveredSeries !== undefined && column.name() == dw.utils.name(hoveredSeries)) { lbl.addClass('hover'); if (lbl.hasClass('showOnHover')) lbl.show(0.5); } else { lbl.removeClass('hover'); if (lbl.hasClass('showOnHover')) lbl.hide(0.5); } if (lbl.hasClass('value')) { lbl.removeClass('hover'); fill = getFill(column, lbl); lbl.addClass('inverted'); //} } }); // animate the bar fill & stroke _.each(me.__elements[column.name()], function(el) { fill = getFill(column, el); stroke = chroma.color(fill).darken(10).hex(); if (el.attrs.fill != fill || el.attrs.stroke != stroke) el.animate({ fill: fill, stroke: stroke }, 50); }); }); // show/hide the labels that show values on top of the bars var visibleLbls = []; _.each(me.__barLbls, function(lbl, key) { if (hoveredSeries && lbl.data('key') == dw.utils.name(hoveredSeries)) { lbl.show(); visibleLbls.push(lbl.data('label')); } else lbl.hide(); }); me.optimizeLabelPositions(visibleLbls, 5); }, unhoverSeries: function() { this.hoverSeries(); }, formatValue: function() { var me = this; // we're overwriting this function with the actual column formatter // when it is first called (lazy evaluation) me.formatValue = me.chart().columnFormatter(me.axes(true).columns[0]); return me.formatValue.apply(me, arguments); }, post_render: function() { }, checkData: function() { return true; } }); }).call(this);
/* Generated with Babel */ /*eslint no-console: 0*/ 'use strict'; var gutil = require('gulp-util'); var PluginError = gutil.PluginError; var path = require('path'); var pluginName = 'gulp-custom-lint'; var rowPad = ' '; var columnPad = ' '; var failedCount = 0; function logLine(rowAndCols, message) { console.log(gutil.colors.gray(rowAndCols), gutil.colors.red(' error '), message); } function reportFailures(lint) { if (!lint.lines) { logLine(' '.repeat(rowPad.length + columnPad.length + 1), lint.message); failedCount++; return; } lint.lines.forEach(function (lineInfo) { var row = (rowPad + lineInfo.row).slice(-rowPad.length); var column = (lineInfo.column + columnPad).substring(0, columnPad.length); logLine(row + ':' + column, lint.message); failedCount++; }); } function failAfterError(target) { if (failedCount > 0) { target.emit('error', new PluginError(pluginName, { message: 'Found ' + failedCount + ' error(s)', showStack: false })); } } function processBuffer(file) { if (file.customLint) { var relativePath = path.relative(process.cwd(), file.path); console.log(relativePath); file.customLint.forEach(reportFailures); console.log(); } } module.exports = { processBuffer: processBuffer, failAfterError: failAfterError };
define(['qunit-assert', 'test-setup', 'AMD/Definition', 'AMD/Dependency'], function(t, testSetup, AMDClass, Dependency) { module("AMD.Definition"); var setup = function (test) { var amd = new AMDClass(); var lodash = new Dependency( 'vendor/lodash', '_' ); var jquery = new Dependency( 'vendor/jquery-1.8.2.min', 'jQuery' ); return t.setup(test, {amd: amd, lodash: lodash, jquery: jquery}); }; test("dependencies can be added to the definition", function() { var that = setup(this); that.assertNotUndefined( that.amd.addDependency( new Dependency( 'vendor/lodash', '_' ) ) ); }); test("getDependency returns the dependency by name if added", function() { var that = setup(this), dependency; that.amd.addDependency(dependency = that.lodash); that.assertSame(dependency, that.amd.getDependency('_')); that.assertUndefined(that.amd.getDependency('jQuery')); }); test("hasDependency returns true for dependency by name if added", function () { var that = setup(this); that.amd.addDependency(that.lodash); that.assertTrue(that.amd.hasDependency('_'), 'hasDependency reflects if dependency was added'); that.assertFalse(that.amd.hasDependency('jQuery')); }); test("getDependencies returns all dependencies in AMD", function () { var that = setup(this); that.assertLength(0, that.amd.getDependencies()); that.amd.addDependency(that.lodash); that.assertLength(1, that.amd.getDependencies()); that.amd.addDependency(that.jquery); that.assertLength(2, that.amd.getDependencies()); }); test("when dependency is added twice with same arguments nothing happens", function () { var that = setup(this); that.amd.addDependency(that.lodash); that.assertLength(1, that.amd.getDependencies()); that.amd.addDependency(that.lodash); that.assertLength(1, that.amd.getDependencies()); }); test("when dependency is added twice with other path an error accurs", function () { var that = setup(this); that.amd.addDependency(that.lodash); try { that.amd.addDependency(new Dependency( 'vendor/other/lodash', '_' )); this.fail('an Error was expected to be thrown'); } catch (err) { this.assertContains("lodash", err.toString()); this.assertContains("already used", err.toString()); } }); test("by default the module definition is anonymous", function () { var that = setup(this); this.assertTrue(that.amd.isAnonymous(), 'amd is anonymous per default'); }); test("when name is given as parameter 1 the module is not anonymous", function () { var that = setup(this); var amd = new AMDClass('Some/ModuleId'); that.assertEquals('Some/ModuleId', amd.getName()); this.assertFalse(amd.isAnonymous(), 'amd is not anonymous'); }); test("when name is set the module definition is not anonymous anymore", function () { var that = setup(this); that.amd.setName('Some/ModuleId'); that.assertEquals('Some/ModuleId', that.amd.getName()); this.assertFalse(that.amd.isAnonymous(), 'amd is not anonymous'); }); });
angular.module('filters.xbmc.asset', []) .filter('asset', function () { return function (input, host) { if (input && host) { var securityPrefix = ''; var asChromeApp = false; if(window.chrome && window.chrome.storage) { asChromeApp = true; } if(!asChromeApp && host.username !== '' && host.password !== '') { securityPrefix = host.username + ':' + host.password + '@'; } var regExp = new RegExp('image://([^/]*)'); var matches = input.match(regExp); if(matches.length === 2) { return 'http://' + securityPrefix + host.ip + ':'+host.httpPort+'/image/' + encodeURIComponent('image://'+matches[1]+'/'); } } return ''; }; });
import { connect } from 'react-redux' import Stats from '../components/stats/Stats' import { tryAgain } from '../actions' const mapStateToProps = (state) => ({ total: state.questions.list.length, open: state.questions.list.filter(q => !q.completed).length, completed: state.questions.list.filter(q => q.completed).length, correct: state.questions.list.filter(q => q.a === q.userAnswer).length, mistakes: state.questions.list.filter(q => q.completed && q.a !== q.userAnswer).length }) const mapDispatchToProps = ({ tryAgain }) const VisibleStats = connect( mapStateToProps, mapDispatchToProps )(Stats) export default VisibleStats
/** * ================================================ * ABElectronics Expander Pi - DAC demo * Version 1.0 Created 19/06/2017 * * Requires rpio to be installed, install with: npm install rpio * * run with: sudo node dacwrite.js * ================================================ */ // link to the expanderpi library var expanderpi = require('../../lib/expanderpi/expanderpi'); // create a new instance of the DAC dac = new ExpanderPiDAC(); // set the DAC gain to 1 dac.setDACGain(1); // set the voltage dac.setDACVoltage(1, 0.8); dac.setDACVoltage(2, 1.5);
import Vue from 'vue' import Vuex from 'vuex' import grid from './modules/Grid' Vue.use(Vuex) console.log('index.js') export default new Vuex.Store({ modules: { grid } })
import React, { PropTypes } from 'react'; import styled from 'styled-components'; import pallete from 'styles/colors'; import date from 'utils/date'; import FlexRow from 'components/FlexRow'; import FlexRowCenter from 'components/FlexRowCenter'; import FlexSB from 'components/FlexSB'; import FlexColumn from 'components/FlexColumn'; import Avatar from 'components/Avatar'; import DateInfo from 'components/DateInfo'; import luckImg from 'assets/images/hongbao-lucy.png'; const ListWrapper = styled.div` marginTop: 0.24rem; padding: 0.12rem 0.24rem; border-top: 0.01rem ${pallete.border.normal} solid; `; const ItemWrapper = styled(FlexRow)` position: relative; padding: 0.15rem 0; background-color: ${pallete.white}; border-bottom: 0.01rem ${pallete.border.normal} solid; `; class HongbaoList extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { const { hongbao, list } = this.props; // 显示抢红包用的时间 let usedTime = 0; if (hongbao.is_finish) { const lastTime = Number(list[list.length - 1].created_at); const diffTime = lastTime - Number(hongbao.created_at); usedTime = date.parseDiffTime(diffTime); } const listView = list && list.map((user) => ( <ItemWrapper key={user.id} style={{ width: '100%', alignSelf: 'flex-start' }}> <Avatar size="0.88rem" id={user.id} avatar={user.avatar} isVip={Number(user.verify_status) === 2} /> <FlexColumn style={{ padding: '0.04rem 0.12rem', width: '100%' }}> <FlexSB style={{ fontSize: '0.28rem', color: '#333333' }}> <section>{user.nickname}</section> <section>{user.total_fee}元</section> </FlexSB> <FlexSB> {user.created_at && <DateInfo time={user.created_at} style={{ color: pallete.text.help, }} />} { user.luck > 0 && ( <FlexRow> <img src={luckImg} role="presetation" style={{ width: '0.3rem', height: '0.24rem' }} /> <div style={{ marginLeft: '0.08rem' ,fontSize: '0.22rem', color: '#fac216' }}>手气最佳</div> </FlexRow> ) } </FlexSB> </FlexColumn> </ItemWrapper> )); return ( <ListWrapper> <div style={{ fontSize: '0.24rem', color: '#999999' }}> {hongbao.total_number}个红包共{hongbao.total_fee}元,{hongbao.is_finish > 0 ? `${usedTime}被抢完` : `已领取${hongbao.get_count}个`} </div> <div> {listView} </div> </ListWrapper> ); } } HongbaoList.propTypes = { hongbao: PropTypes.object, }; export default HongbaoList;
/* * File: jshttp.js * Created on Thu Sep 04 10:51:21 BST 2014 by java2js * -------------------------------------------------- * This file was generated mechanically by the java2js utility. * Permanent edits must be made in the Java file. */ define([ "jslib", "edu/stanford/cs/command", "edu/stanford/cs/java2js", "edu/stanford/cs/jsconsole", "edu/stanford/cs/tokenscanner", "java/awt", "java/lang" ], function(jslib, edu_stanford_cs_command, edu_stanford_cs_java2js, edu_stanford_cs_jsconsole, edu_stanford_cs_tokenscanner, java_awt, java_lang) { /* Imports */ var inheritPrototype = jslib.inheritPrototype; var newArray = jslib.newArray; var toInt = jslib.toInt; var toStr = jslib.toStr; var Command = edu_stanford_cs_command.Command; var CommandLoop = edu_stanford_cs_command.CommandLoop; var HelpCommand = edu_stanford_cs_command.HelpCommand; var QuitCommand = edu_stanford_cs_command.QuitCommand; var ScriptCommand = edu_stanford_cs_command.ScriptCommand; var JSElementList = edu_stanford_cs_java2js.JSElementList; var JSErrorEvent = edu_stanford_cs_java2js.JSErrorEvent; var JSFile = edu_stanford_cs_java2js.JSFile; var JSProgram = edu_stanford_cs_java2js.JSProgram; var JSConsole = edu_stanford_cs_jsconsole.JSConsole; var TokenScanner = edu_stanford_cs_tokenscanner.TokenScanner; var Dimension = java_awt.Dimension; var Font = java_awt.Font; var ActionEvent = java_awt.ActionEvent; var ActionListener = java_awt.ActionListener; var Class = java_lang.Class; /* JSHttpTest.js */ var JSHttpTest = function() { JSProgram.call(this); this.setTitle("JSHttpTest"); this.console = new JSConsole(); this.console.setFont(Font.decode("Courier New-Bold-16")); this.add(this.console, "console"); this.commandLoop = new JSHttpCommandLoop(this, this.console); this.setPreferredSize(new Dimension(800, 600)); this.pack(); this.setVisible(true); }; JSHttpTest.prototype = jslib.inheritPrototype(JSProgram, "JSHttpTest extends JSProgram"); JSHttpTest.prototype.constructor = JSHttpTest; JSHttpTest.prototype.$class = new Class("JSHttpTest", JSHttpTest); JSHttpTest.prototype.run = function() { this.commandLoop.start(); }; JSHttpTest.prototype.getConsole = function() { return this.console; }; JSHttpTest.main = function(args) { new JSHttpTest().run(); }; var JSHttpCommandLoop = function(app, console) { CommandLoop.call(this, console); this.app = app; this.addCommand("quit", new QuitCommand()); this.addCommand("get", new GetCommand()); this.addCommand("ls", new LSCommand()); this.addCommand("help", new HelpCommand()); this.addCommand("script", new ScriptCommand()); }; JSHttpCommandLoop.prototype = jslib.inheritPrototype(CommandLoop, "JSHttpCommandLoop extends CommandLoop"); JSHttpCommandLoop.prototype.constructor = JSHttpCommandLoop; JSHttpCommandLoop.prototype.$class = new Class("JSHttpCommandLoop", JSHttpCommandLoop); JSHttpCommandLoop.prototype.getApplication = function() { return this.app; }; var LSCommand = function() { Command.call(this); }; LSCommand.prototype = jslib.inheritPrototype(Command, "LSCommand extends Command"); LSCommand.prototype.constructor = LSCommand; LSCommand.prototype.$class = new Class("LSCommand", LSCommand); LSCommand.prototype.getHelp = function() { return "ls dir -- Loads and prints the contents of the remote directory"; }; LSCommand.prototype.execute = function(cl, scanner) { var console = cl.getConsole(); var filename = this.scanFilename(scanner); new JSFile(LSCommand.ROOT + filename).read(new HttpReader(cl, true)); return false; }; LSCommand.ROOT = "http://cs.stanford.edu/~eroberts/demos/"; var GetCommand = function() { Command.call(this); }; GetCommand.prototype = jslib.inheritPrototype(Command, "GetCommand extends Command"); GetCommand.prototype.constructor = GetCommand; GetCommand.prototype.$class = new Class("GetCommand", GetCommand); GetCommand.prototype.getHelp = function() { return "get file -- Loads and prints the contents of the remote file"; }; GetCommand.prototype.execute = function(cl, scanner) { var console = cl.getConsole(); var filename = this.scanFilename(scanner); new JSFile(GetCommand.ROOT + filename).read(new HttpReader(cl, false)); return false; }; GetCommand.ROOT = "http://cs.stanford.edu/~eroberts/demos/"; var HttpReader = function(cl, lsFlag) { this.cl = cl; this.lsFlag = lsFlag; }; HttpReader.prototype.actionPerformed = function(e) { var console = this.cl.getConsole(); if (e instanceof JSErrorEvent) { console.showErrorMessage(e.getActionCommand()); } else if (this.lsFlag) { var el = new JSElementList(JSFile.parseHTMLDirectory(e.getActionCommand())); for (var ei = 0; ei < el.size(); ei++) { var line = el.get(ei); console.println(line); } } else { console.print(e.getActionCommand()); } this.cl.resume(); }; /* Exports */ return { JSHttpTest : JSHttpTest }; });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiR2V0Q2xpZW50QnlQb29sUmVzcG9uc2UuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvbW9kZWxzL0dldENsaWVudEJ5UG9vbFJlc3BvbnNlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiIifQ==
import callApi from '../../util/apiCaller'; import localStorage from 'localStorage'; export const ACTIONS = { ADD_USER_NEWS: 'ADD_USER_NEWS', }; export function addUserNews(news) { return { type: ACTIONS.ADD_USER_NEWS, news }; } export function fetchUserNews(id) { return (dispatch) => { return callApi(`news/${id}`, 'get', '').then(res => { dispatch(addUserNews(res.news)); }); } } export function edit(news) { return () => { return callApi('news', 'put', '', { news }).then(res => { return res; }); }; }
var donut = document.getElementByClassName("donutbtn"); donut.addEventListener('click',function(e){ console.log(e); })
"use strict"; const { runTest, runTestWithHelp } = require("../helpers"); const packageName = "info"; const isSubPackage = true; const infoTest = () => { const args = ["info"]; const logMessage = "For using this command you need to install: '@webpack-cli/info' package"; return runTest(packageName, args, logMessage, isSubPackage); }; const infoTestWithHelp = () => { const args = ["help", "info"]; const logMessage = "For using 'info' command you need to install '@webpack-cli/info' package"; return runTestWithHelp(packageName, args, logMessage, isSubPackage); }; module.exports.run = [infoTest, infoTestWithHelp]; module.exports.name = "Missing @webpack-cli/info";
module.exports = { 'DropScreen': require('./dropscreen'), 'DoActionScreen': require('./doactionscreen'), 'EatScreen': require('./eatscreen'), 'ExamineScreen': require('./examinescreen'), 'GainStatsScreen': require('./gainstatscreen'), 'HelpScreen': require('./helpscreen'), 'InventoryScreen': require('./inventoryScreen'), 'LookScreen': require('./lookscreen'), 'LoseScreen': require('./losescreen'), 'PickupScreen': require('./pickupscreen'), 'PlayScreen': require('./playscreen'), 'StartScreen': require('./startscreen'), 'WearScreen': require('./wearscreen'), 'WieldScreen': require('./wieldscreen'), 'WinScreen': require('./winscreen') };
/*--公用方法--*/ ~function (pro) { //->获取URL地址栏问号后面的参数值及HASH值 function queryURLParameter() { var obj = {}, reg = /([^?=&#]+)=([^?=&#]+)/g; this.replace(reg, function () { obj[arguments[1]] = arguments[2]; }); reg = /#([^?=&#]+)/; if (reg.test(this)) { obj["hash"] = reg.exec(this)[1]; } return obj; } pro.queryURLParameter = queryURLParameter; }(String.prototype); var $content = $(".content"), $menu = $content.children(".menu"); //->计算CONTENT及相关区域的高度 computedHeight(); $(window).on("resize", computedHeight); function computedHeight() { var winH = $(window).outerHeight(), headerH = 64, resH = winH - headerH - 40; $content.css("height", resH); $menu.css("height", resH - 2); } //->MENU var menuRender = (function () { //->准备MENU区域的数据 var menuData = '[{"name":"奥运","hash":"olympics","columnId":100009},{"name":"NBA","hash":"nba","columnId":100000},{"name":"欧洲杯","hash":"ec","columnId":3},{"name":"中超","hash":"csl","columnId":208},{"name":"亚冠","hash":"afc","columnId":605},{"name":"欧冠","hash":"ucl","columnId":5},{"name":"英超","hash":"pl","columnId":8},{"name":"西甲","hash":"laliga","columnId":23},{"name":"意甲","hash":"seriea","columnId":21},{"name":"德甲","hash":"bundesliga","columnId":22},{"name":"法甲","hash":"l1","columnId":24},{"name":"cba","hash":"cba","columnId":100008},{"name":"综合","hash":"others","columnId":100002},{"name":"NFL","hash":"nfl","columnId":100005}]'; menuData = "JSON" in window ? JSON.parse(menuData) : eval("(" + menuData + ")"); //->获取需要的元素 var $menu = $(".content>.menu"), $menuCon = $menu.children("ul"); //->bindHTML:使用EJS模板解析我们需要的内容最后实现数据的绑定 function bindHTML() { //->把HTML模板中的内容全部获取到 var str = $("#menuTemplate").html(); //->把模板字符串和需要绑定的数据统一交给EJS渲染 var res = ejs.render(str, {data: menuData}); //->把获取到的内容放入到HTML页面中的指定位置上 $menuCon.html(res); } //->positionLi:加载页面定位到具体的某一个LI function positionLi() { var obj = window.location.href.queryURLParameter(), hash = obj["hash"]; typeof hash === "undefined" ? hash = "olympics" : null; var $curLi = $menuCon.children("li[hash='" + hash + "']"); if ($curLi.length === 0) { $menuCon.children("li:eq(0)").addClass("bg"); return; } $curLi.addClass("bg"); //->根据定位的是哪一项,让右侧的数据跟着动态显示 } //->bindEvent:给所有的LI绑定点击事件 function bindEvent() { $menuCon.children("li").on("click", function () { $(this).addClass("bg").siblings().removeClass("bg"); //->根据点击的是哪一项,让右侧的数据跟着动态显示 }); } return { init: function () { bindHTML(); positionLi(); bindEvent(); } }; })(); menuRender.init();
import { setTitle } from '~/repository/utils/title'; describe('setTitle', () => { it.each` path | title ${'/'} | ${'Files'} ${'app'} | ${'app'} ${'app/assets'} | ${'app/assets'} ${'app/assets/javascripts'} | ${'app/assets/javascripts'} `('sets document title as $title for $path', ({ path, title }) => { setTitle(path, 'master', 'GitLab'); expect(document.title).toEqual(`${title} · master · GitLab`); }); });
//============================================================================= // marker //============================================================================= var MarkerCluster; var MapOverlay_Overlap_chlist={}; //markerのSTATUS種類 1:未完了 5:完了 99:ブックマーク時のアイコン色 MAKER_STATUS_S={ 0:{'color':'336699'},//default 1:{'color':'FC7790'}, 5:{'color':'32ceff'}, 99:{'color':'44f186'}//マーク }; MARKERCLUSTER_GRIDSIZE=50; MARKERCLUSTER_MAXZOOM=15; MARKERCLUSTER_IMG_DIR="js/markers/";//マーカのディレクトリ 「markers/ステータスID/1〜5.png」 function MapOverlay(map,data,manager_ref,select_comp_list) { if(!MarkerCluster){ MarkerCluster={}; for(i in MAKER_STATUS_S){ MarkerCluster[i]=new MarkerClusterer(map,[],{ imagePath:MARKERCLUSTER_IMG_DIR+i+"/m", imageExtension:"png" }); MarkerCluster[i].setGridSize(MARKERCLUSTER_GRIDSIZE); MarkerCluster[i].setMaxZoom(MARKERCLUSTER_MAXZOOM); } } this.select_comp_list=select_comp_list; this.map_ = map; this.data_ = data; this.priority=data.priority.id;//優先度2014/03/12 add this.id=data.id; this.info= new google.maps.InfoWindow(); this.info.setOptions({"disableAutoPan":false});//吹き出しを地図の中心に持ってくるか this.latlng=null; this.status_id=MAKER_STATUS_S[data.status.id]?data.status.id:0;//MAKER_STATUS_Sに定義された物以外はdefaultのマークに var geo=eval("a="+this.data_.geometry); if(geo.coordinates){ if(!isNaN(parseInt(geo.coordinates[1]))&& !isNaN(parseInt(geo.coordinates[0]))){ this.latlng=new google.maps.LatLng(geo.coordinates[1],geo.coordinates[0]); }else{ this.latlng=new google.maps.LatLng("39.8781539650443","139.84579414129257");//往くアテが無いなら富士山でも登りたい } } //this.marker = new google.maps.Marker({'map': this.map_,'position': this.latlng}); this.marker = new google.maps.Marker(); //重なる場合は5mづつ右に座標をずらす var ch=_ad_overlap_man(this.latlng); if(ch){ this.latlng=_m_to_latlon(this.latlng,5*ch,5*ch); }; this.marker.setPosition(this.latlng); MarkerCluster[this.status_id].addMarker(this.marker); // markerclusterを表示(間引き表示) // this.marker.setMap(map);//マーカーでの表示 /* マーカーがクリックされた時 */ var self=this; google.maps.event.addListener(this.marker, 'click', function() { self.show_info(true); }); //重なり管理用 function _ad_overlap_man(latlng){ var v= latlng.toUrlValue(); MapOverlay_Overlap_chlist[v]=(MapOverlay_Overlap_chlist[v]==undefined)?0:++MapOverlay_Overlap_chlist[v]; return MapOverlay_Overlap_chlist[v]; } //距離から緯度経度変換 function _m_to_latlon(latlng,x,y){ var eh=6378137; var lat= (x / eh * Math.cos(latlng.lng() * Math.PI / 180) + latlng.lat() * (Math.PI / 180)) * (180 / Math.PI ); var lng=(y /eh +latlng.lng() *(Math.PI / 180)) * (180 / Math.PI ); return new google.maps.LatLng(lat,lng); } } /** * アイコン生成 */ MapOverlay.prototype.createIco_img = function(is_select,is_large) { var status_id=this.status_id; var color=is_select?MAKER_STATUS_S[99].color:MAKER_STATUS_S[status_id].color; var status= this.data_.status.name.substring(0,1); var rv=""; //アイコンの大小 if(is_large){ rv="http://chart.apis.google.com/chart?chst=d_map_spin&chld=0.8|0|"+color+"|16|b|"+status; }else{ rv="http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld="+status+"|"+color+"|000000"; } return rv; } /** * 吹き出し表示 * @param flg 表示・非表示 */ MapOverlay.prototype.show_info = function(flg) { if(flg){ if(currentInfoWindow){ currentInfoWindow.close(); } this.info.open(this.map_,this.marker); currentInfoWindow=this.info; twttr.widgets.load(); }else{ this.info.close(); currentInfoWindow=undefined; } } MapOverlay.prototype.refresh=function(){ var id=this.id; var description=this.data_.description; var subject=this.data_.subject; var is_select=this.select_comp_list[id]; var is_large=(this.priority==5);//todo::優先度が「今すぐ:5」ならマーカーのサイズを大きくする //完了時と未貼り付け時で吹き出しを変える if(this.data_.status.id==1){ //未貼り付け var t_str='完了したらtwitterに報告<br/><textarea id="tweet_txt_'+id+'" class="tweet_txt" name="tweet_txt" >'+TWEET_FORMAT.replace('<$subject$>',subject)+'</textarea>'; t_str += '<br /><br /><a href="https://twitter.com/intent/tweet?text=' + encodeURIComponent(TWEET_FORMAT.replace('<$subject$>',subject)) + '&url=null" class="twitter-mention-button" data-lang="ja">Tweet to @posterdone</a>'; if(navigator.userAgent.search(/iPhone|Android/) != -1){ t_str += '<br /><br /><a style="text-decoration: underline;" href="twitter://post?message=' + encodeURIComponent(TWEET_FORMAT.replace('<$subject$>',subject)) + '"</a>twitterアプリでツイート</a>'; } //this.info.setContent('<div class="info_w_contents open" style="margin: 5px;">' +'ID:'+id+'<br/>'+subject + '<br/>' + description+'<br/>●'+this.data_.status.name+'<hr/><a onclick="book_mark(this,'+id+')" class="btn comp'+(is_select?" selected":"")+'" >Mark</a></div>'); this.info.setContent('<div class="info_w_contents open" style="margin: 5px;">' +'ID:'+id+'<br/>'+subject + '<br/>' + description+'<br/>●'+this.data_.status.name+'<hr/>'+t_str+'</div>'); }else{ //完了・その他 this.info.setContent('<div class="info_w_contents close other" style="margin: 5px;">' +'ID:'+id+'<br/>'+subject + '<br/>' + description+'<br/>●'+this.data_.status.name+"</div>"); } this.marker.setIcon(this.createIco_img(is_select,is_large)); } MapOverlay.prototype.get_marker_position=function(){ return this.latlng; } MapOverlay.prototype.get_marker=function(){ return this.marker; } /** * markerの削除 */ MapOverlay.prototype.delete_marker=function(){ var p=this.marker.getPosition(); if(p){ MapOverlay_Overlap_chlist[p]=(MapOverlay_Overlap_chlist[p])?--MapOverlay_Overlap_chlist[p]:undefined; } MarkerCluster[this.status_id].removeMarker(this.marker); } /** * markerの一括消去 staticメソッド的に動作 */ MapOverlay.prototype.clear_markers=function(){ for(i in MarkerCluster){ MarkerCluster[i].clearMarkers(); } MapOverlay_Overlap_chlist={}; }
var searchData= [ ['init_5fdetection',['init_detection',['../df/dfe/ncd_8c.html#a09e5952022b76cf427821fee2c4060d4',1,'init_detection():&#160;ncd.c'],['../dc/d68/ncd_8h.html#a09e5952022b76cf427821fee2c4060d4',1,'init_detection():&#160;ncd.c']]], ['ip_5fchecksum',['ip_checksum',['../df/dfe/ncd_8c.html#ad9b2931d45a3e921538a04b9dc56afcf',1,'ip_checksum(void *vdata, size_t length):&#160;ncd.c'],['../dc/d68/ncd_8h.html#ad9b2931d45a3e921538a04b9dc56afcf',1,'ip_checksum(void *vdata, size_t length):&#160;ncd.c']]] ];
var browser = require('bowser').browser; var hasXMLHttpRequest = 'XMLHttpRequest' in global; var hasXDomainRequest = 'XDomainRequest' in global; var support = module.exports = {}; if (hasXMLHttpRequest) { var xhr = new XMLHttpRequest(); support.xhr = {}; support.xhr.getAllResponseHeaders = 'getAllResponseHeaders' in xhr; support.xhr.response = 'response' in xhr; support.xhr.cors = 'withCredentials' in xhr; support.xhr.timeout = 'timeout' in xhr; support.xhr.addEventListener = 'addEventListener' in xhr; support.xhr.responseURL = 'responseURL' in xhr; support.xhr.events = {}; support.xhr.events.loadstart = 'onloadstart' in xhr; support.xhr.events.progress = 'onprogress' in xhr; support.xhr.events.abort = 'onabort' in xhr; support.xhr.events.error = 'onerror' in xhr; support.xhr.events.load = 'onload' in xhr; support.xhr.events.timeout = 'ontimeout' in xhr; support.xhr.events.loadend = 'onloadend' in xhr; support.xhr.events.readystatechange = 'onreadystatechange' in xhr; } if (hasXDomainRequest) { support.xdr = {}; // XDomainRequest implementations are using the same set of features // Only difference is that IE8 does not sends `event` objects in event listeners // And other browsers never sends `event` objects in `progress` listener if (browser.msie && browser.version === '8.0') { support.xdr.eventObjects = []; } else { support.xdr.eventObjects = ['load', 'error', 'timeout']; } }
/** *@Author: chad.ding *@Copyright: 2017-2018 DMF *@Date: 2017-05-25 10:54:27 */ import React, { Component } from 'react'; import { Input, Select } from 'antd'; import './style.less'; export default class SelectInput extends Component { constructor(props) { super(props); let value = this.props.value || {}; this.state = { number: value.number || 1, unit: value.unit || '' }; this.handleNumberChange = this.handleNumberChange.bind(this); this.handleUnitChange = this.handleUnitChange.bind(this); this.triggerChange = this.triggerChange.bind(this); } componentWillReceiveProps(nextProps) { if ('value' in nextProps) { let value = nextProps.value; this.setState(value); } } handleNumberChange(e) { //let number = parseInt(e.target.value || 0, 10); let number = e.target.value; if (isNaN(number)) { return; } if (!('value' in this.props)) { this.setState({ number }); } this.triggerChange({ number }); } handleUnitChange(unit) { if (!('value' in this.props)) { this.setState({ unit }); } this.triggerChange({ unit }); } triggerChange(changedValue) { let onChange = this.props.onChange; if (onChange) { onChange(Object.assign({}, this.state, changedValue)); } } render() { let { size } = this.props; let state = this.state; let Option = Select.Option; return ( <span> <Input type="text" size={size} value={state.number} onChange={this.handleNumberChange} className="input-width"/> <Select value={state.unit} size={size} className="select-width" onChange={this.handleUnitChange}> { this.props.unitMap.map(item => <Option key={item.value} value={item.value}>{item.text}</Option>) } </Select> </span> ); } };
var model = require('./model'); var error = require('../../../error'); var filter = { _id: 0, pwd: 0, __v: 0 }; function getUser(params, callback) { //console.log('GET /user'); var q = model.Q({ uid: 1, pwd: 0 }, params), f = model.F(filter, params); if (q == null) return callback(error.e400); model.User.findOne(q, f).lean().exec(function (err, doc) { if (err) callback(error.e503); else if (doc == null) callback(error.e404); else callback(err, doc); }); } function postUser(params, callback) { //console.log('POST /user'); var m = new model.User(params); m.save(function (err, doc) { if (err) callback(error.e503); else callback(); }); } function putUser(params, callback) { //console.log('PUT /user'); var q = model.Q({ uid: 1 }, params), s = model.S({ nick: 0, gender: 0, image: 0, status: 0, address: 0, phone: 0 }, params); if (q == null || s == null) return callback(error.e400); model.User.update(q, s, function (err) { if (err) callback(error.e503); else callback(); }); } function putUserPwd(params, callback) { //console.log('PUT /user/pwd'); var q = model.Q({ uid: 1, pwd: 1 }, params); if (q == null || params.value === undefined) return callback(error.e400); model.User.update(q, { $set: { pwd: params.value} }, function (err) { if (err) callback(error.e503); else callback(); }); } function postUserQ(params, callback) { //console.log('POST /user/q'); if (!params.uids) return callback(error.e400); var q = { uid: { $in: params.uids} }, f = model.F(filter, params); model.User.find(q, f).lean().exec(function (err, doc) { if (err) callback(error.e503); else callback(err, doc); }); } module.exports = { get: getUser, post: postUser, put: putUser, pwd: { put: putUserPwd }, q: { post: postUserQ } };
import Component from 'ember-component'; import computed from 'ember-computed'; import injectService from 'ember-service/inject'; import {htmlSafe} from 'ember-string'; import {isBlank} from 'ember-utils'; import {isEmberArray} from 'ember-array/utils'; import run from 'ember-runloop'; import layout from '../../templates/components/image-card'; import {invokeAction} from 'ember-invoke-action'; //import ghostPaths from 'ghost-editor/utils/ghost-paths'; import { isRequestEntityTooLargeError, isUnsupportedMediaTypeError, isVersionMismatchError, UnsupportedMediaTypeError } from 'ghost-editor/services/ajax'; export default Component.extend({ layout, tagName: 'section', classNames: ['gh-image-uploader'], classNameBindings: ['dragClass'], image: null, text: '', altText: '', saveButton: true, accept: 'image/gif,image/jpg,image/jpeg,image/png,image/svg+xml', extensions: ['gif', 'jpg', 'jpeg', 'png', 'svg'], validate: null, dragClass: null, failureMessage: null, file: null, formType: 'upload', url: null, uploadPercentage: 0, ajax: injectService(), config: injectService(), notifications: injectService(), // TODO: this wouldn't be necessary if the server could accept direct // file uploads formData: computed('file', function () { let file = this.get('file'); let formData = new FormData(); formData.append('file', file); return formData; }), description: computed('text', 'altText', function () { let altText = this.get('altText'); return this.get('text') || (altText ? `Upload image of "${altText}"` : 'Upload an image'); }), progressStyle: computed('uploadPercentage', function () { let percentage = this.get('uploadPercentage'); let width = ''; if (percentage > 0) { width = `${percentage}%`; } else { width = '0'; } return htmlSafe(`width: ${width}`); }), canShowUploadForm: computed('config.fileStorage', function () { return this.get('config.fileStorage') !== false; }), showUploadForm: computed('formType', function () { let canShowUploadForm = this.get('canShowUploadForm'); let formType = this.get('formType'); return formType === 'upload' && canShowUploadForm; }), didReceiveAttrs() { let image = this.get('payload'); this.set('url', image.img); }, dragOver(event) { let showUploadForm = this.get('showUploadForm'); if (!event.dataTransfer) { return; } // this is needed to work around inconsistencies with dropping files // from Chrome's downloads bar let eA = event.dataTransfer.effectAllowed; event.dataTransfer.dropEffect = (eA === 'move' || eA === 'linkMove') ? 'move' : 'copy'; event.stopPropagation(); event.preventDefault(); if (showUploadForm) { this.set('dragClass', '-drag-over'); } }, dragLeave(event) { let showUploadForm = this.get('showUploadForm'); event.preventDefault(); if (showUploadForm) { this.set('dragClass', null); } }, drop(event) { let showUploadForm = this.get('showUploadForm'); event.preventDefault(); this.set('dragClass', null); if (showUploadForm) { if (event.dataTransfer.files) { this.send('fileSelected', event.dataTransfer.files); } } }, _uploadStarted() { invokeAction(this, 'uploadStarted'); }, _uploadProgress(event) { if (event.lengthComputable) { run(() => { let percentage = Math.round((event.loaded / event.total) * 100); this.set('uploadPercentage', percentage); }); } }, _uploadFinished() { invokeAction(this, 'uploadFinished'); }, _uploadSuccess(response) { this.set('url', response); this.get('payload').img =response; this.get('env').save(this.get('payload'), false); this.send('saveUrl'); this.send('reset'); invokeAction(this, 'uploadSuccess', response); }, _uploadFailed(error) { let message; if (isVersionMismatchError(error)) { this.get('notifications').showAPIError(error); } if (isUnsupportedMediaTypeError(error)) { message = 'The image type you uploaded is not supported. Please use .PNG, .JPG, .GIF, .SVG.'; } else if (isRequestEntityTooLargeError(error)) { message = 'The image you uploaded was larger than the maximum file size your server allows.'; } else if (error.errors && !isBlank(error.errors[0].message)) { message = error.errors[0].message; } else { message = 'Something went wrong :('; } this.set('failureMessage', message); invokeAction(this, 'uploadFailed', error); }, generateRequest() { let ajax = this.get('ajax'); //let formData = this.get('formData'); let file = this.get('file'); let formData = new FormData(); formData.append('uploadimage', file); let url = `${this.get('apiRoot')}/uploads/`; this._uploadStarted(); ajax.post(url, { data: formData, processData: false, contentType: false, dataType: 'text', xhr: () => { let xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', (event) => { this._uploadProgress(event); }, false); xhr.addEventListener('error', event => console.log("error", event)); xhr.upload.addEventListener('error', event => console.log("errorupload", event)); return xhr; } }).then((response) => { let url = JSON.parse(response); this._uploadSuccess(url); }).catch((error) => { this._uploadFailed(error); }).finally(() => { this._uploadFinished(); }); }, _validate(file) { if (this.get('validate')) { return invokeAction(this, 'validate', file); } else { return this._defaultValidator(file); } }, _defaultValidator(file) { let extensions = this.get('extensions'); let [, extension] = (/(?:\.([^.]+))?$/).exec(file.name); if (!isEmberArray(extensions)) { extensions = extensions.split(','); } if (!extension || extensions.indexOf(extension.toLowerCase()) === -1) { return new UnsupportedMediaTypeError(); } return true; }, actions: { fileSelected(fileList) { // can't use array destructuring here as FileList is not a strict // array and fails in Safari // jscs:disable requireArrayDestructuring let file = fileList[0]; // jscs:enable requireArrayDestructuring let validationResult = this._validate(file); this.set('file', file); invokeAction(this, 'fileSelected', file); if (validationResult === true) { run.schedule('actions', this, function () { this.generateRequest(); }); } else { this._uploadFailed(validationResult); } }, onInput(url) { this.set('url', url); invokeAction(this, 'onInput', url); }, reset() { this.set('file', null); this.set('uploadPercentage', 0); }, switchForm(formType) { this.set('formType', formType); run.scheduleOnce('afterRender', this, function () { invokeAction(this, 'formChanged', formType); }); }, saveUrl() { let url = this.get('url'); invokeAction(this, 'update', url); } } });
import { bindActionCreators } from 'redux' import { connect } from 'react-redux'; import * as trayActions from '../actions/trayActions' import { TrayAppPage } from '../components/tray/TrayAppPage.jsx'; function mapStateToProps(store) { return { storyList: store.storyList, timer: store.timer } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(trayActions, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(TrayAppPage)
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), publicPath: 'www/public/assets', resourcesPath: 'www/resources', port: grunt.option('port') || '3003' || '3003', version: '2.15.0', includereplace: { php_views: { options: { globals: { browsersync: ( grunt.option('bs') ) ? '<script type=\'text/javascript\' id="__bs_script__">//<![CDATA[\n\tdocument.write("<script async src=\'http://HOST:<%= port %>/browser-sync/browser-sync-client.<%= version %>.js\'><\\/script>".replace("HOST", location.hostname));\n//]]></script>' : '', } }, expand: true, cwd: 'theme/php/views/', src: '**/*.php', dest: '../<%= resourcesPath %>/views/' }, }, copy: { fonts: { expand: true, cwd: 'theme/fonts/', src: [ '**/*.*', ], dest: '../<%= publicPath %>/fonts/', }, pictos: { expand: true, cwd: 'theme/pictos/', src: [ '**/*.*', ], dest: '../<%= publicPath %>/pictos/', }, php_lang: { expand: true, cwd: 'theme/php/lang/', src: [ '**/*.*', ], dest: '../<%= resourcesPath %>/lang/', }, ckfinder: { expand: true, cwd: 'theme/php/ckfinder/', src: [ '**/*.*', ], dest: '../<%= publicPath %>/ckfinder/', }, }, imagemin: { all: { files: [{ expand: true, cwd: 'theme/images', src: [ '**/*.{png,jpg,gif,svg,ico,mp4,webm}' ], dest: '../<%= publicPath %>/css/images/', }] }, }, concat: { ie_js: { src: [ 'bower_components/html5shiv/dist/html5shiv.min.js', 'bower_components/respond/src/respond.min.js', ], dest: '../<%= publicPath %>/js/ie.min.js', }, lib_js: { src: [ 'bower_components/jquery/dist/jquery.min.js', 'bower_components/jquery-ui/jquery-ui.min.js', 'bower_components/moment/min/moment.min.js', 'bower_components/moment/min/moment-with-locales.min.js', 'bower_components/bootstrap-sass/assets/javascripts/bootstrap.min.js', 'bower_components/eqheight-coffee/jquery.eqheight.js', 'bower_components/moment-duration-format/lib/moment-duration-format.js', 'bower_components/jquery-idleTimeout-plus/dist/js/jquery-idleTimeout-plus-iframe.js', 'bower_components/jquery-storage-api/jquery.storageapi.js', ], dest: '../<%= publicPath %>/js/lib.min.js' }, main_js: { src: [ 'theme/js/main.js', ], dest: '../<%= publicPath %>/js/script.min.js' }, lib_css: { src: [ 'bower_components/fontawesome/css/font-awesome.min.css', 'bower_components/jquery-ui/themes/base/jquery-ui.css', 'bower_components/jquery-idleTimeout-plus/dist/css/jquery-idleTimeout-plus.css', 'bower_components/TimePicki/css/timepicki.css' ], dest: '../<%= publicPath %>/css/lib.min.css' }, }, uglify: { options: { mangle: false }, main_js: { files: { '../<%= publicPath %>/js/script.min.js': [ '../<%= publicPath %>/js/script.min.js' ], } }, }, sass: { options: { sourcemap: 'none' }, main: { files: { '../<%= publicPath %>/css/style.min.css' : 'theme/sass/main/main.scss' }, }, }, postcss: { options: { processors: [ require('autoprefixer')({ browsers: [ 'last 2 versions', 'IE 9', 'IE 10' ] }) ] }, main: { src: '../<%= publicPath %>/css/style.min.css', }, }, cssmin: { main: { files: [{ expand: true, cwd: '../<%= publicPath %>/css', src: [ 'style.min.css' ], dest: '../<%= publicPath %>/css', ext: '.min.css' }] }, }, watch: { main_img: { files: ['theme/img/**/*.*'], tasks: [ 'imagemin:all' ], options: { spawn: false, } }, main_scripts: { files: ['theme/js/**/*.js'], tasks: [ 'concat:main_js', ], options: { spawn: false, } }, php_views: { files: ['theme/php/views/**/*.php'], tasks: [ 'includereplace:php_views', ], options: { spawn: false, } }, ckfinder: { files: ['theme/php/ckfinder/**/*.*'], tasks: [ 'includereplace:ckfinder', ], options: { spawn: false, } }, php_lang: { files: ['theme/php/lang/**/*.php'], tasks: [ 'copy:php_lang', ], options: { spawn: false, } }, main_css: { files: 'theme/sass/**/*.scss', tasks: [ 'sass:main', 'postcss:main', ], options: { spawn: false, } }, }, browserSync: { gen: { bsFiles: { src : [ '../<%= publicPath %>/**/*.*', '../<%= resourcesPath %>/**/*.*', ] }, options: { watchTask: true, port: '<%= port %>', proxy: 'sites.ci', notify: { styles: [ 'z-index: 999', 'opacity: 0.9', 'position: fixed', 'top: calc(50% - 25px)', 'width: 100%', 'height: 50px', 'line-height: 50px', 'background: #333', 'color: #eee', 'text-align: center', ], } } }, }, clean: { options: { force: true, }, files: [ '../<%= publicPath %>/**/*','../<%= resourcesPath %>/views/**/*','../<%= resourcesPath %>/lang/**/*' ], }, }); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-postcss'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-imagemin'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-browser-sync'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-include-replace'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-concurrent'); grunt.registerTask('default', [ 'clean', //JS 'concat:ie_js', 'concat:lib_js', 'concat:main_js', //CSS 'concat:lib_css', //CSS 'sass:main', //PHP 'includereplace:php_views', //CSS // 'postcss:main', //IMG 'imagemin:all', //OTHER 'copy:php_lang', 'copy:ckfinder', 'copy:pictos', 'copy:fonts', ]); grunt.registerTask('prod', [ 'default', //JS 'uglify:main_js', //CSS 'cssmin:main', ]); grunt.registerTask('live', [ 'default', 'browserSync:gen', 'watch' ]); };
/** * o------------------------------------------------------------------------------o * | This file is part of the RGraph package - you can learn more at: | * | | * | http://www.rgraph.net | * | | * | This package is licensed under the RGraph license. For all kinds of business | * | purposes there is a small one-time licensing fee to pay and for non | * | commercial purposes it is free to use. You can read the full license here: | * | | * | http://www.rgraph.net/LICENSE.txt | * o------------------------------------------------------------------------------o */ if (typeof(RGraph) == 'undefined') RGraph = {}; /** * The horizontal bar chart constructor. The horizontal bar is a minor variant * on the bar chart. If you have big labels, this may be useful as there is usually * more space available for them. * * @param object canvas The canvas object * @param array data The chart data */ RGraph.HBar = function (id, data) { // Get the canvas and context objects this.id = id; this.canvas = document.getElementById(id); this.context = this.canvas.getContext ? this.canvas.getContext("2d") : null; this.canvas.__object__ = this; this.data = data; this.type = 'hbar'; this.coords = []; this.isRGraph = true; /** * Compatibility with older browsers */ RGraph.OldBrowserCompat(this.context); this.max = 0; this.stackedOrGrouped = false; // Default properties this.properties = { 'chart.gutter.left': 75, 'chart.gutter.right': 25, 'chart.gutter.top': 35, 'chart.gutter.bottom': 25, 'chart.background.grid': true, 'chart.background.grid.color': '#ddd', 'chart.background.grid.width': 1, 'chart.background.grid.hsize': 25, 'chart.background.grid.vsize': 25, 'chart.background.barcolor1': 'white', 'chart.background.barcolor2': 'white', 'chart.background.grid.hlines': true, 'chart.background.grid.vlines': true, 'chart.background.grid.border': true, 'chart.background.grid.autofit':false, 'chart.background.grid.autofit.numhlines': 14, 'chart.background.grid.autofit.numvlines': 20, 'chart.title': '', 'chart.title.background': null, 'chart.title.xaxis': '', 'chart.title.yaxis': '', 'chart.title.xaxis.pos': 0.25, 'chart.title.yaxis.pos': 10, 'chart.title.hpos': null, 'chart.title.vpos': null, 'chart.text.size': 10, 'chart.text.color': 'black', 'chart.text.font': 'Verdana', 'chart.colors': ['rgb(0,0,255)', '#0f0', '#00f', '#ff0', '#0ff', '#0f0'], 'chart.labels': [], 'chart.labels.above': false, 'chart.labels.above.decimals': 0, 'chart.xlabels': true, 'chart.contextmenu': null, 'chart.key': [], 'chart.key.background': 'white', 'chart.key.position': 'graph', 'chart.key.halign': 'right', 'chart.key.shadow': false, 'chart.key.shadow.color': '#666', 'chart.key.shadow.blur': 3, 'chart.key.shadow.offsetx': 2, 'chart.key.shadow.offsety': 2, 'chart.key.position.gutter.boxed': true, 'chart.key.position.x': null, 'chart.key.position.y': null, 'chart.key.color.shape': 'square', 'chart.key.rounded': true, 'chart.key.linewidth': 1, 'chart.units.pre': '', 'chart.units.post': '', 'chart.units.ingraph': false, 'chart.strokestyle': 'black', 'chart.xmin': 0, 'chart.xmax': 0, 'chart.axis.color': 'black', 'chart.shadow': false, 'chart.shadow.color': '#666', 'chart.shadow.blur': 3, 'chart.shadow.offsetx': 3, 'chart.shadow.offsety': 3, 'chart.vmargin': 3, 'chart.grouping': 'grouped', 'chart.tooltips': null, 'chart.tooltips.event': 'onclick', 'chart.tooltips.effect': 'fade', 'chart.tooltips.css.class': 'RGraph_tooltip', 'chart.tooltips.highlight': true, 'chart.highlight.fill': 'rgba(255,255,255,0.5)', 'chart.highlight.stroke': 'black', 'chart.annotatable': false, 'chart.annotate.color': 'black', 'chart.zoom.factor': 1.5, 'chart.zoom.fade.in': true, 'chart.zoom.fade.out': true, 'chart.zoom.hdir': 'right', 'chart.zoom.vdir': 'down', 'chart.zoom.frames': 10, 'chart.zoom.delay': 50, 'chart.zoom.shadow': true, 'chart.zoom.mode': 'canvas', 'chart.zoom.thumbnail.width': 75, 'chart.zoom.thumbnail.height': 75, 'chart.zoom.background': true, 'chart.zoom.action': 'zoom', 'chart.resizable': false, 'chart.resize.handle.adjust': [0,0], 'chart.resize.handle.background': null, 'chart.scale.point': '.', 'chart.scale.thousand': ',', 'chart.scale.decimals': null } // Check for support if (!this.canvas) { alert('[HBAR] No canvas support'); return; } // Check the canvasText library has been included if (typeof(RGraph) == 'undefined') { alert('[HBAR] Fatal error: The common library does not appear to have been included'); } for (i=0; i<this.data.length; ++i) { if (typeof(this.data[i]) == 'object') { this.stackedOrGrouped = true; } } } /** * A setter * * @param name string The name of the property to set * @param value mixed The value of the property */ RGraph.HBar.prototype.Set = function (name, value) { if (name == 'chart.labels.abovebar') { name = 'chart.labels.above'; } this.properties[name.toLowerCase()] = value; } /** * A getter * * @param name string The name of the property to get */ RGraph.HBar.prototype.Get = function (name) { if (name == 'chart.labels.abovebar') { name = 'chart.labels.above'; } return this.properties[name]; } /** * The function you call to draw the bar chart */ RGraph.HBar.prototype.Draw = function () { /** * Fire the onbeforedraw event */ RGraph.FireCustomEvent(this, 'onbeforedraw'); /** * Clear all of this canvases event handlers (the ones installed by RGraph) */ RGraph.ClearEventListeners(this.id); /** * This is new in May 2011 and facilitates indiviual gutter settings, * eg chart.gutter.left */ this.gutterLeft = this.Get('chart.gutter.left'); this.gutterRight = this.Get('chart.gutter.right'); this.gutterTop = this.Get('chart.gutter.top'); this.gutterBottom = this.Get('chart.gutter.bottom'); /** * Stop the coords array from growing uncontrollably */ this.coords = []; this.max = 0; /** * Check for chart.xmin in stacked charts */ if (this.Get('chart.xmin') > 0 && this.Get('chart.grouping') == 'stacked') { alert('[HBAR] Using chart.xmin is not supported with stacked charts, resetting chart.xmin to zero'); this.Set('chart.xmin', 0); } /** * Work out a few things. They need to be here because they depend on things you can change before you * call Draw() but after you instantiate the object */ this.graphwidth = this.canvas.width - this.gutterLeft - this.gutterRight; this.graphheight = this.canvas.height - this.gutterTop - this.gutterBottom; this.halfgrapharea = this.grapharea / 2; this.halfTextHeight = this.Get('chart.text.size') / 2; // Progressively Draw the chart RGraph.background.Draw(this); this.Drawbars(); this.DrawAxes(); this.DrawLabels(); // Draw the key if necessary if (this.Get('chart.key').length) { RGraph.DrawKey(this, this.Get('chart.key'), this.Get('chart.colors')); } /** * Install the event handlers for tooltips */ if (this.Get('chart.tooltips')) { // Need to register this object for redrawing RGraph.Register(this); /** * Install the window onclick handler */ window.onclick = function () { RGraph.Redraw(); } /** * If the cursor is over a hotspot, change the cursor to a hand */ //this.canvas.onmousemove = function (e) var canvas_onmousemove_func = function (e) { e = RGraph.FixEventObject(e); var canvas = document.getElementById(this.id); var obj = canvas.__object__; /** * Get the mouse X/Y coordinates */ var mouseCoords = RGraph.getMouseXY(e); /** * Loop through the bars determining if the mouse is over a bar */ for (var i=0,len=obj.coords.length; i<len; i++) { var mouseX = mouseCoords[0]; // In relation to the canvas var mouseY = mouseCoords[1]; // In relation to the canvas var left = obj.coords[i][0]; var top = obj.coords[i][1]; var width = obj.coords[i][2]; var height = obj.coords[i][3]; if ( mouseX >= (left) && mouseX <= (left + width) && mouseY >= top && mouseY <= (top + height) && ( typeof(obj.Get('chart.tooltips')) == 'function' || obj.Get('chart.tooltips')[i] ) ) { canvas.style.cursor = 'pointer'; /** * Show the tooltip if the event is onmousemove */ if (obj.Get('chart.tooltips.event') == 'onmousemove') { var tooltipObj = RGraph.Registry.Get('chart.tooltip'); /** * Get the tooltip text */ if (typeof(obj.Get('chart.tooltips')) == 'function') { var text = obj.Get('chart.tooltips')(i); } else if (typeof(obj.Get('chart.tooltips')) == 'object' && typeof(obj.Get('chart.tooltips')[i]) == 'function') { var text = obj.Get('chart.tooltips')[i](i); } else if (typeof(obj.Get('chart.tooltips')) == 'object') { var text = obj.Get('chart.tooltips')[i]; } else { var text = null; } if (text) { if (!tooltipObj || tooltipObj.__index__ != i) { RGraph.HideTooltip(); RGraph.Redraw(); obj.context.beginPath(); obj.context.strokeStyle = obj.Get('chart.highlight.stroke'); obj.context.fillStyle = obj.Get('chart.highlight.fill'); obj.context.strokeRect(left, top, width, height); obj.context.fillRect(left, top, width, height); RGraph.Tooltip(canvas, text, e.pageX, e.pageY, i); } } } return; } canvas.style.cursor = 'default'; } } this.canvas.addEventListener('mousemove', canvas_onmousemove_func, false); RGraph.AddEventListener(this.id, 'mousemove', canvas_onmousemove_func); /** * Install the onclick event handler for the tooltips */ //this.canvas.onclick = function (e) var canvas_onclick_func = function (e) { e = RGraph.FixEventObject(e); //var canvas = document.getElementById(this.id); var canvas = e.target; var obj = canvas.__object__; /** * Redraw the graph first, in effect resetting the graph to as it was when it was first drawn * This "deselects" any already selected bar */ RGraph.Redraw(); /** * Get the mouse X/Y coordinates */ var mouseCoords = RGraph.getMouseXY(e); /** * Loop through the bars determining if the mouse is over a bar */ for (var i=0,len=obj.coords.length; i<len; i++) { var mouseX = mouseCoords[0]; // In relation to the canvas var mouseY = mouseCoords[1]; // In relation to the canvas var left = obj.coords[i][0]; var top = obj.coords[i][1]; var width = obj.coords[i][2]; var height = obj.coords[i][3]; var idx = i; if (mouseX >= left && mouseX <= (left + width) && mouseY >= top && mouseY <= (top + height) ) { /** * Get the tooltip text */ if (typeof(obj.Get('chart.tooltips')) == 'function') { var text = obj.Get('chart.tooltips')(idx); } else if (typeof(obj.Get('chart.tooltips')) == 'object' && typeof(obj.Get('chart.tooltips')[idx]) == 'function') { var text = obj.Get('chart.tooltips')[idx](idx); } else if (typeof(obj.Get('chart.tooltips')) == 'object') { var text = obj.Get('chart.tooltips')[idx]; } else { var text = null; } /** * Show a tooltip if it's defined */ if (String(text).length && text != null) { obj.context.beginPath(); obj.context.strokeStyle = obj.Get('chart.highlight.stroke'); obj.context.fillStyle = obj.Get('chart.highlight.fill'); obj.context.strokeRect(left, top, width, height); obj.context.fillRect(left, top, width, height); obj.context.stroke(); obj.context.fill(); RGraph.Tooltip(canvas, text, e.pageX, e.pageY, i); } } } /** * Stop the event bubbling */ e.stopPropagation(); } this.canvas.addEventListener('click', canvas_onclick_func, false); RGraph.AddEventListener(this.id,'click', canvas_onclick_func); // This resets the bar graph if (RGraph.Registry.Get('chart.tooltip')) { RGraph.Registry.Get('chart.tooltip').style.display = 'none'; RGraph.Registry.Set('chart.tooltip', null) } } /** * Setup the context menu if required */ if (this.Get('chart.contextmenu')) { RGraph.ShowContext(this); } /** * Draw "in graph" labels */ RGraph.DrawInGraphLabels(this); /** * If the canvas is annotatable, do install the event handlers */ if (this.Get('chart.annotatable')) { RGraph.Annotate(this); } /** * This bit shows the mini zoom window if requested */ if (this.Get('chart.zoom.mode') == 'thumbnail' || this.Get('chart.zoom.mode') == 'area') { RGraph.ShowZoomWindow(this); } /** * This function enables resizing */ if (this.Get('chart.resizable')) { RGraph.AllowResizing(this); } /** * Fire the RGraph ondraw event */ RGraph.FireCustomEvent(this, 'ondraw'); } /** * This draws the axes */ RGraph.HBar.prototype.DrawAxes = function () { var halfway = (this.graphwidth / 2) + this.gutterLeft; this.context.beginPath(); this.context.lineWidth = 1; this.context.strokeStyle = this.Get('chart.axis.color'); // Draw the Y axis if (this.Get('chart.yaxispos') == 'center') { this.context.moveTo(halfway, this.gutterTop); this.context.lineTo(halfway, RGraph.GetHeight(this) - this.gutterBottom); } else { this.context.moveTo(this.gutterLeft, this.gutterTop); this.context.lineTo(this.gutterLeft, RGraph.GetHeight(this) - this.gutterBottom); } // Draw the X axis this.context.moveTo(this.gutterLeft, RGraph.GetHeight(this) - this.gutterBottom); this.context.lineTo(RGraph.GetWidth(this) - this.gutterRight, RGraph.GetHeight(this) - this.gutterBottom); // Draw the Y tickmarks var yTickGap = (RGraph.GetHeight(this) - this.gutterTop - this.gutterBottom) / this.data.length; for (y=this.gutterTop; y<(RGraph.GetHeight(this) - this.gutterBottom); y+=yTickGap) { if (this.Get('chart.yaxispos') == 'center') { this.context.moveTo(halfway + 3, y); this.context.lineTo(halfway - 3, y); } else { this.context.moveTo(this.gutterLeft, y); this.context.lineTo( this.gutterLeft - 3, y); } } // Draw the X tickmarks xTickGap = (RGraph.GetWidth(this) - this.gutterLeft - this.gutterRight ) / 10; yStart = RGraph.GetHeight(this) - this.gutterBottom; yEnd = (RGraph.GetHeight(this) - this.gutterBottom) + 3; for (x=(RGraph.GetWidth(this) - this.gutterRight), i=0; this.Get('chart.yaxispos') == 'center' ? x>=this.gutterLeft : x>this.gutterLeft; x-=xTickGap) { if (this.Get('chart.yaxispos') != 'center' || i != 5) { this.context.moveTo(x, yStart); this.context.lineTo(x, yEnd); } i++; } this.context.stroke(); } /** * This draws the labels for the graph */ RGraph.HBar.prototype.DrawLabels = function () { var context = this.context; var canvas = this.canvas; var units_pre = this.Get('chart.units.pre'); var units_post = this.Get('chart.units.post'); var text_size = this.Get('chart.text.size'); var font = this.Get('chart.text.font'); /** * Set the units to blank if they're to be used for ingraph labels only */ if (this.Get('chart.units.ingraph')) { units_pre = ''; units_post = ''; } /** * Draw the X axis labels */ if (this.Get('chart.xlabels')) { this.context.beginPath(); this.context.fillStyle = this.Get('chart.text.color'); if (this.Get('chart.yaxispos') == 'center') { RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (10/10)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, RGraph.number_format(this, Number(this.scale[4]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (9/10)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, RGraph.number_format(this, Number(this.scale[3]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (8/10)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, RGraph.number_format(this, Number(this.scale[2]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (7/10)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, RGraph.number_format(this, Number(this.scale[1]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (6/10)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, RGraph.number_format(this, Number(this.scale[0]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (4/10)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, '-' + RGraph.number_format(this, Number(this.scale[0]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (3/10)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, '-' + RGraph.number_format(this, Number(this.scale[1]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (2/10)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, '-' + RGraph.number_format(this, Number(this.scale[2]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (1/10)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, '-' + RGraph.number_format(this, Number(this.scale[3]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (0)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, '-' + RGraph.number_format(this, Number(this.scale[4]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); } else { RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (5/5)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, RGraph.number_format(this, Number(this.scale[4]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (4/5)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, RGraph.number_format(this, Number(this.scale[3]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (3/5)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, RGraph.number_format(this, Number(this.scale[2]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (2/5)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, RGraph.number_format(this, Number(this.scale[1]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); RGraph.Text(context, font, text_size, this.gutterLeft + (this.graphwidth * (1/5)), this.gutterTop + this.halfTextHeight + this.graphheight + 2, RGraph.number_format(this, Number(this.scale[0]).toFixed(this.Get('chart.scale.decimals')), units_pre, units_post), 'center', 'center'); if (this.Get('chart.xmin') > 0) { RGraph.Text(context,font,text_size,this.gutterLeft,this.gutterTop + this.halfTextHeight + this.graphheight + 2,RGraph.number_format(this, this.Get('chart.xmin'), units_pre, units_post),'center','center'); } } this.context.fill(); this.context.stroke(); } /** * The Y axis labels */ if (typeof(this.Get('chart.labels')) == 'object') { var xOffset = 5; var font = this.Get('chart.text.font'); // Draw the X axis labels this.context.fillStyle = this.Get('chart.text.color'); // How wide is each bar var barHeight = (RGraph.GetHeight(this) - this.gutterTop - this.gutterBottom ) / this.Get('chart.labels').length; // Reset the xTickGap yTickGap = (RGraph.GetHeight(this) - this.gutterTop - this.gutterBottom) / this.Get('chart.labels').length // Draw the X tickmarks var i=0; for (y=this.gutterTop + (yTickGap / 2); y<=RGraph.GetHeight(this) - this.gutterBottom; y+=yTickGap) { RGraph.Text(this.context, font,this.Get('chart.text.size'),this.gutterLeft - xOffset,y,String(this.Get('chart.labels')[i++]),'center','right'); } } } /** * This function draws the actual bars */ RGraph.HBar.prototype.Drawbars = function () { this.context.lineWidth = 1; this.context.strokeStyle = this.Get('chart.strokestyle'); this.context.fillStyle = this.Get('chart.colors')[0]; var prevX = 0; var prevY = 0; /** * Work out the max value */ if (this.Get('chart.xmax')) { this.scale = [ (((this.Get('chart.xmax') - this.Get('chart.xmin')) * 0.2) + this.Get('chart.xmin')).toFixed(this.Get('chart.scale.decimals')), (((this.Get('chart.xmax') - this.Get('chart.xmin')) * 0.4) + this.Get('chart.xmin')).toFixed(this.Get('chart.scale.decimals')), (((this.Get('chart.xmax') - this.Get('chart.xmin')) * 0.6) + this.Get('chart.xmin')).toFixed(this.Get('chart.scale.decimals')), (((this.Get('chart.xmax') - this.Get('chart.xmin')) * 0.8) + this.Get('chart.xmin')).toFixed(this.Get('chart.scale.decimals')), (((this.Get('chart.xmax') - this.Get('chart.xmin')) + this.Get('chart.xmin'))).toFixed(this.Get('chart.scale.decimals')) ]; this.max = this.scale[4]; } else { var grouping = this.Get('chart.grouping'); for (i=0; i<this.data.length; ++i) { if (typeof(this.data[i]) == 'object') { var value = grouping == 'grouped' ? Number(RGraph.array_max(this.data[i], true)) : Number(RGraph.array_sum(this.data[i])) ; } else { var value = Number(Math.abs(this.data[i])); } this.max = Math.max(Math.abs(this.max), Math.abs(value)); } this.scale = RGraph.getScale(this.max, this); /** * Account for chart.xmin */ if (this.Get('chart.xmin') > 0) { this.scale[0] = Number((((this.scale[4] - this.Get('chart.xmin')) * 0.2) + this.Get('chart.xmin')).toFixed(this.Get('chart.scale.decimals'))); this.scale[1] = Number((((this.scale[4] - this.Get('chart.xmin')) * 0.4) + this.Get('chart.xmin')).toFixed(this.Get('chart.scale.decimals'))); this.scale[2] = Number((((this.scale[4] - this.Get('chart.xmin')) * 0.6) + this.Get('chart.xmin')).toFixed(this.Get('chart.scale.decimals'))); this.scale[3] = Number((((this.scale[4] - this.Get('chart.xmin')) * 0.8) + this.Get('chart.xmin')).toFixed(this.Get('chart.scale.decimals'))); this.scale[4] = Number((((this.scale[4] - this.Get('chart.xmin')) * 1.0) + this.Get('chart.xmin')).toFixed(this.Get('chart.scale.decimals'))); } this.max = this.scale[4]; } if (this.Get('chart.scale.decimals') == null && Number(this.max) == 1) { this.Set('chart.scale.decimals', 1); } /** * The bars are drawn HERE */ var graphwidth = (this.canvas.width - this.gutterLeft - this.gutterRight); var halfwidth = graphwidth / 2; for (i=0; i<this.data.length; ++i) { // Work out the width and height var width = (this.data[i] / this.max) * graphwidth; var height = this.graphheight / this.data.length; var orig_height = height; var x = this.gutterLeft; var y = this.gutterTop + (i * height); var vmargin = this.Get('chart.vmargin'); // Account for negative lengths - Some browsers (eg Chrome) don't like a negative value if (width < 0) { x -= width; width = Math.abs(width); } /** * Turn on the shadow if need be */ if (this.Get('chart.shadow')) { this.context.shadowColor = this.Get('chart.shadow.color'); this.context.shadowBlur = this.Get('chart.shadow.blur'); this.context.shadowOffsetX = this.Get('chart.shadow.offsetx'); this.context.shadowOffsetY = this.Get('chart.shadow.offsety'); } /** * Draw the bar */ this.context.beginPath(); if (typeof(this.data[i]) == 'number') { var barHeight = height - (2 * vmargin); var barWidth = ((this.data[i] - this.Get('chart.xmin')) / (this.max - this.Get('chart.xmin'))) * this.graphwidth; var barX = this.gutterLeft; // Account for Y axis pos if (this.Get('chart.yaxispos') == 'center') { barWidth /= 2; barX += halfwidth; } // Set the fill color this.context.strokeStyle = this.Get('chart.strokestyle'); this.context.fillStyle = this.Get('chart.colors')[0]; this.context.strokeRect(barX, this.gutterTop + (i * height) + this.Get('chart.vmargin'), barWidth, barHeight); this.context.fillRect(barX, this.gutterTop + (i * height) + this.Get('chart.vmargin'), barWidth, barHeight); this.coords.push([barX, y + vmargin, barWidth, height - (2 * vmargin), this.Get('chart.colors')[0], this.data[i], true]); /** * Stacked bar chart */ } else if (typeof(this.data[i]) == 'object' && this.Get('chart.grouping') == 'stacked') { if (this.Get('chart.yaxispos') == 'center') { alert('[HBAR] You can\'t have a stacked chart with the Y axis in the center, change it to grouped'); } var barHeight = height - (2 * vmargin); for (j=0; j<this.data[i].length; ++j) { // Set the fill/stroke colors this.context.strokeStyle = this.Get('chart.strokestyle'); this.context.fillStyle = this.Get('chart.colors')[j]; var width = (((this.data[i][j]) / (this.max))) * this.graphwidth; var totalWidth = (RGraph.array_sum(this.data[i]) / this.max) * this.graphwidth; this.context.strokeRect(x, this.gutterTop + this.Get('chart.vmargin') + (this.graphheight / this.data.length) * i, width, height - (2 * vmargin) ); this.context.fillRect(x, this.gutterTop + this.Get('chart.vmargin') + (this.graphheight / this.data.length) * i, width, height - (2 * vmargin) ); /** * Store the coords for tooltips */ // The last property of this array is a boolean which tells you whether the value is the last or not this.coords.push([x, y + vmargin, width, height - (2 * vmargin), this.Get('chart.colors')[j], RGraph.array_sum(this.data[i]), j == (this.data[i].length - 1) ]); x += width; } /** * A grouped bar chart */ } else if (typeof(this.data[i]) == 'object' && this.Get('chart.grouping') == 'grouped') { for (j=0; j<this.data[i].length; ++j) { /** * Turn on the shadow if need be */ if (this.Get('chart.shadow')) { RGraph.SetShadow(this, this.Get('chart.shadow.color'), this.Get('chart.shadow.offsetx'), this.Get('chart.shadow.offsety'), this.Get('chart.shadow.blur')); } // Set the fill/stroke colors this.context.strokeStyle = this.Get('chart.strokestyle'); this.context.fillStyle = this.Get('chart.colors')[j]; var width = ((this.data[i][j] - this.Get('chart.xmin')) / (this.max - this.Get('chart.xmin'))) * (RGraph.GetWidth(this) - this.gutterLeft - this.gutterRight ); var individualBarHeight = (height - (2 * vmargin)) / this.data[i].length; var startX = this.gutterLeft; var startY = y + vmargin + (j * individualBarHeight); // Account for the Y axis being in the middle if (this.Get('chart.yaxispos') == 'center') { width /= 2; startX += halfwidth; } if (width < 0) { startX += width; width *= -1; } this.context.strokeRect(startX, startY, width, individualBarHeight); this.context.fillRect(startX, startY, width, individualBarHeight); this.coords.push([startX, startY, width, individualBarHeight, this.Get('chart.colors')[j], this.data[i][j], true]); } } this.context.closePath(); } this.context.fill(); this.context.stroke(); /** * Now the bars are stroke()ed, turn off the shadow */ RGraph.NoShadow(this); this.RedrawBars(); } /** * This function goes over the bars after they been drawn, so that upwards shadows are underneath the bars */ RGraph.HBar.prototype.RedrawBars = function () { var coords = this.coords; var font = this.Get('chart.text.font'); var size = this.Get('chart.text.size'); var color = this.Get('chart.text.color'); RGraph.NoShadow(this); this.context.strokeStyle = this.Get('chart.strokestyle'); for (var i=0; i<coords.length; ++i) { if (this.Get('chart.shadow')) { this.context.beginPath(); this.context.strokeStyle = this.Get('chart.strokestyle'); this.context.fillStyle = coords[i][4]; this.context.lineWidth = 1; this.context.strokeRect(coords[i][0], coords[i][1], coords[i][2], coords[i][3]); this.context.fillRect(coords[i][0], coords[i][1], coords[i][2], coords[i][3]); this.context.fill(); this.context.stroke(); } /** * Draw labels "above" the bar */ if (this.Get('chart.labels.above') && coords[i][6]) { this.context.fillStyle = color; this.context.strokeStyle = 'black'; RGraph.NoShadow(this); var border = (coords[i][0] + coords[i][2] + 7 + this.context.measureText(this.Get('chart.units.pre') + this.coords[i][5] + this.Get('chart.units.post')).width) > RGraph.GetWidth(this) ? true : false; RGraph.Text(this.context, font, size, coords[i][0] + coords[i][2] + (border ? -5 : 5), coords[i][1] + (coords[i][3] / 2), RGraph.number_format(this, (this.coords[i][5]).toFixed(this.Get('chart.labels.above.decimals')), this.Get('chart.units.pre'), this.Get('chart.units.post')), 'center', border ? 'right' : 'left', border, null, border ? 'rgba(255,255,255,0.9)' : null); } } }
(function($) { var jClock = window.jClock = function(clock, canvas, options) { var ctx, img; // Canvas isn't supported, abort if(!(ctx = canvas.getContext('2d'))) return; options = $.extend(true, {}, jClock.defaults, options); img = new Image(); img.src = clock; // Need to wait until after the image is loaded img.onload = function() { tick(); setInterval(tick, 1000); }; // The ticker, draws the clock upon each tick function tick() { var now = new Date(), sec = now.getSeconds(), min = now.getMinutes(), hour = now.getHours(); if(hour > 12) hour = hour % 12; // do the clock drawClock(); // do the second hand if(options.secondHand === true) drawHand(sec * Math.PI/30, options.second); // do the minute hand drawHand((min + sec/60) * Math.PI/30, options.minute); // do the hour hand drawHand((hour + sec/3600 + min/60) * Math.PI/6, options.hour); } function drawClock() { ctx.clearRect(0, 0, options.height, options.width); ctx.drawImage(img, 0, 0, options.width, options.height); ctx.save(); } function drawHand(radians, opts) { radians -= 90 * Math.PI/180; // fix orientation ctx.save(); ctx.beginPath(); ctx.translate(options.height/2, options.width/2); // Set hand styles ctx.strokeStyle = opts.color; ctx.lineWidth = opts.width; ctx.globalAlpha = opts.alpha; if (options.shadow === true) { ctx.shadowOffsetX = 2; ctx.shadowOffsetY = 2; ctx.shadowBlur = 1; ctx.shadowColor = 'rgba(0, 0, 0, 0.5)'; } ctx.rotate(radians); ctx.moveTo(opts.start, 0); ctx.lineTo(opts.end, 0); ctx.stroke(); ctx.restore(); } }; // Default options jClock.defaults = { height: 125, width: 125, secondHand: true, shadow: true, second: { color: '#f00', width: 2, start: -10, end: 35, alpha: 1 }, minute: { color: '#fff', width: 3, start: -7, end: 30, alpha: 1 }, hour: { color: '#fff', width: 4, start: -7, end: 20, alpha: 1 } }; })(jQuery);
// ========================================================================== // Project: SproutCore - JavaScript Application Framework // Copyright: ©2006-2011 Strobe Inc. and contributors. // portions copyright @2009 Apple Inc. // License: Licensed under MIT license (see license.js) // ========================================================================== /*globals module test ok equals same */ var object ; module("object.registerDependentKeys()", { setup: function() { object = SC.Object.create({ // normal properties firstName: 'John', lastName: 'Doe', observedValue: '', // computed property fullName: function() { return this.getEach('firstName','lastName').compact().join(' '); }.property(), // init to setup registerDependentKey... init: function() { sc_super(); this.registerDependentKey('fullName', 'firstName', 'lastName'); }, //observer that should fire whenever the 'fullName' property changes fullNameDidChange: function() { this.set('observedValue', this.get('fullName')) ; }.observes('fullName') }); } }); test("should indicate the registered property changes if the dependent key value changes", function() { // now, change the firstName... object.set('firstName', 'Jane'); // since fullName is 'dependent' on firstName, then the observer for // 'fullName' should fire here because you changed a dependent key. equals(object.get('observedValue'), 'Jane Doe'); // now change the lastName object.set('lastName', 'Johnson'); // again, fullName is 'dependent' on lastName, so observer for // fullName should fire. equals(object.get('observedValue'), 'Jane Johnson'); }); test("should indicate the registered property changes if the dependent key value changes and change is within begin property loop ", function() { // Wrap the changes with begin property changes call object.beginPropertyChanges(); // now, change the firstName & lastname... object.set('firstName', 'Jane'); object.set('lastName', 'Johnson'); // The observer for fullName should not have fired yet at this // point because we are inside a propertyChange loop. equals(object.get('observedValue'), ''); //End the property changes loop. object.endPropertyChanges(); // now change the lastName object.set('lastName', 'Johnson'); // again, fullName is 'dependent' on lastName, so observer for // fullName should fire. equals(object.get('observedValue'), 'Jane Johnson'); });
'use strict'; angular.module('roadServerApp') .factory('Auth', function Auth($location, $rootScope, $http, User, $cookieStore, $q) { var currentUser = {}; if($cookieStore.get('token')) { currentUser = User.get(); } return { /** * Authenticate user and save token * * @param {Object} user - login info * @param {Function} callback - optional * @return {Promise} */ login: function(user, callback) { var cb = callback || angular.noop; var deferred = $q.defer(); $http.post('/auth/local', { email: user.email, password: user.password }). success(function(data) { $cookieStore.put('token', data.token); currentUser = User.get(); deferred.resolve(data); return cb(); }). error(function(err) { this.logout(); deferred.reject(err); return cb(err); }.bind(this)); return deferred.promise; }, /** * Delete access token and user info * * @param {Function} */ logout: function() { $cookieStore.remove('token'); currentUser = {}; }, /** * Create a new user * * @param {Object} user - user info * @param {Function} callback - optional * @return {Promise} */ createUser: function(user, callback) { var cb = callback || angular.noop; return User.save(user, function(data) { $cookieStore.put('token', data.token); currentUser = User.get(); return cb(user); }, function(err) { this.logout(); return cb(err); }.bind(this)).$promise; }, /** * Change password * * @param {String} oldPassword * @param {String} newPassword * @param {Function} callback - optional * @return {Promise} */ changePassword: function(oldPassword, newPassword, callback) { var cb = callback || angular.noop; return User.changePassword({ id: currentUser._id }, { oldPassword: oldPassword, newPassword: newPassword }, function(user) { return cb(user); }, function(err) { return cb(err); }).$promise; }, /** * Gets all available info on authenticated user * * @return {Object} user */ getCurrentUser: function() { return currentUser; }, /** * Check if a user is logged in * * @return {Boolean} */ isLoggedIn: function() { return currentUser.hasOwnProperty('role'); }, /** * Waits for currentUser to resolve before checking if user is logged in */ isLoggedInAsync: function(cb) { if(currentUser.hasOwnProperty('$promise')) { currentUser.$promise.then(function() { cb(true); }).catch(function() { cb(false); }); } else if(currentUser.hasOwnProperty('role')) { cb(true); } else { cb(false); } }, /** * Check if a user is an admin * * @return {Boolean} */ isAdmin: function() { return currentUser.role === 'admin'; }, /** * Get auth token */ getToken: function() { return $cookieStore.get('token'); } }; });
"use strict"; module.exports = function (grunt) { //project configuration grunt.initConfig({ // 通过connect任务,创建一个静态服务器 connect: { options: { port: 8000, // 服务器端口号,默认为8000 hostname: 'localhost', // 服务器地址(可以使用主机名localhost,也能使用IP) base: './www-root'// 站点的根目录,物理路径(默认为Gruntfile.js所在目录,即值为".") }, livereload: { options: { middleware: function (connect, options, middlewares) { /** * 使用connect-livereload模块,生成一个LiveReload脚本,并通过LiveReload脚本,让页面重新加载: * <script src="http://127.0.0.1:35729/livereload.js?snipver=1" type="text/javascript"></script> */ var lrSnippet = require('connect-livereload')({ port: grunt.config.get('watch').client.options.livereload }); middlewares.unshift(lrSnippet); return middlewares; } } } }, // 检测文件变更,用于开发环境 watch: { // Gruntfile.js变更时:重新加载watch configFiles: { files: ['Gruntfile.js'], options: { reload: true } }, // 这里的文件变化之后,自动调用LiveReload刷新浏览器 client: { options: { livereload: 35729 // LiveReload的端口号,默认为35729 }, files: ['<%=connect.options.base || "."%>/*.html'] } } }); //加载各种grunt插件任务 grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-connect'); //创建服务器且免F5实时刷新页面 grunt.registerTask('default', ['connect', 'watch']); };
/* * This is a catch all, for when nothing is working * on a matched route on the server. */ export default () => { return new Promise((resolve) => { resolve({ status: 404, payload: 'Not found' }); }); }
import React, {Component, PropTypes} from 'react'; import { connect } from 'react-redux' import { Table, message } from 'antd' class List extends Component { render() { const { total, list, getList, id } = this.props const pagination = { total, showTotal: total => `共${total}条`, onChange: offset => getList({ offset, limit: 9, section_id: id }, null, error => message.error(error)) } const columns = [{ }] return ( <Table pagination={pagination} columns={columns} dataSource={list}/> ); } } List.propTypes = { list: PropTypes.object.isRequired, total: PropTypes.number.isRequired, getList: PropTypes.func.isRequired, id: PropTypes.string.isRequired }; export default connect( state => ({ list: state.papers.list, id: state.routing.locationBeforeTransitions.query.id }), dispatch => ({ getList: (params, resolve, reject) => dispatch({ type: 'papers/list', payload: { params, resolve, reject } }) }) )(List);
/** * Porsche.js is licensed under the MIT license. If a copy of the * MIT-license was not distributed with this file, You can obtain one at: * http://opensource.org/licenses/mit-license.html. * * @author: Yang Yang ([email protected]) * @license MIT * @copyright Yang Yang, 2015 */ "use strict"; var Class = require("../../class"); var YObject = require("../../yobject"); Class.define("framework.ui.gesture.Util", YObject, { static: { /** * extend object. * means that properties in dest will be overwritten by the ones in src. * @param {Object} dest * @param {Object} src * @param {Boolean} [merge] * @return {Object} dest */ extend: function(dest, src, merge) { var keys = Object.keys(src); var i = 0; while (i < keys.length) { if (!merge || merge && dest[keys[i]] === undefined) { dest[keys[i]] = src[keys[i]]; } i++; } return dest; }, /** * merge the values from src in the dest. * means that properties that exist in dest will not be overwritten by src * @param {Object} dest * @param {Object} src * @return {Object} dest */ merge: function(dest, src) { return this.extend(dest, src, true); }, /** * let a boolean value also be a function that must return a boolean * this first item in args will be used as the context * @param {Boolean|Function} val * @param {Array} [args] * @return {Boolean} */ boolOrFn: function(val, args) { if (typeof val === "function") { return val.apply(args ? args[0] || undefined : undefined, args); } return val; }, /** * use the val2 when val1 is undefined * @param {*} val1 * @param {*} val2 * @return {*} */ ifUndefined: function(val1, val2) { return val1 === undefined ? val2 : val1; }, /** * find if a array contains the object using indexOf or a simple polyFill * @param {Array} src * @param {String} find * @param {String} [findByKey] * @return {Boolean|Number} false when not found, or the index */ inArray: function(src, find, findByKey) { if (src.indexOf && !findByKey) { return src.indexOf(find); } else { var i = 0; while (i < src.length) { if (findByKey && src[i][findByKey] === find || !findByKey && src[i] === find) { return i; } i++; } return -1; } }, /** * convert array-like objects to real arrays * @param {Object} obj * @return {Array} */ toArray: function(obj) { return Array.prototype.slice.call(obj, 0); }, /** * unique array with objects based on a key (like 'id') or just by the array's value * @param {Array} src [{id:1},{id:2},{id:1}] * @param {String} [key] * @param {Boolean} [sort=False] * @return {Array} [{id:1},{id:2}] */ uniqueArray: function(src, key, sort) { var results = []; var values = []; var i = 0; while (i < src.length) { var val = key ? src[i][key] : src[i]; if (this.inArray(values, val) < 0) { results.push(src[i]); } values[i] = val; i++; } if (sort) { if (!key) { results = results.sort(); } else { results = results.sort(function sortUniqueArray(a, b) { return a[key] > b[key]; }); } } return results; }, /** * get a unique id * @return {number} uniqueId */ uniqueId: function() { if (global._uniqueId === undefined) { global._uniqueId = 0; } return global._uniqueId++; } } }, module);
'use strict'; var _ = require('lodash'); var Collection = require('./Collection'); var io = require('../services/io'); var session = require('../models/session'); var uris = require('../services/uris'); var Modules = Collection.extend({ model: require('../models/Module'), initialize: function () { _.bindAll(this); }, hydrate: function () { this.url = uris('modules', { clientId: session.get('clientId') }); this.reset(); this.fetch({ beforeSend: session.inject, error: function () { io.crit('failed to retrieve modules'); } }); }, parse: function (raw) { raw = raw.modules ? raw.modules : raw; // [KE] personal modules should not be displayed via widget var parsed = _.filter(raw, function (m) { return !m.module.meta.isPersonal; }); return parsed; } }); var modules = new Modules(); module.exports = modules;
/** * Created by koqiui on 2017-04-09. */ (function (global, factory) { var theExports = null; var hasModuleExports = false; if(typeof module === "object" && typeof module.exports === "object") { theExports = module.exports; hasModuleExports = true; } else {//导出为模块 theExports = global['Routes'] = {}; } factory(theExports, hasModuleExports); }(typeof window !== "undefined" ? window : this, function (exports, hasModuleExports) { exports.__name__ = 'Routes'; // if(hasModuleExports) { console && console.log('以模块方式导入[' + exports.__name__ + ']'); } else { console && console.log('以普通方式引入[' + exports.__name__ + ']'); } //--------------------------------------------------------------------------------- var __showDebug = true; var __registFunction = null; //[{path, component}, ...] var __routeMaps = []; //是否检查重复或覆盖注册 var __checkDuplicates = true; //{ path => component} var __routeMapAll = {}; var __routeRegistStates = {}; // function makeSubRoutes(subComps) { subComps = subComps || []; var children = []; for(var i = 0; i < subComps.length; i++) { var comp = subComps[i]; children[i] = { path: comp.path, component: comp, desc: comp.desc }; } // if(children.length > 0) { //插入默认路由 var first = children[0]; children.unshift({ path: '', component: first.component, desc: first.desc }); } // return children; } //----------------------------------- exports ------------------------------------- // exports.debug = function (showDebug) { __showDebug = showDebug; }; //是否检查重复注册 exports.checkDuplicates = function (trueOrFalse) { __checkDuplicates = trueOrFalse !== false; }; //设置注册函数 exports.setRegistFunction = function (registFn) { __registFunction = registFn; }; // exports.add = function () { var routeMaps = arguments; for(var i = 0; i < routeMaps.length; i++) { var routeMap = routeMaps[i]; // if(routeMap == null) { console.warn('缺少参数 或 所要注册的路由组件 尚未加载(往往是因为存在双向依赖导致的)'); } else { var name, desc, path, comp; // var name = routeMap['name']; if(name != null && routeMap['data'] != null) { //传入的是组件 comp = routeMap; desc = comp.desc; path = comp.path; if(path == null) { console.error('组件' + (desc == null ? '' : '(' + desc + ')') + '缺少 path 信息,不能注册为路由组件 : <' + name + '>'); continue; } // routeMap = { path: path, component: comp }; // if(desc != null) { routeMap.desc = desc; } // var subRoutes = comp['subRoutes'] || null; if(subRoutes != null && subRoutes.length > 0) { routeMap.children = makeSubRoutes(subRoutes); } } else { //传入的是配置对象 desc = routeMap.desc; path = routeMap.path; comp = routeMap.component; if(comp == null) { console.warn('找不到路由 ' + path + ' 对应的组件,或 所要注册的路由组件 尚未加载' + (desc == null ? '' : '(' + desc + ')') + '!'); continue; } name = comp.name; if(path == null) { console.error('组件' + (desc == null ? '' : '(' + desc + ')') + '缺少 path 信息,不能注册为路由组件 : <' + name + '>'); continue; } } if(__checkDuplicates) { var existed = __routeMapAll[path]; if(existed != null) { if(comp == existed) { console.warn('路由重复:' + path + ' => ' + (name || '<未命名>') + (desc == null ? '' : '(' + desc + ')')); } else { console.error('路由覆盖:' + path + ' => ' + (name || '<未命名>') + (desc == null ? '' : '(' + desc + ')') + ' 要覆盖 ' + (existed.name || '<未命名>') + (existed.desc == null ? '' : '(' + existed.desc + ')')); } // continue; } } // if(typeof __registFunction == 'function') { //注册路由时注册组件 __registFunction(comp); if(__showDebug) { console.log('路由 ' + path + ' ' + (desc == null ? '' : '(' + desc + ')') + ' <' + name + '> 已加入 并且 已【注册组件】'); } } else { if(__showDebug) { console.log('路由 ' + path + ' ' + (desc == null ? '' : '(' + desc + ')') + ' <' + name + '> 已加入'); } } // __routeMapAll[path] = comp; // if(routeMap.children) { //修正/注册子路由 var parentPath = routeMap.path; var children = routeMap.children; for(var i = 0; i < children.length; i++) { var childMap = children[i]; var childComp = childMap.component; if(childComp.path.charAt(0) == '/') { console.warn('子 路由组件(除有独立使用的场景,否则它)的 path 不应该 以 "/" 开头'); } var childPath = childMap.path; if(childPath.charAt(0) == '/') { childPath = childPath.substring(1); childMap.path = childPath; } var fullPath = parentPath + (childPath ? "/" + childPath : ""); // childComp.fullPath = fullPath; __routeMapAll[fullPath] = childComp; // var registed = false; if(typeof __registFunction == 'function') { __registFunction(childComp); // registed = true; } // if(__showDebug) { var desc = childComp.desc; var name = childComp.name; console.log('子 路由 ' + fullPath + ' ' + (desc == null ? '' : '(' + desc + ')') + ' <' + name + '> 已加入' + (registed ? ' 并且 已【注册组件】' : '')); } } } // __routeMaps.push(routeMap); } } }; exports.get = function (path) { return __routeMapAll[path]; }; exports.all = function () { return __routeMaps; }; exports.clear = function () { __routeMaps.length = 0; __routeMapAll = {}; }; }));
import { Animated, Dimensions, Image, StyleSheet, View } from 'react-native'; import React, { Component } from 'react'; import { HexagonView } from '../hexagonView'; import PropTypes from 'prop-types'; import { isEqual } from 'lodash'; const { width: WINDOW_WIDTH, height: WINDOW_HEIGHT } = Dimensions.get('window'); const normalSize = WINDOW_WIDTH / 2.5 - WINDOW_HEIGHT / 150; const styles = StyleSheet.create({ fillAbsolute: { ...StyleSheet.absoluteFillObject, }, secondImageView: { flexGrow: 1, }, bumpAtTop: { marginTop: -13 }, overlay: { position: 'absolute', right: 0, left: 0, bottom: 0, } }); export class HexagonImage extends Component { static propTypes = { ...View.propTypes, ...Image.propTypes, borderWidth: PropTypes.number, borderColor: PropTypes.string, backgroundColor: PropTypes.string, size: PropTypes.number.isRequired, isHorizontal: PropTypes.bool, transitionDuration: PropTypes.number, src: PropTypes.oneOfType([ Image.propTypes.source, PropTypes.arrayOf(Image.propTypes.source) ]).isRequired, cornerRadius: PropTypes.number, animate: PropTypes.bool, prop: PropTypes.any, timingBetween: PropTypes.shape({ min: PropTypes.number, max: PropTypes.number }) }; static defaultProps = { animate: false, transitionDuration: 500, timingBetween: { min: 2000, max: 5000 } }; constructor(props, context) { super(props, context); this.state = { opacity: new Animated.Value(1), opacitySecond: new Animated.Value(0), currImageIndex: 0, nextImageIndex: 1 }; this.frameShowedCount = 1; this.showFrontImage = true; this.animateViews = this.animateViews.bind(this); this.reset = this.reset.bind(this); this.getNextInvocationTimeout = this.getNextInvocationTimeout.bind(this); this.timeout = null; this._isMounted = false; } componentWillMount() { this._isMounted = true; if ( !Array.isArray(this.props.src) || !this.props.animate || this.props.src.length < 2 ) { return; } this.timeout = setTimeout(() => { this.animateViews(); }, this.getNextInvocationTimeout()); } componentWillReceiveProps(nextProps) { if (!isEqual(this.props.src, nextProps.src)) { this.reset(); } if ( nextProps.animate !== this.props.animate || !isEqual(this.props.src, nextProps.src) ) { this.clearTimeouts(); this.timeout = setTimeout(() => { this.animateViews(nextProps.animate); }, this.getNextInvocationTimeout()); } } shouldComponentUpdate(nProps, nState) { const shouldUpdateProps = !isEqual(this.props, nProps); const shouldUpdateState = !isEqual(this.state, nState); return shouldUpdateState || shouldUpdateProps; } componentWillUnmount() { this._isMounted = false; this.clearTimeouts(); } reset() { this.state.opacity.setValue(1); this.state.opacitySecond.setValue(0); this.frameShowedCount = 1; this.showFrontImage = true; this._isMounted && this.setState({ currImageIndex: 0, nextImageIndex: 1 }); } clearTimeouts() { if (this.timeout) { clearTimeout(this.timeout); } this.timeout = null; } animateViews(useAnimate) { const { src, animate, transitionDuration } = this.props; const { currImageIndex, nextImageIndex } = this.state; const shouldAnimate = typeof useAnimate !== 'undefined' ? useAnimate : animate; if (!Array.isArray(src) || !shouldAnimate || src.length < 2) { return; } this.clearTimeouts(); const MAX_INDEX = src.length - 1; const nextInvocation = this.getNextInvocationTimeout(); const showFrontImage = this.showFrontImage = !this.showFrontImage; let nextIndex = this.frameShowedCount === 1 ? currImageIndex + 2 : currImageIndex; let prepareIndex = this.frameShowedCount === 2 ? nextImageIndex + 2 : nextImageIndex; if (nextIndex > MAX_INDEX) { nextIndex -= MAX_INDEX; nextIndex--; } if (showFrontImage && prepareIndex > MAX_INDEX) { prepareIndex -= MAX_INDEX; prepareIndex--; } Animated.parallel([ Animated.timing(this.state.opacity, { toValue: showFrontImage ? 1 : 0, duration: transitionDuration }), Animated.timing(this.state.opacitySecond, { toValue: showFrontImage ? 0 : 1, duration: transitionDuration }), ]).start(() => { const nextState = { currImageIndex: nextIndex, nextImageIndex: prepareIndex }; if (this.frameShowedCount === 2) { this.frameShowedCount = 1; } else { this.frameShowedCount++; } this._isMounted && this.setState(nextState); }); this.timeout = setTimeout(() => this.animateViews(), nextInvocation); } getNextInvocationTimeout() { const { timingBetween } = this.props; const { min, max } = timingBetween; return Math.floor(Math.random() * (max - min + 1)) + min; } render() { const { children, borderWidth, borderColor, backgroundColor, size, isHorizontal, src, cornerRadius, ...props } = this.props; const { currImageIndex, nextImageIndex, opacity, opacitySecond } = this.state; const sources = Array.isArray(src) ? src : [src]; const delta = Math.sqrt(3) * size / 24; const imageStyle = isHorizontal ? { bottom: delta } : { right: delta }; return ( <HexagonView borderWidth={borderWidth} borderColor={borderColor} size={size} backgroundColor={backgroundColor} isHorizontal={isHorizontal} cornerRadius={cornerRadius} style={{ width: size, height: size }} > <Animated.Image {...props} source={sources[currImageIndex]} style={[ { height: size, width: size }, imageStyle, { opacity } ]} /> {src.length > 1 && ( <Animated.Image {...props} source={sources[nextImageIndex]} resizeMode={'cover'} style={[ styles.fillAbsolute, styles.secondImageView, { height: size, width: size }, imageStyle, { opacity: opacitySecond }, ]} /> )} <View style={[ styles.overlay, { height: size, width: size }, imageStyle ]} > {children} </View> </HexagonView> ); } }
// Generated by CoffeeScript 1.6.1 (function() { var Singool, express, findit, fs, _; _ = require('underscore'); fs = require('fs'); express = require('express'); findit = require('findit'); Singool = (function() { Singool.prototype.config = {}; Singool.prototype.jsPackage = null; Singool.prototype.cssPackage = null; Singool.prototype._compilers = {}; Singool.prototype.defaults = { theme: null, publicPath: null, cssPath: null, jsPath: null, themesPath: null, pluginsPath: null, paths: [], compress: false, plugins: [], vendors: [], ignore: [], compilers: {}, test: false, init: true, cssFile: 'app.css', jsFile: 'app.js' }; function Singool(config) { this.config = _.defaults(config, this.defaults); this.compilers(); this.generators(); } Singool.prototype.generators = function() { var Css, Js, Layout; Css = require('./generators/css'); this.css = new Css(this); Js = require('./generators/js'); this.js = new Js(this); Layout = require('./generators/layout'); return this.layout = new Layout(this); }; Singool.prototype.testCases = function() { var cases, extension, file, filename, files, i, j, path, testCase, _ref; cases = []; _ref = this.config.paths; for (i in _ref) { path = _ref[i]; files = findit.sync(path); for (j in files) { file = files[j]; if (/\/tests\/cases\//.test(file)) { testCase = file.replace(path + '/', ''); filename = _.last(testCase.split('/')); if (filename.indexOf('.') !== -1 || filename.indexOf('.') > 0) { extension = filename.substr(filename.lastIndexOf('.') + 1); cases.push(testCase.replace('.' + extension, '')); } } } } return cases; }; Singool.prototype.compilers = function() { var Compiler, compilerFiles, compilerName, compilers, k, v; compilers = {}; compilerFiles = fs.readdirSync(module.id.replace(_.last(module.id.split('/')), 'compilers/')); for (k in compilerFiles) { v = compilerFiles[k]; compilerName = v.replace('.js', ''); if (!compilerName) { continue; } Compiler = require('./compilers/' + compilerName); this._compilers[compilerName] = new Compiler(this); compilers[compilerName] = this._compilers[compilerName].run; } return this.config.compilers = compilers; }; Singool.prototype.build = function(callback) { if (callback == null) { callback = false; } this.css.write(); this.js.write(); this.layout.write(); if (typeof callback === 'function') { return callback(); } }; Singool.prototype.createServer = function(serveStatic) { var app, _this = this; if (serveStatic == null) { serveStatic = false; } app = express.createServer(); app.configure(function() { return app.use(express["static"](_this.config.publicPath)); }); app.get('/', function(req, res) { return res.send(_this.layout.generate()); }); if (!serveStatic) { app.get('/css/app.css', function(req, res) { return _this.css.generate(function(source) { res.header('Content-Type', 'text/css'); return res.send(source); }); }); app.get('/js/app.js', function(req, res) { return _this.js.generate(function(source) { res.header('Content-Type', 'application/x-javascript'); return res.send(source); }); }); } return app; }; Singool.prototype.clear = function() { this.layout.clear(); this.js.clear(); return this.css.clear(); }; Singool.prototype.registerTasks = function() { var T, k, t, taskFile, taskName, tasks, _results; tasks = fs.readdirSync(module.id.replace(_.last(module.id.split('/')), 'tasks/')); _results = []; for (k in tasks) { taskFile = tasks[k]; taskName = taskFile.replace('.js', ''); T = require('./tasks/' + taskName); t = new T(this); _results.push(task(taskName, t.description, t.run)); } return _results; }; return Singool; })(); module.exports = Singool; }).call(this);
import Phaser from 'phaser' import Lead from '../engine/leading' var W = function(game, x, y, key, frame) { Phaser.Weapon.call(this, game, x, y, key, frame) } W.prototype = Object.create(Phaser.Weapon.prototype) W.prototype.constructor = W W.prototype.update = function() { if (this.lastFire < this.fireInterval) { this.lastFire++ if (this.lastFire % this.fireIntervalMod != 0) { return } } let getTargetDistance = () => { let coords = { x: this.x, y: this.y, x2: this.target.centerX, y2: this.target.centerY } return game.physics.arcade.distanceBetween({ x: coords.x, y: coords.y }, { x: coords.x2, y: coords.y2 }) } if (this.target) { let dead = this.target.life <= 0 if (dead) { this.target = GLOBALS.groups.creeps.getClosestTo(this.sprite) } if (!this.target) { return } let tooFar = getTargetDistance() > GLOBALS.towers.towers[this.brush].rangeRadius + 4 let outOfBounds = this.target._exists == false if (tooFar || outOfBounds) { this.target = GLOBALS.groups.creeps.getClosestTo(this.sprite) } } else { this.target = GLOBALS.groups.creeps.getClosestTo(this.sprite) } if (!this.target) { return } if (getTargetDistance() > GLOBALS.towers.towers[this.brush].rangeRadius + 4) { return } let angle if (this.lastFire % this.fireIntervalMod == 0 && this.lastFire == this.fireInterval) { var fA = this.firingSolution.call(this, this.target) if (fA != null) { angle = game.physics.arcade.angleToXY(this.sprite, fA.x, fA.y, false) } else { console.log('fail') return } this.fireAngle = Phaser.Math.radToDeg(angle) this.sprite.rotation = angle this.fire({ x: this.sprite.centerX, y: this.sprite.centerY }, null, null, 0, 0) this.lastFire = 0 } return this } W.prototype.firingSolution = function(target) { let src, dst, vel dst = { x: target.x, y: target.y, vx: target.velocity.x, vy: target.velocity.y } src = { x: this.sprite.x, y: this.sprite.y } vel = 10 return Lead(src, dst, vel) } export default W
'use strict'; var path = require('path') , util = require('util') , EventEmitter = require('events').EventEmitter , request = require('request') , _ = require('lodash') , cheerio = require('cheerio') , fs = require('fs') , Bottleneck = require('bottleneckp') , seenreq = require('seenreq') , iconvLite = require('iconv-lite') , typeis = require('type-is').is; var whacko=null, level, levels = ['silly','debug','verbose','info','warn','error','critical']; try{ whacko = require('whacko'); }catch(e){ e.code; } function defaultLog(){ //2016-11-24T12:22:55.639Z - debug: if( levels.indexOf(arguments[0]) >= levels.indexOf(level) ) console.log(new Date().toJSON()+' - '+ arguments[0] +': CRAWLER %s', util.format.apply(util, Array.prototype.slice.call(arguments, 1))); } function checkJQueryNaming (options) { if ('jquery' in options) { options.jQuery = options.jquery; delete options.jquery; } return options; } function readJqueryUrl (url, callback) { if (url.match(/^(file:\/\/|\w+:|\/)/)) { fs.readFile(url.replace(/^file:\/\//,''),'utf-8', function(err,jq) { callback(err, jq); }); } else { callback(null, url); } } function contentType(res){ return get(res,'content-type').split(';').filter(item => item.trim().length !== 0).join(';'); } function get(res,field){ return res.headers[field.toLowerCase()] || ''; } var log = defaultLog; function Crawler (options) { var self = this; options = options||{}; if(['onDrain','cache'].some(key => key in options)){ throw new Error('Support for "onDrain", "cache" has been removed! For more details, see https://github.com/bda-research/node-crawler'); } self.init(options); } // augment the prototype for node events using util.inherits util.inherits(Crawler, EventEmitter); Crawler.prototype.init = function init (options) { var self = this; var defaultOptions = { autoWindowClose: true, forceUTF8: true, gzip: true, incomingEncoding: null, jQuery: true, maxConnections: 10, method: 'GET', priority: 5, priorityRange: 10, rateLimit: 0, referer: false, retries: 3, retryTimeout: 10000, timeout: 15000, skipDuplicates: false, rotateUA: false, homogeneous: false }; //return defaultOptions with overriden properties from options. self.options = _.extend(defaultOptions, options); // you can use jquery or jQuery self.options = checkJQueryNaming(self.options); // Don't make these options persist to individual queries self.globalOnlyOptions = ['maxConnections', 'rateLimit', 'priorityRange', 'homogeneous', 'skipDuplicates', 'rotateUA']; self.limiters = new Bottleneck.Cluster(self.options.maxConnections,self.options.rateLimit,self.options.priorityRange, self.options.priority, self.options.homogeneous); level = self.options.debug ? 'debug' : 'info'; if(self.options.logger) log = self.options.logger.log.bind(self.options.logger); self.log = log; self.seen = new seenreq(self.options.seenreq); self.seen.initialize().then(()=> log('debug', 'seenreq is initialized.')).catch(e => log('error', e)); self.on('_release', function(){ log('debug','Queue size: %d',this.queueSize); if(this.limiters.empty) return this.emit('drain'); }); }; Crawler.prototype.setLimiterProperty = function setLimiterProperty (limiter, property, value) { var self = this; switch(property) { case 'rateLimit': self.limiters.key(limiter).setRateLimit(value);break; default: break; } }; Crawler.prototype._inject = function _inject (response, options, callback) { var $; if (options.jQuery === 'whacko') { if(!whacko){ throw new Error('Please install whacko by your own since `crawler` detected you specify explicitly'); } $ = whacko.load(response.body); callback(null, response, options, $); }else if (options.jQuery === 'cheerio' || options.jQuery.name === 'cheerio' || options.jQuery === true) { var defaultCheerioOptions = { normalizeWhitespace: false, xmlMode: false, decodeEntities: true }; var cheerioOptions = options.jQuery.options || defaultCheerioOptions; $ = cheerio.load(response.body, cheerioOptions); callback(null, response, options, $); }else if (options.jQuery.jsdom) { var jsdom = options.jQuery.jsdom; var scriptLocation = path.resolve(__dirname, '../vendor/jquery-2.1.1.min.js'); //Use promises readJqueryUrl(scriptLocation, function(err, jquery) { try { jsdom.env({ url: options.uri, html: response.body, src: [jquery], done: function (errors, window) { $ = window.jQuery; callback(errors, response, options, $); try { window.close(); window = null; } catch (err) { log('error',err); } } }); } catch (e) { options.callback(e,{options}, options.release); } }); } // Jquery is set to false are not set else { callback(null, response, options); } }; Crawler.prototype.isIllegal = function isIllegal (options) { return (_.isNull(options) || _.isUndefined(options) || (!_.isString(options) && !_.isPlainObject(options))); }; Crawler.prototype.direct = function direct (options) { var self = this; if(self.isIllegal(options) || !_.isPlainObject(options)) { return log('warn','Illegal queue option: ', JSON.stringify(options)); } if(!('callback' in options) || !_.isFunction(options.callback)) { return log('warn','must specify callback function when using sending direct request with crawler'); } options = checkJQueryNaming(options); // direct request does not follow the global preRequest options.preRequest = options.preRequest || null; _.defaults(options, self.options); // direct request is not allowed to retry options.retries = 0; // direct request does not emit event:'request' by default options.skipEventRequest = _.isBoolean(options.skipEventRequest) ? options.skipEventRequest : true; self.globalOnlyOptions.forEach(globalOnlyOption => delete options[globalOnlyOption]); self._buildHttpRequest(options); }; Crawler.prototype.queue = function queue (options) { var self = this; // Did you get a single object or string? Make it compatible. options = _.isArray(options) ? options : [options]; options = _.flattenDeep(options); for(var i = 0; i < options.length; ++i) { if(self.isIllegal(options[i])) { log('warn','Illegal queue option: ', JSON.stringify(options[i])); continue; } self._pushToQueue( _.isString(options[i]) ? {uri: options[i]} : options[i] ); } }; Crawler.prototype._pushToQueue = function _pushToQueue (options) { var self = this; // you can use jquery or jQuery options = checkJQueryNaming(options); _.defaults(options, self.options); options.headers = _.assign({}, self.options.headers, options.headers); // Remove all the global options from our options // TODO we are doing this for every _pushToQueue, find a way to avoid this self.globalOnlyOptions.forEach(globalOnlyOption => delete options[globalOnlyOption]); // If duplicate skipping is enabled, avoid queueing entirely for URLs we already crawled if (!self.options.skipDuplicates){ self._schedule(options); return; } self.seen.exists(options, options.seenreq).then(rst => { if(!rst){ self._schedule(options); } }).catch(e => log('error', e)); }; Crawler.prototype._schedule = function _scheduler(options){ var self = this; self.emit('schedule',options); self.limiters.key(options.limiter||'default').submit(options.priority,function(done, limiter){ options.release = function(){ done();self.emit('_release'); }; if(!options.callback) options.callback = options.release; if (limiter) { self.emit('limiterChange', options, limiter); } if (options.html) { self._onContent(null, options, {body:options.html,headers:{'content-type':'text/html'}}); } else if (typeof options.uri === 'function') { options.uri(function(uri) { options.uri = uri; self._buildHttpRequest(options); }); } else { self._buildHttpRequest(options); } }); }; Crawler.prototype._buildHttpRequest = function _buildHTTPRequest (options) { var self = this; log('debug',options.method+' '+options.uri); if(options.proxy) log('debug','Use proxy: %s', options.proxy); // Cloning keeps the opts parameter clean: // - some versions of "request" apply the second parameter as a // property called "callback" to the first parameter // - keeps the query object fresh in case of a retry var ropts = _.assign({},options); if (!ropts.headers) { ropts.headers={}; } if (ropts.forceUTF8) {ropts.encoding=null;} // specifying json in request will have request sets body to JSON representation of value and // adds Content-type: application/json header. Additionally, parses the response body as JSON // so the response will be JSON object, no need to deal with encoding if (ropts.json) {options.encoding=null;} if (ropts.userAgent) { if(self.options.rotateUA && _.isArray(ropts.userAgent)){ ropts.headers['User-Agent'] = ropts.userAgent[0]; // If "rotateUA" is true, rotate User-Agent options.userAgent.push(options.userAgent.shift()); }else{ ropts.headers['User-Agent'] = ropts.userAgent; } } if (ropts.referer) { ropts.headers.Referer = ropts.referer; } if (ropts.proxies && ropts.proxies.length) { ropts.proxy = ropts.proxies[0]; } var doRequest = function(err) { if(err) { err.message = 'Error in preRequest' + (err.message ? ', '+err.message : err.message); switch(err.op) { case 'retry': log('debug', err.message + ', retry ' + options.uri);self._onContent(err,options);break; case 'fail': log('debug', err.message + ', fail ' + options.uri);options.callback(err,{options:options},options.release);break; case 'abort': log('debug', err.message + ', abort ' + options.uri);options.release();break; case 'queue': log('debug', err.message + ', queue ' + options.uri);self.queue(options);options.release();break; default: log('debug', err.message + ', retry ' + options.uri);self._onContent(err,options);break; } return; } if(ropts.skipEventRequest !== true) { self.emit('request',ropts); } var requestArgs = ['uri','url','qs','method','headers','body','form','formData','json','multipart','followRedirect','followAllRedirects', 'maxRedirects','encoding','pool','timeout','proxy','auth','oauth','strictSSL','jar','aws','gzip','time','tunnel','proxyHeaderWhiteList','proxyHeaderExclusiveList','localAddress','forever', 'agent']; request(_.pick.apply(self,[ropts].concat(requestArgs)), function(error,response) { if (error) { return self._onContent(error, options); } self._onContent(error,options,response); }); }; if (options.preRequest && _.isFunction(options.preRequest)) { options.preRequest(ropts, doRequest); } else { doRequest(); } }; Crawler.prototype._onContent = function _onContent (error, options, response) { var self = this; if (error) { log('error','Error '+error+' when fetching '+ (options.uri||options.url)+(options.retries ? ' ('+options.retries+' retries left)' : '')); if (options.retries) { setTimeout(function() { options.retries--; self._schedule(options); options.release(); },options.retryTimeout); } else{ options.callback(error,{options:options},options.release); } return; } if (!response.body) { response.body=''; } log('debug','Got '+(options.uri||'html')+' ('+response.body.length+' bytes)...'); try{ self._doEncoding(options,response); }catch(e){ log('error',e); return options.callback(e,{options:options},options.release); } response.options = options; if(options.method === 'HEAD' || !options.jQuery){ return options.callback(null,response,options.release); } var injectableTypes = ['html','xhtml','text/xml', 'application/xml', '+xml']; if (!options.html && !typeis(contentType(response), injectableTypes)){ log('warn','response body is not HTML, skip injecting. Set jQuery to false to suppress this message'); return options.callback(null,response,options.release); } log('debug','Injecting'); self._inject(response, options, self._injected.bind(self)); }; Crawler.prototype._injected = function(errors, response, options, $){ log('debug','Injected'); response.$ = $; options.callback(errors, response, options.release); }; Crawler.prototype._doEncoding = function(options,response){ var self = this; if(options.encoding === null){ return; } if (options.forceUTF8) { var charset = options.incomingEncoding || self._parseCharset(response); response.charset = charset; log('debug','Charset ' + charset); if (charset !== 'utf-8' && charset !== 'ascii') {// convert response.body into 'utf-8' encoded buffer response.body = iconvLite.decode(response.body, charset); } } response.body = response.body.toString(); }; Crawler.prototype._parseCharset = function(res){ //Browsers treat gb2312 as gbk, but iconv-lite not. //Replace gb2312 with gbk, in order to parse the pages which say gb2312 but actually are gbk. function getCharset(str){ var charset = (str && str.match(/charset=['"]?([\w.-]+)/i) || [0, null])[1]; return charset && charset.replace(/:\d{4}$|[^0-9a-z]/g, '') == 'gb2312' ? 'gbk' : charset; } function charsetParser(header, binary, default_charset = null) { return getCharset(header) || getCharset(binary) || default_charset; } var charset = charsetParser(contentType(res)); if(charset) return charset; if(!typeis(contentType(res), ['html'])){ log('debug','Charset not detected in response headers, please specify using `incomingEncoding`, use `utf-8` by default'); return 'utf-8'; } var body = res.body instanceof Buffer ? res.body.toString() : res.body; charset = charsetParser(contentType(res),body,'utf-8'); return charset; }; Object.defineProperty(Crawler.prototype,'queueSize',{ get:function(){ return this.limiters.unfinishedClients; } }); module.exports = Crawler;
// override loader.translate to rewrite 'locate://' & 'pkg://' path schemes found // in resources loaded by supporting plugins var addLocate = function(loader){ /** * @hide * @function normalizeAndLocate * @description Run a module identifier through Normalize and Locate hooks. * @param {String} moduleName The module to run through normalize and locate. * @return {Promise} A promise to resolve when the address is found. */ var normalizeAndLocate = function(moduleName, parentName){ var loader = this; return Promise.resolve(loader.normalize(moduleName, parentName)) .then(function(name){ return loader.locate({name: name, metadata: {}}); }).then(function(address){ if(address.substr(address.length - 3) === ".js") { address = address.substr(0, address.length - 3); } return address; }); }; var relative = function(base, path){ var uriParts = path.split("/"), baseParts = base.split("/"), result = []; while ( uriParts.length && baseParts.length && uriParts[0] == baseParts[0] ) { uriParts.shift(); baseParts.shift(); } for(var i = 0 ; i< baseParts.length-1; i++) { result.push("../"); } return result.join("") + uriParts.join("/"); }; var schemePattern = /(locate):\/\/([a-z0-9/._@-]*)/ig, parsePathSchemes = function(source, parent) { var locations = []; source.replace(schemePattern, function(whole, scheme, path, index){ locations.push({ start: index, end: index+whole.length, name: path, postLocate: function(address){ return relative(parent, address); } }); }); return locations; }; var _translate = loader.translate; loader.translate = function(load){ var loader = this; // This only applies to plugin resources. if(!load.metadata.plugin) { return _translate.call(this, load); } // Use the translator if this file path scheme is supported by the plugin var locateSupport = load.metadata.plugin.locateScheme; if(!locateSupport) { return _translate.call(this, load); } // Parse array of module names var locations = parsePathSchemes(load.source, load.address); // no locations found if(!locations.length) { return _translate.call(this, load); } // normalize and locate all of the modules found and then replace those instances in the source. var promises = []; for(var i = 0, len = locations.length; i < len; i++) { promises.push( normalizeAndLocate.call(this, locations[i].name, load.name) ); } return Promise.all(promises).then(function(addresses){ for(var i = locations.length - 1; i >= 0; i--) { load.source = load.source.substr(0, locations[i].start) + locations[i].postLocate(addresses[i]) + load.source.substr(locations[i].end, load.source.length); } return _translate.call(loader, load); }); }; }; if(typeof System !== "undefined") { addLocate(System); }
const Command = require('../structures/command.js'); module.exports = class Avatar extends Command { constructor(client) { super(client); this.name = "avatar"; } run(message, args, commandLang) { let embed = this.client.getDekuEmbed(message); let query = args.join(" ").toLowerCase(); let mbr = this.findMember(query, message); let msg = mbr.user == message.author ? commandLang.own_picture : commandLang.someones_picture.replace('{0}', mbr ? mbr.displayName : mbr.user.name); embed.setDescription(`${message.author}, ${msg}\n${mbr.user.displayAvatarURL}`); embed.setImage(mbr.user.displayAvatarURL); message.channel.send({embed}); } canRun(message) { return message.guild ? true : false; } findMember(query, message) { let member = null; if(query) { member = message.guild.members.find(m => { return m.displayName.toLowerCase().startsWith(query) || m.user.username.toLowerCase().startsWith(query) || m.id == query }); } if(!member) { member = message.mentions.members.first() || message.member; } return member; } }
Meteor.publishComposite('servers', function(){ return { find: function(){ return Servers.find({available: true}, { sort: { createdAt: -1 }}); }, children: [{ find: function(){ // Return everything for now to determine what I need to return return PlexCustomers.find({ $and: [{ userId: this.userId }, {paymentSuccess: true}] }, { fields: { serverId: 1, userId: 1, paymentSuccess: 1 }}); } }] }; });
var notWhiteMatch = /\S+/g; function hasClass(v,c) { return ( v.classList ? v.classList.contains(c) : new RegExp('(^| )' + c + '( |$)', 'gi').test(v.className) ); } function addClass(v,c,spacedName){ if (v.classList) { v.classList.add(c); } else if ( spacedName.indexOf(` ${c} `) ) { v.className += ' ' + c; } } function removeClass(v,c){ if (v.classList) { v.classList.remove(c); } else { v.className = v.className.replace(c,''); } } fn.extend({ addClass(c){ var classes = c.match(notWhiteMatch); return this.each(v => { var spacedName = ` ${v.className} `; each(classes,c => { addClass(v,c,spacedName); }); }); }, attr(name, value) { if ( isString(name) ) { return ( value === undefined ? this[0].getAttribute ? this[0].getAttribute(name) : this[0][name] : this.each(v => { if ( v.setAttribute ) { v.setAttribute(name, value); } else { v[name] = value; } }) ); } for (var key in name) { this.attr(key,name[key]); } return this; }, hasClass(c) { var check = false; this.each(v => { check = hasClass(v,c); return !check; }); return check; }, prop(name,value) { if ( isString(name) ) { return ( value === undefined ? this[0][name] : this.each(v => { v[name] = value; }) ); } for (var key in name) { this.prop(key,name[key]); } return this; }, removeAttr(name) { return this.each(v => { if ( v.removeAttribute ) { v.removeAttribute(name); } else { delete v[name]; } }); }, removeClass(c){ var classes = c.match(notWhiteMatch); return this.each(v => { each(classes,c => { removeClass(v,c); }); }); }, removeProp(name){ return this.each(v => { delete v[name]; }); }, toggleClass(c, state){ if ( state !== undefined ) { return this[state ? 'addClass' : 'removeClass' ](c); } var classes = c.match(notWhiteMatch); return this.each(v => { var spacedName = ` ${v.className} `; each(classes,c => { if ( hasClass(v,c) ) { removeClass(v,c); } else { addClass(v,c,spacedName); } }); }); }, });
class SegmentTree { constructor (graph) { this.graph = graph } build (vertexesPath) { this.t = [] let weight = [] if (vertexesPath.length >= 2) { for (let i = 0; i < vertexesPath.length - 1; i += 1) { weight.push(this.graph.edgeCost(vertexesPath[i + 1], vertexesPath[i])) } } else { weight.push(0) } this.vertexesPath = vertexesPath this.weights = weight this.buildSegments(vertexesPath, weight, 1, 0, weight.length - 1) } buildSegments (vertexesPath, a, v, tl, tr) { if (tl === tr) { let start = Math.min(vertexesPath[tl], vertexesPath[tl + 1]) let end = Math.max(vertexesPath[tl], vertexesPath[tl + 1]) this.t[v] = { weight: a[tl], start: start, end: end } } else { let tm = Math.floor((tl + tr) / 2) this.buildSegments(vertexesPath, a, v * 2, tl, tm) this.buildSegments(vertexesPath, a, v * 2 + 1, tm + 1, tr) this.t[v] = this.sum(this.t[v * 2], this.t[v * 2 + 1]) } } sum (a, b) { let result = { weight: a.weight + b.weight } result.start = Math.min(a.start, a.end, b.start, b.end) result.end = Math.max(a.start, a.end, b.start, b.end) return result } update (v, tl, tr, pos, newVal) { if (tl === tr) { this.t[v] = newVal } else { let tm = Math.floor((tl + tr) / 2) if (pos <= tm) { this.update(v * 2, tl, tm, pos, newVal) } else { this.update(v * 2 + 1, tm + 1, tr, pos, newVal) } this.t[v] = this.t[v * 2] + this.t[v * 2 + 1] } } // getMax(v, tl, tr, l, r) { // if (l > r) { // return { weight: -Infinity, start: 0, end: 0 } // } // if (l == tl && r == tr) { // return this.t[v] // } // let tm = Math.floor((tl + tr) / 2) // return this.combine ( // this.getMax(v*2, tl, tm, l, Math.min(r, tm)), // this.getMax(v*2 + 1, tm + 1, tr, Math.max(l, tm + 1), r) // ) // } getMax (v, start, end) { let secondVertex = null let maxEdge = { weight: -Infinity } for (let i = 0; i < this.vertexesPath.length; i += 1) { if (secondVertex !== null) { if (this.vertexesPath[i] === secondVertex) { break } else if (maxEdge.weight < this.weights[i]) { maxEdge = { weight: this.weights[i], start: this.vertexesPath[i], end: this.vertexesPath[i + 1] } } } else { if (this.vertexesPath[i] === start) { secondVertex = end i -= 1 } else if (this.vertexesPath[i] === end) { secondVertex = start i -= 1 } } } return maxEdge } combine (a, b) { if (a.weight >= b.weight) { return a } else { return b } } } export default SegmentTree
import { connect } from 'zefir/utils' import Input from '../../components/ui/input' import Button from '../../components/ui/button' import InputList from '../../components/ui/input-list' const SlackInviteForm = ({ email, sendInvitation, messages }) => ( <div> <form className='Form' onSubmit={sendInvitation}> <InputList errors={messages.get('slack.invite.errors')}> <div className='Form__group'> <Input {...email} full /> <Button type='submit' disabled={messages.has('slack.invite.pending')} secondary > Send me an invite </Button> </div> </InputList> {messages.has('slack.invite.success') ? ( <div className='Form__message'>{messages.get('slack.invite.success')}</div> ) : ''} </form> <style jsx>{` .Form { text-align: left; margin-top: 30px; } .Form__group { display: flex; } .Form__message { color: #25b012; margin-top: 30px; text-align: center; } .Form__group > :global(*) + :global(*) { margin-left: 15px; } .Form__group :global(.Button) { white-space: nowrap; } `}</style> </div> ) SlackInviteForm.form = { formName: 'SlackInviteFormForm', fields: { email: { required: 'true', type: 'email', placeholder: 'E-mail address' } } } SlackInviteForm.init = ({ stores: { messages }, services: { slackInvite: { sendInvitation } }, form: { fields: { email }, submit } }) => ({ messages, email, sendInvitation: (e) => submit(e, sendInvitation) }) export default connect(SlackInviteForm)
function Display(arr){ var d = document.createElement('div'); this.display = d; this.arr = arr; } Display.prototype = { whatToDisplay : function(pos, arr){ // console.log(arr); this.display.innerHTML = arr[pos]['name']; }, count : function(amounts){ //make limiter var s = ''; for (var key in amounts){ s += '<span >'+key+': <span class='+key+'>'+amounts[key]+'</span></span><br>'; } this.display.innerHTML = s; }, filter : function(){ var inner = '<input type="checkbox" name="Forwards" value="F">Forwards<br>'; inner += '<input type="checkbox" name="Center" value="C">Center<br>'; inner += '<input type="checkbox" name="Backs" value="B">Backs<br>'; inner += '<input type="checkbox" name="Rucs" value="R">Rucs<br>'; inner += '<input type="checkbox" name="CenterForwards" value="C,F">Center-F<br>'; inner += '<input type="checkbox" name="BacksForwards" value="B,F">Backs-F<br>'; inner += '<input type="checkbox" name="RucsForwards" value="R,F">Rucs-F<br>'; inner += '<input type="checkbox" name="CenterRucs" value="C,R">Center-R<br>'; inner += '<input type="checkbox" name="BacksCenter" value="B,C">Back-C<br>'; this.display.innerHTML = inner; } }
/** * DevExtreme (ui/pivot_grid/ui.pivot_grid.area_item.js) * Version: 16.2.5 * Build date: Mon Feb 27 2017 * * Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED * EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml */ "use strict"; var $ = require("jquery"), Class = require("../../core/class"), commonUtils = require("../../core/utils/common"); var PIVOTGRID_EXPAND_CLASS = "dx-expand"; var getRealElementWidth = function(element) { var clientRect, width = 0; if (element.getBoundingClientRect) { clientRect = element.getBoundingClientRect(); width = clientRect.width; if (!width) { width = clientRect.right - clientRect.left } } if (width > 0) { return width } else { return element.offsetWidth } }; function getFakeTableOffset(scrollPos, elementOffset, tableSize, viewPortSize) { var offset = 0, halfTableCount = 0, halfTableSize = tableSize / 2; if (scrollPos + viewPortSize - (elementOffset + tableSize) > 1) { if (scrollPos >= elementOffset + tableSize + halfTableSize) { halfTableCount = parseInt((scrollPos - (elementOffset + tableSize)) / halfTableSize, 10) } offset = elementOffset + tableSize + halfTableSize * halfTableCount } else { if (scrollPos < elementOffset) { if (scrollPos <= elementOffset - halfTableSize) { halfTableCount = parseInt((scrollPos - (elementOffset - halfTableSize)) / halfTableSize, 10) } offset = elementOffset - (tableSize - halfTableSize * halfTableCount) } else { offset = elementOffset } } return offset } exports.AreaItem = Class.inherit({ _getRowElement: function(index) { var that = this; if (that._tableElement && that._tableElement.length > 0) { return that._tableElement[0].rows[index] } return null }, _createGroupElement: function() { return $("<div>") }, _createTableElement: function() { return $("<table>") }, _getCellText: function(cell, encodeHtml) { var cellText = cell.isWhiteSpace ? "" : cell.text || ""; if (encodeHtml && (cellText.indexOf("<") !== -1 || cellText.indexOf(">") !== -1)) { cellText = $("<div>").text(cellText).html() } return cellText }, _getRowClassNames: function() {}, _applyCustomStyles: function(options) { if (options.cell.width) { options.cssArray.push("min-width:" + options.cell.width + "px") } if (options.cell.sorted) { options.classArray.push("dx-pivotgrid-sorted") } }, _getMainElementMarkup: function() { return "<tbody>" }, _getCloseMainElementMarkup: function() { return "</tbody>" }, _renderTableContent: function(tableElement, data) { var row, cell, i, j, rowElement, cellElement, cellText, rowClassNames, that = this, rowsCount = data.length, rtlEnabled = that.option("rtlEnabled"), markupArray = [], encodeHtml = that.option("encodeHtml"), colspan = "colspan='", rowspan = "rowspan='"; tableElement.data("area", that._getAreaName()); tableElement.data("data", data); tableElement.css("width", ""); markupArray.push(that._getMainElementMarkup()); for (i = 0; i < rowsCount; i++) { row = data[i]; var columnMarkupArray = []; rowClassNames = []; markupArray.push("<tr "); for (j = 0; j < row.length; j++) { cell = row[j]; this._getRowClassNames(i, cell, rowClassNames); columnMarkupArray.push("<td "); if (cell) { cell.rowspan && columnMarkupArray.push(rowspan + (cell.rowspan || 1) + "'"); cell.colspan && columnMarkupArray.push(colspan + (cell.colspan || 1) + "'"); var styleOptions = { cellElement: cellElement, cell: cell, cellsCount: row.length, cellIndex: j, rowElement: rowElement, rowIndex: i, rowsCount: rowsCount, rtlEnabled: rtlEnabled, classArray: [], cssArray: [] }; that._applyCustomStyles(styleOptions); if (styleOptions.cssArray.length) { columnMarkupArray.push("style='"); columnMarkupArray.push(styleOptions.cssArray.join(";")); columnMarkupArray.push("'") } if (styleOptions.classArray.length) { columnMarkupArray.push("class='"); columnMarkupArray.push(styleOptions.classArray.join(" ")); columnMarkupArray.push("'") } columnMarkupArray.push(">"); if (commonUtils.isDefined(cell.expanded)) { columnMarkupArray.push("<div class='dx-expand-icon-container'><span class='" + PIVOTGRID_EXPAND_CLASS + "'></span></div>") } cellText = this._getCellText(cell, encodeHtml) } else { cellText = "" } columnMarkupArray.push("<span "); if (commonUtils.isDefined(cell.wordWrapEnabled)) { columnMarkupArray.push("style='white-space:", cell.wordWrapEnabled ? "normal" : "nowrap", ";'") } columnMarkupArray.push(">" + cellText + "</span>"); if (cell.sorted) { columnMarkupArray.push("<span class='dx-icon-sorted'></span>") } columnMarkupArray.push("</td>") } if (rowClassNames.length) { markupArray.push("class='"); markupArray.push(rowClassNames.join(" ")); markupArray.push("'") } markupArray.push(">"); markupArray.push(columnMarkupArray.join("")); markupArray.push("</tr>") } markupArray.push(this._getCloseMainElementMarkup()); tableElement.append(markupArray.join("")); this._triggerOnCellPrepared(tableElement, data) }, _triggerOnCellPrepared: function(tableElement, data) { var rowElement, cellElement, onCellPreparedArgs, row, cell, rowIndex, columnIndex, that = this, rowElements = tableElement.find("tr"), areaName = that._getAreaName(), onCellPrepared = that.option("onCellPrepared"), hasEvent = that.component.hasEvent("cellPrepared"), defaultActionArgs = this.component._defaultActionArgs(); if (onCellPrepared || hasEvent) { for (rowIndex = 0; rowIndex < data.length; rowIndex++) { row = data[rowIndex]; rowElement = rowElements.eq(rowIndex); for (columnIndex = 0; columnIndex < row.length; columnIndex++) { cell = row[columnIndex]; cellElement = rowElement.children().eq(columnIndex); onCellPreparedArgs = { area: areaName, rowIndex: rowIndex, columnIndex: columnIndex, cellElement: cellElement, cell: cell }; if (hasEvent) { that.component._trigger("onCellPrepared", onCellPreparedArgs) } else { onCellPrepared($.extend(onCellPreparedArgs, defaultActionArgs)) } } } } }, _getRowHeight: function(index) { var clientRect, row = this._getRowElement(index), height = 0; if (row && row.lastChild) { if (row.getBoundingClientRect) { clientRect = row.getBoundingClientRect(); height = clientRect.height } if (height > 0) { return height } else { return row.offsetHeight } } return 0 }, _setRowHeight: function(index, value) { var row = this._getRowElement(index); if (row) { row.style.height = value + "px" } }, ctor: function(component) { this.component = component }, option: function() { return this.component.option.apply(this.component, arguments) }, getRowsLength: function() { var that = this; if (that._tableElement && that._tableElement.length > 0) { return that._tableElement[0].rows.length } return 0 }, getRowsHeight: function() { var i, that = this, result = [], rowsLength = that.getRowsLength(); for (i = 0; i < rowsLength; i++) { result.push(that._getRowHeight(i)) } return result }, setRowsHeight: function(values) { var i, that = this, totalHeight = 0, valuesLength = values.length; for (i = 0; i < valuesLength; i++) { totalHeight += values[i]; that._setRowHeight(i, values[i]) } this._tableHeight = totalHeight; this._tableElement[0].style.height = totalHeight + "px" }, getColumnsWidth: function() { var rowIndex, row, i, columnIndex, rowsLength = this.getRowsLength(), processedCells = [], result = [], fillCells = function(cells, rowIndex, columnIndex, rowSpan, colSpan) { var rowOffset, columnOffset; for (rowOffset = 0; rowOffset < rowSpan; rowOffset++) { for (columnOffset = 0; columnOffset < colSpan; columnOffset++) { cells[rowIndex + rowOffset] = cells[rowIndex + rowOffset] || []; cells[rowIndex + rowOffset][columnIndex + columnOffset] = true } } }; if (rowsLength) { for (rowIndex = 0; rowIndex < rowsLength; rowIndex++) { processedCells[rowIndex] = processedCells[rowIndex] || []; row = this._getRowElement(rowIndex); for (i = 0; i < row.cells.length; i++) { for (columnIndex = 0; processedCells[rowIndex][columnIndex]; columnIndex++) {} fillCells(processedCells, rowIndex, columnIndex, row.cells[i].rowSpan, row.cells[i].colSpan); if (1 === row.cells[i].colSpan) { result[columnIndex] = result[columnIndex] || getRealElementWidth(row.cells[i]) } } } } return result }, setColumnsWidth: function(values) { var i, totalWidth = 0, tableElement = this._tableElement[0], colgroupElementHTML = "", columnsCount = this.getColumnsCount(), columnWidth = []; for (i = 0; i < columnsCount; i++) { columnWidth.push(values[i] || 0) } for (i = columnsCount; i < values.length && values; i++) { columnWidth[columnsCount - 1] += values[i] } for (i = 0; i < columnsCount; i++) { totalWidth += columnWidth[i]; colgroupElementHTML += '<col style="width: ' + columnWidth[i] + 'px">' } this._colgroupElement.html(colgroupElementHTML); this._tableWidth = totalWidth; tableElement.style.width = totalWidth + "px"; tableElement.style.tableLayout = "fixed" }, resetColumnsWidth: function() { this._colgroupElement.find("col").width("auto"); this._tableElement.css({ width: "", tableLayout: "" }) }, groupWidth: function(value) { if (void 0 === value) { return this._groupElement.width() } else { if (value >= 0) { this._groupWidth = value; return this._groupElement[0].style.width = value + "px" } else { return this._groupElement[0].style.width = value } } }, groupHeight: function(value) { if (void 0 === value) { return this._groupElement.height() } this._groupHeight = null; if (value >= 0) { this._groupHeight = value; this._groupElement[0].style.height = value + "px" } else { this._groupElement[0].style.height = value } }, groupElement: function() { return this._groupElement }, tableElement: function() { return this._tableElement }, element: function() { return this._rootElement }, headElement: function() { return this._tableElement.find("thead") }, setVirtualContentParams: function(params) { this._virtualContent.css({ width: params.width, height: params.height }); this.groupElement().addClass("dx-virtual-mode") }, disableVirtualMode: function() { this.groupElement().removeClass("dx-virtual-mode") }, _renderVirtualContent: function() { var that = this; if (!that._virtualContent && "virtual" === that.option("scrolling.mode")) { that._virtualContent = $("<div>").addClass("dx-virtual-content").insertBefore(that._tableElement) } }, reset: function() { var that = this, tableElement = that._tableElement[0]; that._fakeTable && that._fakeTable.detach(); that._fakeTable = null; that.disableVirtualMode(); that.groupWidth("100%"); that.groupHeight("auto"); that.resetColumnsWidth(); if (tableElement) { for (var i = 0; i < tableElement.rows.length; i++) { tableElement.rows[i].style.height = "" } tableElement.style.height = ""; tableElement.style.width = "100%" } }, _updateFakeTableVisibility: function() { var that = this, tableElement = that.tableElement()[0], fakeTableElement = that._fakeTable[0]; if (tableElement.style.top === fakeTableElement.style.top && fakeTableElement.style.left === tableElement.style.left) { that._fakeTable.addClass("dx-hidden") } else { that._fakeTable.removeClass("dx-hidden") } }, _moveFakeTableLeft: function(scrollPos) { var that = this, tableElementOffsetLeft = parseFloat(that.tableElement()[0].style.left), offsetLeft = getFakeTableOffset(scrollPos, tableElementOffsetLeft, that._tableWidth, that._groupWidth); if (parseFloat(that._fakeTable[0].style.left) !== offsetLeft) { that._fakeTable[0].style.left = offsetLeft + "px" } }, _moveFakeTableTop: function(scrollPos) { var that = this, tableElementOffsetTop = parseFloat(that.tableElement()[0].style.top), offsetTop = getFakeTableOffset(scrollPos, tableElementOffsetTop, that._tableHeight, that._groupHeight); if (parseFloat(that._fakeTable[0].style.top) !== offsetTop) { that._fakeTable[0].style.top = offsetTop + "px" } }, _moveFakeTable: function() { this._updateFakeTableVisibility() }, _createFakeTable: function() { var that = this; if (!that._fakeTable) { that._fakeTable = that.tableElement().clone().addClass("dx-pivot-grid-fake-table").appendTo(that._virtualContent) } }, render: function(rootElement, data) { var that = this; if (that._tableElement) { try { that._tableElement[0].innerHTML = "" } catch (e) { that._tableElement.empty() } that._tableElement.attr("style", "") } else { that._groupElement = that._createGroupElement(); that._tableElement = that._createTableElement(); that._tableElement.appendTo(that._groupElement); that._groupElement.appendTo(rootElement); that._rootElement = rootElement } that._colgroupElement = $("<colgroup>").appendTo(that._tableElement); that._renderTableContent(that._tableElement, data); that._renderVirtualContent() }, _getScrollable: function() { return this.groupElement().data("dxScrollable") }, on: function(eventName, handler) { var scrollable = this._getScrollable(); if (scrollable) { scrollable.on(eventName, handler) } return this }, off: function() { var scrollable = this._getScrollable(); if (scrollable) { scrollable.off.apply(scrollable, arguments) } return this }, scrollTo: function(pos) { var scrollable = this._getScrollable(); if (scrollable) { scrollable.scrollTo(pos); if (this._virtualContent) { this._createFakeTable(); this._moveFakeTable(pos) } } }, updateScrollable: function() { var scrollable = this._getScrollable(); if (scrollable) { return scrollable.update() } }, getColumnsCount: function() { var cells, columnCount = 0, row = this._getRowElement(0); if (row) { cells = row.cells; for (var i = 0, len = cells.length; i < len; ++i) { columnCount += cells[i].colSpan } } return columnCount } });
module.exports = { build: { description: 'Bundle code for release', tasks: [ // Clean output directory 'clean:dist', 'copy:dist', 'sass:dist', // - minify the packaged javascript 'uglify:dist', 'cssmin:dist' ] } };
var modules = require('./modules'); var request = modules.request; exports.fetchMovieByName = function(name, success, error){ request({ method: 'GET', uri: 'http://www.omdbapi.com/?t='+name+'&y=&plot=short&r=json'}, function(e, r, b){ success(JSON.parse(b)); }); }
let extensionInstalled = false; document.getElementById('start').addEventListener('click', () => { // send screen-sharer request to content-script if (!extensionInstalled) { alert( 'Please install the extension:\n' + '1. Go to chrome://extensions\n' + '2. Check: "Enable Developer mode"\n' + '3. Click: "Load the unpacked extension..."\n' + '4. Choose "extension" folder from the repository\n' + '5. Reload this page' ); } window.postMessage({ type: 'SS_UI_REQUEST', text: 'start' }, '*'); }); // listen for messages from the content-script window.addEventListener('message', event => { const { data: { type, streamId }, origin } = event; // NOTE: you should discard foreign events if (origin !== window.location.origin) { console.warn( 'ScreenStream: you should discard foreign event from origin:', origin ); // return; } // content-script will send a 'SS_PING' msg if extension is installed if (type === 'SS_PING') { extensionInstalled = true; } // user chose a stream if (type === 'SS_DIALOG_SUCCESS') { startScreenStreamFrom(streamId); } // user clicked on 'cancel' in choose media dialog if (type === 'SS_DIALOG_CANCEL') { console.log('User cancelled!'); } }); function startScreenStreamFrom(streamId) { navigator.mediaDevices .getUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: streamId, maxWidth: window.screen.width, maxHeight: window.screen.height } } }) .then(stream => { videoElement = document.getElementById('video'); videoElement.srcObject = stream; }) .catch(console.error); }
'use strict'; /* Services */ // Demonstrate how to register services // In this case it is a simple value service. angular.module('energy.services', []). value('version', '0.1');
'use strict'; import GithubApi from 'github-api'; /** * The class that extends Github.js * * @extends GithubApi */ export default class Github extends GithubApi { /** * @constructor * @param {Object} options The object containing the information to work with the GitHub API * @param {string} options.username The username used on GitHub * @param {string} options.password The password of the GitHub account * @param {string} options.auth The type of authentication to use. It can be either `basic` or `oauth` * @param {string} options.token The token to access the GitHub API */ constructor(options) { super(options); let superGetRepo = this.getRepo; let request = this.request || this._request; // jscs:ignore disallowDanglingUnderscores /** * Returns an object representing a specific repository * * @param {string} user The username that possesses the repository * @param {string} repo The name of the repository to work on * * @returns {Object} */ this.getRepo = (user, repo) => { let repository = superGetRepo(user, repo); let superRemove = repository.remove; let superFork = repository.fork; function getRepositoryInfo(repository) { return new Promise((resolve, reject) => { repository.show((error, repo) => { if (error) { reject(error); } resolve(repo); }); }); } /** * Searches files and folders * * @param {string} string The string to search * @param {Object} [options={}] Possible options * @param {string} [options.branch] The name of the branch in which the search must be performed * @param {boolean} [options.caseSensitive=false] If the search must be case sensitive * @param {boolean} [options.excludeFiles=false] If the result must exclude files * @param {boolean} [options.excludeFolders=false] If the result must exclude folders * * @returns {Promise} */ repository.search = (string, options = {}) => { const FILE = 'blob'; const FOLDER = 'tree'; options = Object.assign({ branch: 'master', caseSensitive: false, excludeFiles: false, excludeFolders: false }, options); return new Promise((resolve, reject) => { repository.getSha(options.branch, '', (error, sha) => { if (error) { reject(error); } resolve(sha); }); }) .then(sha => { return new Promise((resolve, reject) => { repository.getTree(`${sha}?recursive=true`, (error, list) => { if (error) { // No matches if (error.error === 404) { resolve([]); } else { reject(error); } } resolve(list); }); }); }) .then(list => { let regex = new RegExp(string, options.caseSensitive ? '' : 'i'); return list.filter(content => { let fileCondition = options.excludeFiles ? content.type !== FILE : true; let folderCondition = options.excludeFolders ? content.type !== FOLDER : true; let extractName = (path) => path.substring(path.lastIndexOf('/') + 1); return fileCondition && folderCondition && regex.test(extractName(content.path)); }); }); }; /** * Merges a pull request * * @param {Object} pullRequest The pull request to merge * @param {Object} [options={}] Possible options * @param {string} [options.commitMessage] The commit message for the merge * * @returns {Promise} */ repository.mergePullRequest = (pullRequest, options = {}) => { options = Object.assign( { commitMessage: `Merged pull request gh-${pullRequest.number}` }, options ); return getRepositoryInfo(repository) .then(repositoryInfo => { return new Promise((resolve, reject) => { request( 'PUT', `/repos/${repositoryInfo.full_name}/pulls/${pullRequest.number}/merge`, // jscs:ignore { commit_message: options.commitMessage, // jscs:ignore sha: pullRequest.head.sha }, (error, mergeInfo) => { if (error) { reject(error); } resolve(mergeInfo); } ); }); }); }; /** * Deletes a file or a folder and all of its content from a given branch * * @param {string} [branchName='master'] The name of the branch in which the deletion must be performed * @param {string} [path=''] The path of the file or the folder to delete * * @returns {Promise} */ repository.remove = (branchName = 'master', path = '') => { function removeFile(branchName, path) { return new Promise((resolve, reject) => { superRemove(branchName, path, error => { if (error) { reject(error); } resolve(); }); }); } function removeFolder() { return new Promise((resolve, reject) => { repository.getRef(`heads/${branchName}`, (error, sha) => { if (error) { reject(error); } resolve(sha); }); }) .then(sha => { return new Promise((resolve, reject) => { repository.getTree(`${sha}?recursive=true`, (error, tree) => { if (error) { reject(error); } resolve(tree); }); }); }) .then(tree => { let filesPromises = Promise.resolve(); // Filters all items that aren't in the path of interest and aren't files // and delete them. tree .filter(item => item.path.indexOf(path) === 0 && item.type === 'blob') .map(item => item.path) .forEach(path => { filesPromises = filesPromises.then(() => removeFile(branchName, path)); }); return filesPromises; }); } // Remove any trailing slash from the path. // GitHub does not accept it even when dealing with folders. path = path.replace(/\/$/, ''); let removeFilePromise = removeFile(branchName, path); return removeFilePromise .then( () => removeFilePromise, error => { // If the operation fails because the path specified is that of a folder // keep going to retrieve the files recursively if (error.error !== 422) { throw error; } return removeFolder(); }); }; /** * Creates a fork of the repository * * @returns {Promise} */ repository.fork = () => { return new Promise((resolve, reject) => { superFork((err, forkInfo) => { function pollFork(fork) { fork.contents('master', '', (err, contents) => { if (contents) { resolve(forkInfo); } else { setTimeout(pollFork.bind(null, fork), 250); } }); } if (err) { reject(err); } else { pollFork(superGetRepo(options.username, repo)); } }); }); }; return repository; }; } }
var searchData= [ ['default_5fbits_5fnot_5fcompare',['DEFAULT_BITS_NOT_COMPARE',['../classthewizardplusplus_1_1anna_1_1maths_1_1_maths.html#a75f09f0aec377a8532b750235c0c16ce',1,'thewizardplusplus::anna::maths::Maths']]], ['density',['density',['../classthewizardplusplus_1_1anna_1_1graphics_1_1_fog_parameters.html#af19a0f5eee7811171354a630a8633095',1,'thewizardplusplus::anna::graphics::FogParameters']]] ];
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define({widgetLabel:"Teckenf\u00f6rklaring",points:"Punkter",lines:"Linjer",polygons:"Polygoner",creatingLegend:"Teckenf\u00f6rklaring skapas",noLegend:"Ingen teckenf\u00f6rklaring",dotValue:"1 prick \x3d {value} {unit}",currentObservations:"Aktuella observationer",previousObservations:"Tidigare observationer",high:"H\u00f6g",low:"L\u00e5g",esriMetersPerSecond:"m/s",esriKilometersPerHour:"km/h",esriKnots:"knop",esriFeetPerSecond:"fot/s",esriMilesPerHour:"mph",showNormField:"{field} delat med {normField}", showNormPct:"{field} som en procentandel av helheten",showRatio:"F\u00f6rh\u00e5llande p\u00e5 {field} till {normField}",showRatioPercent:"{field} som en procentandel av {normField}",showRatioPercentTotal:"{field} som en procentandel av {field} och {normField}",band0:"band_0",band1:"band_1",band2:"band_2",red:"R\u00f6tt",green:"Gr\u00f6nt",blue:"Bl\u00e5tt",clusterCountTitle:"\u00c5_Number of features___________________\u00f6"});
// check if a variable is not undefined, null, or blank var isset = function(variable){ return typeof(variable) !== "undefined" && variable !== null && variable !== ''; } var now = function(){ return 1 * new Date; } var guid = function() { return Config.version + '-xxxxxxxx-'.replace(/[x]/g, function(c) { var r = Math.random()*36|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(36); }) + (1 * new Date()).toString(36); } // reduces all optional data down to a string var optinalData = function(data) { if(isset(data) === false) { return ''; } else if(typeof data === 'object') { // runs optinalData again to reduce to string in case something else was returned return optinalData(JSON.stringify(data)); } else if(typeof data === 'function') { // runs the function and calls optinalData again to reduce further if it isn't a string return optinalData(data()); } else { return String(data); } }
if (typeof exports === 'object') { var assert = require('assert'); var alasql = require('..'); } else { __dirname = '.'; } describe('Test 213 CONVERT data types', function () { it('1. INT', function (done) { alasql('SELECT VALUE CONVERT(INT,123.45)', [], function (res) { assert(res === 123); done(); }); }); it('2. NUMBER', function (done) { alasql('SELECT VALUE CONVERT(NUMBER,"123.45")', [], function (res) { assert(res === 123.45); done(); }); }); it('3. STRING', function (done) { alasql('SELECT VALUE CONVERT(STRING,123.45)', [], function (res) { assert(res === '123.45'); done(); }); }); it('4. BOOLEAN', function (done) { alasql('SELECT VALUE CONVERT(BOOLEAN,0)', [], function (res) { assert(res === false); done(); }); }); it('5. VARCHAR', function (done) { var res = alasql('SELECT VALUE CONVERT(VARCHAR(5),"abcdefghijklmnopqrstuvwxyz")'); assert(res === 'abcde'); var res = alasql('SELECT VALUE CONVERT(VARCHAR(5),"abc")'); assert(res === 'abc'); done(); }); it('6. CHAR', function (done) { alasql('SELECT VALUE CONVERT(CHAR(5),"abc")', [], function (res) { assert(res === 'abc '); done(); }); }); });
//! moment.js locale configuration //! locale : Spanish Spain [es] //! author: https://github.com/moment/moment/blob/develop/locale/es.js var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'); var monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); var es = moment.defineLocale('es', { months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), monthsShort : function (m, format) { if (!m) { return monthsShortDot; } else if (/-MMM-/.test(format)) { return monthsShort[m.month()]; } else { return monthsShortDot[m.month()]; } }, monthsParseExact : true, weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD/MM/YYYY', LL : 'D [de] MMMM [de] YYYY', LLL : 'D [de] MMMM [de] YYYY H:mm', LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm' }, calendar : { sameDay : function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay : function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek : function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay : function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek : function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : 'en %s', past : 'hace %s', s : 'unos segundos', m : 'un minuto', mm : '%d minutos', h : 'una hora', hh : '%d horas', d : 'un día', dd : '%d días', M : 'un mes', MM : '%d meses', y : 'un año', yy : '%d años' }, dayOfMonthOrdinalParse : /\d{1,2}º/, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } });
var express = require('express'), router = express.Router(), resources = require('./../resources/model'); var sensors = require('./../plugins/internal/tempBaroAltPlugin'); router.route('/').get(function (req, res, next) { res.send(resources.pi.sensors); }); router.route('/barometer').get(function (req, res, next) { res.send(resources.pi.sensors.barometer); }); router.route('/temperature').get(function (req, res, next) { res.send(resources.pi.sensors.temperature); }); router.route('/altitude').get(function (req, res, next) { res.send(resources.pi.sensors.altitude); }); module.exports = router;
// Copyright Joyent, Inc. and other Node contributors. // // 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'; const common = require('../common'); const assert = require('assert'); const zlib = require('zlib'); const stream = require('stream'); const fs = require('fs'); const fixtures = require('../common/fixtures'); let zlibPairs = [ [zlib.Deflate, zlib.Inflate], [zlib.Gzip, zlib.Gunzip], [zlib.Deflate, zlib.Unzip], [zlib.Gzip, zlib.Unzip], [zlib.DeflateRaw, zlib.InflateRaw] ]; // how fast to trickle through the slowstream let trickle = [128, 1024, 1024 * 1024]; // tunable options for zlib classes. // several different chunk sizes let chunkSize = [128, 1024, 1024 * 16, 1024 * 1024]; // this is every possible value. let level = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let windowBits = [8, 9, 10, 11, 12, 13, 14, 15]; let memLevel = [1, 2, 3, 4, 5, 6, 7, 8, 9]; let strategy = [0, 1, 2, 3, 4]; // it's nice in theory to test every combination, but it // takes WAY too long. Maybe a pummel test could do this? if (!process.env.PUMMEL) { trickle = [1024]; chunkSize = [1024 * 16]; level = [6]; memLevel = [8]; windowBits = [15]; strategy = [0]; } let testFiles = ['person.jpg', 'elipses.txt', 'empty.txt']; if (process.env.FAST) { zlibPairs = [[zlib.Gzip, zlib.Unzip]]; testFiles = ['person.jpg']; } const tests = {}; testFiles.forEach(common.mustCall((file) => { tests[file] = fixtures.readSync(file); }, testFiles.length)); // stream that saves everything class BufferStream extends stream.Stream { constructor() { super(); this.chunks = []; this.length = 0; this.writable = true; this.readable = true; } write(c) { this.chunks.push(c); this.length += c.length; return true; } end(c) { if (c) this.write(c); // flatten const buf = Buffer.allocUnsafe(this.length); let i = 0; this.chunks.forEach((c) => { c.copy(buf, i); i += c.length; }); this.emit('data', buf); this.emit('end'); return true; } } class SlowStream extends stream.Stream { constructor(trickle) { super(); this.trickle = trickle; this.offset = 0; this.readable = this.writable = true; } write() { throw new Error('not implemented, just call ss.end(chunk)'); } pause() { this.paused = true; this.emit('pause'); } resume() { const emit = () => { if (this.paused) return; if (this.offset >= this.length) { this.ended = true; return this.emit('end'); } const end = Math.min(this.offset + this.trickle, this.length); const c = this.chunk.slice(this.offset, end); this.offset += c.length; this.emit('data', c); process.nextTick(emit); }; if (this.ended) return; this.emit('resume'); if (!this.chunk) return; this.paused = false; emit(); } end(chunk) { // walk over the chunk in blocks. this.chunk = chunk; this.length = chunk.length; this.resume(); return this.ended; } } // windowBits: 8 shouldn't throw zlib.createDeflateRaw({ windowBits: 8 }); { const node = fs.createReadStream(fixtures.path('person.jpg')); const raw = []; const reinflated = []; node.on('data', (chunk) => raw.push(chunk)); // Usually, the inflate windowBits parameter needs to be at least the // value of the matching deflate’s windowBits. However, inflate raw with // windowBits = 8 should be able to handle compressed data from a source // that does not know about the silent 8-to-9 upgrade of windowBits // that most versions of zlib/Node perform, and which *still* results in // a valid 8-bit-window zlib stream. node.pipe(zlib.createDeflateRaw({ windowBits: 9 })) .pipe(zlib.createInflateRaw({ windowBits: 8 })) .on('data', (chunk) => reinflated.push(chunk)) .on('end', common.mustCall( () => assert(Buffer.concat(raw).equals(Buffer.concat(reinflated))))); } // for each of the files, make sure that compressing and // decompressing results in the same data, for every combination // of the options set above. const testKeys = Object.keys(tests); testKeys.forEach(common.mustCall((file) => { const test = tests[file]; chunkSize.forEach(common.mustCall((chunkSize) => { trickle.forEach(common.mustCall((trickle) => { windowBits.forEach(common.mustCall((windowBits) => { level.forEach(common.mustCall((level) => { memLevel.forEach(common.mustCall((memLevel) => { strategy.forEach(common.mustCall((strategy) => { zlibPairs.forEach(common.mustCall((pair) => { const Def = pair[0]; const Inf = pair[1]; const opts = { level, windowBits, memLevel, strategy }; const def = new Def(opts); const inf = new Inf(opts); const ss = new SlowStream(trickle); const buf = new BufferStream(); // verify that the same exact buffer comes out the other end. buf.on('data', common.mustCall((c) => { const msg = `${file} ${chunkSize} ${ JSON.stringify(opts)} ${Def.name} -> ${Inf.name}`; let i; for (i = 0; i < Math.max(c.length, test.length); i++) { if (c[i] !== test[i]) { assert.fail(msg); break; } } })); // the magic happens here. ss.pipe(def).pipe(inf).pipe(buf); ss.end(test); }, zlibPairs.length)); }, strategy.length)); }, memLevel.length)); }, level.length)); }, windowBits.length)); }, trickle.length)); }, chunkSize.length)); }, testKeys.length));