text
stringlengths 2
6.14k
|
|---|
// Node packages
let app = require('express')();
let server = require('http').Server(app);
let io = require('socket.io')(server);
let crypto = require('crypto');
let Victor = require('victor');
// Serverside code modules
require('./server/Global.js').loadGlobalConstants();
let Game = require('./server/Game.js').Game;
// CONSTANTS
const PORT = process.env.PORT || 3000;
const startServer = () => {
server.listen(PORT);
app.get('/', (req, res) => { res.sendFile('index.html', { root: './client/' }); });
app.get('/script.js', (req, res) => { res.sendFile('script.js', { root: './client/' }); });
app.get('/style.css', (req, res) => { res.sendFile('style.css', { root: './client/' }); });
let game = new Game(io);
game.initialize();
game.start();
};
startServer();
|
exports.checkBaseModules = function () {
var value = true;
value &= checkModule('fs');
value &= checkModule('console');
value &= checkModule('binary');
value &= checkModule('shell');
value &= checkModule('system');
return value;
}
exports.checkRequireWorks = function() {
var module = require('fs');
if(typeof module.file === 'undefined') {
return false;
}
return true;
}
exports.checkBaseModules.description = "checking wether base modules are present";
exports.checkRequireWorks.description = "checking wether require works";
|
require.config({
paths: {
'jquery' : '/bundles/app/js/vendors/jquery/jquery.min',
'jquery.ui' : '/bundles/app/js/vendors/jquery-ui/ui/minified/jquery-ui.min',
'underscore' : '/bundles/app/js/vendors/underscore/underscore',
'backbone' : '/bundles/app/js/vendors/backbone/backbone-min',
'bootstrap' : '/bundles/app/js/vendors/bootstrap/docs/assets/js/bootstrap.min',
'marionette' : '/bundles/app/js/vendors/marionette/lib/backbone.marionette',
'moment' : '/bundles/app/js/vendors/moment/min',
'marion' : '/bundles/app/js/vendors/marion/build/marion',
'tpl' : '/bundles/app/js/vendors/requirejs-tpl/tpl',
//
'mercury' : '/bundles/app/js/vendors/mercury/distro/mercury',
'mercury.loader' : '/bundles/app/js/mercury/loader',
'mercury.options' : '/bundles/app/js/mercury/options/loader',
'mercury.regions.path' : '/bundles/app/js/vendors/mercury/distro/regions',
'mercury.deps' : '/bundles/app/js/vendors/mercury/distro/dependencies'
},
shim: {
'mercury': {
deps: ['jquery', 'mercury.loader/rangy', 'mercury.deps/marked-0.2.8'],
exports: 'Mercury'
},
'jquery.ui': ['jquery'],
'underscore': {
exports: '_'
},
'backbone': {
deps: ['underscore'],
exports: 'Backbone'
},
'marionette' : {
exports : 'Backbone.Marionette',
deps : ['backbone']
},
'moment/lang/ru': {
exports: 'moment',
deps: ['moment/moment.min']
},
//Mercury deps
'mercury.loader/rangy': ['mercury.deps/rangy-core'],
'mercury.loader/main': ['mercury.loader/rangy']
},
deps: [
'jquery.ui',
'underscore',
'backbone',
'marionette',
'moment/lang/ru'
]
});
require(['underscore', 'mercury', 'mercury.options'], function(_, Mercury, options) {
_.extend(Mercury.configuration, options.configuration);
require(['mercury.loader/main'], function(){
/*
var model = new Mercury.Model.Page();
model.id = options.id;
console.log(model, Mercury);
*/
Mercury.init();
});
})
|
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import card from '../Card.css'
import Card from '@material-ui/core/Card'
import CardMedia from '@material-ui/core/CardMedia'
import CardActions from '@material-ui/core/CardActions'
import IconButton from '@material-ui/core/IconButton'
export default class Video extends Component {
showTweets() {
this.props.getTweetsForVideo(this.props.searchId, this.props.url)
}
render() {
return (
<Card className={`${card.Card}`} style={{height: "365px"}}>
<CardMedia>
<video style={{width: '300px', height: '300px'}} controls preload="false" poster={this.props.thumbnailUrl}>
<source src={this.props.url} />
</video>
</CardMedia>
<CardActions>
<IconButton aria-label="show tweets" onClick={() => {this.showTweets()}}>
<ion-icon name="logo-twitter"></ion-icon>
</IconButton>
{this.props.count}
</CardActions>
</Card>
)
}
}
Video.propTypes = {
url: PropTypes.string,
thumbnailUrl: PropTypes.string,
count: PropTypes.number,
searchId: PropTypes.number,
getTweetsForVideo: PropTypes.func
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:f8dd740290d07491a415700ff6d7debc31d8f766307c8823bf6d994680cc160c
size 9362
|
/*
create a namespace called Meteoris.SiteController
*/
Namespace('Meteoris.SiteController');
/**
Create controller which extends Meteoris Controller
*/
Meteoris.SiteController = Meteoris.Controller.extend({
constructor : function() {
// set default counter at constructor
Session.setDefault('counter', 0);
},
/* passing data to index helpers template */
index: function() {
//return some value, to be passed on index.js
return {
counter: this.getCounter(),
myName: "Ega Radiegtya",
myHobby: "Drinking Coffee"
};
},
getCounter: function(){
return Session.get("counter");
},
setCounter: function(counter){
Session.set('counter', this.getCounter() + 1);
}
});
|
/* jslint node: true */
'use strict';
var Backbone = require('backbone');
var Cluster = Backbone.Collection.extend({
initialize: function (models, options) {
this.options = options || {};
},
key: function(){
if(this.length > 1){
return this.pluck('id').join('-');
}else{
return this.first().id;
}
},
coordinates: function coordinates() {
var latitude_total = 0;
var longitude_total = 0;
this.each(function(item){
latitude_total += item.latitude();
longitude_total += item.longitude();
});
return [
latitude_total / this.length,
longitude_total / this.length
];
},
data: function () {
return this.pluck('data');
},
changedValues: function () {}
});
module.exports = Cluster;
|
const path = require('path');
const HappyPack = require('happypack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const happyThreadCount = 4;
const config = {
devtool: 'cheap-module-source-map',
plugins: [
new HappyPack({
id: 'eslint',
loaders: [{
loader: 'eslint-loader',
}],
threads: happyThreadCount,
}),
new HappyPack({
id: 'babel',
loaders: [{
loader: 'babel-loader',
options: {
presets: ['es2015'],
},
}],
threads: happyThreadCount,
}),
],
module: {
rules: [{
test: /\.html$/,
use: 'html-loader',
},
{
enforce: 'pre',
test: [/\.js$/],
exclude: [/node_modules/, /\.spec.js$/],
include: path.resolve('src/app'),
use: [{
loader: 'istanbul-instrumenter-loader',
options: {
esModules: true,
},
}],
},
{
test: /\.js$/,
exclude: /node_modules/,
include: /\.spec\.js/,
enforce: 'pre',
use: [{
loader: 'happypack/loader?id=eslint',
}],
},
{
test: /\.js/,
exclude: /node_modules/,
use: [{
loader: 'happypack/loader?id=babel',
}],
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [{
loader: 'css-loader',
},
{
loader: 'sass-loader',
options: {
modules: true,
},
},
],
}),
},
{
test: /\.(jpg|png|gif|svg)$/,
use: [{
loader: 'url-loader',
query: {
limit: 2000,
name: '[name].[ext]',
},
}],
},
],
},
};
module.exports = config;
|
"use strict";
const ThreadChannel = require("./ThreadChannel");
/**
* Represents a news thread channel. See ThreadChannel for extra properties.
* @extends ThreadChannel
*/
class NewsThreadChannel extends ThreadChannel {
constructor(data, client, messageLimit) {
super(data, client, messageLimit);
}
}
module.exports = NewsThreadChannel;
|
var InputText = React.createClass({displayName: "InputText",
componentWillReceiveProps: function (newProps) {
React.findDOMNode(this.refs.input).value = newProps.value
},
onChange(){
var value = React.findDOMNode(this.refs.input).value;
this.props.onChange({value: value});
},
render: function () {
return React.createElement("div", {className: "form-group"},
React.createElement("label", null, this.props.children),
React.createElement("input", {type: "text", className: "form-control", ref: "input", onChange: this.onChange})
)
}
});
var TextArea = React.createClass({displayName: "TextArea",
componentWillReceiveProps: function (newProps) {
React.findDOMNode(this.refs.input).value = newProps.value
},
render: function () {
return React.createElement("div", {className: "form-group"},
React.createElement("label", null, this.props.children),
React.createElement("textarea", {className: "form-control", ref: "input", rows: "5"})
)
}
});
var MovieEdit = React.createClass({displayName: "MovieEdit",
contextTypes: {
router: React.PropTypes.func
},
getInitialState: function () {
return {movie: {}};
},
componentWillMount: function () {
var id = this.context.router.getCurrentParams().id;
var _this = this;
$.getJSON('/api/movies/' + id).then(function (movie) {
_this.setState({movie: movie});
})
},
onChange(e){
console.log(e)
},
save(){
console.log(this.state.movie)
var id = this.context.router.getCurrentParams().id;
var _this = this;
$.ajax('/api/movies/' + id, {
data: this.state.movie,
type: 'put'
}).then(function(){
alert('saved')
});
},
render: function () {
var movie = this.state.movie;
var ratings = movie.ratings || {};
return React.createElement("form", null,
React.createElement(InputText, {onChange: this.onChange, value: movie.title}, "Title"),
React.createElement(InputText, {value: movie.abridgedDirectors}, "Directors"),
React.createElement(TextArea, {value: movie.criticsConsensus}, "Critics Consensus"),
React.createElement(TextArea, {value: movie.synopsis}, "Synopsis"),
React.createElement(InputText, {value: movie.year}, "Year"),
React.createElement(InputText, {value: movie.mpaaRating}, "MPAA Rating"),
React.createElement(InputText, {value: ratings.criticsScore}, "Critics Score"),
React.createElement(InputText, {value: ratings.audienceScore}, "Audience Score"),
React.createElement("div", {className: "form-group"},
React.createElement("button", {type: "submit", onClick: this.save, className: "btn btn-primary"}, "Save"),
React.createElement(Link, {className: "btn btn-danger",
to: "movies"},
"Cancel"
)
)
);
}
});
|
var chai = require('chai')
var expect = require('chai').expect
var sinon = require('sinon')
var clock
chai.use(require('sinon-chai'))
var TeamCityReporter = require('./../index')['reporter:teamcity'][1]
describe('TeamCity reporter', function () {
var reporter
var mosaic = {id: 'id', name: 'Mosaic'}
beforeEach(function () {
reporter = new TeamCityReporter(function (instance) {
instance.write = sinon.stub()
})
clock = sinon.useFakeTimers(new Date(2050, 9, 1, 0, 0, 0, 0).getTime())
})
afterEach(function () {
clock.restore()
})
it('should produce 2 standard messages without browsers', function () {
reporter.onRunStart([])
reporter.onRunComplete([])
expect(reporter.write.firstCall.args).to.be.eql(["##teamcity[blockOpened name='JavaScript Unit Tests' flowId='']\n"])
expect(reporter.write.secondCall.args).to.be.eql(["##teamcity[blockClosed name='JavaScript Unit Tests' flowId='']\n"])
})
it('should produce 2 standard messages without tests', function () {
reporter.onRunStart([mosaic])
reporter.onRunComplete([])
expect(reporter.write.firstCall.args).to.be.eql(["##teamcity[blockOpened name='JavaScript Unit Tests' flowId='']\n"])
expect(reporter.write.secondCall.args).to.be.eql(["##teamcity[blockClosed name='JavaScript Unit Tests' flowId='']\n"])
})
it('should produce messages with one test', function () {
reporter.onRunStart([mosaic])
reporter.specSuccess(mosaic, {description: 'SampleTest', time: 2, suite: ['Suite 1']})
reporter.onRunComplete([])
expect(reporter.write.args).to.be.eql([
[ '##teamcity[blockOpened name=\'JavaScript Unit Tests\' flowId=\'\']\n' ],
[ '##teamcity[testSuiteStarted name=\'Suite 1.Mosaic\' flowId=\'karmaTC-1448140806id\']\n' ],
[ ' ' ],
[ '##teamcity[testStarted name=\'SampleTest\' flowId=\'karmaTC-1448140806id\']\n' ],
[ ' ' ],
[ '##teamcity[testFinished name=\'SampleTest\' duration=\'2\' flowId=\'karmaTC-1448140806id\']\n' ],
[ ' ' ],
[ '##teamcity[testSuiteFinished name=\'Suite 1.Mosaic\' flowId=\'karmaTC-1448140806id\']\n' ],
[ '##teamcity[blockClosed name=\'JavaScript Unit Tests\' flowId=\'\']\n' ]
])
})
})
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
View
} from 'react-native';
class Day06ListViewLoadMore extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('Day06ListViewLoadMore', () => Day06ListViewLoadMore);
|
const fs = require('fs');
const errorLog = {};
/**
* Initialize Error Log
* @param {String} -- File Path
* @public
* Example:
* `errorLog.Init(path.join(__dirname + '/healthCheck.log'));`
*/
errorLog.init = (path) => {
if (path === null) throw 'Error: A file path is a required parameter for errorLog.init'
errorLog.path = path;
}
/**
* Begins writing of errors to file path created in errorLog.Init
* @param {Object} -- Error Object
* @return {File} -- Overwrites old file, persisting old error data and adding new data together
* @public
*/
const queue = [];
errorLog.write = (error) => {
queue.push(error);
}
let logStream = fs.createWriteStream(errorLog.path, {flags:'a'});
const errorStream = (stream) => {
logStream.write(stream);
}
errorLog.readWrite = () => {
if (errorLog.path && queue.length > 0) {
let error = queue.shift();
fs.readFile(errorLog.path, (err, data) => {
if (err) console.log(err, 'Read File error');
let date = new Date();
fs.writeFile(errorLog.path, data ? data + date + ': ' + error + '\n' : date + ': ' + error + '\n', 'utf-8', (err) => {
if (err) console.log(err, 'Write File error');
})
})
} else {
return;
}
}
module.exports = (firstTime = true) => {
if (firstTime) setInterval(() => errorLog.readWrite(), 2000);
return errorLog;
}
|
/**
* Each section of the site has its own module. It probably also has
* submodules, though this boilerplate is too simple to demonstrate it. Within
* `src/app/home`, however, could exist several additional folders representing
* additional modules that would then be listed as dependencies of this one.
* For example, a `note` section could have the submodules `note.create`,
* `note.delete`, `note.edit`, etc.
*
* Regardless, so long as dependencies are managed correctly, the build process
* will automatically take take of the rest.
*
* The dependencies block here is also where component dependencies should be
* specified, as shown below.
*/
angular.module( 'ngBoilerplate.home', [
'ui.state',
'plusOne',
'user'
])
/**
* Each section or module of the site can also have its own routes. AngularJS
* will handle ensuring they are all available at run-time, but splitting it
* this way makes each module more "self-contained".
*/
.config(function config( $stateProvider ) {
$stateProvider.state( 'home', {
url: '/home',
views: {
"main": {
controller: 'HomeCtrl',
templateUrl: 'home/home.tpl.html'
}
},
data:{ pageTitle: 'Home' }
});
})
.factory( 'Stories', function($resource) {
var resource = $resource('http://storymixes.com/api/getstories.php', {}, {
get_by_date: {
method : 'GET',
isArray: true,
params: { search_by: 'date' }
}
} );
return resource;
})
/**
* And of course we define a controller for our route.
*/
.controller( 'HomeCtrl', function HomeController( $scope, Stories ) {
$scope.quantity = 3;
$scope.stories = Stories.get_by_date();
});
|
/*
* Copyright (C) 2014 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration. All Rights Reserved.
*/
/**
* @exports GpuShader
* @version $Id: GpuShader.js 2906 2015-03-17 18:45:22Z tgaskins $
*/
define([
'../error/ArgumentError',
'../util/Logger'
],
function (ArgumentError,
Logger) {
"use strict";
/**
* Constructs a GPU shader of a specified type with specified GLSL source code.
*
* @alias GpuShader
* @constructor
* @classdesc
* Represents an OpenGL shading language (GLSL) shader and provides methods for compiling and disposing
* of them.
*
* @param {WebGLRenderingContext} gl The current WebGL context.
* @param {Number} shaderType The type of shader, either WebGLRenderingContext.VERTEX_SHADER
* or WebGLRenderingContext.FRAGMENT_SHADER.
* @param {String} shaderSource The shader's source code.
* @throws {ArgumentError} If the shader type is unrecognized, the shader source is null or undefined or shader
* compilation fails. If the compilation fails the error thrown contains any compilation messages.
*/
var GpuShader = function (gl, shaderType, shaderSource) {
if (!(shaderType === gl.VERTEX_SHADER
|| shaderType === gl.FRAGMENT_SHADER)) {
throw new ArgumentError(Logger.logMessage(Logger.LEVEL_SEVERE, "GpuShader", "constructor",
"The specified shader type is unrecognized."));
}
if (!shaderSource) {
throw new ArgumentError(Logger.logMessage(Logger.LEVEL_SEVERE, "GpuShader", "constructor",
"The specified shader source is null or undefined."));
}
var shader = gl.createShader(shaderType);
if (!shader) {
throw new ArgumentError(Logger.logMessage(Logger.LEVEL_SEVERE, "GpuShader", "constructor",
"Unable to create shader of type " +
(shaderType == gl.VERTEX_SHADER ? "VERTEX_SHADER." : "FRAGMENT_SHADER.")));
}
if (!this.compile(gl, shader, shaderType, shaderSource)) {
var infoLog = gl.getShaderInfoLog(shader);
gl.deleteShader(shader);
throw new ArgumentError(Logger.logMessage(Logger.LEVEL_SEVERE, "GpuShader", "constructor",
"Unable to compile shader: " + infoLog));
}
this.shaderId = shader;
};
/**
* Compiles the source code for this shader. This method is not meant to be invoked by applications. It is
* invoked internally as needed.
* @param {WebGLRenderingContext} gl The current WebGL rendering context.
* @param {WebGLShader} shaderId The shader ID.
* @param {Number} shaderType The type of shader, either WebGLRenderingContext.VERTEX_SHADER
* or WebGLRenderingContext.FRAGMENT_SHADER.
* @param {String} shaderSource The shader's source code.
* @returns {boolean} <code>true</code> if the shader compiled successfully, otherwise <code>false</code>.
*/
GpuShader.prototype.compile = function (gl, shaderId, shaderType, shaderSource) {
gl.shaderSource(shaderId, shaderSource);
gl.compileShader(shaderId);
return gl.getShaderParameter(shaderId, gl.COMPILE_STATUS);
};
/**
* Releases this shader's WebGL shader.
* @param {WebGLRenderingContext} gl The current WebGL rendering context.
*/
GpuShader.prototype.dispose = function (gl) {
if (this.shaderId) {
gl.deleteShader(this.shaderId);
delete this.shaderId;
}
};
return GpuShader;
});
|
var moment = require('moment');
module.exports = Date.prototype.toMysqlFormat = function() {
return moment(arguments[0] || this).format('YYYY-MM-DDTHH:MM:SS');
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:172e5cf7d9ea54b217fcf33176924d01797be49274ef1f3ba8c7716b39a54d1d
size 564025
|
window.rnd = m => ~~(Math.random() * m);
window.t = new THREE.ImageUtils.loadTexture('./lost.png');
window.t.minFilter = window.t.magFilter = 1003;
window.pal = new THREE.ImageUtils.loadTexture('./palettes.png');
window.pal.minFilter = window.pal.magFilter = 1003;
|
/*
* These are globally available services in any component or any other service
*/
"use strict";
// Angular 2
var common_1 = require('@angular/common');
// Angular 2 Http
var http_1 = require('@angular/http');
// Angular 2 Router
var router_1 = require('@angular/router');
// Angular 2 Material
// TODO(gdi2290): replace with @angular2-material/all
// import {MATERIAL_PROVIDERS} from './angular2-material2';
/*
* Application Providers/Directives/Pipes
* providers/directives/pipes that only live in our browser environment
*/
exports.APPLICATION_PROVIDERS = common_1.FORM_PROVIDERS.concat(http_1.HTTP_PROVIDERS, router_1.ROUTER_PROVIDERS, [
{ provide: common_1.LocationStrategy, useClass: common_1.HashLocationStrategy }
]);
exports.PROVIDERS = exports.APPLICATION_PROVIDERS.slice();
//# sourceMappingURL=providers.js.map
|
'use strict';
angular.module('copayApp.controllers').controller('preferencesBwsUrlController',
function($scope, $log, $stateParams, configService, applicationService, profileService, storageService, appConfigService) {
$scope.success = null;
var wallet = profileService.getWallet($stateParams.walletId);
$scope.wallet = wallet;
var walletId = wallet.credentials.walletId;
var defaults = configService.getDefaults();
var config = configService.getSync();
$scope.appName = appConfigService.nameCase;
$scope.bwsurl = {
value: (config.bwsFor && config.bwsFor[walletId]) || defaults.bws.url
};
$scope.resetDefaultUrl = function() {
$scope.bwsurl.value = defaults.bws.url;
};
$scope.save = function() {
var bws;
switch ($scope.bwsurl.value) {
case 'prod':
case 'production':
bws = 'http://bws.aureus.cc/bws/api'
break;
case 'sta':
case 'staging':
bws = 'http://bws.aureus.cc/bws/api'
break;
case 'loc':
case 'local':
bws = 'http://localhost:3232/bws/api'
break;
};
if (bws) {
$log.info('Using BWS URL Alias to ' + bws);
$scope.bwsurl.value = bws;
}
var opts = {
bwsFor: {}
};
opts.bwsFor[walletId] = $scope.bwsurl.value;
configService.set(opts, function(err) {
if (err) $log.debug(err);
storageService.setCleanAndScanAddresses(walletId, function() {
applicationService.restart();
});
});
};
});
|
var FieldGen=cc.PhysicsSprite.extend({
ctor:function(space, father, mother, pos, rot){
this._super(res.bossGenOff_img);
this.space=space;
this.father=father;
this.mother=mother;
this.active=false;
this.toDel=false;
this.contentSize = this.getContentSize();
this.body=new cp.Body(1, cp.momentForBox(1,this.contentSize.width, this.contentSize.height));
this.space.addBody(this.body);
this.setBody(this.body);
this.body.ajar="FieldGen";
this.body.father=this;
this.setPosition(pos);
this.rotation=rot;
this.scale=0.5;
this.shape=null;
this.energy=new cc.Sprite(res.bossGenOn_img);
this.energy.attr({
x:this.x,
y:this.y,
scale:this.scale,
rotation:this.rotation
});
this.father.addChild(this.energy, 2);
this.scheduleUpdate();
this.space.addCollisionHandler(ColType.FieldGen, ColType.missilP, this.collision.bind(this), null, null, null);
},
update:function(dt){
if(this.toDel){
this.remove();
}else{
if(this.mother.active!=this.active){
this.active=this.mother.active;
if(this.mother.active){
this.on();
}else{
this.off();
};
};
};
},
on:function(){
this.energy.setOpacity(255);
this.energy.runAction(new cc.fadeTo(10, 0));
if(this.shape!=null){
this.body.removeShape(this.shape);
this.space.removeShape(this.shape);
};
},
off:function(){
this.shape= new cp.BoxShape(this.body, (this.contentSize.width*this.scale), (this.contentSize.height*this.scale));
this.shape.setCollisionType(ColType.FieldGen);
this.space.addShape(this.shape);
},
del:function(){
this.toDel=true;
},
remove:function(){
this.body.removeShape(this.shape);
this.space.removeShape(this.shape);
this.space.removeBody(this.body);
this.release();
this.father.removeChild(this);
this.unscheduleUpdate();
},
collision:function(arbiter, space){
if(arbiter.body_a.ajar=="FieldGen"){
arbiter.body_a.father.del();
arbiter.body_a.father.mother.dest();
arbiter.body_b.parent.del();
}else{
arbiter.body_b.father.del();
arbiter.body_b.father.mother.dest();
arbiter.body_a.parent.del();
};
}
});
|
var App = App || {};
(function() {
'use strict';
var events = Backbone.Events;
var Router = Backbone.Router.extend({
routes: {
'': 'index',
'about': 'about',
'contact': 'contact'
},
initialize: function(callback) { // keep an eye on callback
callback(this);
},
execute: function(callback, args, name) {
events.trigger('wait');
$script('scripts/components/' + name + '.js', function() {
if (callback) callback.apply(this, args);
});
},
index: function() {
events.trigger('change', App.Index);
},
about: function() {
events.trigger('change', App.About);
},
contact: function() {
events.trigger('change', App.Contact);
}
});
App.Router = Router;
})();
|
import React, { PropTypes } from 'react';
import { Field } from 'redux-form';
import { Form, Button, Message } from 'semantic-ui-react';
import { FormField } from '../../../components';
const SignupForm = ({ pristine, submitError, submitting, onSubmit }) => (
<div>
<Message content={submitError} error header='Signup Failed!' hidden={!submitError} />
<Form size='large' onSubmit={onSubmit}>
<Field
component={FormField}
icon='mail'
label='Username'
name='username'
placeholder='username'
type='text'
/>
<Field
component={FormField}
icon='lock'
label='Password'
name='password'
placeholder='password'
type='password'
/>
<Field
component={FormField}
icon='lock'
label='Repeat password'
name='repeatPassword'
placeholder='repeat password'
type='password'
/>
<Button className='primary' disabled={pristine || submitting} fluid size='large' type='submit'>
Signup
</Button>
</Form>
</div>
);
SignupForm.propTypes = {
pristine: PropTypes.bool,
submitError: PropTypes.string,
submitting: PropTypes.bool,
onSubmit: PropTypes.func,
};
export default SignupForm;
|
"use strict";
var IRoute = require('./../src/i-route.js');
describe('IRoute #param', function() {
describe('When I add a route with 1 param', function(){
var route;
beforeEach(function(){
route = new IRoute();
});
it('should have a just 1 route', function(){
var count=0;
route.add('/teste/:id', function(request, next){
count++;
});
route.execute('/teste/1');
expect(count).to.equal(1);
});
it('should have a just 2 route', function(){
var count=0;
route.add('/teste/:id', function(request, next){
count++;
next();
});
route.add('/teste/1', function(request, next){
count++;
next();
});
route.execute('/teste/1');
expect(count).to.equal(2);
});
});
describe('When I add a route with 1 param', function(){
var route;
beforeEach(function(){
route = new IRoute();
});
it('and get the param', function(){
var count=0;
var id;
var name;
route.add('/teste/:id/teste/:name', function(request, next){
id = request.param.id;
name = request.param.name;
});
route.execute('/teste/1/teste/testename');
expect(id).to.equal('1');
expect(name).to.equal('testename');
});
it('and I have optional param', function(){
var count=0;
var id;
var name;
route.add('/teste/:id/teste/:name?', function(request, next){
id = request.param.id;
name = request.param.name;
});
route.execute('/teste/1/teste');
expect(id).to.equal('1');
expect(name).to.equal(undefined);
});
});
});
|
(function(window, factory) {
if (typeof define === 'function' && define.amd) {
define([], function() {
return factory();
});
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory();
} else {
(window.LocaleData || (window.LocaleData = {}))['fr_FR@euro'] = factory();
}
}(typeof window !== "undefined" ? window : this, function() {
return {
"LC_ADDRESS": {
"postal_fmt": "%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N",
"country_name": "France",
"country_post": null,
"country_ab2": "FR",
"country_ab3": "FRA",
"country_num": 250,
"country_car": "F",
"country_isbn": "979-10",
"lang_name": "fran\u00e7ais",
"lang_ab": "fr",
"lang_term": "fra",
"lang_lib": "fre"
},
"LC_MEASUREMENT": {
"measurement": 1
},
"LC_MESSAGES": {
"yesexpr": "^[+1oOyY]",
"noexpr": "^[-0nN]",
"yesstr": "oui",
"nostr": "non"
},
"LC_MONETARY": {
"currency_symbol": "\u20ac",
"mon_decimal_point": ",",
"mon_thousands_sep": "\u202f",
"mon_grouping": 3,
"positive_sign": "",
"negative_sign": "-",
"frac_digits": 2,
"p_cs_precedes": 0,
"p_sep_by_space": 1,
"n_cs_precedes": 0,
"n_sep_by_space": 1,
"p_sign_posn": 1,
"n_sign_posn": 1,
"int_curr_symbol": "EUR ",
"int_frac_digits": 2,
"int_p_cs_precedes": null,
"int_p_sep_by_space": null,
"int_n_cs_precedes": null,
"int_n_sep_by_space": null,
"int_p_sign_posn": null,
"int_n_sign_posn": null
},
"LC_NAME": {
"name_fmt": "%d%t%g%t%m%t%f",
"name_gen": null,
"name_mr": null,
"name_mrs": null,
"name_miss": null,
"name_ms": null
},
"LC_NUMERIC": {
"decimal_point": ",",
"thousands_sep": "\u202f",
"grouping": 3
},
"LC_PAPER": {
"height": 297,
"width": 210
},
"LC_TELEPHONE": {
"tel_int_fmt": "+%c %a %l",
"tel_dom_fmt": "%a %l",
"int_select": "00",
"int_prefix": "33"
},
"LC_TIME": {
"date_fmt": "%a %b %e %H:%M:%S %Z %Y",
"abday": [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
"day": [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
],
"week": [
7,
19971130,
4
],
"abmon": [
"janv.",
"f\u00e9vr.",
"mars",
"avril",
"mai",
"juin",
"juil.",
"ao\u00fbt",
"sept.",
"oct.",
"nov.",
"d\u00e9c."
],
"mon": [
"janvier",
"f\u00e9vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\u00fbt",
"septembre",
"octobre",
"novembre",
"d\u00e9cembre"
],
"d_t_fmt": "%a %d %b %Y %T %Z",
"d_fmt": "%d\/\/%m\/\/%Y",
"t_fmt": "%T",
"am_pm": [
"",
""
],
"t_fmt_ampm": "",
"era": null,
"era_year": null,
"era_d_t_fmt": null,
"era_d_fmt": null,
"era_t_fmt": null,
"alt_digits": null,
"first_weekday": 2,
"first_workday": null,
"cal_direction": null,
"timezone": null
}
};
}));
|
'use strict';
const Gulp = require('gulp');
const Sass = require('gulp-sass');
const Paths = require('../config/assets');
const Autoprefixer = require('gulp-autoprefixer');
Gulp.task('styles', function() {
Gulp.src('./assets/styles/index.scss')
.pipe(Sass().on('error', Sass.logError))
.pipe(Autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(Gulp.dest('.build/css/'));
});
Gulp.task('fonts', function() {
return Gulp.src(Paths.get('/fonts'))
.pipe(Gulp.dest('.build/fonts'));
});
Gulp.task('images', function() {
return Gulp.src(Paths.get('/images'))
.pipe(Gulp.dest('.build/images'));
});
Gulp.task('misc', function() {
return Gulp.src(Paths.get('/misc'))
.pipe(Gulp.dest('.build/misc'));
});
Gulp.task('fonts', function() {
return Gulp.src(Paths.get('/fonts'))
.pipe(Gulp.dest('.build/fonts'));
});
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["fastMemoize"] = factory();
else
root["fastMemoize"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict'
var cacheDefault = __webpack_require__(1)
var serializerDefault = __webpack_require__(4)
function memoize (fn, options) {
var cache
var serializer
if (options && options.cache) {
cache = options.cache
} else {
cache = cacheDefault
}
if (options && options.serializer) {
serializer = options.serializer
} else {
serializer = serializerDefault
}
function memoized () {
var cacheKey
if (arguments.length === 1) {
cacheKey = arguments[0]
} else {
cacheKey = serializer(arguments)
}
if (!memoized._cache.has(cacheKey)) {
memoized._cache.set(cacheKey, fn.apply(this, arguments))
}
return memoized._cache.get(cacheKey)
}
memoized._cache = cache.create()
return memoized
}
module.exports = memoize
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict'
var mapCache = __webpack_require__(2)
var objectCache = __webpack_require__(3)
function create () {
var cache
if (mapCache.hasSupport()) {
cache = mapCache.create()
} else {
cache = objectCache.create()
}
return cache
}
module.exports = {
create: create
}
/***/ },
/* 2 */
/***/ function(module, exports) {
'use strict'
function hasSupport () {
var hasSupport = true
try {
var map = new Map()
map.set(null)
} catch (error) {
hasSupport = false
} finally {
return hasSupport
}
}
function create () {
var cache = new Map()
cache._name = 'Map'
return cache
}
module.exports = {
create: create,
hasSupport: hasSupport
}
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict'
function ObjectCache () {
this._cache = {}
// Removing prototype makes key lookup faster.
this._cache.prototype = null
this._name = 'Object'
}
ObjectCache.prototype.has = function (key) {
return (key in this._cache)
}
ObjectCache.prototype.get = function (key) {
return this._cache[key]
}
ObjectCache.prototype.set = function (key, value) {
this._cache[key] = value
}
// IE8 crashes if we use a method called `delete` with dot-notation.
ObjectCache.prototype['delete'] = function (key) {
delete this._cache[key]
}
module.exports = {
create: function () {
return new ObjectCache()
}
}
/***/ },
/* 4 */
/***/ function(module, exports) {
'use strict'
function jsonStringify () {
return JSON.stringify(arguments)
}
jsonStringify._name = 'jsonStringify'
module.exports = jsonStringify
/***/ }
/******/ ])
});
;
|
let store = {
};
module.exports = store;
|
var config = require('../config')
if (!config.tasks.api) return
var browserSync = require('browser-sync')
//var data = require('gulp-data')
var gulp = require('gulp')
var gulpif = require('gulp-if')
var handleErrors = require('../lib/handleErrors')
var htmlmin = require('gulp-htmlmin')
var path = require('path')
var del = require('del')
//var render = require('gulp-nunjucks-render')
var fs = require('fs')
//var exclude = path.normalize('!**/{' + config.tasks.html.excludeFolders.join(',') + '}/**')
var paths = {
src: [path.join(config.root.src, config.tasks.api.src, '**/*.json')],
dest: path.join(config.root.dest, config.tasks.api.dest)
}
var apiTask = function () {
//render.nunjucks.configure([path.join(config.root.src, config.tasks.html.src)], {watch: false})
gulp.src(paths.src)
//.pipe(data(getData))
.on('error', handleErrors)
// .pipe(render())
//.on('error', handleErrors)
.pipe(gulp.dest(paths.dest))
.pipe(browserSync.stream())
}
gulp.task('api', apiTask)
module.exports = apiTask
|
version https://git-lfs.github.com/spec/v1
oid sha256:457b1e468987f644791c68cd2c904cca9cd0fea58afa771c3eea905b6643db6b
size 33695
|
const fs = require('fs'),
path = require('path');
let reader = fs.createReadStream(path.join(__dirname, 'tmp.txt'))
reader.on('readable', function() {
while (true) {
let chunkLen = reader.read(4);
if (!chunkLen) {
break;
}
let len = chunkLen.readUInt32LE();
let buf = reader.read(len);
let json = buf.toString('utf8');
console.log(json);
}
})
// let writer = fs.createWriteStream(path.join(__dirname, 'tmp.js'));
// let objs = [
// { name: '张三', age: 10 },
// { name: '张三', age: 11 },
// { name: '张三', age: 12 },
// { name: '张三', age: 13 }
// ]
// for (var key in objs) {
// if (objs.hasOwnProperty(key)) {
// var obj = objs[key];
// let json = JSON.stringify(obj);
// let buf = new Buffer(json);
// let bufLen = new Buffer(4);
// bufLen.writeInt32LE(buf.length);
// writer.write(bufLen);
// writer.write(buf);
// }
// }
|
'use strict';
var _tslib = require('./_tslib.js');
var aureliaFramework = require('aurelia-framework');
var uiInternal = require('./ui-internal.js');
var BaseInput = (function () {
function BaseInput(element) {
this.element = element;
this.maxlength = 0;
this.allowClear = false;
this.showCounter = false;
this.readonly = false;
this.disabled = false;
this.isDisabled = false;
this.allowClear = element.hasAttribute("clear") || element.hasAttribute("clear.trigger");
this.showCounter = element.hasAttribute("counter");
}
BaseInput.prototype.focus = function () {
this.inputEl.focus();
};
BaseInput.prototype.disable = function (b) {
this.isDisabled = b;
};
Object.defineProperty(BaseInput.prototype, "classes", {
get: function () {
var classes = [];
if (this.errors && this.errors.length > 0) {
classes.push("ui-input--invalid");
}
if (this.isTrue("readonly")) {
classes.push("ui-input--readonly");
}
if (this.isTrue("disabled") || this.isDisabled) {
classes.push("ui-input--disabled");
}
return classes.join(" ");
},
enumerable: true,
configurable: true
});
BaseInput.prototype.bind = function () {
this.readonly = this.isTrue("readonly");
this.disabled = this.isTrue("disabled");
};
BaseInput.prototype.clear = function () {
this.value = "";
this.inputEl.focus();
this.element.dispatchEvent(uiInternal.UIInternal.createEvent("clear"));
this.element.dispatchEvent(uiInternal.UIInternal.createEvent("change"));
};
BaseInput.prototype.fireEnter = function ($event) {
if ($event.keyCode === 13) {
$event.stopEvent();
this.element.dispatchEvent(uiInternal.UIInternal.createEvent("enterpressed", this.value));
}
return true;
};
BaseInput.prototype.canToggleDrop = function (evt) {
if (evt.relatedTarget && evt.relatedTarget !== this.inputEl) {
this.toggleDrop(false);
}
};
BaseInput.prototype.toggleDrop = function (open) {
var _this = this;
if (open === true && this.dropEl.isOpen) {
uiInternal.UIInternal.queueMicroTask(function () { return _this.dropEl.updatePosition(); });
return;
}
var beforeEvent = this.dropEl.isOpen && !open ? "beforeclose" : "beforeopen";
var afterEvent = this.dropEl.isOpen && !open ? "close" : "open";
if (this.element.dispatchEvent(uiInternal.UIInternal.createEvent(beforeEvent)) !== false) {
this.dropEl.toggleDrop(open);
this.element.dispatchEvent(uiInternal.UIInternal.createEvent(afterEvent));
if (this.dropEl.isOpen) {
this.inputEl.select();
return true;
}
else {
return false;
}
}
};
BaseInput.prototype.isTrue = function (prop) {
return this[prop] === "" || this[prop] === prop || isTrue(this[prop]);
};
_tslib.__decorate([
aureliaFramework.computedFrom("isDisabled", "disabled", "readonly", "errors", "errors.length"),
_tslib.__metadata("design:type", String),
_tslib.__metadata("design:paramtypes", [])
], BaseInput.prototype, "classes", null);
return BaseInput;
}());
var view = "<template>\n <div class=\"ui-input__error\" if.bind=\"errors && errors.length\">\n <ui-svg-icon icon=\"alert\"></ui-svg-icon>\n <ul>\n <li repeat.for=\"err of errors\">${err.message || err}</li>\n </ul>\n </div>\n <div class=\"ui-input__counter\" if.bind=\"showCounter && (value.length > 0 || maxlength > 0)\">\n ${counter}\n </div>\n <div class=\"ui-input__clear\" if.bind=\"allowClear && value.length > 0\" click.trigger=\"clear()\">\n <ui-svg-icon icon=\"cross\"></ui-svg-icon>\n </div>\n <div class=\"ui-input__drop-handle\" if.bind=\"dropHandle\" click.trigger=\"toggleDrop()\">\n <ui-svg-icon icon.bind=\"dropHandle\"></ui-svg-icon>\n </div>\n <slot></slot>\n</template>\n";
var InputWrapper = (function () {
function InputWrapper() {
}
InputWrapper = _tslib.__decorate([
aureliaFramework.containerless(),
aureliaFramework.inlineView(view),
aureliaFramework.processContent(function (compiler, resources, node, instruction) {
instruction.inheritBindingContext = true;
return true;
})
], InputWrapper);
return InputWrapper;
}());
exports.BaseInput = BaseInput;
exports.InputWrapper = InputWrapper;
//# sourceMappingURL=input-wrapper.js.map
|
/**
* @component : checkAll全选
* @version : {{VERSION}}
* @author : tommyshao <[email protected]>
* @created : 2016-07-05
* @description :
* @useage :
## 用法
```
<input type="checkbox" data-toggle="checkAll" data-target="selector" />
$(element).on('checked.ui.checkAll', function(e){ e.relatedTarget; });
$(element).on('reversed.ui.checkAll', function(e){ e.relatedTarget; });
```
*/
'use strict';
const $ = require('jquery')
const toggle = '[data-toggle="checkAll"]'
class CheckAll {
// 构造函数
// -------
// * `element` dom元素对象
constructor(element) {
// dom元素
this.$el = $(element)
// 响应元素集合
this.$target = $(this.$el.data('target'))
// 是否反选模式
this.isReverse = Boolean(this.$el.data('reverse'))
// 是否全选不会影响响应元素
this.isNoCheckAll = Boolean(this.$el.data('nocheckall'))
// 版本号
this.VERSION = '{{VERSION}}';
// 初始化事件
this.initEvents()
}
// 事件监听
initEvents() {
// 监听 `click` 点击事件,如果全选不影响单选状态则不监听
this.$el.on('click', $.proxy(this.toggle, this));
// 对全选监听change.toggle事件用于触发单选状态改变全选状态,反选则不触发
!this.isReverse && this.$target.on('change.status', $.proxy(this.targetToggle, this));
}
// 切换中枢
// -------
toggle() {
this.isReverse ? this.reverse() : this.activate()
}
// 单选状态改变全选状态 by Limit
targetToggle() {
// 反选按钮则退出
if (this.isReverse) {
return false;
}
let isCheckAlled = true;
if (!this.isNoCheckAll) {
// 全部选上才触发对象勾选激活
this.$target.map(function() {
if (!$(this).prop('checked')) {
isCheckAlled = false;
return false;
}
});
} else {
// 非全选状态下,只要勾选一个就认为对象勾选激活
isCheckAlled = false;
this.$target.map(function() {
if ($(this).prop('checked')) {
isCheckAlled = true;
return false;
}
});
}
this.$el.prop('checked', isCheckAlled).trigger('change.status');
}
// 全选功能
// --------
// Function activate
activate(isChecked) {
let [
isCheck,
e
] = [
// button触发全选传值可能为false
(!isChecked && isChecked !== false) ? this.$el.is(':checked') : isChecked, // 当前dom元素是否勾选
$.Event('checked.bp.checkAll', {
relatedTarget: this.$el
}) // 创建选中事件
]
// button触发全选时,设置全选为选中 by limit
this.$el.prop('checked', isCheck)
// 设置所有目标元素属性
if (this.isNoCheckAll) {
!isCheck && this.$target.prop('checked', isCheck)
} else {
this.$target.prop('checked', isCheck)
}
// 触发反选事件api
this.$el.trigger(e)
}
// 反选功能
// -------
reverse() {
// 定义反选事件类型
let e = $.Event('reversed.bp.checkAll', {
relatedTarget: this.$el
})
// 遍历所有目标元素,将他们选中属性反转
this.$target.map(function() {
return $(this).prop('checked', function() {
return !$(this).prop('checked')
}).trigger('change.status');
});
// 触发反选事件api
this.$el.trigger(e);
}
}
// 插件定义
// -------
let Plugin = function(option, ...args) {
return $(this).each(() => {
let [$this, data] = [
$(this),
$(this).data('bp.checkAll')
];
if (!data) {
$this.data('bp.checkAll', (data = new CheckAll(this)));
if (option === 'toggle') data.toggle();
}
if (typeof option === 'string' && option !== 'toggle') data[option](...args);
})
}
// jQuery 插件扩展
// -------------
$.fn.checkAll = Plugin;
$.fn.checkAll.Constructor = CheckAll;
// 全局绑定插件
// -------------
// $(function() {
// $(toggle).checkAll()
// });
$(function() {
// 全局绑定插件 单选和全选交互 by limit
$(document).on('click.checkAll', ':checkbox',function(e) {
$(toggle).map(function() {
if (!$(this).data('isCheckAllInited')) {
// 如果为当前点击的checkBox则调用toggle
e.target == this ? $(this).checkAll('toggle') : $(this).checkAll();
$(this).data('isCheckAllInited', true);
}
})
// $(this).checkAll('toggle')
})
// 全局绑定插件 单选和全选交互 by limit 这样会导致新渲染的checkAll控件组无法激活插件
// $(toggle).map(function() {
// $(this).checkAll();
// });
})
module.exports = CheckAll
|
'use strict';
(function(){
angular
.module('beattweakApp')
.factory('socket-new', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
});
})();
|
var createLogger = require("../lib/logger");
var expect = require("chai").expect;
var utilities = require("./helpers/utilities");
describe("A logger", function () {
var restoreEnvironment;
function captureOutput (fn) {
var buffer = [];
var oldWrite = process.stdout.write;
process.stdout.write = buffer.push.bind(buffer);
try {
fn();
}
finally {
process.stdout.write = oldWrite;
}
return buffer.join("");
}
before(function () {
restoreEnvironment = utilities.clearEnvironment();
});
after(function () {
restoreEnvironment();
});
describe("using the default settings", function () {
var output;
before(function () {
var logger = createLogger();
output = captureOutput(function () {
logger.info("hello");
});
});
it("logs to stdout", function () {
expect(output, "failed to write to stdout").to.contain("hello\n");
});
});
describe("with NODE_ENV set to 'test'", function () {
var restoreEnvironment;
before(function () {
restoreEnvironment = utilities.setEnvironmentVariable("NODE_ENV", "test");
});
after(function () {
restoreEnvironment();
});
it("is silent", function () {
var logger = createLogger();
var output = captureOutput(function () {
logger.info("hello");
});
expect(output, "wrote to stdout").to.equal("");
});
describe("and ENABLE_LOGGING set to 'true'", function () {
var restoreEnvironment;
before(function () {
restoreEnvironment = utilities.setEnvironmentVariable("ENABLE_LOGGING", "true");
});
after(function () {
restoreEnvironment();
});
it("logs to stdout", function () {
var logger = createLogger();
var output = captureOutput(function () {
logger.info("hello");
});
expect(output, "failed to write to stdout").to.contain("hello\n");
});
});
});
});
|
var SolemnJS = require('../lib/solemn-js');
var Profane = require('Profane');
var _ = require('lodash');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.solemnjs = {
setUp: function(done) {
// setup here if necessary
this.s = new SolemnJS();
done();
},
detect: function(test) {
test.expect(1);
var violations = this.s.detect('test/fixtures/script.js');
test.equal(violations.length, 3);
test.done();
},
get_dictionary: function(test) {
test.expect(1);
var dictionary = this.s.getDictionary();
test.ok(_.map(dictionary).length > 0);
test.done();
},
set_dictionary: function(test) {
test.expect(1);
var dictionary = new Profane({
"bad": ["inappropriate"]
});
this.s.setDictionary(dictionary);
test.equal(_.map(dictionary).length, 1);
test.done();
},
};
|
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-dep-concat');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-s3');
grunt.registerMultiTask('templates', 'Convert templates to JavaScript', function() {
var buf = [
'var _T = {};'
];
var files = grunt.file.expandFiles(this.file.src);
files.forEach(function(filepath) {
var templateFileName = filepath.split('templates')[1];
var templateId = templateFileName.substr(1).replace(/\.html$/, '');
var content = grunt.file.read(filepath);
var tmp = [];
content.split("\n").forEach(function(line) {
tmp.push(line.replace(/^\s*</, '<'));
});
buf.push('_T["' + templateId + '"] = ' + JSON.stringify(tmp.join('')) + ';');
});
grunt.file.write(this.file.dest, buf.join("\n"));
grunt.log.writeln('File "' + this.file.dest + '" created.');
});
var depconcat = {
bootstrap: {
src: [
'client/app.js',
'client/common/utils/*.js'
],
dest: 'server/public/js/dist/app.setup.js',
separator: ';'
}
};
['top', 'home', 'gacha', 'item', 'card', 'mission', 'cash'].forEach(function(mod) {
depconcat[mod] = {
src: [
'client/common/{models,collections,views,routers}/*.js',
'client/'+ mod + '/**/*.js'
],
dest: 'server/public/js/dist/app.' + mod + '.js'
};
});
grunt.initConfig({
pkg: '<json:package.json>',
lint: {
files: [
'grunt.js',
'client/**/*.js'
]
},
jshint: {
globals: {
console: true,
Backbone: true,
'$': true,
'_': true,
'__DEBUG__': true,
'ASSET_URL': true
}
},
less: {
development: {
options: {
paths: ['client/common/stylesheets']
},
files: {
'server/public/css/app.css': 'client/common/stylesheets/app.less',
'server/public/css/mission.css': 'client/mission/stylesheets/mission.less',
'server/public/css/gacha.css': 'client/gacha/stylesheets/gacha.less',
'server/public/css/card.css': 'client/card/stylesheets/card.less'
}
}
},
templates: {
debug: {
src: [
'client/*/templates/**/*.html'
],
dest: 'server/public/js/dist/app.templates.js'
}
},
depconcat: depconcat,
aws: '<json:aws.json>',
s3: {
key: '<%= aws.key %>',
secret: '<%= aws.secret %>',
bucket: '<%= aws.bucket %>',
access: 'public-read',
upload: [
{
src : 'server/public/js/*.js',
dest: 'naporitan/js/'
},
{
src : 'server/public/js/dist/*.js',
dest: 'naporitan/js/dist/'
},
{
src : 'server/public/css/*.css',
dest: 'naporitan/css/'
}
]
},
watch: {
files: [
'<config:lint.files>',
'<config:templates.debug.src>'
],
tasks: 'default'
}
});
grunt.registerTask('default', 'lint templates depconcat');
};
|
import React from 'react'
import {
render
} from 'react-dom'
import App from './modules/App'
import {
Router,
Route,
hashHistory,
browserHistory,
IndexRoute
} from 'react-router'
import About from './modules/About'
import Repos from './modules/Repos'
import Repo from './modules/Repo'
import Home from './modules/Home'
render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="/repos" component={Repos}>
<Route path="/repos/:userName/:repoName" component={Repo} />
</Route>
<Route path="/about" component={About} />
</Route>
</Router>
), document.getElementById('app'))
|
export function createWithHandlers(handlers, initialState = {}) {
return function reduce(state = initialState, action = {}) {
return handlers[action.type]
? handlers[action.type](state, action)
: state
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:7cb08431a7331f7435081eeed1beb984a9e64bf1293feee6a6c3917324e23ec3
size 17244
|
var dynColChkbox = function (field, checked) {
/// <summary>
/// 复选框列
/// </summary>
dynCol.apply(this, arguments);
if (checked) {
this.ctr = "<input type='checkbox' checked />";
}
};
dynColChkbox.extend(dynCol, {
ctr: "<input type='checkbox' />",
getVal: function (ctr) {
return $.prop ? ctr.prop("checked") : ctr.attr("checked");
},
setVal: function (ctr, v) {
$.prop ? ctr.prop("checked", v) : ctr.attr("checked", v);
},
read: function (ctr, row) {
row[this.name] = this.getVal(ctr);
},
write: function (ctr, row) {
this.setVal(ctr, row[this.name]);
},
onValidate: function (ctr, index, td, grid) {
return true;
},
onCellCreated: function (ctr, idx, allowEdit) {
ctr.parent().css("text-align", "center");
},
getDisplayText: function (ctr) {
return this.getVal(ctr) ? "是" : "否";
}
});
|
this.fitie = function (node) {
// restrict to valid object-fit value
var objectFit = node.currentStyle['object-fit'];
if (!objectFit || !/^(contain|cover|fill)$/.test(objectFit)) return;
// prepare container styles
var outerWidth = node.clientWidth;
var outerHeight = node.clientHeight;
var outerRatio = outerWidth / outerHeight;
var name = node.nodeName.toLowerCase();
var setCSS = node.runtimeStyle;
var getCSS = node.currentStyle;
var addEventListener = node.addEventListener || node.attachEvent;
var removeEventListener = node.removeEventListener || node.detachEvent;
var on = node.addEventListener ? '' : 'on';
var img = name === 'img';
var type = img ? 'load' : 'loadedmetadata';
addEventListener.call(node, on + type, onload);
if (node.complete) onload();
function onload() {
removeEventListener.call(node, on + type, onload);
// prepare container styles
var imgCSS = {
boxSizing: 'content-box',
display: 'inline-block',
overflow: 'hidden'
};
'backgroundColor backgroundImage borderColor borderStyle borderWidth bottom fontSize lineHeight height left opacity margin position right top visibility width'.replace(/\w+/g, function (key) {
imgCSS[key] = getCSS[key];
});
// prepare image styles
setCSS.border = setCSS.margin = setCSS.padding = 0;
setCSS.display = 'block';
setCSS.height = setCSS.width = 'auto';
setCSS.opacity = 1;
var innerWidth = node.videoWidth || node.width;
var innerHeight = node.videoHeight || node.height;
var innerRatio = innerWidth / innerHeight;
// style container
var imgx = document.createElement('object-fit');
imgx.appendChild(node.parentNode.replaceChild(imgx, node));
for (var key in imgCSS) imgx.runtimeStyle[key] = imgCSS[key];
// style image
var newSize;
if (objectFit === 'fill') {
if (img) {
setCSS.width = outerWidth;
setCSS.height = outerHeight;
} else {
setCSS['-ms-transform-origin'] = '0% 0%';
setCSS['-ms-transform'] = 'scale(' + outerWidth / innerWidth + ',' + outerHeight / innerHeight + ')';
}
} else if (innerRatio < outerRatio ? objectFit === 'contain' : objectFit === 'cover') {
newSize = outerHeight * innerRatio;
setCSS.width = Math.round(newSize) + 'px';
setCSS.height = outerHeight + 'px';
setCSS.marginLeft = Math.round((outerWidth - newSize) / 2) + 'px';
} else {
newSize = outerWidth / innerRatio;
setCSS.width = outerWidth + 'px';
setCSS.height = Math.round(newSize) + 'px';
setCSS.marginTop = Math.round((outerHeight - newSize) / 2) + 'px';
}
}
};
this.fitie.init = function () {
if (document.body) {
var all = document.querySelectorAll('img,video');
var index = -1;
while (all[++index]) fitie(all[index]);
} else {
setTimeout(fitie.init);
}
};
if (/MSIE|Trident/.test(navigator.userAgent)) this.fitie.init();
|
import { filter } from 'reducers/filter'
describe('(Reducer) filter', () => {
it('has default value', () => {
nextFilter = filter(undefined, {})
expect(nextFilter).to.eql('ALL')
})
it('changes filter value', () => {
nextFilter = filter('ACTIVE', {
type: 'CHANGE_FILTER',
filter: 'ALL',
})
expect(nextFilter).to.eql('ALL')
})
})
|
var IOTA = require('iota.lib.js');
var iota = new IOTA({
'host': 'http://45.77.4.212',
'port': 14265
});
//create an array of hashes. This should get its values from the react front end
const POE = {
getHash: function (hash, onSuccess, onFail) {
if (iota.valid.isArrayOfHashes([hash])){
iota.api.getNodeInfo(function(error, success) {
if (error) {
onFail(error);
} else {
iota.api.getTransactionsObjects([hash], function(error, success) {
if (error) {
onFail(error);
} else {
onSuccess(success); // success!
}
});
}
});
}
else {
onFail("invalid hash");
}
},
commitHash: function (seed, doc) {
iota.api.sendTransfer('YRBIARWWUFSGYDQFFISFXGFHZZVZ9YKKJZFCQKM9ENZGSXDQJLPTRONRPKWWFZXDBSEQOUIWVXZFCVRKH', 5, 8, [{
'address': 'ADQIFLUGSHOUWDODBIBJUDXHXRHOESIAWDZSIRLDPSOJXSRBVHDHYISQDG9YQPPOJ9JMU9OAUAFYLPPAQXWYHDUAOR',
'value':1,
}], function(error, success) {
if (error) {
console.error(error);
} else {
console.log(success);
}
})
}
}
module.exports = POE;
|
'use strict';
// according to rfc 2616
function isValidToken(c) {
var isInvalid = c <= 0x20 || c >= 0x7f ||
c === 40 || c === 41 || // ( )
c === 60 || c === 62 || // < >
c === 64 || c === 44 || // @ ,
c === 59 || c === 58 || // ; :
c === 92 || c === 34 || // \ "
c === 47 || c === 91 || // / [
c === 93 || c === 63 || // ] ?
c === 61 || c === 123 || // = {
c === 125; // }
return !isInvalid;
}
var table = new Uint8Array(256);
for (var i = 0; i < 256; ++i) {
table[i] = isValidToken(i) ? i : 0;
}
function isValidCharCode(charCode) {
return table[charCode & 0xff] !== 0;
}
exports.isValidCharCode = isValidCharCode;
exports.isValidMethodCharCode = function(charCode) {
return charCode >= 65 && charCode <= 90; // A-Z
};
exports.isValidToken = function(str) {
if (!str) {
return false;
}
for (var i = 0; i < str.length; ++i) {
if (!isValidCharCode(str.charCodeAt(i))) {
return false;
}
}
return true;
};
exports.isValidHeaderName = isValidToken;
exports.isValidHeaderValue = function(str) {
for (var i = 0; i < str.length; ++i) {
var code = str.charCodeAt(i);
if (code > 127 || code === 0 || code === 10 /* \n */ || code === 13 /* \r */) {
return false;
}
}
return true;
};
|
// WebSQL
// -------
var inherits = require('inherits')
var Transaction = require('./transaction')
var Client_SQLite3 = require('../sqlite3')
var Promise = require('../../promise')
import {assign, map, uniqueId, clone} from 'lodash'
function Client_WebSQL(config) {
Client_SQLite3.call(this, config);
this.name = config.name || 'knex_database';
this.version = config.version || '1.0';
this.displayName = config.displayName || this.name;
this.estimatedSize = config.estimatedSize || 5 * 1024 * 1024;
}
inherits(Client_WebSQL, Client_SQLite3);
assign(Client_WebSQL.prototype, {
Transaction: Transaction,
dialect: 'websql',
// Get a raw connection from the database, returning a promise with the connection object.
acquireConnection: function() {
var client = this;
return new Promise(function(resolve, reject) {
try {
/*jslint browser: true*/
var db = openDatabase(client.name, client.version, client.displayName, client.estimatedSize);
db.transaction(function(t) {
t.__knexUid = uniqueId('__knexUid');
resolve(t);
});
} catch (e) {
reject(e);
}
});
},
// Used to explicitly close a connection, called internally by the pool
// when a connection times out or the pool is shutdown.
releaseConnection: function() {
return Promise.resolve()
},
// Runs the query on the specified connection,
// providing the bindings and any other necessary prep work.
_query: function(connection, obj) {
return new Promise(function(resolver, rejecter) {
if (!connection) return rejecter(new Error('No connection provided.'));
connection.executeSql(obj.sql, obj.bindings, function(trx, response) {
obj.response = response;
return resolver(obj);
}, function(trx, err) {
rejecter(err);
});
});
},
_stream: function(connection, sql, stream) {
var client = this;
return new Promise(function(resolver, rejecter) {
stream.on('error', rejecter)
stream.on('end', resolver)
return client._query(connection, sql).then(function(obj) {
return client.processResponse(obj)
}).map(function(row) {
stream.write(row)
}).catch(function(err) {
stream.emit('error', err)
}).then(function() {
stream.end()
})
})
},
processResponse: function(obj, runner) {
var resp = obj.response;
if (obj.output) return obj.output.call(runner, resp);
switch (obj.method) {
case 'pluck':
case 'first':
case 'select':
var results = [];
for (var i = 0, l = resp.rows.length; i < l; i++) {
results[i] = clone(resp.rows.item(i));
}
if (obj.method === 'pluck') results = map(results, obj.pluck);
return obj.method === 'first' ? results[0] : results;
case 'insert':
return [resp.insertId];
case 'delete':
case 'update':
case 'counter':
return resp.rowsAffected;
default:
return resp;
}
},
ping: function(resource, callback) {
callback();
}
})
module.exports = Client_WebSQL;
|
// Karma configuration
// Generated on Sat Mar 15 2014 13:59:05 GMT+0200 (EET)
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'js/**/*.js',
'test/**/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'js/**/*.js': 'coverage'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],//, 'coverage'],
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-coverage'
],
coverageReporter: {
type: 'html',
dir: 'coverage/'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],//, 'Chrome', 'Opera', 'ChromeCanary', 'Firefox', 'Safari', 'PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
|
/* 图片自动上传 */
var uploadCount = 0, uploadList = [], uploadSuccessCount = 0;
var uploadFilePathList = [];
var uploadCountDom = document.getElementById("uploadCount");
weui.uploader('#uploaderCustom', {
url: '/qrcode/insight/upload',
auto: true,
type: 'file',
compress: {
width: 1600,
height: 1600,
quality: .6
},
onBeforeQueued: function(files) {
if(["image/jpg", "image/jpeg", "image/png", "image/gif"].indexOf(this.type) < 0){
$.alert('请上传图片');
return false;
}
if(this.size > 50 * 1024 * 1024){
$.alert('请上传不超过50M的图片');
return false;
}
if (files.length > 5) { // 防止一下子选中过多文件
$.alert('最多只能上传5张图片,请重新选择');
return false;
}
if (files.length <= 0) { // 防止传空
$.alert('请选择至少一张图片');
return false;
}
if (uploadCount + 1 > 5) {
$.alert('最多只能上传5张图片');
return false;
}
++uploadCount;
uploadCountDom.innerHTML = uploadCount;
},
onQueued: function(){
uploadList.push(this);
},
onBeforeSend: function(data, headers){
console.log('beforesend');
},
onProgress: function(procent){
console.log('progress');
},
onSuccess: function (ret) {
if (ret.responseCode == 'RESPONSE_OK')
{
uploadFilePathList.push(ret.data);
}
},
onError: function(err){
console.log(this, err);
}
});
// 手动上传按钮
document.getElementById("uploaderCustomBtn").addEventListener('click', function(){
var codeId = document.getElementById('txt_des').value;
console.log(uploadFilePathList.join(";"));
$.post('/qrcode/insight/upload/' + codeId, {'filePath': uploadFilePathList.join(";")}, function(data){
console.log("upload" + data);
});
});
// 缩略图预览
document.querySelector('#uploaderCustomFiles').addEventListener('click', function(e){
var target = e.target;
while(!target.classList.contains('weui-uploader__file') && target){
target = target.parentNode;
}
if(!target) return;
var url = target.getAttribute('style') || '';
var id = target.getAttribute('data-id');
if(url){
url = url.match(/url\((.*?)\)/)[1].replace(/"/g, '');
}
var gallery = weui.gallery(url, {
onDelete: function(){
weui.confirm('确定删除该图片?', function(){
var index;
for (var i = 0, len = uploadCustomFileList.length; i < len; ++i) {
var file = uploadCustomFileList[i];
if(file.id == id){
index = i;
break;
}
}
if(index !== undefined) uploadCustomFileList.splice(index, 1);
target.remove();
gallery.hide();
});
}
});
});
//问题描述
$("#txt_des").on('input', function () {
if (this.value.length >= 140) {
$("#txt_des").val(this.value.substring(0, 140));
return;
}
$("#des_count").text(this.value.length);
});
|
import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
const Spinner = ({ color, only, className }) => {
const spinnerClasses = cx('spinner-layer', {
[`spinner-${color}-only`]: only,
[`spinner-${color}`]: !only
});
return (
<div className={cx(spinnerClasses, className)}>
<div className="circle-clipper left">
<div className="circle" />
</div>
<div className="gap-patch">
<div className="circle" />
</div>
<div className="circle-clipper right">
<div className="circle" />
</div>
</div>
);
};
Spinner.defaultProps = {
only: true
};
Spinner.propTypes = {
className: PropTypes.string,
color: PropTypes.string,
only: PropTypes.bool
};
export default Spinner;
|
module.exports = require('./lib/procexss');
|
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import { Icon } from 'semantic-ui-react';
import {selectChannel, fetchChannels} from '../../actions/channels';
import './style.css';
const ChannelItem = (props) => (
<li
className= {props.selected ? 'selected' : ''}
onClick={() => props.selectChannel() }
>
<Icon name={props.room.type === 20 ? 'lock' : 'hashtag'} size='small'/>
{props.room.name}
</li>
)
class ChannelList extends Component {
componentDidMount() {
this.props.fetchChannels();
}
render() {
if (this.props.channels.loading === true)
return <div className="channels-loading">
<div>Loading...</div>
</div>;
const rooms= this.props.channels.rooms.map((room_id, index) => {
const room = this.props.channels.entities[room_id];
return (
<ChannelItem
key={room_id}
room={room}
index={index}
selectChannel={() => {
this.props.selectChannel(room);
}}
selected={this.props.channels.selected === room_id}
/>
);
});
if (rooms.length > 0)
return (<ul className='channel-list'>{rooms}</ul>);
else
return (<div>No rooms available</div>);
}
}
;
function mapStateToProps(state) {
return {channels: state.channels};
}
export default connect(mapStateToProps, {selectChannel, fetchChannels})(ChannelList);
|
/**
* Module dependencies.
*/
var express = require('../../');
var app = module.exports = express();
// Fake items
var items = [
{ name: 'foo' }
, { name: 'bar' }
, { name: 'baz' }
];
// Routes
app.get('/', function(req, res, next){
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.write('<p>Visit /item/2</p>');
res.write('<p>Visit /item/2.json</p>');
res.write('<p>Visit /item/2.xml</p>');
res.end();
});
app.get('/item/:id.:format?', function(req, res, next){
var id = req.params.id
, format = req.params.format
, item = items[id];
// Ensure item exists
if (item) {
// Serve the format
switch (format) {
case 'json':
// Detects json
res.send(item);
break;
case 'xml':
// Set contentType as xml then sends
// the string
var xml = ''
+ '<items>'
+ '<item>' + item.name + '</item>'
+ '</items>';
res.type('xml').send(xml);
break;
case 'html':
default:
// By default send some hmtl
res.send('<h1>' + item.name + '</h1>');
}
} else {
// We could simply pass route control and potentially 404
// by calling next(), or pass an exception like below.
next(new Error('Item ' + id + ' does not exist'));
}
});
// Middleware
app.use(express.errorHandler());
if (!module.parent) {
app.listen(3000);
silent || console.log('Express started on port 3000');
}
|
var assert = require('chai').assert;
var rewire = require('rewire');
var h = rewire('../lib/helper');
describe('icon', function() {
var icon = null;
before(function() {
h.getDirData = function() {
return [
{
name: 'word',
data: {
yes: 'yes',
no: 'no',
lock: 'lock',
like: 'like',
unlike: 'unlike'
}
}
];
};
});
beforeEach(function() {
icon = rewire('../lib/icon');
icon.__set__('h', h);
icon.init();
});
describe('#setTheme', function() {
it('should ok with known theme', function() {
icon.setTheme('word');
assert.equal(icon.yes, 'yes');
assert.equal(icon.no, 'no');
assert.equal(icon.lock, 'lock');
assert.equal(icon.like, 'like');
assert.equal(icon.unlike, 'unlike');
});
it('should ok with unknown theme', function() {
icon.setTheme('non-exist');
assert.equal(icon.yes, '✔');
assert.equal(icon.no, '✘');
assert.equal(icon.lock, '🔒');
assert.equal(icon.like, '★');
assert.equal(icon.unlike, '☆');
});
});
});
|
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import MainAppContainer from './containers/MainAppContainer';
import Home from './component/home/home';
import Test from './component/test';
export default (
<Route path="/" component={MainAppContainer}>
<IndexRoute component={Home}/>
<Route path='/mimi' component={Test}/>
</Route>
);
|
(function(servicesModule) {
'use strict';
servicesModule.value('version', '0.0.1');
servicesModule.value('backendUrl', 'http://api.veganaut.net');
})(window.monkeyFace.servicesModule);
|
define(function (require, exports, module) {//
//console.log('three loaded, config.type is ', module.config().type);
console.log('three loaded', module.config());
});
|
$(document).ready(function () {
new ModalMarkus('#upload_dialog', '#uploadModal');
new ModalMarkus('#download_dialog', '#downloadModal');
window.modal_coverage = new ModalMarkus('#groups_coverage_dialog');
window.modal_criteria = new ModalMarkus('#grader_criteria_dialog');
});
|
//提交表单
define([
'jquery',
'component/message',
'hdjs',
'axios',
'lodash'
], function ($,Message, hdjs, axios,_) {
return function (opt) {
let options = $.extend({
type: 'post',
url: window.system ? window.system.url : '',
data: {},
successUrl: 'back',
callback: '',
}, opt);
let ax;
switch (options.type) {
case 'get':
ax = axios.get(options.url, {params: options.data})
break;
case 'post':
ax = axios.post(options.url, options.data)
break;
}
hdjs.loading(function(loadingBox){
ax.then(function (response) {
if (_.isObject(response.data)) {
if ($.isFunction(options.callback)) {
options.callback(response.data);
} else {
if (response.data.code == 0) {
Message(response.data.message, options.successUrl, 'success');
} else {
Message(response.data.message, '', 'info');
}
}
} else {
Message(response.data, '', 'error');
}
}).catch(function (response) {
Message(response, '', 'error');
});
loadingBox.remove();
});
return false;
}
})
|
define(['exports', 'module', 'react', '../ProgressBar'], function (exports, module, _react, _ProgressBar) {
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _React = _interopRequireDefault(_react);
var _ProgressBar2 = _interopRequireDefault(_ProgressBar);
module.exports = _React['default'].createFactory(_ProgressBar2['default']);
});
|
module.exports = function (grunt) {
grunt.initConfig({
jshint: {
all: ["Gruntfile.js", "tasks/*.js"],
},
image_info: {
testJson: {
files: {
'test-result.json': ['test/images/*.png'],
}
},
testScss: {
files: {
'test-result.scss': ['test/images/*.png'],
}
},
},
exec: {
publish: {
command: 'npm publish .',
}
},
bump: {
options: {
push: false,
},
},
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-bump');
grunt.loadNpmTasks('grunt-exec');
grunt.registerTask("default", ["jshint", "image_info"]);
grunt.loadTasks("tasks");
};
|
"use strict";
module.exports = function (Product) {
let controller = {
get: function (req, res) {
let query = {
// name: { $or: ['Gosho', 'Pesho'] }
}; // Filted by
let selectedProperties = {}; // Properties to have
Product.find(query, selectedProperties, {
skip: 0,
limit: 10,
sort: {
date: -1
}
}, function (err, products) {
let result = products;
//result.sort((pr1, pr2) => pr2._id.getTimestamp() - pr1._id.getTimestamp());
//result = result.slice(0, 10);
res.render('products-all', {data: result});
//res.send(result);
});
}
};
return controller;
};
|
AutoForm.addInputType("select-radio", {
template: "afRadioGroup",
valueOut: function () {
if (this.is(":checked")) {
return this.val();
}
}
});
Template["afRadioGroup"].helpers({
atts: function selectedAttsAdjust() {
var atts = _.clone(this.atts);
if (this.selected) {
atts.checked = "";
}
return atts;
}
});
|
'use strict'
var bits = require('bit-twiddle')
var ndarray = require('ndarray')
var ops = require('ndarray-ops')
var cops = require('ndarray-complex')
var fft = require('ndarray-fft')
var pool = require('typedarray-pool')
var cwise = require('cwise')
var conjmuleq = cwise({
args: ['array', 'array', 'array', 'array'],
body: function(out_r, out_i, a_r, a_i) {
var a = a_r
var b = a_i
var c = out_r
var d = out_i
var k1 = c * (a + b)
out_r = k1 - b * (c + d)
out_i = k1 + a * (d - c)
}
})
function conv_impl(out_r, out_i, a_r, a_i, b_r, b_i, cor, wrap) {
if(a_r.shape.length !== b_r.shape.length || out_r.shape.length !== a_r.shape.length) {
throw new Error('ndarray-convolve: Dimension mismatch')
}
var d = a_r.shape.length
, nsize = 1
, nstride = new Array(d)
, nshape = new Array(d)
, i
if(wrap) {
for(i=d-1; i>=0; --i) {
nshape[i] = a_r.shape[i]
nstride[i] = nsize
nsize *= nshape[i]
}
} else {
for(i=d-1; i>=0; --i) {
nshape[i] = bits.nextPow2(a_r.shape[i] + b_r.shape[i] - 1)
nstride[i] = nsize
nsize *= nshape[i]
}
}
var x_t = pool.mallocDouble(nsize)
, x = ndarray(x_t, nshape, nstride, 0)
ops.assigns(x, 0)
ops.assign(x.hi.apply(x, a_r.shape), a_r)
var y_t = pool.mallocDouble(nsize)
, y = ndarray(y_t, nshape, nstride, 0)
ops.assigns(y, 0)
if(a_i) {
ops.assign(y.hi.apply(y, a_i.shape), a_i)
}
//FFT x/y
fft(1, x, y)
var u_t = pool.mallocDouble(nsize)
, u = ndarray(u_t, nshape, nstride, 0)
ops.assigns(u, 0)
ops.assign(u.hi.apply(u, b_r.shape), b_r)
var v_t = pool.mallocDouble(nsize)
, v = ndarray(v_t, nshape, nstride, 0)
ops.assigns(v, 0)
if(b_i) {
ops.assign(v.hi.apply(y, b_i.shape), b_i)
}
fft(1, u, v)
if(cor) {
conjmuleq(x, y, u, v)
} else {
cops.muleq(x, y, u, v)
}
fft(-1, x, y)
var out_shape = new Array(d)
, out_offset = new Array(d)
, need_zero_fill = false
for(i=0; i<d; ++i) {
if(out_r.shape[i] > nshape[i]) {
need_zero_fill = true
}
if (wrap) {
out_offset[i] = 0
} else {
out_offset[i] = Math.max(0, Math.min(nshape[i]-out_r.shape[i], Math.floor(b_r.shape[i]/2)))
}
out_shape[i] = Math.min(out_r.shape[i], nshape[i]-out_offset[i])
}
var cropped_x, cropped_y
if(need_zero_fill) {
ops.assign(out_r, 0.0)
}
cropped_x = x.lo.apply(x, out_offset)
cropped_x = cropped_x.hi.apply(cropped_x, out_shape)
ops.assign(out_r.hi.apply(out_r, out_shape), cropped_x)
if(out_i) {
if(need_zero_fill) {
ops.assign(out_i, 0.0)
}
cropped_y = y.lo.apply(y, out_offset)
cropped_y = cropped_y.hi.apply(cropped_y, out_shape)
ops.assign(out_i.hi.apply(out_i, out_shape), cropped_y)
}
pool.freeDouble(x_t)
pool.freeDouble(y_t)
pool.freeDouble(u_t)
pool.freeDouble(v_t)
}
module.exports = function convolve(a, b, c, d, e, f) {
if(arguments.length === 2) {
conv_impl(a, undefined, a, undefined, b, undefined, false, false)
} else if(arguments.length === 3) {
conv_impl(a, undefined, b, undefined, c, undefined, false, false)
} else if(arguments.length === 4) {
conv_impl(a, b, a, b, c, d, false, false)
} else if(arguments.length === 6) {
conv_impl(a, b, c, d, e, f, false, false)
} else {
throw new Error('ndarray-convolve: Invalid arguments for convolve')
}
return a
}
module.exports.wrap = function convolve_wrap(a, b, c, d, e, f) {
if(arguments.length === 2) {
conv_impl(a, undefined, a, undefined, b, undefined, false, true)
} else if(arguments.length === 3) {
conv_impl(a, undefined, b, undefined, c, undefined, false, true)
} else if(arguments.length === 4) {
conv_impl(a, b, a, b, c, d, false, true)
} else if(arguments.length === 6) {
conv_impl(a, b, c, d, e, f, false, true)
} else {
throw new Error('ndarray-convolve: Invalid arguments for convolve')
}
return a
}
module.exports.correlate = function correlate(a, b, c, d, e, f) {
if(arguments.length === 2) {
conv_impl(a, undefined, a, undefined, b, undefined, true, false)
} else if(arguments.length === 3) {
conv_impl(a, undefined, b, undefined, c, undefined, true, false)
} else if(arguments.length === 4) {
conv_impl(a, b, a, b, c, d, true, false)
} else if(arguments.length === 6) {
conv_impl(a, b, c, d, e, f, true, false)
} else {
throw new Error('ndarray-convolve: Invalid arguments for correlate')
}
return a
}
module.exports.correlate.wrap = function correlate_wrap(a, b, c, d, e, f) {
if(arguments.length === 2) {
conv_impl(a, undefined, a, undefined, b, undefined, true, true)
} else if(arguments.length === 3) {
conv_impl(a, undefined, b, undefined, c, undefined, true, true)
} else if(arguments.length === 4) {
conv_impl(a, b, a, b, c, d, true, true)
} else if(arguments.length === 6) {
conv_impl(a, b, c, d, e, f, true, true)
} else {
throw new Error('ndarray-convolve: Invalid arguments for correlate')
}
return a
}
|
'use strict';
/**
* Module dependencies.
*/
var passport = require('passport'),
url = require('url'),
InstagramStrategy = require('passport-instagram').Strategy,
config = require('../config'),
users = require('../../app/controllers/users');
module.exports = function() {
// Use facebook strategy
passport.use(new InstagramStrategy({
clientID: config.instagram.clientID,
clientSecret: config.instagram.clientSecret,
callbackURL: config.instagram.callbackURL,
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done) {
// Set the provider data and include tokens
var providerData = profile._json;
providerData.accessToken = accessToken;
providerData.refreshToken = refreshToken;
// Create the user OAuth profile
var providerUserProfile = {
// firstName: profile.name.givenName,
// lastName: profile.name.familyName,
displayName: profile.displayName,
// email: profile.emails[0].value,
username: profile.username,
provider: 'instagram',
providerIdentifierField: 'id',
providerData: providerData
};
// Save the user OAuth profile
users.saveOAuthUserProfile(req, providerUserProfile, done);
}
));
};
|
/// <reference path="typings/node/node.d.ts" />
/// <reference path="typings/express/express.d.ts" />
/// <reference path="typings/jquery/jquery.d.ts" />
|
function test() {
var points = [
NEW("HTuple-3").point([0, 0, 1]),
NEW("HTuple-3").point([1, 0, 0]),
NEW("HTuple-3").point([0, 1, 0])
];
points[0].print("0s");
points[1].print("1");
points[2].print("2");
var plane = NEW("Hyperplane-3").initWithPoints(points);
plane.print("plane");
var N = NEW("HTuple-3").point([1, 0, 0]);
var up = NEW("HTuple-3").point([0, 1, 0]);
var right = N.cross (up);
N.print("N");
up.print("up");
right.print("right");
up = right.cross (N);
up.print("up");
}
|
import { STORAGE_KEY } from './state'
const localStoragePlugin = store => {
store.subscribe((mutation, state) => {
const syncedData = {
auth: state.auth,
user: state.user,
places: state.places,
center: state.center
}
localStorage.setItem(STORAGE_KEY, JSON.stringify(syncedData))
if (mutation.type === 'CLEAR_ALL_DATA') {
localStorage.removeItem(STORAGE_KEY)
}
})
}
// TODO: setup env
// export default process.env.NODE_ENV !== 'production' ? [localStoragePlugin] : [localStoragePlugin]
export default [localStoragePlugin]
|
import reconcile from './templateParse/reconcile'
import diffNodes from './templateParse/diffNodes'
import commentsDumpster from './templateParse/commentsDumpster'
import strInterpreter from './strInterpreter'
const DELAY = 0
const morpher = function () {
genElement.call(this)
// exec life-cycle componentDidUpdate
if (this.componentDidUpdate && typeof this.componentDidUpdate === 'function') {
this.componentDidUpdate()
}
}
let timer = {}
const updateContext = function (fn, delay) {
timer[this.ID] = timer[this.ID] || null
clearTimeout(timer[this.ID])
timer[this.ID] = setTimeout(() => fn.call(this), delay)
}
const nextState = function (i) {
let self = this
let state
let value
if (!stateList[this.ID]) return
if (i < stateList[this.ID].length) {
state = stateList[this.ID][i]
value = this[state]
// if value is undefined, likely has object notation we convert it to array
if (value === undefined) value = strInterpreter(state)
if (value && Array.isArray(value)) {
// using split object notation as base for state update
let inVal = this[value[0]][value[1]]
Object.defineProperty(this[value[0]], value[1], {
enumerable: false,
configurable: true,
get: function () {
return inVal
},
set: function (val) {
inVal = val
updateContext.call(self, morpher, DELAY)
}
})
} else {
// handle parent state update if the state is not an object
Object.defineProperty(this, state, {
enumerable: false,
configurable: true,
get: function () {
return value
},
set: function (val) {
value = val
updateContext.call(self, morpher, DELAY)
}
})
}
i++
nextState.call(this, i)
}
}
const setState = function () {
nextState.call(this, 0)
}
let stateList = {}
function clearState () {
if (stateList[this.ID]) stateList[this.ID] = []
}
function addState (state) {
stateList[this.ID] = stateList[this.ID] || []
if (stateList[this.ID].indexOf(state) === -1) { stateList[this.ID] = stateList[this.ID].concat(state) }
}
const genElement = function () {
this.base = this.__pristineFragment__.cloneNode(true)
reconcile.call(this, this.base.firstChild, addState.bind(this))
commentsDumpster.call(this, this.base.firstChild)
diffNodes.call(this, this.base.firstChild)
}
export {
genElement,
addState,
setState,
clearState,
updateContext,
morpher
}
|
(function() {
lab: {
try {
eff(2);
if (eff(3)) break lab;
else throw new Error("error");
eff(4);
} catch (e) {
eff(5);
}
eff(6);
}
eff(7);
});
|
const Koa = require('koa')
const jsonp = require('koa-jsonp')
const app = new Koa()
// 使用中间件
app.use(jsonp())
app.use( async ( ctx ) => {
let returnData = {
success: true,
data: {
text: 'this is a jsonp api',
time: new Date().getTime(),
}
}
ctx.body = returnData
})
app.listen(3000, () => {
console.log('[demo] jsonp is starting at port 3000')
})
|
'use strict';
var React = require('react');
var classNames = require('classnames');
var ClassNameMixin = require('./mixins/ClassNameMixin');
var AvgGrid = require('./AvgGrid');
var omit = require('object.omit');
var Gallery = React.createClass({
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string,
theme: React.PropTypes.oneOf(['default', 'overlay', 'bordered',
'imgbordered']),
data: React.PropTypes.array,
sm: React.PropTypes.number,
md: React.PropTypes.number,
lg: React.PropTypes.number
},
getDefaultProps: function() {
return {
classPrefix: 'gallery',
theme: 'default',
data: []
};
},
renderItem: function(item) {
var img = item.img ? (
<img
src={item.img}
key="galeryImg"
alt={item.alt || item.title || null}
/>
) : null;
var title = item.title ? (
<h3
key="galleryTitle"
className={this.prefixClass('title')}
>
{item.title}
</h3>) : null;
var desc = item.desc ? (
<div
key="galleryDesc"
className={this.prefixClass('desc')}
>
{item.desc}
</div>
) : null;
var galleryItem = item.link ? (
<a href={item.link}>
{img}
{title}
{desc}
</a>
) : [img, title, desc];
return (
<div
className={classNames(this.props.className, this.prefixClass('item'))}
>
{galleryItem}
</div>
);
},
render: function() {
var classSet = this.getClassSet();
var props = omit(this.props, ['classPrefix', 'data', 'theme']);
return (
<AvgGrid
{...props}
sm={this.props.sm || 2}
md={this.props.md || 3}
lg={this.props.lg || 4}
data-am-widget={this.props.classPrefix}
className={classNames(this.props.className, classSet)}
>
{this.props.data.map(function(item, i) {
return (
<li key={i}>
{this.renderItem(item)}
</li>
);
}.bind(this))}
</AvgGrid>
);
}
});
module.exports = Gallery;
|
module.exports = IShape;
/**
* Interface class for all shape types.
* Warn: Shouldn't be instantiated!
*
* @class IShape
* @constructor
* @submodule geometry
*/
function IShape(){}
Object.defineProperties(IShape.prototype, {
/**
* @method contains
* @param {Point|IShape} (in)
* @return {Boolean} whether the param is fully inside shape
*/
"contains": {
"value": null,
"enumerable": true
},
/**
* @method equals
* @param {IShape} (in)
* @return {Boolean} whether the instances of same class are equal
*/
"equals": {
"value": null,
"enumerable": true
},
/**
* @method intersects
* @param {IShape} (in)
* @return {Boolean} whether the param is collide with shape
*/
"intersects": {
"value": null,
"enumerable": true
},
/**
* @method toString
* @final
* @return {String} - standardized object's class name
*/
"toString": {
"value": function(){
return "[object IShape]";
}
}
});
|
function Peon(id, x, y, direction) {
this.id = id;
this.x = x; // (en cases)
this.y = y; // (en cases)
// Chargement de l'image dans l'attribut image
this.image = image;
this.Width = image.width / 8;
this.Height = image.height / 8;
}
Peon.prototype.Draw = function(context) {
var sx = this.Width * 2; // The x coordinate where to start clipping
var sy = this.Height * 0; // The y coordinate where to start clipping
var swidth = this.Width; // The width of the clipped image
var sheight = this.Height; // The height of the clipped image
var x = (this.x)// - (this.Width / 2); // The x coordinate where to place the image on the canvas
var y = (this.y)// - (this.Height / 2); // The y coordinate where to place the image on the canvas
var width = this.Width;// / 2; // The width of the image to use (stretch or reduce the image)
var height = this.Height;// / 2; // The height of the image to use (stretch or reduce the image)
context.drawImage(this.image, sx, sy, swidth, sheight, x, y, width, height);
}
Peon.prototype.Move = function(x, y) {
this.x = x;
this.y = y;
}
|
$('#input').focus(function() {
this.blur();
});
|
import { normalize } from 'normalizr'
import { camelizeKeys } from 'humps'
import 'isomorphic-fetch'
const API_ROOT = 'https://api.spotify.com/v1/'
export const CALL_API = Symbol('Call API')
function callApi(endpoint, schema) {
const finalUrl = (endpoint.indexOf(API_ROOT) === -1) ? API_ROOT + endpoint : endpoint
return fetch(finalUrl)
.then(response =>
response.json().then(json => ({ json, response }))
)
.then(({ json, response }) => {
if (!response.ok) {
return Promise.reject(json)
}
const camelizedJson = camelizeKeys(json)
return schema ? normalize(camelizedJson, schema) : camelizedJson
})
}
export default function middleware() {
return next => action => {
const API_ACTION = action[CALL_API]
if (typeof API_ACTION === 'undefined') {
return next(action)
}
const { endpoint, types, schema } = API_ACTION
if (typeof endpoint !== 'string') {
throw new Error('Specify a string endpoint URL')
}
if (!Array.isArray(types) && types.length !== 3) {
throw new Error('Expected an array of three action types')
}
if (!types.every(type => typeof type === 'string')) {
throw new TypeError('Expected action types to be strings')
}
const [requestType, successType, failureType] = types
function actionWith(data) {
const finalAction = Object.assign({}, action, data)
delete finalAction[CALL_API]
return finalAction
}
next(actionWith({ type: requestType }))
return callApi(endpoint, schema).then(
response => next(actionWith({
response,
type: successType
})),
error => next(actionWith({
error,
type: failureType
}))
)
}
}
|
import DS from 'ember-data';
import env from '../config/environment';
export default DS.JSONAPIAdapter.extend({
host: env.starsHost
});
|
/**
* Created by antoine on 1/21/16.
*/
'use strict';
var Q = require('q'),
providerHelpers = require('../helpers/user.provider'),
OAuth = require('oauthio'),
debug = require('debug')('oauth:oauth.server.controller'),
config = require('../../../config/config'),
jwt = require('jwt-simple');
/**
*
* @param obj is the OAuth object
*/
var signin = function (obj, provider) {
var deferred = Q.defer(),
credentials = obj.getCredentials(),
userData = {
me: null,
userId: null,
provider: null,
providerName: provider,
user: null
};
obj.me().then(function (me) {
userData.me = providerHelpers.loadInMe(me, credentials);
providerHelpers.findProvider(userData)
.then(providerHelpers.findUser)
.catch(function (userData) {
return providerHelpers.findProviderEmail(userData)//->rejects here
.then(providerHelpers.createProvider)
.then(providerHelpers.findUser)
.then(providerHelpers.linkProviderToUser);
})
.catch(function (userData) {
return providerHelpers.createUser(userData)
.then(providerHelpers.createProvider)
.then(providerHelpers.linkProviderToUser);
})
.fail(function (err) {
deferred.reject(err);
})
.done(function (userData) {
deferred.resolve(userData.user);
});
}, function (err) {
deferred.reject(err);
});
return deferred.promise;
};
/* todo
get this from config file
*/
exports.oauthd = function (req, res) {
OAuth.setOAuthdURL(config.oauthd.serverUrl);
OAuth.initialize(config.oauthd.OAUTHD_ID, config.oauthd.OAUTHD_SECRET);
res.send(200, { token: OAuth.generateStateToken(req.session) });
};
/**
* OAUTH
* @param req
* @param res
*/
exports.oauthdSetCode = function (req, res) {
OAuth.setOAuthdURL(config.oauthd.serverURL);
OAuth.initialize(config.oauthd.OAUTHD_ID, config.oauthd.OAUTHD_SECRET);
var provider = req.body.provider;
var code = req.body.code;
debug('code = %s', code);
debug('Generate Token = %s', OAuth.generateStateToken(req));
OAuth.auth(provider, req.session, {
code: code //cf result.code client side
}).then(
function (obj) {
signin(obj, provider)
.then(
function (user) {
debug('REQ.SESSION = ', req.session);
user = user.toObject();
var token = jwt.encode({
user: user._id,
roles: user.roles
}, config.jwt.secret);
user.token = token;
res.set(config.jwt.authHeaderName, token);
providerHelpers.getUserProviderNames(user).then(function (names) {
user.providerNames = names;
req.session.user = user;
res.status(200).send(req.session.user);
});
},
function (err) {
req.session.user = null;
res.status(500).send(err);
}
);
},
function (err) {
req.session.user = null;
debug('Err thrown in OAuth.auth(), ', err);
res.status(500).send(err);
}
)
.fail(
function (err) {
req.session.user = null;
debug('Err thrown in OAuth.auth(), ', err);
res.status(500).send(err);
}
);
};
exports.signin = signin;
|
import { DATATYPE_NAME } from 'constants/pogues-constants';
const { BOOLEAN, TEXT, DATE, NUMERIC } = DATATYPE_NAME;
export const defaultTypageForm = {
type: TEXT,
[TEXT]: {
maxLength: 255,
pattern: ''
},
[NUMERIC]: {
minimum: '',
maximum: '',
decimals: '',
unit: ''
},
[DATE]: {},
[BOOLEAN]: {}
};
|
/*
Plugin: jQuery Parallax
Version 1.0.0
Author: Ionuț Staicu
License: MIT
*/
(function( $, document ){
if (!Object.create) { Object.create = function (o) { if (arguments.length > 1) { throw new Error('Object.create implementation only accepts the first parameter.'); } function F() {} F.prototype = o; return new F(); }; }
var Parallax = {
init: function( el, options ){
this.el = $( el );
this.scrollThrottle = 0;
this.win = $( window );
this.options = options;
this.appendBackground();
this.win.on( 'resize re-parallax', $.proxy( this.reInitialize, this ) );
if( !this.options.disable ){
this.win.on( 'scroll', $.proxy( this.scroll, this ) );
}
$( window ).trigger('re-parallax');
},
reInitialize: function(){
this.setCoords();
this.scroll();
},
setCoords: function(){
this.winHeight = this.win.height();
this.initialTop = this.el.offset().top;
},
appendBackground: function(){
this.divBG = $('<div class="parallaxBG" />');
if( this.options.defaultStyling ){
this.divBG.css({
position : 'absolute',
background : 'no-repeat center center fixed',
backgroundSize : 'cover',
width : '100%',
bottom : 0,
left : 0,
top : 0,
zIndex : -1,
});
this.el.css( 'position', 'relative' );
}
this.divBG.css({
backgroundImage: 'url(' + this.el.attr('data-image') + ')'
});
this.el.append( this.divBG );
},
scroll: function(){
if( this.options.setCoordsLive && this.scrollThrottle > this.options.scrollThrottle ){
this.setCoords();
this.scrollThrottle = 0;
}
var scrollTop = this.win.scrollTop();
var currentTop = this.el.offset().top;
var height = this.el.outerHeight( true );
var newYPos = 0;
if( !this.options.disable ){
newYPos = Math.round( ( this.initialTop - scrollTop ) * this.options.speed );
}
newYPos += 'px';
if ( currentTop + height < scrollTop || currentTop > scrollTop + this.winHeight) {
return;
}
this.divBG.css('backgroundPosition', [ '50%', newYPos ].join(' ') );
this.scrollThrottle += 1;
},
};
$.fn.parallax = function( options ) {
options = options || {};
options = $.extend({
speed : 0.5,
defaultStyling: true,
disable: false,
scrollThrottle : 10,
setCoordsLive : true
}, options );
return this.each(function(){
var obj = Object.create( Parallax );
var itemOptions = $.extend( {}, options, $( this ).data() );
obj.init( this, itemOptions );
});
};
})( jQuery, document );
|
#!/usr/bin/env node
'use strict'
const exec = require('child_process').exec
const program = require('commander')
const chalk = require('chalk')
const notp = require('notp')
const ncp = require('copy-paste')
const base32 = require('thirty-two')
const updateNotifier = require('update-notifier')
const pkg = require('../package.json')
updateNotifier({ pkg }).notify()
const getCode = service => {
let key
const pass = exec(`pass 2fa/${service}/code`)
pass.stdout.on('data', data => {
key = data
})
pass.stderr.on('data', () => {
console.log(chalk.red(`Error: ${service} not stored`)) // eslint-disable-line
process.exit(1)
})
pass.on('close', () => {
const totp = notp.totp.gen(base32.decode(key))
console.log(chalk.green(totp)) // eslint-disable-line
ncp.copy(totp.toString())
process.exit(0)
})
}
program.usage('<service>').parse(process.argv)
if (program.args.length === 0) {
console.log(chalk.red('Service required')) // eslint-disable-line
process.exit(1)
} else {
getCode(program.args[0])
}
|
/**
* String#include(substring) -> Boolean
*
* Checks if the string contains `substring`.
*
* ##### Example
*
* 'Prototype framework'.include('frame');
* //-> true
* 'Prototype framework'.include('frameset');
* //-> false
**/
String.prototype.include = function(pattern) {
return this.indexOf(pattern) !== -1;
}
|
/*
* @file Content pack package unit test
* @author Wade Penistone (Truemedia)
* @overview Class used for TDD of Content pack package
* @copyright Wade Penistone 2014
* @license MIT license ({@link http://opensource.org/licenses/MIT| See here})
* Git repo: {@link http://www.github.com/Truemedia/Regeneration-Primer| Regeneration Primer github repository}
* Author links: {@link http://youtube.com/MCOMediaCityOnline| YouTube} and {@link http://github.com/Truemedia| Github}
*/
// BDD and TDD
var chai = require('chai'),
assert = chai.assert;
expect = chai.expect;
var Backbone = require('backbone');
var contentpack = require('./../main');
suite('contentpack', function()
{
test('Package is an object', function()
{
assert.isObject(contentpack);
});
test('Settings are null by default', function()
{
assert.isNull(contentpack.settings);
});
test('Translations are empty by default', function()
{
expect(contentpack.trans).to.be.empty;
});
test('Package has a load function', function()
{
assert.isFunction(contentpack.load);
});
test('Package has an init function', function()
{
assert.isFunction(contentpack.init);
});
});
|
/**
* Created by sathisu on 3/17/2017.
*/
require.config({
// alias bower_componentsraries paths
paths: {
'domReady': 'bower_components/requirejs-domready/domReady',
'angular': 'bower_components/angular/angular',
'angular-loader': 'bower_components/angular-loader/angular-loader',
'angular-ui-router': 'bower_components/angular-ui-router/release/angular-ui-router',
'angular-cookies': 'bower_components/angular-cookies/angular-cookies',
'ui-bootstrap': 'bower_components/angular-bootstrap/ui-bootstrap-tpls',
'ng-upload': 'bower_components/angular-file-upload/dist/angular-file-upload',
'lodash': 'bower_components/lodash/dist/lodash'
//'bootstrap': 'bower_components/bootstarp/dist/lodash'
},
// angular does not support AMD out of the box, put it in a shim
shim: {
'angular-ui-router': ['angular'],
'underscore.string': ['lodash'],
'ui-bootstrap': ['angular'],
'angular-cookies':['angular'],
'ng-upload':['angular'],
'angular': {
exports: 'angular',
init: function() {
if (window.console) return;
var noop = function() {};
window.console = { log: noop, error: noop, warn: noop };
}
}
},
// kick start application
deps: [
'lodash',
'./bootstrap',
//'./config',
'angular-ui-router',
'angular-cookies',
'ui-bootstrap',
'ng-upload'
]
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CompileSpy = undefined;
var _dec, _dec2, _class;
var _aureliaTemplating = require('aurelia-templating');
var _aureliaDependencyInjection = require('aurelia-dependency-injection');
var _aureliaLogging = require('aurelia-logging');
var LogManager = _interopRequireWildcard(_aureliaLogging);
var _aureliaPal = require('aurelia-pal');
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
var CompileSpy = exports.CompileSpy = (_dec = (0, _aureliaTemplating.customAttribute)('compile-spy'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaPal.DOM.Element, _aureliaTemplating.TargetInstruction), _dec(_class = _dec2(_class = function CompileSpy(element, instruction) {
LogManager.getLogger('compile-spy').info(element, instruction);
}) || _class) || _class);
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var connectCouchDB = require('connect-couchdb')(session);
var app = express();
var store = new connectCouchDB({
name: 'archery-server-sessions',
username: '',
password: '',
host: 'localhost',
post: '5984'
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(session({
name: "connect.sid",
secret: 'secret',
saveUninitialized: true,
cookie: {
httpOnly: false
// bellow is a recommended option. however, it requires an https-enabled website...
// secure: true,
},
store: store
})
);
var routes = require('./routes/index');
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
//--- Error Handlers ---//
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
//--- End Error Handlers ---//
module.exports = app;
|
function minimum(a, b) {
var minimum = (a < b) ? a : b;
return minimum;
}
|
LegalPortal.config(['$stateProvider', '$urlRouterProvider', 'BASE_PATH',
function ($stateProvider, $urlRouterProvider, BASE_PATH) {
'use strict';
var baseUrl = BASE_PATH.modulesUrl;
$stateProvider
.state('documentLibrary', {
url: '/documentLibrary',
templateUrl: baseUrl + 'documentLibrary/grid/gridView.html',
controller: 'gridViewController'
})
.state('documentDetails', {
url: '/documentDetails/:id',
templateUrl: baseUrl + 'documentLibrary/details/documentDetails.html',
controller: 'documentDetailsController'
})
}]);
|
import t from 'tcomb';
class A {
foo(x: t.String): t.String {
return x;
}
}
class B {
bar() {
[].forEach((n): void => {
console.log(this);
});
}
}
|
// TimelinePlayer.js
// (c) 2013 thunder9 (https://github.com/thunder9)
// TimelinePlayer may be freely distributed under the MIT license.
(function(root) {
// Baseline setup
// --------------
// Require Underscore, if we're on the server, and it's not already present.
var _ = root._ || require('underscore');
// TimelinePlayer
// --------------
// Creating an instance of the `TimelinePlayer` that fires given callback
// at the positions on a timeline specified by `sequence` (an array
// of `[position, values]` pairs).
var TimelinePlayer = function(sequence, callback) {
this.sequence = _.isArray(sequence) ? sequence : [];
this.callback = _.isFunction(callback) ? callback : function() {};
this.position = 0;
this._speed = 1;
this._muted = false;
players.push(this);
};
// Define the TimelinePlayer's inheritable methods.
_.extend(TimelinePlayer.prototype, {
// Starts a playback. If `pos` and/or **positive** `speed` are given, updates
// current position and/or speed respectively before starting the playback.
play: function(pos, speed) {
if (this._timeout) this.stop();
if (_.isNumber(pos)) this.position = pos;
if (speed > 0) this._speed = speed;
this._startPosition = this.position;
this._startTime = Date.now();
this._timeout = null;
schedule(this);
},
// Stop current playback and set current position to zero.
stop: function() {
this.pause();
this.position = 0;
},
// Pauses current playback and update current position based on the elapsed time.
pause: function() {
if (this._timeout) clearTimeout(this._timeout);
this._timeout = null;
var elapsed = Date.now() - this._startTime;
this.position = this._startPosition + elapsed * this._speed;
},
// Set speed of current playback. If `speed` is zero, negative or non-number,
// stop current playback immediately.
setSpeed: function(speed) {
if (!(speed > 0)) {
this.stop();
return;
}
if (this._timeout) {
this.pause();
this.play(null, speed);
} else {
this._speed = speed;
}
},
// Mute firing
mute: function() {
this._muted = true;
},
// Unmute firing
unmute: function() {
this._muted = false;
}
});
// Internal method called when fires the timed events.
var schedule = function(state) {
var previous = state.position;
var elapsed = Date.now() - state._startTime;
state.position = state._startPosition + elapsed * state._speed;
var next = _.find(state.sequence, function(v) { return v[0] > state.position; });
if (next) {
var wait = (next[0] - state.position) / state._speed;
state._timeout = setTimeout(schedule, wait, state);
}
if (!state._muted) {
var f = previous === state.position
? function(v) { return v[0] === state.position; }
: function(v) { return v[0] > previous && v[0] <= state.position; };
_.each(_.filter(state.sequence, f), function(v) { state.callback.call(state, state.position, v); });
}
};
// Array of TimelinePlayer's instances.
var players = [];
// Define the TimelinePlayer's static methods for global control.
_.each(_.keys(TimelinePlayer.prototype), function(method) {
TimelinePlayer[method] = function() {
var args = _.toArray(arguments);
_.each(players, function(player) { player[method].apply(player, args); } );
}
});
// Exports the `TimelinePlayer`
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = TimelinePlayer;
}
exports.TimelinePlayer = TimelinePlayer;
} else {
root.TimelinePlayer = TimelinePlayer;
}
})(this);
|
require('jquery-extensions');
require('./lib/provider.js');
|
// resources/assets/js/games/index.js
var Game = {
all: function() {
return [
{
"name": "Final Fantasy IX",
"platform": "Playstation"
},
{
"name": "Final Fantasy X",
"platform": "Playstation II"
},
{
"name": "Command And Conquer",
"platform": "Playstation"
},
{
"name": "Metal Gear Solid",
"platform": "Playstation"
},
{
"name": "The Talos Principle",
"platform": "Steam"
},
{
"name": "The King of Fighter 97",
"platform": "Playstation"
}
]
},
byName: function(name) {
return this.all().filter(function(game){
return game.name == name;
})
}
};
|
;
(function ($, form) {
'use strict';
//We will be using strict java script!
$.extend(form, {
settings: {
},
init: function () {
var $sample = $('#sample');
// Dynamic java script command
$sample.on('click', '#addForm', function () {
samplefunc($(this));
});
},
//Example of a function
samplefunc: function (selectedObject) {
}
});//extend
})(window.jQuery, window.form || (window.form = {}));
jQuery(function () {
forms.init();
});
|
module.exports={content:["./_site/**/*.html"],css:["./_site/assets/css/main.css"]};
|
'use strict';
angular
.module('app')
.directive('jVersion', function() {
return {
restrict: 'E',
template: '<span ng-bind="vm.version"></span>',
controller: ['$http', function($http) {
var self = this;
$http
.get('/api/version')
.then(function(response) {
self.version = response.data;
});
}],
controllerAs: 'vm'
};
});
|
var //commands = require('./commands'),
tables = require('./schema');
module.exports = {
//commands : commands,
tables : tables
};
|
const code = 5;
console.error('error #%d', code); // error #5
console.error('error', code); // error 5
|
'use strict';
var sqlite3 = require('sqlite3').verbose(),
path = require('path'),
nconf = require('nconf');
module.exports = function (server) {
server.get('/image/:id', function (req, res) {
var file = path.dirname(process.mainModule.filename) + '/db/droplet.sqlite3';
var db = new sqlite3.Database(file);
var url;
if(nconf.get('s3Config')) {
var conf = nconf.get('s3Config');
if(conf.hostname) {
url = conf.hostname;
} else {
url = 'https://' + conf.bucket + '.s3.amazonaws.com/items/';
}
} else {
url = req.protocol + '://' + req.get('host') + '/files/';
}
db.get('SELECT filename FROM Files WHERE slug = ?', [req.params.id], function(err, row){
if(row) {
if(nconf.get('s3Config')) {
url = url +'/'+ row.filename;
} else {
url = url + row.filename;
}
var model = {
title: row.filename + ' - Droplet',
id: req.params.id,
filename: row.filename,
filepath: url
};
res.render('image', model);
} else {
res.writeHead(404, {
'content-type': 'text/plain'
});
res.end('404');
}
});
db.close();
});
};
|
$(document).ready(function(){
addClick();
});
function addClick() {
$("nav a").click(function(e){
e.preventDefault();//anchor tags stopped working in order to animate them below
var sectionID=e.currentTarget.id +"Section";
$("html, body").animate({
scrollTop: $("#" + sectionID).offset().top
}, 1000)
})
}
|
class Random{
constructor(seed){
this.seed = seed || Date.now()
}
next(){
return this._random()
}
nextInt(){
return Math.floor(this._random())
}
_random() {
var x = Math.sin(this.seed++) * 10000
return x - Math.floor(x)
}
}
export {Random}
|
// Copyright 2015-2018 FormBucket LLC
import { SecondsInDay, SecondsInHour, SecondsInMinute } from "./constants";
import isDate from "./isdate";
import trunc from "./trunc";
export default function minute(value) {
if (isDate(value)) {
return value.getMinutes();
}
// calculate total seconds
var totalSeconds = (value - trunc(value)) * SecondsInDay;
// calculate number of seconds for hour components
var hourSeconds = trunc(totalSeconds / SecondsInHour) * SecondsInHour;
// calculate the number seconds after remove seconds from the hours and convert to minutes
return trunc((totalSeconds - hourSeconds) / SecondsInMinute);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.