text
stringlengths 2
6.14k
|
|---|
describe('GiftCard Purchase Workflow', function () {
'use strict';
function waitForUrlToChangeTo (urlRegex) {
var currentUrl;
return browser.getCurrentUrl().then(function storeCurrentUrl (url) {
currentUrl = url;
}
).then(function waitForUrlToChangeTo () {
return browser.wait(function waitForUrlToChangeTo () {
return browser.getCurrentUrl().then(function compareCurrentUrl (url) {
return urlRegex === url;
});
});
}
);
}
it('should load first screen', function () {
browser.get('#/cadeau/vinibar/formule?test=true');
expect(browser.getTitle()).toEqual('Cadeau | vinibar');
});
it('should choose gift_card and add some credit', function () {
element(by.css('#init-card')).click();
element(by.model('gift.order.credits')).sendKeys('15');
element(by.css('#delivery-postcard')).click();
element(by.css('.btn-block-primary')).click();
});
it('should fill lucky boy & giver infos', function () {
expect(browser.getCurrentUrl()).toEqual('http://0.0.0.0:9001/#/cadeau/vinibar/infos?test=true');
element(by.cssContainingText('option', 'Mme')).click();
element(by.model('gift.order.receiver_first_name')).sendKeys('John');
element(by.model('gift.order.receiver_last_name')).sendKeys('Mc Test');
element(by.model('gift.order.receiver_email')).sendKeys('felix+test' + Math.random() * 1000 + '@vinify.co');
element(by.model('gift.order.message')).sendKeys('un cadeau pour toi !');
element(by.model('gift.order.comment')).sendKeys('Il aime le chocolat');
element.all(by.css('.gift-checkbox')).first().click();
element(by.model('gift.order.receiver_address.first_name')).sendKeys('John');
element(by.model('gift.order.receiver_address.last_name')).sendKeys('Mc Test');
element(by.model('gift.order.receiver_address.street')).sendKeys('12 rue boinod');
element(by.model('gift.order.receiver_address.zipcode')).sendKeys('75018');
element(by.model('gift.order.receiver_address.city')).sendKeys('Paris');
element(by.css('#is-not-client')).click();
element(by.model('gift.giver.first_name')).sendKeys('John');
element(by.model('gift.giver.last_name')).sendKeys('MacTest');
element(by.model('gift.giver.email')).sendKeys('felix+test' + Math.random() * 1000 + '@vinify.co');
element(by.model('gift.giver.password')).sendKeys('wineisgood');
element(by.css('.btn-block-primary')).click();
});
it('should fill lucky boy & giver infos', function () {
// make payment
element(by.model('number')).sendKeys('4242424242424242');
element(by.model('cvc')).sendKeys('001');
element(by.cssContainingText('option', 'Mai')).click();
element(by.cssContainingText('option', '2017')).click();
element.all(by.css('.btn-block-primary')).last().click();
waitForUrlToChangeTo('http://0.0.0.0:9001/#/remerciement/cadeau?print=false');
});
});
|
var structaaa_1_1sqrt__type =
[
[ "type", "structaaa_1_1sqrt__type.html#a5843af2f9db00396bf14cf79cabecac0", null ]
];
|
import React from 'react';
import Wrapper, {
Header,
Content,
Footer,
Sidebar,
SidebarItem,
MainContent,
MainItem,
} from '../components/common/layouts/Container/Container';
import Menu from '../components/Menu/Menu';
import Filter from '../components/Filter/Filter';
const Main = () =>
<Wrapper>
<Header>
<Menu />
</Header>
<Content>
<Sidebar>
<SidebarItem>
<Filter />
</SidebarItem>
</Sidebar>
<MainContent>
<MainItem>
<div>git checkout step-2</div>
</MainItem>
</MainContent>
</Content>
<Footer>
<div>hex22a</div>
</Footer>
</Wrapper>;
export default Main;
|
var path = require("path");
module.exports = {
watch: false,
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
],
postLoaders: [{ //
test: /\.js$/,
exclude: /(test|node_modules|bower_components|test_helpers)\//,
loader: 'istanbul-instrumenter'
}],
preLoaders: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, "src")
],
loader: "eslint-loader"
}
]
},
resolve: {
// add bower components and main source to resolved
root: [path.join(__dirname, 'src/main'),
path.join(__dirname, 'src/test_helpers')]
}
};
|
recipes['Fiery Ginger Ale (2L)'] = {
type: 'Fiery Ginger Ale (2L)',
volume: '2L',
brewTime: [
'2 days',
],
ingredients: [
'1.5 oz. finely grated fresh ginger (the younger the better; microplane suggested)',
'6 oz. table sugar',
'7.5 cups filtered water',
'1/8 teaspoon (should be around 750mg) champagne yeast (Red Star Premier Blanc formerly known as Pastuer Champagne)',
'2 tablespoons freshly squeezed lemon juice',
'StarSan soln.',
],
equipmentMisc: [
'2L PET bottle (i.e. plastic soda bottle)',
],
recipe: [
'Clean 2L PET bottle with StarSan soln.',
'Place ginger, sugar, and 1/2 cup of the water into a saucepan over medium-high heat. Stir until the sugar dissolves. Remove from heat, cover, and allow to steep for 1 hour.',
'Pour the syrup through a fine strainer, cheese cloth over a bowl, or t-shirt, using pressure to get all the juice out of the mixture. Rapidly chill in an ice bath and stir until the mixture reaches 70 degrees F.',
'Pour the syrup into a 2L PET bottle and add yeast, lemon juice, and remaining 7 cups of water. Shake vigorously for five minutes. Let sit in a dark place at room temperature.',
'At 2 days, burp and refrigerate bottle. Allow 24 hours for yeast to fall asleep, then siphon off into another StarSan\'d 2L soda bottle, leaving the flocculated yeast at the bottom of the first bottle. SG check. Keep chilled and drink quickly; the carbonation will not last long -- 3 days is safe',
],
fdaIngredients: 'water, sugar, ginger, lemon juice, yeast',
};
|
const murmur = require('murmurhash-native/stream')
function createHash () {
// algorithm, seed and endianness - do affect the results!
return murmur.createHash('murmurHash128x86', {
seed: 0,
endianness: 'LE'
})
}
module.exports = createHash
|
var React = require('react');
var Animation = require('react-addons-css-transition-group');
var NBButton = require('./NBItems').NBButton;
var NBTitle = require('./NBItems').NBTitle;
var NBEmpty = require('./NBItems').NBEmpty;
var Navbar = React.createClass({
render: function() {
return (
<div className="navbar">
<div className="navbar-inner">
<NBButton path="/" icon="icon-back" position="left"/>
<NBTitle text="Settings"/>
<NBEmpty position="right"/>
</div>
</div>
)
}
});
var Button = React.createClass({
render: function() {
return (
<div>
</div>
)
}
});
var PageContent = React.createClass({
componentWillMount: function() {
},
render: function() {
return (
<div className="page">
<div className="page-content">
<Navbar/>
<Animation transitionName={{
appear: "slideLeft-enter",
leave: "slideLeft-leave"
}}
transitionEnterTimeout={1000} transitionLeaveTimeout={500} transitionAppearTimeout={500}
transitionAppear={true} transitionLeave={true}>
<div className="content-block">
Content some text alalala ashdihaish uasodj iioash iodhias
</div>
</Animation>
</div>
</div>
)
}
});
module.exports = PageContent;
|
module.exports = {
up: (queryInterface, Sequelize) =>
queryInterface.createTable('Groups', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
name: {
type: Sequelize.STRING,
allowNull: false,
},
createdBy: {
type: Sequelize.STRING,
allowNull: false,
},
description: {
type: Sequelize.STRING,
},
type: {
type: Sequelize.STRING,
allowNull: false,
default: 'public'
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
}),
down: queryInterface =>
queryInterface.dropTable('Groups'),
};
|
var fs = require('fs');
var url = require('url');
var mime = require('mime');
var path = require('path');
exports.css = function(s) {
var pathname = url.parse(s.request.url).pathname;
var path = 'g' + pathname + '.css';
var locale = s.strings('locale.json');
var errors = s.strings('errors.json');
var content = s.renderText(path, locale, true);
if (content == null) {
s.response.writeHead(404, {
'Content-Type': 'text/html'
});
s.response.end(s.renderText('g/error.html', {
errorMessage: errors.stylesheetMissing,
errorInfo: pathname
}));
} else {
s.response.writeHead(200, {
'Content-Type': 'text/css'
});
s.response.end(content);
}
}
exports.js = function(s) {
var pathname = url.parse(s.request.url).pathname;
var path = 'g' + pathname + '.js';
var errors = s.strings('errors.json');
var content = s.renderText(path, {}, true);
if (content == null) {
s.response.writeHead(404, {
'Content-Type': 'text/html'
});
s.response.end(s.renderText('g/error.html', {
errorMessage: errors.scriptMissing,
errorInfo: pathname
}));
} else {
s.response.writeHead(200, {
'Content-Type': 'application/javascript'
});
s.response.end(content);
}
};
exports.static = function(s) {
var pathname = url.parse(s.request.url).pathname;
var fileDir = path.resolve(__dirname , '..' , pathname.substring(1));
fs.stat(fileDir, function(err, stat) {
if (err) {
var errors = s.strings('errors.json');
s.response.writeHead(404, {
'Content-Type': 'text/html'
});
s.response.end(s.renderText('g/error.html', {
errorMessage: errors.staticFileMissing,
errorInfo: pathname
}, false));
} else {
var stream = fs.createReadStream(fileDir);
stream.on('open', function() {
s.response.writeHead(200, {
'Cache-Control': 'public, max-age=9000000',
'Content-Length': stat.size,
'Content-Type': mime.lookup(fileDir)
});
});
stream.on('data', function(data) {
s.response.write(data, null);
});
stream.on('error', function(err) {
console.log(err);
var errors = s.strings('errors.json');
s.response.end(errors.streamingError);
});
stream.on('end', function(data) {
s.response.end();
});
}
});
}
|
import React, { Component } from 'react';
import { SelectField, MenuItem } from 'fusionui-shared-components-react';
import PropTypes from 'prop-types';
import '../../FormField.scss';
import './FormSelectField.scss';
const style = {
width: '100%',
height: 30,
border: 'none',
backgroundColor: 'rgb(239, 239, 239)',
fontSize: 12,
};
class FormSelectField extends Component {
constructor(props) {
super(props);
this.state = {
value: props.value
};
}
componentWillReceiveProps(nextProps) {
this.setState({ value: nextProps.value });
}
handleChange = (ev, idx, value) => {
this.props.onChange(ev, value, this.props.onBlur);
this.setState({ value });
}
render() {
const { label, fchar, options } = this.props;
return (
<div className="form-field__wrapper form-select__wrapper">
<label className="form-field__label" htmlFor={ name }>{ label[fchar] || label.DEFAULT }</label>
<SelectField
style={ style }
menuStyle={ style }
selectedMenuItemStyle={ { fontWeight: 'bold', color: '#000' } }
value={ this.state.value }
onChange={ this.handleChange }
underlineStyle={ { marginBottom: -8, width: '100%' } }
labelStyle={ { paddingLeft: 10, lineHeight: '40px', height: 40 } }
>
<MenuItem value="" primaryText="Select..." />
{ options.map(option => <MenuItem value={ option.value } key={ option.value } primaryText={ option.text } />) }
</SelectField>
</div>
);
}
}
FormSelectField.propTypes = {
fchar: PropTypes.string.isRequired,
label: PropTypes.object,
options: PropTypes.arrayOf(
PropTypes.shape({
text: PropTypes.string,
value: PropTypes.string
})
).isRequired,
onChange: PropTypes.func.isRequired,
onBlur: PropTypes.func.isRequired,
value: PropTypes.string
};
FormSelectField.defaultProps = {
errorText: '',
label: {},
value: ''
};
export default FormSelectField;
|
// this will build and serve the examples
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: {
app: './examples/js/app.js',
vendors: ['webpack-dev-server/client?http://localhost:3004', 'webpack/hot/only-dev-server']
},
debug: true,
devtool: '#eval-source-map',
output: {
path: path.join(__dirname, 'examples'),
filename: '[name].bundle.js'
},
serverConfig: {
port: '3004',// server port
publicPath: '/',// js path
contentBase: 'examples/'//web root path
},
resolve: {
extensions: ['', '.js', '.jsx'],
alias: {
'react-bootstrap-table': path.resolve(__dirname, './src')
}
},
module: {
preLoaders: [
{
test: /\.js$/,
exclude: [ /node_modules/, path.resolve(__dirname, './src/filesaver.js') ],
loader: 'eslint'
}
],
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel']
}, {
test: /\.css$/, loader: 'style-loader!css-loader'
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
|
'use strict';
var mongoose = require('mongoose'),
async = require('async');
var DeleteChildrenPlugin = function(schema, options) {
schema.pre('remove', function(done) {
var parentField = options.parentField;
var childModel = options.childModel;
if (!parentField) {
var err = new Error('parentField not defined');
return done(err);
}
if (!childModel) {
var err = new Error('childModel not defined');
return done(err);
}
// must delete all campuses
console.log('model::', parentField, '>', childModel, '::pre::remove::enter');
var Model = mongoose.model(childModel);
var conditions = {};
conditions[parentField] = this._id;
Model.find(conditions).exec(function(err, results) {
console.log('model::', parentField, '>', childModel, '::pre::remove::find::enter');
if (err) {
return done(err);
}
async.each(results, function(campus, deleteNextModel) {
console.log('model::', parentField, '>', childModel, '::pre::remove::find::each::enter');
campus.remove(deleteNextModel);
}, done);
});
});
};
var ParentAttachPlugin = function(schema, options) {
schema.pre('save', function(doneAttaching) {
var doc = this;
var parentField = options.parentField;
var parentModel = options.parentModel;
var childCollection = options.childCollection;
if (!doc[parentField]) return doneAttaching();
var Parent = mongoose.model(parentModel);
var push = {};
push[childCollection] = doc._id;
Parent.findByIdAndUpdate(doc[parentField], {
$push: push
}).exec(function(err) {
if (err) {
console.log('plugin::ParentAttachPlugin::schema::pre::save::findByIdAndUpdate::err', err);
return doneAttaching(err);
}
console.log('plugin::ParentAttachPlugin::schema::pre::save::findByIdAndUpdate::exit');
doneAttaching();
});
});
schema.pre('remove', function(doneRemoving) {
var doc = this;
var parentField = options.parentField;
var parentModel = options.parentModel;
var childCollection = options.childCollection;
if (!doc[parentField]) return doneRemoving();
var Parent = mongoose.model(parentModel);
var pull = {};
pull[childCollection] = doc._id;
Parent.findByIdAndUpdate(doc[parentField], {
$pull: pull
}).exec(function(err) {
if (err) {
console.log('plugin::ParentAttachPlugin::schema::pre::save::findByIdAndUpdate::err', err);
return doneRemoving(err);
}
console.log('plugin::ParentAttachPlugin::schema::pre::save::findByIdAndUpdate::exit');
doneRemoving();
});
});
};
exports.parentAttach = ParentAttachPlugin;
exports.deleteChildren = DeleteChildrenPlugin;
|
import CoreClient from './CoreClient';
export default CoreClient;
|
import merge from 'webpack-merge'
import { isString } from '../../utils'
export default (config, settings) => {
if (isString(settings)) {
return merge.smart(config, { entry: [settings] })
}
if (Array.isArray(settings)) {
return merge.smart(config, { entry: settings })
}
throw new Error('Unexpected webpack entry value')
}
|
// I am well aware this could be so very much tidier,
// we are going fo basic functionality first.
// will tidy up later.
var boilerplate = function() {
this.popup = function(html) {
$('#popup').html(html);
// add X
var close = '<img id="close" src="libs/icons/close.png"></img>';
$('#popup').append(close);
$('#close').on('click', function() { $('#magic_positioning_table').hide(); $('#overlay').hide(); });
// add overlay
$('#overlay').show();
$('#magic_positioning_table').show();
};
// for ajax popup use: $('#popup').load(URL, function(html) { popup(html); });
};
$(document).ready(function() {
// add in hamburger menu to open aside if aside is present
if ($('#aside').length>0) {
var hamburger = '<img id="hamburger" src="libs/icons/hamburger.png"></img>';
$('#header').append(hamburger);
$('#hamburger').on('click', function() {
if (!$('#aside').is(':visible')) {
$('#aside').show();
$('#header, #footer, #main').transition({ 'left': $('#aside').width() }, 300);
} else {
$('#header, #footer, #main').transition({ 'left': '0' }, 300, function() {
$('#aside').hide(); // in case there is no BG color on the main area's
});
}
});
// also swipe right to open
$$('#main').swipeRight(function(){
if (!$('#aside').is(':visible')) {
$('#aside').show();
$('#header, #footer, #main').transition({ 'left': $('#aside').width() }, 300);
}
});
$$('#main, #aside').swipeLeft(function() {
if ($('#aside').is(':visible')) {
$('#header, #footer, #main').transition({ 'left': '0' }, 300, function() {
$('#aside').hide(); // in case there is no BG color on the main area's
});
}
});
}
// add in the modal popup div (and overlay)
var popup = '<div id="popup" class="white"></div>';
var overlay = '<div id="overlay"></div>';
var magic_positioning_table = '<table id="magic_positioning_table">'+
'<tr><td colspan="4"></td></tr>' +
'<tr><td></td><td class="popupcell"></td><td></td></tr>' +
'<tr><td colspan="4"></td></tr>' +
'</table>';
$('body').append(popup);
$('body').append(overlay);
$('body').append(magic_positioning_table);
$('#popup').appendTo('#magic_positioning_table td.popupcell');
// apply the landscape-fullscreen class - removal of which
// allows turning off the full screen on rotate behaviour
// HAVE TURNED THIS OFF - CONFUSING AND ALSO CAUSES ISSUE WHEN NO ASSIDE - BUT A NEAT IDEA STILL
//$('#header, #footer, #main, #aside, #popup').addClass('landscape-fullscreen');
});
|
import React from 'react';
import { render as mount } from 'enzyme';
import { Provider as ContextProvider } from '../common/context';
import Message from './Message';
describe('Message', () => {
function render(message, context) {
// need the spans otherwise the document has 0 html elements in it.
return mount(
<span>
<ContextProvider value={context}>{message}</ContextProvider>
</span>,
);
}
it('translates the given message', () => {
const translateAsParts = jest.fn(() => [
{ dangerous: false, value: 'translated ' },
{ dangerous: true, value: 'value' },
]);
const context = { translateAsParts };
const component = render(<Message>message.id</Message>, context);
expect(translateAsParts).toHaveBeenCalledTimes(1);
expect(translateAsParts).toHaveBeenCalledWith('message.id', {});
expect(component.text()).toEqual('translated value');
});
it('translates with parameters', () => {
const translateAsParts = jest.fn((key, params) => [
{ dangerous: false, value: 'translated value ' },
{ dangerous: true, value: params.test },
]);
const context = { translateAsParts };
const component = render(<Message params={{ test: 'hello' }}>message.id</Message>, context);
expect(translateAsParts).toHaveBeenCalledTimes(1);
expect(translateAsParts).toHaveBeenCalledWith('message.id', { test: 'hello' });
expect(component.text()).toEqual('translated value hello');
});
it('translates with sanitized html', () => {
const html = '<h1>this is a heading<b>with bold</b></h1>';
const translateAsParts = jest.fn(() => [{ dangerous: false, value: html }]);
const context = { translateAsParts };
const component = render(<Message>message.id</Message>, context);
expect(component.html()).toBe(
'<h1>this is a heading<b>with bold</b></h1>',
);
});
it('allows to translate things as html', () => {
const translateAsParts = jest.fn(() => [
{ dangerous: false, value: '<h1>some safe html</h1>' },
{ dangerous: true, value: '<span>some sketchy user input</span>' },
]);
const context = { translateAsParts };
const component = render(<Message dangerouslyTranslateInnerHTML="message.id" />, context);
expect(component.html()).toBe(
'<span><h1>some safe html</h1></span><span>some sketchy user input</span>',
);
});
it('allows to translate into a string', () => {
const translateAsParts = jest.fn(() => [
{ dangerous: false, value: 'just some ' },
{ dangerous: true, value: 'text' },
]);
const context = { translateAsParts };
const component = render(<Message asString>message.id</Message>, context);
expect(component.html()).toBe('just some text');
});
});
|
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var sortColors = function(nums) {
nums.sort();
};
|
define(function (require) {
'use strict';
/**
* Module dependencies
*/
var defineComponent = require('flight/lib/component');
var tweetItems = require('component/tweet_items');
var templates = require('templates');
var _ = require('underscore');
/**
* Module exports
*/
return defineComponent(searchColumn);
/**
* Module function
*/
function searchColumn() {
this.defaultAttrs({
query: null,
// selectors
titleSelector: '.title',
tweetHolderSelector: '.td-tweet-holder'
});
this.onTitleChangeRequested = function () {
this.trigger('uiShowSearchPrompt');
};
this.onSearchPromptSave = function (ev, data) {
console.log('New search query: ', data.query);
this.attr.query = data.query;
this.update();
};
this.onRemove = function (ev, data) {
ev.stopPropagation();
this.teardown();
// Reraise with tag annotation
this.trigger('uiRemoveColumnRequested', { tag: this.attr.tag });
};
this.render = function () {
this.node.innerHTML = templates.column();
// Not very pretty ...
this.select('titleSelector')[0].childNodes[0].bind(
'textContent', this.model, 'title');
this.update();
};
this.update = function () {
this.model.title = 'Search: ' + this.attr.query;
console.log('Model for', this.node, ':', this.model);
this.requestStream();
Platform.performMicrotaskCheckpoint();
};
this.after('initialize', function () {
this.tag = _.uniqueId('search-');
this.model = {};
this.requestStream = function () {
this.trigger('dataSearchStreamRequested', {
tag: this.tag,
query: this.attr.query
});
};
this.render();
this.on('click', {
titleSelector: this.onTitleChangeRequested
});
this.on('uiSaveSearchPrompt', this.onSearchPromptSave);
this.on('uiRemoveColumnRequested', this.onRemove);
tweetItems.attachTo(this.select('tweetHolderSelector'), {
tag: this.tag
});
});
}
});
|
({
block : 'page',
title : 'bem-components: spin',
mods : { theme : 'islands' },
head : [
{ elem : 'css', url : 'gemini.css' }
],
content : [
{ tag : 'h2', content : 'islands' },
['xs', 's', 'm', 'l', 'xl'].map(function(size){
return {
tag : 'p',
content : [
size,
{ tag : 'br' },
{
block : 'spin',
mods : { paused : true, theme : 'islands', visible : true, size : size },
cls : 'islands-' + size
}
]
}
})
]
});
|
'use strict';
/* App Module */
var phonecatApp = angular.module('phonecatApp', [
'ngRoute',
'phonecatAnimations',
'phonecatControllers',
'phonecatFilters',
'phonecatServices',
]);
phonecatApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/phones', {
templateUrl: 'partials/phone-list.html',
controller: 'PhoneListCtrl'
}).
when('/phones/:phoneId', {
templateUrl: 'partials/phone-detail.html',
controller: 'PhoneDetailCtrl'
}).
otherwise({
redirectTo: '/phones'
});
}]);
|
import ApplicationSerializer from './application';
export default ApplicationSerializer.extend({
normalize: function(type, hash) {
delete hash['author_email'];
delete hash['author_name'];
delete hash['branch'];
delete hash['committed_at'];
delete hash['committer_email'];
delete hash['committer_name'];
delete hash['compare_url'];
delete hash['duration'];
delete hash['event_type'];
delete hash['finished_at'];
delete hash['job_ids'];
delete hash['message'];
delete hash['number'];
delete hash['pull_request'];
delete hash['pull_request_number'];
delete hash['pull_request_title'];
delete hash['started_at'];
return this._super(type, hash);
}
});
|
const { decode, parse } = require('./response')
describe('Protocol > Requests > ListOffsets > v1', () => {
test('response', async () => {
const data = await decode(Buffer.from(require('../fixtures/v1_response.json')))
expect(data).toEqual({
responses: [
{
topic: 'test-topic-16e956902e39874d06f5-91705-2958a472-e582-47a4-86f0-b258630fb3e6',
partitions: [{ partition: 0, errorCode: 0, timestamp: '1543343103774', offset: '0' }],
},
],
})
await expect(parse(data)).resolves.toBeTruthy()
})
})
|
import React from 'react'
import { Header } from 'components/Header/Header'
import { IndexLink, Link } from 'react-router'
import { shallow } from 'enzyme'
describe('(Component) Header', () => {
let _wrapper
beforeEach(() => {
_wrapper = shallow(<Header />)
})
it('Renders a welcome message', () => {
const welcome = _wrapper.find('h1')
expect(welcome).to.exist
expect(welcome.text()).to.match(/React Redux Starter Kit/)
})
describe('Navigation links...', () => {
it('Should render a Link to home route', () => {
expect(_wrapper.contains(
<IndexLink activeClassName='route--active' to='/'>
Home
</IndexLink>
)).to.be.true
})
it('Should render a Link to Counter route', () => {
expect(_wrapper.contains(
<Link activeClassName='route--active' to='/counter'>
Counter
</Link>
)).to.be.true
})
})
})
|
define([],
function() {
'use strict';
/**
* Prints a debugging console message for a shortcut
*
* @param {Shortcut} shortcut - shortcut object
*/
var printDebugConsoleMessage = function(shortcut) {
console.log('Shortcut "' + shortcut.name + '" triggered with key "' + shortcut.key + '"', shortcut);
};
return {
printMessage: printDebugConsoleMessage
};
});
|
module.exports = function(app) {
var _env = app.get('env');
var _log = app.lib.logger;
var _mongoose = app.core.mongo.mongoose;
var _group = 'MODEL:oauth.authcodes';
var Schema = {
authCode : {type: String, required: true, unique: true, alias: 'authCode'},
clientId : {type: String, alias: 'clientId'},
userId : {type: String, required: true, alias: 'userId'},
expires : {type: Date, alias: 'expires'}
};
var AuthCodesSchema = app.core.mongo.db.Schema(Schema);
// statics
AuthCodesSchema.method('getAuthCode', function(authCode, cb) {
var AuthCodes = _mongoose.model('Oauth_AuthCodes');
AuthCodes.findOne({authCode: authCode}, cb);
});
AuthCodesSchema.method('saveAuthCode', function(code, clientId, expires, userId, cb) {
var AuthCodes = _mongoose.model('Oauth_AuthCodes');
if (userId.id)
userId = userId.id;
var fields = {
clientId : clientId,
userId : userId,
expires : expires
};
AuthCodes.update({authCode: code}, fields, {upsert: true}, function(err) {
if (err)
_log.error(_group, err);
cb(err);
});
});
return _mongoose.model('Oauth_AuthCodes', AuthCodesSchema);
};
|
/*
The MIT License (MIT)
Copyright (c) 2017 Adrian Paul Nutiu <nutiuadrianpaul@gmail.com>
http://adrianpaulnutiu.me/
*/
// ==UserScript==
// @name kartwars.io Bot
// @namespace https://github.com/kmataru/kartwars.io-bot/raw/pre-release/src/DracoolaArt.Bot.Kartwars/
// @version 0.7.475
// @description kartwars.io Bot
// @author Adrian Paul Nutiu
// @match http://kartwars.io/
// @icon https://assets-cdn.github.com/images/icons/emoji/unicode/1f697.png
// @updateURL https://github.com/kmataru/kartwars.io-bot/raw/pre-release/src/DracoolaArt.Bot.Kartwars/bot.user.js
// @downloadURL https://github.com/kmataru/kartwars.io-bot/raw/pre-release/src/DracoolaArt.Bot.Kartwars/bot.user.js
// @supportURL https://github.com/kmataru/kartwars.io-bot/issues
// @require https://gist.githubusercontent.com/eligrey/384583/raw/96dd5cd2fd6b752aa3ec0630a003e7a920313d1a/object-watch.js
// @require https://cdn.rawgit.com/stacktracejs/stacktrace.js/master/dist/stacktrace.min.js
// @grant none
// ==/UserScript==
/// <reference path="lib/_references.ts" />
// tslint:disable-next-line:no-unused-expression
!function (window, document) {
var baseURL = 'http://scripts.local.com/';
var baseScriptPath = baseURL + "lib/";
var baseStylePath = baseURL + "style/";
window.botSettings = {
LOAD_DEBUG_SCRIPTS: false,
LOAD_GIT_SCRIPTS: true,
};
window.GM_info = GM_info;
function initLoader(baseURL, baseScriptPath) {
var remoteScript = document.createElement('script');
remoteScript.src = baseScriptPath + "Loader.js?time=" + (+new Date());
remoteScript.onload = function () {
setTimeout(function () {
(new DracoolaArt.KartwarsBot.Loader(baseURL, baseScriptPath)).boot();
}, 0);
};
document.body.appendChild(remoteScript);
}
function loadStylesheet(fileURL) {
fileURL += "?time=" + (+new Date());
var remoteLink = document.createElement('link');
remoteLink.href = fileURL;
remoteLink.type = 'text/css';
remoteLink.rel = 'stylesheet';
remoteLink.media = 'screen,print';
remoteLink.onload = function () {
var jPlayButton = $('#play-btn');
jPlayButton.addClass('btn-none');
jPlayButton.after("<a href=\"#\" id=\"loading-bot\" class=\"btn btn-play btn-loading-bot\">Loading Bot. Please wait!</a>");
};
document.head.appendChild(remoteLink);
}
if (window.botSettings.LOAD_GIT_SCRIPTS) {
$.ajax({
url: 'https://api.github.com/repos/kmataru/kartwars.io-bot/git/refs/heads/pre-release',
cache: false,
dataType: 'jsonp'
}).done(function (response) {
var sha = response['data']['object']['sha'];
var baseURL = "https://cdn.rawgit.com/kmataru/kartwars.io-bot/" + sha + "/src/DracoolaArt.Bot.Kartwars/";
var baseScriptPath = baseURL + "lib/";
var baseStylePath = baseURL + "style/";
loadStylesheet(baseStylePath + "Main.min.css");
initLoader(baseURL, baseScriptPath);
}).fail(function () { });
}
else {
loadStylesheet(baseStylePath + "Main.min.css");
initLoader(baseURL, baseScriptPath);
}
}(window, document);
|
import Page from '../Page';
import './news.scss';
import RoomList from "../parts/RoomList";
export default class NewsPage extends Page {
indexAction() {
this.headerTitle = "新着・おすすめ";
var $switchPanel = $(`
<div class="switch-panel">
<div class="switch-btn selected new">
<span class="title">新着</span>
<span class="count">--</span>
<span class="ken">件</span>
</div>
<div class="switch-btn pickup">
<span class="title">おすすめ</span>
<span class="count">--</span>
<span class="ken">件</span>
</div>
</div>
`);
this.$main.append($switchPanel);
var $newCount = $switchPanel.find(".new .count");
var $pickupCount = $switchPanel.find(".pickup .count");
getPickupCount()
.then( count => $pickupCount.html(count) );
RoomList.findAll({new:1}, $newCount)
.then( $roomList => {
this.$contents.append($roomList);
});
var $pickupBtn = $switchPanel.find(".pickup");
var $newBtn = $switchPanel.find(".new");
$pickupBtn.on("click", () => {
$newBtn.removeClass("selected");
$pickupBtn.addClass("selected");
RoomList.findAll({pickup:1})
.then( $roomList => {
this.$contents.append($roomList);
});
});
$newBtn.on("click", () => {
$pickupBtn.removeClass("selected");
$newBtn.addClass("selected");
RoomList.findAll({new:1})
.then( $roomList => {
this.$contents.append($roomList);
});
});
}
}
function getPickupCount() {
return global.APP.api.ietopia.room.count({pickup:1})
}
|
"use strict";
const test = require("tape");
const aceyDeuceyGameEngine = require("../");
const getInitialGameState = aceyDeuceyGameEngine.getInitialGameState;
test("getInitialGameState", t => {
t.plan(1);
const gameState = {
board: [
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0},
{isPlayerOne: null, numPieces: 0}
],
isPlayerOne: true,
playerOne: {
initialPieces: 15,
barPieces: 0,
winningPieces: 0
},
playerTwo: {
initialPieces: 15,
barPieces: 0,
winningPieces:0
}
};
t.deepEqual(getInitialGameState(), gameState, "returns the correct gameState object");
});
|
'use strict';
(function(module) {
const splashView = {};
splashView.defaultView = function(){
$('#about').hide();
$('#map').css('z-index', -500);
$('form').fadeIn();
$('#splash-page').fadeIn();
}
module.splashView = splashView;
})(window);
$(function(){
$('#home').on('click', function(){
splashView.defaultView();
});
});
|
import Vue from 'vue'
import Router from 'vue-router'
import Resource from'vue-resource'
import { sync } from 'vuex-router-sync'
Vue.use(Router)
Vue.use(Resource)
// components
import App from './components/App.vue'
import Login from './components/Login/Login.vue'
import Dashboard from './components/Dashboard/Dashboard.vue'
import Counter from './components/Counter/Counter.vue'
// model
import store from './vuex/store.js'
// routing
var router = new Router()
router.map({
'/login': {
component: Login
},
'/dashboard': {
component: Dashboard
},
'/counter': {
component: Counter
}
})
router.beforeEach(function() {
window.scrollTo(0, 0)
})
router.redirect({
'*': '/login'
})
sync(store, router)
router.start(App, 'body')
Vue.config.debug = true
Vue.http.interceptors.push({
request: function(request) {
Vue.http.headers.common['Authorization'] = 'JWT' + sessionStorage.getItem('token')
return request
},
response: function(response) {
if (response.status === 401) {
router.go('/login')
}
return response
}
});
|
/**
* Dependencies
* @type {exports}
*/
var fs = require('fs')
, q = require('q')
, _ = require('underscore')
, path = require('path')
, natural = require('natural')
, nounInflector = new natural.NounInflector()
, argv = require('optimist').argv
, path = require('path')
, generator = require('./model.generator');
/**
* Arguments
*/
var directory = path.resolve(process.argv[2])
, dest = path.resolve(process.argv[3]);
var host = ""
, version = "1.0"
, rel = "";
/**
* Functions
*/
var resourceName = function(model) {
return nounInflector.pluralize(model.modelName).toLowerCase();
};
/**
* load a model
* @param modelPath
* @returns {*}
*/
var loadModel = function(modelPath) {
return require(directory + '/' + modelPath);
};
/**
* Write the schema file
* @param modelPath
*/
var profileModel = function(modelPath) {
var model = loadModel(modelPath);
var schema = generator(host, version, model, rel);
mkdir(dest)
fs.writeFile(dest + '/' + resourceName(model) + '.json', JSON.stringify(schema, false, 2), function(err) {
});
};
/**
* Read models from directory
*/
fs.readdir(directory, function(err, files) {
_.each(files, profileModel);
});
/**
* Make a directory
* @param path
* @param root
* @returns {boolean|*}
*/
function mkdir(path, root) {
var dirs = path.split('/')
, dir = dirs.shift()
, root = (root || '') + dir + '/';
try {
fs.mkdirSync(root);
}
catch(e) {
if (!fs.statSync(root).isDirectory()) {
throw new Error(e);
}
}
return !dirs.length || mkdir(dirs.join('/'), root);
}
|
'use strict'
const path = require('path')
const Generator = require('yeoman-generator')
const chalk = require('chalk')
const _ = require('lodash')
_.templateSettings.interpolate = /<%=([\s\S]+?)%>/g
module.exports = Generator.extend({
initializing: function () {
this.props = {}
},
paths: function () {
this.sourceRoot(path.normalize(path.join(__dirname, '/../../templates')))
},
writing: function () {
const props = this.config.getAll()
const newVersion = require('../../package.json').version
if (!this.fs.exists(this.destinationPath('.yo-rc.json'))) {
this.log(chalk.red('Refusing to update, a .yo-rc.json file is required.'))
return
}
const cpTpl = (from, to) => {
this.fs.copyTpl(
this.templatePath(from),
this.destinationPath(to),
props
)
}
const cp = (from, to) => {
this.fs.copy(
this.templatePath(from),
this.destinationPath(to)
)
}
const rm = (p) => {
this.fs.delete(this.destinationPath(p))
}
const pkgTpl = _.template(
this.fs.read(this.templatePath('_package.json'))
)
const pkg = JSON.parse(pkgTpl(props))
// No longer using eslint
pkg.dependencies['eslint'] = undefined
pkg.dependencies['eslint-config-ivantage'] = undefined
pkg.dependencies['eslint-loader'] = undefined
pkg.devDependencies['eslint'] = undefined
pkg.devDependencies['eslint-config-ivantage'] = undefined
pkg.devDependencies['eslint-loader'] = undefined
// React update 15.4 --> 15.5
pkg.devDependencies['react-addons-shallow-compare'] = undefined
pkg.devDependencies['react-addons-test-utils'] = undefined
pkg.devDependencies['prop-types'] = undefined
// Removed postcss plugins
pkg.devDependencies['postcss-custom-properties'] = undefined
// @todo - extendJSON will merge properties, for some things
// (devDependencies) we probably just want to set them so as to not carry
// forward cruft we don't need anymore.
this.fs.extendJSON(this.destinationPath('package.json'), _.pick(pkg, [
'name',
'main',
'description',
'scripts',
'license',
'jest',
'peerDependencies',
'devDependencies'
]))
cpTpl('webpack.config.js', 'webpack.config.js')
if (props.useDotFiles) {
cp('_editorconfig', '.editorconfig')
cp('_gitignore', '.gitignore')
cp('_babelrc', '.babelrc')
} else {
[
'.editorconfig',
'.gitignore',
'.babelrc'
].forEach(rm)
}
// Standard over eslint!
rm('.eslintrc.js')
// No longer using explicit mock files
rm('src/mocks')
this.config.set('generatorVersion', newVersion)
},
end: function () {
const msg = chalk.green('Done.')
this.log(msg)
}
})
|
'use strict'
/* libraries */
var Sequelize = require('sequelize')
/* own code */
var Attribute = require('./attribute')
/**
* Parse DEM entity and create Sequelize definition for the table itself.
* @constructor
*/
function Entity() {
this._parserAttr = new Attribute()
}
/**
* Input JSON (DEM entity):
{
"id": "Person",
"alias": "person",
"comment": "Person basic entity with 2 attributes.",
"attributes": [...]
}
*
* Result data:
{
table: "NameFirst",
columns: {...},
options: {...}
}
*
* See http://sequelize.readthedocs.org/en/latest/docs/models-definition/#configuration
*
* @param jsDem
* @param seqModel
* @return {{}}
* @private
*/
Entity.prototype.parseJson = function _parseJson(jsDem, seqModel) {
var result = {table: '', columns: {}, options: {}};
/* process common properties */
result.table = jsDem.id
var options = result.options
/* parse columns */
if (jsDem.attributes) {
var demAttrs = jsDem.attributes
var columns = result.columns
var i, len, parsedAttr;
for (i = 0, len = demAttrs.length; i < len; ++i) {
parsedAttr = this._parserAttr.parseJson(demAttrs[i])
columns[parsedAttr.column] = parsedAttr.definition
}
}
return result
}
module.exports = Entity
|
const pageIcon = require('./../lib/index');
const helpers = require('./helpers');
const fs = require('fs');
const chai = require('chai');
const path = require('path');
const url = require('url');
const expect = chai.expect;
const {isIconValid, saveToFile} = helpers;
const SITE_URLS = [
'https://www.facebook.com/',
'http://stackoverflow.com/questions/16301503/can-i-use-requirepath-join-to-safely-concatenate-urls',
'https://web.whatsapp.com'
];
const HTTP_TEST_URL = 'http://web.whatsapp.com';
const ICON_TYPE_URL = 'https://web.whatsapp.com';
describe('Page Icon', function() {
this.timeout(10000);
it('Can download all icons', function(done) {
const downloadTests = SITE_URLS.map(function(siteUrl) {
return new Promise(function(resolve, reject) {
pageIcon(siteUrl)
.then(function(icon) {
if (!icon) {
throw `No icon found for url: ${siteUrl}`;
}
return icon;
})
.then(function(icon) {
expect(isIconValid(icon)).to.be.true;
return icon;
})
.then(saveToFile)
.then(() => {
resolve();
})
.catch(reject);
});
});
Promise.all(downloadTests)
.then(function() {
done();
})
.catch(done);
});
it('Can try to https if nothing is found at http', function(done) {
pageIcon(HTTP_TEST_URL)
.then(function(icon) {
if (!icon) {
throw `No icon found for url: ${siteUrl}`;
}
return icon;
})
.then(function(icon) {
expect(isIconValid(icon)).to.be.true;
done()
})
.catch(done);
});
describe('Specification of preferred icon ext', function () {
it('Type .png', function(done) {
iconTypeTest('.png', done);
});
it('Type .ico', function (done) {
iconTypeTest('.ico', done);
});
});
});
function iconTypeTest(ext, callback) {
pageIcon(ICON_TYPE_URL, {ext: ext})
.then(function(icon) {
if (!icon) {
throw `No icon found for url: ${ICON_TYPE_URL}`;
}
return icon;
})
.then(function(icon) {
expect(icon.ext).to.equal(ext, `Should get a ${ext} from WhatsApp`);
return icon;
})
.then(() => {
callback();
})
.catch(callback);
}
|
//
// This is only a SKELETON file for the 'Rectangles' exercise. It's been provided as a
// convenience to get you started writing code faster.
//
export function count() {
throw new Error('Remove this statement and implement this function');
}
|
var async = require('async'),
awsSDK = require('aws-sdk'),
uuid = require('node-uuid');
function client() {
return new awsSDK.DynamoDB().client;
}
function putItem(done) {
var item = {
TableName: "test.performance.ssl",
Item: {
id: {
S: uuid.v1()
}
}
};
client().putItem(item, done);
};
function put10(done) {
var i = 10;
var t = process.hrtime();
async.whilst(function() {
return i > 0;
}, function(cb) {
--i;
return putItem(cb);
}, function(e) {
t = process.hrtime(t);
console.log('%d seconds', t[0] + t[1] / 1000000000);
return done(e);
});
};
describe('ssl tests', function() {
this.timeout(10000);
describe('with ssl', function() {
before(function() {
awsSDK.config.update({
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_SECRET_KEY,
sslEnabled: true,
region: 'us-east-1'
});
});
it('can put 10 items', put10);
});
describe('without ssl', function() {
before(function() {
awsSDK.config.update({
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_SECRET_KEY,
sslEnabled: false,
region: 'us-east-1'
});
});
it('can put 10 items', put10);
});
});
|
'use strict';
var _ = require("lodash-node")
,parserlib = require("parserlib") // for linting CSS
,fse = require("fs-extra")
,cwd = process.cwd()
describe("test 4 - check css is valid", function() {
var originalTimeout;
beforeEach(function() {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 4000;
});
afterEach(function() {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});
/**
* Lodash template used just for converting path vars
*/
var rootDirObj = { rootDir: "./" }
,config = require("./grunt_configs/test4.js").test
,DEST = _.template( config.dest, rootDirObj );
it("should have created a css file for icons which should no longer contains any template syntax, then lint the styles.", function(done) {
expect( fse.existsSync(DEST+"icons.css") ).toBe( true );
var css = fse.readFileSync(DEST+"icons.css").toString();
expect( css.indexOf("<%=") ).toEqual(-1);
lintCSS( done, css );
});
it("should have copied the `svgloader.js` file into dist.", function() {
expect( fse.existsSync(DEST+"svgloader.js") ).toBe( true );
});
it("should have NOT generated sprite and placed it into dist.", function() {
expect( fse.existsSync(DEST + "sprite.png") ).toBe( false );
});
});
function lintCSS( done, returnedStr ) {
// Now we lint the CSS
var parser = new parserlib.css.Parser();
// will get changed to true in error handler if errors detected
var errorsFound = false;
parser.addListener("error", function(event){
console.log("Parse error: " + event.message + " (" + event.line + "," + event.col + ")", "error");
errorsFound = true;
});
parser.addListener("endstylesheet", function(){
console.log("Finished parsing style sheet");
expect( errorsFound ).toBe( false );
// finish the test
done();
});
parser.parse( returnedStr );
}
|
'use strict';
import angular from 'angular';
import NavbarTpl from './navbar.html';
import NavbarService from './navbar-service';
import NavbarCtrl from './navbar-ctrl';
function navbar(NavbarService) {
return {
restrict: 'E',
scope: {
name: '@',
version: '@',
linkTo: '@'
},
templateUrl: NavbarTpl,
link: (scope, el, attr) => {
scope.navbar = NavbarService.getNavbar();
}
}
}
export default angular.module('directives.navbar', [NavbarService])
.directive('navbar', ['NavbarService', navbar])
.controller('NavbarCtrl', ['$scope', '$document', NavbarCtrl])
.name;
|
'use strict'
require('should')
const DummyTransport = require('chix-transport/dummy')
const ProcessManager = require('chix-flow/src/process/manager')
const RuntimeHandler = require('../lib/handler/runtime')
const pkg = require('../package')
const schemas = require('../schemas')
// TODO: this just loads the definitions from the live webserver.
// Doesn't matter that much I think..
describe('Runtime Handler:', () => {
it('Should respond to getruntime', (done) => {
const pm = new ProcessManager()
const transport = new DummyTransport({
// logger: console,
bail: true,
schemas: schemas
})
RuntimeHandler.handle(pm, transport /*, console*/)
transport.capabilities = ['my-capabilities']
transport.once('send', (data, conn) => {
data.protocol.should.eql('runtime')
data.command.should.eql('runtime')
data.payload.version.should.eql(pkg.version)
data.payload.capabilities.should.eql([
'my-capabilities'
])
conn.should.eql('test-connection')
// assume the data from the server is ok
done()
})
// trigger component action
transport.receive({
protocol: 'runtime',
command: 'getruntime'
}, 'test-connection')
})
})
|
/**
* Clase que permite trabajar con la plantilla del profesor.
*
* @param {String} id ID de la etiqueta HTML asociada.
* @param {Boolean revisor ¿Sólo se buscarán revisores?
* @returns {Profesor}
*/
function Profesor(id, revisor)
{
/**
* Establece la etiqueta HTML asociada a esta plantilla.
*/
this.id = id;
/**
* Establece si la plantilla de búsqueda sólo buscará revisores en
* el servidor o no.
*/
this.revisor = false;
if (typeof revisor !== 'undefined')
{
this.revisor = revisor;
}
/**
* Devuelve la etiqueta HTML asociada.
*
* @returns {jQuery}
*/
this.objeto = function ()
{
return $('input#' + this.id);
};
/**
* Inicializa el INPUT como un objeto Select2.
*/
this.inicializar = function ()
{
revisor = this.revisor;
this.objeto().select2(
{
placeholder: 'Elija un profesor',
minimumInputLength: 1,
minimumResultsForSearch: 1,
formatSearching: 'Buscando...',
formatAjaxError: 'Ha habido un error en la petición',
dropdownCssClass: 'bigdrop',
dropdownAutoWidth: true,
ajax:
{
url: '/index/select2Profesor',
dataType: 'json',
type: 'POST',
async: false,
data: function (cadena)
{
var input = new Formulario().objeto().children("input[type = 'hidden']");
var datos = establecerDatosSelect2(input.prop('name'), input.prop('value'), cadena, 2);
if (revisor)
{
datos['NkWQ0yGKJFJ6U4WS7yRS'] = true;
}
console.log(this.revisor);
console.log(datos);
return datos;
},
results: function (datos)
{
return {results: obtenerDatosSelect2(datos)};
}
},
formatResult: function (objeto)
{
return objeto['nombreCompleto'];
},
formatSelection: function (objeto)
{
return objeto['nombreCompleto'];
},
initSelection: function (elemento, callback)
{
var id = $(elemento).val();
if (id !== '')
{
var input = new Formulario().objeto().children("input[type = 'hidden']");
var datos = establecerDatosSelect2(input.prop('name'), input.prop('value'), id, 1);
if (revisor)
{
datos['NkWQ0yGKJFJ6U4WS7yRS'] = true;
}
$.ajax('/index/select2Profesor',
{
dataType: 'json',
type: 'POST',
async: false,
data: datos
}).done(function (datos)
{
callback(obtenerDatosSelect2(datos)[0]);
});
}
}
});
};
/**
* Desplaza las etiquetas HTML Select2 que se usan para este profesor.
*/
this.moverSelect2 = function ()
{
this.objeto().parent().append($('div#s2id_' + this.id));
};
}
|
import React from 'react'
function LoadingIndicator () {
return (
<div>
Loading
<div className='sk-fading-circle'>
<div className='sk-circle1 sk-circle'></div>
<div className='sk-circle2 sk-circle'></div>
<div className='sk-circle3 sk-circle'></div>
<div className='sk-circle4 sk-circle'></div>
<div className='sk-circle5 sk-circle'></div>
<div className='sk-circle6 sk-circle'></div>
<div className='sk-circle7 sk-circle'></div>
<div className='sk-circle8 sk-circle'></div>
<div className='sk-circle9 sk-circle'></div>
<div className='sk-circle10 sk-circle'></div>
<div className='sk-circle11 sk-circle'></div>
<div className='sk-circle12 sk-circle'></div>
</div>
</div>
)
}
export default LoadingIndicator
|
const c = require('ansi-colors')
const glob = require('glob')
const path = require('path')
const terserVersion = require('terser/package.json').version
const TerserWebpackPlugin = require('terser-webpack-plugin')
const webpack = require('webpack')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const { argv } = require('yargs')
const config = require('../config')
// Ensures that production settings for Babel are used
process.env.NODE_ENV = 'build-es'
/* eslint-disable no-await-in-loop */
/* eslint-disable no-console */
/* eslint-disable no-restricted-syntax */
//
// Webpack config
//
const makeWebpackConfig = (entry) => ({
devtool: false,
mode: 'production',
target: 'web',
entry,
output: {
filename: path.basename(entry),
path: config.paths.base('bundle-size', 'dist'),
...(argv.debug && {
pathinfo: true,
}),
},
module: {
rules: [
{
test: /\.(js|ts)$/,
loader: 'babel-loader',
exclude: /node_modules/,
options: {
cacheDirectory: true,
},
},
],
},
externals: {
react: 'react',
'react-dom': 'reactDOM',
},
...(argv.debug && {
optimization: {
minimizer: [
new TerserWebpackPlugin({
cache: true,
parallel: true,
sourceMap: false,
terserOptions: {
mangle: false,
output: {
beautify: true,
comments: true,
preserve_annotations: true,
},
},
}),
],
},
}),
performance: {
hints: false,
},
plugins: [
argv.debug &&
new BundleAnalyzerPlugin({
analyzerMode: 'static',
logLevel: 'warn',
openAnalyzer: false,
reportFilename: `${path.basename(entry, '.js')}.html`,
}),
].filter(Boolean),
resolve: {
alias: {
'semantic-ui-react': config.paths.dist('es', 'index.js'),
},
},
})
function webpackAsync(webpackConfig) {
return new Promise((resolve, reject) => {
const compiler = webpack(webpackConfig)
compiler.run((err, stats) => {
if (err) {
reject(err)
}
const info = stats.toJson()
if (stats.hasErrors()) {
reject(new Error(info.errors.toString()))
}
if (stats.hasWarnings()) {
reject(new Error(info.warnings.toString()))
}
resolve(info)
})
})
}
//
//
//
;(async () => {
const fixtures = glob.sync('fixtures/*.size.js', {
cwd: __dirname,
})
console.log(c.cyan(`ℹ Using Webpack ${webpack.version} & Terser ${terserVersion}`))
console.log(c.cyan('ℹ Running following fixtures:'))
console.log(c.cyan(fixtures.map((fixture) => ` - ${fixture}`).join('\n')))
for (const fixture of fixtures) {
const fixturePath = config.paths.base('bundle-size', fixture)
await webpackAsync(makeWebpackConfig(fixturePath))
console.log(c.green(`✔ Completed: ${fixture}`))
}
})()
|
LearnosityAmd.define([
'jquery-v1.10.2',
'underscore-v1.5.2',
'vendor/mathcore'
], function ($, _, mathcore) {
'use strict';
var padding = 10,
defaults = {
"is_math": true,
"response_id": "custom-mathcore-response-<?php echo $session_id; ?>",
"type": "custom",
"js": "//docs.vg.learnosity.com/demos/products/questionsapi/questiontypes/assets/mathcore/mathcore.js",
"css": "//docs.vg.learnosity.com/demos/products/questionsapi/questiontypes/assets/mathcore/mathcore.css",
"stimulus": "Simplify following expression: <b>\\(2x^2 + 3x - 5 + 5x - 4x^2 + 20\\)</b>",
"score": 1,
"specs": [{
"method": "isSimplified"
}, {
"method": "equivSymbolic",
"value": "2x^2 + 3x - 5 + 5x - 4x^2 + 20"
}]
},
template = _.template('<div class="response_wrapper"><input type="text" /></div>');
var Question = function(options) {
var $response, $input,
self = this,
triggerChanged = function () {
self.clear();
setTimeout(function () {
options.events.trigger('changed', $input.val());
}, 500);
};
self.clear = function () {
$response.removeClass('valid');
$response.removeClass('notValid');
};
self.validate = function () {
var scorer = new Scorer(options.question, $input.val()),
isValid = scorer.isValid();
self.clear();
if (isValid) {
$response.addClass('valid');
} else {
$response.addClass('notValid');
}
};
options.events.on('validate', function () {
self.validate();
});
if (options.state === 'review') {
self.validate();
}
if (options.response) {
$input.val(options.response);
}
options.$el.html(template());
options.events.trigger('ready');
$response = options.$el.find('.response_wrapper');
$input = $response.find('input');
$input.on('change keydown', triggerChanged);
triggerChanged();
};
var Scorer = function (question, response) {
this.question = question;
this.response = response;
};
Scorer.prototype.isValid = function() {
var i, temp,
isValid = true;
for(i = 0; i < this.question.specs.length; i ++) {
temp = mathcore.validate(this.question.specs[i], this.response);
isValid = isValid && temp.result;
}
return isValid;
};
Scorer.prototype.score = function() {
return this.isValid() ? this.maxScore() : 0;
};
Scorer.prototype.maxScore = function() {
return this.question.score || 1;
};
return {
Question: Question,
Scorer: Scorer
};
});
|
/* eslint-disable no-cond-assign, no-param-reassign */
import voidElements from "void-elements";
function isVoidElement(tag) {
const tagName = tag.match(/<([^\s>]+)/);
return Boolean(tagName) && voidElements[tagName[1].toLowerCase()] === true;
}
export default {
strip(str) {
return str.replace(/(<([^>]+)>)/gi, "");
},
map(str) {
const regexp = /<[^>]+>/gi;
const tags = [];
const openers = [];
let result;
let tag;
while ((result = regexp.exec(str))) {
tag = {
tagName: result[0],
position: result.index
};
if (tag.tagName.charAt(1) === "/") {
tag.opener = openers.pop();
} else if (
tag.tagName.charAt(tag.tagName.length - 2) !== "/" &&
!isVoidElement(tag.tagName)
) {
openers.push(tag);
}
tags.push(tag);
}
return tags;
},
inject(str, map) {
for (let i = 0, tag; i < map.length; i += 1) {
tag = map[i];
if (str.length > 0 && tag.position <= str.length) {
str =
str.substr(0, tag.position) + tag.tagName + str.substr(tag.position);
} else if (tag.opener && tag.opener.position < str.length) {
str += tag.tagName;
}
}
return str;
}
};
|
var superagent = require('superagent')
var env = process.env
/**
* put_doc
* initialize with the couchdb to save to
*
* expects that the url, port, username, password are in environment
* variables. If not, add these to the options object.
*
* var cuser = env.COUCHDB_USER ;
* var cpass = env.COUCHDB_PASS ;
* var chost = env.COUCHDB_HOST || '127.0.0.1';
* var cport = env.COUCHDB_PORT || 5984;
*
* Options:
*
* {"cuser":"somerthineg",
* "cpass":"password",
* "chost":"couchdb host",
* "cport":"couchdb port", // must be a number
* "cdb" :"the%2fcouchdb%2fto%2fuse" // be sure to properly escape your db names
* }
*
* If you don't need user/pass to create docs, feel free to skip
* these. I only try to use credentials if these are truthy
*
* returns a function that will save new entries
*
* to create a new doc in couchdb, call with the
* object that is the doc, plus a callback
*
* The object should be a couchdb doc, but th _id field is optional.
*
* but highly recommended
*
* The first argument to the callback is whether there is an error in
* the requqest, the second is the json object returned from couchdb,
* whcih should have the save state of the document (ok or rejected)
*
*/
function put_doc(opts){
if(opts.cdb === undefined)
throw new Error('must define the {"cdb":"dbname"} option')
var cuser = env.COUCHDB_USER
var cpass = env.COUCHDB_PASS
var chost = env.COUCHDB_HOST || '127.0.0.1'
var cport = env.COUCHDB_PORT || 5984
// override env. vars
if(opts.cuser !== undefined) cuser = opts.cuser
if(opts.cpass !== undefined) cpass = opts.cpass
if(opts.chost !== undefined) chost = opts.chost
if(opts.cport !== undefined) cport = +opts.cport
var couch = 'http://'+chost+':'+cport
if(/http/.test(chost)) couch = chost+':'+cport
var overwrite = false
function put(doc,next){
var uri = couch+'/'+opts.cdb
var req
if(overwrite && doc._id !== undefined){
uri += '/'+doc._id
superagent.head(uri)
.end(function(err,res){
if(res.header.etag){
doc._rev=JSON.parse(res.headers.etag)
}
var req = superagent.put(uri)
.type('json')
.set('accept','application/json')
if(cuser && cpass){
req.auth(cuser,cpass)
}
req.send(doc)
req.end(function(e,r){
if(e) return next(e)
return next(null,r.body)
})
})
}else{
if(doc._id !== undefined){
uri += '/'+doc._id
req = superagent.put(uri)
}else{
req = superagent.post(uri)
}
req.type('json')
.set('accept','application/json')
if(cuser && cpass){
req.auth(cuser,cpass)
}
req.send(doc)
req.end(function(e,r){
if(e) return next(e)
return next(null,r.body)
})
}
return null
}
put.overwrite = function(setting){
if(setting === undefined){
return overwrite
}
overwrite = setting
return overwrite
}
return put
}
module.exports=put_doc
|
(function() {
// Creating application
var app = {};
var parseData = function(data) {
var result = {};
// TODO: Get better performance here
var years = _.groupBy(data, 'year');
for (var key in years) {
result[key] = _.groupBy(years[key], 'cartodb_id');
}
return result;
};
var MapView = function() {
this.options = {
map: {
center: [0, 0],
zoom: 2,
minZoom: 2,
maxZoom: 16
},
tiles: {
url: 'http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}',
options: {
attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ',
maxZoom: 16
}
},
featureStyle: {
fillColor: '#999',
color: '#060',
weight: 1,
opacity: 1,
fillOpacity: 0.7
}
};
this.createMap = function() {
this.map = L.map(this.el, this.options.map);
// Adding tiles
// L.tileLayer(this.options.tiles.url, this.options.tiles.options)
// .addTo(this.map);
};
this.createLayer = function(topojson) {
// The problem is here
var geojson = omnivore.topojson.parse(topojson); // it takes 500ms
var style = this.options.featureStyle;
this.layer = L.geoJson(geojson, {
style: function() { return style; }
}); // it takes 750ms
this.map.addLayer(this.layer); // it takes 600ms
};
this.setYear = function(year) {
var self = this;
var data = app.groupedData[year];
var style = _.clone(this.options.featureStyle);
if (!this.getColor) {
console.error('first set colors');
} else {
this.layer.setStyle(function(feature) {
var cartodbId = feature.properties.cartodb_id;
var country = data[cartodbId];
if (country && country[0].total) {
style.fillColor = self.getColor(country[0].total);
} else {
style.fillColor = self.options.featureStyle.fillColor;
}
return style;
});
}
};
this.setColors = function(min, max, buckets) {
this.getColor = d3.scale.quantize()
.domain([min, max])
.range(colorbrewer.GnBu[buckets]);
};
this.init = (function() {
this.el = document.getElementById('map');
this.createMap();
}).bind(this)();
return this;
};
var SliderView = function() {
this.options = { velocity: 100 };
this.setEvents = function() {
var self = this;
var changeYearEvent = new Event('ChangeYear');
this.input.oninput = function() {
self.setText(self.input.value);
self.el.dispatchEvent(changeYearEvent);
};
this.startBtn.onclick = this.start.bind(this);
this.stopBtn.onclick = this.stop.bind(this);
};
this.start = function() {
this.timer = setInterval((function() {
var value = parseInt(this.input.value);
var current = value + 1;
if (this.max === current) {
this.stop();
}
this.setValue(current);
}).bind(this), this.options.velocity)
};
this.stop = function() {
if (this.timer) {
clearInterval(this.timer);
}
};
this.show = function() {
this.el.className = '';
};
this.hide = function() {
this.el.className = 'is-hidden';
};
this.setRange = function(min, max) {
this.min = min;
this.max = max;
this.input.setAttribute('min', min);
this.input.setAttribute('max', max);
};
this.setValue = function(value) {
this.input.value = value;
this.input.oninput();
};
this.setText = function(text) {
this.label.textContent = text;
};
this.init = (function() {
this.timer = null;
this.el = document.getElementById('slider');
this.input = document.getElementById('sliderRange');
this.label = document.getElementById('sliderLabel');
this.startBtn = document.getElementById('sliderPlay');
this.stopBtn = document.getElementById('sliderStop');
this.setEvents();
}).bind(this)();
return this;
};
// Document ready
document.addEventListener('DOMContentLoaded', function() {
app.loader = document.getElementById('loader');
app.map = new MapView();
app.slider = new SliderView();
// When all data is loaded
document.addEventListener('DataLoaded', function() {
var data = responses[1];
var years = utils.getMinMax(data, 'year');
var totals = utils.getMinMax(data, 'total');
var minData = totals[0];
var maxData = totals[1];
var minYear = years[0];
var maxYear = years[1];
app.map.createLayer(responses[0]);
app.groupedData = parseData(data);
app.map.setColors(minData, maxData, 9);
app.slider.el.addEventListener('ChangeYear', function() {
app.map.setYear(parseInt(app.slider.input.value));
});
app.slider.setRange(minYear, maxYear);
app.slider.setValue(minYear);
app.slider.show();
app.loader.className = 'loader is-hidden';
});
});
})();
|
var EffectsList = [
['复古效果', 'sketch', 'dorsy', '2013-10-12'],
['黄色调效果', 'yellowStyle', 'dorsy', '2013-10-12'],
['缩小', 'mini', 'dorsy', '2013-10-12']
];
var EffectTmp = ' <li data-ename="{name}">\
<img src="style/image/effect/{name}.png" />\
<h3>{cnname}</h3>\
<div class="itemInfo">\
<span class="author lightFont">{author}</span>\
<span class="date lightFont">{date}</span>\
</div>\
</li>\
';
|
//= require ../bower_components/jquery/dist/jquery.js
'use strict';
var APP = {};
$(function() {
console.log('Hello from your jQuery application!');
});
|
const userDao = require('../dao/user'),
tokenDao = require('../dao/token'),
appDao = require('../dao/app'),
tokenRedisDao = require('../dao/redis/token'),
userRedisDao = require('../dao/redis/user'),
passport = require('../service/passport'),
STATUS = require('../common/const').STATUS,
ERROR = require('../common/error.map');
var create = async function(ctx, next) {
var body = ctx.request.body;
var app = ctx.get('app');
var user = await userDao.findUserByMobile(body.mobile);
if (user && user.apps && user.apps.length !== 0 && user.apps.indexOf(app) !== -1) {
throw ERROR.USER.EXIST;
} else if (user) {
await userDao.addApp(user._id, app);
} else {
user = await userDao.createUserByMobile(body.mobile, app);
}
var results = await Promise.all([
passport.encrypt(body.password),
userRedisDao.incTotal(app)
]);
var password = results[0];
var shortId = results[1];
await appDao.create(app, user._id, password, shortId);
ctx.user = user.toJSON()
ctx.user.user_short_id = shortId;
ctx.logger.info(`用户 ${body.mobile} 注册app ${app}`)
await next()
};
var getInfo = async function(ctx, next) {
var user = await userDao.getInfo(ctx.oauth.user_id, ctx.oauth.app);
ctx.result = {
user_id: user._id,
mobile: user.mobile,
chance: user.chance
};
};
var updatePassword = async function(ctx, next) {
var body = ctx.request.body;
var appInfo = await appDao.find(ctx.oauth.app, ctx.oauth.user_id);
if (!appInfo || !appInfo.password) {
throw ERROR.USER.NOT_EXIST;
}
if (appInfo.status !== STATUS.USER.ACTIVE) {
throw ERROR.USER.NOT_ACTIVE;
}
var result = await passport.validate(body.old_password, appInfo.password);
if (!result) {
throw ERROR.OAUTH.PASSWORD_ERROR;
}
var newPasswordHash = await passport.encrypt(body.new_password);
await appDao.updatePassword(appInfo._id, newPasswordHash);
ctx.logger.info(`用户 ${ctx.oauth.user_id} 修改密码`);
await next();
};
var resetPassword = async function(ctx, next) {
var body = ctx.request.body;
var app = ctx.get('app');
var userInfo = await userDao.findUserByMobile(body.mobile);
if (!userInfo) {
throw ERROR.USER.NOT_EXIST;
}
var appInfo = await appDao.find(app, userInfo._id);
if (!appInfo || !appInfo.password) {
throw ERROR.USER.NOT_EXIST;
}
if (appInfo.status !== STATUS.USER.ACTIVE) {
throw ERROR.USER.NOT_ACTIVE;
}
var passwordHash = await passport.encrypt(body.password);
await appDao.updatePassword(appInfo._id, passwordHash);
ctx.logger.info(`用户 ${body.mobile} 重置密码 app ${app}`);
await next();
//强制用户登出
var expiredToken = await tokenDao.delToken(app, userInfo._id);
tokenRedisDao.delToken(expiredToken.access_token);
tokenRedisDao.delToken(expiredToken.refresh_token);
};
module.exports = {
create,
getInfo,
updatePassword,
resetPassword
}
|
// ga.addEventBehavior(ga.gameEvents.MouseDown, undefined, undefined, undefined, function (e) {
// var spriteClick = ga.CheckEventPosition(e.offsetX, e.offsetY);
// if (spriteClick != undefined) {
// if (this.lastClick != undefined) {
// this.lastClick.unHighLight();
// }
// this.lastClick = spriteClick;
// spriteClick.highLight(0, 0, 0, 0, 255, 0, 0, 0);
// var parentObj = this;
// setTimeout(function () {
// var seeker = new Seeker("walking", "attacking", 100);
// ga.addEventBehavior(ga.gameEvents.MouseDown, "", spriteClick, "walking", function (e, sprite, engine) {
// if (sprite == parentObj.lastClick) {
// seeker.execute(e, sprite, engine);
// }
// }, -1);
// seeker.setFoundCallback(function (sprite) {
// sprite.unHighLight();
// ga.removeEventBehavior(ga.gameEvents.MouseDown, sprite);
// });
// }, 100);
// }
// }, 1);
|
/**
* modal api
*/
export default {
methods: {
/**
* 点击 Full 的导航按钮
*/
clickFullNav() {
if (this.commit) {
this.no()
} else {
this.hide()
}
},
/**
* 显示pop
*
* @param {Number} - 当前页码
* @return {Object}
*/
show() {
this.modalDisplay = true
return this.$nextTick(() => {
this.$refs.fadeTransition.enter()
this.$refs.pop.show()
return this
})
},
/**
* 隐藏pop
*
* @return {Object}
*/
hide() {
this.$refs.fadeTransition.leave()
this.$refs.pop.hide({
cb: () => {
this.modalDisplay = false
this.isMousedown = false
}
})
return this
},
/**
* 鼠标mouseDown 弹窗头部触发的事件
*
* @return {Object}
*/
mouseDown(event) {
this.isMousedown = true
this.pointStart = {
x: event.clientX,
y: event.clientY
}
return this
},
/**
* 鼠标mouseMove 弹窗头部触发的事件
*
* @return {Object, Boolean}
*/
mouseMove(event) {
event.preventDefault()
if (!this.isMousedown) {
return false
}
this.$refs.pop.computePosition()
this.pointStart = {
x: event.clientX,
y: event.clientY
}
return this
},
/**
* 鼠标mouseUp 弹窗头部触发的事件
*
* @return {Object, Boolean}
*/
mouseUp(event) {
event.preventDefault()
if (!this.isMousedown) {
return false
}
this.isMousedown = false
return this
},
/**
* 弹窗点击确定触发的函数
*
* @return {Object}
*/
ok() {
this.$emit('ok')
if (this.okCbFun) {
if (typeof this.okCbFun === 'function') {
this.okCbFun(this)
}
return this
}
return this.hide()
},
/**
* 弹窗点击取消触发的函数
*
* @return {Object}
*/
no() {
this.$emit('no')
if (this.noCbFun) {
if (typeof this.noCbFun === 'function') {
this.noCbFun(this)
}
return this
}
this.hide()
},
/**
* 获取 / 设置 弹窗的title名
*
* @return {Object, Boolean}
*/
title(text) {
if (text === '' || text) {
this.stateHeader = text
}
return this
},
/**
* alert, confirm 弹窗的文字信息
*
* @param {String} - 需要设置的值
* @return {Object, String}
*/
info(text) {
if (text === '' || text) {
this.stateMessage = text
}
return this
},
/**
* 设置各个组件的配置数据
*
* @param {Object} opt - 选项
* {Function} okCb - 点击的回调函数
* {Function} noCb - 取消的回调函数
* {Function} showCb - 显示之后的回调函数
* {Function} hideCb - 隐藏之后的回调函数
* {String} title - 模态框标题
* {Function} message - 需要展示的信息
*/
set({
okCb,
noCb,
showCb,
hideCb,
title = '',
message = '',
ui = this.ui,
theme = this.theme
} = {}) {
this.okCbFun = okCb
this.noCbFun = noCb
this.showCb = showCb
this.hideCb = hideCb
this.stateHeader = title
this.stateMessage = message
this.stateUI = ui
this.stateTheme = theme
return this
}
}
}
|
(function() {
'use strict';
/**
* @ngdoc function
* @name app.service:badgesService
* @description
* # badgesService
* Service of the app
*/
angular
.module('badges')
.factory('BadgesService', Badges);
// Inject your dependencies as .$inject = ['$http', 'someSevide'];
// function Name ($http, someSevide) {...}
Badges.$inject = ['$http', '$rootScope'];
function Badges ($http, $rootScope) {
return {
getBadges:getBadges
};
function getBadges(vm) {
var badges = [];
var url = "https://raw.githubusercontent.com/ltouroumov/amt-g4mify/master/client/app/assets/images/";
var req = {
method: 'GET',
url: 'http://localhost:8080/api/users/' + $rootScope.username +'/badges',
headers: {
'Content-Type': 'application/json',
'Identity': '1:secret'
}
};
$http(req).then(function(res){
console.log("Badges: OK");
for(var i = 0; i < res.data.length; i++){
var badge = {
level: res.data[i].level,
name: res.data[i].type.name,
image: url + res.data[i].type.image
};
console.log(badges);
badges.push(badge);
}
vm.badges = badges;
}, function(err){
console.log("Badges: ERROR");
vm.msg = "- An error occurred posting the event to the gamification platform";
vm.success = false;
});
}
}
})();
|
import React from 'react';
import renderer from 'react-test-renderer';
import { data, renderers, expectors } from '../../test-utils';
import ImmutableVirtualizedList from '../ImmutableVirtualizedList';
describe('ImmutableVirtualizedList', () => {
it('renders with empty data', () => {
expectors.expectVirtualizedToMatchSnapshotWithData(data.EMPTY_DATA);
});
it('renders basic List', () => {
expectors.expectVirtualizedToMatchSnapshotWithData(data.LIST_DATA);
});
it('renders nested List', () => {
expectors.expectVirtualizedToMatchSnapshotWithData(data.LIST_DATA_NESTED);
});
it('renders basic Range', () => {
expectors.expectVirtualizedToMatchSnapshotWithData(data.RANGE_DATA);
});
});
describe('ImmutableVirtualizedList with renderEmpty', () => {
it('renders normally when there are some items', () => {
const tree = renderer.create(
<ImmutableVirtualizedList
immutableData={data.LIST_DATA}
renderItem={renderers.renderRow}
renderEmpty={() => renderers.renderRow('No items')}
/>,
);
expect(tree.toJSON()).toMatchSnapshot();
});
it('renders empty with a function', () => {
const tree = renderer.create(
<ImmutableVirtualizedList
immutableData={data.EMPTY_DATA}
renderItem={renderers.renderRow}
renderEmpty={() => renderers.renderRow('No items')}
/>,
);
expect(tree.toJSON()).toMatchSnapshot();
});
it('renders empty with a string', () => {
const color = 'red';
const tree = renderer.create(
<ImmutableVirtualizedList
immutableData={data.EMPTY_DATA}
renderItem={renderers.renderRow}
renderEmpty="No items"
contentContainerStyle={{ color }}
/>,
);
expect(tree.toJSON()).toMatchSnapshot();
});
it('doesn\'t render empty with null', () => {
const tree = renderer.create(
<ImmutableVirtualizedList
immutableData={data.EMPTY_DATA}
renderItem={renderers.renderRow}
renderEmpty={null}
renderEmptyInList={null}
/>,
);
expect(tree.toJSON()).toMatchSnapshot();
});
});
describe('ImmutableVirtualizedList with renderEmptyInList', () => {
it('renders normally when there are some items', () => {
const tree = renderer.create(
<ImmutableVirtualizedList
immutableData={data.LIST_DATA}
renderItem={renderers.renderRow}
renderEmptyInList={() => renderers.renderRow('No items')}
/>,
);
expect(tree.toJSON()).toMatchSnapshot();
});
it('renders empty with a function', () => {
const tree = renderer.create(
<ImmutableVirtualizedList
immutableData={data.EMPTY_DATA}
renderItem={renderers.renderRow}
renderEmptyInList={() => renderers.renderRow('No items')}
/>,
);
expect(tree.toJSON()).toMatchSnapshot();
});
it('renders empty with a string', () => {
const color = 'red';
const tree = renderer.create(
<ImmutableVirtualizedList
immutableData={data.EMPTY_DATA}
renderItem={renderers.renderRow}
renderEmptyInList="No items"
contentContainerStyle={{ color }}
/>,
);
expect(tree.toJSON()).toMatchSnapshot();
});
it('doesn\'t render empty with null', () => {
const tree = renderer.create(
<ImmutableVirtualizedList
immutableData={data.EMPTY_DATA}
renderItem={renderers.renderRow}
renderEmpty={null}
renderEmptyInList={null}
/>,
);
expect(tree.toJSON()).toMatchSnapshot();
});
});
|
describe("Quiz API Tests", function() {
var api;
var mock;
beforeAll(function(done) {
api = Playbasis.quizApi;
mock = window.mock;
window.acquireBuiltPlaybasis();
done();
});
describe("List Active Quizzes test", function() {
beforeAll(function(done) {
done();
});
it("should return success", function(done) {
api.listOfActiveQuizzes()
.then((result) => {
done();
}, (e) => { console.log(e.message);})
});
});
describe("Detail of Quiz test", function() {
var quizId = "57f5d72ab350cf67308b81c6"; //pre-existing quiz 1
beforeAll(function(done) {
done();
});
it("should return success", function(done) {
api.detailOfQuiz(quizId)
.then((result) => {
expect(result.response.result).not.toBe(null);
expect(result.response.result.quiz_id).toEqual(quizId);
done();
}, (e) => { console.log(e.message);});
});
});
describe("Random Get a Quiz for Player test", function() {
beforeAll(function(done) {
done();
});
it("should return success", function(done) {
api.randomQuizForPlayer(mock.env.playerId)
.then((result) => {
expect(result.response.result).not.toBe(null);
expect(result.response.result.quiz_id).not.toBe(null);
done();
}, (e) => { console.log(e.message);});
});
});
describe("List Quiz Done by Player test", function() {
beforeAll(function(done) {
done();
});
it("should return success", function(done) {
api.listQuizDone(mock.env.playerId, 5)
.then((result) => {
done();
}, (e) => { console.log(e.message);});
});
});
describe("List Pending Quiz by Player test", function() {
beforeAll(function(done) {
done();
});
it("should return success", function(done) {
api.listPendingQuiz(mock.env.playerId, 5)
.then((result) => {
done();
}, (e) => { console.log(e.message);});
});
});
describe("Get Question from Quiz for Player test", function() {
var quizId = "57f5d72ab350cf67308b81c6"; //pre-existing quiz 1
beforeAll(function(done) {
done();
});
it("should return success", function(done) {
api.getQuestionFromQuiz(quizId, mock.env.playerId)
.then((result) => {
done();
}, (e) => { console.log(e.message);});
});
});
describe("Get Question (with reset timestamp) from Quiz for Player test", function() {
var quizId = "57f5d72ab350cf67308b81c6"; //pre-existing quiz 1
beforeAll(function(done) {
done();
});
it("should return success", function(done) {
api.getQuestionFromQuiz_resetTimeStamp(quizId, mock.env.playerId)
.then((result) => {
done();
}, (e) => { console.log(e.message);});
});
});
describe("Answer a Question for Quiz test", function() {
var quizId = "57f5d72ab350cf67308b81c6"; // pre-existing quiz 1
var optionId = "1521751f31748deab6333a87"; // pre-existing option 1 for quiz 1
var questionId = "138003ef42931448ab4b02e2"; // pre-existing question for quiz 1
beforeAll(function(done) {
done();
});
// ensure to reset progress of quiz after answering question
afterAll(function(done) {
api.resetQuiz(mock.env.playerId, quizId)
.then((result) => {
done();
}, (e) => { console.log(e.message);});
});
it("should return success", function(done) {
api.answerQuestion(quizId, mock.env.playerId, questionId, optionId)
.then((result) => {
expect(result.response.result).not.toBe(null);
expect(result.response.result.score).toEqual(10); // pre-set
done();
}, (e) => { console.log(e.message);});
});
});
describe("Rank Player by Score test", function() {
var quizId = "57f5d72ab350cf67308b81c6"; // pre-existing quiz 1
beforeAll(function(done) {
done();
});
it("should return success", function(done) {
api.rankPlayersByScore(quizId, 10)
.then((result) => {
done();
}, (e) => { console.log(e.message);});
});
});
describe("Query for Quiz's Statistics test", function() {
var quizId = "57f5d72ab350cf67308b81c6"; // pre-existing quiz 1
beforeAll(function(done) {
done();
});
it("should return success", function(done) {
api.quizStatistics(quizId)
.then((result) => {
done();
}, (e) => { console.log(e.message);});
});
});
describe("Reset Quiz test", function() {
var quizId = "57f5d72ab350cf67308b81c6"; // pre-existing quiz 1
beforeAll(function(done) {
done();
});
it("should return success", function(done) {
api.resetQuiz(mock.env.playerId, quizId)
.then((result) => {
done();
}, (e) => { console.log(e.message);});
});
});
});
|
'use babel'
export default function destroySession(self, sharedSession) {
// Checks if shared session in the stack
let shareStackIndex = self.shareStack.indexOf(sharedSession)
if (shareStackIndex !== -1) {
// Removes share session from the stack and updates UI
self.shareStack.splice(shareStackIndex, 1)
self.updateShareView()
} else {
// Logs an error message
console.error(sharedSession, 'not found')
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:7998c9520ed14ac4fc2dcf6956c1dcbd36b02d6dfe63b0e4ec15a1635b951e08
size 4403
|
version https://git-lfs.github.com/spec/v1
oid sha256:6f71532f9445b6d65fbaecee3fa6944aa804f3a8f7364028a6d8c71261adc0e5
size 3643
|
version https://git-lfs.github.com/spec/v1
oid sha256:b519d8c53881da3ce32f92a5c9f583c67d563ea9d7c5cacd3bf2503726443654
size 3420
|
/*! 一叶孤舟 | qq:28701884 | 欢迎指教 */
var bill = bill || {};
//初始化
bill.init = function (){
if (com.store){
clearInterval(bill.timer);
bill.setBillList(com.arr2Clone(com.initMap)); //写入棋谱列表
play.isPlay=false;
com.show();
}else {
bill.timer = setInterval("bill.init()",300);
}
}
//把所有棋谱写入棋谱列表
bill.setBillList = function (map){
var list=com.get("billList")
for (var i=0; i < com.store.length ; i++){
var option = document.createElement('option');
option.text='棋谱'+(i+1);
option.value=i;
list.add(option , null);
}
list.addEventListener("change", function(e) {
bill.setBox (com.store[this.value], map)
})
bill.setBox (com.store[0], map)
}
//棋谱分析 写入
bill.setMove = function (bl,inx,map){
var map = com.arr2Clone(map);
for (var i=0; i<map.length; i++){
for (var n=0; n<map[i].length; n++){
var key = map[i][n];
if (key){
com.mans[key].x=n;
com.mans[key].y=i;
com.mans[key].isShow = true;
}
}
}
for (var i=0; i<= inx ; i++){
var n = i*4
var y = bl[n+1]
var newX = bl[n+2]
var x = bl[n+0]
var newY = bl[n+3]
if (com.mans[map[newY][newX]]) {
com.mans[map[newY][newX]].isShow = false;
}
com.mans[map[y][x]].x = newX;
com.mans[map[y][x]].y = newY;
if (i == inx) {
com.showPane(x ,y,newX,newY);
}
map[newY][newX] = map[y][x];
delete map[y][x];
}
return map;
}
//写入棋谱
bill.setBox = function (bl,initMap){
var map = com.arr2Clone(initMap);
var bl= bl.split("");
var h='';
for (var i=0; i< bl.length ; i+=4){
h +='<li id="move_'+(i/4)+'">';
var x = bl[i+0];
var y = bl[i+1];
var newX = bl[i+2];
var newY = bl[i+3];
h += com.createMove(map,x,y,newX,newY);
h +='</li>\n\r';
}
com.get("billBox").innerHTML = h;
var doms=com.get("billBox").getElementsByTagName("li");
for (var i=0; i<doms.length; i++){
doms[i].addEventListener("click", function(e) {
var inx = this.getAttribute("id").split("_")[1];
bill.setMove (bl , inx , initMap)
com.show();
})
}
}
|
"use strict";
var now = Date.now;
var CircleQueue = require("../../misc/CircleQueue.js");
function TransCommandQueue(mainQueue, object) {
CircleQueue.call(this);
this.object = object;
this.mainQueue = mainQueue;
}
TransCommandQueue.prototype = {
__name__ : "TransCommandQueue",
"__proto__" : CircleQueue.prototype,
constructor : TransCommandQueue,
isClosed : false,
isExecuted : false,
execute : function () {
if (this.isExecuted || !this.length || this.isClosed) {
return;
}
var self = this;
var task = this.shift();
this.object.query(task.sql, task.options, function (err, result) {
self.isExecuted = false;
task.callback(err, result);
self.execute();
});
this.isExecuted = true;
},
destroy : function () {
if (this.isClosed) {
return;
}
this.isClosed = true;
this.clear();
this.mainQueue.pool.returnObject(this.object);
this.mainQueue.execute();
}
};
module.exports = TransCommandQueue;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
var STATUS_ICON = "_CSSClassnames2.default.STATUS_ICON";
var Label = function (_Component) {
(0, _inherits3.default)(Label, _Component);
function Label() {
(0, _classCallCheck3.default)(this, Label);
return (0, _possibleConstructorReturn3.default)(this, (Label.__proto__ || (0, _getPrototypeOf2.default)(Label)).apply(this, arguments));
}
(0, _createClass3.default)(Label, [{
key: 'render',
value: function render() {
var className = STATUS_ICON + ' ' + STATUS_ICON + '-label';
if (this.props.className) {
className += ' ' + this.props.className;
}
return _react2.default.createElement(
'svg',
{ className: className, viewBox: '0 0 24 24', version: '1.1' },
_react2.default.createElement(
'g',
{ className: STATUS_ICON + '__base' },
_react2.default.createElement('circle', { cx: '12', cy: '12', r: '12', stroke: 'none' })
)
);
}
}]);
return Label;
}(_react.Component);
Label.displayName = 'Label';
exports.default = Label;
module.exports = exports['default'];
|
module.exports = { // meta
/**
* The banner is the comment that is placed at the top of our compiled
* source files. It is first processed as a Grunt template, where the `<%=`
* pairs are evaluated based on this very configuration object.
*/
banner: '/**\n' +
' * <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>\n' +
' * <%= pkg.homepage %>\n' +
' *\n' +
' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' +
' * Licensed <%= pkg.licenses.type %> <<%= pkg.licenses.url %>>\n' +
' */\n'
};
|
function DashboardController($scope, $state, $stateParams, dashboardFactory) {
var dc = this;
dc.playerStats = {};
dc.itemForAuction = {};
dc.auctionStarted = false;
// Called on page load to retrieve player data
dashboardFactory.getData(dashboardFactory.getName()).then(function(response) {
dc.playerStats = response.data;
});
var unbindLogout = $scope.$on('logout', function() {
dashboardFactory.logout().then(function(response) {
if (response.status === 200) {
$state.go('login');
}
});
});
var unbindStart = $scope.$on('startAuction', function(evt, data) {
dc.auctionStarted = true;
dc.itemForAuction = data;
$scope.$broadcast('roll it');
});
var unbindClose = $scope.$on('auction closed', function(evt, data) {
updateData(dc.playerStats, data);
dashboardFactory.processBid(data).then(function(response) {
if (response.data === 200) {
dashboardFactory.getData(dashboardFactory.getName()).then(function(res) {
dc.playerStats = res.data;
});
}
});
});
// Clear events
$scope.$on('$destroy', function() {
unbindLogout();
unbindStart();
unbindClose();
});
/**
* @desc function that updates player dashboard in real-time
* @param {Object} playerData - logged in player's data
* @param {Object} newData - contains player's recent transaction
*/
function updateData(playerData, newData) {
playerData.coins = playerData.coins - newData.value;
angular.forEach(playerData.inventoryItems, function(item) {
if (item.name === newData.itemName) {
item.quantity = item.quantity - newData.qty;
}
});
}
}
module.exports = DashboardController;
|
export default class Paths {
/* url, path, relative path... anything */
static normalizePath(path, base, root=lively4url) {
base = base.replace(/[^/]*$/,"") // if it is not a dir
var normalized = path
if (path.match(/^[A-Za-z]+:/)) {
// do nothing
} else if (path.match(/^\//)) {
normalized = path.replace(/^\//, root + "/")
} else {
normalized = base + path
}
return Paths.normalizeURL(normalized)
}
static normalizeURL(urlString) {
var url = new URL(urlString);
url.pathname = this.normalize(url.pathname);
return "" + url;
}
/* normalize only the "path" part of an URL */
static normalize(path) {
let source = path.split(/\/+/)
let target = []
for(let token of source) {
if(token === '..') {
target.pop()
} else if(token !== '' && token !== '.') {
target.push(token)
}
}
if(path.charAt(0) === '/')
return '/' + target.join('/')
else
return target.join('/')
}
static join(a, b) {
if(b[0] === '/') {
return this.normalize(b)
} else {
return this.normalize(a + '/' + b)
}
}
}
|
/**
* Copyright (c) 2014 brian@bevey.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/**
* @author brian@bevey.org
* @fileoverview Prevent an air filter or other device from being turned off if
* air quality is bad. The main intent of this is to prevent
* automated macros or machine learning from turning off a filter
* if air quality (PM 2.5) is really bad.
*/
module.exports = (function () {
'use strict';
return {
version : 20180822,
airFilterWhenSmoggy : function (deviceId, command, controllers, config) {
var deviceState = require(__dirname + '/../../lib/deviceState'),
commandParts = command.split('-'),
filter = config.filter,
maxLevel = config.maxLevel || 34.4,
commandSubdevice = '',
checkState,
status;
checkState = function () {
var currDevice,
currentDevice = {},
status = {},
subdeviceId,
i = 0;
for (currDevice in controllers) {
if (controllers[currDevice].config) {
switch (controllers[currDevice].config.typeClass) {
// Look for bad PM 2.5 values in Air Quality
case 'airQuality' :
currentDevice = deviceState.getDeviceState(currDevice);
if (currentDevice.value && currentDevice.value.report) {
for (i; i < currentDevice.value.report.length; i += 1) {
if (currentDevice.value.report[i].type === 'pm25') {
status.value = currentDevice.value.report[i].value;
}
}
}
break;
case 'nest' :
case 'smartthings' :
case 'wemo' :
currentDevice = deviceState.getDeviceState(currDevice);
if (currentDevice.value) {
for (subdeviceId in currentDevice.value.devices) {
if (currentDevice.value.devices[subdeviceId].label === filter) {
status.filter = currentDevice.value.devices[subdeviceId];
status.newState = currentDevice.value;
}
}
}
break;
}
}
}
return status;
};
if (commandParts.length === 3) {
commandSubdevice = commandParts[1];
// We only care if it's the given subdevice AND we're trying to
// potentially turn it off.
if ((filter === commandSubdevice) && ((commandParts[2] === 'toggle') || (commandParts[2] === 'off'))) {
status = checkState();
// Air quality is beyond it's determined safe bounds and the chosen
// filter is currently on - abort this off or toggle command.
if ((status.value >= maxLevel) && (status.filter.state === 'on')) {
return false;
}
}
}
}
};
}());
|
import {stats} from './stats.js';
import {core} from './core.js';
import {tasks} from './tasks.js';
const scenesRenderInfo = {}; // Used for throttling FPS for each Scene
const tickEvent = {
sceneId: null,
time: null,
startTime: null,
prevTime: null,
deltaTime: null
};
const taskBudget = 10; // Millisecs we're allowed to spend on tasks in each frame
const fpsSamples = [];
const numFPSSamples = 30;
let lastTime = 0;
let elapsedTime;
let totalFPS = 0;
const frame = function () {
let time = Date.now();
if (lastTime > 0) { // Log FPS stats
elapsedTime = time - lastTime;
var newFPS = 1000 / elapsedTime; // Moving average of FPS
totalFPS += newFPS;
fpsSamples.push(newFPS);
if (fpsSamples.length >= numFPSSamples) {
totalFPS -= fpsSamples.shift();
}
stats.frame.fps = Math.round(totalFPS / fpsSamples.length);
}
runTasks(time);
fireTickEvents(time);
renderScenes();
lastTime = time;
window.requestAnimationFrame(frame);
};
function runTasks(time) { // Process as many enqueued tasks as we can within the per-frame task budget
const tasksRun = tasks.runTasks(time + taskBudget);
const tasksScheduled = tasks.getNumTasks();
stats.frame.tasksRun = tasksRun;
stats.frame.tasksScheduled = tasksScheduled;
stats.frame.tasksBudget = taskBudget;
}
function fireTickEvents(time) { // Fire tick event on each Scene
tickEvent.time = time;
for (var id in core.scenes) {
if (core.scenes.hasOwnProperty(id)) {
var scene = core.scenes[id];
tickEvent.sceneId = id;
tickEvent.startTime = scene.startTime;
tickEvent.deltaTime = tickEvent.prevTime != null ? tickEvent.time - tickEvent.prevTime : 0;
/**
* Fired on each game loop iteration.
*
* @event tick
* @param {String} sceneID The ID of this Scene.
* @param {Number} startTime The time in seconds since 1970 that this Scene was instantiated.
* @param {Number} time The time in seconds since 1970 of this "tick" event.
* @param {Number} prevTime The time of the previous "tick" event from this Scene.
* @param {Number} deltaTime The time in seconds since the previous "tick" event from this Scene.
*/
scene.fire("tick", tickEvent, true);
}
}
tickEvent.prevTime = time;
}
function renderScenes() {
const scenes = core.scenes;
const forceRender = false;
let scene;
let renderInfo;
let ticksPerRender;
let id;
for (id in scenes) {
if (scenes.hasOwnProperty(id)) {
scene = scenes[id];
renderInfo = scenesRenderInfo[id];
if (!renderInfo) {
renderInfo = scenesRenderInfo[id] = {}; // FIXME
}
ticksPerRender = scene.ticksPerRender;
if (renderInfo.ticksPerRender !== ticksPerRender) {
renderInfo.ticksPerRender = ticksPerRender;
renderInfo.renderCountdown = ticksPerRender;
}
if (--renderInfo.renderCountdown === 0) {
scene.render(forceRender);
renderInfo.renderCountdown = ticksPerRender;
}
}
}
}
window.requestAnimationFrame(frame);
const loop = {};
export{loop};
|
import BaseStatementNode from './BaseStatementNode';
import * as symbols from '../symbols';
export default class BaseBlockNode extends BaseStatementNode {
packBlock(bitstr, propName) {
var prop = this[propName]
if (!prop) {
bitstr.writebits(0, 1);
return;
}
bitstr.writebits(1, 1);
bitstr.writebits(prop.length, 32);
prop.forEach(p => p.pack(bitstr));
}
[symbols.FMAKEHLIRBLOCK](builder, arr, expectedType) {
return arr.map(a => a[symbols.FMAKEHLIR](builder, expectedType))
.map(a => Array.isArray(a) ? a : [a])
.reduce((a, b) => a.concat(b), []);
}
};
|
"use strict";
////////////////////////////////////////////////////////////////////////////////
// ニコニコ動画再生
////////////////////////////////////////////////////////////////////////////////
Contents.nicovideo = function( cp )
{
var p = $( '#' + cp.id );
var cont = p.find( 'div.contents' );
cp.SetIcon( null );
////////////////////////////////////////////////////////////
// 開始処理
////////////////////////////////////////////////////////////
this.start = function() {
cont.activity( { color: '#ffffff' } );
cont.addClass( 'nicovideo' )
.html( OutputTPL( 'nicovideo', { id: cp.param.id } ) );
cp.SetTitle( 'Nicovideo - ' + cp.param['url'], false );
cont.activity( false );
};
////////////////////////////////////////////////////////////
// 終了処理
////////////////////////////////////////////////////////////
this.stop = function() {
};
}
|
var prependChar = '#';
var util = require('util');
function convertToLines(str) {
return str.split('\n').map(function(newStr) {
return prependChar + newStr;
});
}
var newConsole = {
log : function log() {
convertToLines(util.format.apply(this, arguments)).forEach(function(line) {
console.log(line);
});
},
error : function error() {
convertToLines(util.format.apply(this, arguments)).forEach(function(line) {
console.error(line);
});
}
};
module.exports = newConsole;
|
var page = require('page'),
csp = require('js-csp');
class Router {
constructor(routes){
this.routes = routes;
this.chan = csp.chan();
this.nextTransition = null;
this.nextEl = null;
// Setup channel listening
for(var r in routes)
this.listenToRoute(r);
// Start listening
page();
}
/**
* Go to route
*/
go(route, transition){
this.nextTransition = transition;
page(route || '/');
return this;
}
loc(){ return location.pathname.substr(1); }
listenToRoute(routeName){
var chan = this.chan;
page(this.routes[routeName].path, function(){
csp.go(function*(){
yield csp.put(chan, routeName);
});
});
}
};
module.exports = Router;
|
//= require phaser
|
$(function() {
function cellValue(val) {
return { sortValue: val, displayValue: val.toString() };
}
var yAxis = [{ id: 'store', name: 'Store' }, { id: 'clerk', name: 'Clerk' }];
var keyfigures = [{ id: 'nocustomers', name: 'Customers' }, { id: 'turnover', name: 'Turnover' }];
// normally one would request data here from the server using yAxis and keyfigures
// but to keep things simple, we type in the result below
var reportState = new ReportState({ useExpandCollapse: true });
reportState.dimensionsY = _.map(yAxis, function(e) { return e.id; });
reportState.serverData = [
{ type: 'row', values: [cellValue('Copenhagen'), cellValue(''), cellValue(210), cellValue(43100)] },
{ type: 'row', values: [cellValue('Stockholm'), cellValue(''), cellValue(120), cellValue(22100)] },
{ type: 'row', values: [cellValue('Berlin'), cellValue(''), cellValue(743), cellValue(50032)] },
{ type: 'grandtotal', values: [cellValue('Grand total'), cellValue(''), cellValue(1073), cellValue(115232)] }
];
var allYAxisValues = reportBuilder.getYAxisValues(reportState.serverData, yAxis);
reportState.drawNewData = function(data) {
// this also simulates a server backend returning new results
reportState.serverData = [];
if (_.any(reportState.expandedCells['store'], function(e) { return e == 'store:Copenhagen'; }))
{
reportState.serverData.push({ type: 'row', values: [cellValue('Copenhagen'), cellValue('Stine'), cellValue(110), cellValue(33100)] });
reportState.serverData.push({ type: 'row', values: [cellValue('Copenhagen'), cellValue('Dorthe'), cellValue(100), cellValue(10000)] });
reportState.serverData.push({ type: 'subtotal', values: [cellValue('Copenhagen'), cellValue(''), cellValue(210), cellValue(43100)] });
}
else
reportState.serverData.push({ type: 'row', values: [cellValue('Copenhagen'), cellValue(''), cellValue(210), cellValue(43100)] });
if (_.any(reportState.expandedCells['store'], function(e) { return e == 'store:Stockholm'; }))
{
reportState.serverData.push({ type: 'row', values: [cellValue('Stockholm'), cellValue('Emma'), cellValue(30), cellValue(2100)] });
reportState.serverData.push({ type: 'row', values: [cellValue('Stockholm'), cellValue('Anne'), cellValue(70), cellValue(18000)] });
reportState.serverData.push({ type: 'row', values: [cellValue('Stockholm'), cellValue('Julia'), cellValue(20), cellValue(2000)] });
reportState.serverData.push({ type: 'subtotal', values: [cellValue('Stockholm'), cellValue(''), cellValue(120), cellValue(22100)] });
}
else
reportState.serverData.push({ type: 'row', values: [cellValue('Stockholm'), cellValue(''), cellValue(120), cellValue(22100)] });
if (_.any(reportState.expandedCells['store'], function(e) { return e == 'store:Berlin'; }))
{
reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue('Sandra'), cellValue(93), cellValue(1182)] });
reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue('Katharina'), cellValue(100), cellValue(6700)] });
reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue('Nadine'), cellValue(120), cellValue(10030)] });
reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue('Julia'), cellValue(430), cellValue(30200)] });
reportState.serverData.push({ type: 'subtotal', values: [cellValue('Berlin'), cellValue(''), cellValue(743), cellValue(50032)] });
}
else
reportState.serverData.push({ type: 'row', values: [cellValue('Berlin'), cellValue(''), cellValue(743), cellValue(50032)] });
reportState.serverData.push({ type: 'grandtotal', values: [cellValue('Grand total'), cellValue(''), cellValue(1073), cellValue(115232)] });
if (reportState.sortRowIndex != -1)
reportState.drawData(reportBuilder.sortExpandedData(reportState.serverData, reportState.dimensionsY, reportState.sortRowIndex, reportState.sortDirection, reportState.expandedCells));
else
reportState.drawData(reportState.serverData);
};
reportState.drawData = function(data) {
reportInterface.drawTable("data", reportState, allYAxisValues, data, yAxis, keyfigures);
reportInterface.addSortHeaders("data", reportState);
reportInterface.addExpandCollapseHeaders("data", reportState);
};
reportState.drawData(reportState.serverData);
});
|
var socketio = require('socket.io'),
dotProp = require('dot-prop');
/**
* Constructs a Socket.
* Socket manager powered by Socket.IO.
*
* @constructor
*/
function Socket(){
this.port = null;
this.io = null;
this.scope = {};
}
Socket.prototype.start = function () {
var self = this;
var settings = self.scope.settings();
self.io = socketio(settings.socket.port);
self.io.on('connection', function (socket) {
socket.emit('structure', {key: self.scope.key, title: self.scope.title, sub: self.scope.sub});
socket.on('call', function(data){
dotProp.get(self.scope, data.path).job.call(data);
});
});
return self;
};
module.exports = new Socket();
|
import TestUtils from 'react-dom/test-utils';
import React from 'react';
import ReactDOM from 'react-dom';
import Textarea from '../';
const { findRenderedDOMComponentWithClass, renderIntoDocument, Simulate } = TestUtils;
function fake() {
return () => {
return 'fake function';
}
}
describe('The input textarea', () => {
describe('when mounted with no props', () => {
let reactComponent;
let domNode;
let inputNode;
beforeEach(() => {
reactComponent = renderIntoDocument(<Textarea name='myTextArea' onChange={fake} />);
domNode = ReactDOM.findDOMNode(reactComponent);
inputNode = ReactDOM.findDOMNode(reactComponent.refs.htmlInput);
});
it('should render a node with data-focus attribute', () => {
expect(reactComponent).toBeDefined();
expect(reactComponent).toBeInstanceOf(Object);
expect(domNode.tagName).toBe('DIV');
expect(domNode.getAttribute('data-focus')).toBe('input-textarea');
});
it('should be material designed', () => {
const divMdl = domNode.firstChild;
expect(divMdl).toBeDefined();
expect(divMdl.tagName).toBe('DIV');
expect(divMdl.className).toMatch('mdl-textfield mdl-js-textfield');
});
it('should have a material designed textarea', () => {
expect(inputNode.getAttribute('class')).toBe('mdl-textfield__input');
});
it('should render an empty textarea', () => {
expect(inputNode).toBeDefined();
expect(inputNode.type).toBe('textarea');
expect(inputNode.value).toBe('');
expect(() => findRenderedDOMComponentWithClass(reactComponent, 'label-error')).toThrow('Did not find exactly one match (found: 0) for class:label-error');
});
});
describe('when mounted with onChange props defined', () => {
let component, domNode, onChangeSpy;
const testValue = 'CHANGED_VALUE';
beforeEach(() => {
onChangeSpy = jest.fn(); // test that the method in props onChange is called
component = renderIntoDocument(<Textarea name='myTextArea' onChange={onChangeSpy} />);
});
it('should call the onChange function defined in props when textarea is changed', () => {
expect(onChangeSpy).not.toHaveBeenCalled();
Simulate.change(ReactDOM.findDOMNode(component.refs.htmlInput), { target: { value: testValue } });
expect(onChangeSpy).toHaveBeenCalledTimes(1);
});
});
describe('when an error is declared in props', () => {
let component, errorComponent, inputNode;
const errorLabel = 'this is an error';
beforeEach(() => {
component = renderIntoDocument(<Textarea error={errorLabel} name='myTextArea' onChange={fake} />);
inputNode = ReactDOM.findDOMNode(component.refs.htmlInput);
errorComponent = findRenderedDOMComponentWithClass(component, 'label-error');
});
it('should display the input textarea', () => {
expect(inputNode).toBeDefined();
expect(inputNode.getAttribute('pattern')).toBe('hasError');
});
it('should display the error', () => {
expect(errorComponent).toBeDefined();
expect(errorComponent.innerHTML).toBe(errorLabel);
});
});
});
|
System.register([], function (_export, _context) {
"use strict";
_export("default", function () {
return 'test';
});
return {
setters: [],
execute: function () {}
};
});
|
var arrayOfInts = [1, 10, -5, 1, -100];
function maxProduct(arr) {
var smallest = 0;
var almostSmallest = 0;
var largest = 0;
var second = 0;
var third = 0;
for(var i = 0; i < arr.length; i++ ) {
if(arr[i] > largest){
third = second
second = largest
largest = arr[i]
} else if(arr[i] > second) {
third = second
second = arr[i]
} else if(arr[i] > third){
third = arr[i]
} else if( arr[i] < 0) {
if(arr[i] < smallest) {
almostSmallest = smallest
smallest = arr[i];
} else {
if( arr[i] < almostSmallest) {
almostSmallest = arr[i]
}
}
}
}
if(smallest * almostSmallest > second * third) {
return largest * almostSmallest * smallest
}
return largest * second * third
}
maxProduct(arrayOfInts)
|
export default function isJavascript(scriptTag) {
// TODO: add a console warning if the script tag doesn't have an attribute?
// seems like it's required for some parts of ember consumption
let type = scriptTag.attributes.type ? scriptTag.attributes.type.value : 'text/javascript';
return /(?:application|text)\/javascript/i.test(type);
}
|
'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
(function () {
function pushComponent(array, component) {
if (!array) {
array = [];
}
array.push({ name: component.getAttribute('name'), source: '' + component.textContent });
return array;
}
function getComponents() {
var components = document.getElementsByClassName('component-template');
var componentTree = {};
[].concat(_toConsumableArray(components)).forEach(function (component) {
var componentType = component.getAttribute('data-type');
componentTree[componentType] = pushComponent(componentTree[componentType], component);
});
return componentTree;
}
function createFragment() {
return document.createDocumentFragment();
}
function listElementComponent() {}
function addToElement(source, destination) {
destination.innerHTML = source;
}
/* rewrite this */
function buildComponentList(tree) {
var fragment = createFragment();
var components = getComponents();
var keys = Object.keys(components);
var list = document.createElement('ul');
keys.forEach(function (key) {
var listItem = document.createElement('li');
var subList = document.createElement('ul');
var title = document.createElement('p');
title.textContent = key;
listItem.appendChild(title);
components[key].forEach(function (component) {
var item = document.createElement('li');
item.textContent = component.name;
subList.appendChild(item);
});
listItem.appendChild(subList);
list.appendChild(listItem);
});
fragment.appendChild(list);
document.getElementById('container').appendChild(fragment);
}
/* end */
// temp stuff for demo
buildComponentList(getComponents());
document.getElementById('addBanner').addEventListener('click', function () {
addToElement(getComponents().information[0].source, document.querySelector('.container'));
});
})();
|
(function(){
angular.module('nbTodos')
.component('todoEditor', {
templateUrl: '/app/todos/todo-editor/todo-editor.component.html',
controller: TodoEditorController,
controllerAs: 'vm'
});
TodoEditorController.$inject = ['todosStore'];
function TodoEditorController(todosStore) {
this.text = '';
this.create = function () {
if( this.text.trim().length === 0) {
this.error = true;
return;
}
todosStore.create(this.text);
this.text = '';
}
}
})();
|
import { UPDATE_BOMB_LOCATIONS, REMOVE_PLAYER_BOMBS } from './constants'
const initialState = {
}
//the bombs are stored in an 'allBombs' object within the state, that has keys of the user's socket ID, each with a property of an array of that user's bomb objects
export const bombs = (state = initialState, action) => {
let newState;
switch (action.type) {
case UPDATE_BOMB_LOCATIONS:
newState = Object.assign({}, state);
for (let key in action.allBombs) {
newState[key] = action.allBombs[key]
}
return newState;
case REMOVE_PLAYER_BOMBS:
newState = Object.assign({}, state)
delete newState[action.id]
return newState;
default:
return state;
}
}
|
$('.counter').countTo({
formatter: function (value, options) {
return value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,').slice(0,-3);
}
});
function updateCount(to)
{
$('.counter').countTo({
from: parseInt($('.counter').html().replace(/,/g, '')),
to: to,
formatter: function (value, options) {
return value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,').slice(0,-3);
}
});
}
function getUpdatedCount()
{
$.getJSON("https://petition.parliament.uk/petitions/131215.json", function (data){
updateCount(data.data.attributes.signature_count);
console.log("+" + (data.data.attributes.signature_count - parseInt($('.counter').html().replace(/,/g, ''))) );
});
}
function getCountryData()
{
$.getJSON("https://petition.parliament.uk/petitions/131215.json", function (data){
data.data.attributes.signatures_by_country.sort(function(a,b){
if (a.signature_count > b.signature_count){
return -1;
} else if (a.signature_count < b.signature_count){
return 1;
}
return 0;
});
$("#counties").html("");
data.data.attributes.signatures_by_country.slice(0, 10).forEach(function(item, index){
html = '<img class="flag flag-' + item.code.toLowerCase() + '"> <b>' + item.name + ':</b> ' + item.signature_count.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,').slice(0,-3) + '</p>';
$("#counties").append(html);
});
});
}
|
// LOL
import leftPad from 'left-pad';
export function stringToVec(string) {
// TODO: Handle #rgb form. We may want to use rgb(r, g, b) form, but
// it's not necessary.
if (string == null) return new Float32Array(3);
let r = parseInt(string.slice(1, 3), 16);
let g = parseInt(string.slice(3, 5), 16);
let b = parseInt(string.slice(5, 7), 16);
let vec = new Float32Array(3);
vec[0] = r / 255;
vec[1] = g / 255;
vec[2] = b / 255;
return vec;
}
export function vecToString(vec) {
let r = leftPad((vec[0] * 255 | 0).toString(16), 2, '0');
let g = leftPad((vec[1] * 255 | 0).toString(16), 2, '0');
let b = leftPad((vec[2] * 255 | 0).toString(16), 2, '0');
return '#' + r + g + b;
}
|
'use strict';
/**
* Rounds a number to decimal places
*
* @param {number} number to be rounded
* @param {integer} the number of place to round to
* @param {String} the rounding method to be used
* @returns {number} the number rounded to places
*/
function roundto(value, places, roundMethod) {
var rtn = 0;
var factorial = Math.pow(10, places);
roundMethod = typeof roundMethod !== 'undefined' ? roundMethod : 'round';
switch( roundMethod ) {
case 'floor':
case 'int':
rtn = Math.floor( value * factorial );
break;
case 'ceiling':
rtn = Math.ceil( value * factorial );
break;
default:
rtn = Math.round( value * factorial );
break;
}
// Divide number by factorial to get decimal places
rtn = rtn / factorial;
return rtn;
}
exports = module.exports = roundto;
|
'use strict'
const defaultAPIURL = 'https://api.runmycode.online/run'
const $ = s => document.querySelector(s)
const $$ = s => document.querySelectorAll(s)
const editBtn = $('#edit')
const error = $('#error')
const apiUrl = $('#api-url')
const apiKey = $('#api-key')
const saveBtn = $('#save')
const inputs = Array.from($$('input'))
const toggleInputs = () => {
inputs.forEach((el) => {
if (el.type === 'button') el.disabled = !el.disabled
else if (el.type === 'text') {
el.getAttribute('readonly') ? el.removeAttribute('readonly') : el.setAttribute('readonly', 'readonly')
}
})
}
const enableEdit = () => {
saveBtn.value = 'Save'
toggleInputs()
}
const saveOptions = (e) => {
if (apiUrl.value === '') apiUrl.value = defaultAPIURL
error.style.display = 'block'
if (apiUrl.value !== defaultAPIURL && apiUrl.value.indexOf('.amazonaws.com') === -1) {
error.textContent = `Only ${defaultAPIURL} and AWS API Gateway URLs are supported as API URL`
return
} else if (!apiKey.value && apiUrl.value === defaultAPIURL) {
error.textContent = 'Key cannot be empty for https://api.runmycode.online/run'
return
// key may be not required for custom RunMyCode deployment
}
error.style.display = 'none'
browser.storage.local.set({
'apiUrl': apiUrl.value,
'apiKey': apiKey.value
})
saveBtn.value = 'Saved'
if (e) toggleInputs() // toggle inputs only if save from btn click
}
const restoreOptions = () => {
const getApiUrl = browser.storage.local.get('apiUrl')
const getApiKey = browser.storage.local.get('apiKey')
Promise.all([getApiUrl, getApiKey])
.then((result) => {
apiUrl.value = result[0]['apiUrl'] || defaultAPIURL
apiKey.value = result[1]['apiKey'] || ''
saveOptions()
})
.catch((error) => {
console.log('Error: ', error)
})
}
document.addEventListener('DOMContentLoaded', restoreOptions)
saveBtn.addEventListener('click', saveOptions)
editBtn.addEventListener('click', enableEdit)
|
import React, { Component } from 'react'
import { Layout, Wrapper, Spacer } from './components/Styles'
/*eslint-disable*/
import IconTest from './IconTest'
import { ButtonTest, ButtonTest2 } from './ButtonTest'
/*eslint-enable*/
class App extends Component {
render() {
return (
<div>
<Wrapper>
<Layout>
<div>
<ButtonTest />
<Spacer space={'0.8rem'} />
<ButtonTest2 />
<Spacer space={'0.8rem'} />
{/*<IconTest />*/}
</div>
</Layout>
</Wrapper>
</div>
)
}
}
export default App
|
"use strict";
const forOwn = require('mout/object/forOwn');
const split = new RegExp("\\s*(.+?)(?:=\\s*(?:\"([^\"]*)\"|'([^']*)'|(.*?)))?\\s*(;|$)", "g");
var parse = function(str) {
var res;
var out = {};
while((res = split.exec(str)))
out[res[1]] = res[2] || res[3] || res[4] || null;
return out;
};
parse.parse_cookie = function(str) {
var raw = parse(str);
var name = Object.keys(raw)[0];
var cookie = {value : raw[name], name : name, extras : {}};
delete raw[name];
forOwn(raw, function(v, k) { cookie.extras[k.toLowerCase()] = v; });
return cookie;
};
module.exports = parse;
|
var through = require('through2');
var should = require('should');
var dat = require('dat');
var File = require('vinyl');
var bops = require('bops');
var vdat = require('..');
describe('dest stream', function () {
var destPath = 'test/data/test-dest';
beforeEach(function (done) {
var db = dat(destPath, function (err) {
if (err) return done(err);
db.destroy(done);
});
});
it('should be a stream', function (done) {
var db = dat(destPath, function (err) {
if (err) return done(err);
var output = vdat.dest(db);
should.exist(output.pipe);
output.on('end', function () {
db.close(done);
});
output.write({foo: 'bar'});
output.end();
});
});
it('should write a vinyl file to dat', function (done) {
var expected = new File({
path: 'test-001',
contents: bops.from(JSON.stringify({foo: 'bar'}))
});
var db = dat(destPath, function (err) {
if (err) return done(err);
var output = vdat.dest(db);
output.on('end', function () {
db.get('test-001', function (err, record) {
if (err) done(err);
should.exist(record);
should.exist(record.version);
record.version.should.eql(1);
db.close(done);
});
});
output.write(expected);
output.end();
});
});
});
|
define([], function() {
Path.map("#!/products").to(function(){
}).enter(function() {
require([
'tpl!template/products.html', 'tpl!template/username.html', 'tpl!template/product-tpl.html',
'bootstrap', 'bootstrapHover', 'utils'
], function(tpl, userTpl, productTpl) {
pageStart(tpl, userTpl);
function render(){
var products = JSON.parse(localStorage.getItem('products'));
$('.js-products').empty();
if(products != null){
$.each(products, function(index, value){
$('.js-products').append($(productTpl.apply(value)));
});
} else{
$('.js-products').append("<h3>No search results</h3>");
}
}
setTimeout(render, 100);
var done = false;
$(document).delegate('.js-form-search', 'submit', function(e){
setTimeout(render, 100);
})
.delegate('.js-brands span', 'click', function(e){
var $target = $(e.target),
search = $target.attr('data-search'),
xhr;
xhr = $.ajax({
url: 'api/index.php/products',
type: 'POST',
data: JSON.stringify({
search: search
})
});
xhr
.done(function(response){
var products = response.data;
localStorage.setItem('products', JSON.stringify(products));
setTimeout(render, 100);
}).fail(function(jqXHR, status, error){
var response = JSON.parse(jqXHR.responseText);
localStorage.setItem('products', null);
})
.always(function(response){
});
})
.delegate('.js-flavors a', 'click', function(e){
var $target = $(e.currentTarget),
filter = $target[0].text.toLowerCase(),
$ele = $('[data-flavor='+filter+']');
if(filter == 'clear'){
$('.js-product').parent().fadeIn().removeClass('hidden');
}else{
$('.js-product').parent().fadeOut(function(){
$(this).addClass('hidden');
$ele.parent().fadeIn().removeClass('hidden');
});
if(!done){
$ele.parent( ":hidden" ).fadeIn().removeClass('hidden');
done = true;
}
}
});
});
}).exit(function() {
// Exit from route
$('#main').off().empty();
});
});
|
/**
* aria support for slide
* @author yiminghe@gmail.com
*/
KISSY.add("switchable-ext/slide/aria", function (S, DOM, Event, Switchable) {
// var KEY_PAGEUP = 33;
// var KEY_PAGEDOWN = 34;
// var KEY_END = 35;
// var KEY_HOME = 36;
var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;
// var KEY_TAB = 9;
// var KEY_SPACE = 32;
// var KEY_BACKSPACE = 8;
// var KEY_DELETE = 46;
// var KEY_ENTER = 13;
// var KEY_INSERT = 45;
// var KEY_ESCAPE = 27;
var Aria = Switchable.Aria;
var Slide = Switchable.Slide;
S.mix(Slide.Config, {
aria:false
});
var DOM_EVENT = {originalEvent:{target:1}};
var setTabIndex = Aria.setTabIndex;
Slide.Plugins.push({
name:"aria",
init:function (self) {
if (!self.config.aria) {
return;
}
var triggers = self.triggers;
var panels = self.panels;
var i = 0;
var activeIndex = self.activeIndex;
S.each(triggers, function (t) {
setTabIndex(t, "-1");
i++;
});
i = 0;
S.each(panels, function (p) {
setTabIndex(p, activeIndex == i ? "0" : "-1");
DOM.attr(p, "role", "option");
i++;
});
var content = self.content;
DOM.attr(content, "role", "listbox");
Event.on(content, "keydown", _contentKeydownProcess, self);
setTabIndex(panels[0], 0);
self.on("switch", function (ev) {
var index = ev.currentIndex,
domEvent = !!(ev.originalEvent.target || ev.originalEvent.srcElement),
last = ev.fromIndex;
if (last > -1) {
setTabIndex(panels[last], -1);
}
setTabIndex(panels[index], 0);
//dom 触发的事件,自动聚焦
if (domEvent) {
panels[index].focus();
}
});
}
});
function _contentKeydownProcess(e) {
var self = this,
key = e.keyCode;
switch (key) {
case KEY_DOWN:
case KEY_RIGHT:
self.next(DOM_EVENT);
e.halt();
break;
case KEY_UP:
case KEY_LEFT:
self.prev(DOM_EVENT);
e.halt();
break;
}
}
}, {
requires:["dom", "event", 'switchable']
});
/**
2011-05-12 yiminghe@gmail.com:add support for aria & keydown
<h2>键盘操作</h2>
<ul class="list">
<li>tab 进入卡盘时,停止自动播放</li>
<li>上/左键:当焦点位于卡盘时,切换到上一个 slide 面板</li>
<li>下/右键:当焦点位于卡盘时,切换到下一个 slide 面板</li>
<li>tab 离开卡盘时,开始自动播放</li>
</ul>
**/
|
if (!Number.isInteger) {
Number.isInteger = function(value) {
return typeof value === 'number'
&& isFinite(value)
&& Math.floor(value) === value;
};
}
|
import Immutable from 'immutable';
export const currentUser = Immutable.fromJS({
value: {
_id: 'user/0',
_rev: '55781764180',
_key: '0',
entityId: 'entities/0',
},
});
export const entitiesWithoutAttribute = Immutable.fromJS({
value: {
'entities/0': {
_id: 'entities/0',
_rev: '55781764180',
_key: '0',
type: 'entityTypes/10',
},
},
});
export const entitiesWithAttributes = Immutable.fromJS({
value: {
'entities/0': {
_id: 'entities/0',
_rev: '55781764180',
_key: '0',
type: 'entityTypes/10',
relatedIds: ['attributes/0', 'attributes/1'],
},
},
});
export const noAttribute = Immutable.fromJS({
value: {},
});
export const attributesLinkedToEntity = Immutable.fromJS({
value: {
'attributes/0': {
_id: 'attributes/0',
_rev: '55781764180',
_key: '0',
attrKey: 'attributeKeys/701',
entityId: 'entities/0',
},
'attributes/1': {
_id: 'attributes/0',
_rev: '55781764180',
_key: '1',
attrKey: 'attributeKeys/700',
entityId: 'entities/0',
},
},
});
export const attributeKeys = Immutable.fromJS({
value: {
'attributeKeys/700': {
_id: 'attributeKeys/700',
_rev: '21879324714',
_key: '700',
kind: 'X',
name: 'MINDSET',
constraint: 'entityTypes/10',
},
'attributeKeys/701': {
_id: 'attributeKeys/701',
_rev: '21879455786',
_key: '701',
kind: 'Y',
name: 'MINDSET',
constraint: 'entityTypes/100',
},
},
});
export const visualizations = Immutable.fromJS({
value: {
'vis/1': {
id: 'vis/1',
organisationId: 'entitiyes/1',
graphLayout: { nodes: {}, links: {} },
},
},
});
export const emptyVisualization = Immutable.fromJS({
value: {},
});
|
import Vue from 'vue';
import socket from './sockets';
export default () => new Vue({
el: '#test_donation',
data: {
name: '',
displayName: '',
amount: 0
},
methods: {
clear: function(){
this.name = '';
this.displayName = '';
this.amount = 0;
},
display: function(){
const send = {
name: this.name,
displayName: this.displayName,
amount: this.amount
};
console.log(send);
socket.emit('test-notification', send);
this.clear();
}
}
})
|
// Given a collection of intervals, merge all overlapping intervals.
// For example,
// Given [1,3],[2,6],[8,10],[15,18],
// return [1,6],[8,10],[15,18].
/**
* Definition for an interval.
* function Interval(start, end) {
* this.start = start;
* this.end = end;
* }
*/
/**
* @param {Interval[]} intervals
* @return {Interval[]}
*/
function merge(intervals) { // 148 ms runtime
if (!intervals.length) return intervals;
intervals.sort((a, b) => a.start !== b.start ? a.start - b.start : a.end - b.end);
var prev = intervals[0],
res = [prev];
for (var curr of intervals) {
if (curr.start <= prev.end) {
prev.end = Math.max(prev.end, curr.end);
} else {
res.push(curr);
prev = curr;
}
}
return res;
}
//---------------------------------------------------------
var merge = function(intervals) {
if( intervals.length < 1 ) return intervals;
var start = [],
end = [];
for( var i=0; i<intervals.length; i++ ){
start.push( intervals[i].start );
end.push( intervals[i].end );
}
// if end[i] < start[j]
// store end
// j++
// else
// store start
// i++
var result = [],
tempStart = start[0];
for( var j=0, k=0; j< start.length || k<end.length; ){
if( start[j] < end[k] ){
tempStart = Math.min(tempStart, start[j]);
j++;
} else {
result.push( [tempStart, end[k+1]] );
tempStart = start[j];
k++;
j++;
}
}
// [ 1, 2, 8, 15 ]
// [ 3, 6, 10, 18 ]
return result;
};
|
(function () {
'use strict';
angular
.module('tables')
.config(routeConfig);
routeConfig.$inject = ['$stateProvider'];
function routeConfig($stateProvider) {
$stateProvider
.state('tables', {
abstract: true,
url: '/tables',
template: '<ui-view/>'
})
.state('tables.list', {
url: '',
templateUrl: 'modules/tables/client/views/list-tables.client.view.html',
controller: 'TablesListController',
controllerAs: 'vm',
data: {
pageTitle: 'Tables List'
}
})
.state('tables.create', {
url: '/create',
templateUrl: 'modules/tables/client/views/form-table.client.view.html',
controller: 'TablesController',
controllerAs: 'vm',
resolve: {
tableResolve: newTable
},
data: {
pageTitle : 'Tables Create'
}
})
.state('tables.edit', {
url: '/:tableId/edit',
templateUrl: 'modules/tables/client/views/form-table.client.view.html',
controller: 'TablesController',
controllerAs: 'vm',
resolve: {
tableResolve: getTable
},
data: {
roles: ['*'],
pageTitle: 'Edit Table {{ tableResolve.name }}'
}
})
.state('tables.view', {
url: '/:tableId',
templateUrl: 'modules/tables/client/views/view-table.client.view.html',
controller: 'TablesController',
controllerAs: 'vm',
resolve: {
tableResolve: getTable
},
data:{
pageTitle: 'Table {{ articleResolve.name }}'
}
});
}
getTable.$inject = ['$stateParams', 'TablesService'];
function getTable($stateParams, TablesService) {
return TablesService.get({
tableId: $stateParams.tableId
}).$promise;
}
newTable.$inject = ['TablesService'];
function newTable(TablesService) {
return new TablesService();
}
})();
|
import * as types from '../constants/actionTypes';
const initialState = {
startTime: 0,
endTime: null
};
export default function counter(state = initialState, action) {
switch (action.type) {
case types.SET_PLAY_TIME:
return {
startTime: action.startTime,
endTime: action.endTime
};
default:
return state;
}
};
|
/**
* @module og/bv/Sphere
*/
'use strict';
import { Vec3 } from '../math/Vec3.js';
/**
* Bounding sphere class.
* @class
* @param {Number} [radius] - Bounding sphere radius.
* @param {og.Vec3} [center] - Bounding sphere coordiantes.
*/
class Sphere {
constructor(radius, center) {
/**
* Sphere radius.
* @public
* @type {Number}
*/
this.radius = radius || 0;
/**
* Sphere coordiantes.
* @public
* @type {og.Vec3}
*/
this.center = center ? center.clone() : new Vec3();
}
/**
* Sets bounding sphere coordinates by the bounds array.
* @param {Array.<number>} bounds - Bounds is an array where [minX, minY, minZ, maxX, maxY, maxZ]
*/
setFromBounds(bounds) {
let m = new Vec3(bounds[0], bounds[1], bounds[2]);
this.center.set(m.x + (bounds[3] - m.x) * 0.5, m.y + (bounds[3] - m.y) * 0.5, m.z + (bounds[5] - m.z) * 0.5);
this.radius = this.center.distance(m);
}
/**
* Sets bounding sphere coordiantes by ellipsoid geodetic extend.
* @param {og.Ellipsoid} ellipsoid - Ellipsoid.
* @param {og.Extent} extent - Geodetic extent.
*/
setFromExtent(ellipsoid, extent) {
this.setFromBounds(extent.getCartesianBounds(ellipsoid));
}
};
export { Sphere };
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import * as postsActions from 'redux/modules/posts';
import { asyncConnect } from 'redux-connect';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import ListPosts from '../Posts/ListPosts';
@asyncConnect([{
promise: ({ store: { dispatch, getState } }) => {
dispatch(postsActions.load({
user_id: getState().auth.user.id
}));
}
}])
@connect(
state => ({
posts: state.posts.items
}),
{ ...postsActions, pushState: push }
)
export default class Posts extends Component {
static propTypes = {
posts: PropTypes.array.isRequired,
clearItems: PropTypes.func.isRequired,
dispatch: PropTypes.func.isRequired,
pushState: PropTypes.func.isRequired
};
static defaultProps = {
posts: []
};
static contextTypes = {
};
state = {
editId: 0
}
componentWillUnmount() {
if (!this.state.editId) {
this.props.dispatch(this.props.clearItems());
}
}
gotoEdit = id => {
this.setState({
editId: id
});
this.props.pushState(`/profile/edit_post/${id}`);
}
render() {
const { posts } = this.props;
return (
<div>
<h1>My Posts</h1>
<ListPosts items={posts} editable gotoEdit={this.gotoEdit} />
</div>
);
}
}
|
import React from 'react';
function Home(props) {
return (
<div id='react-home'>
<h1>BC</h1>
<h2>FreeCodeCamp Projects using React</h2>
</div>
);
}
export default Home
|
import axios from 'axios'
export const setAuthorization = token => {
if (token) {
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
} else {
delete axios.defaults.headers.common['Authorization']
}
}
|
/*
* Populate DB with sample data on server start
* to disable, edit config/environment/index.js, and set `seedDB: false`
*/
'use strict';
var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var env = process.env.NODE_ENV || 'development';
var User = require('../api/user/user.model').model;
var Customer = require('../api/customer/customer.model').model;
var Lot = require('../api/lot/lot.model').model;
var Shipment = require('../api/shipment/shipment.model').model;
var Product = require('../api/product/product.model').model;
/*
// Insert some data needed to bootstrap or init the application
if ('production' === env) {
// Insert some data needed to init the production instance only, update a version info ...
}
*/
/*
* Insert dummy data to test the application
*/
exports.users = [{
provider: 'local',
name: 'Test User',
password: 'password',
active: true
}, {
provider: 'local',
role: 'admin',
name: 'Admin',
password: 'password',
active: true
}, {
provider: 'local',
role: 'root',
name: 'Root',
password: 'password',
active: true
}];
exports.shipments = [
{
// _id: '57b4bcf47a18a5b400923d78',
orderId:"DKcRNc7XN",
creationDate:"Aug 6, 2016",
shipByDate:"Aug 12, 2016",
status:"Shipment confirmed",
units:1,
payments:"$3.92",
sku: "06F",
// product: ObjectId('57b4bcf37a18a5b400923d75'),
// customer: ObjectId('57b4bcf37a18a5b400923d73')
}, {
// _id: '57b4bcf47a18a5b400923d79',
orderId:"DplMb07cN",
creationDate:"Aug 6, 2016",
shipByDate:"Aug 12, 2016",
status:"Unshipped",
units:1,
payments:"$6.78",
sku: '12P',
// product: ObjectId('57b4bcf37a18a5b400923d76'),
// customer: ObjectId('57b4bcf37a18a5b400923d74')
},{
// _id: '57b4bcf47a18a5b400923d7a',
orderId:"DpTMbp7bN",
creationDate:"Aug 6, 2016",
shipByDate:"Aug 12, 2016",
status:"Shipment confirmed",
units:1,
payments:"$3.92",
sku: "06F",
// product: '57b4bcf37a18a5b400923d77',
// customer: '57b4bcf37a18a5b400923d74'
}];
exports.customers = [{
// _id: '57b4bcf37a18a5b400923d73',
name: 'Amazon Locker - Hannah',
address: {
street: '12355 15th Ave NE at 7-Eleven',
city: 'Seattle',
state: 'WA',
zip: '98125-4819'
},
phone: "2064985471"
},{
// _id: '57b4bcf37a18a5b400923d74',
name: 'Amazon Locker - George',
address: {
street: '12355 15th Ave NE at 7-Eleven',
city: 'Seattle',
state: 'WA',
zip: '98125-4819'
},
phone: "2064985468"
}];
exports.lots = [{
created: "Aug 11, 2016",
shipped: "Aug 12, 2016",
shipments: []
}];
exports.products = [{
// _id: '57b4bcf37a18a5b400923d77',
name: 'Finess Softpatch for Stress Incontinence',
upc: '860507000213',
asin: 'B01438A52M'
}, {
// _id: '57b4bcf37a18a5b400923d76',
name: 'Finess Softpatch for Stress Incontinence',
upc: '860507000206',
asin: 'B013TT27TA'
}, {
// _id: '57b4bcf37a18a5b400923d75',
name: 'Finess Softpatch for Stress Incontinence',
upc: '860507000220',
asin: 'B01DEDVJLI'
}];
// Join all address fields of customers
exports.customers = exports.customers.map(function(customer) {
var addr = customer.address, lines = [];
lines.push(addr.street);
lines.push(addr.city + ', ' + addr.state + ' ' + addr.zip);
customer.address = lines.join('\n');
return customer;
})
if ('development' === env || 'test' === env) {
console.log('Populating test and development data ...');
User.find({}).remove(function () {
User.create(exports.users, function (err) {
if (err) {
console.error('Error while populating users: %s', err);
} else {
console.log('finished populating users');
}
});
});
Customer.find({}).remove(function () {
Customer.create(exports.customers, function (err) {
if (err) {
console.error('Error while populating customers: %s', err);
} else {
console.log('finished populating customers');
popProducts();
}
});
});
function popProducts() {
Product.find({}).remove(function () {
Product.create(exports.products, function (err) {
if (err) {
console.error('Error while populating products: %s', err);
} else {
console.log('finished populating products');
popShipments();
}
});
});
}
function popShipments() {
Shipment.find({}).remove(function () {
Customer.find({}).exec().then(function(customers) {
exports.shipments.forEach(function (shipment, i) {
shipment.customer = customers[i%2]['_id'];
})
Product.find({}).exec().then(function(products) {
exports.shipments.forEach(function (shipment, i) {
shipment.product = products[i%3]['_id'];
})
Shipment.create(exports.shipments, function (err) {
if (err) {
console.error('Error while populating shipments: %s', err);
} else {
console.log('finished populating shipments');
popLots();
}
});
});
})
});
}
function popLots() {
Lot.find({}).remove(function () {
Shipment.find({}).exec().then(function(shipments) {
// console.log('in popLots, shipments: ' + JSON.stringify(shipments))
exports.lots.forEach(function (lot, i) {
lot.shipments.push(shipments[0]['_id']);
lot.shipments.push(shipments[2]['_id']);
// console.log('created lot shipments: ' + JSON.stringify(lot.shipments))
})
Lot.create(exports.lots, function (err) {
if (err) {
console.error('Error while populating lots: %s', err);
} else {
console.log('finished populating lots');
}
});
})
});
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.