text
stringlengths
2
6.14k
// Private array of chars to use var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); var ID = {}; ID.uuid = function (len, radix) { var chars = CHARS, uuid = [], i; radix = radix || chars.length; if (len) { // Compact form for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix]; } else { // rfc4122, version 4 form var r; // rfc4122 requires these characters uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'; uuid[14] = '4'; // Fill in random data. At i==19 set the high bits of clock sequence as // per rfc4122, sec. 4.1.5 for (i = 0; i < 36; i++) { if (!uuid[i]) { r = 0 | Math.random()*16; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; } } } return uuid.join(''); }; // A more performant, but slightly bulkier, RFC4122v4 solution. We boost performance // by minimizing calls to random() ID.uuidFast = function() { var chars = CHARS, uuid = new Array(36), rnd=0, r; for (var i = 0; i < 36; i++) { if (i==8 || i==13 || i==18 || i==23) { uuid[i] = '-'; } else if (i==14) { uuid[i] = '4'; } else { if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0; r = rnd & 0xf; rnd = rnd >> 4; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; } } return uuid.join(''); }; // A more compact, but less performant, RFC4122v4 solution: ID.uuidCompact = function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); }; module.exports = ID;
// ==UserScript== // @name mineAI // @namespace minesAI // @include http://minesweeperonline.com/#beginner-night // @version 1 // @required http://localhost:8000/convnetjs.js // @grant none // ==/UserScript== // Load the library. var D = document; var appTarg = D.getElementsByTagName ('head')[0] || D.body || D.documentElement; var jsNode = D.createElement ('script'); jsNode.src = 'http://localhost:8000/convnetjs.js'; jsNode.addEventListener ("load", initConvNetJsOnDelay, false); appTarg.appendChild (jsNode); // Allow some time for the library to initialize after loading. function initConvNetJsOnDelay () { setTimeout (initConvNetJs, 666); } // Call the library's start-up function, if any. Note needed use of unsafeWindow. function initConvNetJs () { // species a 2-layer neural network with one hidden layer of 20 neurons var layer_defs = []; // ConvNetJS works on 3-Dimensional volumes (sx, sy, depth), but if you're not dealing with images // then the first two dimensions (sx, sy) will always be kept at size 1 layer_defs.push({type:'input', out_sx:1, out_sy:1, out_depth:2}); // declare 4 neurons, followed by ReLU (rectified linear unit non-linearity) layer_defs.push({type:'fc', num_neurons:4, activation:'relu'}); // 3 more for good measure layer_defs.push({type:'fc', num_neurons:3, activation:'relu'}); // declare the linear classifier on top of the previous hidden layer layer_defs.push({type:'softmax', num_classes:2}); // defined our net with unsafeWindow for use in GreaseMonkey var net = new unsafeWindow.convnetjs.Net(); // create our net with layers as defined above net.makeLayers(layer_defs); // define trainer var trainer = new convnetjs.SGDTrainer(net, {learning_rate:0.01, l2_decay:0.001}); // define inputs (XOR) var t1 = new convnetjs.Vol([0, 0]); // class 0 var t2 = new convnetjs.Vol([0, 1]); // class 1 var t3 = new convnetjs.Vol([1, 0]); // class 1 var t4 = new convnetjs.Vol([1, 1]); // class 0 // train for 1000 iterations with corresponding classes for (var i = 0; i < 1000; i++) { trainer.train(t1, 0); trainer.train(t2, 1); trainer.train(t3, 1); trainer.train(t4, 0); } // learned probability var prob00 = net.forward(t1); var prob01 = net.forward(t2); var prob10 = net.forward(t3); var prob11 = net.forward(t4); // log probability console.log('p(0 | 00): ' + prob00.w[0] + ", p(1 | 00): " + prob00.w[1]); console.log('p(0 | 01): ' + prob01.w[0] + ", p(1 | 01): " + prob01.w[1]); console.log('p(0 | 10): ' + prob10.w[0] + ", p(1 | 10): " + prob10.w[1]); console.log('p(0 | 11): ' + prob11.w[0] + ", p(1 | 11): " + prob11.w[1]); } alert("Done");
var test = require('tst') var assert = require('assert') var noise = require('..') test('white noise', () => { assert(typeof noise.white() === 'function') }) test('pink noise', () => { assert(typeof noise.pink() === 'function') }) test('brown noise', () => { assert(typeof noise.pink() === 'function') })
define(function () { 'use strict'; ({ get foo () { console.log( 'effect' ); return {}; } }).foo.bar; ({ get foo () { return {}; } }).foo.bar.baz; ({ get foo () { console.log( 'effect' ); return () => {}; } }).foo(); ({ get foo () { return () => console.log( 'effect' ); } }).foo(); ({ get foo () { console.log( 'effect' ); return () => () => {}; } }).foo()(); ({ get foo () { return () => () => console.log( 'effect' ); } }).foo()(); });
import {module, inject, createRootFactory} from '../mocks'; describe('solPopmenu directive', function () { let $compile; let $rootScope; let createRoot; let rootEl; beforeEach(module('karma.templates')); beforeEach(module('ui-kit')); beforeEach(inject((_$compile_, _$rootScope_) => { $compile = _$compile_; $rootScope = _$rootScope_; createRoot = createRootFactory($compile); let html = '<div><sol-popmenu icon="list">tranclusion</sol-popmenu></div>'; rootEl = createRoot(html, $rootScope); })); it('should replace the element', () => { let menu = rootEl.find('.popmenu-popup .popmenu-content'); expect(rootEl).not.toContainElement('sol-popmenu'); }); it('should transclude content inside a ".popmenu-popup .popmenu-content" element', () => { let menu = rootEl.find('.popmenu-popup .popmenu-content'); expect(menu).toHaveText('tranclusion'); }); it('should add "fa fa-<icon>" class on toggler according to icon attribute', () => { let toggler = rootEl.find('.popmenu-toggler'); expect(toggler).toHaveClass('fa fa-list'); }); it('should toggle the "closed" class on .popmenu once the .popmenu-toggler clicked', () => { let menu = rootEl.find('.popmenu'); let toggler = rootEl.find('.popmenu-toggler'); expect(menu).not.toHaveClass('closed'); toggler.click(); toggler.click(); $rootScope.$digest(); expect(menu).toHaveClass('closed'); }); it('contains a .popmenu-toggler element', () => { let html = '<div><sol-popmenu></sol-popmenu></div>'; let rootEl = createRoot(html, $rootScope); expect(rootEl).toContainElement('.popmenu-toggler'); }); it('contains a .popmenu element', () => { let html = '<div><sol-popmenu></sol-popmenu></div>'; let rootEl = createRoot(html, $rootScope); expect(rootEl).toContainElement('.popmenu'); }); });
import React from 'react' import Button from 'components/Button' import Flex from 'components/Flex' import { Explanation, TextStep, Buttons } from '../styles' import explanation from 'images/bearing-explanation.svg' export class Step extends React.Component { render () { return ( <TextStep> <div> <h2>Thanks!</h2> <p> If it’s clear which way the camera is pointing, you can go to the next step and try marking the direction and angle of the view of the image. </p> <p> <Explanation alt='Camera and target' title='Camera and target' src={explanation} /> </p> </div> <Buttons> <Flex justifyContent='flex-end'> <Button onClick={this.props.skip} type='skip'>Skip</Button> <Button onClick={this.props.next} type='submit'>Continue</Button> </Flex> </Buttons> </TextStep> ) } } export default Step
export { default } from './ElectronOriginalWordmark'
'use-strict'; var hours = ['6:00am', '7:00am', '8:00am', '9:00am', '10:00am', '11:00am', '12:00pm', '1:00pm', '2:00pm', '3:00pm', '4:00pm', '5:00pm', '6:00pm', '7:00pm']; var allLocations = []; var theTable = document.getElementById('pike'); var el = document.getElementById('moreStores'); // var hourlyTotals = []; // contructor for the Cookie Stores function CookieStore(locationName, minCustomersPerHour, maxCustomersPerHour, avgCookiesPerCustomer) { this.locationName = locationName; this.minCustomersPerHour = minCustomersPerHour; this.maxCustomersPerHour = maxCustomersPerHour; this.avgCookiesPerCustomer = avgCookiesPerCustomer; this.customersEachHour = []; this.cookiesEachHour = []; this.totalDaily = 0; this.calcCustomersThisHour(); this.calcCookiesThisHour(); allLocations.push(this); } // creates total for customers each hour CookieStore.prototype.calcCustomersThisHour = function() { var reference = []; for (var i = 0; i < hours.length; i++) { var numberCustomersPerHour = Math.floor(Math.random() * (this.maxCustomersPerHour - this.minCustomersPerHour + 1)) + this.minCustomersPerHour; reference.push(numberCustomersPerHour); } this.customersEachHour = reference; return numberCustomersPerHour; }; // Creates total for daily cookie sales CookieStore.prototype.calcCookiesThisHour = function() { for (var j = 0; j < hours.length; j++) { var totalCookieSales = Math.ceil(this.customersEachHour[j] * this.avgCookiesPerCustomer); this.cookiesEachHour.push(totalCookieSales); this.totalDaily += this.cookiesEachHour[j]; } this.cookiesEachHour.push(this.totalDaily); }; // creates table elements function makeElement(type, content, parent){ // create var newEl = document.createElement(type); // content newEl.textContent = content; // append parent.appendChild(newEl); } // Push hours to table header var renderHeader = function() { var trEL = document.createElement('tr'); var thEL = document.createElement('th'); thEL.textContent = 'Locations'; trEL.appendChild(thEL); for (var i = 0; i < hours.length; i++) { var thEL = document.createElement('th'); thEL.textContent = hours[i]; trEL.appendChild(thEL); } thEL = document.createElement('th'); thEL.textContent = 'Daily'; trEL.appendChild(thEL); theTable.appendChild(trEL); }; // Push totals to TD's in DOM CookieStore.prototype.render = function() { var trEL = document.createElement('tr'); var tdEL = document.createElement('td'); tdEL.textContent = this.locationName; trEL.appendChild(tdEL); for (var i = 0; i < hours.length + 1; i++) { var tdEL = document.createElement('td'); tdEL.textContent = this.cookiesEachHour[i]; trEL.appendChild(tdEL); } theTable.appendChild(trEL); }; // Footer TOTALLLLL function renderFooter() { var trEL = document.createElement('tr'); var thEL = document.createElement('th'); thEL.textContent = 'Total'; trEL.appendChild(thEL); var totalOfTotals = 0; var hourlyTotal = 0; for (var i = 0; i < hours.length; i++) { hourlyTotal = 0; for (var j = 0; j < allLocations.length; j++) { hourlyTotal += allLocations[j].cookiesEachHour[i]; totalOfTotals += allLocations[j].cookiesEachHour[i]; } thEL = document.createElement('th'); thEL.textContent = hourlyTotal; trEL.appendChild(thEL); } thEL = document.createElement('th'); thEL.textContent = totalOfTotals; trEL.appendChild(thEL); theTable.appendChild(trEL); }; // passing new stores to the cookie store constructor var pikePlace = new CookieStore('Pike Place Market', 23, 65, 6.3); var seaTac = new CookieStore('Seatac', 3, 24, 1.2); var seattleCenter = new CookieStore('Seattle Center', 11, 38, 3.7); var capitolHill = new CookieStore('Capitol Hill', 20, 38, 2.3); var alki = new CookieStore('Alki', 2, 16, 4.6); // Renders the table function renderTable(){ theTable.innerHTML = ''; renderHeader(); for (i = 0; i < allLocations.length; i++) { allLocations[i].render(); } renderFooter(); } renderTable(); // Handler for listener function handleStoreSubmit(event) { event.preventDefault(); var newStoreLocation = event.target.storeLocation.value; var minCustomers = parseInt(event.target.minCustomers.value); var maxCustomers = parseInt(event.target.maxCustomers.value); var avgCookie = parseFloat(event.target.avgCookiesSold.value); console.log('go here'); // prevent empty if(!newStoreLocation || !minCustomers || !maxCustomers || !avgCookie){ return alert('All fields must have a value'); } //validate by type if (typeof minCustomers !== 'number') { return alert('Min customers must be a number'); } // ignore case on store names for(var i = 0; i < allLocations.length; i++){ if(newStoreLocation === allLocations[i].locationName) { allLocations[i].minCustomersPerHour = minCustomers; allLocations[i].maxCustomersPerHour = maxCustomers; allLocations[i].avgCookiesPerCustomer = avgCookie; clearForm(); allLocations[i].totalDaily = 0; allLocations[i].customersEachHour = []; allLocations[i].cookiesEachHour = []; allLocations[i].calcCustomersThisHour(); allLocations[i].calcCookiesThisHour(); console.log('A match was found at index', allLocations[i]); renderTable(); return; } } new CookieStore(newStoreLocation, minCustomers, maxCustomers, avgCookie); function clearForm(){ event.target.storeLocation.value = null; event.target.minCustomers.value = null; event.target.maxCustomers.value = null; event.target.avgCookiesSold.value = null; } clearForm(); // for(var i = allLocations.length - 1; i < allLocations.length; i++){ // allLocations[i].render(); // } renderTable(); }; // Listener code el.addEventListener('submit', handleStoreSubmit);
var express = require('express'); var router = express.Router(); // Play a game from the DB router.get('/games', function (req, res) { res.render('games', data); }); module.exports = router;
import React from 'react'; import ReactTouchPosition from '../../../dist/ReactTouchPosition'; import TouchPositionLabel from './TouchPositionLabel'; import OnPositionChangedLabel from './OnPositionChangedLabel'; import InstructionsLabel from './InstructionsLabel'; export default class extends React.Component { constructor(props) { super(props); this.state = { isPositionOutside: true, touchPosition: { x: 0, y: 0, } } } render() { return ( <div className="example-container"> <ReactTouchPosition {...{ className: 'example', onPositionChanged: ({ isPositionOutside, touchPosition }) => { this.setState({ isPositionOutside, touchPosition }); }, shouldDecorateChildren: false }}> <TouchPositionLabel /> <InstructionsLabel /> </ReactTouchPosition> <OnPositionChangedLabel {...this.state} /> </div> ); } }
/** * React Starter Kit for Firebase * https://github.com/kriasoft/react-firebase-starter * Copyright (c) 2015-present Kriasoft | MIT License */ import { graphql } from 'graphql'; import { Environment, Network, RecordSource, Store } from 'relay-runtime'; import schema from './schema'; import { Context } from './context'; export function createRelay(req) { function fetchQuery(operation, variables, cacheConfig) { return graphql({ schema, source: operation.text, contextValue: new Context(req), variableValues: variables, operationName: operation.name, }).then(payload => { // Passes the raw payload up to the caller (see src/router.js). // This is needed in order to hydrate/de-hydrate that // data on the client during the initial page load. cacheConfig.payload = payload; return payload; }); } const recordSource = new RecordSource(); const store = new Store(recordSource); const network = Network.create(fetchQuery); return new Environment({ store, network }); }
import { Feature } from 'core/feature'; import * as toolkitHelper from 'helpers/toolkit'; export class TargetBalanceWarning extends Feature { constructor() { super(); } shouldInvoke() { return toolkitHelper.getCurrentRouteName().indexOf('budget') !== -1; } invoke() { $('.budget-table-row.is-sub-category').each((index, element) => { const emberId = element.id; const viewData = toolkitHelper.getEmberView(emberId).data; const { subCategory } = viewData; if (subCategory.get('goalType') === ynab.constants.SubCategoryGoalType.TargetBalance) { const available = viewData.get('available'); const targetBalance = subCategory.get('targetBalance'); const currencyElement = $('.budget-table-cell-available .user-data.currency', element); if (available < targetBalance && !currencyElement.hasClass('cautious')) { if (currencyElement.hasClass('positive')) { currencyElement.removeClass('positive'); } currencyElement.addClass('cautious'); } } }); } observe(changedNodes) { if (!this.shouldInvoke()) return; if (changedNodes.has('budget-table-cell-available-div user-data')) { this.invoke(); } } onRouteChanged() { if (!this.shouldInvoke()) return; this.invoke(); } }
angular.module('kindly.requests').directive('request', function() { return { restrict: 'E', replace: true, scope: { request: '=' }, controller: function($scope) { $scope.is = function(medium) { return $scope.request.medium === medium; }; }, templateUrl: 'requests/_request.html' }; });
/** * @license Copyright (c) 2013, Viet Trinh All Rights Reserved. * Available via MIT license. */ /** * A card entity. */ define([ 'framework/entity/base_entity' ], function(BaseEntity) { /** * Constructor. * @param rawObject (optional) * The raw object to create the entity with. */ var Card = function(rawObject) { this.name = null; this.color = null; BaseEntity.call(this, rawObject); return this; }; Card.prototype = new BaseEntity(); BaseEntity.generateProperties(Card); // The card rarities. Card.RARITY = {}; Card.RARITY.MYTHIC = 'M'; Card.RARITY.RARE = 'R'; Card.RARITY.UNCOMMON = 'U'; Card.RARITY.COMMON = 'C'; Card.RARITY.LAND = 'L'; return Card; });
import Ember from 'ember'; import ObjectProxyMixin from '../mixins/object'; export default Ember.ObjectProxy.extend(ObjectProxyMixin, { _storageType: 'session' });
class Auth { isAuthenticate () { return this.getToken() !== null } setToken (token) { window.localStorage.setItem('access_token', token) } getToken () { return window.localStorage.getItem('access_token') } removeToken () { window.localStorage.removeItem('access_token') } } export default new Auth()
'use strict' // import Device from './Device' let Device = require('./Device').Device module.exports = { Device: Device }
//= require active_admin/base //= require jquery.nested-fields //= require chosen-jquery //= require bootstrap //= require bootstrap-wysihtml5 //= require ./active_tweaker
import '../../../../css/rpt/styles.global.css'; import styles from '../../../css/rpt/styles.css'; import React, { Component, PropTypes } from 'react'; import 'react-widgets/lib/less/react-widgets.less'; import DateTimePicker from 'react-widgets/lib/DateTimePicker'; import Multiselect from 'react-widgets/lib/Multiselect'; import { FormGroup,FormControl,HelpBlock,Checkbox,ControlLabel,Label,Row,Col,ListGroup,ListGroupItem,Panel,Table,Button,Glyphicon,ButtonGroup,ButtonToolbar} from 'react-bootstrap'; import { ButtonInput } from 'react-bootstrap'; import * as STATE from "../../../actions/rpt/production/State.js" var dateFormat = require('dateformat'); var Moment = require('moment'); var momentLocalizer = require('react-widgets/lib/localizers/moment'); var classNames = require('classnames'); momentLocalizer(Moment); export default class POWithReceiversDateRange extends React.Component { static propTypes = { ProdRpt: PropTypes.object.isRequired }; constructor(props) { super(props); this.state = { test:this.test.bind(this) }; if ('development'==process.env.NODE_ENV) { } } test(dt,dateStart,dateEnd){ console.log(`dt: ${dt}`); var dtStart = dateFormat(new Date(dt), "mm-dd-yyyy hh:MM:ss"); if ('development'==process.env.NODE_ENV) { console.log(`dtStart=>${dtStart}`); } var dtStartFmt = dateFormat(new Date(dateStart), "mm-dd-yyyy hh:MM:ss"); if ('development'==process.env.NODE_ENV) { console.log(`dtStartFmt=>${dtStartFmt}`); } var dtEndFmt = dateFormat(new Date(dateEnd), "mm-dd-yyyy hh:MM:ss"); if ('development'==process.env.NODE_ENV) { console.log(`dtEndFmt=>${dtEndFmt}`); } } render() { var runAndBackBtn; if(STATE.POWITHRECEIVERS_DATE_RANGE_NOT_READY==this.props.Rpt.state){ runAndBackBtn = <Row> <Col xs={4} >&nbsp;</Col> <Col xs={1}><Button onClick={()=>this.props.poWithReceivers()} bsSize="large" bsStyle="info" disabled>Run</Button></Col> <Col xs={1} >&nbsp;</Col> <Col xs={2}><Button onClick={()=>this.props.setState(STATE.NOT_STARTED)} bsSize="large" bsStyle="warning">Back</Button></Col> <Col xs={3}>&nbsp;</Col> </Row> }else{ runAndBackBtn = <Row> <Col xs={4} >&nbsp;</Col> <Col xs={2}><Button onClick={()=>this.props.poWithReceivers()} bsSize="large" bsStyle="info" >Run</Button></Col> <Col xs={1}><Button onClick={()=>this.props.setState(STATE.NOT_STARTED)} bsSize="large" bsStyle="warning">Back</Button></Col> <Col xs={3}>&nbsp;</Col> </Row> } var pageNoClass = classNames( 'pagination','hidden-xs', 'pull-left' ); var dateHeader; var dateStyle; if(this.props.ProdRpt.openPOWithReceivers.dateHeader.valid){ dateHeader=<h3 style={{textAlign:'center'}}>{this.props.ProdRpt.poWithReceivers.dateHeader.text}</h3> dateStyle='default'; }else{ dateHeader=<h3 style={{textAlign:'center',color:'red !important'}}>{this.props.ProdRpt.openPOWithReceivers.dateHeader.text}</h3> dateStyle='danger'; } return ( <div> <Panel bsStyle={dateStyle} header={dateHeader}> <Row> <Col xs={1} > <h1 style={{marginTop:0}}><Label bsStyle="primary">Start</Label></h1> </Col> <Col xs={8} xsOffset={1} style={{}}> <DateTimePicker onChange={(name,value)=>{ this.state.test(name,this.props.ProdRpt.poWithReceivers.dateStart,this.props.ProdRpt.openPOWithReceivers.dateEnd); this.props.setPOWithReceiversDateStart(name); this.props.poWithReceiversDateRange(); }} defaultValue={this.props.ProdRpt.openPOWithReceivers.dateStart} /> </Col> </Row> <Row> <Col xs={1}> <h1 style={{marginTop:0}}><Label bsStyle="primary">End</Label></h1> </Col> <Col xs={8} xsOffset={1}> <DateTimePicker onChange={(name,value)=>{ this.props.setPOWithReceiversDateEnd(name); this.props.poWithReceiversDateRange(); }} defaultValue={this.props.ProdRpt.poWithReceivers.dateEnd} /> </Col> </Row> </Panel> {runAndBackBtn} </div> ); } }
/*! Pushy - v0.9.1 - 2013-9-16 * Pushy is a responsive off-canvas navigation menu using CSS transforms & transitions. * https://github.com/christophery/pushy/ * by Christopher Yee */ $(window).load(function () { var e = false; if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) { e = true } if (e == false) { menuBtn = $('.menu-btn-left') //css classes to toggle the menu } else { menuBtn = $('.menu-btn-left, .pushy a') //css classes to toggle the menu } $(function() { var pushy = $('.pushy'), //menu css class body = $('body'), container = $('#wrapper'), //container css class container2 = $('section#home'), //container css class push = $('.push-left'), //css class to add pushy capability siteOverlay = $('.site-overlay'), //site overlay pushyClass = "pushy-left pushy-open-left", //menu position & menu open class pushyActiveClass = "pushy-active", //css class to toggle site overlay containerClass = "container-push-left", //container open class pushClass = "push-push-left", //css class to add pushy capability //menuBtn = $('.menu-btn-left'), //css classes to toggle the menu menuSpeed = 200, //jQuery fallback menu speed menuWidth = pushy.width() + "px"; //jQuery fallback menu width function togglePushy(){ body.toggleClass(pushyActiveClass); //toggle site overlay pushy.toggleClass(pushyClass); container.toggleClass(containerClass); container2.toggleClass(containerClass); push.toggleClass(pushClass); //css class to add pushy capability } function openPushyFallback(){ body.addClass(pushyActiveClass); pushy.animate({left: "0px"}, menuSpeed); container.animate({left: menuWidth}, menuSpeed); push.animate({left: menuWidth}, menuSpeed); //css class to add pushy capability } function closePushyFallback(){ body.removeClass(pushyActiveClass); pushy.animate({left: "-" + menuWidth}, menuSpeed); container.animate({left: "0px"}, menuSpeed); push.animate({left: "0px"}, menuSpeed); //css class to add pushy capability } if(Modernizr.csstransforms3d){ //toggle menu menuBtn.click(function() { togglePushy(); }); //close menu when clicking site overlay siteOverlay.click(function(){ togglePushy(); }); }else{ //jQuery fallback pushy.css({left: "-" + menuWidth}); //hide menu by default container.css({"overflow-x": "hidden"}); //fixes IE scrollbar issue //keep track of menu state (open/close) var state = true; //toggle menu menuBtn.click(function() { if (state) { openPushyFallback(); state = false; } else { closePushyFallback(); state = true; } }); //close menu when clicking site overlay siteOverlay.click(function(){ if (state) { openPushyFallback(); state = false; } else { closePushyFallback(); state = true; } }); } }); });
/* eslint-env mocha */ /* eslint-disable func-names, prefer-arrow-callback */ import mainContent from '../pageobjects/main-content.page'; import sideNav from '../pageobjects/side-nav.page'; describe.skip('emoji', ()=> { it('opens general', ()=> { sideNav.openChannel('general'); }); it('opens emoji menu', ()=> { mainContent.emojiBtn.click(); }); describe('render', ()=> { it('should show the emoji picker menu', ()=> { mainContent.emojiPickerMainScreen.isVisible().should.be.true; }); it('click the emoji picker people tab', ()=> { mainContent.emojiPickerPeopleIcon.click(); }); it('should show the emoji picker people tab', ()=> { mainContent.emojiPickerPeopleIcon.isVisible().should.be.true; }); it('should show the emoji picker nature tab', ()=> { mainContent.emojiPickerNatureIcon.isVisible().should.be.true; }); it('should show the emoji picker food tab', ()=> { mainContent.emojiPickerFoodIcon.isVisible().should.be.true; }); it('should show the emoji picker activity tab', ()=> { mainContent.emojiPickerActivityIcon.isVisible().should.be.true; }); it('should show the emoji picker travel tab', ()=> { mainContent.emojiPickerTravelIcon.isVisible().should.be.true; }); it('should show the emoji picker objects tab', ()=> { mainContent.emojiPickerObjectsIcon.isVisible().should.be.true; }); it('should show the emoji picker symbols tab', ()=> { mainContent.emojiPickerSymbolsIcon.isVisible().should.be.true; }); it('should show the emoji picker flags tab', ()=> { mainContent.emojiPickerFlagsIcon.isVisible().should.be.true; }); it('should show the emoji picker custom tab', ()=> { mainContent.emojiPickerCustomIcon.isVisible().should.be.true; }); it('should show the emoji picker change tone button', ()=> { mainContent.emojiPickerChangeTone.isVisible().should.be.true; }); it('should show the emoji picker search bar', ()=> { mainContent.emojiPickerFilter.isVisible().should.be.true; }); it('send a smile emoji', ()=> { mainContent.emojiSmile.click(); }); it('the value on the message input should be the same as the emoji clicked', ()=> { mainContent.messageInput.getValue().should.equal(':smile:'); }); it('send the emoji', ()=> { mainContent.addTextToInput(' '); mainContent.sendBtn.click(); }); it('the value on the message should be the same as the emoji clicked', ()=> { mainContent.lastMessage.getText().should.equal('😄'); }); it('adds emoji text to the message input', ()=> { mainContent.addTextToInput(':smile'); }); it('should show the emoji popup bar', ()=> { mainContent.messagePopUp.isVisible().should.be.true; }); it('the emoji popup bar title should be emoji', ()=> { mainContent.messagePopUpTitle.getText().should.equal('Emoji'); }); it('should show the emoji popup bar items', ()=> { mainContent.messagePopUpItems.isVisible().should.be.true; }); it('click the first emoji on the popup list', ()=> { mainContent.messagePopUpFirstItem.click(); }); it('the value on the message input should be the same as the emoji clicked', ()=> { mainContent.messageInput.getValue().should.equal(':smile:'); }); it('send the emoji', ()=> { mainContent.sendBtn.click(); }); it('the value on the message should be the same as the emoji clicked', ()=> { mainContent.lastMessage.getText().should.equal('😄'); }); }); });
module.exports = function(config) { config.set({ basePath: './', frameworks: ['systemjs', 'jasmine'], systemjs: { configFile: 'config.js', config: { paths: { "*": null, "src/*": "src/*", "typescript": "node_modules/typescript/lib/typescript.js", "systemjs": "node_modules/systemjs/dist/system.js", 'system-polyfills': 'node_modules/systemjs/dist/system-polyfills.js', 'es6-module-loader': 'node_modules/es6-module-loader/dist/es6-module-loader.js' }, packages: { 'test/unit': { defaultExtension: 'ts' }, 'src': { defaultExtension: 'ts' } }, transpiler: 'typescript' }, serveFiles: [ 'src/**/*.ts', 'jspm_packages/**/*.js' ] }, files: [ 'test/unit/*.spec.ts' ], exclude: [], preprocessors: { }, reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
import React, { useState } from 'react'; import { UncontrolledAlert } from 'reactstrap'; import Alert from '../../../src/Alert'; export const AlertFadelessExample = (props) => { const [visible, setVisible] = useState(true); const onDismiss = () => setVisible(false); return ( <div> <Alert color="primary" isOpen={visible} toggle={onDismiss} fade={false}> I am a primary alert and I can be dismissed without animating! </Alert> </div> ); } export function UncontrolledAlertFadelessExample() { return ( <div> <UncontrolledAlert color="info" fade={false}> I am an alert and I can be dismissed without animating! </UncontrolledAlert> </div> ); }
"use strict"; 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 __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var platform_browser_1 = require('@angular/platform-browser'); var forms_1 = require('@angular/forms'); var app_component_1 = require('./app.component'); var people_service_1 = require('./people.service'); var people_list_component_1 = require('./people-list.component'); var person_details_component_1 = require('./person-details.component'); var person_component_1 = require('./+person/person.component'); var http_1 = require('@angular/http'); var angular_datatables_module_1 = require('./shared/modules/datatables/angular-datatables/angular-datatables.module'); var app_routes_1 = require('./app.routes'); var AppModule = (function () { function AppModule() { } AppModule = __decorate([ core_1.NgModule({ imports: [platform_browser_1.BrowserModule, app_routes_1.routing, forms_1.FormsModule, http_1.HttpModule, angular_datatables_module_1.DataTablesModule], declarations: [app_component_1.AppComponent, people_list_component_1.PeopleListComponent, person_details_component_1.PersonDetailsComponent, person_component_1.PersonComponent], bootstrap: [app_component_1.AppComponent], providers: [people_service_1.PeopleService] }), __metadata('design:paramtypes', []) ], AppModule); return AppModule; }()); exports.AppModule = AppModule; //# sourceMappingURL=app.module.js.map
import { div } from '../core/dom-api'; import { urls } from '../urls'; const commentsSort = (a, b) => { if (a.time < b.time) return -1; if (a.time > b.time) return 1; return 0; }; const commentElement = (data) => { let replies = data && data.comments && data.comments.length && data.comments .sort(commentsSort) .map(item => commentElement(item)); return`<div class="comment"> <div class="details"> <div class="user">${data.user}</div> <div class="time">${data.time_ago}</div> </div> <div class="content"> ${data.content} </div> ${replies ? replies.join('') : ''} </div>`; }; const commentsElement = (comments) => { return `<div class="comments">${comments.length && comments.sort(commentsSort).map(data => commentElement(data)).join('')}</div>`; }; export const CommentsView = (props) => { let template; let data; let timeoutId; const loadData = () => { fetch(urls.item(props.routeParams.id)) .then(res => res.json()) .then(res => { data = res; render(); }); }; function createTemplate() { let hasComments = data.comments.length; let commentsContent = commentsElement(data.comments); let url = data.url; url = url.indexOf('item') === 0 ? '/' + url : url; // Set the title document.querySelector('title').innerText = `${data.title} | Vanilla Hacker News PWA`; // Clear timeout if (timeoutId) clearTimeout(timeoutId); return div({ className: 'item-view' }, ` <a class="title" href="${url}" target="_blank"> <h1>${data.title}<span>&#x2197;</span></h1> </a> <div class="subtitle ${data.type}"> <div class="user">${data.user}</div> <div class="time-ago">${data.time_ago}</div> <div class="stars">${data.points} <span>★</span></div> </div> <div class="content"> ${data.content || 'No content'} </div> <div class="comments"> <div class="subtitle">${hasComments ? 'Comments' : 'No coments'}</div> ${commentsContent} </div> `); } function createFirstTemplate() { const firstTemplate = div({ className: 'item-view' }, '<div class="content-loading">Loading content</div>'); timeoutId = setTimeout(() => { firstTemplate.querySelector('.content-loading').innerHTML += '<br/>...<br/>Looks like it takes longer than expected'; scheduleLongerTimeout(firstTemplate); }, 1e3); return firstTemplate; } function scheduleLongerTimeout(el) { timeoutId = setTimeout(() => { el.querySelector('.content-loading').innerHTML += '</br>...<br/>It\'s been over 2 seconds now, content should be arriving soon'; }, 1500); } function render() { if (!!template.parentElement) { let newTemplate = createTemplate(); template.parentElement.replaceChild(newTemplate, template); template = newTemplate; } } template = createFirstTemplate(); loadData(); return template; };
'use strict'; var assert = require('assert'); var resource = require('../resource'); exports.Person = resource.create('Person', {api: 'person', version: 2}) .extend({ flag: function(options){ return this.constructor.post('/people/' + this.id + '/flag', options); } }, { find: function(options){ options = options || {}; assert(options.email, 'An email must be provided'); return this.get('/people/find', options); } });
var opn = require('opn'); console.log('打开二维码...') // Opens the image in the default image viewer opn('static/img/qr.jpg').then(() => { console.log('关闭二维码!') });
//= require "dep3-1-1.js, dep3.js"
import { combineReducers } from 'redux' import userInfo from './userInfo' import userFeed from './userFeed' import popularFeed from './popularFeed' export default combineReducers({ userInfo, userFeed, popularFeed })
/* comment */ var g = 1, i = 2, j = 2/* *//1+g+"\/*"/i, x = 3, a = 2/1/g, b = (i)/i/i/* */, s = 'aaa\ bbb\ ccc'; var z = 1;
const matcher = require('../lib/matcher'); describe('Matcher', () => { describe('path', () => { let mock; let request; beforeEach(() => { mock = { request: { path: '/test' } }; request = { originalUrl: '/test?blah=test', path: '/test' }; }); test('should return true if request path exactly matches mock request path', () => { expect(matcher.path(mock, request)).toBe(true); }); test('should return true if request path matches mock request greedy path', () => { mock.request.path = '/test/*'; request.path = '/test/anything'; expect(matcher.path(mock, request)).toBe(true); }); test('should return true if request path matches mock request named path', () => { mock.request.path = '/test/:named/end'; request.path = '/test/anything/end'; expect(matcher.path(mock, request)).toBe(true); }); test('should return false if request path does not match mock request named path', () => { mock.request.path = '/test/:named/end'; request.path = '/this/will/never/match'; expect(matcher.path(mock, request)).toBe(false); }); }); describe('headers', () => { let mock; let request; beforeEach(() => { mock = { request: { headers: { test: 'this' } } }; request = { headers: { test: 'this' } }; }); test('should return true if request headers exactly match mock request headers', () => { expect(matcher.headers(mock, request)).toBe(true); }); test('should return true if request headers contain the mock request headers', () => { request.headers.another = 'glah'; expect(matcher.headers(mock, request)).toBe(true); }); test('should return false if request headers do not match the mock request header values', () => { request.headers = { test: 'nope' }; expect(matcher.headers(mock, request)).toBe(false); }); test('should return false if request headers do not contain the mock request header values', () => { request.headers = { another: 'header' }; expect(matcher.headers(mock, request)).toBe(false); }); }); describe('query', () => { let mock; let request; beforeEach(() => { mock = { request: { query: { test: 'this' } } }; request = { query: { test: 'this' } }; }); test('should return true if mock has no query specified', () => { delete mock.request.query; expect(matcher.query(mock, request)).toBe(true); }); test('should return true if mock has empty query specified', () => { delete mock.request.query.test; expect(matcher.query(mock, request)).toBe(true); }); test('should return true if request query exactly match mock request query', () => { expect(matcher.query(mock, request)).toBe(true); }); test('should return true if request query contain the mock request query', () => { request.query.another = 'glah'; expect(matcher.query(mock, request)).toBe(true); }); test('should return false if request query does not match the mock request header values', () => { request.query = { test: 'nope' }; expect(matcher.query(mock, request)).toBe(false); }); test('should return false if request query does not contain the mock request header values', () => { request.query = { another: 'header' }; expect(matcher.query(mock, request)).toBe(false); }); test('RegExp - should return true if request query matches', () => { mock.request.query.email = { type: 'regex', value: '.*?@bar\.com' }; request.query = { test: 'this', email: 'foo@bar.com' }; expect(matcher.query(mock, request)).toBe(true); }); }); describe('body', () => { let mock; let request; beforeEach(() => { mock = { request: { body: { test: 'this' } } }; request = { body: { test: 'this' } }; }); test('should return true if request body exactly match mock request body', () => { expect(matcher.body(mock, request)).toBe(true); }); test('should return true if request body contain the mock request body', () => { request.body.another = 'glah'; expect(matcher.body(mock, request)).toBe(true); }); test('should return false if request body does not match the mock request header values', () => { request.body = { test: 'nope' }; expect(matcher.body(mock, request)).toBe(false); }); test('should return false if request body does not contain the mock request header values', () => { request.body = { another: 'field' }; expect(matcher.body(mock, request)).toBe(false); }); }); });
import React, { Component } from "react"; import formatter from "../formatter"; const labelStyle = { fg: "magenta", bold: true }; class RequestBreakdown extends Component { scroll(amount) { // nope } render() { const { respTime, sqlTime, renderingTime } = this.props.data; return ( <box top={0} height="100%-2" left={0} width="100%-2"> <box top={1} height={1} left={0} width={19} content=" Response Time : " style={labelStyle} /> <box top={1} height={1} left={19} width="100%-19" content={formatter.ms(respTime)} /> <box top={2} height={1} left={0} width={29} content=" ===========================" /> <box top={3} height={1} left={0} width={19} content=" SQL Time : " style={labelStyle} /> <box top={3} height={1} left={19} width="100%-19" content={formatter.ms(sqlTime)} /> <box top={4} height={1} left={0} width={19} content=" Rendering Time : " style={labelStyle} /> <box top={4} height={1} left={19} width="100%-19" content={formatter.ms(renderingTime)} /> <box top={5} height={1} left={0} width={19} content=" Others : " style={labelStyle} /> <box top={5} height={1} left={19} width="100%-19" content={formatter.ms(respTime - sqlTime - renderingTime)} /> </box> ); } } export default RequestBreakdown;
const DrawCard = require('../../drawcard.js'); const { CardTypes } = require('../../Constants'); class AsakoTsuki extends DrawCard { setupCardAbilities(ability) { this.reaction({ title: 'Honor a scholar character', when: { onClaimRing: event => event.conflict && event.conflict.hasElement('water') }, target: { cardType: CardTypes.Character, cardCondition: card => card.hasTrait('scholar'), gameAction: ability.actions.honor() } }); } } AsakoTsuki.id = 'asako-tsuki'; module.exports = AsakoTsuki;
import DndStatus from 'ringcentral-integration/modules/Presence/dndStatus'; import i18n from './i18n'; export function getPresenceStatusName( presenceStatus, dndStatus, currentLocale, ) { if (dndStatus === DndStatus.doNotAcceptAnyCalls) { return i18n.getString(dndStatus, currentLocale); } return i18n.getString(presenceStatus, currentLocale); }
"use strict"; const bunyan = require("bunyan") , bformat = require("bunyan-format") , config = require("config") ; const log_level = process.env.LOG_LEVEL || (config.has('app.log_level') ? config.get('app.log_level') : "info"); const formatOut = bformat({ outputMode: "short" , }) , logger = bunyan.createLogger({ name: "pepp", streams: [ { level: log_level, stream: formatOut }/*, { level: 'info', // log ERROR and above to a file path: './output/test.log' }*/ ] }); module.exports = logger;
module.exports = function(grunt) { grunt.initConfig({ // insert the bower files in your index.html wiredep: { target: { src: 'index.html' } } }); grunt.loadNpmTasks('grunt-wiredep'); grunt.registerTask('default', ['wiredep']); };
const test = require('tape') const MinHeap = require('./MinHeap') test('find returns null in empty heap', assert => { const heap = new MinHeap() assert.equal(heap.findMin(), null) assert.end() }) test('length is 0 in empty heap', assert => { const heap = new MinHeap() assert.equal(heap.length, 0) assert.end() }) test('length is updated when items added', assert => { const heap = new MinHeap() heap.insert(1) heap.insert(2) heap.insert(10) assert.equal(heap.length, 3) assert.end() }) test('length is updated when items removed', assert => { const heap = new MinHeap() heap.insert(1) heap.insert(2) heap.insert(10) heap.extractMin() heap.extractMin() assert.equal(heap.length, 1) assert.end() }) test('min item is replaced with given item', assert => { const heap = new MinHeap() heap.insert(1) heap.insert(2) heap.insert(3) assert.equal(heap.findMin(), 1) assert.equal(heap.length, 3) heap.replace(4) assert.equal(heap.findMin(), 2) assert.equal(heap.length, 3) assert.equal(heap.extractMin(), 2) assert.equal(heap.extractMin(), 3) assert.equal(heap.extractMin(), 4) assert.end() }) test('find returns min item from heap', assert => { const heap = new MinHeap() heap.insert(3) heap.insert(1) heap.insert(10) assert.equal(heap.length, 3) assert.equal(heap.findMin(), 1) assert.equal(heap.length, 3) assert.end() }) test('extract returns min item from heap', assert => { const heap = new MinHeap() heap.insert(9) heap.insert(8) heap.insert(7) heap.insert(6) heap.insert(5) heap.insert(4) heap.insert(3) heap.insert(2) heap.insert(2) heap.insert(2) heap.insert(1) assert.equal(heap.extractMin(), 1) assert.equal(heap.extractMin(), 2) assert.equal(heap.extractMin(), 2) assert.equal(heap.extractMin(), 2) assert.equal(heap.extractMin(), 3) assert.equal(heap.extractMin(), 4) assert.equal(heap.extractMin(), 5) assert.equal(heap.extractMin(), 6) assert.equal(heap.extractMin(), 7) assert.equal(heap.extractMin(), 8) assert.equal(heap.extractMin(), 9) assert.equal(heap.extractMin(), null) assert.equal(heap.extractMin(), null) assert.end() }) test('heap can be iterated', assert => { const heap = new MinHeap() heap.insert(5) heap.insert(0) heap.insert(3) heap.insert(2) heap.insert(4) heap.insert(1) assert.deepEqual([...heap], [0, 1, 2, 3, 4, 5]) assert.end() }) test('heap is created from given array', assert => { const input = [5, 6, 3, 1, 2, 0, 4] const heap = new MinHeap(input) assert.deepEqual([...heap], [0, 1, 2, 3, 4, 5, 6]) assert.deepEqual(input, [5, 6, 3, 1, 2, 0, 4]) // input data should not be modified assert.end() }) test('sort random data with heap', assert => { const input = [] for (let i = 0; i < 1e5; i++) { const item = Math.floor(Math.random() * 1e4) input.push(item) } const heap = new MinHeap(input) assert.deepEqual([...heap], input.sort((a, b) => a - b)) assert.end() })
let fs = require('fs'); let path = require('path'); let moviesData = require('../config/database'); module.exports = (req, res) => { if(req.headers.statusheader === "Full") { fs.readFile("./views/status.html", (err, data) => { if(err) { console.log(err); res.writeHead(404); res.write('404 Not Found'); res.end(); } res.writeHead(200, { 'Content-Type': 'text/html' }); let imagesCount = moviesData.getMovies().length; data = data.toString().replace('{content}', `There are currently ${imagesCount} images.`); res.write(data); res.end(); }) } else { return true; } }
/** * js-borschik-include * =================== * * Собирает *js*-файлы инклудами борщика, сохраняет в виде `?.js`. * Технология нужна, если в исходных *js*-файлах используются инклуды борщика. * * В последствии, получившийся файл `?.js` следует раскрывать с помощью технологии `borschik`. * * **Опции** * * * *String* **target** — Результирующий таргет. Обязательная опция. * * *String* **filesTarget** — files-таргет, на основе которого получается список исходных файлов * (его предоставляет технология `files`). По умолчанию — `?.files`. * * *String[]* **sourceSuffixes** — суффиксы файлов, по которым строится files-таргет. По умолчанию — ['js']. * * **Пример** * * ```javascript * nodeConfig.addTechs([ * [ require('enb-borschik/techs/js-borschik-include') ], * [ require('enb-borschik/techs/borschik'), { * source: '?.js', * target: '_?.js' * } ]); * ]); * ``` */ module.exports = require('enb/lib/build-flow').create() .name('js-borschik-include') .target('target', '?.js') .useFileList(['js']) .builder(function (files) { var node = this.node; return files.map(function (file) { return '/*borschik:include:' + node.relativePath(file.fullname) + '*/'; }).join('\n'); }) .createTech();
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm5 16H7v-2h10v2zm-6.7-4L7 10.7l1.4-1.4 1.9 1.9 5.3-5.3L17 7.3 10.3 14z" }), 'OfflinePinSharp');
import * as actions from './actions' describe('App actions', () => { it('selectTerm should create SELECT_TERM action', () => { expect(actions.selectTerm('term')).toEqual({ type: 'SELECT_TERM', term: 'term' }) }) it('startFetch should create START_FETCH action', () => { expect(actions.startFetch()).toEqual({ type: 'START_FETCH', isBusy: true }) }) it('fetchTerm calls RECEIVE_ERROR on complete lookup failure', () => { let failingLookup = (url, settings, onDone ) => { throw "Error" }; let conceptNet = { lookup: failingLookup }; let dispatch = (arg) => { expect(arg['type']).toEqual("RECEIVE_ERROR") }; actions.getIsA(dispatch, conceptNet, "next term"); }) it('fetchTerm calls RECEIVE_ERROR on lookup returning error to onDone', () => { let errorLookup = (url, settings, onDone ) => { onDone("Error", null) }; let conceptNet = { lookup: errorLookup }; let dispatch = (arg) => { expect(arg['type']).toEqual("RECEIVE_ERROR") }; actions.getIsA(dispatch, conceptNet, "next term"); }) it('fetchTerm calls RECEIVE_RESPONSE on lookup returning results to onDone', () => { let successLookup = (url, settings, onDone ) => { onDone(null, {'edges': []}) }; let conceptNet = { lookup: successLookup }; let dispatch = (arg) => { expect(arg['type']).toEqual("RECEIVE_RESPONSE") }; actions.getIsA(dispatch, conceptNet, "next term"); }) })
'use strict'; angular.module('refugeesApp') .controller('SettingsController', function ($scope, Principal, Auth, Language, $translate) { $scope.success = null; $scope.error = null; Principal.identity().then(function(account) { $scope.settingsAccount = copyAccount(account); }); $scope.save = function () { Auth.updateAccount($scope.settingsAccount).then(function() { $scope.error = null; $scope.success = 'OK'; Principal.identity(true).then(function(account) { $scope.settingsAccount = copyAccount(account); }); Language.getCurrent().then(function(current) { if ($scope.settingsAccount.langKey !== current) { $translate.use($scope.settingsAccount.langKey); } }); }).catch(function() { $scope.success = null; $scope.error = 'ERROR'; }); }; /** * Store the "settings account" in a separate variable, and not in the shared "account" variable. */ var copyAccount = function (account) { return { activated: account.activated, email: account.email, firstName: account.firstName, langKey: account.langKey, lastName: account.lastName, login: account.login } } });
var UTIL = require('./util'); var ShadowNode; module.exports = ShadowNode = function(patch,options){ this.shadow = options.shadow; this.native = options.native; this.elem = new patch.type(this); this.elem.props = patch.props; this.elem.props.children = patch.children; this.elem.state = this.elem.getInitialState ? this.elem.getInitialState() : {}; this.elem.componentWillMount(); this.render(); this.elem.componentDidMount(); }; var proto = ShadowNode.prototype; Object.defineProperty(proto,'parent',{ get : function(){ return this.native.parent; } }); proto.setPatch = function(patch){ var oldProps = this.elem.props; this.elem._isUpdating = true; var newProps = patch.props; newProps.children = patch.children; this.elem.componentWillRecieveProps(newProps); this.elem.props = newProps; this.elem.componentDidRecieveProps(oldProps); this.update(); }; proto.update = function(){ // This is called by set state and by props updating this.elem.componentWillUpdate(); this.render(); this.elem.componentWillUpdate(); }; proto.remove = function(){ this.elem.componentWillUnmount(); this.destroyed = true; if (this.figure){ return this.figure.remove(); } this.shadow = void 0; this.figure = void 0; this.native = void 0; this.elem.componentDidUnmount(); }; proto.render = function(){ var newPatch = this.elem.render(); var lastPatch = this.lastPatch; this.lastPatch = newPatch; if (!lastPatch && !newPatch) return; if (UTIL.isNative(newPatch)){ if (this.figure){ this.figure.remove(); this.figure = void 0; } this.native.shadowTail = this; return this.native.setPatch(newPatch); } if (UTIL.differentTypes(lastPatch,newPatch)){ if (this.figure) this.figure.remove(); this.figure = new ShadowNode(newPatch,{ shadow : this,native : this.native }); return this.figure; } if (UTIL.differentPatch(lastPatch,newPatch)){ // component will update this.figure.setPatch(newPatch); // component did update } };
'use strict'; var mongoose = require('mongoose'), Schema = mongoose.Schema; var videoWorksSchema = new Schema ({ title: { type: String }, directedBy: { type: [String] }, editedBy: { type: [String] }, cast: { type: [String] }, videoUrl: { type: String }, copyright: { type: String }, workInfo: { type: String }, coverImageUrl: { type: String }, created: { type: Date, default: Date.now } }); mongoose.model('videoWorks', videoWorksSchema);
'use strict'; module.exports = { extends: ['./index', './rules/imports', './rules/frontend', './rules/vue'].map(require.resolve).concat(['plugin:vue/recommended']), parser: 'vue-eslint-parser', parserOptions: { parser: 'babel-eslint', sourceType: 'module', ecmaVersion: 2017, ecmaFeatures: { jsx: true, experimentalObjectRestSpread: true, }, }, rules: { // this two doesn't work in vue 'import/no-named-as-default': 'off', 'import/no-named-as-default-member': 'off', }, };
import React, {PropTypes} from 'react'; import { Link, IndexLink } from 'react-router'; // import {Navbar, Nav, NavItem, NavDropdown, MenuItem} from 'react-bootstrap'; class Header extends React.Component { constructor(props) { super(props); } render() { return ( <div id="container" className="link_box"> <div id="itemA"></div> <div id="itemB"> <Link to="/"> <img src=" http://cdn.dscount.com/images_2016/top/ntop_all02.jpg" alt="dscount"/> </Link> </div> <div id="itemC"> <Link to="/"> <img src=" http://cdn.dscount.com/images_2016/top/btn_dscoupon02.jpg" alt="dscount"/> </Link> </div> <div id="itemD"></div> <div id="itemE"> <Link to="" >ログイン</Link> </div> <div id="itemF"> <Link to="/signup">会員登録</Link> </div> <div id="itemG"> <a href="#" >マイページ{" "}▼</a> </div> <div id="itemH"> <a href="#" >お客様センター{" "}▼</a> </div> <div id="itemI"> <a href="#" > <span className="glyphicon glyphicon-shopping-cart">(0)</span> </a> </div> <div id="itemJ"> <a href="#" > <span className="glyphicon glyphicon-heart">(1)</span> </a> </div> <form id="itemK"> <div className="field"> <button className="drop-down-btn" type="button" id="search">総合検索{" "}▼</button> <input className="header-search-input" type="text" id="searchterm" placeholder=" what do you want ?" /> <button className="search-submit" type="button" id="search"> <span className="glyphicon glyphicon-search"></span> </button> </div> </form> <div id="itemL"></div> </div> ); } } export default Header;
/* function Canvas(paper, props){ var props = $.extend(true, { "x" : 0, "y" : 0, "width" : "100%", "height" : "100%" }, (props || {})), _scale = 1, _translateX = 0, _translateY = 0, self = this, lx = 0, ly = 0, ox = 0, oy = 0, canvasBg = paper.rect(props.x, props.y, props.width, props.height), canvas = paper.group(), elements = [] ; var moveFnc = function(dx, dy){ lx = dx * (1 / _scale) + ox; ly = dy * (1 / _scale) + oy; self.setTranslate(lx, ly); }, startFnc = function(){ var transform = canvasBg.transform(); for(var i = 0; i < transform.length; i++){ if(transform[i][0].toLowerCase() === "t"){ ox = parseInt(transform[i][1]) * _scale; oy = parseInt(transform[i][2]) * _scale; } } }, endFnc = function(){ ox = lx; oy = ly; }, applyTransform = function(){ canvas.transform("s" + _scale + "t" + _translateX + "," + _translateY); canvasBg.transform("s" + _scale + "t" + _translateX + "," + _translateY); } ; this.add = function(el){ canvas.add(el.getObj()); elements.push(el); return this; }; this.setTranslate = function(x, y){ _translateX = x; _translateY = y; applyTransform(); return this; }; this.getTranslate = function(){ return { "x" : _translateX, "y" : _translateY }; }; this.setScale = function(s, onEachElement){ _scale = s; applyTransform(); if(onEachElement){ for(var i = 0; i < elements.length; i++){ onEachElement(elements[i], s); } } return this; }; this.getScale = function(){ return _scale; }; this.getProps = function(){ return props; }; canvasBg.attr({ "fill" : "rgba(255, 255, 0, .5)", "stroke" : "#000000", "stroke-width" : 1 }); this .setTranslate(0, 0) .setScale(1) ; canvasBg.drag(moveFnc, startFnc, endFnc); } */
export default function(that) { return !isNaN(that.curValue) && that.curValue%1===0; }
'use strict'; angular.module('core').controller('SidebarController', ['$scope', 'Authentication', function($scope, Authentication) { $scope.authentication = Authentication; } ]);
import superagent from 'superagent'; import config from '../config'; const { NODE_ENV } = process.env; const methods = ['get', 'post', 'put', 'patch', 'del']; function formatUrl(path) { const adjustedPath = path[0] !== '/' ? '/' + path : path; if (__SERVER__ || NODE_ENV === 'production') { return `${config.apiHost}/v1${adjustedPath}` } return '/api' + adjustedPath; } export default class ApiClient { constructor() { methods.forEach((method) => this[method] = (path, { params, data } = {}) => new Promise((resolve, reject) => { const request = superagent[method](formatUrl(path)); if (params) { request.query(params); } // if (__SERVER__ && req.get('cookie')) { // request.set('cookie', req.get('cookie')); // } if (data) { request.send(data); } if (__CLIENT__ && window.localStorage.authToken) { request.set('authorization', window.localStorage.authToken) } request.end((err, { body } = {}) => err ? reject(body || err) : resolve(body)); })); } /* * There's a V8 bug where, when using Babel, exporting classes with only * constructors sometimes fails. Until it's patched, this is a solution to * "ApiClient is not defined" from issue #14. * https://github.com/erikras/react-redux-universal-hot-example/issues/14 * * Relevant Babel bug (but they claim it's V8): https://phabricator.babeljs.io/T2455 * * Remove it at your own risk. */ empty() {} }
version https://git-lfs.github.com/spec/v1 oid sha256:bd24e43ef20f9f9e3c711e3d54df98d049591993ab374dbc14fbe801ba528183 size 10061
module.exports = { snowboy: { models: { file: "node_modules/snowboy/resources/snowboy.umdl", sensitivity: "0.5", hotwords: "snowboy" }, detector: { resource: "node_modules/snowboy/resources/common.res", audioGain: 2.0 } } };
var jshint = require('jshint').JSHINT, colors = require('colors'); module.exports = function(code) { var options = { devel: true, node: true, predef: ['expect', 'done'], undef: true }, isValid = jshint(code, options); if (!isValid) { var errorsByLineNumber = {}; jshint.errors.map(function(error) { errorsByLineNumber[error.line] = error.reason; }); code.split('\n').forEach(function(line, index) { var lineNumber = index + 1; if (errorsByLineNumber[lineNumber]) { line = line.yellow + '\t' + ('// ERROR: ' + errorsByLineNumber[lineNumber]).red } console.log(line); }); } return isValid; };
/** * ghostHunter - 0.4.0 * Copyright (C) 2014 Jamal Neufeld (jamal@i11u.me) * MIT Licensed * @license */ (function( $ ) { /* Include the Lunr library */ var lunr=require('./lunr.min.js'); //This is the main plugin definition $.fn.ghostHunter = function( options ) { //Here we use jQuery's extend to set default values if they weren't set by the user var opts = $.extend( {}, $.fn.ghostHunter.defaults, options ); if( opts.results ) { pluginMethods.init( this , opts ); return pluginMethods; } }; $.fn.ghostHunter.defaults = { resultsData : false, onPageLoad : true, onKeyUp : false, result_template : "<a href='{{link}}'><p><h2>{{title}}</h2><h4>{{prettyPubDate}}</h4></p></a>", info_template : "<p>Number of posts found: {{amount}}</p>", displaySearchInfo : true, zeroResultsInfo : true, before : false, onComplete : false, includepages : false, filterfields : false }; var prettyDate = function(date) { var d = new Date(date); var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; return d.getDate() + ' ' + monthNames[d.getMonth()] + ' ' + d.getFullYear(); }; var pluginMethods = { isInit : false, init : function( target , opts ){ var that = this; this.target = target; this.results = opts.results; this.blogData = {}; this.result_template = opts.result_template; this.info_template = opts.info_template; this.zeroResultsInfo = opts.zeroResultsInfo; this.displaySearchInfo = opts.displaySearchInfo; this.before = opts.before; this.onComplete = opts.onComplete; this.includepages = opts.includepages; this.filterfields = opts.filterfields; //This is where we'll build the index for later searching. It's not a big deal to build it on every load as it takes almost no space without data this.index = lunr(function () { this.field('title', {boost: 10}) this.field('description') this.field('link') this.field('plaintext', {boost: 5}) this.field('pubDate') this.field('tag') this.ref('id') }); if ( opts.onPageLoad ) { function miam () { that.loadAPI(); } window.setTimeout(miam, 1); } else { target.focus(function(){ that.loadAPI(); }); } target.closest("form").submit(function(e){ e.preventDefault(); that.find(target.val()); }); if( opts.onKeyUp ) { target.keyup(function() { that.find(target.val()); }); } }, loadAPI : function(){ if(this.isInit) return false; /* Here we load all of the blog posts to the index. This function will not call on load to avoid unnecessary heavy operations on a page if a visitor never ends up searching anything. */ var index = this.index, blogData = this.blogData; obj = {limit: "all", include: "tags", formats:["plaintext"]}; if ( this.includepages ){ obj.filter="(page:true,page:false)"; } $.get(ghost.url.api('posts',obj)).done(function(data){ searchData = data.posts; searchData.forEach(function(arrayItem){ var tag_arr = arrayItem.tags.map(function(v) { return v.name; // `tag` object has an `name` property which is the value of tag. If you also want other info, check API and get that property }) if(arrayItem.meta_description == null) { arrayItem.meta_description = '' }; var category = tag_arr.join(", "); if (category.length < 1){ category = "undefined"; } var parsedData = { id : String(arrayItem.id), title : String(arrayItem.title), description : String(arrayItem.meta_description), plaintext : String(arrayItem.plaintext), pubDate : String(arrayItem.created_at), tag : category, featureImage : String(arrayItem.feature_image), link : String(arrayItem.url) } parsedData.prettyPubDate = prettyDate(parsedData.pubDate); var tempdate = prettyDate(parsedData.pubDate); index.add(parsedData) blogData[arrayItem.id] = { title: arrayItem.title, description: arrayItem.meta_description, pubDate: tempdate, featureImage: arrayItem.feature_image, link: arrayItem.url }; }); }); this.isInit = true; }, find : function(value){ var searchResult = this.index.search(value); var results = $(this.results); var resultsData = []; results.empty(); if(this.before) { this.before(); }; if(this.zeroResultsInfo || searchResult.length > 0) { if(this.displaySearchInfo) results.append(this.format(this.info_template,{"amount":searchResult.length})); } for (var i = 0; i < searchResult.length; i++) { var lunrref = searchResult[i].ref; var postData = this.blogData[lunrref]; results.append(this.format(this.result_template,postData)); resultsData.push(postData); } if(this.onComplete) { this.onComplete(resultsData); }; }, clear : function(){ $(this.results).empty(); this.target.val(""); }, format : function (t, d) { return t.replace(/{{([^{}]*)}}/g, function (a, b) { var r = d[b]; return typeof r === 'string' || typeof r === 'number' ? r : a; }); } } })( jQuery );
import React, { PropTypes, } from 'react'; import { StyleSheet, View, Text, } from 'react-native'; const styles = StyleSheet.create({ all: { paddingHorizontal: 10, paddingVertical: 5, }, text: { fontSize: 12, color: '#666', }, }); function ListItemTitle(props) { return ( <View style={styles.all}> <Text style={styles.text} > {props.text} </Text> </View> ); } ListItemTitle.propTypes = { text: PropTypes.string, }; ListItemTitle.defaultProps = { text: '', }; export default ListItemTitle;
import axios from 'axios'; import {getAuthInfo} from './firebase-service'; import {VIANCA, CHAN, TOPA, IBA_COLOMBIA} from './service-store'; export const ERROR_RESULT = 'ERROR'; export const RESERVED_RESULT = 'R'; export const INSUFICIENT_RESULT = 'I'; export const NOT_FOUND_RESULT = 'NF'; export function submitReserve(reserve, airlineCode) { let _this = this; let apiUrl = getAirlineUrl(airlineCode); reserve.token = getAuthInfo().idToken; return axios.post(apiUrl, reserve).then(result => { if (!result.message) { console.error("No \"message\" attribute in result: ", result) return ERROR_RESULT; } return result.message; }).catch(error => console.log(error)); } function getAirlineUrl(airlineCode) { switch (airlineCode) { case VIANCA.code: return VIANCA.submitReserveUrl; case CHAN.code: return CHAN.submitReserveUrl; case TOPA.code: return TOPA.submitReserveUrl; case IBA_COLOMBIA.code: return IBA_COLOMBIA.submitReserveUrl; default: } } export function searchForReserve(apiUrl) { let _this = this; let url = apiUrl + '?token=' + getAuthInfo().idToken; // + getToken(); return axios.get(url); } export function submitAllReserveSearch() { console.log('Fetching reserve searchs'); let viancaResult = searchForReserve(VIANCA.fetchReserves); let chanResult = searchForReserve(CHAN.fetchReserves); let topaResult = searchForReserve(TOPA.fetchReserves); let ibaResult = searchForReserve(IBA_COLOMBIA.fetchReserves); let mergedResults = axios.all([viancaResult, chanResult, topaResult, ibaResult]); return mergedResults; }
import { DESCRIPTORS, LITTLE_ENDIAN } from '../helpers/constants'; if (DESCRIPTORS) QUnit.test('Int32 conversions', assert => { const int32array = new Int32Array(1); const uint8array = new Uint8Array(int32array.buffer); const dataview = new DataView(int32array.buffer); function viewFrom(it) { return new DataView(new Uint8Array(it).buffer); } function toString(it) { return it === 0 && 1 / it === -Infinity ? '-0' : it; } const data = [ [0, 0, [0, 0, 0, 0]], [-0, 0, [0, 0, 0, 0]], [1, 1, [1, 0, 0, 0]], [-1, -1, [255, 255, 255, 255]], [1.1, 1, [1, 0, 0, 0]], [-1.1, -1, [255, 255, 255, 255]], [1.9, 1, [1, 0, 0, 0]], [-1.9, -1, [255, 255, 255, 255]], [127, 127, [127, 0, 0, 0]], [-127, -127, [129, 255, 255, 255]], [128, 128, [128, 0, 0, 0]], [-128, -128, [128, 255, 255, 255]], [255, 255, [255, 0, 0, 0]], [-255, -255, [1, 255, 255, 255]], [255.1, 255, [255, 0, 0, 0]], [255.9, 255, [255, 0, 0, 0]], [256, 256, [0, 1, 0, 0]], [32767, 32767, [255, 127, 0, 0]], [-32767, -32767, [1, 128, 255, 255]], [32768, 32768, [0, 128, 0, 0]], [-32768, -32768, [0, 128, 255, 255]], [65535, 65535, [255, 255, 0, 0]], [65536, 65536, [0, 0, 1, 0]], [65537, 65537, [1, 0, 1, 0]], [65536.54321, 65536, [0, 0, 1, 0]], [-65536.54321, -65536, [0, 0, 255, 255]], [2147483647, 2147483647, [255, 255, 255, 127]], [-2147483647, -2147483647, [1, 0, 0, 128]], [2147483648, -2147483648, [0, 0, 0, 128]], [-2147483648, -2147483648, [0, 0, 0, 128]], [2147483649, -2147483647, [1, 0, 0, 128]], [-2147483649, 2147483647, [255, 255, 255, 127]], [4294967295, -1, [255, 255, 255, 255]], [4294967296, 0, [0, 0, 0, 0]], [4294967297, 1, [1, 0, 0, 0]], [9007199254740991, -1, [255, 255, 255, 255]], [-9007199254740991, 1, [1, 0, 0, 0]], [9007199254740992, 0, [0, 0, 0, 0]], [-9007199254740992, 0, [0, 0, 0, 0]], [9007199254740994, 2, [2, 0, 0, 0]], [-9007199254740994, -2, [254, 255, 255, 255]], [Infinity, 0, [0, 0, 0, 0]], [-Infinity, 0, [0, 0, 0, 0]], [-1.7976931348623157e+308, 0, [0, 0, 0, 0]], [1.7976931348623157e+308, 0, [0, 0, 0, 0]], [5e-324, 0, [0, 0, 0, 0]], [-5e-324, 0, [0, 0, 0, 0]], [NaN, 0, [0, 0, 0, 0]], ]; for (const [value, conversion, little] of data) { const big = little.slice().reverse(); const representation = LITTLE_ENDIAN ? little : big; int32array[0] = value; assert.same(int32array[0], conversion, `Int32Array ${ toString(value) } -> ${ toString(conversion) }`); assert.arrayEqual(uint8array, representation, `Int32Array ${ toString(value) } -> [${ representation }]`); dataview.setInt32(0, value); assert.arrayEqual(uint8array, big, `dataview.setInt32(0, ${ toString(value) }) -> [${ big }]`); assert.same(viewFrom(big).getInt32(0), conversion, `dataview{${ big }}.getInt32(0) -> ${ toString(conversion) }`); dataview.setInt32(0, value, false); assert.arrayEqual(uint8array, big, `dataview.setInt32(0, ${ toString(value) }, false) -> [${ big }]`); assert.same(viewFrom(big).getInt32(0, false), conversion, `dataview{${ big }}.getInt32(0, false) -> ${ toString(conversion) }`); dataview.setInt32(0, value, true); assert.arrayEqual(uint8array, little, `dataview.setInt32(0, ${ toString(value) }, true) -> [${ little }]`); assert.same(viewFrom(little).getInt32(0, true), conversion, `dataview{${ little }}.getInt32(0, true) -> ${ toString(conversion) }`); } });
/** * Runs a webserver and socket server for visualizating interactions with TJBot */ var ip = require('ip'); var express = require("express") var config = require('./config.js') var path = require("path") var app = express(); var http = require('http'); var exports = module.exports = {}; // routes var routes = require('./routes/index'); var server = http.createServer(app).listen(config.webServerNumber, function() { var addr = server.address(); console.log('Dashboard running at : http://' + ip.address() + ':' + addr.port); }); var bodyParser = require('body-parser'); var bodyParser = require('body-parser'); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()); app.set('view engine', 'pug'); app.use(express.static('public')); app.use('/', routes); var WebSocket = require('ws'); var wss = new WebSocket.Server({ server }); var clients = new Map(); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { }); clients.set(ws._socket._handle.fd, ws); //clients.push({id: ws._socket._handle.fd , client: }); // ws.send('something ......'); var hold = ws; ws.on('close', function close() { console.log("closing "); // clients.delete(ws._socket._handle.fd); }); }); var sendEvent = function(data) { console.log("Number of connectd clients", clients.size) for (var [key, client] of clients) { //console.log(key + ' = sending'); if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify(data)) } else { clients.delete(key); } } } exports.sendEvent = sendEvent; exports.wss = wss
module.exports = LoadsModels const resolve = require.resolve function LoadsModels (models) { const load = models.load.bind(models) /* load( require('./create_root_portfolio.js'), { uri: resolve('./create_root_portfolio.js'), id: 'portfolios/root' } ) */ }
var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'source-map', entry: [ './app/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/dist/' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } }) ], module: { preLoaders: [ { test: /\.tsx?$/, exclude: /(node_modules)/, loader: 'source-map' } ], loaders: [{ test: /\.scss$/, include: /src/, loaders: [ 'style', 'css', 'autoprefixer?browsers=last 3 versions', 'sass?outputStyle=expanded' ]},{ test: /\.tsx?$/, loaders: [ 'babel', 'ts-loader' ], include: path.join(__dirname, 'app') }] }, resolve: { extensions: ["", ".webpack.js", ".web.js", ".js", ".ts", ".tsx"] } };
import React from 'react' import ReactDOM from 'react-dom' import createBrowserHistory from 'history/lib/createBrowserHistory' import { useRouterHistory } from 'react-router' import { mySyncHistoryWithStore, default as createStore } from './store/createStore' import AppContainer from './containers/AppContainer' import injectTapEventPlugin from 'react-tap-event-plugin'; // ======================================================== // Browser History Setup // ======================================================== const browserHistory = useRouterHistory(createBrowserHistory)({ basename: __BASENAME__ }) // ======================================================== // Store and History Instantiation // ======================================================== // Create redux store and sync with react-router-redux. We have installed the // react-router-redux reducer under the routerKey "router" in src/routes/index.js, // so we need to provide a custom `selectLocationState` to inform // react-router-redux of its location. const initialState = window.___INITIAL_STATE__ const store = createStore(initialState, browserHistory) const history = mySyncHistoryWithStore(browserHistory, store) // ======================================================== // Developer Tools Setup // ======================================================== if (__DEBUG__) { if (window.devToolsExtension) { window.devToolsExtension.open() } } // ======================================================== // Render Setup // ======================================================== const MOUNT_NODE = document.getElementById('root') let render = (routerKey = null) => { const routes = require('./routes/index').default(store) // TODO, uncomment this before production // injectTapEventPlugin() ReactDOM.render( <AppContainer store={store} history={history} routes={routes} routerKey={routerKey} />, MOUNT_NODE ) } // Enable HMR and catch runtime errors in RedBox // This code is excluded from production bundle if (__DEV__ && module.hot) { const renderApp = render const renderError = (error) => { const RedBox = require('redbox-react') ReactDOM.render(<RedBox error={error} />, MOUNT_NODE) } render = () => { try { renderApp(Math.random()) } catch (error) { renderError(error) } } module.hot.accept(['./routes/index'], () => render()) } // ======================================================== // Go! // ======================================================== render()
var beep = require('../beep.js'); beep(3);
var github = require('octonode'); var _ = require('lodash'); module.exports = { name:'action', description:'A command to show recent activity for all members of your org', example:'bosco action', cmd:cmd } function cmd(bosco) { getActivity(bosco); } function getActivity(bosco) { var client = github.client(bosco.config.get('github:authToken')); client.get('/orgs/tes/members', {}, function (err, status, body) { if(err) { return bosco.error('Unable to access github with given authKey: ' + err.message); } _.each(body, function(event) { console.dir(event); showUser(bosco, event); }); }); } function showUser(bosco, user) { var client = github.client(bosco.config.get('github:authToken')); client.get('/users/' + user + '/events', {}, function (err, status, body) { if(err) { return bosco.error('Unable to access github with given authKey: ' + err.message); } _.each(body, function(event) { var data = [user, event.type, event.repo.name, event.created_at]; console.dir(data.join(', ')); }); }); }
/** * constants.js */ // TODO: update these to better colors var SHIELD_COLOR = vec4.fromValues(0.0, 0.0, 1.0, 1.0); var ARMOR_COLOR = vec4.fromValues(0.0, 1.0, 0.0, 1.0); var HULL_COLOR = vec4.fromValues(1.0, 0.0, 1.0, 1.0);
'use strict' exports.Utils = require('./utils') exports.Schemas = require('./schemas') exports.Validator = require('./validator')
// @flow import type { Action } from "../actions/types"; import type { UserState } from "../types"; const initialState: UserState = { fetching: false, fetched: false, users: [], error: null }; export default function users(state: UserState = initialState, action: Action) { switch (action.type) { case "FETCH_USERS_PENDING": return { ...state, fetching: true }; case "FETCH_USERS_FULFILLED": return { ...state, fetching: false, fetched: true, users: action.payload.data, error: null }; case "FETCH_USERS_REJECTED": return { ...state, fetching: false, error: action.payload }; default: return state; } }
var ps, acorn; function start(){ ps = new PointStream(); ps.setup(document.getElementById('canvas')); ps.pointSize(5); ps.onKeyDown = function(){ ps.println(window.key); }; ps.onRender = function(){ ps.translate(0, 0, -25); ps.clear(); ps.render(acorn); }; acorn = ps.load("../../clouds/acorn.asc"); }
$identify("org/mathdox/formulaeditor/OrbeonForms.js"); $require("org/mathdox/formulaeditor/FormulaEditor.js"); var ORBEON; $main(function(){ if (ORBEON && ORBEON.xforms && ORBEON.xforms.Document) { /** * Extend the save function of the formula editor to use the orbeon update * mechanism, see also: * http://www.orbeon.com/ops/doc/reference-xforms-2#xforms-javascript */ org.mathdox.formulaeditor.FormulaEditor = $extend(org.mathdox.formulaeditor.FormulaEditor, { save : function() { // call the parent function arguments.callee.parent.save.apply(this, arguments); // let orbeon know about the change of textarea content var textarea = this.textarea; if (textarea.id) { ORBEON.xforms.Document.setValue(textarea.id, textarea.value); } } }); /** * Override Orbeon's xformsHandleResponse method so that it initializes any * canvases that might have been added by the xforms engine. */ /* prevent an error if the xformsHandleResponse doesn't exist */ var xformsHandleResponse; var oldXformsHandleResponse; var newXformsHandleResponse; var ancientOrbeon; if (xformsHandleResponse) { oldXformsHandleResponse = xformsHandleResponse; } else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponse) { oldXformsHandleResponse = ORBEON.xforms.Server.handleResponse; } else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponseDom) { oldXformsHandleResponse = ORBEON.xforms.Server.handleResponseDom; } else if (ORBEON.xforms.server && ORBEON.xforms.server.AjaxServer && ORBEON.xforms.server.AjaxServer.handleResponseDom) { // orbeon 3.9 oldXformsHandleResponse = ORBEON.xforms.server.AjaxServer.handleResponseDom; } else { if (org.mathdox.formulaeditor.options.ancientOrbeon !== undefined && org.mathdox.formulaeditor.options.ancientOrbeon == true) { ancientOrbeon = true; } else { ancientOrbeon = false; alert("ERROR: detected orbeon, but could not add response handler"); } } newXformsHandleResponse = function(request) { // call the overridden method if (ancientOrbeon != true ) { oldXformsHandleResponse.apply(this, arguments); } // go through all canvases in the document var canvases = document.getElementsByTagName("canvas"); for (var i=0; i<canvases.length; i++) { // initialize a FormulaEditor for each canvas var canvas = canvases[i]; if (canvas.nextSibling) { if (canvas.nextSibling.tagName.toLowerCase() == "textarea") { var FormulaEditor = org.mathdox.formulaeditor.FormulaEditor; var editor = new FormulaEditor(canvas.nextSibling, canvas); // (re-)load the contents of the textarea into the editor editor.load(); } } } }; if (xformsHandleResponse) { xformsHandleResponse = newXformsHandleResponse; } else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponse) { ORBEON.xforms.Server.handleResponse = newXformsHandleResponse; } else if (ORBEON.xforms.Server && ORBEON.xforms.Server.handleResponseDom) { ORBEON.xforms.Server.handleResponseDom = newXformsHandleResponse; } else if (ORBEON.xforms.server && ORBEON.xforms.server.AjaxServer && ORBEON.xforms.server.AjaxServer.handleResponseDom) { ORBEON.xforms.server.AjaxServer.handleResponseDom = newXformsHandleResponse; } } });
function isEmpty(value) { return angular.isUndefined(value) || value === '' || value === null || value !== value; } angular.module('Aggie') .directive('ngMin', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, elem, attr, ctrl) { scope.$watch(attr.ngMin, function () { ctrl.$setViewValue(ctrl.$viewValue); }); var minValidator = function (value) { var min = scope.$eval(attr.ngMin) || 0; if (!isEmpty(value) && value < min) { ctrl.$setValidity('ngMin', false); return undefined; } else { ctrl.$setValidity('ngMin', true); return value; } }; ctrl.$parsers.push(minValidator); ctrl.$formatters.push(minValidator); } }; }) .directive('ngMax', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, elem, attr, ctrl) { scope.$watch(attr.ngMax, function () { ctrl.$setViewValue(ctrl.$viewValue); }); var maxValidator = function (value) { var max = scope.$eval(attr.ngMax) || Infinity; if (!isEmpty(value) && value > max) { ctrl.$setValidity('ngMax', false); return undefined; } else { ctrl.$setValidity('ngMax', true); return value; } }; ctrl.$parsers.push(maxValidator); ctrl.$formatters.push(maxValidator); } }; });
require( "../setup" ); var packageResource = require( "../../resource/package/resource.js" ); describe( "Package Resource", function() { var server = { checkForNew: _.noop }; describe( "when getting new package callback", function() { describe( "with matching package", function() { var config, serverMock, result; before( function() { config = { package: { project: "imatch" } }; serverMock = sinon.mock( server ); serverMock.expects( "checkForNew" ).once(); var envelope = { data: { project: "imatch" } }; var handler = packageResource( {}, config, server ); result = handler.actions.new.handle( envelope ); } ); it( "should call checkForNew", function() { serverMock.verify(); } ); it( "should result in a status 200", function() { result.should.eql( { status: 200 } ); } ); } ); describe( "with mis-matched package", function() { var config, serverMock, result; before( function() { config = { package: { project: "lol-aint-no-such" } }; serverMock = sinon.mock( server ); serverMock.expects( "checkForNew" ).never(); var envelope = { data: { project: "imatch" } }; var handler = packageResource( {}, config, server ); result = handler.actions.new.handle( envelope ); } ); it( "should not call checkForNew", function() { serverMock.verify(); } ); it( "should result in a status 200", function() { result.should.eql( { status: 200 } ); } ); } ); } ); } );
/** * Module dependencies. */ var express = require('express'); var routes = require('./routes'); var user = require('./routes/user'); var http = require('http'); var path = require('path'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } app.get('/', routes.index); app.get('/users', user.list); var server = http.createServer(app); var chatServer = require('./chat_server'); chatServer(server); server.listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); });
var resetCollection = function(collection) { collection.find().fetch().forEach(function(obj) { collection.remove({_id: obj._id}); }); }; describe('CapabilityManager', function() { var capabilityManager; beforeAll(function() { capabilityManager = new CapabilityManager(); }); it('should set initial capabilities', function() { var allCaps = capabilityManager.allCapabilities; expect(allCaps.length).toEqual(3); }); });
import _size from './_size'; export default class MapObject { constructor() { this._data = new Map(); } get size() { return _size(); } }
const express = require('express'); const app = express(); app.use(express.static('./src/')) app.listen(8000, () => { console.log('The server is running on the http://localhost:8000/......'); });
/** @jsx html */ import { html } from '../../../snabbdom-jsx'; import Type from 'union-type'; import { bind, pipe, isBoolean, targetValue, targetChecked } from './helpers'; import { KEY_ENTER } from './constants'; // model : {id: Number, title: String, done: Boolean, editing: Boolean, editingValue: String } const Action = Type({ SetTitle : [String], Toggle : [isBoolean], StartEdit : [], CommitEdit : [String], CancelEdit : [] }); function onInput(handler, e) { if(e.keyCode === KEY_ENTER) handler(Action.CommitEdit(e.target.value)) } const view = ({model, handler, onRemove}) => <li key={model.id} class-completed={!!model.done && !model.editing} class-editing={model.editing}> <div selector=".view"> <input selector=".toggle" type="checkbox" checked={!!model.done} on-click={ pipe(targetChecked, Action.Toggle, handler) } /> <label on-dblclick={ bind(handler, Action.StartEdit()) }>{model.title}</label> <button selector=".destroy" on-click={onRemove} /> </div> <input selector=".edit" value={model.title} on-blur={ bind(handler, Action.CancelEdit()) } on-keydown={ bind(onInput, handler) } /> </li> function init(id, title) { return { id, title, done: false, editing: false, editingValue: '' }; } function update(task, action) { return Action.case({ Toggle : done => ({...task, done}), StartEdit : () => ({...task, editing: true, editingValue: task.title}), CommitEdit : title => ({...task, title, editing: false, editingValue: ''}), CancelEdit : title => ({...task, editing: false, editingValue: ''}) }, action); } export default { view, init, update, Action }
import Route from '@ember/routing/route'; export default Route.extend({ redirect() { this._super(...arguments); this.transitionTo('examples.single-date-picker'); } });
/* */ (function(process) { var serial = require('../serial'); module.exports = ReadableSerial; function ReadableSerial(list, iterator, callback) { if (!(this instanceof ReadableSerial)) { return new ReadableSerial(list, iterator, callback); } ReadableSerial.super_.call(this, {objectMode: true}); this._start(serial, list, iterator, callback); } })(require('process'));
/** * Created by li_xiaoliang on 2015/3/29. */ define(['marked','highlight'],function(marked,highlight){ return{ parsemarkdown:function(md){ var pattern=/~.*?~/g; var matches=pattern.exec(md); while(matches!=null){ var match=matches[0]; console.log(match); var bematch=match.replace(match.charAt(0),"<div>").replace(match.substr(-1),"</div>") md=md.replace(match,bematch); matches=pattern.exec(md); } marked.setOptions({ highlight: function (code) { return highlight.highlightAuto(code).value; } }); return marked(md) } } })
define(['exports', 'aurelia-templating'], function (exports, _aureliaTemplating) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.VirtualRepeatNext = undefined; var _dec, _class; var VirtualRepeatNext = exports.VirtualRepeatNext = (_dec = (0, _aureliaTemplating.customAttribute)('virtual-repeat-next'), _dec(_class = function () { function VirtualRepeatNext() { } VirtualRepeatNext.prototype.attached = function attached() {}; VirtualRepeatNext.prototype.bind = function bind(bindingContext, overrideContext) { this.scope = { bindingContext: bindingContext, overrideContext: overrideContext }; }; return VirtualRepeatNext; }()) || _class); });
var extend = require('extend'); var plivo = require('plivo'); var crypto = require('crypto') var phone = require('phone'); var TelcomPlivoClient = module.exports = function(opts){ if (!(this instanceof TelcomPlivoClient)) return new TelcomPlivoClient(options); this.options = {}; extend(this.options,opts); this._client = plivo.RestAPI({ authId: this.options.sid, authToken: this.options.token }); }; TelcomPlivoClient.prototype.validateRequest = function(req,callback){ if(req.header('X-Plivo-Signature') === undefined) return callback('missing requrired header.') var params = req.body; if(req.method === 'GET'){ params = req.query; } var toSign = req._telcomRequestUrlNoQuery; var expectedSignature = create_signature(toSign, params,this.options.token); if(req.header('X-Plivo-Signature') === expectedSignature) callback(); else callback('signature does not match'); } TelcomPlivoClient.prototype.sms = function(obj,callback){ var plivoMesg = { src : phone(obj.from), dst : phone(obj.to), text : obj.body }; /* { api_id: 'xxxxxxxxx-1f9d-11e3-b44b-22000ac53995', message: 'message(s) queued', message_uuid: [ 'xxxxxxxx-1f9d-11e3-b1d3-123141013a24' ] } */ this._client.send_message(plivoMesg, function(err, ret) { if(err === 202){ err = undefined; } if(!ret) ret = {}; callback(err,ret.message_uuid[0],ret.message,ret); }); }; /* { To: '15559633214', Type: 'sms', MessageUUID: 'xxxxxxx-2465-11e3-985d-0025907b94de', From: '15557894561', Text: 'Vg\n' } { to : '', from : '', body : '', messageId : '', } */ TelcomPlivoClient.prototype._convertSmsRequest = function(params){ return { to : phone(params['To']), from : phone(params['From']), body : params['Text'], messageId : params['MessageUUID'], _clientRequest : params }; } // For verifying the plivo server signature // By Jon Keating - https://github.com/mathrawka/plivo-node function create_signature(url, params,token) { var toSign = url; Object.keys(params).sort().forEach(function(key) { toSign += key + params[key]; }); var signature = crypto .createHmac('sha1',token) .update(toSign) .digest('base64'); return signature; };
import GameEvent from './GameEvent'; import Creature from '../entities/creatures/Creature'; import Ability from '../abilities/Ability'; import Tile from '../tiles/Tile'; export default class AbilityEvent extends GameEvent { /** * @class AbilityEvent * @description Fired whenever a creature attacks */ constructor(dungeon, creature, ability, tile) { super(dungeon); if(!(creature instanceof Creature)) { throw new Error('Second parameter must be a Creature'); } else if(!(ability instanceof Ability)) { throw new Error('Third parameter must be an Ability'); } else if((tile instanceof Tile) !== ability.isTargetted()) { throw new Error('Fourth parameter must be a Tile iff ability is targetted'); } this._creature = creature; this._ability = ability; this._tile = tile; } getCreature() { return this._creature; } getAbility() { return this._ability; } getTile() { return this._tile; } getText(dungeon) { var creature = this.getCreature(); var ability = this.getAbility(); var tile = dungeon.getTile(creature); return `${creature} used ${ability}` + (tile ? ` on ${tile}` : ''); } }
/** * @fileOverview * @name aqicn.js * @author ctgnauh <huangtc@outlook.com> * @license MIT */ var request = require('request'); var cheerio = require('cheerio'); var info = require('./info.json'); /** * 从 aqicn.org 上获取空气信息 * @module aqicn */ module.exports = { // 一些多余的信息 info: info, /** * fetchWebPage 的 callback * @callback module:aqicn~fetchWebPageCallback * @param {object} error - 请求错误 * @param {object} result - 页面文本 */ /** * 抓取移动版 aqicn.org 页面。 * aqicn.org 桌面版在300kb以上,而移动版则不足70kb。所以使用移动版,链接后面加 /m/ 。 * @param {string} city - 城市或地区代码,详见[全部地区](http://aqicn.org/city/all/) * @param {module:aqicn~fetchWebPageCallback} callback */ fetchWebPage: function (city, callback) { 'use strict'; var options = { url: 'http://aqicn.org/city/' + city + '/m/', headers: { 'User-Agent': 'wget' } }; request.get(options, function (err, res, body) { if (err) { callback(err, ''); } else { callback(null, body); } }); }, /** * 分析 html 文件并返回指定的 AQI 值 * @param {string} body - 页面文本 * @param {string} name - 污染物代码:pm25、pm10、o3、no2、so2、co * @returns {number} AQI 值 */ selectAQIText: function (body, name) { 'use strict'; var self = this; var $ = cheerio.load(body); var json; var value; try { json = JSON.parse($('#table script').text().slice(12, -2)); // "genAqiTable({...})" value = self.info.species.indexOf(name); } catch (err) { return NaN; } return json.d[value].iaqi; }, /** * 分析 html 文件并返回更新时间 * @param {string} body - 页面文本 * @returns {string} ISO格式的时间 */ selectUpdateTime: function (body) { 'use strict'; var $ = cheerio.load(body); var json; try { json = JSON.parse($('#table script').text().slice(12, -2)); // "genAqiTable({...})" } catch (err) { return new Date(0).toISOString(); } return json.t; }, /** * 污染等级及相关信息 * @param {number} level - AQI 级别 * @param {string} lang - 语言:cn、en、jp、es、kr、ru、hk、fr、pl(但当前只有 cn 和 en) * @returns {object} 由AQI级别、污染等级、对健康影响情况、建议采取的措施组成的对象 */ selectInfoText: function (level, lang) { 'use strict'; var self = this; if (level > 6 || level < 0) { level = 0; } return { value: level, name: self.info.level[level].name[lang], implication: self.info.level[level].implication[lang], statement: self.info.level[level].statement[lang] }; }, /** * 计算 AQI,这里选取 aqicn.org 采用的算法,选取 AQI 中数值最大的一个 * @param {array} aqis - 包含全部 AQI 数值的数组 * @returns {number} 最大 AQI */ calculateAQI: function (aqis) { 'use strict'; return Math.max.apply(null, aqis); }, /** * 计算空气污染等级,分级标准详见[关于空气质量与空气污染指数](http://aqicn.org/?city=&size=xlarge&aboutaqi) * @param {number} aqi - 最大 AQI * @returns {number} AQI 级别 */ calculateLevel: function (aqi) { 'use strict'; var level = 0; if (aqi >= 0 && aqi <= 50) { level = 1; } else if (aqi >= 51 && aqi <= 100) { level = 2; } else if (aqi >= 101 && aqi <= 150) { level = 3; } else if (aqi >= 151 && aqi <= 200) { level = 4; } else if (aqi >= 201 && aqi <= 300) { level = 5; } else if (aqi > 300) { level = 6; } return level; }, /** * getAQIs 的 callback * @callback module:aqicn~getAQIsCallback * @param {object} error - 请求错误 * @param {object} result - 包含全部污染物信息的对象 */ /** * 获取指定城市的全部 AQI 数值 * @param {string} city - 城市或地区代码,详见[全部地区](http://aqicn.org/city/all/) * @param {string} lang - 语言:cn、en、jp、es、kr、ru、hk、fr、pl(但当前只有 cn 和 en) * @param {module:aqicn~getAQIsCallback} callback */ getAQIs: function (city, lang, callback) { 'use strict'; var self = this; self.fetchWebPage(city, function (err, body) { if (err) { callback(err); } var result = {}; var aqis = []; // 城市代码 result.city = city; // 数据提供时间 result.time = self.selectUpdateTime(body); // 全部 AQI 值 self.info.species.forEach(function (name) { var aqi = self.selectAQIText(body, name); aqis.push(aqi); result[name] = aqi; }); // 主要 AQI 值 result.aqi = self.calculateAQI(aqis); // AQI 等级及其它 var level = self.calculateLevel(result.aqi); var levelInfo = self.selectInfoText(level, lang); result.level = levelInfo; callback(null, result); }); }, /** * getAQIByName 的 callback * @callback module:aqicn~getAQIByNameCallback * @param {object} error - 请求错误 * @param {object} result - 城市或地区代码与指定的 AQI */ /** * 获取指定城市的指定污染物数值 * @param {string} city - 城市或地区代码 * @param {string} name - 污染物代码:pm25、pm10、o3、no2、so2、co * @param {module:aqicn~getAQIByNameCallback} callback */ getAQIByName: function (city, name, callback) { 'use strict'; var self = this; self.getAQIs(city, 'cn', function (err, res) { if (err) { callback(err); } callback(null, { city: city, value: res[name], time: res.time }); }); } };
var loadState = { preload: function() { /* Load all game assets Place your load bar, some messages. In this case of loading, only text is placed... */ var loadingLabel = game.add.text(80, 150, 'loading...', {font: '30px Courier', fill: '#fff'}); //Load your images, spritesheets, bitmaps... game.load.image('kayle', 'assets/img/kayle.png'); game.load.image('tree', 'assets/img/tree.png'); game.load.image('rock', 'assets/img/rock.png'); game.load.image('undefined', 'assets/img/undefined.png'); game.load.image('grass', 'assets/img/grass.png'); game.load.image('player', 'assets/img/player.png'); game.load.image('btn-play','assets/img/btn-play.png'); game.load.image('btn-load','assets/img/btn-play.png'); //Load your sounds, efx, music... //Example: game.load.audio('rockas', 'assets/snd/rockas.wav'); //Load your data, JSON, Querys... //Example: game.load.json('version', 'http://phaser.io/version.json'); }, create: function() { game.stage.setBackgroundColor('#DEDEDE'); game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT; game.state.start('menu'); } };
'use strict'; var proxy = require('proxyquire'); var stubs = { googlemaps: jasmine.createSpyObj('googlemaps', ['staticMap']), request: jasmine.createSpy('request'), '@noCallThru': true }; describe('google-static-map', function() { var uut; describe('without auto-setting a key', function() { beforeEach(function() { uut = proxy('./index', stubs ); }); it('should not work without a api key', function() { expect( uut ).toThrow(new Error('You must provide a google api console key')); }); it('should provide a method to set a global api key', function() { expect( uut.set ).toBeDefined(); uut = uut.set('some-key'); expect( uut ).not.toThrow( jasmine.any( Error )); }); }); describe('with auto-setting a key', function() { beforeEach(function() { uut = proxy('./index', stubs ).set('some-key'); }); it('should get/set config options', function() { var map = uut(); var set; ['zoom', 'resolution', 'mapType', 'markers', 'style'].forEach(function( key ) { set = key + ' ' + key; expect( map.config[key] ).toEqual( map[key]() ); var chain = map[key]( set ); expect( map.config[key] ).toEqual( set ); expect( chain ).toEqual( map ); }); }); it('should relay staticMap call to googlemaps module', function() { var map = uut(); var testAddress = 'Some Address, Some Country'; var staticMapReturn = 'http://some.where'; var requestReturn = 'request-return-value'; stubs.googlemaps.staticMap.andReturn( staticMapReturn ); stubs.request.andReturn( requestReturn ); var stream = map.address( testAddress ).staticMap().done(); expect( stream ).toEqual('request-return-value'); expect( stubs.googlemaps.staticMap ).toHaveBeenCalledWith( testAddress, map.config.zoom, map.config.resolution, false, false, map.config.mapType, map.config.markers, map.config.style, map.config.paths ); expect( stubs.request ).toHaveBeenCalledWith( staticMapReturn ); }); }); });
const path = require( 'path' ); const pkg = require( './package.json' ); const webpack = require( 'laxar-infrastructure' ).webpack( { context: __dirname, resolve: { extensions: [ '.js', '.jsx', '.ts', '.tsx' ] }, module: { rules: [ { test: /\.tsx?$/, exclude: /node_modules\/.*\/spec\//, loader: 'ts-loader' }, { test: /\.jsx?$/, exclude: path.resolve( __dirname, 'node_modules' ), loader: 'babel-loader' }, { test: /\.spec.js$/, exclude: path.resolve( __dirname, 'node_modules' ), loader: 'laxar-mocks/spec-loader' } ] } } ); module.exports = [ webpack.library(), webpack.browserSpec( [ `./spec/${pkg.name}.spec.js` ] ) ];
import React, { Component } from "react"; import { AppHeader, AppFooter } from "../App"; import config from "../../../config"; import { fromJS } from "immutable"; import Spinner from "react-spinner"; import { PlaylistNavBar } from "../../components/PlaylistNavBar"; export class LoadingMoment extends Component { constructor(props) { super(props); this.state = { story: null, momentId: 0, storyMomentList: [] }; } async componentDidMount() { let path = this.props.location.pathname; let storyId = path.split("/")[3]; let momentId = path.split("/")[5]; let storyMomentList = []; const response = await fetch(`${config.apiEntry}/api/stories/${storyId}`); let storyObj = await response.json(); let momentList = fromJS(storyObj.momentList); momentList.forEach((m) => storyMomentList.push(m)); this.setState({ story: storyObj, momentId: momentId, storyMomentList: storyMomentList, }); this.props.history.push(`/stories/story/${storyId}/moment/${momentId}`); } render() { return ( <div className="app-container"> <AppHeader /> <PlaylistNavBar currentStory={this.state.story} currentMomentId={this.state.momentId} moments={this.state.storyMomentList} history={this.props.history} /> <div className="text-center lead"> <p>Loading moment...</p> <Spinner /> </div> <AppFooter /> </div> ); } }
var path = require('path'); var winston = require('winston'); var config = require('./config.js'); var util = require('./util.js'); module.exports = initLogger(); function initLogger() { var targetDir = path.join(config('workingdir'), 'log'); util.createDirectoryIfNeeded(targetDir); var winstonConfig = { transports: [ new (winston.transports.Console)({ level: 'debug' }), new (winston.transports.File)({ filename: path.join(targetDir, 'tsync.log') }) ] }; return new (winston.Logger)(winstonConfig); }
const router = require('express').Router(); const db1 = require('../db'); // GET - Get All Students Info (Admin) // response: // [] students: // account_id: uuid // user_id: uuid // first_name: string // last_name: string // hometown: string // college: string // major: string // gender: string // birthdate: date // email: string // date_created: timestamp // image_path: string // bio: string router.get('/student/all', (req, res) => { db1.any(` SELECT account_id, user_id, first_name, last_name, hometown, college, major, gender, bio, birthdate, email, date_created, image_path FROM students natural join account natural join images`) .then(function(data) { // Send All Students Information console.log('Success: Admin Get All Students Information'); res.json({students: data}) }) .catch(function(error) { console.log(error); return res.status(400).send('Error: Problem executing Query'); }); }); // GET - Get All Associations Info (Admin) // response: // [] associations: // account_id: uuid // association_id: uuid // association_name: string // initials: string // email: string // page_link: string // image_path: string // bio: string // date_created: timestamp // room: string // building: string // city: string router.get('/association/all', (req, res) => { db1.any(` SELECT account_id, association_id, association_name, initials, page_link, image_path, email, bio, room, building, city, date_created FROM associations natural join account natural join location natural join images`) .then(function(data) { // Send All Associations Information console.log('Success: Admin Get All Associations Information'); res.json({associations: data}); }) .catch(function(error) { console.log(error); return res.status(400).send('Error: Problem executing Query'); }); }); // GET - Get All Events Info (Admin) // response: // [] events // event_id: id // event_name: string // is_live: bool (yes/no) // registration_link: string // start_date: date // end_date: date // start_time: time // end_time: time // room: string // building: string // city: string // image_path: string // time_stamp: timestamp router.get('/event/all', (req, res) => { db1.any(` SELECT event_id, event_name, is_live, registration_link, start_date, end_date, start_time, end_time, room, building, city, image_path, time_stamp FROM events natural join images natural join location`) .then(function(data) { // Send All Events Information console.log('Success: Admin Get All Events Information'); res.json({events: data}); }) .catch(function(error) { console.log(error); return res.status(400).send('Error: Problem executing Query'); }); }); module.exports = router;
import one from './index-loader-syntax.css'; import two from 'button.modules.css!=!./index-loader-syntax-sass.css'; // Hash should be different import three from './button.module.scss!=!./base64-loader?LmZvbyB7IGNvbG9yOiByZWQ7IH0=!./simple.js?foo=bar'; import four from './other.module.scss!=!./base64-loader?LmZvbyB7IGNvbG9yOiByZWQ7IH0=!./simple.js?foo=baz'; __export__ = [...one, ...two, ...three, ...four]; export default [...one, ...two, ...three, ...four];
var mysql = require('mysql'); function discountMember(router,connection){ var self=this; self.handleRoutes(router,connection); } //KALO...UDH SEKALI DIDISKON>>>BERARTI GABOLEH LAGI LAGI DISKON YAA TODO: discountMember.prototype.handleRoutes = function(router,connection){ router.post('/discountMember',function(req,res){ var sessionCode = req.body.sessionCode; var no_bon = req.body.no_bon; var membershipCode = req.body.membershipCode; if(sessionCode == null || sessionCode == undefined || sessionCode == ''){ res.json({"message":"err.. no params s_c rec"}); }else{ if(no_bon == null || no_bon == undefined || no_bon == ''){ res.json({"message":"err.. no params n_b rec"}); }else{ if(membershipCode == null || membershipCode == undefined || membershipCode == ''){ res.json({"message":"err.. no params m_c rec"}); }else{ var query = "select role.id_role as id_role from `session` join `user` on session.id_user=user.id_user join role on role.id_role=user.id_role where session.session_code='"+sessionCode+"'"; connection.query(query,function(err,rows){ if(err){ res.json({"message":"err.. error on session","query":query}); }else{ if(rows.length == 1){ if(rows[0].id_role == 2 || rows[0].id_role == 1){ var q012 = "select discount,no_bon from `order` where no_bon='"+no_bon+"'"; connection.query(q012,function(err,rows){ if(err){ res.json({"message":"err.. on selecting disc st1"}); }else{ if(rows.length>0){ if(rows[0].discount == null || rows[0].discount == undefined || rows[0].discount == ''){ //ambil jumlah discount dulu di membership code var q2 = "select discount from `membership` where membership_code='"+membershipCode+"'"; connection.query(q2,function(err,rows){ if(err){ res.json({"message":"err.. error selecting discount"}); }else{ if(rows.length>0){ var discount = rows[0].discount; //pending var q3 = "select jumlah_bayar from `order` where no_bon = '"+no_bon+"'"; connection.query(q3,function(err,rows){ if(err){ res.json({"message":"err.. error on selecting jumlah Bayar"}); }else{ if(rows.length>0){ var jumlahBayar = rows[0].jumlah_bayar; var afterDisc = jumlahBayar-(jumlahBayar*discount/100); var q4 = "update `order` set discount="+discount+",harga_bayar_fix="+afterDisc+",jumlah_bayar="+afterDisc+" where no_bon='"+no_bon+"'"; connection.query(q4,function(err,rows){ if(err){ res.json({"message":"err.. error on updating"}); }else{ res.json({"message":"err.. success adding discount","priceAfterDiscount":afterDisc,"discount":discount}); } }); }else{ res.json({"message":"Err.. no rows absbas","q3":q3}); } } }); }else{ res.json({"message":"err.. no rows","q2":q2}); } } }); }else{ res.json({"message":"err.. have already discounted"}); } }else{ res.json({"message":"err.. no rows on order with given n_b"}); } } }); }else{ res.json({"message":"err.. you have no authorize to do this action"}); } }else{ res.json({"message":"err... rows length not equal to 1"}); } } }); } } } }); } module.exports = discountMember;
import React from 'react'; import Home from './Home.js'; import Login from './Login.js'; import PointInTime from './PointInTime.js'; import Vispdat from './VISPDAT.js'; import Refuse from './Refuse.js'; import { Actions, Scene } from 'react-native-router-flux'; /** * Order of rendering is based on index of Child scene. * We set hideNavBar to true to prevent that ugly default * header. We can enable and style when we need to. */ export default Actions.create( <Scene key="root"> <Scene key="login" component={Login} hideNavBar={true} /> <Scene key="home" component={Home} hideNavBar={true} /> <Scene key="pointInTime" component={PointInTime} hideNavBar={true} /> <Scene key="vispdat" component={Vispdat} hideNavBar={true} /> <Scene key="refuse" component={Refuse} hideNavBar={true} /> </Scene> );
/*global Showdown*/ describe('$showdown', function () { 'use strict'; beforeEach(module('pl.itcrowd.services')); it('should be possible to inject initialized $showdown converter', inject(function ($showdown) { expect($showdown).not.toBeUndefined(); })); it('should be instance of $showdown.converter', inject(function ($showdown) { expect($showdown instanceof Showdown.converter).toBeTruthy(); })); });
define(function () { var exports = {}; /** * Hashes string with a guarantee that if you need to hash a new string * that contains already hashed string at it's start, you can pass only * added part of that string along with the hash of already computed part * and will get correctly hash as if you passed full string. * * @param {string} str * @param {number=} hash * @return {number} */ exports.hash = function (str, hash) { hash = hash || 5381; // alghorithm by Dan Bernstein var i = -1, length = str.length; while(++i < length) { hash = ((hash << 5) + hash) ^ str.charCodeAt(i); } return hash; }; var entityDecoder = document.createElement('div'); /** * Correctly decodes all hex, decimal and named entities * @param {string} text * @return {string} */ exports.decodeHtmlEntities = function(text){ return text.replace(/&(?:#(x)?(\d+)|(\w+));/g, function(match, hexFlag, decOrHex, name) { if(decOrHex) { return String.fromCharCode(parseInt(decOrHex, hexFlag ? 16 : 10)); } switch(name) { case 'lt': return '<'; case 'gt': return '>'; case 'amp': return '&'; case 'quote': return '"'; default: entityDecoder.innerHTML = '&' + name + ';'; return entityDecoder.textContent; } }); }; /** * Calculates shallow difference between two object * @param {Object} one * @param {Object} other * @return {Object} */ exports.shallowObjectDiff = function(one, other) { // since we will be calling setAttribute there is no need to // differentiate between changes and additions var set = {}, removed = [], haveChanges = false, keys = Object.keys(one), length, key, i; // first go through all keys of `one` for(i = 0, length = keys.length; i < length; ++i) { key = keys[i]; if(other[key] != null) { if(one[key] !== other[key]) { set[key] = other[key]; haveChanges = true; } } else { removed.push(key); haveChanges = true; } } // then add all missing from the `other` into `one` keys = Object.keys(other); for(i = 0, length = keys.length; i < length; ++i) { key = keys[i]; if(one[key] == null) { set[key] = other[key]; haveChanges = true; } } return haveChanges ? { set: set, removed: removed } : false; }; return exports; });
version https://git-lfs.github.com/spec/v1 oid sha256:558005fd55405d3069b06849812a921274543d712676f42ad4a8c122034c02e4 size 819
let allExpenses exports.up = (knex, Promise) => { return knex('expenses').select('*') .then(expenses => { allExpenses = expenses return knex.schema.createTable('expense_items', (table) => { table.increments('id').primary().notNullable() table.integer('expense_id').notNullable().references('id').inTable('expenses') table.integer('position').notNullable() table.decimal('preTaxAmount').notNullable() table.decimal('taxrate').notNullable() table.text('description') table.index('expense_id') }) }) .then(() => { // this is necessary BEFORE creating the expense items because knex // drops the expenses table and then recreates it (foreign key problem). console.log('Dropping "preTaxAmount" and "taxrate" columns in expenses') return knex.schema.table('expenses', table => { table.dropColumn('preTaxAmount') table.dropColumn('taxrate') }) }) .then(() => { console.log('Migrating ' + allExpenses.length + ' expenses to items') return Promise.all( allExpenses.map(expense => createExpenseItem(knex, expense)) ) }) } exports.down = (knex, Promise) => { return knex.schema.dropTableIfExists('expense_items') } function createExpenseItem(knex, expense) { return knex('expense_items') .insert({ expense_id: expense.id, position: 0, preTaxAmount: expense.preTaxAmount, taxrate: expense.taxrate, description: '' }) }
var express = require('express'); var app = express(); var path = require('path'); var session = require('express-session'); var bodyParser = require('body-parser') var fs = require('fs'); app.use(express.static(path.join(__dirname, 'public'))); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.use(session({ secret: 'angular_tutorial', resave: true, saveUninitialized: true, })); var Db = require('mongodb').Db; var Connection = require('mongodb').Connection; var Server = require('mongodb').Server; var ObjectID = require('mongodb').ObjectID; var db = new Db('tutor', new Server("localhost", 27017, {safe: true}, {auto_reconnect: true}, {})); db.open(function(){ console.log("mongo db is opened!"); db.collection('notes', function(error, notes) { db.notes = notes; }); db.collection('sections', function(error, sections) { db.sections = sections; }); }); app.get("/notes", function(req,res) { db.notes.find(req.query).toArray(function(err, items) { res.send(items); }); }); app.post("/notes", function(req,res) { db.notes.insert(req.body); res.end(); }); app.get("/sections", function(req,res) { db.sections.find(req.query).toArray(function(err, items) { res.send(items); }); }); app.get("/checkUser", function(req,res) { if (req.query.user.length>2) { res.send(true); } else { res.send(false); } }); app.post("/sections/replace", function(req,resp) { // do not clear the list if (req.body.length==0) { resp.end(); } // this should be used only for reordering db.sections.remove({}, function(err, res) { if (err) console.log(err); db.sections.insert(req.body, function(err, res) { if (err) console.log("err after insert",err); resp.end(); }); }); }); app.listen(3000);
var Screen = require('./basescreen'); var Game = require('../game'); var helpScreen = new Screen('Help'); // Define our winning screen helpScreen.render = function (display) { var text = 'jsrogue help'; var border = '-------------'; var y = 0; display.drawText(Game.getScreenWidth() / 2 - text.length / 2, y++, text); display.drawText(Game.getScreenWidth() / 2 - text.length / 2, y++, border); display.drawText(0, y++, 'The villagers have been complaining of a terrible stench coming from the cave.'); display.drawText(0, y++, 'Find the source of this smell and get rid of it!'); y += 3; display.drawText(0, y++, '[h or Left Arrow] to move left'); display.drawText(0, y++, '[l or Right Arrow] to move right'); display.drawText(0, y++, '[j or Down Arrow] to move down'); display.drawText(0, y++, '[k or Up Arrow] to move up'); display.drawText(0, y++, '[,] to pick up items'); //display.drawText(0, y++, '[d] to drop items'); //display.drawText(0, y++, '[e] to eat items'); //display.drawText(0, y++, '[w] to wield items'); //display.drawText(0, y++, '[W] to wield items'); //display.drawText(0, y++, '[x] to examine items'); display.drawText(0, y++, '[i] to view and manipulate your inventory'); display.drawText(0, y++, '[;] to look around you'); display.drawText(0, y++, '[?] to show this help screen'); y += 3; text = '--- press any key to continue ---'; display.drawText(Game.getScreenWidth() / 2 - text.length / 2, y++, text); }; helpScreen.handleInput = function (inputType, inputData) { // Switch back to the play screen. this.getParentScreen().setSubScreen(undefined); }; module.exports = helpScreen;
requirejs(['helper/util'], function(util){ });
// 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: 7.6.1-4-7 description: > Allow reserved words as property names by set function within an object, verified with hasOwnProperty: while, debugger, function includes: [runTestCase.js] ---*/ function testcase() { var test0 = 0, test1 = 1, test2 = 2; var tokenCodes = { set while(value){ test0 = value; }, get while(){ return test0 }, set debugger(value){ test1 = value; }, get debugger(){ return test1; }, set function(value){ test2 = value; }, get function(){ return test2; } }; var arr = [ 'while' , 'debugger', 'function' ]; for(var p in tokenCodes) { for(var p1 in arr) { if(arr[p1] === p) { if(!tokenCodes.hasOwnProperty(arr[p1])) { return false; }; } } } return true; } runTestCase(testcase);
var View = require('ampersand-view'); var templates = require('../templates'); module.exports = View.extend({ template: templates.includes.scholarship, bindings: { 'model.field': '[role=field]', 'model.slots': '[role=slots]', 'model.holder': '[role=holder]', 'model.type': '[role=type]', 'model.link': { type: 'attribute', role: 'link', name: 'href' }, 'model.scholarshipIdUpperCase': '[role=link]', 'model.releaseDateFormated': '[role=release-date]', 'model.closeDateFormated': '[role=close-date]' } });