code stringlengths 2 1.05M |
|---|
/**
* 同步遍历指定路径目录
* @param {String} dir 目录地址
* @param {Function} callback 回调
*/
function traverseSync(dir, callback) {
const fs = require('fs');
const path = require('path');
fs.readdirSync(dir).forEach((file) => {
const pathname = path.join(dir, file);
if (fs.statSync(pathname).isDirectory()) {
traverse(pathname, callback);
} else {
callback && callback(pathname);
}
});
}
/**
* 异步遍历指定路径目录
* @param {Stirng} dir 目录地址
* @param {Function} callback 回调
* @param {Function} finish 遍历结束回调
* @param {Boolean} isDeepTraverse 是否遍历子文件夹
*/
function traverse(dir, callback, finish, isDeepTraverse = true) {
const fs = require('fs');
const path = require('path');
fs.readdir(dir, (err, files) => {
if (err) {
throw err;
}
(function next(i) {
if (i < files.length) {
const pathname = path.join(dir, files[i]);
fs.stat(pathname, function (err, stats) {
if (stats.isDirectory() && isDeepTraverse) {
traverse(pathname, callback, function () {
next(i + 1);
});
} else {
callback && callback(pathname);
next(i + 1);
}
});
} else {
finish && finish();
}
})(0);
});
}
/**
* 发送邮件(需收件方开启smtp)
* @param {Object} options receiver-收件人 title-标题 text-文本格式内容 html-html格式内容
*/
function sendEmail(options) {
const mail = require('nodemailer');
const smtpTransport = mail.createTransport({
host: 'smtp.qq.com',
secureConnection: true,
port: 587, //腾讯端口为465或587
auth: {
user: 'tenfyma@foxmail.com',
pass: 'otiiohqmkqnfbeii',
},
});
//设置邮箱内容
const mailOptions = {
from: options.from || '马腾飞 <tenfyma@foxmail.com>',
to: options.to, //收件人,多个收件人用逗号隔开
subject: options.title, //标题
text: options.text, //文本格式内容
html: options.html, //html格式内容
/*attachments: [{ //上传附件
filename: 'json',
path: './add.html'
}]*/
};
smtpTransport.sendMail(mailOptions, (error, response) => {
let status = '';
if (error) {
console.log(error);
status = error;
} else {
console.log('success' + response.response);
status = '200';
}
smtpTransport.close();
return status;
});
}
/**
* 获取变量类型
* @param {*} variable 变量
* @return {String} 变量类型
*/
function typeOf(variable) {
return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
}
/**
* 将字符串进行正则转义,使之可以构造正则对象
* @param {String} string 待转义字符串
* @return {String} 转义后字符串
*/
function escapeRegExp(string) {
// $&表示整个被匹配的字符串
return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$&');
}
/**
* 加法(纯函数)
* @param {number} args 数字
* @return {Object} 如果含参数,返回该方法,否则返回计算结果
*/
function add(...args) {
const fn = function (...arg_fn) {
if (arg_fn.length === 0) {
return args.reduce((a, b) => a + b);
}
return add.apply(null, args.concat(arg_fn));
};
fn.valueOf = function () {
return args.reduce((a, b) => a + b);
};
fn.toString = function () {
return args.reduce((a, b) => a + b);
};
return fn;
}
/**
* 产生随机整数
* @param {String|Number} min 最小值
* @param {String|Number} max 最大值
* @return {Number} 随机数
*/
function randomBetween(min, max, type = 2) {
if (!/^\d{1,}$/.test(min) || !/^\d{1,}$/.test(max)) {
throw new Error('无效的数字');
}
//如果数值输反了自行纠正
if (min === max) {
return min;
} else if (min > max) {
[min, max] = [max, min];
}
const diff = max - min;
if (type === 0) {
//不包含边界值
return Math.round(Math.random() * (diff - 2) + min + 1);
} else if (type === -1) {
//包含左边界值
return Math.floor(Math.random() * diff + min, 10);
} else if (type === 1) {
//包含右边界值
return Math.round(Math.random() * (diff - 1) + min) + 1;
} else {
//包含边界值,默认类型
return Math.round(Math.random() * diff + min);
}
}
/**
* 16进制颜色值转为RGB格式色值
* @param {String} color 16进制色值
* @return {String} RGB格式色值
*/
function toRGB(color) {
const reg = /#([0-9a-f]{3}){1,2}/gi;
if (!reg.test(color)) return '';
color = color.replace('#', '');
if (color.length === 3) {
color = color
.split('')
.map((item) => item + item)
.join('');
}
return `rgb(${color
.split(/(.{2})/gi)
.filter((item) => item)
.map((item) => parseInt(item, 16))
.join(',')})`;
}
/**
* 浏览器下载
* @param {String|DOMObject} content 要下载的内容,如果为图片则是一个dom对象
* @param {String} filename 下载文件的标题
* @param {String} ext 文件扩展名
*/
function download(content, filename, ext) {
const a = document.createElement('a');
a.download = filename;
a.style.display = 'none';
if (ext === 'jpg' || ext === 'png') {
ext === 'jpg' && (ext = ext.replace('jpg', 'jpeg'));
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// const width = content.naturalWidth;
// const height = content.naturalHeight;
ctx.drawImage(content, 0, 0);
a.href = canvas.toDataURL(`image/${ext}`);
} else {
const blob = new Blob([content]);
a.href = URL.createObjectURL(blob);
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
exports = module.exports = {
traverse,
traverseSync,
sendEmail,
typeOf,
escapeRegExp,
add,
randomBetween,
download,
toRGB,
};
|
// # Ghost Configuration
// Setup your Ghost install for various environments
// Documentation can be found at http://support.ghost.org/config/
var path = require('path'),
config;
config = {
// ### Development **(default)**
development: {
// The url to use when providing links to the site, E.g. in RSS and email.
url: 'http://www.bigertech.com',
// Example mail config
// Visit http://support.ghost.org/mail for instructions
mail: {
transport: 'SMTP',
options: {
auth: {
user: 'bigertech@gmail.com', // mailgun username
pass: 'xxx' // mailgun password
}
}
},
database: {
client: 'mysql',
connection: {
host : '192.168.20.21',
user : 'meizu_bigertech',
password : 'nkLWmeUSPwlbLtNU',
database : 'bigertech_blog',
charset : 'UTF8_GENERAL_CI'
},
//debug: true
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '121.14.58.212',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '8001'
},
paths: {
contentPath: path.join(__dirname, '/content/')
},
cdn: {
isProduction: true,
staticAssetsUrl: 'http://bigertech.res.meizu.com/blog/static/',
dynamicAssetsUrl: 'http://bigertech.res.meizu.com/blog/res/content/images/',
syncImagesPath: '/data/static/images/'
},
images: {
// 如果下面几项留空,则说明上传的图片无需截图
dir: 'image_sm',
targetWidth: 350,
targetHeight: 210,
scale: 0.6
},
changweibo: {
url: 'http://www.bigertech.com',
dir: 'changweibo'
}
},
// ### Production
// When running Ghost in the wild, use the production environment
// Configure your URL and mail settings here
production: {
url: 'http://my-ghost-blog.com',
mail: {},
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost.db')
},
debug: false
},
server: {
// Host to be passed to node's `net.Server#listen()`
host: '127.0.0.1',
// Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
port: '2368'
}
},
// **Developers only need to edit below here**
// ### Testing
// Used when developing Ghost to run tests and check the health of Ghost
// Uses a different port number
testing: {
url: 'http://127.0.0.1:2369',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '/content/data/ghost-test.db')
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing MySQL
// Used by Travis - Automated testing run through GitHub
'testing-mysql': {
url: 'http://127.0.0.1:2369',
database: {
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'root',
password : '',
database : 'bigertech_blog',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
},
// ### Testing pg
// Used by Travis - Automated testing run through GitHub
'testing-pg': {
url: 'http://127.0.0.1:2369',
database: {
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'postgres',
password : '',
database : 'ghost_testing',
charset : 'utf8'
}
},
server: {
host: '127.0.0.1',
port: '2369'
},
logging: false
}
};
// Export config
module.exports = config;
|
Package.describe({
summary: "JavaScript and CSS minifiers",
version: "1.1.4"
});
Npm.depends({
"uglify-js": "2.4.17",
"css-parse": "https://github.com/reworkcss/css-parse/tarball/aa7e23285375ca621dd20250bac0266c6d8683a5",
"css-stringify": "https://github.com/reworkcss/css-stringify/tarball/a7fe6de82e055d41d1c5923ec2ccef06f2a45efa"
});
Npm.strip({
"uglify-js": ["test/"],
"css-parse": ["test/"],
"css-stringify": ["test/"]
});
Package.onUse(function (api) {
api.use('underscore', 'server');
api.export(['CssTools', 'UglifyJSMinify', 'UglifyJS']);
api.addFiles(['minification.js', 'minifiers.js'], 'server');
});
Package.onTest(function (api) {
api.use('minifiers', 'server');
api.use('tinytest');
api.addFiles([
'beautify-tests.js',
'minifiers-tests.js',
'urlrewriting-tests.js'
], 'server');
});
|
// ==============================================================================
// lib/reporters/Coverage.js module
// ==============================================================================
const events = require('events')
const path = require('path')
const istanbulLibCoverage = require('istanbul-lib-coverage')
const istanbulLibReport = require('istanbul-lib-report')
const globalSourceMapStore = require('../lib/source-map-store')
const globalCoverageMap = require('../lib/coverage-map')
const reports = require('../lib/report-creator')
describe('reporter', () => {
// TODO(vojta): remove the dependency on karma
const helper = require('../node_modules/karma/lib/helper')
const Browser = require('../node_modules/karma/lib/browser')
const Collection = require('../node_modules/karma/lib/browser_collection')
require('karma/lib/logger').setup('INFO', false, [])
const resolve = (...args) => helper.normalizeWinPath(path.resolve(...args))
const nodeMocks = require('mocks')
const loadFile = nodeMocks.loadFile
let m = null
const mkdirIfNotExistsStub = sinon.stub()
const mockHelper = {
isDefined: (v) => helper.isDefined(v),
merge: (...arg) => helper.merge(...arg),
mkdirIfNotExists: (dir, done) => {
mkdirIfNotExistsStub(dir, done)
setTimeout(done, 0)
},
normalizeWinPath: (path) => helper.normalizeWinPath(path)
}
// Mock Objects
let mockCoverageSummary = null
let mockFileCoverage = null
let mockCoverageMap = null
let mockDefaultWatermarks = null
let mockPackageSummary = null
let mockSourceMapStore = null
let mockGlobalCoverageMap = null
// Stubs
let createCoverageSummaryStub = null
let createCoverageMapStub = null
let createContextStub = null
let getDefaultWatermarkStub = null
let sourceMapStoreGetStub = null
let globalCoverageMapGetStub = null
let reportCreateStub = null
const mockFs = { writeFile: sinon.spy() }
const mocks = { fs: mockFs }
beforeEach(() => {
mockCoverageSummary = {
merge: sinon.stub(),
toJSON: sinon.stub()
}
mockFileCoverage = {
merge: sinon.stub(),
toJSON: sinon.stub(),
toSummary: sinon.stub()
}
mockFileCoverage.toSummary.returns(mockCoverageSummary)
mockCoverageMap = {
fileCoverageFor: sinon.stub(),
files: sinon.stub(),
merge: sinon.stub(),
toJSON: sinon.stub()
}
mockCoverageMap.fileCoverageFor.returns(mockFileCoverage)
createCoverageSummaryStub = sinon.stub(istanbulLibCoverage, 'createCoverageSummary')
createCoverageSummaryStub.returns(mockCoverageSummary)
createCoverageMapStub = sinon.stub(istanbulLibCoverage, 'createCoverageMap')
createCoverageMapStub.returns(mockCoverageMap)
mockDefaultWatermarks = {
statements: [50, 80],
branches: [50, 80],
functions: [50, 80],
lines: [50, 80]
}
createContextStub = sinon.stub(istanbulLibReport, 'createContext')
getDefaultWatermarkStub = sinon.stub(istanbulLibReport, 'getDefaultWatermarks')
getDefaultWatermarkStub.returns(mockDefaultWatermarks)
mockSourceMapStore = {
transformCoverage: sinon.stub()
}
mockSourceMapStore.transformCoverage.resolves(mockCoverageMap)
sourceMapStoreGetStub = sinon.stub(globalSourceMapStore, 'get')
sourceMapStoreGetStub.returns(mockSourceMapStore)
mockGlobalCoverageMap = {}
globalCoverageMapGetStub = sinon.stub(globalCoverageMap, 'get')
globalCoverageMapGetStub.returns(mockGlobalCoverageMap)
sinon.stub(globalCoverageMap, 'add')
mockPackageSummary = { execute: sinon.stub() }
reportCreateStub = sinon.stub(reports, 'create')
reportCreateStub.returns(mockPackageSummary)
m = loadFile(path.join(__dirname, '/../lib/reporter.js'), mocks)
})
describe('CoverageReporter', () => {
let rootConfig = null
let emitter = null
let reporter = null
let browsers = null
let fakeChrome = null
let fakeOpera = null
const mockLogger = {
create: (name) => {
return {
debug () {},
info () {},
warn () {},
error () {}
}
}
}
beforeEach(() => {
rootConfig = {
basePath: '/base',
coverageReporter: { dir: 'path/to/coverage/' }
}
emitter = new events.EventEmitter()
reporter = new m.CoverageReporter(rootConfig, mockHelper, mockLogger, emitter)
browsers = new Collection(emitter)
// fake user agent only for testing
// cf. helper.browserFullNameToShort
fakeChrome = new Browser('aaa', 'Windows NT 6.1 Chrome/16.0.912.75', browsers, emitter)
fakeOpera = new Browser('bbb', 'Opera/9.80 Mac OS X Version/12.00', browsers, emitter)
browsers.add(fakeChrome)
browsers.add(fakeOpera)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
mkdirIfNotExistsStub.resetHistory()
})
it('has no pending file writings', async () => {
const done = sinon.spy()
await reporter.onExit(done)
expect(done).to.have.been.called
})
it('has no coverage', () => {
const result = {
coverage: null
}
reporter.onBrowserComplete(fakeChrome, result)
expect(mockCoverageMap.merge).not.to.have.been.called
})
it('should handle no result', () => {
reporter.onBrowserComplete(fakeChrome, undefined)
expect(mockCoverageMap.merge).not.to.have.been.called
})
it('should make reports', async () => {
await reporter.onRunComplete(browsers)
expect(mkdirIfNotExistsStub).to.have.been.calledTwice
const dir = rootConfig.coverageReporter.dir
expect(mkdirIfNotExistsStub.getCall(0).args[0]).to.deep.equal(resolve('/base', dir, fakeChrome.name))
expect(mkdirIfNotExistsStub.getCall(1).args[0]).to.deep.equal(resolve('/base', dir, fakeOpera.name))
expect(reportCreateStub).to.have.been.called
expect(mockPackageSummary.execute).to.have.been.called
const createArgs = reportCreateStub.getCall(0).args
expect(createArgs[0]).to.be.equal('html')
expect(createArgs[1].browser).to.be.equal(fakeChrome)
expect(createArgs[1].emitter).to.be.equal(emitter)
})
it('should support a string for the subdir option', async () => {
const customConfig = helper.merge({}, rootConfig, {
coverageReporter: {
subdir: 'test'
}
})
reporter = new m.CoverageReporter(customConfig, mockHelper, mockLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
await reporter.onRunComplete(browsers)
expect(mkdirIfNotExistsStub).to.have.been.calledTwice
const dir = customConfig.coverageReporter.dir
const subdir = customConfig.coverageReporter.subdir
expect(mkdirIfNotExistsStub.getCall(0).args[0]).to.deep.equal(resolve('/base', dir, subdir))
expect(mkdirIfNotExistsStub.getCall(1).args[0]).to.deep.equal(resolve('/base', dir, subdir))
expect(reportCreateStub).to.have.been.called
expect(mockPackageSummary.execute).to.have.been.called
})
it('should support a function for the subdir option', async () => {
const customConfig = helper.merge({}, rootConfig, {
coverageReporter: {
subdir: (browserName) => browserName.toLowerCase().split(/[ /-]/)[0]
}
})
reporter = new m.CoverageReporter(customConfig, mockHelper, mockLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
await reporter.onRunComplete(browsers)
expect(mkdirIfNotExistsStub).to.have.been.calledTwice
const dir = customConfig.coverageReporter.dir
expect(mkdirIfNotExistsStub.getCall(0).args[0]).to.deep.equal(resolve('/base', dir, 'chrome'))
expect(mkdirIfNotExistsStub.getCall(1).args[0]).to.deep.equal(resolve('/base', dir, 'opera'))
expect(reportCreateStub).to.have.been.called
expect(mockPackageSummary.execute).to.have.been.called
})
it('should support a specific dir and subdir per reporter', async () => {
const customConfig = helper.merge({}, rootConfig, {
coverageReporter: {
dir: 'useless',
subdir: 'useless',
reporters: [
{
dir: 'reporter1',
subdir: (browserName) => browserName.toLowerCase().split(/[ /-]/)[0]
},
{
dir: 'reporter2',
subdir: (browserName) => browserName.toUpperCase().split(/[ /-]/)[0]
}
]
}
})
reporter = new m.CoverageReporter(customConfig, mockHelper, mockLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
await reporter.onRunComplete(browsers)
expect(mkdirIfNotExistsStub.callCount).to.equal(4)
expect(mkdirIfNotExistsStub.getCall(0).args[0]).to.deep.equal(resolve('/base', 'reporter1', 'chrome'))
expect(mkdirIfNotExistsStub.getCall(1).args[0]).to.deep.equal(resolve('/base', 'reporter1', 'opera'))
expect(mkdirIfNotExistsStub.getCall(2).args[0]).to.deep.equal(resolve('/base', 'reporter2', 'CHROME'))
expect(mkdirIfNotExistsStub.getCall(3).args[0]).to.deep.equal(resolve('/base', 'reporter2', 'OPERA'))
expect(reportCreateStub).to.have.been.called
expect(mockPackageSummary.execute).to.have.been.called
})
it('should fallback to the default dir/subdir if not provided', async () => {
const customConfig = helper.merge({}, rootConfig, {
coverageReporter: {
dir: 'defaultdir',
subdir: 'defaultsubdir',
reporters: [
{
dir: 'reporter1'
},
{
subdir: (browserName) => browserName.toUpperCase().split(/[ /-]/)[0]
}
]
}
})
reporter = new m.CoverageReporter(customConfig, mockHelper, mockLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
await reporter.onRunComplete(browsers)
expect(mkdirIfNotExistsStub.callCount).to.equal(4)
expect(mkdirIfNotExistsStub.getCall(0).args[0]).to.deep.equal(resolve('/base', 'reporter1', 'defaultsubdir'))
expect(mkdirIfNotExistsStub.getCall(1).args[0]).to.deep.equal(resolve('/base', 'reporter1', 'defaultsubdir'))
expect(mkdirIfNotExistsStub.getCall(2).args[0]).to.deep.equal(resolve('/base', 'defaultdir', 'CHROME'))
expect(mkdirIfNotExistsStub.getCall(3).args[0]).to.deep.equal(resolve('/base', 'defaultdir', 'OPERA'))
expect(reportCreateStub).to.have.been.called
expect(mockPackageSummary.execute).to.have.been.called
})
it('should not create directory if reporting text* to console', async () => {
const run = () => {
reporter = new m.CoverageReporter(rootConfig, mockHelper, mockLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
return reporter.onRunComplete(browsers)
}
rootConfig.coverageReporter.reporters = [
{ type: 'text' },
{ type: 'text-summary' }
]
await run()
expect(mkdirIfNotExistsStub).not.to.have.been.called
})
it('should calls done callback when onComplete event will be complete', async () => {
reporter = new m.CoverageReporter(rootConfig, mockHelper, mockLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
reporter.onRunComplete(browsers)
const done = sinon.stub()
const promiseExit = reporter.onExit(done)
expect(done.notCalled).to.be.true
await promiseExit
expect(done.calledOnce).to.be.true
})
it('should create directory if reporting text* to file', async () => {
const run = () => {
reporter = new m.CoverageReporter(rootConfig, mockHelper, mockLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
return reporter.onRunComplete(browsers)
}
rootConfig.coverageReporter.reporters = [{ type: 'text', file: 'file' }]
await run()
expect(mkdirIfNotExistsStub).to.have.been.calledTwice
mkdirIfNotExistsStub.resetHistory()
rootConfig.coverageReporter.reporters = [{ type: 'text-summary', file: 'file' }]
await run()
expect(mkdirIfNotExistsStub).to.have.been.calledTwice
})
it('should support including all sources', () => {
const customConfig = helper.merge({}, rootConfig, {
coverageReporter: {
dir: 'defaultdir',
includeAllSources: true
}
})
globalCoverageMapGetStub.resetHistory()
createCoverageMapStub.resetHistory()
reporter = new m.CoverageReporter(customConfig, mockHelper, mockLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
expect(globalCoverageMapGetStub).to.have.been.called
expect(createCoverageMapStub).to.have.been.calledWith(globalCoverageMapGetStub.returnValues[0])
})
it('should not retrieve the coverageMap if we aren\'t including all sources', () => {
const customConfig = helper.merge({}, rootConfig, {
coverageReporter: {
dir: 'defaultdir',
includeAllSources: false
}
})
globalCoverageMapGetStub.resetHistory()
reporter = new m.CoverageReporter(customConfig, mockHelper, mockLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
expect(globalCoverageMapGetStub).not.to.have.been.called
})
it('should default to not including all sources', () => {
const customConfig = helper.merge({}, rootConfig, {
coverageReporter: {
dir: 'defaultdir'
}
})
globalCoverageMapGetStub.resetHistory()
reporter = new m.CoverageReporter(customConfig, mockHelper, mockLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
expect(globalCoverageMapGetStub).not.to.have.been.called
})
it('should pass watermarks to istanbul', async () => {
const watermarks = {
statements: [10, 20],
branches: [30, 40],
functions: [50, 60],
lines: [70, 80]
}
const customConfig = helper.merge({}, rootConfig, {
coverageReporter: {
reporters: [
{
dir: 'reporter1'
}
],
watermarks: watermarks
}
})
reportCreateStub.resetHistory()
createContextStub.resetHistory()
reporter = new m.CoverageReporter(customConfig, mockHelper, mockLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
await reporter.onRunComplete(browsers)
expect(createContextStub).to.have.been.called
expect(reportCreateStub).to.have.been.called
const options = reportCreateStub.getCall(0)
expect(options.args[1].watermarks).to.deep.equal(watermarks)
})
it('should merge with istanbul default watermarks', async () => {
const watermarks = {
statements: [10, 20],
lines: [70, 80]
}
const customConfig = helper.merge({}, rootConfig, {
coverageReporter: {
reporters: [
{
dir: 'reporter1'
}
],
watermarks: watermarks
}
})
reportCreateStub.resetHistory()
createContextStub.resetHistory()
reporter = new m.CoverageReporter(customConfig, mockHelper, mockLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
await reporter.onRunComplete(browsers)
expect(createContextStub).to.have.been.called
expect(reportCreateStub).to.have.been.called
const options = reportCreateStub.getCall(0)
expect(options.args[1].watermarks.statements).to.deep.equal(watermarks.statements)
expect(options.args[1].watermarks.branches).to.deep.equal(mockDefaultWatermarks.branches)
expect(options.args[1].watermarks.functions).to.deep.equal(mockDefaultWatermarks.functions)
expect(options.args[1].watermarks.lines).to.deep.equal(watermarks.lines)
})
it('should log errors on low coverage and fail the build', async () => {
const customConfig = helper.merge({}, rootConfig, {
coverageReporter: {
check: {
each: {
statements: 50
}
}
}
})
mockCoverageMap.files.returns(['./foo/bar.js', './foo/baz.js'])
mockCoverageSummary.toJSON.returns({
lines: { total: 5, covered: 1, skipped: 0, pct: 20 },
statements: { total: 5, covered: 1, skipped: 0, pct: 20 },
functions: { total: 5, covered: 1, skipped: 0, pct: 20 },
branches: { total: 5, covered: 1, skipped: 0, pct: 20 }
})
const spy1 = sinon.spy()
const customLogger = {
create: (name) => {
return {
debug () {},
info () {},
warn () {},
error: spy1
}
}
}
const results = { exitCode: 0 }
reporter = new m.CoverageReporter(customConfig, mockHelper, customLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
reporter.onRunComplete(browsers, results)
const done = sinon.stub()
await reporter.onExit(done)
expect(spy1).to.have.been.called
expect(done.calledOnceWith(1)).to.be.true
})
it('should not log errors on sufficient coverage and not fail the build', async () => {
const customConfig = helper.merge({}, rootConfig, {
coverageReporter: {
check: {
each: {
statements: 10
}
}
}
})
mockCoverageMap.files.returns(['./foo/bar.js', './foo/baz.js'])
mockCoverageSummary.toJSON.returns({
lines: { total: 5, covered: 1, skipped: 0, pct: 20 },
statements: { total: 5, covered: 1, skipped: 0, pct: 20 },
functions: { total: 5, covered: 1, skipped: 0, pct: 20 },
branches: { total: 5, covered: 1, skipped: 0, pct: 20 }
})
const spy1 = sinon.spy()
const customLogger = {
create: (name) => {
return {
debug () {},
info () {},
warn () {},
error: spy1
}
}
}
const results = { exitCode: 0 }
reporter = new m.CoverageReporter(customConfig, mockHelper, customLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
await reporter.onRunComplete(browsers, results)
expect(spy1).to.not.have.been.called
expect(results.exitCode).to.equal(0)
})
it('Should log warnings on low coverage and not fail the build', async () => {
const customConfig = helper.merge({}, rootConfig, {
coverageReporter: {
check: {
emitWarning: true,
each: {
statements: 50
}
}
}
})
mockCoverageMap.files.returns(['./foo/bar.js', './foo/baz.js'])
mockCoverageSummary.toJSON.returns({
lines: { total: 5, covered: 1, skipped: 0, pct: 20 },
statements: { total: 5, covered: 1, skipped: 0, pct: 20 },
functions: { total: 5, covered: 1, skipped: 0, pct: 20 },
branches: { total: 5, covered: 1, skipped: 0, pct: 20 }
})
const log = {
debug () {},
info () {},
warn: sinon.stub(),
error: sinon.stub()
}
const customLogger = {
create: (name) => {
return log
}
}
const results = { exitCode: 0 }
reporter = new m.CoverageReporter(customConfig, mockHelper, customLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
reporter.onRunComplete(browsers, results)
const done = sinon.stub()
await reporter.onExit(done)
expect(log.error).to.not.have.been.called
expect(log.warn).to.have.been.called
expect(done.calledOnce).to.be.true
})
it('should handle unexpected errors during the coverage generation', async () => {
const errorSpy = sinon.spy()
const doneSpy = sinon.spy()
const customLogger = {
create: () => {
return {
debug () {},
info () {},
warn () {},
error: errorSpy
}
}
}
const error = new Error('Directory creation failed!')
const customHelper = {
...mockHelper,
mkdirIfNotExists: async (_, done) => done(error)
}
reporter = new m.CoverageReporter(rootConfig, customHelper, customLogger)
reporter.onRunStart()
browsers.forEach(b => reporter.onBrowserStart(b))
reporter.onRunComplete(browsers)
await reporter.onExit(doneSpy)
expect(errorSpy).to.have.been.calledOnceWith('Unexpected error while generating coverage report.\n', error)
expect(doneSpy).to.have.been.calledOnceWith(1)
})
})
})
|
'use strict';
// This brief template description will be displayed along with the template name when the user runs grunt init or grunt-init to display a list of all available init templates.
exports.description = '无线开发环境初始化';
// If specified, this optional extended description will be displayed before any prompts are displayed. This is a good place to give the user a little help explaining naming conventions, which prompts may be required or optional, etc.
exports.notes = '\n1、进入自己的某个目录\
\n2、在该目录下运行“grunt-init box-template”命令并填写一些项目信息\
\n3、之后在该目录下运行“npm install”命令安装依赖包\
\n4、最后在该目录下运行“grunt”命令预览项目静态文件'
// If this optional (but recommended) wildcard pattern or array of wildcard patterns is matched, Grunt will abort with a warning that the user can override with --force. This is very useful in cases where the init template could potentially override existing files.
// 防止文件被覆盖
exports.warnOn = "{{%=ModuleName%}}";
//生成当前时间
var
nowTime = new Date,
nowYear = nowTime.getFullYear(),
nowMonth = nowTime.getMonth()+1,
nowDay = nowTime.getDate(),
nowHours = nowTime.getHours(),
nowMinutes = nowTime.getMinutes(),
nowSeconds = nowTime.getSeconds(),
timeString = '',
spliceTimeString = '';
nowMonth = nowMonth <= 9 ? '0' + nowMonth : nowMonth;
nowDay = nowDay <= 9 ? '0' + nowDay : nowDay;
nowHours = nowHours <= 9 ? '0' + nowHours : nowHours;
nowMinutes = nowMinutes <= 9 ? '0' + nowMinutes : nowMinutes;
nowSeconds = nowSeconds <= 9 ? '0' + nowSeconds : nowSeconds;
timeString = [nowYear, nowMonth, nowDay].join('.') + ' ' + [nowHours, nowMinutes, nowSeconds].join(':');
spliceTimeString = [nowYear, nowMonth, nowDay, nowHours, nowMinutes].join('');
// The grunt argument is a reference to grunt, containing all the grunt methods and libs. The init argument is an object containing methods and properties specific to this init template. The done argument is a function that must be called when the init template is done executing.
exports.template = function(grunt, init, done) {
init.process({}, [
init.prompt('ModuleName', 'mod-'+spliceTimeString),
init.prompt('Description', '盒子组件'),
init.prompt('AuthorName', 'shijun.lisj'),
init.prompt('AuthorEmail', 'shijun.lisj@alibaba-inc.com')
], function(err, props) {
//生成当前时间字符串
props.timeString = timeString;
//默认生成的时间戳
props.timeStamp = spliceTimeString;
// As long as a template uses the init.filesToCopy and init.copyAndProcess methods, any files in the root/ subdirectory will be copied to the current directory when the init template is run.
// Note that all copied files will be processed as templates, with any {% %} template being processed against the collected props data object, unless the noProcess option is set.
var files = init.filesToCopy(props);
init.copyAndProcess(files, props);
});
}; |
'use strict';
var Compiler = require('./lib/compiler');
var gutil = require('gulp-util');
var through = require('through2');
var async = require('async');
module.exports = function (options) {
var sourceFiles = [];
var emitError = (!options || options.emitError !== false);
function eachFile(file, encoding, done) {
sourceFiles.push(file);
done();
}
function endStream(done) {
if (sourceFiles.length === 0) {
return done();
}
var _this = this;
var compiler = new Compiler(sourceFiles, options);
compiler.on('stdout', function (line) {
gutil.log(gutil.colors.green('[tsc] >'), line);
});
compiler.on('stderr', function (line) {
gutil.log(gutil.colors.red('[tsc] >'), line);
});
compiler.on('error', function (err) {
gutil.log(gutil.colors.red('[tsc] Error: ' + err.toString()));
err.stack && console.log(gutil.colors.gray(err.stack));
});
compiler.on('data', function (file) {
_this.push(file);
});
async.waterfall([
function (next) {
compiler.getVersion(next);
},
function (version, next) {
gutil.log('Compiling TypeScript files using tsc version ' + version);
compiler.compile(next);
}
], function (err) {
if (err) {
gutil.log(gutil.colors.red('Failed to compile TypeScript:', err));
if (emitError) {
Compiler.abortAll(function () {
_this.emit('error', new gutil.PluginError('gulp-tsc', 'Failed to compile: ' + (err.message || err)));
sourceFiles = [];
done();
});
return;
}
}
sourceFiles = [];
done();
});
}
return through.obj(eachFile, endStream);
};
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ingredientSchema = new Schema({
name: String,
degree: String,
nutrients: String
});
module.exports = mongoose.model('ingredient', ingredientSchema);
|
$(function() {
sninfo2Obj.initData()
})
jQuery.support.cors = true
var sninfo2Obj = {
initData : function() {
sninfo2Obj.snInterval()
},
sninfo : function(){
var domain = document.domain
$.cloudCall({
method : "sn.info",
async : true,
isLoading : false,
params : {
domain : domain
},
success : function(obj) {
if (obj.error == null && obj.result != null) {
var title = obj.result.websiteTitle
sninfo2Obj.setCookie("Sitetile", title)
sninfo2Obj.setCookie("CustomerUrl",obj.result.onlineCustomerServiceUrl)
sninfo2Obj.setCookie("Modules", obj.result.maintain.modulesJson, 2)// 0.5 h
sninfo2Obj.setCookie("ForwardUrl", obj.result.maintain.forwardUrl)
}
}
})
},
snInterval : function(){
sninfo2Obj.sninfo()
var stt = setTimeout(function(){
clearTimeout(stt)
//0.5 h
var st = setInterval(function() {getSnInfoStatus()}, 5*60*1000)
function getSnInfoStatus() {
sninfo2Obj.sninfo()
}
},100)
},
setCookie : function (name, value, imark) {
if (imark == 1) {
document.cookie = name + "=" + escape(value) + ";path=/"
}if (imark == 2) {
var exp = new Date()
exp.setTime(exp.getTime() + 5 * 60 * 1000)
document.cookie = name + "=" + escape(value) + ";path=/"
} else {
var Days = 1
var exp = new Date()
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
document.cookie = name + "=" + escape(value) + ";path=/;expires="
+ exp.toGMTString()
}
},
getCookie : function (name) {
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)")
if (arr = document.cookie.match(reg))
return unescape(arr[2])
else
return null
}
}
|
/**
* Created by hassaanali on 4/2/15.
*/
$(document.body).on('click', '.like', function () {
var id = $(this).attr("id");
$(this).text("Unlike");
var likes = $(this).parent().children(".likes");
$.get("/like/" + id, function () {
likes.text(parseInt(likes.text()) + 1);
});
$(this).removeClass("like");
$(this).addClass("unlike");
}).on('click', '.unlike', function () {
var id = $(this).attr("id");
$(this).text("Like");
var likes = $(this).parent().children(".likes");
$.get("/unlike/" + id, function () {
likes.text(parseInt(likes.text()) - 1);
});
$(this).removeClass("unlike");
$(this).addClass("like");
});
$(document.body).on('click', '.follow', function () {
var id = $(this).attr("id");
$(this).text("Unfollow!");
$.get("/follow/" + id, function () {
});
$(this).removeClass("follow btn-success");
$(this).addClass("unfollow btn-danger");
}).on('click', '.unfollow', function () {
var id = $(this).attr("id");
$(this).text("Follow!");
var likes = $(this).parent().children(".likes");
$.get("/unfollow/" + id, function () {
});
$(this).removeClass("unfollow btn-danger");
$(this).addClass("follow btn-success");
});
$(".mark-read").click(function(){
var id = $(this).attr("id");
$.get("../notifications/read/" + id, function () {
});
}); |
Slipmat.Collections.Records = Backbone.Collection.extend({
url: "api/records",
model: Slipmat.Models.Record,
initialize: function () {
this.proto = "Records";
this.subview = this.model.prototype.subview;
},
parse: function (payload) {
this._statistics = payload.statistics;
delete payload.statistics;
this._pages = payload.pages;
delete payload.pages;
return payload.records;
},
statistics: function () {
this._statistics = this._statistics || {};
return this._statistics;
},
pages: function () {
this._pages = this._pages || {
upper_limit: 0,
lower_limit: 0,
total_count: "None"
};
return this._pages;
},
hasRecord: function (model) {
return this.some(record => { record.id === Number(model.id) });
},
getOrFetch: function (id, callback) {
var model = this.get(id),
onSuccess = (model) => { callback && callback(model) },
onError = () => { this.remove(model) };
if (model) {
model.fetch({ success: onSuccess });
} else {
model = new this.model({ id: id });
this.add(model);
model.fetch({
success: onSuccess,
error: onError
});
}
return model;
}
});
|
const debug = require('ghost-ignition').debug('importer:clients'),
Promise = require('bluebird'),
_ = require('lodash'),
BaseImporter = require('./base'),
models = require('../../../../models');
class ClientsImporter extends BaseImporter {
constructor(allDataFromFile) {
super(allDataFromFile, {
modelName: 'Client',
dataKeyToImport: 'clients'
});
this.errorConfig = {
allowDuplicates: false,
returnDuplicates: true,
showNotFoundWarning: false
};
}
fetchExisting(modelOptions) {
return models.Client.findAll(_.merge({columns: ['id', 'slug']}, modelOptions))
.then((existingData) => {
this.existingData = existingData.toJSON();
});
}
beforeImport() {
debug('beforeImport');
return super.beforeImport();
}
doImport(options, importOptions = {}) {
debug('doImport', this.dataToImport.length);
let ops = [];
if (!importOptions.include || importOptions.include.indexOf(this.dataKeyToImport) === -1) {
return Promise.resolve().reflect();
}
_.each(this.dataToImport, (obj) => {
ops.push(models[this.modelName].findOne({slug: obj.slug}, options)
.then((client) => {
if (client) {
return models[this.modelName]
.edit(_.omit(obj, 'id'), Object.assign({id: client.id}, options))
.then((importedModel) => {
obj.model = {
id: importedModel.id
};
if (importOptions.returnImportedData) {
this.importedDataToReturn.push(importedModel.toJSON());
}
// for identifier lookup
this.importedData.push({
id: importedModel.id,
slug: importedModel.get('slug'),
originalSlug: obj.slug
});
return importedModel;
})
.catch((err) => {
return this.handleError(err, obj);
});
}
return models[this.modelName].add(obj, options)
.then((importedModel) => {
obj.model = {
id: importedModel.id
};
if (importOptions.returnImportedData) {
this.importedDataToReturn.push(importedModel.toJSON());
}
// for identifier lookup
this.importedData.push({
id: importedModel.id,
slug: importedModel.get('slug'),
originalSlug: obj.slug
});
return importedModel;
})
.catch((err) => {
return this.handleError(err, obj);
});
}).reflect());
});
return Promise.all(ops);
}
}
module.exports = ClientsImporter;
|
// -----------------------
// Test
// --------------------
var Storage = require('node-document-storage');
module.exports = Storage.Spec('ElasticSearch', {
module: require('..'),
engine: require('elastical'),
id: 'elasticsearch',
protocol: 'http',
db: 'default-test',
default_url: 'http://localhost:9200/default-test',
authorized_url: 'http://vt4t5uu0:pk9q6whooingl4uo@jasmine-4473159.us-east-1.bonsai.io:80/test',
unauthorized_url: 'http://vt4t5uu0:123@jasmine-4473159.us-east-1.bonsai.io:80/test',
client: {
get: function(db, type, id, callback) {
var client = new (require('elastical')).Client('localhost', {port: 9200});
client.get(db, id, {type: type}, function(err, res) {
callback(err, res);
});
},
set: function(db, type, id, data, callback) {
var client = new (require('elastical')).Client('localhost', {port: 9200});
client.index(db, type, data, {id: id, create: false}, function(err, res) {
callback(err, res);
});
},
del: function(db, type, id, callback) {
var client = new (require('elastical')).Client('localhost', {port: 9200});
client.delete(db, type, id, {}, function(err, res) {
callback(err, res);
});
},
exists: function(db, type, id, callback) {
var client = new (require('elastical')).Client('localhost', {port: 9200});
// client.count(db, type, {id: id}, function(err, res) {
// callback(err, res);
// });
client.get(self.options.server.db, resource.id, {type: resource.type, ignoreMissing: true}, function(err, data, res) {
callback(err, res);
});
}
}
});
|
const lams = require('../../../index.js')
const mocks = require('../../../lib/mocks.js')
const path= require('path')
const options = {reporting:"no", cwd:__dirname}
require('../../../lib/expect-to-contain-message');
const log = x=>console.log(x)
const testProjectName = __dirname.split(path.sep).slice(-1)[0];
describe('Projects', () => {
describe(testProjectName, () => {
let {spies, process, console} = mocks()
let messages
beforeAll( async () => {
messages = await lams(options,{process, console})
})
it("should not error out", ()=> {
expect(console.error).not.toHaveBeenCalled()
});
it("it should report an error-level message for the file that couldn't be parsed", ()=> {
expect({messages}).toContainMessage({
rule: "P1",
level: "error"
});
});
it("it should still evaluate other files and error for model:bad", ()=> {
expect({messages}).toContainMessage({
rule: "E2",
level: "error",
location: "model:bad/explore:bad/join:foo"
});
});
it("it should still evaluate other files and not error for model:ok", ()=> {
expect({messages}).toContainMessage({
rule: "E2",
level: "info",
});
expect({messages}).not.toContainMessage({
rule: "E2",
level: "error",
location: "model:ok/explore:ok/join:foo"
});
});
});
});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var hddO = exports.hddO = { "viewBox": "0 0 1536 1792", "children": [{ "name": "path", "attribs": { "d": "M1040 1216q0 33-23.5 56.5t-56.5 23.5-56.5-23.5-23.5-56.5 23.5-56.5 56.5-23.5 56.5 23.5 23.5 56.5zM1296 1216q0 33-23.5 56.5t-56.5 23.5-56.5-23.5-23.5-56.5 23.5-56.5 56.5-23.5 56.5 23.5 23.5 56.5zM1408 1376v-320q0-13-9.5-22.5t-22.5-9.5h-1216q-13 0-22.5 9.5t-9.5 22.5v320q0 13 9.5 22.5t22.5 9.5h1216q13 0 22.5-9.5t9.5-22.5zM178 896h1180l-157-482q-4-13-16-21.5t-26-8.5h-782q-14 0-26 8.5t-16 21.5zM1536 1056v320q0 66-47 113t-113 47h-1216q-66 0-113-47t-47-113v-320q0-25 16-75l197-606q17-53 63-86t101-33h782q55 0 101 33t63 86l197 606q16 50 16 75z" } }] }; |
//~ name b866
alert(b866);
//~ component b867.js
|
import sequelize from '../../sequelize';
import Text from './Text';
function sync(...args) {
return sequelize.sync(...args);
}
export default { sync };
export { Text };
|
import Ember from 'ember';
import ApplicationRouteMixin from 'op-firebase-auth/mixins/application-route';
/* globals MockFirebase */
module('ApplicationRouteMixin');
// Replace this with your real tests.
test('it works', function() {
var ApplicationRouteObject = Ember.Object.extend(ApplicationRouteMixin);
// mock firebase injection
ApplicationRouteObject.reopen({
firebase: new MockFirebase()
});
var subject = ApplicationRouteObject.create();
ok(subject);
});
|
import Starfield2D from 'fx/starfield/2d/Starfield2D.js';
import DrawImage from 'canvas/DrawImage.js';
export default class Starfield2DImage extends Starfield2D {
constructor (
width,
height,
{
speedX = 0,
speedY = 0,
paddingX = 0,
paddingY = 0
} = {})
{
super(width, height, { speedX, speedY, paddingX, paddingY });
}
render (i, ctx) {
for (let layer of this.layers)
{
for (let star of layer.stars)
{
let x = star.dx + (star.x - star.dx) * i;
let y = star.dy + (star.y - star.dy) * i;
DrawImage(ctx, layer.image, { x, y });
}
}
}
} |
import * as _commands from './commands';
export const description = 'Setup and manage docker';
export const commands = _commands;
export const hooks = {
'post.default.status'(api) {
return api.runCommand('docker.status');
}
};
|
var dialogsModule = require("ui/dialogs");
var http = require("http");
var spark = require("../../shared/spark-helper");
var view = require("ui/core/view");
var requestUrl = spark.baseUrl + spark.deviceId;
var requestBody = "access_token=" + spark.accessToken + "";
function pageNavigatedTo(args) {
var page = args.object;
page.bindingContext = page.navigationContext;
// iOS-Specific Status-Bar Work
if (page.ios) {
page.ios.title = "Show Plasma";
}
}
exports.pageNavigatedTo = pageNavigatedTo;
function sendTapped(args) {
var sender = args.object;
var parent = sender.parent;
if (parent) {
http.request({ url: requestUrl + "/showPlasma", method: "POST",
headers: spark.requestHeaders,
content: requestBody }).then(function (response) {
var statusCode = response.statusCode;
console.log("**** " + statusCode);
}, function (e) {
console.log("ERROR ***** " + JSON.stringify(e));
done(e);
});
}
}
exports.sendTapped = sendTapped;
|
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
var shell = require('shelljs'),
fs = require('fs'),
url = require('url'),
underscore = require('underscore'),
semver = require('semver'),
PluginInfoProvider = require('cordova-common').PluginInfoProvider,
plugins = require('./util/plugins'),
CordovaError = require('cordova-common').CordovaError,
events = require('cordova-common').events,
metadata = require('./util/metadata'),
path = require('path'),
Q = require('q'),
registry = require('./registry/registry'),
pluginSpec = require('../cordova/plugin_spec_parser'),
fetch = require('cordova-fetch'),
cordovaUtil = require('../cordova/util');
var projectRoot;
// Cache of PluginInfo objects for plugins in search path.
var localPlugins = null;
// possible options: link, subdir, git_ref, client, expected_id
// Returns a promise.
module.exports = fetchPlugin;
function fetchPlugin(plugin_src, plugins_dir, options) {
// Ensure the containing directory exists.
shell.mkdir('-p', plugins_dir);
options = options || {};
options.subdir = options.subdir || '.';
options.searchpath = options.searchpath || [];
if ( typeof options.searchpath === 'string' ) {
options.searchpath = options.searchpath.split(path.delimiter);
}
var pluginInfoProvider = options.pluginInfoProvider || new PluginInfoProvider();
// clone from git repository
var uri = url.parse(plugin_src);
// If the hash exists, it has the form from npm: http://foo.com/bar#git-ref[:subdir]
// git-ref can be a commit SHA, a tag, or a branch
// NB: No leading or trailing slash on the subdir.
if (uri.hash) {
var result = uri.hash.match(/^#([^:]*)(?::\/?(.*?)\/?)?$/);
if (result) {
if (result[1])
options.git_ref = result[1];
if (result[2])
options.subdir = result[2];
//if --fetch was used, throw error for subdirectories
if (options.subdir && options.subdir !== '.') {
events.emit('warn', 'support for subdirectories is deprecated and will be removed in Cordova@7');
if (options.fetch) {
return Q.reject(new CordovaError('--fetch does not support subdirectories'));
}
}
// Recurse and exit with the new options and truncated URL.
var new_dir = plugin_src.substring(0, plugin_src.indexOf('#'));
//skip the return if user asked for --fetch
//cordova-fetch doesn't need to strip out git-ref
if(!options.fetch) {
return fetchPlugin(new_dir, plugins_dir, options);
}
}
}
return Q.when().then(function() {
// If it looks like a network URL, git clone it
// skip git cloning if user passed in --fetch flag
if ( uri.protocol && uri.protocol != 'file:' && uri.protocol[1] != ':' && !plugin_src.match(/^\w+:\\/) && !options.fetch) {
events.emit('log', 'Fetching plugin "' + plugin_src + '" via git clone');
if (options.link) {
events.emit('log', '--link is not supported for git URLs and will be ignored');
}
return plugins.clonePluginGit(plugin_src, plugins_dir, options)
.fail(function (error) {
var message = 'Failed to fetch plugin ' + plugin_src + ' via git.' +
'\nEither there is a connection problems, or plugin spec is incorrect:\n\t' + error;
return Q.reject(new CordovaError(message));
})
.then(function(dir) {
return {
pinfo: pluginInfoProvider.get(dir),
dest: dir,
fetchJsonSource: {
type: 'git',
url: plugin_src,
subdir: options.subdir,
ref: options.git_ref
}
};
});
}
// If it's not a network URL, it's either a local path or a plugin ID.
var plugin_dir = cordovaUtil.fixRelativePath(path.join(plugin_src, options.subdir));
return Q.when().then(function() {
// check if it is a local path
if (fs.existsSync(plugin_dir)) {
if (options.fetch) {
if (!fs.existsSync(path.join(plugin_dir, 'package.json'))) {
return Q.reject(new CordovaError('Invalid Plugin! '+ plugin_dir + ' needs a valid package.json'));
}
projectRoot = path.join(plugins_dir, '..');
//Plugman projects need to go up two directories to reach project root.
//Plugman projects have an options.projectRoot variable
if(options.projectRoot) {
projectRoot = options.projectRoot;
}
return fetch(path.resolve(plugin_dir), projectRoot, options)
.then(function(directory) {
return {
pinfo: pluginInfoProvider.get(directory),
fetchJsonSource: {
type: 'local',
path: directory
}
};
}).fail(function(error) {
//something went wrong with cordova-fetch
return Q.reject(new CordovaError(error.message));
});
} else {
//nofetch
return {
pinfo: pluginInfoProvider.get(plugin_dir),
fetchJsonSource: {
type: 'local',
path: plugin_dir
}
};
}
}
// If there is no such local path, it's a plugin id or id@versionspec.
// First look for it in the local search path (if provided).
var pinfo = findLocalPlugin(plugin_src, options.searchpath, pluginInfoProvider);
if (pinfo) {
events.emit('verbose', 'Found ' + plugin_src + ' at ' + pinfo.dir);
return {
pinfo: pinfo,
fetchJsonSource: {
type: 'local',
path: pinfo.dir
}
};
} else if ( options.noregistry ) {
return Q.reject(new CordovaError(
'Plugin ' + plugin_src + ' not found locally. ' +
'Note, plugin registry was disabled by --noregistry flag.'
));
}
// If not found in local search path, fetch from the registry.
var parsedSpec = pluginSpec.parse(plugin_src);
var P, skipCopyingPlugin;
plugin_dir = path.join(plugins_dir, parsedSpec.id);
// if the plugin has already been fetched, use it.
if (fs.existsSync(plugin_dir)) {
P = Q(plugin_dir);
skipCopyingPlugin = true;
} else {
//use cordova-fetch if --fetch was passed in
if(options.fetch) {
projectRoot = path.join(plugins_dir, '..');
//Plugman projects need to go up two directories to reach project root.
//Plugman projects have an options.projectRoot variable
if(options.projectRoot) {
projectRoot = options.projectRoot;
}
P = fetch(plugin_src, projectRoot, options);
} else {
P = registry.fetch([plugin_src]);
}
skipCopyingPlugin = false;
}
return P
.fail(function (error) {
var message = 'Failed to fetch plugin ' + plugin_src + ' via registry.' +
'\nProbably this is either a connection problem, or plugin spec is incorrect.' +
'\nCheck your connection and plugin name/version/URL.' +
'\n' + error;
return Q.reject(new CordovaError(message));
})
.then(function(dir) {
return {
pinfo: pluginInfoProvider.get(dir),
fetchJsonSource: {
type: 'registry',
id: plugin_src
},
skipCopyingPlugin: skipCopyingPlugin
};
});
}).then(function(result) {
options.plugin_src_dir = result.pinfo.dir;
var P;
if (result.skipCopyingPlugin) {
P = Q(options.plugin_src_dir);
} else {
P = Q.when(copyPlugin(result.pinfo, plugins_dir, options.link && result.fetchJsonSource.type == 'local'));
}
return P.then(function(dir) {
result.dest = dir;
return result;
});
});
}).then(function(result){
checkID(options.expected_id, result.pinfo);
var data = { source: result.fetchJsonSource };
data.is_top_level = options.is_top_level;
data.variables = options.variables || {};
metadata.save_fetch_metadata(plugins_dir, result.pinfo.id, data);
return result.dest;
});
}
// Helper function for checking expected plugin IDs against reality.
function checkID(expectedIdAndVersion, pinfo) {
if (!expectedIdAndVersion) return;
var parsedSpec = pluginSpec.parse(expectedIdAndVersion);
if (parsedSpec.id != pinfo.id) {
throw new Error('Expected plugin to have ID "' + parsedSpec.id + '" but got "' + pinfo.id + '".');
}
if (parsedSpec.version && !semver.satisfies(pinfo.version, parsedSpec.version)) {
throw new Error('Expected plugin ' + pinfo.id + ' to satisfy version "' + parsedSpec.version + '" but got "' + pinfo.version + '".');
}
}
// Note, there is no cache invalidation logic for local plugins.
// As of this writing loadLocalPlugins() is never called with different
// search paths and such case would not be handled properly.
function loadLocalPlugins(searchpath, pluginInfoProvider) {
if (localPlugins) {
// localPlugins already populated, nothing to do.
// just in case, make sure it was loaded with the same search path
if ( !underscore.isEqual(localPlugins.searchpath, searchpath) ) {
var msg =
'loadLocalPlugins called twice with different search paths.' +
'Support for this is not implemented. Using previously cached path.';
events.emit('warn', msg);
}
return;
}
// Populate localPlugins object.
localPlugins = {};
localPlugins.searchpath = searchpath;
localPlugins.plugins = {};
searchpath.forEach(function(dir) {
var ps = pluginInfoProvider.getAllWithinSearchPath(dir);
ps.forEach(function(p) {
var versions = localPlugins.plugins[p.id] || [];
versions.push(p);
localPlugins.plugins[p.id] = versions;
});
});
}
// If a plugin is fund in local search path, return a PluginInfo for it.
// Ignore plugins that don't satisfy the required version spec.
// If several versions are present in search path, return the latest.
// Examples of accepted plugin_src strings:
// org.apache.cordova.file
// org.apache.cordova.file@>=1.2.0
function findLocalPlugin(plugin_src, searchpath, pluginInfoProvider) {
loadLocalPlugins(searchpath, pluginInfoProvider);
var parsedSpec = pluginSpec.parse(plugin_src);
var versionspec = parsedSpec.version || '*';
var latest = null;
var versions = localPlugins.plugins[parsedSpec.id];
if (!versions) return null;
versions.forEach(function(pinfo) {
// Ignore versions that don't satisfy the the requested version range.
// Ignore -dev suffix because latest semver versions doesn't handle it properly (CB-9421)
if (!semver.satisfies(pinfo.version.replace(/-dev$/, ''), versionspec)) {
return;
}
if (!latest) {
latest = pinfo;
return;
}
if (semver.gt(pinfo.version, latest.version)) {
latest = pinfo;
}
});
return latest;
}
// Copy or link a plugin from plugin_dir to plugins_dir/plugin_id.
// if alternative ID of plugin exists in plugins_dir/plugin_id, skip copying
function copyPlugin(pinfo, plugins_dir, link) {
var plugin_dir = pinfo.dir;
var dest = path.join(plugins_dir, pinfo.id);
shell.rm('-rf', dest);
if(!link && dest.indexOf(path.resolve(plugin_dir)+path.sep) === 0) {
if(/^win/.test(process.platform)) {
/*
[CB-10423]
This is a special case. On windows we cannot create a symlink unless we are run as admin
The error that we have is because src contains dest, so we end up with a recursive folder explosion
This code avoids copy the one folder that will explode, and allows plugins to contain a demo project
and to install the plugin via `cordova plugin add ../`
*/
var resolvedSrcPath = path.resolve(plugin_dir);
var filenames = fs.readdirSync(resolvedSrcPath);
var relPath = path.relative(resolvedSrcPath,dest);
var relativeRootFolder = relPath.split('\\')[0];
filenames.splice(filenames.indexOf(relativeRootFolder),1);
shell.mkdir('-p', dest);
events.emit('verbose', 'Copying plugin "' + resolvedSrcPath + '" => "' + dest + '"');
events.emit('verbose', 'Skipping folder "' + relativeRootFolder + '"');
filenames.forEach(function(elem) {
shell.cp('-R', path.join(resolvedSrcPath,elem) , dest);
});
return dest;
}
else {
events.emit('verbose', 'Copy plugin destination is child of src. Forcing --link mode.');
link = true;
}
}
if (link) {
var isRelativePath = plugin_dir.charAt(1) != ':' && plugin_dir.charAt(0) != path.sep;
var fixedPath = isRelativePath ? path.join(path.relative(plugins_dir, process.env.PWD || process.cwd()), plugin_dir) : plugin_dir;
events.emit('verbose', 'Linking "' + dest + '" => "' + fixedPath + '"');
fs.symlinkSync(fixedPath, dest, 'dir');
} else {
shell.mkdir('-p', dest);
events.emit('verbose', 'Copying plugin "' + plugin_dir + '" => "' + dest + '"');
shell.cp('-R', path.join(plugin_dir, '*') , dest);
}
return dest;
}
|
import {Form} from 'widget/form/form'
import {Layout} from 'widget/layout'
import {Panel} from 'widget/panel/panel'
import {RecipeFormPanel, recipeFormPanel} from 'app/home/body/process/recipeFormPanel'
import {compose} from 'compose'
import {msg} from 'translate'
import React from 'react'
import moment from 'moment'
import styles from './dates.module.css'
const DATE_FORMAT = 'YYYY-MM-DD'
const fields = {
startDate: new Form.Field()
.notBlank('process.timeSeries.panel.dates.form.startDate.required')
.date(DATE_FORMAT, 'process.timeSeries.panel.dates.form.startDate.malformed'),
endDate: new Form.Field()
.notBlank('process.timeSeries.panel.dates.form.endDate.required')
.date(DATE_FORMAT, 'process.timeSeries.panel.dates.form.endDate.malformed')
}
const constraints = {
startBeforeEnd: new Form.Constraint(['startDate', 'endDate'])
.skip(({endDate}) => !endDate)
.predicate(({startDate, endDate}) => {
return startDate < endDate
}, 'process.timeSeries.panel.dates.form.startDate.beforeEnd')
}
class Dates extends React.Component {
renderContent() {
const {inputs: {startDate, endDate}} = this.props
return (
<Form.FieldSet
layout='horizontal'
errorMessage={[startDate, endDate, 'startBeforeEnd']}>
<Form.DatePicker
label={msg('process.timeSeries.panel.dates.form.startDate.label')}
tooltip={msg('process.timeSeries.panel.dates.form.startDate.tooltip')}
tooltipPlacement='top'
input={startDate}
startDate='1982-08-22'
endDate={moment()}
/>
<Form.DatePicker
label={msg('process.timeSeries.panel.dates.form.endDate.label')}
tooltip={msg('process.timeSeries.panel.dates.form.endDate.tooltip')}
tooltipPlacement='top'
input={endDate}
startDate={startDate.isInvalid()
? '1982-08-23'
: moment(startDate.value, DATE_FORMAT).add(1, 'days')}
endDate={moment()}
/>
</Form.FieldSet>
)
}
render() {
return (
<RecipeFormPanel
className={styles.panel}
placement='bottom-right'>
<Panel.Header
icon='cog'
title={msg('process.timeSeries.panel.dates.title')}/>
<Panel.Content>
<Layout>
{this.renderContent()}
</Layout>
</Panel.Content>
<Form.PanelButtons/>
</RecipeFormPanel>
)
}
}
Dates.propTypes = {}
export default compose(
Dates,
recipeFormPanel({id: 'dates', fields, constraints})
)
|
'use strict';
// MODULES //
var gammaDeltaRatio = require( 'math-gamma-delta-ratio' );
// GAMMA RATIO //
/**
* FUNCTION: gammaDeltaRatio( x, delta )
* Computes a ratio of gamma functions: Γ(x) / Γ(y).
*
* @param {Number} x - parameter for numerator gamma fcn
* @param {Number} y - parameter for denominator gamma fcn
* @returns {Number} function value
*/
function gammaRatio( x, y ) {
return gammaDeltaRatio( x, y - x );
} // end FUNCTION gammaRatio()
// EXPORTS //
module.exports = gammaRatio;
|
/**
* class Meta
*
* @returns getPegasusVersionInfo
* @returns getPegasusDbVersionInfo
* @returns getLanguages
* @returns getCountries
* @returns getCountryGroups
*/
class Meta {
/**
*
* @param {object} client lib\Client
*/
constructor (client) {
this.client = client;
}
/**
* Get information about the current version of the service
*
* @name lib\mixins\Meta
* @returns {Promise.<*>}
*/
getPegasusVersionInfo () {
let params = {
'getPegasusVersionInfo': {
'provider': this.client._config.provider
}
};
let response = this.client._getRequest(params);
response = this.client._processResponse(response);
return response;
}
/**
* Get information about the current version of the service and the database used
*
* @name lib\mixins\Meta
* @returns {Promise.<*>}
*/
getPegasusDbVersionInfo () {
let params = {
'getPegasusVersionInfo2': {
'provider': this.client._config.provider
}
};
let response = this.client._getRequest(params);
response = this.client._processResponse(response);
return response;
}
/**
* Get TecDoc languages, for example German.
*
* @name lib\mixins\Meta
* @return {*|Promise.<*>}
*/
getLanguages () {
let params = {
'getLanguages': {
'lang': this.client._config.lang,
'provider': this.client._config.provider
}
};
let response = this.client._getRequest(params);
response = this.client._processResponse(response);
return response;
}
/**
* Get TecDoc countries, for example Germany.
*
* @name lib\mixins\Meta
* @return {*|Promise.<*>}
*/
getCountries () {
let params = {
'getCountries': {
'lang': this.client._config.lang,
'provider': this.client._config.provider
}
};
let response = this.client._getRequest(params);
response = this.client._processResponse(response);
return response;
}
/**
* Get TecDoc regions, for example Europe.
*
* @name lib\mixins\Meta
* @return {*|Promise.<*>}
*/
getCountryGroups () {
let params = {
'getCountryGroups': {
'lang': this.client._config.lang,
'provider': this.client._config.provider
}
};
let response = this.client._getRequest(params);
response = this.client._processResponse(response);
return response;
}
/**
* In the results of the request functions references of key tables are returned (KT xxx).
*
* @name lib\mixins\Meta
* @param {object} params
* @return {*}
*/
getKeyValues (params) {
let response = this.client._getRequest({
'getKeyValues': params
});
response = this.client._processResponse(response);
return response;
}
}
/**
*
* @type {Meta}
*/
module.exports = Meta; |
/**
* Gets the ordersitories of the user from Github
*/
import { take, call, put, select, cancel, takeLatest } from 'redux-saga/effects';
import { LOCATION_CHANGE } from 'react-router-redux';
import { LOAD_ORDERS } from './constants';
import { ordersLoaded, orderLoadingError } from './actions';
import request from 'utils/request';
import { makeSelectOrdersQuery } from 'containers/OrdersPage/selectors';
/**
* Github orders request/response handler
*/
export function* getOrders() {
// Select username from store
const ordersQuery = yield select(makeSelectOrdersQuery());
const requestURL = `https://api.github.com/users/${ordersQuery}/repos?type=all&sort=updated`;
try {
// Call our request helper (see 'utils/request')
const orders = yield call(request, requestURL);
yield put(ordersLoaded(orders, ordersQuery));
} catch (err) {
yield put(orderLoadingError(err));
}
}
/**
* Root saga manages watcher lifecycle
*/
export function* githubData() {
// Watches for LOAD_ORDERS actions and calls getOrders when one comes in.
// By using `takeLatest` only the result of the latest API call is applied.
// It returns task descriptor (just like fork) so we can continue execution
const watcher = yield takeLatest(LOAD_ORDERS, getOrders);
// Suspend execution until location changes
yield take(LOCATION_CHANGE);
yield cancel(watcher);
}
// Bootstrap sagas
export default [
githubData,
];
|
/**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var Lib = require('../../lib');
module.exports = {
hasLines: function(trace) {
return trace.visible && trace.mode &&
trace.mode.indexOf('lines') !== -1;
},
hasMarkers: function(trace) {
return trace.visible && (
(trace.mode && trace.mode.indexOf('markers') !== -1) ||
// until splom implements 'mode'
trace.type === 'splom'
);
},
hasText: function(trace) {
return trace.visible && trace.mode &&
trace.mode.indexOf('text') !== -1;
},
isBubble: function(trace) {
return Lib.isPlainObject(trace.marker) &&
Lib.isArrayOrTypedArray(trace.marker.size);
}
};
|
'use strict';
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('favArchApp'));
var MainCtrl,
scope,
$httpBackend;
// Initialize the controller and a mock scope
beforeEach(inject(function (_$httpBackend_, $controller, $rootScope) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('/api/things')
.respond(['HTML5 Boilerplate', 'AngularJS', 'Karma', 'Express']);
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
it('should attach a list of things to the scope', function () {
$httpBackend.flush();
expect(scope.awesomeThings.length).toBe(4);
});
});
|
const { firstLetterLowerCase } = require('../../machinery/word')
const {
getPropertyName,
getJSXElementName, getParentJSXElement,
isRootJSXElement
} = require('../../machinery/ast')
const messages = {
'no layoutClassName in child':
`Unexpected 'layoutClassName', only root elements can use the 'layoutClassName' - set the ` +
`'layoutClassName' as 'className' of the root element`,
'no _root with layoutClassName':
`Unexpected 'layoutClassName', '_root' and 'layoutClassName' can not be combined`,
'no className on custom component':
`Unexpected attribute 'className', only native (lower case) elements can have a 'className' - ` +
`use 'layoutClassName' for manipulating layout`,
'no export base':
`Unexpected 'export', Base components can not be exported - remove the 'export' keyword`,
}
module.exports = {
messages,
meta: { type: 'problem' },
create(context) {
const hasLayoutClassName = new Set()
const foundRootReferences = new Map()
return {
[`ReturnStatement JSXAttribute[name.name = 'className'] Identifier[name = 'layoutClassName']`](node) {
const jsxElement = getParentJSXElement(node)
if (hasLayoutClassName.has(jsxElement)) return
else hasLayoutClassName.add(jsxElement)
if (isRootJSXElement(jsxElement)) reportInvalidComboFromClassName(jsxElement)
else reportLayoutClassNameInChild(node)
},
[`ReturnStatement JSXAttribute[name.name = 'className'] MemberExpression[object.name = 'styles']`](node) {
const jsxElement = getParentJSXElement(node)
const property = findRootProperty(jsxElement, node)
if (!property) return
foundRootReferences.set(jsxElement, property)
reportInvalidComboFromStyles(jsxElement, property)
},
[`JSXSpreadAttribute Property[key.name = 'className']`](node) {
reportClassNameOnCustomComponent(node)
},
[`JSXAttribute[name.name = 'className']`](node) {
reportClassNameOnCustomComponent(node)
},
[`ExportNamedDeclaration > FunctionDeclaration`](node) {
reportExportedBase(node)
},
}
function reportInvalidComboFromClassName(jsxElement) {
if (!foundRootReferences.has(jsxElement)) return
context.report({
message: messages['no _root with layoutClassName'],
node: foundRootReferences.get(jsxElement)
})
}
function reportInvalidComboFromStyles(jsxElement, property) {
if (!hasLayoutClassName.has(jsxElement)) return
context.report({
message: messages['no _root with layoutClassName'],
node: property
})
}
function reportLayoutClassNameInChild(node) {
context.report({
message: messages['no layoutClassName in child'],
node,
})
}
function reportClassNameOnCustomComponent(node) {
const jsxElement = getParentJSXElement(node)
const name = getJSXElementName(jsxElement)
if (firstLetterLowerCase(name) || name.endsWith('Base')) return
context.report({
message: messages['no className on custom component'],
node,
})
}
function reportExportedBase(node) {
const { name } = node.id
if (!name.endsWith('Base') || firstLetterLowerCase(name)) return
const exportNode = node.parent
context.report({
message: messages['no export base'],
node: exportNode,
loc: {
start: exportNode.loc.start,
end: node.loc.start
},
})
}
}
}
function findRootProperty(jsxElement, node) {
if (!isRootJSXElement(jsxElement)) return
const { property } = node
const className = getPropertyName(property)
if (!['_root', 'component_root'].some(x => className.startsWith(x))) return
return property
} |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
// @flow
exports.default = function (haystack /*: Array<Object>*/, needleConstructor /*: Function*/) /*: Object*/ {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = haystack[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var needle = _step.value;
if (needle instanceof needleConstructor) {
return needle;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
throw new Error('Instance not found.');
};
module.exports = exports['default']; |
Meteor.publish('userTrackers', function(){
var currentUserId = this.userId;
var uTrackers = Trackers.find({
user: currentUserId
});
if(uTrackers){
return uTrackers;
}
return this.ready();
}); |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // identity function for calling harmory imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/ // define getter function for harmory exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ };
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 14);
/******/ })
/************************************************************************/
/******/ ({
/***/ 14:
/***/ function(module, exports) {
console.log('derp');
/***/ }
/******/ }); |
var $ = require("jquery");
var Router = require("./service/Router");
var Component = require("./service/Component");
$(function()
{
var secondComponent = new Component("second", "templates/second", require("./controller/SecondCtrl"));
var firstComponent = new Component("first", "templates/first", require("./controller/FirstCtrl"));
var navComponent = new Component("nav", "templates/navigation", require("./controller/NavigationCtrl"));
var router = new Router({
"first": { "#page": firstComponent, "#navigation": navComponent },
"second": { "#page": secondComponent, "#navigation": navComponent },
"*": { "#page": firstComponent, "#navigation": navComponent }
});
}); |
module.exports = function( grunt )
{
grunt.initConfig({
watch : {
literateCode : {
files : [
'**/*.haml.md', '**/*.html.md', '**/*.jade.md',
'**/*.css.md', '**/*.less.md', '**/*.rool.md', '**/*.sass.md', '**/*.scss.md', '**/*.stylus.md',
'**/*.coffee.md', '**/*.js.md', '**/*.php.md',
'**/*.ini.md', '**/*.json.md'
]
}
}
});
grunt.loadNpmTasks( 'grunt-contrib-watch' );
grunt.event.on( 'watch', function( event, literateCode ) {
var executableCode = literateCode.replace( /(.+?)\.md$/g, '$1' );
if( event === 'added' || event === 'changed' ) {
var content = grunt.file.read( literateCode );
content = content.replace( /^(\t|\S)+.*?$/mg, '' );
content = content.replace( /\n+([ \t]*\n){2,}/g, '\n\n' );
content = content.replace( /^(\n*[ \t]*\n)+/, '' );
content = content.replace( /(\n*[ \t]*\n)+$/, '\n' );
content = content.replace( /^ {4}/mg, '' );
grunt.file.write( executableCode, content );
} else try {
grunt.file.delete( executableCode );
} catch ( exception ) {
// file does not exist ...
}
});
grunt.registerTask( 'default', [ 'watch' ] );
};
|
'use strict';
/**
* Module dependencies.
*/
const validator = require('validator');
const menuDao = require('../../dao/sys_menu');
const areaDao = require('../../dao/sys_area');
const dictUtil = require('../../utils/dict_utils');
module.exports = function (app, routeMethod) {
routeMethod.session('/manage/area','sys:area:view');
routeMethod.csurf('/manage/area');
app.get('/manage/area', function (req, res) {
Promise.all([
areaDao.queryAreasByPId('0'),
menuDao.queryMenuByHref('/manage/area')
]).then(result => {
let areas = result[0];
res.render('manage/sys_area/index', {
currentMenu: result[1],
areas: JSON.stringify(areas)
});
});
});
routeMethod.session('/manage/area/findareabypid','sys:area:view');
routeMethod.csurf('/manage/area/findareabypid');
app.post('/manage/area/findareabypid',async function (req, res) {
let areas = await areaDao.queryAreasByPId(req.body.parent_id);
res.json(areas);
});
routeMethod.session('/manage/area/create','sys:area:edit');
routeMethod.csurf('/manage/area/create');
app.get('/manage/area/create', function (req, res) {
Promise.all([
menuDao.queryMenuByHref('/manage/area'),
dictUtil.getDictList('sys_area_type'),
areaDao.queryAreaById(req.query.parent_id),
areaDao.queryChildrenMaxSort(req.query.parent_id)
]).then(result => {
res.render('manage/sys_area/create', {
currentMenu: result[0],
areaTypes: result[1],
parentAreaInfo: result[2],
currentSort: parseInt(result[3] ? result[3] : 0) + 10
});
});
});
/**
* 保存一个区域信息
*/
routeMethod.session('/manage/area/store','sys:area:edit');
routeMethod.csurf('/manage/area/store');
app.post('/manage/area/store', function (req, res) {
let parent_id = req.body.parent_id;
let name = req.body.name;
let sort = req.body.sort;
let code = req.body.code;
let type = req.body.type;
let remarks = req.body.remarks;
let result = null;
// 有ID就视为修改
if (typeof (req.body.id) != 'undefined' && req.body.id != '') {
result = areaDao.updateArea(req);
req.session.notice_info = {
info:'修改区域成功!',
type:'success'
};
} else {
result = areaDao.saveArea(parent_id, name, sort, code, type, remarks, req);
req.session.notice_info = {
info:'保存区域成功!',
type:'success'
};
}
if (result) {
res.json({
result: true
});
} else {
req.session.notice_info = null;
res.json({
result: false,
error: '操作失败请重试!'
});
}
});
/**
* 编辑区域
*/
routeMethod.csurf('/manage/area/edit');
routeMethod.session('/manage/area/edit','sys:area:edit');
app.get('/manage/area/edit',async function (req, res) {
let id = req.query.id;
let area = await areaDao.queryAreaById(id);
Promise.all([
menuDao.queryMenuByHref('/manage/area'),
dictUtil.getDictList('sys_area_type'),
areaDao.queryAreaById(area.parent_id)
]).then(result => {
res.render('manage/sys_area/create', {
currentMenu: result[0],
areaTypes: result[1],
area: area,
parentAreaInfo: result[2]
});
});
});
/**
* 删除一个用户信息
*/
routeMethod.csurf('/manage/area/delete');
routeMethod.session('/manage/area/delete','sys:area:edit');
app.post('/manage/area/delete',async function (req, res) {
let id = req.body.id;
let result = await areaDao.delAreaById(id);
if (result) {
res.json({
result: true
});
} else {
res.json({
result: false
});
}
});
}; |
import { jsdom } from 'jsdom'
import hook from 'css-modules-require-hook'
import postCSSConfig from '../webpack/postcss.config'
global.document = jsdom('<!doctype html><html><body></body></html>')
global.window = document.defaultView
global.navigator = global.window.navigator
hook({
generateScopedName: '[name]__[local]___[hash:base64:5]',
prepend: postCSSConfig.plugins,
})
|
'use strict';
var config = {};
config.jmeterPath = 'C:/apache-jmeter-2.13';
config.resultsPath = 'results';
config.verbose = true;
config.remote = false;
config.cluster = {};
config.cluster.clusterName = 'YOUR_ELASTIC_SEARCH_CLUSTER_NAME';
config.cluster.jumpboxIp = 'YOUR_JUMPBOX_IP';
config.cluster.username = 'YOUR_USER';
config.cluster.password = 'YOUR_PASSWORD';
config.cluster.loadBalancer = {};
config.cluster.loadBalancer.ip = 'YOUR_LOADBALANCER_IP';
config.cluster.loadBalancer.url = 'http://YOUR_LOADBALANCER_IP:9200';
config.testIndex = {};
config.testIndex.indexName = 'systwo'; //default you can change your index here
config.testIndex.replicas = 1; // # of Replicas for this Index
config.testIndex.shards = 5; // # of Shards for this Index
config.testIndex.template = {};
config.testIndex.template.templateName = 'perftemplate';
config.testIndex.template.templateBody = {
"template": "sys*",
"order": 1,
"settings": {
"refresh_interval": "30s"
},
"mappings": {
"_default_": {
"_all": {"enabled": false},
"dynamic_templates": [
{
"notanalyzed": {
"match": "*",
"match_mapping_type": "string",
"mapping": {
"type": "string",
"index": "not_analyzed"
}
}
}
]
}
}
};
module.exports = config; |
var path = require('path');
/**
* Check that a 'filepath' is likely a child of a given directory
* Applies to nested directories
* Only makes String comparison. Does not check for existance
* @param {String} directory
* @param {String} filepath
* @returns {Boolean}
*/
module.exports = function indir (directory, filepath) {
if (directory && filepath) {
directory = path.resolve(directory);
filepath = path.resolve(filepath);
if (~filepath.indexOf(directory)) {
return !~path.relative(directory, filepath).indexOf('..');
}
}
return false;
};
|
/*!
* Adapted from jQuery UI core
*
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/ui-core/
*/
function hidden(el) {
return (el.offsetWidth <= 0 && el.offsetHeight <= 0) ||
el.style.display === 'none';
}
function visible(element) {
while (element) {
if (element === document.body) break;
if (hidden(element)) return false;
element = element.parentNode; // eslint-disable-line no-param-reassign
}
return true;
}
function testElement(element, nodeName, isTabIndexNotNaN) {
if (/input|select|textarea|button|object/.test(nodeName)) return !element.disabled;
if (nodeName === 'a') return element.href || isTabIndexNotNaN;
return isTabIndexNotNaN;
}
function focusable(element, isTabIndexNotNaN) {
const nodeName = element.nodeName.toLowerCase();
return testElement(element, nodeName, isTabIndexNotNaN) && visible(element);
}
function tabbable(element) {
let tabIndex = element.getAttribute('tabindex');
if (tabIndex === null) tabIndex = undefined;
const isTabIndexNaN = isNaN(tabIndex);
return (isTabIndexNaN || tabIndex >= 0) && focusable(element, !isTabIndexNaN);
}
function findTabbableDescendants(element) {
return [].slice.call(element.querySelectorAll('*'), 0).filter(el => tabbable(el));
}
export default findTabbableDescendants;
|
{
return wrap(this.__impl4cf1e782hg__[name]);
}
|
const r = require('./renderer');
const IndexedMap = require('./indexedMap');
const Material = require('./material');
const Mesh = require('./mesh');
const Prefab = require('./prefab');
const Transform = require('./transform');
const Maths = require('./maths');
const Bounds = require('./bounds');
const { mat3, mat4, quat, vec3 } = Maths;
module.exports = (function() {
let nextSceneId = 0;
let exports = {};
// Note Meshes and Materials shared across scenes
// Going to use dictionaries but with an array of keys for enumeration (hence private with accessor methods)
let meshes = IndexedMap.create();
let materials = IndexedMap.create();
let shaders = IndexedMap.create();
let textures = IndexedMap.create();
// Note: clears all resources - any uncleared existing scenes will break
exports.clearResources = function() {
meshes.clear();
materials.clear();
shaders.clear();
textures.clear();
};
// TODO: Add clearUnusedResources - which enumerates through scene renderObjects / prefab instances
// to check objects are used or reference count them - will need to track created scenes
// glState Tracking - shared across scenes
let currentShaderId, currentMaterialId, currentMeshId, pMatrixRebound = false;
let nextTextureLocation = 0, currentTextureBindings = {}, currentTextureLocations = []; // keyed on texture.id to binding location, keyed on binding location to texture.id
exports.create = function({ camera, enableFrustumCulling, forceSphereCulling}) {
let cameras = {};
let cameraNames = [];
let mainCameraName = "main";
// mvMatrix may need to be a stack in future (although a stack which avoids unnecessary mat4.creates)
let pMatrix = mat4.create(), mvMatrix = mat4.create(), nMatrix = mat3.create(), cameraMatrix = mat4.create(), cameraOffset = vec3.create(), inverseCameraRotation = quat.create();
let scene = {};
scene.id = (nextSceneId++).toString();
scene.enableFrustumCulling = !!enableFrustumCulling;
// these renderObjects / instances on prefabs need to contain at minimum materialId, meshId, and transform (currently object just has material and mesh as well as transform)
let renderObjects = IndexedMap.create(); // TODO: use materialId / meshId to bind
let prefabs = { keys: [] }; // Arguably instances could be added to renderer objects and memory would still be saved, however keeping a separate list allows easier batching for now
// TODO: Should have an equivilent to indexedMap but where you supply the keys, keyedMap?.
let alphaRenderObjects = [];
let depths = {};
depths.get = (o) => {
let id = o.sceneId !== undefined ? o.sceneId : o.id;
return depths[id];
};
depths.set = (o, depth) => {
let id = o.sceneId !== undefined ? o.sceneId : o.id;
depths[id] = depth;
};
let addTexturesToScene = function(material) {
for (let i = 0, l = material.shader.textureUniformNames.length; i < l; i++) {
let uniformName = material.shader.textureUniformNames[i];
let texture = material.textures[uniformName];
if (texture) {
textures.add(texture);
bindTextureToLocation(texture);
}
}
};
let bindTextureToLocation = function(texture) {
if (currentTextureBindings[texture.id] === undefined) {
if (currentTextureLocations.length < r.TextureLocations.length) {
r.setTexture(currentTextureLocations.length, texture);
currentTextureBindings[texture.id] = currentTextureLocations.length;
currentTextureLocations.push(texture.id);
} else {
// replace an existing texture
delete currentTextureBindings[currentTextureLocations[nextTextureLocation]];
r.setTexture(nextTextureLocation, texture);
currentTextureBindings[texture.id] = nextTextureLocation;
currentTextureLocations[nextTextureLocation] = texture.id;
nextTextureLocation = (nextTextureLocation+1) % r.TextureLocations.length;
}
}
};
let addToAlphaList = function(object, depth) {
// TODO: Profile using Array sort instead of insertion sorting, also test add/remove from list rather than clear
depths.set(object, depth);
// Binary search
// Could technically do better by batching up items with the same depth according to material / mesh like scene graph
// However this is only relevant for 2D games with orthographic projection
let less, more, itteration = 1, inserted = false, index = Math.floor(alphaRenderObjects.length/2);
while (!inserted) {
less = (index === 0 || depths.get(alphaRenderObjects[index-1]) <= depth);
more = (index >= alphaRenderObjects.length || depths.get(alphaRenderObjects[index]) >= depth);
if (less && more) {
alphaRenderObjects.splice(index, 0, object);
inserted = true;
} else {
itteration++;
var step = Math.ceil(alphaRenderObjects.length/(2*itteration));
if(!less) {
index = Math.max(0, index - step);
} else {
index = Math.min(alphaRenderObjects.length, index + step);
}
}
}
};
let createObjectBounds = function(object, mesh, rotation) {
// If object is static and not rotated, create object AABB from mesh bounds
if (!forceSphereCulling && object.static && (!rotation || Maths.quatIsIdentity(rotation))) {
// TODO: Allow for calculation of AABB of rotated meshes
let center = vec3.clone(mesh.bounds.center);
vec3.add(center, center, object.transform.position);
let size = vec3.clone(mesh.bounds.size);
object.bounds = Bounds.create({ center: center, size: size });
}
};
let isCulledByFrustrum = function(camera, object) {
if (!object.static || !object.bounds) {
return !camera.isSphereInFrustum(object.transform.position, object.mesh.boundingRadius);
} else {
return !camera.isInFrustum(object.bounds);
}
};
let sortByMaterial = function(a, b) {
if (a.materialId == b.materialId) {
return 0;
} else if (a.materialId < b.materialId) { // Note: will not order strings by their parsed numberical value, however this is not required.
return +1;
} else {
return -1;
}
};
// Add Render Object
scene.add = function(config) {
let object = {};
let { mesh, material, static = false, active = true } = config;
object.material = material;
object.mesh = mesh;
if (!mesh || !material) {
throw new Error("Mesh and Material must be present on the object.");
}
// Note: indexedMap.add adds id property to object added and does not add duplicates
object.meshId = meshes.add(object.mesh);
object.materialId = materials.add(object.material);
object.shaderId = shaders.add(object.material.shader);
object.material.shaderId = object.shaderId;
addTexturesToScene(object.material);
object.transform = Transform.create(config);
// For now just sort by material on add
// Ideally would group materials with the same shader and textures together
object.sceneId = renderObjects.add(object, sortByMaterial);
// Would probably be more performant to dynamic changes if kept a record of start and end index
// of all materials and could simply inject at the correct point - TODO: Profile
object.static = static;
object.active = active;
createObjectBounds(object, object.mesh, object.transform.rotation);
return object;
};
scene.remove = function(object) {
// Note: This does not free up the resources (e.g. mesh and material references remain) in the scene, may need to reference count these and delete
if (object.sceneId !== undefined) {
renderObjects.remove(object.sceneId);
} else if (object.id) {
// Is prefab, look on prototype for instances and remove this
object.instances.remove(object.id);
// Note not deleting the locally stored prefab, even if !instances.length as we would get duplicate mesh / materials if we were to readd
// Keeping the prefab details around is preferable and should be low overhead
}
};
scene.clear = function() {
// Note: This does not free up the resources (e.g. mesh and material references remain) in the scene, may need to reference count these and delete
renderObjects.clear();
alphaRenderObjects.length = 0;
if (prefabs.keys.length) {
// Recreate prefab object - i.e. remove all prefabs and instances in one swoop.
prefabs = { keys: [] };
}
};
// Instantiate prefab instance
scene.instantiate = function(config) {
let prefab;
if (!config || !config.name || !Prefab.prefabs[config.name]) {
throw new Error("You must provide a valid prefab name");
}
let name = config.name;
if (!prefabs[name]) {
let defn = Prefab.prefabs[name];
if (!defn.materialConfig || !defn.meshConfig) {
throw new Error("Requested prefab must have a material and a mesh config present");
}
prefab = {
name: name,
instances: IndexedMap.create(),
mesh: Mesh.create(defn.meshConfig),
material: Material.create(defn.materialConfig)
};
prefab.meshId = meshes.add(prefab.mesh);
prefab.materialId = materials.add(prefab.material);
prefab.shaderId = shaders.add(prefab.material.shader);
prefab.material.shaderId = prefab.shaderId;
addTexturesToScene(prefab.material);
prefabs[name] = prefab;
prefabs.keys.push(name);
} else {
prefab = prefabs[name];
}
let instance = Object.create(prefab);
instance.transform = Transform.create(config);
let { static = false, active = true } = config;
instance.id = prefab.instances.add(instance);
instance.static = static;
instance.active = active;
createObjectBounds(instance, prefab.mesh, instance.transform.rotation);
return instance;
};
// Add Camera
// Arguably camera.render(scene) would be a preferable pattern
scene.addCamera = function(camera, name) {
let key = name ? name : "main";
if (cameraNames.length === 0) {
mainCameraName = key;
}
if (!cameras[key]) {
cameraNames.push(key);
}
cameras[key] = camera;
};
// Render
scene.render = function(cameraName) {
let camera = cameras[cameraName ? cameraName : mainCameraName];
if (scene.enableFrustumCulling) {
camera.calculateFrustum();
}
camera.getProjectionMatrix(pMatrix);
// Camera Matrix should transform world space -> camera space
quat.invert(inverseCameraRotation, camera.rotation); // TODO: Not quite sure about this, camera's looking in -z but THREE.js does it so it's probably okay
mat4.fromQuat(cameraMatrix, inverseCameraRotation);
mat4.translate(cameraMatrix, cameraMatrix, vec3.set(cameraOffset, -camera.position[0], -camera.position[1], -camera.position[2]));
pMatrixRebound = false;
alphaRenderObjects.length = 0;
// TODO: Scene Graph
// Batched first by Shader
// Then by Material
// Then by Mesh
// Then render each Mesh Instance
// An extension would be to batch materials such that shaders that textures used overlap
// This batching by shader / material / mesh may need to be combined with scene management techniques
if (camera.clear) {
r.clear();
} else if (camera.clearDepth) {
r.clearDepth();
}
// TODO: Scene graph should provide these as a single thing to loop over, will then only split and loop for instances at mvMatrix binding / drawing
// Scene Graph should be class with enumerate() method, that way it can batch as described above and sort watch its batching / visibility whilst providing a way to simple loop over all elements
let culled = false, renderObject = null;
for (let i = 0, l = renderObjects.keys.length; i < l; i++) {
// TODO: Detect if resorting is necessary (check +1 and -1 in array against sort function)
renderObject = renderObjects[renderObjects.keys[i]];
if (scene.enableFrustumCulling) {
culled = isCulledByFrustrum(camera, renderObject);
}
if (!culled && renderObject.active) {
if(renderObject.material.alpha) {
let sortPosition = renderObject.transform.position
if (renderObject.bounds) {
sortPosition = renderObject.bounds.center;
}
addToAlphaList(renderObject, camera.getDepth(sortPosition));
} else {
bindAndDraw(renderObject);
}
}
}
for (let i = 0, l = prefabs.keys.length; i < l; i++) {
let instances = prefabs[prefabs.keys[i]].instances;
for (let j = 0, n = instances.keys.length; j < n; j++) {
let instance = instances[instances.keys[j]];
if (scene.enableFrustumCulling) {
culled = isCulledByFrustrum(camera, instance);
}
if (!culled && instance.active) {
if (instance.material.alpha) {
let sortPosition = instance.transform.position;
if (instance.bounds) {
sortPosition = instance.bounds.center;
}
addToAlphaList(instance, camera.getDepth(sortPosition));
} else {
bindAndDraw(instance);
}
}
}
}
for (let i = 0, l = alphaRenderObjects.length; i < l; i++) {
renderObject = alphaRenderObjects[i];
let m = renderObject.material;
// Could probably do this in bind and draw method
if (!m.blendSeparate) {
r.enableBlending(m.sourceBlendType, m.destinationBlendType, m.blendEquation);
} else {
r.enableSeparateBlending(m.sourceColorBlendType, m.destinationColorBlendType, m.sourceAlphaBlendType, m.destinationAlphaBlendType, m.blendEquation);
}
bindAndDraw(renderObject);
}
r.disableBlending();
};
let bindAndDraw = function(object) {
let shader = object.material.shader;
let material = object.material;
let mesh = object.mesh;
// BUG:
// If there's only one material or one mesh in the scene real time changes to the material or mesh will not present themselves as the id will still match the currently bound
// mesh / material, seems like we're going need a flag on mesh / material for forceRebind for this case. (should probably be called forceRebind as it 'might' be rebound anyway)
// Having now determined that actually we don't need to rebind uniforms when switching shader programs, we'll need this flag whenever there's only one mesh or material using a given shader.
// TODO: When scene graph implemented - check material.shaderId & object.shaderId against shader.id, and object.materialId against material.id and object.meshId against mesh.id
// as this indicates that this object needs reordering in the graph (as it's been changed).
let shouldRebindShader = false;
let shouldRebindMaterial = false;
if (!shader.id || shader.id != currentShaderId) {
shouldRebindShader = true;
// Check if shader was changed on the material since originally added to scene
if(!shader.id) {
material.shaderId = shaders.add(shader);
object.shaderId = material.shaderId;
} else {
if (material.shaderId != shader.id) {
material.shaderId = shader.id;
}
if (object.shaderId != shader.id) {
object.shaderId = shader.id;
}
}
currentShaderId = shader.id;
r.useShaderProgram(shader.shaderProgram);
pMatrixRebound = false;
}
if (!pMatrixRebound) {
// New Shader or New Frame, rebind projection Matrix
r.setUniformMatrix4(shader.pMatrixUniformName, pMatrix);
pMatrixRebound = true;
}
if (!material.id || material.id != currentMaterialId || material.dirty) {
if (!material.dirty) {
shouldRebindMaterial = true;
} else {
material.dirty = false;
}
// check if material was changed on object since originally
// added to scene TODO: Ideally would mark object for resorting
if (!material.id) {
object.materialId = materials.add(material);
} else if (object.materialId != material.id) {
object.materialId = material.id;
}
currentMaterialId = material.id;
shader.bindMaterial.call(r, material);
}
if (shouldRebindShader || shouldRebindMaterial) {
// Texture Rebinding dependencies
// If the shader has changed you DON'T need to rebind, you only need to rebind if the on the uniforms have changed since the shaderProgram was last used...
// NOTE Large Changes needed because of this
// I think we're just going to have to add a flag to materials and meshes to say "rebind" (because I've changed something)
// This also means we should move the "currentMeshId / currentMaterial id to the shader instead or keep a keyed list on shader the id
// Lets do this after we've done the texture binding though eh? so for now just rebind everything if shader or material changes (overkill but it'll work)
// If the material has changed textures may need rebinding
// Check for gl location rebinds needed, if any needed and rebind all to make sure we don't replace a texture we're using
let locationRebindsNeeded = false, uniformName = null, texture = null;
for (let i = 0, l = shader.textureUniformNames.length; i < l; i++) {
uniformName = shader.textureUniformNames[i];
if (material.textures[uniformName]) {
texture = material.textures[uniformName];
if (!texture.id) {
textures.add(texture);
locationRebindsNeeded = true;
break;
}
if (isNaN(currentTextureBindings[texture.id])) {
locationRebindsNeeded = true;
break;
}
}
}
// Rebind if necessary and set uniforms
for (let i = 0, l = shader.textureUniformNames.length; i < l; i++) {
uniformName = shader.textureUniformNames[i];
if (material.textures[uniformName]) {
texture = material.textures[uniformName];
if (locationRebindsNeeded) {
bindTextureToLocation(texture);
}
r.setUniformInteger(uniformName, currentTextureBindings[texture.id]);
}
}
}
if (!mesh.id || mesh.id != currentMeshId || mesh.dirty) {
// Check if mesh was changed on object since originally added to scene
if (!mesh.id) {
object.meshId = mesh.add(mesh);
} else if (object.meshId != mesh.id) {
object.meshId = mesh.id;
}
currentMeshId = mesh.id;
shader.bindBuffers.call(r, mesh);
mesh.dirty = false;
}
// TODO: If going to use child coordinate systems then will need a stack of mvMatrices and a multiply here
mat4.fromRotationTranslation(mvMatrix, object.transform.rotation, object.transform.position);
mat4.scale(mvMatrix, mvMatrix, object.transform.scale);
if (shader.mMatrixUniformName) {
// TODO: Arguably should send either MV Matrix or M and V Matrices
r.setUniformMatrix4(shader.mMatrixUniformName, mvMatrix);
}
mat4.multiply(mvMatrix, cameraMatrix, mvMatrix);
r.setUniformMatrix4(shader.mvMatrixUniformName, mvMatrix);
if (shader.nMatrixUniformName) {
mat3.normalFromMat4(mvMatrix, nMatrix);
r.setUniformMatrix3(shader.nMatrixUniformName, nMatrix);
}
r.draw(mesh.renderMode, mesh.indexed ? mesh.indexBuffer.numItems : mesh.vertexBuffer.numItems, mesh.indexed, 0);
};
if (camera) {
scene.addCamera(camera);
}
return scene;
};
return exports;
})(); |
angular.module('app').component('componentName',{
templateUrl: 'path/to/component-name.html',
controller: function($scope){
var ctrl = this;
ctrl.selectedFile = '';
ctrl.fileChanged = function (el) {
if(el && el.files && el.files.length > 0){
ctrl.selectedFile = el.files[0].name.toString();
$scope.$apply();
}else{
ctrl.selectedFile = '';
}
}
}
}) |
'use strict'
var express = require('express')
var router = express.Router()
var db = require('../db/api')
router.get('/', function(req, res) {
db.getAllPosts().then(posts => {
res.render('posts/all', {
title: 'Scotty VG - Blog: All Posts',
posts: posts
})
})
})
router.get('/new', function(req, res) {
db.getAllUsers().then(users => {
res.render('posts/new', {
title: 'Scotty VG - Blog: Write a Post',
users: users
})
})
})
router.get('/:id', function(req, res) {
db.getOnePost(req.params.id).then(post => {
db.getAllUsers().then(users => {
res.render('posts/one', {
title: 'Scotty VG - Blog: ' + post.title,
post: post,
users: users
})
})
})
})
router.post('/', function(req, res) {
db.createOnePost().then(post => {
console.log('post', post)
res.redirect('/')
})
})
router.get('/:id/edit', function(req, res) {
db.getOnePost(req.params.id).then(post => {
res.render('posts/edit', {
title: 'Scotty VG - Blog: ' + post.title,
post: post
})
})
})
router.put('/:id', function(req, res) {
db.updateOnePost(req.params.id).then(() => {
res.redirect('/')
})
})
router.delete('/:id', function(req, res) {
db.deleteOnePost(req.params.id).then(() => {
res.redirect('/')
})
})
module.exports = router
|
// Karma configuration
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'../bower_components/jquery/dist/jquery.js',
'../bower_components/imgcache.js/js/imgcache.js',
'../bower_components/angular/angular.js',
'../bower_components/angular-mocks/angular-mocks.js',
'../bower_components/angular-route/angular-route.js',
'../bower_components/semantic/build/packaged/javascript/semantic.js',
'../js/app.js',
'../js/lib/*.js',
'../js/controller/*.js',
'../js/model/*.js',
'*.tests.js'
],
// list of files to exclude
exclude: [
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress'],
// 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, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
browsers: ['Chrome', 'PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
|
var carousel;
var client_arr = [
// 'img/carousel/client01.png',
// 'img/carousel/client02.png',
// 'img/carousel/client03.png',
// 'img/carousel/client04.png',
// 'img/carousel/client05.png',
// 'img/carousel/client06.png',
// 'img/carousel/client07.png',
// 'img/carousel/client08.png',
// 'img/carousel/client09.png'
'img/carousel/appy.png',
'img/carousel/creata.png',
'img/carousel/dena.png',
'img/carousel/glo.png',
'img/carousel/kabam.png',
'img/carousel/mobage.png'
];
$(window).load(function()
{
carousel = new Carousel('#gcs-clients', client_arr, 4, 1);
carousel.createCarouselDOM();
});
$('.button-back').click(function()
{
carousel.slideCarouselBack();
});
$('.button-forward').click(function()
{
carousel.slideCarouselForward();
});
function Carousel(_host, _src_arr, _num_visible, _num_slide)
{
var self = this;
// Array of all elements used in the carousel
var src_arr = _src_arr;
// Number of elements that will be visible in the carousel
var num_visible = _num_visible;
// Number of elements that will slide in/out at a time. Must be <= num_visible
var num_slide = _num_slide;
if (num_slide > num_visible)
{
console.log("num_slide is larger than num_visible!");
return;
}
// Array of indices from src_arr that represent the elements in the carousel DOM
var dom_arr = [];
var first_visible = 0;
var auto_slide = true;
var auto_slide_interval = null;
var carousel_container_css = {
position: 'absolute',
width: '80vw',
height: '100%',
left: '0', // Used for centering
right: '0', // absolutely-positioned
margin: '0 auto', // container to the parent.
clip: 'rect(0, 80vw, 100%, 0)',
'overflow-x': 'hidden'
};
var carousel_css = {
width: '100%',
height: '100%'
};
var carousel_left_css = {
// background: 'red',
position: 'absolute',
width: '' + (num_slide / num_visible * 100) + '%',
height: '100%',
right: '100%'
};
var carousel_middle_css = {
// background: 'green',
position: 'absolute',
width: '100%',
height: '100%',
};
var carousel_right_css = {
// background: 'blue',
position: 'absolute',
width: '' + (num_slide / num_visible * 100) + '%',
height: '100%',
left: '100%'
};
var carousel_reserve_img_container_css = {
width: '' + (1.0 / num_slide * 100) + '%',
height: '100%',
padding: '2vw',
float: 'left',
'text-align': 'center'
};
var carousel_middle_img_container_css = {
width: '' + (1.0 / num_visible * 100) + '%',
height: '100%',
padding: '2vw',
float: 'left',
'text-align': 'center'
};
var carousel_unit_element_css = {
'max-width': '100%',
height: 'auto'
}
var left_translate = $(
"<style>.left-translate{transform: translateX(" + (num_slide / num_visible * 100) + "%); transition-duration: 1000ms;}</style>"
);
var right_translate = $(
"<style>.right-translate{transform: translateX(-" + (num_slide / num_visible * 100) + "%);transition-duration: 1000ms; -webkit-transform: translateX(-" + (num_slide / num_visible * 100) + "%); -webkit-transition-duration: 1000ms;}</style>"
);
// {
// transform: 'translateX(-' + (num_slide / num_visible) + '%)',
// 'transition-duration': '1000ms'
// };
this.createCarouselDOM = function()
{
var carousel_container = $('<div>');
carousel_container.addClass('carousel-container');
carousel_container.css(carousel_container_css);
var carousel_div = $('<div>');
carousel_div.addClass('custom-carousel');
carousel_div.css(carousel_css);
carousel_container.append(carousel_div);
var carousel_left_div = $('<div>');
carousel_left_div.addClass('carousel-left-queue');
carousel_left_div.css(carousel_left_css);
for (var i = 0; i < num_slide; i++)
{
var carousel_reserve_img_container = $('<div>');
carousel_reserve_img_container.addClass('carousel-img');
carousel_reserve_img_container.css(carousel_reserve_img_container_css);
carousel_reserve_img_container.append($('<img>').css(carousel_unit_element_css));
carousel_left_div.append(carousel_reserve_img_container);
}
var carousel_middle_div = $('<div>');
carousel_middle_div.addClass('carousel-visible');
carousel_middle_div.css(carousel_middle_css);
for (var i = 0; i < num_visible; i++)
{
var carousel_middle_img_container = $('<div>');
carousel_middle_img_container.addClass('carousel-img');
carousel_middle_img_container.css(carousel_middle_img_container_css);
carousel_middle_img_container.append($('<img>').css(carousel_unit_element_css));
carousel_middle_div.append(carousel_middle_img_container);
}
var carousel_right_div = $('<div>');
carousel_right_div.addClass('carousel-right-queue');
carousel_right_div.css(carousel_right_css);
for (var i = 0; i < num_slide; i++)
{
var carousel_reserve_img_container = $('<div>');
carousel_reserve_img_container.addClass('carousel-img');
carousel_reserve_img_container.css(carousel_reserve_img_container_css);
carousel_reserve_img_container.append($('<img>').css(carousel_unit_element_css));
carousel_right_div.append(carousel_reserve_img_container);
}
carousel_div.append(carousel_left_div, carousel_middle_div, carousel_right_div);
$(_host).append(carousel_container);
$('html>head').append(right_translate);
setCarouselImages(first_visible);
setCarouselAutoSlide(auto_slide);
};
var setCarouselImages = function(_first_visible)
{
setDomArr(_first_visible);
// query for all image elements in the carousel
var dom_imgs = $('.custom-carousel').find('img');
var length = dom_imgs.length;
for (var i = 0; i < length; i++)
{
$(dom_imgs[i]).attr('src', src_arr[dom_arr[i]]);
}
};
var setDomArr = function(_first_visible)
{
if (dom_arr.length === 0)
{
dom_arr_length = num_slide * 2 + num_visible;
for (var i = 0; i < dom_arr_length; i++)
{
dom_arr.push(-1);
}
}
setLeftQueue(_first_visible);
setVisibleSection(_first_visible);
setRightQueue(dom_arr[num_slide + num_visible - 1]);
};
var setLeftQueue = function(_first_visible)
{
var curr_src_index = _first_visible;
for (var i = num_slide - 1; i >= 0; i--)
{
curr_src_index = decrementArrayIndex(src_arr, curr_src_index);
dom_arr[i] = curr_src_index; //src_arr[curr_src_index];
}
};
var setVisibleSection = function(_first_visible)
{
var curr_src_index = _first_visible;
for (var i = num_slide; i < num_slide + num_visible; i++)
{
dom_arr[i] = curr_src_index;
curr_src_index = incrementArrayIndex(src_arr, curr_src_index);
}
}
var setRightQueue = function(_last_visible)
{
var curr_src_index = _last_visible;
for (var i = num_slide + num_visible; i < dom_arr.length; i++)
{
curr_src_index = incrementArrayIndex(src_arr, curr_src_index);
dom_arr[i] = curr_src_index; //src_arr[curr_src_index];
}
};
this.slideCarouselBack = function()
{
$('.custom-carousel').addClass('left-translate');
$('.custom-carousel').removeClass('right-translate');
setTimeout(function()
{
first_visible = decrementArrayIndex(src_arr, first_visible, num_slide);
setCarouselImages(first_visible);
$('.custom-carousel').removeClass('left-translate');
}, 1000);
};
this.slideCarouselForward = function()
{
$('.custom-carousel').removeClass('left-translate');
$('.custom-carousel').addClass('right-translate');
setTimeout(function()
{
first_visible = incrementArrayIndex(src_arr, first_visible, num_slide);
setCarouselImages(first_visible);
$('.custom-carousel').removeClass('right-translate');
}, 1000);
};
var setCarouselAutoSlide = function(set_auto)
{
if (set_auto)
{
auto_slide_interval = setInterval(function()
{
self.slideCarouselForward();
}, 3000);
}
else
{
clearInterval(auto_slide_interval);
}
};
}
var decrementArrayIndex = function(arr, index)
{
var amount = arguments[2] ? arguments[2] : 1;
var dest = index - amount;
return (dest >= 0 ? dest : arr.length + dest);
}
var incrementArrayIndex = function(arr, index)
{
var amount = arguments[2] ? arguments[2] : 1;
var dest = index + amount;
return (dest < arr.length ? dest : dest - arr.length);
}
|
var User = require('../models/user');
var fs = require('fs');
var passport = require('passport');
var crypto = require('crypto');
module.exports = {
login:function(req,res){
fs.readFile("views/login.html","utf-8",function(err,data){
res.send(data);
})
},
register:function(req,res){
fs.readFile("views/register.html","utf-8",function(err,data){
res.send(data);
})
},
logout:function(req,res){
req.logout();
res.redirect('/');
},
signup:function(req,res){
var username = req.body.username;
var password = req.body.password;
if(username == "" || password == ""){
return res.send({ code:-1,message:"用户名或者密码为空"})
}
User.findOne({username:username},function(err,doc){
if(err) return next(err);
if(doc){
return res.send({code:-1,message:"用户已经存在!"});
}
if(!doc){
var sha1 = crypto.createHash("sha1");
sha1.update(password);
var hash = sha1.digest("hex");
var user = new User({
"username":username,
"password":hash
});
user.save(function(err) {
if (err) return next(err);
res.send({ code:0,message: '注册成功' });
});
}
})
},
signin:function(req,res,next){
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) {
if(info.message == "Missing credentials"){
return res.send({code:-1,message:"用户名或者密码为空"});
}else{
return res.send({code:-1,message:info.message});
}
}
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.send({code:0,message:"认证成功"});
});
})(req, res, next);
},
userinfo:function(req,res){
res.send(req.user.username);
}
} |
import React from 'react';
import Link from 'next/link';
import { Grid, Segment, Button, Container } from 'semantic-ui-react';
import App from '../components/AppContainer';
import FormRecoverPassword from '../components/account/FormRecoverPasswordContainer';
export default ({ ...rest }) => (
<App {...rest} allowAnonymousAccess>
<Container>
<Segment>
<h3 className="title">Passwort zurücksetzen</h3>
<FormRecoverPassword />
</Segment>
<Segment>
<Grid stackable padded columns={2}>
<Grid.Column>
<Segment textAlign="center" basic size="mini">
<Link prefetch href="/sign-up">
<Button as="a" href="/sign-up" primary basic fluid>
Noch keinen Benutzer? Registrieren
</Button>
</Link>
</Segment>
</Grid.Column>
<Grid.Column>
<Segment textAlign="center" basic size="mini">
<Link prefetch href="/sign-in">
<Button as="a" href="/sign-in" primary basic fluid>
Du hast bereits einen Benutzer? Hier anmelden
</Button>
</Link>
</Segment>
</Grid.Column>
</Grid>
</Segment>
</Container>
</App>
);
|
'use strict';
var ZeroPiCore = require('./core');
class ZeroPi extends ZeroPiCore {
constructor(options) {
super(options);
}
digitalWrite(pin, level) {
this.write(`M11 D${pin} L${level}`);
}
pwmWrite(pin, pwm) {
this.write(`M11 D${pin} P${pwm}`);
}
digitalRead(pin, callback) {
this.selectors[`R12 D${pin}`] = callback;
this.write(`M12 D${pin}`);
}
analogRead(pin, callback) {
this.selectors[`R13 A${pin}`] = callback;
this.write(`M13 A${pin}`);
}
dcMotorRun(device, pwm) {
this.write(`M21 D${device} P${pwm}`);
}
dcMotorStop(device) {
this.write(`M22 D${device}`);
}
servoRun(device, angle) {
this.write(`M41 D${device} A${angle}`);
}
stepperRun(device, speed) {
this.write(`M51 D${device} F${speed}`);
}
stepperMove(device, distance, speed, callback) {
this.selectors[`R52 D${device}`] = callback;
this.write(`M52 D${device} R${distance} F${speed}`);
}
stepperMoveTo(device, position, speed, callback) {
this.selectors[`R52 D${device}`] = callback;
this.write(`M52 D${device} A${position} F${speed}`);
}
stepperStop(device) {
this.write(`M54 D${device}`);
}
steppersEnable() {
this.write('M56');
}
steppersDisable() {
this.write('M57');
}
stepperSetting(device, microstep, acceleration) {
this.write(`M53 D${device} S${microstep} A${acceleration}`);
}
}
module.exports = ZeroPi;
|
// Regular expression that matches all symbols in the Runic block as per Unicode v5.0.0:
/[\u16A0-\u16FF]/; |
const chai = require('chai');
chai.use(require('sinon-chai'));
const { expect } = chai;
const cleanup = require('../../util/cleanup');
const { writeFileSync, existsSync } = require('fs');
const getMocks = require('../../mocks');
const lib = require('../../../src/cmds/copy-dir');
describe('# src/cmds/copy-dir.js', async () => {
let mocks;
before(cleanup.before);
after(cleanup.after);
beforeEach(() => {
mocks = getMocks();
return cleanup.beforeEach();
});
it('COPY test1.txt from local to local2 storage', async () => {
writeFileSync('test/fs/local1/tmp/test1.txt', 'test1');
expect(existsSync('test/fs/local2/tmp/test1.txt')).to.be.false;
mocks.argv.dir = 'tmp';
mocks.argv.storage = ['local', 'local2'];
await lib.handler(mocks.argv);
expect(existsSync('test/fs/local2/tmp/test1.txt')).to.be.true;
});
it('COPY test2.txt from local2 to local1 storage', async () => {
writeFileSync('test/fs/local2/tmp/test2.txt', 'test2');
expect(existsSync('test/fs/local1/tmp/test2.txt')).to.be.false;
mocks.argv.dir = 'tmp';
mocks.argv.storage = ['local2', 'local'];
await lib.handler(mocks.argv);
expect(existsSync('test/fs/local1/tmp/test2.txt')).to.be.true;
});
});
|
module.exports = {
rules: {
// enforce spacing inside array brackets
'array-bracket-spacing': 'off',
// OFF enforce line breaks after opening and before closing array brackets
'array-bracket-newline': 'off',
// OFF enforce line breaks between array elements
'array-element-newline': 'off',
// enforce spacing inside single-line blocks
// http://eslint.org/docs/rules/block-spacing
'block-spacing': ['error', 'always'],
// enforce one true brace style
'brace-style': ['error', '1tbs', { allowSingleLine: true }],
// require camel case names
camelcase: ['error', { properties: 'never' }],
// enforce or disallow capitalization of the first letter of a comment
// http://eslint.org/docs/rules/capitalized-comments
'capitalized-comments': [
'off',
'never',
{
line: {
ignorePattern: '.*',
ignoreInlineComments: true,
ignoreConsecutiveComments: true,
},
block: {
ignorePattern: '.*',
ignoreInlineComments: true,
ignoreConsecutiveComments: true,
},
},
],
// enforce spacing before and after comma
'comma-spacing': ['error', { before: false, after: true }],
// enforce one true comma style
'comma-style': ['error', 'last'],
// disallow padding inside computed properties
'computed-property-spacing': ['error', 'never'],
// enforces consistent naming when capturing the current execution context
'consistent-this': 'off',
// enforce newline at the end of file, with no multiple empty lines
'eol-last': ['error', 'always'],
// enforce spacing between functions and their invocations
// http://eslint.org/docs/rules/func-call-spacing
'func-call-spacing': ['error', 'never'],
// requires function names to match the name of the variable or property to which they are
// assigned
// http://eslint.org/docs/rules/func-name-matching
'func-name-matching': [
'off',
'always',
{
includeCommonJSModuleExports: false,
},
],
// (optional) require function expressions to have a name
// http://eslint.org/docs/rules/func-names
'func-names': 'off',
// enforces use of function declarations or expressions
// http://eslint.org/docs/rules/func-style
// TODO: enable
'func-style': ['off', 'expression'],
// Blacklist certain identifiers to prevent them being used
// http://eslint.org/docs/rules/id-blacklist
'id-blacklist': 'off',
// this option enforces minimum and maximum identifier lengths
// (variable names, property names etc.)
'id-length': 'off',
// require identifiers to match the provided regular expression
'id-match': 'off',
// this option sets a specific tab width for your code
// http://eslint.org/docs/rules/indent
indent: [
'error',
'tab',
{
SwitchCase: 1,
VariableDeclarator: 1,
outerIIFEBody: 1,
// MemberExpression: null,
// CallExpression: {
// parameters: null,
// },
FunctionDeclaration: {
parameters: 1,
body: 1,
},
FunctionExpression: {
parameters: 1,
body: 1,
},
},
],
// specify whether double or single quotes should be used in JSX attributes
// http://eslint.org/docs/rules/jsx-quotes
'jsx-quotes': ['off', 'prefer-double'],
// enforces spacing between keys and values in object literal properties
'key-spacing': ['error', { beforeColon: false, afterColon: true }],
// require a space before & after certain keywords
'keyword-spacing': [
'error',
{
before: true,
after: true,
overrides: {
return: { after: true },
throw: { after: true },
case: { after: true },
},
},
],
// enforce position of line comments
// http://eslint.org/docs/rules/line-comment-position
// TODO: enable?
'line-comment-position': [
'off',
{
position: 'above',
ignorePattern: '',
applyDefaultPatterns: true,
},
],
// disallow mixed 'LF' and 'CRLF' as linebreaks
// http://eslint.org/docs/rules/linebreak-style
'linebreak-style': ['error', 'unix'],
// enforces empty lines around comments
'lines-around-comment': 'off',
// require or disallow newlines around directives
// http://eslint.org/docs/rules/lines-around-directive
'lines-around-directive': [
'error',
{
before: 'always',
after: 'always',
},
],
// specify the maximum depth that blocks can be nested
'max-depth': ['off', 4],
// specify the maximum length of a line in your program
// http://eslint.org/docs/rules/max-len
'max-len': [
'off',
100,
2,
{
ignoreUrls: true,
ignoreComments: false,
ignoreRegExpLiterals: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
},
],
// specify the max number of lines in a file
// http://eslint.org/docs/rules/max-lines
'max-lines': [
'off',
{
max: 300,
skipBlankLines: true,
skipComments: true,
},
],
// specify the maximum depth callbacks can be nested
'max-nested-callbacks': 'off',
// limits the number of parameters that can be used in the function declaration.
'max-params': ['off', 3],
// specify the maximum number of statement allowed in a function
'max-statements': ['off', 10],
// restrict the number of statements per line
// http://eslint.org/docs/rules/max-statements-per-line
'max-statements-per-line': ['off', { max: 1 }],
// require multiline ternary
// http://eslint.org/docs/rules/multiline-ternary
// TODO: enable?
'multiline-ternary': ['off', 'never'],
// require a capital letter for constructors
'new-cap': [
'error',
{
newIsCap: true,
newIsCapExceptions: [],
capIsNew: false,
capIsNewExceptions: ['Immutable.Map', 'Immutable.Set', 'Immutable.List'],
},
],
// disallow the omission of parentheses when invoking a constructor with no arguments
// http://eslint.org/docs/rules/new-parens
'new-parens': 'error',
// allow/disallow an empty newline after var statement
'newline-after-var': 'off',
// http://eslint.org/docs/rules/newline-before-return
'newline-before-return': 'off',
// enforces new line after each method call in the chain to make it
// more readable and easy to maintain
// http://eslint.org/docs/rules/newline-per-chained-call
'newline-per-chained-call': ['error', { ignoreChainWithDepth: 4 }],
// disallow use of the Array constructor
'no-array-constructor': 'error',
// disallow use of bitwise operators
// http://eslint.org/docs/rules/no-bitwise
'no-bitwise': 'error',
// disallow use of the continue statement
// http://eslint.org/docs/rules/no-continue
'no-continue': 'error',
// disallow comments inline after code
'no-inline-comments': 'off',
// disallow if as the only statement in an else block
// http://eslint.org/docs/rules/no-lonely-if
'no-lonely-if': 'error',
// disallow un-paren'd mixes of different operators
// http://eslint.org/docs/rules/no-mixed-operators
'no-mixed-operators': [
'error',
{
groups: [
['+', '-', '*', '/', '%', '**'],
['&', '|', '^', '~', '<<', '>>', '>>>'],
['==', '!=', '===', '!==', '>', '>=', '<', '<='],
['&&', '||'],
['in', 'instanceof'],
],
allowSamePrecedence: false,
},
],
// allows mixed spaces and tabs for indentation
'no-mixed-spaces-and-tabs': 'off',
// allows use of chained assignment expressions
// http://eslint.org/docs/rules/no-multi-assign
'no-multi-assign': 'off',
// disallow multiple empty lines and only one newline at the end
'no-multiple-empty-lines': ['error', { max: 3, maxEOF: 1 }],
// disallow negated conditions
// http://eslint.org/docs/rules/no-negated-condition
'no-negated-condition': 'off',
// disallow nested ternary expressions
'no-nested-ternary': 'error',
// disallow use of the Object constructor
'no-new-object': 'error',
// disallow use of unary operators, ++ and --, but allows in last expr of forloop
// http://eslint.org/docs/rules/no-plusplus
'no-plusplus': ['error', { allowForLoopAfterthoughts: true }],
// disallow certain syntax forms
// http://eslint.org/docs/rules/no-restricted-syntax
'no-restricted-syntax': ['error', 'ForInStatement', 'ForOfStatement', 'LabeledStatement', 'WithStatement'],
// disallow space between function identifier and application
'no-spaced-func': 'error',
// disallow tab characters entirely
'no-tabs': 'off',
// disallow the use of ternary operators
'no-ternary': 'off',
// disallow trailing whitespace at the end of lines
'no-trailing-spaces': 'error',
// disallow dangling underscores in identifiers
'no-underscore-dangle': ['off', { allowAfterThis: false }],
// disallow the use of Boolean literals in conditional expressions
// also, prefer `a || b` over `a ? a : b`
// http://eslint.org/docs/rules/no-unneeded-ternary
'no-unneeded-ternary': ['error', { defaultAssignment: false }],
// disallow whitespace before properties
// http://eslint.org/docs/rules/no-whitespace-before-property
'no-whitespace-before-property': 'error',
// enforce the location of single-line statements
// http://eslint.org/docs/rules/nonblock-statement-body-position
'nonblock-statement-body-position': 'off',
// require padding inside curly braces
'object-curly-spacing': ['error', 'always'],
// enforce line breaks between braces
// http://eslint.org/docs/rules/object-curly-newline
// TODO: enable once https://github.com/eslint/eslint/issues/6488 is resolved
'object-curly-newline': [
'off',
{
ObjectExpression: { minProperties: 0, multiline: true },
ObjectPattern: { minProperties: 0, multiline: true },
},
],
// enforce "same line" or "multiple line" on object properties.
// http://eslint.org/docs/rules/object-property-newline
'object-property-newline': [
'error',
{
allowMultiplePropertiesPerLine: true,
},
],
// allow just one var statement per function
'one-var': ['error', 'never'],
// require a newline around variable declaration
// http://eslint.org/docs/rules/one-var-declaration-per-line
'one-var-declaration-per-line': ['error', 'always'],
// require assignment operator shorthand where possible or prohibit it entirely
// http://eslint.org/docs/rules/operator-assignment
'operator-assignment': ['error', 'always'],
// enforce operators to be placed before or after line breaks
'operator-linebreak': 'off',
// NOT enforce padding within blocks
'padded-blocks': ['off'],
// Require or disallow padding lines between statements
// TODO: add unit tests
'padding-line-between-statements': [
'error',
{ blankLine: 'always', prev: '*', next: ['function', 'class', 'cjs-export', 'export'] },
{ blankLine: 'always', prev: ['import', 'cjs-import'], next: '*' },
{ blankLine: 'any', prev: ['import', 'cjs-import'], next: ['import', 'cjs-import'] },
{ blankLine: 'any', prev: ['export', 'cjs-export'], next: ['export', 'cjs-export'] },
],
// require quotes around object literal property names
// http://eslint.org/docs/rules/quote-props.html
'quote-props': ['error', 'as-needed', { keywords: false, unnecessary: true, numbers: false }],
// specify whether double or single quotes should be used
quotes: ['error', 'single', { avoidEscape: true }],
// do not require jsdoc
// http://eslint.org/docs/rules/require-jsdoc
'require-jsdoc': 'off',
// require or disallow use of semicolons instead of ASI
semi: ['error', 'always'],
// enforce spacing before and after semicolons
'semi-spacing': ['error', { before: false, after: true }],
// Enforce location of semicolons
'semi-style': ['error', 'last'],
// requires object keys to be sorted
'sort-keys': ['off', 'asc', { caseSensitive: false, natural: true }],
// sort variables within the same declaration block
'sort-vars': 'off',
// require or disallow space before blocks
'space-before-blocks': 'error',
// require or disallow space before function opening parenthesis
// http://eslint.org/docs/rules/space-before-function-paren
'space-before-function-paren': [
'error',
{
anonymous: 'never',
named: 'never',
asyncArrow: 'always',
},
],
// require or disallow spaces inside parentheses
'space-in-parens': ['error', 'never'],
// require spaces around operators
'space-infix-ops': 'error',
// Require or disallow spaces before/after unary operators
// http://eslint.org/docs/rules/space-unary-ops
'space-unary-ops': [
'error',
{
words: true,
nonwords: false,
overrides: {},
},
],
// require or disallow a space immediately following the // or /* in a comment
// http://eslint.org/docs/rules/spaced-comment
'spaced-comment': [
'off',
'always',
{
line: {
exceptions: ['-', '+'],
markers: ['=', '!'], // space here to support sprockets directives
},
block: {
exceptions: ['-', '+'],
markers: ['=', '!'], // space here to support sprockets directives
balanced: false,
},
},
],
// Enforce spacing around colons of switch statements
'switch-colon-spacing': ['error', { after: true, before: false }],
// Require or disallow spacing between template tags and their literals
// http://eslint.org/docs/rules/template-tag-spacing
// TODO: enable, semver-major
'template-tag-spacing': ['off', 'never'],
// require or disallow the Unicode Byte Order Mark
// http://eslint.org/docs/rules/unicode-bom
'unicode-bom': ['error', 'never'],
// require regex literals to be wrapped in parentheses
'wrap-regex': 'off',
},
};
|
#!/usr/bin/env node
var promfig = require('..')
var properties = {
user : 'Please enter your username : '
, password : 'Please enter your password : '
, '@secret' : 'password'
};
var config = {};
promfig(
properties
, config
, function (err, config) {
if (err) return console.error('err: ', err);
console.log(config);
}
);
|
import {document, window} from 'global';
export default class ThumbnailHelpers {
static hidePlayerOnHoverTime(progressControl) {
const mouseTime = progressControl.el_.getElementsByClassName('vjs-mouse-display')[0];
mouseTime.style.display = 'none';
}
static createThumbnails(...args) {
const thumbnailClip = args.shift() || {};
Object.keys(args).map((i) => {
const singleThumbnail = args[i];
Object.keys(singleThumbnail).map((property) => {
if (singleThumbnail.hasOwnProperty(property)) {
if (typeof singleThumbnail[property] === 'object') {
thumbnailClip[property] = ThumbnailHelpers.createThumbnails(thumbnailClip[property],
singleThumbnail[property]);
} else {
thumbnailClip[property] = singleThumbnail[property];
}
}
return thumbnailClip;
});
return thumbnailClip;
});
return thumbnailClip;
}
static getComputedStyle(thumbnailContent, pseudo) {
return (prop) => {
if (window.getComputedStyle) {
return window.getComputedStyle(thumbnailContent, pseudo)[prop];
}
return thumbnailContent.currentStyle[prop];
};
}
static getVisibleWidth(thumbnailContent, width) {
if (width) {
return parseFloat(width);
}
let clip = ThumbnailHelpers.getComputedStyle(thumbnailContent)('clip');
if (clip !== 'auto' && clip !== 'inherit') {
clip = clip.split(/(?:\(|\))/)[1].split(/(?:,| )/);
if (clip.length === 4) {
return (parseFloat(clip[1]) - parseFloat(clip[3]));
}
}
return 0;
}
static getScrollOffset() {
if (window.pageXOffset) {
return {
x: window.pageXOffset,
y: window.pageYOffset
};
}
return {
x: document.documentElement.scrollLeft,
y: document.documentElement.scrollTop
};
}
static suportAndroidEvents(player) {
// Android doesn't support :active and :hover on non-anchor and non-button elements
// so, we need to fake the :active selector for thumbnails to show up.
const progressControl = player.controlBar.progressControl;
const addFakeActive = () => {
progressControl.addClass('fake-active');
};
const removeFakeActive = () => {
progressControl.removeClass('fake-active');
};
progressControl.on('touchstart', addFakeActive);
progressControl.on('touchend', removeFakeActive);
progressControl.on('touchcancel', removeFakeActive);
}
static createThumbnaislHolder() {
const wrap = document.createElement('div');
wrap.className = 'vjs-thumbnail-holder';
return wrap;
}
static createThumbnailImg(thumbnailClips) {
const thumbnailImg = document.createElement('img');
thumbnailImg.src = thumbnailClips['0'].src;
thumbnailImg.className = 'vjs-thumbnail-img';
return thumbnailImg;
}
static createThumbnailTime() {
const time = document.createElement('div');
time.className = 'vjs-thumbnail-time';
time.id = 'vjs-time';
return time;
}
static createThumbnailArrowDown() {
const arrow = document.createElement('div');
arrow.className = 'vjs-thumbnail-arrow';
arrow.id = 'vjs-arrow';
return arrow;
}
static mergeThumbnailElements(thumbnailsHolder,
thumbnailImg,
timelineTime,
thumbnailArrowDown) {
thumbnailsHolder.appendChild(thumbnailImg);
thumbnailsHolder.appendChild(timelineTime);
thumbnailsHolder.appendChild(thumbnailArrowDown);
return thumbnailsHolder;
}
static centerThumbnailOverCursor(thumbnailImg) {
// center the thumbnail over the cursor if an offset wasn't provided
if (!thumbnailImg.style.left && !thumbnailImg.style.right) {
thumbnailImg.onload = () => {
const thumbnailWidth = { width: -(thumbnailImg.naturalWidth / 2) };
thumbnailImg.style.left = `${thumbnailWidth}px`;
};
}
}
static getVideoDuration(player) {
let duration = player.duration();
player.on('durationchange', () => {
duration = player.duration();
});
return duration;
}
static addThumbnailToPlayer(progressControl, thumbnailsHolder) {
progressControl.el().appendChild(thumbnailsHolder);
}
static findMouseLeftOffset(pageMousePositionX, progressControl, pageXOffset, event) {
// find the page offset of the mouse
let leftOffset = pageMousePositionX || (event.clientX +
document.body.scrollLeft + document.documentElement.scrollLeft);
// subtract the page offset of the positioned offset parent
leftOffset -= progressControl.el().
getBoundingClientRect().left + pageXOffset;
return leftOffset;
}
static getMouseVideoTime(mouseLeftOffset, progressControl, duration) {
return Math.floor((mouseLeftOffset - progressControl.el().offsetLeft) /
progressControl.width() * duration);
}
static updateThumbnailTime(timelineTime, progressControl) {
timelineTime.innerHTML = (progressControl.seekBar.mouseTimeDisplay.
el_.attributes['data-current-time'].value);
}
static getPageMousePositionX(event) {
let pageMouseOffsetX = event.pageX;
if (event.changedTouches) {
pageMouseOffsetX = event.changedTouches[0].pageX;
}
return pageMouseOffsetX;
}
static keepThumbnailInsidePlayer(thumbnailImg,
activeThumbnail,
thumbnailClips,
mouseLeftOffset,
progresBarRightOffset) {
const width = ThumbnailHelpers.getVisibleWidth(thumbnailImg, activeThumbnail.width ||
thumbnailClips[0].width);
const halfWidth = width / 2;
// make sure that the thumbnail doesn't fall off the right side of
// the left side of the player
if ((mouseLeftOffset + halfWidth) > progresBarRightOffset) {
mouseLeftOffset -= (mouseLeftOffset + halfWidth) - progresBarRightOffset;
} else if (mouseLeftOffset < halfWidth) {
mouseLeftOffset = halfWidth;
}
return mouseLeftOffset;
}
static updateThumbnailLeftStyle(mouseLeftOffset, thumbnailsHolder) {
const leftValue = { mouseLeftOffset };
thumbnailsHolder.style.left = `${leftValue.mouseLeftOffset}px`;
}
static getActiveThumbnail(thumbnailClips, mouseTime) {
let activeClip = 0;
for (const clipNumber in thumbnailClips) {
if (mouseTime > clipNumber) {
activeClip = Math.max(activeClip, clipNumber);
}
}
return thumbnailClips[activeClip];
}
static updateThumbnailSrc(activeThumbnail, thumbnailImg) {
if (activeThumbnail.src && thumbnailImg.src !== activeThumbnail.src) {
thumbnailImg.src = activeThumbnail.src;
}
}
static updateThumbnailStyle(activeThumbnail, thumbnailImg) {
if (activeThumbnail.style && thumbnailImg.style !== activeThumbnail.style) {
ThumbnailHelpers.createThumbnails(thumbnailImg.style, activeThumbnail.style);
}
}
static moveListener(event,
progressControl,
thumbnailsHolder,
thumbnailClips,
timelineTime,
thumbnailImg,
player) {
const duration = ThumbnailHelpers.getVideoDuration(player);
const pageXOffset = ThumbnailHelpers.getScrollOffset().x;
const progresBarPosition = progressControl.el().
getBoundingClientRect();
const progresBarRightOffset = (progresBarPosition.width ||
progresBarPosition.right) +
pageXOffset;
const pageMousePositionX = ThumbnailHelpers.getPageMousePositionX(event);
let mouseLeftOffset = ThumbnailHelpers.findMouseLeftOffset(pageMousePositionX,
progressControl,
pageXOffset,
event);
const mouseTime = ThumbnailHelpers.getMouseVideoTime(mouseLeftOffset,
progressControl,
duration);
const activeThumbnail = ThumbnailHelpers.getActiveThumbnail(thumbnailClips,
mouseTime);
ThumbnailHelpers.updateThumbnailTime(timelineTime, progressControl);
ThumbnailHelpers.updateThumbnailSrc(activeThumbnail, thumbnailImg);
ThumbnailHelpers.updateThumbnailStyle(activeThumbnail, thumbnailImg);
mouseLeftOffset = ThumbnailHelpers.keepThumbnailInsidePlayer(thumbnailImg,
activeThumbnail,
thumbnailClips,
mouseLeftOffset,
progresBarRightOffset);
ThumbnailHelpers.updateThumbnailLeftStyle(mouseLeftOffset, thumbnailsHolder);
}
static upadateOnHover(progressControl,
thumbnailsHolder,
thumbnailClips,
timelineTime,
thumbnailImg,
player) {
// update the thumbnail while hovering
progressControl.on('mousemove', (event) => {
ThumbnailHelpers.moveListener(event,
progressControl,
thumbnailsHolder,
thumbnailClips,
timelineTime,
thumbnailImg,
player);
});
progressControl.on('touchmove', (event) => {
ThumbnailHelpers.moveListener(event,
progressControl,
thumbnailsHolder,
thumbnailClips,
timelineTime,
thumbnailImg);
});
}
static hideThumbnail(thumbnailsHolder) {
thumbnailsHolder.style.left = '-1000px';
}
static upadateOnHoverOut(progressControl, thumbnailsHolder, player) {
// move the placeholder out of the way when not hovering
progressControl.on('mouseout', (event) => {
ThumbnailHelpers.hideThumbnail(thumbnailsHolder);
});
progressControl.on('touchcancel', (event) => {
ThumbnailHelpers.hideThumbnail(thumbnailsHolder);
});
progressControl.on('touchend', (event) => {
ThumbnailHelpers.hideThumbnail(thumbnailsHolder);
});
player.on('userinactive', (event) => {
ThumbnailHelpers.hideThumbnail(thumbnailsHolder);
});
}
}
|
const duplicateIRIs = [
["Krakken/Dronning Maud Land", [901165, 901163]],
["Selbukta/Dronning Maud Land", [903220, 901896]],
["Smalegga/Dronning Maud Land", [902045, 902044]],
["Snøfugldalen/Dronning Maud Land", [903182, 903183]],
["Veten/Dronning Maud Land", [902450, 902449]],
["Vindegga/Dronning Maud Land", [903166, 902461]],
["Alkekongen/Svalbard", [186, 187]],
["Ankerbreen/Svalbard", [319, 320]],
["Barentsburg/Svalbard", [733, 734]],
["Baugen/Svalbard", [797, 798]],
["Blomstrandhalvøya/Svalbard", [1303, 1304]],
["Bogen/Svalbard", [1379, 1378]],
["Bohemanflya/Svalbard", [1388, 1389]],
["Bommen/Svalbard", [1421, 1422]],
["Bukkebreen/Svalbard", [1764, 1765]],
["Båtkvelvet/Svalbard", [1859, 1860]],
["Colesbukta/Svalbard", [2378, 2379]],
["Daudmannsøyra/Svalbard", [2615, 2616]],
["De Geerfjellet/Svalbard", [2655, 2654]],
["Dokka/Svalbard", [2918, 2917]],
["Drevfjellet/Svalbard", [3013, 3012]],
["Eggbreen/Svalbard", [3240, 3241]],
["Einstøingen/Svalbard", [3285, 3286]],
["Erta/Svalbard", [3474, 3475]],
["Flatholmen/Svalbard", [3769, 3768]],
["Flykollen/Svalbard", [3842, 3843]],
["Fonndalen/Svalbard", [3896, 3897]],
["Gravodden/Svalbard", [4820, 4819]],
["Gruvedalen/Svalbard", [5003, 5004]],
["Grynet/Svalbard", [5012, 5011]],
["Gråkallen/Svalbard", [5080, 5081]],
["Haugen/Svalbard", [5400, 5399]],
["Hettebreen/Svalbard", [5618, 5619]],
["Holken/Svalbard", [5737, 5738]],
["Huldrehatten/Svalbard", [5946, 5947]],
["Håkjerringa/Svalbard", [6107, 6108]],
["Isbjørnodden/Svalbard", [6354, 6353]],
["Iskollbreen/Svalbard", [6399, 6400]],
["Iskollen/Svalbard", [6402, 6403]],
["Isungen/Svalbard", [6470, 6469]],
["Isvatnet/Svalbard", [6472, 6471]],
["Kambreen/Svalbard", [6744, 6743]],
["Kamtinden/Svalbard", [6754, 6753]],
["Kappfjellet/Svalbard", [7029, 7030]],
["Keipbreen/Svalbard", [7097, 7098]],
["Keipen/Svalbard", [7099, 7100]],
["Kjetta/Svalbard", [7229, 7230]],
["Kjølen/Svalbard", [7241, 7240]],
["Kloa/Svalbard", [7286, 7287]],
["Kloten/Svalbard", [7316, 7315]],
["Kluftvatnet/Svalbard", [7333, 7332]],
["Knekten/Svalbard", [7381, 7380]],
["Kolfjellet/Svalbard", [7473, 7474]],
["Konglomeratodden/Svalbard", [7544, 7543]],
["Krokryggen/Svalbard", [7694, 7693]],
["Krylen/Svalbard", [7766, 7767]],
["Langen/Svalbard", [8138, 8137]],
["Libreen/Svalbard", [8353, 8354]],
["Munken/Svalbard", [10072, 10073]],
["Nordkapp/Svalbard", [10501, 10500]],
["Osten/Svalbard", [10911, 10910]],
["Passnuten/Svalbard", [11071, 11072]],
["Paxbreen/Svalbard", [11090, 11091]],
["Pilten/Svalbard", [11244, 11243]],
["Plogbreen/Svalbard", [11313, 11314]],
["Proppen/Svalbard", [11536, 11535]],
["Pyramiden/Svalbard", [11652, 11653, 11651]],
["Rakryggen/Svalbard", [11734, 11733]],
["Ratjørna/Svalbard", [11768, 11769]],
["Revdalen/Svalbard", [11981, 11980]],
["Ruggen/Svalbard", [12259, 12260]],
["Russekeila/Svalbard", [12329, 12330]],
["Sillhøgda/Svalbard", [12986, 12987]],
["Skaftet/Svalbard", [13046, 13045]],
["Skolten/Svalbard", [13197, 13196]],
["Skålvatnet/Svalbard", [13280, 13279]],
["Snippen/Svalbard", [13441, 13440]],
["Snøkuven/Svalbard", [13466, 13467]],
["Stuptinden/Svalbard", [14085, 14086]],
["Stuttdalen/Svalbard", [14091, 14092]],
["Sukkertoppen/Svalbard", [14123, 14122]],
["Svansen/Svalbard", [14181, 14182]],
["Sylen/Svalbard", [14404, 14405]],
["Syningen/Svalbard", [14412, 14413]],
["Sørhytta/Svalbard", [14550, 14549]],
["Teistpynten/Svalbard", [14709, 14708]],
["Toppbreen/Svalbard", [14982, 14983]],
["Torellmorenen/Svalbard", [15008, 15007]],
["Tovikbukta/Svalbard", [15045, 15046]],
["Trehyrningen/Svalbard", [15083, 15082]],
["Tverrdalen/Svalbard", [15287, 15286]],
["Utstikkaren/Svalbard", [15471, 15470]],
["Vrakbukta/Svalbard", [16025, 16024]],
["Ytstekollen/Svalbard", [16459, 16460]]
];
export const duplicateMap = new Map(duplicateIRIs);
export const getIdents = ({ name, area }, map = duplicateMap) =>
map.get(`${name}/${area}`);
// This will only report current/known duplicates (no good as test for new name!)
export const isUnique = ({ name, area }, map = duplicateMap) =>
!map.has(`${name}/${area}`);
|
//~ name c406
alert(c406);
//~ component c407.js
|
const oss = require('../..');
const cluster = require('../..').ClusterClient;
const config = require('../config').oss;
const utils = require('./utils');
const assert = require('assert');
const mm = require('mm');
describe('test/cluster.test.js', () => {
const { prefix } = utils;
afterEach(mm.restore);
before(async function () {
this.region = config.region;
this.bucket1 = `ali-oss-test-cluster1-${prefix.replace(/[/.]/g, '')}`;
this.bucket2 = `ali-oss-test-cluster2-${prefix.replace(/[/.]/g, '')}`;
const client = oss(config);
await client.putBucket(this.bucket1);
await client.putBucket(this.bucket2);
});
before(function (done) {
const options = {
cluster: [
{
accessKeyId: config.accessKeyId,
accessKeySecret: config.accessKeySecret,
bucket: this.bucket1,
endpoint: config.endpoint
},
{
accessKeyId: config.accessKeyId,
accessKeySecret: config.accessKeySecret,
bucket: this.bucket2,
endpoint: config.endpoint
}
]
};
this.store = cluster(options);
this.store.on('error', (err) => {
if (err.name === 'MockError' || err.name === 'CheckAvailableError') {
return;
}
console.error(err.stack);
});
this.store.ready(done);
});
after(async function () {
await utils.cleanBucket(this.store.clients[0], this.bucket1);
await utils.cleanBucket(this.store.clients[1], this.bucket2);
this.store.close();
});
describe('init', () => {
it('require options.cluster to be an array', () => {
(function () {
cluster({});
}).should.throw('require options.cluster to be an array');
});
it('should _init() _checkAvailable throw error', function (done) {
this.store.once('error', (err) => {
err.message.should.equal('mock error');
done();
});
mm.error(this.store, '_checkAvailable', 'mock error');
this.store._init();
});
it('should skip put status file when ignoreStatusFile is set', async function () {
mm.error(this.store, 'put', 'mock error');
await this.store._checkAvailable(true);
});
});
describe('put()', () => {
it('should add object with local file path', async function () {
const name = `${prefix}ali-sdk/oss/put-localfile.js`;
const object = await this.store.put(name, __filename);
assert.equal(typeof object.res.headers['x-oss-request-id'], 'string');
assert.equal(typeof object.res.rt, 'number');
assert.equal(object.res.size, 0);
assert(object.name, name);
});
it('should error when any one is error', async function () {
mm.error(this.store.clients[1], 'put', 'mock error');
const name = `${prefix}ali-sdk/oss/put-localfile.js`;
try {
await this.store.put(name, __filename);
throw new Error('should never exec');
} catch (err) {
err.message.should.equal('mock error');
}
});
it('should ignore when any one is error', async function () {
mm.error(this.store.clients[1], 'put', 'mock error');
const name = `${prefix}ali-sdk/oss/put-localfile.js`;
try {
await this.store.put(name, __filename);
throw new Error('should never exec');
} catch (err) {
err.message.should.equal('mock error');
}
});
});
describe('putACL() and getACL()', () => {
it('should add object with local file path', async function () {
const name = `${prefix}ali-sdk/oss/put-localfile.js`;
const object = await this.store.put(name, __filename);
assert.equal(typeof object.res.headers['x-oss-request-id'], 'string');
assert.equal(typeof object.res.rt, 'number');
assert.equal(object.res.size, 0);
assert(object.name, name);
let res = await this.store.getACL(name);
assert.equal(res.acl, 'default');
await this.store.putACL(name, 'public-read');
res = await this.store.getACL(name);
assert.equal(res.acl, 'public-read');
});
});
describe('get()', () => {
before(async function () {
this.name = `${prefix}ali-sdk/oss/get-meta.js`;
const object = await this.store.put(this.name, __filename, {
meta: {
uid: 1,
pid: '123',
slus: 'test.html'
}
});
assert.equal(typeof object.res.headers['x-oss-request-id'], 'string');
this.headers = object.res.headers;
});
it('should RR get from clients ok', async function () {
mm(this.store.clients[1], 'get', async () => {
throw new Error('mock error');
});
function onerror(err) {
throw err;
}
this.store.on('error', onerror);
let res = await this.store.get(this.name);
res.res.status.should.equal(200);
mm.restore();
mm(this.store.clients[0], 'get', async () => {
throw new Error('mock error');
});
res = await this.store.get(this.name);
res.res.status.should.equal(200);
this.store.removeListener('error', onerror);
});
it('should RR get from clients[1] when clients[0] not available', async function () {
this.store.index = 0;
mm(this.store.availables, '0', false);
mm.data(this.store.clients[0], 'get', 'foo');
let r = await this.store.get(this.name);
r.res.status.should.equal(200);
this.store.index.should.equal(0);
// again should work
r = await this.store.get(this.name);
r.res.status.should.equal(200);
this.store.index.should.equal(0);
});
it('should RR get from clients[1] when clients[0] error ok', async function () {
this.store.index = 0;
mm.error(this.store.clients[0], 'get', 'mock error');
let r = await this.store.get(this.name);
r.res.status.should.equal(200);
this.store.index.should.equal(1);
// again should work
r = await this.store.get(this.name);
r.res.status.should.equal(200);
this.store.index.should.equal(0);
});
it('should RR get from clients[0] when clients[1] not available', async function () {
this.store.index = 0;
mm(this.store.availables, '1', false);
mm.data(this.store.clients[1], 'get', 'foo');
let r = await this.store.get(this.name);
r.res.status.should.equal(200);
this.store.index.should.equal(1);
// again should work
r = await this.store.get(this.name);
r.res.status.should.equal(200);
this.store.index.should.equal(1);
});
it('should RR get from clients[0] when clients[1] error ok', async function () {
this.store.index = 0;
mm.error(this.store.clients[1], 'get', 'mock error');
let r = await this.store.get(this.name);
r.res.status.should.equal(200);
this.store.index.should.equal(1);
// again should work
r = await this.store.get(this.name);
r.res.status.should.equal(200);
this.store.index.should.equal(0);
});
it('should MS always get from clients[0] ok', async function () {
mm(this.store, 'schedule', 'masterSlave');
mm(this.store.clients[1], 'get', 'mock error');
function onerror() {
throw new Error('should not emit error event');
}
this.store.on('error', onerror);
let res = await this.store.get(this.name);
res.res.status.should.equal(200);
res = await this.store.get(this.name);
res.res.status.should.equal(200);
this.store.removeListener('error', onerror);
});
it('should MS always get from clients[0] when masterOnly === true', async function () {
mm(this.store, 'schedule', 'masterSlave');
mm(this.store, 'masterOnly', true);
mm(this.store.clients[1], 'get', 'mock error');
function onerror() {
throw new Error('should not emit error event');
}
this.store.on('error', onerror);
let res = await this.store.get(this.name);
res.res.status.should.equal(200);
res = await this.store.get(this.name);
res.res.status.should.equal(200);
this.store.removeListener('error', onerror);
});
it('should get from clients[0] when clients[0] response 4xx ok', async function () {
mm(this.store, 'schedule', 'masterSlave');
mm.error(this.store.clients[0], 'get', 'mock error', { status: 403 });
try {
await this.store.get(this.name);
throw new Error('should never exec');
} catch (err) {
err.status.should.equal(403);
}
});
it('should RR error when clients all down', async function () {
mm.error(this.store.clients[0], 'get', 'mock error');
mm.error(this.store.clients[1], 'get', 'mock error');
try {
await this.store.get(this.name);
throw new Error('should never exec');
} catch (err) {
err.name.should.equal('MockError');
err.message.should.equal('mock error (all clients are down)');
}
});
it('should MS error when clients all down', async function () {
mm(this.store, 'schedule', 'masterSlave');
mm.error(this.store.clients[0], 'get', 'mock error');
mm.error(this.store.clients[1], 'get', 'mock error');
try {
await this.store.get(this.name);
throw new Error('should never exec');
} catch (err) {
err.name.should.equal('MockError');
err.message.should.equal('mock error (all clients are down)');
}
});
it('should RR throw error when read err status >= 200 && < 500', async function () {
mm(this.store.clients[0], 'get', async () => {
const err = new Error('mock error');
throw err;
});
mm(this.store.clients[1], 'get', async () => {
const err = new Error('mock 302 error');
err.status = 302;
throw err;
});
this.store.index = 0;
try {
await this.store.get(this.name);
throw new Error('should not run this');
} catch (err) {
err.status.should.equal(302);
}
mm(this.store.clients[0], 'get', async () => {
const err = new Error('mock 404 error');
err.status = 404;
throw err;
});
mm(this.store.clients[1], 'get', async () => {
const err = new Error('mock error');
throw err;
});
this.store.index = 1;
try {
await this.store.get(this.name);
throw new Error('should not run this');
} catch (err) {
err.status.should.equal(404);
}
});
it('should RR use the first client when all server down', async function () {
mm(this.store.availables, '0', false);
mm(this.store.availables, '1', false);
this.store.index = 0;
await this.store.get(this.name);
this.store.index = 1;
await this.store.get(this.name);
});
});
describe('signatureUrl(), getObjectUrl()', () => {
before(async function () {
this.name = `${prefix}ali-sdk/oss/get-meta.js`;
const object = await this.store.put(this.name, __filename, {
meta: {
uid: 1,
pid: '123',
slus: 'test.html'
}
});
assert.equal(typeof object.res.headers['x-oss-request-id'], 'string');
this.headers = object.res.headers;
});
it('should get object cdn url', function () {
const url = this.store.getObjectUrl(this.name);
assert(/\.aliyuncs\.com\//.test(url), url);
assert(/\/ali-sdk\/oss\/get-meta\.js$/.test(url), url);
const cdnurl = this.store.getObjectUrl(this.name, 'https://foo.com');
assert(/^https:\/\/foo\.com\//.test(cdnurl), cdnurl);
assert(/\/ali-sdk\/oss\/get-meta\.js$/.test(cdnurl), cdnurl);
});
it('should RR signatureUrl from clients ok', function () {
mm(this.store.clients[1], 'head', 'mock error');
let url = this.store.signatureUrl(this.name);
url.should.match(/ali-sdk\/oss\/get-meta\.js/);
mm.restore();
mm(this.store.clients[0], 'head', 'mock error');
url = this.store.signatureUrl(this.name);
url.should.match(/ali-sdk\/oss\/get-meta\.js/);
});
it('should RR signature from clients[1] when clients[0] error ok', function () {
const url = this.store.signatureUrl(this.name);
url.should.match(/ali-sdk\/oss\/get-meta\.js/);
});
it('should MS always signature from clients[0] ok', function () {
mm(this.store, 'schedule', 'masterSlave');
mm(this.store.clients[1], 'head', 'mock error');
let url = this.store.signatureUrl(this.name);
url.should.match(/ali-sdk\/oss\/get-meta\.js/);
url = this.store.signatureUrl(this.name);
url.should.match(/ali-sdk\/oss\/get-meta\.js/);
});
it('should signature from clients[0] when clients[0] response 4xx ok', function () {
mm(this.store, 'schedule', 'masterSlave');
mm.error(this.store.clients[0], 'head', 'mock error', { status: 403 });
const url = this.store.signatureUrl(this.name);
url.should.match(/ali-sdk\/oss\/get-meta\.js/);
});
it('should signature ok when clients all down', function () {
mm.error(this.store.clients[0], 'head', 'mock error');
mm.error(this.store.clients[1], 'head', 'mock error');
const url = this.store.signatureUrl(this.name);
url.should.match(/ali-sdk\/oss\/get-meta\.js/);
});
it('should RR use the first client when all server down', function () {
mm(this.store.availables, '0', false);
mm(this.store.availables, '1', false);
this.store.index = 0;
let url = this.store.signatureUrl(this.name);
url.should.match(/ali-sdk\/oss\/get-meta\.js/);
this.store.index = 1;
url = this.store.signatureUrl(this.name);
url.should.match(/ali-sdk\/oss\/get-meta\.js/);
});
it('should masterSlave use the first client when all server down', function () {
mm(this.store, 'schedule', 'masterSlave');
mm(this.store.availables, '0', false);
mm(this.store.availables, '1', false);
this.store.index = 0;
let url = this.store.signatureUrl(this.name);
url.should.match(/ali-sdk\/oss\/get-meta\.js/);
this.store.index = 1;
url = this.store.signatureUrl(this.name);
url.should.match(/ali-sdk\/oss\/get-meta\.js/);
});
});
describe('_checkAvailable()', () => {
it('should write status file on the first check', async function () {
await this.store._checkAvailable(true);
this.store.availables['0'].should.equal(true);
this.store.availables['1'].should.equal(true);
});
it('should write status pass', async function () {
await this.store._checkAvailable();
this.store.availables['0'].should.equal(true);
this.store.availables['1'].should.equal(true);
});
it('should available on err status 404', async function () {
mm(this.store.clients[0], 'head', async () => {
const err = new Error('mock 404 error');
err.status = 404;
throw err;
});
mm(this.store.clients[1], 'head', async () => {
const err = new Error('mock 300 error');
err.status = 300;
throw err;
});
await this.store._checkAvailable();
this.store.availables['0'].should.equal(true);
this.store.availables['1'].should.equal(true);
});
it('should not available on err status < 200 or >= 500', async function () {
mm(this.store.clients[0], 'head', async () => {
const err = new Error('mock -1 error');
err.status = -1;
throw err;
});
mm(this.store.clients[1], 'head', async () => {
const err = new Error('mock 500 error');
err.status = 500;
throw err;
});
await this.store._checkAvailable();
this.store.availables['0'].should.equal(false);
this.store.availables['1'].should.equal(false);
});
it('should available on error count < 3', async function () {
// client[0] error 2 times
let count = 0;
mm(this.store.clients[0], 'head', async (name) => {
count++;
if (count === 3) {
return { name };
}
throw new Error('mock error');
});
await this.store._checkAvailable();
this.store.availables['0'].should.equal(true);
this.store.availables['1'].should.equal(true);
count.should.equal(3);
mm.restore();
// client[1] error 1 times
count = 0;
mm(this.store.clients[1], 'head', async (name) => {
count++;
if (count === 2) {
return { name };
}
throw new Error('mock error');
});
await this.store._checkAvailable();
this.store.availables['0'].should.equal(true);
this.store.availables['1'].should.equal(true);
count.should.equal(2);
});
it('should try 3 times on check status fail', async function () {
// client[0] error
mm.error(this.store.clients[0], 'head', 'mock error');
await this.store._checkAvailable();
this.store.availables['0'].should.equal(false);
this.store.availables['1'].should.equal(true);
mm.restore();
// client[1] error
mm.error(this.store.clients[1], 'head', 'mock error');
await this.store._checkAvailable();
this.store.availables['0'].should.equal(true);
this.store.availables['1'].should.equal(false);
mm.restore();
// all down
mm.error(this.store.clients[0], 'head', 'mock error');
mm.error(this.store.clients[1], 'head', 'mock error');
await this.store._checkAvailable();
this.store.availables['0'].should.equal(false);
this.store.availables['1'].should.equal(false);
mm.restore();
// recover
await this.store._checkAvailable();
this.store.availables['0'].should.equal(true);
this.store.availables['1'].should.equal(true);
});
});
});
|
var productsTable = $('#products-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ 'visible': false, 'targets': 7 },
{ "type": "html-num-fmt", "targets": 3 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#products-table tbody').removeClass("d-none");
productsTable.columns.adjust().draw();
$("#search").on("keyup", Delay(function()
{
var value = $(this).val();
if (value === "all")
{
value = "";
}
productsTable.search(value).draw();
}, 200));
$("#product-group-filter").on("change", function()
{
var value = $("#product-group-filter option:selected").text();
if (value === __t("All"))
{
value = "";
}
productsTable.column(productsTable.colReorder.transpose(6)).search(value).draw();
});
$("#clear-filter-button").on("click", function()
{
$("#search").val("");
$("#product-group-filter").val("all");
productsTable.column(productsTable.colReorder.transpose(6)).search("").draw();
productsTable.search("").draw();
if ($("#show-disabled").is(":checked") || $("#show-only-in-stock").is(":checked"))
{
$("#show-disabled").prop("checked", false);
$("#show-only-in-stock").prop("checked", false);
RemoveUriParam("include_disabled");
RemoveUriParam("only_in_stock");
window.location.reload();
}
});
if (typeof GetUriParam("product-group") !== "undefined")
{
$("#product-group-filter").val(GetUriParam("product-group"));
$("#product-group-filter").trigger("change");
}
$(document).on('click', '.product-delete-button', function(e)
{
var objectName = $(e.currentTarget).attr('data-product-name');
var objectId = $(e.currentTarget).attr('data-product-id');
bootbox.confirm({
message: __t('Are you sure to delete product "%s"?', objectName) + '<br><br>' + __t('This also removes any stock amount, the journal and all other references of this product - consider disabling it instead, if you want to keep that and just hide the product.'),
closeButton: false,
buttons: {
confirm: {
label: __t('Yes'),
className: 'btn-success'
},
cancel: {
label: __t('No'),
className: 'btn-danger'
}
},
callback: function(result)
{
if (result === true)
{
jsonData = {};
jsonData.active = 0;
Grocy.Api.Delete('objects/products/' + objectId, {},
function(result)
{
window.location.href = U('/products');
},
function(xhr)
{
console.error(xhr);
}
);
}
}
});
});
$("#show-disabled").change(function()
{
if (this.checked)
{
UpdateUriParam("include_disabled", "true");
}
else
{
RemoveUriParam("include_disabled");
}
window.location.reload();
});
$("#show-only-in-stock").change(function()
{
if (this.checked)
{
UpdateUriParam("only_in_stock", "true");
}
else
{
RemoveUriParam("only_in_stock");
}
window.location.reload();
});
if (GetUriParam('include_disabled'))
{
$("#show-disabled").prop('checked', true);
}
$(".merge-products-button").on("click", function(e)
{
var productId = $(e.currentTarget).attr("data-product-id");
$("#merge-products-keep").val(productId);
$("#merge-products-remove").val("");
$("#merge-products-modal").modal("show");
});
$("#merge-products-save-button").on("click", function()
{
var productIdToKeep = $("#merge-products-keep").val();
var productIdToRemove = $("#merge-products-remove").val();
Grocy.Api.Post("stock/products/" + productIdToKeep.toString() + "/merge/" + productIdToRemove.toString(), {},
function(result)
{
window.location.href = U('/products');
},
function(xhr)
{
Grocy.FrontendHelpers.ShowGenericError('Error while merging', xhr.response);
}
);
});
|
// All symbols in the Latin-1 Supplement block as per Unicode v9.0.0:
[
'\x80',
'\x81',
'\x82',
'\x83',
'\x84',
'\x85',
'\x86',
'\x87',
'\x88',
'\x89',
'\x8A',
'\x8B',
'\x8C',
'\x8D',
'\x8E',
'\x8F',
'\x90',
'\x91',
'\x92',
'\x93',
'\x94',
'\x95',
'\x96',
'\x97',
'\x98',
'\x99',
'\x9A',
'\x9B',
'\x9C',
'\x9D',
'\x9E',
'\x9F',
'\xA0',
'\xA1',
'\xA2',
'\xA3',
'\xA4',
'\xA5',
'\xA6',
'\xA7',
'\xA8',
'\xA9',
'\xAA',
'\xAB',
'\xAC',
'\xAD',
'\xAE',
'\xAF',
'\xB0',
'\xB1',
'\xB2',
'\xB3',
'\xB4',
'\xB5',
'\xB6',
'\xB7',
'\xB8',
'\xB9',
'\xBA',
'\xBB',
'\xBC',
'\xBD',
'\xBE',
'\xBF',
'\xC0',
'\xC1',
'\xC2',
'\xC3',
'\xC4',
'\xC5',
'\xC6',
'\xC7',
'\xC8',
'\xC9',
'\xCA',
'\xCB',
'\xCC',
'\xCD',
'\xCE',
'\xCF',
'\xD0',
'\xD1',
'\xD2',
'\xD3',
'\xD4',
'\xD5',
'\xD6',
'\xD7',
'\xD8',
'\xD9',
'\xDA',
'\xDB',
'\xDC',
'\xDD',
'\xDE',
'\xDF',
'\xE0',
'\xE1',
'\xE2',
'\xE3',
'\xE4',
'\xE5',
'\xE6',
'\xE7',
'\xE8',
'\xE9',
'\xEA',
'\xEB',
'\xEC',
'\xED',
'\xEE',
'\xEF',
'\xF0',
'\xF1',
'\xF2',
'\xF3',
'\xF4',
'\xF5',
'\xF6',
'\xF7',
'\xF8',
'\xF9',
'\xFA',
'\xFB',
'\xFC',
'\xFD',
'\xFE',
'\xFF'
]; |
process.env.NODE_ENV = 'production';
var app = require('../yoline');
var assert = require('assert');
var request = require('supertest').agent(app.listen());
describe('Test 404', () => {
var url = '/' + Math.floor(Math.random() * 1000);
describe('when GET ' + url, function(){
it('should return the 404 page', (done) => {
request
.get(url)
.expect(404)
.expect(/Not Found/, done);
});
});
});
describe('Test index page', function(){
describe('when GET /', function(){
it('should have two post', function(done){
request
.get('/')
.expect(200)
.expect(function(res){
assert.equal(/<strong>2<\/strong> posts/.test(res.text), true, 'should say there are two posts');
})
.end(done);
});
});
});
describe('Test post page', function(){
describe('when GET /post/11-02-16', function(){
it('should template with first article', function(done){
request
.get('/post/11-02-16')
.expect(200)
.expect(function(res){
assert.equal(/<h1>Learn Memory Static<\/h1>/.test(res.text), true, 'should say the title');
assert.equal(/<span class="time">Thursday, February 11th 2016<\/span>/.test(res.text), true, 'should say the date');
})
.end(done);
});
});
});
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define({enter:"\u041f\u043e\u043b\u043d\u043e\u044d\u043a\u0440\u0430\u043d\u043d\u044b\u0439 \u0440\u0435\u0436\u0438\u043c",exit:"\u0412\u044b\u0439\u0442\u0438 \u0438\u0437 \u043f\u043e\u043b\u043d\u043e\u044d\u043a\u0440\u0430\u043d\u043d\u043e\u0433\u043e \u0440\u0435\u0436\u0438\u043c\u0430"}); |
import React from 'react';
import PropTypes from 'prop-types';
class ModalCover extends React.Component {
onClick(e) {
e.preventDefault();
if (this.props.dismissible && this.props.dismissFunc) {
this.props.dismissFunc.call(null);
}
}
render() {
let coverClass = ['rh-modal-cover'];
if (this.props.dismissible) {
coverClass.push('dismissible');
}
if(!this.props.visible) {
coverClass.push('hidden')
}
return <div className={coverClass.join(' ')}
onClick={this.props.dismissFunc}>
</div>;
}
}
ModalCover.defaultProps = {
dismissible: false,
dismissFunc: () => {
},
visible : true
};
ModalCover.propTypes = {
dismissible: PropTypes.bool,
dismissFunc: PropTypes.func,
visible : PropTypes.bool
};
export default ModalCover; |
"use strict";
var eventEmitter = new (require('events')).EventEmitter();
eventEmitter.all = function(events, callback) {
function onEvent(event) {
eventEmitter.on(events[event], function() {
events.splice(events.indexOf(event), 1);
if (events.length === 0) {
callback();
}
});
}
for (var ev in events) {
if (events.hasOwnProperty(ev)) {
onEvent(ev);
}
}
};
eventEmitter.any = function(events, callback) {
function onEvent(event) {
eventEmitter.on(events[event], function() {
if (events !== null) {
callback();
}
events = null;
});
}
for (var ev in events) {
if (events.hasOwnProperty(ev)) {
onEvent(ev);
}
}
};
module.exports = eventEmitter; |
'use strict';
var fs = require('fs');
var userConfig = JSON.parse(fs.readFileSync('user.config.json', 'utf8')),
packageInfo = JSON.parse(fs.readFileSync('package.json', 'utf8'));
module.exports = {
app: {
title: 'scheduleR',
description: 'schedule R scripts',
keywords: 'R, scheduling'
},
appVersion: packageInfo.version,
runRscript: 'R/run_rscript.R',
runRmarkdown: 'R/run_rmarkdown.R',
runShiny: 'R/run_shiny_app.R',
userConfig: userConfig,
port: process.env.PORT || 3000,
templateEngine: 'swig',
sessionSecret: 'MEAN',
sessionCollection: 'sessions',
assets: {
lib: {
css: [
// 'public/lib/bootstrap/dist/css/bootstrap.css',
// 'public/lib/bootstrap/dist/css/bootstrap-theme.css',
'public/lib/bootswatch-dist/css/bootstrap.css',
'public/lib/bootswatch-dist/css/bootstrap-theme.css'
],
js: [
'public/lib/ng-file-upload/angular-file-upload-shim.js',
'public/lib/angular/angular.js',
'public/lib/ng-file-upload/angular-file-upload.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
'public/lib/later/later.min.js',
'public/lib/underscore/underscore-min.js'
]
},
css: [
'public/modules/**/css/*.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
};
|
import {
FETCH_SEARCH,
LOAD_SEARCH_RESULTS,
CLEAR_SEARCH,
FETCH_SELECTED_ARTICLE,
LOAD_SELECTED_ARTICLE,
} from './constants'
export function fetchSearch({ searchText }){
return {
type: FETCH_SEARCH,
payload: {
searchText,
},
}
}
export function clearSearch(){
return {
type: CLEAR_SEARCH,
}
}
export function loadSearchResults({ results }){
return {
type: LOAD_SEARCH_RESULTS,
payload: {
articles: results,
},
}
}
export function fetchSelectedArticle({ DOI, source }){
return {
type: FETCH_SELECTED_ARTICLE,
payload: {
DOI,
source,
},
}
}
export function loadSelectedArticle(){
return {
type: LOAD_SELECTED_ARTICLE,
}
}
|
/*!
* gulp-rte <https://github.com/jonschlinkert/gulp-rte>
*
* Copyright (c) 2014 Jon Schlinkert
* Licensed under the MIT license.
*/
'use strict';
var path = require('path');
var gutil = require('gulp-util');
var expect = require('chai').expect;
var rte = require('..');
describe('rte dest routing', function () {
it('should route dest files using the given patterns.', function (done) {
var stream = rte();
var expected = new gutil.File({
cwd: './',
base: 'test/fixtures',
path: 'test/fixtures/faux.js',
contents: null
});
stream.once('data', function (file) {
expect(file.path).to.equal('test/fixtures/faux.js');
done();
});
stream.write(expected);
stream.end();
});
it('should route dest files using the given patterns.', function (done) {
var stream = rte(':basename:ext');
var expected = new gutil.File({
cwd: './',
base: 'test/fixtures',
path: 'test/fixtures/faux.js',
contents: null
});
stream.once('data', function (file) {
var basename = path.basename(file.path);
expect(basename).to.equal('faux.js');
done();
});
stream.write(expected);
stream.end();
});
it('should route dest files using the given patterns.', function (done) {
var stream = rte(':basename.min.js');
var expected = new gutil.File({
cwd: './',
base: 'test/fixtures',
path: 'test/fixtures/faux.js',
contents: null
});
stream.once('data', function (file) {
var basename = path.basename(file.path);
expect(basename).to.equal('faux.min.js');
done();
});
stream.write(expected);
stream.end();
});
it('should route dest files using the given patterns.', function (done) {
var stream = rte(':dist/:basename:ext', {
dist: '_gh_pages'
});
var expected = new gutil.File({
cwd: './',
base: 'test/fixtures',
path: 'test/fixtures/faux.js',
contents: null
});
stream.once('data', function (file) {
expect(file.path).to.equal('test/fixtures/_gh_pages/faux.js');
done();
});
stream.write(expected);
stream.end();
});
it('should use an arbitrary non-prop string in the dest', function (done) {
var stream = rte('foo/:dist/:basename:ext', {
dist: '_gh_pages'
});
var expected = new gutil.File({
cwd: './',
base: 'test/fixtures',
path: 'test/fixtures/faux.js',
contents: null
});
stream.once('data', function (file) {
expect(file.path).to.equal('test/fixtures/foo/_gh_pages/faux.js');
done();
});
stream.write(expected);
stream.end();
});
it('should use an arbitrary non-prop string in the dest', function (done) {
var stream = rte('out-fixtures/:basename:ext');
var expected = new gutil.File({
cwd: './',
base: 'test/fixtures',
path: 'test/fixtures/faux.js',
contents: null
});
stream.once('data', function (file) {
expect(file.path).to.equal('test/fixtures/out-fixtures/faux.js');
done();
});
stream.write(expected);
stream.end();
});
it('should pass through writes with cwd', function (done) {
var stream = rte('out-fixtures/:basename:ext');
var expected = new gutil.File({
cwd: './',
base: 'test/fixtures',
path: 'test/fixtures/test.coffee',
contents: null
});
stream.once('data', function (file) {
expect(file.path).to.equal('test/fixtures/out-fixtures/test.coffee');
done();
});
stream.write(expected);
stream.end();
});
it('should use arbitrary properties defined in the options', function (done) {
var stream = rte(':a/:b/:c/:basename:ext', {a: 'one', b: 'two', c: 'three'});
var expected = new gutil.File({
cwd: './',
base: 'test/fixtures',
path: 'test/fixtures/test.coffee',
contents: null
});
stream.once('data', function (file) {
expect(file.path).to.equal('test/fixtures/one/two/three/test.coffee');
done();
});
stream.write(expected);
stream.end();
});
it('should use custom parsers defined on `options.parsers`', function (done) {
var stream = rte('dist/{a}/index{b}', {
parsers: [{
'{a}': function () {
return this.basename;
},
'{b}': function () {
return '.min.js';
}
}]
});
var expected = new gutil.File({
cwd: './',
base: 'foo/bar',
path: 'foo/bar/baz.coffee',
contents: null
});
stream.once('data', function (file) {
expect(file.path).to.equal('foo/bar/dist/baz/index.min.js');
done();
});
stream.write(expected);
stream.end();
});
}); |
// Tally Votes in JavaScript Pairing Challenge.
// I worked on this challenge with: Miqueas Hernandez
// This challenge took me [#] hours.
// These are the votes cast by each student. Do not alter these objects here.
var votes = {
"Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
"Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
"Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
"Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
"Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
"Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
"Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
"Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
"Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
"John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
"Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
"Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
"Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
"Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
"Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
"Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
"Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
"Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
"Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
"Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
"Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
"Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
"Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
"Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
"Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
"Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}
// Tally the votes in voteCount.
var voteCount = {
president: {},
vicePresident: {},
secretary: {},
treasurer: {}
}
/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount. After Alex's votes have been tallied,
voteCount would be ...
var voteCount = {
president: { Bob: 1 },
vicePresident: { Devin: 1 },
secretary: { Gail: 1 },
treasurer: { Kerry: 1 }
}
*/
/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
president: undefined,
vicePresident: undefined,
secretary: undefined,
treasurer: undefined
}
// Pseudocode
// 1. Create a function that iterates over the votes object and pushes vote count tally into voteCount object
// a. Include a nested loop that will iterate over each object property in order to pass tests
// 2. Create a second function that iterates over voteCount nested objects and finds the max numbers of votes for each object property and returns those names
// 3. (winnning) names are assigned to officers object properties
// __________________________________________
// Initial Solution
// voteCount
for (var person in votes){
for (var i in votes[person]){
var a =votes[person][i]
if(voteCount[i][a]===undefined){
voteCount[i][a]=0
}
voteCount[i][a]+=1;
}
}
// winner
// president
var pres = [];
for (var votes in voteCount['president']){
// console.log(voteCount['president'][votes]);
pres.push(voteCount['president'][votes])
}
var winner = Math.max.apply(null, pres);
for (var votes in voteCount['president']){
// console.log(voteCount['president'][votes])
if(voteCount['president'][votes] === winner){
officers['president'] = votes
}
}
// VP
var vice = [];
for (var votes in voteCount['vicePresident']){
// console.log(voteCount['vicePresident'][votes]);
pres.push(voteCount['vicePresident'][votes])
}
var viceWin = Math.max.apply(null, pres);
for (var votes in voteCount['vicePresident']){
// console.log(voteCount['vicePresident'][votes])
if(voteCount['vicePresident'][votes] === viceWin){
officers['vicePresident'] = votes
}
}
// secretary
var sec = [];
for (var votes in voteCount['secretary']){
// console.log(voteCount['secretary'][votes]);
pres.push(voteCount['secretary'][votes])
}
var secWin = Math.max.apply(null, pres);
for (var votes in voteCount['secretary']){
// console.log(voteCount['secretary'][votes])
if(voteCount['secretary'][votes] === secWin){
officers['secretary'] = votes
}
}
// secretary
var tre = [];
for (var votes in voteCount['treasurer']){
// console.log(voteCount['treasurer'][votes]);
pres.push(voteCount['treasurer'][votes])
}
var treWin = Math.max.apply(null, pres);
for (var votes in voteCount['treasurer']){
// console.log(voteCount['treasurer'][votes])
if(voteCount['treasurer'][votes] === treWin){
officers['treasurer'] = votes
}
}
// __________________________________________
// Refactored Solution
// voteCount
for (var person in votes){
for (var i in votes[person]){
var a =votes[person][i]
if(voteCount[i][a]===undefined){
voteCount[i][a]=0
}
voteCount[i][a]+=1;
}
}
// winner
for (var votes in voteCount){
var winner = 0;
for (var person in voteCount[votes]){
if (voteCount[votes][person] > winner){
winner = voteCount[votes][person];
officers[votes] = person;
}
}
}
// __________________________________________
// Reflection
/*
1)What did you learn about iterating over nested objects in JavaScript?
It is a very challenging exercise and am not sure if I fully understand it but since my partner was good we were able to get most of it.
2)Were you able to find useful methods to help you with this?
Not really but while searching, I saw how .apply() works along with Math.max.apply() to get the maximum of an array in javascript.
3)What concepts were solidified in the process of working through this challenge?
I think nothing. I gothered that I don't know most of the things about javascript.
*/
// __________________________________________
// Test Code: Do not alter code below this line.
function assert(test, message, test_number) {
if (!test) {
console.log(test_number + "false");
throw "ERROR: " + message;
}
console.log(test_number + "true");
return true;
}
assert(
(voteCount.president["Bob"] === 3),
"Bob should receive three votes for President.",
"1. "
)
assert(
(voteCount.vicePresident["Bob"] === 2),
"Bob should receive two votes for Vice President.",
"2. "
)
assert(
(voteCount.secretary["Bob"] === 2),
"Bob should receive two votes for Secretary.",
"3. "
)
assert(
(voteCount.treasurer["Bob"] === 4),
"Bob should receive four votes for Treasurer.",
"4. "
)
assert(
(officers.president === "Louise"),
"Louise should be elected President.",
"5. "
)
assert(
(officers.vicePresident === "Hermann"),
"Hermann should be elected Vice President.",
"6. "
)
assert(
(officers.secretary === "Fred"),
"Fred should be elected Secretary.",
"7. "
)
assert(
(officers.treasurer === "Ivy"),
"Ivy should be elected Treasurer.",
"8. "
) |
import React from 'react';
import PropTypes from 'prop-types';
import {default as Component} from '../Common/plugs/index.js'; //提供style, classname方法
import '../Common/css/Button.css';
import '../Common/css/Icon.css';
export default class Button extends Component {
onClick(e) {
if (this.props.onClick) {
this.props.onClick(e);
}
}
render() {
return (
<button
style={this.style()}
className={this.className('ishow-button', this.props.type && `ishow-button--${this.props.type}`, this.props.size && `ishow-button--${this.props.size}`, {
'is-disabled': this.props.disabled,
'is-loading': this.props.loading,
'is-plain': this.props.plain
})}
disabled={this.props.disabled}
type={this.props.nativeType}
onClick={this.onClick.bind(this)}>
{ this.props.loading && <i className="ishow-icon-loading" /> }
{ this.props.icon && !this.props.loading && <i className={`ishow-icon-${this.props.icon}`} /> }
<span>{this.props.children}</span>
</button>
)
}
}
Button.propTypes = {
onClick: PropTypes.func,
type: PropTypes.string,
size: PropTypes.string,
icon: PropTypes.string,
nativeType: PropTypes.string,
loading: PropTypes.bool,
disabled: PropTypes.bool,
plain: PropTypes.bool
}
Button.defaultProps = {
type: 'default',
nativeType: 'button',
loading: false,
disabled: false,
plain: false
};
|
var webpack = require('webpack');
var __DEV__ = JSON.parse(process.env.BUILD_DEV || 'false');
var __PROD__ = JSON.parse(process.env.BUILD_PROD || 'false');
var baseConfig = {
entry: {
background: './src/js/background',
contentscript: './src/js/contentscript',
popup: './src/js/popup'
},
output: {
filename: '[name].bundle.js',
path: './app/build/js/'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader']
}
]
},
plugins: [
new webpack.NoErrorsPlugin()
]
};
if (__DEV__) {
baseConfig['devtool'] = 'cheap-module-source-map';
}
module.exports = baseConfig; |
module.exports = {
plugins: ["@typescript-eslint", "import", "prettier"],
parser: "@typescript-eslint/parser",
extends: [
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking",
"plugin:import/typescript",
"plugin:prettier/recommended", // Must be last
],
rules: {
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/ban-ts-comment.md
"@typescript-eslint/ban-ts-comment": [
"error",
{
"ts-expect-error": "allow-with-description",
"ts-ignore": true,
"ts-nocheck": true,
"ts-check": true,
},
],
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/consistent-type-assertions.md
"@typescript-eslint/consistent-type-assertions": [
"error",
{
assertionStyle: "as",
objectLiteralTypeAssertions: "allow-as-parameter",
},
],
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/explicit-member-accessibility.md
"@typescript-eslint/explicit-member-accessibility": "error",
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/no-base-to-string.md
"@typescript-eslint/no-base-to-string": [
"error",
{ ignoredTypeNames: ["RegExp"] },
],
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/no-confusing-non-null-assertion.md
"@typescript-eslint/no-confusing-non-null-assertion": "error",
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/no-implicit-any-catch.md
"@typescript-eslint/no-implicit-any-catch": [
"error",
{ allowExplicitAny: false },
],
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/no-invalid-void-type.md
"@typescript-eslint/no-invalid-void-type": [
"error",
{
allowInGenericTypeArguments: true,
allowAsThisParameter: true,
},
],
// Set to match `@ndhoule/eslint-config/recommended` configuration
//
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/no-unused-vars.md
"@typescript-eslint/no-unused-vars": [
"error",
{ args: "after-used", argsIgnorePattern: "^_" },
],
// Empty interfaces are often useful for module interfaces you expect to
// grow over time, like program arguments, React props, etc.
//
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/no-empty-interface.md
"@typescript-eslint/no-empty-interface": "off",
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/no-meaningless-void-operator.md
"@typescript-eslint/no-meaningless-void-operator": [
"error",
{ checkNever: false },
],
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/no-non-null-asserted-nullish-coalescing.md
"@typescript-eslint/no-non-null-asserted-nullish-coalescing": "error",
// Restrict `throw` to Error objects
//
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/no-throw-literal.md
"@typescript-eslint/no-throw-literal": "error",
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/no-unnecessary-condition.md
"@typescript-eslint/no-unnecessary-condition": [
"error",
{
allowConstantLoopConditions: true,
},
],
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/no-unsafe-argument.md
"@typescript-eslint/no-unsafe-argument": "error",
// Prohibit empty class constructors
//
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/no-useless-constructor.md
"no-useless-constructor": "off",
"@typescript-eslint/no-useless-constructor": ["error"],
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/non-nullable-type-assertion-style.md
"@typescript-eslint/non-nullable-type-assertion-style": "error",
// Prohibit casting the initial value in Array#reduce calls (a very common
// antipattern).
//
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/prefer-reduce-type-parameter.md
"@typescript-eslint/prefer-reduce-type-parameter": "error",
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/prefer-for-of.md
"@typescript-eslint/prefer-for-of": "error",
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/prefer-enum-initializers.md
"@typescript-eslint/prefer-enum-initializers": "error",
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/prefer-nullish-coalescing.md
"@typescript-eslint/prefer-nullish-coalescing": "error",
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/prefer-optional-chain.md
"@typescript-eslint/prefer-optional-chain": "error",
// Require functions capable of returning a promise to be marked as `async`.
// Helps to improve stylistic consistency and to avoid functions that can
// return both a promise and a non-promise value (e.g. in a conditional).
//
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/promise-function-async.md
"@typescript-eslint/promise-function-async": "error",
// This rule is set in `@typescript-eslint/eslint-recommended`; by default,
// that configuration allows the use of numbers in template expressions.
// However, one of the most--if not *the* most--common reasons for
// converting a number to a string is to show it to a user. In this
// scenario, consistency in string formatting is key: when displaying money,
// you generally either want to consistently show cents or not, and you may
// or may not want to round numbers (or round them to a fixed precision).
// Allowing numbers in template strings without calling attention to their
// formatting is a footgun, so here we prohibit it, knowing that the
// worse-case alternative is not bad (forcing users to call `toString()` on
// their number).
//
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/restrict-template-expressions.md
"@typescript-eslint/restrict-template-expressions": [
"error",
{
allowNumber: false,
allowBoolean: false,
allowAny: false,
allowNullish: false,
},
],
// Prohibit `return await` (see `recommended` configuration for details).
//
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/return-await.md
"no-return-await": "off",
"@typescript-eslint/return-await": "error",
// Disallow non-boolean values in boolean expressions (comparisons to a
// boolean, conditionals in ternaries/if/while/etc.)
//
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/strict-boolean-expressions.md
"@typescript-eslint/strict-boolean-expressions": "error",
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/switch-exhaustiveness-check.md
"@typescript-eslint/switch-exhaustiveness-check": "error",
// https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/docs/rules/unified-signatures.md
"@typescript-eslint/unified-signatures": "error",
// The way Zapatos outputs this built schema file isn't compatible with how
// `import/no-unresolved` resolves files. This doesn't particularly matter,
// anyway; if the schema is unresolvable then `tsc` will fail.
"import/no-unresolved": ["error", { ignore: ["^zapatos/schema$"] }],
},
};
|
const debug = require("debug")("decoder:test:receive-test");
const assert = require("chai").assert;
const Ganache = require("ganache-core");
const path = require("path");
const Web3 = require("web3");
const Decoder = require("../../..");
const { prepareContracts } = require("../../helpers");
describe("Non-function transactions", function() {
let provider;
let abstractions;
let compilations;
let web3;
let Contracts;
before("Create Provider", async function () {
provider = Ganache.provider({seed: "decoder", gasLimit: 7000000});
web3 = new Web3(provider);
});
before("Prepare contracts and artifacts", async function () {
this.timeout(30000);
const prepared = await prepareContracts(provider, path.resolve(__dirname, ".."));
abstractions = prepared.abstractions;
compilations = prepared.compilations;
Contracts = [
abstractions.ReceiveTest,
abstractions.FallbackTest,
];
});
it("should decode transactions that invoke fallback or receive", async function() {
let receiveTest = await abstractions.ReceiveTest.deployed();
let fallbackTest = await abstractions.FallbackTest.deployed();
const decoder = await Decoder.forProject(web3.currentProvider, Contracts);
let receiveHash = (await receiveTest.send(1)).tx;
let fallbackNoDataHash = (await fallbackTest.send(1)).tx;
let fallbackDataHash = (await receiveTest.sendTransaction({
to: receiveTest.address,
data: "0xdeadbeef"
})).tx;
let receiveTx = await web3.eth.getTransaction(receiveHash);
let fallbackNoDataTx = await web3.eth.getTransaction(fallbackNoDataHash);
let fallbackDataTx = await web3.eth.getTransaction(fallbackDataHash);
let receiveDecoding = await decoder.decodeTransaction(receiveTx);
let fallbackNoDataDecoding = await decoder.decodeTransaction(
fallbackNoDataTx
);
let fallbackDataDecoding = await decoder.decodeTransaction(fallbackDataTx);
assert.strictEqual(receiveDecoding.kind, "message");
assert.strictEqual(receiveDecoding.class.typeName, "ReceiveTest");
assert.strictEqual(receiveDecoding.data, "0x");
assert.strictEqual(receiveDecoding.abi.type, "receive");
assert.strictEqual(fallbackNoDataDecoding.kind, "message");
assert.strictEqual(fallbackNoDataDecoding.class.typeName, "FallbackTest");
assert.strictEqual(fallbackNoDataDecoding.data, "0x");
assert.strictEqual(fallbackNoDataDecoding.abi.type, "fallback");
assert.strictEqual(fallbackDataDecoding.kind, "message");
assert.strictEqual(fallbackDataDecoding.class.typeName, "ReceiveTest");
assert.strictEqual(fallbackDataDecoding.data, "0xdeadbeef");
assert.strictEqual(fallbackDataDecoding.abi.type, "fallback");
});
});
|
'use strict';
const periodic = require('periodicjs');
// let reactapp = periodic.locals.extensions.get('periodicjs.ext.reactapp').reactapp();
const reactappLocals = periodic.locals.extensions.get('periodicjs.ext.reactapp');
const reactapp = reactappLocals.reactapp();
const userRoleForm = (options = {}) => reactappLocals.server_manifest.forms.createForm({
method: (options.update) ? 'PUT' : 'POST',
action: (options.update)
? `${reactapp.manifest_prefix}contentdata/standard_userroles/:id?format=json`
: `${reactapp.manifest_prefix}contentdata/standard_userroles?format=json`,
onSubmit:'closeModal',
onComplete: 'refresh',
// loadingScreen: true,
style: {
paddingTop:'1rem',
},
hiddenFields: [
],
validations: [
{
field: 'title',
constraints: {
presence: {
message: '^Please provide a title',
},
},
},
{
field: 'userroleid',
constraints: {
presence: {
message: '^Please provide a user role id',
},
},
},
],
rows: [
{
formElements: [
{
type: 'text',
// placeholder:'Title',
label:'Title',
name:'title',
},
{
type: 'text',
passProps: {
type:'number',
},
label:'User Role ID',
name:'userroleid',
},
],
},
{
formElements: [
{
type: 'text',
name: 'description',
label: 'Description',
// passProps: {
// // multiple:true,
// },
},
],
},
{
formElements: [
{
type: 'datalist',
name: 'privileges',
label: 'Privileges',
datalist: {
multi: true,
// selector: '_id',
entity:'standard_userprivilege',
resourceUrl:`${reactapp.manifest_prefix}contentdata/standard_userprivileges?format=json`
}
// passProps: {
// // multiple:true,
// },
},
],
},
{
formElements: [
{
type: 'submit',
value: (options.update) ? 'Update User Role' : 'Add User Role',
layoutProps: {
style: {
textAlign:'center',
},
},
},
],
},
],
actionParams: (options.update)
? [
{
key: ':id',
val: '_id',
},
]
: undefined,
// hiddenFields
asyncprops: (options.update)
? {
formdata: [ 'userroledata', 'data' ],
}
: {},
});
const uacSettings = periodic.settings.extensions[ 'periodicjs.ext.user_access_control' ];
module.exports = {
containers: (uacSettings.use_manifests)
? {
[ `${reactapp.manifest_prefix}ext/uac/manage-roles` ]: {
layout: {
component: 'Container',
props: {
style: {
padding: '6rem 0',
},
},
children: [
reactappLocals.server_manifest.helpers.getPageTitle({
styles: {
// ui: {}
},
title: 'Manage User Roles',
action: {
type: 'modal',
title: 'Add User Role',
pathname: `${reactapp.manifest_prefix}add-userrole`,
buttonProps: {
props: {
color: 'isSuccess',
},
},
},
}),
reactappLocals.server_manifest.table.getTable({
schemaName: 'standard_userroles',
baseUrl: `${reactapp.manifest_prefix}contentdata/standard_userroles?format=json`,
asyncdataprops: 'userroles',
headers: [
{
buttons: [
{
passProps: {
onClick: 'func:this.props.createModal',
onclickThisProp: 'onclickPropObject',
onclickProps: {
title: 'Edit User Role',
pathname: `${reactapp.manifest_prefix}edit-userrole/:id`,
params: [
{
key: ':id',
val: '_id',
}
],
},
buttonProps: {
color: 'isInfo',
buttonStyle: 'isOutlined',
icon: 'fa fa-pencil',
},
},
}
],
sortid: '_id',
sortable: true,
label: 'ID',
},
{
sortable: true,
sortid: 'name',
label: 'Name',
},
{
sortable: true,
sortid: 'description',
label: 'Description',
headerStyle: {
maxWidth: 200,
overflow: 'hidden',
textOverflow: 'ellipsis',
},
columnStyle: {
maxWidth: 200,
overflow: 'hidden',
textOverflow: 'ellipsis',
},
},
{
sortable: true,
sortid: 'userroleid',
label: 'User Role ID',
},
{
sortable: true,
sortid: 'privileges',
label: 'Privileges',
customCellLayout: {
component: 'DynamicLayout',
// ignoreReduxProps:true,
thisprops: {
items: [ 'cell' ],
},
bindprops: true,
props: {
style: {
display: 'block'
},
layout: {
bindprops: true,
component: 'Tag',
props: {
color: 'isDark',
style: {
margin: '0.25rem'
}
},
children: [
{
bindprops: true,
component: 'span',
thisprops: {
_children: [ 'name' ]
}
},
{
component: 'span',
children: ' (',
},
{
bindprops: true,
component: 'span',
thisprops: {
_children: [ 'userprivilegeid' ]
}
},
{
component: 'span',
children: ')',
},
]
}
}
},
},
],
}),
],
},
resources: {
userroles: `${reactapp.manifest_prefix}contentdata/standard_userroles?format=json`,
},
pageData: {
title: 'Manage User Roles',
},
},
[ `${reactapp.manifest_prefix}add-userrole` ]: {
layout: {
component: 'Content',
children: [ userRoleForm(), ],
},
resources: {},
pageData: {
title: 'Add a User Role',
},
},
[ `${reactapp.manifest_prefix}edit-userrole/:id` ]: {
layout: {
component: 'Content',
children: [ userRoleForm({ update: true, }), ],
},
resources: {
userroledata: `${reactapp.manifest_prefix}contentdata/standard_userroles/:id?format=json`,
},
pageData: {
title: 'Add a User Role',
},
},
}
: {},
}; |
import Ember from "ember";
export default Ember.ArrayController.extend({
needs: ['project'],
projectController: Ember.computed.alias("controllers.project"),
initialize: function() {
//console.log(this.get('model'));
console.log('testing');
console.log(this.get('model'));
var maps = this.get('model').content;
if( maps && maps.length > 0 ) {
this.set('selectedMap', maps[0].get('id'));
}
}.observes('model'),
selectedMap: '',
mapChanged: function() {
var selectedMap = this.selectedMap;
if( !selectedMap ) {
// Try to set the default
var maps = this.get('content');
if( maps.length > 0 ) {
//console.log(maps[0]);
this.set('selectedMap', maps[0]);
}
}else {
//console.log(selectedMap);
this.transitionToRoute('map',selectedMap);
}
}.observes('selectedMap'),
newName: '',
newDescription: '',
isPage1Valid: function() {
return true;
}.property('newName'),
actions: {
save: function() {
var projectId = this.get('projectController').get('model').get('id');
var newMap = this.store.createRecord('map', {
name: this.get('newName'),
description: this.get('newDescription'),
image: '',
steps: [],
project: projectId
});
newMap.save();
// reset the form fields
this.set('newName','');
this.set('newDescription','');
var controller = this;
}
}
});
|
'use strict';
// this is necessary due to a change in node-fetch that no longer supports require
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
var _ = require('lodash'),
Q = require('q'),
utf8 = require('utf8'),
validator = require('validator');
/**
* StopForumSpam Module
* @exports stopforumspam
* @namespace sfs
*/
var sfs = {
/**
* Default Configuration settings for stopforumspam
*/
config: {
url: 'http://stopforumspam.com',
routes: [{
name: 'search',
path: '/api?f=json&nobadusername' // ignore partial username string search
},{
name: 'submit',
path: '/add.php?api_key=%s'
}],
searchParameters: [{
name: 'ip',
searchAdd: '&ip=%s',
submitAdd: '&ip_addr=%s'
},{
name: 'email',
searchAdd: '&email=%s',
submitAdd: '&email=%s'
},{
name: 'username',
searchAdd: '&username=%s',
submitAdd: '&username=%s'
}],
apiKey: ''
}
};
/**
* Checks if a user is a spammer. Pass only the parameters you wish to search for
* @param userObject {object} a hashlike object with each of the parameters to search for.
* Search for as many or as few as you wish.
* @example
* stopforumspam.isSpammer({ ip: '123.456.789.100', email: 'test@test.com', username: 'Spammer!' })
* .then(function (result) {
* // result if false if not found
* // result = {
* // success: 1,
* // username: {
* // lastseen: '2015-03-09 15:22:49',
* // frequency: 3830,
* // appears: 1,
* // confidence: 90.2 } }
* });
* @returns Promise which returns true if the user is found on StopForumSpam.com
* @throws throws an error if the email or IP is passed and invalid or the IP is not IPv4.
* Stopforumsspam.com does not support IPv6 addresses.
* @throws throws any error it recieves from the response, including status codes that are not 200
*/
sfs.isSpammer = function (userObject) {
var deferred = Q.defer();
var url = sfs.config.url + _.find(sfs.config.routes, { name: 'search' }).path;
var fail = false;
_.each(sfs.config.searchParameters, function (parameter) {
if (userObject[parameter.name]) {
if (parameter.name === 'email' && userObject[parameter.name] && !validator.isEmail(userObject[parameter.name])) {
fail = 'email';
}
else if (parameter.name === 'ip' && userObject[parameter.name] && !validator.isIP(userObject[parameter.name], 4)) {
fail = 'ip';
}
url += parameter.searchAdd.replace('%s', encodeURIComponent(utf8.encode(userObject[parameter.name])));
}
});
if (fail) {
if (fail === 'email') {
deferred.reject(new Error('The searched email is not a valid email address'));
}
else if (fail === 'ip') {
deferred.reject(new Error('The searched IP is not a valid IPv4 address'));
}
}
else {
fetch(url)
.then((response) => {
if (response.status !== 200) {
return deferred.reject(new Error('Response Status: ' + response.statusCode));
}
return response.json();
})
.then((jsBody) => {
var result = false;
_.each(sfs.config.searchParameters, function (parameter) {
if (userObject[parameter.name] && jsBody[parameter.name].appears > 0) {
result = jsBody;
}
});
deferred.resolve(result);
}).catch((error) => {
return deferred.reject(error);
});
}
return deferred.promise;
};
/**
* Synchronous version of isSpammer
* Uses ES6 yield trick https://github.com/luciotato/waitfor-ES6#the-funny-thing-is
*/
sfs.isSpammerSync = function* (userObject) {
yield [sfs.isSpammer, userObject];
};
/**
* Submits the user to StopForumSpam.com under your API key
* Requires config.apiKey is set
* @param userObject must contain properties for each searchParameter
* empty parameters will throw an error
* @example
* stopforumspam.Key('some-api-key');
* // or stopforumspam.config.apiKey = 'some-api-key';
* stopforumspam.submit({ ip: '123.456.789.100', email: 'test@test.com', username: 'Spammer!' }, 'Caught You!');
* @param evidence {string} (optional) you can tell StopForumSpam.com your reasoning if you like
* @returns Promise
* @throws throws an error if you have not set the API key
* @throws throws an error if you don't pass a user object with all of the parameters
* (ip, email, & username)
* @throws throws any error it recieves from the response, including status codes that are not 200
*/
sfs.submit = function (userObject, evidence) {
var deferred = Q.defer();
if (!sfs.config.apiKey) {
deferred.reject(new Error('You cannot submit spammers without an API Key.'));
}
else {
var url = sfs.config.url + _.find(sfs.config.routes, { name: 'submit' }).path.replace('%s', sfs.config.apiKey);
var error = false;
_.each(sfs.config.searchParameters, function (parameter) {
if (!userObject[parameter.name]) {
error = true;
}
else {
url += parameter.searchAdd.replace('%s', encodeURIComponent(utf8.encode(userObject[parameter.name])));
}
});
if (error) {
deferred.reject(new Error('You must have all search parameters for StopForumSpam.com to accept your submission.'));
}
else {
if (evidence) {
// unescape in JS is a simple way to convert to UTF-8, which StopForumSpam requires
url += `&evidence=${encodeURIComponent(utf8.encode(evidence))}`;
}
fetch(url)
.then((response) => {
if (response.status !== 200) { return deferred.reject(new Error('Response Status: ' + response.statusCode)); }
deferred.resolve();
}).catch((error) => {
return deferred.reject(error);
});
}
}
return deferred.promise;
};
/**
* Synchronous version of submit
* Uses ES6 yield trick https://github.com/luciotato/waitfor-ES6#the-funny-thing-is
*/
sfs.submitSync = function* (userObject, evidence) {
yield [sfs.submit, userObject, evidence];
};
/**
* Creates a user object to utilize the APi in a more human manner
* @memberOf sfs
* @namespace User
* @param ip {string} the IP address of the user
* @param email {string} the email address of the user
* @param username {string} the username of the user
* @throws throws an error if the email or IP is passed and invalid or the IP is not IPv4.
* Stopforumsspam.com does not support IPv6 addresses.
*/
sfs.User = function (ip, email, username) {
if (email && !validator.isEmail(email)) {
throw new Error('The email address is not a valid email address');
}
if (ip && !validator.isIP(ip, 4)) {
throw new Error('The IP address is not a valid IPv4 address');
}
return {
ip: ip,
email: email,
username: username
};
};
/**
* The User object implements isSpammer
* @example
* var sfsUser = stopforumspam.User('123.456.789.100', 'test@test.com', 'Spammer!');
* sfsUser.isSpammer().then(function (result) {
* // do something with result
* });
*/
sfs.User.prototype.isSpammer = function () {
return sfs.isSpammer(this);
};
/**
* The User object implements isSpammerSync
*/
sfs.User.prototype.isSpammerSync = function* () {
yield [this.isSpammer];
};
/**
* The User object implements submit
* @example
* var sfsUser = stopforumspam.User('123.456.789.100', 'test@test.com', 'Spammer!');
* sfsUser.submit();
*/
sfs.User.prototype.submit = function (evidence) {
return sfs.submit(this, evidence);
};
/**
* The User object implements submitSync
*/
sfs.User.prototype.submitSync = function* (evidence) {
yield [this.submit, evidence];
};
/**
* Getter & Setter for the API Key
* @param key {string} The API Key for StopForumSpam.com Necessary for
* submitting users to the database. Unset it with an empty string or false.
* @returns {string} The current API Key as it is set
*/
sfs.Key = function(key) {
if (key !== undefined) {
sfs.config.apiKey = key;
}
return sfs.config.apiKey;
};
module.exports = sfs;
|
/**
* The "grunt-promise" NPM module.
*
* The MIT License (MIT)
* Copyright (c) 2016 Mark Halliwell
*
* @module module:grunt-promise
*/
(function (exports, native) {
'use strict';
var grunt = require('grunt');
var util = require('./lib/util');
/**
* Determines if an object is "thenable" (aka. Promise object).
*
* An object must have a "then" function or method for it to be considered
* "thenable".
*
* @param {Object|Function} Obj
* An object or function.
* @param {Boolean} [create]
* Flag indicating whether this method should attempt to create a new
* Promise and check for a "then" method.
*
* @return {Boolean}
* TRUE or FALSE
*
* @see https://promisesaplus.com/#point-7
*/
exports.isThenable = function (Obj, create) {
return util.isThenable.apply(util, [Obj, create]);
};
/**
* Loads a Promise library/object.
*
* @deprecated since v1.1.0.
*
* @return {object<Promise>|function<Promise>|Boolean}
* A Promise object or FALSE if unable to load.
*
* @see exports.using
*/
exports.load = util.deprecate(function () {
return exports.using.apply(this, arguments);
}, 'The grunt-promise "load" method is deprecated and has been renamed to "using".');
/**
* Loads a Promise library/object.
*
* @param {String|Function|Object} [library]
* The name of the Promise API library/node module to load. It can
* also be a callback to execute. If left empty, it will attempt to find
* the first available NPM package node module installed.
*
* @return {object<Promise>|function<Promise>|Boolean}
* A Promise object or FALSE if unable to load.
*/
exports.using = function (library) {
var Promise;
// Allow a library to be specified as an option on the CLI.
if (!library) {
library = grunt.option('grunt-promise-library');
}
// Immediately return if there is already a Promise object loaded and no
// specific library was specified by the user.
if (!library && util.current) {
return util.current;
}
// Allow an explicit Promise library/module to be used.
if (library) {
Promise = util.getPromise(library);
if (!Promise) {
util.fail(library);
}
return Promise;
}
// Attempt to dynamically load first available supported promise object.
util.supportedModules.forEach(function (name) {
Promise = Promise || util.getPromise(name);
});
if (!Promise) {
if (library) {
util.fail(library);
}
else {
if (!util.loaded.native) {
util.fail();
}
Promise = util.loaded.native;
}
}
// Cache the currently loaded Promise object.
util.current = Promise;
return Promise;
};
/**
* Registers a new promise based Grunt task.
*
* @param {string} name
* The name of the Grunt task to register.
* @param {string|function} [info]
* (Optional) Descriptive text explaining what the task does. Shows up on
* `--help`. You may omit this argument and replace it with `fn` instead.
* @param {function} [fn]
* (Required) The task function. Remember not to pass in your Promise
* function directly. Promise resolvers are immediately invoked when they
* are created. You should wrap the Promise with an anonymous task function
* instead.
*
* @memberOf grunt
*
* @return {object}
* The task object.
*/
grunt.registerPromise = function (name, info, fn) {
return grunt.registerTask.apply(grunt.task, util.parseArgs(name, info, fn));
};
/**
* Registers a new promise based Grunt multi-task.
*
* @param {string} name
* The name of the Grunt task to register.
* @param {string|function} [info]
* (Optional) Descriptive text explaining what the task does. Shows up on
* `--help`. You may omit this argument and replace it with `fn` instead.
* @param {function} [fn]
* (Required) The task function. Remember not to pass in your Promise
* function directly. Promise resolvers are immediately invoked when they
* are created. You should wrap the Promise with an anonymous task function
* instead.
*
* @memberOf grunt
*
* @return {object}
* The task object.
*/
grunt.registerMultiPromise = function (name, info, fn) {
return grunt.registerMultiTask.apply(grunt.task, util.parseArgs(name, info, fn));
};
})(module.exports, Promise && Promise.toString() === 'function Promise() { [native code] }' && Promise);
|
twoToTheNth = function(n) {
var solutionString = "2";
for (var counter = 1; counter < n; counter++) {
solutionString = addStrings(solutionString, solutionString);
}
return solutionString;
}
addStrings = function(string1, string2) {
var carry = [];
var topNumber = string1;
var bottomNumber = string2;
var solution = [];
if (parseInt(string1) < parseInt(string2)) {
topNumber = string2;
bottomNumber = string1;
}
for (var counter = 1; counter <= topNumber.length; counter++) {
var nextNumber = parseInt(topNumber[topNumber.length - counter]);
if (parseInt(bottomNumber[bottomNumber.length - counter])) {
nextNumber += parseInt(bottomNumber[bottomNumber.length - counter]);
}
if (carry[0]) {
nextNumber += parseInt(carry[0]);
}
if (nextNumber > 9 && counter < topNumber.length) {
carry[0] = nextNumber.toString()[0];
solution.push(nextNumber.toString()[1]);
} else {
carry = [];
solution.push(nextNumber.toString());
}
}
return solution.reverse().join('');
}
var bigNumber = twoToTheNth(1000);
var sumOfDigits = 0;
for (var counter = 0; counter < bigNumber.length; counter++) {
sumOfDigits += parseInt(bigNumber[counter]);
}
console.log(sumOfDigits);
|
var THREE = require('three'); //threejs不用import方式 是不想webpack 出打包警告提示
var TWEEN = require('tween.js');
import { TrackballControls } from './TrackballControls';
import { WWOBJLoader2 } from './WWOBJLoader2';
import { Octree } from './Octree';
var ZipTools = (function() {
function ZipTools(path, vue) {
this.zip = new JSZip();
this.vue = vue;
this.fileLoader = new THREE.FileLoader();
this.fileLoader.setPath(path);
this.fileLoader.setResponseType('arraybuffer');
this.zipContent = null;
}
ZipTools.prototype.load = function(filename, callbacks) {
var scope = this;
var onSuccess = function(zipDataFromFileLoader) {
scope.zip.loadAsync(zipDataFromFileLoader)
.then(function(zip) {
scope.zipContent = zip;
callbacks.success();
});
};
var refPercentComplete = 0;
var percentComplete = 0;
var output;
var onProgress = (event) => {
if (!event.lengthComputable) return;
percentComplete = Math.round(event.loaded / event.total * 100);
if (percentComplete > refPercentComplete) {
refPercentComplete = percentComplete;
output = '正在下载 "' + filename + '": ' + percentComplete + '%';
this.vue.handProcess(output)
// console.log(output);
if (Boolean(callbacks.progress)) callbacks.progress(output);
}
};
var onError = function(event) {
var output = 'Error of type "' + event.type + '" occurred when trying to load: ' + filename;
console.error(output);
callbacks.error(output);
};
this.vue.handProcess(`开始下载${filename}`)
this.fileLoader.load(filename, onSuccess, onProgress, onError);
};
ZipTools.prototype.unpackAsUint8Array = function(filename, callback) {
if (JSZip.support.uint8array) {
this.zipContent.file(filename).async('uint8array')
.then(function(dataAsUint8Array) {
callback(dataAsUint8Array);
});
} else {
this.zipContent.file(filename).async('base64')
.then(function(data64) {
callback(new TextEncoder('utf-8').encode(data64));
});
}
};
ZipTools.prototype.unpackAsString = function(filename, callback) {
this.zipContent.file(filename).async('string')
.then(function(dataAsString) {
callback(dataAsString);
});
};
return ZipTools;
})();
/**
* threeview class
* @class
*/
class Three {
constructor(canvas, w, h, vue) {
this.vue = vue;
//基础属性
this.canvas = canvas;
this.camera = null;
this.controls = null;
this.scene = null;
this.width = w;
this.height = h;
this.aspectRatio = w / h;
this.cameraDefaults = {
posCamera: new THREE.Vector3(0.0, 175.0, 500.0),
posCameraTarget: new THREE.Vector3(0, 0, 0),
near: 0.1,
far: 10000,
fov: 45
};
this.cameraTarget = this.cameraDefaults.posCameraTarget;
//鼠标点击相关属性
this.raycaster = null;
this.mouse = null;
this.selectModels = [];
this.visibleModels = [];
this.isShift = false; //是否多选
this.isOpacity = true;
this.isFollow = true;
this.isSelectColor = false;
this.renderer = null;
this.pinObj3D = new THREE.Object3D();
this.pinObj3D.name = 'pin';
this.mouseMaterialDefault = new THREE.MeshPhongMaterial({
color: 0xadf1a7,
// specular: 0x009900,
// shininess: 30,
// wireframe:true,
// wireframeLinewidth:10,
// flatShading: true
});
//模型相关
this.wwObjLoader2 = new WWOBJLoader2();
this.wwObjLoader2.setCrossOrigin('anonymous');
this.octree;
this.boundMax=null;
this.boundNow=null;
this.loadCounter = 0;
this.objs2Load = [];
this.allAssets = [];
//loading
this.processing = false;
this.loadCallback = null;
//clip
this.clipPlanes = [
new THREE.Plane(new THREE.Vector3(1, 0, 0), 0),
new THREE.Plane(new THREE.Vector3(0, -1, 0), 0),
new THREE.Plane(new THREE.Vector3(0, 0, -1), 0)
];
this.clipParams = {
clipIntersection: false,
planeConstant: 0,
showHelpers: false
};
this.init();
//事件监听
window.addEventListener('resize',this.resizeDisplayGL.bind(this),false)
// this.animate();
}
init() {
this.camera = new THREE.PerspectiveCamera(this.cameraDefaults.fov, this.aspectRatio, this.cameraDefaults.near, this.cameraDefaults.far);
this.resetCamera();
// world
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0xffffff);
// this.scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
//坐标轴辅助
var helper = new THREE.GridHelper(1200, 10, 0xFF4444, 0x404040);
this.scene.add(helper);
// light
var light = new THREE.DirectionalLight(0xffffff);
light.position.set(1, 1, 1);
this.scene.add(light);
// var light = new THREE.DirectionalLight(0x002288);
// light.position.set(-1, -1, -1);
// this.scene.add(light);
var light = new THREE.AmbientLight(0x222222);
this.scene.add(light);
// create octree
this.octree = new Octree({
// when undeferred = true, objects are inserted immediately
// instead of being deferred until next octree.update() call
// this may decrease performance as it forces a matrix update
undeferred: false,
// set the max depth of tree
depthMax: Infinity,
// max number of objects before nodes split or merge
objectsThreshold: 8,
// percent between 0 and 1 that nodes will overlap each other
// helps insert objects that lie over more than one node
overlapPct: 0.15
// pass the scene to visualize the octree
});
//鼠标移动相关操作
var geometry = new THREE.CylinderGeometry(0, 20, 100, 3);
geometry.translate(0, -50, 0);
geometry.scale(0.1, 0.1, 0.1);
geometry.rotateX(-Math.PI / 2);
this.helper = new THREE.Mesh(geometry, new THREE.MeshNormalMaterial());
this.helper.visible = false;
this.scene.add(this.helper);
this.raycaster = new THREE.Raycaster();
this.mouse = new THREE.Vector2();
// renderer
this.renderer = new THREE.WebGLRenderer({ antialias: true, canvas: this.canvas, autoClear: true });
// this.renderer.clippingPlanes = this.clipPlanes;
// this.renderer.setPixelRatio( window.devicePixelRatio );
this.renderer.setSize(this.width, this.height);
this.renderer.localClippingEnabled = true;
// this.container = document.getElementById( 'container' );
// this.container.appendChild( renderer.domElement );
// this.container.appendChild( stats.dom );
//
//
this.controls = new THREE.TrackballControls(this.camera, this.canvas);
}
/**
* canvasHandleClick - 模型点击事件 todo:if 太多需要优化
*
* @param {type} event description
* @return {type} description
*/
canvasHandleClick(event) {
if (this.mouseupTime - this.mousedownTime > 500) { //优化视角操作不触发点击模型
return;
}
event.preventDefault();
//canvas坐标-webgl坐标
let x = (event.offsetX / this.canvas.width) * 2 - 1;
let y = -(event.offsetY / this.canvas.height) * 2 + 1;
this.mouse.x = x;
this.mouse.y = y;
this.raycaster.setFromCamera(this.mouse, this.camera);
let meshesSearch = this.octree.search(this.raycaster.ray.origin, this.raycaster.ray.far, true, this.raycaster.ray.direction);
// let intersections = this.raycaster.intersectObjects( this.objs2Load[0].pivot.children );
let intersections = this.raycaster.intersectOctreeObjects(meshesSearch);
//
if (intersections.length > 0) {
intersections.sort((a, b) => { //先排序
return a.distance - b.distance;
});
if (this.isShift) { //是否按住shift多选
let select;
for (let i = 0; i < intersections.length; i++) {
if (this.boundNow.containsPoint(intersections[i].point)) {
select=intersections[i];
for (let item of this.selectModels) {
if (item == select.object) {
return;
}
}
select.object.currenMaterial = select.object.material;
if (this.isSelectColor) {
select.object.material = this.mouseMaterialDefault;
} else {
if(select.object.material instanceof Array){
select.object.material = select.object.material
}
else{
select.object.material = select.object.material.clone();
}
}
this.selectModels.push(select.object);
if (this.isFollow) {
this.animateClick(this.controls.object.position, this.controls.target, select)
}
}
}
} else {
this.selectModels.forEach((item) => {
item.material = item.currenMaterial;//还原材质
});
let select;
for (let i = 0; i < intersections.length; i++) { //判断是否被切面
if (this.boundNow.containsPoint(intersections[i].point)) {
select = intersections[i];
this.selectModels = [];
select.object.currenMaterial = select.object.material;
if (this.isSelectColor) {
select.object.material = this.mouseMaterialDefault;
} else {
if(select.object.material instanceof Array){
select.object.material = select.object.material
}
else{
select.object.material = select.object.material.clone();
}
}
this.selectModels.push(select.object);
if (this.isFollow) {
this.animateClick(this.controls.object.position, this.controls.target, select)
}
console.log(select);
return;
}
}
}
} else {
this.selectModels.forEach((item, index) => {
item.material = item.currenMaterial;
// console.log(index);
})
this.selectModels = [];
if (this.isOpacity) {
this.octree.objects.forEach((item) => {
item.material.opacity = 1;
})
}
}
// console.log(intersections);
}
canvasHandleMouseup(event) {
this.mouseupTime = new Date().getTime();
event.preventDefault();
}
canvasHandleMousedown(event) {
this.mousedownTime = new Date().getTime();
event.preventDefault();
}
canvasHandleMousemove(event) {
event.preventDefault();
let x = (event.offsetX / this.canvas.width) * 2 - 1;
let y = -(event.offsetY / this.canvas.height) * 2 + 1;
this.mouse.x = x;
this.mouse.y = y;
this.raycaster.setFromCamera(this.mouse, this.camera);
let meshesSearch = this.octree.search(this.raycaster.ray.origin, this.raycaster.ray.far, true, this.raycaster.ray.direction);
let intersections = this.raycaster.intersectOctreeObjects(meshesSearch);
if (intersections.length > 0) {
let select;
intersections.sort((a, b) => {
return a.distance - b.distance;
});
for (let i = 0; i < intersections.length; i++) {
let p = intersections[i].point.clone();
if (this.boundNow.containsPoint(p)) {
select = intersections[i];
var n = select.face.normal.clone();
n.transformDirection(select.object.matrixWorld);
n.multiplyScalar(10);
n.add(select.point);
this.helper.visible = true;
this.helper.lookAt(n);
this.helper.position.copy(p);
return;
}
}
} else {
this.helper.visible = false;
}
}
resetCamera() {
this.camera.position.copy(this.cameraDefaults.posCamera);
this.cameraTarget.copy(this.cameraDefaults.posCameraTarget);
this.updateCamera();
}
updateCamera() {
this.camera.aspect = this.aspectRatio;
this.camera.lookAt(this.cameraTarget);
this.camera.updateProjectionMatrix();
}
initPostGL() {
var scope = this;
var reloadAssetsProxy = function() {
scope.reloadAssets();
};
var materialsLoaded = function(materials) {
var count = Boolean(materials) ? materials.length : 0;
console.log('Loaded #' + count + ' materials.');
};
var meshLoaded = (meshName, bufferGeometry, materials) => {
// just for demonstration...
};
var reportProgress = (text) => {
this.vue.handProcess(text);
}
var errorWhileLoading = function() {
// just for demonstration...
};
this.wwObjLoader2.registerCallbackMaterialsLoaded(materialsLoaded);
this.wwObjLoader2.registerCallbackMeshLoaded(meshLoaded);
this.wwObjLoader2.registerCallbackCompletedLoading(reloadAssetsProxy);
this.wwObjLoader2.registerCallbackProgress(reportProgress);
this.wwObjLoader2.registerCallbackErrorWhileLoading(errorWhileLoading);
// this.reloadAssets();
return true;
}
recalcAspectRatio() {
this.aspectRatio = (this.width === 0) ? 1 : this.width / this.height;
}
/**
* resize canvas
*/
resizeDisplayGL() {
this.width=this.canvas.parentElement.offsetWidth;
this.height=this.canvas.parentElement.offsetHeight;
this.canvas.style.width=this.width+'px';
this.canvas.style.height=this.height+'px';
this.controls.handleResize();
this.recalcAspectRatio();
this.renderer.setSize(this.width, this.height, false);
this.updateCamera();
}
clearAllAssests() {
var ref;
var scope = this;
for (var asset in this.allAssets) {
ref = this.allAssets[asset];
var remover = function(object3d) {
if (object3d === ref.pivot) return;
console.log('Removing ' + object3d.name);
scope.scene.remove(object3d);
if (object3d.hasOwnProperty('geometry')) object3d.geometry.dispose();
if (object3d.hasOwnProperty('material')) {
var mat = object3d.material;
if (mat.hasOwnProperty('materials')) {
var materials = mat.materials;
for (var name in materials) {
if (materials.hasOwnProperty(name)) materials[name].dispose();
}
}
}
if (object3d.hasOwnProperty('texture')) object3d.texture.dispose();
};
scope.scene.remove(ref.pivot);
ref.pivot.traverse(remover);
ref.pivot = null;
}
this.loadCounter = 0;
this.allAssets = [];
}
updateAssets(objs) {
this.objs2Load = [];
this.loadCounter = 0;
this.processing = true;
if (Boolean(objs)) {
var obj2Load;
var pivot;
var errors = '';
for (var i = 0; i < objs.length; i++) {
obj2Load = objs[i];
if (!this.allAssets.hasOwnProperty(obj2Load.name)) {
pivot = new THREE.Object3D();
pivot.position.set(obj2Load.pos.x, obj2Load.pos.y, obj2Load.pos.z);
pivot.scale.set(obj2Load.scale, obj2Load.scale, obj2Load.scale);
pivot.name = obj2Load.name;
let radian = Math.PI / 180 * obj2Load.rotate.angle;
let axis = new THREE.Vector3(obj2Load.rotate.x, obj2Load.rotate.y, obj2Load.rotate.z);
pivot.rotateOnAxis(axis, radian);
obj2Load.pivot = pivot;
this.objs2Load.push(obj2Load);
this.allAssets[obj2Load.name] = obj2Load;
} else {
errors += obj2Load.name + ' ';
}
if (errors !== '') {
this.reportProgress('Will not reload: ' + errors);
}
}
}
}
reportProgress(text) {
// console.log(this);
// document.getElementById('feedback').innerHTML = text;
}
reloadAssets() {
var scope = this;
if (scope.loadCounter < scope.objs2Load.length) {
var obj2Load = scope.objs2Load[scope.loadCounter];
var prepData;
scope.loadCounter++;
scope.scene.add(obj2Load.pivot);
if (Boolean(obj2Load.fileZip)) {
var zipTools = new ZipTools(obj2Load.pathBase, this.vue);
var mtlAsString = null;
var setObjAsArrayBuffer = function(data) {
scope.reportProgress('');
prepData = new THREE.OBJLoader2.WWOBJLoader2.PrepDataArrayBuffer(
obj2Load.name, data, obj2Load.pathTexture, mtlAsString
);
prepData.setSceneGraphBaseNode(obj2Load.pivot);
scope.wwObjLoader2.prepareRun(prepData);
scope.wwObjLoader2.run();
};
var setMtlAsString = function(data) {
mtlAsString = data;
scope.reportProgress('Unzipping: ' + obj2Load.fileObj);
zipTools.unpackAsUint8Array(obj2Load.fileObj, setObjAsArrayBuffer);
};
var doneUnzipping = function() {
if (Boolean(obj2Load.fileMtl)) {
zipTools.unpackAsString(obj2Load.fileMtl, setMtlAsString);
} else {
setMtlAsString(null);
}
};
var errorCase = function(text) {
scope.reportProgress(text);
scope.processing = false;
};
zipTools.load(obj2Load.fileZip, { success: doneUnzipping, progress: scope.reportProgress, error: errorCase });
} else {
scope.reportProgress('');
prepData = new THREE.OBJLoader2.WWOBJLoader2.PrepDataFile(
obj2Load.name, obj2Load.pathBase, obj2Load.fileObj, obj2Load.pathTexture, obj2Load.fileMtl
);
prepData.setSceneGraphBaseNode(obj2Load.pivot);
scope.wwObjLoader2.prepareRun(prepData);
scope.wwObjLoader2.run();
}
} else { //当所有模型加载完毕后填充 octree
this.objs2Load.forEach((item) => {
item.pivot.children.forEach((child) => {
if(child.material instanceof Array){
child.material.forEach((materialChild)=>{
materialChild.clippingPlanes=this.clipPlanes;
materialChild.clipIntersection=this.clipParams.clipIntersection;
materialChild.side=THREE.DoubleSide;
})
}
else {
child.material.clippingPlanes = this.clipPlanes;
child.material.clipIntersection = this.clipParams.clipIntersection;
child.material.side = THREE.DoubleSide;
}
child.geometry.computeBoundingBox();
let box=child.geometry.boundingBox.clone();
// console.log(box,11111);
box.applyMatrix4(child.matrixWorld)
// console.log(box,2222);
if(!this.boundMax){
this.boundMax=box;
}
else{
//求模型的最大边界 todo:应该有更好的方法
if(this.boundMax.max.x<box.max.x){
this.boundMax.max.x=box.max.x;
}
if(this.boundMax.max.y<box.max.y){
this.boundMax.max.y=box.max.y;
}
if(this.boundMax.max.z<box.max.z){
this.boundMax.max.z=box.max.z;
}
//求模型的最小边界 todo:应该有更好的方法
if(this.boundMax.min.x>box.min.x){
this.boundMax.min.x=box.min.x;
}
if(this.boundMax.min.y>box.min.y){
this.boundMax.min.y=box.min.y;
}
if(this.boundMax.min.z>box.min.z){
this.boundMax.min.z=box.min.z;
}
}
this.octree.add(child);
// this.meshs.push(child);
})
})
let axes = new THREE.Group();
this.clipPlanes[0].constant=this.boundMax.max.x;
this.clipPlanes[1].constant=this.boundMax.max.y;
this.clipPlanes[2].constant=this.boundMax.max.z;
this.boundNow=this.boundMax.clone();
axes.add(new THREE.AxisHelper(10));
axes.add(new THREE.PlaneHelper(this.clipPlanes[0], 30, 0xff0000));
axes.add(new THREE.PlaneHelper(this.clipPlanes[1], 30, 0x00ff00));
axes.add(new THREE.PlaneHelper(this.clipPlanes[2], 30, 0x0000ff));
axes.visible = true;
this.scene.add(axes);
//监听事件
this.canvas.addEventListener('click', this.canvasHandleClick.bind(this), false);
this.canvas.addEventListener('mousemove', this.canvasHandleMousemove.bind(this), false);
this.canvas.addEventListener('mouseup', this.canvasHandleMouseup.bind(this), false);
this.canvas.addEventListener('mousedown', this.canvasHandleMousedown.bind(this), false);
window.addEventListener('keydown', this.canvasHadnleKeydown.bind(this), false);
window.addEventListener('keyup', this.canvasHadnleKeyup.bind(this), false);
scope.processing = false;
//执行回调
this.loadCallback()
}
}
canvasHadnleKeydown(event) {
var e = event || window.event || arguments.callee.caller.arguments[0];
if (e && e.keyCode == 16) { // 按 shift
this.isShift = true;
}
}
canvasHadnleKeyup(event) {
var e = event || window.event || arguments.callee.caller.arguments[0];
if (e && e.keyCode == 16) { // 按 shift
this.isShift = false
}
}
animateClick(oldP, oldT, intersections) {
let boundCenter;
if (intersections.object.name == 'pin') {
boundCenter = intersections.object.position.clone();
} else {
boundCenter = intersections.object.geometry.boundingSphere.center.clone();
}
let sobj = this.selectModels[this.selectModels.length - 1];
let boundingSphere = sobj.geometry.boundingSphere;
this.objs2Load.forEach((item) => {
if (item.name == sobj.parent.name) {
item.pivot.children.forEach((child) => {
if (child.uuid != sobj.uuid) {
if (this.isOpacity) {
child.material.transparent = true;
child.material.opacity = 0.3;
}
} else {
let radian = Math.PI / 180 * item.rotate.angle;
let axis = new THREE.Vector3(item.rotate.x, item.rotate.y, item.rotate.z);
boundCenter.applyAxisAngle(axis, radian);
boundCenter.x += item.pos.x;
boundCenter.y += item.pos.y;
boundCenter.z += item.pos.z;
if (this.isOpacity) {
child.material.transparent = true;
child.material.opacity = 1;
}
}
})
}
})
this.selectModels.forEach((item) => {
item.material.transparent = false;
})
console.log(this.selectModels);
var r = boundingSphere.radius;
var offset = r / Math.tan(Math.PI / 180.0 * this.controls.object.fov * 0.5);
var vector = new THREE.Vector3(0, 0, 1);
var dir = vector.applyQuaternion(this.controls.object.quaternion);
var newPos = new THREE.Vector3();
dir.multiplyScalar(offset * 1.1);
newPos.addVectors(boundCenter, dir);
var that = this;
var tween = new TWEEN.Tween(oldP)
.to({
x: newPos.x,
y: newPos.y,
z: newPos.z
}, 500)
/**
* Circular 间接的动画
* Elastic 弹性动画
* Exponential 指数动画
* Back 后退动画
* Bounce 抖动
* Sinusoidal 正弦曲线动画
* Quintic 5次方动画
* Quartic 4次方
* Cubic 立方体动画
* Quadratic 2次方动画*/
.easing(TWEEN.Easing.Quadratic.InOut)
.onUpdate(() => {
that.controls.target = new THREE.Vector3(boundCenter.x, boundCenter.y, boundCenter.z);
});
var tween1 = new TWEEN.Tween(oldT)
.to({
x: newPos.x,
y: newPos.y,
z: newPos.z
}, 10)
.easing(TWEEN.Easing.Quadratic.InOut)
.onUpdate(() => {
that.controls.object.position.set(newPos.x, newPos.y, newPos.z);
});
tween.chain(tween1);
tween.start();
}
interfaceLoadObjOrZip(assets, loadCallback) {
if (!this.processing) {
this.updateAssets(assets)
this.reloadAssets()
this.loadCallback = loadCallback;
}
}
interfaceDrawPin(arrs) {
this.objs2Load.forEach((item) => {
item.pivot.children.forEach((child) => {
let center = child.geometry.boundingSphere.center.clone();
let radian = Math.PI / 180 * item.rotate.angle;
let axis = new THREE.Vector3(item.rotate.x, item.rotate.y, item.rotate.z);
center.applyAxisAngle(axis, radian);
center.x += item.pos.x;
center.y += item.pos.y;
center.z += item.pos.z;
let geometry = new THREE.CylinderGeometry(0, 10, 100, 12);
geometry.rotateX(Math.PI / 2);
// geometry.translate ( 0, -50, 0 );
geometry.scale(0.2, 0.2, 0.2);
// geometry.rotateX( -Math.PI / 2 );
let pin = new THREE.Mesh(geometry, new THREE.MeshNormalMaterial());
pin.name = 'pin';
pin.lookAt(this.controls.object.position);
pin.position.set(center.x, center.y, center.z);
this.pinObj3D.add(pin);
this.octree.add(pin);
})
this.scene.add(this.pinObj3D);
})
}
interfaceVisbileSelects() {
this.selectModels.forEach((item) => {
item.visible = false;
this.visibleModels.push(item);
})
}
interfaceShowModels() {
this.visibleModels.forEach((item) => {
item.visible = true;
})
}
interfaceEnableFollow() {
this.isFollow = !this.isFollow;
this.isSelectColor = !this.isSelectColor;
}
interfaceClippingX(val){
let result;
let x=(this.boundMax.max.x-this.boundMax.min.x)/100;
result=this.boundMax.max.x-x*val;
this.clipPlanes[0].constant=result;
this.boundNow.min.x=-result;
console.log(result,this.boundMax);
}
interfaceClippingY(val){
let result;
let y=(this.boundMax.max.y-this.boundMax.min.y)/100;
result=this.boundMax.max.y-y*val;
this.clipPlanes[1].constant=result;
this.boundNow.max.y=result;
}
interfaceClippingZ(val){
let result;
let z=(this.boundMax.max.z-this.boundMax.min.z)/100;
result=this.boundMax.max.z-z*val;
this.clipPlanes[2].constant=result;
this.boundNow.max.z=result;
}
render() {
if (!this.renderer.autoClear) this.renderer.clear();
this.controls.update();
// this.CameraHelper.update();
TWEEN.update();
this.pinObj3D.children.forEach((item) => {
item.lookAt(this.controls.object.position);
})
this.octree.update();
this.renderer.render(this.scene, this.camera);
}
}
export default {
Three
}
|
const crypto = require('crypto');
let key = crypto.randomBytes(32);
process.stdout.write(`CARDSTACK_SESSIONS_KEY=${key.toString('base64')}\n`);
|
'use strict';
/**
* Module to store the passed in options
* Useful for middlewares
*/
module.exports = {
authenticatedRequest: null,
grasshopper : null
};
|
game.PlayScreen = me.ScreenObject.extend({
/**
* action to perform on state change
*/
onResetEvent: function() {
// background color
me.game.world.addChild(new me.ColorLayer("background", "#330000"), 0);
// static background image
var background = new me.Sprite(480, 320, {
image: game.texture,
region : "backdrop.png"
});
me.game.world.addChild(background, 1);
// character animation
var animationSheet = game.texture.createAnimationFromName([
"slice04_04.png", "slice05_05.png", "slice12_12.png", "slice13_13.png"
]);
animationSheet.pos.set(200, 200, 2);
me.game.world.addChild(animationSheet, 2);
}
});
|
import commonMiddleware from './rx-middleware/commonMiddleware';
import {combineReducers} from 'redux-core';
import * as reducers from './reducers/counter';
const middleware = [commonMiddleware];
export function applyRxMiddleware(intent$, store) {
return middleware.reduce((prev, cur) => {
return prev.flatMap(cur(store.getState));
}, intent$);
}
export const reducer = combineReducers(reducers);
|
$(document).ready(function(){
var myPlaylist = new jPlayerPlaylist({
jPlayer: "#jplayer_N",
cssSelectorAncestor: "#jp_container_N"
}, [
{
title:"K6",
artist:"G-Man",
mp3:"http://picosong.com/cdn/387a5d42d3c7996be677441a8f4990e0.mp3",
poster: "images/m0.jpg"
},
{
title:"Chucked Knuckles",
artist:"3studios",
mp3:"http://flatfull.com/themes/assets/musics/adg3com_chuckedknuckles.mp3",
poster: "images/m0.jpg"
},
{
title:"Cloudless Days",
artist:"ADG3 Studios",
mp3:"http://flatfull.com/themes/assets/musics/adg3com_cloudlessdays.mp3",
poster: "images/m0.jpg"
},
{
title:"Core Issues",
artist:"Studios",
mp3:"http://flatfull.com/themes/assets/musics/adg3com_coreissues.mp3",
poster: "images/m0.jpg"
},
{
title:"Cryptic Psyche",
artist:"ADG3",
mp3:"http://flatfull.com/themes/assets/musics/adg3com_crypticpsyche.mp3",
poster: "images/m0.jpg"
},
{
title:"Electro Freak",
artist:"Studios",
mp3:"http://flatfull.com/themes/assets/musics/adg3com_electrofreak.mp3",
poster: "images/m0.jpg"
},
{
title:"Freeform",
artist:"ADG",
mp3:"http://flatfull.com/themes/assets/musics/adg3com_freeform.mp3",
poster: "images/m0.jpg"
}
], {
playlistOptions: {
enableRemoveControls: true,
autoPlay: false
},
swfPath: "js/jPlayer",
supplied: "webmv, ogv, m4v, oga, mp3",
smoothPlayBar: true,
keyEnabled: true,
audioFullScreen: false
});
$(document).on($.jPlayer.event.pause, myPlaylist.cssSelector.jPlayer, function(){
$('.musicbar').removeClass('animate');
$('.jp-play-me').removeClass('active');
$('.jp-play-me').parent('li').removeClass('active');
});
$(document).on($.jPlayer.event.play, myPlaylist.cssSelector.jPlayer, function(){
$('.musicbar').addClass('animate');
});
$(document).on('click', '.jp-play-me', function(e){
e && e.preventDefault();
var $this = $(e.target);
if (!$this.is('a')) $this = $this.closest('a');
$('.jp-play-me').not($this).removeClass('active');
$('.jp-play-me').parent('li').not($this.parent('li')).removeClass('active');
$this.toggleClass('active');
$this.parent('li').toggleClass('active');
if( !$this.hasClass('active') ){
myPlaylist.pause();
}else{
var i = Math.floor(Math.random() * (1 + 7 - 1));
myPlaylist.play(i);
}
});
// video
$("#jplayer_1").jPlayer({
ready: function () {
$(this).jPlayer("setMedia", {
title: "Big Buck Bunny",
m4v: "http://flatfull.com/themes/assets/video/big_buck_bunny_trailer.m4v",
ogv: "http://flatfull.com/themes/assets/video/big_buck_bunny_trailer.ogv",
webmv: "http://flatfull.com/themes/assets/video/big_buck_bunny_trailer.webm",
poster: "images/m41.jpg"
});
},
swfPath: "js",
supplied: "webmv, ogv, m4v",
size: {
width: "100%",
height: "auto",
cssClass: "jp-video-360p"
},
globalVolume: true,
smoothPlayBar: true,
keyEnabled: true
});
}); |
/**
* Sleep charter, event handlers
* Roy Curtis, MIT license, 2017
*/
/**
* Handles mousing over of sleep bars. Uses the entire sleep chart element, so that we can
* avoid attaching an event listener to every single sleep bar.
*
* @param {MouseEvent} evt
*/
function onSleepChartMouseOver(evt)
{
/** @type HTMLElement|EventTarget */
var selected = evt.target;
// Do nothing if already hovering over same bar
if (STATE.selected === selected)
return;
// Remove selection class from previously selected bar
if (STATE.selected !== null)
{
STATE.selected.classList.remove("selected");
if (STATE.selected.pairedBar)
STATE.selected.pairedBar.classList.remove("selected");
STATE.selected.title = "";
STATE.selected = null;
}
// If started hovering over a(nother) bar
if (selected.tagName === "SLEEP")
{
STATE.selected = selected;
STATE.selected.title = getSleepBarMessage(selected);
selected.classList.add("selected");
if (STATE.selected.pairedBar)
STATE.selected.pairedBar.classList.add("selected");
}
}
/** @param {WheelEvent} evt */
function onSleepChartMouseWheel(evt)
{
if (evt.ctrlKey || evt.shiftKey)
return;
// Chrome uses deltaMode 0 (pixels)
// Firefox uses deltaMode 1 (lines)
DOM.sleepChart.scrollLeft += evt.deltaMode === 0
? evt.deltaY
: evt.deltaY * 33;
evt.preventDefault();
}
function onSleepChartClick(evt)
{
/** @type SleepBar|EventTarget */
var selected = evt.target;
// Handle only sleep bars
if (selected.tagName !== "SLEEP")
return;
window.alert( getSleepBarMessage(selected) );
if (STATE.selected.pairedBar)
STATE.selected.pairedBar.classList.add("selected");
}
function onSleepChartResize()
{
layoutSleepBars();
layoutTimeAxis();
STATE.rescaleIdx = 0;
if (!STATE.rescaling)
rescaleSleeps();
} |
var React = require('react');
var _ = require('lodash');
var classNames = require('classnames');
var Modal = React.createClass({
closeClick: function(event) {
event.preventDefault();
this.close();
},
backdropClick: function(event) {
if (!$(event.target).closest('.modal-dialog').length) {
this.close();
}
},
close: function(){
if (this.state.open) {
this.removeBackdrop();
this.setState({ open: false });
this.props.onClose();
}
},
open: function() {
if (!this.state.open) {
this.addBackdrop();
this.setState({ open: true });
this.props.onOpen();
}
},
setLoading: function(value) {
if (typeof value === "boolean") {
this.setState({ loading: value });
}
},
addBackdrop: function() {
$('body').addClass('modal-open');
var backdropEl = document.createElement('div');
backdropEl.id = 'modal-backdrop';
backdropEl.className = 'modal-backdrop in';
document.body.appendChild(backdropEl);
},
removeBackdrop: function(){
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
},
buildFooter: function() {
if (this.props.footerBtns.length) {
var footerBtns = _.map(this.props.footerBtns, _.bind(function(btnConfig, index){
var text = btnConfig.text;
var classes = 'btn';
if (btnConfig.classes) {
classes = classes + ' ' + btnConfig.classes;
} else {
classes = classes + ' btn-default';
}
var icon;
if (btnConfig.iconName) {
var iconClass = 'icon glyphicon glyphicon-' + btnConfig.iconName;
var icon = (<span className={iconClass}></span>);
}
return (
<button type="button" ref={btnConfig.ref || ''} className={classes} onClick={btnConfig.onClick || this.close} key={index}>
{icon}
{text}
</button>
);
}, this));
return (
<div className="modal-footer">
{footerBtns}
</div>
);
}
},
// Lifecycle hooks
getInitialState: function() {
return {
open: false,
loading: false
};
},
getDefaultProps: function() {
return {
size: 'small',
modalClasses: '',
footerBtns: [],
onOpen: function(){},
onClose: function(){}
};
},
componentDidMount: function() {
$(document).on('click', '.modal.block', _.bind(this.backdropClick, this));
$(document).on('keyup', _.bind(function(e) {
// Escapism?
if (e.keyCode === 27 && e.target.className.indexOf('react-select-input') < 0) {
this.close();
}
}, this));
},
componentWillUnmount: function() {
$(document).off('click', '.modal-backdrop');
},
render: function() {
var modalClasses = this.props.modalClasses + ' modal';
if (this.state.open) {
modalClasses += ' block';
}
var modalDialogClasses = classNames({
'modal-dialog': true,
'modal-lg': this.props.size === 'large'
});
var titleIcon;
if (this.props.titleIcon) {
var titleIconClasses = "icon glyphicon glyphicon-" + this.props.titleIcon;
if (!this.props.title) titleIconClasses += " big no-margin";
if (this.props.iconClasses) titleIconClasses = titleIconClasses + " " + this.props.iconClasses;
titleIcon = <span className={titleIconClasses}></span>
}
return (
<div className={modalClasses}>
<div className={modalDialogClasses}>
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" onClick={this.closeClick}>
<span aria-hidden="true">×</span>
<span className="sr-only">Close</span>
</button>
<h3 className="modal-title">
{titleIcon}
{this.props.title}
</h3>
</div>
<div className="modal-body">
{this.props.children}
</div>
{this.buildFooter()}
</div>
</div>
</div>
);
}
});
module.exports = Modal;
|
var less;
(function () {
'use strict';
function getScript(url) {
document.write('<script type="text/javascript" src="' + url + '"></script>');
}
function getStyleSheet(url) {
var fileExtension = url.split('.').pop(), rel = (fileExtension === 'less') ? '/less' : '';
document.write('<link type="text/css" href="' + url + '" rel="stylesheet' + rel + '" />');
}
var srcPath = '../../src', vendorPath = '../../vendor/';
//External libraries
getScript(vendorPath + '/angularJs/angular.min.js');
getScript(vendorPath + '/angularJs/angular-ui-router.min.js');
//Common src resources
getScript(srcPath + '/common/app.js');
getStyleSheet(srcPath + '/common/main.less');
//Business logic src resources
//Home
getScript(srcPath + '/app/home/HomeCtrl.js');
getScript(srcPath + '/app/home/helloWorldDirective.js');
getScript(srcPath + '/app/home/helloWorldService.js');
//Details
getScript(srcPath + '/app/details/DetailsCtrl.js');
//Less vendor library (has to be loaded at the end of the stylesheet chain
less = { env: "production" }; //Set production environment to avoid log messages
getScript(vendorPath + '/less/less.min.js');
})(); |
'use strict';
//Students service used for communicating with the students REST endpoints
angular.module('students').factory('Students', ['$resource',
function ($resource) {
return $resource('api/students/:studentId', {
studentId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
|
$(document).ready(function() {
var socket = io.connect();
var selItem = '';
var tempItem = '';
socket.on('connect', function() {
console.log('connected');
socket.emit('pageID', 'page1');
});
socket.on('disconnect', function() {
console.log('disconnected');
});
socket.on('error', function(err) {
if (err === 'handshake error') {
console.log('handshake error', err);
} else {
console.log('io error', err);
}
});
// Initial stage of page
$(function() {
$('#menu').hide();
});
socket.on('menu', function(data) {
console.log(data);
if (data == 'on') {
$('span').hide();
$('#menu').show();
} else if (data == 'off') {
$('#menu').hide();
$('span').show();
} else {
console.log('Error in Javascript');
}
});
socket.on('option', function(data) {
tempItem = data;
console.log(tempItem);
if (selItem != tempItem) {
hiSel = '#' + tempItem;
loSel = '#' + selItem;
$(hiSel).css({'background-color': '#55ee44'});
$(loSel).css({'background-color': '#555555'});
} else {
console.log('........');
}
selItem = tempItem;
});
});
|
/**
* Controller for render the pages
*/
PagesController = new Object();
PagesController.homePage = function (req, res) {
//Vars
//Render
}
//User CRUD
//How Many List
//How Many CRUD
//How Many Done
//Congratulations
//Configuration
//PagesController.
module.exports = PagesController;
/**
* Locomotive Style
var locomotive = require('locomotive')
, Controller = locomotive.Controller;
var PagesController = new Controller();
PagesController.main = function() {
this.title = 'Locomotive'
this.render();
}
PagesController.homePage = function() {
//this.req
//this.res
//this.render()
//this.urlFor({ action: 'login' })
//this.res.redirect(this.urlFor({ action: 'login' }));
}
module.exports = PagesController;
*/ |
var expect = require('expect.js');
var utils = require("../lib/utils");
describe("Utils", function() {
describe("dominantMovement", function() {
it("returns the dominant movement as a direction and distance", function() {
var movementOne = [1, 2, 3];
var movementTwo = [2, -4, 4];
expect(utils.dominantMovement(movementOne, movementTwo)).to.eql({direction: "y", distance: -6});
})
it("throws an exception if one or both values are null", function() {
expect(function() { utils.dominantMovement(null, [1, 2, 3]) }).to.throwException();
expect(function() { utils.dominantMovement([1, 2, 3], null) }).to.throwException();
expect(function() { utils.dominantMovement(null, null) }).to.throwException();
})
})
})
|
Schema.UserLog = new SimpleSchema({
userId: {
type: String
},
date: {
type: Number
},
details: {
type: Object,
blackbox: true
}
});
UserLogs = new Mongo.Collection("userLogs");
UserLogs.attachSchema(Schema.UserLog);
|
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
var App = Ember.Application.extend({
modulePrefix: 'appkit', // TODO: loaded via config
Resolver: Resolver,
LOG_TRANSITIONS: true
});
loadInitializers(App, 'appkit');
export default App;
|
const prefix = 'jquery-extras-id-';
let idCounter = 0;
export default () => prefix + ++idCounter;
|
'use strict';
module.exports = function() {
var //---------------
// Imports
//---------------
lang = require('rw-mercenary/lang'),
partial = lang.partial,
push = lang.push,
get = lang.get,
set = lang.set,
//----------------------
// Implementation
//----------------------
// The middleware registry.
registry = {
pre: {
build: []
},
post: {
build: []
}
},
// Register pre-build middleware.
registerPreBuild = function(fn) {
var middleware = get(registry, 'pre', 'build');
push(middleware, fn);
set(registry, 'pre', 'build', middleware);
},
// Register post-build middleware.
registerPostBuild = function(fn) {
var middleware = get(registry, 'post', 'build');
push(middleware, fn);
set(registry, 'post', 'build', middleware);
};
//------------------
// Public API
//------------------
return {
register: {
pre: {
build: registerPreBuild
},
post: {
build: registerPostBuild
}
},
get: {
pre: {
build: partial(get, registry, 'pre', 'build')
},
post: {
build: partial(get, registry, 'post', 'build')
}
}
};
};
|
// @flow
import type { ApiBooking } from '../../../common/apiTypes';
import { getDateString, numberToTimestring, timestringToNumber } from '../../../common/utils';
// Time from 08:00 - 17:00
const timeslotsInNumbers = [
480,
510,
540,
570,
600,
630,
660,
690,
720,
750,
780,
810,
840,
870,
900,
930,
960,
990,
1020,
1050,
1080,
];
const hasValidTimeslots = (bod: ApiBooking, ts: number) =>
ts < timestringToNumber(bod.start) || ts >= timestringToNumber(bod.start) + bod.duration;
export default function findTimeslots(bookings: ApiBooking[], date: Date): string[] {
const dateString = getDateString(date);
const bookingsOfDate = bookings.filter(booking => booking.day === dateString);
const newDate = new Date();
const isToday = dateString === getDateString(newDate);
const isInPast = date < new Date().setDate(newDate.getDate() - 1);
const minutesToday = newDate.getHours() * 60 + newDate.getMinutes();
const availableTimeslots = timeslotsInNumbers.filter(ts => {
if (isToday) {
if (bookingsOfDate.length > 0) {
return bookingsOfDate.map(bod => minutesToday < ts && hasValidTimeslots(bod, ts)).every(val => val === true);
} else {
return minutesToday < ts;
}
} else if (isInPast) {
return false;
} else {
return bookingsOfDate.map(bod => hasValidTimeslots(bod, ts)).every(val => val === true);
}
});
return availableTimeslots.map(ts => numberToTimestring(ts));
}
|
require(["worldOptions", "patterns/pattern", "world", "patterns/patternGenerator", "life", "controls", "patterns/patternList", "patterns/patternBinding"], function(worldOptions, pattern, world, patternGenerator, life, controls, patternList, patternBinding)
{
theWorld = world.map(worldOptions);
patternGenerator.attach(theWorld);
theLife = life.run(theWorld);
controls.attachTo({
life: theLife,
startButton: "#start-life-btn",
stopButton: "#stop-life-btn",
intervalLengthInput: "#interval-length-input"
});
Object.keys(patternList).forEach(function (patternName) {
var patternInstance = pattern.initialize(patternList[patternName].map(), patternList[patternName].translation);
var patternElement = (typeof patternList[patternName].element === "undefined") ? "#" + patternName + "-btn" : patternList[patternName].element;
patternBinding.bind(patternInstance, patternElement, patternGenerator);
});
});
|
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['655',"Tlece.Recruitment.Entities Namespace","topic_0000000000000265.html"],['1065',"tlece_ProductMaster Class","topic_00000000000003E5.html"],['1066',"Properties","topic_00000000000003E5_props--.html"],['1074',"Name Property","topic_00000000000003E8.html"]]; |
import schema_generator from './schema-generator';
const api = {
generateDefinition(key, definition) {
const schema_list = schema_generator.createSchemaList(definition);
return `### ${key}\n\n**Schema**\n\n${schema_list}`;
},
};
export default api;
|
// Regular expression that matches all symbols in the Variation Selectors block as per Unicode v6.2.0:
/[\uFE00-\uFE0F]/; |
const {readImage} = require('./helpers')
jest.setTimeout(15000)
test('[trim] can trim an image using auto mode', (done) => {
readImage('trim.jpg?trim=auto').then((img) => {
expect(img.width).toBe(1024)
expect(img.height <= 592).toBeTruthy()
done()
})
})
test('[trim] can trim an image using color mode', (done) => {
readImage('trim.jpg?trim=color').then((img) => {
expect(img.width).toBe(1024)
expect(img.height <= 592).toBeTruthy()
done()
})
})
test('[trim] can trim with increased tolerance', (done) => {
readImage('trim.jpg?trim=color&trimtol=25').then((img) => {
expect(img.width).toBe(1024)
expect(img.height <= 585).toBeTruthy()
done()
})
})
|
/**
* @apiDefinePermission public This information is publicly accessible.
* No authentication is required.
*
* @apiVersion 1.0.0
*/
/**
* @apiDefinePermission user Authenticated access is required.
* An API key is required.
*
* @apiVersion 1.0.0
*/
/**
* @api {get} /wow/?api_key={API_KEY}&a=get_balance Get Balance
* @apiVersion 1.0.0
* @apiName GetBalance
* @apiGroup DogeCoin
* @apiPermission user
*
* @apiDescription Returns the DOGE balance of your entire account to 8 decimal places.
*
* @apiParam {String} api_key The user's api key
* @apiParam {String} a The action to perform
*
* @apiExample CURL example:
* curl -X GET 'https://dogeapi.com/wow/?api_key={API_KEY}&a=get_balance'
*
* @apiSuccess {int} amount The amount in the entire account
*
* @apiSuccessExample Success-Response (example):
* HTTP/1.1 200 OK
* 18.95245109
*
* @apiError (Success 200) InvalidAPIKey The user's API key is either missing or invalid.
*
* @apiErrorExample Error-Response (example):
* HTTP/1.1 200 OK
* "Invalid API Key"
*
*/
/**
* @api {get} /wow/?api_key={API_KEY}&a=withdraw&amount={AMOUNT}&payment_address={PAYMENT_ADDRESS} Withdraw
* @apiVersion 1.0.0
* @apiName Withdraw
* @apiGroup DogeCoin
* @apiPermission user
*
* @apiDescription Withdraws {AMOUNT} doge to a {PAYMENT_ADDRESS} you specify.
*
* @apiParam {String} api_key The user's api key
* @apiParam {String} a The action to perform
* @apiParam {int} amount The amount to withdraw
* @apiParam {String} payment_address The account to withdraw to
*
* @apiExample CURL example:
* curl -X GET 'https://dogeapi.com/wow/?api_key={API_KEY}&a=withdraw&amount={AMOUNT}&payment_address={PAYMENT_ADDRESS}'
*
* @apiSuccess {string} transaction The unique transaction id on the market
*
* @apiSuccessExample Success-Response (example):
* HTTP/1.1 200 OK
* "52c5a2923b113ef07c47b077ba8bf3a03381c687f218f6b326773892565d6963"
*
* @apiError (Success 200) InvalidAPIKey The user's API key is either missing or invalid.
*
* @apiErrorExample Error-Response (example):
* HTTP/1.1 200 OK
* "Invalid API Key"
*
* @apiError (Success 200) NotEnoughDoge The user does not have enough Doge in their account.
*
* @apiErrorExample Error-Response (example):
* HTTP/1.1 200 OK
* "Not enough Doge"
*
* @apiError (Success 200) BadQuery The query was invalid, probably indicated a missing parameter
*
* @apiErrorExample Error-Response (example):
* HTTP/1.1 200 OK
* "Bad Query"
*
*/
/**
* @api {get} /wow/?api_key={API_KEY}&a=get_new_address&address_label={ADDRESS_LABEL} Get New Address
* @apiVersion 1.0.0
* @apiName GetNewAddress
* @apiGroup DogeCoin
* @apiPermission user
*
* @apiDescription Returns a new payment address for your account. You can pass an optional alphanumeric {ADDRESS_LABEL} as a label for the address.
*
* @apiParam {String} api_key The user's api key
* @apiParam {String} a The action to perform
* @apiParam {String} address_label The optional, alphanumerical address label for the wallet
*
* @apiExample CURL example:
* curl -X GET 'https://dogeapi.com/wow/?api_key={API_KEY}&a=get_new_address&address_label={ADDRESS_LABEL}'
*
* @apiSuccess {String} address The address created
*
* @apiSuccessExample Success-Response (example):
* HTTP/1.1 200 OK
* "DQrzy6eccdPZ4n3Hi6oD6XZ4ndBFRX"
*
* @apiError (Unauthorized 401) InvalidAPIKey The user's API key is either missing or invalid.
*
* @apiErrorExample Error-Response (example):
* HTTP/1.1 401 Unauthorized
* "Invalid API Key"
*
*/
/**
* @api {get} /wow/?api_key={API_KEY}&a=get_my_addresses Get My Addresses
* @apiVersion 1.0.0
* @apiName GetMyAddresses
* @apiGroup DogeCoin
* @apiPermission user
*
* @apiDescription Returns all payment addresses/address_ids for your account.
*
* @apiParam {String} api_key The user's api key
* @apiParam {String} a The action to perform
*
* @apiExample CURL example:
* curl -X GET 'https://dogeapi.com/wow/?api_key={API_KEY}&a=get_my_addresses'
*
* @apiSuccess {Array} addresses The list of addresses on your account.
*
* @apiSuccessExample Success-Response (example):
* HTTP/1.1 200 OK
* ["DQ6eccdPZ4n3Hi6orzyD6XZ6XF24ndBFRX", "DQrzy5eci6oZ4n9HD6XFRX4dnBZ4ncdPdB"]
*
* @apiError (Success 200) InvalidAPIKey The user's API key is either missing or invalid.
*
* @apiErrorExample Error-Response (example):
* HTTP/1.1 200 OK
* "Invalid API Key"
*
*/
/**
* @api {get} /wow/?api_key={API_KEY}&a=get_address_received&payment_address={PAYMENT_ADDRESS} Get Address Received
* @apiVersion 1.0.0
* @apiName GetAddressReceived
* @apiGroup DogeCoin
* @apiPermission user
*
* @apiDescription Returns the current amount received to all addresses with {ADDRESS_LABEL} or {PAYMENT_ADDRESS}.
*
* @apiParam {String} api_key The user's api key
* @apiParam {String} a The action to perform
* @apiParam {String} payment_address The payment address to check the amount with
* @apiParam {String} address_label The address label to check the amount with
*
* @apiExample CURL example:
* curl -X GET 'https://dogeapi.com/wow/?api_key={API_KEY}&a=get_address_received&payment_address={PAYMENT_ADDRESS}'
*
* @apiExample CURL example:
* curl -X GET 'https://dogeapi.com/wow/?api_key={API_KEY}&a=get_address_received&address_label={ADDRESS_LABEL}'
*
* @apiSuccess {Array} addresses The list of addresses on your account.
*
* @apiSuccessExample Success-Response (example):
* HTTP/1.1 200 OK
* ["DQ6eccdPZ4n3Hi6orzyD6XZ6XF24ndBFRX", "DQrzy5eci6oZ4n9HD6XFRX4dnBZ4ncdPdB"]
*
* @apiError (Success 200) InvalidAPIKey The user's API key is either missing or invalid.
*
* @apiErrorExample Error-Response (example):
* HTTP/1.1 200 OK
* "Invalid API Key"
*
*/
/**
* @api {get} /wow/?api_key={API_KEY}&a=get_address_by_label&address_label={ADDRESS_LABEL} Get Address By Label
* @apiVersion 1.0.0
* @apiName GetAddressByLabel
* @apiGroup DogeCoin
* @apiPermission user
*
* @apiDescription Returns the payment address for the given {ADDRESS_LABEL}
*
* @apiParam {String} api_key The user's api key
* @apiParam {String} a The action to perform
* @apiParam {String} address_label The address label to check the amount with
*
* @apiExample CURL example:
* curl -X GET 'https://dogeapi.com/wow/?api_key={API_KEY}&a=get_address_by_label&address_label={ADDRESS_LABEL}'
*
* @apiSuccess {String} address The addresses on your account.
*
* @apiSuccessExample Success-Response (example):
* HTTP/1.1 200 OK
* "DQ6eccdPZ4n3Hi6orzyD6XZ6XF24ndBFRX"
*
* @apiError (Success 200) InvalidAPIKey The user's API key is either missing or invalid.
* @apiError (Success 200) InvalidAddress The user's address key is invalid.
* @apiErrorExample Error-Response (example):
* HTTP/1.1 200 OK
* "Invalid API Key"
*
* @apiErrorExample Error-Response (example):
* HTTP/1.1 200 OK
* null
*/
/**
* @api {get} /wow/?a=get_difficulty Get Difficulty
* @apiVersion 1.0.0
* @apiName GetDifficulty
* @apiGroup DogeCoin
* @apiPermission public
*
* @apiDescription Returns the current difficulty. This doesn't require an API key.
*
* @apiParam {String} a The action to perform
*
* @apiExample CURL example:
* curl -X GET 'https://dogeapi.com/wow/?a=get_difficulty'
*
* @apiSuccess {int} difficulty The current difficulty
*
* @apiSuccessExample Success-Response (example):
* HTTP/1.1 200 OK
* 321.8045805
*
*/
/**
* @api {get} /wow/?a=get_current_block Get Current Block
* @apiVersion 1.0.0
* @apiName GetCurrentBlock
* @apiGroup DogeCoin
* @apiPermission public
*
* @apiDescription Returns the current block. This doesn't require an API key.
*
* @apiParam {String} a The action to perform
*
* @apiExample CURL example:
* curl -X GET 'https://dogeapi.com/wow/?a=get_current_block'
*
* @apiSuccess {int} currentBlock The current block
*
* @apiSuccessExample Success-Response (example):
* HTTP/1.1 200 OK
* 39405
*
*/
/**
* @api {get} /wow/?a=get_current_price Get Current Price
* @apiVersion 1.0.0
* @apiName GetCurrentPrice
* @apiGroup DogeCoin
* @apiPermission public
*
* @apiDescription Returns the current price in USD or BTC. This doesn't require an API key.
*
* @apiParam {String} a The action to perform
* @apiParam {String} convert_to To convert to USD or BTC (Defaults to USD)
* @apiParam {int} amount_doge The amount of Doge to convert (Defaults to 1 Doge.)
*
* @apiExample CURL example:
* curl -X GET 'https://dogeapi.com/wow/?a=get_current_price&convert_to=BTC&amount_doge=1000'
*
* @apiSuccess {int} currentPrice The current price of BTC or USD for the Doge amount given.
*
* @apiSuccessExample Success-Response (example):
* HTTP/1.1 200 OK
* 0.00206000
*
* @apiError (Success 200) InvalidConversion The conversion unit was not USD or BTC
*
* @apiErrorExample Error-Response (example):
* HTTP/1.1 200 OK
* "invalid conversion unit"
*
* @apiError (Success 200) InvalidAmount The amount was not a valid amount of Doge. (Probably not a number)
*
* @apiErrorExample Error-Response (example):
* HTTP/1.1 200 OK
* "Invalid Amount"
*
*/ |
/*
*
* DashboardContainer
*
*/
import React from 'react';
import Helmet from 'react-helmet';
export default class DashboardContainer extends React.PureComponent {
constructor(props){
super(props);
this.state ={
title:"",
body:"",
image:"",
preview:"",
}
}
handleTitle = (event) => {
this.setState({
title:event.target.value
})
console.log(this.state.title);
}
handleBody = (event) => {
this.setState({
body:event.target.value
})
console.log(this.state.body);
}
handleImage = (event) => {
event.preventDefault();
let reader = new FileReader();
let file = event.target.files[0];
reader.onloadend= () => {
this.setState({
image:file,
preview: reader.result
})
}
reader.readAsDataURL(file);
}
storeArticle = () => {
var data = new FormData();
data.append("title",this.state.title);
data.append("body",this.state.body);
data.append("image",this.state.image);
fetch("http://owlversee.com/api/storeArticle",{
method:"post",
body:data
})
.then(function(response) {
return response.json();
})
.then(function(json) {
if(json.success) {
alert(json.success);
}
else if(json.error) {
alert(json.error);
}
})
}
render() {
const dashEnv={
height:"100vh",
width:"100%",
backgroundColor:"rgba(3,150,3,.3)",
padding:"10%",
justifyContent:"center",
}
const dashForm={
backgroundColor:"rgba(160,255,160,1)",
display:"flex",
flexDirection:"column",
padding:"5%",
boxShadow:"0 0 20px 5px rgba(0,0,0,0.4)",
borderRadius:"2px",
}
const dashBoxColor={
height:"auto",
width:"auto",
backgroundColor:"rgba(220,255,220,1)",
marginBottom:"3%",
border:"1px solid green",
maxHeight:"500px",
overflow:"hidden",
padding:"10"
}
const dashTitle={
fontSize:"3em",
textAlign:"center",
fontWeight:"bold",
fontVariant:"small-caps",
fontFamily:"Lato",
color:"green",
}
const imgConstraint={
maxHeight:"600px",
margin:"10",
}
return (
<div style={dashEnv}>
<div style={dashForm}>
<Helmet title="DashboardContainer" meta={[ { name: 'description', content: 'Description of DashboardContainer' }]}/>
<div style={dashTitle}>
GreenWorx Article Dash
</div>
<div style={dashBoxColor}>
<input onChange={this.handleTitle} type="text" placeholder="New Title"/>
</div>
<div style={dashBoxColor}>
<textarea onChange={this.handleBody} rows="5" placeholder="Write Body"> </textarea>
</div>
<div style={dashBoxColor}>
<input onChange={this.handleImage} type="file"/>
<img style={imgConstraint} src={this.state.preview}/>
</div>
<div style={dashBoxColor}>
<input onTouchTap={this.storeArticle} type="submit"/>
</div>
</div>
</div>
);
}
}
|
/**!
* urlencode - lib/urlencode.js
*
* Copyright(c) 2012 - 2014
* MIT Licensed
*
* Authors:
* fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
*/
"use strict";
/**
* Module dependencies.
*/
var iconv = require('iconv-lite');
function isUTF8(charset) {
if (!charset) {
return true;
}
charset = charset.toLowerCase();
return charset === 'utf8' || charset === 'utf-8';
}
function encode(str, charset) {
if (isUTF8(charset)) {
return encodeURIComponent(str);
}
var buf = iconv.encode(str, charset);
var encodeStr = '';
for (var i = 0; i < buf.length; i++) {
encodeStr += '%' + buf[i].toString('16');
}
encodeStr = encodeStr.toUpperCase();
return encodeStr;
}
function decode(str, charset) {
if (isUTF8(charset)) {
return decodeURIComponent(str);
}
var bytes = [];
for (var i = 0; i < str.length; ) {
if (str[i] === '%') {
i++;
bytes.push(parseInt(str.substring(i, i + 2), 16));
i += 2;
} else {
bytes.push(str.charCodeAt(i));
i++;
}
}
var buf = new Buffer(bytes);
return iconv.decode(buf, charset);
}
module.exports = encode;
module.exports.encode = encode;
module.exports.decode = decode;
module.exports.parse = require('./parse');
module.exports.stringify = require('./stringify');
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.