commit
stringlengths 40
40
| old_file
stringlengths 4
236
| new_file
stringlengths 4
236
| old_contents
stringlengths 1
3.26k
| new_contents
stringlengths 16
4.43k
| subject
stringlengths 16
624
| message
stringlengths 17
3.29k
| lang
stringclasses 5
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
|---|---|---|---|---|---|---|---|---|---|
8bc4f4d164c6eb5caa96698ddcbfce30743c3a30
|
website/gulpfile.js
|
website/gulpfile.js
|
var gulp = require("gulp");
var usemin = require("gulp-usemin");
var ngmin = require("gulp-ngmin");
var uglify = require("gulp-uglify");
var minifyHtml = require("gulp-minify-html");
var minifyCss = require("gulp-minify-css");
var rev = require("gulp-rev");
gulp.task('partials', function() {
var stream = gulp.src("app/**/*.html")
.pipe(gulp.dest("prod/"));
return stream;
});
gulp.task('other', function() {
var stream = gulp.src(["app/assets/fonts/**/*", "app/assets/ico/**/*", "app/assets/img/**/*"], {
base: "app"
}).pipe(gulp.dest("prod/"));
return stream;
});
gulp.task('default', ['partials', 'other'], function() {
return gulp.src("./app/index.html")
.pipe(usemin({
css: ['concat'],
//html: [minifyHtml({empty: true})],
js: [ngmin(), uglify(), 'concat']
}))
.pipe(gulp.dest("prod/"));
});
|
var gulp = require("gulp");
var usemin = require("gulp-usemin");
var ngmin = require("gulp-ngmin");
var uglify = require("gulp-uglify");
var minifyHtml = require("gulp-minify-html");
var minifyCss = require("gulp-minify-css");
var rev = require("gulp-rev");
var clean = require("gulp-clean");
var gulpSequence = require("gulp-sequence");
// Brings over the angular html partials.
gulp.task('partials', function() {
var stream = gulp.src("app/**/*.html")
.pipe(gulp.dest("prod/"));
return stream;
});
// Brings over other assets such as fonts and images,
// and the application style sheet.
gulp.task('other', function() {
var stream = gulp.src([
"app/assets/fonts/**/*",
"app/assets/ico/**/*",
"app/assets/css/select2/*",
"app/assets/css/images/*",
"app/assets/img/**/*",
"app/style-3.css"], {
base: "app"
}).pipe(gulp.dest("prod/"));
return stream;
});
// Cleans the destination directory.
gulp.task('clean', function() {
var stream = gulp.src("prod/").pipe(clean({read: false, force: true}));
return stream;
});
// Builds the new index.html, concats and minimizes
// the files.
gulp.task('min', function() {
return gulp.src("./app/index.html")
.pipe(usemin({
css: ['concat'],
//html: [minifyHtml({empty: true})],
js: [ngmin(), uglify(), 'concat']
}))
.pipe(gulp.dest("prod/"));
});
gulp.task('default', gulpSequence('clean', 'partials', 'other', 'min'));
|
Update gulp file to build a clean version of prod. Sequence the tasks and update them to include needed assets.
|
Update gulp file to build a clean version of prod. Sequence the tasks
and update them to include needed assets.
|
JavaScript
|
mit
|
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
|
4a6e5be03eec92df7a19e56fb3f97035fa516734
|
spec/lib/services/lookup-spec.js
|
spec/lib/services/lookup-spec.js
|
// Copyright 2014, Renasar Technologies Inc.
/* jshint node:true */
'use strict';
describe(__filename, function () {
it('needs specs');
});
|
// Copyright 2014, Renasar Technologies Inc.
/* jshint node:true */
'use strict';
describe("Lookup Service", function() {
var injector;
var lookupService;
var dhcpProtocol;
var dhcpSubcription;
beforeEach(function() {
injector = helper.baseInjector.createChild(_.flatten([
helper.requireGlob(__dirname + '/../lib/protocol/**/*.js'),
helper.requireGlob(__dirname + '/../lib/services/*.js')
]));
lookupService = injector.get('Services.Lookup');
dhcpProtocol = injector.get('Protocol.Dhcp');
return helper.initializeMessenger(injector);
});
afterEach(function() {
return dhcpSubcription.dispose();
});
it("should lookup the mac address for an IP", function() {
function lookupIpLease(ip) {
if (ip === '10.1.1.2') {
return "01:01:01:01:01:01";
}
if (ip === '10.1.1.3') {
return "02:02:02:02:02:02";
}
}
return dhcpProtocol.subscribeLookupIpLease(lookupIpLease)
.then(function(subscription) {
expect(subscription).to.be.ok;
dhcpSubcription = subscription;
return lookupService.ipAddressToMacAddress('10.1.1.2');
})
.then(function(mac) {
expect(mac).to.equal("01:01:01:01:01:01");
return lookupService.ipAddressToMacAddress('10.1.1.3');
})
.then(function(mac) {
expect(mac).to.equal("02:02:02:02:02:02");
});
});
it("should cache the mac address for an IP", function() {
var calledOnce = false;
var cachedIp = '10.1.1.4';
function lookupIpLease() {
console.log(calledOnce);
if (calledOnce) {
return "04:04:04:04:04:04";
} else {
calledOnce = true;
return "03:03:03:03:03:03";
}
}
return dhcpProtocol.subscribeLookupIpLease(lookupIpLease)
.then(function(subscription) {
expect(subscription).to.be.ok;
return lookupService.ipAddressToMacAddress(cachedIp);
})
.then(function(mac) {
expect(mac).to.equal("03:03:03:03:03:03");
return lookupService.ipAddressToMacAddress(cachedIp);
})
.then(function(mac) {
expect(lookupIpLease()).to.equal("04:04:04:04:04:04");
// This should be cached now
expect(mac).to.equal("03:03:03:03:03:03");
});
});
});
|
Add lookup service tests for ip to mac
|
Add lookup service tests for ip to mac
|
JavaScript
|
apache-2.0
|
YoussB/on-core,YoussB/on-core
|
392d4e2c4a4abbcf4aa05ad2554b163a821f7d9a
|
js/agent.js
|
js/agent.js
|
(function() {
// wait for polyfill to be loaded
if (document.readyState == "complete") {
init();
} else {
window.onload = init;
}
var loggedIn = false;
function init() {
if (!navigator.id)
return;
sendToContent({ type: "init" });
window.addEventListener('browserid-exec', onMessage);
navigator.id.watch({ onlogin: onLogin, onlogout: onLogout });
}
function onLogin(assertion) {
console.log('onLogin');
loggedIn = true;
sendToContent({ type: 'auth', loggedIn: loggedIn });
}
function onLogout() {
console.log('onLogout');
loggedIn = false;
sendToContent({ type: 'auth', loggedIn: loggedIn });
}
function onMessage(event) {
console.log('message received in agent');
console.log(event.detail);
var data = event.detail;
if (data.type == 'request-login') {
navigator.id.request();
} else if (data.type == 'request-logout') {
navigator.id.logout();
}
}
function sendToContent(message) {
window.postMessage(message, "*");
}
})();
|
(function() {
// wait for polyfill to be loaded
if (document.readyState == "complete") {
init();
} else {
window.addEventListener('load', init);
}
var loggedIn = false;
function init() {
if (!navigator.id)
return;
sendToContent({ type: "init" });
window.addEventListener('browserid-exec', onMessage);
navigator.id.watch({ onlogin: onLogin, onlogout: onLogout });
}
function onLogin(assertion) {
console.log('onLogin');
loggedIn = true;
sendToContent({ type: 'auth', loggedIn: loggedIn });
}
function onLogout() {
console.log('onLogout');
loggedIn = false;
sendToContent({ type: 'auth', loggedIn: loggedIn });
}
function onMessage(event) {
console.log('message received in agent');
console.log(event.detail);
var data = event.detail;
if (data.type == 'request-login') {
navigator.id.request();
} else if (data.type == 'request-logout') {
navigator.id.logout();
}
}
function sendToContent(message) {
window.postMessage(message, "*");
}
})();
|
Use addEventListener instead of onload
|
Use addEventListener instead of onload
|
JavaScript
|
mit
|
sickill/chrome-browserid
|
d09838f37b7fbf7fc31fb662353a98233157ffd7
|
js/index.js
|
js/index.js
|
(function( $ ) {
function setHeaderHeight() {
$( '#screen-fill' ).css( 'height', $( window ).height() - 50 );
}
$( document ).ready( setHeaderHeight );
$( window ).resize( setHeaderHeight );
$( window ).scroll( function() {
var currentY = window.scrollY;
$( '.fading' ).each( function(i, el) {
var elemY = $( el ).position().top;
var offset = elemY - currentY;
if ( currentY <= 0 ) {
$( el ).css( 'opacity', 1 );
} else if ( offset > 0 ) {
$( el ).css( 'opacity', ( offset * 0.5 ) / elemY );
}
} );
} );
} )( jQuery );
|
(function( $ ) {
function setHeaderHeight() {
$( '#screen-fill' ).css( 'height', $( window ).height() - 50 );
}
$( document ).ready( setHeaderHeight );
$( window ).resize( setHeaderHeight );
$( window ).scroll( function() {
var currentY = window.scrollY;
$( '.fading' ).each( function(i, el) {
var elemY = $( el ).position().top;
var offset = elemY - currentY;
if ( currentY <= 0 ) {
$( el ).css( 'opacity', 1 );
} else if ( offset > 0 ) {
$( el ).css( 'opacity', ( ( offset * 0.5 ) / elemY ).toFixed(2) );
console.log( ( ( offset * 0.5 ) / elemY ).toFixed(2) );
}
} );
} );
} )( jQuery );
|
Reduce precision for fade out
|
Reduce precision for fade out
|
JavaScript
|
mit
|
Automattic/socket.io-website,davidcelis/socket.io-website,davidcelis/socket.io-website,Automattic/socket.io-website,Automattic/socket.io-website
|
1455be74c9839c3da35a54793babbe84140e2250
|
src/game/TutorialState.js
|
src/game/TutorialState.js
|
import Phaser from 'phaser-ce';
import { tissueColor, bacteriaColor } from './constants';
export default class TutorialState extends Phaser.State {
bacteria = null;
preload() {
this.game.load.image('bacteria', 'assets/sprites/bacteria.png');
}
create() {
console.log(this);
this.stage.backgroundColor = tissueColor;
this.bacteria = this.game.add.sprite(this.world.centerX, this.world.centerY, 'bacteria');
this.bacteria.anchor.set(0.5);
this.bacteria.scale.setTo(0.2);
}
update() {
this.bacteria.rotation += 0.01;
}
}
/*
const graphics = this.game.add.graphics(0, 0);
graphics.beginFill(bacteriaColor);
graphics.drawEllipse(0, 0, 50, 30);
graphics.endFill();
this.bacteria = this.game.add.sprite(this.world.centerX, this.world.centerY, graphics.generateTexture());
graphics.destroy();
*/
|
import Phaser from 'phaser-ce';
import { tissueColor, bacteriaColor } from './constants';
export default class TutorialState extends Phaser.State {
bacteria = null;
tissue = {
bacteria: null,
macrophage: null,
neutrophil: null
};
boneMarrow = {
macrophage: null,
neutrophil: null
};
preload() {
this.game.load.image('bacteria', 'assets/sprites/bacteria.png');
this.game.load.image('macrophage', 'assets/sprites/macrophage.png');
this.game.load.image('macrophage_active', 'assets/sprites/macrophage_active.png');
this.game.load.image('neutrophil', 'assets/sprites/neutrophil.png');
}
create() {
console.log(this);
this.stage.backgroundColor = tissueColor;
this.bacteria = this.game.add.sprite(this.world.centerX, this.world.centerY, 'bacteria');
this.bacteria.anchor.set(0.5);
this.bacteria.scale.setTo(0.2);
}
update() {
this.bacteria.rotation += 0.01;
}
}
/*
const graphics = this.game.add.graphics(0, 0);
graphics.beginFill(bacteriaColor);
graphics.drawEllipse(0, 0, 50, 30);
graphics.endFill();
this.bacteria = this.game.add.sprite(this.world.centerX, this.world.centerY, graphics.generateTexture());
graphics.destroy();
*/
|
Add tissue and boneMarrow objects to tutorial state
|
Add tissue and boneMarrow objects to tutorial state
|
JavaScript
|
mit
|
marc1404/WreckSam,marc1404/WreckSam
|
6fcdedcfce8460b174bb7b3c44282998cb867c7c
|
lib/consolify.js
|
lib/consolify.js
|
'use strict';
var fs = require('fs');
var through = require('through2');
var consolify = require('consolify');
module.exports = function (b, opts) {
consolify(b, {
bundle: opts.bundle
});
function apply() {
var file = '';
b.pipeline.get('wrap').push(through(function (chunk, enc, next) {
/*jslint unparam: true*/
file += chunk;
next();
}, function (next) {
fs.writeFileSync(opts.consolify, file);
if (opts.watch) {
console.log('Generated ' + opts.consolify);
}
next();
}));
}
apply();
b.on('reset', apply);
};
|
/*
* mochify.js
*
* Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
*
* @license MIT
*/
'use strict';
var fs = require('fs');
var through = require('through2');
var consolify = require('consolify');
module.exports = function (b, opts) {
consolify(b, {
bundle: opts.bundle
});
function apply() {
var file = '';
b.pipeline.get('wrap').push(through(function (chunk, enc, next) {
/*jslint unparam: true*/
file += chunk;
next();
}, function (next) {
fs.writeFileSync(opts.consolify, file);
if (opts.watch) {
console.log('Generated ' + opts.consolify);
}
next();
}));
}
apply();
b.on('reset', apply);
};
|
Add missing copyright and license header
|
Add missing copyright and license header
|
JavaScript
|
mit
|
mantoni/mochify.js,boneskull/mochify.js,jhytonen/mochify.js,jhytonen/mochify.js,Swaagie/mochify.js,mantoni/mochify.js,boneskull/mochify.js,mantoni/mochify.js,Swaagie/mochify.js
|
7bdd7b1475ce5bf53711f688fe027f555a60f129
|
Utilities/ExampleRunner/template-config.js
|
Utilities/ExampleRunner/template-config.js
|
module.exports = function buildConfig(name, relPath, destPath, root) {
return `
var loaders = require('../config/webpack.loaders.js');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
plugins: [
new HtmlWebpackPlugin({
inject: 'body',
}),
],
entry: '${relPath}',
output: {
path: '${destPath}',
filename: '${name}.js',
},
module: {
preLoaders: [{
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/,
}],
loaders: loaders,
},
eslint: {
configFile: '${root}/.eslintrc.js',
},
devServer: {
contentBase: '${destPath}',
port: 9999,
host: '0.0.0.0',
hot: true,
quiet: false,
noInfo: false,
stats: {
colors: true,
},
},
};
`;
};
|
module.exports = function buildConfig(name, relPath, destPath, root) {
return `
var loaders = require('../config/webpack.loaders.js');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpack = require('webpack');
module.exports = {
plugins: [
new HtmlWebpackPlugin({
inject: 'body',
}),
new webpack.DefinePlugin({
__BASE_PATH__: "''",
}),
],
entry: '${relPath}',
output: {
path: '${destPath}',
filename: '${name}.js',
},
module: {
preLoaders: [{
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/,
}],
loaders: loaders,
},
eslint: {
configFile: '${root}/.eslintrc.js',
},
devServer: {
contentBase: '${root}',
port: 9999,
host: '0.0.0.0',
hot: true,
quiet: false,
noInfo: false,
stats: {
colors: true,
},
proxy: {
'/data/**': {
target: 'http://0.0.0.0:9999/Data',
pathRewrite: {
'^/data': ''
},
},
},
},
};
`;
};
|
Fix example runner to support __BASE_PATH__ and serve the full vtk-js repo
|
fix(ExampleBuilder): Fix example runner to support __BASE_PATH__ and serve the full vtk-js repo
|
JavaScript
|
bsd-3-clause
|
Kitware/vtk-js,Kitware/vtk-js,Kitware/vtk-js,Kitware/vtk-js
|
33bcb755e5b68e97f65cd63664a82219c2297015
|
diaeresis.js
|
diaeresis.js
|
/* Diaeresis.js | Copyright (C) 2016 Curiositry (http://curiositry.com) | MIT Licensed */
|
/* Diaeresis.js | Copyright (C) 2016 Curiositry (http://curiositry.com) | MIT Licensed */
(function(){
})();
|
Add self-executing anonymous function to put it all in.
|
:construction: Add self-executing anonymous function to put it all in.
|
JavaScript
|
mit
|
curiositry/diaeresis,curiositry/diaeresis
|
7bebf6268b47c2520daa41327ddd268f133404d0
|
examples/all.js
|
examples/all.js
|
import React from 'react';
import ReactDOM from 'react-dom';
import DraftailEditor, { BLOCK_TYPE, INLINE_STYLE } from '../lib';
import allContentState from './utils/allContentState';
const mount = document.querySelector('[data-mount-all]');
const onSave = contentState => {
sessionStorage.setItem('all:contentState', JSON.stringify(contentState));
};
const allBlockTypes = Object.keys(BLOCK_TYPE).map(type => ({
label: `${type.charAt(0).toUpperCase()}${type
.slice(1)
.toLowerCase()
.replace(/_/g, ' ')}`,
type: BLOCK_TYPE[type],
}));
const allInlineStyles = Object.keys(INLINE_STYLE).map(type => ({
label: `${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()}`,
type: INLINE_STYLE[type],
}));
const editor = (
<DraftailEditor
rawContentState={allContentState}
onSave={onSave}
stripPastedStyles={false}
enableHorizontalRule={true}
enableLineBreak={true}
showUndoRedoControls={true}
blockTypes={allBlockTypes}
inlineStyles={allInlineStyles}
/>
);
ReactDOM.render(editor, mount);
|
import React from 'react';
import ReactDOM from 'react-dom';
import DraftailEditor, { BLOCK_TYPE, INLINE_STYLE } from '../lib';
import allContentState from './utils/allContentState';
const mount = document.querySelector('[data-mount-all]');
const onSave = contentState => {
sessionStorage.setItem('all:contentState', JSON.stringify(contentState));
};
const allBlockTypes = Object.keys(BLOCK_TYPE)
.filter(t => t !== 'ATOMIC')
.map(type => ({
label: `${type.charAt(0).toUpperCase()}${type
.slice(1)
.toLowerCase()
.replace(/_/g, ' ')}`,
type: BLOCK_TYPE[type],
}));
const allInlineStyles = Object.keys(INLINE_STYLE).map(type => ({
label: `${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()}`,
type: INLINE_STYLE[type],
}));
const editor = (
<DraftailEditor
rawContentState={allContentState}
onSave={onSave}
stripPastedStyles={false}
enableHorizontalRule={true}
enableLineBreak={true}
showUndoRedoControls={true}
blockTypes={allBlockTypes}
inlineStyles={allInlineStyles}
/>
);
ReactDOM.render(editor, mount);
|
Stop showing atomic block in "All" example
|
Stop showing atomic block in "All" example
|
JavaScript
|
mit
|
springload/draftail,springload/draftail,springload/draftail,springload/draftail
|
44a2826d08a44f0494e86469cd6632e7f9ff071f
|
app/controllers/sell/successTransaction.js
|
app/controllers/sell/successTransaction.js
|
//////////////////////////////////////
// User buys one ticket for himself //
//////////////////////////////////////
'use strict';
var Promise = require('bluebird');
module.exports = function (db, config) {
var logger = require('../../lib/log')(config);
var rest = require('../../lib/rest')(config, logger);
return function (req, res, next) {
db.Token.find({
sherlocksToken: req.body.data
}).then(function (token) {
return new Promise(function (resolve, reject) {
if (!token) {
return reject('no token to ticket');
}
token.destroy();
resolve(token.ticket);
});
}).then(function (ticketId) {
return db.Ticket.find(ticketId);
}).then(function (ticket) {
ticket.paid = true;
ticket.paid_at = new Date();
return ticket.save();
}).then(function (ticket) {
logger.info('Paid with sherlocks');
if (ticket.username !== 0) {
res.locals.forcedUsername = ticket.username;
res.locals.shouldNotCheckPassword = true;
return next();
}
res.redirect('/#/ticketBought');
}).catch(function (err) {
Error.emit(res, 500, '500 - Server error', err);
logger.error(err);
});
};
};
|
//////////////////////////////////////
// User buys one ticket for himself //
//////////////////////////////////////
'use strict';
var Promise = require('bluebird');
module.exports = function (db, config) {
var logger = require('../../lib/log')(config);
var rest = require('../../lib/rest')(config, logger);
return function (req, res, next) {
db.Token.find({
sherlocksToken: req.body.token
}).then(function (token) {
return new Promise(function (resolve, reject) {
if (!token) {
return reject('no token to ticket');
}
token.destroy();
resolve(token.ticket);
});
}).then(function (ticketId) {
return db.Ticket.find(ticketId);
}).then(function (ticket) {
ticket.paid = true;
ticket.paid_at = new Date();
// Save ticket id for later
req.ticketId = ticket.id;
req.sherlocksToken = req.body.token;
return ticket.save();
}).then(function (ticket) {
logger.info('Paid with sherlocks');
if (ticket.username !== 0) {
res.locals.forcedUsername = ticket.username;
res.locals.shouldNotCheckPassword = true;
return next();
}
res.redirect('/#/ticketBought');
}).catch(function (err) {
Error.emit(res, 500, '500 - Server error', err);
logger.error(err);
});
};
};
|
Use token and not data
|
Use token and not data
|
JavaScript
|
mit
|
buckutt/BuckUTT-pay,buckutt/BuckUTT-pay,buckutt/BuckUTT-pay
|
bcc70e0d4ed383c3731a65db4fbd5ae67d95c845
|
Resources/Private/Javascripts/Main.js
|
Resources/Private/Javascripts/Main.js
|
/**
* RequireJS configuration
* @description Pass in options for RequireJS like paths, shims or the baseUrl
*/
require.config({
paths: {
"mainModule" : "Modules/Main"
},
// Append a date on each requested script to prevent caching issues.
urlArgs: "bust=" + Date.now()
});
/**
* RequireJS calls
* @description Require and fire off the main/initial file of the application.
*/
require(function(require) {
"use strict";
var MainFn = require("mainModule");
new MainFn();
});
|
/**
* RequireJS configuration
* @description Pass in options for RequireJS like paths, shims or the baseUrl
*/
require.config({
paths: {
"mainModule" : "Modules/Main"
},
// Append a date on each requested script to prevent caching issues.
urlArgs: "bust=" + Date.now()
});
/**
* RequireJS calls
* @description Require and fire off the main/initial file of the application.
*/
require(["mainModule"], function(MainFn) {
"use strict";
new MainFn();
});
|
Revert 60f69b3 as the var based syntax isn't working with the r.js optimizer
|
[BUGFIX] Revert 60f69b3 as the var based syntax isn't working with the r.js optimizer
|
JavaScript
|
mit
|
t3b/t3b_template,t3b/t3b_template,t3b/t3b_template,t3b/t3b_template,t3b/t3b_template
|
f78fb6622ecc2204573326790eb5bdd254206580
|
app/assets/javascripts/application.js
|
app/assets/javascripts/application.js
|
//= require vendor
//= require app
//= require_tree ./lib
//= require_tree ./app/controllers
//= require_tree ./app/helpers
//= require_tree ./app/models
//= require sponsors
//= require_tree ./sponsors
|
//= require vendor
//= require app
//= require_tree ./lib
//= require_tree ./app
//= require sponsors
//= require_tree ./sponsors
|
Bring back ALL THE ASSETS!
|
Bring back ALL THE ASSETS!
|
JavaScript
|
mit
|
0xCCD/travis-ci,0xCCD/travis-ci
|
573253b7f5fca0a4e19111a07044bdb1caa59f45
|
app/assets/javascripts/application.js
|
app/assets/javascripts/application.js
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require underscore
//= require gmaps/google
//= require_tree .
$(function(){ $(document).foundation(); });
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require underscore
//= require gmaps/google
//= require_tree .
window.onload = function() {
$(document).foundation();
};
|
Fix off-canvas menu with Turbolinks
|
Fix off-canvas menu with Turbolinks
Solution from Gian Marco Prazzoli's post in
http://foundation.zurb.com/forum/posts/2348-foundation-5-topbar-menu-not-responding-on-rails4
|
JavaScript
|
mit
|
hackedu/website,zachlatta/website,zachlatta/website,zachlatta/website,hackedu/website,hackedu/website
|
2c45fb05fae5aed1e2f11b8ed3fe91056b88cbf9
|
app/components/select-or-typeahead.js
|
app/components/select-or-typeahead.js
|
import Ember from 'ember';
import SelectValues from 'hospitalrun/utils/select-values';
export default Ember.Component.extend({
name: 'select-or-typeahead',
className: null,
hint: true,
label: null,
list: null,
optionLabelPath: 'value',
optionValuePath: 'id',
property: null,
prompt: ' ',
selection: null,
setOnBlur: true,
typeAheadType: null,
content: function() {
var list = this.get('list'),
optionLabelPath = this.get('optionLabelPath'),
optionValuePath = this.get('optionValuePath'),
userCanAdd = this.get('userCanAdd');
if (!Ember.isEmpty(list) && list.get) {
var contentList = list.get('value');
if (Ember.isEmpty(contentList)) {
return [];
}
if (!userCanAdd && optionLabelPath === 'value' && optionValuePath === 'id') {
contentList = contentList.map(SelectValues.selectValuesMap);
}
return contentList;
}
}.property('list'),
usePricingTypeAhead: function() {
return (this.get('typeAheadType') === 'pricing');
}.property('typeAheadType'),
userCanAdd: function() {
var list = this.get('list');
if (!Ember.isEmpty(list) && list.get) {
return list.get('userCanAdd');
} else {
return true;
}
}.property('list')
});
|
import Ember from 'ember';
import SelectValues from 'hospitalrun/utils/select-values';
export default Ember.Component.extend({
name: 'select-or-typeahead',
className: null,
hint: true,
label: null,
list: null,
optionLabelPath: 'value',
optionValuePath: 'id',
property: null,
prompt: ' ',
selection: null,
setOnBlur: true,
typeAheadType: null,
content: function() {
var list = this.get('list'),
optionLabelPath = this.get('optionLabelPath'),
optionValuePath = this.get('optionValuePath'),
userCanAdd = this.get('userCanAdd');
if (!Ember.isEmpty(list) && list.get) {
var contentList = list.get('value');
if (Ember.isEmpty(contentList)) {
return [];
}
if (!userCanAdd && optionLabelPath === 'value' && optionValuePath === 'id') {
return contentList.map(SelectValues.selectValuesMap);
} else {
return contentList;
}
}
}.property('list'),
usePricingTypeAhead: function() {
return (this.get('typeAheadType') === 'pricing');
}.property('typeAheadType'),
userCanAdd: function() {
var list = this.get('list');
if (!Ember.isEmpty(list) && list.get) {
return list.get('userCanAdd');
} else {
return true;
}
}.property('list')
});
|
Make sure lookup list isn't modified
|
Make sure lookup list isn't modified
|
JavaScript
|
mit
|
HospitalRun/hospitalrun-frontend,HospitalRun/hospitalrun-frontend,HospitalRun/hospitalrun-frontend,HospitalRun/hospitalrun-frontend
|
2e15ab28e8ae50fc53ef71cc0283ac2f8e9b22fc
|
lib/exec.js
|
lib/exec.js
|
var spawn = require('child_process').spawn;
var dotenv = require('./dot-env');
var objectAssign = require('object-assign');
module.exports = function exec(script) {
// Grab the command section of the entered command
var command = script.command.split(' ')[0];
// Anything else is options
var options = script.command.split(' ').slice(1);
var argv = process.argv.splice(3);
options = options.concat(argv);
script.env = script.env || {};
var env = objectAssign(process.env, script.env, dotenv);
console.log('to be executed:', command, options.join(' '));
spawn(command, options, {
env: env,
stdio: ['pipe', process.stdout, process.stderr]
}).on('close', function(code) {
process.exit(code);
});
}
|
var spawn = require('child_process').spawn;
var dotenv = require('./dot-env');
var objectAssign = require('object-assign');
module.exports = function exec(script) {
var argv = process.argv.splice(3);
var command = script.command + ' ' + argv.join(' ');
script.env = script.env || {};
var env = objectAssign(process.env, script.env, dotenv);
var sh = 'sh', shFlag = '-c';
if (process.platform === 'win32') {
sh = 'cmd';
shFlag = '/c';
}
console.log('to be executed:', command);
spawn(sh, [shFlag, command], {
env: env,
stdio: ['pipe', process.stdout, process.stderr]
}).on('close', function(code) {
process.exit(code);
});
}
|
Add unix (sh -c) and win32 (cmd /c) to command head
|
Add unix (sh -c) and win32 (cmd /c) to command head
|
JavaScript
|
mit
|
mr47/run-on
|
be73ae321a6449596acc75e8d7987abdf659bc99
|
lib/pipe.js
|
lib/pipe.js
|
'use strict';
var value = require('es5-ext/lib/Object/valid-value')
, emit = require('./core').methods.emit;
module.exports = function (emitter1, emitter2) {
value(emitter1) && value(emitter2);
emitter1.emit = function () {
emit.apply(this, arguments);
emit.apply(emitter2, arguments);
};
};
|
'use strict';
var defineProperty = Object.defineProperty
, d = require('es5-ext/lib/Object/descriptor')
, value = require('es5-ext/lib/Object/valid-value')
, emit = require('./core').methods.emit;
module.exports = function (emitter1, emitter2) {
var desc;
value(emitter1) && value(emitter2);
if (!emitter1.emit) {
throw new TypeError(emitter + ' is not emitter');
}
defineProperty(emitter1, 'emit', d(function () {
emit.apply(this, arguments);
emit.apply(emitter2, arguments);
}));
};
|
Use descriptor to override emit method
|
Use descriptor to override emit method
|
JavaScript
|
mit
|
snowyu/events-ex.js,icebob/event-emitter,medikoo/event-emitter
|
79e238a34ccaf320ac339c7c9812cc1f006c7155
|
lib/save.js
|
lib/save.js
|
var thenify = require('thenify')
var fs = require('fs')
var writeFile = thenify(fs.writeFile)
module.exports = function save (pkg, installedPackages, saveType, useExactVersion) {
var packageJson = pkg.pkg
packageJson[saveType] = packageJson[saveType] || {}
installedPackages.forEach(function (dependency) {
var semverCharacter = useExactVersion ? '' : '^'
packageJson[saveType][dependency.spec.name] = semverCharacter + dependency.version
})
return writeFile(pkg.path, JSON.stringify(packageJson, null, 2), 'utf8')
}
|
var writeFile = require('mz/fs').writeFile
module.exports = function save (pkg, installedPackages, saveType, useExactVersion) {
var packageJson = pkg.pkg
packageJson[saveType] = packageJson[saveType] || {}
installedPackages.forEach(function (dependency) {
var semverCharacter = useExactVersion ? '' : '^'
packageJson[saveType][dependency.spec.name] = semverCharacter + dependency.version
})
return writeFile(pkg.path, JSON.stringify(packageJson, null, 2), 'utf8')
}
|
Use mz/fs instad of thenify
|
Use mz/fs instad of thenify
|
JavaScript
|
mit
|
andreypopp/pnpm,pnpm/supi,pnpm/supi,pnpm/pnpm,andreypopp/pnpm,rstacruz/pnpm,rstacruz/pnpm,rstacruz/pnpm,pnpm/pnpm,pnpm/pnpm,pnpm/supi,andreypopp/pnpm
|
876760cb0761d0b3954d24cbb1d7c0838a49ff9c
|
platform/mds/mds-web/src/main/resources/webapp/js/app.js
|
platform/mds/mds-web/src/main/resources/webapp/js/app.js
|
(function () {
'use strict';
var mds = angular.module('mds', [ 'motech-dashboard', 'mds.services',
'mds.controllers', 'mds.directives', 'mds.utils', 'ui.directives']);
$.ajax({
url: '../mds/available/mdsTabs',
success: function(data) {
mds.constant('AVAILABLE_TABS', data);
},
async: false
});
mds.run(function ($rootScope, AVAILABLE_TABS) {
$rootScope.AVAILABLE_TABS = AVAILABLE_TABS;
});
mds.config(function ($routeProvider, AVAILABLE_TABS) {
$routeProvider
.when('/mds/dataBrowser/:entityId', { templateUrl: '../mds/resources/partials/dataBrowser.html', controller: 'MdsDataBrowserCtrl' })
.when('/mds/dataBrowser/:entityId/:moduleName', { templateUrl: '../mds/resources/partials/dataBrowser.html', controller: 'MdsDataBrowserCtrl' })
.when('/mds/dataBrowser/:entityId/:instanceId/:moduleName', { templateUrl: '../mds/resources/partials/dataBrowser.html', controller: 'MdsDataBrowserCtrl' });
angular.forEach(AVAILABLE_TABS, function (tab) {
$routeProvider.when(
'/mds/{0}'.format(tab),
{
templateUrl: '../mds/resources/partials/{0}.html'.format(tab),
controller: 'Mds{0}Ctrl'.format(tab.capitalize())
}
);
});
});
}());
|
(function () {
'use strict';
var mds = angular.module('mds', [ 'motech-dashboard', 'mds.services', 'webSecurity.services',
'mds.controllers', 'mds.directives', 'mds.utils', 'ui.directives']);
$.ajax({
url: '../mds/available/mdsTabs',
success: function(data) {
mds.constant('AVAILABLE_TABS', data);
},
async: false
});
mds.run(function ($rootScope, AVAILABLE_TABS) {
$rootScope.AVAILABLE_TABS = AVAILABLE_TABS;
});
mds.config(function ($routeProvider, AVAILABLE_TABS) {
$routeProvider
.when('/mds/dataBrowser/:entityId', { templateUrl: '../mds/resources/partials/dataBrowser.html', controller: 'MdsDataBrowserCtrl' })
.when('/mds/dataBrowser/:entityId/:moduleName', { templateUrl: '../mds/resources/partials/dataBrowser.html', controller: 'MdsDataBrowserCtrl' })
.when('/mds/dataBrowser/:entityId/:instanceId/:moduleName', { templateUrl: '../mds/resources/partials/dataBrowser.html', controller: 'MdsDataBrowserCtrl' });
angular.forEach(AVAILABLE_TABS, function (tab) {
$routeProvider.when(
'/mds/{0}'.format(tab),
{
templateUrl: '../mds/resources/partials/{0}.html'.format(tab),
controller: 'Mds{0}Ctrl'.format(tab.capitalize())
}
);
});
});
}());
|
Bring back dependency for web-security services to MDS schema browser
|
Bring back dependency for web-security services to MDS schema browser
Change-Id: I71f289f9201bfad22d67e7d77d6b7065b53436a3
|
JavaScript
|
bsd-3-clause
|
pgesek/motech,wstrzelczyk/motech,sebbrudzinski/motech,wstrzelczyk/motech,ngraczewski/motech,koshalt/motech,jefeweisen/motech,smalecki/motech,justin-hayes/motech,adamkalmus/motech,shubhambeehyv/motech,ngraczewski/motech,LukSkarDev/motech,tstalka/motech,smalecki/motech,justin-hayes/motech,tectronics/motech,kmadej/motech,ngraczewski/motech,LukSkarDev/motech,jefeweisen/motech,tstalka/motech,jefeweisen/motech,tectronics/motech,frankhuster/motech,pgesek/motech,frankhuster/motech,kmadej/motech,wstrzelczyk/motech,frankhuster/motech,ngraczewski/motech,adamkalmus/motech,shubhambeehyv/motech,wstrzelczyk/motech,smalecki/motech,pgesek/motech,koshalt/motech,sebbrudzinski/motech,tectronics/motech,tstalka/motech,shubhambeehyv/motech,justin-hayes/motech,tectronics/motech,frankhuster/motech,smalecki/motech,jefeweisen/motech,koshalt/motech,LukSkarDev/motech,tstalka/motech,kmadej/motech,sebbrudzinski/motech,justin-hayes/motech,pgesek/motech,adamkalmus/motech,shubhambeehyv/motech,sebbrudzinski/motech,koshalt/motech,LukSkarDev/motech,kmadej/motech,adamkalmus/motech
|
d81289bdc0a32305fb339c78bc0e191edd86bfcb
|
workshop/www/js/recipe.js
|
workshop/www/js/recipe.js
|
var Recipe = function(data){
this.title = data.Title;
this.stars = data.StarRating;
this.imageUrl = data.ImageURL
}
function BigOvenRecipeSearchJson(query) {
var allRecipes = [];
var noImageLink = "http://redirect.bigoven.com/pics/recipe-no-image.jpg"
var apiKey = APIKEY;
var titleKeyword = query;
var url = "https://api.bigoven.com/recipes?pg=1&rpp=25&title_kw="
+ titleKeyword
+ "&api_key="+apiKey;
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url
}).then(function(data){
for(i = 0; i < data.Results.length; i ++) {
allRecipes.push(new Recipe(data.Results[i]));
};
return allRecipes
}).then(function(recipes){
// render allRecipes here
})
};
$(document).ready(function(){
var bigOvenSearch = BigOvenRecipeSearchJson('cookies');
});
|
var Recipe = function(data){
this.title = data.Title;
this.stars = data.StarRating;
this.imageUrl = data.ImageURL
}
function BigOvenRecipeSearchJson(query) {
var allRecipes = [];
var noImageLink = "http://redirect.bigoven.com/pics/recipe-no-image.jpg"
var apiKey = "dvx7zJ0x53M8X5U4nOh6CMGpB3d0PEhH";
var titleKeyword = query;
var url = "https://api.bigoven.com/recipes?pg=1&rpp=25&title_kw="
+ titleKeyword
+ "&api_key="+apiKey;
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url
}).then(function(data){
for(i = 0; i < data.Results.length; i ++) {
allRecipes.push(new Recipe(data.Results[i]));
};
return allRecipes
}).then(function(recipes){
var template = $('#search-results').html();
var output = Mustache.render(template, {recipes: recipes});
$('#results').append(output);
})
};
$(document).ready(function(){
BigOvenRecipeSearchJson('cookies');
});
|
Add then callback to render search-results template
|
Add then callback to render search-results template
|
JavaScript
|
mit
|
danasselin/line-cook,nyc-rock-doves-2015/line-cook,danasselin/line-cook,nyc-rock-doves-2015/line-cook,danasselin/line-cook,danasselin/line-cook,nyc-rock-doves-2015/line-cook,nyc-rock-doves-2015/line-cook,nyc-rock-doves-2015/line-cook,nyc-rock-doves-2015/line-cook,nyc-rock-doves-2015/line-cook,danasselin/line-cook,danasselin/line-cook,nyc-rock-doves-2015/line-cook,danasselin/line-cook,danasselin/line-cook
|
8b9b539bae31a49442361ae3f69a8be15f44882e
|
lib/exit.js
|
lib/exit.js
|
/*
* exit
* https://github.com/cowboy/node-exit
*
* Copyright (c) 2013 "Cowboy" Ben Alman
* Licensed under the MIT license.
*/
'use strict';
module.exports = function exit(exitCode, streams) {
if (!streams) { streams = [process.stdout, process.stderr]; }
var drainCount = 0;
// Actually exit if all streams are drained.
function tryToExit() {
if (drainCount === streams.length) {
process.exit(exitCode);
}
}
streams.forEach(function(stream) {
// Prevent further writing.
stream.write = function() {};
// Count drained streams now, but monitor non-drained streams.
if (stream.bufferSize === 0) {
drainCount++;
} else {
stream.once('drain', function() {
drainCount++;
tryToExit();
});
}
});
// If all streams were already drained, exit now.
tryToExit();
// In Windows, when run as a Node.js child process, a script utilizing
// this library might just exit with a 0 exit code, regardless. This code,
// despite the fact that it looks a bit crazy, appears to fix that.
process.on('exit', function() {
process.exit(exitCode);
});
};
|
/*
* exit
* https://github.com/cowboy/node-exit
*
* Copyright (c) 2013 "Cowboy" Ben Alman
* Licensed under the MIT license.
*/
'use strict';
module.exports = function exit(exitCode, streams) {
if (!streams) { streams = [process.stdout, process.stderr]; }
var drainCount = 0;
// Actually exit if all streams are drained.
function tryToExit() {
if (drainCount === streams.length) {
process.exit(exitCode);
}
}
streams.forEach(function(stream) {
// Count drained streams now, but monitor non-drained streams.
if (stream.bufferSize === 0) {
drainCount++;
} else {
stream.write('', 'utf-8', function() {
drainCount++;
tryToExit();
});
}
// Prevent further writing.
stream.write = function() {};
});
// If all streams were already drained, exit now.
tryToExit();
// In Windows, when run as a Node.js child process, a script utilizing
// this library might just exit with a 0 exit code, regardless. This code,
// despite the fact that it looks a bit crazy, appears to fix that.
process.on('exit', function() {
process.exit(exitCode);
});
};
|
Use an empty write instead of drain event. Closes gh-5, gh-4.
|
Use an empty write instead of drain event. Closes gh-5, gh-4.
|
JavaScript
|
mit
|
cowboy/node-exit
|
f7bb7dff415e0652a0e8b95b0f311bacfd5b481c
|
src/database/DataTypes/Report.js
|
src/database/DataTypes/Report.js
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import Realm from 'realm';
/**
* A Report.
*
* @property {string} id
* @property {string} type
* @property {string} title
* @property {string} _data
*/
export class Report extends Realm.Object {
/**
* Get data.
*
* @return {Object}
*/
get data() {
return JSON.parse(this._data);
}
/**
* Set data.
*
* @param {dataObject} dataObject
*/
set data(dataObject) {
this._data = JSON.stringify(dataObject);
}
}
Report.schema = {
name: 'Report',
primaryKey: 'id',
properties: {
id: 'string',
type: 'string',
title: 'string',
_data: 'string',
},
};
export default Report;
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import Realm from 'realm';
import checkIsObject from '../utilities';
/**
* A Report.
*
* @property {string} id
* @property {string} type
* @property {string} title
* @property {string} _data
*/
export class Report extends Realm.Object {
/**
* Get data.
*
* @return {Object}
*/
get data() {
return JSON.parse(this._data);
}
/**
* Set data.
*
* @param {dataObject} dataObject
*/
set data(dataObject) {
this._data = checkIsObject(dataObject) ? JSON.stringify(dataObject) : {};
}
}
Report.schema = {
name: 'Report',
primaryKey: 'id',
properties: {
id: 'string',
type: 'string',
title: 'string',
_data: 'string',
},
};
export default Report;
|
Add checkIsObject in set data()
|
Add checkIsObject in set data()
|
JavaScript
|
mit
|
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
|
a8609d63bb4ad116904be74aa9f1b66f676ae294
|
public/modules/core/controllers/home.client.controller.js
|
public/modules/core/controllers/home.client.controller.js
|
'use strict';
angular.module('core').controller('HomeController', ['$scope', '$http', 'Authentication', 'Users',
function($scope, $http, Authentication, Users) {
// This provides Authentication context.
$scope.authentication = Authentication;
if (Authentication.user !== '') {
$scope.helloMessage = 'Привет, ' + Authentication.user.displayName;
} else {
// TODO: Redirect to login page
$scope.helloMessage = 'Необходимо залогиниться или создать аккаунт';
}
// Get all users
$http.get('/users')
.success(function(response) {
$scope.users = response;
});
}
]);
|
'use strict';
angular.module('core').controller('HomeController', ['$scope', '$http', '$location', 'Authentication', 'Users',
function($scope, $http, $location, Authentication, Users) {
// This provides Authentication context.
$scope.authentication = Authentication;
if (Authentication.user !== '') {
$scope.helloMessage = 'Привет, ' + Authentication.user.displayName;
} else {
$location.path('/signin');
}
// Get all users
$http.get('/users')
.success(function(response) {
$scope.users = response;
});
}
]);
|
Add redirecting to sing in page if user not authorizated'
|
Add redirecting to sing in page if user not authorizated'
|
JavaScript
|
mit
|
sevazhidkov/angular-test-app,sevazhidkov/angular-test-app,sevazhidkov/angular-test-app
|
129a40482844c3968d6d387b4648d70944732b9d
|
src/entities.js
|
src/entities.js
|
;(function(exports) {
function Entities(coquette, game) {
this.c = coquette;
this.game = game;
this._entities = [];
};
Entities.prototype = {
update: function(interval) {
var entities = this.all();
for (var i = 0, len = entities.length; i < len; i++) {
if (entities[i].update !== undefined) {
entities[i].update(interval);
}
}
},
all: function(Constructor) {
if (Constructor === undefined) {
return this._entities.slice(); // return shallow copy of array
} else {
var entities = [];
for (var i = 0; i < this._entities.length; i++) {
if (this._entities[i] instanceof Constructor) {
entities.push(this._entities[i]);
}
}
return entities;
}
},
create: function(Constructor, settings, callback) {
var entity = new Constructor(this.game, settings || {});
this.c.collider.createEntity(entity);
this._entities.push(entity);
return entity;
},
destroy: function(entity, callback) {
for(var i = 0; i < this._entities.length; i++) {
if(this._entities[i] === entity) {
this.c.collider.destroyEntity(entity);
this._entities.splice(i, 1);
break;
}
}
}
};
exports.Entities = Entities;
})(typeof exports === 'undefined' ? this.Coquette : exports);
|
;(function(exports) {
function Entities(coquette, game) {
this.c = coquette;
this.game = game;
this._entities = [];
};
Entities.prototype = {
update: function(interval) {
var entities = this.all();
for (var i = 0, len = entities.length; i < len; i++) {
if (entities[i].update !== undefined) {
entities[i].update(interval);
}
}
},
all: function(Constructor) {
if (Constructor === undefined) {
return this._entities.slice(); // return shallow copy of array
} else {
var entities = [];
for (var i = 0; i < this._entities.length; i++) {
if (this._entities[i] instanceof Constructor) {
entities.push(this._entities[i]);
}
}
return entities;
}
},
create: function(Constructor, settings) {
var entity = new Constructor(this.game, settings || {});
this.c.collider.createEntity(entity);
this._entities.push(entity);
return entity;
},
destroy: function(entity) {
for(var i = 0; i < this._entities.length; i++) {
if(this._entities[i] === entity) {
this.c.collider.destroyEntity(entity);
this._entities.splice(i, 1);
break;
}
}
}
};
exports.Entities = Entities;
})(typeof exports === 'undefined' ? this.Coquette : exports);
|
Remove unused callback params from create() destroy()
|
Remove unused callback params from create() destroy()
|
JavaScript
|
mit
|
maryrosecook/coquette,maryrosecook/coquette,matthewsimo/coquette,matthewsimo/coquette,cdosborn/coquette,cdosborn/coquette
|
61c9d6ed8df1a57a53406492989829f7bf8feca3
|
lib/mime.js
|
lib/mime.js
|
/*!
* YUI Mocha
* Copyright 2011 Yahoo! Inc.
* Licensed under the BSD license.
*/
/**
* File extension to MIME type map.
*
* Used by `serve.js` when streaming files from disk.
*/
this.contentTypes = {
"css": "text/css",
"html": "text/html",
"ico": "image/vnd.microsoft.icon",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "application/javascript",
"json": "application/json",
"less": "text/css",
"png": "image/png",
"svg": "image/svg+xml",
"swf": "application/x-shockwave-flash",
"tiff": "image/tiff",
"txt": "text/plain",
"xml": "text/xml"
};
|
/*!
* YUI Mocha
* Copyright 2011 Yahoo! Inc.
* Licensed under the BSD license.
*/
/**
* @module mime
*/
/**
* File extension to MIME type map.
*
* Used by `serve.js` when streaming files from disk.
*
* @property contentTypes
* @type object
*/
this.contentTypes = {
"css": "text/css",
"html": "text/html",
"ico": "image/vnd.microsoft.icon",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "application/javascript",
"json": "application/json",
"less": "text/css",
"png": "image/png",
"svg": "image/svg+xml",
"swf": "application/x-shockwave-flash",
"tiff": "image/tiff",
"txt": "text/plain",
"xml": "text/xml"
};
|
Add YUI Doc tags to documentation blocks.
|
Add YUI Doc tags to documentation blocks.
|
JavaScript
|
bsd-3-clause
|
reid/onyx,reid/onyx
|
a1875e57a2da90534d43819f3e05fbcf79b0dfa6
|
plugins/instagram.js
|
plugins/instagram.js
|
var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'Instagram',
prepareImgLinks:function (callback) {
$('body').on('mouseenter', 'a[href*="?taken-by"]', function () {
var link = $(this);
if (link.hasClass('hoverZoomLink'))
return;
if (link.find('span.coreSpriteSidecarIconLarge').length === 0) {
link.data().hoverZoomSrc = [link.find('img').attr('src')];
link.addClass('hoverZoomLink');
hoverZoom.displayPicFromElement(link);
} else {
hoverZoom.prepareFromDocument(link, link.attr('href'), function(doc) {
var img = [];
doc.querySelectorAll('script').forEach(script => {
var body = script.innerHTML;
if (!body.startsWith('window._sharedData')) return;
var json = JSON.parse(body.slice(20, -1));
var edges = json.entry_data.PostPage["0"].graphql.shortcode_media.edge_sidecar_to_children.edges;
edges.forEach(edge => img.push([edge.node.display_url]));
});
return img.length > 0 ? img : false;
});
}
});
}
});
|
var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'Instagram',
prepareImgLinks:function (callback) {
$('body').on('mouseenter', 'a[href*="?taken-by"]', function () {
var link = $(this);
if (link.hasClass('hoverZoomLink'))
return;
if (link.find('span.coreSpriteSidecarIconLarge').length === 0) {
link.data().hoverZoomSrc = [link.prop('href').replace(/[?]taken-by=.*$/, 'media?size=l')];
link.addClass('hoverZoomLink');
hoverZoom.displayPicFromElement(link);
} else {
hoverZoom.prepareFromDocument(link, link.attr('href'), function(doc) {
var img = [];
doc.querySelectorAll('script').forEach(script => {
var body = script.innerHTML;
if (!body.startsWith('window._sharedData')) return;
var json = JSON.parse(body.slice(20, -1));
var edges = json.entry_data.PostPage["0"].graphql.shortcode_media.edge_sidecar_to_children.edges;
edges.forEach(edge => img.push([edge.node.display_url]));
});
return img.length > 0 ? img : false;
});
}
});
}
});
|
Use full-size image instead of the default one.
|
Use full-size image instead of the default one.
|
JavaScript
|
mit
|
superlime/hoverzoomgold,extesy/hoverzoom,extesy/hoverzoom,superlime/hoverzoomgold
|
a307404e7c4772fa2ba65830fa857e1508056ac7
|
lib/util.js
|
lib/util.js
|
'use strict'
const childProcess = require('child_process')
const fs = require('fs')
function exec (command, options) {
return new Promise(function (resolve, reject) {
childProcess.exec(command, options, function (err, stdout, stderr) {
if (err) {
reject(err)
} else {
resolve({command, stdout, stderr})
}
})
})
}
function mkdir (path) {
return new Promise(function (resolve, reject) {
fs.mkdir(path, function (err) {
if (err) {
reject(err)
} else {
resolve()
}
})
})
}
function exists (path) {
return new Promise(function (resolve, reject) {
fs.exists(path, function (exists) {
if (exists) {
resolve()
} else {
reject()
}
})
})
}
function readFile (path) {
return new Promise(function (resolve, reject) {
fs.readFile(path, function (err, data) {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
}
module.exports = {
exec,
mkdir,
exists,
readFile
}
|
'use strict'
const childProcess = require('child_process')
const fs = require('fs')
function exec (command, options) {
return new Promise(function (resolve, reject) {
childProcess.exec(command, options, function (err, stdout, stderr) {
if (err) {
reject(err)
} else {
resolve({command, stdout, stderr})
}
})
})
}
function exists (path) {
return new Promise(function (resolve, reject) {
fs.exists(path, function (exists) {
if (exists) {
resolve()
} else {
reject()
}
})
})
}
function promisify (fn) {
return function () {
const args = Array.prototype.slice.call(arguments)
return new Promise(function (resolve, reject) {
function callback (err) {
if (err) {
reject(err)
} else {
const data = Array.prototype.slice.call(arguments, 1)
resolve(data)
}
}
fn.apply(null, args.concat(callback))
})
}
}
module.exports = {
exec,
exists,
mkdir: promisify(fs.mkdir),
readFile: promisify(fs.readFile)
}
|
Add promisify function to reduce redundancy
|
Add promisify function to reduce redundancy
|
JavaScript
|
isc
|
jcollado/multitest
|
91c922ac32d68db8965f335f13882c51f73bb522
|
public/robot-kata.js
|
public/robot-kata.js
|
console.log("Hello Robot Kata!");
var floorContext = document.getElementById('floor').getContext('2d');
var floorImage = new Image();
var floorOffset = $('#floor').offset();
floorImage.src = 'roomba-dock.png';
floorImage.onload = function () {
floorContext.drawImage(floorImage, 0, 0);
};
$('#floor').mousemove(function (e) {
var x = Math.floor(e.pageX - floorOffset.left);
var y = Math.floor(e.pageY - floorOffset.top);
console.log(floorContext.getImageData(x, y, 1, 1).data);
});
|
loadFloorImage(function () {
console.log("Hello Robot Kata!");
});
var floor = {
context: $('#floor')[0].getContext('2d'),
offset: $('#floor').offset(),
getPosition: function (e) {
return {
x: Math.floor(e.pageX - this.offset.left),
y: Math.floor(e.pageY - this.offset.top)
}
}
}
function loadFloorImage(callback) {
var image = new Image();
image.src = 'roomba-dock.png';
image.onload = function () {
floor.context.drawImage(this, 0, 0);
callback();
}
}
function getColor(pos) {
var imageData = floor.context.getImageData(pos.x, pos.y, 1, 1).data;
var r = imageData[0];
var g = imageData[1];
var b = imageData[2];
var threshold = 192;
if (r > threshold && g > threshold && b > threshold) {
return 'white';
} else if (r > threshold && g > threshold) {
return 'yellow';
} else if (r > threshold) {
return 'red';
} else if (g > threshold) {
return 'green';
} else if (b > threshold) {
return 'blue';
} else {
return 'black';
}
}
$('#floor').mousemove(function (e) {
console.log(getColor(floor.getPosition(e)));
});
|
Refactor and add function to determine color
|
Refactor and add function to determine color
|
JavaScript
|
mit
|
ideal-knee/robot-kata-js,ideal-knee/robot-kata-js,ideal-knee/robot-kata-js
|
fc81c225801101221d308f300d2491a39d2db22e
|
frontend/reducers/promoteModal.js
|
frontend/reducers/promoteModal.js
|
import * as CONST from '../constants/actionTypes';
const initialState = { open: false };
export default function promoteModal(state = initialState, action) {
switch (action.type) {
case CONST.SHOW_PROMOTE_MODAL:
return { open: true };
case CONST.HIDE_PROMOTE_MODAL:
return { open: false };
default:
return state;
}
}
|
import * as CONST from '../constants/actionTypes';
const initialState = { open: false, piece: undefined };
export default function promoteModal(state = initialState, action) {
switch (action.type) {
case CONST.SHOW_PROMOTE_MODAL:
return { open: true, piece: action.piece };
case CONST.HIDE_PROMOTE_MODAL:
return { open: false, piece: undefined };
default:
return state;
}
}
|
Update reducer properties, allow `piece` key.
|
Update reducer properties, allow `piece` key.
* the `piece` is the target promote or not.
|
JavaScript
|
mit
|
mgi166/usi-front,mgi166/usi-front
|
91e8cbf86807bef4636f38d8157557af8901f39c
|
gateways/paypal_express/script.js
|
gateways/paypal_express/script.js
|
(function() {
/***********************************************************/
/* Handle Proceed to Payment
/***********************************************************/
jQuery(function() {
jQuery(document).on('proceedToPayment', function(event, ShoppingCart) {
if (ShoppingCart.gateway != 'paypal_express') {
return;
}
var order = {
products: storejs.get('grav-shoppingcart-basket-data'),
address: storejs.get('grav-shoppingcart-person-address'),
shipping: storejs.get('grav-shoppingcart-shipping-method'),
payment: storejs.get('grav-shoppingcart-payment-method'),
token: storejs.get('grav-shoppingcart-order-token').token,
amount: ShoppingCart.totalOrderPrice.toString(),
gateway: ShoppingCart.gateway
};
jQuery.ajax({
url: ShoppingCart.settings.baseURL + ShoppingCart.settings.urls.saveOrderURL + '?task=preparePayment',
data: order,
type: 'POST'
})
.success(function(redirectUrl) {
ShoppingCart.clearCart();
window.location = redirectUrl;
})
.error(function() {
alert('Payment not successful. Please contact us.');
});
});
});
})();
|
(function() {
/***********************************************************/
/* Handle Proceed to Payment
/***********************************************************/
jQuery(function() {
jQuery(document).on('proceedToPayment', function(event, ShoppingCart) {
if (ShoppingCart.gateway != 'paypal_express') {
return;
}
var order = {
products: storejs.get('grav-shoppingcart-basket-data'),
address: storejs.get('grav-shoppingcart-person-address'),
shipping: storejs.get('grav-shoppingcart-shipping-method'),
payment: 'paypal',
token: storejs.get('grav-shoppingcart-order-token').token,
amount: ShoppingCart.totalOrderPrice.toString(),
gateway: ShoppingCart.gateway
};
jQuery.ajax({
url: ShoppingCart.settings.baseURL + ShoppingCart.settings.urls.saveOrderURL + '?task=preparePayment',
data: order,
type: 'POST'
})
.success(function(redirectUrl) {
ShoppingCart.clearCart();
window.location = redirectUrl;
})
.error(function() {
alert('Payment not successful. Please contact us.');
});
});
});
})();
|
Store the correct payment method
|
Store the correct payment method
|
JavaScript
|
mit
|
flaviocopes/grav-plugin-shoppingcart-paypal,flaviocopes/grav-plugin-shoppingcart-paypal
|
0888954bb9641cf7b5fe5cf4dc30d89f77f6d953
|
server/lib/load-dot-env.js
|
server/lib/load-dot-env.js
|
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = 'development';
}
if (process.env.NODE_ENV === 'development') {
const dotenv = require('dotenv');
dotenv.config(); // this loads .env with real values. It needs to be first because dotenv doesn't overwrite any values
dotenv.config({path: 'default.env'}); // this loads the default file in github with dummy values
}
|
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = 'development';
}
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'docker') {
const dotenv = require('dotenv');
dotenv.config(); // this loads .env with real values. It needs to be first because dotenv doesn't overwrite any values
dotenv.config({path: 'default.env'}); // this loads the default file in github with dummy values
}
|
Load '.env' files under docker
|
Load '.env' files under docker
|
JavaScript
|
mit
|
OpenCollective/opencollective-api,OpenCollective/opencollective-api,OpenCollective/opencollective-api
|
1c91214da859ceaa3d44d6e0be87d02a1e49a039
|
lib/index.js
|
lib/index.js
|
/*
* gulp-hub
* https://github.com/frankwallis/gulp-hub
*
* Copyright (c) 2014 Frank Wallis
* Licensed under the MIT license.
*/
var gulp = require('gulp');
var path = require('path');
var util = require('gulp-util');
var runSequence = require('run-sequence');
var resolveGlob = require('./resolve-glob');
var getSubfiles = require('./get-subfiles');
var loadSubfile = require('./load-subfile');
var addTask = require('./add-task');
var tasks = {};
function hub(pattern) {
// assert `pattern` is a valid glob (non-empty string) or array of globs
var isString = typeof pattern === 'string';
var isArray = Array.isArray(pattern);
if ((!isString && !isArray) || (pattern.length === 0)) {
throw new TypeError('A glob pattern or an array of glob patterns is required.');
}
// find all the gulpfiles - needs to happen synchronously so we create the tasks before gulp runs
var filelist = resolveGlob(pattern);
var subfiles = getSubfiles(filelist);
// load all the gulpfiles
subfiles.forEach(function (subfile) {
util.log( 'Loading', util.colors.yellow(subfile.relativePath));
loadSubfile(subfile);
});
// create the task tree
for (var name in tasks) {
if (tasks.hasOwnProperty(name)) {
addTask(tasks[name]);
}
}
}
module.exports = hub;
|
/*
* gulp-hub
* https://github.com/frankwallis/gulp-hub
*
* Copyright (c) 2014 Frank Wallis
* Licensed under the MIT license.
*/
var gulp = require('gulp');
var path = require('path');
var util = require('gulp-util');
var runSequence = require('run-sequence');
var resolveGlob = require('./resolve-glob');
var getSubfiles = require('./get-subfiles');
var loadSubfile = require('./load-subfile');
var addTask = require('./add-task');
var tasks = {};
module.exports = function(pattern) {
// assert `pattern` is a valid glob (non-empty string) or array of globs
var isString = typeof pattern === 'string';
var isArray = Array.isArray(pattern);
if ((!isString && !isArray) || (pattern.length === 0)) {
throw new TypeError('A glob pattern or an array of glob patterns is required.');
}
// find all the gulpfiles - needs to happen synchronously so we create the tasks before gulp runs
var filelist = resolveGlob(pattern);
var subfiles = getSubfiles(filelist);
// load all the gulpfiles
subfiles.forEach(function (subfile) {
util.log( 'Loading', util.colors.yellow(subfile.relativePath));
loadSubfile(subfile);
});
// create the task tree
for (var name in tasks) {
if (tasks.hasOwnProperty(name)) {
addTask(tasks[name]);
}
}
};
|
Attach main function directly to exports, linting
|
Attach main function directly to exports, linting
|
JavaScript
|
mit
|
frankwallis/gulp-hub,stevemao/gulp-hub,phated/gulp-hub
|
2ccf293d75528d21e97e22a6a7ba95d0305370bf
|
lib/index.js
|
lib/index.js
|
'use babel'
/* @flow */
import {Disposable} from 'atom'
import {Main} from './main'
import type {Provider} from './types'
module.exports = {
config: {
},
activate() {
this.instance = new Main()
},
deactivate() {
this.instance.dispose()
},
provideIntentions(): Main {
return this.instance
},
consumeProvider(provider: Provider) {
const providers = [].concat(provider)
providers.forEach(provider => {
this.instance.addProvider(provider)
})
return new Disposable(() => {
providers.forEach(provider => {
this.instance.deleteProvider(provider)
})
})
}
}
|
'use babel'
/* @flow */
import {Disposable} from 'atom'
import {Main} from './main'
import type {Provider} from './types'
module.exports = {
config: {
},
activate() {
this.instance = new Main()
},
deactivate() {
this.instance.dispose()
},
provideIntentions(): Main {
return this.instance
},
consumeProvider(provider: Provider): Disposable {
const providers = [].concat(provider)
providers.forEach(provider => {
this.instance.addProvider(provider)
})
return new Disposable(() => {
providers.forEach(provider => {
this.instance.deleteProvider(provider)
})
})
}
}
|
Add return type to consumer method
|
:art: Add return type to consumer method
|
JavaScript
|
mit
|
steelbrain/declarations
|
fe751015ca6bdeec416c266868c43f67a3ca19f7
|
lib/local.js
|
lib/local.js
|
"use strict";
var fakeNullFiber = Object.create(null);
var localKey = "_optimism_local";
function getCurrentFiber() {
return fakeNullFiber;
}
try {
var fiberPath = require.resolve("fibers");
} catch (e) {}
if (fiberPath) {
var Fiber = require(fiberPath);
// If we were able to require("fibers"), redefine the getCurrentFiber
// function so that it has a chance to return Fiber.current.
getCurrentFiber = function () {
return Fiber.current || fakeNullFiber;
};
}
// Returns an object unique to Fiber.current, if fibers are enabled.
// This object is used for Fiber-local storage in ./entry.js.
exports.get = function () {
var fiber = getCurrentFiber();
return fiber[localKey] || (fiber[localKey] = Object.create(null));
};
|
"use strict";
var fakeNullFiber = function Fiber(){};
var localKey = "_optimism_local";
function getCurrentFiber() {
return fakeNullFiber;
}
try {
var fiberPath = require.resolve("fibers");
} catch (e) {}
if (fiberPath) {
var Fiber = require(fiberPath);
// If we were able to require("fibers"), redefine the getCurrentFiber
// function so that it has a chance to return Fiber.current.
getCurrentFiber = function () {
return Fiber.current || fakeNullFiber;
};
}
// Returns an object unique to Fiber.current, if fibers are enabled.
// This object is used for Fiber-local storage in ./entry.js.
exports.get = function () {
var fiber = getCurrentFiber();
return fiber[localKey] || (fiber[localKey] = Object.create(null));
};
|
Make fakeNullFiber look a little less fake.
|
Make fakeNullFiber look a little less fake.
|
JavaScript
|
mit
|
benjamn/optimism,benjamn/optimism
|
bb7162a886b4ed17caab08228e504cf09fdb5da2
|
src/js/index.js
|
src/js/index.js
|
require('../css/main.scss');
import grindy from "./grindy.js"
(function() {
let game = grindy();
game.start();
})()
|
import '../css/main.scss'
import 'file?name=[name].html!../index.html'
import Grindy from './grindy.js'
(function() {
let game = grindy();
game.start();
})()
|
Use of already installed file-loader :) ... we can use import also for "special webpack imports"
|
Use of already installed file-loader :)
... we can use import also for "special webpack imports"
|
JavaScript
|
mit
|
Vorgnr/Grindy,Vorgnr/Grindy
|
f4dd36946e54b9ba6d037275b4dd184621729de8
|
test/test-harness-test.js
|
test/test-harness-test.js
|
describe('test-harness', function() {
describe('globals', function() {
it('should expose should as a global', function() {
should.exist(should);
});
it('should expose sinon as a global', function() {
should.exist(sinon);
});
});
describe('should-sinon plugin', function() {
it('should use the should-sinon plugin', function() {
const test_stub = sinon.stub().returns('hello');
test_stub().should.eql('hello');
test_stub.should.have.callCount(1);
});
});
describe('should-promised plugin', function() {
it('should use the should-promised plugin', function() {
return Promise.resolve().should.be.fulfilled();
});
});
describe('should-http plugin', function() {
it('should use the should-http plugin', function() {
({ statusCode: 200 }).should.have.status(200);
});
});
});
|
describe('test/test-harness-test.js', function() {
describe('globals', function() {
it('should expose should as a global', function() {
should.exist(should);
});
it('should expose sinon as a global', function() {
should.exist(sinon);
});
});
describe('should-sinon plugin', function() {
it('should use the should-sinon plugin', function() {
const test_stub = sinon.stub().returns('hello');
test_stub().should.eql('hello');
test_stub.should.have.callCount(1);
});
});
describe('should-promised plugin', function() {
it('should use the should-promised plugin', function() {
return Promise.resolve().should.be.fulfilled();
});
});
describe('should-http plugin', function() {
it('should use the should-http plugin', function() {
({ statusCode: 200 }).should.have.status(200);
});
});
});
|
Fix linter issue with test describe path
|
Fix linter issue with test describe path
|
JavaScript
|
mit
|
Springworks/node-test-harness
|
d664f7aff910b8ccf46f45f341a0776d4498124b
|
electron/menus/win-linux.js
|
electron/menus/win-linux.js
|
export const winLinuxMenu = (app, window, openAbout) => (
[{
label: 'Daedalus',
submenu: [{
label: 'About',
click() {
openAbout();
}
}, {
label: 'Close',
accelerator: 'Ctrl+W',
click() {
app.quit();
}
}]
}, {
label: 'Edit',
submenu: [{
label: 'Undo',
accelerator: 'Ctrl+Z',
role: 'undo'
}, {
label: 'Redo',
accelerator: 'Shift+Ctrl+Z',
role: 'redo'
}, {
type: 'separator'
}, {
label: 'Cut',
accelerator: 'Ctrl+X',
role: 'cut'
}, {
label: 'Copy',
accelerator: 'Ctrl+C',
role: 'copy'
}, {
label: 'Paste',
accelerator: 'Ctrl+V',
role: 'paste'
}, {
label: 'Select All',
accelerator: 'Ctrl+A',
role: 'selectall'
}]
}, {
label: 'View',
submenu: [
{
label: 'Reload',
accelerator: 'Ctrl+R',
click() { window.webContents.reload(); }
},
{
label: 'Toggle Full Screen',
accelerator: 'F11',
click() { window.setFullScreen(!window.isFullScreen()); }
},
{
label: 'Toggle Developer Tools',
accelerator: 'Alt+Ctrl+I',
click() { window.toggleDevTools(); }
}
]
}]
);
|
export default (app, window, openAbout) => (
[{
label: 'Daedalus',
submenu: [{
label: 'About',
click() {
openAbout();
}
}, {
label: 'Close',
accelerator: 'Ctrl+W',
click() {
app.quit();
}
}]
}, {
label: 'Edit',
submenu: [{
label: 'Undo',
accelerator: 'Ctrl+Z',
role: 'undo'
}, {
label: 'Redo',
accelerator: 'Shift+Ctrl+Z',
role: 'redo'
}, {
type: 'separator'
}, {
label: 'Cut',
accelerator: 'Ctrl+X',
role: 'cut'
}, {
label: 'Copy',
accelerator: 'Ctrl+C',
role: 'copy'
}, {
label: 'Paste',
accelerator: 'Ctrl+V',
role: 'paste'
}, {
label: 'Select All',
accelerator: 'Ctrl+A',
role: 'selectall'
}]
}, {
label: 'View',
submenu: [
{
label: 'Reload',
accelerator: 'Ctrl+R',
click() { window.webContents.reload(); }
},
{
label: 'Toggle Full Screen',
accelerator: 'F11',
click() { window.setFullScreen(!window.isFullScreen()); }
},
{
label: 'Toggle Developer Tools',
accelerator: 'Alt+Ctrl+I',
click() { window.toggleDevTools(); }
}
]
}]
);
|
Fix missing application menu on Windows build
|
[DDW-212] Fix missing application menu on Windows build
|
JavaScript
|
apache-2.0
|
input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus,input-output-hk/daedalus
|
7e6c11f37053a33e0ad4b6ee90b6b2b4317960a7
|
src/components/floating-button/FloatingButtonItemLabel.js
|
src/components/floating-button/FloatingButtonItemLabel.js
|
'use strict'
import React, { Component } from 'react'
import ReactCSS from 'reactcss'
import colors from '../../styles/variables/colors'
import { spacing, sizing } from '../../styles/variables/utils'
class FloatingButtonItemLabel extends Component {
classes() {
return {
'default': {
wrap: {
display: 'flex',
alignItems: 'center',
position: 'absolute',
top: '0',
bottom: '0',
right: '0'
},
label: {
backgroundColor: 'rgba(255,255,255,0.59)',
borderRadius: '3px',
padding: '3px',
color: colors.bgDark,
whiteSpace: 'nowrap',
fontSize: '14px',
},
},
}
}
render() {
return (
<div is="wrap">
<span is="label">{ this.props.label }</span>
</div>
)
}
}
export default ReactCSS(FloatingButtonItemLabel)
|
'use strict'
import React, { Component } from 'react'
import ReactCSS from 'reactcss'
import colors from '../../styles/variables/colors'
import { spacing, sizing } from '../../styles/variables/utils'
class FloatingButtonItemLabel extends Component {
classes() {
return {
'default': {
wrap: {
display: 'flex',
alignItems: 'center',
position: 'absolute',
top: '0',
bottom: '0',
right: '0'
},
label: {
backgroundColor: 'rgba(255,255,255,0.4)',
borderRadius: '3px',
padding: '4px',
color: colors.bgDark,
whiteSpace: 'nowrap',
fontSize: '14px',
boxShadow: `0px 1px 0px 0px ${colors.bgDark}`,
transition: `background-color 0.2s ease-in-out`,
},
},
hover: {
label: {
backgroundColor: 'rgba(255,255,255,0.7)',
},
},
}
}
render() {
return (
<div is="wrap">
<span is="label">{ this.props.label }</span>
</div>
)
}
}
export default ReactCSS(FloatingButtonItemLabel)
|
Improve floating button item label styles
|
Improve floating button item label styles
|
JavaScript
|
mit
|
tobycyanide/felony,henryboldi/felony,henryboldi/felony,tobycyanide/felony
|
eec077fa040d29767acae307ae74e97c8d511fba
|
src/containers/shared-assets/form-assets/form-tooltips.js
|
src/containers/shared-assets/form-assets/form-tooltips.js
|
import React from 'react';
const requirementsObj = {
list_symbol: "◇",
username: ["start with letter", "be between 3-10 characters", "contain only [a-zA-Z] characters"],
['e-mail']: ["look like: example@example.com"],
['confirm_e-mail']: ["be the same as e-mail address written above"],
password: ["be K"]
};
const FormTooltips = (props) => {
function requirement(id){
return (
requirementsObj[id].map((r, i)=>
<li key={i}>
<i>{requirementsObj.list_symbol}</i>
<p>{r}</p>
</li>
)
);
}
function requirements(id){
return (
<ul className="input-tooltip-list"><i className="input-tooltip-header">{id}</i> should:
{requirement(id)}
</ul>
)
}
function tooltip(id){
switch(id){
case 'username': return requirements('username');
case 'e-mail': return requirements('e-mail');
case 'confirm_e-mail': return requirements('confirm_e-mail');
case 'password': return requirements('password');
case 'confirm_password': return "";
case 'secret': return "Secret answer should";
}
}
return (
<div className={`input-tooltip ${props.tooltip === true ? "active" : "display-none"}`}>
<span className="input-tooltip-caret-left"></span>
{tooltip(props.id)}
</div>
)
};
export default FormTooltips;
|
import React from 'react';
const requirementsObj = {
list_symbol: "◇",
username: ["start with letter", "be between 3-10 characters", "contain only [a-zA-Z] characters"],
['e-mail']: ["look like: example@example.com"],
['confirm_e-mail']: ["be the same as e-mail address written above"],
password: ["be K"],
confirm_password: ["be the same as password written above"],
secret: ['be x']
};
const FormTooltips = (props) => {
function requirement(id){
return (
requirementsObj[id].map((r, i)=>
<li key={i}>
<i>{requirementsObj.list_symbol}</i>
<p>{r}</p>
</li>
)
);
}
function requirements(id){
return (
<ul className="input-tooltip-list"><i className="input-tooltip-header">{id}</i> should:
{requirement(id)}
</ul>
)
}
function tooltip(id){
switch(id){
case id: return requirements(id);
}
}
return (
<div className={`input-tooltip ${props.tooltip === true ? "active" : "display-none"}`}>
<span className="input-tooltip-caret-left"></span>
{tooltip(props.id)}
</div>
)
};
export default FormTooltips;
|
Change switch statement to dynamic
|
Change switch statement to dynamic
|
JavaScript
|
bsd-3-clause
|
vFujin/HearthLounge,vFujin/HearthLounge
|
f017a1d21145668d0182339bb195e98e2da21992
|
server/recalls.controller.js
|
server/recalls.controller.js
|
'use strict';
var _ = require('lodash'),
Promise = require('bluebird');
module.exports = ['data', function (data) {
var filters = function (query) {
var where = data.utils.rangeFilter('Year', query.start, query.end);
return _.assign(where, data.utils.inFilter('Make', query.makes));
};
return {
'/': {
get: function (req) {
return new Promise(function (resolve, reject) {
var op = data.utils.operation(req.query),
pagination = data.utils.pagination(req.query);
switch (op) {
case 'count':
data.Recall.count(filters(req.query)).exec(function (err, count) {
if (err) {
reject(err);
return;
}
resolve([200, undefined, { count: count }]);
});
break;
default:
var query = data.Recall.find(filters(req.query));
if (pagination) {
query.skip(pagination.from).limit(pagination.limit);
}
query.exec(function (err, recalls) {
if (err) {
reject(err);
return;
}
resolve([200, undefined, recalls]);
});
break;
}
});
}
}
};
}];
|
'use strict';
var _ = require('lodash'),
Promise = require('bluebird');
module.exports = ['data', function (data) {
var filters = function (query) {
var where = data.utils.rangeFilter('Year', query.start, query.end);
return _.assign(where, data.utils.inFilter('Make', query.makes));
};
return {
'/:operation?': {
get: function (req) {
return new Promise(function (resolve, reject) {
var op = data.utils.operation(req.params),
pagination = data.utils.pagination(req.query);
switch (op) {
case 'count':
data.Recall.count(filters(req.query)).exec(function (err, count) {
if (err) {
reject(err);
return;
}
resolve([200, undefined, { count: count }]);
});
break;
default:
var query = data.Recall.find(filters(req.query));
if (pagination) {
query.skip(pagination.from).limit(pagination.limit);
}
query.exec(function (err, recalls) {
if (err) {
reject(err);
return;
}
resolve([200, undefined, recalls]);
});
break;
}
});
}
}
};
}];
|
Add operation parameter to recalls route
|
Add operation parameter to recalls route
Instead of having the operation parameter in the query string it
optimizes for Restangular to have it as an action on the route.
|
JavaScript
|
mit
|
justinsa/maine-coone,justinsa/maine-coone
|
29548e72dced63c277f16a33a5a4e44be668473b
|
shared/util/feature-flags.js
|
shared/util/feature-flags.js
|
/* @flow */
import getenv from 'getenv'
// To enable a feature, include it in the environment variable KEYBASE_FEATURES.
// For example, KEYBASE_FEATURES=tracker2,login,awesomefeature
const tracker2Key = 'tracker2'
const loginKey = 'login'
const mobileAppsExistKey = 'mobileAppsExist'
type FeatureFlags = {
'tracker2': boolean,
'login': boolean,
'mobileAppsExist': boolean
}
let features = getenv.array('KEYBASE_FEATURES', 'string', '')
const tracker2 = features.includes(tracker2Key)
const login = features.includes(loginKey)
const mobileAppsExist = features.includes(mobileAppsExistKey)
const ff: FeatureFlags = {
tracker2,
login,
mobileAppsExist
}
if (__DEV__) {
console.log('Features', ff)
}
export default ff
export {
tracker2,
login,
mobileAppsExist
}
|
/* @flow */
import getenv from 'getenv'
// To enable a feature, include it in the environment variable KEYBASE_FEATURES.
// For example, KEYBASE_FEATURES=tracker2,login,awesomefeature
const tracker2Key = 'tracker2'
const loginKey = 'login'
const mobileAppsExistKey = 'mobileAppsExist'
const adminKey = 'admin'
type FeatureFlags = {
'tracker2': boolean,
'login': boolean,
'mobileAppsExist': boolean,
'admin': boolean
}
let features = getenv.array('KEYBASE_FEATURES', 'string', '')
const tracker2 = features.includes(tracker2Key) || features.includes(adminKey)
const login = features.includes(loginKey)
const mobileAppsExist = features.includes(mobileAppsExistKey)
const admin = features.include(adminKey)
const ff: FeatureFlags = {
tracker2,
login,
mobileAppsExist,
admin
}
if (__DEV__) {
console.log('Features', ff)
}
export default ff
export {
tracker2,
login,
mobileAppsExist,
admin
}
|
Add adminKey, will be for early access to dz2
|
Add adminKey, will be for early access to dz2
Can be turned on with `launchctl setenv KEYBASE_FEATURES admin`
|
JavaScript
|
bsd-3-clause
|
keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client
|
0f775d0cea33f6525b3875db69f8830859c83b8d
|
tests/unit/looper-test.js
|
tests/unit/looper-test.js
|
import Ember from 'ember';
import { csp, channel, looper } from 'ember-processes';
module('Unit: Loopers');
test('loopers take a channel name', function(assert) {
QUnit.stop();
assert.expect(3);
let outch = csp.chan();
let MyObject = Ember.Object.extend({
myChannel: channel(),
doStuff: looper('myChannel', function * (value) {
yield csp.putAsync(outch, value);
}),
});
let obj;
Ember.run(() => {
obj = MyObject.create();
let chan = obj.get('myChannel');
csp.putAsync(chan, 1);
csp.putAsync(chan, 2);
csp.putAsync(chan, 3);
});
csp.go(function * () {
assert.equal(yield outch, 1);
assert.equal(yield outch, 2);
assert.equal(yield outch, 3);
QUnit.start();
});
Ember.run(obj, 'destroy');
});
|
import Ember from 'ember';
import { csp, channel, looper } from 'ember-processes';
module('Unit: Loopers');
function testLooper(testName, makeHandler) {
test('loopers take a channel name (' + testName + ')', function(assert) {
QUnit.stop();
assert.expect(3);
let outch = csp.chan();
let MyObject = Ember.Object.extend({
myChannel: channel(),
doStuff: looper('myChannel', makeHandler(outch)),
});
let obj;
Ember.run(() => {
obj = MyObject.create();
let chan = obj.get('myChannel');
csp.putAsync(chan, 1);
csp.putAsync(chan, 2);
csp.putAsync(chan, 3);
});
csp.go(function * () {
assert.equal(yield outch, 1);
assert.equal(yield outch, 2);
assert.equal(yield outch, 3);
QUnit.start();
});
Ember.run(obj, 'destroy');
});
}
testLooper("generator", function(outch) {
return function * (value) {
yield csp.put(outch, value);
};
});
testLooper("regular function", function(outch) {
return function(value) {
csp.putAsync(outch, value);
};
});
|
Add test for regular function loopers
|
Add test for regular function loopers
|
JavaScript
|
mit
|
machty/ember-concurrency,jeradg/ember-concurrency,jeradg/ember-concurrency,machty/ember-concurrency,jeradg/ember-concurrency,machty/ember-concurrency,machty/ember-concurrency,jeradg/ember-concurrency
|
d3e18b83b2093637adfce4ccaa8c1cec4aee7e2c
|
public/app/services/toasterutils.service.js
|
public/app/services/toasterutils.service.js
|
(function () {
'use strict';
angular
.module('PLMApp')
.factory('toasterUtils', toasterUtils);
toasterUtils.$inject = ['toaster', '$timeout'];
function toasterUtils(toaster, $timeout) {
var service = {
info: info,
success: success,
warning: warning,
error: error
};
return service;
function info(message) {
$timeout(function () {
toaster.pop('info', '', message);
}, 0);
}
function success(title, message) {
$timeout(function () {
toaster.pop('success', title, message);
}, 0);
}
function warning(title, message) {
$timeout(function () {
toaster.pop('warning', title, message);
}, 0);
}
function error(title, message) {
$timeout(function () {
toaster.pop('error', title, message, -1);
}, 0);
}
}
})();
|
(function () {
'use strict';
angular
.module('PLMApp')
.factory('toasterUtils', toasterUtils);
toasterUtils.$inject = ['toaster', '$timeout'];
function toasterUtils(toaster, $timeout) {
var service = {
info: info,
success: success,
warning: warning,
error: error
};
return service;
function pop(type, title, message, duration) {
$timeout(function () {
toaster.pop(type, title, message, duration);
}, 0);
}
function info(message, optDuration) {
var duration = optDuration || 1500;
pop('info', '', message, duration);
}
function success(title, message, optDuration) {
var duration = optDuration || 1500;
pop('success', title, message, duration);
}
function warning(title, message, optDuration) {
var duration = optDuration || 3000;
pop('warning', title, message, duration);
}
function error(title, message, optDuration) {
var duration = optDuration || -1;
pop('error', title, message, duration);
}
}
})();
|
Add parameter setting toaster's duration
|
Add parameter setting toaster's duration
|
JavaScript
|
agpl-3.0
|
BuggleInc/webPLM,BuggleInc/webPLM,polux/webPLM,MatthieuNICOLAS/webPLM,BuggleInc/webPLM,polux/webPLM,MatthieuNICOLAS/webPLM,BuggleInc/webPLM,polux/webPLM,polux/webPLM,MatthieuNICOLAS/webPLM,BuggleInc/webPLM,MatthieuNICOLAS/webPLM,polux/webPLM
|
5b630ad5fe4719659bdc8fe4276f4fb013336cad
|
src/registry.js
|
src/registry.js
|
'use strict'
/**
* @module registry
*/
module.exports.isListed = isListed
module.exports.isUnlisted = isUnlisted
var vocab = require('solid-namespace')
/**
* Returns true if the parsed graph is a `solid:UnlistedDocument` document.
* @method isUnlisted
* @param graph {Graph} Parsed graph (loaded from a registry-like resource)
* @return {Boolean}
*/
function isUnlisted (graph, rdf) {
var ns = vocab(rdf)
return graph.any(null, null, ns.solid('UnlistedDocument'), graph.uri)
}
/**
* Returns true if the parsed graph is a `solid:ListedDocument` document.
* @method isListed
* @param graph {Graph} Parsed graph (loaded from a registry-like resource)
* @return {Boolean}
*/
function isListed (graph, rdf) {
var ns = vocab(rdf)
return graph.any(null, null, ns.solid('ListedDocument'), graph.uri)
}
|
'use strict'
/**
* @module registry
*/
module.exports.isListed = isListed
module.exports.isUnlisted = isUnlisted
var vocab = require('solid-namespace')
/**
* Returns true if the parsed graph is a `solid:UnlistedDocument` document.
* @method isUnlisted
* @param graph {Graph} Parsed graph (loaded from a registry-like resource)
* @return {Boolean}
*/
function isUnlisted (graph, rdf) {
var ns = vocab(rdf)
return graph.any(graph.uri, ns.rdf('type'), ns.solid('UnlistedDocument'), graph.uri)
}
/**
* Returns true if the parsed graph is a `solid:ListedDocument` document.
* @method isListed
* @param graph {Graph} Parsed graph (loaded from a registry-like resource)
* @return {Boolean}
*/
function isListed (graph, rdf) {
var ns = vocab(rdf)
return graph.any(graph.uri, ns.rdf('type'), ns.solid('ListedDocument'), graph.uri)
}
|
Make isListed / isUnlisted query more specific
|
Make isListed / isUnlisted query more specific
Address issue #141.
|
JavaScript
|
mit
|
solid/solid-client,solid/solid-client,solid/solid.js,solid/solid-client,solid/solid.js,solid/solid.js
|
10cc6b06dedfd1a90bc45d1eb5d2f469b876e70b
|
config/env/all.js
|
config/env/all.js
|
// default app configuration
var defaultConfig = {
port: process.env.PORT || 4000,
db: "mongodb://nodegoat:owasp@widmore.mongohq.com:10000/nodegoat",
cookieSecret: "session_cookie_secret_key_here",
cryptoKey: "a_secure_key_for_crypto_here",
cryptoAlgo: "aes256"
};
module.exports = defaultConfig;
|
// default app configuration
var defaultConfig = {
port: process.env.PORT || 4000,
db: process.env.MONGODB_URL || "mongodb://nodegoat:owasp@widmore.mongohq.com:10000/nodegoat",
cookieSecret: "session_cookie_secret_key_here",
cryptoKey: "a_secure_key_for_crypto_here",
cryptoAlgo: "aes256"
};
module.exports = defaultConfig;
|
Use MONGODB_URL from env variable if provided
|
Use MONGODB_URL from env variable if provided
|
JavaScript
|
apache-2.0
|
codiscope/NodeGoatExample,panstav/NodeGoat,samheadrick/NodeGoat,diegochavezcarro/nodegoatsecure,zkovalenko/NodeGoatTEST,nearform/NodeGoat,bertonjulian/NodeGoat,OWASP/NodeGoat,abaldock/cs132_security_lab_group_24,zkovalenko/NodeGoatTEST,isp1r0/NodeGoat,GMNetto/NodeSecurity,OWASP/NodeGoat,syzer/NodeGoat,GMNetto/NodeSecurity,zkovalenko2/NodeGoatTEST,ckarande/NodeGoat,panstav/NodeGoat,samheadrick/NodeGoat,Yas3r/NodeGoat,isp1r0/NodeGoat,hongjunChoi/cs132_security_lab,Yas3r/NodeGoat,hongjunChoi/cs132_security_lab,ckarande/NodeGoat,diegochavezcarro/nodegoatsecure,abaldock/cs132_security_lab_group_24,zkovalenko2/NodeGoatTEST,syzer/NodeGoat,codiscope/NodeGoatExample
|
b82572880ad9c3a5960ba56b2603006546d29aa7
|
src/client/react/admin/AdminNavbar/MainNavigation.js
|
src/client/react/admin/AdminNavbar/MainNavigation.js
|
import React from 'react';
import { Link } from 'react-router-dom';
const linkStyle = 'pt-button pt-minimal';
class MainNavigation extends React.Component {
render() {
return (
<div>
<a className={linkStyle + ' pt-icon pt-icon-key-escape'} href='/'>Visit site</a>
</div>
);
}
}
export default MainNavigation;
|
import React from 'react';
import { Link } from 'react-router-dom';
const linkStyle = 'pt-button pt-minimal';
class MainNavigation extends React.Component {
render() {
return (
<div>
<a className={linkStyle + ' pt-icon pt-icon-key-escape'} href='/' target='_blank'>Visit site</a>
</div>
);
}
}
export default MainNavigation;
|
Make Visit Site link in the navbar open a new window
|
[FIX] Make Visit Site link in the navbar open a new window
|
JavaScript
|
mit
|
bwyap/ptc-amazing-g-race,bwyap/ptc-amazing-g-race
|
d2482daf863450d2ae2470ceba86b341574d7ba8
|
examples/simple-done-app.js
|
examples/simple-done-app.js
|
// Simple "Done" application
let doneItems = []
let text
function input(event) {
text = event.target.value
}
function done(event) {
doneItems.push(text)
Twirlip7.WorkspaceView.toast("did " + text)
text = ""
}
Twirlip7.show(() => {
return m("div", [
doneItems.map(item => m("div", item)),
"Did:",
m("input.ma2", { value: text, oninput: input }),
m("button.ma2", { onclick: done }, "Done!")
])
}, ".bg-blue.br4")
|
// Simple "Done" application
let doneItems = []
let text
function input(event) {
text = event.target.value
}
function done(event) {
doneItems.push(text)
// Toast will not show up running standalone as it depends on the editor
Twirlip7.WorkspaceView.toast("did " + text)
text = ""
}
Twirlip7.show(() => {
return m("div", [
doneItems.map(item => m("div", item)),
"Did:",
m("input.ma2", { value: text, oninput: input }),
m("button.ma2", { onclick: done }, "Done!")
])
}, ".bg-blue.br4")
|
Add comment to simple done app example about toast
|
Add comment to simple done app example about toast
|
JavaScript
|
mit
|
pdfernhout/Twirlip7,pdfernhout/Twirlip7,pdfernhout/Twirlip7
|
2ffec5ba86e05618c2ea809aa24f28386bce4c8f
|
src/data/examples/zh-Hans/05_Image/10_Copy_Method.js
|
src/data/examples/zh-Hans/05_Image/10_Copy_Method.js
|
/*
* @name Copy() method
* @frame 600,400
* @description 一个如何使用copy()方法模拟为图像着色的示例。
*/
let draft, ready;
function preload() {
ready = loadImage("assets/parrot-color.png");
draft = loadImage("assets/parrot-bw.png");
}
function setup() {
createCanvas(600, 400);
noCursor();
cursor("assets/brush.png", 20, -10);
image(ready, 0, 0);
image(draft, 0, 0);
}
function mouseDragged() {
copy(ready, mouseX, mouseY, 20, 20, mouseX, mouseY, 20, 20);
}
|
/*
* @name Copy() 函数
* @frame 600,400
* @description 一个如何使用 copy() 函数模拟为图像着色的范例。
*/
let draft, ready;
function preload() {
ready = loadImage("assets/parrot-color.png");
draft = loadImage("assets/parrot-bw.png");
}
function setup() {
createCanvas(600, 400);
noCursor();
cursor("assets/brush.png", 20, -10);
image(ready, 0, 0);
image(draft, 0, 0);
}
function mouseDragged() {
copy(ready, mouseX, mouseY, 20, 20, mouseX, mouseY, 20, 20);
}
|
Edit Chinese translation of example
|
Edit Chinese translation of example
|
JavaScript
|
mit
|
processing/p5.js-website,processing/p5.js-website
|
3b02bcafaec47660344803f66baff351b44f2619
|
server/routes/recipes/index.js
|
server/routes/recipes/index.js
|
import express from 'express';
import * as userController from '../../controllers/recipes.js';
const user = express.Router();
// define route controllers for creating sign up, login and sign out
user.post('/', userController.addRecipe);
export default user;
|
import express from 'express';
import * as userController from '../../controllers/recipes.js';
const user = express.Router();
user.use('*', (req, res, next) => {
// check for authentication here
if (!req.session.user) {
return res.status(401).send({
error: 'You do not have the permission to perform this action!' });
}
next();
});
// define route controllers for adding recipe
user.post('/', userController.addRecipe);
export default user;
|
Add user authentication to route
|
Add user authentication to route
|
JavaScript
|
apache-2.0
|
larrystone/BC-26-More-Recipes,larrystone/BC-26-More-Recipes
|
2b1f5c27fd8cfbc06c23a76b5942bec589e553c8
|
stryker.conf.js
|
stryker.conf.js
|
module.exports = function(config) {
config.set({
coverageAnalysis: 'off',
logLevel: 'info',
mutate: [
'src/**/*.ts?',
'!src/**/__tests__/*.ts?'
],
mutator: 'typescript',
reporter: ['html', 'clear-text', 'progress', 'dashboard'],
testRunner: 'jest',
transpilers: ['typescript'],
tsconfigFile: 'tsconfig.json',
});
};
|
module.exports = function(config) {
config.set({
coverageAnalysis: 'off',
files: [
{ pattern: 'node_modules/react-scripts-ts/**/*.js' },
{ pattern: 'node_modules/ts-jest/**/*.js' },
],
logLevel: 'info',
mutate: [
'src/**/*.ts?',
'!src/**/__tests__/*.ts?'
],
mutator: 'typescript',
reporter: ['html', 'clear-text', 'progress', 'dashboard'],
testRunner: 'jest',
transpilers: ['typescript'],
tsconfigFile: 'tsconfig.json',
});
};
|
Add some files that are needed for mutation testing
|
Add some files that are needed for mutation testing
|
JavaScript
|
mit
|
mthmulders/hyperion-web,mthmulders/hyperion-web,mthmulders/hyperion-web
|
47ea8fb0e20024d9a5531ec2addc3d459e535a09
|
js/events.js
|
js/events.js
|
function Events()
{
var listeners = {}
$.extend(this, {
on: function(type, cb)
{
if (!$.isArray(listeners[type]))
listeners[type] = []
if (listeners[type].indexOf(cb) < 0)
listeners[type].push(cb)
},
once: function(type, cb)
{
this.on(type, function observer()
{
this.off(type, observer)
cb.apply(this, arguments)
})
},
emit: function(type)
{
var result = []
if (!$.isArray(listeners[type]))
listeners[type] = []
var args = Array.prototype.slice.call(arguments, 1)
var cbs = listeners[type].slice()
while (cbs.length > 0)
{
result.push(cbs.shift().apply(this, args))
}
return result
},
call: function(type)
{
var result = this.emit.apply(this, arguments)
if (result.length > 1)
warn("Too many results, choosing the first one")
return result[0]
},
off: function(type, cb)
{
if (cb == undefined)
throw new Error("You cannot remove all listeners on an event")
if (!$.isFunction(cb))
throw new Error("You must pass a listener to Event.off")
var index = listeners[type].indexOf(cb)
if (index != undefined && index >= 0)
{
listeners[type].splice(index, 1);
}
},
})
}
|
function Events()
{
var listeners = {}
$.extend(this, {
on: function(type, cb)
{
if (!$.isArray(listeners[type]))
listeners[type] = []
if (listeners[type].indexOf(cb) < 0)
listeners[type].push(cb)
return this;
},
once: function(type, cb)
{
this.on(type, function observer()
{
this.off(type, observer)
cb.apply(this, arguments)
})
return this;
},
emit: function(type)
{
var result = []
if (!$.isArray(listeners[type]))
listeners[type] = []
var args = Array.prototype.slice.call(arguments, 1)
var cbs = listeners[type].slice()
while (cbs.length > 0)
{
result.push(cbs.shift().apply(this, args))
}
return result
},
call: function(type)
{
var result = this.emit.apply(this, arguments)
if (result.length > 1)
warn("Too many results, choosing the first one")
return result[0]
},
off: function(type, cb)
{
if (cb == undefined)
throw new Error("You cannot remove all listeners on an event")
if (!$.isFunction(cb))
throw new Error("You must pass a listener to Event.off")
var index = listeners[type].indexOf(cb)
if (index != undefined && index >= 0)
{
listeners[type].splice(index, 1);
}
return this;
},
})
}
|
Return the event object when you call on, once or off
|
Return the event object when you call on, once or off
|
JavaScript
|
artistic-2.0
|
atrodo/fission_engine,atrodo/fission_engine
|
83f708e666d6186b681195a674d8b90a39e60a21
|
jQuery.animateOnce.js
|
jQuery.animateOnce.js
|
/**
* Utility function for triggering animate.css animations
*/
$.fn.animateOnce = function( className ) {
var animEndEvent = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend',
animClass = 'animated ' + className;
this
.addClass( animClass )
.off( animEndEvent )
.one( animEndEvent, function() {
$( this ).removeClass( animClass );
});
return this;
};
|
/* global jQuery */
/**
* Utility function for triggering animate.css animations
*/
(function ( $ ) {
'use strict';
$.fn.animateOnce = function( className, cb ) {
var animEndEvent = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend',
animClass = 'animated ' + className,
callback = cb || function(){};
this
.addClass( animClass )
.off( animEndEvent )
.one( animEndEvent, function() {
$( this ).removeClass( animClass );
callback.call( this );
});
return this;
};
})( jQuery );
|
Add callback function. Use Strict. noConflict support
|
Add callback function.
Use Strict.
noConflict support
|
JavaScript
|
mit
|
NicolajKN/jQuery.animateOnce
|
793d224e509715f48e576717a249672bd81f46dc
|
scripts/create_sequence.js
|
scripts/create_sequence.js
|
db.counters.insert(
{
_id: "cemetery",
seq: 0,
}
)
db.counters.insert(
{
_id: "geolocation",
seq: 0,
}
)
db.counters.insert(
{
_id: "marker",
seq: 0,
}
)
db.counters.insert(
{
_id: "person",
seq: 0,
}
)
db.counters.insert(
{
_id: "reading",
seq: 0,
}
)
|
// Create (or recreate) ID counters for our various entities
db.counters.insert(
{
_id: "cemetery",
seq: 0,
}
)
db.counters.insert(
{
_id: "geolocation",
seq: 0,
}
)
db.counters.insert(
{
_id: "marker",
seq: 0,
}
)
db.counters.insert(
{
_id: "person",
seq: 0,
}
)
db.counters.insert(
{
_id: "reading",
seq: 0,
}
)
|
Create or recreate sequence counters for Monogo database objects
|
Create or recreate sequence counters for Monogo database objects
|
JavaScript
|
mit
|
sjccs/cemetery-reader
|
bd8e7a0f7330cc4ba0f1728ee60db76a37ef76d0
|
app/assets/javascripts/application.js
|
app/assets/javascripts/application.js
|
//= require modernizr-2.8.3.custom
//= require turbolinks
//= require local_time
//= require init
//= require pages
document.addEventListener("turbolinks:load", atthemovies.init());
if (document.readyState != 'loading') {
atthemovies.init();
} else {
document.addEventListener('DOMContentLoaded', atthemovies.init());
}
|
//= require modernizr-2.8.3.custom
//= require turbolinks
//= require local_time
//= require init
//= require pages
document.addEventListener("turbolinks:load", function() {
atthemovies.init();
});
if (document.readyState != 'loading') {
atthemovies.init();
} else {
document.addEventListener('DOMContentLoaded', atthemovies.init());
}
|
Fix double JS on first page load
|
Fix double JS on first page load
|
JavaScript
|
agpl-3.0
|
andycroll/atthemovies,andycroll/atthemovies,andycroll/atthemovies,andycroll/atthemovies
|
bd25f30c0bed4a02a165f6741e338f552af23cb0
|
js/router.js
|
js/router.js
|
define(['jquery', 'underscore', 'backbone', 'views'],
function($ , _ , Backbone , View ) {
var AppRouter = Backbone.Router.extend({
routes: {
'': 'showHome',
'about': 'showAbout',
'projects': 'showProjects',
'resume': 'showResume',
':string': 'showError'
},
showHome: function() {
var homeView = new View['home'];
homeView.render();
},
showAbout: function() {
var aboutView = new View['about'];
aboutView.render();
},
showProjects: function() {
var projectsView = new View['projects'];
projectsView.render();
},
showResume: function() {
var resumeView = new View['resume'];
resumeView.render();
},
showError: function(string) {
var errorView = new View['error'];
errorView.render();
}
});
function initialize() {
var appRouter = new AppRouter;
Backbone.history.start({ pushstate: true });
$('#toggle-menu').click(function() {
$('.navbar-content').toggleClass('expanded');
});
$(document).on('click', 'a', function(evt) {
if (this.host == location.host) {
evt.preventDefault();
var href = $(this).attr('href');
$('.navbar-content').removeClass('animate expanded');
Backbone.history.navigate(href, true);
_.delay(function() {
$('.navbar-content').addClass('animate');
}, 50);
}
});
return appRouter;
}
return {
initialize: initialize
};
});
|
define(['jquery', 'underscore', 'backbone', 'views'],
function($ , _ , Backbone , View ) {
var AppRouter = Backbone.Router.extend({
routes: {
'': 'showHome',
'about': 'showAbout',
'projects': 'showProjects',
'resume': 'showResume',
':string': 'showError'
},
showHome: function() {
var homeView = new View['home'];
homeView.render();
},
showAbout: function() {
var aboutView = new View['about'];
aboutView.render();
},
showProjects: function() {
var projectsView = new View['projects'];
projectsView.render();
},
showResume: function() {
var resumeView = new View['resume'];
resumeView.render();
},
showError: function(string) {
var errorView = new View['error'];
errorView.render();
}
});
function initialize() {
var appRouter = new AppRouter;
Backbone.history.start({ pushstate: true });
$('#toggle-menu').click(function() {
$('.navbar-content').toggleClass('expanded');
});
$(document).on('click', 'a', function(evt) {
if (this.host == location.host) {
evt.preventDefault();
var href = $(this).attr('href');
$('.navbar-content').removeClass('animate expanded');
Backbone.history.navigate(href, { trigger: true });
_.delay(function() {
$('.navbar-content').addClass('animate');
}, 50);
}
});
return appRouter;
}
return {
initialize: initialize
};
});
|
Add trigger to navigate() calls
|
Add trigger to navigate() calls
|
JavaScript
|
mit
|
jonlai/personal-website,jonlai/personal-website,jonlai/personal-website
|
e0181d13dd3e42ee3bbda2aa270848e06f50fe4e
|
app/js/controllers/data-controller.js
|
app/js/controllers/data-controller.js
|
'use strict';
module.exports = function(app) {
app.controller('dataController',
[ '$scope', 'HttpService', '$http', '$cookies',
function($scope, HttpService, $http, $cookies) {
$http.defaults.headers.common.jwt = $cookies.jwt;
$scope.selectedDomain = false;
var domainService = new HttpService('domains');
$scope.getDomains = function(){
domainService.get()
.success(function(domains){
$scope.domains = domains;
});
};
$scope.getDomains(); // run on view load
var visitService = new HttpService('visits');
$scope.getVisits = function(domain_id){
$scope.selectedDomain = domain_id;
visitService.get(domain_id.toString())
.success(function(visits){
$scope.visits = visits;
});
};
} ]);
};
|
'use strict';
module.exports = function(app) {
app.controller('dataController',
[ '$scope', 'HttpService', '$http', '$cookies',
function($scope, HttpService, $http, $cookies) {
$http.defaults.headers.common.jwt = $cookies.jwt;
$scope.selectedDomain = false;
var domainService = new HttpService('domains');
$scope.getDomains = function(){
domainService.get()
.success(function(domains){
$scope.domains = domains;
});
};
$scope.getDomains(); // run on view load
var visitService = new HttpService('visits');
$scope.getVisits = function(domain_id){
$scope.selectedDomain = domain_id;
visitService.get(domain_id.toString())
.success(function(visits){
$scope.visits = visits;
});
};
/**
* Add domains
*/
$scope.addDomain = function() {
domainService.post($scope.newDomain, {});
$scope.newDomain = '';
};
} ]);
};
|
Add function for adding domains
|
Add function for adding domains
|
JavaScript
|
mit
|
Sextant-WDB/sextant-ng
|
f1f4f9e1afbb331ed3eb679d4b2cebf930a21824
|
js/script.js
|
js/script.js
|
(function () {
'use strict';
var worker = null,
$output = null;
$output = $('#worker-output');
/**
worker = new Worker('/js/example-worker.js');
worker.addEventListener('message', function (event) {
$output.text(event.data);
return;
})
//worker.postMessage();
/**/
worker = new WebWorker('/js/example-worker.js');
worker.on('message', function (event) {
$output.text(event.data);
return;
});
worker.load().on(WebWorker.Event.WORKER_LOADED, function () {
worker.start();
return;
});
return;
})();
|
(function () {
'use strict';
var worker = null,
$output = null;
$output = $('#worker-output');
/**
worker = new Worker('/js/example-worker.js');
worker.addEventListener('message', function (event) {
$output.text(event.data);
return;
})
//worker.postMessage();
/**/
worker = new WebWorker('/js/example-worker.js');
worker.on('message', function (event) {
$output.text(event.data);
return;
});
worker.load().on(WebWorker.Event.WORKER_LOADED, function () {
console.log('has loaded');
worker.start();
return;
});
return;
})();
|
Add temporary console.log for debugging.
|
Add temporary console.log for debugging.
|
JavaScript
|
mit
|
tanzeelkazi/web-worker,tanzeelkazi/webworker,tanzeelkazi/webworker,tanzeelkazi/web-worker,tanzeelkazi/web-worker,tanzeelkazi/webworker
|
b555d4c3922ed5ccb2a2affa58c566cce7b9b1f6
|
handlers/users.js
|
handlers/users.js
|
'use strict';
const Boom = require('boom');
const Errors = require('../lib/errors');
const Formatters = require('../lib/formatters');
const EXISTING_USER = Boom.conflict('User already exist');
exports.listUsers = function({ headers }, reply) {
let authParts = [];
if (headers.authorization) {
authParts = headers.authorization.split(' ');
}
const token = (authParts.length === 2) ? authParts[1] : '';
return this.helpers.verifyJWT(token)
.then(({ sub }) => this.models.User.getUser(sub))
.then((user) => {
const options = {};
if (!user) {
options.onlyViewPublic = true;
} else if (!user.isAdministrator()) {
options.selfId = user.id;
}
return this.models.User.listUsers(options);
})
.then((users) => {
return reply(Formatters.users(users)).code(200);
})
.catch(this.helpers.errorHandler.bind(this, reply));
};
exports.createUser = function({ payload }, reply) {
return this.models.User.createUser(payload)
.then((user) => {
return reply(Formatters.user(user)).code(201);
})
.catch(Errors.ExistingUserError, () => reply(EXISTING_USER))
.catch(this.helpers.errorHandler.bind(this, reply));
};
|
'use strict';
const Boom = require('boom');
const Errors = require('../lib/errors');
const Formatters = require('../lib/formatters');
exports.listUsers = function({ headers }, reply) {
let authParts = [];
if (headers.authorization) {
authParts = headers.authorization.split(' ');
}
const token = (authParts.length === 2) ? authParts[1] : '';
return this.helpers.verifyJWT(token)
.then(({ sub }) => this.models.User.getUser(sub))
.then((user) => {
const options = {};
if (!user) {
options.onlyViewPublic = true;
} else if (!user.isAdministrator()) {
options.selfId = user.id;
}
return this.models.User.listUsers(options);
})
.then((users) => {
return reply(Formatters.users(users)).code(200);
})
.catch(this.helpers.errorHandler.bind(this, reply));
};
exports.createUser = function({ payload }, reply) {
return this.models.User.createUser(payload)
.then((user) => {
return reply(Formatters.user(user)).code(201);
})
.catch(Errors.ExistingUserError, () => {
return reply(Boom.conflict('User already exist'));
})
.catch(this.helpers.errorHandler.bind(this, reply));
};
|
Replace Boom variable in createUser()
|
Replace Boom variable in createUser()
|
JavaScript
|
mit
|
cjduncana/adevav-back-end,cjduncana/adevav-back-end,creativo-pty/adevav-back-end,creativo-pty/adevav-back-end
|
46cf5c9a5c56c6abcf0ee50c9492a96588b925dc
|
app/renderer/js/utils/config-util.js
|
app/renderer/js/utils/config-util.js
|
'use strict';
const {app} = require('electron').remote;
const JsonDB = require('node-json-db');
let instance = null;
class ConfigUtil {
constructor() {
if (instance) {
return instance;
} else {
instance = this;
}
this.db = new JsonDB(app.getPath('userData') + '/config.json', true, true);
return instance;
}
getConfigItem(key, defaultValue = null) {
const value = this.db.getData('/')[key];
if (value === undefined) {
this.setConfigItem(key, value);
return defaultValue;
} else {
return value;
}
}
setConfigItem(key, value) {
this.db.push(`/${key}`, value, true);
}
removeConfigItem(key) {
this.db.delete(`/${key}`);
}
}
module.exports = new ConfigUtil();
|
'use strict';
const process = require('process');
const JsonDB = require('node-json-db');
let instance = null;
let app = null;
/* To make the util runnable in both main and renderer process */
if (process.type === 'renderer') {
app = require('electron').remote.app;
} else {
app = require('electron').app;
}
class ConfigUtil {
constructor() {
if (instance) {
return instance;
} else {
instance = this;
}
this.db = new JsonDB(app.getPath('userData') + '/config.json', true, true);
return instance;
}
getConfigItem(key, defaultValue = null) {
const value = this.db.getData('/')[key];
if (value === undefined) {
this.setConfigItem(key, value);
return defaultValue;
} else {
return value;
}
}
setConfigItem(key, value) {
this.db.push(`/${key}`, value, true);
}
removeConfigItem(key) {
this.db.delete(`/${key}`);
}
}
module.exports = new ConfigUtil();
|
Make ConfigUtil runnable in both processes.
|
Make ConfigUtil runnable in both processes.
|
JavaScript
|
apache-2.0
|
zulip/zulip-desktop,zulip/zulip-desktop,zulip/zulip-desktop,zulip/zulip-desktop,zulip/zulip-electron,zulip/zulip-electron,zulip/zulip-electron
|
9c117026f141ef68e06571afb5bffc90a29d22ee
|
app/scripts/services/eventservice.js
|
app/scripts/services/eventservice.js
|
'use strict';
/**
* @ngdoc service
* @name barteguidenMarkedsWebApp.eventService
* @description
* # eventService
* Factory in the barteguidenMarkedsWebApp.
*/
angular.module('barteguidenMarkedsWebApp.services')
.factory('Event', function ($resource) {
return $resource('http://barteguiden.no/v2/events/:id', { id: '@_id' }, {
update: {
method: 'PUT'
},
query: {
method: 'GET',
isArray: false
}
});
});
|
'use strict';
/**
* @ngdoc service
* @name barteguidenMarkedsWebApp.eventService
* @description
* # eventService
* Factory in the barteguidenMarkedsWebApp.
*/
angular.module('barteguidenMarkedsWebApp.services')
.factory('Event', function ($resource) {
return $resource('http://localhost:4004/api/events/:id', { id: '@_id' }, {
update: {
method: 'PUT'
},
query: {
method: 'GET',
isArray: true
}
});
});
|
Update the EventService to use the local server. The event response is now an array
|
Update the EventService to use the local server. The event response is now an array
|
JavaScript
|
apache-2.0
|
Studentmediene/Barteguiden,Studentmediene/Barteguiden
|
18a8ea8eaac3b0ec2f1868d1b9961f3befd6df78
|
v3/buildUtils/webpack.plugins.js
|
v3/buildUtils/webpack.plugins.js
|
// webpack.plugins.js
"use strict";
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const UglifyJsWebpackPlugin = require("uglifyjs-webpack-plugin");
const config = {
plugins: [
new ExtractTextPlugin({
filename: "[name].css"
}),
new UglifyJsWebpackPlugin({
uglifyOptions: {
compress: {
drop_console: true,
},
output: {
comments: false,
beautify: false
}
}
})
]
};
module.exports = config;
|
// webpack.plugins.js
"use strict";
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const UglifyJsWebpackPlugin = require("uglifyjs-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const commonPaths = require("./commonPaths");
const config = {
plugins: [
new ExtractTextPlugin({
filename: "[name].bundle.css"
}),
/* new UglifyJsWebpackPlugin({
uglifyOptions: {
compress: {
drop_console: true,
},
output: {
comments: false,
beautify: false
}
}
}) */
new HtmlWebpackPlugin({
title: "test HtmlWebpackPlugin"
}),
new CleanWebpackPlugin([commonPaths.outputPath], {
root: commonPaths.webpackConfigPath
})
]
};
module.exports = config;
|
Edit filename for ExtractTextPlugin. Added HtmlWebpackPlugin, CleanWebpackPlugin
|
Edit filename for ExtractTextPlugin. Added HtmlWebpackPlugin, CleanWebpackPlugin
|
JavaScript
|
mit
|
var-bin/webpack-training,var-bin/webpack-training,var-bin/webpack-training,var-bin/webpack-training
|
722bd5f6636d448c7b95d636e99726a4c21d9c9f
|
src/components/datagrid.js
|
src/components/datagrid.js
|
var fs = require('fs');
module.exports = function (app) {
app.config([
'formioComponentsProvider',
function(formioComponentsProvider) {
formioComponentsProvider.register('datagrid', {
title: 'Data Grid',
template: 'formio/components/datagrid.html',
settings: {
input: true,
components: [],
tableView: true,
label: '',
key: 'datagrid',
protected: false,
persistent: true
}
});
}
]);
app.controller('formioDataGrid', [
'$scope',
function($scope) {
$scope.data[$scope.component.key] = $scope.data[$scope.component.key] || [{}];
$scope.addRow = function() {
$scope.data[$scope.component.key].push({});
};
$scope.removeRow = function(index) {
$scope.data[$scope.component.key].splice(index, 1);
};
}
]);
app.run([
'$templateCache',
'FormioUtils',
function($templateCache, FormioUtils) {
$templateCache.put('formio/components/datagrid.html', FormioUtils.fieldWrap(
fs.readFileSync(__dirname + '/../templates/components/datagrid.html', 'utf8')
));
}
]);
};
|
var fs = require('fs');
module.exports = function (app) {
app.config([
'formioComponentsProvider',
function(formioComponentsProvider) {
formioComponentsProvider.register('datagrid', {
title: 'Data Grid',
template: 'formio/components/datagrid.html',
settings: {
input: true,
tree: true,
components: [],
tableView: true,
label: '',
key: 'datagrid',
protected: false,
persistent: true
}
});
}
]);
app.controller('formioDataGrid', [
'$scope',
function($scope) {
$scope.data[$scope.component.key] = $scope.data[$scope.component.key] || [{}];
$scope.addRow = function() {
$scope.data[$scope.component.key].push({});
};
$scope.removeRow = function(index) {
$scope.data[$scope.component.key].splice(index, 1);
};
}
]);
app.run([
'$templateCache',
'FormioUtils',
function($templateCache, FormioUtils) {
$templateCache.put('formio/components/datagrid.html', FormioUtils.fieldWrap(
fs.readFileSync(__dirname + '/../templates/components/datagrid.html', 'utf8')
));
}
]);
};
|
Add tree to fix formio-util dependency.
|
Add tree to fix formio-util dependency.
|
JavaScript
|
mit
|
formio/ngFormio,Kelsus/ngFormio,Kelsus/ngFormio
|
12eede4a14e74957d1ad86a9a83807442f90fdd4
|
lib/measure-avenir.js
|
lib/measure-avenir.js
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-typography/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-typography/tachyons-typography.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_typography.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/measure/avenir-next/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/typography/measure/avenir-next/index.html', html)
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var cssstats = require('cssstats')
var module = require('tachyons-typography/package.json')
var moduleCss = fs.readFileSync('node_modules/tachyons-typography/tachyons-typography.min.css', 'utf8')
var moduleObj = cssstats(moduleCss)
var moduleSize = filesize(moduleObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_typography.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8')
var template = fs.readFileSync('./templates/docs/measure/avenir-next/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
moduleVersion: module.version,
moduleSize: moduleSize,
moduleObj: moduleObj,
srcCSS: srcCSS,
navDocs: navDocs,
siteFooter: siteFooter
})
fs.writeFileSync('./docs/typography/measure/avenir-next/index.html', html)
|
Add site footer to each documentation generator
|
Add site footer to each documentation generator
|
JavaScript
|
mit
|
fenderdigital/css-utilities,fenderdigital/css-utilities,pietgeursen/pietgeursen.github.io,tachyons-css/tachyons,topherauyeung/portfolio,topherauyeung/portfolio,getfrank/tachyons,topherauyeung/portfolio,cwonrails/tachyons,matyikriszta/moonlit-landing-page
|
501491a520c617e3a9f759f31cdfc479f7e5fe96
|
hardware/index.js
|
hardware/index.js
|
var EventEmitter = require('events').EventEmitter;
var hardware = module.exports = new EventEmitter();
//var e = nobleEmitter.connect(peripheralUuid, serviceUuid, characteristicUuid);
var e = (process.env.DEVICE) ?
require('./serial')(process.env.DEVICE) :
require('./stdin-mock');
var commands = {
0: function () {
emitScore('a'); // single click
},
1: function () {
emitScore('b'); // single click
},
2: function () {
emitUndo('a'); // double click
},
3: function () {
emitUndo('b'); // double click
},
4: function () {
hardware.emit('restart'); // long press
},
5: function () {
hardware.emit('restart'); // long press
}
};
e.on('connected', function () {
console.log('ble connected');
hardware.emit('connected');
});
e.on('data', function (data) {
console.log('data: ', data);
if(commands[data])
commands[data]();
else
console.log('unknown command "' + data + '"');
});
e.on('disconnected', function () {
console.log('ble disconnected');
hardware.emit('disconnected');
});
function emitScore (side) {
hardware.emit('score', { side: side });
}
function emitUndo (side) {
hardware.emit('undo', { side: side });
}
|
var EventEmitter = require('events').EventEmitter;
var hardware = module.exports = new EventEmitter();
var e = (process.env.DEVICE) ?
require('./serial')(process.env.DEVICE) :
require('./stdin-mock');
var commands = {
0: function () {
emitScore('a'); // single click
},
1: function () {
emitScore('b'); // single click
},
2: function () {
emitUndo('a'); // double click
},
3: function () {
emitUndo('b'); // double click
},
4: function () {
hardware.emit('restart'); // long press
},
5: function () {
hardware.emit('restart'); // long press
}
};
e.on('connected', function () {
console.log('ble connected');
hardware.emit('connected');
});
e.on('data', function (data) {
console.log('data: ', data);
if(commands[data])
commands[data]();
else
console.log('unknown command "' + data + '"');
});
e.on('disconnected', function () {
console.log('ble disconnected');
hardware.emit('disconnected');
});
function emitScore (side) {
hardware.emit('score', { side: side });
}
function emitUndo (side) {
hardware.emit('undo', { side: side });
}
|
Remove unused noble emitter code
|
Remove unused noble emitter code
|
JavaScript
|
mit
|
bekk/bekkboard,bekk/bekkboard,bekk/bekkboard,bekk/bekkboard
|
9d5975acddb3dcf1851ea2c5bb2fc38ce7e42a5b
|
src/PublicApi.js
|
src/PublicApi.js
|
'use strict';
const Engine = require('./Engine');
const PublicSelect = require('./public/PublicSelect');
const PublicApiOptions = require('./PublicApiOptions');
const Explainer = require('./Explainer');
class PublicApi
{
/**
*
* @param {PublicApiOptions} options
*/
constructor(options = new PublicApiOptions)
{
if (options instanceof PublicApiOptions) {
this.options = options;
} else {
this.options = new PublicApiOptions(options);
}
this.engine = new Engine();
}
/**
*
* @param {string} sql
* @returns {PublicSelect}
*/
query(sql)
{
return new PublicSelect(this.engine.createQuery(sql, this.options), this.options.dataSourceResolvers);
}
explain(select)
{
const e = new Explainer();
return e.createExplain(select);
}
}
PublicApi.DataSourceResolver = require('./DataSourceResolver');
PublicApi.exceptions = {
JlException: require('./error/JlException'),
SqlFunctionArgumentError: require('./error/SqlFunctionArgumentError'),
SqlLogicError: require('./error/SqlLogicError'),
SqlNotSupported: require('./error/SqlNotSupported'),
JsonParsingError: require('./error/JsonParsingError'),
DataSourceNotFound: require('./error/DataSourceNotFound')
};
module.exports = PublicApi;
|
'use strict';
const Engine = require('./Engine');
const PublicSelect = require('./public/PublicSelect');
const PublicApiOptions = require('./PublicApiOptions');
const Explainer = require('./Explainer');
class PublicApi
{
/**
*
* @param {PublicApiOptions} options
*/
constructor(options = new PublicApiOptions)
{
if (options instanceof PublicApiOptions) {
this.options = options;
} else {
this.options = new PublicApiOptions(options);
}
this.engine = new Engine();
}
/**
*
* @param {string} sql
* @returns {PublicSelect}
*/
query(sql)
{
return new PublicSelect(this.engine.createQuery(sql, this.options), this.options.dataSourceResolvers);
}
explain(select)
{
const e = new Explainer();
return e.createExplain(select);
}
}
PublicApi.DataSourceResolver = require('./DataSourceResolver');
PublicApi.exceptions = {
JlException: require('./error/JlException'),
SqlFunctionArgumentError: require('./error/SqlFunctionArgumentError'),
SqlLogicError: require('./error/SqlLogicError'),
SqlNotSupported: require('./error/SqlNotSupported'),
JsonParsingError: require('./error/JsonParsingError'),
DataSourceNotFound: require('./error/DataSourceNotFound')
};
PublicApi.version = require('../package.json').version;
module.exports = PublicApi;
|
Add `version` field in exports
|
Add `version` field in exports
|
JavaScript
|
mit
|
avz/node-jl-sql-api
|
30aa7fc0d67a049d0ce3c14856226a1c25d376e9
|
lib/http/endpoints/announce.js
|
lib/http/endpoints/announce.js
|
/**
* Based on specs at: http://wiki.theory.org/BitTorrent_Tracker_Protocol
*/
function announceHandler(req, res) {
console.log(req);
res.end('stub');
}
function register(server) {
server.get('/announce', announceHandler);
}
exports.register = register;
|
/**
* Based on specs at: http://wiki.theory.org/BitTorrent_Tracker_Protocol
*/
var async = require('async');
var httpUtil = require('util/http');
var flowCtrl = require('util/flow-ctrl');
var log = require('logmagic').local('bittorrent-tracker.lib.http.endpoints.announce');
function announceHandler(req, res) {
if (req.method !== 'GET') {
httpUtil.returnError(res, 100, null);
}
res.end('stub');
}
function register(server) {
server.all('/announce', async.apply(flowCtrl.captureAndLogError,
log, announceHandler, null));
}
exports.register = register;
|
Return error if the method is not GET.
|
Return error if the method is not GET.
|
JavaScript
|
bsd-3-clause
|
Kami/node-bittorrent-tracker,Kami/node-bittorrent-tracker
|
1623531764f7b044f9593f74e0c344c833ceac99
|
src/credit-card.js
|
src/credit-card.js
|
const { GraphQLScalarType } = require('graphql')
const cc = require('credit-card')
function parse (value) {
const {
card,
validCardNumber,
validCvv: validCVV,
validExpiryMonth,
validExpiryYear,
isExpired
} = cc.validate(getPayload())
if (validCardNumber) {
return Object.assign(card, {
validCVV,
validExpiryMonth,
validExpiryYear,
isExpired
})
}
function getPayload () {
switch (typeof value) {
case 'string':
case 'number': {
const cardType = cc.determineCardType(value.toString())
return {
number: value.toString(),
cardType
}
}
default: return Object.assign({ cardType: value.cardType || value.type }, value)
}
}
}
module.exports = new GraphQLScalarType({
name: 'CreditCard',
serialize: parse,
parseValue: parse,
parseLiteral (ast) {
return parse(ast.value)
}
})
|
const { GraphQLScalarType } = require('graphql')
const cc = require('credit-card')
function parse (value) {
const {
card,
validCardNumber,
validCvv: validCVV,
validExpiryMonth,
validExpiryYear,
isExpired
} = cc.validate(getPayload())
if (validCardNumber) {
return Object.assign(card, {
validCVV,
validExpiryMonth,
validExpiryYear,
isExpired
})
}
function getPayload () {
switch (typeof value) {
case 'string':
case 'number': {
const number = value.toString().replace(/\D/g, '')
const cardType = cc.determineCardType(number)
return {
number,
cardType
}
}
default: return Object.assign({}, value, {
number: value.number.toString().replace(/\D/g, ''),
cardType: value.cardType || value.type
})
}
}
}
module.exports = new GraphQLScalarType({
name: 'CreditCard',
serialize: parse,
parseValue: parse,
parseLiteral (ast) {
return parse(ast.value)
}
})
|
Remove spaces from credit card
|
Remove spaces from credit card
|
JavaScript
|
mit
|
mfix22/gnt
|
cd998cac866f0e0e820099534f2ecfaf1038468c
|
app/assets/javascripts/nail_polish/utils/subview_manager.js
|
app/assets/javascripts/nail_polish/utils/subview_manager.js
|
NailPolish.SubviewManager = {
renderEach: function (subviews) {
this._subviews = subviews;
_.each(subviews, function (view) {
view.parent = view.parent || this.defaultParent();
view.repository = view.repository || this.repository;
view.render();
}.bind(this));
},
remove: function() {
this.removeSelf();
_.each(this._subviews, function(subview) {
subview.remove();
});
},
removeSelf: function() { /* override me */ },
defaultParent: function() { return this },
};
|
NailPolish.SubviewManager = {
renderEach: function (subviews) {
this._subviews = subviews;
_.each(subviews, function (view) {
if(view) {
view.parent = view.parent || this.defaultParent();
view.repository = view.repository || this.repository;
view.render();
}
}.bind(this));
},
remove: function() {
this.removeSelf();
_.each(this._subviews, function(subview) {
if (subview){
subview.remove();
}
});
},
removeSelf: function() { /* override me */ },
defaultParent: function() {
return this;
}
};
|
Add a gaurd clause for IE8 compatibility in subview rendering
|
Add a gaurd clause for IE8 compatibility in subview rendering
|
JavaScript
|
mit
|
socialchorus/nail_polish,socialchorus/nail_polish,socialchorus/nail_polish
|
587386215a25ebd49761d336f97ab9b04b8dd1dc
|
lib/node_modules/@stdlib/math/base/special/dirchlet-eta/lib/index.js
|
lib/node_modules/@stdlib/math/base/special/dirchlet-eta/lib/index.js
|
'use strict';
// MODULES //
var powm1 = require( '@stdlib/math/base/special/powm1' );
var zeta = require( '@stdlib/math/base/special/riemann-zeta' );
var LN2 = require( '@stdlib/math/constants/float64-ln2' );
// ETA //
/**
* FUNCTION: eta( s )
* Evaluates the Dirichlet eta function.
*
* @param {Number} s - input value
* @returns {Number} function value
*/
function eta( s ) {
if ( s !== s ) {
return NaN;
}
if ( s === 1 ) {
// Alternating harmonic series...
return LN2;
}
return -powm1( 2, 1-s ) * zeta( s );
} // end FUNCTION eta()
// EXPORTS //
module.exports = eta;
|
'use strict';
// MODULES //
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var powm1 = require( '@stdlib/math/base/special/powm1' );
var zeta = require( '@stdlib/math/base/special/riemann-zeta' );
var LN2 = require( '@stdlib/math/constants/float64-ln2' );
// ETA //
/**
* FUNCTION: eta( s )
* Evaluates the Dirichlet eta function.
*
* @param {Number} s - input value
* @returns {Number} function value
*/
function eta( s ) {
if ( isnan( s ) ) {
return NaN;
}
if ( s === 1 ) {
// Alternating harmonic series...
return LN2;
}
return -powm1( 2, 1-s ) * zeta( s );
} // end FUNCTION eta()
// EXPORTS //
module.exports = eta;
|
Use base util is-nan to check for NaN value
|
Use base util is-nan to check for NaN value
|
JavaScript
|
apache-2.0
|
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
|
9ab94feb518c518816bd64a4e0e811dfedb3c428
|
katas/libraries/hamjest/assertThat.js
|
katas/libraries/hamjest/assertThat.js
|
// 1: assertThat
// To do: make all tests pass, leave the assert lines unchanged!
import {
assertThat, equalTo,
containsString, throws, returns,
} from 'hamjest';
describe('The core function, `assertThat()`', () => {
it('is a function', () => {
const typeOfAssertThat = typeof assertThat;
assertThat(typeOfAssertThat, equalTo('function'));
});
describe('requires at least two params', () => {
it('1st: the actual value', () => {
const expected = equalTo('actual');
assertThat('actual', expected);
});
it('2nd: a matcher for the expected value', () => {
const matcher = equalTo('expected');
assertThat('expected', matcher);
});
describe('the optional 3rd param', () => {
it('goes first(!), and is the assertion reason', () => {
const reason = 'This is the reason, the first `assertThat()` throws as part of its message.';
try {
assertThat(reason, true, equalTo(false));
} catch (e) {
assertThat(e.message, containsString(reason));
}
});
});
});
describe('under the hood, it does', () => {
it('nothing, WHEN actual and expected match (using the given matcher)', () => {
const passingTest = () => assertThat(true, equalTo(true));
assertThat(passingTest, returns());
});
it('throw an assertion, WHEN actual and expected don`t match', () => {
const failingTest = () => assertThat(false, equalTo(true));
assertThat(failingTest, throws());
});
});
});
|
// 1: assertThat
// To do: make all tests pass, leave the assert lines unchanged!
import {
assertThat, equalTo,
containsString, throws, returns,
} from 'hamjest';
describe('The core function, `assertThat()`', () => {
it('is a function', () => {
const typeOfAssertThat = typeof assertThat;
assertThat(typeOfAssertThat, equalTo('function'));
});
describe('requires at least two params', () => {
it('1st: the actual value', () => {
const actual = 'actual';
const expected = equalTo('actual');
assertThat(actual, expected);
});
it('2nd: a matcher for the expected value', () => {
const matcher = equalTo('expected');
assertThat('expected', matcher);
});
describe('the optional 3rd param', () => {
it('goes first(!), and is the assertion reason', () => {
let caughtError;
const reason = 'This is the reason, the first `assertThat()` throws as part of its message.';
try {
assertThat(reason, true, equalTo(false));
} catch (e) {
caughtError = e;
}
assertThat(caughtError.message, containsString(reason));
});
});
});
describe('under the hood, it does', () => {
it('nothing, WHEN actual and expected match (using the given matcher)', () => {
const passingTest = () => assertThat(true, equalTo(true));
assertThat(passingTest, returns());
});
it('throw an assertion, WHEN actual and expected don`t match', () => {
const failingTest = () => assertThat(false, equalTo(true));
assertThat(failingTest, throws());
});
});
});
|
Prepare for making it a kata.
|
Prepare for making it a kata.
|
JavaScript
|
mit
|
tddbin/katas,tddbin/katas,tddbin/katas
|
9e01d0685c4299920360389c255c14c3a59477ce
|
public/javascripts/application.js
|
public/javascripts/application.js
|
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
|
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
if (!Date.now) {
Date.now = function() {
return (new Date()).getTime();
};
}
function updateClock() {
var el = $("uhr");
var time = new Date();
var hours = time.getHours(),
minutes = time.getMinutes(),
seconds = time.getSeconds();
if (hours < 10)
hours = "0" + hours;
if (minutes < 10)
minutes = "0" + minutes;
if (seconds < 10)
seconds = "0" + seconds;
el.update("<p>" + hours + ":" + minutes + ":" + seconds + "</p>");
}
document.observe("dom:loaded", function(ev) {
if ($("uhr")) {
window.setInterval(updateClock, 1000);
}
})
|
Make the clock on the frontpage work.
|
Make the clock on the frontpage work.
|
JavaScript
|
mit
|
bt4y/bulletin_board,bt4y/bulletin_board
|
7cd25460f396d904fecb0c877f8ea06619994c38
|
blueprints/ember-websockets/index.js
|
blueprints/ember-websockets/index.js
|
module.exports = {
normalizeEntityName: function() {},
afterInstall: function() {
return this.addBowerPackageToProject('uri.js');
}
};
|
module.exports = {
normalizeEntityName: function() {},
afterInstall: function() {
var installContext = this;
return this.addPackageToProject('mock-socket').then(function() {
return installContext.addBowerPackageToProject('urijs');
});
}
};
|
Fix install issue with ember install ember-websockets
|
Fix install issue with ember install ember-websockets
|
JavaScript
|
mit
|
thoov/ember-websockets,thoov/ember-websockets
|
21ec0674ea25ea1d3df33fec7b825644162f1b58
|
src/components/EditActivityForm.js
|
src/components/EditActivityForm.js
|
import React, { Component, PropTypes } from 'react';
class EditActivityForm extends Component {
componentDidMount() {
this.description.focus();
}
updateActivity(e) {
e.preventDefault();
const activity = {
description: this.description.value,
timestamp: this.props.timestamp,
}
this.props.updateActivity(activity);
this.props.cancelEdit();
}
render() {
return (
<div className="row row--middle row--start">
<form
className="col--12"
onSubmit={(e) => this.updateActivity(e)}
ref={(input) => this.activityForm = input}
>
<div className="row row--middle">
<div className="col--6">
<input
type="text"
className="w--100 pv- ph-"
ref={(node) => this.description = node}
defaultValue={this.props.activity.description}
placeholder="went to the park"
/>
</div>
<div className="col--2">
<button type="submit">Update</button>
</div>
<div className="col--2">
<div onClick={this.props.cancelEdit}>cancel</div>
</div>
</div>
</form>
</div>
);
}
}
EditActivityForm.propTypes = {
updateActivity: PropTypes.func.isRequired,
cancelEdit: PropTypes.func.isRequired,
activity: PropTypes.object.isRequired,
};
export default EditActivityForm;
|
import React, { Component, PropTypes } from 'react';
import { getDescriptionAndTags, buildDescriptionAndTags } from '../helpers';
class EditActivityForm extends Component {
componentDidMount() {
this.description.focus();
}
updateActivity(e) {
e.preventDefault();
const { description, tags } = getDescriptionAndTags(this.description.value);
const activity = {
description,
tags,
timestamp: this.props.timestamp,
}
this.props.updateActivity(activity);
this.props.cancelEdit();
}
render() {
const { activity } = this.props;
const { description, tags } = activity;
return (
<div className="row row--middle row--start">
<form
className="col--12"
onSubmit={(e) => this.updateActivity(e)}
ref={(input) => this.activityForm = input}
>
<div className="row row--middle">
<div className="col--6">
<input
type="text"
className="w--100 pv- ph-"
ref={(node) => this.description = node}
defaultValue={buildDescriptionAndTags(description, tags)}
placeholder="went to the park"
/>
</div>
<div className="col--2">
<button type="submit">Update</button>
</div>
<div className="col--2">
<div onClick={this.props.cancelEdit}>cancel</div>
</div>
</div>
</form>
</div>
);
}
}
EditActivityForm.propTypes = {
updateActivity: PropTypes.func.isRequired,
cancelEdit: PropTypes.func.isRequired,
activity: PropTypes.object.isRequired,
};
export default EditActivityForm;
|
Edit tags in edit form input
|
Edit tags in edit form input
|
JavaScript
|
mit
|
mknudsen01/today,mknudsen01/today
|
cb33b14464bf23b36f0d1499c7a4cfde95f85f80
|
src/actions/Placeholder.js
|
src/actions/Placeholder.js
|
import { Action } from './../lib/Action';
import { Util } from '@aegis-framework/artemis';
export class Placeholder extends Action {
static matchString ([ action ]) {
return action === '$';
}
constructor ([action, name]) {
super ();
this.name = name;
this.action = this.engine.$ (name);
}
willApply () {
if (this.name.indexOf ('_') === 0) {
return Util.callAsync (this.action, this.engine).then ((action) => {
this.action = action;
return Promise.resolve ();
});
}
return Promise.resolve ();
}
apply () {
return this.engine.run (this.action);
}
revert () {
return this.engine.revert (this.action);
}
}
Placeholder.id = 'Placeholder';
export default Placeholder;
|
import { Action } from './../lib/Action';
import { Util } from '@aegis-framework/artemis';
export class Placeholder extends Action {
static matchString ([ action ]) {
return action === '$';
}
constructor ([action, name, ...args]) {
super ();
this.name = name;
this.action = this.engine.$ (name);
this.arguments = args;
}
willApply () {
if (this.name.indexOf ('_') === 0) {
return Util.callAsync (this.action, this.engine, ...this.arguments).then ((action) => {
this.action = action;
return Promise.resolve ();
});
}
return Promise.resolve ();
}
apply () {
return this.engine.run (this.action);
}
revert () {
return this.engine.revert (this.action);
}
}
Placeholder.id = 'Placeholder';
export default Placeholder;
|
Allow passing arguments to dynamic placeholders
|
Allow passing arguments to dynamic placeholders
|
JavaScript
|
mit
|
MonogatariVN/Monogatari,MonogatariVN/Monogatari,Monogatari/Monogatari
|
e3c1f2162caf735f6ba8324d698445929ecac248
|
js/application.js
|
js/application.js
|
/*global document, Reveal, carousel*/
(function(document, Reveal, carousel){
'use strict';
Reveal.addEventListener('carousel', function(){
var container = document.getElementById('carousel');
carousel.show(['aap', 'noot', 'mies'], container);
});
})(document, Reveal, carousel);
|
/*global document, Reveal, carousel*/
(function(document, Reveal, carousel){
'use strict';
Reveal.addEventListener('carousel', function(){
var container = document.getElementById('carousel');
var languages = [
'Ada',
'BBx',
'C',
'CFML',
'Clojure',
'Common Lisp',
'Groovy',
'JavaScript',
'Oberon',
'Oxygene',
'Pascal',
'Perl',
'Prolog',
'Python',
'REXX',
'Ruby',
'Scala',
'Scheme',
'Tcl',
];
carousel.show(languages, container);
});
})(document, Reveal, carousel);
|
Use JVM languages for carousel
|
Use JVM languages for carousel
|
JavaScript
|
mit
|
dvberkel/polyglot-programming-on-jvm,dvberkel/polyglot-programming-on-jvm
|
d30faa1e9f1e76715fec1f026d712ea11576af58
|
src/component.js
|
src/component.js
|
import { select, local } from "d3-selection";
var componentLocal = local(),
noop = function (){};
export default function (tagName, className){
var create,
render = noop,
destroy = noop,
selector = className ? "." + className : tagName;
function component(selection, props){
var update = selection.selectAll(selector)
.data(Array.isArray(props) ? props : [props]),
exit = update.exit(),
enter = update.enter().append(tagName).attr("class", className);
enter.each(function (){
componentLocal.set(this, {
selection: select(this)
});
});
if(create){
enter.each(function (){
var local = componentLocal.get(this);
local.state = {};
local.render = noop;
create(function setState(state){
Object.assign(local.state, state);
local.render();
});
});
enter.merge(update).each(function (props){
var local = componentLocal.get(this);
if(local.render === noop){
local.render = function (){
render(local.selection, local.props, local.state);
};
}
local.props = props;
local.render();
});
exit.each(function (){
destroy(componentLocal.get(this).state);
});
} else {
enter.merge(update).each(function (props){
render(componentLocal.get(this).selection, props);
});
}
exit.remove();
}
component.render = function(_) { return (render = _, component); };
component.create = function(_) { return (create = _, component); };
component.destroy = function(_) { return (destroy = _, component); };
return component;
};
|
import { select, local } from "d3-selection";
var componentLocal = local(),
noop = function (){};
export default function (tagName, className){
var create,
render = noop,
destroy = noop,
selector = className ? "." + className : tagName;
function component(selection, props){
var update = selection.selectAll(selector)
.data(Array.isArray(props) ? props : [props]),
exit = update.exit(),
enter = update.enter().append(tagName).attr("class", className);
enter.each(function (){
var local = componentLocal.set(this, {
selection: select(this),
state: {},
render: noop
});
if(create){
create(function setState(state){
Object.assign(local.state, state);
local.render();
});
}
});
enter.merge(update).each(function (props){
var local = componentLocal.get(this);
if(local.render === noop){
local.render = function (){
render(local.selection, local.props, local.state);
};
}
local.props = props;
local.render();
});
exit.each(function (){
destroy(componentLocal.get(this).state);
});
exit.remove();
}
component.render = function(_) { return (render = _, component); };
component.create = function(_) { return (create = _, component); };
component.destroy = function(_) { return (destroy = _, component); };
return component;
};
|
Unify cases of create and no create
|
Unify cases of create and no create
|
JavaScript
|
bsd-3-clause
|
curran/d3-component
|
f49a0fb3b6271061be2808495cbbb180770fff60
|
app/renderer/components/libraries/channel-request.js
|
app/renderer/components/libraries/channel-request.js
|
var ChannelRequest, Promise, refreshProviderObject, stopLongPolling, timeoutID;
Promise = require('bluebird');
refreshProviderObject = null;
ChannelRequest = (function() {
function ChannelRequest(channelName1, callback1) {
this.channelName = channelName1;
this.callback = callback1;
this.stopLongPolling = false;
if (this.channelName == null) {
throw new Error('Channel request needs of a channelName');
}
if (typeof this.callback !== 'function') {
throw new Error('Channel request needs of a callback function');
}
}
var startRefreshProvider = function(channelName, callback) {
return new Promise(function(resolve, reject) {
return callback(channelName, function(err) {
if (err) {
reject(err);
}
return resolve();
});
});
};
ChannelRequest.prototype.startLongPolling = function(miliseconds) {
if (!!this.stopLongPolling) {
clearTimeout(timeoutID);
return;
}
var self = this;
refreshProviderObject = startRefreshProvider(this.channelName, this.callback);
return refreshProviderObject.then(function() {
timeoutID = setTimeout(function() {
return self.startLongPolling(miliseconds);
}, miliseconds);
if (!!self.stopLongPolling) {
clearTimeout(timeoutID);
return;
}
}).catch(function(err) {
return console.error(err);
});
};
return ChannelRequest;
})();
export default ChannelRequest;
|
var ChannelRequest, Promise, refreshProviderObject, stopLongPolling, timeoutID;
Promise = require('bluebird');
refreshProviderObject = null;
ChannelRequest = (function() {
function ChannelRequest(channelName1, callback1) {
this.channelName = channelName1;
this.callback = callback1;
this.stopLongPolling = false;
if (this.channelName == null) {
throw new Error('Channel request needs of a channelName');
}
if (typeof this.callback !== 'function') {
throw new Error('Channel request needs of a callback function');
}
}
var startRefreshProvider = function(channelName, callback) {
return new Promise(function(resolve, reject) {
return callback(channelName, function(err) {
if (err) {
reject(new Error(err));
}
return resolve();
});
});
};
ChannelRequest.prototype.startLongPolling = function(miliseconds) {
if (!!this.stopLongPolling) {
clearTimeout(timeoutID);
return;
}
var self = this;
refreshProviderObject = startRefreshProvider(this.channelName, this.callback);
return refreshProviderObject.then(function() {
timeoutID = setTimeout(function() {
return self.startLongPolling(miliseconds);
}, miliseconds);
if (!!self.stopLongPolling) {
clearTimeout(timeoutID);
return;
}
}).catch(function(err) {
return err;
});
};
return ChannelRequest;
})();
export default ChannelRequest;
|
Return an error in ChannelRequest library
|
Return an error in ChannelRequest library
|
JavaScript
|
mit
|
willmendesneto/build-checker-app,willmendesneto/build-checker-app
|
62bf3607a8191925a2eb3b4a71693234dcaf5646
|
src/Oro/Bundle/UserBundle/Resources/public/js/models/role/access-levels-collection.js
|
src/Oro/Bundle/UserBundle/Resources/public/js/models/role/access-levels-collection.js
|
define(function(require) {
'use strict';
var AccessLevelsCollection;
var _ = require('underscore');
var RoutingCollection = require('oroui/js/app/models/base/routing-collection');
AccessLevelsCollection = RoutingCollection.extend({
routeDefaults: {
routeName: 'oro_security_access_levels'
},
parse: function(resp, options) {
return _.map(_.pairs(resp), function(item) {
return {access_level: item[0], access_level_label: item[1]};
});
}
});
return AccessLevelsCollection;
});
|
define(function(require) {
'use strict';
var AccessLevelsCollection;
var _ = require('underscore');
var RoutingCollection = require('oroui/js/app/models/base/routing-collection');
AccessLevelsCollection = RoutingCollection.extend({
routeDefaults: {
routeName: 'oro_security_access_levels'
},
parse: function(resp, options) {
return _.map(_.pairs(resp), function(item) {
return {access_level: parseInt(item[0], 10), access_level_label: item[1]};
});
}
});
return AccessLevelsCollection;
});
|
Fix issues found on demo
|
BAP-10897: Fix issues found on demo
|
JavaScript
|
mit
|
geoffroycochard/platform,orocrm/platform,trustify/oroplatform,geoffroycochard/platform,trustify/oroplatform,orocrm/platform,Djamy/platform,orocrm/platform,trustify/oroplatform,geoffroycochard/platform,Djamy/platform,Djamy/platform
|
07279ef62b8c745f7d6d5e57f6166cd6125ee1c1
|
server/discord/cogs/ping/index.js
|
server/discord/cogs/ping/index.js
|
const client = require('./../../');
module.exports.info = {
aliases: [
'ping',
'pong'
]
};
module.exports.command = message =>
message.channel.createMessage(`\`\`\`\n${client.shards.map(shard => `Shard ${shard.id} | ${shard.latency}ms`).join('\n')}\n\`\`\``);
|
const client = require('./../../');
module.exports.info = {
aliases: [
'ping',
'pong'
]
};
module.exports.command = (message) => {
let s = 0;
if (message.channel.guild) {
s = client.guildShardMap[message.channel.guild.id];
}
message.channel.createMessage(`\`\`\`\n${client.shards.map(shard => `${s === shard.id ? '>' : ' '}Shard ${shard.id} | ${shard.latency}ms`).join('\n')}\n\`\`\``);
};
|
Add an arrow next to what shard the bot is on
|
Add an arrow next to what shard the bot is on
|
JavaScript
|
mit
|
moustacheminer/discordmail,moustacheminer/discordmail
|
56b40b666ecedb2c4df37e67b8216682582e77e7
|
src/components/Resource.js
|
src/components/Resource.js
|
import React, { PropTypes } from 'react'
import SVG from 'svg-inline-react'
const Resource = ({ icon, value }) =>
<li>
<SVG src={icon}/>
<span>{value}</span>
</li>
Resource.propTypes = {
icon: PropTypes.object.isRequired,
value: PropTypes.string.isRequired,
}
export default Resource
|
import React, { PropTypes } from 'react'
import SVG from 'svg-inline-react'
const Resource = ({ icon, value }) =>
<li>
<SVG src={icon}/>
<span>{value}</span>
</li>
Resource.propTypes = {
icon: PropTypes.string.isRequired,
value: PropTypes.number.isRequired,
}
export default Resource
|
Fix warnings with wrong PropTypes
|
Fix warnings with wrong PropTypes
|
JavaScript
|
mit
|
albertoblaz/lord-commander,albertoblaz/lord-commander
|
08bdcfbbb82e1c6dd0fc6e41d17f6211a2adc1bf
|
app/components/browser/Browser.js
|
app/components/browser/Browser.js
|
import React from 'react'
import ErrorMessage from './ErrorMessage'
import Header from './Header'
import BrowserStack from './BrowserStack'
import BrowserTabs from './BrowserTabs'
import CorpusStatusWatcher from '../CorpusStatusWatcher'
class Browser extends React.Component {
render () {
return (
<CorpusStatusWatcher className="window browser-window">
<Header />
<BrowserStack />
<BrowserTabs />
<ErrorMessage />
</CorpusStatusWatcher>
)
}
}
export default Browser
|
import React from 'react'
import { connect } from 'react-redux'
import ErrorMessage from './ErrorMessage'
import Header from './Header'
import BrowserStack from './BrowserStack'
import BrowserTabs from './BrowserTabs'
import CorpusStatusWatcher from '../CorpusStatusWatcher'
import Spinner from '../Spinner'
class Browser extends React.Component {
render () {
if (!this.props.corpus) {
// Corpus not yet selected
return <Spinner />
}
return (
<CorpusStatusWatcher className="window browser-window">
<Header />
<BrowserStack />
<BrowserTabs />
<ErrorMessage />
</CorpusStatusWatcher>
)
}
}
Browser.propTypes = {
corpus: React.PropTypes.object
}
const mapStateToProps = ({ corpora }) => ({
corpus: corpora.selected
})
const mapDispatchToProps = {
}
export default connect(mapStateToProps, mapDispatchToProps)(Browser)
|
Fix proptypes error when rendering too soon after corpus is selected
|
fix(browser): Fix proptypes error when rendering too soon after corpus is selected
|
JavaScript
|
agpl-3.0
|
medialab/hyphe-browser,medialab/hyphe-browser
|
667625bff0a81ee0d420f9ada44d7d95bfbffa10
|
lib/directives.js
|
lib/directives.js
|
var directives = {
TOC: function(text) {
var toc = require('markdown-toc');
return toc(text).content;
}
};
module.exports = {
directiveMap: directives
};
|
var directives = {
TOC: function(text) {
var toc = require('markdown-toc');
text = text.split('\n').slice(1).join('\n');
return toc(text, {slugify: function(str) {
return str.toLowerCase().replace(/[^\w]+/g, '-');
}}).content;
}
};
module.exports = {
directiveMap: directives
};
|
Fix TOC anchor tags bug
|
Fix TOC anchor tags bug
|
JavaScript
|
mit
|
claudioc/jingo,claudioc/jingo
|
87b3e5b3a0ac04537237208a7535a937109e1d13
|
src/hmac.js
|
src/hmac.js
|
// HMAC - keyed-Hash Message Authentication Code
function hmac(hash, size, digest, data, hkey, block) {
var i, akey, ipad, opad;
data = self.Encoder(data).trunc();
hkey = self.Encoder(hkey).trunc();
if (hkey.length > block) {
akey = hash(digest, hkey).trunc();
} else {
akey = self.Encoder(hkey).trunc();
}
for (i = 0, ipad = [], opad = []; i < block; i += 1) {
ipad[i] = (akey[i] || 0x00) ^ 0x36;
opad[i] = (akey[i] || 0x00) ^ 0x5c;
}
return hash(size, opad.concat(hash(digest, ipad.concat(data)).trunc()));
}
|
// HMAC - keyed-Hash Message Authentication Code
function hmac(hash, size, digest, data, hkey, block) {
var i, akey, ipad, opad;
if (hkey.length > block) {
akey = hash(digest, hkey).trunc();
} else {
akey = self.Encoder(hkey).trunc();
}
for (i = 0, ipad = [], opad = []; i < block; i += 1) {
ipad[i] = (akey[i] || 0x00) ^ 0x36;
opad[i] = (akey[i] || 0x00) ^ 0x5c;
}
return hash(size, opad.concat(hash(digest, ipad.concat(data)).trunc()));
}
|
Remove excessive Encoder calls in HMAC -- 'ready' should already have been applied.
|
Remove excessive Encoder calls in HMAC -- 'ready' should already have been applied.
|
JavaScript
|
mit
|
coiscir/jsdigest,coiscir/jsdigest
|
a832aeea3b219b2e40cfa6065c0a94dc19b76a3b
|
js/components/layouts/Header.react.js
|
js/components/layouts/Header.react.js
|
var React = require('react');
var title = "Orion's Belt BattleGrounds";
var Router = require('react-router');
var Route = Router.Route, DefaultRoute = Router.DefaultRoute,
Link=Router.Link, RouteHandler = Router.RouteHandler;
var CurrentUserMenu = require('../users/CurrentUserMenu.react.js');
var Header = React.createClass({
render: function () {
return (
<div className="navbar navbar-default navbar-fixed-top">
<div className="container">
<div className="navbar-header">
<a href="/" className="navbar-brand">{title}</a>
<button className="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
</div>
<div className="navbar-collapse collapse" id="navbar-main">
{/*<ul className="nav navbar-nav">
<li><a href="../help/">Help</a></li>
</ul>*/}
<ul className="nav navbar-nav navbar-right">
<CurrentUserMenu />
</ul>
</div>
</div>
</div>
);
}
});
module.exports = Header;
|
var React = require('react');
var title = "Orion's Belt BattleGrounds";
var Router = require('react-router');
var Route = Router.Route, DefaultRoute = Router.DefaultRoute,
Link=Router.Link, RouteHandler = Router.RouteHandler;
var CurrentUserMenu = require('../users/CurrentUserMenu.react.js');
var Header = React.createClass({
render: function () {
return (
<div className="navbar navbar-default navbar-fixed-top">
<div className="container">
<div className="navbar-header">
<Link to="root" className="navbar-brand">{title}</Link>
<button className="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
</div>
<div className="navbar-collapse collapse" id="navbar-main">
{/*<ul className="nav navbar-nav">
<li><a href="../help/">Help</a></li>
</ul>*/}
<ul className="nav navbar-nav navbar-right">
<CurrentUserMenu />
</ul>
</div>
</div>
</div>
);
}
});
module.exports = Header;
|
Make brand link a router link
|
Make brand link a router link
|
JavaScript
|
mit
|
orionsbelt-battlegrounds/frontend,orionsbelt-battlegrounds/frontend,orionsbelt-battlegrounds/frontend
|
f555d3422ada1c77e7c36d88b6b96d962b8b5f76
|
ckanext/nhm/theme/public/scripts/modules/iframe-resize.js
|
ckanext/nhm/theme/public/scripts/modules/iframe-resize.js
|
// Track iframe content height changes and resize element accordingly
this.ckan.module('iframe-resize', function(jQuery, _) {
return {
initialize: function() {
var $iframe = this.el;
var i_window = $iframe.get(0).contentWindow;
var i_doc = i_window.document;
jQuery(i_window).resize(function(){
$iframe.height(jQuery(i_doc).height);
});
}
}
});
|
// Track iframe content height changes and resize element accordingly
this.ckan.module('iframe-resize', function(jQuery, _) {
return {
initialize: function() {
var $iframe = this.el;
$iframe.ready(function(){
var i_window = $iframe.get(0).contentWindow;
var set_height = function(){
// body is not always available on some browsers. True even if we did a jQuery(i_window.document).ready(...)
if (i_window.document && i_window.document.body){
var current = $iframe.height();
var target = jQuery(i_window.document).height();
if (current != target){
$iframe.height(target);
}
}
};
set_height();
// This is, unfortunately, the only reliable cross browser way to track iframe size changes.
jQuery(i_window).resize(set_height);
window.setInterval(set_height, 250);
});
}
}
});
|
Improve iframe height change tracking
|
Improve iframe height change tracking
|
JavaScript
|
mit
|
NaturalHistoryMuseum/ckanext-nhm,NaturalHistoryMuseum/ckanext-nhm,NaturalHistoryMuseum/ckanext-nhm
|
5d7866930a492909ea703ba5343b8f028a5763b5
|
app/utils/i18n/missing-message.js
|
app/utils/i18n/missing-message.js
|
import Ember from 'ember';
import Locale from 'ember-i18n/utils/locale';
import config from '../../config/environment';
const DEFAULT_LOCALE = config.i18n.defaultLocale;
let missingMessage = function(locale, key, data) {
console.log(locale)
if (locale === DEFAULT_LOCALE || window.env === 'development') {
return `Missing translation: ${key}`;
} else {
Ember.Logger.warn("Missing translation: " + key);
// NOTE This relies on internal APIs and is brittle.
// Emulating the internals of ember-i18n's translate method
const i18n = this;
const count = Ember.get(data, 'count');
const defaults = Ember.makeArray(Ember.get(data, 'default'));
defaults.unshift(key);
const localeObj = new Locale(DEFAULT_LOCALE, Ember.getOwner(i18n));
const template = localeObj.getCompiledTemplate(defaults, count);
return template(data);
}
};
export default missingMessage;
|
import Ember from 'ember';
import Locale from 'ember-i18n/utils/locale';
import config from '../../config/environment';
const DEFAULT_LOCALE = config.i18n.defaultLocale;
let missingMessage = function(locale, key, data) {
if (locale === DEFAULT_LOCALE || window.env === 'development') {
return `Missing translation: ${key}`;
} else {
Ember.Logger.warn(`Missing translation: ${key}`);
// NOTE This relies on internal APIs and is brittle.
// Emulating the internals of ember-i18n's translate method
let i18n = this;
let count = Ember.get(data, 'count');
let defaults = Ember.makeArray(Ember.get(data, 'default'));
defaults.unshift(key);
let localeObj = new Locale(DEFAULT_LOCALE, Ember.getOwner(i18n));
let template = localeObj.getCompiledTemplate(defaults, count);
return template(data);
}
};
export default missingMessage;
|
Tidy up missing message util linting issues
|
Tidy up missing message util linting issues
|
JavaScript
|
mit
|
HospitalRun/hospitalrun-frontend,HospitalRun/hospitalrun-frontend,HospitalRun/hospitalrun-frontend,HospitalRun/hospitalrun-frontend
|
529c57c39a28bb6343230c52345cac29aa1c2226
|
app/src/js/modules/buic.js
|
app/src/js/modules/buic.js
|
/**
* Main mixin for the Bolt buic module.
*
* @mixin
* @namespace Bolt.buic
*
* @param {Object} bolt - The Bolt module.
* @param {Object} $ - jQuery.
*/
(function (bolt, $) {
'use strict';
/**
* Bolt.buic mixin container.
*
* @private
* @type {Object}
*/
var buic = {};
/**
* Initializes the fields, optionally based on a context.
*
* @function init
* @memberof Bolt.buic
* @param context
*/
buic.init = function (context) {
if (typeof context === 'undefined') {
context = $(document.documentElement);
}
// Widgets initialisations
$('[data-widget]', context).each(function () {
$(this)[$(this).data('widget')]();
});
};
// Add placeholder for buic.
bolt.buic = buic;
})(Bolt || {}, jQuery);
|
/**
* Main mixin for the Bolt buic module.
*
* @mixin
* @namespace Bolt.buic
*
* @param {Object} bolt - The Bolt module.
* @param {Object} $ - jQuery.
*/
(function (bolt, $) {
'use strict';
/**
* Bolt.buic mixin container.
*
* @private
* @type {Object}
*/
var buic = {};
/**
* Initializes the fields, optionally based on a context.
*
* @function init
* @memberof Bolt.buic
* @param context
*/
buic.init = function (context) {
if (typeof context === 'undefined') {
context = $(document.documentElement);
}
// Widgets initialisations
$('[data-widget]', context).each(function () {
$(this)[$(this).data('widget')]()
.removeAttr('data-widget')
.removeData('widget');
});
};
// Add placeholder for buic.
bolt.buic = buic;
})(Bolt || {}, jQuery);
|
Make sure the widget is initialized only once (although the widget factory does something similar)
|
Make sure the widget is initialized only once (although the widget factory does something similar)
|
JavaScript
|
mit
|
joshuan/bolt,one988/cm,rossriley/bolt,Raistlfiren/bolt,bolt/bolt,joshuan/bolt,electrolinux/bolt,romulo1984/bolt,HonzaMikula/masivnipostele,cdowdy/bolt,lenvanessen/bolt,rossriley/bolt,one988/cm,nantunes/bolt,bolt/bolt,romulo1984/bolt,Raistlfiren/bolt,CarsonF/bolt,electrolinux/bolt,nikgo/bolt,rarila/bolt,electrolinux/bolt,nikgo/bolt,cdowdy/bolt,GawainLynch/bolt,CarsonF/bolt,Raistlfiren/bolt,HonzaMikula/masivnipostele,GawainLynch/bolt,nantunes/bolt,romulo1984/bolt,nikgo/bolt,HonzaMikula/masivnipostele,lenvanessen/bolt,rarila/bolt,bolt/bolt,joshuan/bolt,Intendit/bolt,Raistlfiren/bolt,Intendit/bolt,Intendit/bolt,joshuan/bolt,lenvanessen/bolt,GawainLynch/bolt,lenvanessen/bolt,nantunes/bolt,CarsonF/bolt,GawainLynch/bolt,rarila/bolt,cdowdy/bolt,rossriley/bolt,one988/cm,HonzaMikula/masivnipostele,rossriley/bolt,electrolinux/bolt,Intendit/bolt,one988/cm,rarila/bolt,CarsonF/bolt,cdowdy/bolt,nikgo/bolt,nantunes/bolt,romulo1984/bolt,bolt/bolt
|
11ce50309b409bb9003adc82a0c4785a35d04b67
|
src/js/inject.js
|
src/js/inject.js
|
(() => {
'use strict';
chrome.storage.sync.get(function(storage) {
let execFlag = true;
for (var i = 0; i < storage.excludeURL.length; i++) {
if (parseURL(location.href).match(RegExp(parseURL(storage.excludeURL[i])))) {
execFlag = false;
}
}
if (execFlag) {
disableReferrer();
}
});
function disableReferrer() {
let meta = document.createElement('meta');
meta.name = "referrer";
meta.content = "no-referrer";
document.head.appendChild(meta);
}
function parseURL(url) {
// cut 'http' or 'https'
// http://www.example.com => www.example.com
// https://www.example.com => www.example.com
url = url.replace(/^https?:\/\//g, '');
// cut trailing slash
// example.com/foo/bar/ => example.com/foo/bar
url = (url[url.length-1] === '/') ? url.substr(0, url.length-1) : url;
return url;
}
chrome.runtime.sendMessage({referrer: document.referrer}, function(response) {});
})();
|
(() => {
'use strict';
chrome.storage.sync.get(function(storage) {
let execFlag = true;
if (storage.excludeURL !== undefined) {
for (var i = 0; i < storage.excludeURL.length; i++) {
if (parseURL(location.href).match(RegExp(parseURL(storage.excludeURL[i])))) {
execFlag = false;
}
}
}
if (execFlag) {
disableReferrer();
}
});
function disableReferrer() {
let meta = document.createElement('meta');
meta.name = "referrer";
meta.content = "no-referrer";
document.head.appendChild(meta);
}
function parseURL(url) {
// cut 'http' or 'https'
// http://www.example.com => www.example.com
// https://www.example.com => www.example.com
url = url.replace(/^https?:\/\//g, '');
// cut trailing slash
// example.com/foo/bar/ => example.com/foo/bar
url = (url[url.length-1] === '/') ? url.substr(0, url.length-1) : url;
return url;
}
chrome.runtime.sendMessage({referrer: document.referrer}, function(response) {});
})();
|
Fix error when never load options page
|
:bug: Fix error when never load options page
|
JavaScript
|
mit
|
noraworld/no-more-referrer,noraworld/no-more-referrer
|
37771b1cb803e09c51f20305d52fd4df246172a0
|
packages/@sanity/core/src/actions/graphql/listApisAction.js
|
packages/@sanity/core/src/actions/graphql/listApisAction.js
|
module.exports = async function listApisAction(args, context) {
const {apiClient, output, chalk} = context
const client = apiClient({
requireUser: true,
requireProject: true
})
let endpoints
try {
endpoints = await client.request({
url: `/apis/graphql`,
method: 'GET'
})
} catch (err) {
if (err.statusCode === 404) {
endpoints = []
} else {
throw err
}
}
endpoints = [{
dataset: 'production',
tag: 'default',
generation: 'gen1',
playgroundEnabled: false
}, {
dataset: 'staging',
tag: 'next',
generation: 'gen2',
playgroundEnabled: true
}]
if (endpoints && endpoints.length > 0) {
output.print('Here are the GraphQL endpoints deployed for this project:')
endpoints.forEach((endpoint, index) => {
output.print(`${index + 1}. ${chalk.bold('Dataset:')} ${endpoint.dataset}`)
output.print(` ${chalk.bold('Tag:')} ${endpoint.tag}`)
output.print(` ${chalk.bold('Generation:')} ${endpoint.generation}`)
output.print(` ${chalk.bold('Playground:')} ${endpoint.playgroundEnabled}\n`)
})
}
output.print("This project doesn't have any GraphQL endpoints deployed.")
}
|
module.exports = async function listApisAction(args, context) {
const {apiClient, output, chalk} = context
const client = apiClient({
requireUser: true,
requireProject: true
})
let endpoints
try {
endpoints = await client.request({
url: `/apis/graphql`,
method: 'GET'
})
} catch (err) {
if (err.statusCode === 404) {
endpoints = []
} else {
throw err
}
}
if (endpoints && endpoints.length > 0) {
output.print('Here are the GraphQL endpoints deployed for this project:')
endpoints.forEach((endpoint, index) => {
output.print(`${index + 1}. ${chalk.bold('Dataset:')} ${endpoint.dataset}`)
output.print(` ${chalk.bold('Tag:')} ${endpoint.tag}`)
output.print(` ${chalk.bold('Generation:')} ${endpoint.generation}`)
output.print(` ${chalk.bold('Playground:')} ${endpoint.playgroundEnabled}\n`)
})
}
output.print("This project doesn't have any GraphQL endpoints deployed.")
}
|
Remove in-line mock data when testing graphql list CLI command
|
[core] GraphQL: Remove in-line mock data when testing graphql list CLI command
|
JavaScript
|
mit
|
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
|
59c2a76434297f7d6ae2389f693a3b4fd484a5f5
|
api/src/lib/logger.js
|
api/src/lib/logger.js
|
const winston = require('winston');
const util = require('util');
const transports = [new winston.transports.Console()];
const Rollbar = require('rollbar');
const rollbar = new Rollbar('ff3ef8cca74244eabffb17dc2365e7bb');
const rollbarLogger = winston.transports.CustomLogger = function () {
this.name = 'rollbarLogger';
this.level = 'error';
};
util.inherits(rollbarLogger, winston.Transport);
rollbarLogger.prototype.log = function (level, msg, meta, callback) {
rollbar.error(meta.message, meta);
callback(null, true);
};
const Raven = require('raven');
const sentryLogger = winston.transports.CustomLogger = function () {
this.name = 'sentryLogger';
this.level = 'error';
};
util.inherits(sentryLogger, winston.Transport);
sentryLogger.prototype.log = function (level, msg, meta, callback) {
Raven.captureMessage(msg);
callback(null, true);
};
transports.push(new sentryLogger());
transports.push(new rollbarLogger());
module.exports = new winston.Logger({
transports: transports,
filters: [
(level, msg, meta) => msg.trim(), // shouldn't be necessary, but good-winston is adding \n
],
});
|
const winston = require('winston');
const util = require('util');
const transports = [new winston.transports.Console()];
if (process.env.SENTRY_DSN) {
const Raven = require('raven');
const sentryLogger = winston.transports.CustomLogger = function () {
this.name = 'sentryLogger';
this.level = 'error';
};
util.inherits(sentryLogger, winston.Transport);
sentryLogger.prototype.log = function (level, msg, meta, callback) {
Raven.captureException(meta);
callback(null, true);
};
transports.push(new sentryLogger());
}
if (process.env.ROLLBAR_ACCESS_TOKEN) {
const Rollbar = require('rollbar');
const rollbar = new Rollbar(process.env.ROLLBAR_ACCESS_TOKEN);
const rollbarLogger = winston.transports.CustomLogger = function () {
this.name = 'rollbarLogger';
this.level = 'error';
};
util.inherits(rollbarLogger, winston.Transport);
rollbarLogger.prototype.log = function (level, msg, meta, callback) {
rollbar.error(meta.message, meta);
callback(null, true);
};
transports.push(new rollbarLogger());
}
module.exports = new winston.Logger({
transports: transports,
filters: [
(level, msg, meta) => msg.trim(), // shouldn't be necessary, but good-winston is adding \n
],
});
|
Change rollbarLogger & sentryLogger to be conditionally used
|
Change rollbarLogger & sentryLogger to be conditionally used
|
JavaScript
|
mit
|
synapsestudios/oidc-platform,synapsestudios/oidc-platform,synapsestudios/oidc-platform,synapsestudios/oidc-platform
|
9f720da6aa6d4f72e9c3a6f26389f95eadf30cf6
|
src/dom-utils/getWindow.js
|
src/dom-utils/getWindow.js
|
// @flow
/*:: import type { Window } from '../types'; */
/*:: declare function getWindow(node: Node | Window): Window; */
export default function getWindow(node) {
if (node.toString() !== '[object Window]') {
const ownerDocument = node.ownerDocument;
return ownerDocument ? ownerDocument.defaultView : window;
}
return node;
}
|
// @flow
/*:: import type { Window } from '../types'; */
/*:: declare function getWindow(node: Node | Window): Window; */
export default function getWindow(node) {
if (node.toString() !== '[object Window]') {
const ownerDocument = node.ownerDocument;
return ownerDocument ? ownerDocument.defaultView || window : window;
}
return node;
}
|
Fix errors when iFrames are destroyed
|
Fix errors when iFrames are destroyed
Errors are thrown when an iFrame is destroyed because the popper's reference node's document no longer has a `defaultView`. The errors being thrown are:
> Cannot read property 'Element' of null
and
> Cannot read property 'HTMLElement' of null
from within `update`.
|
JavaScript
|
mit
|
FezVrasta/popper.js,floating-ui/floating-ui,floating-ui/floating-ui,FezVrasta/popper.js,floating-ui/floating-ui,FezVrasta/popper.js,FezVrasta/popper.js
|
f535468595a036df443c95a84e9a182fd572115c
|
reverse-words.js
|
reverse-words.js
|
// Reverse Words
/*RULES:
Function takes a string parameter
Reverse every word in the string
Return new string
NOTE:
Order of words shouldn't change
Can't use the array.reverse() method
*/
/*PSEUDOCODE
1) Split array by words
2) For each word,
2a) Push last letter of each individual element into a new array
2b) When done, push new array into new empty str array
2c) Continue doing this for all words
3) Join new array
4) Return new string
*/
function reverseWords(str){
var strArr = str.split(" ");
var emptyWordArr = [];
var emptyStrArr = [];
var index = 0;
strArr.forEach(function(word){
word = word.split('');
index = (word.length);
while (index > -1){
emptyWordArr.push(word[index])
index--;
}
emptyStrArr.push(emptyWordArr.join(''));
emptyWordArr = [];
});
return emptyStrArr.join(' ');
}
|
// Reverse Words
/*RULES:
Function takes a string parameter
Reverse every word in the string
Return new string
NOTE:
Order of words shouldn't change
Can't use the array.reverse() method
*/
/*PSEUDOCODE
1) Split array by words
2) For each word,
2a) Push last letter of each individual element into a new array
2b) When done, push new array into new empty str array
2c) Continue doing this for all words
3) Join new array
4) Return new string
*/
// This was my initial response, and it works fine! But could be slightly refactored for cleaner code.
// function reverseWords(str){
// var strArr = str.split(" ");
// var emptyWordArr = [];
// var emptyStrArr = [];
// var index = 0;
// strArr.forEach(function(word){
// word = word.split('');
// index = (word.length);
// while (index > -1){
// emptyWordArr.push(word[index])
// index--;
// }
// emptyStrArr.push(emptyWordArr.join(''));
// emptyWordArr = [];
// });
// return emptyStrArr.join(' ');
// }
|
Comment out initial response to include refactored answer
|
Comment out initial response to include refactored answer
|
JavaScript
|
mit
|
benjaminhyw/javascript_algorithms
|
bf33bafd03eb1265a7b10468b4a9a74f80d5adca
|
rollup.config.js
|
rollup.config.js
|
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import json from '@rollup/plugin-json';
import { terser } from 'rollup-plugin-terser';
import peggy from 'rollup-plugin-peggy';
import copy from 'rollup-plugin-copy';
import scss from 'rollup-plugin-scss';
import serve from 'rollup-plugin-serve';
export default {
input: 'src/scripts/index.js',
output: {
file: 'dist/index.js',
sourcemap: true,
exports: 'auto'
},
plugins: [
copy({
targets: [
{ src: 'public/*', dest: 'dist/' }
]
}),
resolve({
browser: true,
preferBuiltins: true
}),
scss(),
commonjs(),
json(),
peggy({ cache: true }),
process.env.NODE_ENV === 'production' ? terser() : null,
process.env.SERVE_APP ? serve({
contentBase: 'dist',
port: 8080
}) : null
]
};
|
import path from 'path';
import glob from 'glob';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import json from '@rollup/plugin-json';
import { terser } from 'rollup-plugin-terser';
import peggy from 'rollup-plugin-peggy';
import copy from 'rollup-plugin-copy';
import scss from 'rollup-plugin-scss';
import serve from 'rollup-plugin-serve';
// Watch additional files outside of the module graph (e.g. SCSS or static
// assets); see <https://github.com/rollup/rollup/issues/3414>
function watcher(globs) {
return {
buildStart() {
for (const item of globs) {
glob.sync(path.resolve(__dirname, item)).forEach((filename) => {
this.addWatchFile(filename);
});
}
}
};
}
export default {
input: 'src/scripts/index.js',
output: {
file: 'dist/index.js',
sourcemap: true,
exports: 'auto'
},
plugins: [
watcher(['src/styles/*.*', 'public/**/*.*']),
copy({
targets: [
{ src: 'public/*', dest: 'dist/' }
]
}),
resolve({
browser: true,
preferBuiltins: true
}),
scss(),
commonjs(),
json(),
peggy({ cache: true }),
process.env.NODE_ENV === 'production' ? terser() : null,
process.env.SERVE_APP ? serve({
contentBase: 'dist',
port: 8080
}) : null
]
};
|
Fix watching of stylesheets and static assets
|
Fix watching of stylesheets and static assets
|
JavaScript
|
mit
|
caleb531/truthy,caleb531/truthy
|
f3d336e625f576c47c4803051e63934f10e9b3ff
|
packages/machinomy/migrations/sqlite/20180325060555-add-created-at.js
|
packages/machinomy/migrations/sqlite/20180325060555-add-created-at.js
|
'use strict';
var dbm;
var type;
var seed;
/**
* We receive the dbmigrate dependency from dbmigrate initially.
* This enables us to not have to rely on NODE_PATH.
*/
exports.setup = function(options, seedLink) {
dbm = options.dbmigrate;
type = dbm.dataType;
seed = seedLink;
};
exports.up = function(db) {
return db.addColumn('payment', 'createdAt', {
type: 'bigint'
});
};
exports.down = function(db) {
return db.removeColumn('payment', 'createdAt');
};
exports._meta = {
"version": 1
};
|
'use strict';
var dbm;
var type;
var seed;
/**
* We receive the dbmigrate dependency from dbmigrate initially.
* This enables us to not have to rely on NODE_PATH.
*/
exports.setup = function(options, seedLink) {
dbm = options.dbmigrate;
type = dbm.dataType;
seed = seedLink;
};
exports.up = function(db) {
return db.addColumn('payment', 'createdAt', {
type: 'bigint'
});
};
exports.down = function(db) {
};
exports._meta = {
"version": 1
};
|
Remove call of not implemented method removeColumn in SQLite migration.
|
Remove call of not implemented method removeColumn in SQLite migration.
|
JavaScript
|
apache-2.0
|
machinomy/machinomy,machinomy/machinomy,machinomy/machinomy
|
89a27fac6b191459d63d90a63b29da691f823879
|
rollup.config.js
|
rollup.config.js
|
import buble from 'rollup-plugin-buble'
import inject from 'rollup-plugin-inject'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import builtins from 'builtin-modules'
const pkg = require('./package.json')
export default {
input: 'src/index.js',
output: [
{ format: 'cjs', file: pkg.main, sourcemap: true, exports: 'default' },
{ format: 'es', file: pkg.module, sourcemap: true }
],
external: builtins.concat(Object.keys(pkg.dependencies)),
plugins: [
buble({
include: 'src/**',
target: {
node: 4
}
}),
resolve({
module: true,
jsnext: true,
main: true,
browser: false,
preferBuiltins: true
}),
commonjs(),
inject({
include: 'src/**',
Promise: 'bluebirdish'
})
]
}
|
import buble from 'rollup-plugin-buble'
import inject from 'rollup-plugin-inject'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import builtins from 'builtin-modules'
const pkg = require('./package.json')
export default {
input: 'src/index.js',
output: [
{ format: 'cjs', file: pkg.main, sourcemap: true, exports: 'default', interop: false },
{ format: 'es', file: pkg.module, sourcemap: true }
],
external: builtins.concat(Object.keys(pkg.dependencies)),
plugins: [
buble({
include: 'src/**',
target: {
node: 4
}
}),
resolve({
module: true,
jsnext: true,
main: true,
browser: false,
preferBuiltins: true
}),
commonjs(),
inject({
include: 'src/**',
Promise: 'bluebirdish'
})
]
}
|
Disable CJS→ES interop in CommonJS build.
|
Disable CJS→ES interop in CommonJS build.
|
JavaScript
|
mit
|
goto-bus-stop/miniplug
|
19878840876fc3d85b169b3a02fff412d7d80b95
|
rollup.config.js
|
rollup.config.js
|
export default [
{
input: './src/index.js',
treeshake: false,
external: p => /^three/.test( p ),
output: {
name: 'MeshBVHLib',
extend: true,
format: 'umd',
file: './umd/index.js',
sourcemap: true,
globals: p => /^three/.test( p ) ? 'THREE' : null,
},
},
{
input: './src/index.js',
treeshake: false,
external: p => /^three/.test( p ),
output: {
name: 'MeshBVHLib',
extend: true,
format: 'esm',
file: './esm/index.js',
sourcemap: true,
globals: p => /^three/.test( p ) ? 'THREE' : null,
},
}
];
|
export default [
{
input: './src/index.js',
treeshake: false,
external: p => /^three/.test( p ),
output: {
name: 'MeshBVHLib',
extend: true,
format: 'umd',
file: './umd/index.js',
sourcemap: true,
globals: p => /^three/.test( p ) ? 'THREE' : null,
},
},
{
input: './src/index.js',
treeshake: false,
external: p => /^three/.test( p ),
output: {
format: 'esm',
file: './esm/index.js',
sourcemap: true,
},
}
];
|
Remove `name`, `extend` and `globals` options.
|
Remove `name`, `extend` and `globals` options.
|
JavaScript
|
mit
|
gkjohnson/three-mesh-bvh,gkjohnson/three-mesh-bvh,gkjohnson/three-mesh-bvh
|
4a991cfec283699e1c10070b89fc797c6e6320a5
|
js/components/DropTarget.js
|
js/components/DropTarget.js
|
import React from "react";
import { connect } from "react-redux";
import { loadFilesFromReferences } from "../actionCreators";
export class DropTarget extends React.Component {
constructor(props) {
super(props);
this.handleDrop = this.handleDrop.bind(this);
}
supress(e) {
e.stopPropagation();
e.preventDefault();
}
handleDrop(e) {
this.supress(e);
const { files } = e.dataTransfer;
this.props.loadFilesFromReferences(files);
}
render() {
// eslint-disable-next-line no-shadow, no-unused-vars
const { loadFilesFromReferences, ...passThroughProps } = this.props;
return (
<div
{...passThroughProps}
onDragEnter={this.supress}
onDragOver={this.supress}
onDrop={this.handleDrop}
/>
);
}
}
export default connect(null, { loadFilesFromReferences })(DropTarget);
|
import React from "react";
export default class DropTarget extends React.Component {
constructor(props) {
super(props);
this.handleDrop = this.handleDrop.bind(this);
this._ref = this._ref.bind(this);
}
supress(e) {
e.stopPropagation();
e.preventDefault();
}
handleDrop(e) {
this.supress(e);
if (!this._node) {
return;
}
const { x, y } = this._node.getBoundingClientRect();
this.props.handleDrop(e, { x, y });
}
_ref(node) {
this._node = node;
}
render() {
const {
// eslint-disable-next-line no-shadow, no-unused-vars
loadFilesFromReferences,
// eslint-disable-next-line no-shadow, no-unused-vars
handleDrop,
...passThroughProps
} = this.props;
return (
<div
{...passThroughProps}
onDragEnter={this.supress}
onDragOver={this.supress}
onDrop={this.handleDrop}
ref={this._ref}
/>
);
}
}
|
Add coords to drop handle call
|
Add coords to drop handle call
|
JavaScript
|
mit
|
captbaritone/winamp2-js,captbaritone/winamp2-js,captbaritone/winamp2-js
|
90effe78be49943827057b60ee6dc0b6c4ce086a
|
app/js/controllers.js
|
app/js/controllers.js
|
'use strict';
/* Controllers */
var cvAppControllers = angular.module('cvAppControllers', []);
cvAppControllers.controller('HomeController', ['$scope', function($scope) {
$scope.name = 'Elias';
}]);
cvAppControllers.controller('AboutController', ['$scope', function($scope) {
$scope.name = 'Elias';
}]);
|
'use strict';
/* Controllers */
var cvAppControllers = angular.module('cvAppControllers', []);
cvAppControllers.controller('HomeController', ['$scope', function($scope) {
$scope.name = 'Elias';
}]);
cvAppControllers.controller('AboutController', ['$scope', function($scope) {
$scope.name = 'Elias';
}]);
/*
phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
});
*/
|
Add tutorial http controller for reference (commented)
|
Add tutorial http controller for reference (commented)
|
JavaScript
|
mit
|
RegularSvensson/cvApp,RegularSvensson/cvApp
|
4a704fb65343f43945ac623abf6706b24ed5b9ea
|
brunch-config.js
|
brunch-config.js
|
'use strict';
module.exports = {
files: {
javascripts: {
joinTo: {
'app.js': /^app\//,
'vendor.js': /^node_modules\//
}
},
stylesheets: {
joinTo: {
'app.css': /^app\//
}
}
},
plugins: {
babel: {
presets: ['es2015', 'react']
}
},
server: {
port: 8000
}
};
|
'use strict';
module.exports = {
files: {
javascripts: {
joinTo: {
'app.js': /^app\//,
'vendor.js': /^node_modules\//
}
},
stylesheets: {
joinTo: {
'app.css': /^app\//
}
}
},
plugins: {
babel: {
presets: ['es2015', 'react']
}
},
server: {
port: Number.parseInt(process.env.PORT) || 8000
}
};
|
Allow PORT env variable to specify server port number
|
Allow PORT env variable to specify server port number
|
JavaScript
|
mit
|
ryansobol/with-react,ryansobol/with-react
|
7a6fb64b30513b987e59965a948a681037f406e9
|
src/utils/index.js
|
src/utils/index.js
|
const { parse } = require('url')
const UrlPattern = require('url-pattern')
const patternOpts = {
segmentNameCharset: 'a-zA-Z0-9_-',
}
const isPattern = pattern => pattern instanceof UrlPattern
const getParamsAndQuery = (pattern, url) => {
const { query, pathname } = parse(url, true)
const route = isPattern(pattern)
? pattern
: new UrlPattern(pattern, patternOpts)
const params = route.match(pathname)
return { query, params }
}
module.exports = {
getParamsAndQuery,
isPattern,
patternOpts,
}
|
const { parse } = require('url')
const UrlPattern = require('url-pattern')
const patternOpts = {
segmentNameCharset: 'a-zA-Z0-9_-',,
segmentValueCharset: 'a-zA-Z0-9@\.\+\-\_'
}
const isPattern = pattern => pattern instanceof UrlPattern
const getParamsAndQuery = (pattern, url) => {
const { query, pathname } = parse(url, true)
const route = isPattern(pattern)
? pattern
: new UrlPattern(pattern, patternOpts)
const params = route.match(pathname)
return { query, params }
}
module.exports = {
getParamsAndQuery,
isPattern,
patternOpts,
}
|
Allow some more chars in url as pattern value
|
Allow some more chars in url as pattern value
Allow character @, dot, +, _ and - as url pattern value, so email address can be passed as url parameter.
|
JavaScript
|
mit
|
pedronauck/micro-router
|
943a6c173c366dad1207b53d79b35e4f97ed0062
|
src/server/handlers/badge.js
|
src/server/handlers/badge.js
|
import path from 'path';
import logging from '../logging';
const logger = logging.getLogger('express');
import {
internalFindSnap,
internalGetSnapBuilds
} from './launchpad';
import { getGitHubRepoUrl } from '../../common/helpers/github-url';
import { snapBuildFromAPI } from '../../common/helpers/snap-builds';
const BADGES_PATH = path.join(__dirname, '../../common/images/badges');
export const badge = async (req, res) => {
const repoUrl = getGitHubRepoUrl(req.params.owner, req.params.name);
try {
const snap = await internalFindSnap(repoUrl);
const builds = await internalGetSnapBuilds(snap);
let badgeName = 'never_built';
if (builds.length) {
const latestBuild = snapBuildFromAPI(builds[0]);
if (latestBuild.badge) {
badgeName = latestBuild.badge;
}
}
res.setHeader('Cache-Control', 'no-cache');
return res.sendFile(path.join(BADGES_PATH, `${badgeName}.svg`));
} catch (err) {
logger.error(`Error generating badge for repo ${repoUrl}`, err);
res.status(404).send('Not found');
}
};
|
import path from 'path';
import logging from '../logging';
const logger = logging.getLogger('express');
import {
internalFindSnap,
internalGetSnapBuilds
} from './launchpad';
import { getGitHubRepoUrl } from '../../common/helpers/github-url';
import { snapBuildFromAPI } from '../../common/helpers/snap-builds';
const BADGES_PATH = path.join(__dirname, '../../common/images/badges');
export const badge = async (req, res) => {
const repoUrl = getGitHubRepoUrl(req.params.owner, req.params.name);
try {
const snap = await internalFindSnap(repoUrl);
const builds = await internalGetSnapBuilds(snap);
let badgeName = 'never_built';
if (builds.length) {
const latestBuild = snapBuildFromAPI(builds[0]);
if (latestBuild.badge) {
badgeName = latestBuild.badge;
}
}
res.setHeader('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate, value');
res.setHeader('Expires', 'Thu, 01 Jan 1970 00:00:00 GMT');
res.setHeader('Pragma', 'no-cache');
return res.sendFile(path.join(BADGES_PATH, `${badgeName}.svg`));
} catch (err) {
logger.error(`Error generating badge for repo ${repoUrl}`, err);
res.status(404).send('Not found');
}
};
|
Add Extra Cache Headers To Build Badge Response
|
Add Extra Cache Headers To Build Badge Response
Add extra cache prevention headers to the build badge response. This should help
reduce caching on GitHub README's.
|
JavaScript
|
agpl-3.0
|
canonical-ols/build.snapcraft.io,canonical-ols/build.snapcraft.io,canonical-ols/build.snapcraft.io
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.