text
stringlengths
2
6.14k
var MJ = require("mongo-fast-join"), MongoClient = require('mongodb').MongoClient, mongoJoin = new MJ(); MongoClient.connect("mongodb://localhost:27017/yelp", function(err, db) { if (!err) { mongoJoin .query( db.collection("business"), { categories: 'Veterinarians' }, { business_id: 1, _id: 0 } ) .join({ joinCollection: db.collection("review"), leftKeys: ["business_id"], rightKeys: ["business_id"], newKey: "reviews" }) .exec(function(err, items) { for (var i = 0; i < items.length; i++) { var item = items[i]; for (var j = 0; j < item.reviews.length; j++) { var review = item.reviews[j].text.replace(/(?:\r\n|\r|\n)/g, ' '); if (!RegExp(/(cat|kitten|gato|gata)/g).test(review) && !RegExp( /(dog|puppy|perro|perra|dogs)/g).test(review)) { console.log(review); } } } }); } });
import React from 'react'; import PropTypes from 'prop-types'; import { mount } from 'enzyme'; import { isClassExists, makeControlled } from './utils'; describe('test-utils', () => { describe('isClassExists function', () => { const classes = 'class class2 class3'; const element = {className: classes}; classes.split(' ').forEach(className => it(`should return true for className ${className}`, () => { expect(isClassExists(element, className)).toBe(true); }) ); [undefined, 'cla', 'class4'].forEach(className => it(`should return false for className ${className}`, () => { expect(isClassExists(element, className)).toBe(false); }) ); }); describe('makeControlled function', () => { const UncontrolledInput = props => <input {...props}/>; it('should init uncontrolled component with initial value', () => { const ControlledInput = makeControlled(UncontrolledInput); const initialValue = 'some value'; const component = mount( <ControlledInput value={initialValue} /> ); expect(component.find('input').getNode().value).toBe(initialValue); }); it('should invoke onChange callback', () => { const onChange = jest.fn(); const ControlledInput = makeControlled(UncontrolledInput); const component = mount( <ControlledInput onChange={onChange} /> ); const enteredValue = 'some value'; const input = component.find('input'); input.simulate('change', {target: {value: enteredValue}}); expect(onChange).toHaveBeenCalledTimes(1); expect(onChange.mock.calls[0][0].target.value).toBe(enteredValue); expect(input.getNode().value).toBe(enteredValue); }); it('should bind passed prop-functions to *this*', () => { // NOTE: don't use arrow functions const onEnter = function () { this.setState({value: ''}); }; const NotifyOnEnter = ({onEnter, ...passedProps}) => ( <UncontrolledInput {...passedProps} onKeyPress={e => e.key === 'Enter' && onEnter()} /> ); NotifyOnEnter.propTypes = { onEnter: PropTypes.func }; const ControlledInput = makeControlled(NotifyOnEnter); const component = mount( <ControlledInput value="some value" onEnter={onEnter} /> ); const input = component.find('input'); input.simulate('keypress', {key: 'Enter'}); expect(input.getNode().value).toBe(''); }); }); });
const html = require('choo/html') let listening module.exports = (props, actions) => { if (props.results.length && !listening) { listening = true document.addEventListener('click', onClick) } return html` <div id="autocomplete" class="control" style="position: relative;"> <input name="searchInput" placeholder="Search..." oninput=${onInput}} class="input"> <aside class="menu ${!props.results.length ? 'is-hidden' : ''}"> <ul class="menu-list"> ${props.results.map(result => html` <li> <a onclick=${e => select(result)}> ${result.prefLabel || result.label} </a> </li> `)} </ul> </aside> </div>` function onInput (e) { const value = e.target.value actions.search(value) } function select (result) { actions.select(result) closeDropdown() } function closeDropdown () { document.removeEventListener('click', onClick) actions.search(null) listening = false } function onClick (e) { const el = document.getElementById('autocomplete') const clickedOutside = e.target !== el && !el.contains(e.target) if (clickedOutside) { closeDropdown() } } }
'use strict'; var _ = require('lodash-node'); function isHealthy(prop) { return _.chain(prop).values().all(function(val) { return val === true; }).value(); } exports.status = function(status) { var mHealthy = isHealthy(status.Mobile); var wHealthy = isHealthy(status.Website); var rHealthy = status.RealTimeDataAvailable; return { 'all': { 'healthy': mHealthy && wHealthy && rHealthy }, 'mobile': { 'healthy': mHealthy }, 'website': { 'healthy': wHealthy }, 'realtime': { 'healthy': rHealthy }, }; };
'use strict'; galleryApp.controller('MainController', function MainController($scope, author, copyright, $location) { $scope.author = author; $scope.copyright = copyright; $scope.signOut = function () { $scope.isLoggedIn = false; $location.path('/home'); localStorage.clear(); }; if (localStorage.getItem('isLoggedIn')) { $scope.isLoggedIn = true; $scope.username = localStorage.getItem('username'); } });
import { AboutComponent, InfoComponent, EmploymentComponent, ProjectsComponent, SkillsComponent, ServiceComponent, EducationComponent, SocialComponent, RecognitionComponent, WritingComponent, ReadingComponent, SpeakingComponent, GovernanceComponent, LanguagesComponent, SamplesComponent, ReferencesComponent, TestimonialsComponent, InterestsComponent, ExtracurricularComponent, AffiliationsComponent } from '../default/default.facade'; const DIRECTIVES = [ AboutComponent, InfoComponent, EmploymentComponent, ProjectsComponent, SkillsComponent, ServiceComponent, EducationComponent, SocialComponent, RecognitionComponent, WritingComponent, ReadingComponent, SpeakingComponent, GovernanceComponent, LanguagesComponent, SamplesComponent, ReferencesComponent, TestimonialsComponent, InterestsComponent, ExtracurricularComponent, AffiliationsComponent ]; export const BASIS_DIRECTIVES = DIRECTIVES; export const BASIS_DECLARATIONS = [ ...DIRECTIVES ]
var ElementType = require("domelementtype"); var re_whitespace = /\s+/g; var NodePrototype = require("./lib/node"); var ElementPrototype = require("./lib/element"); function DomHandler(callback, options, elementCB){ if(typeof callback === "object"){ elementCB = options; options = callback; callback = null; } else if(typeof options === "function"){ elementCB = options; options = defaultOpts; } this._callback = callback; this._options = options || defaultOpts; this._elementCB = elementCB; this.dom = []; this._done = false; this._tagStack = []; this._parser = this._parser || null; } //default options var defaultOpts = { normalizeWhitespace: false, //Replace all whitespace with single spaces withStartIndices: false, //Add startIndex properties to nodes }; DomHandler.prototype.onparserinit = function(parser){ this._parser = parser; }; //Resets the handler back to starting state DomHandler.prototype.onreset = function(){ DomHandler.call(this, this._callback, this._options, this._elementCB); }; //Signals the handler that parsing is done DomHandler.prototype.onend = function(){ if(this._done) return; this._done = true; this._parser = null; this._handleCallback(null); }; DomHandler.prototype._handleCallback = DomHandler.prototype.onerror = function(error){ if(typeof this._callback === "function"){ this._callback(error, this.dom); } else { if(error) throw error; } }; DomHandler.prototype.onclosetag = function(name, lastLt , lastGt ){ //if(this._tagStack.pop().name !== name) this._handleCallback(Error("Tagname didn't match!")); var elem = this._tagStack.pop(); if(elem && elem.inner) elem.inner.end = lastLt ; if(elem && elem.outer) elem.outer.end = lastGt + 1 ; if(this._elementCB) this._elementCB(elem); }; DomHandler.prototype._addDomElement = function(element){ var parent = this._tagStack[this._tagStack.length - 1]; var siblings = parent ? parent.children : this.dom; var previousSibling = siblings[siblings.length - 1]; element.next = null; if(this._options.withStartIndices){ element.startIndex = this._parser.startIndex; } if (this._options.withDomLvl1) { element.__proto__ = element.type === "tag" ? ElementPrototype : NodePrototype; } if(previousSibling){ element.prev = previousSibling; previousSibling.next = element; } else { element.prev = null; } siblings.push(element); element.parent = parent || null; }; DomHandler.prototype.onopentag = function(name, attribs , lastLt , lastGt ){ var element = { type: name === "script" ? ElementType.Script : name === "style" ? ElementType.Style : ElementType.Tag, name: name, attribs: attribs, children: [], inner: {}, outer: {}, }; if(element.inner) element.inner.start = lastGt + 1; if(element.outer) element.outer.start = lastLt; this._addDomElement(element); this._tagStack.push(element); }; DomHandler.prototype.ontext = function(data){ //the ignoreWhitespace is officially dropped, but for now, //it's an alias for normalizeWhitespace var normalize = this._options.normalizeWhitespace || this._options.ignoreWhitespace; var lastTag; if(!this._tagStack.length && this.dom.length && (lastTag = this.dom[this.dom.length-1]).type === ElementType.Text){ if(normalize){ lastTag.data = (lastTag.data + data).replace(re_whitespace, " "); } else { lastTag.data += data; } } else { if( this._tagStack.length && (lastTag = this._tagStack[this._tagStack.length - 1]) && (lastTag = lastTag.children[lastTag.children.length - 1]) && lastTag.type === ElementType.Text ){ if(normalize){ lastTag.data = (lastTag.data + data).replace(re_whitespace, " "); } else { lastTag.data += data; } } else { if(normalize){ data = data.replace(re_whitespace, " "); } this._addDomElement({ data: data, type: ElementType.Text }); } } }; DomHandler.prototype.oncomment = function(data){ var lastTag = this._tagStack[this._tagStack.length - 1]; if(lastTag && lastTag.type === ElementType.Comment){ lastTag.data += data; return; } var element = { data: data, type: ElementType.Comment }; this._addDomElement(element); this._tagStack.push(element); }; DomHandler.prototype.oncdatastart = function(){ var element = { children: [{ data: "", type: ElementType.Text }], type: ElementType.CDATA }; this._addDomElement(element); this._tagStack.push(element); }; DomHandler.prototype.oncommentend = DomHandler.prototype.oncdataend = function(){ this._tagStack.pop(); }; DomHandler.prototype.onprocessinginstruction = function(name, data){ this._addDomElement({ name: name, data: data, type: ElementType.Directive }); }; module.exports = DomHandler;
import Ember from 'ember'; import RSVP from 'rsvp'; export default Ember.Route.extend({ model() { return RSVP.Promise.resolve('Hello World'); } });
const { createElement: r } = require('react') const ReactDOM = require('react-dom') const { AppContainer } = require('./containers/App') const renderApp = (state) => { ReactDOM.render( r(AppContainer, state), document.getElementById('root') ) } module.exports = { renderApp }
webpackJsonp([3],{ /***/ 683: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__about_module__ = __webpack_require__(691); /* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "AboutComponent", function() { return __WEBPACK_IMPORTED_MODULE_0__about_module__["a"]; }); /* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "AboutModule", function() { return __WEBPACK_IMPORTED_MODULE_0__about_module__["b"]; }); /***/ }), /***/ 691: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_router__ = __webpack_require__(117); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AboutComponent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return AboutModule; }); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var AboutComponent = (function () { function AboutComponent() { } return AboutComponent; }()); AboutComponent = __decorate([ __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["b" /* Component */])({ selector: 'About', template: __webpack_require__(707) }) ], AboutComponent); var AboutModule = (function () { function AboutModule() { } return AboutModule; }()); AboutModule = __decorate([ __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["a" /* NgModule */])({ imports: [ __WEBPACK_IMPORTED_MODULE_1__angular_router__["a" /* RouterModule */].forChild([{ path: '', component: AboutComponent }]) ], declarations: [AboutComponent] }) ], AboutModule); /***/ }), /***/ 707: /***/ (function(module, exports) { module.exports = "<section class=\"about\">\r\n <h3>Angular + nodejs + express 驱动的一个博客</h3>\r\n <p>\r\n 热爱前端工作,关注前端最新动态。\r\n </p>\r\n <p>\r\n 可以通过 github 或者 <a href=\"mailto:le720@outlook.com\">le720@outlook.com</a> 联系我。\r\n </p>\r\n</section>" /***/ }) });
module.exports = function(router) { require('./asset/index')(router); require('./companion/index')(router); require('./feature/index')(router); require('./npc/index')(router); require('./person/index')(router); require('./site/index')(router); require('./story/index')(router); require('./user/index')(router); require('./world/index')(router); };
'use strict'; var path = require('path'); var defer = require('config/defer').deferConfig; var chalk = require('chalk'); var pkgjson = require(path.resolve('./package.json')); module.exports = { nodeEnvShort: defer(function() { throw new Error(chalk.red('NODE_ENV value not recognised!')); }), repo: { title: 'NXFC Base', description: 'NXFC Base configuration', pkgjson: pkgjson }, depends: { }, provides: { } };
import React from 'react'; import { Provider } from 'react-redux'; import renderer from 'react-test-renderer'; import configureStore from 'redux-mock-store'; import Main from './Main'; const mockStore = configureStore(); const state = { auth: { signIn: { signingIn: false } } }; const store = mockStore(state); it('renders', () => { const component = renderer.create( <Provider store={store}> <Main /> </Provider> ); expect(component.toJSON()).toMatchSnapshot(); });
require( '../setup' ); var requestor = require( 'request' ).defaults( { jar: true } ); var postal = require( 'postal' ); var events = postal.channel( 'events' ); var port = 8988; var config = { port: port, socketio: true, websocket: true, defaultUser: true }; var post, get; var harnessFn = require( '../../src/harness' ); describe( 'Session Management', function() { var harness, loggedOut; before( function() { harness = harnessFn( config ); var testCall = function( env ) { env.reply( { data: 'hello' } ); }; var logout = function( env ) { env.logout(); env.reply( { data: 'session ended' } ); }; harness.addResource( { name: 'test', actions: { call: { url: '/call', method: 'get', topic: 'call', handle: testCall }, logout: { url: '/logout', method: 'all', topic: 'logout', handle: logout }, } } ); harness.addMiddleware( '/api/test/logout', function logout( req, res, next ) { loggedOut = true; next(); } ); harness.setActionRoles( 'test.call', [ 'user' ] ); harness.start(); get = function( req ) { return when.promise( function( resolve, reject ) { requestor.get( req, function( err, res ) { if ( err ) { reject( err ); } else { resolve( res ); } } ); } ); }; post = lift( requestor.post ); } ); describe( 'HTTP: when making requests before and after logout', function() { var counter = 0; var originalAuthenticate; var requests = [ { url: 'http://localhost:8988/api/test/call', headers: { 'Authorization': 'Bearer one' } }, { url: 'http://localhost:8988/api/test/call', headers: { 'Authorization': 'Bearer one' } }, { url: 'http://localhost:8988/api/test/call', }, { url: 'http://localhost:8988/api/test/logout' }, { url: 'http://localhost:8988/api/test/call' } ]; var getFn = function( req ) { return function() { return get( req ); }; }; before( function() { originalAuthenticate = harness.auth.authenticate; harness.auth.authenticate = function( req, res, next ) { // don't count the call after logout if ( !loggedOut ) { counter = counter + 1; } originalAuthenticate( req, res, next ); }; } ); it( 'should have completed all requests successfully', function() { return seq( _.map( requests, getFn ) ) .then( function( responses ) { return _.map( responses, 'statusCode' ); } ) .should.eventually.deep.equal( [ 200, 200, 200, 200, 401 ] ); } ); it( 'should not authenticate requests once session is established', function() { counter.should.be.lessThan( 2 ); } ); after( function() { harness.auth.authenticate = originalAuthenticate; } ); } ); describe( 'Socket.io: when logging out via socket', function() { var responses = []; var initialUser, initialRoles, loggedOutUser, loggedOutRoles; var disconnected; before( function( done ) { var io = harness.getIOClient( 'http://localhost:8988?token=one', { query: 'token=one' } ); io.once( 'test.call', function( msg ) { responses.push( msg ); io.emit( 'test.logout', { thing: 'whatever' } ); } ); io.on( 'connect', function() { io.emit( 'test.call', { thing: 'whatever' } ); } ); events.subscribe( 'socket.client.connected', function( c ) { initialUser = c.socket.user.name; initialRoles = c.socket.user.roles; } ); events.subscribe( 'socket.client.closed', function( c ) { if ( !disconnected ) { disconnected = true; loggedOutUser = c.socket.user.name; loggedOutRoles = c.socket.user.roles; done(); } } ); io.open(); } ); it( 'should have attached the correct user on connect', function() { initialUser.should.equal( 'userone' ); } ); it( 'should have attached the correct user roles on connect', function() { initialRoles.should.eql( [ 'user' ] ); } ); it( 'should report correct user with socket disconnection', function() { loggedOutUser.should.equal( 'userone' ); } ); it( 'should report correct roles socket disconnection', function() { loggedOutRoles.should.eql( [ 'user' ] ); } ); it( 'should completed request', function() { responses.should.eql( [ 'hello' ] ); } ); it( 'should have closed socket', function() {} ); } ); after( function() { harness.stop(); } ); } );
module.exports = { description: "", ns: "react-material-ui", type: "ReactNode", dependencies: { npm: { "material-ui/svg-icons/image/camera-alt": require('material-ui/svg-icons/image/camera-alt') } }, name: "ImageCameraAlt", ports: { input: {}, output: { component: { title: "ImageCameraAlt", type: "Component" } } } }
$(function(){ $("body").on("click", "#menu-trigger", function(t) { t.preventDefault(); var e = $(this).data("trigger"); $(e).toggleClass("toggled"), $(this).toggleClass("open"), "#sidebar" == e && ($elem = "#sidebar", $elem2 = "#menu-trigger", $("#chat").hasClass("toggled") ? $("#chat").removeClass("toggled") : $("#header-c").toggleClass("sidebar-toggled")), $("#header-c").hasClass("sidebar-toggled") && $(document).on("click", function(t) { 0 === $(t.target).closest($elem).length && 0 === $(t.target).closest($elem2).length && setTimeout(function() { $($elem).removeClass("toggled"), $("#header-c").removeClass("sidebar-toggled"), $($elem2).removeClass("open") }) }) }) })
import ApiRequest from './helpers/apiHelper'; async function unrateConversationComment(conversationCommentId) { const request = new ApiRequest(); request .setMethod('DELETE') .setEndpoint(`comments/${conversationCommentId}/rating`) .setBody({ data: { type: 'ratings', }, }); const response = await request.executeRequest(); const responseBody = await response.json(); return responseBody.data; } export default unrateConversationComment;
var _ = require('lodash'); var _EventHandlingMixin = require('./_EventHandlingMixin'); var _DestroyableMixin = require('./_DestroyableMixin'); module.exports = _.extend({ initializeRecordHandling: function () { this._registeredRecords = {}; this.initializeEventHandling(); this.initializeDestroyable(); }, record: function (name) { if (_.isObject(name)) { return name; } if (!this._registeredRecords[name]) { return null; } return this._registeredRecords[name]; }, bindRecordState: function (mapping, stateSetterFunction) { var recordName, record, recordMap, property, bind; for (recordName in mapping) { recordMap = mapping[recordName]; record = this._registeredRecords[recordName]; if (!record) { continue; } var invokeState = function (recordMap, record, stateSetterFunction) { var state = {}, isArray = _.isArray(recordMap); _.each(recordMap, function (record, recordProperty, stateProperty) { if (true === isArray) { stateProperty = recordProperty; } // @todo escape this? state[stateProperty] = record.get(recordProperty); }.bind(this, record)); stateSetterFunction(state); }.bind(this, recordMap, record, stateSetterFunction); this.own(record, 'change', invokeState); record.hookEngage(); this.bgOnDestroy(function (record) { record.hookDisable(); }.bind(this, record)); invokeState(); } }, registerRecords: function (records) { var name; for (name in records) { this.registerRecord(name, records[name]); } return this; }, registerRecord: function (name, record) { this._registeredRecords[name] = record; return this; } }, _EventHandlingMixin, _DestroyableMixin);
'use strict'; var gulp = require('gulp'), gulpLoadPlugins = require('gulp-load-plugins'), plugins = gulpLoadPlugins(), appRoot = process.cwd(), paths = { jsSrc: [`${appRoot}/src/**/*.js`], jsDist: [`${appRoot}/dist/**/*.js`], jsTests: [`${appRoot}/test/**/*-test.js`] }; gulp.task('test', ['env:test', 'test:babel', 'test:jshint', 'test:coverage']); gulp.task('env:test', () => { process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; process.env.NODE_ENV = 'test'; }); gulp.task('test:babel', () => { return gulp.src(paths.jsSrc) .pipe(plugins.babel()) .pipe(gulp.dest(`${appRoot}/dist`)); }); gulp.task('test:jshint', ['test:babel'], () => { return gulp.src(paths.jsDist) .pipe(plugins.jshint()) .pipe(plugins.jshint.reporter('jshint-stylish')) .pipe(plugins.jshint.reporter('fail')); }); gulp.task('test:coverage', ['test:jshint'], () => { let deferred = require('q').defer(); let executeTests = () => { gulp.src(paths.jsTests) .pipe(plugins.plumber()) .pipe(plugins.mocha({ reporters: 'spec' })) .pipe(plugins.istanbul.writeReports({ reports: ['lcovonly'] })); // Creating the reports after tests runned }; // instrumentation *.js gulp.src(paths.jsDist) .pipe(plugins.plumber()) .pipe(plugins.istanbul({ includeUntested: true })) // Covering files .pipe(plugins.istanbul.hookRequire())// Force `require` to return covered files .on('finish', () => executeTests()); return deferred.promise; });
(function() { angular.module('app.dashboard') .controller('NewEmailCtrl', NewEmailCtrl); function NewEmailCtrl($uibModalInstance, Auth, Alert) { var vm = this; vm.newEmail = {}; vm.newEmail.close = close; vm.newEmail.send = send; //////////// function close() { $uibModalInstance.close(); } function send(form) { if (form.$valid) { Auth.sendEmail(this.to, this.subject, this.message, function(isSent) { if (isSent === true) { // Hide modal and show confirmation $uibModalInstance.close(); Alert.add('success', 'Email successfully sent'); } else { // Hide modal and show alert $uibModalInstance.close(); Alert.add('danger', 'Problems sending your email'); } }); } } } })();
import React, {PropTypes} from 'react'; import { Menu, Icon } from 'semantic-ui-react'; import { Link } from 'react-router'; import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import * as loginActions from '../actions/loginActions'; class Header extends React.Component { constructor(props, context) { super(props, context); this.logout = this.logout.bind(this); } logout() { this.props.actions.logout(); } render() { const {loading, login, location} = this.props; return ( <Menu pointing secondary stackable> <Menu.Item as={Link} to="/" name="home" active={location === '/'} onClick={this.handleItemClick}/> <Menu.Item as={Link} to="/csr" name="csr" active={location === '/csr'} onClick={this.handleItemClick}/> <Menu.Item as={Link} to="/agency" name="agency" active={location === '/agency'} onClick={this.handleItemClick}/> <Menu.Item as={Link} to="/about" name="about" active={location === '/about'} onClick={this.handleItemClick}/> {loading && <Menu.Item><Icon loading name="spinner"/></Menu.Item>} <Menu.Menu position="right"> {!login && <Menu.Item as={Link} to="/login" name="login" active={location === '/login'} onClick={this.handleItemClick}/> } {login && <Menu.Item as={Link} to="/" name="logout" onClick={this.logout}/> } </Menu.Menu> </Menu> ); } } Header.propTypes = { loading: PropTypes.bool.isRequired, login: PropTypes.bool.isRequired, location: PropTypes.string.isRequired, actions: PropTypes.object.isRequired }; function mapStateToProps(state) { return { loading: state.numberAjaxCallsInProgress > 0, login: state.login, location: state.location }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(loginActions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(Header);
/** * @authors: @qdouble and @AngularClass */ const webpack = require('webpack'); const root = require('../helpers').root; /** * Webpack Plugins */ const ProvidePlugin = require('webpack/lib/ProvidePlugin'); const DefinePlugin = require('webpack/lib/DefinePlugin'); const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin; const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin'); const EXCLUDE_SOURCE_MAPS = require('../constants').EXCLUDE_SOURCE_MAPS; const MY_TEST_RULES = require('../constants').MY_TEST_RULES; const MY_TEST_PLUGINS = require('../constants').MY_TEST_PLUGINS; /** * Webpack configuration * * See: http://webpack.github.io/docs/configuration.html#cli */ module.exports = { entry: {}, /** * Source map for Karma from the help of karma-sourcemap-loader & karma-webpack * * Do not change, leave as is or it wont work. * See: https://github.com/webpack/karma-webpack#source-maps */ devtool: 'inline-source-map', /** * Options affecting the resolving of modules. * * See: http://webpack.github.io/docs/configuration.html#resolve */ resolve: { /** * An array of extensions that should be used to resolve modules. * * See: http://webpack.github.io/docs/configuration.html#resolve-extensions */ extensions: ['.ts', '.js'] }, /** * Options affecting the normal modules. * * See: http://webpack.github.io/docs/configuration.html#module */ module: { /** * An array of applied pre and post loaders. * * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders */ rules: [ /** * Tslint loader support for *.ts files * * See: https://github.com/wbuchwalter/tslint-loader */ { test: /\.ts$/, enforce: 'pre', loader: 'tslint-loader', exclude: [root('node_modules')] }, /** * Source map loader support for *.js files * Extracts SourceMaps for source files that as added as sourceMappingURL comment. * * See: https://github.com/webpack/source-map-loader */ { test: /\.js$/, enforce: 'pre', loader: 'source-map-loader', exclude: [EXCLUDE_SOURCE_MAPS] }, /** * Typescript loader support for .ts and Angular 2 async routes via .async.ts * * See: https://github.com/s-panferov/awesome-typescript-loader */ { test: /\.ts$/, loaders: [ 'awesome-typescript-loader?sourceMap=false,inlineSourceMap=true,compilerOptions{}=removeComments:true', 'angular2-template-loader' ], exclude: [/\.e2e\.ts$/] }, /** * Json loader support for *.json files. * * See: https://github.com/webpack/json-loader */ { test: /\.json$/, loader: 'json-loader', exclude: [ root('src/client/a2/a2.html'), root('src/client/main/main.html') ] }, /** * Raw loader support for *.css files * Returns file content as string * * See: https://github.com/webpack/raw-loader */ { test: /\.css$/, loaders: ['to-string-loader', 'css-loader'], exclude: [ root('src/client/a2/a2.html'), root('src/client/main/main.html') ] }, /** * Raw loader support for *.html * Returns file content as string * * See: https://github.com/webpack/raw-loader */ { test: /\.html$/, loader: 'raw-loader', exclude: [ root('src/client/a2/a2.html'), root('src/client/main/main.html') ] }, /** * Instruments JS files with Istanbul for subsequent code coverage reporting. * Instrument only testing sources. * * See: https://github.com/deepsweet/istanbul-instrumenter-loader */ { test: /\.(js|ts)$/, loader: 'istanbul-instrumenter-loader', enforce: 'post', include: root('src'), exclude: [ /\.(e2e|spec)\.ts$/, /node_modules/ ] }, ...MY_TEST_RULES ] }, /** * Add additional plugins to the compiler. * * See: http://webpack.github.io/docs/configuration.html#plugins */ plugins: [ new webpack.ContextReplacementPlugin( /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/, root('./src') ), /** * Plugin: DefinePlugin * Description: Define free variables. * Useful for having development builds with debug logging or adding global constants. * * Environment helpers * * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin */ // NOTE: when adding more properties make sure you include them in custom-typings.d.ts new DefinePlugin({ AOT: false, ENV: JSON.stringify('test'), HMR: false, PORT: 3000, HOST: JSON.stringify('localhost'), UNIVERSAL: false }), new NamedModulesPlugin(), new webpack.LoaderOptionsPlugin({ options: { tslint: { emitErrors: false, failOnHint: false, resourcePath: root('./src') } } }), ...MY_TEST_PLUGINS ], /** * Include polyfills or mocks for various node stuff * Description: Node configuration * * See: https://webpack.github.io/docs/configuration.html#node */ node: { global: true, process: false, crypto: false, module: false, clearImmediate: false, setImmediate: false } };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.bindInstances = bindInstances; exports.generateValidateSchema = generateValidateSchema; exports.clone = clone; var _extend = require('extend'); var _extend2 = _interopRequireDefault(_extend); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function applyEntityConstructor(field, data) { var Type = field.ref; if (field.type === 'array') { return Array.isArray(data) ? data.map(function (instance) { return new Type(instance); }) : undefined; } return new Type(data); } function createGetterAndSetter(instance, field) { return { set: function set(value) { if (instance.data[field] !== value) { instance.data[field] = value; //eslint-disable-line // instance._validate(); } }, get: function get() { return instance.data[field]; }, enumerable: true }; } function bindInstances(data) { var _this = this; var newData = {}; Object.keys(this.schema).forEach(function (field) { newData[field] = data[field] || _this.schema[field].defaultValue; if (_this.schema[field].ref) { newData[field] = applyEntityConstructor(_this.schema[field], newData[field]); } Object.defineProperty(_this, field, createGetterAndSetter(_this, field)); }); return newData; } function generateValidateSchema(schemaObj) { var schema = (0, _extend2.default)(true, {}, schemaObj); var validateSchema = {}; Object.keys(schema).forEach(function (field) { var attr = schema[field]; if (attr.ref) { if (attr.type === 'array') { validateSchema[field] = attr; validateSchema[field].items = [attr.ref.validateSchema]; delete validateSchema[field].ref; } else { validateSchema[field] = attr.ref.validateSchema; } } else { validateSchema[field] = attr; } }); return validateSchema; } function clone(obj) { return JSON.parse(JSON.stringify(obj)); } exports.default = { bindInstances: bindInstances, generateValidateSchema: generateValidateSchema, clone: clone };
var cp = require('child_process'); var EventEmitter = require("events").EventEmitter; var e1 = new EventEmitter(); e1.on("open", function(){ cp.fork("./child2.js", []); cp.fork("./child2.js", []); cp.fork("./child2.js", []); }); setTimeout(function(){ e1.emit("open"); }, 1000);
import FormEntry from './FormEntry'; module.exports = { FormEntry: FormEntry }
import "babel-polyfill"; import express from "express"; import path from "path"; import { getSites, getSitesForClient } from "./siteStore"; import scan from "./scan"; import * as store from "./store"; const app = express(); app.set("view engine", "pug"); app.get("/client.entry.js", (req, res) => { res.sendFile("client.entry.js", { root: path.join(__dirname, "../dist/") }); }); app.get("/", (req, res) => { res.render("index"); }); /** * Gets all supported sites that can be scanned. Returns JSON of the following format: * { * key: string, * name: string, * visitUrl: string * }[] */ app.get("/sites", (req, res) => { res.send(getSitesForClient()); }); /** * Scans for new dresses for a site denoted by the provided key. Returns JSON of the * following format: * { * image: string, * seen: boolean, * link?: string, * price?: string * }[] */ app.get("/scan/:key", (req, res) => { const { key } = req.params; const site = getSites().get(key); if (!site) { res.status(500).send({ error: "bad site" }); return; } scan(site).then( result => res.send(result), error => { console.error("error scanning site:", error); const errorString = error ? error.toString() : "unknown"; res.status(500).send({ error: errorString }); } ); }); /** * Gets recently-scanned dresses. Returns JSON of the following format: * { * image: string, * siteKey: string, * added: number * }[] */ app.get("/recent", async (req, res) => { const dresses = await store.getRecent(); res.send( dresses.map(({ image, site_key: siteKey, added }) => ({ image, siteKey, added })) ); }); // Initialize database. store.createSeenTable(); app.listen(process.env.PORT || 3000, () => console.log("Ready"));
# -*- python -*- # ex: set syntax=python: # This is a sample buildmaster config file. It must be installed as # 'master.cfg' in your buildmaster's base directory. # This is the dictionary that the buildmaster pays attention to. We also use # a shorter alias to save typing. c = BuildmasterConfig = {} ####### BUILDSLAVES # The 'slaves' list defines the set of recognized buildslaves. Each element is # a BuildSlave object, specifying a unique slave name and password. The same # slave name and password must be configured on the slave. from buildbot.buildslave import BuildSlave c['slaves'] = [] {% for slave in buildbot_slaves %} c['slaves'].append( BuildSlave("{{ slave.name }}", "{{ slave.password }}", {% if slave.keyword_arguments is defined %} {% for key, value in slave.keyword_arguments.iteritems() %} {{ key }}={{ value }}, {% endfor %} {% endif %} ) ) {% endfor %} # 'slavePortnum' defines the TCP port to listen on for connections from slaves. # This must match the value configured into the buildslaves (with their # --master option) c['slavePortnum'] = {{ buildbot_slave_port }} ####### CHANGESOURCES # the 'change_source' setting tells the buildmaster how it should find out # about source code changes. from buildbot.changes.gitpoller import GitPoller from twisted.internet import utils import os c['change_source'] = [] {% for change_source in buildbot_change_sources %} c['change_source'].append( {{ change_source.type }}( {% for key, value in change_source.keyword_arguments.iteritems() %} {{ key }}={{ value }}, {% endfor %} ) ) {% endfor %} ####### SCHEDULERS from buildbot.schedulers.basic import * from buildbot.schedulers.forcesched import ForceScheduler from buildbot.schedulers.timed import Nightly from buildbot.changes import filter c['schedulers'] = [] {% for scheduler in buildbot_schedulers %} c['schedulers'].append( {{ scheduler.type }}( {% if scheduler.arguments is defined %}{{ scheduler.arguments|default([])|join(',') }}, {% endif %} {% for key, value in scheduler.keyword_arguments.iteritems() %} {{ key }}={{ value }}, {% endfor %} ) ) {% endfor %} ####### BUILDERS # The 'builders' list defines the Builders, which tell Buildbot how to perform a build: # what steps, and which slaves can execute them. Note that any particular build will # only take place on one slave. from buildbot.process.factory import BuildFactory from buildbot.steps.source.git import Git from buildbot.steps.shell import ShellCommand from buildbot.steps.transfer import FileUpload from buildbot.steps.transfer import FileDownload from buildbot.config import BuilderConfig c['builders'] = [] {% for builder in buildbot_builders %} factory = BuildFactory() factory.addStep(Git(repourl="{{ builder.url }}", mode="incremental")) {% for build_step in builder.build_steps %} factory.addStep({{ build_step }}) {% endfor %} c['builders'].append( BuilderConfig( name="{{ builder.name }}", slavenames=["{{ builder.slave_names|join('","') }}"], factory=factory ) ) {% endfor %} ####### STATUS TARGETS # 'status' is a list of Status Targets. The results of each build will be # pushed to these targets. buildbot/status/*.py has a variety to choose from, # including web pages, email senders, and IRC bots. c['status'] = [] from buildbot.status import html, mail from buildbot.status.web import authz, auth {% for status in buildbot_status %} c['status'].append( {{ status.type }}({% if status.arguments is defined %}{{ status.arguments|default([])|join(',') }}, {% endif %} {% if status.keyword_arguments is defined %} {% for key, value in status.keyword_arguments.iteritems() %} {{ key }}={{ value }}, {% endfor %} {% endif %} ) ) {% endfor %} authz_cfg=authz.Authz( # change any of these to True to enable; see the manual for more # options {% if buildbot_basic_auth %} auth=auth.BasicAuth([("{{ buildbot_basic_auth_username }}","{{ buildbot_basic_auth_password }}")]), {% endif %} gracefulShutdown = False, forceBuild = 'auth', # use this to test your slave once it is set up forceAllBuilds = False, pingBuilder = False, stopBuild = False, stopAllBuilds = False, cancelPendingBuild = False, ) c['status'].append(html.WebStatus(http_port={{ buildbot_web_port }}, authz=authz_cfg)) ####### PROJECT IDENTITY # the 'title' string will appear at the top of this buildbot # installation's html.WebStatus home page (linked to the # 'titleURL') and is embedded in the title of the waterfall HTML page. c['title'] = "{{ buildbot_title }}" c['titleURL'] = "{{ buildbot_project_url }}" # the 'buildbotURL' string should point to the location where the buildbot's # internal web server (usually the html.WebStatus page) is visible. This # typically uses the port number set in the Waterfall 'status' entry, but # with an externally-visible host name which the buildbot cannot figure out # without some help. c['buildbotURL'] = "http://{{ buildbot_web_host }}:{{ buildbot_web_port }}/" ####### DB URL c['db'] = { # This specifies what database buildbot uses to store its state. You can leave # this at its default for all but the largest installations. 'db_url' : "sqlite:///state.sqlite", }
import template from './mv-notification-area.html'; class mvNotificationAreaController { constructor($element) { 'ngInject'; this.$element = $element[0]; this.notifications = []; this.offCssClass = 'off'; } checkEmpty() { let elementClass = this.$element.classList; return (this.notifications < 1) ? elementClass.add(this.offCssClass) : elementClass.remove(this.offCssClass); } } let mvNotificationAreaComponent = { bindings: {}, template: template, controller: mvNotificationAreaController, bindToController: true, controllerAs: 'vm' }; export default mvNotificationAreaComponent; // app.directive('mvNotificationArea', ['mvNotificationService', '$rootScope', // function (mvNotificationService, $rootScope) { // return { // restrict: 'AC', // templateUrl: 'views/directives/mv-notification-area.html', // transclude: true, // controller: function ($scope, $element, $attrs) { // $scope.notifications = mvNotificationService.get(); // // $scope.checkEmpty = function () { // if ($scope.notifications < 1) { // $element.addClass('off'); // return true; // } // if ($element.hasClass('off')) { // $element.removeClass('off'); // } // return false; // }; // // $scope.$on('mvNotificationService.set', function ($event) { // $scope.notifications = mvNotificationService.get(); // $scope.checkEmpty(); // }); // // }, // link: function (scope, element, attrs) { // if (scope.notifications.length < 1) { // $element.addClass("off"); // } // } // }; // }]);
define(['marionette', 'templates/compiled', 'lib/cookie'], function(Marionette, JST, Cookie) { var EmployeeRowView = Marionette.ItemView.extend({ template: JST.EmployeeRowTemplate, tagName: 'tr', }); var DesignerRowView = Marionette.ItemView.extend({ template: JST.DesignerRowTemplate, tagName: 'tr', }); var CustomerRowView = Marionette.ItemView.extend({ template: JST.CustomerRowTemplate, tagName: 'tr', }); var EmployeeTableView = Marionette.CompositeView.extend({ template: JST.EmployeeTableTemplate, className: 'employee-table', childView: EmployeeRowView, childViewContainer: "tbody", initialize: function() { var Model = Backbone.Model.extend({}); var Collection = Backbone.Collection.extend({ model: Model, url: '/data/Account/Employee', }); this.collection = new Collection(); this.collection.fetch(); } }); var DesignerTableView = Marionette.CompositeView.extend({ template: JST.DesignerTableTemplate, className: 'designer-table', childView: DesignerRowView, childViewContainer: "tbody", initialize: function() { var Model = Backbone.Model.extend({}); var Collection = Backbone.Collection.extend({ model: Model, url: '/data/Account/Designer', }); this.collection = new Collection(); this.collection.fetch(); } }); var CustomerTableView = Marionette.CompositeView.extend({ template: JST.CustomerTableTemplate, className: 'customer-table', childView: CustomerRowView, childViewContainer: "tbody", initialize: function() { var Model = Backbone.Model.extend({}); var Collection = Backbone.Collection.extend({ model: Model, url: '/data/Account/Customer', }); this.collection = new Collection(); this.collection.fetch(); } }); var Account = Marionette.LayoutView.extend({ className: 'account-body', template: JST.AccountTemplate, regions: { employeeTable: '#employeeTable', designerTable: '#designerTable', customerTable: '#customerTable', }, onShow: function() { var cookie = Cookie.getCookie(); if ('admin' === cookie.username && 'pass' === cookie.password) { this.employeeTable.show(new EmployeeTableView()); this.designerTable.show(new DesignerTableView()); this.customerTable.show(new CustomerTableView()); } else { } } }); return Account; });
(function($){ // Search var $searchWrap = $('#search-form-wrap'), isSearchAnim = false, searchAnimDuration = 200; var startSearchAnim = function(){ isSearchAnim = true; }; var stopSearchAnim = function(callback){ setTimeout(function(){ isSearchAnim = false; callback && callback(); }, searchAnimDuration); }; $('#nav-search-btn').on('click', function(){ if (isSearchAnim) return; startSearchAnim(); $searchWrap.addClass('on'); stopSearchAnim(function(){ $('.search-form-input').focus(); }); }); $('.search-form-input').on('blur', function(){ startSearchAnim(); $searchWrap.removeClass('on'); stopSearchAnim(); }); // Share $('body').on('click', function(){ $('.article-share-box.on').removeClass('on'); }).on('click', '.article-share-link', function(e){ e.stopPropagation(); var $this = $(this), url = $this.attr('data-url'), encodedUrl = encodeURIComponent(url), id = 'article-share-box-' + $this.attr('data-id'), offset = $this.offset(); if ($('#' + id).length){ var box = $('#' + id); if (box.hasClass('on')){ box.removeClass('on'); return; } } else { var html = [ '<div id="' + id + '" class="article-share-box">', '<input class="article-share-input" value="' + url + '">', '<div class="article-share-links">', '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>', '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>', '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="article-share-pinterest" target="_blank" title="Pinterest"></a>', '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="article-share-google" target="_blank" title="Google+"></a>', '</div>', '</div>' ].join(''); var box = $(html); $('body').append(box); } $('.article-share-box.on').hide(); box.css({ top: offset.top + 25, left: offset.left }).addClass('on'); }).on('click', '.article-share-box', function(e){ e.stopPropagation(); }).on('click', '.article-share-box-input', function(){ $(this).select(); }).on('click', '.article-share-box-link', function(e){ e.preventDefault(); e.stopPropagation(); window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450'); }); // Caption $('.article-entry').each(function(i){ $(this).find('img').each(function(){ if ($(this).is('.nofancybox')) return; // Avoid to apply fansybox if ($(this).parent().hasClass('fancybox')) return; var alt = this.alt; if (alt) $(this).after('<span class="caption">' + alt + '</span>'); $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>'); }); $(this).find('.fancybox').each(function(){ $(this).attr('rel', 'article' + i); }); }); if ($.fancybox){ $('.fancybox').fancybox(); } // Mobile nav var $container = $('#container'), isMobileNavAnim = false, mobileNavAnimDuration = 200; var startMobileNavAnim = function(){ isMobileNavAnim = true; }; var stopMobileNavAnim = function(){ setTimeout(function(){ isMobileNavAnim = false; }, mobileNavAnimDuration); } $('#main-nav-toggle').on('click', function(){ if (isMobileNavAnim) return; startMobileNavAnim(); $container.toggleClass('mobile-nav-on'); stopMobileNavAnim(); }); $('#wrap').on('click', function(){ if (isMobileNavAnim || !$container.hasClass('mobile-nav-on')) return; $container.removeClass('mobile-nav-on'); }); })(jQuery);
const zlib = require('zlib'); const { EventEmitter } = require('events'); const { parse: parseUrl } = require('url'); const http = require('http'); const https = require('https'); const dataSource = require('./dataSource'); exports.AUTH_URL = 'x-whistle-.script-auth-url'; exports.SNI_URL = 'x-whistle-.script-sni-url'; exports.REQ_RULES_URL = 'x-whistle-.script-req-rules-url'; exports.RES_RULES_URL = 'x-whistle-.script-res-rules-url'; exports.STATS_URL = 'x-whistle-.script-stats-url'; exports.DATA_URL = 'x-whistle-.script-data-url'; exports.noop = () => {}; const POLICY = 'x-whistle-.script-policy'; const isFunction = fn => typeof fn === 'function'; const URL_RE = /^https?:(?:\/\/|%3A%2F%2F)[\w.-]/; exports.isFunction = isFunction; exports.noop = () => {}; const getCharset = (headers) => { if (/charset=([^\s]+)/.test(headers['content-type'])) { return RegExp.$1; } return 'utf8'; }; exports.getCharset = getCharset; exports.isText = (headers) => { const type = headers['content-type']; return !type || /javascript|css|html|json|xml|application\/x-www-form-urlencoded|text\//i.test(type); }; const unzipBody = (headers, body, callback) => { let unzip; let encoding = headers['content-encoding']; if (body && typeof encoding === 'string') { encoding = encoding.trim().toLowerCase(); if (encoding === 'gzip') { unzip = zlib.gunzip.bind(zlib); } else if (encoding === 'deflate') { unzip = zlib.inflate.bind(zlib); } } if (!unzip) { return callback(null, body); } unzip(body, (err, data) => { if (err) { return zlib.inflateRaw(body, callback); } callback(null, data); }); }; exports.getStreamBuffer = (stream) => { return new Promise((resolve, reject) => { let buffer; stream.on('data', (data) => { buffer = buffer ? Buffer.concat([buffer, data]) : data; }); stream.on('end', () => { unzipBody(stream.headers, buffer, (err, data) => { if (err) { reject(err); } else { resolve(data || null); } }); }); stream.on('error', reject); }); }; exports.setupContext = (ctx, options) => { ctx.options = options; ctx.fullUrl = ctx.req.originalReq.url; }; const formateRules = (ctx) => { if (ctx.rules || ctx.values) { return { rules: Array.isArray(ctx.rules) ? ctx.rules.join('\n') : `${ctx.rules}`, values: ctx.values, }; } }; exports.formateRules = formateRules; exports.responseRules = (ctx) => { if (!ctx.body) { ctx.body = formateRules(ctx); } }; exports.getDataSource = () => { const ds = new EventEmitter(); const handleData = (type, args) => { ds.emit(type, ...args); }; dataSource.on('data', handleData); return { dataSource: ds, clearup: () => { dataSource.removeListener('data', handleData); ds.removeAllListeners(); }, }; }; exports.getContext = (req, res) => { const fullUrl = req.originalReq.url; return { req, res, fullUrl, url: fullUrl, headers: req.headers, method: req.method, }; }; exports.getFn = (f1, f2) => { if (isFunction(f1)) { return f1; } if (isFunction(f2)) { return f2; } }; const request = (url, headers, data) => { if (!url) { return; } const options = parseUrl(url); options.headers = Object.assign({}, headers); delete options.headers.host; if (data) { data = Buffer.from(JSON.stringify(data)); options.method = 'POST'; } return new Promise((resolve, reject) => { const httpModule = options.protocol === 'https:' ? https : http; options.rejectUnauthorized = false; const client = httpModule.request(options, (res) => { res.on('error', handleError); // eslint-disable-line let body; res.on('data', (chunk) => { body = body ? Buffer.concat([body, chunk]) : chunk; }); res.on('end', () => { clearTimeout(timer); // eslint-disable-line if (body) { try { resolve(JSON.parse(body.toString()) || ''); } catch (e) {} } resolve(''); }); }); const handleError = (err) => { clearTimeout(timer); // eslint-disable-line client.destroy(); reject(err); }; const timer = setTimeout(() => handleError(new Error('Timeout')), 12000); client.on('error', handleError); client.end(data); }); }; exports.request = async (url, headers, data) => { try { return await request(url, headers, data); } catch (e) { if (!data) { return request(url, headers, data); } } }; const hasPolicy = ({ headers }, name) => { const policy = headers[POLICY]; if (typeof policy === 'string') { return policy.toLowerCase().indexOf(name) !== -1; } }; const isRemote = (req) => { return hasPolicy(req, 'remote'); }; exports.isRemote = isRemote; exports.isSni = (req) => { return hasPolicy(req, 'sni'); }; exports.getRemoteUrl = (req, name) => { let url = req.headers[name]; if (typeof url === 'string') { url = decodeURIComponent(url); if (URL_RE.test(url)) { return url; } } };
/** * Policy Mappings * (sails.config.policies) * * Policies are simple functions which run **before** your controllers. * You can apply one or more policies to a given controller, or protect * its actions individually. * * Any policy file (e.g. `api/policies/authenticated.js`) can be accessed * below by its filename, minus the extension, (e.g. "authenticated") * * For more information on how policies work, see: * http://sailsjs.org/#/documentation/concepts/Policies * * For more information on configuring policies, check out: * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.policies.html */ module.exports.policies = { /*************************************************************************** * * * Default policy for all controllers and actions (`true` allows public * * access) * * * ***************************************************************************/ '*': ['passport', 'sessionAuth', 'hooks', 'users', 'system', 'helper'], 'auth': { '*': ['passport'] }, SettingsController: { '*': ['passport', 'sessionAuth', 'hooks', 'users', 'system', 'modules', 'helper'] }, RunController: { '*': true } /*************************************************************************** * * * Here's an example of mapping some policies to run before a controller * * and its actions * * * ***************************************************************************/ // RabbitController: { // Apply the `false` policy as the default for all of RabbitController's actions // (`false` prevents all access, which ensures that nothing bad happens to our rabbits) // '*': false, // For the action `nurture`, apply the 'isRabbitMother' policy // (this overrides `false` above) // nurture : 'isRabbitMother', // Apply the `isNiceToAnimals` AND `hasRabbitFood` policies // before letting any users feed our rabbits // feed : ['isNiceToAnimals', 'hasRabbitFood'] // } };
var Decimal = require('decimal.js'); var constants = require('../constants'); var cacheLimit = 100; var formulasInCache = []; var cache = {}; // the precision is slightly less than that of IEEE754 double // the range is slightly wider (9e308 is still ok here but Infinity in double) to make sure numeric data feeds can be safely read. When written, overflowing datafeeds will be saved as strings only Decimal.set({ precision: 15, // double precision is 15.95 https://en.wikipedia.org/wiki/IEEE_754 rounding: Decimal.ROUND_HALF_EVEN, maxE: 308, // double overflows between 1.7e308 and 1.8e308 minE: -324, // double underflows between 2e-324 and 3e-324 toExpNeg: -7, // default, same as for js number toExpPos: 21, // default, same as for js number }); var objBaseAssetInfo = { cap: constants.TOTAL_WHITEBYTES, is_private: false, is_transferrable: true, auto_destroy: false, fixed_denominations: false, issued_by_definer_only: true, cosigned_by_definer: false, spender_attested: false, is_issued: true, exists: true, definer_address: 'MZ4GUQC7WUKZKKLGAS3H3FSDKLHI7HFO', }; function isFiniteDecimal(val) { return (Decimal.isDecimal(val) && val.isFinite() && isFinite(val.toNumber())); } function toDoubleRange(val) { // check for underflow return (val.toNumber() === 0) ? new Decimal(0) : val; } // reduces precision to 15 digits to calculate the same result as Oscript would calculate function toOscriptPrecision(num) { return (new Decimal(num).times(1)).toString(); } exports.cache = cache; exports.formulasInCache = formulasInCache; exports.cacheLimit = cacheLimit; exports.Decimal = Decimal; exports.objBaseAssetInfo = objBaseAssetInfo; exports.isFiniteDecimal = isFiniteDecimal; exports.toDoubleRange = toDoubleRange; exports.toOscriptPrecision = toOscriptPrecision;
//I guess I need a comment $(document).on("click",".polllist .increment-poll span", function(){ var user_id = $(this).parent().parent().data("user-id"); var item_id = $(this).parent().parent().data("poll-list-item-id"); var value_span = $(this).parent().siblings(".value"); $.ajax({ url: '/poll_list_items/'+item_id+'.json', data: { poll_list_item: {value: (parseInt(value_span.html()) + 1), users_voted: user_id} }, type: 'PUT', success: function(response) { value_span.html(response["item"]["value"]); $.each(response["other_items"], function( index, value) { var item = $("*[data-poll-list-item-id="+value["id"]+"]"); $(item).children(".value").html(value["value"]); }) //logic to add user's picture }, failure: function(response){ //logic to display alert of why it failed } }); });
/** * DevExtreme (viz/gauges/linear_range_container.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 BaseRangeContainer = require("./base_range_container"), _Number = Number, _max = Math.max, _normalizeEnum = require("../core/utils").normalizeEnum; var LinearRangeContainer = BaseRangeContainer.inherit({ _processOptions: function() { var that = this; that.vertical = that._options.vertical; that._inner = that._outer = 0; if (that.vertical) { switch (_normalizeEnum(that._options.horizontalOrientation)) { case "left": that._inner = 1; break; case "center": that._inner = that._outer = .5; break; default: that._outer = 1 } } else { switch (_normalizeEnum(that._options.verticalOrientation)) { case "top": that._inner = 1; break; case "center": case "middle": that._inner = that._outer = .5; break; default: that._outer = 1 } } }, _isVisible: function() { return true }, _createRange: function(range, layout) { var points, that = this, inner = that._inner, outer = that._outer, startPosition = that._translator.translate(range.start), endPosition = that._translator.translate(range.end), x = layout.x, y = layout.y, startWidth = range.startWidth, endWidth = range.endWidth; if (that.vertical) { points = [x - startWidth * inner, startPosition, x - endWidth * inner, endPosition, x + endWidth * outer, endPosition, x + startWidth * outer, startPosition] } else { points = [startPosition, y + startWidth * outer, startPosition, y - startWidth * inner, endPosition, y - endWidth * inner, endPosition, y + endWidth * outer] } return that._renderer.path(points, "area") }, measure: function(layout) { var width, result = {}; result.min = result.max = layout[this.vertical ? "x" : "y"]; width = this._options.width; width = _Number(width) || _max(_Number(width.start), _Number(width.end)); result.min -= this._inner * width; result.max += this._outer * width; return result } }); module.exports = LinearRangeContainer;
var path = require('path'); var inflection = require('./inflection'); var lpad = require('./util').lpad; var Class = require('./class'); var internals = {}; function formatPath(dir, name) { return path.join(dir, name); } function formatName(title, date) { return formatDate(date) + '-' + formatTitle(title); } function formatDate(date) { return [ date.getUTCFullYear(), lpad(date.getUTCMonth() + 1, '0', 2), lpad(date.getUTCDate(), '0', 2), lpad(date.getUTCHours(), '0', 2), lpad(date.getUTCMinutes(), '0', 2), lpad(date.getUTCSeconds(), '0', 2) ].join(''); } function formatTitle(title) { return inflection.dasherize(title); } function parseDate(name) { var date = new Date(); var match = name.match(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})-[^\.]+/); date.setUTCFullYear(match[1]); date.setUTCDate(match[3]); date.setUTCMonth(match[2] - 1); date.setUTCHours(match[4]); date.setUTCMinutes(match[5]); date.setUTCSeconds(match[6]); return date; } function parseTitle(name) { var match = name.match(/\d{14}-([^\.]+)/); var dashed = match[1]; return inflection.humanize(dashed, true); } var Skeleton = Class.extend({ init: function(intern) { internals = intern; }, _up: function() { return require(this.path).up.apply(this, arguments); }, _down: function() { return require(this.path).down.apply(this, arguments); }, up: function(db, callback) { this._up(db, callback); }, down: function(db, callback) { this._down(db, callback); }, setup: function() { return require(this.path).setup; }, parseName: function(path) { var match = path.match(/(\d{14}-[^.]+)(?:\.*?)?/); return match[1]; }, parseTitle: parseTitle, parseDate: parseDate, formatTitle: formatTitle, formatPath: formatPath, formatName: formatName }); module.exports = Skeleton;
define(["require", "exports", "../Util", "../Factory", "../Shape", "../Validators", "../Global"], function (require, exports, Util_1, Factory_1, Shape_1, Validators_1, Global_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RegularPolygon = void 0; /** * RegularPolygon constructor. Examples include triangles, squares, pentagons, hexagons, etc. * @constructor * @memberof Konva * @augments Konva.Shape * @param {Object} config * @param {Number} config.sides * @param {Number} config.radius * @@shapeParams * @@nodeParams * @example * var hexagon = new Konva.RegularPolygon({ * x: 100, * y: 200, * sides: 6, * radius: 70, * fill: 'red', * stroke: 'black', * strokeWidth: 4 * }); */ class RegularPolygon extends Shape_1.Shape { _sceneFunc(context) { const points = this._getPoints(); context.beginPath(); context.moveTo(points[0].x, points[0].y); for (var n = 1; n < points.length; n++) { context.lineTo(points[n].x, points[n].y); } context.closePath(); context.fillStrokeShape(this); } _getPoints() { const sides = this.attrs.sides; const radius = this.attrs.radius || 0; const points = []; for (var n = 0; n < sides; n++) { points.push({ x: radius * Math.sin((n * 2 * Math.PI) / sides), y: -1 * radius * Math.cos((n * 2 * Math.PI) / sides), }); } return points; } getSelfRect() { const points = this._getPoints(); var minX = points[0].x; var maxX = points[0].y; var minY = points[0].x; var maxY = points[0].y; points.forEach((point) => { minX = Math.min(minX, point.x); maxX = Math.max(maxX, point.x); minY = Math.min(minY, point.y); maxY = Math.max(maxY, point.y); }); return { x: minX, y: minY, width: maxX - minX, height: maxY - minY, }; } getWidth() { return this.radius() * 2; } getHeight() { return this.radius() * 2; } setWidth(width) { this.radius(width / 2); } setHeight(height) { this.radius(height / 2); } } exports.RegularPolygon = RegularPolygon; RegularPolygon.prototype.className = 'RegularPolygon'; RegularPolygon.prototype._centroid = true; RegularPolygon.prototype._attrsAffectingSize = ['radius']; Global_1._registerNode(RegularPolygon); /** * get/set radius * @method * @name Konva.RegularPolygon#radius * @param {Number} radius * @returns {Number} * @example * // get radius * var radius = shape.radius(); * * // set radius * shape.radius(10); */ Factory_1.Factory.addGetterSetter(RegularPolygon, 'radius', 0, Validators_1.getNumberValidator()); /** * get/set sides * @method * @name Konva.RegularPolygon#sides * @param {Number} sides * @returns {Number} * @example * // get sides * var sides = shape.sides(); * * // set sides * shape.sides(10); */ Factory_1.Factory.addGetterSetter(RegularPolygon, 'sides', 0, Validators_1.getNumberValidator()); Util_1.Collection.mapMethods(RegularPolygon); });
var test = require('tape'); var bodies = require('../lib/bodies'); test('bodies basic crud methods', function (t) { t.plan(6); t.ok(Array.isArray(bodies.getBodies()), 'getBodies returns an array'); t.deepEqual(bodies.getBodies(), [], 'bodies starts off with no bodies'); var b1 = bodies.createBody({}); var b2 = bodies.createBody({}); var b3 = bodies.createBody({}); t.equal(bodies.getBodies().length, 3, 'createBody method add one body'); var removed = bodies.removeBody(b2); t.equal(removed, b2, 'removeBody method returns the removed body'); t.deepEqual(bodies.getBodies(), [b1, b3], 'removeBody method removes bodies'); t.deepEqual(bodies.resetBodies(), [], 'resetBodies deletes all bodies'); }); test('removeBody method', function (t) { var randomObj = {}; t.plan(1); t.throws(function () { bodies.removeBody(randomObj); }, /can only remove bodies/i, 'throws when trying to remove non bodies'); });
if (!window['YT']) { var YT = { loading:0, loaded: 0 }; } if (!window['YTConfig']) { var YTConfig = { 'host': 'http://www.youtube.com' }; } if (!YT.loading) { YT.loading = 1; (function() { var l = []; YT.ready = function(f) { if (YT.loaded) { f(); } else { l.push(f); } }; window.onYTReady = function() { YT.loaded = 1; for (var i=0; i < l.length; i++) { try { l[i](); } catch (e) { } } }; YT.setConfig = function(c) { for (var k in c) { if (c.hasOwnProperty(k)) { YTConfig[k] = c[k]; } } }; var a = document.createElement('script'); a.src = 'https:' + '//s.ytimg.com/yts/jsbin/www-widgetapi-vflBy1d5C/www-widgetapi.js'; var b = document.getElementsByTagName('script')[0]; b.parentNode.insertBefore(a, b); })(); }
System.register([],function(exports,module){'use strict';return{execute:function(){exports({x:x,missingFn:dep.missingFn,missingExport:dep.missingFn});var _missingExportShim=void 0;function x () { sideEffect(); }}}});
/** * Copyright © 2016-present Giddy. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* eslint-disable no-restricted-syntax, no-await-in-loop */ const faker = require('faker'); module.exports.seed = async db => { // Create 10 random website users (as an example) const users = Array.from({ length: 10 }).map(() => ({ display_name: faker.name.findName(), image_url: faker.internet.avatar(), })); await Promise.all( users.map(user => db .table('users') .insert(user) .returning('id') .then(rows => db .table('users') .where('id', '=', rows[0]) .first() .then(u => db .table('emails') .insert({ user_id: u.id, email: faker.internet.email().toLowerCase(), }) .then(() => u), ), ) .then(row => Object.assign(user, row)), ), ); // Create 500 stories const stories = Array.from({ length: 500 }).map(() => Object.assign( { author_id: users[faker.random.number({ min: 0, max: users.length - 1 })].id, title: faker.lorem .sentence(faker.random.number({ min: 4, max: 7 })) .slice(0, -1) .substr(0, 80), }, Math.random() > 0.3 ? { text: faker.lorem.text() } : { url: faker.internet.url() }, (date => ({ created_at: date, updated_at: date }))(faker.date.past()), ), ); await Promise.all( stories.map(story => db .table('stories') .insert(story) .returning('id') .then(rows => db .table('stories') .where('id', '=', rows[0]) .first(), ) .then(row => Object.assign(story, row)), ), ); // Create some user comments const comments = Array.from({ length: 2000 }).map(() => Object.assign( { story_id: stories[faker.random.number({ min: 0, max: stories.length - 1 })].id, author_id: users[faker.random.number({ min: 0, max: users.length - 1 })].id, text: faker.lorem.sentences(faker.random.number({ min: 1, max: 10 })), }, (date => ({ created_at: date, updated_at: date }))(faker.date.past()), ), ); await Promise.all( comments.map(comment => db .table('comments') .insert(comment) .returning('id') .then(rows => db .table('comments') .where('id', '=', rows[0]) .first(), ) .then(row => Object.assign(comment, row)), ), ); };
#!/usr/bin/env node var path = require('path') var fs = require('fs') var constants = require('@tradle/constants') var utils = require('@tradle/utils') var ChainedObj = require('./') var Builder = ChainedObj.Builder var filePath = process.argv[2] var obj = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), filePath))) if (!obj[constants.NONCE]) { throw new Error('object is missing nonce') } Builder() .data(obj) .build(function (err, result) { if (err) throw err utils.getStorageKeyFor(result.form, function (err, rootHash) { console.log(err || rootHash.toString('hex')) }) })
require('babel-polyfill'); // Webpack config for creating the production bundle. var path = require('path'); var webpack = require('webpack'); var CleanPlugin = require('clean-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var strip = require('strip-loader'); var projectRootPath = path.resolve(__dirname, '../'); var assetsPath = path.resolve(projectRootPath, './static/dist'); // https://github.com/halt-hammerzeit/webpack-isomorphic-tools var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin'); var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools')); module.exports = { devtool: 'source-map', context: path.resolve(__dirname, '..'), entry: { 'main': [ './src/client.js' ] }, output: { path: assetsPath, filename: '[name]-[chunkhash].js', chunkFilename: '[name]-[chunkhash].js', publicPath: '/dist/' }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: [strip.loader('debug'), 'babel']}, { test: /\.json$/, loader: 'json-loader' }, { test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css?importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap=true&sourceMapContents=true') }, { test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css?importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true') }, { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" }, { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" }, { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" }, { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" }, { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" }, { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' } ] }, progress: true, resolve: { modulesDirectories: [ 'src', 'node_modules' ], extensions: ['', '.json', '.js', '.jsx'] }, plugins: [ new CleanPlugin([assetsPath], { root: projectRootPath }), // css files from the extract-text-plugin loader new ExtractTextPlugin('[name]-[chunkhash].css', {allChunks: true}), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' }, __CLIENT__: true, __SERVER__: false, __DEVELOPMENT__: false, __DEVTOOLS__: false }), // ignore dev config new webpack.IgnorePlugin(/\.\/dev/, /\/config$/), // optimizations new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), webpackIsomorphicToolsPlugin ] };
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), cssmin: { options: { shorthandCompacting: false, roundingPrecision: -1 }, target: { files: { 'css/main.css': ['node_modules/bootstrap/dist/css/bootstrap.css', 'node_modules/bootstrap/dist/css/bootstrap-theme.css', 'css/screen.css'] } } }, copy: { main: { files: [ // includes files within path { expand: true, src: ['node_modules/angular/angular.js','node_modules/bootstrap/dist/js/bootstrap.min.js'], dest: 'js/', filter: 'isFile', flatten: true }, ], }, }, watch: { scripts: { files: ['css/*.css'], tasks: ['cssmin'], options: { spawn: false, }, }, }, }); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-watch'); // Default task(s). grunt.registerTask('default', ['cssmin', 'copy', 'watch']); };
// import Searchbar from '../index'; import expect from 'expect'; // import { shallow } from 'enzyme'; // import React from 'react'; describe('<Searchbar />', () => { it('Expect to have unit tests specified', () => { expect(true).toEqual(false); }); });
;(() => { /* DOM Section variables */ const app = document.querySelector('#app') const headerSection = document.querySelector('header') const jumboSection = document.querySelector('#jumbo') const aboutSection = document.querySelector('#about') const portfolioSection = document.querySelector('#projects') const contactSection = document.querySelector('#contact') const footerSection = app.lastElementChild /* Turn data keys into variables */ const nav = data.nav const jumbo = data.jumbo const about = data.about const portfolio = data.portfolio2 const contact = data.contact const social = data.social /* Functions */ const createLinkLI = (linkTxt, link) => { const a = document.createElement('a') const li = document.createElement('li') li.innerHTML = linkTxt a.href = link a.appendChild(li) return a } /* Header section */ const title = createLinkLI(nav.title.text, nav.title.link) title.classList.add('title') headerSection.firstElementChild.appendChild(title) const navButton = document.createElement('p') navButton.innerHTML = `&#9776;` navButton.classList.add('navButton') headerSection.firstElementChild.appendChild(navButton) const headerList = document.createElement('ul') headerList.classList.add('headerList') navButton.addEventListener('click', () => { headerList.classList.toggle('active') }) const headerLinks = nav.navLinks headerLinks.forEach((link) => { const li = createLinkLI(link.name, link.url) li.addEventListener('click', () => { headerList.classList.toggle('active') }) headerList.appendChild(li) }) headerSection.firstElementChild.appendChild(headerList) /* Jumbotron section */ jumboSection.style.backgroundImage = `linear-gradient( rgba(0, 0, 0, .8), rgba(255, 255, 255, .4)), url(` + data.jumbo.img + `)` const jumboContentContainer = document.createElement('div') jumboContentContainer.classList.add('jumboContentContainer') const jumboText = document.createElement('h1') jumboText.textContent = jumbo.text jumboContentContainer.appendChild(jumboText) const jumboButton = document.createElement('a') jumboButton.textContent = jumbo.buttonText jumboButton.href = jumbo.buttonLink jumboContentContainer.appendChild(jumboButton) jumboSection.appendChild(jumboContentContainer) const scrollDown = document.createElement('a') scrollDown.href = jumbo.scrollDownLink scrollDown.classList.add('scrollDown') scrollDown.innerHTML = '<i class="fa fa-angle-down fa-2x" aria-hidden="true"></i>' jumboSection.appendChild(scrollDown) /* About section */ const aboutImg = document.createElement('img') aboutImg.src = about.img aboutSection.firstElementChild.firstElementChild.appendChild(aboutImg) const aboutTxt = document.createElement('p') aboutTxt.textContent = about.aboutText aboutSection.firstElementChild.lastElementChild.appendChild(aboutTxt) /* Portfolio Section */ portfolioSection.style.background = `url(` + portfolio.backgroundImg + `) center center fixed` portfolio.projects.forEach((project) => { const projContainer = document.createElement('div') const proj = document.createElement('div') const imgLink = document.createElement('a') proj.style.background = 'url(' + project.img + ') no-repeat center' proj.style.transition = 'all 0.2s ease' projContainer.classList.add('col-md-4', 'col-sm-6', 'projContainer') proj.style.backgroundSize = 'cover' imgLink.textContent = project.title imgLink.href = project.link imgLink.target = '_blank' $(imgLink).hover( () => { imgLink.parentElement.style.transform = 'scale(1.1)' }, () => { imgLink.parentElement.style.transform = 'scale(1)' } ) proj.appendChild(imgLink) projContainer.appendChild(proj) portfolioSection.firstElementChild.children[1].appendChild(projContainer) }) /* Contact Section */ /* Footer Section */ const year = new Date().getFullYear() let footerCopyright = document.createElement('p') footerCopyright.textContent = `Handmade by me © ${year}.` footerSection.firstElementChild.appendChild(footerCopyright) social.forEach((socialAccount) => { const socialLink = document.createElement('a') if (socialAccount.fontAwesome === true) { const faIcon = '<i class="fa fa-' + socialAccount.name + ' fa-2x" aria-hidden="true"></i>' socialLink.innerHTML = faIcon } else if (socialAccount.img !== '') { const iconImg = '<img src="' + socialAccount.img + '">' socialLink.innerHTML = iconImg } else { socialLink.textContent = socialAccount.name } socialLink.href = socialAccount.fullLink socialLink.target = '_blank' footerSection.lastElementChild.appendChild(socialLink) }) })()
module.exports = LazyArgument; // A LazyArgument is a declaration to override the given dependency id // with an argument specified at the time the lazy resolution function is called. function LazyArgument(dependencyId) { this.dependencyId = dependencyId; }
({ set if(a) { a } })
/*TMODJS:{"version":1,"md5":"6e6d75cb3c907cb3075417ce004b1665"}*/ template('wx/mallcontent',function($data,$filename /**/) { 'use strict';var $utils=this,$helpers=$utils.$helpers,$each=$utils.$each,content=$data.content,value=$data.value,index=$data.index,$escape=$utils.$escape,value2=$data.value2,index2=$data.index2,value3=$data.value3,index3=$data.index3,$out='';$out+='<nav id="mallScrollspy" class="col-xs-3 mallsidebar" style = "padding: 0"> <ul id="mallNav" class="nav"> '; $each(content._subtype1,function(value,index){ $out+=' '; if(index == 0){ $out+=' <li class="active"><a href="#gt_'; $out+=$escape(index); $out+='">'; $out+=$escape(value); $out+='</a> '; }else{ $out+=' <li><a href="#gt_'; $out+=$escape(index); $out+='">'; $out+=$escape(value); $out+='</a> '; } $out+=' <ul class="nav"> '; $each(content._subtype2[index],function(value2,index2){ $out+=' '; if((index == 0 && index2 == 0)){ $out+=' <li class="active"><a href="#gt_'; $out+=$escape(index); $out+='_'; $out+=$escape(index2); $out+='">'; $out+=$escape(value2); $out+='</a></li> '; }else{ $out+=' <li><a href="#gt_'; $out+=$escape(index); $out+='_'; $out+=$escape(index2); $out+='">'; $out+=$escape(value2); $out+='</a></li> '; } $out+=' '; }); $out+=' </ul> </li> '; }); $out+=' </ul> </nav> <div id = "mallgoodscontainer" class="col-xs-9"> '; $each(content._subtype1,function(value,index){ $out+=' <div id="gt_'; $out+=$escape(index); $out+='"> '; $each(content._subtype2[index],function(value2,index2){ $out+=' <div id="gt_'; $out+=$escape(index); $out+='_'; $out+=$escape(index2); $out+='" class = "mallgoodsindex"> '; $each(content.__goods[index][index2],function(value3,index3){ $out+=' <div class = "container"> <div id = "mlg_'; $out+=$escape(value3.productCode); $out+='" class="mallgoodsinfo row"> <div class="col-xs-4" style="padding-left: 2px;padding-right: 2px;"> <img class = "img-responsive" src = "'; $out+=$escape(value3.productIntroUri); $out+='" style="width: 90px; height: 90px;min-width: 90px;min-height: 90px"> </div> <div class="col-xs-8 container"> <div class="row"> <div class="col-xs-12" style = "height: 62px; padding-right: 1px; overflow: hidden;"> <div> '; if(value3.isPromotions){ $out+=' <span style="font-size: 10px; background-color: #007431; color: #ffffff;font-weight: bolder" class="badge">促销</span> '; }else if(!value3.isPromotions && value3.oldProductPrice != value3.productPrice){ $out+=' <span style="font-size: 10px; background-color: #FF5353; color: #ffffff;" class="badge">特价</span> '; } $out+=' <span style="font-size: 16px; font-weight: bolder;">'; $out+=$escape(value3.productName); $out+='</span> '; if(value3.isPromotions){ $out+=' <span style="font-size: 10px; background-color: #FF5353; color: #ffffff;" class="badge">买就送</span> '; } $out+=' </div> <div> <span style="font-size: 12px; color:#444444;">'; $out+=$escape(value3.productUnit); $out+='</span> </div> </div> <div class="col-xs-9" style = "height: 30px; padding-right: 1px"> <div style="overflow: hidden; height: 36px"> <span class = "mallgoodsprice" style="font-size: 18px;color: #FF3F00">¥'; $out+=$escape(value3.productPrice); $out+='</span> <span style="font-size: 12px;text-decoration:line-through;color: gray">¥'; $out+=$escape(value3.oldProductPrice); $out+='</span> </div> </div> <div class="col-xs-3 malladdgoods" style="color: #007e3b; padding-left: 2px;padding-right: 2px; height: 30px;"> <span style="font-size: 24px" class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> </div> </div> </div> </div> </div> '; }); $out+=' </div> '; }); $out+=' </div> '; }); $out+=' </div> '; return new String($out); });
var test = require('tape'); var Provider = require('../lib'); test('correct types exported', function (t) { t.equal(typeof Provider, 'function'); t.equal(typeof Provider.prototype.mail, 'function'); t.end(); }); test('correct types after initialization', function (t) { var provider = new Provider(); t.assert(provider instanceof Provider); t.equal(typeof provider.mail, 'function'); t.end(); }); test('api port is chosen correctly', function (t) { var prov1 = new Provider(); var prov2 = new Provider({ apiSecure: false }); var prov3 = new Provider({ apiSecure: true }); t.assert(prov1._ses); t.assert(prov2._ses); t.assert(prov3._ses); t.end(); }); test('empty options doesn\'t cause exception', function (t) { t.doesNotThrow(function () { new Provider({}); }); t.end(); }); test('invalid message returns error', function (t) { var provider = new Provider(); t.plan(3); provider.mail(null, function (error) { t.equal(error.message, 'Invalid parameters'); }); provider.mail({}, function (error) { t.equal(error.message, 'Invalid parameters'); }); provider.mail({to:['']}, function (error) { t.equal(error.message, 'Invalid parameters'); }); });
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdLocation(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M24 4c7.73 0 14 6.27 14 14 0 10.5-14 26-14 26S10 28.5 10 18c0-7.73 6.27-14 14-14zm0 19c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5z" /> </IconBase> ); } export default MdLocation;
function Person (name, age) { this.name = name; this.age = age; } var family = []; var people = {alice:40, bob:42, michelle:8, timmy:6}; var keys = Object.keys(people); for (var i = 0; i < keys.length; i++) { family.push(new Person(keys[i], people[keys[i]])); } console.log(family); console.log(keys); document.write(JSON.stringify(family));
/*jslint node: true */ 'use strict'; var noop = function () {}; var toStr = Object.prototype.toString; function isNotFunction (func) { return !func || toStr.call (func) !== '[object Function]'; } var throwError = { doubleContinue: function (loopName) { throw new Error ('An async for loop called _continue twice during the same iteration. ' + 'Be sure the loop ' + (loopName || "") + ' calls "return void _continue() rather than just _continue().'); }, continuedAfterBreak: function (loopName) { throw new Error ( 'An async for loop continued iterating after _break was called. ' + 'Be sure the loop ' + (loopName || "") + ' calls "return void _break()" rather than just "_break()"'); }, forgotCallback: function (loopName) { throw new Error ('Called ' + (loopName || 'an async for loop ') + 'with no callback. Use "' + (loopName || 'loop') + '.fireAndForget()" instead of "' + (loopName || 'loop') + '()" if this is desired behaviour.'); }, calledBreakAndContinue: function (loopName) { throw new Error ( 'Called both break and continue during an async for loop. Be sure the loop ' + (loopName || "") + ' calls "return void _break()" or "return void continue()" rather than just "break()" or "continue()".'); } }; function getLoopInstance (initial, test, increment, func, enableExceptions, syncMode) { function makeLoopState () { return { count: initial, iteration: 0, broke: false, lastContinueIteration: -1 }; } function makeContinue (state) { var called = false; return function _continue () { if (enableExceptions && called) throwError.doubleContinue (state.name); called = true; state.lastContinueIteration = state.iteration; state.count = increment (state.count); if (syncMode) return void runIterator (state); setImmediate (runIterator, state); }; } function makeBreak (state) { return function _break () { if (enableExceptions && state.broke) throwError.continuedAfterBreak (state.name); if (enableExceptions && state.lastContinueIteration === state.iteration) throwError.calledBreakAndContinue (state.name); state.broke = true; if (state.callback) state.callback.apply (null, arguments); }; } function makeInitialIterator (name, fireAndForget) { var initial = function initialIterator (data, cb) { var state = makeLoopState (); //Called with just callback, no data if (!cb) { cb = data; } else { state.data = data; } if (!fireAndForget && enableExceptions && isNotFunction (cb)) throwError.forgotCallback (name); state.callback = cb; state.name = name; runIterator (state); }; if (!fireAndForget) initial.fireAndForget = makeInitialIterator (name, true); initial.setName = function setLoopName (loopName) { return makeInitialIterator (loopName); }; return initial; } function runIterator (state) { if (enableExceptions && state.broke) throwError.continuedAfterBreak (state.name); state.iteration++; if (!test (state.count)) { return makeBreak (state)(); } func (state.count, makeBreak (state), makeContinue (state), state.data); } return makeInitialIterator (); } var defaultIncrement = function (count) { return count + 1; }; function makeAsyncFor (enableExceptions, syncMode) { return function (initial, test, increment, func) { if (!func) { //we got (maxCount, func) var max = initial; var defaultTest = function (count) { return count < max; }; return getLoopInstance (0, defaultTest, defaultIncrement, test, enableExceptions, syncMode); } return getLoopInstance (initial, test, increment, func, enableExceptions, syncMode); }; } var _for = makeAsyncFor (true); _for.unsafe = makeAsyncFor (false); _for.sync = makeAsyncFor (true, true); _for.unsafeSync = makeAsyncFor (false, true); module.exports = _for;
const mongoose = require('mongoose'); // define the schema for our user model const subscriberSchema = mongoose.Schema({ relatedUserId: String, email: String, firstName: String, lastName: String, dateRegistred: String }); // create the model for users and expose it to our app module.exports = mongoose.model('Subscriber', subscriberSchema);
angular.module('app.site', ['site-admin']);
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import cn from 'classnames'; import OvertimeBlock from '../../TimeAndSalary/common/OvertimeBlock'; import WorkingHourTable from './WorkingHourTable'; import styles from '../../TimeAndSalary/common/WorkingHourBlock.module.css'; class WorkingHourBlock extends Component { static propTypes = { data: PropTypes.array, statistics: PropTypes.object, pageType: PropTypes.string, pageName: PropTypes.string, hideContent: PropTypes.bool.isRequired, }; renderBlockContent = () => { const { data, hideContent, statistics, pageType } = this.props; return ( <div> <div className={styles.overtimeBlock}> <div className={styles.overtimeBlockInner}> <OvertimeBlock type="salary" heading="加班有無加班費" statistics={statistics} /> <OvertimeBlock type="dayoff" heading="加班有無補休" statistics={statistics} /> </div> <div className={styles.overtimeBlockUnit}>單位:資料筆數</div> </div> <WorkingHourTable data={data} hideContent={hideContent} pageType={pageType} /> </div> ); }; render() { return ( <section className={styles.container}> <div className={cn(styles.content, styles.expanded)}> {this.renderBlockContent()} </div> </section> ); } } export default WorkingHourBlock;
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Profesore Schema */ var ProfesoreSchema = new Schema({ name: { type: String, default: '', required: 'Please fill Nombre', trim: true }, apellido1: { type: String, default: '', required: 'Please fill Apellido 1', trim: true }, apellido2: { type: String, default: '', required: 'Please fill Apellido 2', trim: true }, created: { type: Date, default: Date.now }, alumno: { type: Schema.ObjectId, ref: 'Alumno' } }); mongoose.model('Profesore', ProfesoreSchema);
var Layers = require('navigator'); module.exports = { run(em, sender) { if (!this.toAppend) { var collection = em.DomComponents.getComponent().get('components'); var config = em.getConfig(); var pfx = config.stylePrefix; var panels = em.Panels; var lyStylePfx = config.layers.stylePrefix || 'nv-'; config.layers.stylePrefix = config.stylePrefix + lyStylePfx; config.layers.pStylePrefix = config.stylePrefix; config.layers.em = em.editor; config.layers.opened = em.editor.get('opened'); // Check if panel exists otherwise crate it if(!panels.getPanel('views-container')) this.panel = panels.addPanel({id: 'views-container'}); else this.panel = panels.getPanel('views-container'); const toAppend = $(`<div class="${pfx}layers"></div>`); this.panel.set('appendContent', toAppend).trigger('change:appendContent'); config.layers.sortContainer = toAppend.get(0); const layers = new Layers().init(collection, config.layers); this.$layers = layers.render(); toAppend.append(this.$layers); this.toAppend = toAppend; } this.toAppend.show(); }, stop() { this.toAppend && this.toAppend.hide(); } };
if (typeof define !== 'function') { var define = require('amdefine')(module) } define( function(require,exports,module){ /* #Ethersheet Container View Container template for all other ethersheet views. */ var $ = require('jquery'); var t = require('../templates'); var RefBinder = require('ref-binder'); var View = require('backbone').View; var EthersheetContainer = module.exports = View.extend({ initialize: function(o){ this.$expression = null; this.$table = null; this.$grid = null; this.is_rendered = false; this.models = new RefBinder(this); this.data = o.data; this.models.set('sheets', o.data.sheets); $(window).resize(this.resize.bind(this)); }, events: { 'click #es-modal-close': 'closeModal', 'click .es-sidebar-toggle': 'toggleSidebar', }, render: function(){ var title = this.models.get('sheets').id; $(this.el).html(t.es_container({title: title})); this.$expression = $("#es-expression-editor-container",this.$el); this.$table = $("#es-table-container",this.$el); this.$menu = $("#es-menu-container",this.$el); this.$panel_0 = $("#es-panel-0", this.$el); this.$panel_1 = $("#es-panel-1", this.$el); this.is_rendered = true; this.resize(); return this; }, resize: function(){ if(!this.is_rendered) return; /*var table_height = this.$el.innerHeight() - 118;//(70 + 48(table-function-menu)) this.$table.height(table_height);*/ }, closeModal: function(){ $("#es-modal-overlay").hide() }, toggleSidebar: function(e){ var speed = 400; var $el = $(e.currentTarget); if($el.hasClass('active')){ //close the panel $el.removeClass('active'); this.$menu.animate({'right':'258px'},speed); this.$panel_0.animate({'width':'0'},speed, 'swing', function(){ $("#es-panel-0").hide(); $('menu-container').hide(); }); $('#es-panel-1').animate({'margin-left':'10px'},speed); }else{ $('.es-sidebar-toggle').removeClass('active'); $el.addClass('active'); this.$panel_0.show(); $('.menu-container').hide(); var container = $el.attr('id').replace('icon', 'menu-container'); $("#" + container).show(); if(this.$panel_0.width() <= 0){ this.$menu.animate({'right':'0px'},speed); this.$panel_0.animate({'width':'258px'},speed); this.$panel_1.animate({'margin-left':'255px'},speed); } } } }); });
const temp = require('temp') const fs = require('fs') const path = require('path') const childProcess = require('child_process') const GitHubApi = require('github') const {GitProcess} = require('dugite') const request = require('request') const rootPackageJson = require('../package.json') if (!process.env.ELECTRON_NPM_OTP) { console.error('Please set ELECTRON_NPM_OTP') process.exit(1) } const github = new GitHubApi({ // debug: true, headers: { 'User-Agent': 'electron-npm-publisher' }, followRedirects: false }) let tempDir temp.track() // track and cleanup files at exit const files = [ 'cli.js', 'index.js', 'install.js', 'package.json', 'README.md', 'LICENSE' ] const jsonFields = [ 'name', 'version', 'repository', 'description', 'license', 'author', 'keywords' ] let npmTag = '' new Promise((resolve, reject) => { temp.mkdir('electron-npm', (err, dirPath) => { if (err) { reject(err) } else { resolve(dirPath) } }) }) .then((dirPath) => { tempDir = dirPath // copy files from `/npm` to temp directory files.forEach((name) => { const noThirdSegment = name === 'README.md' || name === 'LICENSE' fs.writeFileSync( path.join(tempDir, name), fs.readFileSync(path.join(__dirname, '..', noThirdSegment ? '' : 'npm', name)) ) }) // copy from root package.json to temp/package.json const packageJson = require(path.join(tempDir, 'package.json')) jsonFields.forEach((fieldName) => { packageJson[fieldName] = rootPackageJson[fieldName] }) fs.writeFileSync( path.join(tempDir, 'package.json'), JSON.stringify(packageJson, null, 2) ) return github.repos.getReleases({ owner: 'electron', repo: rootPackageJson.version.indexOf('nightly') > 0 ? 'nightlies' : 'electron' }) }) .then((releases) => { // download electron.d.ts from release const release = releases.data.find( (release) => release.tag_name === `v${rootPackageJson.version}` ) if (!release) { throw new Error(`cannot find release with tag v${rootPackageJson.version}`) } return release }) .then((release) => { const tsdAsset = release.assets.find((asset) => asset.name === 'electron.d.ts') if (!tsdAsset) { throw new Error(`cannot find electron.d.ts from v${rootPackageJson.version} release assets`) } return new Promise((resolve, reject) => { request.get({ url: tsdAsset.url, headers: { 'accept': 'application/octet-stream', 'user-agent': 'electron-npm-publisher' } }, (err, response, body) => { if (err || response.statusCode !== 200) { reject(err || new Error('Cannot download electron.d.ts')) } else { fs.writeFileSync(path.join(tempDir, 'electron.d.ts'), body) resolve(release) } }) }) }) .then(async (release) => { if (release.tag_name.indexOf('nightly') > 0) { const currentBranch = await getCurrentBranch() if (currentBranch === 'master') { npmTag = 'nightly' } else { npmTag = `nightly-${currentBranch}` } } else { npmTag = release.prerelease ? 'beta' : 'latest' } }) .then(() => childProcess.execSync('npm pack', { cwd: tempDir })) .then(() => { // test that the package can install electron prebuilt from github release const tarballPath = path.join(tempDir, `${rootPackageJson.name}-${rootPackageJson.version}.tgz`) return new Promise((resolve, reject) => { childProcess.execSync(`npm install ${tarballPath} --force --silent`, { env: Object.assign({}, process.env, { electron_config_cache: tempDir }), cwd: tempDir }) resolve(tarballPath) }) }) .then((tarballPath) => childProcess.execSync(`npm publish ${tarballPath} --tag ${npmTag} --otp=${process.env.ELECTRON_NPM_OTP}`)) .catch((err) => { console.error(`Error: ${err}`) process.exit(1) }) async function getCurrentBranch () { const gitDir = path.resolve(__dirname, '..') console.log(`Determining current git branch`) let gitArgs = ['rev-parse', '--abbrev-ref', 'HEAD'] let branchDetails = await GitProcess.exec(gitArgs, gitDir) if (branchDetails.exitCode === 0) { let currentBranch = branchDetails.stdout.trim() console.log(`Successfully determined current git branch is ` + `${currentBranch}`) return currentBranch } else { let error = GitProcess.parseError(branchDetails.stderr) console.log(`Could not get details for the current branch, error was ${branchDetails.stderr}`, error) process.exit(1) } }
function ecuatie2() { this.citeste = function(){ this.a = document.getElementById("a").value; this.b = document.getElementById("b").value; this.c = document.getElementById("c").value; }; //----------------------------------- this.calculeaza = function(){ var delta = this.b * this.b - 4 * this.a * this.c; if (delta >= 0){ this.x1 = {re:(-this.b + Math.sqrt(delta)) / (2 * this.a), im:0} this.x2 = {re:(-this.b - Math.sqrt(delta)) / (2 * this.a), im:0}; } else{ this.x1 = {re:-this.b / (2 * this.a), im: Math.sqrt(-this.delta) / (2 * this.a)}; this.x2 = {re:-this.b / (2 * this.a), im:-Math.sqrt(-this.delta) / (2 * this.a)}; } }; //----------------------------------- this.afiseaza = function(){ document.getElementById("x1").innerHTML = this.x1.re + "+" + this.x1.im + "i"; document.getElementById("x2").innerHTML = this.x2.re + "+" + this.x2.im + "i"; }; //----------------------------------- } //------------------------------------- function rezolva() { var e = new ecuatie2(); e.citeste(); e.calculeaza(); e.afiseaza(); } //-------------------------------------
//global.iflicks_settings = require('./settings'); global.iflicks_settings = require ('./.testSettings'); require('./lib/nedb.js'); require('./lib/sqlserver.js'); module.exports = function (grunt) { grunt.initConfig({ concurrent: { //compress: ['less', 'concat', 'uglify'], start: { tasks: ['mochaTest', 'watch'], options: { logConcurrentOutput: true } } }, mochaTest: { test: { options: { reporter: 'spec' }, src: ['test/**/*.js'] } }, jshint: { // define the files to lint files: ['public/js/index.js'], // configure JSHint (documented at http://www.jshint.com/docs/) options: { // more options here if you want to override JSHint defaults /*globals: { jQuery: true, document: true, console: true, module: true, $: true, window: true, browser: true, setInterval: true, clearTimeout: true, setTimeout: true, location: true, strict: true }*/ } }, uglify: { my_target: { files: { 'public/js/index.min.js': ['public/js/index.js'], 'public/js/toolbox.min.js': ['public/js/toolbox.js'] } } }, cssmin: { add_banner: { options: { banner: '/* My minified css file */' }, files: { 'public/css/white.min.css': ['public/css/layout.css', 'public/css/white.css'], 'public/css/black_yellow.min.css': ['public/css/layout.css', 'public/css/black_yellow.css'], 'public/css/toolbox.min.css': ['public/css/toolbox.css'] } } }, jsdoc : { dist : { src: ['app.js', 'routes/*.js', 'models/*.js', 'lib/*.js', 'public/js/*.js', 'README.md'], options: { destination: 'doc', configure: '.jsdoc' } } }, watch: { files: ['routes/**/*.*', 'lib/**/*.*', 'views/**/*.*', '!**/dist/**' ]//, // ignore dist folder //tasks: ['concurrent:compress'] } }); // Dependencies grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-mocha-test'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-concurrent'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-jsdoc'); // Run tests grunt.registerTask('test', ['mochaTest']); // Default tasks //grunt.registerTask('default', ['concurrent:start']); grunt.registerTask('default', ['jshint', 'mochaTest', 'uglify', 'cssmin', 'jsdoc']); };
define(['test1', 'test2'], function() { let [test1, test2] = arguments; console.log(test1); console.log(test2); });
module.exports = { env: { browser: true, es6: true, jasmine: true, }, extends: ["plugin:react/recommended", "airbnb"], globals: { Atomics: "readonly", SharedArrayBuffer: "readonly" }, parser: "@typescript-eslint/parser", parserOptions: { ecmaFeatures: { jsx: true }, ecmaVersion: 2018, sourceType: "module" }, ignorePatterns: ["node_modules", "public", ".vscode"], plugins: ["react", "react-hooks", "@typescript-eslint", "jasmine"], rules: { "implicit-arrow-linebreak": ["error", "beside"], "no-unused-vars": [0, { args: 'none' }], // https://github.com/typescript-eslint/typescript-eslint/issues/46 "no-use-before-define": [0], "react/jsx-filename-extension": [1, { extensions: [".tsx"] }], "no-underscore-dangle": [0], "object-curly-spacing": [2, "never"], "import/extensions": [0], "react/destructuring-assignment": [0], "import/prefer-default-export": [0], "no-shadow": [1], "no-multiple-empty-lines": ["error", { max: 7 }], "linebreak-style": [0], "max-len": ["error", { "code": 180 }], "dot-notation": [1], "padded-blocks": [0], "object-curly-newline": ["error", { "ImportDeclaration": "never" }], "no-plusplus": [0], "react/no-children-prop": [0], "class-methods-use-this": [0], "react/jsx-props-no-spreading": [0], "arrow-parens": ["error", "as-needed"], "react/no-array-index-key": [0], "lines-between-class-members": [0], "prefer-destructuring": [0], "arrow-body-style": [0], }, "settings": { "import/resolver": { "node": { "extensions": [".js", ".ts", ".tsx"] } } }, };
Schema.Departments = new SimpleSchema({ Name: { type: String, label: 'ชื่อแผนก', max: 50, unique: true } }); Model.Departments.attachSchema(Schema.Departments);
import Ember from 'ember'; import { moduleForComponent, test } from 'ember-qunit'; import { assertTooltipNotVisible, assertTooltipVisible, triggerTooltipTargetEvent } from '../../helpers/ember-tooltips'; import hbs from 'htmlbars-inline-precompile'; const { run } = Ember; moduleForComponent('tooltip-on-element', 'Integration | Option | duration', { integration: true }); test('tooltip-on-element hides after the given duration', function(assert) { assert.expect(3); this.render(hbs`{{tooltip-on-element duration=300}}`); const done = assert.async(); const $tooltipTarget = this.$(); assertTooltipNotVisible(assert); /* Check the tooltip is hidden after the duration */ triggerTooltipTargetEvent($tooltipTarget, 'mouseenter'); assertTooltipVisible(assert); run.later(() => { assertTooltipNotVisible(assert); done(); }, 500); }); test('tooltip-on-element hides before the given duration, if requested', function(assert) { assert.expect(3); this.render(hbs`{{tooltip-on-element duration=300}}`); const $tooltipTarget = this.$(); assertTooltipNotVisible(assert); triggerTooltipTargetEvent($tooltipTarget, 'mouseenter'); assertTooltipVisible(assert); triggerTooltipTargetEvent($tooltipTarget, 'mouseleave'); assertTooltipNotVisible(assert); }); test('tooltip-on-element uses duration after the first show', function(assert) { assert.expect(5); this.render(hbs`{{tooltip-on-element duration=300}}`); const done = assert.async(); const $tooltipTarget = this.$(); assertTooltipNotVisible(assert); triggerTooltipTargetEvent($tooltipTarget, 'mouseenter'); assertTooltipVisible(assert); triggerTooltipTargetEvent($tooltipTarget, 'mouseleave'); assertTooltipNotVisible(assert); /* Check the tooltip is hidden after the duration */ triggerTooltipTargetEvent($tooltipTarget, 'mouseenter'); assertTooltipVisible(assert); run.later(() => { assertTooltipNotVisible(assert); done(); }, 500); });
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); exports.__esModule = true; exports.HomeIcon = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose")); var _react = _interopRequireDefault(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _excluded = ["color", "title"]; var HomeIcon = function HomeIcon(_ref) { var color = _ref.color, title = _ref.title, props = (0, _objectWithoutPropertiesLoose2.default)(_ref, _excluded); return /*#__PURE__*/_react.default.createElement("svg", (0, _extends2.default)({ width: "24", height: "20", viewBox: "0 0 24 20", xmlns: "http://www.w3.org/2000/svg" }, props), title && /*#__PURE__*/_react.default.createElement("title", null, title), /*#__PURE__*/_react.default.createElement("path", { d: "M17.633 9.432l2 1.636v8.224h-7v-5c0-.473-.329-.87-.77-.974l-.113-.019-.117-.007a1 1 0 00-.993.883l-.007.117v5h-7v-8.224l2-1.636v7.86h3v-3a3 3 0 012.824-2.995l.176-.005a3 3 0 012.995 2.824l.005.176v3h3v-7.86zm-6-9.432l11.633 9.518L22 11.066 11.633 2.583 1.266 11.066 0 9.518 11.633 0z", fill: color })); }; exports.HomeIcon = HomeIcon; HomeIcon.propTypes = { color: _propTypes.default.string, title: _propTypes.default.string }; HomeIcon.defaultProps = { color: '#222', title: '' };
var builder = require('nodeBundle').basicBundleBuilder(); var basic = builder.init(); function attach(){ } basic.set('attach', attach); module.exports = basic.getBundle();
var debug = require('debug')('server:models:Analysis'); var path = require('path'); var fs = require('fs'); var Promise = require('bluebird'); module.exports = { identity: 'analysis', tableName: 'analyses', connection: 'default', migrate: 'safe', attributes: { //data type: 'string', fileName: 'string', path: 'string', params: 'json', image: { model: 'image' }, //meta requesterIP: 'string' }, afterDestroy: function (deleted, next) { debug('Analysis.afterDestroy'); return Promise.map(deleted, function (analysis) { return Promise.fromNode(function (callback) { return fs.unlink(path.join(analysis.path, analysis.fileName), callback); }); }) .finally(function () { next(); }); } };
version https://git-lfs.github.com/spec/v1 oid sha256:38b3e7d3bafc4618a2bd6d6bf4d5ed2b45d4916362f9f48458ad71b2e206d97d size 5958
import { Mongo } from 'meteor/mongo'; import SimpleSchema from 'simpl-schema'; import { Tracker } from 'meteor/tracker'; /** Encapsulates state and variable values for this collection. */ class ProjectsInterestsCollection { constructor() { // The name of this collection. this.name = 'ProjectsInterestsCollection'; // Define the Mongo collection. this.collection = new Mongo.Collection(this.name); // Define the structure of each document in the collection. this.schema = new SimpleSchema({ project: String, interest: String, }, { tracker: Tracker }); // Ensure collection documents obey schema. this.collection.attachSchema(this.schema); // Define names for publications and subscriptions this.userPublicationName = `${this.name}.publication.user`; this.adminPublicationName = `${this.name}.publication.admin`; } } export const ProjectsInterests = new ProjectsInterestsCollection();
$(document).ready(function(){ $('#month_from_date').datepicker({ format: 'dd-mm-yyyy', weekStart: 1, autoclose: true }); $('#month_to_date').datepicker({ format: 'dd-mm-yyyy', weekStart: 1, autoclose: true }); $('#chbx').on('click', function(){ $("input[type='checkbox']").prop("checked", $('#chbx').prop("checked")) }); });
import SelectRadio from '../'; const {renderIntoDocument, scryRenderedDOMComponentsWithTag, Simulate} = TestUtils; const values = [ {code: 'A', label: 'Value A'}, {code: 'B', label: 'Value B'}, {code: 'C', label: 'Value C'} ]; describe('Select Radio Component', () => { describe('Rendering', () => { describe('When a default select-radio is rendered', () => { let renderedSelectRadio; before(() => { renderedSelectRadio = renderIntoDocument(<SelectRadio rawInputValue='B' values={values} />); }); it('should have its default state value equals to the props value', () => { expect(renderedSelectRadio.state.value).to.equal(renderedSelectRadio.props.rawInputValue) }); }); describe('When a radio is selected', () => { let renderedSelectRadio, arr, initalValueState; before(() => { renderedSelectRadio = renderIntoDocument(<SelectRadio rawInputValue='B' values={values} />); arr = scryRenderedDOMComponentsWithTag(renderedSelectRadio, 'input') initalValueState = renderedSelectRadio.state.value; Simulate.change(arr[2]); }); it('should change the state value', () => { expect(renderedSelectRadio.state).to.not.equal(initalValueState); }); it('should check the radio', () => { expect(arr[2].value).to.equal('true'); }); }); }); });
function getPaintOrder(element) { var divElementsBeforePromote = []; var divElementsAfterPromote = []; var paintOrderListBeforePromote = window.internals.paintOrderListBeforePromote(element); var paintOrderListAfterPromote = window.internals.paintOrderListAfterPromote(element); for (var i = 0; i < paintOrderListBeforePromote.length; ++i) if (paintOrderListBeforePromote[i].nodeName === "DIV") divElementsBeforePromote.push(paintOrderListBeforePromote[i]); for (var i = 0; i < paintOrderListAfterPromote.length; ++i) if (paintOrderListAfterPromote[i].nodeName === "DIV") divElementsAfterPromote.push(paintOrderListAfterPromote[i]); return {"beforePromote": divElementsBeforePromote, "afterPromote": divElementsAfterPromote}; } function comparePaintOrderLists(oldPaintOrder, newPaintOrder) { if (oldPaintOrder.length !== newPaintOrder.length) return false; for (var i = 0; i < oldPaintOrder.length; i++) if (oldPaintOrder[i] !== newPaintOrder[i]) return false; return true; } function countOccurrencesOfElementInPaintOrderList(paintOrder, element) { var occurrenceCount = 0; for (var i = 0; i < paintOrder.length; i++) if (paintOrder[i] === element) occurrenceCount++; return occurrenceCount; } function compareStackingOrderWithPaintOrder(stackingOrder, paintOrder) { if (debugMode) { write("paint order:") for (var i = 0; i < paintOrder.length; i++) write(paintOrder[i].id + " " + paintOrder[i].className + " " + paintOrder[paintOrder.length - i - 1].tagName); write("stacking order:") for (var i = 0; i < stackingOrder.length; i++) write(stackingOrder[i].id + " " + stackingOrder[i].className + " " + stackingOrder[i].tagName); } if (stackingOrder.length < paintOrder.length) return false; // We expect the stacking order list to contain more than the paint order // list sometimes because after we promote, the container's children won't // appear in the stacking context's ancestor's lists anymore (which is // expected and correct). They'll still be in the stacking order list. // The important part is that the order of the things present in the paint // order list is preserved in the stacking order list. for (var i = 0, j = 0; i < stackingOrder.length && j < paintOrder.length; i++) if (stackingOrder[i] === paintOrder[paintOrder.length - j - 1]) j++; if (debugMode) write(stackingOrder.length + " " + i + " " + paintOrder.length + " " + j); return j == paintOrder.length; } function testPaintOrderListPermutation(count) { if (!window.internals) return; var container = document.getElementById('container'); window.internals.setNeedsCompositedScrolling(container, window.internals.COMPOSITED_SCROLLING_ALWAYS_OFF); var oldStackingOrder = getStackingOrder(container); var oldPaintOrder = getPaintOrder(container); window.internals.setNeedsCompositedScrolling(container, window.internals.COMPOSITED_SCROLLING_ALWAYS_ON); var newStackingOrder = getStackingOrder(container); var newPaintOrder = getPaintOrder(container); window.internals.setNeedsCompositedScrolling(container, window.internals.DO_NOT_FORCE_COMPOSITED_SCROLLING); // The getPaintOrder() function should return a pair of paint orders. // One before promotion and one after. This pair of lists should remain // identical whether the element is actually currently promoted or not, // its purpose is to generate hypothetical pre- and post-lists to // determine if the element is promotable. if (!comparePaintOrderLists(oldPaintOrder, newPaintOrder)) write("iteration " + count + " FAIL - paint order lists not identical before/after promotion"); if (!compareStackingOrderWithPaintOrder(oldStackingOrder, oldPaintOrder.beforePromote)) write("iteration " + count + " FAIL - paint order list before promote doesn't match stacking order"); if (!compareStackingOrderWithPaintOrder(newStackingOrder, oldPaintOrder.afterPromote)) write("iteration " + count + " FAIL - paint order list after promote doesn't match stacking order"); var containerOccurrences = countOccurrencesOfElementInPaintOrderList(oldPaintOrder.beforePromote, container); if (containerOccurrences !== 1) write("iteration " + count + " FAIL - paint order list before promote contains " + containerOccurrences + " occurrences of container. Should be exactly 1."); containerOccurrences = countOccurrencesOfElementInPaintOrderList(oldPaintOrder.afterPromote, container); if (containerOccurrences !== 1) write("iteration " + count + " FAIL - paint order list after promote contains " + containerOccurrences + " occurrences of container. Should be exactly 1."); } function runPaintOrderPermutationSet(permutationSet) { runPermutationSet(testPaintOrderListPermutation, permutationSet); }
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.4.4.22-9-c-i-20 description: > Array.prototype.reduceRight - element to be retrieved is own accessor property without a get function that overrides an inherited accessor property on an Array includes: [runTestCase.js] ---*/ function testcase() { var testResult = false; function callbackfn(prevVal, curVal, idx, obj) { if (idx === 1) { testResult = (typeof curVal === "undefined"); } } try { Array.prototype[1] = 1; var arr = [0, ,2]; Object.defineProperty(arr, "1", { set: function () { }, configurable: true }); arr.reduceRight(callbackfn, "initialValue"); return testResult; } finally { delete Array.prototype[1]; } } runTestCase(testcase);
import { connect } from 'react-redux' import { loginStart, observeAuthenticationStart, logoutStart } from '../../actions/current-user' import { createGameStart } from '../../actions/game' import App from './index' function mapStateToProps(storeStates, ownProps) { return { currentUser: storeStates.models.currentUser } } function mapDispatchToProps(dispatch) { return { dispatchGoogleLoginStart: (isObservingAuth) => { dispatch(loginStart(isObservingAuth)) }, dispatchLogoutStart: (currentUserId) => { dispatch(logoutStart(currentUserId)) }, dispatchObserveAuthenticationStart: () => { dispatch(observeAuthenticationStart()) }, dispatchCreateGameStart: (gameName: ?string) => { dispatch(createGameStart(gameName)) } } } const connectStoreToApp: func = connect(mapStateToProps, mapDispatchToProps) const AppContainer = connectStoreToApp(App) export default AppContainer
/** * @author A;Ming * @email y2443@163.com * @site wwww.y2443.com,logs.moe * @date 2015-01-23 */ var Kcvp = function() {}; //head Kcvp.prototype.Head = function() { var obj = new Object(); obj.count = 0; obj.list = null; obj.changetime = 4000; obj.index = 0; obj.$head_bg_img = null; obj.$head_title = null; obj.$avatar = null; obj.$avatar_title = null; obj.$avatar_img = null; obj.Init = function() { obj.$head_bg_img = $(".content_frame > .head .pic"); obj.$head_title = $(".content_frame > .head .bg .title"); obj.$avatar = $(".content_frame > .head .avatar"); obj.$avatar_title = $(".content_frame > .head .avatar .img .title"); obj.$avatar_img = $(".content_frame > .head .avatar .img"); obj.GetList(); }; obj.GetList = function() { $.ajax({ url: '/data/headlist.php', type: 'GET', dataType: 'json' }).done(function(data) { if (data) { obj.list = data; obj.count = data.length; } }).always(function() { if (obj.list) { obj.Auto(); } }); }; obj.Auto = function() { obj.index++; if (obj.index >= obj.count) { obj.index = 0; } obj.ChangeHeadImage(); setTimeout(obj.Auto, obj.changetime); }; obj.GetItem = function(index) { return obj.list[index]; }; obj.ChangeHeadImage = function() { var data = obj.GetItem(obj.index); var img_left = (data.avatarLeft+14) * -1; obj.$head_bg_img.animate({ opacity: 0 }, 400, function() { obj.$head_bg_img.css("background-image", "url(" + data.img + ")"); obj.$avatar_img.css({ "background-position-x": img_left + "px" }, 800); obj.$head_bg_img.animate({ opacity: 1 }, 400); obj.$head_title.css("color", data.color); obj.$avatar_title.css("color", data.color); obj.$head_title.html(data.title); obj.$avatar_title.html(data.des); }); obj.$avatar.animate({ left: data.avatarLeft }, 800); obj.$head_title.animate({ left: data.titleLeft }, 800); }; return obj; }(); // nav Kcvp.prototype.Nav = function() { var obj = new Object(); obj.list = null; obj.changetime = 5400; obj.$win = null; obj.$main_nav = null; obj.$nav_bg = null; obj.$nav_menu = null; obj.Init = function() { obj.$win = $(window); obj.$main_nav = $(".main_nav"); obj.$nav_bg = $(".main_nav .bg"); obj.$nav_menu = $(".main_nav .menu"); obj.GetList(); obj.BindEvent(); obj.ResizeNav(); }; obj.GetList = function() { $.ajax({ url: '/data/navlist.php', type: 'GET', dataType: 'json' }).done(function(data) { if (data) { obj.list = []; $.each(data, function(index, val) { obj.list.push(val.img); }); } }).always(function() { if (obj.list) { obj.Start(); } }); }; obj.ResizeNav = function() { var left_nav_bg = (obj.$win.width() - obj.$nav_bg.width()) / 2; var left_nav_menu = (obj.$win.width() - obj.$nav_menu.width()) / 2; left_nav_menu = left_nav_menu < 0 ? 0 : left_nav_menu; obj.$nav_bg.css("margin-left", left_nav_bg + "px"); obj.$nav_menu.css("left", left_nav_menu + "px"); }; obj.BindEvent = function() { obj.$win.bind('resize', obj.ResizeNav); }; obj.Start = function() { obj.$nav_bg.css("opacity", "0.6"); obj.$main_nav.show(); obj.$nav_bg.amingslide({ imglist: obj.list, column_count: 60, rom_count: 1, change_time: obj.changetime }); }; return obj; }(); // init Kcvp.prototype.Init = function() { this.Head.Init(); this.Nav.Init(); } var kcvp = new Kcvp(); $(document).ready(function() { kcvp.Init(); $(window).aming_scrolltop({ imgurl: '/images/totop.png', showopacity: 1, mainwidth: 1050 }); $('.aming_to_top').css('-webkit-border-radius', '25px'); });
// Load the Visualization API and the piechart package. google.charts.load('current', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.charts.setOnLoadCallback(drawChart); var jsonData = $.ajax({ url: "http://localhost:8080/votweet-backend-master/metricasCandidatos/ultimasAprobacionesNacionales", dataType: "json", async: false }).responseJSON; console.log(jsonData); function procesarArray(json) { var datos = []; datos.push(['Candidato','Aprobacion'],) for (var i = 0, l = json.length; i < l; i++) { datos.push([json[i].nombreCandidato,json[i].aprobacion],); } return datos; } var datosPre = procesarArray(jsonData); function drawChart() { console.log("datosProcesados?"); console.log(datosPre); var data = google.visualization.arrayToDataTable( datosPre); var aux2=google.visualization.arrayToDataTable(datosPre); console.log(data); console.log(aux2); var options = { title: 'Detalle de Aprobación', is3D: true, pieStartAngle: 100, }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); }
export default Marionette.Object.extend({ home() { console.log('home route'); } });
angular.module('mcts.services', ['ngResource']) .factory('BusService', function($resource) { var socket = new WebSocket("ws://localhost:9999"); var listeners = []; socket.onmessage = function(e) { _.each( _.select(listeners, function(listener) { return listener.route == e.data.ROUTE_NUMBER || listener.route == "all" }), function(listener) { listener.callback(JSON.parse(e.data)); } ); } // BusService.listenTo(10, function(event) {}) // BusService.listenTo([10,15], function(event) {}) // BusService.listenTo("all", function(event) {}) return { listen: function() { var cb = arguments[arguments.length - 1]; listeners.push({ route: arguments[0], callback: cb }) }, ignore: function() { }, getSocketFor: function(route) { return new WebSocket("ws://localhost:9999",[route]) } } })
import { addons } from '@storybook/addons'; import { theme } from './theme'; addons.setConfig({ theme, panelPosition: 'right', });
var searchData= [ ['pp_5fstack',['pp_stack',['../classcpplint_1_1_nesting_state.html#a3a5ca37e3066d91830ea1faa8feae4e5',1,'cpplint::NestingState']]], ['previous_5fstack_5ftop',['previous_stack_top',['../classcpplint_1_1_nesting_state.html#a7aa34c8fb8df73d76f702c7012c46911',1,'cpplint::NestingState']]], ['pump_5f8py',['pump_8py',['../pump__8py_8js.html#a9e35fb16373682bd01b46640ceb90119',1,'pump_8py.js']]] ];
"use strict"; module.exports = { up: function(migration, DataTypes, done) { // add altering commands here, calling 'done' when finished migration.addColumn( "Images", "extension", { type: DataTypes.STRING, defaultValue: '.jpg' } ).complete(function(err) { if (err) { console.log("There was an error: ", err); } else { console.log("Finished successfully."); } done(err); }); }, down: function(migration, DataTypes, done) { // add reverting commands here, calling 'done' when finished migration.removeColumn("Images", "extension").complete(function(err) { if (err) { console.log("There was an error: ", err); } else { console.log("Finished successfully."); } done(err); }); } };
module.exports = { "rules": { "at-rule-empty-line-before": ["always", { "except": ["blockless-after-same-name-blockless", "first-nested"], "ignore": ["after-comment"] }], "at-rule-name-case": "lower", "at-rule-name-space-after": "always-single-line", "at-rule-semicolon-newline-after": "always", "block-closing-brace-empty-line-before": "never", "block-closing-brace-newline-after": "always", "block-closing-brace-newline-before": "always-multi-line", "block-closing-brace-space-before": "always-single-line", "block-no-empty": true, "block-opening-brace-newline-after": "always-multi-line", "block-opening-brace-space-after": "always-single-line", "block-opening-brace-space-before": "always", "color-hex-case": "upper", "color-hex-length": "short", "color-no-invalid-hex": true, "comment-empty-line-before": "never", "comment-no-empty": true, "comment-whitespace-inside": "always", "custom-property-empty-line-before": ["always", { "except": ["after-custom-property", "first-nested"], "ignore": ["after-comment", "inside-single-line-block"] }], "declaration-bang-space-after": "never", "declaration-bang-space-before": "always", "declaration-block-no-duplicate-properties": [true, { "ignore": ["consecutive-duplicates-with-different-values"] }], "declaration-block-no-redundant-longhand-properties": true, "declaration-block-no-shorthand-property-overrides": true, "declaration-block-semicolon-newline-after": "always-multi-line", "declaration-block-semicolon-space-after": "always-single-line", "declaration-block-semicolon-space-before": "never", "declaration-block-single-line-max-declarations": 1, "declaration-block-trailing-semicolon": "always", "declaration-colon-newline-after": "always-multi-line", "declaration-colon-space-after": "always", "declaration-colon-space-before": "never", "declaration-empty-line-before": ["always", { "except": ["after-declaration", "first-nested"], "ignore": ["after-comment", "inside-single-line-block"] }], "declaration-no-important": true, "font-family-name-quotes": "always-unless-keyword", "font-family-no-duplicate-names": true, "function-calc-no-unspaced-operator": true, "function-comma-newline-after": "always-multi-line", "function-comma-space-after": "always-single-line", "function-comma-space-before": "never", "function-linear-gradient-no-nonstandard-direction": true, "function-max-empty-lines": 0, "function-name-case": "lower", "function-parentheses-newline-inside": "always-multi-line", "function-parentheses-space-inside": "never-single-line", "function-url-quotes": "always", "function-whitespace-after": "always", "indentation": 4, "keyframe-declaration-no-important": true, "length-zero-no-unit": true, "max-empty-lines": 1, "media-feature-colon-space-after": "always", "media-feature-colon-space-before": "never", "media-feature-name-case": "lower", "media-feature-name-no-unknown": true, "media-feature-parentheses-space-inside": "never", "media-feature-range-operator-space-after": "always", "media-feature-range-operator-space-before": "always", "media-query-list-comma-newline-after": "always-multi-line", "media-query-list-comma-space-after": "always-single-line", "media-query-list-comma-space-before": "never", "no-duplicate-selectors": true, "no-empty-source": true, "no-eol-whitespace": true, "no-extra-semicolons": true, "no-invalid-double-slash-comments": true, "no-missing-end-of-source-newline": true, "number-leading-zero": "always", "number-no-trailing-zeros": true, "property-case": "lower", "property-no-unknown": true, // "rule-empty-line-before": "always-multi-line", "selector-attribute-brackets-space-inside": "never", "selector-attribute-operator-space-after": "never", "selector-attribute-operator-space-before": "never", "selector-attribute-quotes": "always", "selector-combinator-space-after": "always", "selector-combinator-space-before": "always", "selector-descendant-combinator-no-non-space": true, "selector-list-comma-space-before": "never", "selector-max-empty-lines": 0, "selector-pseudo-class-case": "lower", "selector-pseudo-class-no-unknown": true, "selector-pseudo-class-parentheses-space-inside": "never", "selector-pseudo-element-case": "lower", "selector-pseudo-element-colon-notation": "double", "selector-pseudo-element-no-unknown": true, "selector-type-case": "lower", "selector-type-no-unknown": true, "shorthand-property-no-redundant-values": true, "string-no-newline": true, "string-quotes": "double", "unit-case": "lower", "unit-no-unknown": true, "value-list-comma-newline-after": "always-multi-line", "value-list-comma-space-after": "always-single-line", "value-list-comma-space-before": "never", "value-list-max-empty-lines": 0 } }
define([ 'dojo/_base/declare', './TextBox', './_TypeaheadMixin', 'dojo/text!./Template/TextBox.html' ], function ( declare, TextBox, TypeaheadMixin, template ){ // module: // Sds/Form/Typeahead return declare( [TextBox, TypeaheadMixin], { templateString: template } ); });
// Project imports var BotPlayer = require('./minionPlayer'); var FakeSocket = require('./minionSocket'); var PacketHandler = require('../PacketHandler'); function MinionLoader(gameServer) { this.gameServer = gameServer; this.loadNames(); } module.exports = MinionLoader; // todo bad constructor name? MinionLoader.prototype.getName = function() { return this.gameServer.minionname; }; MinionLoader.prototype.loadNames = function() { this.randomNames = []; // Load names try { var fs = require("fs"); // Import the util library // Read and parse the names - filter out whitespace-only names // fs.readFileSync is only used during server start this.randomNames = fs.readFileSync("./botnames.txt", "utf8").split(/[\r\n]+/).filter(function(x) { return x != ''; // filter empty names }); } catch (e) { // Nothing, use the default names } this.nameIndex = 0; }; MinionLoader.prototype.addBot = function(owner, name) { var fakeSocket = new FakeSocket(this.gameServer); fakeSocket.playerTracker = new BotPlayer(this.gameServer, fakeSocket, owner); fakeSocket.packetHandler = new PacketHandler(this.gameServer, fakeSocket); // Add to client list this.gameServer.clients.push(fakeSocket); if (!name || typeof name == "undefined") name = "minion"; // Add to world fakeSocket.packetHandler.setNickname(name); };
export function getInfo(data) { const majorData = [ ['vendor', 'Производитель'], ['vendorcode', 'Модель'], ['country_of_origin', 'Страна происхождения'], ['weight', 'Вес'], ] const majorParams = [ 'Тип', 'Комплектация', 'Цвет', ] const info = [] const params = [] majorData.forEach((el) => { const [value, name] = el if (data[value]) info.push({ name, value: data[value] }) }) majorParams.forEach((value) => { const param = data.param.find(el => el.name === value) if (param) params.push({ name: param.name, value: param.keyValue }) }) info.unshift(...params) if (data.dimensions) { info.push({ name: 'Размеры', value: data.dimensions .split('/') .map(e => parseFloat(e)) .join(' x '), }) } return info } export function prepareFacets(data) { const facets = [...data.facets] const majorFacetsKeys = ['Страна бренда', 'Цвет', 'Год выпуска'] const majorFacets = [] majorFacetsKeys.forEach((facetKey) => { const item = facets.find(e => e.facet === facetKey) if (item) { majorFacets.push(item) facets.splice(facets.findIndex(e => e.facet === facetKey), 1) } }) const out = [...data.vendor, ...data.country, ...majorFacets, ...facets] out.reduce((prev, cur) => { if (!/\d{4}-\d{2}-\d{2}[tT]\d{2}:\d{2}:\d{2}.\d{3}[zZ]/.test(cur.facet)) prev.push(cur) return prev }, []) for (let i = 0; i < out.length; i += 1) { out[i].id = `f${i + 1}` out[i].view = (out[i].facet === 'Цвет') ? 'color' : 'standard' out[i].values = out[i].values.reduce((prev, cur) => { if (typeof cur !== 'string' || !/\d{4}-\d{2}-\d{2}[tT]\d{2}:\d{2}:\d{2}.\d{3}[zZ]/.test(cur)) { prev.push(cur) } return prev }, []) } return out } export function removeGarbage(items = []) { if (!items) return [] const out = [] items.forEach((val) => { if (!/\d{4}-\d{2}-\d{2}[tT]\d{2}:\d{2}:\d{2}.\d{3}[zZ]/.test(val)) { out.push(val) } }) return out }
import chat from 'aircheck/services/chat'; import Recording from 'aircheck/services/recording'; var App; module('Acceptances - Room', { setup: function(){ App = startApp(); //App.reset(); }, teardown: function() { Ember.run(App, 'destroy'); } }); test('room renders', 1, function(){ this.stub(chat, 'joinRoom', function() { return Ember.RSVP.resolve({ peers: [] }); }); visit('/room/asdf').then(function(){ equal($('.name').text().trim(), 'Room:'); }); }); test('clicking send should send a message', 1, function(){ var send = this.spy(); this.stub(chat, 'joinRoom', function() { return Ember.RSVP.resolve({ peers: [], send: send }); }); visit('/room/asdf').then(function(){ return click('button.send'); }).then(function() { ok(send.called); }); }); test('the user should be able to change their nick', 1, function(){ var setNick = this.spy(); this.stub(chat, 'joinRoom', function() { return Ember.RSVP.resolve({ peers: [], setNick: setNick }); }); visit('/room/asdf'). click('.nick'). fillIn('.new-nick', 'new nick name'). keyEvent('.new-nick', 'keyup', 13). // 13 === enter then(function() { ok(setNick.called); }); }); test('the user should be able to download their audio', 1, function(){ sinon.stub(Recording, 'downloadWAV'); var setNick = this.spy(); this.stub(chat, 'joinRoom', function() { return Ember.RSVP.resolve({ peers: [], setNick: setNick }); }); visit('/room/asdf'). click('.download-audio'). then(function() { ok(Recording.downloadWAV.called, 'downloadWAV was called'); Recording.downloadWAV.restore(); }); });
/* jshint node: true */ "use strict"; var Backbone = require("backbone"); module.exports = Backbone.Marionette.AppRouter.extend({ appRoutes: { "": "management" } });
'use strict'; angular.module('meansandApp.admin') .config(function($stateProvider) { $stateProvider.state('admin', { url: '/admin', templateUrl: 'app/admin/admin.html', controller: 'AdminController', controllerAs: 'admin', authenticate: 'admin' }); });
var express = require('express'); var deviceRouter = express.Router(); var config = require("./config"); deviceRouter.get("/", function (req, res) { var user = req.userInfo; var devices = config.getUserDeviceMap(user).devices; var converted = config.convertInternalDeviceArrayToClientArray(devices); console.log(devices); console.log(converted); res.send(converted); }); // return devices for this specific hub deviceRouter.get("/:deviceId", function (req, res) { var user = req.userInfo; var deviceId = req.params.deviceId; var device = config.getUserDevice(user, deviceId); var converted = config.convertInternalDeviceToClientDevice(device); res.send(converted); }); module.exports = deviceRouter;
import { Platform } from 'react-native'; import { Navigation } from 'react-native-navigation'; const Icon = require('react-native-vector-icons/MaterialIcons'); import Parse from 'parse/react-native'; import registerScreens from './screens'; registerScreens(); globalIconMap = {}; class App { constructor() { Parse.initialize("ParamotorSpots"); Parse.serverURL = "http://bluecensus.mhsilva.io:1338/parse"; this._populateIcons().then(() => { this._startApp(); }).catch((error) => { console.error(error); }); } _populateIcons = function () { return new Promise(function (resolve, reject) { Promise.all([ Icon.getImageSource('list', 24), Icon.getImageSource('map', 24), Icon.getImageSource('assistant-photo', 24), Icon.getImageSource('add-location', 24, "#fff"), Icon.getImageSource('send', 24, "#fff"), ]).then((values) => { globalIconMap['list'] = values[0]; globalIconMap['map'] = values[1]; globalIconMap['top-spotters'] = values[2]; globalIconMap['add-spot-white'] = values[3]; globalIconMap['send'] = values[4]; resolve(true); }).catch((error) => { console.log(error); reject(error); }).done(); }); }; _startApp = function() { Navigation.startTabBasedApp({ tabs: [ { label: 'Spots', screen: 'ppg-spots.spots', icon: globalIconMap['list'], title: 'Spots', }, { label: 'Map', screen: 'ppg-spots.map', icon: globalIconMap['map'], title: 'Map', }, { label: 'Top Spotters', screen: 'ppg-spots.top-spotters', icon: globalIconMap['top-spotters'], title: 'Top Spotters', } ], tabsStyle: { tabBarBackgroundColor: '#003a66', navBarButtonColor: '#ffffff', tabBarButtonColor: '#ffffff', navBarTextColor: '#ffffff', tabBarSelectedButtonColor: '#E11D32', navigationBarColor: '#003a66', navBarBackgroundColor: '#003a66', statusBarColor: '#002b4c', tabFontFamily: 'BioRhyme-Bold', }, appStyle: { orientation: 'portrait', tabBarBackgroundColor: '#003a66', navBarButtonColor: '#ffffff', tabBarButtonColor: '#ffffff', navBarTextColor: '#ffffff', tabBarSelectedButtonColor: '#E11D32', navigationBarColor: '#003a66', navBarBackgroundColor: '#003a66', statusBarColor: '#002b4c', tabFontFamily: 'BioRhyme-Bold', } }); } } new App();
import Container from './container.js'; export class Form extends Container { get defaultSelector() { return 'form'; } } export default Form;
require("app/config"); var test = [1, 2, 3, 4, 5, 6]; var [ one, two, ...rest] = test; console.log(one, two, rest, `schfifty-five = ${5 + 5}`);
import expect from 'expect';
/* * grunt-node-deploy * https://github.com/ValeriiVasin/grunt-node-deploy * * Copyright (c) 2013 Valerii Vasin * Licensed under the MIT license. */ module.exports = function (grunt) { 'use strict'; var Deploy = require('./deployHelper').Deploy; grunt.registerMultiTask('deploy', 'Simplify your apps deploying', function () { var data = this.data, done = this.async(), args = this.args, deploy; /** * @todo Check params */ deploy = new Deploy({ user: data.user, domain: data.domain, deployTo: data.deployTo, repository: data.repository, branch: data.branch, keepReleases: data.keepReleases, tasks: data.tasks }, function init() { // grunt deploy:<env> --exec="ls -lah" if ( typeof grunt.option('exec') !== 'undefined' ) { deploy.run( grunt.option('exec') ); deploy.exec(done); return; } // grunt deploy:<env> --invoke=task1,task2 if ( typeof grunt.option('invoke') === 'string' ) { deploy.invokeTasks(grunt.option('invoke').split(','), done); return; } // grunt deploy:<env> --setup if ( grunt.option('setup') ) { deploy.invokeTask('setup', done); return; } // grunt deploy:<env> --rollback if ( grunt.option('rollback') ) { deploy.invokeTask('rollback', done); return; } // default task: deploy deploy.invokeTask('deploy', done); }); }); };
var env = process.env.NODE_ENV var dev = env !== 'production' var path = require('path') var webpack = require('webpack') var ExtractTextPlugin = require('extract-text-webpack-plugin') var HtmlWebpackPlugin = require('html-webpack-plugin') var extractSass = new ExtractTextPlugin({ filename: 'cssloading.css', disable: dev }) module.exports = { entry: { 'cssloading': !dev ? './src/cssloading.js' : ['./client', './src/cssloading.js'] }, output: { path: !dev ? path.join(__dirname, './dist') : '/', publicPath: !dev ? './dist' : '/', filename: '[name].js', libraryTarget: 'umd' }, module: { rules: [{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.scss$/, exclude: /node_modules/, use: extractSass.extract({ fallback: 'style-loader', use: 'css-loader!postcss-loader!sass-loader' }) }] }, plugins: [ extractSass, new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.tpl', inject: true }) ] }
// Source : https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/ // Author : Dean Shi // Date : 2015-06-11 /********************************************************************************** * * Given a digit string, return all possible letter combinations that the number could represent. * * A mapping of digit to letters (just like on the telephone buttons) is given below. * * Input:Digit string "23" * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. * * Note: * Although the above answer is in lexicographical order, your answer could be in any order you want. * * **********************************************************************************/ /** * @param {string} digits * @return {string[]} */ var letterCombinations = function(digits) { let result, const [first, ...rest] = digits const digitMap = { 2: ['a', 'b', 'c'], 3: ['d', 'e', 'f'], 4: ['g', 'h', 'i'], 5: ['j', 'k', 'l'], 6: ['m', 'n', 'o'], 7: ['p', 'q', 'r', 's'], 8: ['t', 'u', 'v'], 9: ['w', 'x', 'y', 'z'] } return rest.reduce((arr, d) => { result = [] arr.forEach(a => digitMap[d].forEach(b => result.push(a + b))) return result }, digitMap[first] || []) };
var express = require('express'); var path = require('path'); var app = express(); app.use(express.static(process.argv[3] || path.join(__dirname, 'public'))); app.listen(process.argv[2]);
import React, { Component } from 'react'; import Search from './Search'; import PostJobComponent from './PostJobComponent'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import Actions from '../../DataStore/Actions'; const MainApp = (props) => { return(<Search State = {props} searchAction = {props.Actions.searchJobs} data = {props.search_results} suggestions = {props.suggestions}/>); } function mapStateToProps( state ){ return{ AccountUser: state.AccountUser, Bids: state.Bids, Jobs: state.Jobs, Categories: state.Categories, search_results: state.search_results, suggestions: state.suggestions, routing: state.routing, Messages: state.Messages, SentMessages: state.SentMessages, JobsAvailable: state.JobsAvailable } } function mapDispatchToProps(dispatch){ //this function makes it that we do not have to call the dispatch method each time return{ Actions: bindActionCreators( Actions, dispatch ) } } export default connect(mapStateToProps, mapDispatchToProps)(MainApp);