text
stringlengths 2
6.14k
|
|---|
const rangeParser = require(`parse-numeric-range`)
module.exports = language => {
if (!language) {
return ``
}
if (language.split(`{`).length > 1) {
let [splitLanguage, ...options] = language.split(`{`)
let highlightLines = [],
numberLines = false,
numberLinesStartAt
// Options can be given in any order and are optional
options.forEach(option => {
option = option.slice(0, -1)
// Test if the option is for line hightlighting
if (rangeParser.parse(option).length > 0) {
highlightLines = rangeParser.parse(option).filter(n => n > 0)
}
option = option.split(`:`)
// Test if the option is for line numbering
// Option must look like `numberLines: true` or `numberLines: <integer>`
// Otherwise we disable line numbering
if (
option.length === 2 &&
option[0] === `numberLines` &&
(option[1].trim() === `true` ||
Number.isInteger(parseInt(option[1].trim(), 10)))
) {
numberLines = true
numberLinesStartAt =
option[1].trim() === `true` ? 1 : parseInt(option[1].trim(), 10)
}
})
return {
splitLanguage,
highlightLines,
numberLines,
numberLinesStartAt,
}
}
return { splitLanguage: language }
}
|
import ruleError from './ruleError'
// Tags that have no associated components but are allowed even so
const componentLessTags = [
'mj-all',
'mj-class',
'mj-selector',
'mj-html-attribute',
]
export default function validateTag(element, { components }) {
const { tagName } = element
if (componentLessTags.includes(tagName)) return null
const Component = components[tagName]
if (!Component) {
return ruleError(
`Element ${tagName} doesn't exist or is not registered`,
element,
)
}
return null
}
|
class dximagetransform_microsoft_crblinds_1 {
constructor() {
// short bands () {get} {set}
this.bands = undefined;
// int Capabilities () {get}
this.Capabilities = undefined;
// string Direction () {get} {set}
this.Direction = undefined;
// float Duration () {get} {set}
this.Duration = undefined;
// float Progress () {get} {set}
this.Progress = undefined;
// float StepResolution () {get}
this.StepResolution = undefined;
}
}
module.exports = dximagetransform_microsoft_crblinds_1;
|
'use strict';
var webpack = require('webpack');
var cfg = {
entry: './src/main.jsx',
output: {
path: __dirname + '/dist',
filename: 'main.js',
},
externals: {
yaspm: 'commonjs yaspm'
},
target: process.env.NODE_ENV === 'web' ? 'web' : 'node-webkit',
module: {
loaders: [
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
loader: 'style-loader!css-loader!sass-loader?includePaths[]=' +
__dirname + '/src'
},
{
test: /\.(js|jsx)$/,
loader: 'jsx-loader?harmony'
}
]
},
plugins: [
new webpack.DefinePlugin({
'__NODEWEBKIT__': process.env.NODE_ENV === 'nodewebkit',
})
]
};
module.exports = cfg;
|
/**
* Created by ff on 2016/10/25.
*/
require('./style.css');
var vm = avalon.define({
$id:'map'
})
module.exports = vm;
|
'use strict';
const _ = require('lodash');
const path = require('path');
/**
* Special settings for use with serverless-offline.
*/
module.exports = {
prepareOfflineInvoke() {
// Use service packaging for compile
_.set(this.serverless, 'service.package.individually', false);
return this.serverless.pluginManager.spawn('webpack:validate').then(() => {
// Set offline location automatically if not set manually
if (!this.options.location && !_.get(this.serverless, 'service.custom.serverless-offline.location')) {
_.set(
this.serverless,
'service.custom.serverless-offline.location',
path.relative(this.serverless.config.servicePath, path.join(this.webpackOutputPath, 'service'))
);
}
return null;
});
}
};
|
let widget = document.getElementsByClassName('markdownx-widget')[0];
let element = document.getElementsByClassName('markdownx');
let element_divs = element[0].getElementsByTagName('div');
let div_editor = element_divs[0];
let div_preview = element_divs[1];
let navbar_bar = document.getElementsByClassName('markdownx-toolbar')[0].getElementsByTagName('li');
let btn_preview = navbar_bar[0];
let btn_fullscreen = navbar_bar[1];
var turn_active = function(element) {
value = element.classname;
classval = element.getAttribute('class');
if (value.indexOf('active') >= 0) {
element.removeClass('active');
}
else {
value += 'active'
}
}
var refresh_pretty = function() {
// 每次有都需要重新渲染code
PR.prettyPrint();
};
var enable_preview = function() {
var class_btn_preview = btn_preview.getAttribute('class');
var index = class_btn_preview.indexOf('active');
if (index >= 0) {
btn_preview.setAttribute('class', '');
div_editor.setAttribute('class', 'col-md-12 child-left');
div_preview.style.display = 'none';
}
else {
btn_preview.setAttribute('class', 'active');
div_editor.setAttribute('class', 'col-md-6 child-left');
div_preview.style.display = 'block';
}
};
var enable_fullscreen = function() {
var class_btn_fullscreen = btn_fullscreen.getAttribute('class');
var index = class_btn_fullscreen.indexOf('active');
if (index >= 0) {
btn_fullscreen.setAttribute('class', '');
widget.setAttribute('class', 'markup-widget');
}
else{
btn_fullscreen.setAttribute('class', 'active');
widget.setAttribute('class', 'markup-widget fullscreen');
}
}
Object.keys(element).map(key =>
element[key].addEventListener('markdownx.update', refresh_pretty)
);
btn_preview.addEventListener('click', enable_preview);
btn_fullscreen.addEventListener('click', enable_fullscreen);
|
module.exports = {};
var app_data = {};
function initCharts()
{
$(document).ready(function() {
$.get(app_data.config.analytics_data_route, function(analytics_data) {
data = analytics_data.data;
max_val = analytics_data.highest_value;
var parseDate = d3.time.format('%Y%m%d').parse;
data.forEach(function(d) {
d.date = parseDate(d.date);
});
$('.sessions-value').html(formatAnalyticsValue((analytics_data.total_sessions).toString()));
$('.views-value').html(formatAnalyticsValue((analytics_data.total_views).toString()));
d3.select(window).on('resize', resize);
loadCharts();
}, 'json');
});
}
function loadChart(data, max_val, selector, graph_width, graph_height)
{
var margin = { top: 20, right: 0, bottom: 30, left: 50 },
width = graph_width - margin.left - margin.right,
height = graph_height - margin.top - margin.bottom;
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var color = d3.scale.category10();
var x_axis = d3.svg.axis().scale(x).orient('bottom'); //.tickFormat(d3.time.format('%m/%d/%y'));
var y_axis = d3.svg.axis().scale(y).orient('left').ticks(6);
var line = d3.svg.line()
.interpolate('cardinal')
.tension(0.8)
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.val); });
var line_gridline = d3.svg.line()
.x(function(d) { return x(d[0]); })
.y(function(d) { return y(d[1]); });
var area = d3.svg.area()
.interpolate('cardinal')
.tension(0.8)
.x(function(d) { return x(d.date); })
.y0(height)
.y1(function(d) { return y(d.val); });
d3.select(selector + ' > svg').remove();
var svg = d3.select(selector).append('svg')
.attr('viewBox', '0 0 ' + graph_width + ' ' + graph_height)
.attr('perserveAspectRatio', 'xMinYMid')
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
color.domain([ 'sessions', 'views' ]);
var analytics = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, val: +d[name]};
})
};
});
var x_extent = d3.extent(data, function(d) { return d.date; });
x.domain(x_extent);
y.domain([
d3.min(analytics, function(c) { return 0; }),
d3.max(analytics, function(c) { return max_val; /*d3.max(c.values, function(v) { return v.val; });*/ })
]);
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(x_axis);
svg.append('g')
.attr('class', 'y axis')
.call(y_axis)
.append('text')
.style('text-anchor', 'end');
var gridline_data = [];
svg.selectAll('.y.axis .tick').each(function(data) {
var tick = d3.select(this);
var transform = d3.transform(tick.attr('transform')).translate;
if (data > 0)
{
gridline_data.push({ values: [[x_extent[0], transform[1]], [x_extent[1], transform[1]]] });
}
});
gridline_data.forEach(function(data) {
svg.append('line')
.attr('class', 'gridline')
.attr('x1', x(data.values[0][0]))
.attr('x2', x(data.values[1][0]))
.attr('y1', data.values[0][1])
.attr('y2', data.values[1][1]);
});
var analytics_line = svg.selectAll('.analytics_line')
.data(analytics)
.enter().append('g')
.attr('class', 'analytics_line');
analytics_line.append('path')
.attr('class', 'line')
.attr('d', function(d) { return line(d.values); })
.style('stroke', function(d) { return '#f2711c'; });
analytics_line.append('path')
.attr('class', 'area')
.attr('d', function(d) { return area(d.values); })
.style('fill', function(d) { return '#f2711c'; });
/*analytics.forEach(function(category) {
category.values.forEach(function(item) {
analytics_line.append('circle')
.attr('class', 'dot')
.attr('r', 4)
.attr('cx', x(item.date))
.attr('cy', y(item.val))
.style('fill', '#f2711c');
});
});*/
}
function formatAnalyticsValue(value)
{
var formatted_val = '';
var c = 1;
for (var i=value.length-1; i>=0; i--)
{
formatted_val = (c++ % 3 == 0 && i > 0 ? ' ' : '') + value.substring(i, i+1) + formatted_val;
}
return formatted_val;
}
var aspect = 4;
var chart = null;
var data = null;
var max_val = 0;
var resize_timeout = -1;
function resize()
{
if (resize_timeout != -1) clearTimeout(resize_timeout);
resize_timeout = setTimeout(function() {
resize_timeout = -1;
loadCharts();
}, 1000);
}
function loadCharts()
{
if (data == null) return;
var width = $('.analytics-graph').width();
var height = Math.max(200, $('.analytics-graph').width()/aspect); //prevents height to be smaller than 200px
loadChart(data, max_val, '.analytics-graph', width, height);
chart = $('.analytics-graph > svg');
}
module.exports.init = function(trans, config) {
app_data.trans = trans;
app_data.config = config;
$(document).ready(function() {
initCharts();
});
};
|
const SpecReporter = require('jasmine-spec-reporter').SpecReporter;
jasmine.getEnv().clearReporters(); // remove default reporter logs
jasmine.getEnv().addReporter(new SpecReporter({ // add jasmine-spec-reporter
spec: {
displayPending: true,
},
summary: {
displayDuration: true,
}
}));
|
const webpack = require('atool-build/lib/webpack');
module.exports = function (webpackConfig, env) {
webpackConfig.babel.plugins.push('transform-runtime');
webpackConfig.babel.plugins.push(['import', {
libraryName: 'antd',
style: 'css' // if true, use less
}]);
// Support hmr
if (env === 'development') {
webpackConfig.devtool = '#eval';
webpackConfig.babel.plugins.push('dva-hmr');
} else {
webpackConfig.babel.plugins.push('dev-expression');
}
// Don't extract common.js and common.css
webpackConfig.plugins = webpackConfig.plugins.filter(function (plugin) {
return !(plugin instanceof webpack.optimize.CommonsChunkPlugin);
});
// Support CSS Modules
// Parse all less files as css module.
webpackConfig.module.loaders.forEach(function (loader, index) {
if (typeof loader.test === 'function' && loader.test.toString().indexOf('\\.less$') > -1) {
loader.include = /node_modules/;
loader.test = /\.less$/;
}
if (loader.test.toString() === '/\\.module\\.less$/') {
loader.exclude = /node_modules/;
loader.test = /\.less$/;
}
if (typeof loader.test === 'function' && loader.test.toString().indexOf('\\.css$') > -1) {
loader.include = /node_modules/;
loader.test = /\.css$/;
}
if (loader.test.toString() === '/\\.module\\.css$/') {
loader.exclude = /node_modules/;
loader.test = /\.css$/;
}
});
return webpackConfig;
};
|
'use strict';
describe('Controllers Tests ', function () {
beforeEach(module('solrpressApp'));
describe('SessionsController', function () {
var $scope, SessionsService;
beforeEach(inject(function ($rootScope, $controller, Sessions) {
$scope = $rootScope.$new();
SessionsService = Sessions;
$controller('SessionsController',{$scope:$scope, Sessions:SessionsService});
}));
it('should invalidate session', function () {
//GIVEN
$scope.series = "123456789";
//SET SPY
spyOn(SessionsService, 'delete');
//WHEN
$scope.invalidate($scope.series);
//THEN
expect(SessionsService.delete).toHaveBeenCalled();
expect(SessionsService.delete).toHaveBeenCalledWith({series: "123456789"}, jasmine.any(Function), jasmine.any(Function));
//SIMULATE SUCCESS CALLBACK CALL FROM SERVICE
SessionsService.delete.calls.mostRecent().args[1]();
expect($scope.error).toBeNull();
expect($scope.success).toBe('OK');
});
});
});
|
Template.registerHelper("itemTypes", function() {
return [
{label: i18n.t('choose'), value: ''},
{label: i18n.t('offer'), value: 'offer', icon: 'icon gift'},
{label: i18n.t('need'), value: 'need', icon: 'icon fire'},
{label: i18n.t('wish'), value: 'wish', icon: 'icon wizard'},
{label: i18n.t('idea'), value: 'idea', icon: 'icon cloud'}
]
})
|
var GlobezGame = GlobezGame || {};
GlobezGame.Boot = function() {};
GlobezGame.Boot.prototype = {
preload: function() {
console.log("%cStarting Fish Vs Mines", "color:white; background:red");
this.load.image("loading", "assets/sprites/loading.png");
this.load.image("logo", "assets/sprites/logo.png");
},
create: function() {
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
// this.scale.setScreenSize(true);
this.physics.startSystem(Phaser.Physics.ARCADE);
this.state.start("Preload");
}
}
var GlobezGame = GlobezGame || {};
GlobezGame.Preload = function() {};
GlobezGame.Preload.prototype = {
preload: function() {
console.log("%cPreloading assets", "color:white; background:red")
var loadingBar = this.add.sprite(160, 340, "loading");
loadingBar.anchor.setTo(0.5, 0.5);
this.load.setPreloadSprite(loadingBar);
var logo = this.add.sprite(160, 240, "logo");
logo.anchor.setTo(0.5, 0.5);
this.load.image("background", "assets/sprites/background.png");
this.load.image("playbutton", "assets/sprites/playbutton.png");
this.load.image("gametitle_sealife", "assets/sprites/gametitle_sealife.png");
this.load.image("gametitle_vs", "assets/sprites/gametitle_vs.png");
this.load.image("gametitle_mines", "assets/sprites/gametitle_mines.png");
this.load.image("blackfade", "assets/sprites/blackfade.png");
this.load.image("bubble", "assets/sprites/bubble.png");
},
create: function() {
this.state.start("GameTitle");
}
}
var GlobezGame = GlobezGame || {};
GlobezGame.GameTitle = function() {
startGame = false;
};
GlobezGame.GameTitle.prototype = {
create: function() {
console.log("%cStarting game title", "color:white; background:red");
this.add.image(0, 0, "background");
//
var bubblesEmitter = this.add.emitter(160, 500, 50);
bubblesEmitter.makeParticles("bubble");
bubblesEmitter.maxParticleScale = 0.6;
bubblesEmitter.minParticleScale = 0.2;
bubblesEmitter.setYSpeed(-30, -40);
bubblesEmitter.setXSpeed(-3, 3);
bubblesEmitter.gravity = 0;
bubblesEmitter.width = 320;
bubblesEmitter.minRotation = 0;
bubblesEmitter.maxRotation = 40;
bubblesEmitter.flow(15000, 2000)
//
var gameTitleSeaLife = this.add.image(160, 70, "gametitle_sealife");
gameTitleSeaLife.anchor.setTo(0.5, 0.5);
gameTitleSeaLife.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1);
var seaLifeTween = this.add.tween(gameTitleSeaLife);
seaLifeTween.to({
angle: -gameTitleSeaLife.angle
}, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true);
//
var gameTitleVs = this.add.image(190, 120, "gametitle_vs");
gameTitleVs.anchor.setTo(0.5, 0.5);
gameTitleVs.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1);
var vsTween = this.add.tween(gameTitleVs);
vsTween.to({
angle: -gameTitleVs.angle
}, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true);
//
var gameTitleMines = this.add.image(160, 160, "gametitle_mines");
gameTitleMines.anchor.setTo(0.5, 0.5);
gameTitleMines.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1);
var minesTween = this.add.tween(gameTitleMines);
minesTween.to({
angle: -gameTitleMines.angle
}, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true);
//
var playButton = this.add.button(160, 320, "playbutton", this.playTheGame, this)
playButton.anchor.setTo(0.5, 0.5);
playButton.angle = (2 + Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1);
var playTween = this.add.tween(playButton);
playTween.to({
angle: -playButton.angle
}, 5000 + Math.random() * 5000, Phaser.Easing.Linear.None, true, 0, 1000, true);
//
var blackFade = this.add.sprite(0, 0, "blackfade");
var fadeTween = this.add.tween(blackFade);
fadeTween.to({
alpha: 0
}, 2000, Phaser.Easing.Cubic.Out, true);
},
playTheGame: function() {
if (!startGame) {
startGame = true
alert("Start the game!!");
}
}
}
var GlobezGame = GlobezGame || {};
GlobezGame.gameOptions = {
gameWidth: 320,
gameHeight: 480
}
GlobezGame.game = new Phaser.Game(GlobezGame.gameOptions.gameWidth, GlobezGame.gameOptions.gameHeight, Phaser.CANVAS, "");
GlobezGame.game.state.add("Boot", GlobezGame.Boot);
GlobezGame.game.state.add("Preload", GlobezGame.Preload);
GlobezGame.game.state.add("GameTitle", GlobezGame.GameTitle);
GlobezGame.game.state.start("Boot");
|
'use strict';
describe('nothing', () => {
it('should do nothing', () => {
//
});
});
|
define(function(require) {
var Checker = require("checkers/controller/Checker"),
GameBoard = require("checkers/controller/GameBoard"),
GameSpace = require("checkers/controller/GameSpace");
var instance = null;
function GameBoardUtil() {
}
var getInstance = function() {
if (instance === null) {
instance = new GameBoardUtil();
}
return instance;
}
GameBoardUtil.prototype.getValidMoves = function(checker, gameBoard, posDir) {
var validMoves = new Array();
$.merge(validMoves, this.getEmptySpaceMoves(checker, gameBoard, posDir));
$.merge(validMoves, this.getJumpMoves(checker, gameBoard, posDir));
return validMoves;
}
GameBoardUtil.prototype.getEmptySpaceMoves = function(checker, gameBoard, posDir) {
var emptySpaceMoves = new Array();
var row = checker.getRow() + posDir;
// Checks left move
if (this.isValidMove(row, checker.getColumn() - 1)) {
var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() - 1)
if (gameSpace.isEmpty()) {
emptySpaceMoves.push(gameSpace);
}
}
// Checks right move
if (this.isValidMove(row, checker.getColumn() + 1)) {
var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() + 1);
if (gameSpace.isEmpty()) {
emptySpaceMoves.push(gameSpace);
}
}
if (checker.isKing()) {
var kRow = checker.getRow() - posDir;
// Checks left move
if (this.isValidMove(kRow, checker.getColumn() - 1)) {
var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() - 1)
if (gameSpace.isEmpty()) {
emptySpaceMoves.push(gameSpace);
}
}
// Checks right move
if (this.isValidMove(kRow, checker.getColumn() + 1)) {
var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() + 1);
if (gameSpace.isEmpty()) {
emptySpaceMoves.push(gameSpace);
}
}
}
return emptySpaceMoves;
}
GameBoardUtil.prototype.isValidMove = function(row, column) {
if (row < 0 || row >= GameBoard.NUMSQUARES || column < 0 || column >= GameBoard.NUMSQUARES) {
return false;
}
return true;
}
GameBoardUtil.prototype.getJumpMoves = function(checker, gameBoard, posDir) {
var jumpMoves = new Array();
var row = checker.getRow() + posDir * 2;
// Checks left jump move
if (this.isValidMove(row, checker.getColumn() - 2)) {
var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() - 2);
if (gameSpace.isEmpty()) {
var jumpedGameSpace = gameBoard.getGameSpace(row - posDir, checker.getColumn() - 1);
if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) {
jumpMoves.push(gameSpace);
}
}
}
// Checks right jump move
if (this.isValidMove(row, checker.getColumn() + 2)) {
var gameSpace = gameBoard.getGameSpace(row, checker.getColumn() + 2);
if (gameSpace.isEmpty()) {
var jumpedGameSpace = gameBoard.getGameSpace(row - posDir, checker.getColumn() + 1);
if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) {
jumpMoves.push(gameSpace);
}
}
}
if (checker.isKing()) {
// Checks left jump move
var kRow = checker.getRow() - posDir * 2;
if (this.isValidMove(kRow, checker.getColumn() - 2)) {
var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() - 2);
if (gameSpace.isEmpty()) {
var jumpedGameSpace = gameBoard.getGameSpace(kRow + posDir, checker.getColumn() - 1);
if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) {
jumpMoves.push(gameSpace);
}
}
}
// Checks right jump move
if (this.isValidMove(kRow, checker.getColumn() + 2)) {
var gameSpace = gameBoard.getGameSpace(kRow, checker.getColumn() + 2);
if (gameSpace.isEmpty()) {
var jumpedGameSpace = gameBoard.getGameSpace(kRow + posDir, checker.getColumn() + 1);
if (!jumpedGameSpace.isEmpty() && jumpedGameSpace.getChecker().getPlayerId() != checker.getPlayerId()) {
jumpMoves.push(gameSpace);
}
}
}
}
return jumpMoves;
}
return ({getInstance:getInstance});
});
|
import { LOCAL_STORAGE_REMOVE_ITEM, LOCAL_STORAGE_SET_ITEM } from './actionTypes'
import createMiddleware from './middleware'
describe('middleware', () => {
let removeItem
let setItem
let middleware
let next
let store
beforeEach(() => {
removeItem = jest.fn()
setItem = jest.fn()
middleware = createMiddleware({
removeItem,
setItem,
})
next = jest.fn()
store = {
dispatch: jest.fn(),
getState: jest.fn(),
}
})
it('calls next on dummy actionType', () => {
const action = {
type: 'dummyType',
payload: {
key: 'key',
},
}
middleware(store)(next)(action)
expect(next.mock.calls.length).toBe(1)
})
it(`calls removeItem on ${LOCAL_STORAGE_REMOVE_ITEM}`, () => {
const action = {
type: LOCAL_STORAGE_REMOVE_ITEM,
payload: {
key: 'key',
},
}
middleware(store)(next)(action)
expect(removeItem.mock.calls.length).toBe(1)
})
it(`calls removeItem on ${LOCAL_STORAGE_SET_ITEM}`, () => {
const action = {
type: LOCAL_STORAGE_SET_ITEM,
payload: {
key: 'key',
value: 'value',
},
}
middleware(store)(next)(action)
expect(setItem.mock.calls.length).toBe(1)
})
})
|
import s from './Callouts.css';
import React, { PropTypes } from 'react';
import numbro from 'numbro';
function diversityAtParityOrGreater(conf) {
return conf.diversityPercentage >= 50;
}
function confFromCurrentYear(conf) {
return conf.year == (new Date()).getFullYear();
}
function diversityAccumulator(accumulator, conf) {
return accumulator + conf.diversityPercentage;
}
function diversitySorter(confA, confB) {
if (confA.diversityPercentage < confB.diversityPercentage) {
return 1;
}
if (confA.diversityPercentage > confB.diversityPercentage) {
return -1;
}
return 0;
}
class Callouts extends React.Component {
constructor(props) {
super(props);
this.currentYearConfs = props.confs.filter(confFromCurrentYear);
this.state = {
confs: props.confs,
bestPerformer: props.confs.sort(diversitySorter)[0],
numberOfConfs: props.confs.length,
numberOfConfsAtParityOrGreater: props.confs.filter(diversityAtParityOrGreater).length,
averageDiversity: props.confs.reduce(diversityAccumulator, 0) / props.confs.length,
averageDiversityCurrentYear: this.currentYearConfs.reduce(diversityAccumulator, 0) / this.currentYearConfs.length
};
}
render() {
return (
<div className={s.container}>
<div className="row">
<div className="col-sm-2">
<div className={s.title}>Conferences<br/>tracked</div>
<div className={s.pop}>{this.state.numberOfConfs}</div>
</div>
<div className="col-sm-2">
<div className={s.title}>Best<br/>performer</div>
<div className={s.body}><strong>{this.state.bestPerformer.name} ({this.state.bestPerformer.year})</strong><br/>{numbro(this.state.bestPerformer.diversityPercentage).format('0')}%</div>
</div>
<div className="col-sm-2">
<div className={s.title}>Biggest recent improver</div>
<div className={s.body}><strong>1st Conf</strong><br/>+36%<br/>2016 -> 2017</div>
</div>
<div className="col-sm-2" id={s.nbrConfAtParity}>
<div className={s.title}>#confs >= 50%<br/>diversity</div>
<div className={s.pop}>{this.state.numberOfConfsAtParityOrGreater}</div>
</div>
<div className="col-sm-2">
<div className={s.title}>Average<br/>f:m%</div>
<div className={s.pop}>{numbro(this.state.averageDiversity).format('0')}%</div>
</div>
<div className="col-sm-2">
<div className={s.title}>Average<br/>f:m% (2017)</div>
<div className={s.pop}>{numbro(this.state.averageDiversityCurrentYear).format('0')}%</div>
</div>
</div>
</div>
);
}
}
export default Callouts;
|
/*! simpler-sidebar v1.4.9 (https://github.com/dcdeiv/simpler-sidebar)
** Copyright (c) 2015 - 2016 Davide Di Criscito
** Dual licensed under MIT and GPL-2.0
*/
( function( $ ) {
$.fn.simplerSidebar = function( options ) {
var cfg = $.extend( true, $.fn.simplerSidebar.settings, options );
return this.each( function() {
var align, sbw, ssbInit, ssbStyle, maskInit, maskStyle,
attr = cfg.attr,
$sidebar = $( this ),
$opener = $( cfg.opener ),
$links = cfg.sidebar.closingLinks,
duration = cfg.animation.duration,
sbMaxW = cfg.sidebar.width,
gap = cfg.sidebar.gap,
winMaxW = sbMaxW + gap,
w = $( window ).width(),
animationStart = {},
animationReset = {},
hiddenFlow = function() {
$( "body, html" ).css( "overflow", "hidden" );
},
autoFlow = function() {
$( "body, html" ).css( "overflow", "auto" );
},
activate = {
duration: duration,
easing: cfg.animation.easing,
complete: hiddenFlow
},
deactivate = {
duration: duration,
easing: cfg.animation.easing,
complete: autoFlow
},
animateOpen = function() {
$sidebar
.animate( animationStart, activate )
.attr( "data-" + attr, "active" );
$mask.fadeIn( duration );
},
animateClose = function() {
$sidebar
.animate( animationReset, deactivate )
.attr( "data-" + attr, "disabled" );
$mask.fadeOut( duration );
},
closeSidebar = function() {
var isWhat = $sidebar.attr( "data-" + attr ),
csbw = $sidebar.width();
animationReset[ align ] = -csbw;
if ( isWhat === "active" ) {
animateClose();
}
},
$mask = $( "<div>" ).attr( "data-" + attr, "mask" );
//Checking sidebar align
if ( [ undefined, "right" ].indexOf( cfg.sidebar.align ) !== -1 ) {
align = "right";
} else if ( cfg.sidebar.align === "left" ) {
align = "left";
} else {
console.log( "ERR sidebar.align: you typed \"" + cfg.sidebar.align + "\". You should choose between \"right\" or \"left\"." );
}
//Sidebar style
if ( w < winMaxW ) {
sbw = w - gap;
} else {
sbw = sbMaxW;
}
ssbInit = {
position: "fixed",
top: cfg.top,
bottom: 0,
width: sbw
};
ssbInit[ align ] = -sbw;
animationStart[ align ] = 0;
ssbStyle = $.extend( true, ssbInit, cfg.sidebar.css );
$sidebar.css( ssbStyle )
.attr( "data-" + attr, "disabled" );
//Mask style
maskInit = {
position: "fixed",
top: cfg.top,
right: 0,
bottom: 0,
left: 0,
zIndex: cfg.sidebar.css.zIndex - 1,
display: "none"
};
maskStyle = $.extend( true, maskInit, cfg.mask.css );
//Appending Mask if mask.display is true
if ( [ true, "true", false, "false" ].indexOf( cfg.mask.display) !== -1 ) {
if ( [ true, "true" ].indexOf( cfg.mask.display ) !== -1 ) {
$mask.appendTo( "body" ).css( maskStyle );
}
} else {
console.log( "ERR mask.display: you typed \"" + cfg.mask.display + "\". You should choose between true or false." );
}
//Opening and closing the Sidebar when $opener is clicked
$opener.click( function() {
var isWhat = $sidebar.attr( "data-" + attr ),
csbw = $sidebar.width();
animationReset[ align ] = -csbw;
if ( isWhat === "disabled" ) {
animateOpen();
} else if ( isWhat === "active" ) {
animateClose();
}
});
//Closing Sidebar when the mask is clicked
$mask.click( closeSidebar );
//Closing Sidebar when a link inside of it is clicked
$sidebar.on( "click", $links, closeSidebar );
//Adjusting width;
$( window ).resize( function() {
var rsbw, update,
isWhat = $sidebar.attr( "data-" + attr ),
nw = $( window ).width();
if ( nw < winMaxW ) {
rsbw = nw - gap;
} else {
rsbw = sbMaxW;
}
update = {
width: rsbw
};
if ( isWhat === "disabled" ) {
update[ align ] = -rsbw;
$sidebar.css( update );
} else if ( isWhat === "active" ) {
$sidebar.css( update );
}
});
});
};
$.fn.simplerSidebar.settings = {
attr: "simplersidebar",
top: 0,
animation: {
duration: 500,
easing: "swing"
},
sidebar: {
width: 300,
gap: 64,
closingLinks: "a",
css: {
zIndex: 3000
}
},
mask: {
display: true,
css: {
backgroundColor: "black",
opacity: 0.5,
filter: "Alpha(opacity=50)"
}
}
};
} )( jQuery );
|
// Fill in topbar details.
$('header .right').append(Handlebars.templates.userTopbar(user));
// Fill in sidebar details.
user.created_at = moment(user.created_at).format('MMM DD, YYYY');
var userStars = {user: user, stars: stars};
$('aside').prepend(Handlebars.templates.userSidebar(userStars));
// Populate the organizations list on the sidebar.
var orgList = $('aside #organizations');
orgs.forEach(function (org) {
orgList.append(Handlebars.templates.org(org));
});
// Populate the repos list in the main page.
var repoList = $('section.main .repo-list');
repos = _.sortBy( repos, 'updated_at' ).reverse();
repos.forEach(function (repo) {
repo.updated_at = moment(repo.updated_at).fromNow();
repoList.append(Handlebars.templates.repo(repo));
});
|
import { faker } from 'ember-cli-mirage';
import lodash from 'npm:lodash';
export const CONTAINER_MEMORY = 8023089152;
export function getPorts(isContainer=false) {
let ports = [];
for (let j = 1; j <= faker.random.number({ max: 3 }); j++) {
let obj = {
name: faker.hacker.noun(),
protocol: 'TCP',
};
obj[isContainer ? 'hostPort': 'port'] = faker.random.number();
obj[isContainer ? 'containerPort': 'targetPort'] = faker.random.number();
ports.push(obj);
}
return ports;
}
export function getLabels() {
let labels = {};
for (let j = 1; j <= faker.random.number({ max: 3 }); j++) {
labels[faker.hacker.verb()] = faker.hacker.noun();
}
return labels;
}
export function getSpec(isContainer=false) {
let containers = [];
for (let j = 1; j <= faker.random.number({ min: 1, max: 5 }); j++) {
const name = faker.hacker.verb();
containers.push({
name,
image: `${name}:v${j / 2}`,
ports: getPorts(isContainer),
terminationMessagePath: '/dev/termination-log',
imagePullPolicy: faker.random.arrayElement(['Always', 'Never', 'IfNotPresent'])
});
}
return {
containers,
restartPolicy: faker.random.arrayElement(['Always', 'OnFailure', 'Never']),
terminationGracePeriodSeconds: faker.random.number(),
dnsPolicy: faker.random.arrayElement(['ClusterFirst', 'Default']),
nodeName: faker.internet.ip(),
hostNetwork: faker.random.boolean()
};
}
export function getId(kind, index) {
return `${kind.toLowerCase()}-${index}`;
}
export function getMetadata(kind='Node', index=0, namespace=null) {
let name = getId(kind, index),
creationTimestamp = faker.date.recent(),
labels = getLabels();
if (!namespace && kind !== 'Node') {
namespace = faker.random.arrayElement(['default', 'kube-system', 'app-namespace']);
}
return { name, namespace, creationTimestamp, labels };
}
export function getCAdvisorContainerSpec() {
return {
creation_time: faker.date.recent(),
has_cpu: true,
has_memory: true,
has_filesystem: true,
memory: {
limit: CONTAINER_MEMORY
}
};
}
export function getStat(total, timestamp, cpus=4) {
let per_cpu_usage = [],
maxPerCpu = Math.round(total / cpus);
for (let i = 1; i < cpus; i++) {
per_cpu_usage.push(faker.random.number({ max: maxPerCpu }));
}
let cpu = { usage: { total, per_cpu_usage } },
memory = { usage: faker.random.number({ max: CONTAINER_MEMORY }) },
filesystems = [],
devices = [
'/dev/sda1',
'docker-8:1-7083173-pool',
'/dev/mapper/docker-8:1-7083173-8f138ecc6e8dc81a08b9fee2f256415e96de06a8eb4ab247bde008932fc53c3a'
];
lodash.each(devices, (device) => {
let min = 1024,
max = 1024 * 20,
capacity = faker.random.number({ min, max }),
usage = faker.random.number({ min, max: capacity });
filesystems.push({ device, capacity, usage });
});
return { timestamp, cpu, memory, filesystem: filesystems };
}
|
module.exports = function () {
return {
templateUrl : './shared/partials/footer/directives/footer.html',
controller: require('./footerCtrl'),
restrict: 'E',
scope: {}
};
};
|
import React from 'react';
import PropTypes from 'prop-types';
import ColumnChart from './columnChart';
import Tooltip from './../tooltip/tooltip';
import {dateFormats} from './../../utils/displayFormats';
import './columnWidget.css';
const ColumnWidget = ({
chartTitle,
chartDescription,
chartUpdatedDate,
series,
xAxis,
yAxis,
viewport,
displayHighContrast,
}) => {
return (
<article role="article" className="D_widget">
<header>
{chartDescription && <div className="D_CW_infoContainer"><Tooltip text={chartDescription} viewport={viewport} /></div>}
<h1 className="highcharts-title">{chartTitle}</h1>
<span className="highcharts-subtitle">Last updated at <time dateTime={dateFormats.dateTime(chartUpdatedDate)}>{dateFormats.dayMonthYear(chartUpdatedDate)}</time></span>
</header>
<section>
<ColumnChart series={series}
xAxis={xAxis}
yAxis={yAxis}
chartDescription={chartDescription}
displayHighContrast={displayHighContrast} />
</section>
</article>
)
};
if (__DEV__) {
ColumnWidget.propTypes = {
chartTitle: PropTypes.string,
chartDescription: PropTypes.string,
chartUpdatedDate: PropTypes.string,
series: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string.isRequired,
units: PropTypes.string,
color: PropTypes.string,
data: PropTypes.array.isRequired,
})).isRequired,
xAxis: PropTypes.arrayOf(PropTypes.shape({
categories: PropTypes.array,
})),
yAxis: PropTypes.arrayOf(PropTypes.shape({
title: PropTypes.object,
})),
viewport: PropTypes.oneOf(['sm', 'md', 'lg', 'xl']),
displayHighContrast: PropTypes.bool,
};
}
export default ColumnWidget;
|
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import App from './containers/App';
import configureStore from './store/configureStore';
import 'todomvc-app-css/index.css';
const store = configureStore();
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('layout')
);
|
//
// window.onload = function() {
// var data = {username:'52200', password:'123', remember:52200};
// fetch('/api/users/getUser?id=1').then(function(res) {
// console.log("请求的数据是", res);
// if (res.ok) {
// alert('Submitted!');
// } else {
// alert('Error!');
// }
// }).then(function(body) {
// console.log("请求body的数据是", body);
// // body
// });
// };
|
Meteor.methods({
addAllUserToRoom(rid, activeUsersOnly = false) {
check (rid, String);
check (activeUsersOnly, Boolean);
if (RocketChat.authz.hasRole(this.userId, 'admin') === true) {
const userCount = RocketChat.models.Users.find().count();
if (userCount > RocketChat.settings.get('API_User_Limit')) {
throw new Meteor.Error('error-user-limit-exceeded', 'User Limit Exceeded', {
method: 'addAllToRoom',
});
}
const room = RocketChat.models.Rooms.findOneById(rid);
if (room == null) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'addAllToRoom',
});
}
const userFilter = {};
if (activeUsersOnly === true) {
userFilter.active = true;
}
const users = RocketChat.models.Users.find(userFilter).fetch();
const now = new Date();
users.forEach(function(user) {
const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, user._id);
if (subscription != null) {
return;
}
RocketChat.callbacks.run('beforeJoinRoom', user, room);
RocketChat.models.Subscriptions.createWithRoomAndUser(room, user, {
ts: now,
open: true,
alert: true,
unread: 1,
userMentions: 1,
groupMentions: 0,
});
RocketChat.models.Messages.createUserJoinWithRoomIdAndUser(rid, user, {
ts: now,
});
Meteor.defer(function() {});
return RocketChat.callbacks.run('afterJoinRoom', user, room);
});
return true;
} else {
throw (new Meteor.Error(403, 'Access to Method Forbidden', {
method: 'addAllToRoom',
}));
}
},
});
|
const HttpStatus = require('http-status-codes');
const build = status => {
return (ctx, message) => {
ctx.status = status
ctx.body = message || {message: HttpStatus.getStatusText(status)}
return ctx
}
}
module.exports = {
accepted: build(HttpStatus.ACCEPTED), // 202
badGateway: build(HttpStatus.BAD_GATEWAY), // 502
badRequest: build(HttpStatus.BAD_REQUEST), // 400
conflict: build(HttpStatus.CONFLICT), // 409
continue: build(HttpStatus.CONTINUE), // 100
created: build(HttpStatus.CREATED), // 201
expectationFailed: build(HttpStatus.EXPECTATION_FAILED), // 417
failedDependency: build(HttpStatus.FAILED_DEPENDENCY), // 424
forbidden: build(HttpStatus.FORBIDDEN), // 403
gatewayTimeout: build(HttpStatus.GATEWAY_TIMEOUT), // 504
gone: build(HttpStatus.GONE), // 410
httpVersionNotSupported: build(HttpStatus.HTTP_VERSION_NOT_SUPPORTED), // 505
imATeapot: build(HttpStatus.IM_A_TEAPOT), // 418
insufficientSpaceOnResource: build(HttpStatus.INSUFFICIENT_SPACE_ON_RESOURCE), // 419
insufficientStorage: build(HttpStatus.INSUFFICIENT_STORAGE), // 507
internalServerError: build(HttpStatus.INTERNAL_SERVER_ERROR), // 500
lengthRequired: build(HttpStatus.LENGTH_REQUIRED), // 411
locked: build(HttpStatus.LOCKED), // 423
methodFailure: build(HttpStatus.METHOD_FAILURE), // 420
methodNotAllowed: build(HttpStatus.METHOD_NOT_ALLOWED), // 405
movedPermanently: build(HttpStatus.MOVED_PERMANENTLY), // 301
movedTemporarily: build(HttpStatus.MOVED_TEMPORARILY), // 302
multiStatus: build(HttpStatus.MULTI_STATUS), // 207
multipleChoices: build(HttpStatus.MULTIPLE_CHOICES), // 300
networkAuthenticationRequired: build(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED), // 511
noContent: build(HttpStatus.NO_CONTENT), // 204
nonAuthoritativeInformation: build(HttpStatus.NON_AUTHORITATIVE_INFORMATION), // 203
notAcceptable: build(HttpStatus.NOT_ACCEPTABLE), // 406
notFound: build(HttpStatus.NOT_FOUND), // 404
notImplemented: build(HttpStatus.NOT_IMPLEMENTED), // 501
notModified: build(HttpStatus.NOT_MODIFIED), // 304
ok: build(HttpStatus.OK), // 200
partialContent: build(HttpStatus.PARTIAL_CONTENT), // 206
paymentRequired: build(HttpStatus.PAYMENT_REQUIRED), // 402
permanentRedirect: build(HttpStatus.PERMANENT_REDIRECT), // 308
preconditionFailed: build(HttpStatus.PRECONDITION_FAILED), // 412
preconditionRequired: build(HttpStatus.PRECONDITION_REQUIRED), // 428
processing: build(HttpStatus.PROCESSING), // 102
proxyAuthenticationRequired: build(HttpStatus.PROXY_AUTHENTICATION_REQUIRED), // 407
requestHeaderFieldsTooLarge: build(HttpStatus.REQUEST_HEADER_FIELDS_TOO_LARGE), // 431
requestTimeout: build(HttpStatus.REQUEST_TIMEOUT), // 408
requestTooLong: build(HttpStatus.REQUEST_TOO_LONG), // 413
requestUriTooLong: build(HttpStatus.REQUEST_URI_TOO_LONG), // 414
requestedRangeNotSatisfiable: build(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE), // 416
resetContent: build(HttpStatus.RESET_CONTENT), // 205
seeOther: build(HttpStatus.SEE_OTHER), // 303
serviceUnavailable: build(HttpStatus.SERVICE_UNAVAILABLE), // 503
switchingProtocols: build(HttpStatus.SWITCHING_PROTOCOLS), // 101
temporaryRedirect: build(HttpStatus.TEMPORARY_REDIRECT), // 307
tooManyRequests: build(HttpStatus.TOO_MANY_REQUESTS), // 429
unauthorized: build(HttpStatus.UNAUTHORIZED), // 401
unprocessableEntity: build(HttpStatus.UNPROCESSABLE_ENTITY), // 422
unsupportedMediaType: build(HttpStatus.UNSUPPORTED_MEDIA_TYPE), // 415
useProxy: build(HttpStatus.USE_PROXY) // 305
}
|
module.exports = function verify(check) {
if (typeof check !== 'object') {
throw new Error('check is not an object');
}
var errors = [];
Object.keys(check).forEach(_verify, check);
if (errors.length > 0) {
throw new Error('Health checks failed: '+ errors.join(', '));
}
return true;
function _verify(key, i) {
if (this[key] === false || this[key] instanceof Error) {
errors.push(key);
}
else if (this[key] && typeof this[key] === 'object' && !Array.isArray(this[key])) {
Object.keys(this[key]).forEach(_verify, this[key]);
}
}
};
|
/* globals describe, beforeEach, it, expect, inject, vehicles, VehicleMock */
describe("Vehicles Factory:", function() {
'use strict';
var $httpBackend,
vehicles,
request,
Showcase;
// Load the main module
beforeEach(module('sc'));
beforeEach(inject(function($injector, _vehicles_, _Showcase_) {
$httpBackend = $injector.get('$httpBackend');
vehicles = _vehicles_;
Showcase = _Showcase_;
request = $httpBackend.whenGET(Showcase.API + 'vehicles').respond(200, angular.copy(VehicleMock.ALL));
$httpBackend.whenGET(Showcase.API + 'vehicles/1').respond(200, VehicleMock.DETAIL);
$httpBackend.whenGET(Showcase.API + 'vehicles/compare/1').respond(200, angular.copy(VehicleMock.COMPARE));
}));
it("should return 4 vehicles", function() {
vehicles.getAll().then(function(response) {
expect(response.length).toEqual(4);
});
$httpBackend.flush();
});
it("should return Toyota as the first Brand", function() {
vehicles.getAll().then(function(response) {
expect(response[0].brand).toEqual('Toyota');
});
$httpBackend.flush();
});
it("should return a 404 error", function() {
request.respond(404, {error: true});
$httpBackend.expectGET(Showcase.API + 'vehicles');
vehicles.getAll().catch(function(error) {
expect(error.error).toBe(true);
});
$httpBackend.flush();
});
it("should return vehicle detail", function() {
vehicles.get(1).then(function(response) {
expect(response.model).toEqual('Avalon');
});
$httpBackend.flush();
});
it("should compare 3 vehicles", function() {
vehicles.compare(1,2,3).then(function(response) {
expect(response.length).toEqual(2);
});
$httpBackend.flush();
});
});
|
import { createGlobalStyle } from 'styled-components';
export const GlobalStyle = createGlobalStyle`
body {
margin: 0;
font-family: 'Montserrat', sans-serif;
}
* {
box-sizing: border-box;
}
`;
|
import React, { Component, PropTypes } from 'react'
import cx from 'classnames'
import { Icon } from '../icon'
import { capitalize } from 'utils/string'
import './button.view.styl'
export class Button extends Component {
static propTypes = {
className: PropTypes.string,
children: PropTypes.oneOfType([
PropTypes.element,
PropTypes.string
]),
icon: PropTypes.string,
type: PropTypes.oneOf(['primary', 'text', 'danger', 'normal']),
htmlType: PropTypes.oneOf(['submit', 'button', 'reset']),
size: PropTypes.oneOf(['small', 'normal', 'large']),
block: PropTypes.bool,
loading: PropTypes.bool,
disabled: PropTypes.bool,
ghost: PropTypes.bool,
onClick: PropTypes.func
}
static defaultProps = {
type: 'primary',
size: 'normal',
onClick: () => {}
}
getRootClassNames () {
const {
className,
type,
size,
block,
loading,
disabled,
ghost
} = this.props
return cx(
'button',
`button${capitalize(type)}`,
`size${capitalize(size)}`,
{ isBlock: block },
{ isGhost: ghost },
{ isLoading: loading },
{ isDisabled: disabled },
className
)
}
handleClick = (e) => {
const {
loading,
disabled,
onClick
} = this.props
if (loading || disabled) {
e.preventDefault()
return null
}
if (onClick) {
onClick(e)
}
}
render () {
const {
icon,
htmlType,
// loading,
children
} = this.props
const iconName = icon // @OLD: loading ? 'loading' : icon
const iconNode = iconName ? <Icon name={iconName} /> : null
return (
<button
className={this.getRootClassNames()}
onClick={this.handleClick}
type={htmlType || 'button'}
>
{iconNode}{children}
</button>
)
}
}
|
'use strict';
var os = require('os');
// expose our config directly to our application using module.exports
module.exports = {
'twitterAuth' : {
'consumerKey' : process.env.TWITTER_CONSUMER_KEY || 'unknown',
'consumerSecret' : process.env.TWITTER_CONSUMER_SECRET || 'unknown' ,
'callbackURL' : 'http://' + os.hostname() + '/auth/twitter/callback'
}
};
|
var mySteal = require('@steal');
if (typeof window !== "undefined" && window.assert) {
assert.ok(mySteal.loader == steal.loader, "The steal's loader is the loader");
done();
} else {
console.log("Systems", mySteal.loader == steal.loader);
}
|
define(function(require, exports, module) {
require('jquery.cycle2');
exports.run = function() {
$('.homepage-feature').cycle({
fx:"scrollHorz",
slides: "> a, > img",
log: "false",
pauseOnHover: "true"
});
$('.live-rating-course').find('.media-body').hover(function() {
$( this ).find( ".rating" ).show();
}, function() {
$( this ).find( ".rating" ).hide();
});
};
});
|
import React from 'react';
import Slider from 'material-ui/Slider';
/**
* The `defaultValue` property sets the initial position of the slider.
* The slider appearance changes when not at the starting position.
*/
const SliderTransparency = (props) => (
<Slider defaultValue={props.transparency} onChange={props.update} sliderStyle={{margin:'auto',pointerEvents:'all'}} axis='y' style={{height:'400px', paddingTop:"30px"}}
data-tip={`Opacity`}
data-offset="{'top': -30}"
/>
);
export default SliderTransparency;
|
import { Transform } from './transform.js';
/**
* Calculate the transform for a Cornerstone enabled element
*
* @param {EnabledElement} enabledElement The Cornerstone Enabled Element
* @param {Number} [scale] The viewport scale
* @return {Transform} The current transform
*/
export default function (enabledElement, scale) {
const transform = new Transform();
transform.translate(enabledElement.canvas.width / 2, enabledElement.canvas.height / 2);
// Apply the rotation before scaling for non square pixels
const angle = enabledElement.viewport.rotation;
if (angle !== 0) {
transform.rotate(angle * Math.PI / 180);
}
// Apply the scale
let widthScale = enabledElement.viewport.scale;
let heightScale = enabledElement.viewport.scale;
if (enabledElement.image.rowPixelSpacing < enabledElement.image.columnPixelSpacing) {
widthScale *= (enabledElement.image.columnPixelSpacing / enabledElement.image.rowPixelSpacing);
} else if (enabledElement.image.columnPixelSpacing < enabledElement.image.rowPixelSpacing) {
heightScale *= (enabledElement.image.rowPixelSpacing / enabledElement.image.columnPixelSpacing);
}
transform.scale(widthScale, heightScale);
// Unrotate to so we can translate unrotated
if (angle !== 0) {
transform.rotate(-angle * Math.PI / 180);
}
// Apply the pan offset
transform.translate(enabledElement.viewport.translation.x, enabledElement.viewport.translation.y);
// Rotate again so we can apply general scale
if (angle !== 0) {
transform.rotate(angle * Math.PI / 180);
}
if (scale !== undefined) {
// Apply the font scale
transform.scale(scale, scale);
}
// Apply Flip if required
if (enabledElement.viewport.hflip) {
transform.scale(-1, 1);
}
if (enabledElement.viewport.vflip) {
transform.scale(1, -1);
}
// Translate the origin back to the corner of the image so the event handlers can draw in image coordinate system
transform.translate(-enabledElement.image.width / 2, -enabledElement.image.height / 2);
return transform;
}
|
'use strict';
const AWS = require('aws-sdk');
let x = "/delegationset/NHKXBB6SHGKLN";
console.log(x.replace('/delegationset/', ''));
return;
const route53 = new AWS.Route53();
route53.listHostedZones({}).promise()
.then(response => {
console.log(response);
return response.HostedZones.find(hostedZone => {
return hostedZone.Name === 'manapaho.com.';
});
})
.catch(err => {
console.log(err);
})
.then(hostedZone => {
console.log(hostedZone);
});
return;
/*
route53.listReusableDelegationSets({}).promise()
.then(response => {
return response.DelegationSets.find(delegationSet => {
return delegationSet.CallerReference === 'arn:aws:lambda:us-east-1:238541850529:function:Prod-Wessels-us-east-1-Route53ReusableDelegationSet';
});
})
.catch(err => {
console.log(err);
})
.then(reusableDelegationSet => {
console.log(reusableDelegationSet);
});
return;
AWS.config.update({region: 'us-east-1'});
let stackName = 'Prod-Manapaho-us-east-1-NameServerSet';
let responseStatus = "FAILED";
let responseData = {};
let cfn = new AWS.CloudFormation();
cfn.describeStacks({StackName: stackName}).promise()
.then(data => {
console.log('333333333333333333333', JSON.stringify(data, null, 2));
data.Stacks[0].Outputs.forEach(function (output) {
responseData[output.OutputKey] = output.OutputValue;
});
responseStatus = "SUCCESS";
console.log(JSON.stringify(responseData, null, 2));
})
.catch(err => {
console.log('4444444444444444444444444');
console.log('FAILED TO DESCRIBE STACK:', err);
});
return;
const route53 = new AWS.Route53();
route53.listReusableDelegationSets({}).promise()
.then(response => {
console.log(response.DelegationSets.find(delegationSet => {
return delegationSet.CallerReference === 'arn:aws:lambda:us-east-1:238541850529:function:Prod-Manapaho-us-east-1-Route53ReusableDelegationSet';
}));
})
.catch(err => {
console.log(err);
});
return;
route53.createReusableDelegationSet({CallerReference: 'createReusableDelegationSet'}).promise()
.then(response => {
console.log('XXXXXXXX', JSON.stringify(response, null, 2));
})
.catch(err => {
console.log(err, err.stack);
});
*/
|
const defaultEnv = process.env.NODE_ENV || 'development';
function getEnv(name = defaultEnv) {
const isProduction = name === 'production' || name === 'prod';
const isDev = !isProduction;
return { name, isProduction, isDev, getEnv };
}
const env = getEnv();
module.exports = env;
|
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/DashboardHub'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
|
var React = require('react-native');
var {
StyleSheet,
View,
Animated,
} = React;
var Dot = React.createClass({
propTypes: {
isPlacedCorrectly: React.PropTypes.bool.isRequired,
},
getInitialState: function() {
return {
scale: new Animated.Value(this.props.isPlacedCorrectly ? 1 : 0.1),
visible: this.props.isPlacedCorrectly,
};
},
componentWillReceiveProps: function(nextProps) {
if (!this.props.isPlacedCorrectly && nextProps.isPlacedCorrectly) {
this.animateShow();
} else if (this.props.isPlacedCorrectly && !nextProps.isPlacedCorrectly) {
this.animateHide();
}
},
animateShow: function() {
this.setState({visible: true}, () => {
Animated.timing(this.state.scale, {
toValue: 1,
duration: 100,
}).start();
});
},
animateHide: function() {
Animated.timing(this.state.scale, {
toValue: 0.1,
duration: 100,
}).start(() => this.setState({visible: false}));
},
render: function() {
if (!this.state.visible) {
return null;
}
return (
<Animated.View style={[styles.dot, {transform: [{scale: this.state.scale}]}]}/>
);
},
});
var styles = StyleSheet.create({
dot: {
backgroundColor: '#FF3366',
width: 6,
height: 6,
borderRadius: 3,
margin: 3,
},
});
module.exports = Dot;
|
var namespacehryky_1_1log =
[
[ "AutoElapsed", "structhryky_1_1log_1_1_auto_elapsed.html", null ],
[ "level_type", "namespacehryky_1_1log.html#a6005efaf1fc45416ed6aa211f939993f", null ],
[ "writer_type", "namespacehryky_1_1log.html#a855ba68dea65f57a39b7a1cb03aee800", null ],
[ "write", "namespacehryky_1_1log.html#a5c7e76e7e42521f83c90fc8813f1f3ea", null ]
];
|
var assert = require('assert');
describe('src/components/model/classes/Collection', function () {
var Collection = require('../../../../src/components/model/classes/Collection');
var collection;
var handler = function (event, changes) {
callbacks[event]++;
};
var callbacks = {
add: 0,
remove: 0,
change: 0
};
describe.only('new Collection(obj)', function () {
it('Should return a new Collection instance', function (done) {
collection = new Collection([1, 2, 3], handler);
done();
});
});
describe.only('.push(item)', function () {
it('Should call "add" callback', function (done) {
collection.push(4);
assert(callbacks.add, 1);
done();
});
});
describe.only('.unshift(item)', function () {
it('Should call "add" callback', function (done) {
collection.unshift(0);
assert(callbacks.add, 2);
done();
});
});
describe.only('.pop()', function () {
it('Should call "remove" callback', function (done) {
collection.pop();
assert(callbacks.remove, 1);
done();
});
});
describe.only('.shift()', function () {
it('Should call "remove" callback', function (done) {
collection.shift();
assert(callbacks.remove, 2);
done();
});
});
describe.only('.splice(index, number)', function () {
it('Should call "remove" callback', function (done) {
collection.splice(0, 1);
assert(callbacks.remove, 3);
done();
});
});
describe.only('.reverse()', function () {
it('Should call "change" callback', function (done) {
collection.reverse();
assert(callbacks.change, 1);
done();
});
});
describe.only('.sort()', function () {
it('Should call "change" callback', function (done) {
collection.sort(function (a, b) {
return -1;
});
assert(callbacks.change, 2);
done();
});
});
});
|
/**
* boot/middleware.js
* Express middleware
*/
|
import React from 'react';
import Status from 'components/Status';
import renderer from 'react-test-renderer';
describe('Status component', () => {
function getComponent(piecesLeftCount) {
return renderer.create(
<Status piecesLeftCount={piecesLeftCount} />
);
}
it('should show pieces left', () => {
expect(getComponent(9).toJSON()).toMatchSnapshot();
});
it('should show "Done" when no pieces left', () => {
expect(getComponent(0).toJSON()).toMatchSnapshot();
});
});
|
var struct_l_p_c___r_t_c___type_def =
[
[ "ALDOM", "struct_l_p_c___r_t_c___type_def.html#aae1199a3f1f40f90aba18aee4d6325fd", null ],
[ "ALDOW", "struct_l_p_c___r_t_c___type_def.html#a5f56710f005f96878defbdb8ef1333c2", null ],
[ "ALDOY", "struct_l_p_c___r_t_c___type_def.html#a4c7ceb477c4a865ae51f5052dd558667", null ],
[ "ALHOUR", "struct_l_p_c___r_t_c___type_def.html#ac56690c26258c2cf9d28d09cc3447c1d", null ],
[ "ALMIN", "struct_l_p_c___r_t_c___type_def.html#a7e45902fca36066b22f41d0ef60d3c36", null ],
[ "ALMON", "struct_l_p_c___r_t_c___type_def.html#ad22f635b8c8b51dad2956e797a4dd9d3", null ],
[ "ALSEC", "struct_l_p_c___r_t_c___type_def.html#af3ff64ab3671109971425a05194acc7c", null ],
[ "ALYEAR", "struct_l_p_c___r_t_c___type_def.html#ab7f49ad885a354164adc263629d3a555", null ],
[ "AMR", "struct_l_p_c___r_t_c___type_def.html#a13f4e9721184b326043e6c6596f87790", null ],
[ "CALIBRATION", "struct_l_p_c___r_t_c___type_def.html#abe224f8608ae3d2c5b1036bf943b6c27", null ],
[ "CCR", "struct_l_p_c___r_t_c___type_def.html#af959ddb88caef28108c2926e310a72bd", null ],
[ "CIIR", "struct_l_p_c___r_t_c___type_def.html#a0df12e53986b72fbfcdceb537f7bf20e", null ],
[ "CTIME0", "struct_l_p_c___r_t_c___type_def.html#a97fa06b91b698236cb770d9618707bef", null ],
[ "CTIME1", "struct_l_p_c___r_t_c___type_def.html#a5b1a1b981a72c6d1cd482e75f1d44de4", null ],
[ "CTIME2", "struct_l_p_c___r_t_c___type_def.html#a411e06dfdcddd3fc19170231aa3a98be", null ],
[ "DOM", "struct_l_p_c___r_t_c___type_def.html#a7c70513eabbefbc5c5dd865a01ecc487", null ],
[ "DOW", "struct_l_p_c___r_t_c___type_def.html#a61f22d3ccb1c82db258f66d7d930db35", null ],
[ "DOY", "struct_l_p_c___r_t_c___type_def.html#a7b4a3d5692df3c5062ec927cedd16734", null ],
[ "GPREG0", "struct_l_p_c___r_t_c___type_def.html#ac42f0d8452c678fa007f0e0b862fb0c6", null ],
[ "GPREG1", "struct_l_p_c___r_t_c___type_def.html#abee4ae6eab2c33bdf38985d3b8a439f1", null ],
[ "GPREG2", "struct_l_p_c___r_t_c___type_def.html#a75f852bb2980febd2af7cc583e1445ec", null ],
[ "GPREG3", "struct_l_p_c___r_t_c___type_def.html#aad058be0cc120fffbbc66ad6f7c0c731", null ],
[ "GPREG4", "struct_l_p_c___r_t_c___type_def.html#afcc8f7898dce77fdb1082ff681387692", null ],
[ "HOUR", "struct_l_p_c___r_t_c___type_def.html#a76b8d6a8b13febe4289797f34ba73998", null ],
[ "ILR", "struct_l_p_c___r_t_c___type_def.html#aba869620e961b6eb9280229dad81e458", null ],
[ "MIN", "struct_l_p_c___r_t_c___type_def.html#a7a07167f54a5412387ee581fcd6dd2e0", null ],
[ "MONTH", "struct_l_p_c___r_t_c___type_def.html#a28fb9798e07b54b1098e9efe96ac244a", null ],
[ "RESERVED0", "struct_l_p_c___r_t_c___type_def.html#ad539ffa4484980685ca2da36b54fe61d", null ],
[ "RESERVED1", "struct_l_p_c___r_t_c___type_def.html#ad9fb3ef44fb733b524dcad0dfe34290e", null ],
[ "RESERVED10", "struct_l_p_c___r_t_c___type_def.html#a2d9caf1d8be9f2169521470b6ccd0377", null ],
[ "RESERVED11", "struct_l_p_c___r_t_c___type_def.html#a11e504ee49142f46dcc67740ae9235e5", null ],
[ "RESERVED12", "struct_l_p_c___r_t_c___type_def.html#a06137f06d699f26661c55209218bcada", null ],
[ "RESERVED13", "struct_l_p_c___r_t_c___type_def.html#a17672e7a5546cef19ee778266224c193", null ],
[ "RESERVED14", "struct_l_p_c___r_t_c___type_def.html#a1b9781efee5466ce7886eae907f24e60", null ],
[ "RESERVED15", "struct_l_p_c___r_t_c___type_def.html#a781148146471db4cd7d04029e383d115", null ],
[ "RESERVED16", "struct_l_p_c___r_t_c___type_def.html#af3ff60ce094e476f447a8046d873acb0", null ],
[ "RESERVED17", "struct_l_p_c___r_t_c___type_def.html#ae98d0c41e0bb8aef875fa8b53b25af54", null ],
[ "RESERVED18", "struct_l_p_c___r_t_c___type_def.html#aae0a4a7536dc03a352e8c48436b10263", null ],
[ "RESERVED19", "struct_l_p_c___r_t_c___type_def.html#a5552e97d80fc1a5bd195a9c81b270ffc", null ],
[ "RESERVED2", "struct_l_p_c___r_t_c___type_def.html#aff8b921ce3122ac6c22dc654a4f1b7ca", null ],
[ "RESERVED20", "struct_l_p_c___r_t_c___type_def.html#af7fcad34b88077879694c020956bf69b", null ],
[ "RESERVED21", "struct_l_p_c___r_t_c___type_def.html#ae26a65f4079b1f3af0490c463e6f6e90", null ],
[ "RESERVED3", "struct_l_p_c___r_t_c___type_def.html#a1936698394c9e65033538255b609f5d5", null ],
[ "RESERVED4", "struct_l_p_c___r_t_c___type_def.html#a23568af560875ec74b660f1860e06d3b", null ],
[ "RESERVED5", "struct_l_p_c___r_t_c___type_def.html#a17b8ef27f4663f5d6b0fe9c46ab9bc3d", null ],
[ "RESERVED6", "struct_l_p_c___r_t_c___type_def.html#a585b017c54971fb297a30e3927437015", null ],
[ "RESERVED7", "struct_l_p_c___r_t_c___type_def.html#af2e6e355909e4223f7665881b0514716", null ],
[ "RESERVED8", "struct_l_p_c___r_t_c___type_def.html#a8cb0d97b1d31d1921acc7aa587d1c60b", null ],
[ "RESERVED9", "struct_l_p_c___r_t_c___type_def.html#ad8b1fadb520f7a200ee0046e110edc79", null ],
[ "RTC_AUX", "struct_l_p_c___r_t_c___type_def.html#a8a91a5b909fbba65b28d972c3164a4ed", null ],
[ "RTC_AUXEN", "struct_l_p_c___r_t_c___type_def.html#a4f807cc73e86fa24a247e0dce31512a4", null ],
[ "SEC", "struct_l_p_c___r_t_c___type_def.html#a77f4a78b486ec068e5ced41419805802", null ],
[ "YEAR", "struct_l_p_c___r_t_c___type_def.html#aaf0ddcf6e202e34e9cf7b35c584f9849", null ]
];
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
var RemoveTileAt = require('./RemoveTileAt');
var WorldToTileX = require('./WorldToTileX');
var WorldToTileY = require('./WorldToTileY');
/**
* Removes the tile at the given world coordinates in the specified layer and updates the layer's
* collision information.
*
* @function Phaser.Tilemaps.Components.RemoveTileAtWorldXY
* @private
* @since 3.0.0
*
* @param {number} worldX - [description]
* @param {number} worldY - [description]
* @param {boolean} [replaceWithNull=true] - If true, this will replace the tile at the specified
* location with null instead of a Tile with an index of -1.
* @param {boolean} [recalculateFaces=true] - [description]
* @param {Phaser.Cameras.Scene2D.Camera} [camera=main camera] - [description]
* @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon.
*
* @return {Phaser.Tilemaps.Tile} The Tile object that was removed.
*/
var RemoveTileAtWorldXY = function (worldX, worldY, replaceWithNull, recalculateFaces, camera, layer)
{
var tileX = WorldToTileX(worldX, true, camera, layer);
var tileY = WorldToTileY(worldY, true, camera, layer);
return RemoveTileAt(tileX, tileY, replaceWithNull, recalculateFaces, layer);
};
module.exports = RemoveTileAtWorldXY;
|
/**
* Created by JiaHao on 27/10/15.
*/
var fs = require('fs');
var path = require('path');
var normalizeNewline = require('normalize-newline');
function occurenceIndexes(inp, toFind) {
var indices = [];
var element = toFind;
var idx = inp.indexOf(element);
while (idx != -1) {
indices.push(idx);
idx = inp.indexOf(element, idx + 1);
}
return indices;
}
const ANNONATION = {
start: '{',
end: '}'
};
/**
* Parses a file at a path
* @param path
* @returns {Array}
* @param annotation
*/
function parseText(path, annotation) {
var rawText = normalizeNewline(fs.readFileSync(path).toString());
var annotationToken = annotation || ANNONATION;
var startOccurances = occurenceIndexes(rawText, annotationToken.start);
var endOccurances = occurenceIndexes(rawText, annotationToken.end);
var allOccurances = startOccurances.concat(endOccurances).sort(function(a, b){return a-b});
var subtractIndexes = {};
for (var i = 0; i < allOccurances.length; i++) {
subtractIndexes[allOccurances[i]] = i;
}
var result = [];
var stack = []; // stack of start occurances
var counter = 0;
var startOccuranceCounter = 0;
var endOccuranceCounter = 0;
var startOccuranceNext;
var endOccuranceNext;
while (counter < rawText.length) {
startOccuranceNext = startOccurances[startOccuranceCounter];
endOccuranceNext = endOccurances[endOccuranceCounter];
if (counter === startOccuranceNext) {
stack.push(startOccuranceNext);
startOccuranceCounter+=1;
} else if (counter === endOccuranceNext) {
var stackNext = stack.pop();
result.push([stackNext, endOccuranceNext]);
endOccuranceCounter+=1;
}
counter += 1;
}
var subtractFunction = function (element) {
return element - subtractIndexes[element];
};
result = result.map(function (tuple) {
return tuple.map(subtractFunction);
});
return result;
}
module.exports = parseText;
if (require.main === module) {
var expected = [
[6, 10],
[35, 39],
[71, 76],
[296, 303],
[356,362]
];
var toParsePath = path.join(__dirname, '../', 'examples/annotatedData.txt');
var result = parseText(toParsePath);
}
|
module.exports.sum = function (arr, prop, exp) {
var total = 0
for (var i = 0, _len = arr.length; i < _len; i++) {
var value = arr[i][prop];
if (exp) {
if (arr[i][exp.field] == exp.value) {
total += value * 1;
}
} else {
total += value * 1;
}
}
return total
};
|
describe('Modules.Ellipsis.js', function() {
it('should exist with expected constructures', function() {
expect(moj.Modules.CaseCreation.init).toBeDefined();
});
});
|
import React, { Component } from 'react'
import {
Circle,
FeatureGroup,
LayerGroup,
Map,
Popup,
Rectangle,
TileLayer,
} from '../../src'
export default class OtherLayersExample extends Component {
render () {
const center = [51.505, -0.09]
const rectangle = [
[51.49, -0.08],
[51.5, -0.06],
]
return (
<Map center={center} zoom={13}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
<LayerGroup>
<Circle center={center} fillColor='blue' radius={200} />
<Circle center={center} fillColor='red' radius={100} stroke={false} />
<LayerGroup>
<Circle center={[51.51, -0.08]} color='green' fillColor='green' radius={100} />
</LayerGroup>
</LayerGroup>
<FeatureGroup color='purple'>
<Popup>
<span>Popup in FeatureGroup</span>
</Popup>
<Circle center={[51.51, -0.06]} radius={200} />
<Rectangle bounds={rectangle} />
</FeatureGroup>
</Map>
)
}
}
|
/**
* @author shirishgoyal
* created on 16.12.2015
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.auth', [
'BlurAdmin.services'
])
.config(routeConfig);
/** @ngInject */
function routeConfig($stateProvider) {
$stateProvider
.state('auth', {
url: '/auth',
abstract: true,
views: {
'full_screen': {
templateUrl: 'static/app/pages/auth/auth.html'
}
},
authenticate: false
})
// .state('auth.register', {
// url: '/register',
// templateUrl: 'static/app/pages/auth/register.html',
// controller: 'RegisterPageCtrl',
// controllerAs: 'vm'
// })
// .state('auth.login', {
// url: '/login',
// templateUrl: 'static/app/pages/auth/login.html',
// controller: 'LoginPageCtrl',
// controllerAs: 'vm'
// })
;
}
})();
|
/**
* Base js functions
*/
$(document).ready(function(){
//Init jQuery Masonry layout
init_masonry();
//Select menu onchange
$("#collapsed-navbar").change(function () {
window.location = $(this).val();
});
});
function init_masonry(){
var $container = $('#content');
$container.imagesLoaded( function(){
$container.masonry({
itemSelector: '.box',
isAnimated: true
});
});
}
*/
$(document).ready(function(){
//Start carousel
$('.carousel').carousel({interval:false});
});
|
var React = require('react');
var RulePicker = require('./RulePicker.js');
var TimePicker = require('react-time-picker');
var DatePicker = require('react-date-picker');
var RuleSummary = require("./RuleSummary.js");
var moment = require('moment');
var Tabs = require('react-simpletabs');
var RecurringSelect = React.createClass({displayName: "RecurringSelect",
getInitialState: function() {
return ({
rule: "daily",
interval: 1,
validations: null,
until: moment().format('YYYY-MM-DD'),
startTime: "10:00 AM"
});
},
handleRuleChange: function(e) {
var rule = e.target.value;
var validations = null;
if (rule === "weekly") validations = [];
if (rule === "monthly (by day of week)") {
rule = "monthly";
validations = {1: [], 2: [], 3: [], 4: []};
}
if (rule === "monthly (by day of month)") {
rule = "monthly";
validations = [];
}
this.setState({
rule: rule,
validations: validations
});
},
handleIntervalChange: function(e) {
var interval;
if (e.target.value != "") {
interval = parseInt(e.target.value);
} else {
interval = 0;
}
this.setState({
interval: interval
});
},
handleValidationsChange: function(validations) {
this.setState({
validations: validations
});
},
handleEndDateChange: function (date) {
this.setState({
until: date
});
},
handleTimeChange: function(time) {
this.setState({
startTime: time
});
},
handleSave: function(e) {
var hash = this.state;
console.log(hash.validations);
var iceCubeHash = {};
var start = moment(hash.startTime, "hh:mm a A");
var minute = start.minute();
var hour = start.hour();
var rule_type;
switch (hash.rule) {
case 'daily':
rule_type = "IceCube::DailyRule";
break;
case 'weekly':
rule_type = "IceCube::WeeklyRule";
break;
case 'monthly':
rule_type = "IceCube::MonthlyRule";
break;
case 'yearly':
rule_type = "IceCube::YearlyRule";
break;
}
var interval = hash.interval;
var validations = hash.validations == null ? {} : hash.validations;
var newValidations = {};
if (Array.isArray(validations) && rule_type == "IceCube::WeeklyRule") {
newValidations["day"] = validations
} else if (Array.isArray(validations) && rule_type == "IceCube::MonthlyRule") {
newValidations["day_of_month"] = validations;
} else if (rule_type == "IceCube::MonthlyRule") {
newValidations["day_of_week"] = validations;
}
newValidations["hour_of_day"] = hour;
newValidations["minute_of_hour"] = minute;
var until = hash.until;
iceCubeHash["rule_type"] = rule_type;
iceCubeHash["interval"] = interval;
iceCubeHash["validations"] = newValidations;
iceCubeHash["until"] = until;
this.props.onSave(JSON.stringify(iceCubeHash));
},
render: function() {
return (
React.createElement("div", {className: "recurring-select"},
React.createElement(Tabs, null,
React.createElement(Tabs.Panel, {title: "Recurrence Rule"},
React.createElement(RulePicker, {
rule: this.state.rule,
interval: this.state.interval,
validations: this.state.validations,
onRuleChange: this.handleRuleChange,
onIntervalChange: this.handleIntervalChange,
onValidationsChange: this.handleValidationsChange})
),
React.createElement(Tabs.Panel, {title: "Occurence Time"},
React.createElement(TimePicker, {value: this.state.startTime, onChange: this.handleTimeChange})
),
React.createElement(Tabs.Panel, {title: "Recurring Until"},
React.createElement(DatePicker, {minDate: moment().format("YYYY-MM-DD"), date: this.state.until, onChange: this.handleEndDateChange})
)
),
React.createElement("hr", null),
React.createElement(RuleSummary, {fields: this.state}),
React.createElement("button", {className: "btn save", onClick: this.handleSave}, "Save")
)
);
}
});
module.exports = RecurringSelect;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = eachLimit;
var _eachOfLimit = require('./internal/eachOfLimit');
var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
var _withoutIndex = require('./internal/withoutIndex');
var _withoutIndex2 = _interopRequireDefault(_withoutIndex);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
*
* @name eachLimit
* @static
* @memberOf module:Collections
* @method
* @see [async.each]{@link module:Collections.each}
* @alias forEachLimit
* @category Collection
* @param {Array|Iterable|Object} coll - A colleciton to iterate over.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} iteratee - A function to apply to each item in `coll`. The
* iteratee is passed a `callback(err)` which must be called once it has
* completed. If no error has occurred, the `callback` should be run without
* arguments or with an explicit `null` argument. The array index is not passed
* to the iteratee. Invoked with (item, callback). If you need the index, use
* `eachOfLimit`.
* @param {Function} [callback] - A callback which is called when all
* `iteratee` functions have finished, or an error occurs. Invoked with (err).
*/
function eachLimit(coll, limit, iteratee, callback) {
(0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)(iteratee), callback);
}
module.exports = exports['default'];
|
angular.module('green-streak.controllers', ['LocalStorageModule'])
.controller('MenuController', function ($scope, $location, MenuService) {
// "MenuService" is a service returning mock data (services.js)
$scope.list = MenuService.all();
$scope.goTo = function (page) {
console.log('Going to ' + page);
$scope.sideMenuController.toggleLeft();
$location.url('/' + page);
};
})
.controller('AuthController', function ($scope, $ionicPlatform, $state, localStorageService) {
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
})
.controller('IndexController', function ($scope, $ionicPlatform, $state, localStorageService) {
// var authenticated = localStorageService.get('authenticated');
// if (authenticated)
// {
// $state.go('one');
// }
$scope.navTitle = "Green Streak";
$scope.user = {userName: ''};
$scope.search = function () {
console.log("Searching for userName: " + $scope.user.userName)
localStorageService.set("userName", $scope.user.userName);
$state.go('square');
};
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
})
.controller("CallbackController", function ($scope, $location, $state, AuthService, localStorageService) {
$scope.currentURL = $location.absUrl();
var paramPartOfURL = $scope.currentURL.slice($scope.currentURL.indexOf('code=') + 5);
var indexOfSlash = paramPartOfURL.indexOf('/');
var oAuthCode = paramPartOfURL.slice(0, indexOfSlash)
AuthService.get({'tokenId': oAuthCode}, function (success) {
localStorageService.add("authenticated", true);
$state.go('one');
}, function (error) { // error callback
localStorageService.remove("authenticated");
});
})
.controller('OneController', function ($scope, LanguageCountService) {
$scope.navTitle = "Language Data by count";
$scope.d3Data = LanguageCountService.query();
$scope.d3OnClick = function (item) {
// alert(item.name);
};
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
})
.controller('SquareController', function ($scope, ContributionsService, localStorageService) {
$scope.navTitle = "Daily Contribution";
$scope.contributionData = ContributionsService.list({'userId': localStorageService.get("userName")}, function (success) {
var result = [];
for (var i = 0; i < success.length; i++) {
result.push(success[i][1]);
}
console.log("returning results")
$scope.contributionData = result;
});
$scope.deviceWidth = window.innerWidth || document.body.clientWidth;
$scope.deviceHeight = window.innerHeight || document.body.clientHeight;
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
})
.controller('ThreeController', function ($scope) {
$scope.navTitle = "Page Three Title";
$scope.leftButtons = [
{
type: 'button-icon icon ion-navicon',
tap: function (e) {
$scope.sideMenuController.toggleLeft();
}
}
];
$scope.rightButtons = [];
});
|
import templateUrl from './image.html';
import controller from './image-controller';
export default {
name: 'image',
url: '/:image',
templateUrl,
controller,
controllerAs: 'image',
resolve: {
image: ['$http', '$stateParams', function($http, $stateParams){
const config = {
method: 'GET',
url: 'api/images/'+$stateParams.image,
params: {metadata: true}
};
return $http(config);
}]
}
};
|
const mongoose = require('mongoose')
let literatureSchema = mongoose.Schema({
category: { type: String, required: true},
name: { type: String, required: true },
description: { type: String },
content: { type: String, required: true },
author: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
comments: [{type: mongoose.Schema.Types.ObjectId, ref: 'Comment'}],
views: {type: Number},
date: { type: String }
})
literatureSchema.method({
prepareDelete: function () {
let User = mongoose.model('User')
User.findById(this.author).then(user => {
"use strict";
if (user) {
user.literature.remove(this.id)
user.save()
}
})
let Comment = mongoose.model('Comment')
for (let commentId of this.comments) {
Comment.findOneAndRemove(commentId).populate('author').then(comment => {
"use strict";
if (comment) {
let author = comment.author
let index = author.comments.indexOf(commentId)
let count = 1
author.comments.splice(index, count);
author.save()
comment.save()
}
})
}
}
})
literatureSchema.set('versionKey', false);
const Literature = mongoose.model('Literature', literatureSchema)
module.exports = Literature
|
// Saves options to chrome.storage
function save_options () {
var saveDict = []
var i = 1
$('input').map(function () {
var dict = {
id: 'scbcc' + i,
value: this.value
}
i++
console.log('save: ', dict)
ga('send', 'event', 'setting', 'save', this.value)
saveDict.push(dict)
}).get()
chrome.storage.sync.set({
scbccRegexDict: saveDict
})
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options () {
chrome.storage.sync.get({
scbccRegexDict: []
}, function (items) {
$('#field1').attr('value', items.scbccRegexDict[0].value)
for (var i = 0; i < items.scbccRegexDict.length; i++) {
var value = items.scbccRegexDict[i].value
var next = i
var addto = '#remove' + next
var addRemove = '#field' + (next + 1)
next = next + 1
var newIn = '<input autocomplete="off" placeholder="e.g. /this is test/g" id="field' + next + '" name="field' + next + '" type="text" tabindex="1" value=' + value + '>'
var newInput = $(newIn)
var removeBtn = '<button id="remove' + (next) + '" class="btn btn-danger remove-me" >-</button>'
var removeButton = $(removeBtn)
$(addto).after(newInput)
if (i !== 0) {
$(addRemove).after(removeButton)
}
$('#count').val(next)
$('.remove-me').click(function (e) {
e.preventDefault()
ga('send', 'event', 'setting', 'remove_regex')
var fieldNum = this.id.charAt(this.id.length - 1)
var fieldID = '#field' + fieldNum
$(this).remove()
$(fieldID).remove()
$('#style').attr('href', 'extra/styles.css')
})
}
var next = items.scbccRegexDict.length || 1
$('.add-more').click(function (e) {
ga('send', 'event', 'setting', 'add_regex')
e.preventDefault()
var addto = '#remove' + next
var addRemove = '#field' + (next + 1)
next = next + 1
var newIn = '<input autocomplete="off" placeholder="e.g. /this is test/g" id="field' + next + '" name="field' + next + '" type="text" tabindex="1">'
var newInput = $(newIn)
var removeBtn = '<button id="remove' + (next) + '" class="btn btn-danger remove-me" >-</button>'
var removeButton = $(removeBtn)
$(addto).after(newInput)
$(addRemove).after(removeButton)
$('#count').val(next)
$('.remove-me').click(function (e) {
e.preventDefault()
ga('send', 'event', 'setting', 'remove_regex')
var fieldNum = this.id.charAt(this.id.length - 1)
var fieldID = '#field' + fieldNum
$(this).remove()
$(fieldID).remove()
$('#style').attr('href', 'extra/styles.css')
})
})
})
}
document.addEventListener('DOMContentLoaded', restore_options)
document.getElementById('save').addEventListener('click', save_options)
|
'use strict';
module.exports = {
colors: {
black: '#000000',
red: '#D54E53',
green: '#B9CA4A',
yellow: '#E7C547',
blue: '#7AA6DA',
magenta: '#C397D8',
cyan: '#70C0B1',
white: '#EAEAEA',
lightBlack: '#969896',
lightRed: '#D54E53',
lightGreen: '#B9CA4A',
lightYellow: '#E7C547',
lightBlue: '#7AA6DA',
lightMagenta: '#C397D8',
lightCyan: '#70C0B1',
lightWhite: '#EAEAEA',
},
// Default
backgroundColor: '#000000',
foregroundColor: '#EAEAEA',
cursorColor: '#EAEAEA',
borderColor: '#171717',
// Accent color
accentColor: '#7AA6DA',
// Other
tabTitleColor: 'rgba(255, 255, 255, 0.2)',
selectedTabTitleColor: '#EAEAEA',
};
|
/**
* @Author: Yingya Zhang <zyy>
* @Date: 2016-07-08 11:29:00
* @Email: zyy7259@gmail.com
* @Last modified by: zyy
* @Last modified time: 2016-07-10 22:18:85
*/
import {
notexist,
isEmpty
} from 'type'
import {
calcHeight,
remove,
dataset
} from 'dom'
describe('dom', () => {
it('calcHeight', () => {
const height = 42
const p = document.createElement('p')
p.id = 'calcHeight-' + (+new Date())
p.style.margin = 0
p.style.padding = 0
p.style.lineHeight = height + 'px'
p.style.fontSize = '18px'
const textNode = document.createTextNode('text')
p.appendChild(textNode)
const height1 = calcHeight(p)
expect(height1).toBe(height)
})
it('remove', () => {
const domStr = '<div id="divRemove"></div>'
document.body.innerHTML += domStr
const div = document.getElementById('divRemove')
expect(div.parentNode).toEqual(jasmine.anything())
remove(div)
expect(notexist(div.parentNode)).toBe(true)
})
it('dataset', () => {
const domStr = '<div id="divDataset"></div>'
document.body.innerHTML += domStr
const div = document.getElementById('divDataset')
const name = dataset(div, 'name')
expect(isEmpty(name)).toBe(true)
dataset(div, 'name', 'foo')
expect(dataset(div, 'name')).toBe('foo')
remove(div)
})
// TODO html2node
})
|
/* http://fiidmi.fi/documentation/customer_order_history */
module.exports = {
"bonus": {
"type": "object",
"properties": {
"session_id": { "type": "string", "minLength": 2, "maxLength": 50 },
"restaurant_id": { "type": "string", "minLength": 1, "maxLength": 50 }
},
"required": ["session_id", "restaurant_id"]
},
"po_credit": {
"type": "object",
"properties": {
"session_id": { "type": "string", "minLength": 2, "maxLength": 50 }
},
"required": ["session_id", "order_id"]
}
};
|
var ItineraryWalkStep = require('./itinerary-walk-step')
var Backbone = window.Backbone
var ItineraryWalkSteps = Backbone.Collection.extend({
model: ItineraryWalkStep
})
module.exports = ItineraryWalkSteps
|
/*
* Copyright (c) 2015 by Greg Reimer <gregreimer@gmail.com>
* MIT License. See license.txt for more info.
*/
var stream = require('stream')
, util = require('util')
, co = require('co')
, unresolved = require('./unresolved')
// -----------------------------------------------------
function Readable(opts, sender) {
stream.Readable.call(this, opts);
this._ponySending = unresolved();
var self = this;
function output(data, enc) {
return self._ponySending.then(function() {
if (!self.push(data, enc)) {
self._ponySending = unresolved();
}
});
}
co(sender.bind(this, output))
.then(function() { self.push(null); })
.catch(function(err) { self.emit('error', err); });
}
util.inherits(Readable, stream.Readable);
Readable.prototype._read = function() {
this._ponySending.resolve();
};
// -----------------------------------------------------
module.exports = Readable;
|
'use strict';
describe('E2E testing: Change password', function () {
var constants = require('../../../testConstants');
var loginPage = require('../../pages/loginPage');
var header = require('../../pages/pageHeader');
var changePasswordPage = require('../../pages/changePasswordPage');
var expectedCondition = protractor.ExpectedConditions;
var CONDITION_TIMEOUT = 3000;
var newPassword = '12345678';
it('setup: login as user, go to change password page', function () {
loginPage.loginAsUser();
changePasswordPage.get();
});
it('refuses to allow form submission if the confirm input does not match', function () {
changePasswordPage.password.sendKeys(newPassword);
changePasswordPage.confirm.sendKeys('blah12345');
expect(changePasswordPage.submitButton.isEnabled()).toBeFalsy();
changePasswordPage.password.clear();
changePasswordPage.confirm.clear();
});
it('allows form submission if the confirm input matches', function () {
changePasswordPage.password.sendKeys(newPassword);
changePasswordPage.confirm.sendKeys(newPassword);
expect(changePasswordPage.submitButton.isEnabled()).toBeTruthy();
changePasswordPage.password.clear();
changePasswordPage.confirm.clear();
});
/* cant test this yet because I don't know how to test for HTML 5 form validation - cjh 2014-06
it('should not allow a password less than 7 characters', function() {
var shortPassword = '12345';
changePasswordPage.password.sendKeys(shortPassword);
changePasswordPage.confirm.sendKeys(shortPassword);
expect(changePasswordPage.submitButton.isEnabled()).toBe(false);
changePasswordPage.password.clear();
changePasswordPage.confirm.clear();
});
*/
it('can successfully changes user\'s password after form submission', function () {
changePasswordPage.password.sendKeys(newPassword);
changePasswordPage.confirm.sendKeys(newPassword);
browser.wait(expectedCondition.visibilityOf(changePasswordPage.passwordMatchImage),
CONDITION_TIMEOUT);
browser.wait(expectedCondition.elementToBeClickable(changePasswordPage.submitButton),
CONDITION_TIMEOUT);
changePasswordPage.submitButton.click();
expect(changePasswordPage.noticeList.count()).toBe(1);
expect(changePasswordPage.noticeList.first().getText()).toContain('Password Updated');
loginPage.logout();
loginPage.login(constants.memberUsername, newPassword);
browser.wait(expectedCondition.visibilityOf(header.myProjects.button), CONDITION_TIMEOUT);
expect(header.myProjects.button.isDisplayed()).toBe(true);
// reset password back to original
changePasswordPage.get();
changePasswordPage.password.sendKeys(constants.memberPassword);
changePasswordPage.confirm.sendKeys(constants.memberPassword);
browser.wait(expectedCondition.visibilityOf(changePasswordPage.passwordMatchImage),
CONDITION_TIMEOUT);
browser.wait(expectedCondition.elementToBeClickable(changePasswordPage.submitButton),
CONDITION_TIMEOUT);
changePasswordPage.submitButton.click();
});
});
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014-2022 Mickael Jeanroy
*
* 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.
*/
import {isNumber} from './is-number.js';
/**
* Check that a given value is a falsy value.
*
* @param {*} a Value to check.
* @return {boolean} `true` if parameter is a falsy value.
*/
export function isFiniteNumber(a) {
return isNumber(a) && isFinite(a);
}
|
/**
* Created by TC on 2016/10/10.
*/
import React, {
Component,
} from 'react'
import {
Image,
View,
ToastAndroid,
ActivityIndicator,
}
from 'react-native'
import PixelRatio from "react-native/Libraries/Utilities/PixelRatio";
class GirlComponent extends Component {
constructor(props) {
super(props);
this.state = {
imgUrl: ''
}
}
loadImage() {
this.setState({imgUrl: ''});
this.getImage();
}
componentWillMount() {
this.getImage();
}
getImage() {
fetch('http://gank.io/api/data/福利/100/1')//异步请求图片
.then((response) => {
return response.json();
})
.then((responseJson) => {
if (responseJson.results) {
const index = Math.ceil(Math.random() * 100 - 1);//随机取一张福利图
this.setState({imgUrl: responseJson.results[index].url});
}
}).catch((error) => console.error(error))
.done();
}
render() {
if (this.state.imgUrl.length == 0) {
return (
<View style={ {flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
<ActivityIndicator size='large' color='#00BCD4'/>
</View>
);
} else {
return (
<View style={{flexDirection: 'column', flex: 1}}>
<Image source={{uri: this.state.imgUrl}}
style={{width: 200 * PixelRatio.get(), height: 200 * PixelRatio.get()}}/>
</View>
);
}
}
}
export default GirlComponent;
|
export * from '../common';
export NodeBundle from './NodeBundle';
export CommonJsResolver from './CommonJsResolver';
|
const webpack = require("webpack");
const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const AssetsPlugin = require("assets-webpack-plugin");
module.exports = {
entry: {
main: path.join(__dirname, "src", "index.js")
},
output: {
path: path.join(__dirname, "dist")
},
module: {
rules: [
{
test: /\.((png)|(eot)|(woff)|(woff2)|(ttf)|(svg)|(gif))(\?v=\d+\.\d+\.\d+)?$/,
loader: "file-loader?name=/[hash].[ext]"
},
{test: /\.json$/, loader: "json-loader"},
{
loader: "babel-loader",
test: /\.js?$/,
exclude: /node_modules/,
query: {cacheDirectory: true}
},
{
test: /\.(sa|sc|c)ss$/,
exclude: /node_modules/,
use: ["style-loader", MiniCssExtractPlugin.loader, "css-loader", "postcss-loader", "sass-loader"]
}
]
},
plugins: [
new webpack.ProvidePlugin({
fetch: "imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch"
}),
new AssetsPlugin({
filename: "webpack.json",
path: path.join(process.cwd(), "site/data"),
prettyPrint: true
}),
// new CopyWebpackPlugin([
// {
// from: "./src/fonts/",
// to: "fonts/",
// flatten: true
// }
// ])
]
};
|
window.onload=function() {
var start = document.getElementById('start');
start.onclick = function () {
var name = document.getElementById('Name').value;
var id = document.getElementById('Id').value;
var tel = document.getElementById("Tel").value;
if (name == "") {
alert("请输入名字");
return false;
}
if (!isName(name)) {
alert("请输入正确的姓名")
return false;
}
if (id =="") {
alert("请输入学号");
return false;
}
if (!isId(id)) {
alert("请输入正确学号");
return false;
}
if (tel == "") {
alert("请输入电话号码");
return false;
}
if (!isTelephone(tel)) {
alert("请输入正确的手机号码");
return false;
}
else {
start.submit();
// document.getElementById("myform").submit();
// window.open("answer.html","_self");
}
}
function isName(obj) {
var nameReg = /[\u4E00-\u9FA5]+$/;
return nameReg.test(obj);
}
function isId(obj) {
var emailReg = /^2017\d{8}$/;
return emailReg.test(obj);
}
function isTelephone(obj) {
reg = /^1[34578]\d{9}$/;
return reg.test(obj);
}
}
|
(function (){
"use strict";
(function() {
var $bordered = $('.bordered');
window.setInterval(function() {
var top = window.pageYOffset || document.documentElement.scrollTop;
if(top > 0) {
$bordered.fadeOut('fast');
} else if(top == 0 && !$bordered.is(':visible')) {
$bordered.fadeIn("fast");
}
}, 200);
})();
$(function() {
$('.scroll').click(function(e) {
e.preventDefault();
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
(function () {
var $hash = $(location.hash);
if ($hash.hasClass('modal')) {
$hash.modal('show');
}
})();
//
// carousels intervals and disabled the keyboard support
//
$(document).ready(function(){
$('#backgroundCarousel').carousel({
interval: 10000000, // TODO just one slide for now
keyboard : false
});
$('#partnersCarousel').carousel({
interval: 4000,
keyboard : false
});
});
})();
(function(){
"use strict";
//
// toggle popups from pricing dialog to the partners dialog
//
var cennik = $("#cennik");
var ponuka = $("#ponuka");
function toggle(){
cennik.modal("toggle");
ponuka.modal("toggle");
}
$("#cennik button").on("click", toggle);
})();
(function(){
"use strict";
//
// deep linking for tracking google analytics
// requested by michael, should not be also standard deep linking
//
function setDeeplinking(event){
window.location.hash = $(event.target).data("target");
}
function clearDeeplinking(event){
window.location.hash = "";
}
$("nav .menu").on("click", setDeeplinking);
$("#try").on("click", setDeeplinking);
$('#cennik').on('hidden.bs.modal', clearDeeplinking);
$('#ponuka').on('hidden.bs.modal', clearDeeplinking);
$('#kontakt').on('hidden.bs.modal', clearDeeplinking);
})();
(function(){
"use strict";
//
// sending emails via the rest api
//
$("#form1").on("click", function(e){
e.preventDefault();
sendContent(
$("#formName1")[0].value,
$("#formEmail1")[0].value,
$("#formNote1")[0].value,
$($("#events1")[0]).prop('checked'),
function(){
$("#formName1").css("display", "none");
$("#form1").css("display", "none");
$("#formEmail1").css("display", "none");
$("#formNote1").css("display", "none");
$("#events1").css("display", "none");
$(".events-align label").css("display", "none");
$("#mobilethanks").css("display", "block");
}
);
});
$("#form2").on("click", function(e){
e.preventDefault();
sendContent(
$("#formName2")[0].value,
$("#formEmail2")[0].value,
$("#formNote2")[0].value,
$($("#events2")[0]).prop('checked'),
function emptyCallback(){}
);
});
function sendContent(name, email, note, newsletter, callback){
var EMAIL_RECIPIENT = "pridajsa@halmispace.sk";
var NAME_RECIPIENT = "HalmiSpace";
var SND_EMAIL_RECIPIENT = "x+25519533291603@mail.asana.com";
var SND_NAME_RECIPIENT = "Lolovia";
if (!email){
email = ":( Uchádzač nespokytol žiadny email.";
}
if (!note){
note = ":( Uchádzač neposlal žiadnu poznámku.";
}
if (!name){
name = "Uchádzač";
}
console.log("newsletter", newsletter);
var wantsReceiveEmail = newsletter
? "Áno, mám záujem o newsletter."
: "Nemám záujem o newsletter.";
var toParam = {
"email": EMAIL_RECIPIENT,
"name": NAME_RECIPIENT,
"type": "to"
};
var message = "";
message += "Uchádzač: " + name + "<br/>";
message += "Email: " + email + "<br/>";
message += "Poznámka: " + note + "<br/>";
message += "Newsletter: " + wantsReceiveEmail + "<br/>";
var messageParam = {
"from_email": "pridajsa@halmispace.sk",
"to": [toParam, {
"email": SND_EMAIL_RECIPIENT,
"name": SND_NAME_RECIPIENT,
"type": "to"
}],
"headers": {
"Reply-To": email
},
"autotext": "true",
"subject": "Uchádzač o coworking: " + name,
"html": message
};
var opts = {
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: { "key": "9WZGkQuvFHBbuy-p8ZOPjQ", "message": messageParam },
type: "POST",
crossDomain: true,
success: function(msg){ console.info("success email message", msg[0]); },
error : function(){ alert("Vyskytla sa chyba, kontaktuj nas na pridajsa@halmispace.sk!") }
};
$.ajax(opts).done(function(){
$("#formName1")[0].value = "";
$("#formEmail1")[0].value = "";
$("#formNote1")[0].value = "";
$("#formName2")[0].value = "";
$("#formEmail2")[0].value = "";
$("#formNote2")[0].value = "";
$("#thanks").addClass("active");
callback();
});
}
})();
|
describe('$materialPopup service', function() {
beforeEach(module('material.services.popup', 'ngAnimateMock'));
function setup(options) {
var popup;
inject(function($materialPopup, $rootScope) {
$materialPopup(options).then(function(p) {
popup = p;
});
$rootScope.$apply();
});
return popup;
}
describe('enter()', function() {
it('should append to options.appendTo', inject(function($animate, $rootScope) {
var parent = angular.element('<div id="parent">');
var popup = setup({
appendTo: parent,
template: '<div id="element"></div>'
});
popup.enter();
$rootScope.$digest();
expect($animate.queue.shift().event).toBe('enter');
expect(popup.element.parent()[0]).toBe(parent[0]); //fails
}));
it('should append to $rootElement by default', inject(function($rootScope, $document, $rootElement) {
var popup = setup({
template: '<div id="element"></div>'
});
popup.enter();
$rootScope.$digest();
expect(popup.element.parent()[0]).toBe($rootElement[0]);
}));
});
describe('destroy()', function() {
it('should leave and then destroy scope', inject(function($rootScope, $animate) {
var popup = setup({
template: '<div>'
});
popup.enter();
$rootScope.$apply();
var scope = popup.element.scope();
spyOn($animate, 'leave').andCallFake(function(element, cb) { cb(); });
spyOn(scope, '$destroy');
popup.destroy();
expect($animate.leave).toHaveBeenCalled();
expect(scope.$destroy).toHaveBeenCalled();
}));
});
});
|
/**
* Created by Samuel Schmid on 23.03.14.
*
* Class for Database Handling
*
* Containing
* - App Config
* - Database Information
*
* @type {Database}
*/
module.exports = Database;
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
String.prototype.replaceAll = function(target, replacement) {
return this.split(target).join(replacement);
};
function Database(grunt) {
this.grunt = grunt;
this.appconfig = grunt.config().appconfig;
this.db = this.appconfig.db;
}
/**
* delete Database Schemes of Docs
*
* @param docs
*/
Database.prototype.deleteSchemes = function(docs) {
var grunt = this.grunt;
grunt.log.debug("start ");
if(docs.docs.length > 0) {
var firstDoc = docs.docs[0];
var rootfolder = firstDoc.schemefolder.split("/")[0];
grunt.log.debug("Database: delete files in folder:" + rootfolder);
grunt.file.delete(rootfolder);
} else {
grunt.log.debug("Empty");
return;
}
}
/**
* create Database Schemes for Docs
*
* @param docs
*/
Database.prototype.createSchemes = function(docs) {
var grunt = this.grunt;
if(this.db.name === "mongodb") {
if(this.db.provider === "mongoose") {
grunt.log.write("start writing schemes for database " + this.db.name + " and provider "+this.db.provider + ".");
var Provider = require('./providers/mongoose/mongoose-provider.js');
var provider = new Provider(grunt);
for(var i=0;i<docs.docs.length;i++) {
var doc = docs.docs[i];
if(doc.json.type.endsWith('.abstract')) {
provider.writeAbstractScheme(doc);
}
}
for(var i=0;i<docs.docs.length;i++) {
var doc = docs.docs[i];
if(!doc.json.type.endsWith('.apidescription') && !doc.json.type.endsWith('.abstract')) {
provider.writeScheme(doc);
}
}
provider.writeLib();
} else {
grunt.log.write("cannot create schemes for database " + this.db.name + ", because there we can't use the provider "+this.db.provider+" for it.");
}
} else {
grunt.log.write("cannot create schemes for database " + this.db.name + ", because there is no provider for it.");
}
}
|
Test.expect(reverseWords('The quick brown fox jumps over the lazy dog.') === 'ehT kciuq nworb xof spmuj revo eht yzal .god');
Test.expect(reverseWords('apple') === 'elppa');
Test.expect(reverseWords('a b c d') === 'a b c d');
Test.expect(reverseWords('double spaced words') === 'elbuod decaps sdrow');
|
'use strict';
import { gl } from './Context';
import { mat4 } from 'gl-matrix';
import Camera from './Camera';
class OrthographicCamera extends Camera
{
constructor(
{
path,
uniforms,
background,
translucence,
right,
top,
name = 'orthographic.camera',
left = -1,
bottom = -1,
near = 0.1,
far = 1
} = {})
{
super({ name, path, uniforms, background, translucence });
this.left = left;
this.right = right;
this.bottom = bottom;
this.top = top;
this.near = near;
this.far = far;
this.inheritance = ['Entity', 'Structure', 'Camera', 'OrthographicCamera'];
this.configure();
}
get left()
{
return this._left;
}
set left(left)
{
this._left = left;
}
get right()
{
return this._right;
}
set right(right)
{
this._right = right;
}
get bottom()
{
return this._bottom;
}
set bottom(bottom)
{
this._bottom = bottom;
}
get top()
{
return this._top;
}
set top(top)
{
this._top = top;
}
get near()
{
return this._near;
}
set near(near)
{
this._near = near;
}
get far()
{
return this._far;
}
set far(far)
{
this._far = far;
}
configure()
{
super.configure();
mat4.ortho(this.projectionMatrix, this.left, this.right, this.bottom, this.top, this.near, this.far);
mat4.identity(this.modelViewMatrix);
}
bind(program)
{
super.bind(program);
gl.disable(gl.DEPTH_TEST);
gl.viewport(0, 0, this.right, this.top);
}
}
export default OrthographicCamera;
|
// Karma configuration
// Generated on Wed Feb 17 2016 10:45:47 GMT+0100 (CET)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['systemjs', 'jasmine'],
// list of files / patterns to load in the browser
files: [
'app/**/*spec.js'
],
systemjs: {
// Point out where the SystemJS config file is
configFile: 'app/systemjs.config.js',
serveFiles: [
'app/**/*.js'
]
},
plugins: [
'karma-systemjs',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-junit-reporter',
'karma-coverage'
],
// list of files to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'app/**/!(*spec).js': ['coverage']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage'],
coverageReporter: {
reporters:[
{type: 'lcov', subdir: 'report-lcov'},
{type: 'json', subdir: 'report-json', file: 'coverage-final.json'},
]
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
|
'use strict'
// create a net-peer compatible object based on a UDP datagram socket
module.exports = function udpAdapter(udpSocket, udpDestinationHost, udpDestinationPort) {
const _listeners = []
udpSocket.on('message', (msg, rinfo) => {
//console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`)
for(let i=0; i < _listeners.length; i++) {
_listeners[i](msg)
}
})
let on = function(event, fn) {
if (event === 'data') {
_listeners.push(fn)
}
}
let send = function(message) {
udpSocket.send(Buffer.from(message.buffer), udpDestinationPort, udpDestinationHost, (err) => { })
}
return Object.freeze({ on, send })
}
|
var Filter = require('broccoli-filter')
module.exports = WrapFilter;
WrapFilter.prototype = Object.create(Filter.prototype);
WrapFilter.prototype.constructor = WrapFilter;
function WrapFilter (inputTree, options) {
if (!(this instanceof WrapFilter)) return new WrapFilter(inputTree, options)
Filter.call(this, inputTree, options)
this.options = options || {};
this.options.extensions = this.options.extensions || ['js'];
this.extensions = this.options.extensions;
}
WrapFilter.prototype.processString = function (string) {
var wrapper = this.options.wrapper;
if ( !(wrapper instanceof Array) ) {
return string;
}
var startWith = wrapper[0] || '';
var endWith = wrapper[1] || '';
return [startWith, string, endWith].join('')
}
|
Template.formeditprofile.events({
'submit #editform': function(event){
event.preventDefault();
var firstNameVar = event.target.firstname.value;
var lastNameVar = event.target.lastname.value;
var classVar = event.target.classvar.value;
Profiles.insert({
uid:Meteor.userId(),
firstname: firstNameVar,
lastname: lastNameVar,
classvar: classVar
});
alert("Done!");
}
});
Template.addprofile.rendered = function(){
this.$('.ui.dropdown').dropdown();
}
|
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import './PostListView.scss';
import { toastr } from 'react-redux-toastr';
import { bindActionCreators } from 'redux';
import {
fetchPostsFromApi,
selectPostCategory,
clearPostsErrors,
clearPostsMessages
} from '../../../actions/actionCreators';
import CategoryFilterContainer from '../../CategoryFilterContainer/CategoryFilterContainer';
import {
PostList,
LoadingIndicator,
Divider,
MessagesSection
} from '../../../components';
import NoPostsFound from '../Misc/NoPostsFound';
// containsCategory :: Object -> Object -> Bool
const containsCategory = (post, category) => {
const categories = post.categories.filter(
(cat) => cat._id == category.id
);
return categories.length > 0;
};
// getFilteredPosts :: Object -> [Object] -> [Object]
const getFilteredPosts = (
category,
posts
) => {
if (category === null || category.name === 'All') {
return posts;
}
return posts.filter((post) => {
if (containsCategory(post, category)) {
return post;
}
return undefined;
});
};
/* Only used internally and it's so small so not worth creating a new component */
const SectionSubTitle = ({
title
}) => (
<h4 className="section-sub-title">
{title}
</h4>
);
SectionSubTitle.propTypes = {
title: PropTypes.string.isRequired
};
class PostListView extends React.Component {
constructor(props) {
super(props);
this.handleSelectCategory = this.handleSelectCategory.bind(this);
this.handleChangePage = this.handleChangePage.bind(this);
this.handleClose = this.handleClose.bind(this);
}
componentDidMount() {
const {
posts,
fetchPosts
} = this.props;
if (!posts.items || posts.items.length === 0) {
fetchPosts();
}
}
handleChangePage() {
//TODO: Implement me!!
}
handleSelectCategory(category) {
const {
selectPostCat
} = this.props;
selectPostCat(category);
}
showMessage(message) {
toastr.info(message);
}
handleClose(sender) {
const {
clearErrors,
clearMessages
} = this.props;
const theElement = sender.target.id;
if (theElement === 'button-close-error-panel') {
clearErrors();
} else if (theElement === 'button-close-messages-panel') {
clearMessages();
}
}
render() {
const {
posts,
isFetching,
postCategories,
selectedCategory,
errors,
messages
} = this.props;
const items = posts.items;
const visiblePosts = getFilteredPosts(selectedCategory, items);
return (
<LoadingIndicator isLoading={isFetching}>
<div className="post-list-view__wrapper">
<MessagesSection messages={messages} errors={errors} onClose={this.handleClose} />
<h1 className="section-header">From the Blog</h1>
<SectionSubTitle
title={selectedCategory.name == 'All' ? // eslint-disable-line
'All Posts'
:
`Selected Category: ${selectedCategory.name}`
}
/>
<Divider />
<CategoryFilterContainer
categories={postCategories}
onSelectCategory={this.handleSelectCategory}
selectedCategory={selectedCategory}
/>
{visiblePosts !== undefined && visiblePosts.length > 0 ?
<PostList
posts={visiblePosts}
onChangePage={this.handleChangePage}
/>
:
<NoPostsFound
selectedCategory={selectedCategory}
/>
}
</div>
</LoadingIndicator>
);
}
}
PostListView.propTypes = {
dispatch: PropTypes.func.isRequired,
errors: PropTypes.array.isRequired,
messages: PropTypes.array.isRequired,
posts: PropTypes.object.isRequired,
isFetching: PropTypes.bool.isRequired,
fetchPosts: PropTypes.func.isRequired,
selectPostCat: PropTypes.func.isRequired,
postCategories: PropTypes.array.isRequired,
selectedCategory: PropTypes.object.isRequired,
clearMessages: PropTypes.func.isRequired,
clearErrors: PropTypes.func.isRequired
};
// mapStateToProps :: {State} -> {Props}
const mapStateToProps = (state) => ({
posts: state.posts,
postCategories: state.posts.categories,
selectedCategory: state.posts.selectedCategory,
messages: state.messages.posts,
errors: state.errors.posts,
isFetching: state.posts.isFetching
});
// mapDispatchToProps :: {Dispatch} -> {Props}
const mapDispatchToProps = (dispatch) =>
bindActionCreators({
fetchPosts: () => fetchPostsFromApi(),
selectPostCat: (category) => selectPostCategory(category),
clearMessages: () => clearPostsMessages(),
clearErrors: () => clearPostsErrors()
}, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps
)(PostListView);
|
version https://git-lfs.github.com/spec/v1
oid sha256:4a4e80129485fe848fa53149568184f09fa2da8648b6476b750ef97344bd4c5b
size 10959
|
function showErrorMessage(errorMessage) {
$("#authorize-prompt")
.addClass("error-prompt")
.removeClass("success-prompt")
.html(errorMessage);
}
function showSuccessMessage(message) {
$("#authorize-prompt")
.removeClass("error-prompt")
.addClass("success-prompt")
.html(message);
}
function shake() {
var l = 10;
var original = -150;
for( var i = 0; i < 8; i++ ) {
var computed;
if (i % 2 > 0.51) {
computed = original - l;
} else {
computed = original + l;
}
$("#login-box").animate({
"left": computed + "px"
}, 100);
}
$("#login-box").animate({
"left": "-150px"
}, 50);
}
function handleAuthSuccess(data) {
showSuccessMessage(data.message);
$("#login-button").prop("disabled", true);
setTimeout(function() {
location.href = data.redirectUri;
}, 1000);
}
function handleAuthFailure(data) {
showErrorMessage(data.responseJSON.message);
shake();
}
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
function handleGrantAuthorization() {
var csrf_token = $("#csrf_token").val();
var client_id = $("#client_id").val();
$.ajax("/oauth/authorize", {
"method": "POST",
"data": {
client_id,
csrf_token
},
"success": handleAuthSuccess,
"error": handleAuthFailure
});
}
|
module.exports = [
'M6 2 L26 2 L26 30',
'L16 24 L6 30 Z'
].join(' ');
|
// DATA_TEMPLATE: empty_table
oTest.fnStart("5396 - fnUpdate with 2D arrays for a single row");
$(document).ready(function () {
$('#example thead tr').append('<th>6</th>');
$('#example thead tr').append('<th>7</th>');
$('#example thead tr').append('<th>8</th>');
$('#example thead tr').append('<th>9</th>');
$('#example thead tr').append('<th>10</th>');
var aDataSet = [
[
"1",
"홍길동",
"1154315",
"etc1",
[
[ "test1@daum.net", "2011-03-04" ],
[ "test1@naver.com", "2009-07-06" ],
[ "test4@naver.com", ",hide" ],
[ "test5?@naver.com", "" ]
],
"2011-03-04",
"show"
],
[
"2",
"홍길순",
"2154315",
"etc2",
[
[ "test2@daum.net", "2009-09-26" ],
[ "test2@naver.com", "2009-05-21,hide" ],
[ "lsb@naver.com", "2010-03-05" ],
[ "lsb3@naver.com", ",hide" ],
[ "sooboklee9@daum.net", "2010-03-05" ]
],
"2010-03-05",
"show"
]
]
var oTable = $('#example').dataTable({
"aaData": aDataSet,
"aoColumns": [
{ "mData": "0"},
{ "mData": "1"},
{ "mData": "2"},
{ "mData": "3"},
{ "mData": "4.0.0"},
{ "mData": "4.0.1"},
{ "mData": "4.1.0"},
{ "mData": "4.1.1"},
{ "mData": "5"},
{ "mData": "6"}
]
});
oTest.fnTest(
"Initialisation",
null,
function () {
return $('#example tbody tr:eq(0) td:eq(0)').html() == '1';
}
);
oTest.fnTest(
"Update row",
function () {
$('#example').dataTable().fnUpdate([
"0",
"홍길순",
"2154315",
"etc2",
[
[ "test2@daum.net", "2009-09-26" ],
[ "test2@naver.com", "2009-05-21,hide" ],
[ "lsb@naver.com", "2010-03-05" ],
[ "lsb3@naver.com", ",hide" ],
[ "sooboklee9@daum.net", "2010-03-05" ]
],
"2010-03-05",
"show"
], 1);
},
function () {
return $('#example tbody tr:eq(0) td:eq(0)').html() == '0';
}
);
oTest.fnTest(
"Original row preserved",
null,
function () {
return $('#example tbody tr:eq(1) td:eq(0)').html() == '1';
}
);
oTest.fnComplete();
});
|
/*
* jQuery Touch Optimized Sliders "R"Us
* HTML media
*
* Copyright (c) Fred Heusschen
* www.frebsite.nl
*/
!function(i){var n="tosrus",e="html";i[n].media[e]={filterAnchors:function(n){return"#"==n.slice(0,1)&&i(n).is("div")},initAnchors:function(e,t){i('<div class="'+i[n]._c("html")+'" />').append(i(t)).appendTo(e),e.removeClass(i[n]._c.loading).trigger(i[n]._e.loaded)},filterSlides:function(i){return i.is("div")},initSlides:function(){}}}(jQuery);
|
/**
* Knook-mailer
* https://github.com/knook/knook.git
* Auhtors: Alexandre Lagrange-Cetto, Olivier Graziano, Olivier Marin
* Created on 15/04/2016.
* version 0.1.0
*/
'use strict';
module.exports = {
Accounts: require('./src/Accounts'),
Email: require('./src/Email'),
Init: require('./src/Init'),
Prefs: require('./src/Prefs'),
Security: require('./src/Security')
};
|
/*global window*/
(function($){
'use strict';
var Observable = function(){
this.observers = {};
};
Observable.prototype.on = function(event, observer){
(this.observers[event] = this.observers[event] || []).push(observer);
};
Observable.prototype.emit = function(event){
var args = Array.prototype.slice.call(arguments, 1);
(this.observers[event] || []).forEach(function(observer){
observer.apply(this, args);
}.bind(this));
};
var Model = $.Model = function(alpha){
Observable.call(this);
this._alpha = alpha || 30;
};
Model.prototype = Object.create(Observable.prototype);
Model.prototype.constructor = Model;
Model.prototype.alpha = function(alpha){
this._alpha = alpha || this._alpha;
if (alpha !== undefined) {
this.emit('alpha', this._alpha);
}
return this._alpha;
};
var Step = function(){};
Step.prototype.description = function(){
return this.type + this.x + ',' + this.y;
};
var MoveTo = function(x, y){
Step.call(this);
this.type = 'M';
this.x = x;
this.y = y;
};
MoveTo.prototype = Object.create(Step.prototype);
MoveTo.prototype.constructor = MoveTo;
var LineTo = function(x, y){
Step.call(this);
this.type = 'L';
this.x = x;
this.y = y;
};
LineTo.prototype = Object.create(Step.prototype);
LineTo.prototype.constructor = LineTo;
var HalfCircleTo = function(x, y, r, direction) {
Step.call(this);
this.type = 'A';
this.x = x;
this.y = y;
this.r = r;
this.direction = direction;
};
HalfCircleTo.prototype = Object.create(Step.prototype);
HalfCircleTo.prototype.constructor = HalfCircleTo;
HalfCircleTo.prototype.description = function(){
return [
this.type,
this.r + ',' + this.r,
0,
'0,' + (this.direction === -1 ? 1: 0),
this.x + ',' + this.y
].join(' ');
};
var ControlPoints = $.ControlPoints = function(model, direction, x, y){
Observable.call(this);
this.model = model;
this.direction = direction;
this.x = x;
this.y = y;
this.model.on('alpha', this.signal.bind(this));
};
ControlPoints.prototype = Object.create(Observable.prototype);
ControlPoints.prototype.constructor = ControlPoints;
ControlPoints.prototype.signal = function(){
this.emit('controlpoints', this.controlPoints());
};
ControlPoints.prototype.controlPoints = function(){
var alpha = this.model.alpha() * Math.PI / 180;
var sinAlpha = Math.sin(alpha);
var coefficient = 1/2 * sinAlpha * (1 - sinAlpha);
var ab = this.y/(1 + coefficient);
var w = ab * 1/2 * Math.sin(2 * alpha);
var h = ab * 1/2 * Math.cos(2 * alpha);
var r = ab * 1/2 * sinAlpha;
var points = [
new MoveTo(this.x, this.y),
new LineTo(this.x + this.direction * w, this.y - ab/2 - h),
new HalfCircleTo(this.x, this.y - ab, r, this.direction),
];
var n=10;
var ds = ab/n;
var dw = ds * 1/2 * Math.tan(alpha);
for (var index = 0; index < n; index++) {
points.push(new LineTo(this.x + dw, this.y - ab + (index + 1/2) * ds));
points.push(new LineTo(this.x, this.y - ab + (index + 1) * ds));
}
return points;
};
var View = $.View = function(model, path){
this.model = model;
this.path = path;
this.update();
};
View.prototype.update = function(){
this.path.setAttribute('d', this.description());
};
View.prototype.description = function(){
return this.model.controlPoints().map(function(point){
return point.description();
}).join('');
};
})(window.heart = window.heart || {});
|
import root from './_root.js';
import toString from './toString.js';
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeParseInt = root.parseInt;
/**
* Converts `string` to an integer of the specified radix. If `radix` is
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a
* hexadecimal, in which case a `radix` of `16` is used.
*
* **Note:** This method aligns with the
* [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
*
* @static
* @memberOf _
* @since 1.1.0
* @category String
* @param {string} string The string to convert.
* @param {number} [radix=10] The radix to interpret `value` by.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {number} Returns the converted integer.
* @example
*
* _.parseInt('08');
* // => 8
*
* _.map(['6', '08', '10'], _.parseInt);
* // => [6, 8, 10]
*/
function parseInt(string, radix, guard) {
if (guard || radix == null) {
radix = 0;
} else if (radix) {
radix = +radix;
}
return nativeParseInt(toString(string), radix || 0);
}
export default parseInt;
|
import $ from 'jquery';
module.exports = function(root) {
root = root ? root : global;
root.expect = root.chai.expect;
root.$ = $;
beforeEach(() => {
// Using these globally-available Sinon features is preferrable, as they're
// automatically restored for you in the subsequent `afterEach`
root.sandbox = root.sinon.sandbox.create();
root.stub = root.sandbox.stub.bind(root.sandbox);
root.spy = root.sandbox.spy.bind(root.sandbox);
root.mock = root.sandbox.mock.bind(root.sandbox);
root.useFakeTimers = root.sandbox.useFakeTimers.bind(root.sandbox);
root.useFakeXMLHttpRequest = root.sandbox.useFakeXMLHttpRequest.bind(root.sandbox);
root.useFakeServer = root.sandbox.useFakeServer.bind(root.sandbox);
});
afterEach(() => {
delete root.stub;
delete root.spy;
root.sandbox.restore();
});
};
|
const mongoose = require('mongoose');
const UserModel = mongoose.model('User');
module.exports = {
login: (email, password) => {
return UserModel.findOne({email, password});
}
};
|
module.exports = {
login: function(user, req)
{
// Parse detailed information from user-agent string
var r = require('ua-parser').parse(req.headers['user-agent']);
// Create new UserLogin row to database
sails.models.loglogin.create({
ip: req.ip,
host: req.host,
agent: req.headers['user-agent'],
browser: r.ua.toString(),
browserVersion: r.ua.toVersionString(),
browserFamily: r.ua.family,
os: r.os.toString(),
osVersion: r.os.toVersionString(),
osFamily: r.os.family,
device: r.device.family,
user: user.id
})
.exec(function(err, created) {
if(err) sails.log(err);
created.user = user;
sails.models.loglogin.publishCreate(created);
});
},
request: function(log, req, resp)
{
//var userId = -1;
// if (req.token) {
// userId = req.token;
// } else {
// userId = -1;
// }
sails.models.logrequest.create({
ip: log.ip,
protocol: log.protocol,
method: log.method,
url: log.diagnostic.url,
headers: req.headers || {},
parameters: log.diagnostic.routeParams,
body: log.diagnostic.bodyParams,
query: log.diagnostic.queryParams,
responseTime: log.responseTime || 0,
middlewareLatency: log.diagnostic.middlewareLatency || 0,
user: req.token || 0
})
.exec(function(err, created) {
if(err) sails.log(err);
sails.models.logrequest.publishCreate(created);
});
}
};
|
const isObjectId = objectId => objectId && /^[0-9a-fA-F]{24}$/.test(objectId)
const isEmail = email => email && /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(email.trim())
const isNick = nick => nick && /^[\u4E00-\u9FA5\uF900-\uFA2DA-Za-z0-9\-\_]{2,40}$/.test(nick.trim())
const isUrl = url => url && /^(http(?:|s)\:)*\/\/([^\/]+)/.test(url.trim())
export {
isObjectId,
isEmail,
isNick,
isUrl
}
|
var Command = require("../Command");
var RealDirection = require("../../RealDirection");
var MessageCategory = require("../../MessageCategory");
var _dir = RealDirection.NORTHEAST;
class Northeast extends Command{
constructor(){
super();
this.rule = /^n(?:orth)?e(?:ast)?$/g;
}
exec(){
if(this.step(_dir)){
this.showRoom();
} else {
this.sendMessage("Alas, you can't go that way.", MessageCategory.COMMAND);
}
}
}
module.exports = Northeast;
|
module.exports = (name, node) => (
name === "apply" &&
node.type === "CallExpression" &&
node.callee.type === "Identifier");
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 The Regents of the University of California
* Author: Jim Robinson
*
* 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.
*/
import {loadIndex} from "./indexFactory.js"
import AlignmentContainer from "./alignmentContainer.js"
import BamUtils from "./bamUtils.js"
import {BGZip, igvxhr} from "../../node_modules/igv-utils/src/index.js"
import {buildOptions} from "../util/igvUtils.js"
/**
* Class for reading a bam file
*
* @param config
* @constructor
*/
class BamReader {
constructor(config, genome) {
this.config = config
this.genome = genome
this.bamPath = config.url
this.baiPath = config.indexURL
BamUtils.setReaderDefaults(this, config)
}
async readAlignments(chr, bpStart, bpEnd) {
const chrToIndex = await this.getChrIndex()
const queryChr = this.chrAliasTable.hasOwnProperty(chr) ? this.chrAliasTable[chr] : chr
const chrId = chrToIndex[queryChr]
const alignmentContainer = new AlignmentContainer(chr, bpStart, bpEnd, this.config)
if (chrId === undefined) {
return alignmentContainer
} else {
const bamIndex = await this.getIndex()
const chunks = bamIndex.blocksForRange(chrId, bpStart, bpEnd)
if (!chunks || chunks.length === 0) {
return alignmentContainer
}
let counter = 1
for (let c of chunks) {
let lastBlockSize
if (c.maxv.offset === 0) {
lastBlockSize = 0 // Don't need to read the last block.
} else {
const bsizeOptions = buildOptions(this.config, {range: {start: c.maxv.block, size: 26}})
const abuffer = await igvxhr.loadArrayBuffer(this.bamPath, bsizeOptions)
lastBlockSize = BGZip.bgzBlockSize(abuffer)
}
const fetchMin = c.minv.block
const fetchMax = c.maxv.block + lastBlockSize
const range = {start: fetchMin, size: fetchMax - fetchMin + 1}
const compressed = await igvxhr.loadArrayBuffer(this.bamPath, buildOptions(this.config, {range: range}))
var ba = BGZip.unbgzf(compressed) //new Uint8Array(BGZip.unbgzf(compressed)); //, c.maxv.block - c.minv.block + 1));
const done = BamUtils.decodeBamRecords(ba, c.minv.offset, alignmentContainer, this.indexToChr, chrId, bpStart, bpEnd, this.filter)
if (done) {
// console.log(`Loaded ${counter} chunks out of ${chunks.length}`);
break
}
counter++
}
alignmentContainer.finish()
return alignmentContainer
}
}
async getHeader() {
if (!this.header) {
const genome = this.genome
const index = await this.getIndex()
let start
let len
if (index.firstBlockPosition) {
const bsizeOptions = buildOptions(this.config, {range: {start: index.firstBlockPosition, size: 26}})
const abuffer = await igvxhr.loadArrayBuffer(this.bamPath, bsizeOptions)
const bsize = BGZip.bgzBlockSize(abuffer)
len = index.firstBlockPosition + bsize // Insure we get the complete compressed block containing the header
} else {
len = 64000
}
const options = buildOptions(this.config, {range: {start: 0, size: len}})
this.header = await BamUtils.readHeader(this.bamPath, options, genome)
}
return this.header
}
async getIndex() {
const genome = this.genome
if (!this.index) {
this.index = await loadIndex(this.baiPath, this.config, genome)
}
return this.index
}
async getChrIndex() {
if (this.chrToIndex) {
return this.chrToIndex
} else {
const header = await this.getHeader()
this.chrToIndex = header.chrToIndex
this.indexToChr = header.chrNames
this.chrAliasTable = header.chrAliasTable
return this.chrToIndex
}
}
}
export default BamReader
|
var mongoose = require('mongoose');
var Shape = require('./Shape');
var User = require('./User');
// Create a session model, _id will be assigned by Mongoose
var CanvasSessionSchema = new mongoose.Schema(
{
_id: String,
users: [User],
dateCreated: Date,
dateUpdated: Date,
// canDraw: Boolean,
// canChat: Boolean,
// maxUsers: Number,
sessionProperties: {
canDraw: Boolean,
canChat: Boolean,
maxUsers: Number
},
//canvasModel: { type: Object },
canvasShapes: { type: Array, unique: true, index: true },
messages: Array
},
{ autoIndex: false }
);
// Make Session available to rest of the application
module.exports = mongoose.model('Session', CanvasSessionSchema);
|
import config from '../components/configLoader';
import { addToDefaultPluginDOM } from '../components/helpers';
const pluginConfig = config.plugins.find(obj => obj.name === 'age');
// DOM setup
const pluginId = 'js-plugin-age';
addToDefaultPluginDOM(pluginId);
const ageDOM = document.getElementById(pluginId);
const renderAge = () => {
const { birthday, goal } = pluginConfig;
// Inspired by:
// Alex MacCaw https://github.com/maccman/motivation
const now = new Date();
const age = (now - new Date(birthday)) / 3.1556952e+10; // divided by 1 year in ms
let remainder = 100 - (age / goal * 100);
let goalPrefix = 'left until';
if (remainder < 0) {
goalPrefix = 'over goal of';
remainder = -remainder;
}
ageDOM.innerHTML = `Age: ${age.toFixed(5)}, ${remainder.toFixed(2)}% ${goalPrefix} ${goal}`;
};
// Initialize plugin
export const init = () => renderAge(); // eslint-disable-line import/prefer-default-export
|
Meteor.startup(function () {
});
Deps.autorun(function(){
Meteor.subscribe('userData');
});
|
// will this be needed?
var getMotionEventName = function(type) {
var t;
var el = document.createElement('fakeelement');
var map = {};
if (type == 'transition') {
map = {
'transition': 'transitionend',
'OTransition': 'oTransitionEnd',
'MozTransition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd'
};
} else if (type == 'animation') {
map = {
'animation': 'animationend',
'OAnimation': 'oAnimationEnd',
'MozAnimation': 'animationend',
'WebkitAnimation': 'webkitAnimationEnd'
};
};
for (t in map) {
if (el.style[t] !== undefined) {
return map[t];
}
}
};
|
// Include gulp
import gulp from 'gulp';
import fs from 'fs';
// Include Our Plugins
import eslint from 'gulp-eslint';
import mocha from 'gulp-mocha';
import browserSyncJs from 'browser-sync';
import sassJs from 'gulp-sass';
import sassCompiler from 'sass';
import rename from "gulp-rename";
import uglify from 'gulp-uglify';
import postcss from 'gulp-postcss';
import replace from 'gulp-replace';
import autoprefixer from 'autoprefixer';
import gulpStylelint from '@ronilaukkarinen/gulp-stylelint';
const browserSync = browserSyncJs.create();
const pkg = JSON.parse(fs.readFileSync('./package.json'));
const sass = sassJs(sassCompiler);
const doEslint = function() {
return gulp.src(
[
'*.js',
pkg.directories.bin + '/**/*',
pkg.directories.lib + '/**/*.js',
pkg.directories.test + '/**/*.js'
])
.pipe(eslint())
.pipe(eslint.format())
// .pipe(eslint.failAfterError())
;
};
const doMocha = function() {
return gulp.src(pkg.directories.test + '/**/*.js', {read: false})
.pipe(mocha({
reporter: 'dot'
}))
;
};
const buildJs = function() {
return gulp.src(pkg.directories.theme + '/**/js-src/*.js')
.pipe(eslint())
.pipe(eslint.format())
//.pipe(eslint.failAfterError())
.pipe(rename(function(path){
path.dirname = path.dirname.replace(/js-src/, 'js');
}))
.pipe(uglify({output: {
max_line_len: 9000
}}))
.pipe(gulp.dest(pkg.directories.theme))
;
};
const buildCss = function() {
return gulp.src(pkg.directories.theme + '/**/*.scss')
.pipe(gulpStylelint({
reporters: [
{formatter: 'string', console: true}
]
}))
.pipe(sass().on('error', sass.logError))
.pipe(postcss([
autoprefixer()
]))
.pipe(rename(function(path){
path.dirname = path.dirname.replace(/sass/, 'css');
}))
.pipe(replace(/(\n)\s*\n/g, '$1'))
.pipe(gulp.dest(pkg.directories.theme))
;
};
const serve = function() {
browserSync.init({
server: pkg.directories.htdocs,
port: 8080
});
gulp.watch(pkg.directories.htdocs + '/**/*').on('change', browserSync.reload);
};
// Watch Files For Changes
const watch = function() {
gulp.watch(['gulpfile.js', 'package.json'], process.exit);
gulp.watch(
[
'*.js', pkg.directories.bin + '/**/*',
pkg.directories.lib + '/**/*.js',
pkg.directories.test + '/**/*.js'
],
test
);
gulp.watch(pkg.directories.theme + '/**/*.js', buildJs);
gulp.watch(pkg.directories.theme + '/**/*.scss', buildCss);
};
// Bundle tasks
const test = gulp.parallel(doEslint, doMocha);
const build = gulp.parallel(buildJs, buildCss);
const defaultTask = gulp.parallel(serve, watch);
// Expose tasks
export {doEslint, doMocha, buildJs, buildCss, serve, watch, test, build};
export default defaultTask;
|
//
// Jala Project [http://opensvn.csie.org/traccgi/jala]
//
// Copyright 2004 ORF Online und Teletext GmbH
//
// Licensed under the Apache License, Version 2.0 (the ``License'');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an ``AS IS'' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// $Revision: 213 $
// $LastChangedBy: tobi $
// $LastChangedDate: 2007-05-08 16:12:32 +0200 (Die, 08 Mai 2007) $
// $HeadURL: http://dev.orf.at/source/jala/trunk/code/AsyncRequest.js $
//
/**
* @fileoverview Fields and methods of the jala.AsyncRequest class.
*/
// Define the global namespace for Jala modules
if (!global.jala) {
global.jala = {};
}
/**
* Creates a new AsyncRequest instance.
* @class This class is used to create requests of type "INTERNAL"
* (like cron-jobs) that are processed in a separate thread and
* therefor asynchronous.
* @param {Object} obj Object in whose context the method should be called
* @param {String} funcName Name of the function to call
* @param {Array} args Array containing the arguments that should be passed
* to the function (optional). This option is <em>deprecated</em>, instead
* pass the arguments directly to the {@link #run} method.
* @constructor
* @returns A new instance of AsyncRequest
* @type AsyncRequest
* @deprecated Use the {@link http://helma.zumbrunn.net/reference/core/app.html#invokeAsync
* app.invokeAsync} method instead (built-in into Helma as
* of version 1.6)
*/
jala.AsyncRequest = function(obj, funcName, args) {
app.logger.warn("Use of jala.AsyncRequest is deprecated in this version.");
app.logger.warn("This module will probably be removed in a " +
"future version of Jala.");
/**
* Contains a reference to the thread started by this AsyncRequest
* @type java.lang.Thread
* @private
*/
var thread;
/**
* Contains the timeout defined for this AsyncRequest (in milliseconds)
* @type Number
* @private
*/
var timeout;
/**
* Contains the number of milliseconds to wait before starting
* the asynchronous request.
* @type Number
* @private
*/
var delay;
/**
* Run method necessary to implement java.lang.Runnable.
* @private
*/
var runner = function() {
// evaluator that will handle the request
var ev = app.__app__.getEvaluator();
if (delay != null) {
java.lang.Thread.sleep(delay);
}
try {
if (args === undefined || args === null || args.constructor != Array) {
args = [];
}
if (timeout != null) {
ev.invokeInternal(obj, funcName, args, timeout);
} else {
ev.invokeInternal(obj, funcName, args);
}
} catch (e) {
// ignore it, but log it
app.log("[Runner] Caught Exception: " + e);
} finally {
// release the ev in any case
app.__app__.releaseEvaluator(ev);
// remove reference to underlying thread
thread = null;
}
return;
};
/**
* Sets the timeout of this asynchronous request.
* @param {Number} seconds Thread-timeout.
*/
this.setTimeout = function(seconds) {
timeout = seconds * 1000;
return;
};
/**
* Defines the delay to wait before evaluating this asynchronous request.
* @param {Number} millis Milliseconds to wait
*/
this.setDelay = function(millis) {
delay = millis;
return;
};
/**
* Starts this asynchronous request. Any arguments passed to
* this method will be passed to the method executed by
* this AsyncRequest instance.
*/
this.run = function() {
if (arguments.length > 0) {
// convert arguments object into array
args = Array.prototype.slice.call(arguments, 0, arguments.length);
}
thread = (new java.lang.Thread(new java.lang.Runnable({"run": runner})));
thread.start();
return;
};
/**
* Starts this asynchronous request.
* @deprecated Use {@link #run} instead
*/
this.evaluate = function() {
this.run.apply(this, arguments);
return;
};
/**
* Returns true if the underlying thread is alive
* @returns True if the underlying thread is alive,
* false otherwise.
* @type Boolean
*/
this.isAlive = function() {
return thread != null && thread.isAlive();
}
/** @ignore */
this.toString = function() {
return "[jala.AsyncRequest]";
};
/**
* Main constructor body
*/
if (!obj || !funcName)
throw "jala.AsyncRequest: insufficient arguments.";
return this;
}
|
const OFF = 0;
const WARN = 1;
const ERROR = 2;
module.exports = {
extends: "../.eslintrc.js",
rules: {
"max-len": [ ERROR, 100 ],
},
env: {
"es6": true,
"node": true,
"mocha": true,
},
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.