text
stringlengths 2
6.14k
|
|---|
var namespaces =
[
[ "read", "namespaceread.html", null ],
[ "send", "namespacesend.html", null ]
];
|
var path = require('path');
module.exports = {
entry: [
'babel-polyfill',
path.resolve(__dirname, 'app/cms/post/main.jsx')
],
output: {
path: __dirname + '/public/scripts/bundles',
filename: 'posts-cms.js'
},
resolve: {
extensions: [ '', '.js', '.jsx' ]
},
devtool: 'source-map',
module: {
preLoaders: [
{ test: /\.jsx?$/, loader: 'eslint', exclude: /node_modules/ }
],
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
query: {
presets: [ 'es2015', 'react', 'stage-1' ]
}
},
{ test: /\.css$/, loader: 'style-loader!css-loader' }
]
},
eslint: {
failOnWarning: false,
failOnError: true
}
};
|
'use strict';
app.factory('Revision', ['Restangular', function(Restangular) {
return Restangular.service('revision');
}]);
|
Ext.define('SlateTheme.resizer.Splitter', {
override: 'Ext.resizer.Splitter',
size: 12
});
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { Component, PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import { connect } from 'react-redux';
import $ from 'jquery';
import s from './TopK.scss';
import {summaEndpoint} from '../../config';
@connect((store) => {
return {
namedGraph: store.qa.namedGraph,
}
})
class TopK extends Component {
static propTypes = {
sumid: PropTypes.string.isRequired,
uri: PropTypes.string.isRequired,
topK: PropTypes.number.isRequired,
lang: PropTypes.string.isRequired,
};
constructor(props) {
super(props);
}
componentDidMount() {
var id = this.props.sumid;
var uri = this.props.uri;
var topK = this.props.topK;
$.ajaxSetup({
accepts : {
"json" : "application/ld+json, application/json, text/javascript"
},
contents : {
"ld+json" : "application/ld+json"
},
converters : {
"ld+json json" : jQuery.parseJSON
}
});
var url = summaEndpoint+this.props.kb+"/sum" + "?entity=" + encodeURIComponent(uri) + "&topK=" + topK + "&maxHops=1" + "&language=" + this.props.lang;
console.log("URL "+url);
$.ajax({
dataType : "json",
url : url,
beforeSend : function() {
// show loading bar
$("#" + id + "_loading").show();
},
complete : function() {
// remove loading bar
$("#" + id + "_loading").remove();
},
success : function(data) {
console.log(data);
$("#" + id).empty();
function label(uri) {
for ( k = 0; k < keys.length; k++) {
if(data[keys[k]]["@id"] == uri){
var part1 = data[keys[k]];
}
}
if (part1 != null) {
var labels = part1["http://www.w3.org/2000/01/rdf-schema#label"][0]["@value"];
return labels;
} else {
var strArry = uri.split("/");
strArry[strArry.length - 1] = strArry[strArry.length - 1].split("_").join(" ");
return strArry[strArry.length - 1];
}
}
var print = {
"entity" : "",
"statements" : []
};
var keys = Object.keys(data);
for (var j = 0; j < topK; j++) {
for (var i = 0; i < keys.length; i++) {
var types = data[keys[i]]["http://purl.org/voc/summa/statement"];
if (types != null) {
print["entity"] = data[keys[i]]["http://purl.org/voc/summa/entity"][0]["@id"];
for (var k = 0; k < keys.length; k++) {
if (data[keys[i]]["http://purl.org/voc/summa/statement"].length > j) {
if(data[keys[k]]["@id"] == data[keys[i]]["http://purl.org/voc/summa/statement"][j]["@id"]){
var statement = {
"subject" : "",
"predicate" : "",
"object" : ""
};
statement["subject"] = data[keys[k]]["http://www.w3.org/1999/02/22-rdf-syntax-ns#subject"][0]["@id"];
statement["predicate"] = data[keys[k]]["http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate"][0]["@id"];
statement["object"] = data[keys[k]]["http://www.w3.org/1999/02/22-rdf-syntax-ns#object"][0]["@id"];
print.statements.push(statement);
}
}
}
}
}
}
$("#" + id).append("<h2>Summary</h2><table></table>");
for (var i = 0; i < print.statements.length; i++) {
if (print.statements[i].subject == print.entity) {
var path = "/question?query="+label(print.statements[i].object)+"&lang="+this.props.lang+"&kb="+this.props.kb+"&uri="+print.statements[i].object+"&ng="+this.props.namedGraph;
$("#" + id).children("table").append("<tr><td>" + label(print.statements[i].predicate) + " </td><td><a href=\""+path+"\">"+label(print.statements[i].object)+"</a></td></tr>");
} else if (print.statements[i].object == print.entity) {
var path = "/question?query="+label(print.statements[i].subject)+"&lang="+this.props.lang+"&kb="+this.props.kb+"&uri="+print.statements[i].subject+"&ng="+this.props.namedGraph;
$("#" + id).children("table").append("<tr><td>" + label(print.statements[i].predicate) + " of </td><td><a href=\""+path+"\">"+label(print.statements[i].subject)+"</a></td></tr>");
}
}
$("#" + id).append("<i style='font-size:10px'>_______<br>Summary by <a href='" + url.substring(0,url.indexOf("/sum")+4) +"'>"+ url.substring(0,url.indexOf("/sum"))+"</a></i>");
}.bind(this),
error: function(error){
console.log(error);
}
});
}
componentWillUnmount(){
var id = this.props.sumid;
$("#" + id).empty();
$("#" + id).remove();
}
render() {
return (
<div className={s.container}>
<div className={s.sum} id={this.props.sumid}></div>
</div>
);
}
}
export default withStyles(TopK, s);
|
var eventHistoryListCtrl = {
eventSize : 10,
feathersRoute: "homera/modules/eventHistoryList",
feathersCtrl: server.modules.feathersMemory(),
events: [],
create: function (serviceName,config) {
var newEvent = new event(serviceName,config);
var feathersService = server.modules.feathers.service(this.feathersRoute);
//remove the end
feathersService.find({
query : {
order : "ascending",
sort : ["dateStr"]
}
}, function(error, result){
if(result.length > eventHistoryListCtrl.eventSize)
{
feathersService.remove(result[0].id, {}, function(){});
}
}),
feathersService.create(newEvent, {}, function (error, newEvent) {
//console.debug('Created event', newEvent);
});
return newEvent;
}
};
//the individual application scope
var event = function (serviceName,config) {
this.serviceName = serviceName;
this.dateStr = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
this.desc = config.desc;
this.room = config.room;
};
module.exports = eventHistoryListCtrl;
|
var fs = require('fs');
var util = require('util');
var path = require('path');
var AWS = require('../');
var apis = require('../lib/api_loader');
var defaultServices = 'cloudwatch,cloudwatchlogs,codepipeline,cognitoidentity,cognitosync,devicefarm,dynamodb,dynamodbstreams,ec2,elastictranscoder,firehose,inspector,kinesis,kms,lambda,marketplacecommerceanalytics,mobileanalytics,machinelearning,opsworks,route53,s3,sqs,sns,ssm,sts,waf';
var sanitizeRegex = /[^a-zA-Z0-9,-]/;
var serviceClasses = {};
Object.keys(AWS).forEach(function(name) {
if (AWS[name].serviceIdentifier) {
serviceClasses[AWS[name].serviceIdentifier] = AWS[name];
}
});
function getServiceHeader(service) {
if (service === 'all') {
return Object.keys(serviceClasses).map(function(name) {
return getServiceHeader(name);
}).join('\n');
}
if (!serviceClasses[service]) return null;
var versions = serviceClasses[service].apiVersions.map(function(version) {
return version.indexOf('*') >= 0 ? null : version;
}).filter(function(c) { return c !== null; });
var file = util.format(
'AWS.apiLoader.services[\'%s\'] = {};\n' +
'AWS.%s = AWS.Service.defineService(\'%s\', %s);\n',
service, apis.serviceName(service), service, util.inspect(versions));
var svcPath = path.join(__dirname, '..', 'lib', 'services', service + '.js');
if (fs.existsSync(svcPath)) {
file += 'require(\'./services/' + service + '\');\n';
}
return file;
}
function getService(service, version) {
if (service === 'all') {
return Object.keys(serviceClasses).map(function(name) {
var out = serviceClasses[name].apiVersions.map(function(svcVersion) {
if (svcVersion.indexOf('*') >= 0) return null;
return getService(name, svcVersion);
}).filter(function(c) { return c !== null; }).join('\n');
return out;
}).join('\n');
}
var svc, api;
if (!serviceClasses[service]) {
return null;
}
try {
var ClassName = serviceClasses[service];
svc = new ClassName({apiVersion: version, endpoint: 'localhost'});
api = apis.load(service, svc.api.apiVersion);
} catch (e) {
return null;
}
var line = util.format(
'AWS.apiLoader.services[\'%s\'][\'%s\'] = %s;',
service, svc.api.apiVersion, JSON.stringify(api));
return line;
}
function ServiceCollector(services) {
var builtServices = {};
function buildService(name, usingDefaultServices) {
var match = name.match(/^(.+?)(?:-(.+?))?$/);
var service = match[1], version = match[2] || 'latest';
var contents = [];
var lines, err;
if (!builtServices[service]) {
builtServices[service] = {};
lines = getServiceHeader(service);
if (lines === null) {
if (!usingDefaultServices) {
err = new Error('Invalid module: ' + service);
err.name = 'InvalidModuleError';
throw err;
}
} else {
contents.push(lines);
}
}
if (!builtServices[service][version]) {
builtServices[service][version] = true;
lines = getService(service, version);
if (lines === null) {
if (!usingDefaultServices) {
err = new Error('Invalid module: ' + service + '-' + version);
err.name = 'InvalidModuleError';
throw err;
}
} else {
contents.push(lines);
}
}
return contents.join('\n');
}
var serviceCode = '';
var usingDefaultServicesToggle = false;
if (!services) {
usingDefaultServicesToggle = true;
services = defaultServices;
}
if (services.match(sanitizeRegex)) {
throw new Error('Incorrectly formatted service names');
}
var invalidModules = [];
var stsIncluded = false;
services.split(',').sort().forEach(function(name) {
if (name.match(/^sts\b/) || name === 'all') stsIncluded = true;
try {
serviceCode += buildService(name, usingDefaultServicesToggle) + '\n';
} catch (e) {
if (e.name === 'InvalidModuleError') invalidModules.push(name);
else throw e;
}
});
if (!stsIncluded) {
serviceCode += buildService('sts') + '\n';
}
if (invalidModules.length > 0) {
throw new Error('Missing modules: ' + invalidModules.join(', '));
}
return serviceCode;
}
module.exports = ServiceCollector;
|
var map = L.map('map').setView([48.85568, 2.34558], 13);
var marker = L.marker([48.85568, 2.34558]).addTo(map);
var mqTilesAttr = 'Map data © <a href="http://www.openstreetmap.org/" […]">';
L.tileLayer('http://otile{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png', { subdomains: '1234', attribution: mqTilesAttr }).addTo(map);
var circle = L.circle([48.594, 7.746], 500, {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5
}).addTo(map);
marker.bindPopup("Bouh !").openPopup();
function my_tchat() // ouvre le tchat
{
document.getElementsByClassName("my_html")[1].style.display="";
document.getElementsByClassName("my_html")[0].style.width="60%";
document.getElementsByClassName("my_html")[1].style.width="30%";
}
marker.addEventListener("click",my_tchat);
|
import fetch from 'isomorphic-fetch'
// ------------------------------------
// Constants
// ------------------------------------
export const FETCH_STATRT = 'FETCH_STATRT'
export const FETCH_SUCCESS = 'FETCH_SUCCESS'
// ------------------------------------
// Actions
// ------------------------------------
export function fetchStart () {
return {
type: FETCH_STATRT
}
}
export function fetchSuccess (categories) {
return {
type: FETCH_SUCCESS,
payload: categories
}
}
export const actions = {
fetchStart,
fetchSuccess
}
// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
[FETCH_SUCCESS]:(state, action) => {
return Object.assign({}, state, Array.from(action.payload))
}
}
// ------------------------------------
// Reducer
// ------------------------------------
const initialState = []
export default function categoryReducer (state = initialState, action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
// ------------------------------------
// Functions
// ------------------------------------
export function fetchCategories () {
return function (dispatch) {
dispatch(fetchStart())
var fetchInit = { method: 'GET',
cache: 'default'
}
fetch(`http://localhost:3001/api/category`, fetchInit)
.then(response => response.json())
.then(json => {
dispatch(fetchSuccess(json))
})
}
}
|
var path = require('path');
module.exports = {
entry: "./src/index.js",
output: {
path: "./dist",
filename: "app.js"
},
module: {
loaders: [
{
test: /\.md$/,
loader: 'vue-doc-loader'
},
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.html/,
loader: 'html'
},
{ test: /\.json$/, loader: 'json' },
{
test: /\.js$/,
loader: 'babel'
},
{
test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
loader: 'file-loader'
},
{
test: /\.(png|jpe?g|gif|svg)(\?\S*)?$/,
loader: 'file-loader',
query: {
name: '[name].[ext]?[hash]'
}
}
]
},
vue: {
loaders: {
scss: "vue-style-loader!css-loader!sass"
}
},
resolve :{
extensions: ['', '.js', '.vue'],
alias: {
vue: 'vue/dist/vue.js'
}
}
};
|
var liveOnStage = require('../live-on-stage.js');
window.liveOnStage = liveOnStage;
|
// This file is not empty
/*! Generated with PostCSS Click */
$(function() {
$(".foo").on("click", function() {
$(this).next().css({
"color": "red"
}).toggleClass("new").modal();
});
$(".bar .woo").on("click", function() {
$(".opa a").css({
"color": "green",
"background-color": "yellow"
});
});
});
|
module.exports = (collection) => {
const tagSet = new Set();
collection.getAll().forEach((item) => {
if ("tags" in item.data) {
let { tags } = item.data;
tags = tags.filter((item) => {
const filterOut = [
"all",
"nav",
"post",
"posts"
];
return !filterOut.includes(item);
});
for (const tag of tags) {
tagSet.add(tag);
}
}
});
// returning an array in addCollection works in Eleventy 0.5.3
return [...tagSet];
};
|
(function () {
'use strict';
var settings = require('./mm.settings.js'),
request = require('request').defaults({ headers: settings.headers }),
cheerio = require('cheerio');
var vid = module.exports = {};
vid.youtube = function (metaInfo, callback) {
if (!metaInfo || !callback) {
return;
}
var artist = metaInfo.artist.toLowerCase().replace(/ /g, '+');
var title = metaInfo.title.toLowerCase().replace(/^[0-9]{2,3} - /, '').replace(/ /g, '+');
var uri = 'http://www.google.com/search?q=' + [artist, title].join('+') + '+official+site:www.youtube.com';
uri = encodeURI(uri);
request({ uri: uri }, function (err, res, body) {
if (err) {
callback(undefined, { error: 'Request error.' });
return;
}
var $ = cheerio.load(body, { ignoreWhitespace: true });
var links = $('body h3 a');
var link = null;
for (var i = 0, endi = links.length; i < endi; i++) {
if (links[i] && links[i].attribs && links[i].attribs.href && (links[i].attribs.href.indexOf('watch') > -1)) {
link = links[i];
break;
}
}
if (link === null) {
callback(undefined, { error: 'Malformed response from google.' });
return;
}
var matches = link.attribs.href.replace('/url?q=', '').match(/watch%3Fv%3D(.*?)&/);
if (matches !== null && matches.length > 1) {
callback(undefined, { data: matches[1] });
} else {
callback(undefined, { error: 'No /watch url found.' });
}
});
};
}) ();
|
var mvcApp = angular.module('episodio5App', []);
mvcApp.controller('ep05Controller', function ep05Controller($scope) {
$scope.states = [
{name:'Minas Gerais', capital: 'Belo Horizonte'},
{name:'São Paulo', capital: 'São Paulo'},
{name:'Paraíba', capital: 'João Pessoa'},
{name:'Rio de Janeiro', capital: 'Rio de Janeiro'},
{name:'Espírito Santo', capital: 'Vitória'}
];
$scope.addState = function() {
$scope.states.push({name : $scope.estado, capital : $scope.capital});
$scope.estado = '';
$scope.capital = '';
};
$scope.incrementa = function() {
$scope.contador = $scope.contador + 1;
};
$scope.gostei = false;
$scope.escondido = false;
$scope.contador = 0;
});
|
import React from 'react';
import { shallow } from 'enzyme';
import ActivityMaps from '../index';
describe('<ActivityMaps />', () => {
it('should render a div', () => {
const rc = shallow(<ActivityMaps />);
expect(rc.find('div').length).toEqual(2);
});
});
|
/* eslint-disable */
const syntax-error
|
'use strict';
var JSIGSnippet = require('../lib/jsig-snippet.js');
JSIGSnippet.test('correctly infer function type', function m() {/*
var foo = "";
foo = bar("");
function bar(x) {
return x;
}
*/}, function t(snippet, assert) {
snippet.compileAndCheck(assert);
assert.end();
});
JSIGSnippet.test('infer function type error', function m() {/*
var foo = "";
foo = bar(4);
function bar(x) {
return x;
}
*/}, function t(snippet, assert) {
var meta = snippet.compile(assert);
var errors = meta.errors;
assert.equal(errors.length, 4);
assert.equal(errors[0].type, 'jsig.sub-type.type-class-mismatch');
assert.equal(errors[0].expected, 'String');
assert.equal(errors[0].actual, 'Number');
assert.equal(errors[0].line, 6);
assert.equal(errors[1].type, 'jsig.sub-type.type-class-mismatch');
assert.equal(errors[1].expected, 'String');
assert.equal(errors[1].actual, 'Number');
assert.equal(errors[1].line, 6);
assert.equal(errors[2].type, 'jsig.verify.untyped-function-call');
assert.equal(errors[2].funcName, 'bar');
assert.equal(errors[2].callExpression, 'bar');
assert.equal(errors[2].line, 3);
assert.equal(errors[3].type, 'jsig.verify.untyped-function-found');
assert.equal(errors[3].funcName, 'bar');
assert.equal(errors[3].line, 5);
assert.end();
});
JSIGSnippet.test('infer func type through assignment', function m() {/*
var foo = "";
foo = toFixed(genNum());
function genNum() {
return 5;
}
function toFixed(n) {
return n.toFixed(2);
}
*/}, function t(snippet, assert) {
snippet.compileAndCheck(assert);
assert.end();
});
JSIGSnippet.test('infer func type through return', function m() {/*
var foo = "";
foo = f();
function f() {
return toFixed(genNum());
}
function genNum() {
return 5;
}
function toFixed(n) {
return n.toFixed(2);
}
*/}, function t(snippet, assert) {
snippet.compileAndCheck(assert);
assert.end();
});
JSIGSnippet.test('infer function type via callback (decl)', {
snippet: function m() {/*
readFile('fileName', onFile);
function onFile(err, str) {
str.split('')
}
*/},
header: function h() {/*
readFile : (String, (Error, String) => void) => void
*/}
}, function t(snippet, assert) {
snippet.compileAndCheck(assert);
assert.end();
});
JSIGSnippet.test('infer function type via callback (expr)', {
snippet: function m() {/*
readFile('fileName', function onFile(err, str) {
str.split('');
});
*/},
header: function h() {/*
readFile : (String, (Error, String) => void) => void
*/}
}, function t(snippet, assert) {
snippet.compileAndCheck(assert);
assert.end();
});
JSIGSnippet.test('infer function type via field (decl)', {
snippet: function m() {/*
var req = readFile('fileName');
req.onDone = onFile;
function onFile(err, str) {
str.split('')
}
*/},
header: function h() {/*
readFile : (String) => {
onDone: (Error, String) => void
}
*/}
}, function t(snippet, assert) {
snippet.compileAndCheck(assert);
assert.end();
});
JSIGSnippet.test('infer function type via field (expr)', {
snippet: function m() {/*
var req = readFile('fileName');
req.onDone = function onFile(err, str) {
str.split('');
};
*/},
header: function h() {/*
readFile : (String) => {
onDone: (Error, String) => void
}
*/}
}, function t(snippet, assert) {
snippet.compileAndCheck(assert);
assert.end();
});
JSIGSnippet.test('infer function type via option (decl)', {
snippet: function m() {/*
readFile('fileName', {
onDone: onFile
});
function onFile(err, str) {
str.split('')
}
*/},
header: function h() {/*
readFile : (String, {
onDone: (Error, String) => void
}) => void
*/}
}, function t(snippet, assert) {
snippet.compileAndCheck(assert);
assert.end();
});
JSIGSnippet.test('infer function type via option (expr)', {
snippet: function m() {/*
readFile('fileName', {
onDone: function onFile(err, str) {
str.split('');
}
});
*/},
header: function h() {/*
readFile : (String, {
onDone: (Error, String) => void
}) => void
*/}
}, function t(snippet, assert) {
snippet.compileAndCheck(assert);
assert.end();
});
|
/**
* Udp module
* @module udp/module
*/
/**
* Module main class
*/
class Udp {
/**
* Create the module
* @param {App} app The application
*/
constructor(app) {
this._app = app;
}
/**
* Service name is 'modules.udp'
* @type {string}
*/
static get provides() {
return 'modules.udp';
}
/**
* Dependencies as constructor arguments
* @type {string[]}
*/
static get requires() {
return ['app'];
}
/**
* Register with the server
* @param {object} server Server instance
* @return {Promise}
*/
async register(server) {
if (server.constructor.provides !== 'servers.udp')
return;
this.events = this._app.get(/^udp\.events\..+$/);
for (let event of this.events.values())
server.on(event.name, event.handle.bind(event));
}
}
module.exports = Udp;
|
/**
* Created by MarkHsiu on 2015/10/20.
*/
function Logger(){
if(typeof Logger.single_instance === "undefined"){
Logger.single_instance=this;
}
return Logger.single_instance;
}
var single = (function(ddd){
var unique;
function Const(){
// TODO code
}
unique = new Const();
return function(){
return unique;
};
})();
function Singleton(){
function Const(){
if(typeof Const.single_instance === "undefined"){
Const.single_instance=this;
}
return Const.single_instance;
};
return (function(){
return new Const();
})();
}
var a =new Logger();
var b =new Logger();
var aa= new single();
var bb= new single();
var aaa= new Singleton();
var bbb= new Singleton();
console.log(a===b);
console.log(aa===bb);
console.log(aaa===bbb);
|
angular.module("ssFilters")
.filter("printedTime",function(){
return function(input, game, forGraph) {
var secondsToTime = function (totSeconds) {
var seconds = totSeconds%60;
var minutes = (totSeconds-seconds)/60;
seconds = (seconds < 10) ? "0"+seconds : seconds;
return minutes + ":" + seconds;
}
if (game) {
if (game && game.sport) {
if (game.totTime && game.sport.q && game.boxScore) {
var totPeriods = game.boxScore.length,
n = game.sport.q.n,
time;
input = +input;
while (totPeriods > n && input >= game.sport.q.o) {
totPeriods--;
input -= game.sport.q.o;
}
while (totPeriods > 1 && input >= game.sport.q.t) {
totPeriods--;
input -= game.sport.q.t;
}
if (input == 0) {
if (totPeriods === game.boxScore.length && (forGraph || !forGraph && game.aScore != game.hScore)) {
time = "Final";
if (n >= totPeriods || forGraph) {
return time;
}
}
else if (totPeriods === n/2) {
return "Half"
} else if (forGraph) {
return game.boxScore[totPeriods].l;
} else {
time = "End";
}
} else {
time = secondsToTime(input);
if (forGraph) {
return time;
}
}
return time + " " + game.boxScore[totPeriods-1].l;
}
}
}
return secondsToTime(+input);
}
});
|
/**
* Remove file extension.
* @function removeExtname
* @param {string} filename - Filename to change.
* @param {string} extname - Extname to remove.
* @returns {string} Changed file name.
*/
'use strict'
const path = require('path')
/** @lends removeExtname */
function removeExtname (filename, extname) {
let dirname = path.dirname(filename)
let basename = path.basename(filename, extname)
return path.join(dirname, basename)
}
module.exports = removeExtname;
|
import {assert} from 'chai';
import chain from '../src/chain';
import first from '../src/first';
describe('first', () => {
it('should handle an array', () => {
let xs = [1, 2, 3, 4];
let result = chain(xs).first();
assert.equal(result, 1);
});
it('should handle a string', () => {
let xs = 'abcd';
let result = chain(xs).first();
assert.equal(result, 'a');
});
it('should handle a set', () => {
let xs = new Set([1, 1, 2, 3, 4]);
let result = chain(xs).first();
assert.equal(result, 1);
});
it('should handle a map', () => {
let xs = new Map([[1, 1], [2, 2]]);
let result = chain(xs).first();
assert.deepEqual(result, [1, 1]);
});
it('should work unchained', () => {
let xs = [1, 2, 3, 4];
let result = first(xs);
assert.equal(result, 1);
});
});
|
var $ = require("jquery-deferred"),
flow = require("../../sebastian").flow;
flow("someFlow")
.step("one", function() {
console.log("one..");
})
.step("two", function() {
console.log("two..");
})
.step("three", function() {
console.log("three..");
});
flow("someFlow")
.skip("one")
.begin();
|
'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');
gulp.task('nsp', function(cb) {
nsp({package: __dirname + '/package.json'}, cb);
});
gulp.task('pre-test', function() {
return gulp.src('lib\**\*.js')
.pipe(istanbul({
includeUntested: true
}))
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['pre-test'], function(cb) {
var mochaErr;
gulp.src('test/**/*.js')
.pipe(plumber())
.pipe(mocha({
reporter: 'spec'
}))
.on('error', function(err) {
mochaErr = err;
})
.pipe(istanbul.writeReports({
reporters: ['lcov']
}))
.on('end', function() {
cb(mochaErr);
});
});
gulp.task('coveralls', ['test'], function() {
if (!process.env.CI) {
return;
}
return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
.pipe(coveralls()); // Crashes: 'error from lcovParse: ' 'Failed to parse string'
});
gulp.task('prepublish', ['nsp']);
gulp.task('default', ['test']); // + 'coveralls'
|
/**
*
* Bosses is a factory who seed the entities group with the given bosses of the level
*
*
*
* @params Game
*
*/
(function() {
'use strict';
function Bosses(game) {
this.game = game;
// Spawn timer
this.bossesTimer = this.game.time.create(false);
this.bossesTimer.start();
// Shared health bar initialisation
this.healthBarParams = {
x: this.game.width/2-150,
y: this.game.height-40,
width: 300,
height: 20,
radius: 3,
color: '#FFFFFF',
bgColor: '#651828',
highlight: false,
hiddable: true,
name: "BOSS",
names: "BOSSES"
};
this.sharedHealthbar = new HealthBar(this.game, 0, this.healthBarParams);
this.sharedHealthbar.hideHealthBar();
}
Bosses.prototype = {
/** Return the list of the bosses **/
getBossesList: function(){
return ['david', 'rat'];
},
/** Return a new boss **/
getBoss: function (entity, game, parameters) {
if(entity == 'david') return new David(game, parameters);
if(entity == 'rat') return new Rat(game, parameters);
},
/** Add bosses to entities group **/
addBosses: function(){
this.addBoss();
},
/** Add boss to the entities group **/
addBoss: function(){
var self = this;
var boss = null;
var nbBossesAlive = 0;
// Before create a new boss, we try to get one from the dead bosses
this.game.entities.filter(function(child) {
if(self.getBossesList().indexOf(child.type) != -1){
//retrive the first boss dead
if (boss === null && !child.alive) {
boss = child;
}
nbBossesAlive++;
}
}, true);
if(boss !== null && nbBossesAlive <= boss.maxBoss) {
// Reset the dead boss that we got
var location = boss.popLocation();
boss.reset(location.x,location.y);
boss.init(this.game.level.bossParameters[boss.type]);
}else if(nbBossesAlive < this.game.level.maxBosses && this.game.level.bossParameters){
// Create a new random boss from the available boss parameters list
this.createRandomBoss(Object.keys(this.game.level.bossParameters));
}else{
return;
}
// Create a new boss in X seconds
this.bossesTimer.add(Math.random() * (this.game.level.maxSpawnDelay - this.game.level.minSpawnDelay)+this.game.level.minSpawnDelay, this.addBoss, this);
},
/** Create a new random boss from the parameters list **/
createRandomBoss: function(bosses){
if(bosses.length < 1) return null;
//pick random boss
var boss = bosses[ bosses.length * Math.random() << 0 ];
var nbAlive = 0; //number of boss alive: A type of enemies can have a limit
this.game.entities.forEachAlive(function(e){
if(e.type == boss) nbAlive++;
});
if (nbAlive < this.game.level.bossParameters[boss].maxBoss){
//add a new boss to the entities group
var boss = this.getBoss(boss, this.game, this.game.level.bossParameters);
this.game.entities.add(boss);
}else{
//In case, we have reach the limit of the picked one, we to look for an another one
var index = bosses.indexOf(boss);
if (index > -1) {
bosses.splice(index, 1);
}
this.createRandomBoss(bosses);
}
}
};
window['awaken'] = window['awaken'] || {};
window['awaken'].Bosses = Bosses;
}());
|
/**
* Created by Stone on 2016/11/12.
*/
"use strict";
var CategoryDal = require('../dal/category'),
q = require('q'),
moment = require('moment');
var CategoryBLL = new Object();
//增
CategoryBLL.addInfo = function (info) {
var defer = q.defer();
info.status = 1;
info.addtime = moment().format('YYYY-MM-DD hh:mm:ss');
info.updatetime = moment().format('YYYY-MM-DD hh:mm:ss');
CategoryDal.create(info, function (res) {
//callback(res);
defer.resolve(res);
});
return defer.promise;
};
//删
CategoryBLL.deleteInfo = function (info, callback) {
CategoryDal.delete(info, function (res) {
//删除二级菜单
//。。。。。。。。
callback(res);
});
};
//查
CategoryBLL.getList = function (info) {
var defer = q.defer();
var fields = null;//查询所有的列
var sort = {sort: {'updatetime': -1}};
CategoryDal.find(info, fields, sort, function (res) {
defer.resolve(res);
});
return defer.promise;
};
CategoryBLL.findById = function (id, callback) {
CategoryDal.findById(id, function (res) {
callback(res);
});
};
//改
CategoryBLL.update = function (info, updatecol, callback) {
CategoryDal.update(info, updatecol, function (res) {
callback(res);
});
};
module.exports = CategoryBLL;
|
version https://git-lfs.github.com/spec/v1
oid sha256:b1365a2d0518a4cac32fd8ac91154d0ef6c6a5a5bb5987ee7238fdf44a9d08f5
size 22885
|
/**
* @constructor documentjs.tags.demo @demo
* @parent documentjs.tags
*
* @description Placeholder for an application demo.
*
* @signature `@demo SRC [HEIGHT]`
*
* @codestart javascript
* /**
* * @demo can/control/control.html 300
* *|
* @codeend
*
* @param {String} SRC The source of the html page.
* @param {Number} [HEIGHT] The height of the html page. If
* a height is not provided, the height is determined as
* the content of the body.
*
* @body
*
* ## Specifying the HTML and JS source
*
* By default, `@demo` uses the html of the body minus
* any script tags as the HTML source. This can
* be changed by:
*
* - Adding an element with `id="demo-html"` or
* setting `window.DEMO_HTML` to the source text.
* - Adding `id="demo-source"` to a script tag or
* setting `window.DEMO_SOURCE` to the source JS.
*/
module.exports = {
add: function( line, curData, scope, objects, currentWrite ) {
var m = line.match(/^\s*@demo\s*([\w\.\/\-\$]*)\s*([\w]*)/)
if ( m ) {
var src = m[1] ? m[1].toLowerCase() : '';
var heightAttr = m[2].length > 0 ? " data-demo-height='" + m[2] + "'" : '';
var cd = ( curData && curData.length !== 2),
cw = (currentWrite || "body"),
html = "<div class='demo_wrapper' data-demo-src='" + src + "'" + heightAttr + "></div>\n";
// use curData if it is not an array
var useCurData = cd && (typeof curData.description === "string") && !curData.body;
if(useCurData) {
curData.description += html;
} else {
this.body += html;
}
}
}
};
|
var gulp = require('gulp');
var gutil = require('gulp-util');
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var addsrc = require('gulp-add-src');
var wrap = require('gulp-wrap');
var elementQuery = require('./tasks/gulp');
var babelify = require('babelify');
var sourcemaps = require('gulp-sourcemaps');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
gulp.task('build', function() {
return browserify({
entries: 'index.js',
debug: true,
transform: [babelify]
})
.bundle()
.on('error', function(err) { console.error(err); this.emit('end'); })
.pipe(source('index.min.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(uglify())
.on('error', gutil.log)
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(''));
});
gulp.task('js', function() {
return gulp
.src([
'node_modules/jquery/dist/jquery.min.js',
'node_modules/codemirror/lib/codemirror.js',
'node_modules/codemirror/mode/css/css.js',
'node_modules/codemirror/mode/xml/xml.js',
'node_modules/codemirror/mode/htmlmixed/htmlmixed.js'
])
.pipe(concat('index.js'))
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
gulp.task('css', function() {
return gulp.src('./index.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('dist'))
.pipe(elementQuery())
.pipe(addsrc.append([
'node_modules/codemirror/lib/codemirror.css',
'node_modules/codemirror/theme/base16-light.css',
'node_modules/codemirror/theme/neat.css'
]))
.pipe(concat('index.css'))
.pipe(gulp.dest('dist'));
});
gulp.task('watch', function() {
gulp.watch(['**/*.js', '!**/*.min.js', '!gulpfile.js', '!node_modules/', '!dist/'], ['build', 'js']);
gulp.watch(['**/*.scss', '../*.scss', '!node_modules/'], ['css']);
});
gulp.task('default', ['build', 'js', 'css', 'watch']);
|
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import ButtonBase from '../ButtonBase';
import StepLabel from '../StepLabel';
import { isMuiElement } from '../utils/reactHelpers';
export const styles = {
/* Styles applied to the root element. */
root: {
width: '100%',
padding: '24px 16px',
margin: '-24px -16px',
boxSizing: 'content-box'
},
/* Styles applied to the root element if `orientation="horizontal"`. */
horizontal: {},
/* Styles applied to the root element if `orientation="vertical"`. */
vertical: {
justifyContent: 'flex-start'
},
/* Styles applied to the `ButtonBase` touch-ripple. */
touchRipple: {
color: 'rgba(0, 0, 0, 0.3)'
}
};
const StepButton = React.forwardRef(function StepButton(props, ref) {
const {
active,
alternativeLabel,
children,
classes,
className: classNameProp,
completed,
disabled,
icon,
optional,
orientation
} = props,
other = _objectWithoutPropertiesLoose(props, ["active", "alternativeLabel", "children", "classes", "className", "completed", "disabled", "icon", "last", "optional", "orientation"]);
const childProps = {
active,
alternativeLabel,
completed,
disabled,
icon,
optional,
orientation
};
const child = isMuiElement(children, ['StepLabel']) ? React.cloneElement(children, childProps) : React.createElement(StepLabel, childProps, children);
return React.createElement(ButtonBase, _extends({
disabled: disabled,
TouchRippleProps: {
className: classes.touchRipple
},
className: clsx(classes.root, classes[orientation], classNameProp),
ref: ref
}, other), child);
});
process.env.NODE_ENV !== "production" ? StepButton.propTypes = {
/**
* @ignore
* Passed in via `Step` - passed through to `StepLabel`.
*/
active: PropTypes.bool,
/**
* @ignore
* Set internally by Stepper when it's supplied with the alternativeLabel property.
*/
alternativeLabel: PropTypes.bool,
/**
* Can be a `StepLabel` or a node to place inside `StepLabel` as children.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* @ignore
* Sets completed styling. Is passed to StepLabel.
*/
completed: PropTypes.bool,
/**
* @ignore
* Disables the button and sets disabled styling. Is passed to StepLabel.
*/
disabled: PropTypes.bool,
/**
* The icon displayed by the step label.
*/
icon: PropTypes.node,
/**
* @ignore
*/
last: PropTypes.bool,
/**
* The optional node to display.
*/
optional: PropTypes.node,
/**
* @ignore
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical'])
} : void 0;
export default withStyles(styles, {
name: 'MuiStepButton'
})(StepButton);
|
/**
* Created by long on 4/13/17.
*/
/**
*
*/
'use strict';
import React, {Component, PropTypes} from "react";
import Text from '../../common/text/text-component';
import Icon from '../../common/icon/icon-component';
import Cell from './cell-map-finder-dropdown-component';
export default class MapFinderDropdownComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
expand:this.props.expand,
groupName:this.props.groupName,
arrObject:this.props.arrObject,
};
}
/**
* @desc This is callback function when click on item
* @param {object} event - Event of element
*/
onClick(event) {
event.stopPropagation();
event.preventDefault();
this.setState({
expand:!this.state.expand,
});
}
itemClick(tempData,index) {
let tempArrObject = this.state.arrObject;
tempArrObject[index] = tempData;
this.setState({
arrObject:tempArrObject,
});
}
renderList() {
const itemClick = (tempData,index) => this.itemClick(tempData,index);
if(this.state.arrObject) {
return this.state.arrObject.map((item, index)=> {
return (
<Cell
key={index}
index={index}
data={item}
onClick={itemClick}
/>
);
});
}else{
return null;
}
}
render() {
const {cellStyle} = this.props;
let titleNormalStyle = {
height:'16px',
fontSize: '10',
color: 'rgba(81,81,81,1)',
fontFamily: 'Roboto-Regular',
marginLeft: '16px',
marginRight: '16px',
};
let titleSelectStyle = {
height:'16px',
fontSize: '10',
color: 'rgba(0,154,222,1)',
fontFamily: 'Roboto-Medium',
marginLeft: '16px',
marginRight: '16px',
};
let iconDownStyle = {
width: '12px',
height: '6px',
right: '6px',
top: '12px',
position: 'absolute',
};
let iconUpStyle = {
width: '11px',
height: '8px',
right: '6px',
top: '12px',
position: 'absolute',
};
let srcIconDown = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAMCAYAAAB4MH11AAAAAXNSR0IArs4c6QAAAVdJREFUOBGlUktOhEAQtWXhDo7gEdi58gyjGcLOySRGnRiDF9BJiHqHGX+xTdwR2Dvegr3n0I3ge0wX6QATMLLgVVfVe4+qRm2ZZzweTxDqsiy3gW++70/jOC6k3ofgz8G9YZ9Sap5l2R1jismzZ8R5PsrzXMPArktfC21xU9wPw9BhXAukaXoJ54WwYTYZYgLxa/lycqHx7rruYZIkPzzXBiiUMLlAbskCH2PysmmSIAiu0HO77q7eK4prrb8lpyQQBEGBuADOJAd8xZ0c23dC8aIoqj2bvpXneQe2OPP1BKaJI3KSc+C95IBTrOtZJhkqTn5rAhE1kyyBZ5KDqUb8iVy9FuQ+sJZR88trjgRdSBNcIic57ar3iZPTWpEtBIES//MM+GTnGQ8Rr/qaxK6zWdcD8KQi9azF1th4B3YTY2PyiHDXcZwR/vOvZs+/zzSJomjnL0K/AnKp+wvhCV0AAAAASUVORK5CYII=";
let srcIconUp = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAPCAYAAAALWoRrAAAAAXNSR0IArs4c6QAAAZ9JREFUOBGtkr9Kw1AUxr97bcFF21WXJuITiG9RiiilUBy00FZRFCfRwT/gIKKgQlEhqYOKSKGIm4Po4CbiE4jJCzi4iCjmeKLJTasmdjAQ8p1zvvu7554boJWHSLRi8z1/m01rDA5lkNSHkBOv/sKor4wqwrCmGbjHnjSe7BNcUSzS7xXDoaY1C6JtBSEaxL19wLnwNZFQw1riDtcU0BdEeZi2yeDIsf3c1bBWedGyz4EQl/zuqpiowGOpqPgX0Qw1rE0GzimfEOeI8TyL2iQEqioPTMB42GiIm+TXMdzjmPYOA8dVVYgzJLScunF3lqbFM8Vw4JErKGmLKvaEZJBE1d7/BqyhV8sqoGsWwkFCH2FV99YC5CzwRvMq9oTg+RwzMB8U5CGSqQID34Ncg7qlOO6sU86kVVaKGRR19ae4nQZAHgJKqdFQoEvpF2+IiyyrCwV1aIubK/ux5GORF1R4t/LnMf1q2Legv6CrfYAv71pZKOicO+WbFHId5Z6phg2UN1Rkup8hO9IMvmFPHX18B//2HD12okZt/8YLA30A9fSGH4lwGL0AAAAASUVORK5CYII=";
const onClick = (event) => this.onClick(event);
if(this.state.expand){
return (
<div className="list-expanse-wrapper" >
<div className="cell-select-wrapper" onClick={onClick}>
<Text
style={titleSelectStyle}
text={this.state.groupName?this.state.groupName:''}
/>
<Icon
src={srcIconUp}
style={iconUpStyle}
/>
</div>
{this.renderList()}
<style>{css}</style>
</div>
);
}else{
return (
<div className="cell-wrapper" onClick={onClick} style={cellStyle?cellStyle:{}}>
<Text
style={titleNormalStyle}
text={this.state.groupName?this.state.groupName:''}
/>
<Icon
src={srcIconDown}
style={iconDownStyle}
/>
<style>{css}</style>
</div>
);
}
}
}
MapFinderDropdownComponent.propTypes = {
expand: PropTypes.bool,
groupName: PropTypes.string,
arrObject: PropTypes.array,
cellStyle: PropTypes.object,
};
const css = `
.list-expanse-wrapper {
background: rgba(0, 154, 222, 0.1);
padding-bottom: 10px;
}
.cell-select-wrapper {
border: none;
color: white;
height: 32px;
line-height: 32px;
text-align: left;
position: relative;
}
.cell-wrapper {
background: white;
border: none;
border-bottom: 1px solid #EAEAEA;
color: white;
height: 32px;
line-height: 32px;
text-align: left;
position: relative;
}
`;
|
export { default } from 'ember-flexberry-gis/map-tools/identify-all-polyline';
|
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
const expect = require('chai').expect;
const {
getCompositeDetails,
} = require('../../../../packages/workbox-build/build/lib/get-composite-details');
describe(`[workbox-build] lib/get-composite-details.js`, function () {
const URL = '/test';
const ENTRY1 = {
file: 'file1.txt',
size: 1234,
hash: 'hash1',
};
const ENTRY2 = {
file: 'file2.txt',
size: 5678,
hash: 'hash2',
};
it(`should return the expected composite details for a single file`, function () {
const details = getCompositeDetails(URL, [ENTRY1]);
expect(details).to.eql({
file: URL,
hash: '00c6ee2e21a7548de6260cf72c4f4b5b',
size: ENTRY1.size,
});
});
it(`should return the expected composite details for multiple files`, function () {
const details = getCompositeDetails(URL, [ENTRY1, ENTRY2]);
expect(details).to.eql({
file: URL,
hash: '3dcd1f089c4a94cbbedb7a00d7ec9829',
size: ENTRY1.size + ENTRY2.size,
});
});
});
|
import { locationsSaga } from './modules/location';
import { signupSaga } from './modules/signup';
import { loginSaga } from './modules/login';
export default function* IndexSaga() {
yield [locationsSaga(), signupSaga(), loginSaga()];
}
|
(function () {
'use strict';
// Configuring the Interventions Admin module
angular
.module('interventions.admin')
.run(menuConfig);
menuConfig.$inject = ['menuService'];
function menuConfig(Menus) {
Menus.addSubMenuItem('topbar', 'admin', {
title: 'Manage Interventions',
state: 'admin.interventions.list'
});
}
}());
|
'use strict';
var path = require('path');
var test = require('ava');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');
test.before(() => {
var deps = [
[helpers.createDummyGenerator(), 'statisk:git'],
[helpers.createDummyGenerator(), 'statisk:editorconfig'],
[helpers.createDummyGenerator(), 'statisk:gulp'],
[helpers.createDummyGenerator(), 'statisk:readme'],
[helpers.createDummyGenerator(), 'jekyllized:jekyll']
];
return helpers.run(path.join(__dirname, '../generators/app'))
.withPrompts({
projectName: 'jekyllized',
projectDescription: 'Test site for Jekyllized',
projectURL: 'www.test.com',
authorName: 'Ola Nordmann',
authorEmail: 'ola.nordmann@gmail.com',
authorBio: 'A norwegian dude',
uploading: 'None',
jekyllPermalinks: 'pretty'
})
.withOptions({'skip-install': true})
.withGenerators(deps)
.toPromise();
});
test('generates expected files', () => {
assert.file([
'.editorconfig',
'.gitignore',
'.gitattributes',
'package.json',
'gulpfile.js',
'README.md',
'_config.yml',
'_config.build.yml',
'Gemfile'
]);
});
test('creates package.json correctly', () => {
assert.file('package.json');
assert.jsonFileContent('package.json', {
name: 'jekyllized',
description: 'Test site for Jekyllized',
homepage: 'www.test.com',
author: {
name: 'Ola Nordmann',
email: 'ola.nordmann@gmail.com'
}
});
});
|
const db = require('../db/index')
const models = require('../db/models/index')
const ITEMS = {
'milk': '2',
'joghurt': '3',
'bananas': '0.5',
'cornflakes': '4',
'raisins': '1'
}
async function getProductIds () {
const productNames = Object.keys(ITEMS)
const products = await models.Product.findAll({ where: { name: { $in: productNames } } })
const result = {}
products.forEach(product => { result[product.name] = product.id })
return result
}
async function createSampleItems () {
let productIds
try {
productIds = await getProductIds()
} catch (err) {
console.error('Unable to query products', err)
return db.close()
}
const itemPromises = Promise.all(Object.keys(ITEMS).map(
productName => models.Item.create({
productId: productIds[productName],
amount: ITEMS[productName]
})
))
try {
await itemPromises
console.log('Items were created')
} catch (err) {
console.error('Unable to create models:', err)
}
return db.close()
}
createSampleItems()
|
Template.entity.helpers({
entity: function(){
// returns all entities in the collection
// reactive so updates automatically when called in the
// HTML template file
return Entity.find({});
}
});
Template.entity.events({
'click #deleteEntity': function(){
Meteor.call('deleteEntity', this, function(err,res){
if(err){
return err
} else {
return res
}
});
},
'submit form': function(e){
// submit method for the entity form on the entity admin page
e.preventDefault();
var entity = {
name: $(e.target).find('[name=name]').val(),
description: $(e.target).find('[name=description]').val(),
categories: []
};
_.map(e.target, function(e){ e.type=='checkbox' && e.checked ? entity.categories.push(e.value) : "false" });
console.log(entity);
if(entity.name != ""){
Meteor.call("insertEntity", entity, function(err,res){
console.log(err,res)
});
$('#entityForm').trigger("reset");
} else {
console.error('Cannot submit new Entity without a NAME')
}
}, // submit form end
'click #entity-search': function(){
var entities = Entity.find({}).fetch();
console.log(entities);
Meteor.call('entitySearch', 'Haiti', entities, function(err,res){
console.log('entitySearch',err,res);
})
},
'click #entityEdit': function(){
// each entity in the list has an edit button next to the title
// this method links to the edit button, resets the entity form
// and inserts all the Entity data in the form to be edited
$('#entityForm').trigger("reset");
$('#entityName').val(this.name);
$('#entityDescription').val(this.description);
_.contains(this.categories, "place") ? document.getElementById('check-place').checked = true : document.getElementById('check-place').checked = false;
_.contains(this.categories, "ngo") ? document.getElementById('check-ngo').checked = true : document.getElementById('check-place').checked = false;
_.contains(this.categories, "person") ? document.getElementById('check-person').checked = true : document.getElementById('check-place').checked = false;
}
});
|
var Locker = {
locks: {},
purgeTime: 3600 * 1000,
lock: function (page, user) {
var d = new Date()
this.locks[page] = {
user: user,
ts: d.getTime() + (d.getTimezoneOffset() * 60 * 1000)
}
},
unlock: function (page) {
delete this.locks[page]
},
getLock: function (page) {
return this.locks[page] ? this.locks[page] : null
},
reset: function () {
this.locks = {}
},
count: function () {
return Object.keys(this.locks).length
},
purge: function () {
var d = new Date()
var now = d.getTime() + (d.getTimezoneOffset() * 60 * 1000)
for (var page in this.locks) {
if ((now - this.locks[page].ts) > this.purgeTime) {
this.unlock(page)
}
}
}
}
setTimeout(function () {
Locker.purge()
}, 3600 * 1000)
module.exports = Locker
|
var ipc = require('ipc')
var TargetsCollection = require('./lib/TargetsCollection');
var app = angular.module('app', ['ngAnimate', 'ngMaterial', 'LocalStorageModule']);
var discoverUrl = 'http://localhost:9222/json'
app.config(function($mdThemingProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('blue')
.accentPalette('pink');
});
app.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('app');
});
app.filter('regex', function() {
return function(input, field, regex) {
var patt = new RegExp(regex);
var out = [];
if(input) {
for (var i = 0; i < input.length; i++){
if(patt.test(input[i][field])) {
out.push(input[i]);
}
}
}
return out;
};
});
app.directive('devtools', function() {
return {
restrict: 'E',
replace: true,
template: '<div class="devtools-wrapper"><iframe src="{{src}}"></iframe></div>',
scope: {
'src': '@',
},
link: function ($scope, element, attr) {
}
}
});
app.controller('home', function ($scope, $http, $location, localStorageService, $timeout, $mdDialog, $window) {
$scope.REDISCOVERY_DELAY = 500; // Half a second
$scope.filter = '^page$';
$scope.targetsFilterSelectedIndex = 1;
$scope.devtoolsUrl = '';
$scope.targets = new TargetsCollection();
$scope.connect = function(target) {
if(!target.devtoolsFrontendUrl) {
throw new Error("devtoolsFrontendUrl is missing");
}
var webSocketUrl = target.webSocketDebuggerUrl.replace(/(ws|wss)\:\/\//, '');
$scope.devtoolsUrl = 'devtools/front_end/inspector.html?ws=' + webSocketUrl + '&remoteFrontend=true';
}
$scope.setTargetFilter = function(filter) {
switch(filter) {
case 'apps':
$scope.filter = '^app$';
$scope.targetsFilterSelectedIndex = 0;
break;
case 'pages':
$scope.filter = '^page$';
$scope.targetsFilterSelectedIndex = 1;
break;
case 'background_page':
$scope.filter = '^background_page$';
$scope.targetsFilterSelectedIndex = 2;
break;
}
localStorageService.set('currentFilter', filter)
}
$scope.discover = function() {
var req = $http.get(discoverUrl);
req.success(function(data, status, headers, config) {
$scope.targets.clear();
data.forEach(function(item) {
$scope.targets.add(item.id, item);
});
});
req.catch(function() {
});
}
$scope.showTargets = function() {
$scope.devtoolsUrl = '';
}
$scope.showConnectPrompt = function(ev) {
$mdDialog.show({
controller: ConnectPromptController,
templateUrl: 'connectPrompt.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
})
.then(function(url) {
discoverUrl = url;
}, function() {
});
};
$scope.startDiscoveryChecks = function rediscover(){
$timeout(function(){
$scope.discover()
rediscover()
}, $scope.REDISCOVERY_DELAY)
}
// Initialize
$scope.discover();
// $scope.startDiscoveryChecks()
$scope.setTargetFilter(localStorageService.get('currentFilter') || 'pages')
});
function ConnectPromptController($scope, $mdDialog) {
$scope.url = 'http://localhost:9222';
$scope.cancel = function() {
$mdDialog.cancel();
}
$scope.connect = function(url) {
$mdDialog.hide(url);
}
}
|
module.exportts = {
"buffer": {
"type": "array"
},
"rms": {
"type": "number"
},
"energy": {
"type": "number"
},
"zcr": {
"type": "number"
},
"complexSpectrum": {
"type": "multipleArrays",
"arrayNames": {
"1": "real",
"2": "imag"
}
},
"amplitudeSpectrum": {
"type": "array"
},
"powerSpectrum": {
"type": "array"
},
"spectralCentroid": {
"type": "number"
},
"spectralFlatness": {
"type": "number"
},
"spectralSlope": {
"type": "number"
},
"spectralRolloff": {
"type": "number"
},
"spectralSpread": {
"type": "number"
},
"spectralSkewness": {
"type": "number"
},
"spectralKurtosis": {
"type": "number"
},
"loudness": {
"type": "multipleArrays",
"arrayNames": {
"1": "total",
"2": "specific"
}
},
"perceptualSpread": {
"type": "number"
},
"perceptualSharpness": {
"type": "number"
},
"mfcc": {
"type": "array"
}
};
|
var objectKit = require('objectkit').Ok;
var trevorObject = {
group: function groupValues(data, props) {
var chain = {};
if (typeof props === 'string') {
props = [props];
}
props.map(function(prop) {
chain[prop] = data.map(function(dataSet) {
return objectKit(dataSet).getIfExists(prop);
});
});
return chain;
},
reduce: function reduceValues(data, cbs) {
var reduced = {};
for (var prop in cbs) {
if (typeof data[prop] === 'undefined') {
reduced[prop] = null;
} else {
reduced[prop] = cbs[prop](data[prop]);
}
}
return reduced;
},
reduceAll: function reduceAllValue(data, cbs) {
return data.map(function(item) {
return trevorObject.reduce(item, cbs);
});
},
};
module.exports = trevorObject;
|
'use strict';
module.exports = function ctype_cntrl(text) {
// eslint-disable-line camelcase
// discuss at: http://locutus.io/php/ctype_cntrl/
// original by: Brett Zamir (http://brett-zamir.me)
// example 1: ctype_cntrl('\u0020')
// returns 1: false
// example 2: ctype_cntrl('\u001F')
// returns 2: true
var setlocale = require('../strings/setlocale');
if (typeof text !== 'string') {
return false;
}
// ensure setup of localization variables takes place
setlocale('LC_ALL', 0);
var $global = typeof window !== 'undefined' ? window : GLOBAL;
$global.$locutus = $global.$locutus || {};
var $locutus = $global.$locutus;
var p = $locutus.php;
return text.search(p.locales[p.localeCategories.LC_CTYPE].LC_CTYPE.ct) !== -1;
};
//# sourceMappingURL=ctype_cntrl.js.map
|
import React, {Component} from 'react';
import axios from 'axios';
import CompanyInfo from 'components/company-info';
export default class CategoryPage extends Component{
constructor(){
super();
this.state = {
companies: []
};
}
componentWillMount() {
axios.get(`/api/companies/category/${this.props.params.category}`)
.then(({data}) => this.setState({companies: data}))
.catch((err) => console.error(err))
}
render(){
const { companies } = this.state;
return (
<div className="company-list">
{companies.map((company, idx) =>
<CompanyInfo key={company.name} company={company} />
)}
</div>
);
}
}
|
'use strict';
angular.module('randomGeneratorApp')
.factory('User', function ($resource) {
return $resource('/api/users/:id/:controller', {
id: '@_id'
},
{
changePassword: {
method: 'PUT',
params: {
controller:'password'
}
},
get: {
method: 'GET',
params: {
id:'me'
}
}
});
});
|
require('./help.js');
require('./version.js');
|
Space.ui.BlazeComponent.extend('Donations.OpenAppealsPage', {
dependencies: {
store: 'Donations.OpenAppealsStore'
},
appeals() {
return this.store.appeals.find()
}
});
Donations.OpenAppealsPage.register('open_appeals_page');
|
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.SSCameraControl = function ( camera ) {
var scope = this;
camera.rotation.set( 0, 0, 0 );
var pitchObject = new THREE.Object3D();
pitchObject.add( camera );
var yawObject = new THREE.Object3D();
yawObject.position.y = 10;
yawObject.add( pitchObject );
var moveForward = false;
var moveBackward = false;
var moveLeft = false;
var moveRight = false;
var isOnObject = false;
var canJump = false;
var prevTime = performance.now();
var velocity = new THREE.Vector3();
var PI_2 = Math.PI / 2;
var onMouseMove = function ( event ) {
if ( scope.enabled === false ) return;
var movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
var movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;
yawObject.rotation.y -= movementX * 0.002;
pitchObject.rotation.x -= movementY * 0.002;
pitchObject.rotation.x = Math.max( - PI_2, Math.min( PI_2, pitchObject.rotation.x ) );
};
var onKeyDown = function ( event ) {
switch ( event.keyCode ) {
case 38: // up
case 87: // w
moveForward = true;
break;
case 37: // left
case 65: // a
moveLeft = true; break;
case 40: // down
case 83: // s
moveBackward = true;
break;
case 39: // right
case 68: // d
moveRight = true;
break;
case 32: // space
if ( canJump === true ) velocity.y += 350;
canJump = false;
break;
}
};
var onKeyUp = function ( event ) {
switch( event.keyCode ) {
case 38: // up
case 87: // w
moveForward = false;
break;
case 37: // left
case 65: // a
moveLeft = false;
break;
case 40: // down
case 83: // s
moveBackward = false;
break;
case 39: // right
case 68: // d
moveRight = false;
break;
}
};
document.addEventListener( 'mousemove', onMouseMove, false );
document.addEventListener( 'keydown', onKeyDown, false );
document.addEventListener( 'keyup', onKeyUp, false );
this.enabled = false;
this.getObject = function () {
return yawObject;
};
this.isOnObject = function ( boolean ) {
isOnObject = boolean;
canJump = boolean;
};
this.getDirection = function() {
// assumes the camera itself is not rotated
var direction = new THREE.Vector3( 0, 0, -1 );
var rotation = new THREE.Euler( 0, 0, 0, "YXZ" );
return function( v ) {
rotation.set( pitchObject.rotation.x, yawObject.rotation.y, 0 );
v.copy( direction ).applyEuler( rotation );
return v;
}
}();
this.update = function () {
if ( scope.enabled === false ) return;
var time = performance.now();
var delta = ( time - prevTime ) / 1000;
velocity.x -= velocity.x * 10.0 * delta;
velocity.z -= velocity.z * 10.0 * delta;
velocity.y -= 9.8 * 100.0 * delta; // 100.0 = mass
if ( moveForward ) velocity.z -= 400.0 * delta;
if ( moveBackward ) velocity.z += 400.0 * delta;
if ( moveLeft ) velocity.x -= 400.0 * delta;
if ( moveRight ) velocity.x += 400.0 * delta;
if ( isOnObject === true ) {
velocity.y = Math.max( 0, velocity.y );
}
yawObject.translateX( velocity.x * delta );
yawObject.translateY( velocity.y * delta );
yawObject.translateZ( velocity.z * delta );
if ( yawObject.position.y < 10 ) {
velocity.y = 0;
yawObject.position.y = 10;
canJump = true;
}
prevTime = time;
};
};
|
angular.module('ro.dropdown')
.directive('roDropdown', function() {
var instances = 0;
return {
restrict: 'EA',
replace: true,
transclude: true,
template: function(tElem, tAttrs) {
var tag = tAttrs.tagName || 'div';
var html = '<' + tag + ' class="dropdown" data-ng-transclude></' + tag + '>';
return html;
},
scope: true,
controller: ['$scope', '$element', function($scope, $element) {
var dropdown = this;
// increment instances to assign a unique id for aria-labelledby to use
dropdown.toggleId = 'ro-dropdown-toggle-' + (++instances);
var backdropHtml = '<div class="dropdown-backdrop"></div>';
dropdown.open = function() {
$element.addClass('open');
angular.element(backdropHtml)
.insertBefore($element.find('.dropdown-menu'))
.on('click touchstart', dropdown.close);
};
dropdown.close = function() {
angular.element('.dropdown-backdrop').remove();
$element.removeClass('open');
};
dropdown.isOpen = function() {
return $element.hasClass('open');
};
// store a selector for focusable elements
var focusable = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]';
$element.on('keydown', function(evt) {
if (evt.which !== 38 && evt.which !== 40) return;
var $target = angular.element(evt.target);
var $focusableItems;
// down arrow pressed when focusing dropdown-toggle
if ($target.is('.dropdown-toggle') && evt.which == 40) {
if (dropdown.isOpen()) {
$element.find('.dropdown-menu').find(focusable).first().trigger('focus');
} else {
dropdown.open();
}
} else {
// select all focusable items within dropdown-menu
$focusableItems = $element.find('.dropdown-menu').find(focusable);
var focusedIndex = $focusableItems.index(evt.target);
// default behavior is to focus the first item
var nextFocusedIndex = 0;
// if the target is in $focusableItems...
if (~focusedIndex) {
// up arrow focuses the previous item
if (evt.which == 38 && focusedIndex > 0) {
nextFocusedIndex = focusedIndex - 1;
}
// down arrow focuses the next item
if (evt.which == 40 && focusedIndex < $focusableItems.length - 1) {
nextFocusedIndex = focusedIndex + 1;
}
}
$focusableItems.eq(nextFocusedIndex).trigger('focus');
}
})
}],
controllerAs: 'dropdown'
};
})
|
import TooltipMessage from 'ember-cli-tooled/components/tooltip-message';
export default TooltipMessage;
|
$(document).on("keyup", ".list-input", function ( event ) {
var that = this;
var form = $(that).parents(".list-input-form");
$(form).find('input:text').filter(function() { return $(this).val() == ""; }).each( function ( index, element ) {
if ( $(element).get(0) != that ) {
$(element).parent("div").parent("div").parent("div").remove();
}
} );
if ( $(this).get(0) == $(form).find("input.list-input").last().get(0) && $(this).val() !== "" ) {
$(this).parent("div").parent("div").parent("div").after(returnElement(null, form));
}
} );
$(document).on("click", "button.remove-input", function () {
var element = $(this).parent("span").prev("input");
var form = $(element).parents(".list-input-form");
if ( $(element).attr("data-id") !== undefined ) {
if ( ! localStorage.getItem("tws_token") === false ) {
$.ajax({
type : "DELETE",
url : base_url + $(form).attr("data-item-endpoint") + $(element).attr("data-id") + "?token=" + localStorage.getItem("tws_token"),
}).success( function ( xhr, status, data ) {
alert(null, translations["admin_object_deleted"], "alertsSuccessTemplate", $("#errors"), "append", null, 2000);
} ).error( function ( xhr, status, data ) {
var response = $.parseJSON(xhr.responseText);
for ( var index in response.error_messages ) {
alert(null, response.error_messages[index] , "alertsErrorTemplate", $("#errors"), "append", null, 5000);
}
} );
} else {
alert(null, translations["admin_please_log_in"], "alertsErrorTemplate", $("#errors"), "append", null, 2000);
}
}
$(element).parent("div").parent("div").parent("div").remove();
if ( $(form).find('.list-input').last().val() != "" ) {
$(form).find('.list-input').last().parent("div").parent("div").parent("div").after(returnElement(null, form));
}
if ( $(form).find('.list-input').length == 0 ) {
$(form).find(".list-input-form").prepend(returnElement());
}
} );
$(document).on("submit", ".list-input-form", function ( event ) {
event.preventDefault();
var data = [];
var that = this;
$(this).find('.list-input').each( function ( index, element ) {
if ( ( $(element).attr("data-value") === undefined || $(element).attr('data-value') !== $(element).val() ) && $(element).val() != "" ) {
if ( $(element).attr("data-id") !== undefined ) {
data.push({
"id" : $(element).attr("data-id"),
"value" : $(element).val()
});
} else {
data.push({
"value" : $(element).val()
});
}
}
} );
if ( data.length > 0) {
if ( ! localStorage.getItem("tws_token") === false ) {
var arrayName = $(this).attr("data-array-name");
var post = {};
post[arrayName] = data;
$.ajax({
type : "POST",
url : base_url + $(this).attr("data-save-endpoint") + "?token=" + localStorage.getItem("tws_token"),
data : JSON.stringify(post),
contentType: "application/json",
dataType: "json"
}).success( function ( xhr, status, data ) {
alert(null, translations["admin_saved_successfully"], "alertsSuccessTemplate", $("#errors"), "append", null, 2000);
$("#alertsSuccessTemplateClone").bind("closed.bs.alert", function () {
if ( $(that).attr("data-ajax-url") !== undefined ) {
$.ajax({
url : base_url + $(that).attr("data-ajax-url")
}).success( function ( data ) {
$(that).replaceWith(data);
} ).error( function () {
window.location = window.location;
} );
} else {
window.location = window.location;
}
});
}).error( function () {
alert(null, translations["admin_duplicated"], "alertsErrorTemplate", $("#errors"), "append", null, 2000);
removeDuplicate();
$('.list-input').trigger("keyup");
} );
} else {
alert(null, translations["admin_please_log_in"], "alertsErrorTemplate", $("#errors"), "append", null, 2000);
}
}
} );
function returnElement ( after, form ) {
var classString = $(form).attr("data-input-class") || "col-sm-offset-4 col-sm-6";
var input = '<input type="text" class="form-control list-input" placeholder="' + $(form).attr("data-placeholder-text") + '">';
return '<div class="form-group">' +
'<div class="' + classString + '">' +
'<div class="input-group">' +
input +
'<span class="input-group-btn">' +
'<button class="btn btn-lg btn-danger button-addon remove-input" type="button">' + translations["admin_remove_string"] + '</button>' +
'</span>' +
'</div>' +
'</div>'+
'</div>';
}
function removeDuplicate ( values, second ) {
second = second || false;
values = values || [];
$(".list-input-form").each( function ( i, form ) {
$(form).find(".list-input").each( function ( index, element ) {
if ( $.inArray($(element).val(), values) ) {
if ( $(element).attr("data-id") === undefined ) {
$(element).parent("div").parent("div").parent("div").remove();
} else {
if ( ! second ) {
removeDuplicate(values, true);
}
}
} else {
values.push($(element).val());
}
} );
$('.list-input').trigger("keyup");
} );
}
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { ScheduleColumn } from './ScheduleColumn';
class DayView extends Component {
render() {
const {
dayViewing,
startTime,
endTime,
ripTime,
changeDragged,
draggedSession,
sessions,
tracks,
previewSlots,
rooms,
slots,
handleMoveSessionResponse,
unscheduledSessions,
sessionFormats,
showErrors,
} = this.props;
let rows = rooms.map((room) => {
const height = (endTime - startTime + 1) * 90 + 25 + 'px';
return (
<ScheduleColumn
key={'day' + dayViewing + 'room' + room.id}
height={height}
room={room}
startTime={startTime}
endTime={endTime}
ripTime={ripTime}
dayViewing={dayViewing}
changeDragged={changeDragged}
draggedSession={draggedSession}
sessions={sessions}
tracks={tracks}
previewSlots={previewSlots}
slots={slots}
handleMoveSessionResponse={handleMoveSessionResponse}
unscheduledSessions={unscheduledSessions}
sessionFormats={sessionFormats}
showErrors={showErrors}
/>
);
});
return <React.Fragment>{rows}</React.Fragment>;
}
}
DayView.propTypes = {
schedule: PropTypes.object,
dayViewing: PropTypes.number,
startTime: PropTypes.number,
endTime: PropTypes.number,
ripTime: PropTypes.func,
changeDragged: PropTypes.func,
draggedSession: PropTypes.object,
sessions: PropTypes.array,
tracks: PropTypes.array,
previewSlots: PropTypes.array,
handleMoveSessionResponse: PropTypes.func,
unscheduledSessions: PropTypes.array,
sessionFormats: PropTypes.array,
showErrors: PropTypes.func,
};
DayView.defaultProps = { sessions: [] };
export { DayView };
|
var xmpp = require('node-xmpp-server');
var ltx = require('node-xmpp-core').ltx;
var events = require('events');
var HangManServer = function (settings)
{
var r = new xmpp.Router();
var emitter = new events.EventEmitter();
r.register(settings.domain, function (stanza)
{
emitter.emit('message',stanza);
});
this.on = function ()
{
emitter.on.apply(emitter, arguments);
};
this.once = function ()
{
emitter.once.apply(emitter, arguments);
};
this.removeListener = function ()
{
emitter.removeListener.apply(emitter, arguments);
};
};
module.exports = {
HangManServer: HangManServer
}
|
#!/usr/bin/env node
const assert = require('assert');
const path = require('path');
assert.equal(process.argv.length, 4);
assert.equal(process.argv[1], __filename);
assert.equal(process.argv[2].indexOf(path.resolve(__dirname, 'testdir/test-')),
0);
assert.equal(process.argv[3], 'aaa');
|
/**
* Created by jiangyun on 16/8/30.
*/
(function () {
'use strict';
angular
.module('core')
.config(exceptionConfig);
exceptionConfig.$inject = ['$provide'];
function exceptionConfig($provide) {
$provide.decorator('$exceptionHandler', extendExceptionHandler);
}
extendExceptionHandler.$inject = ['$delegate'];
function extendExceptionHandler($delegate) {
return function (exception, cause) {
$delegate(exception, cause);
var errorData = {
exception: exception,
cause: cause
};
/**
* Could add the error to a service's collection,
* add errors to $rootScope, log errors to remote web server,
* or log locally. Or throw hard. It is entirely up to you.
* throw exception;
*/
//toastr.error(exception.msg, errorData);
};
}
}());
|
export default function email(value) {
if(value === undefined || value === null || value.length === 0) {
return false;
}
if(value.indexOf('@') === -1) {
return false;
}
if(value.length < 5 || value.length > 254) {
return false;
}
const simpleEmailRegex = /\S+@\S+/;
if(!simpleEmailRegex.test(value)) {
return false;
}
return true;
};
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var META_TAGS = ['title', 'subtitle'];
var ALIASES = {
t: 'title',
st: 'subtitle'
};
var translateTagNameAlias = function translateTagNameAlias(name) {
if (name in ALIASES) {
return ALIASES[name];
}
return name;
};
var Tag = function () {
function Tag(name, value) {
_classCallCheck(this, Tag);
this.name = name;
this.value = value;
}
_createClass(Tag, [{
key: 'hasValue',
value: function hasValue() {
return !!this._value.trim().length;
}
}, {
key: 'isMetaTag',
value: function isMetaTag() {
return META_TAGS.indexOf(this.name) !== -1;
}
}, {
key: 'name',
set: function set(name) {
this._name = translateTagNameAlias(name);
this._originalName = name;
},
get: function get() {
return this._name.trim();
}
}, {
key: 'originalName',
get: function get() {
return this._originalName.trim();
}
}, {
key: 'value',
set: function set(value) {
this._value = value;
},
get: function get() {
return this._value.trim();
}
}]);
return Tag;
}();
exports.default = Tag;
|
module.exports = {
up: function(migration, DataTypes, done) {
// add altering commands here
migration.addColumn('Jobs', 'lastNotifiedProgress', { type: Sequelize.FLOAT, defaultValue: 0.0 }).complete(done);
},
down: function(migration, DataTypes, done) {
// add reverting commands here
migration.removeColumn('Jobs', 'lastNotifiedProgress').complete(done);
}
}
|
var path = require('path');
var http = require('http');
var express = require('express');
const WebSocket = require('uws');
var app = express();
var server = http.createServer(app);
var ROOT_DIR = 'public';
var port = process.env.PORT || 3000;
app.use('/', express.static(path.join(__dirname, ROOT_DIR)));
const wss = new WebSocket.Server({server});
var Game = require('./server/Game.js');
let game = new Game();
let socketCount = 0;
wss.on('connection', (ws) => {
ws.id = socketCount++;
console.log(`Client ${ws.id} connected`);
game.addPlayer(ws.id);
ws.send(JSON.stringify({type: 'init', payload: {id: ws.id, players: game.players}}));
wss.clients.forEach((client) => client.send(JSON.stringify({
type: 'newPlayer', payload: {id: ws.id, player: game.players[ws.id]}
})));
ws.on('close', () => {
console.log(`Client ${ws.id} disconnected`);
game.removePlayer(ws.id);
wss.clients.forEach((client) => client.send(JSON.stringify({
type: 'removePlayer', payload: {id: ws.id}
})));
});
ws.on('message', (message) => {
let msg = JSON.parse(message);
switch(msg.type) {
case 'update':
game.updatePlayer(ws.id, msg.payload);
let temp = game.players[ws.id];
temp.id = ws.id;
let updateMsg = JSON.stringify({type: 'update', payload: temp});
wss.clients.forEach((client) => client.send(updateMsg));
break;
}
});
});
server.listen(port, function() {
console.log(`listening on port ${port}`);
});
|
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', {title: '登录系统'});
});
router.route("/login").get(function (req, res) {
res.render("login", {title: "Use Login"});
}).post(function (req, res) {
var User = global.dbHandel.getModel('user');
var uname = req.body.uname;
User.findOne({name: uname}, function (err, doc) {
if (err) {
res.send(500);
console.log(err);
} else if (!doc) {
req.session.error = '用户名不存在';
res.send(404);
} else {
if (req.body.upwd != doc.password) {
req.session.error = "密码错误";
res.send(404);
} else {
req.session.user = doc;
res.send(200);
}
}
});
});
router.route("/register").get(function (req, res) {
res.render("register", {title: "User register"});
}).post(function (req, res) {
var User = global.dbHandel.getModel('user');
var uname = req.body.uname;
var upwd = req.body.upwd;
User.findOne({name: uname}, function (err, doc) {
if (err) {
res.send(500);
req.session.error = "网络异常错误!";
console.log(err);
} else if (doc) {
req.session.error = "用户名已存在!";
res.send(500);
} else {
User.create({
name: uname,
password: upwd
}, function (err, doc) {
if (err) {
res.send(500);
console.log(err);
} else {
req.session.error = "用户名创建成功!"
res.send(200);
}
});
}
});
})
router.get("/home", function (req, res) {
if (!req.session.user) {
req.session.error = "请先登录";
res.redirect("/login");
}
res.render("home", {title: "Home"});
});
router.get("/logout", function (req, res) {
req.session.user = null;
req.session.error = null;
res.redirect("/");
});
module.exports = router;
|
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
const { Object, RSVP } = Ember;
const { resolve } = RSVP;
moduleForComponent('learnergroup-header', 'Integration | Component | learnergroup header', {
integration: true
});
test('it renders', function(assert) {
let learnerGroup = Object.create({
title: 'our group',
allParents: resolve([{title: 'parent group'}])
});
this.set('learnerGroup', learnerGroup);
this.render(hbs`{{learnergroup-header learnerGroup=learnerGroup}}`);
assert.equal(this.$('h2').text().trim(), 'our group');
assert.equal(this.$('.breadcrumbs').text().replace(/\s/g,''), 'LearnerGroupsparentgroupourgroup');
});
test('can change title', function(assert) {
let learnerGroup = Object.create({
title: 'our group',
save(){
assert.equal(this.get('title'), 'new title');
}
});
this.set('learnerGroup', learnerGroup);
this.render(hbs`{{learnergroup-header learnerGroup=learnerGroup}}`);
assert.equal(this.$('h2').text().trim(), 'our group');
this.$('h2 .editable').click();
this.$('h2 input').val('new title');
this.$('h2 input').trigger('change');
this.$('h2 .done').click();
});
test('counts members correctly', function(assert) {
let cohort = Object.create({
title: 'test group',
users: [1, 2]
});
let subGroup = Object.create({
title: 'test sub-group',
users: [],
children: [],
});
let learnerGroup = Object.create({
title: 'test group',
usersOnlyAtThisLevel: [1],
cohort,
children: resolve([subGroup])
});
this.set('learnerGroup', learnerGroup);
this.render(hbs`{{learnergroup-header learnerGroup=learnerGroup}}`);
assert.equal(this.$('.detail-header .info').text().trim(), 'Members: 1 / 2');
});
|
var React = require('react-native')
var {
ListView,
ActivityIndicatorIOS,
StyleSheet,
View,
Text,
PropTypes,
} = React
var isPromise = require('is-promise')
// must be less than ~50px due to ScrollView bug (event only fires once)
// https://github.com/facebook/react-native/pull/452
// TODO: expose as a prop when onScroll works properly
var PULLDOWN_DISTANCE = 40 // pixels
var RefreshableListView = React.createClass({
propTypes: {
onScroll: PropTypes.func,
loadData: PropTypes.func.isRequired,
minDisplayTime: PropTypes.number,
activityIndicatorComponent: PropTypes.func,
stylesheet: PropTypes.object,
refreshDescription: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
},
getDefaultProps() {
return {
activityIndicatorComponent: ActivityIndicatorIOS,
minDisplayTime: 300,
}
},
getInitialState() {
return {
reloading: false,
}
},
handleScroll(e) {
if (e.nativeEvent.contentOffset.y < -PULLDOWN_DISTANCE) {
this.reloadData()
}
this.props.onScroll && this.props.onScroll(e)
},
reloadData() {
if (this.willReload || this.state.reloading) return
this.willReload = true
var loadingDataPromise = new Promise((resolve) => {
var loadDataReturnValue = this.props.loadData(resolve)
if (isPromise(loadDataReturnValue)) {
loadingDataPromise = loadDataReturnValue
}
Promise.all([
loadingDataPromise,
new Promise((resolve) => this.setState({reloading: true}, resolve)),
new Promise((resolve) => setTimeout(resolve, this.props.minDisplayTime)),
]).then(([data]) => {
this.willReload = false
this.setState({reloading: false})
})
})
},
renderHeader() {
if (this.state.reloading) {
var styles = Object.assign({}, baseStyles, this.props.stylesheet)
var ActivityIndicator = this.props.activityIndicatorComponent
return (
<View style={[styles.container, styles.wrapper]}>
<View style={[styles.container, styles.loading]}>
<Text style={styles.description}>
{this.props.refreshDescription}
</Text>
<ActivityIndicator style={styles.activityIndicator} />
</View>
</View>
)
} else {
return null
}
},
getScrollResponder() {
return this.refs.listview
},
setNativeProps(props) {
this.refs.listview.setNativeProps(props)
},
render() {
return (
<ListView
{...this.props}
ref="listview"
onScroll={this.handleScroll}
renderHeader={this.renderHeader}
/>
)
},
})
var baseStyles = StyleSheet.create({
wrapper: {
height: 60,
marginTop: 10,
},
container: {
flex: 1,
justifyContent: 'space-around',
alignItems: 'center',
backgroundColor: 'white',
},
loading: {
height: 60,
},
})
RefreshableListView.DataSource = ListView.DataSource
module.exports = RefreshableListView
|
var start= new Date()
, fs = require('fs')
, beautify_html = require('js-beautify').html
, ent = require('ent')
, dust = require('dustjs-linkedin')
, templates = require("./docs/doc-templates")(dust);
//disable whitespace compression
dust.optimizers.format = function(ctx, node) { return node };
var files = ['static/multiple-choice.html',
'static/text-input.html',
'static/code-input.html'];
// create slides for each question
var slides=""
, sId = zeroPad(3,2) //start from number 3
, x = 3000;
files.forEach(function(file){
var question = fs.readFileSync(file, "utf-8");
//open slide tag
slides += '\r\n\r\n<section class="step" id="slide' + sId +'"\
data-x="'+ x+'" data-y="0" data-z="1000">';
slides += question;
//close slide tag
slides += '</section>';
x += 1500;
});
// append questions to single page demo
dust.render("all", {questionSlides:slides}, function(err, out){
if (err) throw err;
// make html pretty
var html = beautify_html(out, {
indent_size: 2 ,
preserve_newlines: true,
indent_inner_html: true });
//restore html entities escaped from beautify
html = ent.decode(html);
//save presentation
fs.writeFile('docs/all.html', html, function (err) {
if (err) return console.error('could not write', err.stack);
console.log("Single page generated in %s ms", new Date - start)
});
})
// append slides to demo presentation
dust.render("impress-demo", {questionSlides:slides}, function(err, out){
if (err) throw err;
// make html pretty
var html = beautify_html(out, {
indent_size: 2 ,
preserve_newlines: true,
indent_inner_html: true });
//restore html entities escaped from beautify
html = ent.decode(html);
//save presentation
fs.writeFile('docs/impress-demo.html', html, function (err) {
if (err) return console.error('could not write', err.stack);
console.log("Presentation generated in %s ms", new Date - start)
});
})
// adds zeros to reach the required width
// zeroPad(13, 4) => 0013
function zeroPad(number , width){
var n_ = Math.abs(number);
var zeros = Math.max(0, width - Math.floor(n_).toString().length );
var zeroString = Math.pow(10,zeros).toString().substr(1);
if( number < 0 ) {
zeroString = '-' + zeroString;
}
return zeroString+number;
}
|
/*global exports, require, process*/
(function (exports, require, process) {
"use strict";
exports.testSimplePage = function (test) {
var fs = require("fs"),
validate = require("../lib/vnu-angular").validate;
fs.readFile("./tests/data/simplePage.html", function (err, data) {
if (err) {
throw err;
}
validate(data.toString(), function (validationErr, result) {
if (validationErr) {
throw validationErr;
}
test.equal(
result.length,
0,
"Assessment result should be an empty list"
);
test.done();
}, process.env.VNU_BIN);
});
};
}(exports, require, process));
|
require('../')(
{
pattern:'coverage/*/coverage-final.json',
reporters:{
html:{},
json:{}
}
},
function(err){
if(err) throw err;
console.log("***********ASYNC COMPLETE*********");
}
);
console.log("*********STARTING SYNC**************");
require('../').sync({
pattern:'coverage/*/coverage-final.json',
reporters:{
html:{},
json:{}
}
});
console.log("***********SYNC COMPLETE**************");
|
// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-phantomjs-launcher'),
require('karma-spec-reporter'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
files: [
{ pattern: './src/assets/**/*.*', watched: false, included: false }
],
proxies: {
'/assets/': '/base/src/assets/'
},
preprocessors: {
},
mime: {
'text/x-typescript': ['ts','tsx']
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, 'coverage'), reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
reporters: process.env.CODECOV
? ['spec', 'coverage-istanbul']
: ['spec', 'kjhtml'],
specReporter: {
maxLogLines: 5,
suppressErrorSummary: true,
suppressFailed: false,
suppressPassed: false,
suppressSkipped: true,
showSpecTiming: false
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: [process.env.PHANTOM ? 'PhantomJS' : 'Chrome'],
singleRun: false
});
};
|
'use strict';
angular.module('mean.links').controller('LinksController', ['$scope', '$stateParams', '$location', 'Global', 'Links',
function($scope, $stateParams, $location, Global, Links) {
$scope.global = Global;
$scope.hasAuthorization = function(link) {
if (!link || !link.user) return false;
return $scope.global.isAdmin || link.user._id === $scope.global.user._id;
};
$scope.create = function(isValid) {
if (isValid) {
var link = new Links({
label: this.label,
link: this.link
});
link.$save(function(response) {
$location.path('links/' + response._id);
});
this.label = '';
this.link = '';
} else {
$scope.submitted = true;
}
};
$scope.remove = function(link) {
if (link) {
link.$remove();
for (var i in $scope.links) {
if ($scope.links[i] === link) {
$scope.links.splice(i, 1);
}
}
} else {
$scope.link.$remove(function(response) {
$location.path('links');
});
}
};
$scope.update = function(isValid) {
if (isValid) {
var link = $scope.link;
if (!link.updated) {
link.updated = [];
}
link.updated.push(new Date().getTime());
link.$update(function() {
$location.path('links/' + link._id);
});
} else {
$scope.submitted = true;
}
};
$scope.find = function() {
Links.query(function(links) {
$scope.links = links;
});
};
$scope.findOne = function() {
Links.get({
linkId: $stateParams.linkId
}, function(link) {
$scope.link = link;
});
};
}
]);
|
import React, { Component } from 'react';
import PropTypes from 'utils/PropTypes';
import ContextButton from 'components/ContextButton';
import { Modal } from 'antd';
import { isFunction } from 'utils/fp';
export default class ConfirmButton extends Component {
static propTypes = {
title: PropTypes.stringOrFunc.isRequired,
content: PropTypes.stringOrFunc,
onOk: PropTypes.func,
okText: PropTypes.string,
method: PropTypes.string,
};
static defaultProps = {
okText: 'OK',
};
_handleClick = (ev, actions) => {
const { title, content, onOk, okText, method } = this.props;
ev.preventDefault();
Modal.confirm({
title: isFunction(title) ? title(actions.getData()) : title,
content: isFunction(content) ? content(actions.getData()) : content,
okText,
onOk: () => {
if (onOk) { onOk(actions); }
if (method) {
actions.store.call(method, {
method: 'POST',
keys: actions.selectedKeys,
});
}
}
});
};
render() {
const {
title, content, onOk, okText, method,
...other
} = this.props;
return (
<ContextButton
{...other}
onClick={this._handleClick}
/>
);
}
}
|
/*
* index.js
* Copyright (C) 2017 jkirchartz <me@jkirchartz.com>
*
* Distributed under terms of the NPL (Necessary Public License) license.
*/
module.exports = require('./dist/gleech');
|
import { isFunction, isObject, isUndefined, toNode, toNodes } from './lang';
export function attr(element, name, value) {
if (isObject(name)) {
for (const key in name) {
attr(element, key, name[key]);
}
return;
}
if (isUndefined(value)) {
return toNode(element)?.getAttribute(name);
} else {
for (const el of toNodes(element)) {
if (isFunction(value)) {
value = value.call(el, attr(el, name));
}
if (value === null) {
removeAttr(el, name);
} else {
el.setAttribute(name, value);
}
}
}
}
export function hasAttr(element, name) {
return toNodes(element).some((element) => element.hasAttribute(name));
}
export function removeAttr(element, name) {
const elements = toNodes(element);
for (const attribute of name.split(' ')) {
for (const element of elements) {
element.removeAttribute(attribute);
}
}
}
export function data(element, attribute) {
for (const name of [attribute, `data-${attribute}`]) {
if (hasAttr(element, name)) {
return attr(element, name);
}
}
}
|
$( document ).ready(function() {
// mailchimp form submission
$("#mc-form").formchimp({
// sucesss
// error
});
//show hide on sucsess
$( document ).on( 'mailChimpSuccess', function() {
$('#mc-form').hide();
$('.sucsess').css('visibility','visible').hide().fadeIn('slow');
});
});
|
/**
* React Components & Router
*/
import React from 'react';
import {Router, Route, hashHistory} from 'react-router';
import ReactDom from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import Main from './container/main';
var $ = function(f){
document.addEventListener('DOMContentLoaded', f, false);
};
$(()=> {
injectTapEventPlugin();
ReactDom.render(
<Main/>,
document.getElementById('jobads-webapp')
);
});
|
const path = require('path');
const nconf = require('nconf');
const bodyParser = require('body-parser');
const uuid = require('node-uuid');
const morgan = require('morgan');
const Express = require('express');
const ArmClient = require('armclient');
const Queue = require('./lib/queue');
const logger = require('./lib/logger');
// Initialize configuration.
nconf.argv()
.env()
.file({ file: './config.json' })
.defaults({
NODE_ENV: 'development',
PORT: 3500
});
// ARM client.
const armClient = ArmClient({
subscriptionId: nconf.get('SUBSCRIPTION_ID'),
auth: ArmClient.clientCredentials({
tenantId: nconf.get('TENANT_ID'),
clientId: nconf.get('CLIENT_ID'),
clientSecret: nconf.get('CLIENT_SECRET')
})
});
// Runbook queue.
const queue = Queue(nconf.get('STORAGE_ACCOUNT'), nconf.get('STORAGE_ACCOUNT_KEY'), 'azure-runslash-jobs');
queue.create()
.catch((err) => {
throw err;
});
// Helper method to execute a runbook.
const executeRunbook = (channel, requestedBy, name, params) => {
const jobId = uuid.v4();
const request = {
properties: {
runbook: {
name
},
parameters: {
context: JSON.stringify(params),
MicrosoftApplicationManagementStartedBy: "\"azure-runslash\"",
MicrosoftApplicationManagementRequestedBy: `\"${requestedBy}\"`
}
},
tags: {}
};
return queue.send({ posted: new Date(), jobId: jobId, channel: channel, requestedBy: requestedBy, runbook: name })
.then(() => {
return armClient.provider(nconf.get('RESOURCE_GROUP'), 'Microsoft.Automation')
.put(`/automationAccounts/${nconf.get('AUTOMATION_ACCOUNT')}/Jobs/${jobId}`, { 'api-version': '2015-10-31' }, request);
});
};
// Initialize the app.
const app = new Express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan(':method :url :status :response-time ms - :res[content-length]', {
stream: logger.stream
}));
app.post('/execute', (req, res) => {
if (!req.body) {
return res.send(400);
}
if (req.body.token != nconf.get('SLACK_TOKEN')) {
return res.status(401).send({ message: 'Invalid Slack token' });
}
// Runbook name is required.
if (!req.body.text || req.body.text.length === 0) {
return res.send({
response_type: "in_channel",
attachments: [{
color: '#F35A00',
fallback: `Unable to execute Azure Automation Runbook: The runbook name is required.`,
text: `Unable to execute Azure Automation Runbook: The runbook name is required.`
}]
});
}
// Collect information.
const input = req.body.text.trim().split(' ');
const runbook = input[0];
const params = input.splice(1);
// Execute the runbook.
executeRunbook(`#${req.body.channel_name}`, req.body.user_name, runbook, params)
.then((data) => {
const subscriptionsUrl = 'https://portal.azure.com/#resource/subscriptions';
const runbookUrl = `${subscriptionsUrl}/${nconf.get('SUBSCRIPTION_ID')}/resourceGroups/${nconf.get('RESOURCE_GROUP')}/providers/Microsoft.Automation/automationAccounts/${nconf.get('AUTOMATION_ACCOUNT')}/runbooks/${runbook}`;
res.send({
response_type: 'in_channel',
attachments: [{
color: '#00BCF2',
mrkdwn_in: ['text'],
fallback: `Azure Automation Runbook ${runbook} has been queued.`,
text: `Azure Automation Runbook *${runbook}* has been queued (<${runbookUrl}|Open Runbook>).`,
fields: [
{ 'title': 'Automation Account', 'value': nconf.get('AUTOMATION_ACCOUNT'), 'short': true },
{ 'title': 'Runbook', 'value': runbook, 'short': true },
{ 'title': 'Job ID', 'value': data.body.properties.jobId, 'short': true },
{ 'title': 'Parameters', 'value': `"${params.join('", "')}"`, 'short': true },
],
}]
});
})
.catch((err) => {
if (err) {
logger.error(err);
}
res.send({
response_type: 'in_channel',
attachments: [{
color: '#F35A00',
fallback: `Unable to execute Azure Automation Runbook: ${err.message || err.details && err.details.message || err.status}.`,
text: `Unable to execute Azure Automation Runbook: ${err.message || err.details && err.details.message || err.status}.`
}]
});
});
})
// Start the server.
app.listen(nconf.get('PORT'), (error) => {
if (error) {
logger.error(error);
} else {
logger.info('Listening on http://localhost:' + nconf.get('PORT'));
}
});
|
'use strict';
import angular from 'angular';
import Controller from '../../account/controller';
import moment from 'moment';
moment.locale('pt-br');
export default class LeadController extends Controller {
/*@ngInject*/
constructor($window, $scope, toastr, LeadService, usSpinnerService) {
super($window, $scope, toastr, usSpinnerService);
this.LeadService = LeadService;
this.LeadService.loadLeadList()
.then(leads => {
this.leads = leads;
this.formatMoment();
})
.catch(err => {
console.log('Ex:', err);
})
.finally(() => {
usSpinnerService.stop('spinner-1');
});
this.status = '';
this.viewDetails = false;
}
findLeadListStatus(status) {
this.status = status;
this.usSpinnerService.spin('spinner-1');
this.LeadService.loadLeadList({
status,
})
.then(leads => {
//this.toastr.success('', `Leads ${status} (${leads.length})`);
this.leads = leads;
this.formatMoment();
})
.catch(err => {
console.log('Ex:', err);
})
.finally(() => {
this.usSpinnerService.stop('spinner-1');
});
}
formatMoment() {
this.leads.forEach(item => {
item.createdAt = moment(item.createdAt).fromNow();
});
}
isActive(status) {
return status === this.status;
}
}
|
'use strict';
eventsApp.directive('mySample', function($compile) {
return {
restrict: 'AEC', //jf Attribute, Element <my-sample />, CLass <div class="my-sample" />, M Comment
template: "<input type='text' ng-model='sampleData' /> {{sampleData}} <br/>",
scope: {
}
};
});
|
"use strict";
import _ from 'lodash';
import { Router } from 'express';
import model from './../model';
import post from './post';
import put from './put';
import del from './delete';
import patch from './patch';
import { get, getAll } from './get';
const getRouter = (_conn, url, params, enableOdataSyntax) => {
let options = params.options || {};
let rest = params.rest || {};
let actions = params.actions || {};
let resourceURL = `/${url}`;
let entityURL = `${resourceURL}\\(:id\\)`;
let routes = [
{
method: 'post',
url: resourceURL,
controller: post,
config: rest.post || {},
},
{
method: 'put',
url: entityURL,
controller: put,
config: rest.put || {},
},
{
method: 'patch',
url: entityURL,
controller: patch,
config: rest.patch || {},
},
{
method: 'delete',
url: entityURL,
controller: del,
config: rest.delete || rest.del || {},
},
{
method: 'get',
url: entityURL,
controller: get,
config: rest.get || {},
},
{
method: 'get',
url: resourceURL,
controller: getAll,
config: rest.getAll || {},
},
];
let mongooseModel = model.get(_conn, url);
/*jshint -W064 */
let router = Router();
routes.map((route) => {
router[route.method](route.url, (req, res, next) => {
if (checkAuth(route.config.auth, req)) {
//TODO: should run controller func after before done. [use app.post(url, auth, before, fn, after)]
if (route.config.before) {
if (route.method === 'post') {
route.config.before(req.body);
} else {
mongooseModel.findOne({ _id: req.params.id }, (err, entity) => {
if (err) {
return;
}
route.config.before(entity);
});
}
}
route.controller(req, mongooseModel, options).then((result = {}) => {
res.status(result.status || 200);
if (result.text) {
res.send(result.text);
}
else if (result.entity) {
res.jsonp(result.entity);
}
else {
res.end();
}
if (route.config.after) {
route.config.after(result.entity, result.originEntity);
}
}, (err) => {
if (err.status) {
res.status(err.status).send(err.text || '');
}
else {
next(err);
}
});
}
else {
res.status(401).end();
}
});
});
for(let actionUrl in actions) {
let action = actions[actionUrl];
((actionUrl, action) => {
let fullUrl = `${entityURL}${actionUrl}`;
router.post(fullUrl, (req, res, next) => {
if(checkAuth(action.auth)) {
action(req, res, next);
}
else {
res.status(401).end();
}
});
})(actionUrl, action);
}
return router;
};
const checkAuth = (auth, req) => {
if (!auth) {
return true;
}
return auth(req);
};
export default { getRouter };
|
var router = require('express').Router();
var mongoose = require('mongoose');
var User = require('../../../lib/models/user/user.model');
var Errors = require('../../../lib/errors');
var redirector = require('../../../lib/redirector');
router
.get('/sign-up', function(req,res,next){
res.render('signup.jade');
})
.post('/sign-up', function(req,res,next){
req.assert('firstName', 'First name required').notEmpty();
req.assert('lastName', 'Last name required').notEmpty();
req.assert('email', 'Email address required').notEmpty();
req.assert('email', 'Valid email required').isEmail();
req.assert('password', 'Password must be 6 to 20').len(6, 20);
var errors = req.validationErrors();
if (errors) {
return res
.status(400)
.render('signup.jade', {
validationError: true,
errors: errors,
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email
});
}
var user = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email
});
user._auth.local = req.body.password;
user.save(function (err, doc) {
if (err){
// Email might already be taken...
if (err instanceof mongoose.Error.ValidationError) {
if (err.errors.email &&
err.errors.email instanceof mongoose.Error.ValidatorError &&
err.errors.email.type === 'unique') {
return res
.status(400)
.render('signup.jade', {
validationError: true,
errors: [{msg: 'Email is already registered'}],
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email
});
}
}
// Some other error occured, let the central err middleware handle it
return next(err);
}
return redirector().redirect(doc, req, res, next);
});
});
module.exports = exports = router;
|
import fetch from 'isomorphic-fetch';
import {equal} from 'assert';
import {start, stop} from '../lib';
describe('Subkit server integration tests', () => {
let url = null;
before(() => start({logStyle: 'none'}).then(x => (url = x.url)));
after(() => stop());
it('Response with 200', async () => {
const res = await fetch(url, {
method: 'POST',
headers: {'content-type': 'application/json'},
body: JSON.stringify({
query: `{
items {
id
}
}`,
variables: null,
operationName: null
})
});
equal(res.status, 200);
});
});
|
var Icon = require('../icon');
var element = require('magic-virtual-element');
var clone = require('../clone');
exports.render = function render(component) {
var props = clone(component.props);
delete props.children;
return element(
Icon,
props,
element('path', { d: 'M12 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 7h-6v13h-2v-6h-2v6H9V9H3V7h18v2z' })
);
};
|
/**
* AuthController
*
* @description :: Server-side logic for managing auths
* @help :: See http://links.sailsjs.org/docs/controllers
*/
var passport = require('passport');
module.exports = {
/**
* `AuthController.login()`
*/
login: function (req, res) {
if (req.session.authenticated) { return res.redirect('/chat') }
// ログイン画面表示
return res.view();
},
/**
* `AuthController.process()`
*/
//ログイン認証処理
process: function (req, res) {
passport.authenticate('local', function(err, user, info) {
console.log(info);
if ((err) || (!user)) {
return res.send({
message: 'login failed'
});
}
// req.isAuthenticated() -> false
// req.user -> undefined
req.logIn(user, function(err) {
if (err) res.send(err);
// req.isAuthenticated() -> true
// req.user -> user -> When new LocalStrategy, Callback user Object
req.session.authenticated = req.isAuthenticated();
return res.redirect("/chat");
});
})(req, res);
},
/**
* `AuthController.logout()`
*/
logout: function (req, res) {
// ログイン状態解
req.logout();
req.session.destroy();
return res.redirect('/');
},
/**
* `AuthController.signup()`
*/
signup: function (req, res) {
return res.view();
}
};
|
/// <reference path="../../../Code/RequireJS/require.js" />
window.chutzpah.preventAutoStart();
requirejs(['base/core', 'ui/screen'],
function (core, screen) {
describe("base/core", function () {
it("will return correct version from core", function () {
var version = core.version;
expect(version).toEqual(8);
});
});
describe("ui/screen", function () {
it("will build display version", function () {
var disp = screen.displayVersion;
expect(disp).toEqual("Version: 8");
});
});
window.chutzpah.start();
});
|
'use strict';
module.exports = function(app) {
// Root routing
var core = require('../../app/controllers/core.server.controller');
app.route('/')
.get(core.index);
app.route('/search').get(core.search);
app.route('/nextsearch').get(core.nextsearch);
};
|
/**
* Scale children based on audio frequency levels.
*/
AFRAME.registerComponent('audioanalyser-levels-scale', {
schema: {
analyserEl: {type: 'selector'},
max: {default: 20},
multiplier: {default: 100}
},
tick: function (time) {
var analyserEl;
var children;
var data = this.data;
var levels;
analyserEl = data.analyserEl || this.el;
levels = analyserEl.components.audioanalyser.levels;
if (!levels) { return; }
children = this.el.children;
for (var i = 0; i < children.length; i++) {
children[i].setAttribute('scale', {
x: 0.85,
y: Math.min(data.max, Math.max(levels[i] * data.multiplier, 0.05)),
z: 0.85
});
}
}
});
|
var gulp = require("gulp");
var runSeq = require("run-sequence");
var typescript = require("typescript");
var tsc = require("gulp-typescript");
var sourcemaps = require("gulp-sourcemaps");
var plumber = require("gulp-plumber");
var sass = require("gulp-sass");
var paths = require("../paths");
gulp.task("build", (cb) => {
return runSeq(
["compile:ts", "compile:sass", "html", "copy:imgs"],
cb);
});
gulp.task("rebuild", (cb) => {
return runSeq(
"clean",
"build",
cb);
});
// scripts
gulp.task("compile:ts", () => {
var tsProject = getTscProject();
var tsResult = gulp.src([paths.src.typings, paths.src.ts])
.pipe(plumber())
//.pipe(changed(paths.output.dist, { extension: ".js" }))
.pipe(sourcemaps.init())
.pipe(tsc(tsProject));
return tsResult.js
.pipe(sourcemaps.write("."))
.pipe(gulp.dest(`${paths.output.dist}`));
});
function getTscProject() {
return tsc.createProject("tsconfig.json", {
sortOutput: true,
typescript: typescript
});
}
// sass
gulp.task("compile:sass", () => {
return gulp.src(paths.src.sass)
.pipe(sass({
includePaths: paths.sass.includePaths
}).on("error", sass.logError))
.pipe(gulp.dest(`${paths.output.dist}/assets`));
});
// html
gulp.task("html", (cb) => {
return runSeq(
["compile:html", "compile:index-html"],
cb);
});
gulp.task("compile:html", () => {
return gulp.src(paths.src.html)
.pipe(gulp.dest(`${paths.output.dist}/app`));
});
gulp.task("compile:index-html", () => {
return gulp.src(paths.src.indexHtml)
.pipe(gulp.dest(paths.output.root));
});
// images
gulp.task("copy:imgs", () => {
return gulp.src(paths.src.imgs)
.pipe(gulp.dest(`${paths.output.dist}/assets`));
});
|
import navbarApi from '../API/mockNavbarApi';
export function loadNavbarSuccess(navbar_items) {
return { type: 'LOAD_NAVBAR_SUCCESS', navbar_items};
}
export function loadNavbar() {
return function (dispatch) {
return navbarApi.getAllItems().then(navbar_items => {
dispatch(loadNavbarSuccess(navbar_items));
}).catch(error => {
throw(error);
});
};
}
|
window.fbAsyncInit = function() {
debugger;
FB.init(initParams || {status: true, xfbml: true});
initialised = true;
angular.forEach(queue, function(func) {
func();
});
};
|
game.module(
'game.assets'
)
.body(function () {
game.addAsset('sprite.png');
game.addAsset('sprite_red.png');
});
|
window.iframe = window.iframe || {};
window.iframe = new function ()
{
var that = this;
that.generate = function (el, url)
{
frame = document.createElement('iframe');
frame.id = 'kernsoccer';
frame.style.width = "100%";
frame.style.height = "100%";
frame.style.border = "none";
frame.style.position = "absolute";
frame.style.top = "0px";
frame.style.left = "0px";
frame.style.zIndex = 99999;
el.appendChild(frame);
frame.src = url;
}
that.remove = function ()
{
var iframe = document.getElementById('kernsoccer');
if (iframe != null)
{
iframe.parentElement.removeChild(iframe);
}
}
}
var mapping = {
start: {
type: "button",
buttons: [9],
toggle: true
},
return: {
type: "button",
buttons: [8],
toggle: true
}
};
var ctrlMgr = ControllerManager();
for (var i=0; i < ctrlMgr.controllers.length; i++) {
ctrlMgr.controllers[i].setMapping(mapping);
}
function updateIFrame() {
ctrlMgr.update();
var connected = false;
for (var i=0; i < ctrlMgr.controllers.length; i++) {
if (ctrlMgr.controllers[i].isConnected()) {
connected = true;
}
if (ctrlMgr.controllers[i].get("return")) {
window.iframe.remove();
requestAnimationFrame(update);
return;
}
}
if (!connected) {
window.iframe.remove();
requestAnimationFrame(update);
return;
}
requestAnimationFrame(updateIFrame);
}
function update() {
ctrlMgr.update();
for (var i=0; i < ctrlMgr.controllers.length; i++) {
if (ctrlMgr.controllers[i].get("start")) {
window.iframe.generate(window.document.body, '//kernsoccer.github.io?start');
requestAnimationFrame(updateIFrame);
return;
}
}
requestAnimationFrame(update);
}
requestAnimationFrame(update);
|
/* eslint-disable func-names, space-before-function-paren, no-var, space-before-blocks, prefer-rest-params, wrap-iife, one-var, one-var-declaration-per-line, consistent-return, no-param-reassign, padded-blocks, no-undef, max-len */
(function() {
var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
this.SingleFileDiff = (function() {
var COLLAPSED_HTML, ERROR_HTML, LOADING_HTML, WRAPPER;
WRAPPER = '<div class="diff-content diff-wrap-lines"></div>';
LOADING_HTML = '<i class="fa fa-spinner fa-spin"></i>';
ERROR_HTML = '<div class="nothing-here-block"><i class="fa fa-warning"></i> Could not load diff</div>';
COLLAPSED_HTML = '<div class="nothing-here-block diff-collapsed">This diff is collapsed. <a class="click-to-expand">Click to expand it.</a></div>';
function SingleFileDiff(file, forceLoad, cb) {
this.file = file;
this.toggleDiff = bind(this.toggleDiff, this);
this.content = $('.diff-content', this.file);
this.$toggleIcon = $('.diff-toggle-caret', this.file);
this.diffForPath = this.content.find('[data-diff-for-path]').data('diff-for-path');
this.isOpen = !this.diffForPath;
if (this.diffForPath) {
this.collapsedContent = this.content;
this.loadingContent = $(WRAPPER).addClass('loading').html(LOADING_HTML).hide();
this.content = null;
this.collapsedContent.after(this.loadingContent);
this.$toggleIcon.addClass('fa-caret-right');
} else {
this.collapsedContent = $(WRAPPER).html(COLLAPSED_HTML).hide();
this.content.after(this.collapsedContent);
this.$toggleIcon.addClass('fa-caret-down');
}
$('.file-title, .click-to-expand', this.file).on('click', this.toggleDiff);
if (forceLoad) {
this.toggleDiff(null, cb);
}
}
SingleFileDiff.prototype.toggleDiff = function(e, cb) {
var $target = $(e.target);
if (!$target.hasClass('file-title') && !$target.hasClass('click-to-expand') && !$target.hasClass('diff-toggle-caret')) return;
this.isOpen = !this.isOpen;
if (!this.isOpen && !this.hasError) {
this.content.hide();
this.$toggleIcon.addClass('fa-caret-right').removeClass('fa-caret-down');
this.collapsedContent.show();
if (typeof gl.diffNotesCompileComponents !== 'undefined') {
gl.diffNotesCompileComponents();
}
} else if (this.content) {
this.collapsedContent.hide();
this.content.show();
this.$toggleIcon.addClass('fa-caret-down').removeClass('fa-caret-right');
if (typeof gl.diffNotesCompileComponents !== 'undefined') {
gl.diffNotesCompileComponents();
}
} else {
this.$toggleIcon.addClass('fa-caret-down').removeClass('fa-caret-right');
return this.getContentHTML(cb);
}
};
SingleFileDiff.prototype.getContentHTML = function(cb) {
this.collapsedContent.hide();
this.loadingContent.show();
$.get(this.diffForPath, (function(_this) {
return function(data) {
_this.loadingContent.hide();
if (data.html) {
_this.content = $(data.html);
_this.content.syntaxHighlight();
} else {
_this.hasError = true;
_this.content = $(ERROR_HTML);
}
_this.collapsedContent.after(_this.content);
if (typeof gl.diffNotesCompileComponents !== 'undefined') {
gl.diffNotesCompileComponents();
}
if (cb) cb();
};
})(this));
};
return SingleFileDiff;
})();
$.fn.singleFileDiff = function(forceLoad, cb) {
return this.each(function() {
if (!$.data(this, 'singleFileDiff') || forceLoad) {
return $.data(this, 'singleFileDiff', new SingleFileDiff(this, forceLoad, cb));
}
});
};
}).call(this);
|
var User = require('../app/models/user');
var Auth = require('./middlewares/authorization.js');
module.exports = function(app, passport){
app.get("/", function(req, res){
if(req.isAuthenticated()){
res.render("index", { user : req.user});
}else{
res.render("index", { user : null});
}
});
app.get("/login", function(req, res){
res.render("login", { message: req.flash('info'), error: req.flash('error') });
});
app.post("/login", function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err) }
if (!user) {
return res.json({message: info.message});
}
req.login(user, function(err){
if(err) return next(err);
return res.json({user: user});
});
})(req, res, next);
});
app.get("/signup", function (req, res) {
res.render("signup");
});
app.post("/signup", Auth.userExist, function (req, res, next) {
console.log("signing up...");
User.signup(req.body.email, req.body.password, req.body.firstName, req.body.lastName, function(err, user){
if(err) throw err;
req.login(user, function(err){
if(err) return next(err);
return res.json({user: user});
});
});
});
app.post("/add_account", function (req, res, next) {
User.add_account( req.user.email, req.body.id, req.body.name, req.body.password, function(err, user) {
if(err) throw err;
var last = user.accounts.length - 1;
return res.json({account: user.accounts[last]});
});
});
app.get("/edit_account/:account_id", function (req, res) {
if(req.isAuthenticated()){
var account = User.find_account( req.user, req.params.account_id, function(err, account) {
if (err) throw err;
if (!account) {
req.flash('error', 'Account does not exist.');
return res.redirect("profile");
}
res.render( "account/edit", {
account: account
});
});
}else{
res.render("login", { message: req.flash('info'), error: req.flash('error') });
}
});
app.post("/edit_account", function (req, res) {
User.save_account( req.user.email, req.body.oid, req.body.id, req.body.name, req.body.password, function(err, account) {
if (err) throw err;
return res.json({message: 'Cards changes saved.'});
});
});
app.get("/remove_account/:account_oid", function (req, res) {
if(req.isAuthenticated()){
User.remove_account( req.user.email, req.params.account_oid, function(err, user) {
if(err) throw err;
return res.json({message: 'Card removed from your account.'});
});
} else {
res.json({message: 'Any error occured while trying to remove this card.'});
};
});
app.get("/auth/facebook", passport.authenticate("facebook",{ scope : "email"}));
app.get("/auth/facebook/callback",
passport.authenticate("facebook",{ failureRedirect: '/login'}),
function(req,res){
req.login(req.user, function(err){
if(err) return err;
return res.json({user: user});
});
}
);
app.get("/profile", function(req, res){
if(req.isAuthenticated()){
res.render("profile", { user: req.user, message: req.flash('info'), error: req.flash('error') });
}else{
res.render("login", { message: req.flash('info'), error: req.flash('error') });
}
});
app.get('/logout', function(req, res){
req.logout();
req.flash('info', 'You are now logged out.')
res.redirect('/login');
});
}
|
function SwipeSide(cont, userOptions) {
"use strict";
var container,
options = {
accessClasses: {
left : 'pull-left',
right: 'pull-right'
},
direction: ['left', 'right']
},
utils = {
hasClass: function(obj, cssClass) {
var re = new RegExp("\\b" + cssClass + "\\b", 'g');
return (obj.className.match(re) !== null);
},
addClass: function(obj, cssClass) {
var current = obj.className || '';
var re = new RegExp("\\b" + cssClass + "\\b", 'g');
if (current.match(re) === null) {
obj.className = (current += ' ' + cssClass).trim();
}
},
removeClass: function(obj, cssClass) {
var current = obj.className || '';
var re = new RegExp("\\b" + cssClass + "\\b", 'g');
obj.className = current.replace(re, '').trim();
},
parentUntilAttr: function(obj, attr) {
if (obj.getAttribute && obj.getAttribute(attr)) {
return obj;
} else if (obj.parentNode) {
return this.parentUntilAttr(obj.parentNode, attr);
}
return false;
}
},
actions = {
swipe: function(dir) {
// We're accessing the opposite side to the direction we're swiping
var access = (dir === 'left') ? 'right' : 'left';
// If the opposite side is already open, close it
if (utils.hasClass(container, options.accessClasses[dir])) {
utils.removeClass(container, options.accessClasses[dir]);
} else if ( ! utils.hasClass(container, options.accessClasses[access]) && options.direction.indexOf(access) !== -1) {
// If the side we're trying to expose isn't already open and if we're allowed to expose the panel
utils.addClass(container, options.accessClasses[access]);
}
}
},
events = {
start: {},
differences: {},
isHorizontal: null,
invalidTarget: false,
handleEvent: function(event) {
switch (event.type) {
case 'touchstart':
this.touchstart(event);
break;
case 'touchmove':
this.touchmove(event);
break;
case 'touchend':
this.touchend(event);
break;
}
},
touchstart: function(event) {
var touch = event.touches[0];
events.start = {
x: touch.pageX,
y: touch.pageY
};
if (utils.parentUntilAttr(touch.target, 'data-swipeme-ignore')) {
events.invalidTarget = true;
}
},
touchmove: function(event) {
var touch = event.touches[0];
events.differences = {
x: touch.pageX - events.start.x,
y: touch.pageY - events.start.y
};
if (events.isHorizontal === null) {
events.isHorizontal = (Math.abs(events.differences.x) > Math.abs(events.differences.y));
}
if (events.isHorizontal && ! events.invalidTarget) {
event.preventDefault();
}
},
touchend: function() {
if (events.isHorizontal && ! events.invalidTarget) {
if(zdztool.isNavAutoHide()) {
zdztool.previous(zdztool.getNavDirection());
} else {
var swipeDir = (events.differences.x > 0) ? 'left' : 'right';
actions.swipe(swipeDir);
}
}
events.isHorizontal = null;
events.invalidTarget = false;
events.differences = {};
}
};
function setup(cont, userOptions) {
container = cont;
var opt;
for (opt in options) {
if (typeof userOptions[opt] !== 'undefined') {
options[opt] = userOptions[opt];
}
}
if (typeof options.direction === 'string') {
options.direction = [options.direction];
}
return {
swipe : function(dir) {
// if dir is undefined assume left as is most common
dir = dir || 'left';
actions.swipe(dir);
},
container : container,
actions : actions,
events : events
};
}
if (cont && window.addEventListener) {
cont.addEventListener('touchstart', events);
cont.addEventListener('touchmove', events);
cont.addEventListener('touchend', events);
}
return setup(cont, userOptions);
};
|
export default function fetchAPI(path, options) {
return fetch(process.env.REACT_APP_API_URL + path, options)
.then(response => {
// Successful
if (response.ok) {
// Decode JSON
return response.json()
}
// Error
else {
// Client error
if (response.status >= 400 && response.status < 500) {
return response.json()
.then(json => {
return Promise.reject(json)
})
}
// Server error or redirect
else {
// Reject with entire response
return Promise.reject(response)
}
}
})
}
export function postAPI(path, bodyJSON) {
return fetchAPI(path, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(bodyJSON)
})
}
export function patchAPI(path, bodyJSON) {
return fetchAPI(path, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(bodyJSON)
})
}
|
"use strict";
/**
* Blogger
*/
const mongoose = require("mongoose"), Schema = mongoose.Schema;
const BloggerSchema = new Schema(
{
// 名字
name: {
type: String,
unique: true
},
// 博客地址
url: {
type: String,
default: ""
},
// 任务js
taskjs: {
type: String,
default: ""
},
// 创建时间
createTime: {
type: Date,
default: Date.now
},
// 最近一次更新
lastUpdateTime: {
type: Date,
default: Date.now
}
},
{ versionKey: false }
);
BloggerSchema.set("toJSON", { getters: true, virtuals: true });
BloggerSchema.set("toObject", { getters: true, virtuals: true });
BloggerSchema.path("createTime").get(function(v) {
var date = null;
if (v) {
date = new Date(v);
return date.format("yyyy-MM-dd hh:mm:ss");
} else {
return new Date().format("yyyy-MM-dd hh:mm:ss");
}
});
BloggerSchema.path("lastUpdateTime").get(function(v) {
var date = null;
if (v) {
date = new Date(v);
return date.format("yyyy-MM-dd hh:mm:ss");
} else {
return new Date().format("yyyy-MM-dd hh:mm:ss");
}
});
const bloggerModel = mongoose.model("blogger", BloggerSchema);
module.exports = bloggerModel;
|
(function(){
angular
.module('youtube-videos')
.controller('YoutubeVideosCtrl', YoutubeVideosCtrl);
function YoutubeVideosCtrl(YoutubePlayerSettings, YoutubeSearch, YoutubeVideoInfo){
var vm = this;
vm.playVideo = playVideo;
vm.playPlaylist = playPlaylist;
vm.queueVideo = YoutubePlayerSettings.queueVideo;
vm.feedType = YoutubeSearch.getFeedType;
vm.videos = YoutubeSearch.items;
vm.loadMore = YoutubeSearch.searchMore;
activate();
///////////
function activate () {
YoutubeSearch.search();
}
function playVideo (video) {
YoutubePlayerSettings.queueVideo(video);
YoutubePlayerSettings.playVideoId(video);
}
function playPlaylist (playlist) {
return YoutubeVideoInfo.getPlaylist(playlist.id).then(YoutubePlayerSettings.playPlaylist);
}
}
})();
|
import autoBind from '../auto-bind';
class Test {
constructor(data, bind = true) {
this.bar = data;
bind && autoBind(this);
}
foo() {
return this.bar;
}
}
describe('auto-bind', () => {
const test = new Test('Bind');
it('should bind all class functions to class instance', () => {
const { foo } = test;
expect(foo()).toBe(test.foo());
});
});
describe('without auto-bind', () => {
const test = new Test('No Bind', false);
it('should access when it is called from class instance', () => {
expect(test.foo()).toBe('No Bind');
});
it('cannot read bar field', () => {
const { foo } = test;
expect(foo).toThrow("Cannot read property 'bar' of undefined");
});
});
|
/**
* @file Functions related to performances ratios computation.
* @author Roman Rubsamen <roman.rubsamen@gmail.com>
*/
/**
* @function gainToPainRatio
*
* @summary Compute the gain to pain ratio of a portfolio.
*
* @description This function returns the gain to pain ratio of a portfolio, provided as an
* equity curve.
*
* The the gain to pain ratio is defined as the sum of all returns divided by the absolute value of the sum of all losses, c.f. the reference.
*
* From the reference, a gain to pain ratio above 1.0 is very good, and a gain to pain ratio above 1.5 is excellent.
*
* @see <a href="http://onlinelibrary.wiley.com/doi/10.1002/9781119203469.app1/summary">Hedge Fund Market Wizards: How Winning Traders Win, Jack D. Schwager, Wiley, 2012</a>
*
* @param {Array.<number>} portfolioEquityCurve the portfolio equity curve, an array of real numbers.
* @return {number} the gain to pain ratio of the portfolio.
*
* @example
* gainToPainRatio([1, 2, 1]);
* // 1.0
*
* @example
* gainToPainRatio([1, 1.1, 1.4]);
* // NaN
*/
self.gainToPainRatio = function(portfolioEquityCurve) {
// Compute the arithmetic returns of the portfolio
var returns = self.arithmeticReturns(portfolioEquityCurve).slice(1); // First value is NaN
// If there is no usable returns, exit
if (returns.length == 0) {
return NaN;
}
// Else, compute the gain to pain ratio as the the sum of the returns divided by
// the sum of the absolute values of the negative returns, c.f. the reference.
var numerator = mean_(returns);
var denominator = lpm_(returns, 1, 0.0);
// Return the gain to pain ratio
if (denominator == 0.0) {
return NaN; // The gain to pain ratio is undefined in case there is no negative returns
}
else {
return numerator/denominator;
}
}
|
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import navbarComponent from './navbar.component';
import collapse from 'angular-ui-bootstrap/src/collapse'
let navbarModule = angular.module('navbar', [
uiRouter,
collapse
])
.component('navbar', navbarComponent);
export default navbarModule;
|
/*------------------------------------------------------------------
[ Lock Screen Trigger Js]
Project : Fickle Responsive Admin Template
Version : 1.0
Author : AimMateTeam
URL : http://aimmate.com
Support : aimmateteam@gmail.com
Primary use : Lock Screen Page
-------------------------------------------------------------------*/
jQuery(document).ready(function($) {
'use strict';
form_lock_screen_trigger_call();
ladda_progress_button_load();
});
function form_lock_screen_trigger_call(){
$('#form-lock-screen').submit(function () {
/*var setUrl = window.location.origin + '/index.html'
window.location.assign(setUrl);*/
return false;
});
}
function ladda_progress_button_load(){
Ladda.bind('button.ladda-button', {
callback: function (instance) {
var progress = 0;
var interval = setInterval(function () {
progress = Math.min(progress + Math.random() * 0.1, 1);
instance.setProgress(progress);
if (progress === 1) {
instance.stop();
clearInterval(interval);
//Checking Login in here
var jacked = humane.create({baseCls: 'humane-jackedup', addnCls: 'humane-jackedup-success'});
jacked.log("<span class='fa fa-unlock'></span> Successfully unlock <i class='fa fa-smile-o'></i> ");
setInterval(function () {
var setUrl = '/index.html';
window.location.assign(setUrl);
}, 500);
}
}, 200);
}
});
}
|
Meteor.publish('adminAccountsIndexTabular', function (tableName, ids, fields) {
check(tableName, String);
check(ids, Array);
check(fields, Match.Optional(Object));
if (!Roles.userHasPermission(this.userId, 'accounts.index')) {
return [];
}
var self = this;
var transform = function(user) {
user.usedServices = _.keys(user.services);
delete user.services;
return user;
};
fields.services = 1;
fields.roles = 1;
var usersHandle = Meteor.users.find({ _id: { $in: ids } }, { fields: fields }).observe({
added: function (user) {
self.added('users', user._id, transform(user));
},
changed: function (user) {
self.changed('users', user._id, transform(user));
},
removed: function (user) {
self.removed('users', user._id);
}
});
self.onStop(function() {
usersHandle.stop();
});
if (Roles._collection) {
var rolesHandle = Roles._collection.find({ userId: { $in: ids } }).observe({
added: function (role) {
self.added('roles', role._id, role);
},
changed: function (role) {
self.changed('roles', role._id, role);
},
removed: function (role) {
self.removed('roles', role._id);
}
});
self.onStop(function() {
rolesHandle.stop();
});
}
self.ready();
});
Meteor.publish('adminAccountsUpdateRoles', function (userId) {
check(userId, String);
if (!Roles.userHasPermission(this.userId, 'accounts.update.roles')) {
return [];
}
if (Roles._collection) {
return [
Meteor.users.find(userId, { fields: { services: 0 } }),
Roles._collection.find({ userId: userId })
];
} else {
return Meteor.users.find(userId, { fields: { services: 0 } });
}
});
Meteor.methods({
updateRoles: function (userId, roles) {
check(userId, String);
check(roles, Array);
if (!Roles.userHasPermission(this.userId, 'accounts.update.roles')) {
throw new Meteor.Error('unauthorized', i18n('accounts.update.messages.noPermissions'));
}
var allowed = _.union.apply(this, Roles.helper(this.userId, 'accounts.allowedRoles'));
var denied = _.union.apply(this, Roles.helper(this.userId, 'accounts.deniedRoles'));
var finalRoles = _.difference(allowed, denied);
if (_.difference(roles, finalRoles).length !== 0) {
throw new Meteor.Error('unauthorized', i18n('accounts.update.messages.noPermissions'));
}
Roles.setUserRoles(userId, roles);
},
scorpiusAccountsUpdatePassword: function(modifier, userId) {
if (!Roles.userHasPermission(this.userId, 'accounts.update.password', userId)) {
throw new Meteor.Error('unauthorized', i18n('accounts.update.messages.noPermissions'));
}
var options = modifier.$set;
check(options, UsersPasswordSchema);
Accounts.setPassword(userId, options.password, { logout: true });
},
scorpiusAccountsUpdateEmails: function(modifier, userId) {
if (!Roles.userHasPermission(this.userId, 'accounts.update.emails', userId)) {
throw new Meteor.Error('unauthorized', i18n('accounts.update.messages.noPermissions'));
}
Meteor.users.update(userId, modifier);
},
scorpiusAccountsUpdateProfile: function(modifier, userId) {
if (!Roles.userHasPermission(this.userId, 'accounts.update.profile', userId)) {
throw new Meteor.Error('unauthorized', i18n('accounts.update.messages.noPermissions'));
}
Meteor.users.update(userId, modifier);
},
removeUser: function(userId){
check(userId, String);
if (!Roles.userHasPermission(this.userId, 'accounts.remove', userId)) {
throw new Meteor.Error('unauthorized', i18n('accounts.update.messages.noPermissions'));
}
Meteor.users.remove({ _id: userId });
},
adminSendEnrollmentEmail: function(userId) {
check(userId, String);
Roles.checkPermission(this.userId, 'accounts.index');
return Accounts.sendEnrollmentEmail(userId);
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.