code stringlengths 2 1.05M |
|---|
define(function() {
var UrbanPlugin = function(mod) {
var UrbanCommandHandler = function(cmd, args) {
if (args.length < 1) {
return;
}
$.ajax({
url: 'http://api.urbandictionary.com/v0/define',
traditional: true,
data: {
'term': args
},
dataType: 'json',
success: function(result) {
if (result && result.hasOwnProperty('list')) {
var definition = result['list'][0]['definition'];
definition = definition.replace(/(?:\r\n|\r|\n)/g, ' ');
var message = '!' + cmd + ' ' + args + ' - ' + definition;
InfernoShoutbox.postShout(message);
}
}
});
};
mod.registerCommand('urban', UrbanCommandHandler);
};
return {
id: 'urban',
init: UrbanPlugin
};
}); |
'use strict';
const test = require('ava');
const combijson = require('.');
test('handles zero arguments', t => {
t.deepEqual(combijson(), {});
});
test('handles empty object', t => {
t.deepEqual(combijson([{}]), {});
});
test('takes just one object', t => {
const obj = {hello: 'test'};
t.deepEqual(combijson([obj]), obj);
});
test('merges two objects', t => {
const obj1 = {hello: 'test'};
const obj2 = {hello: 'world', testing: 'tests'};
const obj3 = {hello: 'test', testing: 'tests'};
t.deepEqual(combijson([obj1, obj2]), obj3);
});
test('merges three objects', t => {
const obj1 = {hello: 'test', feeling: 'good'};
const obj2 = {hello: 'test', feeling: 'mad', randomText: true};
const obj3 = {hello: 'test', randomText: false, turtles: 'rock'};
const obj4 = {
hello: 'test',
feeling: 'good',
turtles: 'rock',
randomText: true,
};
t.deepEqual(combijson([obj1, obj2, obj3]), obj4);
});
test('merges nested objects', t => {
const obj1 = {hello: {msg: true}};
const obj2 = {hello: {msg: false, colour: 'blue'}};
const obj3 = {hello: {msg: true, colour: 'blue'}};
t.deepEqual(combijson([obj1, obj2]), obj3);
const obj4 = {hello: {}};
const obj5 = {hello: {world: {msg: true}}};
const obj6 = {hello: {world: {msg: false}}};
const obj7 = {hello: {world: {msg: true}}};
t.deepEqual(combijson([obj4, obj5, obj6]), obj7);
});
test('merges JSON strings', t => {
const obj1 = '{"hello": "world"}';
const obj2 = '{"hello": "world"}';
const obj3 = '{"hello": "there", "weather": "nice"}';
const obj4 = {hello: 'world', weather: 'nice'};
t.deepEqual(combijson([obj1, obj2, obj3]), obj4);
});
test('merges JSON strings and objects', t => {
const obj1 = '{"hello": "world"}';
const obj2 = {hello: 'there', weather: 'nice'};
const obj3 = {hello: 'world', weather: 'nice'};
t.deepEqual(combijson([obj1, obj2]), obj3);
});
test('fails with arguments of wrong type', t => {
t.deepEqual(combijson([2]), new Error('Expected object or JSON string'));
});
|
// Promise-like mock, to be used for sync resolution of modules
"use strict";
const PassThru = (module.exports = function (value) { this.value = value; });
PassThru.prototype.then = function (fn) {
const result = fn(this.value);
if (result instanceof PassThru) return result;
return new PassThru(result);
};
|
"use strict";
const repl = require('repl');
var msg = 'message';
var rx = require("./lib/index");
var utils = require("./lib/utils");
var rxTree = require("./lib/rxtree");
//Create node repl
var c = repl.start('> ').context;
// Exports the following:
// incrRegEx - utility function to parse a regular expression an (combines RxParser, and IREGEX),
// instance of an incremental matcher IREGEX;
//
// Matching Status
// ---------------
// DONE - regexp is done matching, it will match no further charactes
// MORE - Regex is not yet done, (so far so good) but requires more characters
// MAYBE - Maybe DONE, match is complete but will accept more characters,
// e.g. /abc[0-9]{1,4}/
// after you enter 'ab1' will return MAYBE status,
// after you enter 'ab15678' will return DONE
// FAILED - the last char(s) entered are not allowed
//
// RXInputMask - utility class that provides support for providing
// support to an html input element support as you type regex checking (and a whole lot more)
// see npm project (react-maskinput)
// RxParser - parse a Regular Expression (this is a utility class)
// IREGEX - class that matches a regular expression
//
// Utilities
// ---------
// printExpr,
// matchable,dot,or,zero_or_one,zero_or_more - utilities to walk the regex tree structure
// isMeta, isOptional,isHolder - utilities used by RXInputMask
// contract - general contracts checking see: https://github.com/metaweta/jscategory/blob/master/jscategory.js
// convertMask - utility to convert 'mask' meta-cheracters to ascii characters
// Add names to the repl context
// rx, incrRegEx, printExpr, p, RXInputMast
//
// Note: c = repl context
c.rxTree = rxTree;
c.rxStepArr = rxTree.rxStepArr;
c.advancedRxMatcher = rxTree.advancedRxMatcher;
c.rx = rx;//
c.help = function(containsStr) {
var s = "";
var v;
for(v in c) {
if( containsStr && v.toLowerCase().indexOf(containsStr) < 0) continue;
s += v + " "
}
console.log("avaliable variables: "+ s);
}
c.StackDedup = utils.StackDedup;
c.utils = utils;
c.RX= c.rx.RxParser;
c.p = new c.RX();
c.RXInputMask = c.rx.RXInputMask;
c.RxMatcher = c.rx.RxMatcher;
c.MANY = rx.MANY; c.TERM = rx.TERM; c.PERHAPS_MORE = rx.PERHAPS_MORE; c.BOUNDARY = rx.BOUNDARY; c.matchable = rx.matchable;
c.boundary = rx.boundary; c.dot = rx.dot; c.or = rx.or; c.zero_or_one = rx.zero_or_one; c.zero_or_more = rx.zero_or_more;
c.anychar = rx.anychar; c.charset = rx.charset; c.OP = rx.OP; c.SKIP = rx.SKIP; c.BS = rx.BS; c.LP = rx.LP; c.RP = rx.RP;
c.OR = rx.OR; c.ZERO_OR_ONE = rx.ZERO_OR_ONE; c.ZERO_OR_MORE = rx.ZERO_OR_MORE; c.ONE_OR_MORE = rx.ONE_OR_MORE; c.DOT = rx.DOT;
c.FALSE = rx.FALSE; c.DONE = rx.DONE; c.MAYBE = rx.MAYBE; c.MORE = rx.MORE; c.FAILED = rx.FAILED; c.RX_OP = rx.RX_OP;
c.RX_UNARY = rx.RX_UNARY; c.RX_CONS = rx.RX_CONS; c.RX_OR = rx.RX_OR; c.RX_ZERO_OR_ONE = rx.RX_ZERO_OR_ONE;
c.RX_ZERO_OR_MORE = rx.RX_ZERO_OR_MORE; c.RX_ONE_OR_MORE = rx.RX_ONE_OR_MORE; c.copyNode = rx.copyNode; c.stdRxMeta = rx.stdRxMeta;
c.makeCharSet = rx.makeCharSet; c.makeFSM = rx.makeFSM; c.rxMatchArr = rx.rxMatchArr; c.rxNextState = rx.rxNextState;
c.rxMatch = rx.rxMatch; c.rxCanReach = rx.rxCanReach; c.rxGetActualStartState = rx.rxGetActualStartState;
c.advancedRxMatcher = rx.advancedRxMatcher; c.incrRegEx = rx.incrRegEx; c.printExpr = rx.printExpr; c.printExprS = rx.printExprS;
c.RxParser = rx.RxParser; c.RXInputMask = rx.RXInputMask; c.contract = rx.contract; c.RxMatcher = rx.RxMatcher;
c.matchable = rx.matchable; c.dot = rx.dot; c.or = rx.or; c.zero_or_one = rx.zero_or_one; c.zero_or_more = rx.zero_or_more;
c.IREGEX = rx.IREGEX; c.convertMask = rx.convertMask; c.isMeta = rx.isMeta; c.isOptional = rx.isOptional; c.isHolder = rx.isHolder;
c.insx = function (rxi) {
return function(str) {
for(var i=0; i<str.length; i++) {
rxi.input(str.charAt(i));
}
};
};
c.emailStr = "Mail: [a-zA-Z0-9_.-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]{2,})*(\\.[a-zA-Z0-9_-]{2,8})|ssn: \\d{3}-\\d{2}-\\d{4}|Phone: (\\+\\d{1,3})? \\(\\d{3}\\)-\\d{3}-\\d{4}";
c.email = c.incrRegEx(c.emailStr);
c.anRx = c.incrRegEx(/aa[a-zA-Z]+@@\d+!!/); // create an incremental matcher for regex.
c.funky = new c.RxMatcher(c.anRx); // create a matcher fron an existing matcher
c.rxi1 = new c.RXInputMask({pattern: /aa[a-zA-Z]+@@\d+!!/ });
c.rxi = new c.RXInputMask({pattern: /\+\(\d{3}\)-\d{3}-\d{4}|#\d{3}\.\d{3}X?YZ| ?\d{3}---\d{4}\./ });
c.sel = { start: 0, end: 1};
c.im = new c.RXInputMask({pattern: "aa[a-zA-Z]+@\\d+"});
function st(arr) { return arr.map(c.printExpr).toArray().join("\n"); }
function ot(iRx) {
return iRx.current === iRx.one? iRx.two : iRx.one;
}
c.st = st;
c.ot = ot;
c.pr =pr;
c.getStr = getStr;
c.getStateLen = getStateLen;
c.getStateFixed = getStateFixed;
c.x = c.incrRegEx(/...\b\b../);
function st(arr) { return arr.map(c.printExpr).toArray().join("\n"); }
function ot(iRx) {
return iRx.current === iRx.one? iRx.two : iRx.one;
}
function pr(iRx) {
return ["match: [" + st(iRx.current)+"]\n",
"prev: [" + st(ot(iRx))+"]\n",
iRx.tracker.map(a => '<'+a[0]+'>').join("")];
}
// arr = [ [state, ch] ...]
/*
function getStr(arr) {
return arr.reduce( (str, [state,ch]) => str+ch, '');
}
function getStateLen(arr) {
//return arr.map( ([[state],ch]) => state === undefined?0:state.length);
}
function getStateFixed(arr) {
const fx = (
([state,ch]) => state === undefined? '~' : (getArrayFixedAt(state[1]) || '_')
);
return arr.map( fx );
}
*/
|
import { Constants } from 'alpheios-data-models'
import Suffix from '@lib/suffix.js'
import GreekView from '@views/lang/greek/greek-view.js'
export default class GreekAdjectiveView extends GreekView {
constructor (homonym, inflectionData) {
super(homonym, inflectionData)
this.id = 'adjectiveDeclension'
this.name = 'adjective declension'
this.title = 'Adjective declension'
if (this.isImplemented) {
this.createTable()
}
}
static get viewID () {
return 'greek_adjective_view'
}
static get partsOfSpeech () {
return [Constants.POFS_ADJECTIVE]
}
static get inflectionType () {
return Suffix
}
static getOrderedGenders (ancestorFeatures) {
const ancestorValue = ancestorFeatures.length > 0 ? ancestorFeatures[ancestorFeatures.length - 1].value : ''
if (ancestorValue === Constants.ORD_2ND) {
return [
this.featureMap.get(GreekView.datasetConsts.GEND_MASCULINE_FEMININE),
this.featureMap.get(Constants.GEND_NEUTER)
]
} else if (ancestorValue === Constants.ORD_3RD) {
return [
this.featureMap.get(Constants.GEND_FEMININE),
this.featureMap.get(GreekView.datasetConsts.GEND_MASCULINE_FEMININE),
this.featureMap.get(Constants.GEND_NEUTER)
]
} else {
return [
this.featureMap.get(Constants.GEND_FEMININE),
this.featureMap.get(Constants.GEND_MASCULINE),
this.featureMap.get(Constants.GEND_NEUTER)
]
}
}
}
|
var config = require('../../config/baseConfig.js');
var utility = require('../lib/utility.js');
var mysqlHelper = require('../lib/mysqlHelper.js');
var mysql=new mysqlHelper(config.basicSettings.currentDb);
var logger = require('../lib/logger.js');
/**
* 查询当前用户所在系统的部门和部门下的所有子部门
* @param params
* @param cb
*/
function getGroupInfo(params,cb){
var sql = 'CALL proc_get_core_group_bysys_userid(?,?)';
mysql.executeQueryNoCache({sql: sql, params: params, cb: function (err, result) {
if (cb) {
cb(err, result);
}
}});
}
/**
* 添加角色部门数据
* @param params
* @param cb
*/
function addGroupInfo(params,cb){
var sql = 'CALL proc_add_core_group(?,?,?,?,?)';
mysql.executeQueryNoCache({sql: sql, params: params, cb: function (err, result) {
if (cb) {
cb(err, result);
}
}});
}
/**
* 修改角色部门数据
* @param params
* @param cb
*/
function updateGroupInfo(params,cb){
var sql = 'CALL proc_update_core_group(?,?,?,?,?)';
mysql.executeQueryNoCache({sql: sql, params: params, cb: function (err, result) {
if (cb) {
cb(err, result);
}
}});
}
/**
* 删除角色部门数据
* @param params
* @param cb
*/
function deleteGroupInfo(params,cb){
var sql = 'CALL proc_delete_core_group(?,?,?,?,?)';
mysql.executeQueryNoCache({sql: sql, params: params, cb: function (err, result) {
if (cb) {
cb(err, result);
}
}});
}
/**
* 获取组在所有模块中的权限
* @param params
* @param cb
*/
function getGroupModuleAction(params,cb){
var sql = 'CALL proc_get_model_system_group_action(?,?)';
mysql.executeQueryNoCache({sql: sql, params: params, cb: function (err, result) {
if (cb) {
cb(err, result);
}
}});
}
/**
* 保存部门权限
* 保存部门、模块、行为之间的关系
* @param params
* @param cb
*/
function addGroupAction(params,cb){
var sql = 'CALL proc_add_core_group_module(?,?,?)';
mysql.executeQueryNoCache({sql: sql, params: params, cb: function (err, result) {
if (cb) {
cb(err, result);
}
}});
}
/**
* 查询当前用户所在系统的部门和部门下的所有子部门
* 例如:params={systemId:2,userId:2}
* @param req
* @param res
*/
exports.getGroupInfo=function (req, res){
var params = utility.parseParams(req), sqlParams = [],systemInfo=req.session.systemInfo;
if (utility.isValidData(params.systemId)) {
sqlParams.push(params.systemId);
}
else {
sqlParams.push(systemInfo.systemId)
}
if (utility.isValidData(params.userId)) {
sqlParams.push(params.userId);
}
else {
sqlParams.push(systemInfo.userId);
}
getGroupInfo(sqlParams,callback)
function callback(err, result) {
var returnData={};
if (err) {
returnData=utility.jsonResult('获取数据失败!');
logger.error({message: err.message, req: req, method: this.name});
}
else {
returnData=utility.jsonResult(null,null,result[0],result[1].count);
}
res.send(returnData);
}
}
/**
* 添加或修改角色部门数据
* @param req
* @param res
*/
exports.editGroup=function (req, res){
var params = utility.parseParams(req), sqlParams = [],systemInfo=req.session.systemInfo;
if (utility.isValidData(params.id)) {
sqlParams.push(params.id);
}
if (utility.isValidData(params.name)) {
sqlParams.push(params.name);
}
else {
return res.send(utility.jsonResult('名称不能为空!'));
}
if (utility.isValidData(params.state)) {
sqlParams.push(params.state);
}
else {
sqlParams.push(1);
}
if (utility.isValidData(params.parentId)) {
sqlParams.push(params.parentId);
}
else {
return res.send(utility.jsonResult('部门不能为空!'));
}
if (utility.isValidData(params.userId)) {
sqlParams.push(params.userId);
}
else {
sqlParams.push(systemInfo.userId);
}
if (utility.isValidData(params.systemId)) {
sqlParams.push(params.systemId);
}
else {
sqlParams.push(systemInfo.systemId)
}
//编辑
if (utility.isValidData(params.id)) {
updateGroupInfo(sqlParams,callback);
}
//添加
else{
addGroupInfo(sqlParams,callback);
}
function callback(err, result) {
var returnData={};
if (err) {
returnData=utility.returnJson('保存数据失败!');
logger.error({message: err.message, req: req, method: this.name});
}
else {
returnData=utility.jsonResult(null,null,result[0],0);
}
res.send(returnData);
}
}
/**
* 根据id删除角色部门数据
* 例如:params={systemId:2,id:2}
* @param req
* @param res
* @returns {*}
*/
exports.deleteGroupInfo=function (req, res){
var params = utility.parseParams(req), sqlParams = [],systemInfo=req.session.systemInfo;
if (utility.isValidData(params.id)) {
sqlParams.push(params.id);
}
else{
return res.send(utility.jsonResult('Id不能为空!'));
}
if (utility.isValidData(params.systemId)) {
sqlParams.push(params.systemId);
}
else {
sqlParams.push(systemInfo.systemId)
}
function callback(err, result) {
var returnData={};
if (err) {
returnData=utility.returnJson('删除数据失败!');
logger.error({message: err.message, req: req, method: this.name});
}
else {
returnData=utility.jsonResult(null,null,result[0],0);
}
res.send(returnData);
}
}
/**
* 获取用户在所有模块中的权限
* @param req
* @param res
* @returns {*}
*/
exports.getGroupModuleAction=function (req, res){
var params = utility.parseParams(req), sqlParams = [],systemInfo=req.session.systemInfo;
if (utility.isValidData(params.systemId)) {
sqlParams.push(params.systemId);
}
else {
sqlParams.push(systemInfo.systemId)
}
if (utility.isValidData(params.groupId)) {
sqlParams.push(params.groupId);
}
else{
return res.send(utility.jsonResult('部门id不能为空!'));
}
getGroupModuleAction(sqlParams,callback);
function callback(err, result) {
var returnData={};
if (err) {
returnData=utility.returnJson('获取数据失败!');
logger.error({message: err.message, req: req, method: this.name});
}
else {
returnData=utility.jsonResult(null,null,result[0],0);
}
res.send(returnData);
}
}
/**
* 保存部门权限
* 保存部门、模块、行为之间的关系
* @param req
* @param res
*/
exports.addGroupPermission=function (req, res){
var params = utility.parseParams(req), sqlParams = [],systemInfo=req.session.systemInfo,insertAction="",actions;
if (utility.isValidData(params.systemId)) {
sqlParams.push(params.systemId);
}
else {
sqlParams.push(systemInfo.systemId)
}
if (utility.isValidData(params.groupId)) {
sqlParams.push(params.groupId);
}
else{
return res.send(utility.jsonResult('部门id不能为空!'));
}
if (utility.isValidData(params.actions)) {
actions = JSON.parse(params.actions)
}
else{
actions=[];
}
for(var i=0;i<actions.length;i++) {
var row = actions[i];
if (insertAction == "") {
insertAction = "(" + sqlParams[0] + "," + sqlParams[1] + "," + row.moduleId + "," + row.id + ",'" + row.showName + "')";
}
else {
insertAction += ",(" + sqlParams[0] + "," + sqlParams[1] + "," + row.moduleId + "," + row.id + ",'" + row.showName + "')";
}
}
sqlParams.push(insertAction);
addGroupAction(sqlParams,callback);
function callback(err, result) {
var returnData = {};
if (err) {
returnData = utility.returnJson('保存数据失败!');
logger.error({message: err.message, req: req, method: this.name});
}
else {
returnData = utility.jsonResult(null, null, result[0], 0);
var returntext = result[0][0].returntext;
if (returntext == "1") {
returnData = utility.jsonResult(null, "保存成功", returntext, 0);
}
else {
returnData = utility.jsonResult("保存数据失败");
}
}
res.send(returnData);
}
}
|
'use strict';
const
express = require('express'),
app = express(),
expressWs = require('express-ws')(app),
os = require('os'),
pty = require('pty.js'),
shortid = require('shortid'),
spawn = require('child_process').spawn,
RateLimit = require('express-rate-limit');
// rate limiter
app.enable('trust proxy');
let limiter = new RateLimit({
windowMs: 30 * 60 * 1000, // 30 minutes
delayAfter: 10, // begin slowing down responses after the first request
delayMs: 2 * 1000, // slow down subsequent responses by 2 seconds per request
max: 15, // start blocking after 30 requests
message: "Too many requests from this IP, please try again after 30 minutes"
});
// apply to all requests
app.use("/terminals", limiter);
let terminals = {},
logs = {};
app.use(express.static(__dirname + '/public'));
app.use("/xterm", express.static(__dirname + '/../node_modules/xterm'));
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.post('/terminals', (req, res) => {
let cols = parseInt(req.query.cols),
rows = parseInt(req.query.rows),
repl_name = shortid.generate(),
term = pty.spawn('docker', ["run", "-it", "--name", repl_name, "wunsh/alpine-elm:latest", "repl"], {
name: 'xterm-color',
cols: cols || 80,
rows: rows || 32,
cwd: process.env.PWD,
env: process.env
});
console.log(`Created terminal with PID: ${term.pid}, container: ${repl_name}, size: ${cols}x${rows}`);
// console.log(simpleStringify(term));
terminals[repl_name] = term;
logs[repl_name] = '';
term.on('data', (data) => {
logs[repl_name] += data;
});
res.send(repl_name);
res.end();
});
app.post('/terminals/:repl_name/size', (req, res) => {
let term = terminals[req.params.repl_name],
pid = parseInt(term.pid),
cols = parseInt(req.query.cols),
rows = parseInt(req.query.rows);
term.resize(cols, rows);
console.log('Resized terminal ' + req.params.repl_name + ' to ' + cols + ' cols and ' + rows + ' rows.');
res.end();
});
app.ws('/ws/:repl_name', (ws, req) => {
let repl_name = req.params.repl_name,
term = terminals[repl_name];
console.log('Connected to terminal ' + repl_name);
try {
ws.send(logs[repl_name]);
} catch (ex) {
console.error(ex)
ws.close();
}
term.on('data', (data) => {
try {
ws.send(data);
} catch (ex) {
// The WebSocket is not open, ignore
}
});
term.on('exit', (code, signal) => {
try {
ws.close();
} catch (ex) {
console.error(ex)
}
});
ws.on('message', (msg) => {
try {
term.write(msg);
} catch (ex) {
console.error(ex)
ws.close();
}
});
ws.on('close', () => {
try {
let stop_container = spawn('docker', ["rm", "-f", repl_name]);
stop_container.on('close', code => {
console.log("stop_container exited with code " + code);
});
stop_container.stdout.on('data', data => {
console.log(`stdout: ${data}`);
});
stop_container.stderr.on('data', data => {
console.log(`stderr: ${data}`);
});
// Clean things up
delete terminals[repl_name];
delete logs[repl_name];
} catch (ex) {
console.error(ex)
}
});
});
var port = process.env.PORT || 3000,
host = '127.0.0.1';
console.log('App listening to http://' + host + ':' + port);
app.listen(port, host);
// helpers
let simpleStringify = (object) => {
let simpleObject = {};
for (let prop in object) {
if (!object.hasOwnProperty(prop)) {
continue;
}
if (typeof(object[prop]) == 'object') {
continue;
}
if (typeof(object[prop]) == 'function') {
continue;
}
simpleObject[prop] = object[prop];
}
return JSON.stringify(simpleObject); // returns cleaned up JSON
};
|
import mod578 from './mod578';
var value=mod578+1;
export default value;
|
/**
* Temperature module. This module was created to be used with a TMP36 temperature sensor.
* The TMP36 needs to be wired to the beaglebone's 3.3V, GNDA_ADC, and AIn_1 (pin #40).
* Wiring diagram: https://learn.adafruit.com/system/assets/assets/000/009/312/medium800/beaglebone_fritzing.png
* @module lib/temperature
* @author Brandon Kite
*/
if (process.env.MODE === 'desktop') {
var _ = require('./_');
module.exports.readTemperature = function(callback) {
callback(_.random(37, 38)); // dummy data
}
} else {
var bs = require('bonescript');
var SENSOR_PIN = 'P9_40';
/**
* Read the temperature sensor.
* @param {requestCallback} cb - The callback that handles the response.
*/
function readTemperature(callback) {
//voltage range [0, 1.8]
bs.analogRead(SENSOR_PIN, function(v_in) {
var millivolts = v_in.value * 1800; // 1.8V reference = 1800 mV
var temp_c = (millivolts - 500) / 10;
var temp_f = (temp_c * 9 / 5) + 32;
callback(temp_f);
});
}
module.exports.readTemperature = readTemperature;
}
/**
* The callback to handle the temperature reading
* @callback requestCallback
* @param {number} temperature - The temperature reading in fahrenheit.
*/
/**
* Warning: The analog inputs of the BBB operate at 1.8V.
* Since the TMP36 has a theoretical maximum output of 3.3V,
* there is a potential for the BBB to be damaged if the voltage in millivolts exceeds 1.8V.
* This will only happen on a TMP36 if the temperature exceeds 130 degrees C (266 degrees F).
*/
|
"use strict";
const test = require("ava");
const { parse } = require(".");
const jid = require("@xmpp/jid");
test("parse", (t) => {
t.deepEqual(
parse(
"xmpp://guest@example.com/support@example.com/truc?message;subject=Hello%20World",
),
{
authority: jid("guest@example.com"),
path: jid("support@example.com/truc"),
query: {
type: "message",
params: {
subject: "Hello World",
},
},
},
);
t.deepEqual(jid("foobar"), jid("foobar"));
t.deepEqual(
parse(
"xmpp:support@example.com/truc?message;subject=Hello%20World;body=foobar",
),
{
path: jid("support@example.com/truc"),
query: {
type: "message",
params: {
subject: "Hello World",
body: "foobar",
},
},
},
);
t.deepEqual(parse("xmpp:support@example.com/truc"), {
path: jid("support@example.com/truc"),
});
t.deepEqual(parse("xmpp:support@example.com/"), {
path: jid("support@example.com/"),
});
t.deepEqual(parse("xmpp:support@example.com/?foo"), {
path: jid("support@example.com/"),
query: {
type: "foo",
params: {},
},
});
t.deepEqual(parse("xmpp:support@example.com?foo"), {
path: jid("support@example.com"),
query: {
type: "foo",
params: {},
},
});
});
|
require('./main.scss');
require('./main-image.scss');
require('./swiper.min.js');
var mySwiper = new Swiper('#mainSwiper', {
direction: 'vertical'
});
new Swiper('#subSwiper', {
direction: 'horizontal',
initialSlide: 1,
loop: true
});
var subscribes = document.getElementsByClassName('btn-subscribe');
subscribes = Array.prototype.slice.call(subscribes);
subscribes.forEach(function(element,index){
element.addEventListener('touchstart', function(e){
mySwiper.slideTo(6);
})
});
document.getElementById('btn-campaign-reward').addEventListener('touchstart', function(e){
toggleDetail('block');
});
var toggleDetail = function(toggle){
document.getElementsByClassName('campaign-detail-cover')[0].style.display = toggle;
document.getElementsByClassName('campaign-detail-content')[0].style.display = toggle;
}
document.getElementsByClassName('campaign-detail-cover')[0].addEventListener('touchstart', function(e){
toggleDetail('none');
});
document.getElementsByClassName('campaign-detail-content')[0].addEventListener('touchstart', function(e){
toggleDetail('none');
});
|
/* eslint-env jest */
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import mockAsyncStorage from '@react-native-async-storage/async-storage/jest/async-storage-mock'
Enzyme.configure({
adapter: new Adapter()
})
function suppressDomErrors() {
const regex = new RegExp('(Use PascalCase for React components)|'
+ '(is unrecognized in this browser)|'
+ '(Unknown event handler property)|'
+ '(React does not recognize the .* prop on a DOM element)|'
+ '(for a non-boolean attribute)')
const actualConsoleError = console.error;
console.error = (...args) => {
const message = args[0]
if (!regex.test(message)) {
actualConsoleError(...args)
}
}
}
suppressDomErrors()
jest.mock('@react-native-async-storage/async-storage', () => (
mockAsyncStorage
))
|
export default String('\n\
#ifdef USE_LIGHTMAP\n\
\n\
reflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity; // factor of PI should not be present; included here to prevent breakage\n\
\n\
#endif\n\
').replace( /[ \t]*\/\/.*\n/g, '' ).replace( /[ \t]*\/\*[\s\S]*?\*\//g, '' ).replace( /\n{2,}/g, '\n' ); |
/// <binding ProjectOpened='preload_debug' />
/*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
var gulp = require('gulp');
var merge = require('merge2');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglifyjs');
var rename = require("gulp-rename");
var runSequence = require("run-sequence");
var ts = require("gulp-typescript");
var less = require("gulp-less");
var minifyCSS = require("gulp-minify-css");
var typedoc = require("gulp-typedoc");
var jasmineBrowser = require('gulp-jasmine-browser');
var spritesmith = require('gulp.spritesmith');
var git = require('gulp-git');
var exec = require('child_process').exec;
var tslint = require('gulp-tslint');
var download = require("gulp-download");
var unzip = require("gulp-unzip");
var fs = require("fs");
var minimist = require("minimist");
var os = require("os");
var open = require("gulp-open");
var gutil = require('gulp-util');
require('require-dir')('./gulp');
// Command line option:
// --fatal=[warning|error|off]
var fatalLevel = require('yargs').argv.fatal;
var isDebug = false;
var cliOptions = {
string: [
"files",
"openInBrowser"
],
boolean: "debug",
alias: {
files: "f",
debug: "d",
openInBrowser: ["o", "oib"]
}
};
var cliArguments = minimist(process.argv.slice(2), cliOptions);
isDebug = Boolean(cliArguments.debug);
function getOptionFromCli(cliArg) {
if (cliArg && cliArg.length > 0) {
return cliArg.split(/[,;]/);
}
return [];
}
var filesOption = getOptionFromCli(cliArguments.files);
var jsUglifyOptions = {
compress: {
drop_console: true,
pure_funcs: [
"debug.assertValue",
"debug.assertFail",
"debug.assert",
"debug.assertAnyValue"
],
warnings: false,
dead_code: true,
sequences: true,
properties: true,
conditionals: true,
comparisons: true,
booleans: true,
cascade: true,
unused: true,
loops: true,
if_return: true,
join_vars: true,
global_defs: {
"DEBUG": false
}
}
};
/* ------------------------ GET PATH --------------------------------------- */
function getPathsForVisualsTests(paths) {
var includePaths = [];
if (paths && paths.length > 0) {
includePaths.push("_references.ts");
includePaths = includePaths.concat(paths.map(function (path) {
return "visuals/" + path;
}));
}
return includePaths;
}
function getBuildPaths(projectPath, outFileName, includePaths) {
var paths = [];
if (includePaths && includePaths.length > 0) {
paths = paths.concat(includePaths.map(function (path) {
return projectPath + "/" + path;
}));
} else {
paths.push(projectPath + "/**/*.ts");
}
paths.push("!" + projectPath + "/obj/**");
paths.push("!" + projectPath + "/**/*.d.ts");
return paths;
}
/* --------------------------- BUILD PROJECTS---------------------------------- */
var dontEmitTSbuildErrors = false;
function buildProject(projectPath, outFileName, includePaths) {
var paths = getBuildPaths(projectPath, outFileName, includePaths);
var srcResult = gulp.src(paths);
if (isDebug)
srcResult = srcResult.pipe(sourcemaps.init());
var tscResult = srcResult
.pipe(ts({
sortOutput: true,
target: "ES5",
declarationFiles: true,
noEmitOnError: dontEmitTSbuildErrors,
out: projectPath + "/obj/" + outFileName + ".js"
}));
if (isDebug) {
tscResult.js = tscResult.js.pipe(sourcemaps.write());
}
if (isDebug)
return merge([tscResult.js.pipe(gulp.dest("./")),
tscResult.dts.pipe(gulp.dest("./"))]);
else
return merge([tscResult.dts.pipe(gulp.dest("./")),
tscResult.js
.pipe(uglify(outFileName + ".js", jsUglifyOptions))
.pipe(gulp.dest(projectPath + "/obj"))
]);
}
gulp.task("build_visuals_common", function () {
return buildProject("src/Clients/VisualsCommon", "VisualsCommon");
});
gulp.task("build_visuals_data", function () {
return buildProject("src/Clients/VisualsData", "VisualsData");
});
gulp.task("build_visuals_project", function () {
return buildProject("src/Clients/Visuals", "Visuals");
});
gulp.task("build_visuals_playground_project", function () {
return buildProject("src/Clients/PowerBIVisualsPlayground", "PowerBIVisualsPlayground");
});
gulp.task("build_visuals_tests", function () {
return buildProject(
"src/Clients/PowerBIVisualsTests",
"PowerBIVisualsTests",
getPathsForVisualsTests(filesOption));
});
/* --------------------------- LESS/CSS ---------------------------------- */
gulp.task("build_visuals_sprite", function () {
var spriteData = gulp.src("src/Clients/Visuals/images/sprite-src/*.png").pipe(spritesmith({
imgName: "images/visuals.sprites.png",
cssName: "styles/sprites.less"
}));
return spriteData.pipe(gulp.dest("src/Clients/Visuals/"));
});
gulp.task("build_visuals_less", function () {
var css = gulp.src(["src/Clients/Externals/ThirdPartyIP/jqueryui/1.11.4/jquery-ui.min.css",
"src/Clients/Visuals/styles/visuals.less"])
.pipe(less())
.pipe(concat("visuals.css"));
if (!isDebug) {
css = css.pipe(minifyCSS());
}
return css.pipe(gulp.dest("build/styles"))
.pipe(gulp.dest("src/Clients/PowerBIVisualsPlayground"));
});
/* -------------- COMBINERS LINKERS CONCATENATORS ------------------------- */
function concatFilesWithSourceMap(source, outFileName) {
var result = source;
if (isDebug)
result = result.pipe(sourcemaps.init({loadMaps: true}));
result = result.pipe(concat(outFileName));
if (isDebug)
result = result.pipe(sourcemaps.write());
return result;
}
var internalsPaths = ["src/Clients/VisualsCommon/obj/VisualsCommon.js",
"src/Clients/VisualsData/obj/VisualsData.js",
"src/Clients/Visuals/obj/Visuals.js"];
gulp.task("combine_internal_js", function () {
var srcResult = gulp.src(internalsPaths);
if (isDebug)
return concatFilesWithSourceMap(srcResult, "powerbi-visuals.js")
.pipe(concat("powerbi-visuals.js"))
.pipe(gulp.dest("build/scripts"))
.pipe(gulp.dest("src/Clients/PowerBIVisualsPlayground"))
else
return concatFilesWithSourceMap(srcResult, "powerbi-visuals.js")
.pipe(uglify("powerbi-visuals.js", jsUglifyOptions))
.pipe(gulp.dest("build/scripts"))
.pipe(gulp.dest("src/Clients/PowerBIVisualsPlayground"));
});
gulp.task("combine_internal_d_ts", function () {
return gulp.src([
"src/Clients/VisualsCommon/obj/VisualsCommon.d.ts",
"src/Clients/VisualsData/obj/VisualsData.d.ts"
])
.pipe(concat("powerbi-visuals.d.ts"))
.pipe(gulp.dest("build"));
});
gulp.task("combine_all", function () {
var src = [
"build/scripts/externals.min.js"
];
src.push("build/scripts/powerbi-visuals.js");
return concatFilesWithSourceMap(gulp.src(src), "powerbi-visuals.all.js")
.pipe(gulp.dest("build/scripts"));
});
/* --------------------------- EXTERNALS ---------------------------------- */
var externalsPath = ["src/Clients/Externals/ThirdPartyIP/D3/*.min.js",
"src/Clients/Externals/ThirdPartyIP/GlobalizeJS/globalize.min.js",
"src/Clients/Externals/ThirdPartyIP/GlobalizeJS/globalize.culture.en-US.js",
"src/Clients/Externals/ThirdPartyIP/JQuery/**/*.min.js",
"src/Clients/Externals/ThirdPartyIP/jqueryui/1.11.4/jquery-ui.min.js",
"src/Clients/Externals/ThirdPartyIP/LoDash/*.min.js"];
gulp.task("combine_external_js", function () {
return gulp.src(externalsPath)
.pipe(concat("externals.min.js"))
.pipe(gulp.dest("build/scripts"))
.pipe(gulp.dest("src/Clients/PowerBIVisualsPlayground"));
});
/* --------------------------- TS-LINT ---------------------------------- */
var tslintPaths = ["src/Clients/VisualsCommon/**/*.ts",
"!src/Clients/VisualsCommon*/obj/*.*",
"!src/Clients/VisualsCommon/**/*.d.ts",
"src/Clients/VisualsData/**/*.ts",
"!src/Clients/VisualsData*/obj/*.*",
"!src/Clients/VisualsData/**/*.d.ts",
"src/Clients/Visuals/**/*.ts",
"!src/Clients/Visuals*/obj/*.*",
"!src/Clients/Visuals/**/*.d.ts",
"src/Clients/PowerBIVisualsTests/**/*.ts",
"!src/Clients/PowerBIVisualsTests*/obj/*.*",
"!src/Clients/PowerBIVisualsTests/**/*.d.ts",
"src/Clients/PowerBIVisualsPlayground/**/*.ts",
"!src/Clients/PowerBIVisualsPlayground*/obj/*.*",
"!src/Clients/PowerBIVisualsPlayground/**/*.d.ts"];
gulp.task("tslint", function () {
return gulp.src(tslintPaths)
.pipe(tslint())
.pipe(tslint.report("verbose"));
});
/* --------------------------- COPY FILES ---------------------------------- */
gulp.task("copy_internal_dependencies_visuals_playground", function () {
var src = [];
src.push("src/Clients/PowerBIVisualsPlayground/obj/PowerBIVisualsPlayground.js");
return gulp.src(src)
.pipe(rename("PowerBIVisualsPlayground.js"))
.pipe(gulp.dest("src/Clients/PowerBIVisualsPlayground"))
});
/* --------------------------- WATCHERS ---------------------------------- */
var lintErrors = false;
const lintReporter = function (output, file, options) {
if (output.length > 0)
lintErrors = true;
// file is a reference to the vinyl File object
console.log("Found " + output.length + " errors in " + file.path);
for (var i = 0; i < output.length; i++)
gutil.log('TsLint Error ' + i + ': ', '', gutil.colors
.red(' line:' + output[i].endPosition.line + ', char:' + output[i].endPosition.character +
', message: ' + output[i].failure));
// options is a reference to the reporter options, e.g. including the emitError boolean
};
gulp.task('preload_debug', function (callback) {
isDebug = true;
runSequence(
"preload",
callback);
});
gulp.task('preload', function (callback) {
dontEmitTSbuildErrors = true;
// first time build
runSequence(
// "tslint", -- not really need to lint here
"build_projects",
callback);
//do stuff
gulp.watch(getBuildPaths("src/Clients/VisualsCommon", "VisualsCommon")).on("change", function (file) {
lintErrors = false;
gulp.src(file.path).pipe(tslint()).pipe(tslint.report(lintReporter).on('error', function (error) {})
.on('end', function () {
if (!lintErrors)
runSequence("build_visuals_common");
}));
});
gulp.watch(getBuildPaths("src/Clients/VisualsData", "VisualsData")).on("change", function (file) {
lintErrors = false;
gulp.src(file.path).pipe(tslint()).pipe(tslint.report(lintReporter).on('error', function (error) {})
.on('end', function () {
if (!lintErrors)
runSequence("build_visuals_data");
}));
});
gulp.watch(getBuildPaths("src/Clients/Visuals", "Visuals")).on("change", function (file) {
lintErrors = false;
gulp.src(file.path).pipe(tslint()).pipe(tslint.report(lintReporter).on('error', function (error) {})
.on('end', function () {
if (!lintErrors)
runSequence("build_visuals_project");
}));
});
gulp.watch(getBuildPaths("src/Clients/PowerBIVisualsPlayground", "PowerBIVisualsPlayground")).on("change", function (file) {
lintErrors = false;
gulp.src(file.path).pipe(tslint()).pipe(tslint.report(lintReporter).on('error', function (error) {})
.on('end', function () {
if (!lintErrors)
runSequence("build_visuals_playground");
}));
});
gulp.watch("src/Clients/Visuals/images/sprite-src/*.png", ['build_visuals_sprite']);
gulp.watch(["src/Clients/Externals/ThirdPartyIP/jqueryui/1.11.4/jquery-ui.min.css", "src/Clients/Visuals/styles/visuals.less", "src/Clients/Visuals/images/visuals.sprites.png", "src/Clients/Visuals/styles/sprites.less"], ["build_visuals_less"]);
gulp.watch(externalsPath, ['combine_external_js']);
gulp.watch(internalsPaths, ['combine_internal_js']);
});
/** ---------------------------------- DOWNLOADs ------------------------------------------*/
/** --------------------------Download 'JASMINE-jquery.js' --------------------------------*/
gulp.task('jasmine-dependency', function (callback) {
fs.exists('src/Clients/Externals/ThirdPartyIP/JasmineJQuery/jasmine-jquery.js', function (exists) {
if (!exists) {
console.log('Jasmine test dependency missing. Downloading dependency.');
download('https://raw.github.com/velesin/jasmine-jquery/master/lib/jasmine-jquery.js')
.pipe(gulp.dest("src/Clients/Externals/ThirdPartyIP/JasmineJQuery"))
.on("end", callback);
} else {
console.log('Jasmine test dependency exists.');
callback();
}
});
});
/** ------------------------------ Download PHANTOM --------------------------------------- */
gulp.task('phantomjs-dependency', function (callback) {
var zipUrl = "https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.0.0-windows.zip";
var phantomExe = "phantomjs.exe";
var jasmineBrowserDir = "./node_modules/gulp-jasmine-browser/lib/";
// Download phantomjs only for Windows OS.
if (os.type().search("Windows") !== -1) {
onPhantomjsExist(jasmineBrowserDir, function (exists, version) {
if (!exists) {
console.log('Phantomjs missing. Downloading dependency.');
download(zipUrl)
.pipe(unzip({
filter: function (entry) {
if (entry.path.search(phantomExe) !== -1) {
entry.path = phantomExe;
return true;
}
}}))
.pipe(gulp.dest(jasmineBrowserDir))
.on("end", callback);
} else {
logIfExists(version);
callback();
}
});
} else {
onPhantomjsExist(jasmineBrowserDir, function (exists, version) {
if (exists) {
logIfExists(version);
} else {
console.log("Automatic installation does not allowed for current OS [" + os.type() + "]. Please install Phantomjs manually. (https://bitbucket.org/ariya/phantomjs)");
}
});
callback();
}
function logIfExists(version) {
console.log("Phantomjs has already exist. [Version: " + version + "]");
}
function onPhantomjsExist(path, callback) {
exec("phantomjs -v", {cwd: path}, function (error, stdout) {
if (error !== null) {
callback(false, null);
} else if (stdout !== null) {
callback(true, stdout.substring(0, 5));
}
});
}
});
/** ----------------------------- TESTS ------------------------------------------- */
gulp.task("copy_internal_dependencies_visuals_tests", function () {
var src = [];
src.push("src/Clients/PowerBIVisualsTests/obj/PowerBIVisualsTests.js");
return gulp.src(src)
.pipe(rename("powerbi-visuals-tests.js"))
.pipe(gulp.dest("VisualsTests"));
});
gulp.task("copy_external_dependencies_visuals_tests", function () {
return gulp.src([
"build/scripts/powerbi-visuals.all.js"
])
.pipe(gulp.dest("VisualsTests"));
});
gulp.task("copy_dependencies_visuals_tests", function (callback) {
runSequence(
"copy_internal_dependencies_visuals_tests",
"copy_external_dependencies_visuals_tests",
callback
);
});
function addLinks(links) {
return (links.map(function (link) {
return '<link rel="stylesheet" href="' + link + '"/>';
})).join("");
}
function addScripts(scripts) {
return (scripts.map(function (script) {
return '<script src="' + script + '"></script>';
})).join("");
}
function addTestName(testName) {
if (testName && testName.length > 0) {
var specName = "?spec=" + encodeURI(testName);
return "<script>" + "if (window.location.search !=='" + specName + "') {" +
"window.location.search = '" + specName + "';}</script>";
} else {
return "";
}
}
function createHtmlTestRunner(fileName, scripts, styles, testName) {
var html = "<!DOCTYPE html><html>";
var head = '<head><meta charset="utf-8">' + addLinks(styles) + '</head>';
var body = "<body>" + addScripts(scripts) + addTestName(testName) + "</body>";
html = html + head + body + "</html>";
fs.writeFileSync(fileName, html);
}
gulp.task("run_tests", function () {
var src = [
"powerbi-visuals.all.js",
"../src/Clients/externals/ThirdPartyIP/JasmineJQuery/jasmine-jquery.js",
"../src/Clients/externals/ThirdPartyIP/MomentJS/moment.min.js",
"../src/Clients/externals/ThirdPartyIP/Velocity/velocity.min.js",
"../src/Clients/externals/ThirdPartyIP/Velocity/velocity.ui.min.js",
"../src/Clients/externals/ThirdPartyIP/QuillJS/quill.min.js",
"powerbi-visuals-tests.js"
];
var scripts = [
"../node_modules/jasmine-core/lib/jasmine-core/jasmine.js",
"../node_modules/jasmine-core/lib/jasmine-core/jasmine-html.js",
"../node_modules/jasmine-core/lib/jasmine-core/boot.js"
];
var links = [
"../node_modules/jasmine-core/lib/jasmine-core/jasmine.css"
];
var specRunnerFileName = "VisualsTests/runner.html";
var openInBrowser = cliArguments.openInBrowser;
createHtmlTestRunner(
specRunnerFileName,
scripts.concat(src),
links,
getOptionFromCli(openInBrowser)[0]);
if (openInBrowser) {
return gulp.src(specRunnerFileName)
.pipe(open());
} else {
return gulp.src(src, {cwd: "VisualsTests"})
.pipe(jasmineBrowser.specRunner({console: true}))
.pipe(jasmineBrowser.headless());
}
});
gulp.task("run_performance_tests", function (callback) {
filesOption.push("performance/performanceTests.ts");
runSequence("test", callback);
});
gulp.task("test", function (callback) {
runSequence(
"build",
"build_visuals_tests",
"jasmine-dependency",
"phantomjs-dependency",
"combine_all",
"copy_dependencies_visuals_tests",
"run_tests",
callback);
}); |
version https://git-lfs.github.com/spec/v1
oid sha256:929c8c7060f19031f1f15431146c608dee4d4c9c49547f6fa7f0cf0b16217c8b
size 21631
|
var url = 'http://soo.trade.great:8008';
module.exports = {
navigate: {
home: url+'/',
list: url+'/markets/results/'
},
pageHeader: element(by.css('h1.h1'))
};
|
/**
* @file InstallerRawPlugin
* @author Jim Bulkowski <jim.b@paperelectron.com>
* @project pom-plugin-builder
* @license MIT {@link http://opensource.org/licenses/MIT}
*/
'use strict';
const _ = require('pom-framework-utils').lodash
const CommonRawPlugin = require('./CommonRawPlugin')
/**
*
* @module InstallerRawPlugin
*/
module.exports = class InstallerRawPlugin extends CommonRawPlugin{
constructor(pluginModule){
super(pluginModule)
this.installer = this.checkArgs(pluginModule.loaded) && this.validInstaller(pluginModule.loaded.installer);
// this.options = null
// this.errors = null
// this.plugin = null
}
/**
* Override method, prevents Errors from being recorded for missing plugin hooks.
*
* @returns {boolean} false
*/
validHooks(){
return false
}
validInstaller(installer){
if(!_.isFunction(installer)) {
this.valid = false;
this.Errors.push(new Error('Installer property must be a function..'));
return false
}
return installer
}
isInstaller(){
return true
}
} |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _class, _temp;
var _Git = require('./Git');
var _Git2 = _interopRequireDefault(_Git);
var _Start = require('./phases/Start');
var _Start2 = _interopRequireDefault(_Start);
var _Publish = require('./phases/Publish');
var _Publish2 = _interopRequireDefault(_Publish);
var _Finish = require('./phases/Finish');
var _Finish2 = _interopRequireDefault(_Finish);
var _defaults = require('./defaults');
var _defaults2 = _interopRequireDefault(_defaults);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { return step("next", value); }, function (err) { return step("throw", err); }); } } return step("next"); }); }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Release = (_temp = _class = function () {
_createClass(Release, null, [{
key: 'registerPlugin',
value: function registerPlugin(name, fn) {
this.plugins[name] = fn;
}
}]);
function Release(options) {
_classCallCheck(this, Release);
options = Object.assign({}, _defaults2.default, options);
this.options = options;
this.phases = {
start: new _Start2.default(),
publish: new _Publish2.default(),
finish: new _Finish2.default()
};
this.logger = new options.Logger({ logLevel: options.logLevel });
this.errorFactory = new options.ErrorFactory();
this.git = new _Git2.default(options);
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = options.plugins[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var plugin = _step.value;
this.plugin(plugin);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
_createClass(Release, [{
key: 'start',
value: function start() {
return this.phases.start.run(this);
}
}, {
key: 'publish',
value: function publish() {
return this.phases.publish.run(this);
}
}, {
key: 'finish',
value: function finish() {
return this.phases.finish.run(this);
}
}, {
key: 'full',
value: function () {
var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee() {
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return this.start();
case 2:
_context.next = 4;
return this.publish();
case 4:
_context.next = 6;
return this.finish();
case 6:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function full() {
return _ref.apply(this, arguments);
}
return full;
}()
}, {
key: 'error',
value: function error() {
var _errorFactory;
return (_errorFactory = this.errorFactory).createError.apply(_errorFactory, arguments);
}
}, {
key: 'plugin',
value: function plugin(fnOrString) {
if (typeof fnOrString === 'function') {
fnOrString(this);
} else {
Release.plugins[fnOrString](this);
}
}
}]);
return Release;
}(), _class.plugins = {}, _temp);
exports.default = Release; |
var weatherEnum = {
CLEAR_DAY: 0,
CLEAR_NIGHT: 1,
CLOUD_DAY: 2,
CLOUD_NIGHT: 3,
CLOUD: 4,
RAIN: 5,
THUNDER: 6,
SNOW: 7,
MIST: 8
}
var mapWeather = {
'01d': weatherEnum.CLEAR_DAY,
'01n': weatherEnum.CLEAR_NIGHT,
'02d': weatherEnum.CLOUD_DAY,
'02n': weatherEnum.CLOUD_NIGHT,
'03d': weatherEnum.CLOUD,
'03n': weatherEnum.CLOUD,
'04d': weatherEnum.CLOUD,
'04n': weatherEnum.CLOUD,
'09d': weatherEnum.RAIN,
'09n': weatherEnum.RAIN,
'10d': weatherEnum.RAIN,
'10n': weatherEnum.RAIN,
'11d': weatherEnum.THUNDER,
'11n': weatherEnum.THUNDER,
'13d': weatherEnum.SNOW,
'13n': weatherEnum.SNOW,
'50d': weatherEnum.MIST,
'50n': weatherEnum.MIST,
}
var xhrRequest = function (url, type, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
callback(this.responseText);
};
xhr.open(type, url);
xhr.send();
};
var appinfo = require('appinfo.json');
var Clay = require('clay');
var clayConfig = require('config.json');
var clay = new Clay(clayConfig, null, {autoHandleEvents: false});
Pebble.addEventListener('ready',
function(e) {
// Any saved data?
console.log('JS: Ready event.');
Pebble.sendAppMessage({'KEY_TOWATCH_READY': 1});
// getWeather();
}
);
Pebble.addEventListener('showConfiguration', function(e) {
Pebble.openURL(clay.generateUrl());
});
Pebble.addEventListener('webviewclosed', function(e) {
if (e && !e.response) { return; }
// Send settings to Pebble watchapp
Pebble.sendAppMessage(clay.getSettings(e.response), function(e) {
console.log('Sent config data to Pebble');
}, function() {
console.log('Failed to send config data!');
console.log(JSON.stringify(e));
});
});
Pebble.addEventListener('appmessage', function(e) {
console.log('JS: Got an AppMessage: ' + JSON.stringify(e.payload));
var weatherOn = e.payload['KEY_TOPHONE_GETWEATHER'];
// Did this message include a request to update the weather?
if (weatherOn) {
getWeather();
}
});
function locationSuccess(pos) {
// Construct URL
var myAPIKey = '19998043751c4c655bf250b29610c683';
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=' +
pos.coords.latitude + '&lon=' + pos.coords.longitude + '&appid=' + myAPIKey;
// Send request to OpenWeatherMap
xhrRequest(url, 'GET',
function(responseText) {
// responseText contains a JSON object with weather info
var json = JSON.parse(responseText);
console.log('JS got weather ' + json);
// Temperature in Kelvin requires adjustment
var temperature = Math.round(json.main.temp - 273.15);
console.log('JS: Temperature in ' + json.name + ' is ' + temperature);
var weatherCode = json.weather[0].icon;
var icon = weatherEnum.CLEAR_DAY;
if (weatherCode in mapWeather) icon = mapWeather[weatherCode];
console.log('JS: Conditions are code:' + weatherCode + " icon ID:" + icon);
var dict = {};
dict['KEY_TOWATCH_WEATHER_TEMP'] = temperature;
dict['KEY_TOWATCH_WEATHER_ICON'] = icon;
// Send to watchapp
Pebble.sendAppMessage(dict, function() {
console.log('JS: Weather send successful: ' + JSON.stringify(dict));
}, function() {
console.log('JS: Weather send failed!');
});
}
);
}
function locationError(err) {
console.log('JS: Error requesting location!');
}
function getWeather() {
navigator.geolocation.getCurrentPosition(
locationSuccess,
locationError,
{timeout: 15000, maximumAge: 60000}
);
}
|
import crypto from 'crypto'
import isGitRepo from 'is-git-repo'
import gitConfig from 'git-scope-config'
export default [
{
type: 'input',
name: 'authorName',
message: 'Your name',
default: function() {
var done = this.async()
gitConfig({scope: 'global'}).get('user.name', (err, name) => {
if (err) {
return done()
}
name = name.replace(/(\r\n|\n|\r)/gm, '')
done(null, name)
})
}
},
{
type: 'input',
name: 'authorEmail',
message: 'Your email',
default: function() {
const done = this.async()
gitConfig({scope: 'global'}).get('user.email', (err, email) => {
if (err) {
return done()
}
email = email.replace(/(\r\n|\n|\r)/gm, '')
done(null, email)
})
}
},
{
type: 'input',
name: 'projectName',
message: 'Name of the project',
default: 'awesome-api'
},
{
type: 'input',
name: 'projectDescription',
message: 'Description of your project',
default: 'A RESTful API'
},
{
type: 'prompt',
name: 'git',
message: 'Do you wanna use GIT?',
default: true
},
{
type: 'input',
name: 'gitURL',
message: 'Repository URL',
when: (answers) => {
return answers.git
},
default: function() {
const done = this.async()
isGitRepo(process.cwd(), isGit => {
if (!isGit) {
return done(null)
}
gitConfig({scope: 'local'}).get('remote.origin.url', (err, url) => {
if (err) {
return done()
}
url = url.replace(/(\r\n|\n|\r)/gm, '')
done(null, url)
})
})
}
},
{
type: 'confirm',
name: 'authentication',
message: 'Need authentication?',
default: true
},
{
type: 'confirm',
name: 'authenticationFacebook',
message: 'Allow Sign In with Facebook?',
default: true,
when: answers => answers.authentication
},
{
type: 'input',
name: 'facebookClientId',
message: 'Client ID of your Facebook app',
when: answers => answers.authenticationFacebook
},
{
type: 'password',
name: 'facebookClientSecret',
message: 'Client Secret of your Facebook app',
when: answers => answers.authenticationFacebook
},
{
type: 'input',
name: 'secret',
message: 'Your API secret',
default: crypto.randomBytes(16).toString('hex')
},
{
type: 'confirm',
name: 'persistence',
message: 'Need peristance?',
default: true
},
{
type: 'list',
name: 'database',
choices: ['PostgreSQL', 'MySQL', 'MongoDB', 'Memory'],
message: 'Choose a database',
default: 'Memory',
when: answers => {
return answers.persistence
}
},
{
type: 'input',
name: 'databaseHost',
message: 'Database host',
default: 'localhost',
when: answers => {
if (!answers.persistence) {
return false
}
if (answers.database === 'Memory') {
return false
}
return true
}
},
{
type: 'input',
name: 'databasePort',
message: 'Database port',
default: answers => {
if (answers.database === 'PostgreSQL') {
return 5432
}
if (answers.database === 'MySQL') {
return 3306
}
if (answers.database === 'MongoDB') {
return 27017
}
return 10000
},
when: answers => {
if (!answers.persistence) {
return false
}
if (answers.database === 'Memory') {
return false
}
return true
}
},
{
type: 'input',
name: 'databaseName',
message: 'Database name',
default: 'netiam',
when: answers => {
if (!answers.persistence) {
return false
}
if (answers.database === 'PostgreSQL') {
return true
}
if (answers.database === 'MySQL') {
return true
}
if (answers.database === 'MongoDB') {
return true
}
return false
}
},
{
type: 'input',
name: 'databaseUsername',
message: 'Database username',
default: 'netiam',
when: answers => {
if (answers.database === 'PostgreSQL') {
return true
}
if (answers.database === 'MySQL') {
return true
}
return false
}
},
{
type: 'password',
name: 'databasePassword',
message: 'Database password',
when: answers => {
if (answers.database === 'PostgreSQL') {
return true
}
if (answers.database === 'MySQL') {
return true
}
return false
}
},
{
type: 'input',
name: 'port',
message: 'Server port',
default: 3000
},
{
type: 'checkbox',
name: 'features',
message: 'Enable middleware and features',
choices: [
{
name: 'Compression (e.g. gzip)',
value: 'compression'
},
{
name: 'Reverse Proxy (e.g. nginx)',
value: 'proxy'
},
{
name: 'Cluster',
value: 'cluster'
},
{
name: 'CORS',
value: 'cors'
},
{
name: 'ACL',
value: 'acl'
},
{
name: 'JSONAPI',
value: 'jsonapi'
},
{
name: 'Documentation',
value: 'documentation'
},
{
name: 'Dockerfile',
value: 'dockerfile'
},
],
default: [
'compression',
'proxy',
'cors',
'documentation'
]
}
]
|
'use strict';
const AzuriteTableResponse = require('./../../model/table/AzuriteTableResponse'),
tableStorageManager = require('./../../core/table/TableStorageManager'),
N = require('./../../core/HttpHeaderNames');
class DeleteTable {
constructor() {
}
process(request, res) {
tableStorageManager.deleteTable(request)
.then((response) => {
res.set(request.httpProps);
res.status(201).send();
});
}
}
module.exports = new DeleteTable; |
var FacetedValuesJS = require('faceted-values-js');
var FacetedValue = FacetedValuesJS.FacetedValue;
var Cloak = FacetedValuesJS.Cloak;
var view = [];
var b = new FacetedValue('admin', 42, 0);
var c = b.binaryOps('+', 3, false); |
var app = getApp()
Page( {
data: {
userInfo: {},
// projectSource: 'https://github.com/liuxuanqiang/wechat-weapp-mall',
userListInfo: [ {
icon: 'http://sc.hanjren.com/images/orders-icon.png',
text: '我的优惠卷',
link:"/pages/youhui/index"
// isunread: true,
// unreadNum: 2
},
// {4px
// icon: '../../images/iconfont-card.png',
// text: '我的代金券',
// isunread: false,
// unreadNum: 2
// },
// {
// icon: '../../images/iconfont-icontuan.png',
// text: '我的拼团',
// isunread: true,
// unreadNum: 1
// },
{
icon: 'http://sc.hanjren.com/images/adress-icon.png',
text: '到店咨询',
link:"/pages/lx/lx"
},
// {
// icon: 'http://sc.hanjren.com/images/iconfont-kefu.png',
// text: '联系客服---02089857585',
// bindtap:"callmeTap"
// },
// {
// icon: 'http://sc.hanjren.com/images/iconfont-help.png',
// text: '常见问题',
// link:"/page/component/index"
// }
]
},
onLoad: function() {
var that = this
//调用应用实例的方法获取全局数据
app.getUserInfo( function( userInfo ) {
//更新数据
that.setData( {
userInfo: userInfo
})
}),
wx.login({
success: function () {
wx.getUserInfo({
success: function (res) {
that.setData({
userInfo: res.userInfo
})
}
})
}
});
},
callmeTap: function() {
wx.makePhoneCall({
phoneNumber: '02089857585'
})
},
makephone:function(){
wx.makePhoneCall({
phoneNumber: '02089857585' //仅为示例,并非真实的电话号码
})
},
fankui:function(){
wx.showActionSheet({
itemList: ['写评论', '发图片'],
success: function(res) {
console.log(res.tapIndex);
if(res.tapIndex==1){
wx.chooseImage({
success: function(res) {
var tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'https://sc.hanjren.com/index.php/admin/upload/getImg', //仅为示例,非真实的接口地址
filePath: tempFilePaths[0],
name: 'file',
formData:{
'user': res
},
success: function(res){
var data = res.data
//do something
console.log(data);
}
})
}
})
}else{
wx.navigateTo({
url: '/pages/rj/rj'
})
}
},
fail: function(res) {
console.log(res.errMsg)
}
})
}
,
tuichu:function(){
wx.showToast({
title: '成功',
icon: 'success',
duration: 2000,
success:function(){
wx.clearStorage();
}
})
},
choseImg:function(){
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
var tempFilePaths = res.tempFilePaths
wx.showLoading({
title: '颜值测试中...',
success:function(){
wx.uploadFile({
url: 'https://sc.hanjren.com/index.php/admin/yanzhi/test',
filePath: tempFilePaths[0],
name: 'file',
formData:{
'pic': res
},
success: function(res){
var data = res.data
console.log(data);
//性别
// console.log(data.substr(309,1));
//年龄
// console.log(data.substr(337,2));
var age=data.substr(197,3);
console.log(age);
var sex='';
console.log(data.substr(171,1));
if(data.substr(171,1)=='F'){
sex='漂亮女性';
}else{
sex="魅力男士";
age=data.substr(195,3);
}
wx.showModal({
title: '测试结果',
content: "经测试,您是"+age+"岁的"+sex,
showCancel: false,//去掉取消按钮
})
}
})
// wx.chooseImage({
// success: function(res) {
// var tempFilePaths = res.tempFilePaths
// }
// })
}
})
setTimeout(function(){
wx.hideLoading()
},2000)
}
})
}
}) |
module.exports = {
toRadians: function toRadians(theta) {
return normalizeAngle(theta)*(Math.PI / 180);
},
normalizeAngle: normalizeAngle,
};
function normalizeAngle(theta) {
while (theta < 0) { theta += 360; }
return theta % 360;
} |
// In production, we register a service worker to serve assets from local cache.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://goo.gl/SC7cgQ'
);
});
} else {
// Is not local host. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
// Execute callback
if (config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
|
import chai from 'chai';
let assert = chai.assert;
import {StyleManager} from '../src/styles/style_manager';
import {Style} from '../src/styles/style';
import Context from '../src/gl/context';
import ShaderProgram from '../src/gl/shader_program';
import Camera from '../src/scene/camera';
import Light from '../src/lights/light';
import sampleScene from './fixtures/sample-scene.json';
var canvas, gl;
describe('Styles:', () => {
let style_manager;
beforeEach(() => {
style_manager = new StyleManager();
});
describe('StyleManager:', () => {
beforeEach(() => {
// These create global shader blocks required by all rendering styles
Camera.create('default', null, { type: 'flat' });
Light.inject();
canvas = document.createElement('canvas');
gl = Context.getContext(canvas, { alpha: false });
style_manager.init();
});
afterEach(() => {
style_manager.destroy();
canvas = null;
gl = null;
});
it('initializes built-in styles', () => {
assert.equal(style_manager.styles.polygons.constructor, Style.constructor);
assert.equal(style_manager.styles.points.constructor, Style.constructor);
assert.equal(style_manager.styles.text.constructor, Style.constructor);
});
it('creates a custom style', () => {
style_manager.create('rainbow', sampleScene.styles.rainbow);
assert.equal(style_manager.styles.rainbow.constructor, Style.constructor);
assert.equal(style_manager.styles.rainbow.base, 'polygons');
});
describe('builds custom styles w/dependencies from stylesheet', () => {
beforeEach(() => {
ShaderProgram.reset();
style_manager.build(sampleScene.styles);
style_manager.initStyles();
});
it('compiles parent custom style', () => {
style_manager.styles.rainbow.setGL(gl);
style_manager.styles.rainbow.getProgram();
assert.equal(style_manager.styles.rainbow.constructor, Style.constructor);
assert.equal(style_manager.styles.rainbow.base, 'polygons');
assert.ok(style_manager.styles.rainbow.program.compiled);
});
it('compiles child style dependent on another custom style', () => {
style_manager.styles.rainbow_child.setGL(gl);
style_manager.styles.rainbow_child.getProgram();
assert.equal(style_manager.styles.rainbow_child.constructor, Style.constructor);
assert.equal(style_manager.styles.rainbow_child.base, 'polygons');
assert.ok(style_manager.styles.rainbow_child.program.compiled);
});
it('compiles a style with the same style mixed by multiple ancestors', () => {
style_manager.styles.descendant.setGL(gl);
style_manager.styles.descendant.getProgram();
assert.equal(style_manager.styles.descendant.constructor, Style.constructor);
assert.equal(style_manager.styles.descendant.base, 'polygons');
assert.ok(style_manager.styles.descendant.program.compiled);
});
});
});
describe('Style:', () => {
beforeEach(() => {
canvas = document.createElement('canvas');
gl = Context.getContext(canvas, { alpha: false });
style_manager.init();
});
afterEach(() => {
style_manager.destroy();
canvas = null;
gl = null;
});
it('compiles a program', () => {
style_manager.styles.polygons.init();
style_manager.styles.polygons.setGL(gl);
style_manager.styles.polygons.getProgram();
assert.ok(style_manager.styles.polygons.program.compiled);
});
it('injects a dependent uniform in a custom style', () => {
style_manager.create('scale', sampleScene.styles.scale);
style_manager.styles.scale.init();
style_manager.styles.scale.setGL(gl);
style_manager.styles.scale.getProgram();
assert.ok(style_manager.styles.scale.program.compiled);
});
});
});
|
(function() {
'use strict';
angular.module('Tournament.Common').factory('configurationProvider',
configurationProvider);
function configurationProvider() {
const serviceBase_ = 'http://localhost/Tournament.API/';
return {
serviceBase: serviceBase_
};
}
}
)();
|
'use strict'
var fs = require('fs-extra')
var path = require('path')
var spawn = require('cross-spawn')
var chalk = require('chalk')
function dependencies (streamLib) {
var basicDependencies = [
'@cycle/dom',
'xstream'
]
switch (streamLib) {
case 'xstream':
return basicDependencies.concat(['@cycle/xstream-run'])
case 'most':
return basicDependencies.concat(['@cycle/most-run', 'most'])
case 'rxjs':
return basicDependencies.concat(['@cycle/rxjs-run', 'rxjs'])
case 'rx':
return basicDependencies.concat(['@cycle/rx-run', 'rx'])
default:
throw new Error('Unsupported stream library: ' + streamLib)
}
}
function replacements (streamLib) {
switch (streamLib) {
case 'xstream':
return {
'--RUN-LIB--': '@cycle/xstream-run',
'--IMPORT--': "import xs from 'xstream'",
'--STREAM--': 'xs'
}
case 'most':
return {
'--RUN-LIB--': '@cycle/most-run',
'--IMPORT--': "import * as most from 'most'",
'--STREAM--': 'most'
}
case 'rxjs':
return {
'--RUN-LIB--': '@cycle/rxjs-run',
'--IMPORT--': "import Rx from 'rxjs'",
'--STREAM--': 'Rx.Observable'
}
case 'rx':
return {
'--RUN-LIB--': '@cycle/rx-run',
'--IMPORT--': "import Rx from 'rx'",
'--STREAM--': 'Rx.Observable'
}
default:
throw new Error('Unsupported stream library: ' + streamLib)
}
}
function patchGitignore (appPath) {
// Rename gitignore after the fact to prevent npm from renaming it to .npmignore
// See: https://github.com/npm/npm/issues/1862
var gitignorePath = path.join(appPath, 'gitignore')
var dotGitignorePath = path.join(appPath, '.gitignore')
fs.move(gitignorePath, dotGitignorePath, [], function (err) {
if (err) {
// Append if there's already a `.gitignore` file there
if (err.code === 'EEXIST') {
var content = fs.readFileSync(gitignorePath)
fs.appendFileSync(dotGitignorePath, content)
fs.unlinkSync(gitignorePath)
} else {
throw err
}
}
})
}
function replaceTags (content, tags) {
var newContent = content
Object.keys(tags).forEach(function (tag) {
newContent = newContent.replace(tag, tags[tag])
})
return newContent
}
function patchIndexJs (appPath, tags) {
var indexJsPath = path.join(appPath, 'src', 'index.js')
var content = fs.readFileSync(indexJsPath, {encoding: 'utf-8'})
fs.writeFileSync(
indexJsPath,
replaceTags(content, tags)
)
}
function patchAppJs (appPath, tags) {
var indexJsPath = path.join(appPath, 'src', 'app.js')
var content = fs.readFileSync(indexJsPath, {encoding: 'utf-8'})
fs.writeFileSync(
indexJsPath,
replaceTags(content, tags)
)
}
function successMsg (appName, appPath) {
console.log()
console.log('Success! Created ' + appName + ' at ' + appPath)
console.log('Inside that directory, you can run several commands:')
console.log()
console.log(chalk.cyan(' npm start'))
console.log(' Starts the development server')
console.log()
console.log(chalk.cyan(' npm test'))
console.log(' Start the test runner')
console.log()
console.log(chalk.cyan(' npm run build'))
console.log(' Bundles the app into static files for production')
console.log()
console.log(chalk.cyan(' npm run eject'))
console.log(' Removes this tool and copies build dependencies, configuration files')
console.log(' and scripts into the app directory. If you do this, you can\'t go back!')
console.log()
console.log('We suggest that you begin by typing:')
console.log()
console.log(chalk.cyan(' cd ' + appName))
console.log(chalk.cyan(' npm start'))
console.log()
console.log('If you have questions, issues or feedback about Cycle.js and create-cycle-app, please, join us on the Gitter:')
console.log()
console.log(chalk.cyan(' https://gitter.im/cyclejs/cyclejs'))
console.log()
console.log('Happy cycling!')
}
module.exports = function (appPath, appName, streamLib, verbose, originalDirectory) {
var ownPackageName = require(path.join(__dirname, '..', 'package.json')).name
var ownPath = path.join(appPath, 'node_modules', ownPackageName)
var appPackageJson = path.join(appPath, 'package.json')
var appPackage = require(appPackageJson)
// Manipulate app's package.json
appPackage.dependencies = appPackage.dependencies || {}
appPackage.devDependencies = appPackage.devDependencies || {}
appPackage.scripts = {
'start': 'cycle-scripts start',
'test': 'cycle-scripts test',
'build': 'cycle-scripts build',
'eject': 'cycle-scripts eject'
}
appPackage.babel = {
'presets': ['es2015']
}
fs.writeFileSync(
appPackageJson,
JSON.stringify(appPackage, null, 2)
)
// Copy flavor files
fs.copySync(path.join(ownPath, 'template'), appPath)
patchGitignore(appPath)
var tags = replacements(streamLib)
patchIndexJs(appPath, tags)
patchAppJs(appPath, tags)
console.log('Installing dependencies from npm...')
console.log()
var args = [
'install'
].concat(
dependencies(streamLib) // Flavor dependencies
).concat([
'--save',
verbose && '--verbose'
]).filter(Boolean)
var proc = spawn('npm', args, {stdio: 'inherit'})
proc.on('close', function (code) {
if (code !== 0) {
console.error(chalk.red('`npm ' + args.join(' ') + '` failed'))
return
}
successMsg(appName, appPath)
})
}
|
import { connect } from 'react-redux';
import {
fetchPaymentMethod,
updatePaymentMethod,
fetchShippingMethods,
createPaymentMethod,
receivePaymentMethod
} from '../actions';
import Form from './components/form';
const mapStateToProps = (state, ownProps) => {
const { methodId } = ownProps.match.params;
const gateway = state.settings.paymentMethodEdit
? state.settings.paymentMethodEdit.gateway
: null;
return {
methodId: methodId,
gateway: gateway,
settings: state.settings.settings,
initialValues: state.settings.paymentMethodEdit,
shippingMethods: state.settings.shippingMethods
};
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onLoad: () => {
const { methodId } = ownProps.match.params;
if (methodId) {
dispatch(fetchPaymentMethod(methodId));
} else {
dispatch(receivePaymentMethod({ enabled: true }));
}
dispatch(fetchShippingMethods());
},
onSubmit: method => {
if (
method.conditions &&
method.conditions.countries &&
!Array.isArray(method.conditions.countries)
) {
const countriesStr = method.conditions.countries;
method.conditions.countries = countriesStr
.split(',')
.map(item => item.trim().toUpperCase())
.filter(item => item.length === 2);
}
if (method.id) {
dispatch(updatePaymentMethod(method));
} else {
dispatch(createPaymentMethod(method));
ownProps.history.push('/admin/settings/payments');
}
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Form);
|
const server = require('../../lib/server');
const port = process.env.PORT || 3000;
server.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
|
import Helper from './_helper';
import { Model } from 'ember-cli-mirage';
import { module, test } from 'qunit';
module('Integration | ORM | Belongs To | One-way Polymorphic | create', {
beforeEach() {
this.helper = new Helper();
this.helper.schema.registerModel('foo', Model);
}
});
test('it sets up associations correctly when passing in the foreign key', function(assert) {
let post = this.helper.schema.create('post');
let comment = this.helper.schema.create('comment', {
commentableId: { id: post.id, type: 'post' }
});
assert.deepEqual(comment.commentableId, { id: post.id, type: 'post' });
assert.deepEqual(comment.commentable.attrs, post.attrs);
assert.equal(this.helper.schema.db.posts.length, 1);
assert.deepEqual(this.helper.schema.db.posts[0], { id: '1' });
assert.equal(this.helper.schema.db.comments.length, 1);
assert.deepEqual(this.helper.schema.db.comments[0], { id: '1', commentableId: { id: '1', type: 'post' } });
});
test('it sets up associations correctly when passing in the association itself', function(assert) {
let post = this.helper.schema.create('post');
let comment = this.helper.schema.create('comment', {
commentable: post
});
assert.deepEqual(comment.commentableId, { id: post.id, type: 'post' });
assert.deepEqual(comment.commentable.attrs, post.attrs);
assert.equal(this.helper.schema.db.posts.length, 1);
assert.deepEqual(this.helper.schema.db.posts[0], { id: '1' });
assert.equal(this.helper.schema.db.comments.length, 1);
assert.deepEqual(this.helper.schema.db.comments[0], { id: '1', commentableId: { id: '1', type: 'post' } });
});
|
Handlebars.registerHelper('fullName', function(person) {
return person.firstName + " " + person.lastName;
});
Handlebars.registerHelper('titleName', function(){
return "The Right Honourable Anthony Eden";
});
|
"use strict";
angular.module("sbAdminApp").controller('relationCtrl', ['$scope', 'relationFactory', 'Notification',
function ($scope, factory, Notification) {
$scope.status;
$scope.listBean;
$scope.bean;
getList();
function getList() {
console.log('getList is working!');
factory.getList()
.success(function (list) {
$scope.listBean = list;
})
.error(function (error) {
$scope.status = 'Unable to load listBean data: ' + error.message;
console.log($scope.status);
});
}
$scope.setBean = function (bean) {
console.log('setBean is working!');
factory.tempBean = bean;
$scope.bean = bean;
};
$scope.add = function () {
console.log('add is working!');
factory.tempBean = {};
};
$scope.delete = function () {
console.log('delete is working!');
var selectedBean = $scope.bean;
factory.deleteBean(selectedBean.id)
.success(function () {
$scope.status = 'Deleted ! Refreshing os list.';
for (var i = 0; i < $scope.listBean.length; i++) {
var temp = $scope.listBean[i];
if (temp.id == selectedBean.id) {
$scope.listBean.splice(i, 1);
break;
}
}
Notification.success($scope.status);
console.log($scope.status);
})
.error(function (error) {
$scope.status = 'Unable to delete : ' + error.message;
Notification.error($scope.status);
console.log($scope.status);
});
};
}]); |
// Filter definitions to build tables for
// resizing convolvers.
//
// Presets for quality 0..3. Filter functions + window size
//
'use strict';
const filter = {
// Nearest neibor
box: {
win: 0.5,
fn: function (x) {
if (x < 0) x = -x;
return (x < 0.5) ? 1.0 : 0.0;
}
},
// // Hamming
hamming: {
win: 1.0,
fn: function (x) {
if (x < 0) x = -x;
if (x >= 1.0) { return 0.0; }
if (x < 1.19209290E-07) { return 1.0; }
var xpi = x * Math.PI;
return ((Math.sin(xpi) / xpi) * (0.54 + 0.46 * Math.cos(xpi / 1.0)));
}
},
// Lanczos, win = 2
lanczos2: {
win: 2.0,
fn: function (x) {
if (x < 0) x = -x;
if (x >= 2.0) { return 0.0; }
if (x < 1.19209290E-07) { return 1.0; }
var xpi = x * Math.PI;
return (Math.sin(xpi) / xpi) * Math.sin(xpi / 2.0) / (xpi / 2.0);
}
},
// Lanczos, win = 3
lanczos3: {
win: 3.0,
fn: function (x) {
if (x < 0) x = -x;
if (x >= 3.0) { return 0.0; }
if (x < 1.19209290E-07) { return 1.0; }
var xpi = x * Math.PI;
return (Math.sin(xpi) / xpi) * Math.sin(xpi / 3.0) / (xpi / 3.0);
}
},
// Magic Kernel Sharp 2013, win = 2.5
// http://johncostella.com/magic/
mks2013: {
win: 2.5,
fn: function (x) {
if (x < 0) x = -x;
if (x >= 2.5) { return 0.0; }
if (x >= 1.5) { return -0.125 * (x - 2.5) * (x - 2.5); }
if (x >= 0.5) { return 0.25 * (4 * x * x - 11 * x + 7); }
return 1.0625 - 1.75 * x * x;
}
}
};
module.exports = {
filter: filter,
// Legacy mapping
f2q: { box: 0, hamming: 1, lanczos2: 2, lanczos3: 3 },
q2f: [ 'box', 'hamming', 'lanczos2', 'lanczos3' ]
};
|
export default [{
label: 'Avatar',
valuePath: 'avatar',
width: '60px',
sortable: false,
cellComponent: 'user-avatar'
}, {
label: 'First Name',
valuePath: 'firstName',
width: '150px'
}, {
label: 'Last Name',
valuePath: 'lastName',
width: '150px'
}, {
label: 'Address',
valuePath: 'address'
}, {
label: 'State',
valuePath: 'state'
}, {
label: 'Country',
valuePath: 'country'
}];
export const GroupedColumns = [{
label: 'User Details',
sortable: false,
align: 'center',
subColumns: [{
label: 'Avatar',
valuePath: 'avatar',
width: '60px',
sortable: false,
cellComponent: 'user-avatar'
}, {
label: 'First',
valuePath: 'firstName',
width: '150px'
}, {
label: 'Last',
valuePath: 'lastName',
width: '150px'
}]
}, {
label: 'Contact Information',
sortable: false,
align: 'center',
subColumns: [{
label: 'Address',
valuePath: 'address'
}, {
label: 'State',
valuePath: 'state'
}, {
label: 'Country',
valuePath: 'country'
}]
}];
|
/* eslint no-magic-numbers: off */
module.exports = {
rules: {
'accessor-pairs': 'off',
'array-callback-return': 'error',
'block-scoped-var': 'error',
'class-methods-use-this': 'error',
'complexity': [
'error',
10
],
'consistent-return': 'error',
'curly': [
'error',
'all'
],
'default-case': 'error',
'dot-location': [
'error',
'property'
],
'dot-notation': 'error',
'eqeqeq': 'error',
'guard-for-in': 'error',
'no-alert': 'error',
'no-caller': 'error',
'no-div-regex': 'error',
'no-else-return': 'error',
'no-empty-function': 'error',
// Though probably unnecessary with 'eqeqeq'
'no-eq-null': 'error',
'no-eval': 'error',
'no-extend-native': 'error',
'no-extra-bind': 'error',
'no-extra-label': 'error',
'no-extra-parens': 'off',
'no-floating-decimal': 'error',
'no-global-assign': 'error',
'no-implicit-coercion': 'error',
'no-implicit-globals': 'error',
'no-implied-eval': 'error',
'no-invalid-this': 'error',
'no-iterator': 'error',
'no-labels': 'error',
'no-lone-blocks': 'error',
'no-loop-func': 'error',
'no-magic-numbers': 'error',
'no-multi-str': 'error',
'no-new': 'error',
'no-new-func': 'error',
'no-new-wrappers': 'error',
'no-octal-escape': 'error',
'no-param-reassign': 'error',
'no-proto': 'error',
'no-return-assign': 'error',
'no-script-url': 'error',
'no-self-compare': 'error',
'no-sequences': 'error',
'no-template-curly-in-string': 'error',
'no-throw-literal': 'error',
'no-unmodified-loop-condition': 'error',
'no-unsafe-finally': 'error',
'no-unsafe-negation': 'error',
'no-unused-expressions': 'error',
'no-useless-call': 'error',
'no-useless-concat': 'error',
'no-useless-escape': 'error',
'no-void': 'error',
'no-warning-comments': 'error',
'no-with': 'error',
'prefer-numeric-literals': 'error',
'radix': 'error',
'symbol-description': 'error',
'vars-on-top': 'error',
'wrap-iife': 'error',
'yoda': 'error'
}
}
|
import remark from 'remark'
import remarkAlign from 'remark-align'
import toEmoji from 'remark-gemoji-to-emoji'
import slug from 'remark-slug'
import highlight from 'remark-highlight.js'
import yamlFront from '../../utils/loadFront'
import headings from 'remark-autolink-headings'
import remark2rehype from 'remark-rehype'
import raw from 'rehype-raw'
import mini from './safe-preset-minify'
import rehypeStringify from 'rehype-stringify'
import DetectChanged from 'detect-one-changed/remark-plugin'
import visit from 'unist-util-visit'
import loaderUtils from 'loader-utils'
export const alignClass = {
left: 'align-left',
center: 'align-center',
right: 'align-right'
}
function generate(
content,
info,
callback,
remarkTransformers = [],
rehypeTransformers = []
) {
const { __content, ...meta } = yamlFront.loadFront(content)
toHTML(__content, info, remarkTransformers, rehypeTransformers)
.then(data => callback(null, meta, data))
.catch(err => callback(err))
}
generate.toHTML = toHTML
const detectChanged = DetectChanged.create()
function toHTML(md, info = {}, remarkTransformers, rehypeTransformers) {
const extra = {}
function middleForThis() {
this.picidae = () => ({
info,
inject(key, value) {
extra[key] = value
}
})
return node => {
visit(node, 'code', codeNode => {
let lang = codeNode.lang || ''
let i = lang.lastIndexOf('?')
let query = {}
if (i >= 0) {
query = loaderUtils.parseQuery(lang.substr(i))
lang = lang.substring(0, i)
}
codeNode.lang = lang
codeNode.data = codeNode.data || {}
codeNode.data.hProperties = codeNode.data.hProperties || {}
codeNode.data.hProperties['data-query'] = JSON.stringify(query)
codeNode.data.hProperties['data-lang'] = lang
})
}
}
const { filesMap, path } = info
const filepath = filesMap[path]
detectChanged.options = { filepath }
remarkAlign.options = alignClass
const presetTransformers = [
process.env.PICIDAE_ENV !== 'production' && detectChanged,
toEmoji,
remarkAlign,
slug,
headings,
middleForThis
].filter(Boolean)
remark2rehype.options = { allowDangerousHTML: true }
let appended = [remark2rehype, raw]
.concat(rehypeTransformers)
.concat([mini, rehypeStringify])
let source = remark()
let transformers = presetTransformers.concat(
remarkTransformers,
highlight,
appended
)
return new Promise((resolve, reject) => {
source = transformers.reduce(
(source, transformer) =>
source.use(transformer, transformer.options || {}),
source
)
source.process(md, function(err, file) {
if (err) {
reject(err)
} else {
resolve({
content: file.contents,
extra
})
}
})
})
}
module.exports = generate
|
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-47057526-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})(); |
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class Lightbulb extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<path d="M256,32c-70.7,0-128,55.4-128,123.8c0,4.9,0.3,9.7,0.9,14.5c0.6,5.4,1.6,10.6,3,15.7c0.1,0.5,0.3,1.1,0.4,1.6
c16.6,62.8,45.3,71.5,58.9,167.6c0,0.2,0.1,0.4,0.1,0.5c1.5,9.2,9.8,12.3,19.8,12.3H301c10,0,18.2-3.1,19.7-12.3
c0-0.2,0.1-0.4,0.1-0.5c13.6-96.1,42.3-104.7,58.9-167.6c0.2-0.5,0.3-1,0.4-1.6c1.3-5.1,2.3-10.4,3-15.7c0.6-4.7,0.9-9.6,0.9-14.5
C384,87.4,326.7,32,256,32z"></path>
<path d="M317.8,396.5c0.1-0.2,0.3-0.4,0.4-0.6c1.1-1.7,1.7-3.6,1.7-5.7c0-3.5,1.6-6.2-6.5-6.2H198.6c-8.1,0-6.5,2.1-6.5,6.2
c0,2.1,0.6,4,1.7,5.7c0.1,0.2,0.3,0.4,0.5,0.6c0,0.1,0.1,0.1,0.1,0.2c1.7,2.6,2.7,4.4,2.7,7.6c0,3.1-0.9,4.9-2.6,7.5
c-0.3,0.4-0.5,0.7-0.7,1c-1,1.7-1.6,3.6-1.6,5.6c0,2.1,0.6,4,1.7,5.8c0.1,0.2,0.3,0.4,0.4,0.6c1.8,2.7,2.8,4.5,2.8,7.8
c0,3.1-0.9,4.9-2.6,7.4c-0.2,0.4-0.5,0.7-0.8,1.1c-1,1.7-1.6,3.6-1.6,5.6c0,5.4,4.3,10.1,10.2,11.6c0.3,0.1,0.6,0.1,0.9,0.2
c6,1.4,12.2,1.6,18.5,2.5c0.7,0.1,1.4,0.2,2.2,0.3c5.6,1,10.3,3.9,13.4,7.7l0,0c3.8,5.3,10.8,11,18.8,11c7.6,0,14.3-5.4,18.2-10.4
h0c3-4.2,8-7.3,13.9-8.4c0.7-0.1,1.4-0.3,2.2-0.3c6.3-0.9,12.5-1.1,18.5-2.5c0.3-0.1,0.6-0.1,0.9-0.2c5.9-1.6,10.2-6.2,10.2-11.6
c0-2-0.6-3.9-1.6-5.6c-0.3-0.4-0.5-0.7-0.8-1.1c-1.6-2.6-2.6-4.3-2.6-7.4c0-3.2,1-5.1,2.8-7.8c0.1-0.2,0.3-0.4,0.4-0.6
c1.1-1.7,1.7-3.7,1.7-5.8c0-2-0.6-3.9-1.6-5.6c-0.3-0.3-0.5-0.7-0.7-1c-1.6-2.6-2.6-4.3-2.6-7.5c0-3.2,1-5,2.7-7.6
C317.7,396.7,317.7,396.6,317.8,396.5z"></path>
</g>
</g>;
} return <IconBase>
<g>
<path d="M256,32c-70.7,0-128,55.4-128,123.8c0,4.9,0.3,9.7,0.9,14.5c0.6,5.4,1.6,10.6,3,15.7c0.1,0.5,0.3,1.1,0.4,1.6
c16.6,62.8,45.3,71.5,58.9,167.6c0,0.2,0.1,0.4,0.1,0.5c1.5,9.2,9.8,12.3,19.8,12.3H301c10,0,18.2-3.1,19.7-12.3
c0-0.2,0.1-0.4,0.1-0.5c13.6-96.1,42.3-104.7,58.9-167.6c0.2-0.5,0.3-1,0.4-1.6c1.3-5.1,2.3-10.4,3-15.7c0.6-4.7,0.9-9.6,0.9-14.5
C384,87.4,326.7,32,256,32z"></path>
<path d="M317.8,396.5c0.1-0.2,0.3-0.4,0.4-0.6c1.1-1.7,1.7-3.6,1.7-5.7c0-3.5,1.6-6.2-6.5-6.2H198.6c-8.1,0-6.5,2.1-6.5,6.2
c0,2.1,0.6,4,1.7,5.7c0.1,0.2,0.3,0.4,0.5,0.6c0,0.1,0.1,0.1,0.1,0.2c1.7,2.6,2.7,4.4,2.7,7.6c0,3.1-0.9,4.9-2.6,7.5
c-0.3,0.4-0.5,0.7-0.7,1c-1,1.7-1.6,3.6-1.6,5.6c0,2.1,0.6,4,1.7,5.8c0.1,0.2,0.3,0.4,0.4,0.6c1.8,2.7,2.8,4.5,2.8,7.8
c0,3.1-0.9,4.9-2.6,7.4c-0.2,0.4-0.5,0.7-0.8,1.1c-1,1.7-1.6,3.6-1.6,5.6c0,5.4,4.3,10.1,10.2,11.6c0.3,0.1,0.6,0.1,0.9,0.2
c6,1.4,12.2,1.6,18.5,2.5c0.7,0.1,1.4,0.2,2.2,0.3c5.6,1,10.3,3.9,13.4,7.7l0,0c3.8,5.3,10.8,11,18.8,11c7.6,0,14.3-5.4,18.2-10.4
h0c3-4.2,8-7.3,13.9-8.4c0.7-0.1,1.4-0.3,2.2-0.3c6.3-0.9,12.5-1.1,18.5-2.5c0.3-0.1,0.6-0.1,0.9-0.2c5.9-1.6,10.2-6.2,10.2-11.6
c0-2-0.6-3.9-1.6-5.6c-0.3-0.4-0.5-0.7-0.8-1.1c-1.6-2.6-2.6-4.3-2.6-7.4c0-3.2,1-5.1,2.8-7.8c0.1-0.2,0.3-0.4,0.4-0.6
c1.1-1.7,1.7-3.7,1.7-5.8c0-2-0.6-3.9-1.6-5.6c-0.3-0.3-0.5-0.7-0.7-1c-1.6-2.6-2.6-4.3-2.6-7.5c0-3.2,1-5,2.7-7.6
C317.7,396.7,317.7,396.6,317.8,396.5z"></path>
</g>
</IconBase>;
}
};Lightbulb.defaultProps = {bare: false} |
// A layer on top of `Array.prototype` to allow for the generalization of these methods.
// Collection is mixed directly into `./util.js`, giving the chaining API for washi
// access to functional helpers.
// Save a shorthand reference to the Array prototype
const _ = Array.prototype
// The whitelist contains all of the methods we want to pluck from Array
const whitelist = [
'join',
'reverse',
'sort',
'push',
'pop',
'shift',
'unshift',
'splice',
'concat',
'slice',
'indexOf',
'lastIndexOf',
'forEach',
'map',
'reduce',
'reduceRight',
'filter',
'some',
'every'
]
// Reduce the whitelist into an object of wrapped functions that apply
// upon a given list.
const collection = whitelist.reduce(function(memo, method) {
memo[method] = function(list) {
// Extract out the list argument
var withoutList = _.slice.call(arguments, 1)
// Then apply the Array method within the list context,
// injecting all of the other arguments provided to this function
return _[method].apply(list, withoutList)
}
return memo
}, {})
// Next we add a few more helpers. Array.isArray and a method to convert list-like
// values into arrays (useful for working with arguments)
collection.isArray = Array.isArray
collection.toArray = function(list) {
return _.slice.call(list, 0)
}
export default collection
|
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
'use strict';
const users = {
4: {name: 'Mark'},
5: {name: 'Paul'},
};
export default function request(url) {
return new Promise((resolve, reject) => {
const userID = parseInt(url.substr('/users/'.length), 10);
process.nextTick(() =>
users[userID]
? resolve(users[userID])
: reject({
error: `User with ${userID} not found.`,
}),
);
});
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:4d3816a10dd2418368fd6912f4f122adc89ba1ba7519d671e4080aa93c10bdc2
size 12464
|
version https://git-lfs.github.com/spec/v1
oid sha256:debd77c1129b78647422be4abd04880e71eeec44adcafb7718daceefb9b9bc38
size 42706
|
import React from 'node_modules/react/dist/react';
import Arbiter from 'node_modules/arbiter-subpub/arbiter';
import { createGame, revealGameTile, toggleTileMark } from 'game';
import { createRenderer } from 'ui';
const arbiter = Arbiter.create();
const renderGame = createRenderer( arbiter );
const realizeGame = function realizeGame( game ) {
React.render(
renderGame( game ),
document.getElementById( 'board' )
);
};
arbiter.subscribe( 'game.reveal', data => {
const newGame = revealGameTile( data.game, data.tile );
realizeGame( newGame );
} );
arbiter.subscribe( 'game.flag', data => {
const newGame = toggleTileMark( data.game, data.tile );
realizeGame( newGame );
} );
arbiter.subscribe( 'game.new', data => {
const height = 10;
const width = 10;
const mines = Math.floor( height * width * 0.2 * Math.random() );
realizeGame( createGame( height, width, mines ) );
} );
arbiter.publish( 'game.new' );
|
Meteor.methods({
addGear: function (gearData) {
// Make sure the user is logged in before inserting a task
if (! Meteor.userId()) {
throw new Meteor.Error("not-authorized");
}
return GearList.insert({
code: gearData.code,
name: gearData.name,
description: gearData.description,
updated: new Date(),
created: new Date()
});
},
editGear: function (data) {
// Make sure the user is logged in before inserting a task
var gearId = data[0];
var gearData = data[1];
var validData = Match.test(gearData, {
code: String,
name: String,
description: String,
condition: Number
});
var validCode = Schema.inventoryCodeRegEx.test(gearData.code);
if (!validData) {
throw new Meteor.Error("invalid-data", "Incorrect Data", "Some of the information you provided was of the incorrect type.");
}
if (!validCode) {
throw new Meteor.Error("invalid-code-format", "Invalid Inventory Code", "The inventory code "+gearData.code+" does not match the pattern WM-EL-04.");
}
if (! Meteor.userId()) {
throw new Meteor.Error("not-authorized", "Not Logged In", "You must be logged in to edit equipment.");
}
GearList.update(gearId, { $set: {
code: gearData.code,
name: gearData.name,
description: gearData.description,
condition: gearData.condition,
updated: new Date()
}});
},
updateRoles: function (targetUserId, roles, group) {
var loggedInUser = Meteor.user()
if (!loggedInUser ||
!Roles.userIsInRole(loggedInUser, ['admin'], group)) {
throw new Meteor.Error(403, "Access denied")
}
Roles.setUserRoles(targetUserId, roles, group)
},
checkOut: function(userId, description, queue, notes, dueInterval) {
// require a user ID, and at least one gear item in the queue
if (! Meteor.userId()) {
throw new Meteor.Error("not-authorized");
}
if (! queue.length) {
throw new Meteor.Error("No equipment queued.");
}
// set due by date to current date + interval
var currentDate = new Date();
var dueDate = new Date();
dueDate.setDate(dueDate.getDate() + (dueInterval || 14));
// create a checkout object of the userId, user's name, all the gear and codes
var checkoutData = {
userId: userId,
notes: notes,
gearRented: queue,
dateDue: dueDate
};
// insert the object to the 'checkouts' collection
var checkoutId = Checkouts.insert(checkoutData);
// update user profile with currently rented gear
// update gear with user ID
_.each(queue, function(gearItem) {
// Create rental object
var rental = {
rentedBy: userId,
dateRented: currentDate,
checkoutId: checkoutId,
dateDue: dueDate,
returned: false,
dateReturned: null
};
GearList.update(gearItem._id, {
$set: {status: rental}
});
Meteor.call('createGearRevision', gearItem._id, 'Checked out', userId);
})
},
checkIn: function(checkoutId) {
//
},
returnGear: function(gearId) {
// get the gear object
let item = GearList.findOne(gearId);
let now = new Date();
// check if the gear item exists before continuing
if (!item) {
return;
}
// get the current status
let status = item.status
// make sure the gear is still rented out
if (status.returned) {
return;
}
// set the returned prop and returnedDate on both the history and status objects
GearList.update( gearId, {
$set: {
'status.returned' : true,
'status.dateReturned' : now
}
});
Meteor.call('createGearRevision', gearId, 'Checked in');
},
createGearRevision: function(gearId, message, userId) {
let item = GearList.findOne(gearId);
userId = userId || this.userId
message = message.trim();
History.insert({
userId: userId,
itemId: item._id,
message: message,
modified: new Date(),
model: item
})
}
});
|
'use strict';
import assert from 'yeoman-assert';
const checkContent = (status, content) => (
status ?
assert.fileContent('.circleci/config.yml', content) :
assert.noFileContent('.circleci/config.yml', content)
);
export default ({
website,
graphql,
mobileApp
}) => {
it('.circleci/config.yml', () => {
checkContent(website && graphql, '- image: jotadrilo/watchman');
checkContent(!mobileApp, '- run:');
checkContent(!mobileApp, 'name: Build');
checkContent(!mobileApp, 'command: yarn build');
checkContent(!mobileApp, 'name: Prod');
checkContent(!mobileApp, 'command: yarn prod');
});
};
|
/*
* palindrome
* https://github.com/growlybear/palindrome
*
* Copyright (c) 2012 Michael Allan
* Licensed under the MIT license.
*/
exports.test = function (string) {
var relevantCharacters,
filteredString,
reversedString;
if (typeof string !== 'string') {
return false;
}
relevantCharacters = string.match(/[a-z0-9]/gi);
if (!relevantCharacters) {
return false;
}
filteredString = relevantCharacters.join('').toLowerCase();
reversedString = filteredString.split('').reverse().join('');
return (
// is this necessary?
filteredString.length > 0 &&
filteredString === reversedString
);
};
|
const componentsPath = './components';
// classic Promise
import(`${componentsPath}/modal.js`).then(({modal}) => {
modal.open();
});
// with async/await
async function openModal() {
const {modal} = await import(`${componentsPath}/modal.js`);
modal.open();
}
openModal(); |
Vdos.find().map((elt) => Vdos.remove(elt._id))
Vdos.insert({video_id: 'AxRg12345tG'})
Vdos.insert({video_id: 'CaBPn3vZkRs'})
Vdos.insert({video_id: 'Xjrb1kDnUYY'})
Vdos.insert({video_id: 'Jw8HYF1ZpJM'})
|
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jasmine_node: {
specNameMatcher: "_test", // load only specs containing specNameMatcher
projectRoot: "test",
requirejs: false,
forceExit: true,
jUnit: {
report: false,
savePath: "./build/reports/jasmine/",
useDotNotation: true,
consolidate: true
}
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['lib/**/*.js']
},
test: {
src: ['test/**/*.js']
}
},
watch: {
test: {
files: ['lib/*.js', 'test/*.js'],
tasks: ['jshint', 'jasmine_node']
}
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-jasmine-node');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
// Default task.
grunt.registerTask('default', ['jshint', 'jasmine_node']);
};
|
var path = require('path');
var fs = require('fs');
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
function resolveApp(relativePath) {
return path.resolve(appDirectory, relativePath);
}
// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.
// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
// We will export `nodePaths` as an array of absolute paths.
// It will then be used by Webpack configs.
// Jest doesn’t need this because it already handles `NODE_PATH` out of the box.
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421
// eslint-disable-next-line vars-on-top
const nodePaths = (process.env.NODE_PATH || '')
.split(process.platform === 'win32' ? ';' : ':')
.filter(Boolean)
.filter(folder => !path.isAbsolute(folder))
.map(resolveApp);
// config after eject: we're in ./config/
module.exports = {
appBuild: resolveApp('example'),
appDist: resolveApp('dist'),
appPublic: resolveApp('public'),
appHtml: resolveApp('src/index.html'),
appExampleJs: resolveApp('src/example.js'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
yarnLockFile: resolveApp('yarn.lock'),
appNodeModules: resolveApp('node_modules'),
ownNodeModules: resolveApp('node_modules'),
nodePaths: nodePaths,
};
|
(function () {
var app = angular.module("projectManagerSPA", [
'ui.router',
'ui.bootstrap',
'toaster'
]);
app.config(['$stateProvider', '$urlRouterProvider', '$httpProvider', function($stateProvider, $urlRouterProvider, $httpProvider) {
$httpProvider.interceptors.push(function ($q) {
return {
'responseError': function (rejection) {
var defer = $q.defer();
if(rejection.status === 401) {
console.log("unauthenticated");
window.location = "#/login";
}
if(rejection.status === 400) {
console.log("bad request");
}
if(rejection.status === 403) {
console.log("unauthorized")
}
if(rejection.status === 500) {
console.log("internal server error")
}
console.log(rejection.data);
defer.reject(rejection);
return defer.promise;
}
};
});
$httpProvider.interceptors.push(function () {
return {
request: function (config) {
if(config.headers.username == null && config.headers.password == null) {
config.headers.username = localStorage.getItem('username');
config.headers.password = localStorage.getItem('password');
}
return config;
}
};
});
$urlRouterProvider.otherwise('projects');
$stateProvider.state('organizationList', {
url: '/organizations',
templateUrl: '/partials/organization.list.html',
controller: 'organizationListController'
});
$stateProvider.state('organizationCreate', {
url: '/organizations/new',
templateUrl: '/partials/organization.create.html',
controller: 'organizationCreateController'
});
$stateProvider.state('organizationEdit', {
url: '/organizations/:organizationId',
templateUrl: '/partials/organization.edit.html',
controller: 'organizationEditController'
});
$stateProvider.state('projectList', {
url: '/projects',
templateUrl: '/partials/project.list.html',
controller: 'projectListController'
});
$stateProvider.state('projectCreate', {
url: '/projects/new',
templateUrl: '/partials/project.create.html',
controller: 'projectCreateController'
});
$stateProvider.state('projectEdit', {
url: '/projects/:projectId',
templateUrl: '/partials/project.edit.html',
controller: 'projectEditController'
});
$stateProvider.state('userList', {
url: '/users',
templateUrl: '/partials/user.list.html',
controller: 'userListController'
});
$stateProvider.state('userLogin', {
url: '/login',
templateUrl: '/partials/user.login.html',
controller: 'userLoginController'
});
$stateProvider.state('userLogout', {
url: '/logout',
controller: ['authenticationService', '$state', function (authenticationService, $state) {
authenticationService.logOut();
$state.go('userLogin');
}]
});
}]);
app.run(['$state', 'authenticationService', '$rootScope', function ($state, authenticationService, $rootScope) {
if(!authenticationService.isAuthenticated()) {
$state.go('userLogin', {});
} else {
authenticationService.getCurrentUser(function (response) {
$rootScope.currentUser = response.data;
console.log(response.data);
}, function () {
})
}
}])
})();
|
import test from 'ava'
import './makeApp'
import '../helpers/Models/UserModel'
import '../helpers/Models/UserAvatarModel'
test.beforeEach(async t => {
t.context.app = await makeApp()
UserModel.app(t.context.app)
UserModel.knex(t.context.app.db)
t.context.UserModel = UserModel
UserAvatarModel.app(t.context.app)
UserAvatarModel.knex(t.context.app.db)
t.context.UserAvatarModel = UserAvatarModel
})
test.afterEach.always(t => t.context.app.shutdown())
module.exports = {
test: test.serial
}
|
var meaning, word, context;
var backend = chrome.runtime.connect({name: "connectionToBackend"});
$(document).ready(function () {
$(document).dblclick(function(e){
// Don't show meaning on double click on input
if ($(document.activeElement).is('input, textarea')) {
return;
}
var wordObject = window.getSelection();
word = $.trim(wordObject.toString().toLowerCase());
var result = word.split(/[\n\r\s]+/);
// To disable multiple words selection
// and null selection
if (result.length != 1 || !isValidInput(word)) {
return;
}
showQtip(e.target, e);
fetchMeaningCambridge(word, function(message){
meaning = message;
changeQtipText(meaning);
});
context = getContext(wordObject);
});
});
function showQtip(selector, e) {
$(selector).qtip({
id: 'meaningTooltip',
content: {
text: "Searching for meaning...",
button: true
},
position: {
target: [e.pageX, e.pageY],
viewport: $(window),
adjust: {
y: 12,
mouse: false,
method: "flipinvert"
},
my: "top center",
at: "bottom center"
},
show: {
ready: true
},
style: {
classes: "qtip-blue"
},
hide: {
event: 'unfocus'
},
events: {
hide: function(event, api) {
if (!meaning || meaning === noMeaningFoundError || meaning == otherError) {
// First destroy the qTip
api.destroy();
// Don't save the word
return;
}
// If no context exists
if (!context) {
context = "No context found";
}
// Save the word if user has selected to
if ($('#zingerShowLater').is(':checked')) {
backend.postMessage({type: "saveWord", word: word, meaning: meaning, context: context});
}
// When next time this function is called and meaning
// is not updated (i.e still searching for meaning)
// then don't use the previous meaning
meaning = null;
api.destroy();
}
}
});
}
function changeQtipText(newText) {
newText += "\
<strong>\
<p>Show later <input type='checkbox' id='zingerShowLater' checked></p>\
</strong>";
$('#qtip-meaningTooltip').qtip('option', 'content.text', newText);
}
function isValidInput(string) {
if(/^[a-zA-Z]+$/.test(string) == false) {
return false;
} else {
return true;
}
}
// Listen for incoming requests from browser_action script
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection") {
sendResponse({data: window.getSelection().toString(), context:getContext(window.getSelection())});
} else {
sendResponse({}); // snub them.
}
});
|
/**
* Get the self object reference.
* @returns {Object} The self object if client side, false otherwise.
*/
function getSelf()
{
if (typeof self !== "undefined")
return self;
return false;
}
module.exports = getSelf; |
var exResults = [];
//viz. http://jsfiddle.net/KJQ9K/554/
function syntaxHighlight(json) {
json = json.replace(/&/g, '&');//.replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
function prettify(json) {
var pretty = syntaxHighlight(json);
return "<pre>" + pretty + "</pre>";
}
var descCounter = 0;
function desc(str, func) {
if(!func) {
document.write(str);
return;
}
var out = "";
out += str;
var funcBody = func.toString();
funcBody = funcBody.substr(funcBody.indexOf("{") + 1);
funcBody = funcBody.substr(0, funcBody.lastIndexOf("\n"));
funcBody = funcBody.split("\n").map(function (s) {
return s.substr(4);
}).join("\n");
funcBody = syntaxHighlight(funcBody);
var exCount = 0;
funcBody = funcBody.split("\n").map(function (s) {
if (s.match(/^\s*ex\(/)) {
exCount++;
return "<span class='ex-index'>" + exCount + ".</span>" + s.substr(2);
} else {
return s;
}
}).join("\n");
out += "<pre>" + funcBody + "</pre>";
exResults = [];
func();
out += "<ol class='examples'>";
var errorCount = 0;
for (var i = 0; i < exResults.length; i++) {
var left = exResults[i].left;
var right = exResults[i].right;
var renderer = exResults[i].renderer;
if (left == right || right === undefined) {
out += "<li class='good'>" +
"<details>" +
"<summary>ex " + (i + 1) + " as expected.</summary>" +
renderer(left) +
"</details>";
} else {
out += "<li class='bad'>" +
"<details open='true'>" +
"<summary>ex " + (i + 1) + " not as expected.</summary>" +
renderer(left) +
renderer(right) +
"</details>";
console.error("Got",left,"expected",right);
errorCount++;
}
}
out += "</ol>";
document.write(out);
if (errorCount) {
console.error("Desc " + descCounter + " had " + errorCount + " errors");
} else {
console.info("Desc " + descCounter + " OK");
}
exResults = [];
descCounter++;
}
function isString(s) {
return typeof s === 'string' || s instanceof String;
}
function fnReplacer(_key, value) {
if(typeof(value) == "function") {
return value.toString().replace(/\n/g,"<br/>");
}
return value;
}
function preRenderer(val) {
return "<pre>"+val+"</pre>";
}
function jsonRenderer(val) {
return JSON.stringify(val, fnReplacer, 2);
}
function ex(v1, v2, renderer) {
var result;
if (isString(v1) && (v2 === undefined || isString(v2))) {
result = {
left: v1,
right: v2,
renderer: renderer || preRenderer
};
} else {
result = {
left: JSON.stringify(v1, fnReplacer, 2),
right: (v2 === undefined ? undefined : JSON.stringify(v2, fnReplacer, 2)),
renderer: renderer || prettify
};
}
exResults.push(result);
}
document.addEventListener("DOMContentLoaded", function(_e) {
var elts = document.getElementsByClassName("diagram");
for(var i = 0; i < elts.length; i++) {
var elt = elts[i];
elt.innerHTML = Viz(elt.textContent);
}
}); |
var line = "#"
while(line.length <= 7){
console.log(line);
line += "#"
} |
import { canChangeLocation } from '../../lib/helpers/scanner';
import i18n from '../../lib/i18n';
import { open as openModal } from '../modalActions';
export default () => (dispatch) => {
if (canChangeLocation()) {
dispatch(openModal({
cancelable: false,
message: i18n('general.scanner.invalid.message'),
title: i18n('general.scanner.invalid.title'),
}));
}
};
|
define(function (require) {
var entities = [];
function init(callback) {
entities.push({ type: 'gameOver' });
callback();
}
return {
'name': 'game-over',
'init': init,
'entities': entities,
'width': 1280,
'height': 720
};
});
|
import { runAuthenticatedQuery } from "test/utils"
describe("FollowGene", () => {
it("follows a gene", () => {
const mutation = `
mutation {
followGene(input: { gene_id: "pop-art" }) {
gene {
id
name
}
}
}
`
const rootValue = {
followGeneLoader: () =>
Promise.resolve({
gene: {
family: {},
id: "pop-art",
name: "Pop Art",
image_url: "",
image_urls: {},
display_name: null,
},
}),
geneLoader: () =>
Promise.resolve({
family: {
id: "styles-and-movements",
},
id: "pop-art",
name: "Pop Art",
browseable: true,
}),
}
const expectedGeneData = {
gene: {
id: "pop-art",
name: "Pop Art",
},
}
expect.assertions(1)
return runAuthenticatedQuery(mutation, rootValue).then(({ followGene }) => {
expect(followGene).toEqual(expectedGeneData)
})
})
})
|
// This exposes the plugin utilities
var plugin = require('shelljs/plugin');
// Require whatever modules you need for your project
var opener = require('opener');
var fs = require('fs');
var pathExistsSync = function (filePath) {
try {
fs.accessSync(filePath);
return true;
} catch (e) {
return false;
}
};
// Implement your command in a function, which accepts `options` as the
// first parameter, and other arguments after that
function open(options, fileName) {
var URL_REGEX = /^https?:\/\/.*/;
if (!pathExistsSync(fileName) && !fileName.match(URL_REGEX)) {
plugin.error('Unable to locate file: ' + fileName);
}
var proc = opener(fileName);
proc.unref();
proc.stdin.unref();
proc.stdout.unref();
proc.stderr.unref();
return '';
}
// Register the new plugin as a ShellJS command
plugin.register('open', open, {
cmdOptions: {}, // There are no supported options for this command
});
// Optionally, you can export the implementation of the command like so:
exports.open = open;
|
(function () {
'use strict';
describe('Billdetails Controller Tests', function () {
// Initialize global variables
var BilldetailsController,
$scope,
$httpBackend,
$state,
Authentication,
BilldetailsService,
mockBilldetail;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function () {
jasmine.addMatchers({
toEqualData: function (util, customEqualityTesters) {
return {
compare: function (actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _BilldetailsService_) {
// Set a new global scope
$scope = $rootScope.$new();
// Point global variables to injected services
$httpBackend = _$httpBackend_;
$state = _$state_;
Authentication = _Authentication_;
BilldetailsService = _BilldetailsService_;
// create mock Billdetail
mockBilldetail = new BilldetailsService({
_id: '525a8422f6d0f87f0e407a33',
name: 'Billdetail Name'
});
// Mock logged in user
Authentication.user = {
roles: ['user']
};
// Initialize the Billdetails controller.
BilldetailsController = $controller('BilldetailsController as vm', {
$scope: $scope,
billdetailResolve: {}
});
// Spy on state go
spyOn($state, 'go');
}));
describe('vm.save() as create', function () {
var sampleBilldetailPostData;
beforeEach(function () {
// Create a sample Billdetail object
sampleBilldetailPostData = new BilldetailsService({
name: 'Billdetail Name'
});
$scope.vm.billdetail = sampleBilldetailPostData;
});
it('should send a POST request with the form input values and then locate to new object URL', inject(function (BilldetailsService) {
// Set POST response
$httpBackend.expectPOST('api/billdetails', sampleBilldetailPostData).respond(mockBilldetail);
// Run controller functionality
$scope.vm.save(true);
$httpBackend.flush();
// Test URL redirection after the Billdetail was created
expect($state.go).toHaveBeenCalledWith('billdetails.view', {
billdetailId: mockBilldetail._id
});
}));
it('should set $scope.vm.error if error', function () {
var errorMessage = 'this is an error message';
$httpBackend.expectPOST('api/billdetails', sampleBilldetailPostData).respond(400, {
message: errorMessage
});
$scope.vm.save(true);
$httpBackend.flush();
expect($scope.vm.error).toBe(errorMessage);
});
});
describe('vm.save() as update', function () {
beforeEach(function () {
// Mock Billdetail in $scope
$scope.vm.billdetail = mockBilldetail;
});
it('should update a valid Billdetail', inject(function (BilldetailsService) {
// Set PUT response
$httpBackend.expectPUT(/api\/billdetails\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
$scope.vm.save(true);
$httpBackend.flush();
// Test URL location to new object
expect($state.go).toHaveBeenCalledWith('billdetails.view', {
billdetailId: mockBilldetail._id
});
}));
it('should set $scope.vm.error if error', inject(function (BilldetailsService) {
var errorMessage = 'error';
$httpBackend.expectPUT(/api\/billdetails\/([0-9a-fA-F]{24})$/).respond(400, {
message: errorMessage
});
$scope.vm.save(true);
$httpBackend.flush();
expect($scope.vm.error).toBe(errorMessage);
}));
});
describe('vm.remove()', function () {
beforeEach(function () {
// Setup Billdetails
$scope.vm.billdetail = mockBilldetail;
});
it('should delete the Billdetail and redirect to Billdetails', function () {
// Return true on confirm message
spyOn(window, 'confirm').and.returnValue(true);
$httpBackend.expectDELETE(/api\/billdetails\/([0-9a-fA-F]{24})$/).respond(204);
$scope.vm.remove();
$httpBackend.flush();
expect($state.go).toHaveBeenCalledWith('billdetails.list');
});
it('should should not delete the Billdetail and not redirect', function () {
// Return false on confirm message
spyOn(window, 'confirm').and.returnValue(false);
$scope.vm.remove();
expect($state.go).not.toHaveBeenCalled();
});
});
});
}());
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import moment from 'moment';
import DayPicker, { DateUtils } from 'react-day-picker';
// STORE
import { loadEvents } from 'redux/modules/eventsModule';
// COMPONENTS
import { LoadingScreen } from 'components';
const debug = false;
const mappedState = ({ events }) => ({
events: events.all,
loadingEvents: events.loadingEvents,
eventsLoaded: events.eventsLoaded
});
const mappedActions = { loadEvents };
@connect(mappedState, mappedActions)
export default class EventsCalendar extends Component {
static propTypes = {
events: PropTypes.array.isRequired,
loadingEvents: PropTypes.bool.isRequired,
eventsLoaded: PropTypes.bool.isRequired,
loadEvents: PropTypes.func.isRequired,
onDayClick: PropTypes.func,
showEventsList: PropTypes.bool
};
state = {
from: null,
to: null,
activeMonth: moment()
};
componentWillMount() {
if (!this.props.eventsLoaded && !this.props.loadingEvents) {
this.props.loadEvents();
}
}
handleDayClick = (day, modifiers) => {
if (modifiers.disabled) return;
const range = DateUtils.addDayToRange(day, this.state);
if (range.from) {
let rangeTo = new Date(range.from.setHours(23, 59));
range.from = new Date(range.from.setHours(0, 0));
if (range.to) rangeTo = new Date(range.to.setHours(23, 59));
range.to = rangeTo;
}
this.setState(range);
if (this.props.onDayClick) this.props.onDayClick(range);
if (debug) console.info('Clicked date:', day, modifiers);
this.setState({ selectedDay: modifiers.selected ? null : day });
};
handleMonthChange = date => {
this.setState({ activeMonth: moment(date) });
};
render() {
const { from, to, activeMonth } = this.state;
const activeMonthEvents = this.props.events.filter(event =>
activeMonth.isSame(moment(event.date), 'month')
);
return (
<LoadingScreen loading={this.props.loadingEvents}>
<div>
<DayPicker
initialMonth={activeMonth.toDate()}
selectedDays={[from, { from, to }]}
onDayClick={this.handleDayClick}
onMonthChange={this.handleMonthChange}
modifiers={{
hasEvent: day => {
// Mark days that has the same date as an event
return !!this.props.events.find(event =>
moment(day).isSame(moment(event.date), 'day')
);
}
}}
/>
{this.props.showEventsList &&
<div>
Events for the month of {activeMonth.format('MMMM')}:
<ul>
{activeMonthEvents.map(event => (
<li key={event.id}>{event.title}</li>
))}
</ul>
</div>}
</div>
</LoadingScreen>
);
}
}
|
import $ from 'jquery';
import Backbone from 'backbone';
import Marionette from 'backbone.marionette';
import DeleteView from './views/delete';
export default Marionette.Object.extend({
initialize: function(App, data) {
this.app = App;
this.data = data;
},
respond: function() {
return $.when(this.data).then(function(data) {
return new DeleteView({
model: data
});
})
}
}); |
$(document).ready(function () {
var questionNumber=0;
var questionBank=new Array();
var stage="#game1";
var stage2=new Object;
var questionLock=false;
var numberOfQuestions;
var score=0;
$.getJSON('activity3.json', function(data) {
for(i=0;i<data.quizlist.length;i++){
questionBank[i]=new Array;
questionBank[i][0]=data.quizlist[i].question;
questionBank[i][1]=data.quizlist[i].option1;
questionBank[i][2]=data.quizlist[i].option2;
questionBank[i][3]=data.quizlist[i].option3;
questionBank[i][4]=data.quizlist[i].option4;
questionBank[i][5]=data.quizlist[i].option5;
questionBank[i][6]=data.quizlist[i].option6;
}
numberOfQuestions=questionBank.length;
displayQuestion();
})//gtjson
fillDB();
function displayQuestion(){
var rnd=Math.random()*3;
rnd=Math.ceil(rnd);
var q1;
var q2;
var q3;
var q4;
var q5;
var q6;
if(rnd==1){q1=questionBank[questionNumber][1];q2=questionBank[questionNumber][2];q3=questionBank[questionNumber][3];}
if(rnd==2){q2=questionBank[questionNumber][1];q3=questionBank[questionNumber][2];q1=questionBank[questionNumber][3];}
if(rnd==3){q3=questionBank[questionNumber][1];q1=questionBank[questionNumber][2];q2=questionBank[questionNumber][3];}
if(rnd==4){q4=questionBank[questionNumber][1];q5=questionBank[questionNumber][2];q6=questionBank[questionNumber][3];}
if(rnd==5){q5=questionBank[questionNumber][1];q6=questionBank[questionNumber][2];q4=questionBank[questionNumber][3];}
if(rnd==6){q6=questionBank[questionNumber][1];q4=questionBank[questionNumber][2];q5=questionBank[questionNumber][3];}
$(stage).append('<div class="questionText">'+questionBank[questionNumber][0]+'</div><div id="1" class="pix"><img src="img/'+q1+'"></div><div id="2" class="pix"><img src="img/'+q2+'"></div><div id="3" class="pix"><img src="img/'+q3+'"></div>');
$('.pix').click(function(){
var audio = new Audio('y.mp3');
var audio2 = new Audio('z.mp3');
if(questionLock==false){questionLock=true;
//correct answer
if(this.id==rnd){
$(stage).append('<div class="feedback1">CORRECT</div>');
audio.play();
score++;
}
//wrong answer
if(this.id!=rnd){
$(stage).append('<div class="feedback2">WRONG</div>');
audio2.play();
}
setTimeout(function(){changeQuestion()},1000);
}})
}//display question
function changeQuestion(){
questionNumber++;
if(stage=="#game1"){stage2="#game1";stage="#game2";}
else{stage2="#game2";stage="#game1";}
if(questionNumber<numberOfQuestions){displayQuestion();}else{displayFinalSlide();}
$(stage2).animate({"right": "+=800px"},"slow", function() {$(stage2).css('right','-800px');$(stage2).empty();});
$(stage).animate({"right": "+=800px"},"slow", function() {questionLock=false;});
}//change question
function displayFinalSlide(){
$(stage).append('<div class="questionText"><b>You have finished the quiz!<br><br>Total questions: '+numberOfQuestions+'<br>Correct answers: '+score+'</div>');
$(stage).append('<br><a href="menu.html"><input type="image" src="img/home.png" name="image" width="60" height="60"></a>');
$(stage).append('<span class="exit"><a href="quizlevel.html"><input type="image" src="img/exit.png" name="image" width="60" height="60"></a></span>');
}//display final slide
});//doc ready |
define([
'angular',
'angular-ui-router',
'angular-translate',
'angular-growl',
'angular-animate',
'ocLazyLoad',
'ngActivityIndicator',
'bootstrap',
'common/main'
], function(angular, uiRoute, translate, animate, growl, ocLazyLoad, ngActivityIndicator, bootstrap) {
'use strict';
var app = angular.module('app', [
'ui.router',
'pascalprecht.translate',
'oc.lazyLoad',
'ui.bootstrap',
'angular-growl',
'ngAnimate',
'ngActivityIndicator',
'common'
]);
app.config([
'$translateProvider',
'$activityIndicatorProvider',
'growlProvider',
function($translateProvider, $activityIndicatorProvider, growlProvider) {
// growl messages..
growlProvider.globalPosition('bottom-right');
$activityIndicatorProvider.setActivityIndicatorStyle('CircledDark');
$translateProvider.translations('en', {
HEADLINE: 'Hello !'
}).translations('hi', {
HEADLINE: 'नमस्कार!'
});
$translateProvider.preferredLanguage('hi');
}
]);
return app;
}); |
(function(angular){
"use strict";
/**
* @ngdoc module
*
* @name mfl.setup.routes
*
* @description
* Contains the modules used for setup routes
*/
angular.module("mfl.setup.routes",[
"mfl.setup.routes.constituencies",
"mfl.setup.routes.counties",
"mfl.setup.routes.sub_counties",
"mfl.setup.routes.dashboard",
"mfl.setup.routes.keph",
"mfl.setup.routes.towns",
"mfl.setup.routes.wards",
"mfl.setup.routes.contacts",
"mfl.setup.routes.facilities",
"mfl.setup.routes.chu",
"mfl.setup.routes.gis",
"mfl.setup.routes.documents"
]);
})(window.angular);
|
/**
* Created by Chi J on 6/17/2016.
*/
function appRouter( $stateProvider, $urlRouterProvider ){
$urlRouterProvider.otherwise('/');
$stateProvider
.state( 'login', {
url: '/',
templateUrl: '../templates/login.html',
controller: 'loginController as vm',
resolve: {
loginService: loginService
}
} )
.state( 'signUp', {
url: '/signUp',
templateUrl: '../templates/signUp.html'
} )
.state( 'publicHall', {
url:'/publicHall',
templateUrl: '../templates/publicHall.html',
controller: 'publicHallController as publicVM',
resolve: {
loginService: loginService
}
} )
.state( 'homepage', {
url:'/homepage',
templateUrl: '../templates/homepage.html',
controller: 'homePageController as homeVM'
} )
.state( 'homepage.settings', {
url: '/settings',
templateUrl: '../templates/settings.html'
} )
.state( 'homepage.new', {
url:'/new',
templateUrl: '../templates/homeTabsContent/myNewNews.html',
controller: 'myNewNewsController as newNewsVM'
} )
.state( 'homepage.trending', {
url:'/trending',
templateUrl: '../templates/homeTabsContent/trending.html'
} )
.state( 'homepage.top', {
url:'/top',
templateUrl: '../templates/homeTabsContent/top.html'
} )
.state( 'userHomePage', {
url: '/userHomePage',
templateUrl: '../templates/userHomePage.html',
controller: 'userHomePageController as userHomeVM'
} )
.state( 'userHomePage.followers', {
url: '/followers',
templateUrl: '../templates/userHomeTabsContents/followers.html'
} )
.state( 'userHomePage.leaders', {
url: '/leaders',
templateUrl: '../templates/userHomeTabsContents/leaders.html'
} )
.state( 'userHomePage.myPolls', {
url: '/myPolls',
templateUrl: '../templates/userHomeTabsContents/myPolls.html',
controller : 'myPollsController as myPollVM',
resolve: {
myPollService: myPollService
}
} )
.state( 'userHomePage.requests', {
url: '/requests',
templateUrl: '../templates/userHomeTabsContents/requests.html'
} );
}
angular
.module('myApp')
.config( appRouter ); |
var util = require("util");
var choreography = require("temboo/core/choreography");
/*
FilterPlacesByCategories
Filter queries by category.
*/
var FilterPlacesByCategories = function(session) {
/*
Create a new instance of the FilterPlacesByCategories Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/Factual/FilterPlacesByCategories"
FilterPlacesByCategories.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new FilterPlacesByCategoriesResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new FilterPlacesByCategoriesInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the FilterPlacesByCategories
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var FilterPlacesByCategoriesInputSet = function() {
FilterPlacesByCategoriesInputSet.super_.call(this);
/*
Set the value of the APIKey input for this Choreo. ((optional, string) The API Key provided by Factual (AKA the OAuth Consumer Key).)
*/
this.set_APIKey = function(value) {
this.setInput("APIKey", value);
}
/*
Set the value of the APISecret input for this Choreo. ((optional, string) The API Secret provided by Factual (AKA the OAuth Consumer Secret).)
*/
this.set_APISecret = function(value) {
this.setInput("APISecret", value);
}
/*
Set the value of the Category input for this Choreo. ((required, string) Enter a Factual category to narrow the search results.)
*/
this.set_Category = function(value) {
this.setInput("Category", value);
}
/*
Set the value of the City input for this Choreo. ((required, string) Enter a city to narrow results to.)
*/
this.set_City = function(value) {
this.setInput("City", value);
}
/*
Set the value of the Query input for this Choreo. ((optional, string) A search string (i.e. Starbucks))
*/
this.set_Query = function(value) {
this.setInput("Query", value);
}
}
/*
A ResultSet with methods tailored to the values returned by the FilterPlacesByCategories Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var FilterPlacesByCategoriesResultSet = function(resultStream) {
FilterPlacesByCategoriesResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Factual.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
}
util.inherits(FilterPlacesByCategories, choreography.Choreography);
util.inherits(FilterPlacesByCategoriesInputSet, choreography.InputSet);
util.inherits(FilterPlacesByCategoriesResultSet, choreography.ResultSet);
exports.FilterPlacesByCategories = FilterPlacesByCategories;
/*
FilterPlacesByCity
Restrict a query to a specified city.
*/
var FilterPlacesByCity = function(session) {
/*
Create a new instance of the FilterPlacesByCity Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/Factual/FilterPlacesByCity"
FilterPlacesByCity.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new FilterPlacesByCityResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new FilterPlacesByCityInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the FilterPlacesByCity
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var FilterPlacesByCityInputSet = function() {
FilterPlacesByCityInputSet.super_.call(this);
/*
Set the value of the APIKey input for this Choreo. ((optional, string) The API Key provided by Factual (AKA the OAuth Consumer Key).)
*/
this.set_APIKey = function(value) {
this.setInput("APIKey", value);
}
/*
Set the value of the APISecret input for this Choreo. ((optional, string) The API Secret provided by Factual (AKA the OAuth Consumer Secret).)
*/
this.set_APISecret = function(value) {
this.setInput("APISecret", value);
}
/*
Set the value of the City input for this Choreo. ((required, string) Enter a city to narrow results to.)
*/
this.set_City = function(value) {
this.setInput("City", value);
}
/*
Set the value of the Query input for this Choreo. ((optional, string) A search string (i.e. Starbucks))
*/
this.set_Query = function(value) {
this.setInput("Query", value);
}
}
/*
A ResultSet with methods tailored to the values returned by the FilterPlacesByCity Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var FilterPlacesByCityResultSet = function(resultStream) {
FilterPlacesByCityResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Factual.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
}
util.inherits(FilterPlacesByCity, choreography.Choreography);
util.inherits(FilterPlacesByCityInputSet, choreography.InputSet);
util.inherits(FilterPlacesByCityResultSet, choreography.ResultSet);
exports.FilterPlacesByCity = FilterPlacesByCity;
/*
FilterPlacesByMultipleCities
Restrict a query to a specified city.
*/
var FilterPlacesByMultipleCities = function(session) {
/*
Create a new instance of the FilterPlacesByMultipleCities Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/Factual/FilterPlacesByMultipleCities"
FilterPlacesByMultipleCities.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new FilterPlacesByMultipleCitiesResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new FilterPlacesByMultipleCitiesInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the FilterPlacesByMultipleCities
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var FilterPlacesByMultipleCitiesInputSet = function() {
FilterPlacesByMultipleCitiesInputSet.super_.call(this);
/*
Set the value of the APIKey input for this Choreo. ((optional, string) The API Key provided by Factual (AKA the OAuth Consumer Key).)
*/
this.set_APIKey = function(value) {
this.setInput("APIKey", value);
}
/*
Set the value of the APISecret input for this Choreo. ((optional, string) The API Secret provided by Factual (AKA the OAuth Consumer Secret).)
*/
this.set_APISecret = function(value) {
this.setInput("APISecret", value);
}
/*
Set the value of the Cities input for this Choreo. ((required, string) Enter a list of cities to filter results. Use the following comma-separated format: "New York", "Ithaca", "Albany")
*/
this.set_Cities = function(value) {
this.setInput("Cities", value);
}
/*
Set the value of the Query input for this Choreo. ((optional, string) A search string (i.e. Starbucks).)
*/
this.set_Query = function(value) {
this.setInput("Query", value);
}
}
/*
A ResultSet with methods tailored to the values returned by the FilterPlacesByMultipleCities Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var FilterPlacesByMultipleCitiesResultSet = function(resultStream) {
FilterPlacesByMultipleCitiesResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Factual.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
}
util.inherits(FilterPlacesByMultipleCities, choreography.Choreography);
util.inherits(FilterPlacesByMultipleCitiesInputSet, choreography.InputSet);
util.inherits(FilterPlacesByMultipleCitiesResultSet, choreography.ResultSet);
exports.FilterPlacesByMultipleCities = FilterPlacesByMultipleCities;
/*
FilterPlacesByTopLevelCategory
Find places by top-level category and near specified latitude, longitude coordinates.
*/
var FilterPlacesByTopLevelCategory = function(session) {
/*
Create a new instance of the FilterPlacesByTopLevelCategory Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/Factual/FilterPlacesByTopLevelCategory"
FilterPlacesByTopLevelCategory.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new FilterPlacesByTopLevelCategoryResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new FilterPlacesByTopLevelCategoryInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the FilterPlacesByTopLevelCategory
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var FilterPlacesByTopLevelCategoryInputSet = function() {
FilterPlacesByTopLevelCategoryInputSet.super_.call(this);
/*
Set the value of the APIKey input for this Choreo. ((optional, string) The API Key provided by Factual (AKA the OAuth Consumer Key).)
*/
this.set_APIKey = function(value) {
this.setInput("APIKey", value);
}
/*
Set the value of the APISecret input for this Choreo. ((optional, string) The API Secret provided by Factual (AKA the OAuth Consumer Secret).)
*/
this.set_APISecret = function(value) {
this.setInput("APISecret", value);
}
/*
Set the value of the Category input for this Choreo. ((required, string) Enter a Factual top-level category to narrow the search results. See Choreo doc for a list of Factual top-level categories.)
*/
this.set_Category = function(value) {
this.setInput("Category", value);
}
/*
Set the value of the Latitude input for this Choreo. ((required, decimal) Enter latitude coordinates of the location defining the center of the search radius.)
*/
this.set_Latitude = function(value) {
this.setInput("Latitude", value);
}
/*
Set the value of the Longitude input for this Choreo. ((required, decimal) Enter longitude coordinates of the location defining the center of the search radius.)
*/
this.set_Longitude = function(value) {
this.setInput("Longitude", value);
}
/*
Set the value of the Query input for this Choreo. ((optional, string) A search string (i.e. Starbucks))
*/
this.set_Query = function(value) {
this.setInput("Query", value);
}
/*
Set the value of the Radius input for this Choreo. ((required, integer) Provide the radius (in meters, and centered on the latitude-longitude coordinates specified) for which search results will be returned.)
*/
this.set_Radius = function(value) {
this.setInput("Radius", value);
}
}
/*
A ResultSet with methods tailored to the values returned by the FilterPlacesByTopLevelCategory Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var FilterPlacesByTopLevelCategoryResultSet = function(resultStream) {
FilterPlacesByTopLevelCategoryResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Factual.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
}
util.inherits(FilterPlacesByTopLevelCategory, choreography.Choreography);
util.inherits(FilterPlacesByTopLevelCategoryInputSet, choreography.InputSet);
util.inherits(FilterPlacesByTopLevelCategoryResultSet, choreography.ResultSet);
exports.FilterPlacesByTopLevelCategory = FilterPlacesByTopLevelCategory;
/*
FilterRestaurantsByCuisineAndCoordinates
Find restaurants by cuisine and near specified latitude, longitude coordinates.
*/
var FilterRestaurantsByCuisineAndCoordinates = function(session) {
/*
Create a new instance of the FilterRestaurantsByCuisineAndCoordinates Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/Factual/FilterRestaurantsByCuisineAndCoordinates"
FilterRestaurantsByCuisineAndCoordinates.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new FilterRestaurantsByCuisineAndCoordinatesResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new FilterRestaurantsByCuisineAndCoordinatesInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the FilterRestaurantsByCuisineAndCoordinates
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var FilterRestaurantsByCuisineAndCoordinatesInputSet = function() {
FilterRestaurantsByCuisineAndCoordinatesInputSet.super_.call(this);
/*
Set the value of the APIKey input for this Choreo. ((optional, string) The API Key provided by Factual (AKA the OAuth Consumer Key).)
*/
this.set_APIKey = function(value) {
this.setInput("APIKey", value);
}
/*
Set the value of the APISecret input for this Choreo. ((optional, string) The API Secret provided by Factual (AKA the OAuth Consumer Secret).)
*/
this.set_APISecret = function(value) {
this.setInput("APISecret", value);
}
/*
Set the value of the Cuisine input for this Choreo. ((required, string) Enter a desired cuisine to narrow the search results. See Choreo doc for a list of available cuisine parameters.)
*/
this.set_Cuisine = function(value) {
this.setInput("Cuisine", value);
}
/*
Set the value of the Latitude input for this Choreo. ((required, decimal) Enter latitude coordinates of the location defining the center of the search radius.)
*/
this.set_Latitude = function(value) {
this.setInput("Latitude", value);
}
/*
Set the value of the Longitude input for this Choreo. ((required, decimal) Enter longitude coordinates of the location defining the center of the search radius.)
*/
this.set_Longitude = function(value) {
this.setInput("Longitude", value);
}
/*
Set the value of the Radius input for this Choreo. ((required, integer) Provide the radius (in meters, and centered on the latitude-longitude coordinates specified) for which search results will be returned.)
*/
this.set_Radius = function(value) {
this.setInput("Radius", value);
}
}
/*
A ResultSet with methods tailored to the values returned by the FilterRestaurantsByCuisineAndCoordinates Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var FilterRestaurantsByCuisineAndCoordinatesResultSet = function(resultStream) {
FilterRestaurantsByCuisineAndCoordinatesResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Factual.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
}
util.inherits(FilterRestaurantsByCuisineAndCoordinates, choreography.Choreography);
util.inherits(FilterRestaurantsByCuisineAndCoordinatesInputSet, choreography.InputSet);
util.inherits(FilterRestaurantsByCuisineAndCoordinatesResultSet, choreography.ResultSet);
exports.FilterRestaurantsByCuisineAndCoordinates = FilterRestaurantsByCuisineAndCoordinates;
/*
FindPlacesByName
Search for places by name.
*/
var FindPlacesByName = function(session) {
/*
Create a new instance of the FindPlacesByName Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/Factual/FindPlacesByName"
FindPlacesByName.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new FindPlacesByNameResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new FindPlacesByNameInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the FindPlacesByName
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var FindPlacesByNameInputSet = function() {
FindPlacesByNameInputSet.super_.call(this);
/*
Set the value of the APIKey input for this Choreo. ((optional, string) The API Key provided by Factual (AKA the OAuth Consumer Key).)
*/
this.set_APIKey = function(value) {
this.setInput("APIKey", value);
}
/*
Set the value of the APISecret input for this Choreo. ((optional, string) The API Secret provided by Factual (AKA the OAuth Consumer Secret).)
*/
this.set_APISecret = function(value) {
this.setInput("APISecret", value);
}
/*
Set the value of the Query input for this Choreo. ((required, string) A search string (i.e. Starbucks))
*/
this.set_Query = function(value) {
this.setInput("Query", value);
}
}
/*
A ResultSet with methods tailored to the values returned by the FindPlacesByName Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var FindPlacesByNameResultSet = function(resultStream) {
FindPlacesByNameResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Factual.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
}
util.inherits(FindPlacesByName, choreography.Choreography);
util.inherits(FindPlacesByNameInputSet, choreography.InputSet);
util.inherits(FindPlacesByNameResultSet, choreography.ResultSet);
exports.FindPlacesByName = FindPlacesByName;
/*
FindPlacesNearCoordinates
Find places near specified latitude, longitude coordinates.
*/
var FindPlacesNearCoordinates = function(session) {
/*
Create a new instance of the FindPlacesNearCoordinates Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/Factual/FindPlacesNearCoordinates"
FindPlacesNearCoordinates.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new FindPlacesNearCoordinatesResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new FindPlacesNearCoordinatesInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the FindPlacesNearCoordinates
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var FindPlacesNearCoordinatesInputSet = function() {
FindPlacesNearCoordinatesInputSet.super_.call(this);
/*
Set the value of the APIKey input for this Choreo. ((optional, string) The API Key provided by Factual (AKA the OAuth Consumer Key).)
*/
this.set_APIKey = function(value) {
this.setInput("APIKey", value);
}
/*
Set the value of the APISecret input for this Choreo. ((optional, string) The API Secret provided by Factual (AKA the OAuth Consumer Secret).)
*/
this.set_APISecret = function(value) {
this.setInput("APISecret", value);
}
/*
Set the value of the Latitude input for this Choreo. ((required, decimal) Enter latitude coordinates of the location defining the center of the search radius.)
*/
this.set_Latitude = function(value) {
this.setInput("Latitude", value);
}
/*
Set the value of the Longitude input for this Choreo. ((required, decimal) Enter longitude coordinates of the location defining the center of the search radius.)
*/
this.set_Longitude = function(value) {
this.setInput("Longitude", value);
}
/*
Set the value of the Query input for this Choreo. ((optional, string) A search string (i.e. Starbucks))
*/
this.set_Query = function(value) {
this.setInput("Query", value);
}
/*
Set the value of the Radius input for this Choreo. ((required, integer) Provide the radius (in meters, and centered on the latitude-longitude coordinates specified) for which search results will be returned.)
*/
this.set_Radius = function(value) {
this.setInput("Radius", value);
}
}
/*
A ResultSet with methods tailored to the values returned by the FindPlacesNearCoordinates Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var FindPlacesNearCoordinatesResultSet = function(resultStream) {
FindPlacesNearCoordinatesResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Factual.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
}
util.inherits(FindPlacesNearCoordinates, choreography.Choreography);
util.inherits(FindPlacesNearCoordinatesInputSet, choreography.InputSet);
util.inherits(FindPlacesNearCoordinatesResultSet, choreography.ResultSet);
exports.FindPlacesNearCoordinates = FindPlacesNearCoordinates;
/*
FindRestaurantsByName
Search for restaurants by name.
*/
var FindRestaurantsByName = function(session) {
/*
Create a new instance of the FindRestaurantsByName Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
*/
var location = "/Library/Factual/FindRestaurantsByName"
FindRestaurantsByName.super_.call(this, session, location);
/*
Define a callback that will be used to appropriately format the results of this Choreo.
*/
var newResultSet = function(resultStream) {
return new FindRestaurantsByNameResultSet(resultStream);
}
/*
Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
*/
this.newInputSet = function() {
return new FindRestaurantsByNameInputSet();
}
/*
Execute this Choreo with the specified inputs, calling the specified callback upon success,
and the specified errorCallback upon error.
*/
this.execute = function(inputs, callback, errorCallback) {
this._execute(inputs, newResultSet, callback, errorCallback);
}
}
/*
An InputSet with methods appropriate for specifying the inputs to the FindRestaurantsByName
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/
var FindRestaurantsByNameInputSet = function() {
FindRestaurantsByNameInputSet.super_.call(this);
/*
Set the value of the APIKey input for this Choreo. ((optional, string) The API Key provided by Factual (AKA the OAuth Consumer Key).)
*/
this.set_APIKey = function(value) {
this.setInput("APIKey", value);
}
/*
Set the value of the APISecret input for this Choreo. ((optional, string) The API Secret provided by Factual (AKA the OAuth Consumer Secret).)
*/
this.set_APISecret = function(value) {
this.setInput("APISecret", value);
}
/*
Set the value of the Query input for this Choreo. ((required, string) A search string (i.e. Starbucks))
*/
this.set_Query = function(value) {
this.setInput("Query", value);
}
}
/*
A ResultSet with methods tailored to the values returned by the FindRestaurantsByName Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/
var FindRestaurantsByNameResultSet = function(resultStream) {
FindRestaurantsByNameResultSet.super_.call(this, resultStream);
/*
Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Factual.)
*/
this.get_Response = function() {
return this.getResult("Response");
}
}
util.inherits(FindRestaurantsByName, choreography.Choreography);
util.inherits(FindRestaurantsByNameInputSet, choreography.InputSet);
util.inherits(FindRestaurantsByNameResultSet, choreography.ResultSet);
exports.FindRestaurantsByName = FindRestaurantsByName;
/******************************************************************************
Begin output wrapper classes
******************************************************************************/
/**
* Utility function, to retrieve the array-type sub-item specified by the key from the parent (array) specified by the item.
* Returns an empty array if key is not present.
*/
function getSubArrayByKey(item, key) {
var val = item[key];
if(val == null) {
val = new Array();
}
return val;
}
|
const module = angular.module("maTools");
module.directive("settingOption", () => {
return {
restrict: "A",
replace: true,
templateUrl: "templates/settingOption.html",
link: (scope, elements) => {
const element = $(elements[0]);
const inputElement = element.find("input");
const setting = scope.setting;
for(const key in setting.meta) {
inputElement.attr(key, setting.meta[key])
}
if (setting.type != "range") {
element.find(".value-preview").hide();
}
}
};
}); |
const fs = require('fs');
module.exports = function getJsPaths (target) {
return new Promise((resolve, reject) => {
fs.readdir(target, function (err, files) {
files = files.filter(f => f[0] !== '.'); // ignore system files
if (err) {
reject(err);
}
const list = [];
for (let file of files) {
if (file.search('.js') === -1) {
list.push(getJsPaths(`${target}/${file}`));
} else {
list.push(`${target}/${file}`);
}
}
Promise.all(list)
.then(function (result) {
resolve([].concat.apply([], result));
});
});
});
};
|
//= require datatables/jquery.dataTables
//optional add '=' enable
// require datatables/extensions/AutoFill/dataTables.autoFill
// require datatables/extensions/Buttons/dataTables.buttons
// require datatables/extensions/Buttons/buttons.html5
// require datatables/extensions/Buttons/buttons.print
// require datatables/extensions/Buttons/buttons.colVis
// require datatables/extensions/Buttons/buttons.flash
// require datatables/extensions/ColReorder/dataTables.colReorder
// require datatables/extensions/FixedColumns/dataTables.fixedColumns
// require datatables/extensions/FixedHeader/dataTables.fixedHeader
// require datatables/extensions/KeyTable/dataTables.keyTable
//= require datatables/extensions/Responsive/dataTables.responsive
//= require datatables/extensions/RowReorder/dataTables.rowReorder
//= require datatables/extensions/Scroller/dataTables.scroller
//= require datatables/extensions/Select/dataTables.select
//= require datatables/dataTables.bootstrap
//= require datatables/extensions/AutoFill/autoFill.bootstrap
//= require datatables/extensions/Buttons/buttons.bootstrap
//= require datatables/extensions/Responsive/responsive.bootstrap
|
var Openid = require('openid')
var shortid = require('shortid')
var uuid = require('node-uuid')
var request = require('request-promise')
var Promise = require('bluebird')
var lodash = require('lodash')
var LRU = require('lru-cache')
var querystring = require('querystring')
//pulled from https://github.com/cpancake/steam-login
function getUserInfo(steamIDURL,apiKey)
{
var steamID = steamIDURL.replace('http://steamcommunity.com/openid/id/', '');
// our url is http://steamcommunity.com/openid/id/<steamid>
return request('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key='+apiKey+'&steamids=' + steamID)
.then(function(res) {
var players = JSON.parse(res).response.players;
if(players.length == 0) throw new Error('No players found for the given steam ID.');
var player = players[0];
return Promise.resolve({
steamid: steamID,
username: player.personaname,
name: player.realname,
profile: player.profileurl,
avatar: {
small: player.avatar,
medium: player.avatarmedium,
large: player.avatarfull
}
})
});
}
function updateUserSteam(cache,token,steamData){
userData = cache.get(token)
userData = userData || {}
userData.steam = steamData
cache.set(token,userData)
return userData
}
//hacky state managment because steam openid does not support associations
//the openid relying party should only be generated once on program start
//and reused for each auth. Here we create a new one each with different endpoint.
function statefulAuthenticate(url,verify,host,cache,state){
var id = uuid.v4()
verify = verify + '/' + id
var openid = new Openid.RelyingParty(verify,host,true,true,[])
state.verify = Promise.promisify(openid.verifyAssertion,{context:openid})
cache.set(id,state)
return Promise.fromCallback(function(cb){
return openid.authenticate(url,false,cb)
})
}
function statefulVerify(cache,id,req){
var state = cache.get(id)
if(state == null) return Promise.reject(new Error('steam association not found'))
return state.verify(req).then(function(result){
cache.del(id)
result.state = state
return result
})
}
module.exports = function(app,env,cache){
if(env.HOSTNAME == null || env.PORT == null){
throw 'must supply HOSTNAME and PORT in .env file'
}
if(env.STEAM_API_KEY == null){
throw 'must supply steam api key in STEAM_API_KEY in .env file'
}
var cacheOptions = {
maxAge: 1000 * 60 * 60
}
var authCache = LRU(cacheOptions)
var steamURL = 'http://steamcommunity.com/openid'
var host = [env.HOSTNAME,':',env.PORT].join('')
var verify = [host,'steam','verify'].join('/')
app.get('/steam/verify/:id?',function(req,res,next){
var state = null
statefulVerify(authCache,req.params.id,req).then(function(result){
if(!result || !result.authenticated) throw new Error('Steam user did not log in successfully')
state = result.state
return getUserInfo(result.claimedIdentifier,env.STEAM_API_KEY)
}).then(function(steamData){
return updateUserSteam(cache,state.token,steamData)
}).then(function(result){
return res.redirect(state.onsuccess)
}).catch(function(err){
var error = querystring.stringify({
error:err.message
})
console.log(error)
if(state && state.onfailure){
return res.redirect(state.onfailure + '?' + error)
}else{
return res.status(500).json(err)
}
}).finally(function(){
authCache.del(req.params.id)
})
})
app.get('/steam/auth/:token',function(req,res,next){
req.query.onsuccess = req.query.onsuccess || host
var token = cache.get(req.params.token)
if(token == null) return res.status(404).send('client token not found')
var state = {
token:token.id,
onsuccess:req.query.onsuccess || host,
onfailure:req.query.onfailure || req.query.onsuccess
}
//hack to add stateful data to steam response
statefulAuthenticate(steamURL,verify,host,authCache,state).then(function(authURL){
if(authURL == null) throw new Error('Steam Authentication Error: No auth url returned')
res.redirect(authURL)
}).catch(function(err){
if(err) return res.status(500).send(err.message)
})
})
}
|
/*
///// FOR STATEMENT/////
var names = ["George", "Margaret", "Sean"];
for (var x = 1; x <= 10; x++) {
console.log(x);
}
To print the names in the array:
for (var y = 0; y < names.length; y++) {
console.log(names[y]);
}
We started from 0 and we are going up until names the length, in this case three (George, Margaret, Sean)
So we're going to 0, 1 and 2 and incrementing y as we go along and were out putting those names to the consul
///// DO-WHILE STATEMENT/////
var names = ["George", "Margaret", "Sean"];
var x = 0;
do {
console.log(names[x]);
x++;
} while (x < names.length);
/* this is not met
do {
console.log(x)
} while (x > 0);
*/
// WHILE STATEMENT//
var names = ["George", "Margaret", "Sean"];
var x = 0;
while (x <5) {
console.log(x++);
}
/* this statement has not been executed
while (x > 0) {
console.log(x);
} */ |
/*
* Presenter.js
*
* from Original Apple example code - modfied to use XMLHttpRequest loading in rResouceLoader
*
*/
var Presenter = {
// The default Presenter
defaultPresenter: function(xml) {
if(this.loadingIndicatorVisible) {
navigationDocument.replaceDocument(xml, this.loadingIndicator);
this.loadingIndicatorVisible = false;
} else {
navigationDocument.pushDocument(xml);
}
},
// modal presenter
modalDialogPresenter: function(xml) {
navigationDocument.presentModal(xml);
},
// menu bar presenter
menuBarItemPresenter: function(xml, ele) {
var feature = ele.parentNode.getFeature("MenuBarDocument");
if (feature) {
var currentDoc = feature.getDocument(ele);
if (!currentDoc) {
feature.setDocument(xml, ele);
}
}
},
// document load event handler
load: function(event) {
console.log(event);
var self = this,
ele = event.target,
templateURL = ele.getAttribute("template"),
presentation = ele.getAttribute("presentation");
if (templateURL) {
self.showLoadingIndicator(presentation);
// modified to use our XMLHttpRequest Loader
resourceLoader.loadResource(templateURL, function(doc) {
doc.addEventListener("select", self.load.bind(self));
doc.addEventListener("highlight", self.load.bind(self));
if (self[presentation] instanceof Function) {
self[presentation].call(self, doc, ele);
} else {
self.defaultPresenter.call(self, doc);
}
});
}
},
// generate doc from TVML code
makeDocument: function(resource) {
if (!Presenter.parser) {
Presenter.parser = new DOMParser();
}
var doc = Presenter.parser.parseFromString(resource, "application/xml");
return doc;
},
// display a loading indicator
showLoadingIndicator: function(presentation) {
if (!this.loadingIndicator) {
this.loadingIndicator = this.makeDocument(this.loadingTemplate);
}
if (!this.loadingIndicatorVisible && presentation != "modalDialogPresenter" && presentation != "menuBarItemPresenter") {
navigationDocument.pushDocument(this.loadingIndicator);
this.loadingIndicatorVisible = true;
}
},
// remove loading indicator
removeLoadingIndicator: function() {
if (this.loadingIndicatorVisible) {
navigationDocument.removeDocument(this.loadingIndicator);
this.loadingIndicatorVisible = false;
}
},
/**
* @description Instead of a loading a template from the server, it can stored in a property
* or variable for convenience. This is generally employed for templates that can be reused and
* aren't going to change often, like a loadingIndicator.
*/
loadingTemplate: `<?xml version="1.0" encoding="UTF-8" ?>
<document>
<loadingTemplate>
<activityIndicator>
<text>Loading...</text>
</activityIndicator>
</loadingTemplate>
</document>`
}
|
function array_diff_ukey(n){var o={},r=arguments.length-1,t=arguments[r],e="",i=1,f={},a="",y="undefined"!=typeof window?window:global;t="string"==typeof t?y[t]:"[object Array]"===Object.prototype.toString.call(t)?y[t[0]][t[1]]:t;n:for(e in n)for(i=1;i<r;i++){f=arguments[i];for(a in f)if(0===t(a,e))continue n;o[e]=n[e]}return o} |
"use strict";
var ORIGDATA = [];
/* -------------------------
makes data request with arguments site, callback, and callbackArgs
site: url to get
callback: function to use following completion of function, takes arguments
callback(data,callbackArgs)
where callbackArgs is an array with one json object as follows [{name:value,name:value}]
callback function can use callbackArgs[0] as object
var args = callbackArgs[0];
if(args.type == reqType) {code;};
------------------------- */
function request(site, callback, callbackArgs) {
"use strict";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", site, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var data = JSON.parse(xmlhttp.responseText);
callback(data, callbackArgs);
}
};
xmlhttp.send();
}
/* -------------------------
filters array based on parameters and their arguments
parameters
[parameter1,parameter2,parameter3,...]
args
[[p1arg1,p1arg2],[p2arg1,p2arg2],[p3arg1,p3arg2],...]
args treated as OR, parameters treated as AND
------------------------- */
/*function filterArray(arr, param, args) {
// var el = arr;
// this thing needs to be able to handle the different params as && and the different args as ||
// AND filter
var andResult = [];
var workingData = arr;
for (var j = 0; j < param.length; j++) {
// OR filter
var orResult = [];
for (var i = 0; i < workingData.length; i++) {
for (var k = 0; k < args[j].length; k++) {
if (workingData[i][param[j]] == args[j][k]) {
orResult.push(workingData[i]);
}
}
}
workingData = orResult;
}
return workingData;
}*/
function filterArray(arr, param, args) {
"use strict";
var workingData = arr;
var orResult;
param.forEach(function (parameter, paramIndex) {
// console.log("Checking parameter " + parameter + " with index " + paramIndex);
orResult = [];
workingData.forEach(function (entry) {
// console.log("Checking entry " + entry.toString() + " with index " + index_2);
args[paramIndex].forEach(function (argument, indivArgIndex) {
// console.log("Checking arg " + args[paramIndex] + " with individual index " + indivArgIndex);
// console.log(entry[parameter] + ', ' + argument);
// format for wattage args is low,hi
if (parameter === "wattage") {
if (!indivArgIndex) {
if (entry[parameter] >= argument && entry[parameter] <= args[paramIndex][indivArgIndex + 1]) {
orResult.push(entry);
}
}
} else {
// for each argument in the args[paramIndex] check whether value matches the entry
// entry.parameter where parameter is the current property being checked
if (entry[parameter] === argument) {
orResult.push(entry);
}
}
});
});
workingData = orResult;
});
return orResult;
}
// filter example
// {["brand":[148,52]]}
/*function filterPsu(arr, filterSet) {
var workingData = arr;
var filteredData = [];
for (var i = 0; i < filterSet.brand.length; i++) {
for (var j = 0; j < workingData.length; j++) {
if (workingData[j].brand == filterSet.brand[i]) {
filteredData.push(workingData[j]);
}
}
}
workingData = filteredData;
for (var i = 0; i < filterSet.platformOEM.length; i++) {
for (var j = 0; j < workingData.length; j++) {
if (workingData[j].platformOEM == filterSet.platformOEM[i]) {
filteredData.push(workingData[j]);
}
}
}
workingData = filteredData;
return filteredData;
}*/
/* -------------------------
Needed functions:
brand/number conversion
efficiency conversion
pcpartpicker search
regular search
Additions to JSON + program:
modularity - probably not as it's not completely required?
------------------------- */
function storeData(data, argsArr) {
"use strict";
if (argsArr) {return;}
ORIGDATA = data;
return data;
}
function inflateTable(data, filterArgs, sortArgs, callback) {
//var finishedArray = sortArray(filterArray(data, filterArgs[0], filterArgs[1]), sortArgs[1], sortArgs[2], callback);
var finishedArray = ORIGDATA;
var table = document.getElementById("psu-content-table");
var tableOrigContent = '<tr id="header-row"><td>Brand</td><td>Series</td><td>Platform OEM</td><td>Efficiency</td><td>Wattage</td><td>Tier</td></tr><tr id="divider" style="border-top: 1px solid rgba(0,0,0,0.12);height: 1px;"><td style="padding:0;border-spacing:0" colspan="6"></td></tr>';
var tableNewContent = tableOrigContent;
ORIGDATA.forEach(function (entry, index) {
/*entry.forEach(function (psu, pIndex) {
psu.forEach(function () {
});
});*/
});
}
request("json/psu.json", storeData, []); |
'use babel';
'use strict';
import { stripIndents, oneLine } from 'common-tags';
import Command from '../command';
export default class HelpCommand extends Command {
constructor(bot) {
super(bot, {
name: 'help',
module: 'info',
memberName: 'help',
aliases: ['commands'],
description: 'Displays a list of available commands, or detailed information for a specified command.',
usage: 'help [command]',
details: 'The command may be part of a command name or a whole command name. If it isn\'t specified, all available commands will be listed.',
examples: ['help', 'help roll']
});
}
async run(message, args) {
const util = this.bot.util;
const modules = this.bot.registry.modules;
const commands = this.bot.registry.findCommands(args[0], message);
const showAll = args[0] && args[0].toLowerCase() === 'all';
if(args[0] && !showAll) {
if(commands.length === 1) {
let help = stripIndents`
__Command **${commands[0].name}**:__ ${commands[0].description}${commands[0].guildOnly ? ' (Usable only in servers)' : ''}
**Usage:** ${util.usage(commands[0].usage, message.guild)}
`;
if(commands[0].aliases.length > 0) help += `\n**Aliases:** ${commands[0].aliases.join(', ')}`;
help += `\n**Module:** ${this.bot.registry.findModules(commands[0].module)[0].name} (\`${commands[0].module}:${commands[0].memberName}\`)`;
if(commands[0].details) help += `\n**Details:** ${commands[0].details}`;
if(commands[0].examples) help += `\n**Examples:**\n${commands[0].examples.join('\n')}`;
return { direct: help, reply: 'Sent a DM to you with information.' };
} else if(commands.length > 1) {
return util.disambiguation(commands, 'commands');
} else {
return `Unable to identify command. Use ${util.usage('help', message.guild)} to view the list of all commands.`;
}
} else {
return {
direct: util.split(stripIndents`
${oneLine`
To run a command in ${message.guild || 'any server'},
use ${util.usage('command', message.guild, !message.guild)}.
For example, ${util.usage('prefix', message.guild, !message.guild)}.
`}
To run a command in this DM, simply use ${util.usage('command')} with no prefix. For example, ${util.usage('roll d20')}.
Hyphens (\`-\`) are always optional in commands.
Use ${util.usage('help <command>')} to view detailed information about a specific command.
Use ${util.usage('help all')} to view a list of *all* commands, not just available ones.
__**${showAll ? 'All commands' : `Available commands in ${message.guild || 'this DM'}`}**__
${(showAll ? modules : modules.filter(mod => mod.commands.some(cmd => cmd.isUsable(message)))).map(mod => stripIndents`
__${mod.name}__
${(showAll ? mod.commands : mod.commands.filter(cmd => cmd.isUsable(message)))
.map(cmd => `**${cmd.name}:** ${cmd.description}`).join('\n')
}
`).join('\n\n')}
`),
reply: 'Sent a DM to you with information.'
};
}
}
}
|
const GA_ACCOUNT = ""; //Google anylics account number, "XY-01234567-1" for example
const G_AD_CLIENT = ""; //Google addsense "google_ad_client" thing
const G_AD_SLOT = ""; //Google addsense "google_ad_slot" thing
const G_SITE_VERIFY = ""; //Google site verification thing
const TWITTER = true; //Do you want to use twitter?
const RANKING = false; //Use the ranking system?
const QUEST_URL = "http://badge.wolfthatissavage.com/quests.json"; //The quests JSON, feel free to use mine at http://badge.wolfthatissavage.com/quests.json
const REFERRER = ""; //Who shall we use referrers for?
const SCRIPT_ACCESS = true; //Allow the "run javascript" thing?
const HELLO = "Hello person! This is a tool to view and sort badges on <a href='http://www.kongregate.com'>Kongregate</a>."; //A greeting! Hooray! |
/**
* @license AngularJS v1.3.0-build.51+sha.e888dde
* (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {'use strict';
/**
* @ngdoc module
* @name ngTouch
* @description
*
* # ngTouch
*
* The `ngTouch` module provides touch events and other helpers for touch-enabled devices.
* The implementation is based on jQuery Mobile touch event handling
* ([jquerymobile.com](http://jquerymobile.com/)).
*
*
* See {@link ngTouch.$swipe `$swipe`} for usage.
*
* <div doc-module-components="ngTouch"></div>
*
*/
// define ngTouch module
/* global -ngTouch */
var ngTouch = angular.module('ngTouch', []);
/* global ngTouch: false */
/**
* @ngdoc service
* @name $swipe
*
* @description
* The `$swipe` service is a service that abstracts the messier details of hold-and-drag swipe
* behavior, to make implementing swipe-related directives more convenient.
*
* Requires the {@link ngTouch `ngTouch`} module to be installed.
*
* `$swipe` is used by the `ngSwipeLeft` and `ngSwipeRight` directives in `ngTouch`, and by
* `ngCarousel` in a separate component.
*
* # Usage
* The `$swipe` service is an object with a single method: `bind`. `bind` takes an element
* which is to be watched for swipes, and an object with four handler functions. See the
* documentation for `bind` below.
*/
ngTouch.factory('$swipe', [function() {
// The total distance in any direction before we make the call on swipe vs. scroll.
var MOVE_BUFFER_RADIUS = 10;
function getCoordinates(event) {
var touches = event.touches && event.touches.length ? event.touches : [event];
var e = (event.changedTouches && event.changedTouches[0]) ||
(event.originalEvent && event.originalEvent.changedTouches &&
event.originalEvent.changedTouches[0]) ||
touches[0].originalEvent || touches[0];
return {
x: e.clientX,
y: e.clientY
};
}
return {
/**
* @ngdoc method
* @name $swipe#bind
*
* @description
* The main method of `$swipe`. It takes an element to be watched for swipe motions, and an
* object containing event handlers.
*
* The four events are `start`, `move`, `end`, and `cancel`. `start`, `move`, and `end`
* receive as a parameter a coordinates object of the form `{ x: 150, y: 310 }`.
*
* `start` is called on either `mousedown` or `touchstart`. After this event, `$swipe` is
* watching for `touchmove` or `mousemove` events. These events are ignored until the total
* distance moved in either dimension exceeds a small threshold.
*
* Once this threshold is exceeded, either the horizontal or vertical delta is greater.
* - If the horizontal distance is greater, this is a swipe and `move` and `end` events follow.
* - If the vertical distance is greater, this is a scroll, and we let the browser take over.
* A `cancel` event is sent.
*
* `move` is called on `mousemove` and `touchmove` after the above logic has determined that
* a swipe is in progress.
*
* `end` is called when a swipe is successfully completed with a `touchend` or `mouseup`.
*
* `cancel` is called either on a `touchcancel` from the browser, or when we begin scrolling
* as described above.
*
*/
bind: function(element, eventHandlers) {
// Absolute total movement, used to control swipe vs. scroll.
var totalX, totalY;
// Coordinates of the start position.
var startCoords;
// Last event's position.
var lastPos;
// Whether a swipe is active.
var active = false;
element.on('touchstart mousedown', function(event) {
startCoords = getCoordinates(event);
active = true;
totalX = 0;
totalY = 0;
lastPos = startCoords;
eventHandlers['start'] && eventHandlers['start'](startCoords, event);
});
element.on('touchcancel', function(event) {
active = false;
eventHandlers['cancel'] && eventHandlers['cancel'](event);
});
element.on('touchmove mousemove', function(event) {
if (!active) return;
// Android will send a touchcancel if it thinks we're starting to scroll.
// So when the total distance (+ or - or both) exceeds 10px in either direction,
// we either:
// - On totalX > totalY, we send preventDefault() and treat this as a swipe.
// - On totalY > totalX, we let the browser handle it as a scroll.
if (!startCoords) return;
var coords = getCoordinates(event);
totalX += Math.abs(coords.x - lastPos.x);
totalY += Math.abs(coords.y - lastPos.y);
lastPos = coords;
if (totalX < MOVE_BUFFER_RADIUS && totalY < MOVE_BUFFER_RADIUS) {
return;
}
// One of totalX or totalY has exceeded the buffer, so decide on swipe vs. scroll.
if (totalY > totalX) {
// Allow native scrolling to take over.
active = false;
eventHandlers['cancel'] && eventHandlers['cancel'](event);
return;
} else {
// Prevent the browser from scrolling.
event.preventDefault();
eventHandlers['move'] && eventHandlers['move'](coords, event);
}
});
element.on('touchend mouseup', function(event) {
if (!active) return;
active = false;
eventHandlers['end'] && eventHandlers['end'](getCoordinates(event), event);
});
}
};
}]);
/* global ngTouch: false */
/**
* @ngdoc directive
* @name ngClick
*
* @description
* A more powerful replacement for the default ngClick designed to be used on touchscreen
* devices. Most mobile browsers wait about 300ms after a tap-and-release before sending
* the click event. This version handles them immediately, and then prevents the
* following click event from propagating.
*
* Requires the {@link ngTouch `ngTouch`} module to be installed.
*
* This directive can fall back to using an ordinary click event, and so works on desktop
* browsers as well as mobile.
*
* This directive also sets the CSS class `ng-click-active` while the element is being held
* down (by a mouse click or touch) so you can restyle the depressed element if you wish.
*
* @element ANY
* @param {expression} ngClick {@link guide/expression Expression} to evaluate
* upon tap. (Event object is available as `$event`)
*
* @example
<example>
<file name="index.html">
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
count: {{ count }}
</file>
</example>
*/
ngTouch.config(['$provide', function($provide) {
$provide.decorator('ngClickDirective', ['$delegate', function($delegate) {
// drop the default ngClick directive
$delegate.shift();
return $delegate;
}]);
}]);
ngTouch.directive('ngClick', ['$parse', '$timeout', '$rootElement',
function($parse, $timeout, $rootElement) {
var TAP_DURATION = 750; // Shorter than 750ms is a tap, longer is a taphold or drag.
var MOVE_TOLERANCE = 12; // 12px seems to work in most mobile browsers.
var PREVENT_DURATION = 2500; // 2.5 seconds maximum from preventGhostClick call to click
var CLICKBUSTER_THRESHOLD = 25; // 25 pixels in any dimension is the limit for busting clicks.
var ACTIVE_CLASS_NAME = 'ng-click-active';
var lastPreventedTime;
var touchCoordinates;
// TAP EVENTS AND GHOST CLICKS
//
// Why tap events?
// Mobile browsers detect a tap, then wait a moment (usually ~300ms) to see if you're
// double-tapping, and then fire a click event.
//
// This delay sucks and makes mobile apps feel unresponsive.
// So we detect touchstart, touchmove, touchcancel and touchend ourselves and determine when
// the user has tapped on something.
//
// What happens when the browser then generates a click event?
// The browser, of course, also detects the tap and fires a click after a delay. This results in
// tapping/clicking twice. So we do "clickbusting" to prevent it.
//
// How does it work?
// We attach global touchstart and click handlers, that run during the capture (early) phase.
// So the sequence for a tap is:
// - global touchstart: Sets an "allowable region" at the point touched.
// - element's touchstart: Starts a touch
// (- touchmove or touchcancel ends the touch, no click follows)
// - element's touchend: Determines if the tap is valid (didn't move too far away, didn't hold
// too long) and fires the user's tap handler. The touchend also calls preventGhostClick().
// - preventGhostClick() removes the allowable region the global touchstart created.
// - The browser generates a click event.
// - The global click handler catches the click, and checks whether it was in an allowable region.
// - If preventGhostClick was called, the region will have been removed, the click is busted.
// - If the region is still there, the click proceeds normally. Therefore clicks on links and
// other elements without ngTap on them work normally.
//
// This is an ugly, terrible hack!
// Yeah, tell me about it. The alternatives are using the slow click events, or making our users
// deal with the ghost clicks, so I consider this the least of evils. Fortunately Angular
// encapsulates this ugly logic away from the user.
//
// Why not just put click handlers on the element?
// We do that too, just to be sure. The problem is that the tap event might have caused the DOM
// to change, so that the click fires in the same position but something else is there now. So
// the handlers are global and care only about coordinates and not elements.
// Checks if the coordinates are close enough to be within the region.
function hit(x1, y1, x2, y2) {
return Math.abs(x1 - x2) < CLICKBUSTER_THRESHOLD && Math.abs(y1 - y2) < CLICKBUSTER_THRESHOLD;
}
// Checks a list of allowable regions against a click location.
// Returns true if the click should be allowed.
// Splices out the allowable region from the list after it has been used.
function checkAllowableRegions(touchCoordinates, x, y) {
for (var i = 0; i < touchCoordinates.length; i += 2) {
if (hit(touchCoordinates[i], touchCoordinates[i+1], x, y)) {
touchCoordinates.splice(i, i + 2);
return true; // allowable region
}
}
return false; // No allowable region; bust it.
}
// Global click handler that prevents the click if it's in a bustable zone and preventGhostClick
// was called recently.
function onClick(event) {
if (Date.now() - lastPreventedTime > PREVENT_DURATION) {
return; // Too old.
}
var touches = event.touches && event.touches.length ? event.touches : [event];
var x = touches[0].clientX;
var y = touches[0].clientY;
// Work around desktop Webkit quirk where clicking a label will fire two clicks (on the label
// and on the input element). Depending on the exact browser, this second click we don't want
// to bust has either (0,0) or negative coordinates.
if (x < 1 && y < 1) {
return; // offscreen
}
// Look for an allowable region containing this click.
// If we find one, that means it was created by touchstart and not removed by
// preventGhostClick, so we don't bust it.
if (checkAllowableRegions(touchCoordinates, x, y)) {
return;
}
// If we didn't find an allowable region, bust the click.
event.stopPropagation();
event.preventDefault();
// Blur focused form elements
event.target && event.target.blur();
}
// Global touchstart handler that creates an allowable region for a click event.
// This allowable region can be removed by preventGhostClick if we want to bust it.
function onTouchStart(event) {
var touches = event.touches && event.touches.length ? event.touches : [event];
var x = touches[0].clientX;
var y = touches[0].clientY;
touchCoordinates.push(x, y);
$timeout(function() {
// Remove the allowable region.
for (var i = 0; i < touchCoordinates.length; i += 2) {
if (touchCoordinates[i] == x && touchCoordinates[i+1] == y) {
touchCoordinates.splice(i, i + 2);
return;
}
}
}, PREVENT_DURATION, false);
}
// On the first call, attaches some event handlers. Then whenever it gets called, it creates a
// zone around the touchstart where clicks will get busted.
function preventGhostClick(x, y) {
if (!touchCoordinates) {
$rootElement[0].addEventListener('click', onClick, true);
$rootElement[0].addEventListener('touchstart', onTouchStart, true);
touchCoordinates = [];
}
lastPreventedTime = Date.now();
checkAllowableRegions(touchCoordinates, x, y);
}
// Actual linking function.
return function(scope, element, attr) {
var clickHandler = $parse(attr.ngClick),
tapping = false,
tapElement, // Used to blur the element after a tap.
startTime, // Used to check if the tap was held too long.
touchStartX,
touchStartY;
function resetState() {
tapping = false;
element.removeClass(ACTIVE_CLASS_NAME);
}
element.on('touchstart', function(event) {
tapping = true;
tapElement = event.target ? event.target : event.srcElement; // IE uses srcElement.
// Hack for Safari, which can target text nodes instead of containers.
if(tapElement.nodeType == 3) {
tapElement = tapElement.parentNode;
}
element.addClass(ACTIVE_CLASS_NAME);
startTime = Date.now();
var touches = event.touches && event.touches.length ? event.touches : [event];
var e = touches[0].originalEvent || touches[0];
touchStartX = e.clientX;
touchStartY = e.clientY;
});
element.on('touchmove', function(event) {
resetState();
});
element.on('touchcancel', function(event) {
resetState();
});
element.on('touchend', function(event) {
var diff = Date.now() - startTime;
var touches = (event.changedTouches && event.changedTouches.length) ? event.changedTouches :
((event.touches && event.touches.length) ? event.touches : [event]);
var e = touches[0].originalEvent || touches[0];
var x = e.clientX;
var y = e.clientY;
var dist = Math.sqrt( Math.pow(x - touchStartX, 2) + Math.pow(y - touchStartY, 2) );
if (tapping && diff < TAP_DURATION && dist < MOVE_TOLERANCE) {
// Call preventGhostClick so the clickbuster will catch the corresponding click.
preventGhostClick(x, y);
// Blur the focused element (the button, probably) before firing the callback.
// This doesn't work perfectly on Android Chrome, but seems to work elsewhere.
// I couldn't get anything to work reliably on Android Chrome.
if (tapElement) {
tapElement.blur();
}
if (!angular.isDefined(attr.disabled) || attr.disabled === false) {
element.triggerHandler('click', [event]);
}
}
resetState();
});
// Hack for iOS Safari's benefit. It goes searching for onclick handlers and is liable to click
// something else nearby.
element.onclick = function(event) { };
// Actual click handler.
// There are three different kinds of clicks, only two of which reach this point.
// - On desktop browsers without touch events, their clicks will always come here.
// - On mobile browsers, the simulated "fast" click will call this.
// - But the browser's follow-up slow click will be "busted" before it reaches this handler.
// Therefore it's safe to use this directive on both mobile and desktop.
element.on('click', function(event, touchend) {
scope.$apply(function() {
clickHandler(scope, {$event: (touchend || event)});
});
});
element.on('mousedown', function(event) {
element.addClass(ACTIVE_CLASS_NAME);
});
element.on('mousemove mouseup', function(event) {
element.removeClass(ACTIVE_CLASS_NAME);
});
};
}]);
/* global ngTouch: false */
/**
* @ngdoc directive
* @name ngSwipeLeft
*
* @description
* Specify custom behavior when an element is swiped to the left on a touchscreen device.
* A leftward swipe is a quick, right-to-left slide of the finger.
* Though ngSwipeLeft is designed for touch-based devices, it will work with a mouse click and drag
* too.
*
* Requires the {@link ngTouch `ngTouch`} module to be installed.
*
* @element ANY
* @param {expression} ngSwipeLeft {@link guide/expression Expression} to evaluate
* upon left swipe. (Event object is available as `$event`)
*
* @example
<example>
<file name="index.html">
<div ng-show="!showActions" ng-swipe-left="showActions = true">
Some list content, like an email in the inbox
</div>
<div ng-show="showActions" ng-swipe-right="showActions = false">
<button ng-click="reply()">Reply</button>
<button ng-click="delete()">Delete</button>
</div>
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngSwipeRight
*
* @description
* Specify custom behavior when an element is swiped to the right on a touchscreen device.
* A rightward swipe is a quick, left-to-right slide of the finger.
* Though ngSwipeRight is designed for touch-based devices, it will work with a mouse click and drag
* too.
*
* Requires the {@link ngTouch `ngTouch`} module to be installed.
*
* @element ANY
* @param {expression} ngSwipeRight {@link guide/expression Expression} to evaluate
* upon right swipe. (Event object is available as `$event`)
*
* @example
<example>
<file name="index.html">
<div ng-show="!showActions" ng-swipe-left="showActions = true">
Some list content, like an email in the inbox
</div>
<div ng-show="showActions" ng-swipe-right="showActions = false">
<button ng-click="reply()">Reply</button>
<button ng-click="delete()">Delete</button>
</div>
</file>
</example>
*/
function makeSwipeDirective(directiveName, direction, eventName) {
ngTouch.directive(directiveName, ['$parse', '$swipe', function($parse, $swipe) {
// The maximum vertical delta for a swipe should be less than 75px.
var MAX_VERTICAL_DISTANCE = 75;
// Vertical distance should not be more than a fraction of the horizontal distance.
var MAX_VERTICAL_RATIO = 0.3;
// At least a 30px lateral motion is necessary for a swipe.
var MIN_HORIZONTAL_DISTANCE = 30;
return function(scope, element, attr) {
var swipeHandler = $parse(attr[directiveName]);
var startCoords, valid;
function validSwipe(coords) {
// Check that it's within the coordinates.
// Absolute vertical distance must be within tolerances.
// Horizontal distance, we take the current X - the starting X.
// This is negative for leftward swipes and positive for rightward swipes.
// After multiplying by the direction (-1 for left, +1 for right), legal swipes
// (ie. same direction as the directive wants) will have a positive delta and
// illegal ones a negative delta.
// Therefore this delta must be positive, and larger than the minimum.
if (!startCoords) return false;
var deltaY = Math.abs(coords.y - startCoords.y);
var deltaX = (coords.x - startCoords.x) * direction;
return valid && // Short circuit for already-invalidated swipes.
deltaY < MAX_VERTICAL_DISTANCE &&
deltaX > 0 &&
deltaX > MIN_HORIZONTAL_DISTANCE &&
deltaY / deltaX < MAX_VERTICAL_RATIO;
}
$swipe.bind(element, {
'start': function(coords, event) {
startCoords = coords;
valid = true;
},
'cancel': function(event) {
valid = false;
},
'end': function(coords, event) {
if (validSwipe(coords)) {
scope.$apply(function() {
element.triggerHandler(eventName);
swipeHandler(scope, {$event: event});
});
}
}
});
};
}]);
}
// Left is negative X-coordinate, right is positive.
makeSwipeDirective('ngSwipeLeft', -1, 'swipeleft');
makeSwipeDirective('ngSwipeRight', 1, 'swiperight');
})(window, window.angular);
|
chai = require("chai");
chai.should();
var config = require("cson").load("./test/fixtures/config.cson");
var request = require("request");
var TutorServer = require("@tutor/server");
var memDB = require("@tutor/memory-database")();
var restoreDB = function(){
memDB.Restore("./test/fixtures/db.json");
};
var restAPI = require("../src/rest")(memDB);
config.modules = [function(app,config){
app.use(function(req,res,next){ req.session = {uid:"tutor"}; next() });
}];
config.log = {error:function(){},log:function(){}};
var server = TutorServer(config);
// register rest API
restAPI.forEach(function(rest){
server.createRestCall(rest);
});
server.start()
var doSimpleRequest = function(method, path, data, fn){
request({
url: "http://"+config.domainname+":"+config.developmentPort+"/api"+path,
method: method, //Specify the method
form: data,
headers: { //We can define headers too
'Content-Type': 'MyContentType',
'Custom-Header': 'Custom Value'
}
}, fn);
}
var doRequest = function(method,path,data,fn){
if(typeof(data) == "function"){
fn = data;
data = null;
}
doSimpleRequest(method,path,data,function(err,res,body){
var parsed = null;
try{
parsed = JSON.parse(body);
fn(err,res,parsed);
} catch(e){
console.log("Error parsing body\n"+body);
console.log(e);
fn(e);
}
});
}
beforeEach(function(){
restoreDB();
})
describe("Student REST API", function(){
it("should return all exercises",function(done){
doRequest("GET","/exercises",
function(err, res, body){
(err == null).should.be.true;
body.should.have.length(2);
res.statusCode.should.equal(200);
done();
});
});
it("a single exercise should contain tasks", function(done){
doRequest("GET", "/exercises/ee256059-9d92-4774-9db2-456378e04586",
function(err, res, body){
(err == null).should.be.true;
body.tasks.forEach(function(t){
(typeof(t)).should.equal("object");
});
res.statusCode.should.equal(200);
done();
});
});
it("should return the number of pending solutions", function(done){
doRequest("GET", "/correction/pending/ee256059-9d92-4774-9db2-456378e04586",
function(err, res, body){
(err == null).should.be.true;
body.should.equal(2);
done();
});
});
it("has a method for storing the result without finalizing", function(done){
doSimpleRequest("PUT", "/correction/store", {id: "85ca34c0-61d6-11e5-97cb-685b35b5d746", results:[]},
function(err, res, body){
(err == null).should.be.true;
res.statusCode.should.equal(204);
done();
});
});
it("should return the status of all corrections", function(done){
doRequest("GET", "/correction",
function(err, res, body){
(err == null).should.be.true;
res.statusCode.should.equal(200);
body.should.have.length(2);
body.should.deep.include.members([
{ exercise: 'ee256059-9d92-4774-9db2-456378e04586', solutions: 2, corrected: 0, locked: 1 },
{ exercise: 'f31ad341-9d92-4774-9db2-456378e04586', solutions: 0, corrected: 0, locked: 0 }
]);
done();
})
});
it("should (on demand) assign a new solution to the tutor", function(done){
doRequest("GET", "/correction/next/ee256059-9d92-4774-9db2-456378e04586",
function(err, res, body){
(err == null).should.be.true;
res.statusCode.should.equal(200);
body.group.should.equal("fd8c6b08-572d-11e5-9824-685b35b5d746");
done();
}
)
});
it("should list all unfinished corrections", function(done){
doRequest("GET", "/correction/unfinished",
function(err, res, body){
(err == null).should.be.true;
res.statusCode.should.equal(200);
body.should.have.length(1);
done();
});
});
it("should finalize exercises for a tutor", function(done){
doSimpleRequest("POST", "/correction/finish", {id: "85ca34c0-61d6-11e5-97cb-685b35b5d746"},
function(err, res, body){
(err == null).should.be.true;
res.statusCode.should.equal(204);
done();
});
});
it("should be possible to get user information", function(done){
doRequest("GET", "/tutor",
function(err, res, body){
(err == null).should.be.true;
res.statusCode.should.equal(200);
body.name.should.equal("tutor");
body.should.not.have.key("pw");
done();
});
});
});
|
/**
* Module dependencies.
*/
var express = require('../..');
var bodyParser = require('body-parser');
var format = require('util').format;
var app = module.exports = express();
app.use(bodyParser());
app.get('/', function(req, res){
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Title: <input type="text" name="title" /></p>'
+ '<p>Image: <input type="file" name="image" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.post('/', function(req, res, next){
// the uploaded file can be found as `req.files.image` and the
// title field as `req.body.title`
res.send(format('\nuploaded %s (%d Kb) to %s as %s'
, req.files.image.name
, req.files.image.size / 1024 | 0
, req.files.image.path
, req.body.title));
});
if (!module.parent) {
app.listen(3000);
console.log('Express started on port 3000');
}
|
import PropTypes from 'prop-types';
import createConnector from '../core/createConnector';
import { find } from '../core/utils';
import {
cleanUpValue,
refineValue,
getCurrentRefinementValue,
getResults,
getIndexId,
} from '../core/indexUtils';
function stringifyItem(item) {
if (typeof item.start === 'undefined' && typeof item.end === 'undefined') {
return '';
}
const start = typeof item.start !== 'undefined' ? item.start : '';
const end = typeof item.end !== 'undefined' ? item.end : '';
return `${start}:${end}`;
}
function parseItem(value) {
if (value.length === 0) {
return { start: null, end: null };
}
const [startStr, endStr] = value.split(':');
return {
start: startStr.length > 0 ? parseFloat(startStr) : null,
end: endStr.length > 0 ? parseFloat(endStr) : null,
};
}
const namespace = 'multiRange';
function getId(props) {
return props.attribute;
}
function getCurrentRefinement(props, searchState, context) {
return getCurrentRefinementValue(
props,
searchState,
context,
`${namespace}.${getId(props)}`,
'',
(currentRefinement) => {
if (currentRefinement === '') {
return '';
}
return currentRefinement;
}
);
}
function isRefinementsRangeIncludesInsideItemRange(stats, start, end) {
return (
(stats.min > start && stats.min < end) ||
(stats.max > start && stats.max < end)
);
}
function isItemRangeIncludedInsideRefinementsRange(stats, start, end) {
return (
(start > stats.min && start < stats.max) ||
(end > stats.min && end < stats.max)
);
}
function itemHasRefinement(attribute, results, value) {
const stats = results.getFacetByName(attribute)
? results.getFacetStats(attribute)
: null;
const range = value.split(':');
const start =
Number(range[0]) === 0 || value === ''
? Number.NEGATIVE_INFINITY
: Number(range[0]);
const end =
Number(range[1]) === 0 || value === ''
? Number.POSITIVE_INFINITY
: Number(range[1]);
return !(
Boolean(stats) &&
(isRefinementsRangeIncludesInsideItemRange(stats, start, end) ||
isItemRangeIncludedInsideRefinementsRange(stats, start, end))
);
}
function refine(props, searchState, nextRefinement, context) {
const nextValue = { [getId(props, searchState)]: nextRefinement };
const resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace);
}
function cleanUp(props, searchState, context) {
return cleanUpValue(searchState, context, `${namespace}.${getId(props)}`);
}
/**
* connectNumericMenu connector provides the logic to build a widget that will
* give the user the ability to select a range value for a numeric attribute.
* Ranges are defined statically.
* @name connectNumericMenu
* @requirements The attribute passed to the `attribute` prop must be holding numerical values.
* @kind connector
* @propType {string} attribute - the name of the attribute in the records
* @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds.
* @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string.
* @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the NumericMenu can display.
*/
export default createConnector({
displayName: 'AlgoliaNumericMenu',
propTypes: {
id: PropTypes.string,
attribute: PropTypes.string.isRequired,
items: PropTypes.arrayOf(
PropTypes.shape({
label: PropTypes.node,
start: PropTypes.number,
end: PropTypes.number,
})
).isRequired,
transformItems: PropTypes.func,
},
getProvidedProps(props, searchState, searchResults) {
const attribute = props.attribute;
const currentRefinement = getCurrentRefinement(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue,
});
const results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue,
});
const items = props.items.map((item) => {
const value = stringifyItem(item);
return {
label: item.label,
value,
isRefined: value === currentRefinement,
noRefinement: results
? itemHasRefinement(getId(props), results, value)
: false,
};
});
const stats =
results && results.getFacetByName(attribute)
? results.getFacetStats(attribute)
: null;
const refinedItem = find(items, (item) => item.isRefined === true);
if (!items.some((item) => item.value === '')) {
items.push({
value: '',
isRefined: refinedItem === undefined,
noRefinement: !stats,
label: 'All',
});
}
const transformedItems = props.transformItems
? props.transformItems(items)
: items;
return {
items: transformedItems,
currentRefinement,
canRefine:
transformedItems.length > 0 &&
transformedItems.some((item) => item.noRefinement === false),
};
},
refine(props, searchState, nextRefinement) {
return refine(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue,
});
},
cleanUp(props, searchState) {
return cleanUp(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue,
});
},
getSearchParameters(searchParameters, props, searchState) {
const { attribute } = props;
const { start, end } = parseItem(
getCurrentRefinement(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue,
})
);
searchParameters = searchParameters.addDisjunctiveFacet(attribute);
if (typeof start === 'number') {
searchParameters = searchParameters.addNumericRefinement(
attribute,
'>=',
start
);
}
if (typeof end === 'number') {
searchParameters = searchParameters.addNumericRefinement(
attribute,
'<=',
end
);
}
return searchParameters;
},
getMetadata(props, searchState) {
const id = getId(props);
const value = getCurrentRefinement(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue,
});
const items = [];
const index = getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue,
});
if (value !== '') {
const { label } = find(
props.items,
(item) => stringifyItem(item) === value
);
items.push({
label: `${props.attribute}: ${label}`,
attribute: props.attribute,
currentRefinement: label,
value: (nextState) =>
refine(props, nextState, '', {
ais: props.contextValue,
multiIndexContext: props.indexContextValue,
}),
});
}
return { id, index, items };
},
});
|
var assert = require('assert')
var fs = require('fs')
module.exports = function (_, dir, finish, gm) {
var original = dir + '/original.jpg';
var result = dir + '/resizeFromBuffer.png';
var buf = fs.readFileSync(original);
var m = gm(buf, 'resizefrombuffer.jpg')
.resize('48%')
var args = m.args();
assert.equal('convert', args[0]);
assert.equal('-', args[1]);
assert.equal('-resize', args[2]);
if (m._options.imageMagick) {
assert.equal('48%', args[3]);
} else {
assert.equal('48%x', args[3]);
}
if (!gm.integration)
return finish();
size(original, function (err, origSize) {
if (err) return finish(err);
m
.write(result, function resizeFromBuffer (err) {
if (err) return finish(err);
size(result, function (err, newSize) {
if (err) return finish(err);
assert.ok(origSize.width / 2 >= newSize.width);
assert.ok(origSize.height / 2 >= newSize.height);
finish();
});
});
});
function size (file, cb) {
gm(file).identify(function (err, data) {
if (err) return cb(err);
cb(err, data.size);
});
}
}
|
import { createServer } from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import { app as settings } from '../../package.json';
import log from '../log';
// Hot reloadable modules
let subscriptionManager = require('./api/subscriptions').subscriptionManager;
let server;
const port = process.env.WS_PORT || settings.wsPort;
const websocketServer = createServer((req, res) => {
res.writeHead(404);
res.end();
});
server = websocketServer.listen(port, () => log(
`WebSocket Server is now running on port ${port}`
));
server.on('close', () => {
server = null;
});
new SubscriptionServer({
subscriptionManager,
}, websocketServer);
if (module.hot) {
try {
module.hot.dispose(() => {
if (server) {
server.close();
}
});
module.hot.accept();
// Reload reloadable modules
module.hot.accept('./api/subscriptions',
() => { subscriptionManager = require('./api/subscriptions').subscriptionManager; });
} catch (err) {
log(err.stack);
}
}
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule RelayCodeGenerator
*
* @format
*/
'use strict';
var _toConsumableArray3 = _interopRequireDefault(require('babel-runtime/helpers/toConsumableArray'));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _require = require('graphql'),
GraphQLList = _require.GraphQLList;
var getRawType = require('./GraphQLSchemaUtils').getRawType,
isAbstractType = require('./GraphQLSchemaUtils').isAbstractType,
getNullableType = require('./GraphQLSchemaUtils').getNullableType;
/* eslint-disable no-redeclare */
/**
* @public
*
* Converts a Relay IR node into a plain JS object representation that can be
* used at runtime.
*/
function generate(node) {
require('fbjs/lib/invariant')(['Root', 'Fragment'].indexOf(node.kind) >= 0, 'RelayCodeGenerator: Unknown AST kind `%s`. Source: %s.', node.kind, getErrorMessage(node));
return require('./RelayIRVisitor').visit(node, RelayCodeGenVisitor);
}
/* eslint-enable no-redeclare */
var RelayCodeGenVisitor = {
leave: {
Root: function Root(node) {
return {
argumentDefinitions: node.argumentDefinitions,
kind: 'Root',
name: node.name,
operation: node.operation,
selections: flattenArray(node.selections)
};
},
Fragment: function Fragment(node) {
return {
argumentDefinitions: node.argumentDefinitions,
kind: 'Fragment',
metadata: node.metadata || null,
name: node.name,
selections: flattenArray(node.selections),
type: node.type.toString()
};
},
LocalArgumentDefinition: function LocalArgumentDefinition(node) {
return {
kind: 'LocalArgument',
name: node.name,
type: node.type.toString(),
defaultValue: node.defaultValue
};
},
RootArgumentDefinition: function RootArgumentDefinition(node) {
return {
kind: 'RootArgument',
name: node.name,
type: node.type ? node.type.toString() : null
};
},
Condition: function Condition(node, key, parent, ancestors) {
require('fbjs/lib/invariant')(node.condition.kind === 'Variable', 'RelayCodeGenerator: Expected static `Condition` node to be ' + 'pruned or inlined. Source: %s.', getErrorMessage(ancestors[0]));
return {
kind: 'Condition',
passingValue: node.passingValue,
condition: node.condition.variableName,
selections: flattenArray(node.selections)
};
},
FragmentSpread: function FragmentSpread(node) {
return {
kind: 'FragmentSpread',
name: node.name,
args: valuesOrNull(sortByName(node.args))
};
},
InlineFragment: function InlineFragment(node) {
return {
kind: 'InlineFragment',
type: node.typeCondition.toString(),
selections: flattenArray(node.selections)
};
},
LinkedField: function LinkedField(node) {
var handles = node.handles && node.handles.map(function (handle) {
return {
kind: 'LinkedHandle',
alias: node.alias,
args: valuesOrNull(sortByName(node.args)),
handle: handle.name,
name: node.name,
key: handle.key,
filters: handle.filters
};
}) || [];
var type = getRawType(node.type);
return [{
kind: 'LinkedField',
alias: node.alias,
args: valuesOrNull(sortByName(node.args)),
concreteType: !isAbstractType(type) ? type.toString() : null,
name: node.name,
plural: isPlural(node.type),
selections: flattenArray(node.selections),
storageKey: getStorageKey(node.name, node.args)
}].concat((0, _toConsumableArray3['default'])(handles));
},
ScalarField: function ScalarField(node) {
var handles = node.handles && node.handles.map(function (handle) {
return {
kind: 'ScalarHandle',
alias: node.alias,
args: valuesOrNull(sortByName(node.args)),
handle: handle.name,
name: node.name,
key: handle.key,
filters: handle.filters
};
}) || [];
return [{
kind: 'ScalarField',
alias: node.alias,
args: valuesOrNull(sortByName(node.args)),
name: node.name,
selections: valuesOrUndefined(flattenArray(node.selections)),
storageKey: getStorageKey(node.name, node.args)
}].concat((0, _toConsumableArray3['default'])(handles));
},
Variable: function Variable(node, key, parent) {
return {
kind: 'Variable',
name: parent.name,
variableName: node.variableName,
type: parent.type ? parent.type.toString() : null
};
},
Literal: function Literal(node, key, parent) {
return {
kind: 'Literal',
name: parent.name,
value: node.value,
type: parent.type ? parent.type.toString() : null
};
},
Argument: function Argument(node, key, parent, ancestors) {
require('fbjs/lib/invariant')(['Variable', 'Literal'].indexOf(node.value.kind) >= 0, 'RelayCodeGenerator: Complex argument values (Lists or ' + 'InputObjects with nested variables) are not supported, argument ' + '`%s` had value `%s`. Source: %s.', node.name, require('./prettyStringify')(node.value), getErrorMessage(ancestors[0]));
return node.value.value !== null ? node.value : null;
}
}
};
function isPlural(type) {
return getNullableType(type) instanceof GraphQLList;
}
function valuesOrUndefined(array) {
return !array || array.length === 0 ? undefined : array;
}
function valuesOrNull(array) {
return !array || array.length === 0 ? null : array;
}
function flattenArray(array) {
return array ? Array.prototype.concat.apply([], array) : [];
}
function sortByName(array) {
return array instanceof Array ? array.sort(function (a, b) {
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
}) : array;
}
function getErrorMessage(node) {
return 'document ' + node.name;
}
/**
* Computes storage key if possible.
*
* Storage keys which can be known ahead of runtime are:
*
* - Fields that do not take arguments.
* - Fields whose arguments are all statically known (ie. literals) at build
* time.
*/
function getStorageKey(fieldName, args) {
if (!args || !args.length) {
return null;
}
var isLiteral = true;
var preparedArgs = {};
args.forEach(function (arg) {
if (arg.kind !== 'Literal') {
isLiteral = false;
} else {
preparedArgs[arg.name] = arg.value;
}
});
return isLiteral ? require('./formatStorageKey')(fieldName, preparedArgs) : null;
}
module.exports = { generate: generate }; |
angular.module('brandid.states.demo', ['ParseServices','anal.controllers.list'])
.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('list',{
url: '/',
views: {
'@': { templateUrl: 'app/views/app-layout.html' },
'panel@list': {
templateUrl: 'app/views/list.html',
controller: 'ListController',
resolve: {
nikki: function() {
var nikkis = new (Parse.Collection.getClass("Nikki"));
return nikkis.list();
}
}
}
}
})
.state('demo', {
abstract: false,
url: '/{nikkiId}',
views: {
'@': {
templateUrl: 'app/views/app-layout.html',
},
'panel@demo': {
templateUrl: 'app/views/nikki.html',
controller: 'MasterDetailController',
resolve: {
nikki: ['$stateParams', function($stateParams) {
var nikkiId = $stateParams.nikkiId;
var nikkis = new (Parse.Collection.getClass("Nikki"));
if (nikkiId) { return nikkis.findById(nikkiId) };
return nikkis.first();
}],
next: ['$stateParams', function($stateParams) {
var nikkiId = $stateParams.nikkiId;
var nikkis = new (Parse.Collection.getClass("Nikki"));
return nikkis.nextVideo(nikkiId);
}],
prev: ['$stateParams', function($stateParams) {
var nikkiId = $stateParams.nikkiId;
var nikkis = new (Parse.Collection.getClass("Nikki"));
return nikkis.previousVideo(nikkiId);
}]
}
}
}
})
}])
|
'use strict';
const spawn = require('cross-spawn');
const inspectFile = require.resolve('./server2.js');
const WebSocket = require('ws');
const assert = require('assert');
const urllib = require('urllib');
const coffee = require('coffee');
const utils = require('./utils');
const version = require('../package').version;
describe('test/bin.test.js', () => {
const bin = require.resolve('../bin/bin.js');
let proc;
afterEach(() => {
proc && proc.kill();
});
it('should work correctly', done => {
proc = spawn(bin, [ `--file=${inspectFile}`, '--silent=true' ]);
proc.stdout.on('data', data => {
if (data.toString().includes('127.0.0.1:9229/__ws_proxy__')) {
done();
}
});
proc.stderr.on('data', data => {
console.log(data.toString());
});
});
it('should show help', done => {
coffee.fork(bin, [ '-h' ])
.expect('stdout', /Usage: inspector-proxy/)
.expect('stdout', /Options/)
.end(done);
});
it('should show version', done => {
coffee.fork(bin, [ '-v' ])
.expect('stdout', new RegExp(version))
.end(done);
});
it('should work correctly without appointing file', function* () {
proc = spawn(bin, [ '--proxy=9228' ]);
let serverProc;
utils.createServer(5858).then(({ process }) => {
serverProc = process;
});
let str = '';
yield new Promise(resolve => {
proc.stdout.on('data', data => {
str += data.toString();
if (data.toString().includes('127.0.0.1:9228/__ws_proxy__')) {
serverProc.kill();
resolve();
}
});
});
assert(str.includes('5858 opened'));
});
it('should appoint port by argv', done => {
proc = spawn(bin, [
'--proxy=9228',
'--debug=9888',
'--silent=true',
'./test/server2.js',
]);
proc.stderr.on('data', data => {
assert(data.includes('127.0.0.1:9888/'));
});
proc.stdout.on('data', data => {
if (data.toString().includes('127.0.0.1:9228/__ws_proxy__')) {
const ws = new WebSocket('ws://127.0.0.1:9228/__ws_proxy__');
ws.on('open', done);
ws.on('error', done);
}
});
});
it('should restart inspect process while it was killed', function* () {
proc = spawn(bin, [ '--proxy=9228', '--debug=9888', inspectFile ]);
// cfork ready
const forkReady = () => new Promise(resolve =>
proc.stdout.on('data', data => {
const content = data.toString();
if (content.includes('127.0.0.1:9228/__ws_proxy__')) {
proc.stdout.removeAllListeners('data');
setTimeout(resolve, 1000);
}
})
);
// start inspect server
yield forkReady();
// kill server
const json = yield urllib.request('http://127.0.0.1:7001/');
process.kill(json.data.toString());
// restart server
yield forkReady();
});
});
|
import {isObject, isBoolean} from './is';
export const Next = x => ({done: false, value: x});
export const Done = x => ({done: true, value: x});
export const isIteration = x => isObject(x) && isBoolean(x.done);
|
import React, { Component, PropTypes } from 'react'
import * as THREE from 'three'
import actions from './actions'
import reducer from './reducer'
import MapTile from 'component/maptile'
class Map extends Component {
static displayName = '[component] map';
static propTypes = {
tiles : PropTypes.array,
x : PropTypes.number,
y : PropTypes.number
};
static defaultProps = {
tiles : [],
x : 0,
y : 0
};
get mapTiles() {
const tiles = this.props.tiles;
const selfX = this.props.x;
const selfY = this.props.y;
console.log('tiles', tiles);
return tiles.map((row, _y) => {
return row.map((tile, _x) => {
//const x = _x - selfX;
//const y = selfY - _y;
const x = _x - selfX;
const y = selfY - _y;
const z = tile.z;
const sides = [
tiles[_y][_x - 1],
tiles[_y - 1] ? tiles[_y - 1][_x] : null,
tiles[_y + 1] ? tiles[_y + 1][_x] : null,
tiles[_y][_x + 1]
];
const corners = [
tiles[_y - 1] ? tiles[_y - 1][_x - 1] : null,
tiles[_y + 1] ? tiles[_y + 1][_x - 1] : null,
tiles[_y - 1] ? tiles[_y - 1][_x + 1] : null,
tiles[_y + 1] ? tiles[_y + 1][_x + 1] : null
];
/*
const sides = [
tiles[_x - 1] ? tiles[_x - 1][_y] : null,
tiles[_x][_y - 1],
tiles[_x][_y + 1],
tiles[_x + 1] ? tiles[_x + 1][_y] : null
]
const corners = [
tiles[_x - 1] ? tiles[_x - 1][_y - 1] : null,
tiles[_x - 1] ? tiles[_x - 1][_y + 1] : null,
tiles[_x + 1] ? tiles[_x + 1][_y - 1] : null,
tiles[_x + 1] ? tiles[_x + 1][_y + 1] : null
];*/
const props = {
position : new THREE.Vector3(x, y, z),
corners,
sides,
id: tile.id,
key : `${x}.${y}`
};
return <MapTile {...props} />
})
});
}
get mapTiles_old() {
const tiles = this.props.tiles;
const selfX = this.props.x;
const selfY = this.props.y;
console.log('tiles', tiles);
return tiles.reduce((arr, row, _x) => {
return arr.concat(
row.map((tile, _y) => {
const x = _x - selfX;
const y = selfY - _y;
const z = tile.z;
const position = new THREE.Vector3(x, y, z);
const sides = [
tiles[_x - 1] ? tiles[_x - 1][_y] : null,
tiles[_x][_y - 1],
tiles[_x][_y + 1],
tiles[_x + 1] ? tiles[_x + 1][_y] : null
]
const corners = [
tiles[_x - 1] ? tiles[_x - 1][_y - 1] : null,
tiles[_x - 1] ? tiles[_x - 1][_y + 1] : null,
tiles[_x + 1] ? tiles[_x + 1][_y - 1] : null,
tiles[_x + 1] ? tiles[_x + 1][_y + 1] : null
];
return (
<MapTile corners={corners}
sides={sides}
id={tile.id}
key={`${x}.${y}`}
position={position}
/>
);
})
);
}, []);
}
render() {
/*
TODO:
- orthogonal camera
- update camera position
- zoom level
- use range attribute? store this in redux store
- look for packet that sets range
*/
return (
<object3D>
{this.mapTiles}
</object3D>
);
}
}
export { Map as default, actions, reducer }
|
"use strict";
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
var _bunyan = require('bunyan');
var _bunyan2 = _interopRequireDefault(_bunyan);
module.exports = {
RouteHandlerLogger: _bunyan2['default'].createLogger({
name: 'CR_RouteHandler',
streams: [{
type: 'rotating-file',
period: '1d',
count: 5,
level: 'info',
path: './logs/cr-routehandler-info.log'
}, {
type: 'rotating-file',
period: '1d',
count: 5,
level: 'error',
path: './logs/cr-routehandler-error.log'
}]
}),
WebServerLogger: _bunyan2['default'].createLogger({
name: 'CR_WebServer',
streams: [{
type: 'rotating-file',
period: '1d',
count: 3,
level: 'info',
path: './logs/cr-webserver-info.log'
}, {
type: 'rotating-file',
period: '1d',
count: 3,
level: 'error',
path: './logs/cr-webserver-error.log'
}],
serializers: {
req: _bunyan2['default'].stdSerializers.req
}
}),
CallRouterLogger: _bunyan2['default'].createLogger({
name: 'CR_CallRouter',
streams: [{
type: 'rotating-file',
period: '1d',
count: 3,
level: 'info',
path: './logs/cr-callrouter-info.log'
}, {
type: 'rotating-file',
period: '1d',
count: 3,
level: 'error',
path: './logs/cr-callrouter-error.log'
}]
})
}; |
/* Project specific Javascript goes here. */
/*
Formatting hack to get around crispy-forms unfortunate hardcoding
in helpers.FormHelper:
if template_pack == 'bootstrap4':
grid_colum_matcher = re.compile('\w*col-(xs|sm|md|lg|xl)-\d+\w*')
using_grid_layout = (grid_colum_matcher.match(self.label_class) or
grid_colum_matcher.match(self.field_class))
if using_grid_layout:
items['using_grid_layout'] = True
Issues with the above approach:
1. Fragile: Assumes Bootstrap 4's API doesn't change (it does)
2. Unforgiving: Doesn't allow for any variation in template design
3. Really Unforgiving: No way to override this behavior
4. Undocumented: No mention in the documentation, or it's too hard for me to find
*/
const $ = require('jquery')
window.jQuery = $
window.$ = $
require('./app/sass/bootstrap.scss')
$('.form-group').removeClass('row');
|
var searchData=
[
['keygen_20',['KeyGen',['../classipfs_1_1Client.html#ada01369adfda81c869a7095d98197961',1,'ipfs::Client']]],
['keylist_21',['KeyList',['../classipfs_1_1Client.html#a49d9bb4e44e66170c8e32134300ccfb1',1,'ipfs::Client']]],
['keyrm_22',['KeyRm',['../classipfs_1_1Client.html#a8c8c8703f4be0e4eb5053301b3577ed8',1,'ipfs::Client']]],
['kfilecontents_23',['kFileContents',['../structipfs_1_1http_1_1FileUpload.html#a76d8546add495d01fd1dcd82ea8170adafc941c889c1d94c918bfd225c22aed65',1,'ipfs::http::FileUpload']]],
['kfilename_24',['kFileName',['../structipfs_1_1http_1_1FileUpload.html#a76d8546add495d01fd1dcd82ea8170ada5bfe73daee1615146c6c4fa093c7d9ef',1,'ipfs::http::FileUpload']]]
];
|
Router.configure({
layoutTemplate: 'main'
});
Router.route('/listing');
Router.route('/todos');
Router.route('/register');
Router.route('/login');
Router.route('/', {
name: 'home',
template: 'home'
});
Router.route('/test', {
data: function () {
console.log('shiiit');
}
});
|
import 'babel/polyfill';
import ReactDOM from 'react-dom';
import FastClick from 'fastclick';
import Dispatcher from './core/Dispatcher';
import Router from './Router';
import Location from './core/Location';
import SessionStore from './stores/SessionStore';
import { addEventListener, removeEventListener } from './utils/DOMUtils';
const container = document.getElementById('app');
const context = {
onSetTitle: value => document.title = value,
onSetMeta: (name, content) => {
// Remove and create a new <meta /> tag in order to make it work
// with bookmarks in Safari
let elements = document.getElementsByTagName('meta');
[].slice.call(elements).forEach((element) => {
if (element.getAttribute('name') === name) {
element.parentNode.removeChild(element);
}
});
let meta = document.createElement('meta');
meta.setAttribute('name', name);
meta.setAttribute('content', content);
document.getElementsByTagName('head')[0].appendChild(meta);
}
};
function cleanUp() {
let done = false;
if (!done) {
// Remove the pre-rendered CSS because it's no longer used
// after the React app is launched
const css = document.getElementById('css');
if (css) {
css.parentNode.removeChild(css);
done = true;
}
}
}
function render(state) {
Router.dispatch(state, (_, component) => {
ReactDOM.render(component, container, () => {
// Restore the scroll position if it was saved into the state
if (state.scrollY !== undefined) {
window.scrollTo(state.scrollX, state.scrollY);
} else {
window.scrollTo(0, 0);
}
cleanUp();
});
});
}
function run() {
let currentLocation = null;
let currentState = null;
// Make taps on links and buttons work fast on mobiles
FastClick.attach(document.body);
// Re-render the app when window.location changes
const unlisten = Location.listen(location => {
currentLocation = location;
currentState = Object.assign({}, location.state, {
path: location.pathname,
query: location.query,
state: location.state,
context
});
render(currentState);
});
// Save the page scroll position into the current location's state
var supportPageOffset = window.pageXOffset !== undefined;
var isCSS1Compat = ((document.compatMode || '') === 'CSS1Compat');
const setPageOffset = () => {
currentLocation.state = currentLocation.state || Object.create(null);
currentLocation.state.scrollX = supportPageOffset ? window.pageXOffset : isCSS1Compat ?
document.documentElement.scrollLeft : document.body.scrollLeft;
currentLocation.state.scrollY = supportPageOffset ? window.pageYOffset : isCSS1Compat ?
document.documentElement.scrollTop : document.body.scrollTop;
};
addEventListener(window, 'scroll', setPageOffset);
addEventListener(window, 'pagehide', () => {
removeEventListener(window, 'scroll', setPageOffset);
unlisten();
});
}
// Run the application when both DOM is ready
// and page content is loaded
if (window.addEventListener) {
window.addEventListener('DOMContentLoaded', run);
} else {
window.attachEvent('onload', run);
}
|
/**
* User: Marc Edouard Raffalli
* Date: 01/08/14
* Time: 18:20
* Website: http://marc-ed-raffalli.com/
*/
/* global define */
define([
'backbone'
], function (Backbone) {
'use strict';
return Backbone.Marionette.Region.extend({
attachHtml: function (view) {
this.hideCurrentView({
complete: function () {
this.$el.append(view.$el);
this.showCurrentView();
}.bind(this)
});
},
hideCurrentView: function (options) {
options = options || {};
this.$el.fadeOut(200, options.complete);
},
showCurrentView: function (options) {
options = options || {};
this.$el.fadeIn(500, options.complete);
}
});
});
|
angular.module('kcd.bp.web.services').factory('EntityDeletorService', function(CommonModalService, DS, AlertEventBroadcaster, ErrorDisplayService) {
'use strict';
return {
deleteResource: deleteResource
};
function deleteResource(resourceType, resourceId, resourceDisplayName) {
var onError = ErrorDisplayService.getErrorResponseHandler();
var resourceDefinition = DS.definitions[resourceType];
var displayName = resourceDefinition.meta.getDisplayName();
var promise = CommonModalService.confirm({
header: 'Are you sure you want to delete "' + resourceDisplayName + '" ' + displayName + '?',
message: 'Deleting this ' + displayName + ' cannot be undone!',
yesButton: 'Delete'
}).result;
promise.then(function(yes) {
if (yes) {
return DS.destroy(resourceType, resourceId).then(function() {
AlertEventBroadcaster.broadcast({
type: 'info',
message: displayName + ' successfully deleted'
});
}, onError);
} else {
return null;
}
});
return promise;
}
}); |
"use strict";
var forEachAction = require( "./forEachAction" );
var oneShotCallbacks = require( "./oneShotCallbacks" );
var repeatCallbacks = require( "./repeatCallbacks" );
function attach( notifiers, value, rawCallback ) {
var then;
if ( value instanceof Attempt ) {
forEachAction( notifiers, function( notifier, methodName ) {
value[ methodName ]( notifier );
} );
} else if ( value && typeof ( then = value.then ) === "function" ) {
then.call( value, notifiers[ 0 ], notifiers[ 1 ] );
} else {
rawCallback( value, notifiers );
}
}
function internal( initValue ) {
function Constructor() {}
var proto = Constructor.prototype = new Attempt( internal );
var successCallbacks = oneShotCallbacks();
var failureCallbacks = oneShotCallbacks();
var progressCallbacks = repeatCallbacks();
var abort;
forEachAction( [
successCallbacks,
failureCallbacks,
progressCallbacks
], function( handler, methodName ) {
proto[ methodName ] = handler.a;
} );
var self = new Constructor();
attach( [
function() {
abort = false;
failureCallbacks.l();
progressCallbacks.l();
successCallbacks.f.apply( null, arguments );
},
function() {
abort = false;
successCallbacks.l();
progressCallbacks.l();
failureCallbacks.f.apply( null, arguments );
},
progressCallbacks.f
], initValue, function( initFunction, notifiers ) {
var tmp = initFunction.apply( self, notifiers );
if ( tmp ) {
proto.abort = function() {
if ( !abort ) {
return false;
}
if ( typeof abort === "function" ) {
setImmediate( abort );
}
successCallbacks.l();
failureCallbacks.l();
progressCallbacks.l();
abort = false;
return true;
};
if ( abort !== false ) {
abort = tmp;
}
}
} );
return self;
}
function Attempt( initValue ) {
return initValue !== internal && internal( initValue );
}
Attempt.prototype = {
always: function( callback ) {
return this.success( callback ).failure( callback );
},
chain: function() {
var self = this;
var callbacks = arguments;
return new Attempt( function() {
var notifiers = arguments;
forEachAction( callbacks, function( callback, methodName, index ) {
self[ methodName ]( callback ? function() {
attach( notifiers, callback.apply( null, arguments ), function( value ) {
notifiers[ index ]( value );
} );
} : notifiers[ index ] );
} );
} );
},
promise: function() {
var self = this;
return new Promise( function() {
forEachAction( arguments, function( notifier, methodName ) {
if ( notifier ) {
self[ methodName ]( function( arg ) {
notifier( arguments.length > 1 ? [].slice.call( arguments ) : arg );
} );
}
} );
} );
}
};
forEachAction( function( methodName, _, index ) {
if ( index < 2 ) {
Attempt[ "create" + methodName.substr( 0, 1 ).toUpperCase() + methodName.substr( 1 ) ] = function() {
var args = arguments;
return new Attempt( function() {
arguments[ index ].apply( null, args );
} );
};
}
} );
function getValue( args ) {
return args.length > 1 ? [].slice.apply( args ) : args[ 0 ];
}
Attempt.join = function() {
var args = arguments;
var length = args.length;
return Attempt( function( success, failure, progress ) {
var count = length + 1;
var successArray = new Array( length );
var progressArray = new Array( length );
function tick() {
if ( !( --count ) ) {
success.apply( null, successArray );
}
}
function notifiersFactory( index ) {
return [
function() {
successArray[ index ] = getValue( arguments );
tick();
},
function() {
failure.apply( null, arguments );
},
function() {
progressArray[ index ] = getValue( arguments );
progress.apply( null, progressArray );
}
];
}
for ( var i = 0; i < length; i++ ) {
attach( notifiersFactory( i ), args[ i ], function( value, notifiers ) {
notifiers[ 0 ]( value );
} );
}
tick();
} );
};
Attempt.joinArray = function( array ) {
return Attempt.join.apply( null, array );
};
module.exports = Attempt;
|
module.exports = {
type: 'react-component',
npm: {
umd: false
}
}
|
'use strict'
// Template version: 1.2.4
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
// proxy all requests starting with /api
'/solr': {
target: 'http://192.168.11.2:9983',
changeOrigin: true
},
'/files': {
target: 'http://192.168.11.2:9983',
changeOrigin: true
},
'/subscriptions': {
target: 'http://192.168.11.2:9983',
changeOrigin: true
},
'/errors': {
target: 'http://192.168.11.2:9983',
changeOrigin: true
}
},
// Various Dev Server settings
host: '0.0.0.0', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
// Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: true,
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false,
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false,
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.